Add some missing doc comments

As pointed out by the linter, some exported functions and types are
missing doc comments.
The linter warnings have been reduced from 194 to 116.
Not all missing comments have been added in this commit though.
This commit is contained in:
Jorin Vogel 2017-08-02 14:25:05 +02:00 committed by Bjørn Erik Pedersen
parent 9891c0fb0e
commit 81c13171a9
30 changed files with 109 additions and 23 deletions

View File

@ -49,6 +49,7 @@ type ArchetypeFileData struct {
}
const (
// ArchetypeTemplateTemplate is used as inital template when adding an archetype template.
ArchetypeTemplateTemplate = `---
title: "{{ replace .TranslationBaseName "-" " " | title }}"
date: {{ .Date }}
@ -123,7 +124,7 @@ func executeArcheTypeAsTemplate(s *hugolib.Site, kind, targetPath, archetypeFile
if !bytes.Contains(archetypeContent, []byte("date")) || !bytes.Contains(archetypeContent, []byte("title")) {
// TODO(bep) remove some time in the future.
s.Log.FEEDBACK.Println(fmt.Sprintf(`WARNING: date and/or title missing from archetype file %q.
s.Log.FEEDBACK.Println(fmt.Sprintf(`WARNING: date and/or title missing from archetype file %q.
From Hugo 0.24 this must be provided in the archetype file itself, if needed. Example:
%s
`, archetypeFilename, ArchetypeTemplateTemplate))

7
deps/deps.go vendored
View File

@ -14,7 +14,7 @@ import (
)
// Deps holds dependencies used by many.
// There will be normally be only one instance of deps in play
// There will be normally only one instance of deps in play
// at a given time, i.e. one per Site built.
type Deps struct {
// The logger to use.
@ -55,10 +55,12 @@ type ResourceProvider interface {
Clone(deps *Deps) error
}
// TemplateHandler returns the used tpl.TemplateFinder as tpl.TemplateHandler.
func (d *Deps) TemplateHandler() tpl.TemplateHandler {
return d.Tmpl.(tpl.TemplateHandler)
}
// LoadResources loads translations and templates.
func (d *Deps) LoadResources() error {
// Note that the translations need to be loaded before the templates.
if err := d.translationProvider.Update(d); err != nil {
@ -76,6 +78,9 @@ func (d *Deps) LoadResources() error {
return nil
}
// New initializes a Dep struct.
// Defaults are set for nil values,
// but TemplateProvider, TranslationProvider and Language are always required.
func New(cfg DepsCfg) (*Deps, error) {
var (
logger = cfg.Logger

View File

@ -19,14 +19,19 @@ import (
"encoding/json"
)
// DocProviders contains all DocProviders added to the system.
var DocProviders = make(map[string]DocProvider)
// AddDocProvider adds or updates the DocProvider for a given name.
func AddDocProvider(name string, provider DocProvider) {
DocProviders[name] = provider
}
// DocProvider is used to save arbitrary JSON data
// used for the generation of the documentation.
type DocProvider func() map[string]interface{}
// MarshalJSON returns a JSON representation of the DocProvider.
func (d DocProvider) MarshalJSON() ([]byte, error) {
return json.MarshalIndent(d(), "", " ")
}

View File

@ -30,7 +30,8 @@ func (b BaseURL) String() string {
return b.urlStr
}
// Protocol is normally on the form "scheme://", i.e. "webcal://".
// WithProtocol returns the BaseURL prefixed with the given protocol.
// The Protocol is normally of the form "scheme://", i.e. "webcal://".
func (b BaseURL) WithProtocol(protocol string) (string, error) {
u := b.URL()
@ -55,8 +56,9 @@ func (b BaseURL) WithProtocol(protocol string) (string, error) {
return u.String(), nil
}
// URL returns a copy of the internal URL.
// The copy can be safely used and modified.
func (b BaseURL) URL() *url.URL {
// create a copy as it will be modified.
c := *b.url
return &c
}

View File

@ -42,6 +42,7 @@ var SummaryLength = 70
// SummaryDivider denotes where content summarization should end. The default is "<!--more-->".
var SummaryDivider = []byte("<!--more-->")
// ContentSpec provides functionality to render markdown content.
type ContentSpec struct {
blackfriday map[string]interface{}
footnoteAnchorPrefix string
@ -50,6 +51,8 @@ type ContentSpec struct {
cfg config.Provider
}
// NewContentSpec returns a ContentSpec initialized
// with the appropriate fields from the given config.Provider.
func NewContentSpec(cfg config.Provider) *ContentSpec {
return &ContentSpec{
blackfriday: cfg.GetStringMap("blackfriday"),

View File

@ -22,7 +22,10 @@ import (
"github.com/russross/blackfriday"
)
// LinkResolverFunc describes a custom function to resolve a given link.
type LinkResolverFunc func(ref string) (string, error)
// FileResolverFunc describes a custom function to resolve a given file path.
type FileResolverFunc func(ref string) (string, error)
// HugoHTMLRenderer wraps a blackfriday.Renderer, typically a blackfriday.Html
@ -32,6 +35,8 @@ type HugoHTMLRenderer struct {
blackfriday.Renderer
}
// BlockCode renders a given text as a block of code.
// Pygments is used if it is setup to handle code fences.
func (r *HugoHTMLRenderer) BlockCode(out *bytes.Buffer, text []byte, lang string) {
if r.Cfg.GetBool("pygmentsCodeFences") && (lang != "" || r.Cfg.GetBool("pygmentsCodeFencesGuessSyntax")) {
opts := r.Cfg.GetString("pygmentsOptions")
@ -84,13 +89,15 @@ func (r *HugoHTMLRenderer) List(out *bytes.Buffer, text func() bool, flags int)
}
}
// HugoMmarkHTMLRenderer wraps a mmark.Renderer, typically a mmark.html
// Enabling Hugo to customise the rendering experience
// HugoMmarkHTMLRenderer wraps a mmark.Renderer, typically a mmark.html,
// enabling Hugo to customise the rendering experience.
type HugoMmarkHTMLRenderer struct {
mmark.Renderer
Cfg config.Provider
}
// BlockCode renders a given text as a block of code.
// Pygments is used if it is setup to handle code fences.
func (r *HugoMmarkHTMLRenderer) BlockCode(out *bytes.Buffer, text []byte, lang string, caption []byte, subfigure bool, callouts bool) {
if r.Cfg.GetBool("pygmentsCodeFences") && (lang != "" || r.Cfg.GetBool("pygmentsCodeFencesGuessSyntax")) {
str := html.UnescapeString(string(text))

View File

@ -38,6 +38,7 @@ func (v HugoVersion) String() string {
return hugoVersion(v.Number, v.PatchLevel, v.Suffix)
}
// ParseHugoVersion parses a version string.
func ParseHugoVersion(s string) (HugoVersion, error) {
var vv HugoVersion
@ -53,6 +54,8 @@ func ParseHugoVersion(s string) (HugoVersion, error) {
return vv, nil
}
// MustParseHugoVersion parses a version string
// and panics if any error occurs.
func MustParseHugoVersion(s string) HugoVersion {
vv, err := ParseHugoVersion(s)
if err != nil {
@ -72,7 +75,7 @@ func (v HugoVersion) Next() HugoVersion {
return HugoVersion{Number: v.Number + 0.01}
}
// Pre returns the previous Hugo release version.
// Prev returns the previous Hugo release version.
func (v HugoVersion) Prev() HugoVersion {
return HugoVersion{Number: v.Number - 0.01}
}

View File

@ -35,6 +35,7 @@ var globalOnlySettings = map[string]bool{
strings.ToLower("multilingual"): true,
}
// Language manages specific-language configuration.
type Language struct {
Lang string
LanguageName string
@ -50,10 +51,13 @@ func (l *Language) String() string {
return l.Lang
}
// NewLanguage creates a new language.
func NewLanguage(lang string, cfg config.Provider) *Language {
return &Language{Lang: lang, Cfg: cfg, params: make(map[string]interface{})}
}
// NewDefaultLanguage creates the default language for a config.Provider.
// If not otherwise specified the default is "en".
func NewDefaultLanguage(cfg config.Provider) *Language {
defaultLang := cfg.GetString("defaultContentLanguage")
@ -64,8 +68,11 @@ func NewDefaultLanguage(cfg config.Provider) *Language {
return NewLanguage(defaultLang, cfg)
}
// Languages is a sortable list of languages.
type Languages []*Language
// NewLanguages creates a sorted list of languages.
// NOTE: function is currently unused.
func NewLanguages(l ...*Language) Languages {
languages := make(Languages, len(l))
for i := 0; i < len(l); i++ {
@ -79,6 +86,7 @@ func (l Languages) Len() int { return len(l) }
func (l Languages) Less(i, j int) bool { return l[i].Weight < l[j].Weight }
func (l Languages) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
// Params retunrs language-specific params merged with the global params.
func (l *Language) Params() map[string]interface{} {
l.paramsInit.Do(func() {
// Merge with global config.

View File

@ -32,6 +32,7 @@ var (
// ErrThemeUndefined is returned when a theme has not be defined by the user.
ErrThemeUndefined = errors.New("no theme set")
// ErrWalkRootTooShort is returned when the root specified for a file walk is shorter than 4 characters.
ErrWalkRootTooShort = errors.New("Path too short. Stop walking.")
)
@ -480,7 +481,7 @@ func FindCWD() (string, 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
// the file structure.
func SymbolicWalk(fs afero.Fs, root string, walker filepath.WalkFunc) error {
// Sanity check

View File

@ -22,6 +22,8 @@ import (
// Os points to an Os Afero file system.
var Os = &afero.OsFs{}
// Fs abstracts the file system to separate source and destination file systems
// and allows both to be mocked for testing.
type Fs struct {
// Source is Hugo's source file system.
Source afero.Fs
@ -30,6 +32,7 @@ type Fs struct {
Destination afero.Fs
// Os is an OS file system.
// NOTE: Field is currently unused.
Os afero.Fs
// WorkingDir is a read-only file system

View File

@ -17,6 +17,7 @@ import (
"github.com/gohugoio/hugo/source"
)
// Handler is used for processing files of a specific type.
type Handler interface {
FileConvert(*source.File, *Site) HandledResult
PageConvert(*Page) HandledResult
@ -24,14 +25,17 @@ type Handler interface {
Extensions() []string
}
// Handle identifies functionality assosiated with certain file extentions.
type Handle struct {
extensions []string
}
// Extensions returns a list of extentions.
func (h Handle) Extensions() []string {
return h.extensions
}
// HandledResult describes the results of a file handling operation.
type HandledResult struct {
page *Page
file *source.File
@ -55,6 +59,7 @@ func (h HandledResult) String() string {
return h.Error()
}
// Page returns the affected page.
func (h HandledResult) Page() *Page {
return h.page
}

View File

@ -23,6 +23,7 @@ import (
var handlers []Handler
// MetaHandler abstracts reading and converting functionality of a Handler.
type MetaHandler interface {
// Read the Files in and register
Read(*source.File, *Site, HandleResults)
@ -33,14 +34,18 @@ type MetaHandler interface {
Handle() Handler
}
// HandledResults is a channel for HandledResult.
type HandleResults chan<- HandledResult
// NewMetaHandler creates a MetaHandle for a given extention.
func NewMetaHandler(in string) *MetaHandle {
x := &MetaHandle{ext: in}
x.Handler()
return x
}
// MetaHandle is a generic MetaHandler that internally uses
// the globally registered handlers for handling specific file types.
type MetaHandle struct {
handler Handler
ext string
@ -55,6 +60,7 @@ func (mh *MetaHandle) Read(f *source.File, s *Site, results HandleResults) {
results <- HandledResult{err: errors.New("No handler found"), file: f}
}
// Convert handles the convertion of files and pages.
func (mh *MetaHandle) Convert(i interface{}, s *Site, results HandleResults) {
h := mh.Handler()
@ -78,6 +84,7 @@ func (mh *MetaHandle) Convert(i interface{}, s *Site, results HandleResults) {
}
}
// Handler finds the registered handler for the used extention.
func (mh *MetaHandle) Handler() Handler {
if mh.handler == nil {
mh.handler = FindHandler(mh.ext)
@ -90,6 +97,7 @@ func (mh *MetaHandle) Handler() Handler {
return mh.handler
}
// FindHandler finds a Handler in the globally registered handlers.
func FindHandler(ext string) Handler {
for _, h := range Handlers() {
if HandlerMatch(h, ext) {
@ -99,6 +107,7 @@ func FindHandler(ext string) Handler {
return nil
}
// HandlerMatch checks if the given extention matches.
func HandlerMatch(h Handler, ext string) bool {
for _, x := range h.Extensions() {
if ext == x {
@ -108,10 +117,12 @@ func HandlerMatch(h Handler, ext string) bool {
return false
}
// RegisterHandler adds a handler to the globally registered ones.
func RegisterHandler(h Handler) {
handlers = append(handlers, h)
}
// Handlers returns the globally registered handlers.
func Handlers() []Handler {
return handlers
}

View File

@ -26,6 +26,7 @@ import (
"github.com/spf13/cast"
)
// Multilingual manages the all languages used in a multilingual site.
type Multilingual struct {
Languages helpers.Languages
@ -35,6 +36,7 @@ type Multilingual struct {
langMapInit sync.Once
}
// Language returns the Language assosiated with the given string.
func (ml *Multilingual) Language(lang string) *helpers.Language {
ml.langMapInit.Do(func() {
ml.langMap = make(map[string]*helpers.Language)

View File

@ -179,7 +179,7 @@ func (p *Page) checkRender() bool {
// OutputFormats holds a list of the relevant output formats for a given resource.
type OutputFormats []*OutputFormat
// And OutputFormat links to a representation of a resource.
// OutputFormat links to a representation of a resource.
type OutputFormat struct {
// Rel constains a value that can be used to construct a rel link.
// This is value is fetched from the output format definition.
@ -227,7 +227,7 @@ func newOutputFormat(p *Page, f output.Format) *OutputFormat {
return &OutputFormat{Rel: rel, f: f, p: p}
}
// OutputFormats gives the alternative output formats for this PageOutput.
// AlternativeOutputFormats gives the alternative output formats for this PageOutput.
// Note that we use the term "alternative" and not "alternate" here, as it
// does not necessarily replace the other format, it is an alternative representation.
func (p *PageOutput) AlternativeOutputFormats() (OutputFormats, error) {
@ -266,7 +266,7 @@ func (o *OutputFormat) Permalink() string {
return perm
}
// Permalink returns the relative permalink to this output format.
// RelPermalink returns the relative permalink to this output format.
func (o *OutputFormat) RelPermalink() string {
rel := o.p.createRelativePermalinkForOutputFormat(o.f)
return o.p.s.PathSpec.PrependBasePath(rel)

View File

@ -26,7 +26,7 @@ const (
defaultDelimiter = "."
)
// A media type (also known as MIME type and content type) is a two-part identifier for
// Type (also known as MIME type and content type) is a two-part identifier for
// file formats and format contents transmitted on the Internet.
// For Hugo's use case, we use the top-level type name / subtype name + suffix.
// One example would be image/jpeg+jpg
@ -39,7 +39,7 @@ type Type struct {
Delimiter string `json:"delimiter"` // defaults to "."
}
// FromTypeString creates a new Type given a type sring on the form MainType/SubType and
// FromString creates a new Type given a type sring on the form MainType/SubType and
// an optional suffix, e.g. "text/html" or "text/html+html".
func FromString(t string) (Type, error) {
t = strings.ToLower(t)

View File

@ -30,7 +30,7 @@ type LayoutDescriptor struct {
Layout string
}
// Layout calculates the layout template to use to render a given output type.
// LayoutHandler calculates the layout template to use to render a given output type.
type LayoutHandler struct {
hasTheme bool
@ -44,6 +44,7 @@ type layoutCacheKey struct {
f Format
}
// NewLayoutHandler creates a new LayoutHandler.
func NewLayoutHandler(hasTheme bool) *LayoutHandler {
return &LayoutHandler{hasTheme: hasTheme, cache: make(map[layoutCacheKey][]string)}
}
@ -75,7 +76,7 @@ _default/indexes.VARIATIONS
`
layoutsTaxonomy = `
taxonomy/SECTION.VARIATIONS
indexes/SECTION.VARIATIONS
indexes/SECTION.VARIATIONS
_default/taxonomy.VARIATIONS
_default/list.VARIATIONS
`
@ -86,6 +87,8 @@ indexes/indexes.VARIATIONS
`
)
// For returns a layout for the given LayoutDescriptor and options.
// Layouts are rendered and cached internally.
func (l *LayoutHandler) For(d LayoutDescriptor, layoutOverride string, f Format) ([]string, error) {
// We will get lots of requests for the same layouts, so avoid recalculations.

View File

@ -11,7 +11,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
// Package release implements a set of utilities and a wrapper around Goreleaser
// Package releaser implements a set of utilities and a wrapper around Goreleaser
// to help automate the Hugo release process.
package releaser

View File

@ -31,12 +31,13 @@ import (
const commitPrefix = "releaser:"
// ReleaseHandler provides functionality to release a new version of Hugo.
type ReleaseHandler struct {
cliVersion string
// If set, we do the releases in 3 steps:
// 1: Create and write a draft release notes
// 2: Prepare files for new version.
// 1: Create and write a draft release note
// 2: Prepare files for new version
// 3: Release
step int
skipPublish bool
@ -80,6 +81,7 @@ func (r ReleaseHandler) calculateVersions() (helpers.HugoVersion, helpers.HugoVe
return newVersion, finalVersion
}
// New initialises a ReleaseHandler.
func New(version string, step int, skipPublish, try bool) *ReleaseHandler {
rh := &ReleaseHandler{cliVersion: version, step: step, skipPublish: skipPublish, try: try}
@ -95,6 +97,7 @@ func New(version string, step int, skipPublish, try bool) *ReleaseHandler {
return rh
}
// Run creates a new release.
func (r *ReleaseHandler) Run() error {
if os.Getenv("GITHUB_TOKEN") == "" {
return errors.New("GITHUB_TOKEN not set, create one here with the repo scope selected: https://github.com/settings/tokens/new")

View File

@ -24,6 +24,7 @@ import (
"github.com/gohugoio/hugo/helpers"
)
// SourceSpec abstracts language-specific file creation.
type SourceSpec struct {
Cfg config.Provider
Fs *hugofs.Fs
@ -32,6 +33,7 @@ type SourceSpec struct {
defaultContentLanguage string
}
// NewSourceSpec initializes SourceSpec using languages from a given configuration.
func NewSourceSpec(cfg config.Provider, fs *hugofs.Fs) SourceSpec {
defaultLang := cfg.GetString("defaultContentLanguage")
languages := cfg.GetStringMap("languages")

View File

@ -13,6 +13,8 @@
package source
// ByteSource represents a source's name and content.
// It's currently only used for testing purposes.
type ByteSource struct {
Name string
Content []byte

View File

@ -26,15 +26,18 @@ func New() *Namespace {
type Namespace struct {
}
// Print returns string representation of the passed arguments.
func (ns *Namespace) Print(a ...interface{}) string {
return _fmt.Sprint(a...)
}
// Printf returns a formatted string representation of the passed arguments.
func (ns *Namespace) Printf(format string, a ...interface{}) string {
return _fmt.Sprintf(format, a...)
}
// Print returns string representation of the passed arguments ending with a newline.
func (ns *Namespace) Println(a ...interface{}) string {
return _fmt.Sprintln(a...)
}

View File

@ -29,14 +29,17 @@ func New() *Namespace {
// Namespace provides template functions for the "math" namespace.
type Namespace struct{}
// Add adds two numbers.
func (ns *Namespace) Add(a, b interface{}) (interface{}, error) {
return DoArithmetic(a, b, '+')
}
// Div divides two numbers.
func (ns *Namespace) Div(a, b interface{}) (interface{}, error) {
return DoArithmetic(a, b, '/')
}
// Log returns the natural logarithm of a number.
func (ns *Namespace) Log(a interface{}) (float64, error) {
af, err := cast.ToFloat64E(a)
@ -84,10 +87,12 @@ func (ns *Namespace) ModBool(a, b interface{}) (bool, error) {
return res == int64(0), nil
}
// Mul multiplies two numbers.
func (ns *Namespace) Mul(a, b interface{}) (interface{}, error) {
return DoArithmetic(a, b, '*')
}
// Sub substracts two numbers.
func (ns *Namespace) Sub(a, b interface{}) (interface{}, error) {
return DoArithmetic(a, b, '-')
}

View File

@ -70,9 +70,9 @@ func readFile(fs *afero.BasePathFs, filename string) (string, error) {
return string(b), nil
}
// ReadFilereads the file named by filename relative to the configured
// WorkingDir. It returns the contents as a string. There is a upper size
// limit set at 1 megabytes.
// ReadFile reads the file named by filename relative to the configured WorkingDir.
// It returns the contents as a string.
// There is an upper size limit set at 1 megabytes.
func (ns *Namespace) ReadFile(i interface{}) (string, error) {
s, err := cast.ToStringE(i)
if err != nil {

View File

@ -24,6 +24,8 @@ import (
"github.com/gohugoio/hugo/deps"
)
// TestTemplateProvider is global deps.ResourceProvider.
// NOTE: It's currently unused.
var TestTemplateProvider deps.ResourceProvider
// partialCache represents a cache of partials protected by a mutex.

View File

@ -39,6 +39,7 @@ type htmlTag struct {
openTag bool
}
// Truncate truncates a given string to the specified length.
func (ns *Namespace) Truncate(a interface{}, options ...interface{}) (template.HTML, error) {
length, err := cast.ToIntE(a)
if err != nil {

View File

@ -101,6 +101,7 @@ func (t *TemplateAdapter) Tree() string {
return s
}
// TemplateFuncsGetter allows to get a map of functions.
type TemplateFuncsGetter interface {
GetFuncs() map[string]interface{}
}

View File

@ -17,12 +17,14 @@ import (
"github.com/gohugoio/hugo/deps"
)
// TemplateProvider manages templates.
type TemplateProvider struct{}
// DefaultTemplateProvider is a globally available TemplateProvider.
var DefaultTemplateProvider *TemplateProvider
// Update updates the Hugo Template System in the provided Deps.
// with all the additional features, templates & functions
// Update updates the Hugo Template System in the provided Deps
// with all the additional features, templates & functions.
func (*TemplateProvider) Update(deps *deps.Deps) error {
newTmpl := newTemplateAdapter(deps)

View File

@ -54,6 +54,7 @@ func (ns *Namespace) RelURL(a interface{}) (template.HTML, error) {
return template.HTML(ns.deps.PathSpec.RelURL(s, false)), nil
}
// URLize returns the given argument formatted as URL.
func (ns *Namespace) URLize(a interface{}) (string, error) {
s, err := cast.ToStringE(a)
if err != nil {

View File

@ -18,6 +18,8 @@ import (
"fmt"
)
// LiveReloadInject returns a function that can be used
// to inject a script tag for the livereload JavaScript in a HTML document.
func LiveReloadInject(port int) func(ct contentTransformer) {
return func(ct contentTransformer) {
endBodyTag := "</body>"

View File

@ -19,6 +19,7 @@ import (
"github.com/fsnotify/fsnotify"
)
// Batcher batches file watch events in a given interval.
type Batcher struct {
*fsnotify.Watcher
interval time.Duration
@ -27,6 +28,7 @@ type Batcher struct {
Events chan []fsnotify.Event // Events are returned on this channel
}
// New creates and starts a Batcher with the given time interval.
func New(interval time.Duration) (*Batcher, error) {
watcher, err := fsnotify.NewWatcher()
@ -64,6 +66,7 @@ OuterLoop:
close(b.done)
}
// Close stops the watching of the files.
func (b *Batcher) Close() {
b.done <- struct{}{}
b.Watcher.Close()