From d90e37e0c6e812f9913bf256c9c81aa05b7a08aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Pedersen?= Date: Wed, 2 Dec 2020 13:23:25 +0100 Subject: [PATCH] all: Format code with gofumpt See https://github.com/mvdan/gofumpt --- cache/filecache/filecache.go | 5 - cache/filecache/filecache_config_test.go | 3 - cache/filecache/filecache_pruner.go | 2 - cache/filecache/filecache_pruner_test.go | 1 - cache/filecache/filecache_test.go | 3 - cache/namedmemcache/named_cache.go | 1 - codegen/methods.go | 16 +- codegen/methods_test.go | 4 - commands/check.go | 9 +- commands/check_darwin.go | 9 +- commands/commandeer.go | 22 +- commands/commands.go | 2 +- commands/commands_test.go | 15 +- commands/convert.go | 7 +- commands/env.go | 25 +- commands/genautocomplete.go | 1 - commands/genchromastyles.go | 4 +- commands/gendocshelper.go | 5 +- commands/hugo.go | 37 +- commands/hugo_test.go | 1 - commands/import_jekyll.go | 12 +- commands/import_jekyll_test.go | 116 ++++-- commands/list.go | 5 - commands/mod.go | 2 - commands/mod_npm.go | 2 - commands/new.go | 1 - commands/new_site.go | 1 - commands/new_theme.go | 2 - commands/nodeploy.go | 1 + commands/release.go | 1 - commands/server.go | 10 +- commands/server_test.go | 2 - commands/static_syncer.go | 1 - common/collections/append.go | 1 - common/collections/append_test.go | 43 ++- common/collections/slice_test.go | 14 +- common/herrors/error_locator_test.go | 1 - common/herrors/file_error.go | 4 +- common/herrors/file_error_test.go | 1 - common/hreflect/helpers.go | 1 - common/hugo/hugo_test.go | 1 - common/hugo/version.go | 2 - common/loggers/ignorableLogger.go | 1 - common/loggers/loggers.go | 9 +- common/loggers/loggers_test.go | 1 - common/maps/maps_test.go | 1 - common/maps/params.go | 1 - common/maps/params_test.go | 4 - common/maps/scratch.go | 1 - common/maps/scratch_test.go | 3 - common/para/para_test.go | 4 - common/text/position.go | 3 +- common/text/position_test.go | 1 - common/text/transform_test.go | 1 - common/types/convert_test.go | 2 - compare/compare_strings_test.go | 1 - config/commonConfig.go | 8 +- config/commonConfig_test.go | 8 +- config/configLoader.go | 1 - config/privacy/privacyConfig_test.go | 1 - config/services/servicesConfig_test.go | 1 - create/content.go | 10 +- create/content_template_handler.go | 2 - create/content_test.go | 10 +- deploy/deploy.go | 3 +- deploy/deployConfig.go | 1 - deploy/deploy_test.go | 6 +- deps/deps.go | 2 - deps/deps_test.go | 2 - helpers/content.go | 6 +- helpers/content_test.go | 4 +- helpers/docshelper.go | 3 - helpers/emoji.go | 1 - helpers/emoji_test.go | 8 +- helpers/general.go | 2 - helpers/general_test.go | 3 - helpers/path.go | 16 +- helpers/path_test.go | 21 +- helpers/pathspec.go | 2 - helpers/pathspec_test.go | 1 - helpers/processing_stats.go | 3 - helpers/testhelpers_test.go | 1 - helpers/url.go | 5 +- helpers/url_test.go | 3 - htesting/test_helpers.go | 1 - hugofs/decorators.go | 6 - hugofs/fileinfo.go | 5 +- hugofs/files/classifier.go | 6 +- hugofs/files/classifier_test.go | 2 - hugofs/filter_fs.go | 10 - hugofs/filter_fs_test.go | 2 - hugofs/fs.go | 6 +- hugofs/fs_test.go | 2 - hugofs/glob.go | 1 - hugofs/glob/glob.go | 2 - hugofs/glob/glob_test.go | 4 - hugofs/glob_test.go | 1 - hugofs/hashing_fs.go | 4 +- hugofs/hashing_fs_test.go | 1 - hugofs/nosymlink_fs.go | 5 +- hugofs/nosymlink_test.go | 1 - hugofs/rootmapping_fs.go | 14 +- hugofs/rootmapping_fs_test.go | 22 +- hugofs/slice_fs.go | 5 - hugofs/walk.go | 4 +- hugofs/walk_test.go | 11 +- hugolib/404_test.go | 2 - hugolib/alias.go | 1 - hugolib/alias_test.go | 6 +- hugolib/breaking_changes_test.go | 11 - hugolib/cascade_test.go | 11 - hugolib/case_insensitive_test.go | 2 - hugolib/config.go | 11 - hugolib/config_test.go | 6 - hugolib/configdir_test.go | 2 - hugolib/content_map.go | 14 +- hugolib/content_map_page.go | 8 - hugolib/content_map_test.go | 12 - hugolib/content_render_hooks_test.go | 11 - hugolib/datafiles_test.go | 13 +- hugolib/disableKinds_test.go | 8 +- hugolib/embedded_shortcodes_test.go | 10 +- hugolib/embedded_templates_test.go | 1 - hugolib/fileInfo.go | 2 - hugolib/filesystems/basefs.go | 18 +- hugolib/filesystems/basefs_test.go | 4 - hugolib/gitinfo.go | 1 - hugolib/hugo_modules_test.go | 28 +- hugolib/hugo_sites.go | 15 +- hugolib/hugo_sites_build.go | 12 - hugolib/hugo_sites_build_errors_test.go | 10 - hugolib/hugo_sites_build_test.go | 20 +- hugolib/hugo_sites_multihost_test.go | 3 +- hugolib/hugo_sites_rebuild_test.go | 8 - hugolib/hugo_smoke_test.go | 4 +- hugolib/image_test.go | 4 - hugolib/js_test.go | 2 - hugolib/language_content_dir_test.go | 11 +- hugolib/language_test.go | 1 - hugolib/menu_test.go | 10 +- hugolib/multilingual.go | 4 +- hugolib/openapi_test.go | 1 - hugolib/page.go | 11 - hugolib/page__content.go | 1 - hugolib/page__data.go | 1 - hugolib/page__menus.go | 3 - hugolib/page__meta.go | 9 +- hugolib/page__new.go | 9 +- hugolib/page__output.go | 4 - hugolib/page__paginator.go | 2 - hugolib/page__paths.go | 6 +- hugolib/page__per_output.go | 8 - hugolib/page__position.go | 1 - hugolib/page__ref.go | 2 - hugolib/page__tree.go | 3 - hugolib/page_kinds.go | 7 +- hugolib/page_permalink_test.go | 3 - hugolib/page_test.go | 39 +- hugolib/pagebundler_test.go | 29 +- hugolib/pagecollections.go | 2 - hugolib/pagecollections_test.go | 18 +- hugolib/pages_capture.go | 18 +- hugolib/pages_capture_test.go | 5 +- hugolib/pages_language_merge_test.go | 1 - hugolib/pages_process.go | 2 - hugolib/pages_test.go | 14 +- hugolib/paginator_test.go | 2 - hugolib/paths/paths.go | 3 - hugolib/permalinker.go | 4 +- hugolib/resource_chain_babel_test.go | 1 - hugolib/resource_chain_test.go | 28 +- hugolib/robotstxt_test.go | 1 - hugolib/shortcode.go | 34 +- hugolib/shortcode_test.go | 119 +++--- hugolib/site.go | 36 +- hugolib/siteJSONEncode_test.go | 1 - hugolib/site_benchmark_new_test.go | 234 ++++++------ hugolib/site_output.go | 3 - hugolib/site_output_test.go | 16 +- hugolib/site_render.go | 11 +- hugolib/site_sections_test.go | 9 - hugolib/site_stats_test.go | 4 +- hugolib/site_test.go | 32 +- hugolib/site_url_test.go | 7 +- hugolib/sitemap_test.go | 7 +- hugolib/taxonomy_test.go | 17 +- hugolib/template_test.go | 34 +- hugolib/testhelpers_test.go | 38 +- identity/identity.go | 1 - identity/identity_test.go | 4 - langs/config.go | 3 - langs/i18n/i18n.go | 6 +- langs/i18n/i18n_test.go | 3 - langs/i18n/translationProvider.go | 2 - langs/language.go | 2 - lazy/init.go | 2 - lazy/init_test.go | 4 - lazy/once.go | 1 - livereload/livereload.go | 3 +- magefile.go | 1 - main.go | 1 - markup/asciidocext/convert.go | 3 +- markup/asciidocext/convert_test.go | 1 - markup/blackfriday/convert.go | 2 - markup/blackfriday/convert_test.go | 2 +- markup/converter/converter.go | 4 +- markup/goldmark/autoid.go | 1 - markup/goldmark/autoid_test.go | 4 - markup/goldmark/convert.go | 7 +- markup/goldmark/convert_test.go | 4 - markup/goldmark/render_hooks.go | 2 - markup/goldmark/toc_test.go | 3 +- markup/highlight/config.go | 4 +- markup/highlight/config_test.go | 2 - markup/highlight/highlight_test.go | 2 - markup/internal/external.go | 1 - markup/markup.go | 2 +- markup/markup_config/config.go | 1 - markup/markup_config/config_test.go | 1 - markup/markup_test.go | 1 - markup/mmark/convert.go | 3 - markup/mmark/convert_test.go | 2 +- markup/pandoc/convert.go | 1 - markup/rst/convert.go | 2 +- markup/tableofcontents/tableofcontents.go | 2 +- .../tableofcontents/tableofcontents_test.go | 1 - media/mediaType_test.go | 28 +- metrics/metrics.go | 13 +- metrics/metrics_test.go | 2 - minifiers/config_test.go | 1 - minifiers/minifiers_test.go | 3 - modules/client.go | 18 +- modules/client_test.go | 9 +- modules/collect.go | 9 - modules/collect_test.go | 11 +- modules/config.go | 9 +- modules/config_test.go | 2 - modules/npm/package_builder.go | 3 - navigation/menu.go | 8 +- navigation/pagemenus.go | 5 - output/docshelper.go | 5 +- output/layout_test.go | 144 +++++-- output/outputFormat.go | 4 +- output/outputFormat_test.go | 39 +- parser/lowercase_camel_json.go | 7 +- parser/metadecoders/decoder.go | 5 - parser/metadecoders/decoder_test.go | 1 - parser/metadecoders/format.go | 2 - parser/pageparser/item_test.go | 1 - parser/pageparser/pagelexer.go | 7 - parser/pageparser/pagelexer_intro.go | 2 - parser/pageparser/pagelexer_shortcode.go | 3 - parser/pageparser/pagelexer_test.go | 1 - parser/pageparser/pageparser.go | 1 - parser/pageparser/pageparser_intro_test.go | 1 - parser/pageparser/pageparser_main_test.go | 2 +- .../pageparser/pageparser_shortcode_test.go | 149 +++++--- publisher/htmlElementsCollector.go | 12 +- publisher/htmlElementsCollector_test.go | 7 +- publisher/publisher.go | 1 - related/inverted_index.go | 1 - related/inverted_index_test.go | 9 +- releaser/git.go | 4 +- releaser/git_test.go | 2 - releaser/github.go | 1 - releaser/releasenotes_writer.go | 9 +- releaser/releasenotes_writer_test.go | 1 - resources/image.go | 7 - resources/image_test.go | 8 - resources/images/color.go | 1 - resources/images/color_test.go | 1 - resources/images/config_test.go | 1 - resources/images/exif/exif.go | 4 - resources/images/exif/exif_test.go | 1 - resources/images/filters_test.go | 1 - resources/images/image.go | 3 - resources/images/smartcrop.go | 1 - resources/internal/key.go | 1 - resources/jsconfig/jsconfig.go | 1 - resources/page/page_data_test.go | 2 - .../page_generate/generate_page_wrappers.go | 2 - resources/page/page_kinds_test.go | 1 - resources/page/page_marshaljson.autogen.go | 5 +- resources/page/page_matcher.go | 2 - resources/page/page_matcher_test.go | 2 - resources/page/page_nop.go | 4 +- resources/page/page_paths.go | 4 - resources/page/page_paths_test.go | 87 +++-- resources/page/page_wrappers.autogen.go | 18 +- resources/page/pagegroup.go | 2 - resources/page/pagegroup_test.go | 1 - resources/page/pagemeta/page_frontmatter.go | 16 +- .../page/pagemeta/page_frontmatter_test.go | 5 - resources/page/pagemeta/pagemeta_test.go | 4 +- resources/page/pages_cache.go | 1 - resources/page/pages_language_merge.go | 4 +- resources/page/pages_prev_next.go | 1 - resources/page/pages_prev_next_test.go | 2 - resources/page/pages_related.go | 4 - resources/page/pages_sort.go | 11 - resources/page/pages_sort_search.go | 1 - resources/page/pages_sort_search_test.go | 16 +- resources/page/pages_sort_test.go | 2 - resources/page/pages_test.go | 4 - resources/page/pagination.go | 8 - resources/page/pagination_test.go | 22 +- resources/page/permalinks.go | 8 +- resources/page/permalinks_test.go | 1 - resources/page/testhelpers_test.go | 3 +- resources/page/weighted.go | 4 +- resources/page/zero_file.autogen.go | 12 + resources/postpub/fields.go | 2 +- resources/postpub/fields_test.go | 1 - resources/postpub/postpub.go | 1 - resources/resource.go | 4 - resources/resource/params.go | 1 - resources/resource_cache.go | 10 +- .../resource_factories/bundler/bundler.go | 6 +- .../bundler/bundler_test.go | 1 - resources/resource_factories/create/create.go | 15 +- resources/resource_metadata.go | 3 +- resources/resource_metadata_test.go | 10 - resources/resource_spec.go | 9 +- resources/resource_test.go | 16 +- .../resource_transformers/babel/babel.go | 2 +- .../integrity/integrity.go | 1 - .../integrity/integrity_test.go | 3 - resources/resource_transformers/js/options.go | 9 +- .../resource_transformers/js/options_test.go | 7 +- .../resource_transformers/minifier/minify.go | 1 - .../minifier/minify_test.go | 1 - .../resource_transformers/postcss/postcss.go | 7 +- .../postcss/postcss_test.go | 2 - .../tocss/scss/client_test.go | 1 - .../resource_transformers/tocss/scss/tocss.go | 2 +- resources/testhelpers_test.go | 8 +- resources/transform.go | 3 - resources/transform_test.go | 3 +- scripts/fork_go_templates/main.go | 41 +- source/fileInfo.go | 2 - source/fileInfo_test.go | 4 - source/filesystem.go | 2 - source/filesystem_test.go | 1 - source/sourceSpec.go | 1 - tpl/cast/cast_test.go | 1 - tpl/cast/docshelper.go | 1 - tpl/cast/init.go | 1 - tpl/cast/init_test.go | 1 - tpl/collections/append.go | 1 - tpl/collections/append_test.go | 7 +- tpl/collections/apply.go | 1 - tpl/collections/apply_test.go | 5 +- tpl/collections/collections.go | 7 +- tpl/collections/collections_test.go | 16 +- tpl/collections/complement_test.go | 4 +- tpl/collections/index_test.go | 1 - tpl/collections/merge_test.go | 30 +- tpl/collections/reflect_helpers.go | 1 - tpl/collections/sort_test.go | 2 - tpl/collections/symdiff.go | 1 - tpl/collections/symdiff_test.go | 1 - tpl/collections/where_test.go | 9 +- tpl/compare/compare_test.go | 7 +- tpl/compare/init.go | 1 - tpl/crypto/init.go | 1 - tpl/data/data.go | 1 - tpl/data/data_test.go | 4 +- tpl/data/resources.go | 2 - tpl/data/resources_test.go | 1 - tpl/fmt/fmt.go | 1 - tpl/hugo/init.go | 2 - tpl/images/init.go | 1 - tpl/inflect/init.go | 1 - .../go_templates/fmtsort/sort_test.go | 3 +- .../go_templates/htmltemplate/content_test.go | 2 +- tpl/internal/go_templates/htmltemplate/css.go | 6 +- .../go_templates/htmltemplate/escape_test.go | 2 - .../go_templates/htmltemplate/example_test.go | 2 - tpl/internal/go_templates/htmltemplate/js.go | 1 + .../go_templates/htmltemplate/js_test.go | 3 +- .../go_templates/htmltemplate/transition.go | 6 +- .../htmltemplate/transition_test.go | 1 - tpl/internal/go_templates/testenv/testenv.go | 3 +- .../go_templates/testenv/testenv_windows.go | 6 +- .../go_templates/texttemplate/example_test.go | 2 +- .../go_templates/texttemplate/exec.go | 5 +- .../go_templates/texttemplate/exec_test.go | 50 ++- .../texttemplate/hugo_template.go | 1 - .../texttemplate/hugo_template_test.go | 1 - .../go_templates/texttemplate/multi_test.go | 35 +- .../go_templates/texttemplate/parse/node.go | 1 - .../go_templates/texttemplate/parse/parse.go | 2 +- .../texttemplate/parse/parse_test.go | 360 ++++++++++++------ .../go_templates/texttemplate/template.go | 3 +- tpl/internal/templatefuncsRegistry.go | 2 - tpl/js/js.go | 1 - tpl/lang/init.go | 1 - tpl/math/init.go | 1 - tpl/math/math.go | 2 - tpl/math/math_test.go | 1 - tpl/openapi/openapi3/init.go | 1 - tpl/openapi/openapi3/openapi3.go | 3 - tpl/os/init.go | 1 - tpl/os/os.go | 2 - tpl/partials/init.go | 1 - tpl/partials/partials.go | 1 - tpl/partials/partials_test.go | 1 - tpl/path/init.go | 1 - tpl/resources/init.go | 1 - tpl/resources/resources.go | 4 - tpl/safe/init.go | 1 - tpl/safe/safe_test.go | 1 - tpl/site/init.go | 2 - tpl/strings/truncate.go | 1 - tpl/strings/truncate_test.go | 2 - tpl/template.go | 3 +- tpl/templates/init.go | 4 +- tpl/templates/templates.go | 1 - tpl/time/init.go | 1 - tpl/tplimpl/embedded/generate/generate.go | 2 - tpl/tplimpl/shortcodes.go | 2 - tpl/tplimpl/shortcodes_test.go | 6 - tpl/tplimpl/template.go | 14 - tpl/tplimpl/template_ast_transformers.go | 11 +- tpl/tplimpl/template_ast_transformers_test.go | 6 - tpl/tplimpl/template_funcs.go | 8 +- tpl/tplimpl/template_funcs_test.go | 5 +- tpl/tplimpl/template_info_test.go | 2 - tpl/transform/init.go | 22 +- tpl/transform/remarshal_test.go | 2 - tpl/transform/transform.go | 1 - tpl/transform/transform_test.go | 2 - tpl/transform/unmarshal.go | 2 +- tpl/transform/unmarshal_test.go | 5 - tpl/urls/init.go | 1 - tpl/urls/urls.go | 2 - .../livereloadinject/livereloadinject.go | 11 +- .../livereloadinject/livereloadinject_test.go | 1 - transform/metainject/hugogenerator.go | 7 +- transform/metainject/hugogenerator_test.go | 1 - transform/urlreplacers/absurlreplacer.go | 9 +- transform/urlreplacers/absurlreplacer_test.go | 5 +- 442 files changed, 1426 insertions(+), 2254 deletions(-) diff --git a/cache/filecache/filecache.go b/cache/filecache/filecache.go index 37870dd5..c586f9a5 100644 --- a/cache/filecache/filecache.go +++ b/cache/filecache/filecache.go @@ -158,7 +158,6 @@ func (c *Cache) ReadOrCreate(id string, err = create(info, f) return - } // GetOrCreate tries to get the file with the given id from cache. If not found or expired, create will @@ -220,7 +219,6 @@ func (c *Cache) GetOrCreateBytes(id string, create func() ([]byte, error)) (Item return info, nil, err } return info, b, nil - } // GetBytes gets the file content with the given id from the cahce, nil if none found. @@ -276,7 +274,6 @@ func (c *Cache) getOrRemove(id string) hugio.ReadSeekCloser { } f, err := c.Fs.Open(id) - if err != nil { return nil } @@ -299,7 +296,6 @@ func (c *Cache) getString(id string) string { defer c.nlocker.Unlock(id) f, err := c.Fs.Open(id) - if err != nil { return "" } @@ -307,7 +303,6 @@ func (c *Cache) getString(id string) string { b, _ := ioutil.ReadAll(f) return string(b) - } // Caches is a named set of caches. diff --git a/cache/filecache/filecache_config_test.go b/cache/filecache/filecache_config_test.go index 9f80a4f9..cd1d2c82 100644 --- a/cache/filecache/filecache_config_test.go +++ b/cache/filecache/filecache_config_test.go @@ -69,7 +69,6 @@ dir = "/path/to/c3" c3 := decoded["images"] c.Assert(c3.MaxAge, qt.Equals, time.Duration(-1)) c.Assert(c3.Dir, qt.Equals, filepath.FromSlash("/path/to/c3/filecache/images")) - } func TestDecodeConfigIgnoreCache(t *testing.T) { @@ -110,7 +109,6 @@ dir = "/path/to/c3" for _, v := range decoded { c.Assert(v.MaxAge, qt.Equals, time.Duration(0)) } - } func TestDecodeConfigDefault(t *testing.T) { @@ -178,7 +176,6 @@ dir = "/" _, err = DecodeConfig(fs, cfg) c.Assert(err, qt.Not(qt.IsNil)) - } func newTestConfig() *viper.Viper { diff --git a/cache/filecache/filecache_pruner.go b/cache/filecache/filecache_pruner.go index b77f5331..db187570 100644 --- a/cache/filecache/filecache_pruner.go +++ b/cache/filecache/filecache_pruner.go @@ -110,7 +110,6 @@ func (c *Cache) Prune(force bool) (int, error) { } func (c *Cache) pruneRootDir(force bool) (int, error) { - info, err := c.Fs.Stat(c.pruneAllRootDir) if err != nil { if os.IsNotExist(err) { @@ -124,5 +123,4 @@ func (c *Cache) pruneRootDir(force bool) (int, error) { } return hugofs.MakeReadableAndRemoveAllModulePkgDir(c.Fs, c.pruneAllRootDir) - } diff --git a/cache/filecache/filecache_pruner_test.go b/cache/filecache/filecache_pruner_test.go index 48bce723..46e1317c 100644 --- a/cache/filecache/filecache_pruner_test.go +++ b/cache/filecache/filecache_pruner_test.go @@ -107,5 +107,4 @@ dir = ":resourceDir/_gen" } } - } diff --git a/cache/filecache/filecache_test.go b/cache/filecache/filecache_test.go index 00b4e557..6a051a26 100644 --- a/cache/filecache/filecache_test.go +++ b/cache/filecache/filecache_test.go @@ -183,7 +183,6 @@ dir = ":cacheDir/c" c.Assert(string(b), qt.Equals, "Hugo is great!") } - } func TestFileCacheConcurrent(t *testing.T) { @@ -253,7 +252,6 @@ func TestFileCacheReadOrCreateErrorInRead(t *testing.T) { var result string rf := func(failLevel int) func(info ItemInfo, r io.ReadSeeker) error { - return func(info ItemInfo, r io.ReadSeeker) error { if failLevel > 0 { if failLevel > 1 { @@ -347,5 +345,4 @@ func newPathsSpec(t *testing.T, fs afero.Fs, configStr string) *helpers.PathSpec p, err := helpers.NewPathSpec(hugofs.NewFrom(fs, cfg), cfg, nil) c.Assert(err, qt.IsNil) return p - } diff --git a/cache/namedmemcache/named_cache.go b/cache/namedmemcache/named_cache.go index d8c229a0..d67bcc28 100644 --- a/cache/namedmemcache/named_cache.go +++ b/cache/namedmemcache/named_cache.go @@ -49,7 +49,6 @@ func (c *Cache) Clear() { c.cache = make(map[string]cacheEntry) c.nlocker = locker.NewLocker() - } // GetOrCreate tries to get the value with the given cache key, if not found diff --git a/codegen/methods.go b/codegen/methods.go index ed8dba92..38477e33 100644 --- a/codegen/methods.go +++ b/codegen/methods.go @@ -58,7 +58,7 @@ func (c *Inspector) MethodsFromTypes(include []reflect.Type, exclude []reflect.T var methods Methods - var excludes = make(map[string]bool) + excludes := make(map[string]bool) if len(exclude) > 0 { for _, m := range c.MethodsFromTypes(exclude, nil) { @@ -99,11 +99,9 @@ func (c *Inspector) MethodsFromTypes(include []reflect.Type, exclude []reflect.T name = pkgPrefix + name return name, pkg - } for _, t := range include { - for i := 0; i < t.NumMethod(); i++ { m := t.Method(i) @@ -153,7 +151,6 @@ func (c *Inspector) MethodsFromTypes(include []reflect.Type, exclude []reflect.T methods = append(methods, method) } - } sort.SliceStable(methods, func(i, j int) bool { @@ -167,16 +164,13 @@ func (c *Inspector) MethodsFromTypes(include []reflect.Type, exclude []reflect.T } return wi < wj - }) return methods - } func (c *Inspector) parseSource() { c.init.Do(func() { - if !strings.Contains(c.ProjectRootDir, "hugo") { panic("dir must be set to the Hugo root") } @@ -200,7 +194,6 @@ func (c *Inspector) parseSource() { filenames = append(filenames, path) return nil - }) for _, filename := range filenames { @@ -230,7 +223,6 @@ func (c *Inspector) parseSource() { c.methodWeight[iface] = weights } } - } return true }) @@ -247,7 +239,6 @@ func (c *Inspector) parseSource() { } } } - }) } @@ -385,7 +376,7 @@ func (m Methods) ToMarshalJSON(receiver, pkgPath string, excludes ...string) (st fmt.Fprintf(&sb, "func Marshal%sToJSON(%s %s) ([]byte, error) {\n", what, r, receiver) var methods Methods - var excludeRes = make([]*regexp.Regexp, len(excludes)) + excludeRes := make([]*regexp.Regexp, len(excludes)) for i, exclude := range excludes { excludeRes[i] = regexp.MustCompile(exclude) @@ -450,7 +441,6 @@ func (m Methods) ToMarshalJSON(receiver, pkgPath string, excludes ...string) (st } return sb.String(), pkgImports - } func collectMethodsRecursive(pkg string, f []*ast.Field) []string { @@ -481,7 +471,6 @@ func collectMethodsRecursive(pkg string, f []*ast.Field) []string { } return methodNames - } func firstToLower(name string) string { @@ -544,5 +533,4 @@ func varName(name string) string { } return name - } diff --git a/codegen/methods_test.go b/codegen/methods_test.go index 77399f4e..66000f4e 100644 --- a/codegen/methods_test.go +++ b/codegen/methods_test.go @@ -25,7 +25,6 @@ import ( ) func TestMethods(t *testing.T) { - var ( zeroIE = reflect.TypeOf((*IEmbed)(nil)).Elem() zeroIEOnly = reflect.TypeOf((*IEOnly)(nil)).Elem() @@ -58,7 +57,6 @@ func TestMethods(t *testing.T) { methodsStr := fmt.Sprint(methods) c.Assert(methodsStr, qt.Contains, "MethodEmbed3(arg0 string) string") - }) t.Run("ToMarshalJSON", func(t *testing.T) { @@ -76,9 +74,7 @@ func TestMethods(t *testing.T) { c.Assert(pkg, qt.Contains, "encoding/json") fmt.Println(pkg) - }) - } type I interface { diff --git a/commands/check.go b/commands/check.go index f36f2396..f9be8485 100644 --- a/commands/check.go +++ b/commands/check.go @@ -26,9 +26,10 @@ type checkCmd struct { } func newCheckCmd() *checkCmd { - return &checkCmd{baseCmd: &baseCmd{cmd: &cobra.Command{ - Use: "check", - Short: "Contains some verification checks", - }, + return &checkCmd{baseCmd: &baseCmd{ + cmd: &cobra.Command{ + Use: "check", + Short: "Contains some verification checks", + }, }} } diff --git a/commands/check_darwin.go b/commands/check_darwin.go index 9291be84..ac542916 100644 --- a/commands/check_darwin.go +++ b/commands/check_darwin.go @@ -24,10 +24,11 @@ type checkCmd struct { } func newCheckCmd() *checkCmd { - cc := &checkCmd{baseCmd: &baseCmd{cmd: &cobra.Command{ - Use: "check", - Short: "Contains some verification checks", - }, + cc := &checkCmd{baseCmd: &baseCmd{ + cmd: &cobra.Command{ + Use: "check", + Short: "Contains some verification checks", + }, }} cc.cmd.AddCommand(newLimitCmd().getCommand()) diff --git a/commands/commandeer.go b/commands/commandeer.go index e0eae4a6..024651aa 100644 --- a/commands/commandeer.go +++ b/commands/commandeer.go @@ -16,24 +16,22 @@ package commands import ( "bytes" "errors" + "io/ioutil" + "os" + "path/filepath" + "regexp" "sync" + "time" hconfig "github.com/gohugoio/hugo/config" "golang.org/x/sync/semaphore" - "io/ioutil" - "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hugo" jww "github.com/spf13/jwalterweatherman" - "os" - "path/filepath" - "regexp" - "time" - "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/config" @@ -156,7 +154,6 @@ func (c *commandeer) initFs(fs *hugofs.Fs) error { } func newCommandeer(mustHaveConfigFile, running bool, h *hugoBuilderCommon, f flagsToConfigHandler, cfgInit func(c *commandeer) error, subCmdVs ...*cobra.Command) (*commandeer, error) { - var rebuildDebouncer func(f func()) if running { // The time value used is tested with mass content replacements in a fairly big Hugo site. @@ -248,7 +245,6 @@ func (f *fileChangeDetector) PrepareNew() { } func (c *commandeer) loadConfig(mustHaveConfigFile, running bool) error { - if c.DepsCfg == nil { c.DepsCfg = &deps.DepsCfg{} } @@ -277,7 +273,6 @@ func (c *commandeer) loadConfig(mustHaveConfigFile, running bool) error { environment := c.h.getEnvironment(running) doWithConfig := func(cfg config.Provider) error { - if c.ftch != nil { c.ftch.flagsToConfig(cfg) } @@ -309,7 +304,8 @@ func (c *commandeer) loadConfig(mustHaveConfigFile, running bool) error { Filename: c.h.cfgFile, AbsConfigDir: c.h.getConfigDir(dir), Environ: os.Environ(), - Environment: environment}, + Environment: environment, + }, cfgSetAndInit, doWithConfig) @@ -389,7 +385,7 @@ func (c *commandeer) loadConfig(mustHaveConfigFile, running bool) error { } // To debug hard-to-find path issues. - //fs.Destination = hugofs.NewStacktracerFs(fs.Destination, `fr/fr`) + // fs.Destination = hugofs.NewStacktracerFs(fs.Destination, `fr/fr`) err = c.initFs(fs) if err != nil { @@ -402,7 +398,6 @@ func (c *commandeer) loadConfig(mustHaveConfigFile, running bool) error { h, err = hugolib.NewHugoSites(*c.DepsCfg) c.hugoSites = h close(c.created) - }) if err != nil { @@ -418,5 +413,4 @@ func (c *commandeer) loadConfig(mustHaveConfigFile, running bool) error { cfg.Logger.Infoln("Using config file:", config.ConfigFileUsed()) return nil - } diff --git a/commands/commands.go b/commands/commands.go index ce5f0ff7..1135dc01 100644 --- a/commands/commands.go +++ b/commands/commands.go @@ -88,6 +88,7 @@ var _ commandsBuilderGetter = (*baseBuilderCmd)(nil) type commandsBuilderGetter interface { getCommandsBuilder() *commandsBuilder } + type baseBuilderCmd struct { *baseCmd *commandsBuilder @@ -138,7 +139,6 @@ func (c *nilCommand) getCommand() *cobra.Command { } func (c *nilCommand) flagsToConfig(cfg config.Provider) { - } func (b *commandsBuilder) newHugoCmd() *hugoCmd { diff --git a/commands/commands_test.go b/commands/commands_test.go index 22e99685..0b154316 100644 --- a/commands/commands_test.go +++ b/commands/commands_test.go @@ -35,7 +35,6 @@ import ( ) func TestExecute(t *testing.T) { - c := qt.New(t) createSite := func(c *qt.C) (string, func()) { @@ -124,7 +123,6 @@ func TestExecute(t *testing.T) { c.Assert(config, qt.Contains, "baseURL = \"http://example.org/\"") checkNewSiteInited(c, siteDir) }) - } func checkNewSiteInited(c *qt.C, basepath string) { @@ -185,7 +183,8 @@ func TestFlags(t *testing.T) { }, { name: "Persistent flags", - args: []string{"server", + args: []string{ + "server", "--config=myconfig.toml", "--configDir=myconfigdir", "--contentDir=mycontent", @@ -235,12 +234,12 @@ func TestFlags(t *testing.T) { // The flag is named i18n-warnings c.Assert(cfg.GetBool("logI18nWarnings"), qt.Equals, true) - - }}} + }, + }, + } for _, test := range tests { c.Run(test.name, func(c *qt.C) { - b := newCommandsBuilder() root := b.addAll().build() @@ -257,11 +256,9 @@ func TestFlags(t *testing.T) { test.check(c, b.commands[0].(*serverCmd)) }) } - } func TestCommandsExecute(t *testing.T) { - c := qt.New(t) dir, clean, err := createSimpleTestSite(t, testSiteConfig{}) @@ -330,7 +327,6 @@ func TestCommandsExecute(t *testing.T) { } } - } type testSiteConfig struct { @@ -399,7 +395,6 @@ Environment: {{ hugo.Environment }} `) return d, clean, nil - } func writeFile(t *testing.T, filename, content string) { diff --git a/commands/convert.go b/commands/convert.go index d8976f7e..3047add0 100644 --- a/commands/convert.go +++ b/commands/convert.go @@ -16,6 +16,7 @@ package commands import ( "bytes" "fmt" + "path/filepath" "strings" "time" @@ -34,14 +35,10 @@ import ( "github.com/gohugoio/hugo/hugolib" - "path/filepath" - "github.com/spf13/cobra" ) -var ( - _ cmder = (*convertCmd)(nil) -) +var _ cmder = (*convertCmd)(nil) type convertCmd struct { outputDir string diff --git a/commands/env.go b/commands/env.go index 76c16b93..975c3bd0 100644 --- a/commands/env.go +++ b/commands/env.go @@ -27,18 +27,19 @@ type envCmd struct { } func newEnvCmd() *envCmd { - return &envCmd{baseCmd: newBaseCmd(&cobra.Command{ - Use: "env", - Short: "Print Hugo version and environment info", - Long: `Print Hugo version and environment info. This is useful in Hugo bug reports.`, - RunE: func(cmd *cobra.Command, args []string) error { - printHugoVersion() - jww.FEEDBACK.Printf("GOOS=%q\n", runtime.GOOS) - jww.FEEDBACK.Printf("GOARCH=%q\n", runtime.GOARCH) - jww.FEEDBACK.Printf("GOVERSION=%q\n", runtime.Version()) + return &envCmd{ + baseCmd: newBaseCmd(&cobra.Command{ + Use: "env", + Short: "Print Hugo version and environment info", + Long: `Print Hugo version and environment info. This is useful in Hugo bug reports.`, + RunE: func(cmd *cobra.Command, args []string) error { + printHugoVersion() + jww.FEEDBACK.Printf("GOOS=%q\n", runtime.GOOS) + jww.FEEDBACK.Printf("GOARCH=%q\n", runtime.GOARCH) + jww.FEEDBACK.Printf("GOVERSION=%q\n", runtime.Version()) - return nil - }, - }), + return nil + }, + }), } } diff --git a/commands/genautocomplete.go b/commands/genautocomplete.go index b0b98abb..e8d9890c 100644 --- a/commands/genautocomplete.go +++ b/commands/genautocomplete.go @@ -59,7 +59,6 @@ or just source them in directly: } err := cmd.Root().GenBashCompletionFile(cc.autocompleteTarget) - if err != nil { return err } diff --git a/commands/genchromastyles.go b/commands/genchromastyles.go index 6d54b6ab..53fb2be6 100644 --- a/commands/genchromastyles.go +++ b/commands/genchromastyles.go @@ -22,9 +22,7 @@ import ( "github.com/spf13/cobra" ) -var ( - _ cmder = (*genChromaStyles)(nil) -) +var _ cmder = (*genChromaStyles)(nil) type genChromaStyles struct { style string diff --git a/commands/gendocshelper.go b/commands/gendocshelper.go index 68ac035e..34d45154 100644 --- a/commands/gendocshelper.go +++ b/commands/gendocshelper.go @@ -23,9 +23,7 @@ import ( "github.com/spf13/cobra" ) -var ( - _ cmder = (*genDocsHelper)(nil) -) +var _ cmder = (*genDocsHelper)(nil) type genDocsHelper struct { target string @@ -70,5 +68,4 @@ func (g *genDocsHelper) generate() error { fmt.Println("Done!") return nil - } diff --git a/commands/hugo.go b/commands/hugo.go index 58f33b77..b850f7e6 100644 --- a/commands/hugo.go +++ b/commands/hugo.go @@ -19,10 +19,16 @@ import ( "context" "fmt" "io/ioutil" + "os" "os/signal" + "path/filepath" + "runtime" "runtime/pprof" "runtime/trace" + "strings" "sync/atomic" + "syscall" + "time" "github.com/gohugoio/hugo/hugofs" @@ -34,18 +40,10 @@ import ( "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/terminal" - "syscall" - "github.com/gohugoio/hugo/hugolib/filesystems" "golang.org/x/sync/errgroup" - "os" - "path/filepath" - "runtime" - "strings" - "time" - "github.com/gohugoio/hugo/config" flag "github.com/spf13/pflag" @@ -82,7 +80,6 @@ func (r Response) IsUserError() bool { // Execute adds all child commands to the root command HugoCmd and sets flags appropriately. // The args are usually filled with os.Args[1:]. func Execute(args []string) Response { - hugoCmd := newCommandsBuilder().addAll().build() cmd := hugoCmd.getCommand() cmd.SetArgs(args) @@ -120,14 +117,12 @@ func initializeConfig(mustHaveConfigFile, running bool, h *hugoBuilderCommon, f flagsToConfigHandler, cfgInit func(c *commandeer) error) (*commandeer, error) { - c, err := newCommandeer(mustHaveConfigFile, running, h, f, cfgInit) if err != nil { return nil, err } return c, nil - } func (c *commandeer) createLogger(cfg config.Provider, running bool) (loggers.Logger, error) { @@ -246,7 +241,6 @@ func initializeFlags(cmd *cobra.Command, cfg config.Provider) { setValueFromFlag(cmd.Flags(), "destination", cfg, "publishDir", false) setValueFromFlag(cmd.Flags(), "i18n-warnings", cfg, "logI18nWarnings", false) setValueFromFlag(cmd.Flags(), "path-warnings", cfg, "logPathWarnings", false) - } func setValueFromFlag(flags *flag.FlagSet, key string, cfg config.Provider, targetKey string, force bool) { @@ -282,7 +276,6 @@ func isTerminal() bool { } func (c *commandeer) fullBuild() error { - var ( g errgroup.Group langCount map[string]uint64 @@ -298,7 +291,6 @@ func (c *commandeer) fullBuild() error { } copyStaticFunc := func() error { - cnt, err := c.copyStatic() if err != nil { return errors.Wrap(err, "Error copying static files") @@ -346,7 +338,6 @@ func (c *commandeer) fullBuild() error { } return nil - } func (c *commandeer) initCPUProfile() (func(), error) { @@ -419,7 +410,6 @@ func (c *commandeer) initMutexProfile() (func(), error) { pprof.Lookup("mutex").WriteTo(f, 0) f.Close() }, nil - } func (c *commandeer) initMemTicker() func() { @@ -429,7 +419,6 @@ func (c *commandeer) initMemTicker() func() { var m runtime.MemStats runtime.ReadMemStats(&m) fmt.Printf("\n\nAlloc = %v\nTotalAlloc = %v\nSys = %v\nNumGC = %v\n\n", formatByteCount(m.Alloc), formatByteCount(m.TotalAlloc), formatByteCount(m.Sys), m.NumGC) - } go func() { @@ -442,7 +431,6 @@ func (c *commandeer) initMemTicker() func() { printMem() return } - } }() @@ -452,7 +440,6 @@ func (c *commandeer) initMemTicker() func() { } func (c *commandeer) initProfiling() (func(), error) { - stopCPUProf, err := c.initCPUProfile() if err != nil { return nil, err @@ -538,7 +525,7 @@ func (c *commandeer) build() error { checkErr(c.Logger, err) defer watcher.Close() - var sigs = make(chan os.Signal, 1) + sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) <-sigs @@ -584,7 +571,6 @@ func (c *commandeer) copyStatic() (map[string]uint64, error) { } func (c *commandeer) doWithPublishDirs(f func(sourceFs *filesystems.SourceFilesystem) (uint64, error)) (map[string]uint64, error) { - langCount := make(map[string]uint64) staticFilesystems := c.hugo().BaseFs.SourceFilesystems.Static @@ -712,7 +698,6 @@ func (c *commandeer) getDirList() ([]string, error) { } return nil - } watchFiles := c.hugo().PathSpec.BaseFs.WatchDirs() @@ -753,7 +738,6 @@ func (c *commandeer) rebuildSites(events []fsnotify.Event) error { c.buildErr = nil visited := c.visitedURLs.PeekAllSet() if c.fastRenderMode { - // Make sure we always render the home pages for _, l := range c.languages { langPath := c.hugo().PathSpec.GetLangSubDir(l.Lang) @@ -763,7 +747,6 @@ func (c *commandeer) rebuildSites(events []fsnotify.Event) error { home := c.hugo().PathSpec.PrependBasePath("/"+langPath, false) visited[home] = true } - } return c.hugo().Build(hugolib.BuildCfg{RecentlyVisited: visited, ErrRecovery: c.wasError}, events...) } @@ -793,13 +776,11 @@ func (c *commandeer) fullRebuild(changeType string) { c.fullRebuildSem.Acquire(context.Background(), 1) go func() { - defer c.fullRebuildSem.Release(1) c.printChangeDetected(changeType) defer func() { - // Allow any file system events to arrive back. // This will block any rebuild on config changes for the // duration of the sleep. @@ -848,7 +829,6 @@ func (c *commandeer) newWatcher(dirList ...string) (*watcher.Batcher, error) { } watcher, err := watcher.New(1 * time.Second) - if err != nil { return nil, err } @@ -909,7 +889,6 @@ func (c *commandeer) handleEvents(watcher *watcher.Batcher, staticSyncer *staticSyncer, evs []fsnotify.Event, configSet map[string]bool) { - defer func() { c.wasError = false }() @@ -950,7 +929,6 @@ func (c *commandeer) handleEvents(watcher *watcher.Batcher, time.Sleep(100 * time.Millisecond) } } - } // Config file(s) changed. Need full rebuild. @@ -1194,7 +1172,6 @@ func partitionDynamicEvents(sourceFs *filesystems.SourceFilesystems, events []fs } } return - } func pickOneWriteOrCreatePath(events []fsnotify.Event) string { diff --git a/commands/hugo_test.go b/commands/hugo_test.go index 65a0416c..4bead09f 100644 --- a/commands/hugo_test.go +++ b/commands/hugo_test.go @@ -44,5 +44,4 @@ contentDir = "thisdoesnotexist" _, err = cmd.ExecuteC() c.Assert(err, qt.IsNil) - } diff --git a/commands/import_jekyll.go b/commands/import_jekyll.go index 2dd0fc05..b9ea56d4 100644 --- a/commands/import_jekyll.go +++ b/commands/import_jekyll.go @@ -74,11 +74,9 @@ Import from Jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root cc.cmd.AddCommand(importJekyllCmd) return cc - } func (i *importCmd) importFromJekyll(cmd *cobra.Command, args []string) error { - if len(args) < 2 { return newUserError(`import from jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`.") } @@ -255,13 +253,11 @@ func (i *importCmd) loadJekyllConfig(fs afero.Fs, jekyllRoot string) map[string] defer f.Close() b, err := ioutil.ReadAll(f) - if err != nil { return nil } c, err := metadecoders.Default.UnmarshalToMap(b, metadecoders.YAML) - if err != nil { return nil } @@ -338,8 +334,10 @@ func (i *importCmd) copyJekyllFilesAndFolders(jekyllRoot, dest string, jekyllPos } } else { lowerEntryName := strings.ToLower(entry.Name()) - exceptSuffix := []string{".md", ".markdown", ".html", ".htm", - ".xml", ".textile", "rakefile", "gemfile", ".lock"} + exceptSuffix := []string{ + ".md", ".markdown", ".html", ".htm", + ".xml", ".textile", "rakefile", "gemfile", ".lock", + } isExcept := false for _, suffix := range exceptSuffix { if strings.HasSuffix(lowerEntryName, suffix) { @@ -602,8 +600,8 @@ func replaceImageTag(match string) string { } result.WriteString(">}}") return result.String() - } + func replaceOptionalPart(buffer *bytes.Buffer, partName string, part string) { if len(part) > 0 { buffer.WriteString(partName + "=\"" + part + "\" ") diff --git a/commands/import_jekyll_test.go b/commands/import_jekyll_test.go index c87c224b..3819d03a 100644 --- a/commands/import_jekyll_test.go +++ b/commands/import_jekyll_test.go @@ -53,25 +53,41 @@ func TestConvertJekyllMetadata(t *testing.T) { draft bool expect string }{ - {map[interface{}]interface{}{}, "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), false, - `{"date":"2015-10-01T00:00:00Z"}`}, - {map[interface{}]interface{}{}, "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), true, - `{"date":"2015-10-01T00:00:00Z","draft":true}`}, - {map[interface{}]interface{}{"Permalink": "/permalink.html", "layout": "post"}, + { + map[interface{}]interface{}{}, "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), false, - `{"date":"2015-10-01T00:00:00Z","url":"/permalink.html"}`}, - {map[interface{}]interface{}{"permalink": "/permalink.html"}, + `{"date":"2015-10-01T00:00:00Z"}`, + }, + { + map[interface{}]interface{}{}, + "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), true, + `{"date":"2015-10-01T00:00:00Z","draft":true}`, + }, + { + map[interface{}]interface{}{"Permalink": "/permalink.html", "layout": "post"}, "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), false, - `{"date":"2015-10-01T00:00:00Z","url":"/permalink.html"}`}, - {map[interface{}]interface{}{"category": nil, "permalink": 123}, + `{"date":"2015-10-01T00:00:00Z","url":"/permalink.html"}`, + }, + { + map[interface{}]interface{}{"permalink": "/permalink.html"}, "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), false, - `{"date":"2015-10-01T00:00:00Z"}`}, - {map[interface{}]interface{}{"Excerpt_Separator": "sep"}, + `{"date":"2015-10-01T00:00:00Z","url":"/permalink.html"}`, + }, + { + map[interface{}]interface{}{"category": nil, "permalink": 123}, "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), false, - `{"date":"2015-10-01T00:00:00Z","excerpt_separator":"sep"}`}, - {map[interface{}]interface{}{"category": "book", "layout": "post", "Others": "Goods", "Date": "2015-10-01 12:13:11"}, + `{"date":"2015-10-01T00:00:00Z"}`, + }, + { + map[interface{}]interface{}{"Excerpt_Separator": "sep"}, "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), false, - `{"Others":"Goods","categories":["book"],"date":"2015-10-01T12:13:11Z"}`}, + `{"date":"2015-10-01T00:00:00Z","excerpt_separator":"sep"}`, + }, + { + map[interface{}]interface{}{"category": "book", "layout": "post", "Others": "Goods", "Date": "2015-10-01 12:13:11"}, + "testPost", time.Date(2015, 10, 1, 0, 0, 0, 0, time.UTC), false, + `{"Others":"Goods","categories":["book"],"date":"2015-10-01T12:13:11Z"}`, + }, } for _, data := range testDataList { @@ -90,44 +106,68 @@ func TestConvertJekyllContent(t *testing.T) { content string expect string }{ - {map[interface{}]interface{}{}, - "Test content\r\n\npart2 content", "Test content\n\npart2 content"}, - {map[interface{}]interface{}{}, - "Test content\n\npart2 content", "Test content\n\npart2 content"}, - {map[interface{}]interface{}{"excerpt_separator": ""}, + { + map[interface{}]interface{}{}, + "Test content\r\n\npart2 content", "Test content\n\npart2 content", + }, + { + map[interface{}]interface{}{}, + "Test content\n\npart2 content", "Test content\n\npart2 content", + }, + { + map[interface{}]interface{}{"excerpt_separator": ""}, "Test content\n\npart2 content", - "---\nexcerpt_separator: \n---\nTest content\n\npart2 content"}, + "---\nexcerpt_separator: \n---\nTest content\n\npart2 content", + }, {map[interface{}]interface{}{}, "{% raw %}text{% endraw %}", "text"}, {map[interface{}]interface{}{}, "{%raw%} text2 {%endraw %}", "text2"}, - {map[interface{}]interface{}{}, + { + map[interface{}]interface{}{}, "{% highlight go %}\nvar s int\n{% endhighlight %}", - "{{< highlight go >}}\nvar s int\n{{< / highlight >}}"}, - {map[interface{}]interface{}{}, + "{{< highlight go >}}\nvar s int\n{{< / highlight >}}", + }, + { + map[interface{}]interface{}{}, "{% highlight go linenos hl_lines=\"1 2\" %}\nvar s string\nvar i int\n{% endhighlight %}", - "{{< highlight go \"linenos=table,hl_lines=1 2\" >}}\nvar s string\nvar i int\n{{< / highlight >}}"}, + "{{< highlight go \"linenos=table,hl_lines=1 2\" >}}\nvar s string\nvar i int\n{{< / highlight >}}", + }, // Octopress image tag - {map[interface{}]interface{}{}, + { + map[interface{}]interface{}{}, "{% img http://placekitten.com/890/280 %}", - "{{< figure src=\"http://placekitten.com/890/280\" >}}"}, - {map[interface{}]interface{}{}, + "{{< figure src=\"http://placekitten.com/890/280\" >}}", + }, + { + map[interface{}]interface{}{}, "{% img left http://placekitten.com/320/250 Place Kitten #2 %}", - "{{< figure class=\"left\" src=\"http://placekitten.com/320/250\" title=\"Place Kitten #2\" >}}"}, - {map[interface{}]interface{}{}, + "{{< figure class=\"left\" src=\"http://placekitten.com/320/250\" title=\"Place Kitten #2\" >}}", + }, + { + map[interface{}]interface{}{}, "{% img right http://placekitten.com/300/500 150 250 'Place Kitten #3' %}", - "{{< figure class=\"right\" src=\"http://placekitten.com/300/500\" width=\"150\" height=\"250\" title=\"Place Kitten #3\" >}}"}, - {map[interface{}]interface{}{}, + "{{< figure class=\"right\" src=\"http://placekitten.com/300/500\" width=\"150\" height=\"250\" title=\"Place Kitten #3\" >}}", + }, + { + map[interface{}]interface{}{}, "{% img right http://placekitten.com/300/500 150 250 'Place Kitten #4' 'An image of a very cute kitten' %}", - "{{< figure class=\"right\" src=\"http://placekitten.com/300/500\" width=\"150\" height=\"250\" title=\"Place Kitten #4\" alt=\"An image of a very cute kitten\" >}}"}, - {map[interface{}]interface{}{}, + "{{< figure class=\"right\" src=\"http://placekitten.com/300/500\" width=\"150\" height=\"250\" title=\"Place Kitten #4\" alt=\"An image of a very cute kitten\" >}}", + }, + { + map[interface{}]interface{}{}, "{% img http://placekitten.com/300/500 150 250 'Place Kitten #4' 'An image of a very cute kitten' %}", - "{{< figure src=\"http://placekitten.com/300/500\" width=\"150\" height=\"250\" title=\"Place Kitten #4\" alt=\"An image of a very cute kitten\" >}}"}, - {map[interface{}]interface{}{}, + "{{< figure src=\"http://placekitten.com/300/500\" width=\"150\" height=\"250\" title=\"Place Kitten #4\" alt=\"An image of a very cute kitten\" >}}", + }, + { + map[interface{}]interface{}{}, "{% img right /placekitten/300/500 'Place Kitten #4' 'An image of a very cute kitten' %}", - "{{< figure class=\"right\" src=\"/placekitten/300/500\" title=\"Place Kitten #4\" alt=\"An image of a very cute kitten\" >}}"}, - {map[interface{}]interface{}{"category": "book", "layout": "post", "Date": "2015-10-01 12:13:11"}, + "{{< figure class=\"right\" src=\"/placekitten/300/500\" title=\"Place Kitten #4\" alt=\"An image of a very cute kitten\" >}}", + }, + { + map[interface{}]interface{}{"category": "book", "layout": "post", "Date": "2015-10-01 12:13:11"}, "somecontent", - "---\nDate: \"2015-10-01 12:13:11\"\ncategory: book\nlayout: post\n---\nsomecontent"}, + "---\nDate: \"2015-10-01 12:13:11\"\ncategory: book\nlayout: post\n---\nsomecontent", + }, } for _, data := range testDataList { result, err := convertJekyllContent(data.metadata, data.content) diff --git a/commands/list.go b/commands/list.go index 0b7c1879..3c09cad2 100644 --- a/commands/list.go +++ b/commands/list.go @@ -46,7 +46,6 @@ func (lc *listCmd) buildSites(config map[string]interface{}) (*hugolib.HugoSites } sites, err := hugolib.NewHugoSites(*c.DepsCfg) - if err != nil { return nil, newSystemError("Error creating sites", err) } @@ -77,7 +76,6 @@ List requires a subcommand, e.g. ` + "`hugo list drafts`.", Long: `List all of the drafts in your content directory.`, RunE: func(cmd *cobra.Command, args []string) error { sites, err := cc.buildSites(map[string]interface{}{"buildDrafts": true}) - if err != nil { return newSystemError("Error building sites", err) } @@ -97,7 +95,6 @@ List requires a subcommand, e.g. ` + "`hugo list drafts`.", Long: `List all of the posts in your content directory which will be posted in the future.`, RunE: func(cmd *cobra.Command, args []string) error { sites, err := cc.buildSites(map[string]interface{}{"buildFuture": true}) - if err != nil { return newSystemError("Error building sites", err) } @@ -126,7 +123,6 @@ List requires a subcommand, e.g. ` + "`hugo list drafts`.", Long: `List all of the posts in your content directory which has already expired.`, RunE: func(cmd *cobra.Command, args []string) error { sites, err := cc.buildSites(map[string]interface{}{"buildExpired": true}) - if err != nil { return newSystemError("Error building sites", err) } @@ -159,7 +155,6 @@ List requires a subcommand, e.g. ` + "`hugo list drafts`.", "buildDrafts": true, "buildFuture": true, }) - if err != nil { return newSystemError("Error building sites", err) } diff --git a/commands/mod.go b/commands/mod.go index b390d1e7..c6870e1d 100644 --- a/commands/mod.go +++ b/commands/mod.go @@ -91,7 +91,6 @@ Also note that if you configure a positive maxAge for the "modules" file cache, } func (b *commandsBuilder) newModCmd() *modCmd { - c := &modCmd{} const commonUsage = ` @@ -264,7 +263,6 @@ If a module is vendored, that is where Hugo will look for it's dependencies. c.baseBuilderCmd = b.newBuilderCmd(cmd) return c - } func (c *modCmd) withModsClient(failOnMissingConfig bool, f func(*modules.Client) error) error { diff --git a/commands/mod_npm.go b/commands/mod_npm.go index a73908e7..852d9857 100644 --- a/commands/mod_npm.go +++ b/commands/mod_npm.go @@ -20,7 +20,6 @@ import ( ) func newModNPMCmd(c *modCmd) *cobra.Command { - cmd := &cobra.Command{ Use: "npm", Short: "Various npm helpers.", @@ -47,7 +46,6 @@ removed from Hugo, but we need to test this out in "real life" to get a feel of so this may/will change in future versions of Hugo. `, RunE: func(cmd *cobra.Command, args []string) error { - return c.withHugo(func(h *hugolib.HugoSites) error { return npm.Pack(h.BaseFs.SourceFs, h.BaseFs.Assets.Dirs) }) diff --git a/commands/new.go b/commands/new.go index 576976e8..a2d87371 100644 --- a/commands/new.go +++ b/commands/new.go @@ -72,7 +72,6 @@ func (n *newCmd) newContent(cmd *cobra.Command, args []string) error { } c, err := initializeConfig(true, false, &n.hugoBuilderCommon, n, cfgInit) - if err != nil { return err } diff --git a/commands/new_site.go b/commands/new_site.go index 9fb47096..6fac2c22 100644 --- a/commands/new_site.go +++ b/commands/new_site.go @@ -58,7 +58,6 @@ Use ` + "`hugo new [contentPath]`" + ` to create new content.`, cc.baseBuilderCmd = b.newBuilderBasicCmd(cmd) return cc - } func (n *newSiteCmd) doNewSite(fs *hugofs.Fs, basepath string, force bool) error { diff --git a/commands/new_theme.go b/commands/new_theme.go index cb85a1db..3ffd85c0 100644 --- a/commands/new_theme.go +++ b/commands/new_theme.go @@ -53,7 +53,6 @@ as you see fit.`, // newTheme creates a new Hugo theme template func (n *newThemeCmd) newTheme(cmd *cobra.Command, args []string) error { c, err := initializeConfig(false, false, &n.hugoBuilderCommon, n, nil) - if err != nil { return err } @@ -145,7 +144,6 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } func (n *newThemeCmd) createThemeMD(fs *hugofs.Fs, inpath string) (err error) { - by := []byte(`# theme.toml template for a Hugo theme # See https://github.com/gohugoio/hugoThemes#themetoml for an example diff --git a/commands/nodeploy.go b/commands/nodeploy.go index 146a61f1..363602c5 100644 --- a/commands/nodeploy.go +++ b/commands/nodeploy.go @@ -17,6 +17,7 @@ package commands import ( "errors" + "github.com/spf13/cobra" ) diff --git a/commands/release.go b/commands/release.go index 4de165f3..3b78590e 100644 --- a/commands/release.go +++ b/commands/release.go @@ -61,7 +61,6 @@ func (c *releaseCommandeer) getCommand() *cobra.Command { } func (c *releaseCommandeer) flagsToConfig(cfg config.Provider) { - } func (r *releaseCommandeer) release() error { diff --git a/commands/server.go b/commands/server.go index ef504f20..93d82599 100644 --- a/commands/server.go +++ b/commands/server.go @@ -228,7 +228,6 @@ func (sc *serverCmd) server(cmd *cobra.Command, args []string) error { } return err - } if err := memStats(); err != nil { @@ -262,7 +261,6 @@ func (sc *serverCmd) server(cmd *cobra.Command, args []string) error { jww.FEEDBACK.Printf("Watching for changes in %s\n", group) } watcher, err := c.newWatcher(watchDirs...) - if err != nil { return err } @@ -272,7 +270,6 @@ func (sc *serverCmd) server(cmd *cobra.Command, args []string) error { } return c.serve(sc) - } func getRootWatchDirsStr(baseDir string, watchDirs []string) string { @@ -301,7 +298,6 @@ func (f *fileServer) rewriteRequest(r *http.Request, toPath string) *http.Reques r2.Header.Set("X-Rewrite-Original-URI", r.URL.RequestURI()) return r2 - } func (f *fileServer) createEndpoint(i int) (*http.ServeMux, string, string, error) { @@ -393,7 +389,6 @@ func (f *fileServer) createEndpoint(i int) (*http.ServeMux, string, string, erro } else { doRedirect = false } - } } @@ -413,7 +408,6 @@ func (f *fileServer) createEndpoint(i int) (*http.ServeMux, string, string, erro } if f.c.fastRenderMode && f.c.buildErr == nil { - if strings.HasSuffix(requestURI, "/") || strings.HasSuffix(requestURI, "html") || strings.HasSuffix(requestURI, "htm") { if !f.c.visitedURLs.Contains(requestURI) { // If not already on stack, re-render that single page. @@ -453,8 +447,8 @@ var logErrorRe = regexp.MustCompile(`(?s)ERROR \d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{ func removeErrorPrefixFromLog(content string) string { return logErrorRe.ReplaceAllLiteralString(content, "") } -func (c *commandeer) serve(s *serverCmd) error { +func (c *commandeer) serve(s *serverCmd) error { isMultiHost := c.hugo().IsMultihost() var ( @@ -496,7 +490,7 @@ func (c *commandeer) serve(s *serverCmd) error { livereload.Initialize() } - var sigs = make(chan os.Signal, 1) + sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) for i := range baseURLs { diff --git a/commands/server_test.go b/commands/server_test.go index 04e874f9..cc2a6d92 100644 --- a/commands/server_test.go +++ b/commands/server_test.go @@ -73,7 +73,6 @@ func TestServer(t *testing.T) { // Stop the server. stop <- true - } func TestFixURL(t *testing.T) { @@ -127,7 +126,6 @@ ERROR 2018/10/07 13:11:12 Rebuild failed: logged 1 error(s) withoutError := removeErrorPrefixFromLog(content) c.Assert(strings.Contains(withoutError, "ERROR"), qt.Equals, false) - } func isWindowsCI() bool { diff --git a/commands/static_syncer.go b/commands/static_syncer.go index bd696520..23bdbe2d 100644 --- a/commands/static_syncer.go +++ b/commands/static_syncer.go @@ -128,5 +128,4 @@ func (s *staticSyncer) syncsStaticEvents(staticEvents []fsnotify.Event) error { _, err := c.doWithPublishDirs(syncFn) return err - } diff --git a/common/collections/append.go b/common/collections/append.go index b56455bc..d6fb8924 100644 --- a/common/collections/append.go +++ b/common/collections/append.go @@ -51,7 +51,6 @@ func Append(to interface{}, from ...interface{}) (interface{}, error) { } else if !fromt.AssignableTo(tot) { // Fall back to a []interface{} slice. return appendToInterfaceSliceFromValues(tov, fromv) - } } } diff --git a/common/collections/append_test.go b/common/collections/append_test.go index 4086570b..7d6117de 100644 --- a/common/collections/append_test.go +++ b/common/collections/append_test.go @@ -36,28 +36,44 @@ func TestAppend(t *testing.T) { {nil, []interface{}{"a", "b"}, []string{"a", "b"}}, {nil, []interface{}{nil}, []interface{}{nil}}, {[]interface{}{}, []interface{}{[]string{"c", "d", "e"}}, []string{"c", "d", "e"}}, - {tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}}, + { + tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}}, []interface{}{&tstSlicer{"c"}}, - tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}, &tstSlicer{"c"}}}, - {&tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}}, + tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}, &tstSlicer{"c"}}, + }, + { + &tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}}, []interface{}{&tstSlicer{"c"}}, - tstSlicers{&tstSlicer{"a"}, + tstSlicers{ + &tstSlicer{"a"}, &tstSlicer{"b"}, - &tstSlicer{"c"}}}, - {testSlicerInterfaces{&tstSlicerIn1{"a"}, &tstSlicerIn1{"b"}}, + &tstSlicer{"c"}, + }, + }, + { + testSlicerInterfaces{&tstSlicerIn1{"a"}, &tstSlicerIn1{"b"}}, []interface{}{&tstSlicerIn1{"c"}}, - testSlicerInterfaces{&tstSlicerIn1{"a"}, &tstSlicerIn1{"b"}, &tstSlicerIn1{"c"}}}, + testSlicerInterfaces{&tstSlicerIn1{"a"}, &tstSlicerIn1{"b"}, &tstSlicerIn1{"c"}}, + }, //https://github.com/gohugoio/hugo/issues/5361 - {[]string{"a", "b"}, []interface{}{tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}}}, - []interface{}{"a", "b", &tstSlicer{"a"}, &tstSlicer{"b"}}}, - {[]string{"a", "b"}, []interface{}{&tstSlicer{"a"}}, - []interface{}{"a", "b", &tstSlicer{"a"}}}, + { + []string{"a", "b"}, + []interface{}{tstSlicers{&tstSlicer{"a"}, &tstSlicer{"b"}}}, + []interface{}{"a", "b", &tstSlicer{"a"}, &tstSlicer{"b"}}, + }, + { + []string{"a", "b"}, + []interface{}{&tstSlicer{"a"}}, + []interface{}{"a", "b", &tstSlicer{"a"}}, + }, // Errors {"", []interface{}{[]string{"a", "b"}}, false}, // No string concatenation. - {"ab", + { + "ab", []interface{}{"c"}, - false}, + false, + }, } { result, err := Append(test.start, test.addend...) @@ -71,5 +87,4 @@ func TestAppend(t *testing.T) { c.Assert(err, qt.IsNil) c.Assert(result, qt.DeepEquals, test.expected) } - } diff --git a/common/collections/slice_test.go b/common/collections/slice_test.go index 3ebfe6d1..93bad84d 100644 --- a/common/collections/slice_test.go +++ b/common/collections/slice_test.go @@ -20,11 +20,13 @@ import ( qt "github.com/frankban/quicktest" ) -var _ Slicer = (*tstSlicer)(nil) -var _ Slicer = (*tstSlicerIn1)(nil) -var _ Slicer = (*tstSlicerIn2)(nil) -var _ testSlicerInterface = (*tstSlicerIn1)(nil) -var _ testSlicerInterface = (*tstSlicerIn1)(nil) +var ( + _ Slicer = (*tstSlicer)(nil) + _ Slicer = (*tstSlicerIn1)(nil) + _ Slicer = (*tstSlicerIn2)(nil) + _ testSlicerInterface = (*tstSlicerIn1)(nil) + _ testSlicerInterface = (*tstSlicerIn1)(nil) +) type testSlicerInterface interface { Name() string @@ -54,7 +56,6 @@ func (p *tstSlicerIn1) Slice(in interface{}) (interface{}, error) { default: return nil, errors.New("invalid type") } - } return result, nil } @@ -120,5 +121,4 @@ func TestSlice(t *testing.T) { c.Assert(test.expected, qt.DeepEquals, result, errMsg) } - } diff --git a/common/herrors/error_locator_test.go b/common/herrors/error_locator_test.go index bc34a2cd..0cd5fb2d 100644 --- a/common/herrors/error_locator_test.go +++ b/common/herrors/error_locator_test.go @@ -125,5 +125,4 @@ E`, offsetMatcher) c.Assert(location.Lines, qt.DeepEquals, []string{"A", "B", "C", "D"}) c.Assert(location.Position().LineNumber, qt.Equals, 2) c.Assert(location.LinesPos, qt.Equals, 1) - } diff --git a/common/herrors/file_error.go b/common/herrors/file_error.go index 039c25dc..1cb31ff9 100644 --- a/common/herrors/file_error.go +++ b/common/herrors/file_error.go @@ -21,9 +21,7 @@ import ( "github.com/pkg/errors" ) -var ( - _ causer = (*fileError)(nil) -) +var _ causer = (*fileError)(nil) // FileError represents an error when handling a file: Parsing a config file, // execute a template etc. diff --git a/common/herrors/file_error_test.go b/common/herrors/file_error_test.go index b1b5c5a0..4b42f8f3 100644 --- a/common/herrors/file_error_test.go +++ b/common/herrors/file_error_test.go @@ -52,5 +52,4 @@ func TestToLineNumberError(t *testing.T) { c.Assert(pos.ColumnNumber, qt.Equals, test.columnNumber, errMsg) c.Assert(errors.Cause(got), qt.Not(qt.IsNil)) } - } diff --git a/common/hreflect/helpers.go b/common/hreflect/helpers.go index d936da19..cd5714d2 100644 --- a/common/hreflect/helpers.go +++ b/common/hreflect/helpers.go @@ -67,7 +67,6 @@ func IsTruthful(in interface{}) bool { default: return IsTruthfulValue(reflect.ValueOf(in)) } - } var zeroType = reflect.TypeOf((*types.Zeroer)(nil)).Elem() diff --git a/common/hugo/hugo_test.go b/common/hugo/hugo_test.go index 8840a9e9..0862f36e 100644 --- a/common/hugo/hugo_test.go +++ b/common/hugo/hugo_test.go @@ -35,5 +35,4 @@ func TestHugoInfo(t *testing.T) { devHugoInfo := NewInfo("development") c.Assert(devHugoInfo.IsProduction(), qt.Equals, false) - } diff --git a/common/hugo/version.go b/common/hugo/version.go index 038537fc..b87dab54 100644 --- a/common/hugo/version.go +++ b/common/hugo/version.go @@ -16,7 +16,6 @@ package hugo import ( "fmt" "io" - "runtime" "strings" @@ -146,7 +145,6 @@ func BuildVersionString() string { } return fmt.Sprintf("%s %s %s BuildDate: %s", program, version, osArch, date) - } func version(version float32, patchVersion int, suffix string) string { diff --git a/common/loggers/ignorableLogger.go b/common/loggers/ignorableLogger.go index 1bd4d99b..766aae07 100644 --- a/common/loggers/ignorableLogger.go +++ b/common/loggers/ignorableLogger.go @@ -34,7 +34,6 @@ func NewIgnorableLogger(logger Logger, statements ...string) IgnorableLogger { statementsSet := make(map[string]bool) for _, s := range statements { statementsSet[strings.ToLower(s)] = true - } return ignorableLogger{ Logger: logger, diff --git a/common/loggers/loggers.go b/common/loggers/loggers.go index 5c04b9ea..c9b5d21b 100644 --- a/common/loggers/loggers.go +++ b/common/loggers/loggers.go @@ -29,10 +29,8 @@ import ( jww "github.com/spf13/jwalterweatherman" ) -var ( - // Counts ERROR logs to the global jww logger. - GlobalErrorCounter *jww.Counter -) +// Counts ERROR logs to the global jww logger. +var GlobalErrorCounter *jww.Counter func init() { GlobalErrorCounter = &jww.Counter{} @@ -253,7 +251,6 @@ func (a labelColorizer) Write(p []byte) (n int, err error) { // bytes, so we lie a little. _, err = a.w.Write([]byte(replaced)) return len(p), err - } // InitGlobalLogger initializes the global logger, used in some rare cases. @@ -264,7 +261,6 @@ func InitGlobalLogger(stdoutThreshold, logThreshold jww.Threshold, outHandle, lo jww.SetLogOutput(logHandle) jww.SetLogThreshold(logThreshold) jww.SetStdoutThreshold(stdoutThreshold) - } func getLogWriters(outHandle, logHandle io.Writer) (io.Writer, io.Writer) { @@ -279,7 +275,6 @@ func getLogWriters(outHandle, logHandle io.Writer) (io.Writer, io.Writer) { } return outHandle, logHandle - } type fatalLogWriter int diff --git a/common/loggers/loggers_test.go b/common/loggers/loggers_test.go index 7af3ca9d..0c0cc859 100644 --- a/common/loggers/loggers_test.go +++ b/common/loggers/loggers_test.go @@ -31,7 +31,6 @@ func TestLogger(t *testing.T) { l.Warnln("A warning") c.Assert(l.LogCounters().ErrorCounter.Count(), qt.Equals, uint64(2)) - } func TestLoggerToWriterWithPrefix(t *testing.T) { diff --git a/common/maps/maps_test.go b/common/maps/maps_test.go index bde77071..7e527aac 100644 --- a/common/maps/maps_test.go +++ b/common/maps/maps_test.go @@ -154,5 +154,4 @@ func TestRenameKeys(t *testing.T) { if !reflect.DeepEqual(expected, m) { t.Errorf("Expected\n%#v, got\n%#v\n", expected, m) } - } diff --git a/common/maps/params.go b/common/maps/params.go index 5e973051..4c881093 100644 --- a/common/maps/params.go +++ b/common/maps/params.go @@ -80,7 +80,6 @@ func GetNestedParam(keyStr, separator string, candidates ...Params) (interface{} } return nil, nil - } func GetNestedParamFn(keyStr, separator string, lookupFn func(key string) interface{}) (interface{}, string, map[string]interface{}, error) { diff --git a/common/maps/params_test.go b/common/maps/params_test.go index 46d672d8..df8cbf8d 100644 --- a/common/maps/params_test.go +++ b/common/maps/params_test.go @@ -20,7 +20,6 @@ import ( ) func TestGetNestedParam(t *testing.T) { - m := map[string]interface{}{ "string": "value", "first": 1, @@ -48,12 +47,10 @@ func TestGetNestedParam(t *testing.T) { c.Assert(must("nested.nestednested.color", ".", m), qt.Equals, "green") c.Assert(must("string.name", ".", m), qt.IsNil) c.Assert(must("nested.foo", ".", m), qt.IsNil) - } // https://github.com/gohugoio/hugo/issues/7903 func TestGetNestedParamFnNestedNewKey(t *testing.T) { - c := qt.New(t) nested := map[string]interface{}{ @@ -71,5 +68,4 @@ func TestGetNestedParamFnNestedNewKey(t *testing.T) { c.Assert(existing, qt.IsNil) c.Assert(nestedKey, qt.Equals, "new") c.Assert(owner, qt.DeepEquals, nested) - } diff --git a/common/maps/scratch.go b/common/maps/scratch.go index 7a3cd374..ccd03ef3 100644 --- a/common/maps/scratch.go +++ b/common/maps/scratch.go @@ -51,7 +51,6 @@ func NewScratcher() Scratcher { // // If the first add for a key is an array or slice, then the next value(s) will be appended. func (c *Scratch) Add(key string, newAddend interface{}) (string, error) { - var newVal interface{} c.mu.RLock() existingAddend, found := c.values[key] diff --git a/common/maps/scratch_test.go b/common/maps/scratch_test.go index 40df3bb6..d893ccb0 100644 --- a/common/maps/scratch_test.go +++ b/common/maps/scratch_test.go @@ -53,7 +53,6 @@ func TestScratchAdd(t *testing.T) { if err == nil { t.Errorf("Expected error from invalid arithmetic") } - } func TestScratchAddSlice(t *testing.T) { @@ -96,7 +95,6 @@ func TestScratchAddTypedSliceToInterfaceSlice(t *testing.T) { _, err := scratch.Add("slice", []int{1, 2}) c.Assert(err, qt.IsNil) c.Assert(scratch.Get("slice"), qt.DeepEquals, []int{1, 2}) - } // https://github.com/gohugoio/hugo/issues/5361 @@ -110,7 +108,6 @@ func TestScratchAddDifferentTypedSliceToInterfaceSlice(t *testing.T) { _, err := scratch.Add("slice", []int{1, 2}) c.Assert(err, qt.IsNil) c.Assert(scratch.Get("slice"), qt.DeepEquals, []interface{}{"foo", 1, 2}) - } func TestScratchSet(t *testing.T) { diff --git a/common/para/para_test.go b/common/para/para_test.go index 9b268b0c..e89f9360 100644 --- a/common/para/para_test.go +++ b/common/para/para_test.go @@ -16,7 +16,6 @@ package para import ( "context" "runtime" - "sort" "sync" "sync/atomic" @@ -60,7 +59,6 @@ func TestPara(t *testing.T) { c.Assert(sort.IntsAreSorted(result), qt.Equals, false, qt.Commentf("Para does not seem to be parallel")) sort.Ints(result) c.Assert(result, qt.DeepEquals, ints) - }) c.Run("Time", func(c *qt.C) { @@ -84,7 +82,5 @@ func TestPara(t *testing.T) { c.Assert(r.Wait(), qt.IsNil) c.Assert(counter, qt.Equals, int64(n)) c.Assert(time.Since(start) < n/2*time.Millisecond, qt.Equals, true) - }) - } diff --git a/common/text/position.go b/common/text/position.go index 0c43c5ae..5dd64526 100644 --- a/common/text/position.go +++ b/common/text/position.go @@ -50,12 +50,11 @@ func (pos Position) IsValid() bool { var positionStringFormatfunc func(p Position) string func createPositionStringFormatter(formatStr string) func(p Position) string { - if formatStr == "" { formatStr = "\":file::line::col\"" } - var identifiers = []string{":file", ":line", ":col"} + identifiers := []string{":file", ":line", ":col"} var identifiersFound []string for i := range formatStr { diff --git a/common/text/position_test.go b/common/text/position_test.go index ba482434..a1f43c5d 100644 --- a/common/text/position_test.go +++ b/common/text/position_test.go @@ -29,5 +29,4 @@ func TestPositionStringFormatter(t *testing.T) { c.Assert(createPositionStringFormatter("好::col")(pos), qt.Equals, "好:13") c.Assert(createPositionStringFormatter("")(pos), qt.Equals, "\"/my/file.txt:12:13\"") c.Assert(pos.String(), qt.Equals, "\"/my/file.txt:12:13\"") - } diff --git a/common/text/transform_test.go b/common/text/transform_test.go index 70b10d14..08265f97 100644 --- a/common/text/transform_test.go +++ b/common/text/transform_test.go @@ -25,5 +25,4 @@ func TestRemoveAccents(t *testing.T) { c.Assert(string(RemoveAccents([]byte("Resumé"))), qt.Equals, "Resume") c.Assert(string(RemoveAccents([]byte("Hugo Rocks!"))), qt.Equals, "Hugo Rocks!") c.Assert(string(RemoveAccentsString("Resumé")), qt.Equals, "Resume") - } diff --git a/common/types/convert_test.go b/common/types/convert_test.go index 8a4f04db..d053ede6 100644 --- a/common/types/convert_test.go +++ b/common/types/convert_test.go @@ -26,7 +26,6 @@ func TestToStringSlicePreserveString(t *testing.T) { c.Assert(ToStringSlicePreserveString("Hugo"), qt.DeepEquals, []string{"Hugo"}) c.Assert(ToStringSlicePreserveString([]interface{}{"A", "B"}), qt.DeepEquals, []string{"A", "B"}) c.Assert(ToStringSlicePreserveString(nil), qt.IsNil) - } func TestToString(t *testing.T) { @@ -34,5 +33,4 @@ func TestToString(t *testing.T) { c.Assert(ToString([]byte("Hugo")), qt.Equals, "Hugo") c.Assert(ToString(json.RawMessage("Hugo")), qt.Equals, "Hugo") - } diff --git a/compare/compare_strings_test.go b/compare/compare_strings_test.go index db286c2c..9c4aa586 100644 --- a/compare/compare_strings_test.go +++ b/compare/compare_strings_test.go @@ -61,5 +61,4 @@ func TestLexicographicSort(t *testing.T) { }) c.Assert(s, qt.DeepEquals, []string{"A", "b", "Ba", "ba", "ba", "Bz"}) - } diff --git a/config/commonConfig.go b/config/commonConfig.go index 9b4edfd9..260ebe73 100644 --- a/config/commonConfig.go +++ b/config/commonConfig.go @@ -14,12 +14,12 @@ package config import ( - "github.com/pkg/errors" - "sort" "strings" "sync" + "github.com/pkg/errors" + "github.com/gohugoio/hugo/common/types" "github.com/gobwas/glob" @@ -88,7 +88,6 @@ type Sitemap struct { } func DecodeSitemap(prototype Sitemap, input map[string]interface{}) Sitemap { - for key, value := range input { switch key { case "changefreq": @@ -116,7 +115,6 @@ type Server struct { } func (s *Server) init() { - s.compiledInit.Do(func() { for _, h := range s.Headers { s.compiledHeaders = append(s.compiledHeaders, glob.MustCompile(h.For)) @@ -150,7 +148,6 @@ func (s *Server) MatchHeaders(pattern string) []types.KeyValueStr { }) return matches - } func (s *Server) MatchRedirect(pattern string) Redirect { @@ -176,7 +173,6 @@ func (s *Server) MatchRedirect(pattern string) Redirect { } return Redirect{} - } type Headers struct { diff --git a/config/commonConfig_test.go b/config/commonConfig_test.go index b8b6e679..d4273277 100644 --- a/config/commonConfig_test.go +++ b/config/commonConfig_test.go @@ -57,7 +57,6 @@ func TestBuild(t *testing.T) { c.Assert(b.UseResourceCache(herrors.ErrFeatureNotAvailable), qt.Equals, false) c.Assert(b.UseResourceCache(errors.New("err")), qt.Equals, false) c.Assert(b.UseResourceCache(nil), qt.Equals, false) - } func TestServer(t *testing.T) { @@ -98,7 +97,8 @@ status = 301 c.Assert(s.MatchHeaders("/foo.jpg"), qt.DeepEquals, []types.KeyValueStr{ {Key: "X-Content-Type-Options", Value: "nosniff"}, {Key: "X-Frame-Options", Value: "DENY"}, - {Key: "X-XSS-Protection", Value: "1; mode=block"}}) + {Key: "X-XSS-Protection", Value: "1; mode=block"}, + }) c.Assert(s.MatchRedirect("/foo/bar/baz"), qt.DeepEquals, Redirect{ From: "/foo/**", @@ -122,7 +122,8 @@ status = 301 c.Assert(s.MatchRedirect("/default/index.html"), qt.DeepEquals, Redirect{}) c.Assert(s.MatchRedirect("/default/"), qt.DeepEquals, Redirect{}) - for _, errorCase := range []string{`[[server.redirects]] + for _, errorCase := range []string{ + `[[server.redirects]] from = "/**" to = "/file" status = 301`, @@ -138,5 +139,4 @@ status = 301`, c.Assert(err, qt.Not(qt.IsNil)) } - } diff --git a/config/configLoader.go b/config/configLoader.go index 2e37a5b3..6d94f0b7 100644 --- a/config/configLoader.go +++ b/config/configLoader.go @@ -86,7 +86,6 @@ func readConfig(format metadecoders.Format, data []byte) (map[string]interface{} RenameKeys(m) return m, nil - } func loadConfigFromFile(fs afero.Fs, filename string) (map[string]interface{}, error) { diff --git a/config/privacy/privacyConfig_test.go b/config/privacy/privacyConfig_test.go index a750ba28..0fb599c0 100644 --- a/config/privacy/privacyConfig_test.go +++ b/config/privacy/privacyConfig_test.go @@ -69,7 +69,6 @@ simple = true } c.Assert(got, qt.All(qt.Equals), true) - } func TestDecodeConfigFromTOMLCaseInsensitive(t *testing.T) { diff --git a/config/services/servicesConfig_test.go b/config/services/servicesConfig_test.go index ed303815..6e979b99 100644 --- a/config/services/servicesConfig_test.go +++ b/config/services/servicesConfig_test.go @@ -65,5 +65,4 @@ func TestUseSettingsFromRootIfSet(t *testing.T) { c.Assert(config.Disqus.Shortname, qt.Equals, "root_short") c.Assert(config.GoogleAnalytics.ID, qt.Equals, "ga_root") - } diff --git a/create/content.go b/create/content.go index 13e66820..d1594a19 100644 --- a/create/content.go +++ b/create/content.go @@ -16,15 +16,14 @@ package create import ( "bytes" - - "github.com/pkg/errors" - "io" "os" "os/exec" "path/filepath" "strings" + "github.com/pkg/errors" + "github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugofs" @@ -131,7 +130,6 @@ func newContentFromDir( sites *hugolib.HugoSites, targetFs afero.Fs, cm archetypeMap, name, targetPath string) error { - for _, f := range cm.otherFiles { meta := f.Meta() filename := meta.Path() @@ -196,11 +194,9 @@ func mapArcheTypeDir( ps *helpers.PathSpec, fs afero.Fs, archetypeDir string) (archetypeMap, error) { - var m archetypeMap walkFn := func(path string, fi hugofs.FileMetaInfo, err error) error { - if err != nil { return err } @@ -308,7 +304,6 @@ func resolveContentPath(sites *hugolib.HugoSites, fs afero.Fs, targetPath string } if siteContentDir == "" { - } if siteContentDir != "" { @@ -324,7 +319,6 @@ func resolveContentPath(sites *hugolib.HugoSites, fs afero.Fs, targetPath string } return s.PathSpec.AbsPathify(filepath.Join(contentDir, targetPath)), s } - } // FindArchetype takes a given kind/archetype of content and returns the path diff --git a/create/content_template_handler.go b/create/content_template_handler.go index 3a7007f1..3e9701e4 100644 --- a/create/content_template_handler.go +++ b/create/content_template_handler.go @@ -83,7 +83,6 @@ var ( ) func executeArcheTypeAsTemplate(s *hugolib.Site, name, kind, targetPath, archetypeFilename string) ([]byte, error) { - var ( archetypeContent []byte archetypeTemplate []byte @@ -145,5 +144,4 @@ func executeArcheTypeAsTemplate(s *hugolib.Site, name, kind, targetPath, archety archetypeContent = []byte(archetypeShortcodeReplacementsPost.Replace(buff.String())) return archetypeContent, nil - } diff --git a/create/content_test.go b/create/content_test.go index f43d3a5f..37dbf98b 100644 --- a/create/content_test.go +++ b/create/content_test.go @@ -14,6 +14,7 @@ package create_test import ( + "fmt" "os" "path/filepath" "strings" @@ -23,8 +24,6 @@ import ( "github.com/gohugoio/hugo/hugolib" - "fmt" - "github.com/gohugoio/hugo/hugofs" qt "github.com/frankban/quicktest" @@ -35,7 +34,6 @@ import ( ) func TestNewContent(t *testing.T) { - cases := []struct { kind string path string @@ -59,7 +57,8 @@ func TestNewContent(t *testing.T) { `title = "GO"`, "{{< myshortcode >}}", "{{% myshortcode %}}", - "{{}}\n{{%/* comment */%}}"}}, // shortcodes + "{{}}\n{{%/* comment */%}}", + }}, // shortcodes } for i, cas := range cases { @@ -140,7 +139,6 @@ i18n: {{ T "hugo" }} c.Assert(create.NewContent(h, "my-theme-bundle", "post/my-theme-post"), qt.IsNil) cContains(c, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-theme-post/index.md")), `File: index.md`, `Site Lang: en`, `Name: My Theme Post`, `i18n: Hugo Rocks!`) cContains(c, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-theme-post/resources/hugo1.json")), `hugo1: {{ printf "no template handling in here" }}`) - } func initFs(fs afero.Fs) error { @@ -248,7 +246,6 @@ func readFileFromFs(t *testing.T, fs afero.Fs, filename string) string { } func newTestCfg(c *qt.C, mm afero.Fs) (*viper.Viper, *hugofs.Fs) { - cfg := ` theme = "mytheme" @@ -281,5 +278,4 @@ other = "Hugo Rokkar!"`), 0755), qt.IsNil) c.Assert(err, qt.IsNil) return v, hugofs.NewFrom(mm, v) - } diff --git a/deploy/deploy.go b/deploy/deploy.go index 0c793bca..1aaae5aa 100644 --- a/deploy/deploy.go +++ b/deploy/deploy.go @@ -466,7 +466,7 @@ func (lf *localFile) MD5() []byte { // knownHiddenDirectory checks if the specified name is a well known // hidden directory. func knownHiddenDirectory(name string) bool { - var knownDirectories = []string{ + knownDirectories := []string{ ".well-known", } @@ -697,7 +697,6 @@ func findDiffs(localFiles map[string]*localFile, remoteFiles map[string]*blob.Li // // The subslices are sorted by Local.SlashPath. func applyOrdering(ordering []*regexp.Regexp, uploads []*fileToUpload) [][]*fileToUpload { - // Sort the whole slice by Local.SlashPath first. sort.Slice(uploads, func(i, j int) bool { return uploads[i].Local.SlashPath < uploads[j].Local.SlashPath }) diff --git a/deploy/deployConfig.go b/deploy/deployConfig.go index d4f78011..443c5901 100644 --- a/deploy/deployConfig.go +++ b/deploy/deployConfig.go @@ -112,7 +112,6 @@ func (m *matcher) Matches(path string) bool { // decode creates a config from a given Hugo configuration. func decodeConfig(cfg config.Provider) (deployConfig, error) { - var ( mediaTypesConfig []map[string]interface{} dcfg deployConfig diff --git a/deploy/deploy_test.go b/deploy/deploy_test.go index 987c472c..264ca9f9 100644 --- a/deploy/deploy_test.go +++ b/deploy/deploy_test.go @@ -211,7 +211,6 @@ func TestFindDiffs(t *testing.T) { } func TestWalkLocal(t *testing.T) { - tests := map[string]struct { Given []string Expect []string @@ -355,7 +354,10 @@ func TestLocalFile(t *testing.T) { MediaTypesConfig: []map[string]interface{}{ { "hugo/custom": map[string]interface{}{ - "suffixes": []string{"hugo"}}}}, + "suffixes": []string{"hugo"}, + }, + }, + }, WantContent: contentBytes, WantSize: contentLen, WantMD5: contentMD5[:], diff --git a/deps/deps.go b/deps/deps.go index f6b64c27..c2919c9c 100644 --- a/deps/deps.go +++ b/deps/deps.go @@ -231,7 +231,6 @@ func New(cfg DepsCfg) (*Deps, error) { } ps, err := helpers.NewPathSpec(fs, cfg.Language, logger) - if err != nil { return nil, errors.Wrap(err, "create PathSpec") } @@ -347,7 +346,6 @@ func (d Deps) ForLanguage(cfg DepsCfg, onCreated func(d *Deps) error) (*Deps, er d.BuildStartListeners = &Listeners{} return &d, nil - } // DepsCfg contains configuration options that can be used to configure Hugo diff --git a/deps/deps_test.go b/deps/deps_test.go index 5c58ed7a..d6827673 100644 --- a/deps/deps_test.go +++ b/deps/deps_test.go @@ -20,7 +20,6 @@ import ( ) func TestBuildFlags(t *testing.T) { - c := qt.New(t) var bf BuildState bf.Incr() @@ -28,5 +27,4 @@ func TestBuildFlags(t *testing.T) { bf.Incr() c.Assert(bf.Incr(), qt.Equals, 4) - } diff --git a/helpers/content.go b/helpers/content.go index c59e41a8..5e56ad6b 100644 --- a/helpers/content.go +++ b/helpers/content.go @@ -20,6 +20,7 @@ package helpers import ( "bytes" "html/template" + "strings" "unicode" "unicode/utf8" @@ -33,8 +34,6 @@ import ( bp "github.com/gohugoio/hugo/bufferpool" "github.com/gohugoio/hugo/config" - - "strings" ) // SummaryDivider denotes where content summarization should end. The default is "". @@ -66,7 +65,6 @@ type ContentSpec struct { // NewContentSpec returns a ContentSpec initialized // with the appropriate fields from the given config.Provider. func NewContentSpec(cfg config.Provider, logger loggers.Logger, contentFs afero.Fs) (*ContentSpec, error) { - spec := &ContentSpec{ summaryLength: cfg.GetInt("summaryLength"), BuildFuture: cfg.GetBool("buildFuture"), @@ -81,7 +79,6 @@ func NewContentSpec(cfg config.Provider, logger loggers.Logger, contentFs afero. ContentFs: contentFs, Logger: logger, }) - if err != nil { return nil, err } @@ -112,7 +109,6 @@ var stripHTMLReplacer = strings.NewReplacer("\n", " ", "

", "\n", "
", "\n // StripHTML accepts a string, strips out all HTML tags and returns it. func StripHTML(s string) string { - // Shortcut strings with no tags in them if !strings.ContainsAny(s, "<>") { return s diff --git a/helpers/content_test.go b/helpers/content_test.go index 86e5412c..573c1c90 100644 --- a/helpers/content_test.go +++ b/helpers/content_test.go @@ -118,7 +118,6 @@ func TestNewContentSpec(t *testing.T) { c.Assert(spec.BuildFuture, qt.Equals, true) c.Assert(spec.BuildExpired, qt.Equals, true) c.Assert(spec.BuildDrafts, qt.Equals, true) - } var benchmarkTruncateString = strings.Repeat("This is a sentence about nothing.", 20) @@ -225,7 +224,7 @@ func TestExtractTOCGreaterThanSeventy(t *testing.T) { content := []byte("`, qt.Commentf(got)) - } diff --git a/media/mediaType_test.go b/media/mediaType_test.go index ee7d4407..4526c1e0 100644 --- a/media/mediaType_test.go +++ b/media/mediaType_test.go @@ -62,7 +62,6 @@ func TestDefaultTypes(t *testing.T) { } c.Assert(len(DefaultTypes), qt.Equals, 26) - } func TestGetByType(t *testing.T) { @@ -147,13 +146,12 @@ func TestFromExtensionMultipleSuffixes(t *testing.T) { c.Assert(tp.String(), qt.Equals, "image/svg+xml") c.Assert(found, qt.Equals, true) c.Assert(tp.FullSuffix(), qt.Equals, ".svg") - } func TestDecodeTypes(t *testing.T) { c := qt.New(t) - var tests = []struct { + tests := []struct { name string maps []map[string]interface{} shouldError bool @@ -164,7 +162,10 @@ func TestDecodeTypes(t *testing.T) { []map[string]interface{}{ { "application/json": map[string]interface{}{ - "suffixes": []string{"jasn"}}}}, + "suffixes": []string{"jasn"}, + }, + }, + }, false, func(t *testing.T, name string, tt Types) { c.Assert(len(tt), qt.Equals, len(DefaultTypes)) @@ -172,7 +173,8 @@ func TestDecodeTypes(t *testing.T) { c.Assert(found, qt.Equals, true) c.Assert(json.String(), qt.Equals, "application/json") c.Assert(json.FullSuffix(), qt.Equals, ".jasn") - }}, + }, + }, { "MIME suffix in key, multiple file suffixes, custom delimiter", []map[string]interface{}{ @@ -180,7 +182,9 @@ func TestDecodeTypes(t *testing.T) { "application/hugo+hg": map[string]interface{}{ "suffixes": []string{"hg1", "hg2"}, "Delimiter": "_", - }}}, + }, + }, + }, false, func(t *testing.T, name string, tt Types) { c.Assert(len(tt), qt.Equals, len(DefaultTypes)+1) @@ -193,14 +197,17 @@ func TestDecodeTypes(t *testing.T) { hg, found = tt.GetByType("application/hugo+hg") c.Assert(found, qt.Equals, true) - - }}, + }, + }, { "Add custom media type", []map[string]interface{}{ { "text/hugo+hgo": map[string]interface{}{ - "Suffixes": []string{"hgo2"}}}}, + "Suffixes": []string{"hgo2"}, + }, + }, + }, false, func(t *testing.T, name string, tt Types) { c.Assert(len(tt), qt.Equals, len(DefaultTypes)+1) @@ -212,7 +219,8 @@ func TestDecodeTypes(t *testing.T) { hugo, found := tt.GetBySuffix("hgo2") c.Assert(found, qt.Equals, true) c.Assert(hugo.String(), qt.Equals, "text/hugo+hgo") - }}, + }, + }, } for _, test := range tests { diff --git a/metrics/metrics.go b/metrics/metrics.go index 30a69be4..f48ee33e 100644 --- a/metrics/metrics.go +++ b/metrics/metrics.go @@ -15,21 +15,20 @@ package metrics import ( - "reflect" - - "github.com/gohugoio/hugo/helpers" - - "github.com/gohugoio/hugo/common/types" - "fmt" "io" "math" + "reflect" "sort" "strconv" "strings" "sync" "time" + "github.com/gohugoio/hugo/helpers" + + "github.com/gohugoio/hugo/common/types" + "github.com/gohugoio/hugo/compare" ) @@ -182,7 +181,6 @@ func (s *Store) WriteMetrics(w io.Writer) { fmt.Fprintf(w, " %13s %12s %12s %5d %s\n", v.sum, v.avg, v.max, v.count, v.key) } } - } // A result represents the calculated results for a given metric. @@ -243,7 +241,6 @@ func howSimilar(a, b interface{}) int { return 100 } return 0 - } // howSimilar is a naive diff implementation that returns diff --git a/metrics/metrics_test.go b/metrics/metrics_test.go index 057d5866..d28efa25 100644 --- a/metrics/metrics_test.go +++ b/metrics/metrics_test.go @@ -43,7 +43,6 @@ func TestSimilarPercentage(t *testing.T) { c.Assert(howSimilar(template.HTML("Hugo Rules"), template.HTML("Hugo Rules")), qt.Equals, 100) c.Assert(howSimilar(map[string]interface{}{"a": 32, "b": 33}, map[string]interface{}{"a": 32, "b": 33}), qt.Equals, 100) c.Assert(howSimilar(map[string]interface{}{"a": 32, "b": 33}, map[string]interface{}{"a": 32, "b": 34}), qt.Equals, 0) - } type testStruct struct { @@ -56,7 +55,6 @@ func TestSimilarPercentageNonString(t *testing.T) { c.Assert(howSimilar(page.Pages{}, page.Pages{}), qt.Equals, 90) c.Assert(howSimilar(testStruct{Name: "A"}, testStruct{Name: "B"}), qt.Equals, 0) c.Assert(howSimilar(testStruct{Name: "A"}, testStruct{Name: "A"}), qt.Equals, 100) - } func BenchmarkHowSimilar(b *testing.B) { diff --git a/minifiers/config_test.go b/minifiers/config_test.go index f90bad99..85186384 100644 --- a/minifiers/config_test.go +++ b/minifiers/config_test.go @@ -61,5 +61,4 @@ func TestConfigLegacy(t *testing.T) { conf, err := decodeConfig(v) c.Assert(err, qt.IsNil) c.Assert(conf.MinifyOutput, qt.Equals, true) - } diff --git a/minifiers/minifiers_test.go b/minifiers/minifiers_test.go index fb222fd6..c3922b06 100644 --- a/minifiers/minifiers_test.go +++ b/minifiers/minifiers_test.go @@ -72,7 +72,6 @@ func TestNew(t *testing.T) { c.Assert(m.Minify(test.tp, &b, strings.NewReader(test.rawString)), qt.IsNil) c.Assert(b.String(), qt.Equals, test.expectedMinString) } - } func TestConfigureMinify(t *testing.T) { @@ -145,7 +144,6 @@ func TestJSONRoundTrip(t *testing.T) { c.Assert(json.Unmarshal(b.Bytes(), &m2), qt.IsNil) c.Assert(m1, qt.DeepEquals, m2) } - } func TestBugs(t *testing.T) { @@ -166,5 +164,4 @@ func TestBugs(t *testing.T) { c.Assert(m.Minify(test.tp, &b, strings.NewReader(test.rawString)), qt.IsNil) c.Assert(b.String(), qt.Equals, test.expectedMinString) } - } diff --git a/modules/client.go b/modules/client.go index 7d2175c9..88c1e933 100644 --- a/modules/client.go +++ b/modules/client.go @@ -25,6 +25,8 @@ import ( "os/exec" "path/filepath" "regexp" + "strings" + "time" hglob "github.com/gohugoio/hugo/hugofs/glob" @@ -36,9 +38,6 @@ import ( "github.com/gohugoio/hugo/common/loggers" - "strings" - "time" - "github.com/gohugoio/hugo/config" "github.com/rogpeppe/go-internal/module" @@ -49,9 +48,7 @@ import ( "github.com/spf13/afero" ) -var ( - fileSeparator = string(os.PathSeparator) -) +var fileSeparator = string(os.PathSeparator) const ( goBinaryStatusOK goBinaryStatus = iota @@ -93,7 +90,6 @@ func NewClient(cfg ClientConfig) *Client { if cfg.CacheDir != "" { // Module cache stored below $GOPATH/pkg config.SetEnvVars(&env, "GOPATH", cfg.CacheDir) - } logger := cfg.Logger @@ -113,7 +109,8 @@ func NewClient(cfg ClientConfig) *Client { noVendor: noVendor, moduleConfig: mcfg, environ: env, - GoModulesFilename: goModFilename} + GoModulesFilename: goModFilename, + } } // Client contains most of the API provided by this package. @@ -165,7 +162,6 @@ func (c *Client) Graph(w io.Writer) error { // Local dir. dep += " => " + replace.Dir() } - } fmt.Fprintln(w, prefix+dep) } @@ -357,7 +353,6 @@ var verifyErrorDirRe = regexp.MustCompile(`dir has been modified \((.*?)\)`) func (c *Client) Verify(clean bool) error { // TODO1 add path to mod clean err := c.runVerify() - if err != nil { if clean { m := verifyErrorDirRe.FindAllStringSubmatch(err.Error(), -1) @@ -450,7 +445,6 @@ func (c *Client) listGoMods() (goModules, error) { } return modules, err - } func (c *Client) rewriteGoMod(name string, isGoMod map[string]bool) error { @@ -515,7 +509,6 @@ func (c *Client) rewriteGoModRewrite(name string, isGoMod map[string]bool) ([]by } return b.Bytes(), nil - } func (c *Client) rmVendorDir(vendorDir string) error { @@ -539,7 +532,6 @@ func (c *Client) runGo( ctx context.Context, stdout io.Writer, args ...string) error { - if c.goBinaryStatus != 0 { return nil } diff --git a/modules/client_test.go b/modules/client_test.go index 7cc1058f..c7a07fb8 100644 --- a/modules/client_test.go +++ b/modules/client_test.go @@ -30,7 +30,6 @@ import ( ) func TestClient(t *testing.T) { - modName := "hugo-modules-basic-test" modPath := "github.com/gohugoio/tests/" + modName expect := `github.com/gohugoio/tests/hugo-modules-basic-test github.com/gohugoio/hugoTestModules1_darwin/modh2_2@v1.4.0 @@ -41,7 +40,6 @@ github.com/gohugoio/hugoTestModules1_darwin/modh2_2@v1.4.0 github.com/gohugoio/h c := qt.New(t) newClient := func(c *qt.C, withConfig func(cfg *ClientConfig)) (*Client, func()) { - workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, modName) c.Assert(err, qt.IsNil) themesDir := filepath.Join(workingDir, "themes") @@ -55,7 +53,7 @@ github.com/gohugoio/hugoTestModules1_darwin/modh2_2@v1.4.0 github.com/gohugoio/h } withConfig(&ccfg) - ccfg.ModuleConfig.Imports = []Import{Import{Path: "github.com/gohugoio/hugoTestModules1_darwin/modh2_2"}} + ccfg.ModuleConfig.Imports = []Import{{Path: "github.com/gohugoio/hugoTestModules1_darwin/modh2_2"}} client := NewClient(ccfg) return client, clean @@ -98,7 +96,6 @@ project github.com/gohugoio/hugoTestModules1_darwin/modh2_2_2@v1.3.0+vendor // Test Tidy c.Assert(client.Tidy(), qt.IsNil) - }) c.Run("IgnoreVendor", func(c *qt.C) { @@ -165,15 +162,12 @@ project github.com/gohugoio/hugoTestModules1_darwin/modh2_2_2@v1.3.0+vendor dirname, err = client.createThemeDirname(absDir, false) fmt.Println(dirname) c.Assert(err, qt.Not(qt.IsNil)) - }) - } var globAll, _ = glob.GetGlob("**") func TestGetModlineSplitter(t *testing.T) { - c := qt.New(t) gomodSplitter := getModlineSplitter(true) @@ -184,5 +178,4 @@ func TestGetModlineSplitter(t *testing.T) { gosumSplitter := getModlineSplitter(false) c.Assert(gosumSplitter("github.com/BurntSushi/toml v0.3.1"), qt.DeepEquals, []string{"github.com/BurntSushi/toml", "v0.3.1"}) - } diff --git a/modules/collect.go b/modules/collect.go index e00fa540..179b9d1f 100644 --- a/modules/collect.go +++ b/modules/collect.go @@ -110,7 +110,6 @@ func (h *Client) collect(tidy bool) (ModulesConfig, *collector) { AllModules: c.modules, GoModulesFilename: c.GoModulesFilename, }, c - } type ModulesConfig struct { @@ -325,7 +324,6 @@ func (c *collector) add(owner *moduleAdapter, moduleImport Import, disabled bool c.modules = append(c.modules, ma) return ma, nil - } func (c *collector) addAndRecurse(owner *moduleAdapter, disabled bool) error { @@ -363,7 +361,6 @@ func (c *collector) applyMounts(moduleImport Import, mod *moduleAdapter) error { if len(mounts) == 0 { // Mounts not defined by the import. mounts = modConfig.Mounts - } if !mod.projectMod && len(mounts) == 0 { @@ -397,7 +394,6 @@ func (c *collector) applyMounts(moduleImport Import, mod *moduleAdapter) error { } func (c *collector) applyThemeConfig(tc *moduleAdapter) error { - var ( configFilename string cfg config.Provider @@ -477,7 +473,6 @@ func (c *collector) applyThemeConfig(tc *moduleAdapter) error { tc.config = config return nil - } func (c *collector) collect() { @@ -502,7 +497,6 @@ func (c *collector) collect() { // Add the project mod on top. c.modules = append(Modules{projectMod}, c.modules...) - } func (c *collector) isVendored(dir string) bool { @@ -515,7 +509,6 @@ func (c *collector) collectModulesTXT(owner Module) error { filename := filepath.Join(vendorDir, vendorModulesFilename) f, err := c.fs.Open(filename) - if err != nil { if os.IsNotExist(err) { return nil @@ -656,7 +649,6 @@ func (c *collector) wrapModuleNotFound(err error) error { } return err - } type vendoredModule struct { @@ -679,7 +671,6 @@ func createProjectModule(gomod *goModule, workingDir string, conf Config) *modul projectMod: true, config: conf, } - } // In the first iteration of Hugo Modules, we do not support multiple diff --git a/modules/collect_test.go b/modules/collect_test.go index 7f320f40..9487c0a0 100644 --- a/modules/collect_test.go +++ b/modules/collect_test.go @@ -34,21 +34,18 @@ func TestPathKey(t *testing.T) { } { c.Assert(pathKey(test.in), qt.Equals, test.expect) } - } func TestFilterUnwantedMounts(t *testing.T) { - mounts := []Mount{ - Mount{Source: "a", Target: "b", Lang: "en"}, - Mount{Source: "a", Target: "b", Lang: "en"}, - Mount{Source: "b", Target: "c", Lang: "en"}, + {Source: "a", Target: "b", Lang: "en"}, + {Source: "a", Target: "b", Lang: "en"}, + {Source: "b", Target: "c", Lang: "en"}, } filtered := filterUnwantedMounts(mounts) c := qt.New(t) c.Assert(len(filtered), qt.Equals, 2) - c.Assert(filtered, qt.DeepEquals, []Mount{Mount{Source: "a", Target: "b", Lang: "en"}, Mount{Source: "b", Target: "c", Lang: "en"}}) - + c.Assert(filtered, qt.DeepEquals, []Mount{{Source: "a", Target: "b", Lang: "en"}, {Source: "b", Target: "c", Lang: "en"}}) } diff --git a/modules/config.go b/modules/config.go index 1ce8c9f0..d56f3834 100644 --- a/modules/config.go +++ b/modules/config.go @@ -113,10 +113,11 @@ func ApplyProjectConfigDefaults(cfg config.Provider, mod Module) error { source := cfg.GetString(d.key) componentsConfigured[d.component] = true - return []Mount{Mount{ + return []Mount{{ // No lang set for layouts etc. Source: source, - Target: d.component}} + Target: d.component, + }} } return nil @@ -166,7 +167,6 @@ func ApplyProjectConfigDefaults(cfg config.Provider, mod Module) error { var mounts []Mount for _, dirKey := range dirKeys { if componentsConfigured[dirKey.component] { - continue } @@ -240,7 +240,6 @@ func decodeConfig(cfg config.Provider, pathReplacements map[string]string) (Conf c.Imports[i] = imp } } - } for i, mnt := range c.Mounts { @@ -393,11 +392,9 @@ func getStaticDirs(cfg config.Provider) []string { } func getStringOrStringSlice(cfg config.Provider, key string, id int) []string { - if id >= 0 { key = fmt.Sprintf("%s%d", key, id) } return config.GetStringSlicePreserveString(cfg, key) - } diff --git a/modules/config_test.go b/modules/config_test.go index dd9dbc22..458240b6 100644 --- a/modules/config_test.go +++ b/modules/config_test.go @@ -120,7 +120,6 @@ path="github.com/bep/mycomponent" } }) - } func TestDecodeConfigBothOldAndNewProvided(t *testing.T) { @@ -141,7 +140,6 @@ path="a" c.Assert(err, qt.IsNil) c.Assert(len(modCfg.Imports), qt.Equals, 3) c.Assert(modCfg.Imports[0].Path, qt.Equals, "a") - } // Test old style theme import. diff --git a/modules/npm/package_builder.go b/modules/npm/package_builder.go index c0a5b0da..f407a92b 100644 --- a/modules/npm/package_builder.go +++ b/modules/npm/package_builder.go @@ -45,7 +45,6 @@ const ( ) func Pack(fs afero.Fs, fis []hugofs.FileMetaInfo) error { - var b *packageBuilder // Have a package.hugo.json? @@ -140,7 +139,6 @@ func Pack(fs afero.Fs, fis []hugofs.FileMetaInfo) error { } return nil - } func newPackageBuilder(source string, first io.Reader) *packageBuilder { @@ -220,7 +218,6 @@ func (b *packageBuilder) addm(source string, m map[string]interface{}) { } } } - } func (b *packageBuilder) unmarshal(r io.Reader) map[string]interface{} { diff --git a/navigation/menu.go b/navigation/menu.go index 498078e3..1fb970c7 100644 --- a/navigation/menu.go +++ b/navigation/menu.go @@ -14,14 +14,14 @@ package navigation import ( - "github.com/gohugoio/hugo/common/maps" - "github.com/gohugoio/hugo/common/types" - "github.com/gohugoio/hugo/compare" - "html/template" "sort" "strings" + "github.com/gohugoio/hugo/common/maps" + "github.com/gohugoio/hugo/common/types" + "github.com/gohugoio/hugo/compare" + "github.com/spf13/cast" ) diff --git a/navigation/pagemenus.go b/navigation/pagemenus.go index 352a9155..1dfa7125 100644 --- a/navigation/pagemenus.go +++ b/navigation/pagemenus.go @@ -94,7 +94,6 @@ func PageMenusFromPage(p Page) (PageMenus, error) { } return pm, nil - } func NewMenuQueryProvider( @@ -102,7 +101,6 @@ func NewMenuQueryProvider( pagem PageMenusGetter, sitem MenusGetter, p Page) MenuQueryProvider { - return &pageMenus{ p: p, pagem: pagem, @@ -119,7 +117,6 @@ type pageMenus struct { } func (pm *pageMenus) HasMenuCurrent(menuID string, me *MenuEntry) bool { - // page is labeled as "shadow-member" of the menu with the same identifier as the section if pm.setionPagesMenu != "" { section := pm.p.Section() @@ -136,7 +133,6 @@ func (pm *pageMenus) HasMenuCurrent(menuID string, me *MenuEntry) bool { menus := pm.pagem.Menus() if m, ok := menus[menuID]; ok { - for _, child := range me.Children { if child.IsEqual(m) { return true @@ -165,7 +161,6 @@ func (pm *pageMenus) HasMenuCurrent(menuID string, me *MenuEntry) bool { } return false - } func (pm *pageMenus) IsMenuCurrent(menuID string, inme *MenuEntry) bool { diff --git a/output/docshelper.go b/output/docshelper.go index 450c323d..42b871ab 100644 --- a/output/docshelper.go +++ b/output/docshelper.go @@ -23,7 +23,6 @@ func init() { } func createLayoutExamples() interface{} { - type Example struct { Example string Kind string @@ -78,11 +77,11 @@ func createLayoutExamples() interface{} { Kind: example.d.Kind, OutputFormat: example.f.Name, Suffix: example.f.MediaType.Suffix(), - Layouts: makeLayoutsPresentable(layouts)}) + Layouts: makeLayoutsPresentable(layouts), + }) } return basicExamples - } func makeLayoutsPresentable(l []string) []string { diff --git a/output/layout_test.go b/output/layout_test.go index 853b2475..f98eea96 100644 --- a/output/layout_test.go +++ b/output/layout_test.go @@ -65,7 +65,9 @@ func TestLayout(t *testing.T) { expect []string }{ { - "Home", LayoutDescriptor{Kind: "home"}, "", ampType, + "Home", + LayoutDescriptor{Kind: "home"}, + "", ampType, []string{ "index.amp.html", "home.amp.html", @@ -82,7 +84,9 @@ func TestLayout(t *testing.T) { }, }, { - "Home baseof", LayoutDescriptor{Kind: "home", Baseof: true}, "", ampType, + "Home baseof", + LayoutDescriptor{Kind: "home", Baseof: true}, + "", ampType, []string{ "index-baseof.amp.html", "home-baseof.amp.html", @@ -103,7 +107,9 @@ func TestLayout(t *testing.T) { }, }, { - "Home, HTML", LayoutDescriptor{Kind: "home"}, "", htmlFormat, + "Home, HTML", + LayoutDescriptor{Kind: "home"}, + "", htmlFormat, // We will eventually get to index.html. This looks stuttery, but makes the lookup logic easy to understand. []string{ "index.html.html", @@ -121,7 +127,9 @@ func TestLayout(t *testing.T) { }, }, { - "Home, HTML, baseof", LayoutDescriptor{Kind: "home", Baseof: true}, "", htmlFormat, + "Home, HTML, baseof", + LayoutDescriptor{Kind: "home", Baseof: true}, + "", htmlFormat, []string{ "index-baseof.html.html", "home-baseof.html.html", @@ -142,7 +150,9 @@ func TestLayout(t *testing.T) { }, }, { - "Home, french language", LayoutDescriptor{Kind: "home", Lang: "fr"}, "", ampType, + "Home, french language", + LayoutDescriptor{Kind: "home", Lang: "fr"}, + "", ampType, []string{ "index.fr.amp.html", "home.fr.amp.html", @@ -171,7 +181,9 @@ func TestLayout(t *testing.T) { }, }, { - "Home, no ext or delim", LayoutDescriptor{Kind: "home"}, "", noExtDelimFormat, + "Home, no ext or delim", + LayoutDescriptor{Kind: "home"}, + "", noExtDelimFormat, []string{ "index.nem", "home.nem", @@ -182,7 +194,9 @@ func TestLayout(t *testing.T) { }, }, { - "Home, no ext", LayoutDescriptor{Kind: "home"}, "", noExt, + "Home, no ext", + LayoutDescriptor{Kind: "home"}, + "", noExt, []string{ "index.nex", "home.nex", @@ -193,11 +207,15 @@ func TestLayout(t *testing.T) { }, }, { - "Page, no ext or delim", LayoutDescriptor{Kind: "page"}, "", noExtDelimFormat, + "Page, no ext or delim", + LayoutDescriptor{Kind: "page"}, + "", noExtDelimFormat, []string{"_default/single.nem"}, }, { - "Section", LayoutDescriptor{Kind: "section", Section: "sect1"}, "", ampType, + "Section", + LayoutDescriptor{Kind: "section", Section: "sect1"}, + "", ampType, []string{ "sect1/sect1.amp.html", "sect1/section.amp.html", @@ -220,7 +238,9 @@ func TestLayout(t *testing.T) { }, }, { - "Section, baseof", LayoutDescriptor{Kind: "section", Section: "sect1", Baseof: true}, "", ampType, + "Section, baseof", + LayoutDescriptor{Kind: "section", Section: "sect1", Baseof: true}, + "", ampType, []string{ "sect1/sect1-baseof.amp.html", "sect1/section-baseof.amp.html", @@ -249,7 +269,9 @@ func TestLayout(t *testing.T) { }, }, { - "Section, baseof, French, AMP", LayoutDescriptor{Kind: "section", Section: "sect1", Lang: "fr", Baseof: true}, "", ampType, + "Section, baseof, French, AMP", + LayoutDescriptor{Kind: "section", Section: "sect1", Lang: "fr", Baseof: true}, + "", ampType, []string{ "sect1/sect1-baseof.fr.amp.html", "sect1/section-baseof.fr.amp.html", @@ -302,7 +324,9 @@ func TestLayout(t *testing.T) { }, }, { - "Section with layout", LayoutDescriptor{Kind: "section", Section: "sect1", Layout: "mylayout"}, "", ampType, + "Section with layout", + LayoutDescriptor{Kind: "section", Section: "sect1", Layout: "mylayout"}, + "", ampType, []string{ "sect1/mylayout.amp.html", "sect1/sect1.amp.html", @@ -331,7 +355,9 @@ func TestLayout(t *testing.T) { }, }, { - "Term, French, AMP", LayoutDescriptor{Kind: "term", Section: "tags", Lang: "fr"}, "", ampType, + "Term, French, AMP", + LayoutDescriptor{Kind: "term", Section: "tags", Lang: "fr"}, + "", ampType, []string{ "term/term.fr.amp.html", "term/tags.fr.amp.html", @@ -400,7 +426,9 @@ func TestLayout(t *testing.T) { }, }, { - "Term, baseof, French, AMP", LayoutDescriptor{Kind: "term", Section: "tags", Lang: "fr", Baseof: true}, "", ampType, + "Term, baseof, French, AMP", + LayoutDescriptor{Kind: "term", Section: "tags", Lang: "fr", Baseof: true}, + "", ampType, []string{ "term/term-baseof.fr.amp.html", "term/tags-baseof.fr.amp.html", @@ -485,7 +513,9 @@ func TestLayout(t *testing.T) { }, }, { - "Term", LayoutDescriptor{Kind: "term", Section: "tags"}, "", ampType, + "Term", + LayoutDescriptor{Kind: "term", Section: "tags"}, + "", ampType, []string{ "term/term.amp.html", "term/tags.amp.html", @@ -522,7 +552,9 @@ func TestLayout(t *testing.T) { }, }, { - "Taxonomy", LayoutDescriptor{Kind: "taxonomy", Section: "categories"}, "", ampType, + "Taxonomy", + LayoutDescriptor{Kind: "taxonomy", Section: "categories"}, + "", ampType, []string{ "categories/categories.terms.amp.html", "categories/terms.amp.html", @@ -551,14 +583,18 @@ func TestLayout(t *testing.T) { }, }, { - "Page", LayoutDescriptor{Kind: "page"}, "", ampType, + "Page", + LayoutDescriptor{Kind: "page"}, + "", ampType, []string{ "_default/single.amp.html", "_default/single.html", }, }, { - "Page, baseof", LayoutDescriptor{Kind: "page", Baseof: true}, "", ampType, + "Page, baseof", + LayoutDescriptor{Kind: "page", Baseof: true}, + "", ampType, []string{ "_default/single-baseof.amp.html", "_default/baseof.amp.html", @@ -567,7 +603,9 @@ func TestLayout(t *testing.T) { }, }, { - "Page with layout", LayoutDescriptor{Kind: "page", Layout: "mylayout"}, "", ampType, + "Page with layout", + LayoutDescriptor{Kind: "page", Layout: "mylayout"}, + "", ampType, []string{ "_default/mylayout.amp.html", "_default/single.amp.html", @@ -576,7 +614,9 @@ func TestLayout(t *testing.T) { }, }, { - "Page with layout, baseof", LayoutDescriptor{Kind: "page", Layout: "mylayout", Baseof: true}, "", ampType, + "Page with layout, baseof", + LayoutDescriptor{Kind: "page", Layout: "mylayout", Baseof: true}, + "", ampType, []string{ "_default/mylayout-baseof.amp.html", "_default/single-baseof.amp.html", @@ -587,7 +627,9 @@ func TestLayout(t *testing.T) { }, }, { - "Page with layout and type", LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype"}, "", ampType, + "Page with layout and type", + LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype"}, + "", ampType, []string{ "myttype/mylayout.amp.html", "myttype/single.amp.html", @@ -600,7 +642,9 @@ func TestLayout(t *testing.T) { }, }, { - "Page baseof with layout and type", LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype", Baseof: true}, "", ampType, + "Page baseof with layout and type", + LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype", Baseof: true}, + "", ampType, []string{ "myttype/mylayout-baseof.amp.html", "myttype/single-baseof.amp.html", @@ -617,7 +661,9 @@ func TestLayout(t *testing.T) { }, }, { - "Page baseof with layout and type in French", LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype", Lang: "fr", Baseof: true}, "", ampType, + "Page baseof with layout and type in French", + LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype", Lang: "fr", Baseof: true}, + "", ampType, []string{ "myttype/mylayout-baseof.fr.amp.html", "myttype/single-baseof.fr.amp.html", @@ -646,7 +692,9 @@ func TestLayout(t *testing.T) { }, }, { - "Page with layout and type with subtype", LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype/mysubtype"}, "", ampType, + "Page with layout and type with subtype", + LayoutDescriptor{Kind: "page", Layout: "mylayout", Type: "myttype/mysubtype"}, + "", ampType, []string{ "myttype/mysubtype/mylayout.amp.html", "myttype/mysubtype/single.amp.html", @@ -660,7 +708,9 @@ func TestLayout(t *testing.T) { }, // RSS { - "RSS Home", LayoutDescriptor{Kind: "home"}, "", RSSFormat, + "RSS Home", + LayoutDescriptor{Kind: "home"}, + "", RSSFormat, []string{ "index.rss.xml", "home.rss.xml", @@ -680,7 +730,9 @@ func TestLayout(t *testing.T) { }, }, { - "RSS Home, baseof", LayoutDescriptor{Kind: "home", Baseof: true}, "", RSSFormat, + "RSS Home, baseof", + LayoutDescriptor{Kind: "home", Baseof: true}, + "", RSSFormat, []string{ "index-baseof.rss.xml", "home-baseof.rss.xml", @@ -701,7 +753,9 @@ func TestLayout(t *testing.T) { }, }, { - "RSS Section", LayoutDescriptor{Kind: "section", Section: "sect1"}, "", RSSFormat, + "RSS Section", + LayoutDescriptor{Kind: "section", Section: "sect1"}, + "", RSSFormat, []string{ "sect1/sect1.rss.xml", "sect1/section.rss.xml", @@ -728,7 +782,9 @@ func TestLayout(t *testing.T) { }, }, { - "RSS Term", LayoutDescriptor{Kind: "term", Section: "tag"}, "", RSSFormat, + "RSS Term", + LayoutDescriptor{Kind: "term", Section: "tag"}, + "", RSSFormat, []string{ "term/term.rss.xml", "term/tag.rss.xml", @@ -770,7 +826,9 @@ func TestLayout(t *testing.T) { }, }, { - "RSS Taxonomy", LayoutDescriptor{Kind: "taxonomy", Section: "tag"}, "", RSSFormat, + "RSS Taxonomy", + LayoutDescriptor{Kind: "taxonomy", Section: "tag"}, + "", RSSFormat, []string{ "tag/tag.terms.rss.xml", "tag/terms.rss.xml", @@ -803,7 +861,9 @@ func TestLayout(t *testing.T) { }, }, { - "Home plain text", LayoutDescriptor{Kind: "home"}, "", JSONFormat, + "Home plain text", + LayoutDescriptor{Kind: "home"}, + "", JSONFormat, []string{ "index.json.json", "home.json.json", @@ -820,14 +880,18 @@ func TestLayout(t *testing.T) { }, }, { - "Page plain text", LayoutDescriptor{Kind: "page"}, "", JSONFormat, + "Page plain text", + LayoutDescriptor{Kind: "page"}, + "", JSONFormat, []string{ "_default/single.json.json", "_default/single.json", }, }, { - "Reserved section, shortcodes", LayoutDescriptor{Kind: "section", Section: "shortcodes", Type: "shortcodes"}, "", ampType, + "Reserved section, shortcodes", + LayoutDescriptor{Kind: "section", Section: "shortcodes", Type: "shortcodes"}, + "", ampType, []string{ "section/shortcodes.amp.html", "section/section.amp.html", @@ -844,7 +908,9 @@ func TestLayout(t *testing.T) { }, }, { - "Reserved section, partials", LayoutDescriptor{Kind: "section", Section: "partials", Type: "partials"}, "", ampType, + "Reserved section, partials", + LayoutDescriptor{Kind: "section", Section: "partials", Type: "partials"}, + "", ampType, []string{ "section/partials.amp.html", "section/section.amp.html", @@ -862,14 +928,18 @@ func TestLayout(t *testing.T) { }, // This is currently always HTML only { - "404, HTML", LayoutDescriptor{Kind: "404"}, "", htmlFormat, + "404, HTML", + LayoutDescriptor{Kind: "404"}, + "", htmlFormat, []string{ "404.html.html", "404.html", }, }, { - "404, HTML baseof", LayoutDescriptor{Kind: "404", Baseof: true}, "", htmlFormat, + "404, HTML baseof", + LayoutDescriptor{Kind: "404", Baseof: true}, + "", htmlFormat, []string{ "404-baseof.html.html", "baseof.html.html", @@ -882,7 +952,9 @@ func TestLayout(t *testing.T) { }, }, { - "Content hook", LayoutDescriptor{Kind: "render-link", RenderingHook: true, Layout: "mylayout", Section: "blog"}, "", ampType, + "Content hook", + LayoutDescriptor{Kind: "render-link", RenderingHook: true, Layout: "mylayout", Section: "blog"}, + "", ampType, []string{ "blog/_markup/render-link.amp.html", "blog/_markup/render-link.html", diff --git a/output/outputFormat.go b/output/outputFormat.go index c9c108ac..ee5881e2 100644 --- a/output/outputFormat.go +++ b/output/outputFormat.go @@ -16,11 +16,10 @@ package output import ( "encoding/json" "fmt" + "reflect" "sort" "strings" - "reflect" - "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/media" @@ -200,7 +199,6 @@ func (formats Formats) Less(i, j int) bool { } return fi.Weight > 0 && fi.Weight < fj.Weight - } // GetBySuffix gets a output format given as suffix, e.g. "html". diff --git a/output/outputFormat_test.go b/output/outputFormat_test.go index 2b10c5a9..d91f1e41 100644 --- a/output/outputFormat_test.go +++ b/output/outputFormat_test.go @@ -77,7 +77,6 @@ func TestDefaultTypes(t *testing.T) { c.Assert(RSSFormat.IsPlainText, qt.Equals, false) c.Assert(RSSFormat.NoUgly, qt.Equals, true) c.Assert(CalendarFormat.IsHTML, qt.Equals, false) - } func TestGetFormatByName(t *testing.T) { @@ -144,7 +143,6 @@ func TestGetFormatByFilename(t *testing.T) { c.Assert(f, eq, noExt) _, found = formats.FromFilename("my.css") c.Assert(found, qt.Equals, false) - } func TestDecodeFormats(t *testing.T) { @@ -152,7 +150,7 @@ func TestDecodeFormats(t *testing.T) { mediaTypes := media.Types{media.JSONType, media.XMLType} - var tests = []struct { + tests := []struct { name string maps []map[string]interface{} shouldError bool @@ -164,7 +162,10 @@ func TestDecodeFormats(t *testing.T) { { "JsON": map[string]interface{}{ "baseName": "myindex", - "isPlainText": "false"}}}, + "isPlainText": "false", + }, + }, + }, false, func(t *testing.T, name string, f Formats) { msg := qt.Commentf(name) @@ -173,8 +174,8 @@ func TestDecodeFormats(t *testing.T) { c.Assert(json.BaseName, qt.Equals, "myindex") c.Assert(json.MediaType, eq, media.JSONType) c.Assert(json.IsPlainText, qt.Equals, false) - - }}, + }, + }, { "Add XML format with string as mediatype", []map[string]interface{}{ @@ -182,7 +183,9 @@ func TestDecodeFormats(t *testing.T) { "MYXMLFORMAT": map[string]interface{}{ "baseName": "myxml", "mediaType": "application/xml", - }}}, + }, + }, + }, false, func(t *testing.T, name string, f Formats) { c.Assert(len(f), qt.Equals, len(DefaultFormats)+1) @@ -194,8 +197,8 @@ func TestDecodeFormats(t *testing.T) { // Verify that we haven't changed the DefaultFormats slice. json, _ := f.GetByName("JSON") c.Assert(json.BaseName, qt.Equals, "index") - - }}, + }, + }, { "Add format unknown mediatype", []map[string]interface{}{ @@ -203,11 +206,13 @@ func TestDecodeFormats(t *testing.T) { "MYINVALID": map[string]interface{}{ "baseName": "mymy", "mediaType": "application/hugo", - }}}, + }, + }, + }, true, func(t *testing.T, name string, f Formats) { - - }}, + }, + }, { "Add and redefine XML format", []map[string]interface{}{ @@ -215,11 +220,13 @@ func TestDecodeFormats(t *testing.T) { "MYOTHERXMLFORMAT": map[string]interface{}{ "baseName": "myotherxml", "mediaType": media.XMLType, - }}, + }, + }, { "MYOTHERXMLFORMAT": map[string]interface{}{ "baseName": "myredefined", - }}, + }, + }, }, false, func(t *testing.T, name string, f Formats) { @@ -228,7 +235,8 @@ func TestDecodeFormats(t *testing.T) { c.Assert(found, qt.Equals, true) c.Assert(xml.BaseName, qt.Equals, "myredefined") c.Assert(xml.MediaType, eq, media.XMLType) - }}, + }, + }, } for _, test := range tests { @@ -263,5 +271,4 @@ func TestSort(t *testing.T) { c.Assert(formats[0].Name, qt.Equals, "JSON") c.Assert(formats[1].Name, qt.Equals, "HTML") c.Assert(formats[2].Name, qt.Equals, "AMP") - } diff --git a/parser/lowercase_camel_json.go b/parser/lowercase_camel_json.go index 6994d121..fb283a1c 100644 --- a/parser/lowercase_camel_json.go +++ b/parser/lowercase_camel_json.go @@ -22,8 +22,10 @@ import ( ) // Regexp definitions -var keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`) -var wordBarrierRegex = regexp.MustCompile(`(\w)([A-Z])`) +var ( + keyMatchRegex = regexp.MustCompile(`\"(\w+)\":`) + wordBarrierRegex = regexp.MustCompile(`(\w)([A-Z])`) +) // Code adapted from https://gist.github.com/piersy/b9934790a8892db1a603820c0c23e4a7 type LowerCaseCamelJSONMarshaller struct { @@ -36,7 +38,6 @@ func (c LowerCaseCamelJSONMarshaller) MarshalJSON() ([]byte, error) { converted := keyMatchRegex.ReplaceAllFunc( marshalled, func(match []byte) []byte { - // Attributes on the form XML, JSON etc. if bytes.Equal(match, bytes.ToUpper(match)) { return bytes.ToLower(match) diff --git a/parser/metadecoders/decoder.go b/parser/metadecoders/decoder.go index 2624ad16..7fc8330a 100644 --- a/parser/metadecoders/decoder.go +++ b/parser/metadecoders/decoder.go @@ -119,7 +119,6 @@ func (d Decoder) Unmarshal(data []byte, f Format) (interface{}, error) { default: return make(map[string]interface{}), nil } - } var v interface{} err := d.UnmarshalTo(data, f, &v) @@ -129,7 +128,6 @@ func (d Decoder) Unmarshal(data []byte, f Format) (interface{}, error) { // UnmarshalTo unmarshals data in format f into v. func (d Decoder) UnmarshalTo(data []byte, f Format, v interface{}) error { - var err error switch f { @@ -181,7 +179,6 @@ func (d Decoder) UnmarshalTo(data []byte, f Format, v interface{}) error { } return toFileError(f, errors.Wrap(err, "unmarshal failed")) - } func (d Decoder) unmarshalCSV(data []byte, v interface{}) error { @@ -203,7 +200,6 @@ func (d Decoder) unmarshalCSV(data []byte, v interface{}) error { } return nil - } func parseORGDate(s string) string { @@ -255,7 +251,6 @@ func toFileError(f Format, err error) error { // // Inspired by https://github.com/stripe/stripe-mock, MIT licensed func stringifyMapKeys(in interface{}) (interface{}, bool) { - switch in := in.(type) { case []interface{}: for i, v := range in { diff --git a/parser/metadecoders/decoder_test.go b/parser/metadecoders/decoder_test.go index d11d578b..e0990a5f 100644 --- a/parser/metadecoders/decoder_test.go +++ b/parser/metadecoders/decoder_test.go @@ -87,7 +87,6 @@ func TestUnmarshalToInterface(t *testing.T) { } } - } func TestUnmarshalStringTo(t *testing.T) { diff --git a/parser/metadecoders/format.go b/parser/metadecoders/format.go index 9e9cc2e1..d2b35223 100644 --- a/parser/metadecoders/format.go +++ b/parser/metadecoders/format.go @@ -39,7 +39,6 @@ func FormatFromString(formatStr string) Format { if strings.Contains(formatStr, ".") { // Assume a filename formatStr = strings.TrimPrefix(filepath.Ext(formatStr), ".") - } switch formatStr { case "yaml", "yml": @@ -55,7 +54,6 @@ func FormatFromString(formatStr string) Format { } return "" - } // FormatFromMediaType gets the Format given a MIME type, empty string diff --git a/parser/pageparser/item_test.go b/parser/pageparser/item_test.go index a30860f1..cd01202c 100644 --- a/parser/pageparser/item_test.go +++ b/parser/pageparser/item_test.go @@ -31,5 +31,4 @@ func TestItemValTyped(t *testing.T) { c.Assert(Item{Val: []byte("true")}.ValTyped(), qt.Equals, true) c.Assert(Item{Val: []byte("false")}.ValTyped(), qt.Equals, false) c.Assert(Item{Val: []byte("trues")}.ValTyped(), qt.Equals, "trues") - } diff --git a/parser/pageparser/pagelexer.go b/parser/pageparser/pagelexer.go index 7092b7b2..c360642c 100644 --- a/parser/pageparser/pagelexer.go +++ b/parser/pageparser/pagelexer.go @@ -59,7 +59,6 @@ func (l *pageLexer) Iterator() *Iterator { func (l *pageLexer) Input() []byte { return l.input - } type Config struct { @@ -286,7 +285,6 @@ func (s *sectionHandlers) skip() int { } func createSectionHandlers(l *pageLexer) *sectionHandlers { - shortCodeHandler := §ionHandler{ l: l, skipFunc: func(l *pageLexer) int { @@ -327,7 +325,6 @@ func createSectionHandlers(l *pageLexer) *sectionHandlers { skipFunc: func(l *pageLexer) int { if l.summaryDividerChecked || l.summaryDivider == nil { return -1 - } return l.index(l.summaryDivider) }, @@ -343,7 +340,6 @@ func createSectionHandlers(l *pageLexer) *sectionHandlers { l.emit(TypeLeadSummaryDivider) return origin, true - }, } @@ -425,7 +421,6 @@ func (s *sectionHandler) skip() int { } func lexMainSection(l *pageLexer) stateFunc { - if l.isEOF() { return lexDone } @@ -451,11 +446,9 @@ func lexMainSection(l *pageLexer) stateFunc { l.pos = len(l.input) return lexDone - } func lexDone(l *pageLexer) stateFunc { - // Done! if l.pos > l.start { l.emit(tText) diff --git a/parser/pageparser/pagelexer_intro.go b/parser/pageparser/pagelexer_intro.go index 45ad4f26..961528ef 100644 --- a/parser/pageparser/pagelexer_intro.go +++ b/parser/pageparser/pagelexer_intro.go @@ -147,12 +147,10 @@ LOOP: l.emit(TypeFrontMatterORG) return lexMainSection - } // Handle YAML or TOML front matter. func (l *pageLexer) lexFrontMatterSection(tp ItemType, delimr rune, name string, delim []byte) stateFunc { - for i := 0; i < 2; i++ { if r := l.next(); r != delimr { return l.errorf("invalid %s delimiter", name) diff --git a/parser/pageparser/pagelexer_shortcode.go b/parser/pageparser/pagelexer_shortcode.go index e8e3490a..774a8f69 100644 --- a/parser/pageparser/pagelexer_shortcode.go +++ b/parser/pageparser/pagelexer_shortcode.go @@ -84,7 +84,6 @@ func lexShortcodeRightDelim(l *pageLexer) stateFunc { // 5. `param` // 6. param=`123` func lexShortcodeParam(l *pageLexer, escapedQuoteStart bool) stateFunc { - first := true nextEq := false @@ -138,7 +137,6 @@ func lexShortcodeParam(l *pageLexer, escapedQuoteStart bool) stateFunc { l.emit(tScParam) return lexInsideShortcode - } func lexShortcodeParamVal(l *pageLexer) stateFunc { @@ -356,7 +354,6 @@ func (l *pageLexer) currentLeftShortcodeDelim() []byte { return leftDelimScWithMarkup } return leftDelimScNoMarkup - } func (l *pageLexer) currentRightShortcodeDelim() []byte { diff --git a/parser/pageparser/pagelexer_test.go b/parser/pageparser/pagelexer_test.go index 3bc3bf6a..00669c27 100644 --- a/parser/pageparser/pagelexer_test.go +++ b/parser/pageparser/pagelexer_test.go @@ -25,5 +25,4 @@ func TestMinIndex(t *testing.T) { c.Assert(minIndex(4, 0, -2, 2, 5), qt.Equals, 0) c.Assert(minIndex(), qt.Equals, -1) c.Assert(minIndex(-2, -3), qt.Equals, -1) - } diff --git a/parser/pageparser/pageparser.go b/parser/pageparser/pageparser.go index 3d17aa8e..19d068ec 100644 --- a/parser/pageparser/pageparser.go +++ b/parser/pageparser/pageparser.go @@ -71,7 +71,6 @@ func ParseFrontMatterAndContent(r io.Reader) (ContentFrontMatter, error) { frontMatterSource = item.Val } return true - } iter.PeekWalk(walkFn) diff --git a/parser/pageparser/pageparser_intro_test.go b/parser/pageparser/pageparser_intro_test.go index e776cb3e..1b903d54 100644 --- a/parser/pageparser/pageparser_intro_test.go +++ b/parser/pageparser/pageparser_intro_test.go @@ -106,7 +106,6 @@ func collect(input []byte, skipFrontMatter bool, stateStart stateFunc) (items [] var cfg Config return collectWithConfig(input, skipFrontMatter, stateStart, cfg) - } // no positional checking, for now ... diff --git a/parser/pageparser/pageparser_main_test.go b/parser/pageparser/pageparser_main_test.go index 008c88c5..8fed2bff 100644 --- a/parser/pageparser/pageparser_main_test.go +++ b/parser/pageparser/pageparser_main_test.go @@ -21,7 +21,7 @@ import ( func TestMain(t *testing.T) { t.Parallel() - var mainTests = []lexerTest{ + mainTests := []lexerTest{ {"emoji #1", "Some text with :emoji:", []Item{nti(tText, "Some text with "), nti(TypeEmoji, ":emoji:"), tstEOF}}, {"emoji #2", "Some text with :emoji: and some text.", []Item{nti(tText, "Some text with "), nti(TypeEmoji, ":emoji:"), nti(tText, " and some text."), tstEOF}}, {"looks like an emoji #1", "Some text and then :emoji", []Item{nti(tText, "Some text and then "), nti(tText, ":"), nti(tText, "emoji"), tstEOF}}, diff --git a/parser/pageparser/pageparser_shortcode_test.go b/parser/pageparser/pageparser_shortcode_test.go index b8bf5f72..54580217 100644 --- a/parser/pageparser/pageparser_shortcode_test.go +++ b/parser/pageparser/pageparser_shortcode_test.go @@ -51,8 +51,10 @@ var shortCodeLexerTests = []lexerTest{ {"simple with markup", `{{% sc1 %}}`, []Item{tstLeftMD, tstSC1, tstRightMD, tstEOF}}, {"with spaces", `{{< sc1 >}}`, []Item{tstLeftNoMD, tstSC1, tstRightNoMD, tstEOF}}, - {"mismatched rightDelim", `{{< sc1 %}}`, []Item{tstLeftNoMD, tstSC1, - nti(tError, "unrecognized character in shortcode action: U+0025 '%'. Note: Parameters with non-alphanumeric args must be quoted")}}, + {"mismatched rightDelim", `{{< sc1 %}}`, []Item{ + tstLeftNoMD, tstSC1, + nti(tError, "unrecognized character in shortcode action: U+0025 '%'. Note: Parameters with non-alphanumeric args must be quoted"), + }}, {"inner, markup", `{{% sc1 %}} inner {{% /sc1 %}}`, []Item{ tstLeftMD, tstSC1, @@ -65,57 +67,77 @@ var shortCodeLexerTests = []lexerTest{ tstEOF, }}, {"close, but no open", `{{< /sc1 >}}`, []Item{ - tstLeftNoMD, nti(tError, "got closing shortcode, but none is open")}}, + tstLeftNoMD, nti(tError, "got closing shortcode, but none is open"), + }}, {"close wrong", `{{< sc1 >}}{{< /another >}}`, []Item{ tstLeftNoMD, tstSC1, tstRightNoMD, tstLeftNoMD, tstSCClose, - nti(tError, "closing tag for shortcode 'another' does not match start tag")}}, + nti(tError, "closing tag for shortcode 'another' does not match start tag"), + }}, {"close, but no open, more", `{{< sc1 >}}{{< /sc1 >}}{{< /another >}}`, []Item{ tstLeftNoMD, tstSC1, tstRightNoMD, tstLeftNoMD, tstSCClose, tstSC1, tstRightNoMD, tstLeftNoMD, tstSCClose, - nti(tError, "closing tag for shortcode 'another' does not match start tag")}}, + nti(tError, "closing tag for shortcode 'another' does not match start tag"), + }}, {"close with extra keyword", `{{< sc1 >}}{{< /sc1 keyword>}}`, []Item{ tstLeftNoMD, tstSC1, tstRightNoMD, tstLeftNoMD, tstSCClose, tstSC1, - nti(tError, "unclosed shortcode")}}, + nti(tError, "unclosed shortcode"), + }}, {"float param, positional", `{{< sc1 3.14 >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, "3.14"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, nti(tScParam, "3.14"), tstRightNoMD, tstEOF, + }}, {"float param, named", `{{< sc1 param1=3.14 >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, "3.14"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, "3.14"), tstRightNoMD, tstEOF, + }}, {"named param, raw string", `{{< sc1 param1=` + "`" + "Hello World" + "`" + " >}}", []Item{ - tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, "Hello World"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, "Hello World"), tstRightNoMD, tstEOF, + }}, {"float param, named, space before", `{{< sc1 param1= 3.14 >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, "3.14"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, "3.14"), tstRightNoMD, tstEOF, + }}, {"Youtube id", `{{< sc1 -ziL-Q_456igdO-4 >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, "-ziL-Q_456igdO-4"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, nti(tScParam, "-ziL-Q_456igdO-4"), tstRightNoMD, tstEOF, + }}, {"non-alphanumerics param quoted", `{{< sc1 "-ziL-.%QigdO-4" >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, "-ziL-.%QigdO-4"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, nti(tScParam, "-ziL-.%QigdO-4"), tstRightNoMD, tstEOF, + }}, {"raw string", `{{< sc1` + "`" + "Hello World" + "`" + ` >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, "Hello World"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, nti(tScParam, "Hello World"), tstRightNoMD, tstEOF, + }}, {"raw string with newline", `{{< sc1` + "`" + `Hello World` + "`" + ` >}}`, []Item{ tstLeftNoMD, tstSC1, nti(tScParam, `Hello - World`), tstRightNoMD, tstEOF}}, + World`), tstRightNoMD, tstEOF, + }}, {"raw string with escape character", `{{< sc1` + "`" + `Hello \b World` + "`" + ` >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, `Hello \b World`), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, nti(tScParam, `Hello \b World`), tstRightNoMD, tstEOF, + }}, {"two params", `{{< sc1 param1 param2 >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, tstParam2, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, tstParam2, tstRightNoMD, tstEOF, + }}, // issue #934 {"self-closing", `{{< sc1 />}}`, []Item{ - tstLeftNoMD, tstSC1, tstSCClose, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstSCClose, tstRightNoMD, tstEOF, + }}, // Issue 2498 {"multiple self-closing", `{{< sc1 />}}{{< sc1 />}}`, []Item{ tstLeftNoMD, tstSC1, tstSCClose, tstRightNoMD, - tstLeftNoMD, tstSC1, tstSCClose, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstSCClose, tstRightNoMD, tstEOF, + }}, {"self-closing with param", `{{< sc1 param1 />}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, tstSCClose, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, tstSCClose, tstRightNoMD, tstEOF, + }}, {"multiple self-closing with param", `{{< sc1 param1 />}}{{< sc1 param1 />}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, tstSCClose, tstRightNoMD, - tstLeftNoMD, tstSC1, tstParam1, tstSCClose, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, tstSCClose, tstRightNoMD, tstEOF, + }}, {"multiple different self-closing with param", `{{< sc1 param1 />}}{{< sc2 param1 />}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, tstSCClose, tstRightNoMD, - tstLeftNoMD, tstSC2, tstParam1, tstSCClose, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC2, tstParam1, tstSCClose, tstRightNoMD, tstEOF, + }}, {"nested simple", `{{< sc1 >}}{{< sc2 >}}{{< /sc1 >}}`, []Item{ tstLeftNoMD, tstSC1, tstRightNoMD, tstLeftNoMD, tstSC2, tstRightNoMD, - tstLeftNoMD, tstSCClose, tstSC1, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSCClose, tstSC1, tstRightNoMD, tstEOF, + }}, {"nested complex", `{{< sc1 >}}ab{{% sc2 param1 %}}cd{{< sc3 >}}ef{{< /sc3 >}}gh{{% /sc2 %}}ij{{< /sc1 >}}kl`, []Item{ tstLeftNoMD, tstSC1, tstRightNoMD, nti(tText, "ab"), @@ -132,64 +154,93 @@ var shortCodeLexerTests = []lexerTest{ }}, {"two quoted params", `{{< sc1 "param nr. 1" "param nr. 2" >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, "param nr. 1"), nti(tScParam, "param nr. 2"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, nti(tScParam, "param nr. 1"), nti(tScParam, "param nr. 2"), tstRightNoMD, tstEOF, + }}, {"two named params", `{{< sc1 param1="Hello World" param2="p2Val">}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, tstVal, tstParam2, nti(tScParamVal, "p2Val"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, tstVal, tstParam2, nti(tScParamVal, "p2Val"), tstRightNoMD, tstEOF, + }}, {"escaped quotes", `{{< sc1 param1=\"Hello World\" >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, tstVal, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, tstVal, tstRightNoMD, tstEOF, + }}, {"escaped quotes, positional param", `{{< sc1 \"param1\" >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, tstParam1, tstRightNoMD, tstEOF, + }}, {"escaped quotes inside escaped quotes", `{{< sc1 param1=\"Hello \"escaped\" World\" >}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, - nti(tScParamVal, `Hello `), nti(tError, `got positional parameter 'escaped'. Cannot mix named and positional parameters`)}}, - {"escaped quotes inside nonescaped quotes", - `{{< sc1 param1="Hello \"escaped\" World" >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, `Hello "escaped" World`), tstRightNoMD, tstEOF}}, - {"escaped quotes inside nonescaped quotes in positional param", - `{{< sc1 "Hello \"escaped\" World" >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, `Hello "escaped" World`), tstRightNoMD, tstEOF}}, + nti(tScParamVal, `Hello `), nti(tError, `got positional parameter 'escaped'. Cannot mix named and positional parameters`), + }}, + { + "escaped quotes inside nonescaped quotes", + `{{< sc1 param1="Hello \"escaped\" World" >}}`, + []Item{ + tstLeftNoMD, tstSC1, tstParam1, nti(tScParamVal, `Hello "escaped" World`), tstRightNoMD, tstEOF, + }, + }, + { + "escaped quotes inside nonescaped quotes in positional param", + `{{< sc1 "Hello \"escaped\" World" >}}`, + []Item{ + tstLeftNoMD, tstSC1, nti(tScParam, `Hello "escaped" World`), tstRightNoMD, tstEOF, + }, + }, {"escaped raw string, named param", `{{< sc1 param1=` + `\` + "`" + "Hello World" + `\` + "`" + ` >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, nti(tError, "unrecognized escape character")}}, + tstLeftNoMD, tstSC1, tstParam1, nti(tError, "unrecognized escape character"), + }}, {"escaped raw string, positional param", `{{< sc1 param1 ` + `\` + "`" + "Hello World" + `\` + "`" + ` >}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam1, nti(tError, "unrecognized escape character")}}, + tstLeftNoMD, tstSC1, tstParam1, nti(tError, "unrecognized escape character"), + }}, {"two raw string params", `{{< sc1` + "`" + "Hello World" + "`" + "`" + "Second Param" + "`" + ` >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, "Hello World"), nti(tScParam, "Second Param"), tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC1, nti(tScParam, "Hello World"), nti(tScParam, "Second Param"), tstRightNoMD, tstEOF, + }}, {"unterminated quote", `{{< sc1 param2="Hello World>}}`, []Item{ - tstLeftNoMD, tstSC1, tstParam2, nti(tError, "unterminated quoted string in shortcode parameter-argument: 'Hello World>}}'")}}, + tstLeftNoMD, tstSC1, tstParam2, nti(tError, "unterminated quoted string in shortcode parameter-argument: 'Hello World>}}'"), + }}, {"unterminated raw string", `{{< sc1` + "`" + "Hello World" + ` >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tError, "unterminated raw string in shortcode parameter-argument: 'Hello World >}}'")}}, + tstLeftNoMD, tstSC1, nti(tError, "unterminated raw string in shortcode parameter-argument: 'Hello World >}}'"), + }}, {"unterminated raw string in second argument", `{{< sc1` + "`" + "Hello World" + "`" + "`" + "Second Param" + ` >}}`, []Item{ - tstLeftNoMD, tstSC1, nti(tScParam, "Hello World"), nti(tError, "unterminated raw string in shortcode parameter-argument: 'Second Param >}}'")}}, + tstLeftNoMD, tstSC1, nti(tScParam, "Hello World"), nti(tError, "unterminated raw string in shortcode parameter-argument: 'Second Param >}}'"), + }}, {"one named param, one not", `{{< sc1 param1="Hello World" p2 >}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, tstVal, - nti(tError, "got positional parameter 'p2'. Cannot mix named and positional parameters")}}, + nti(tError, "got positional parameter 'p2'. Cannot mix named and positional parameters"), + }}, {"one named param, one quoted positional param, both raw strings", `{{< sc1 param1=` + "`" + "Hello World" + "`" + "`" + "Second Param" + "`" + ` >}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, tstVal, - nti(tError, "got quoted positional parameter. Cannot mix named and positional parameters")}}, + nti(tError, "got quoted positional parameter. Cannot mix named and positional parameters"), + }}, {"one named param, one quoted positional param", `{{< sc1 param1="Hello World" "And Universe" >}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, tstVal, - nti(tError, "got quoted positional parameter. Cannot mix named and positional parameters")}}, + nti(tError, "got quoted positional parameter. Cannot mix named and positional parameters"), + }}, {"one quoted positional param, one named param", `{{< sc1 "param1" param2="And Universe" >}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, - nti(tError, "got named parameter 'param2'. Cannot mix named and positional parameters")}}, + nti(tError, "got named parameter 'param2'. Cannot mix named and positional parameters"), + }}, {"ono positional param, one not", `{{< sc1 param1 param2="Hello World">}}`, []Item{ tstLeftNoMD, tstSC1, tstParam1, - nti(tError, "got named parameter 'param2'. Cannot mix named and positional parameters")}}, + nti(tError, "got named parameter 'param2'. Cannot mix named and positional parameters"), + }}, {"commented out", `{{}}`, []Item{ - nti(tText, "{{<"), nti(tText, " sc1 "), nti(tText, ">}}"), tstEOF}}, + nti(tText, "{{<"), nti(tText, " sc1 "), nti(tText, ">}}"), tstEOF, + }}, {"commented out, with asterisk inside", `{{}}`, []Item{ - nti(tText, "{{<"), nti(tText, " sc1 \"**/*.pdf\" "), nti(tText, ">}}"), tstEOF}}, + nti(tText, "{{<"), nti(tText, " sc1 \"**/*.pdf\" "), nti(tText, ">}}"), tstEOF, + }}, {"commented out, missing close", `{{}}`, []Item{ - nti(tError, "comment must be closed")}}, + nti(tError, "comment must be closed"), + }}, {"commented out, misplaced close", `{{}}*/`, []Item{ - nti(tError, "comment must be closed")}}, + nti(tError, "comment must be closed"), + }}, // Inline shortcodes {"basic inline", `{{< sc1.inline >}}Hello World{{< /sc1.inline >}}`, []Item{tstLeftNoMD, tstSC1Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSCClose, tstSC1Inline, tstRightNoMD, tstEOF}}, {"basic inline with space", `{{< sc1.inline >}}Hello World{{< / sc1.inline >}}`, []Item{tstLeftNoMD, tstSC1Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSCClose, tstSC1Inline, tstRightNoMD, tstEOF}}, {"inline self closing", `{{< sc1.inline >}}Hello World{{< /sc1.inline >}}Hello World{{< sc1.inline />}}`, []Item{tstLeftNoMD, tstSC1Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSCClose, tstSC1Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSC1Inline, tstSCClose, tstRightNoMD, tstEOF}}, {"inline self closing, then a new inline", `{{< sc1.inline >}}Hello World{{< /sc1.inline >}}Hello World{{< sc1.inline />}}{{< sc2.inline >}}Hello World{{< /sc2.inline >}}`, []Item{ tstLeftNoMD, tstSC1Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSCClose, tstSC1Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSC1Inline, tstSCClose, tstRightNoMD, - tstLeftNoMD, tstSC2Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSCClose, tstSC2Inline, tstRightNoMD, tstEOF}}, + tstLeftNoMD, tstSC2Inline, tstRightNoMD, tstText, tstLeftNoMD, tstSCClose, tstSC2Inline, tstRightNoMD, tstEOF, + }}, {"inline with template syntax", `{{< sc1.inline >}}{{ .Get 0 }}{{ .Get 1 }}{{< /sc1.inline >}}`, []Item{tstLeftNoMD, tstSC1Inline, tstRightNoMD, nti(tText, "{{ .Get 0 }}"), nti(tText, "{{ .Get 1 }}"), tstLeftNoMD, tstSCClose, tstSC1Inline, tstRightNoMD, tstEOF}}, {"inline with nested shortcode (not supported)", `{{< sc1.inline >}}Hello World{{< sc1 >}}{{< /sc1.inline >}}`, []Item{tstLeftNoMD, tstSC1Inline, tstRightNoMD, tstText, nti(tError, "inline shortcodes do not support nesting")}}, {"inline case mismatch", `{{< sc1.Inline >}}Hello World{{< /sc1.Inline >}}`, []Item{tstLeftNoMD, nti(tError, "period in shortcode name only allowed for inline identifiers")}}, diff --git a/publisher/htmlElementsCollector.go b/publisher/htmlElementsCollector.go index b9b0f4e1..82846e3d 100644 --- a/publisher/htmlElementsCollector.go +++ b/publisher/htmlElementsCollector.go @@ -14,15 +14,14 @@ package publisher import ( - "regexp" - - "github.com/gohugoio/hugo/helpers" - "golang.org/x/net/html" - "bytes" + "regexp" "sort" "strings" "sync" + + "github.com/gohugoio/hugo/helpers" + "golang.org/x/net/html" ) func newHTMLElementsCollector() *htmlElementsCollector { @@ -52,7 +51,6 @@ func (h *HTMLElements) Merge(other HTMLElements) { h.Tags = helpers.UniqueStringsReuse(h.Tags) h.Classes = helpers.UniqueStringsReuse(h.Classes) h.IDs = helpers.UniqueStringsReuse(h.IDs) - } func (h *HTMLElements) Sort() { @@ -153,7 +151,6 @@ func (c *cssClassCollectorWriter) insertStandinHTMLElement(el string) (string, s } newv := strings.Replace(el, tag, "div", 1) return newv, strings.ToLower(tag) - } func (c *cssClassCollectorWriter) endCollecting(drop bool) { @@ -196,7 +193,6 @@ type htmlElementsCollector struct { } func (c *htmlElementsCollector) getHTMLElements() HTMLElements { - var ( classes []string ids []string diff --git a/publisher/htmlElementsCollector_test.go b/publisher/htmlElementsCollector_test.go index ab152928..2c2fd373 100644 --- a/publisher/htmlElementsCollector_test.go +++ b/publisher/htmlElementsCollector_test.go @@ -68,9 +68,11 @@ func TestClassCollector(t *testing.T) { `, f("body div", "class1 class2 class3", "")}, - {"Alpine bind 2", `
FOO
`, - f("div", "bg-black bg-gray-300 inline-block mb-2 mr-1 px-2 py-2 rounded", "")}, + f("div", "bg-black bg-gray-300 inline-block mb-2 mr-1 px-2 py-2 rounded", ""), + }, {"Alpine bind 3", `
`, f("div", "text-gray-800 text-white", "")}, {"Alpine bind 4", `
index { return pages[index], nil @@ -207,7 +206,6 @@ func splitPages(pages Pages, size int) []paginatedElement { } func splitPageGroups(pageGroups PagesGroup, size int) []paginatedElement { - type keyPage struct { key interface{} page Page @@ -269,7 +267,6 @@ func ResolvePagerSize(cfg config.Provider, options ...interface{}) (int, error) } func Paginate(td TargetPathDescriptor, seq interface{}, pagerSize int) (*Paginator, error) { - if pagerSize <= 0 { return nil, errors.New("'paginate' configuration setting must be positive to paginate") } @@ -300,7 +297,6 @@ func Paginate(td TargetPathDescriptor, seq interface{}, pagerSize int) (*Paginat // The motivation behind this is to avoid potential costly reflect.DeepEqual // when "probably" is good enough. func probablyEqualPageLists(a1 interface{}, a2 interface{}) bool { - if a1 == nil || a2 == nil { return a1 == a2 } @@ -347,7 +343,6 @@ func probablyEqualPageLists(a1 interface{}, a2 interface{}) bool { } func newPaginatorFromPages(pages Pages, size int, urlFactory paginationURLFactory) (*Paginator, error) { - if size <= 0 { return nil, errors.New("Paginator size must be positive") } @@ -358,7 +353,6 @@ func newPaginatorFromPages(pages Pages, size int, urlFactory paginationURLFactor } func newPaginatorFromPageGroups(pageGroups PagesGroup, size int, urlFactory paginationURLFactory) (*Paginator, error) { - if size <= 0 { return nil, errors.New("Paginator size must be positive") } @@ -389,7 +383,6 @@ func newPaginator(elements []paginatedElement, total, size int, urlFactory pagin } func newPaginationURLFactory(d TargetPathDescriptor) paginationURLFactory { - return func(pageNumber int) string { pathDescriptor := d var rel string @@ -399,6 +392,5 @@ func newPaginationURLFactory(d TargetPathDescriptor) paginationURLFactory { } return CreateTargetPaths(pathDescriptor).RelPermalink(d.PathSpec) - } } diff --git a/resources/page/pagination_test.go b/resources/page/pagination_test.go index f4441a89..8d4f857d 100644 --- a/resources/page/pagination_test.go +++ b/resources/page/pagination_test.go @@ -37,7 +37,6 @@ func TestSplitPages(t *testing.T) { lastChunk := chunks[4] c.Assert(lastChunk.Len(), qt.Equals, 1) - } func TestSplitPageGroups(t *testing.T) { @@ -78,7 +77,6 @@ func TestSplitPageGroups(t *testing.T) { } else { t.Fatal("Excepted PageGroup") } - } func TestPager(t *testing.T) { @@ -111,7 +109,6 @@ func TestPager(t *testing.T) { first = pag.Pagers()[0].First() c.Assert(first.PageGroups(), qt.Not(qt.HasLen), 0) c.Assert(first.Pages(), qt.HasLen, 0) - } func doTestPages(t *testing.T, paginator *Paginator) { @@ -171,7 +168,6 @@ func TestPagerNoPages(t *testing.T) { first = paginator.Pagers()[0].First() c.Assert(first.PageGroups(), qt.HasLen, 0) c.Assert(first.Pages(), qt.HasLen, 0) - } func doTestPagerNoPages(t *testing.T, paginator *Paginator) { @@ -195,7 +191,6 @@ func doTestPagerNoPages(t *testing.T, paginator *Paginator) { c.Assert(pageOne.TotalPages(), qt.Equals, 0) c.Assert(pageOne.PageNumber(), qt.Equals, 1) c.Assert(pageOne.PageSize(), qt.Equals, 5) - } func TestPaginationURLFactory(t *testing.T) { @@ -206,7 +201,6 @@ func TestPaginationURLFactory(t *testing.T) { for _, uglyURLs := range []bool{false, true} { c.Run(fmt.Sprintf("uglyURLs=%t", uglyURLs), func(c *qt.C) { - tests := []struct { name string d TargetPathDescriptor @@ -215,10 +209,16 @@ func TestPaginationURLFactory(t *testing.T) { expected string expectedUgly string }{ - {"HTML home page 32", - TargetPathDescriptor{Kind: KindHome, Type: output.HTMLFormat}, "http://example.com/", 32, "/zoo/32/", "/zoo/32.html"}, - {"JSON home page 42", - TargetPathDescriptor{Kind: KindHome, Type: output.JSONFormat}, "http://example.com/", 42, "/zoo/42/index.json", "/zoo/42.json"}, + { + "HTML home page 32", + TargetPathDescriptor{Kind: KindHome, Type: output.HTMLFormat}, + "http://example.com/", 32, "/zoo/32/", "/zoo/32.html", + }, + { + "JSON home page 42", + TargetPathDescriptor{Kind: KindHome, Type: output.JSONFormat}, + "http://example.com/", 42, "/zoo/42/index.json", "/zoo/42.json", + }, } for _, test := range tests { @@ -242,7 +242,6 @@ func TestPaginationURLFactory(t *testing.T) { } }) - } } @@ -276,7 +275,6 @@ func TestProbablyEqualPageLists(t *testing.T) { if result != this.expect { t.Errorf("[%d] got %t but expected %t", i, result, this.expect) - } } } diff --git a/resources/page/permalinks.go b/resources/page/permalinks.go index 0e9b9e21..19ac5217 100644 --- a/resources/page/permalinks.go +++ b/resources/page/permalinks.go @@ -60,7 +60,6 @@ func (p PermalinkExpander) callback(attr string) (pageToPermaAttribute, bool) { // NewPermalinkExpander creates a new PermalinkExpander configured by the given // PathSpec. func NewPermalinkExpander(ps *helpers.PathSpec) (PermalinkExpander, error) { - p := PermalinkExpander{ps: ps} p.knownPermalinkAttributes = map[string]pageToPermaAttribute{ @@ -103,11 +102,9 @@ func (l PermalinkExpander) Expand(key string, p Page) (string, error) { } return expand(p) - } func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Page) (string, error), error) { - expanders := make(map[string]func(Page) (string, error)) // Allow " " and / to represent the root section. @@ -138,7 +135,6 @@ func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Pa } expanders[k] = func(p Page) (string, error) { - if matches == nil { return pattern, nil } @@ -149,7 +145,6 @@ func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Pa attr := replacement[1:] callback := callbacks[i] newAttr, err := callback(p, attr) - if err != nil { return "", &permalinkExpandError{pattern: pattern, err: err} } @@ -159,7 +154,6 @@ func (l PermalinkExpander) parse(patterns map[string]string) (map[string]func(Pa } return newField, nil - } } @@ -176,7 +170,7 @@ var attributeRegexp = regexp.MustCompile(`:\w+`) // validate determines if a PathPattern is well-formed func (l PermalinkExpander) validate(pp string) bool { fragments := strings.Split(pp[1:], "/") - var bail = false + bail := false for i := range fragments { if bail { return false diff --git a/resources/page/permalinks_test.go b/resources/page/permalinks_test.go index e4eeda74..e40e7e0e 100644 --- a/resources/page/permalinks_test.go +++ b/resources/page/permalinks_test.go @@ -113,7 +113,6 @@ func TestPermalinkExpansionMultiSection(t *testing.T) { expanded, err = expander.Expand("blog", page) c.Assert(err, qt.IsNil) c.Assert(expanded, qt.Equals, "/blue/2012") - } func TestPermalinkExpansionConcurrent(t *testing.T) { diff --git a/resources/page/testhelpers_test.go b/resources/page/testhelpers_test.go index 54a908d3..96384843 100644 --- a/resources/page/testhelpers_test.go +++ b/resources/page/testhelpers_test.go @@ -128,8 +128,8 @@ func (p *testPage) AlternativeOutputFormats() OutputFormats { func (p *testPage) Author() Author { return Author{} - } + func (p *testPage) Authors() AuthorList { return nil } @@ -165,6 +165,7 @@ func (p *testPage) Sitemap() config.Sitemap { func (p *testPage) Layout() string { return "" } + func (p *testPage) Date() time.Time { return p.date } diff --git a/resources/page/weighted.go b/resources/page/weighted.go index 7e5e2545..af8b5444 100644 --- a/resources/page/weighted.go +++ b/resources/page/weighted.go @@ -20,9 +20,7 @@ import ( "github.com/gohugoio/hugo/common/collections" ) -var ( - _ collections.Slicer = WeightedPage{} -) +var _ collections.Slicer = WeightedPage{} // WeightedPages is a list of Pages with their corresponding (and relative) weight // [{Weight: 30, Page: *1}, {Weight: 40, Page: *2}] diff --git a/resources/page/zero_file.autogen.go b/resources/page/zero_file.autogen.go index 23e36b76..f928982e 100644 --- a/resources/page/zero_file.autogen.go +++ b/resources/page/zero_file.autogen.go @@ -38,50 +38,62 @@ func (z zeroFile) Path() (o0 string) { z.log.Println(".File.Path on zero object. Wrap it in if or with: {{ with .File }}{{ .Path }}{{ end }}") return } + func (z zeroFile) Section() (o0 string) { z.log.Println(".File.Section on zero object. Wrap it in if or with: {{ with .File }}{{ .Section }}{{ end }}") return } + func (z zeroFile) Lang() (o0 string) { z.log.Println(".File.Lang on zero object. Wrap it in if or with: {{ with .File }}{{ .Lang }}{{ end }}") return } + func (z zeroFile) Filename() (o0 string) { z.log.Println(".File.Filename on zero object. Wrap it in if or with: {{ with .File }}{{ .Filename }}{{ end }}") return } + func (z zeroFile) Dir() (o0 string) { z.log.Println(".File.Dir on zero object. Wrap it in if or with: {{ with .File }}{{ .Dir }}{{ end }}") return } + func (z zeroFile) Extension() (o0 string) { z.log.Println(".File.Extension on zero object. Wrap it in if or with: {{ with .File }}{{ .Extension }}{{ end }}") return } + func (z zeroFile) Ext() (o0 string) { z.log.Println(".File.Ext on zero object. Wrap it in if or with: {{ with .File }}{{ .Ext }}{{ end }}") return } + func (z zeroFile) LogicalName() (o0 string) { z.log.Println(".File.LogicalName on zero object. Wrap it in if or with: {{ with .File }}{{ .LogicalName }}{{ end }}") return } + func (z zeroFile) BaseFileName() (o0 string) { z.log.Println(".File.BaseFileName on zero object. Wrap it in if or with: {{ with .File }}{{ .BaseFileName }}{{ end }}") return } + func (z zeroFile) TranslationBaseName() (o0 string) { z.log.Println(".File.TranslationBaseName on zero object. Wrap it in if or with: {{ with .File }}{{ .TranslationBaseName }}{{ end }}") return } + func (z zeroFile) ContentBaseName() (o0 string) { z.log.Println(".File.ContentBaseName on zero object. Wrap it in if or with: {{ with .File }}{{ .ContentBaseName }}{{ end }}") return } + func (z zeroFile) UniqueID() (o0 string) { z.log.Println(".File.UniqueID on zero object. Wrap it in if or with: {{ with .File }}{{ .UniqueID }}{{ end }}") return } + func (z zeroFile) FileInfo() (o0 hugofs.FileMetaInfo) { z.log.Println(".File.FileInfo on zero object. Wrap it in if or with: {{ with .File }}{{ .FileInfo }}{{ end }}") return diff --git a/resources/postpub/fields.go b/resources/postpub/fields.go index f1cfe609..ed349143 100644 --- a/resources/postpub/fields.go +++ b/resources/postpub/fields.go @@ -53,7 +53,7 @@ func structToMap(s interface{}) map[string]interface{} { // insert placeholder for the templates. Do it very shallow for now. func insertFieldPlaceholders(root string, m map[string]interface{}, createPlaceholder func(s string) string) { - for k, _ := range m { + for k := range m { m[k] = createPlaceholder(root + "." + k) } } diff --git a/resources/postpub/fields_test.go b/resources/postpub/fields_test.go index d67c7c9a..10a68ac5 100644 --- a/resources/postpub/fields_test.go +++ b/resources/postpub/fields_test.go @@ -42,5 +42,4 @@ func TestCreatePlaceholders(t *testing.T) { "SubType": "pre_foo.SubType_post", "Suffixes": "pre_foo.Suffixes_post", }) - } diff --git a/resources/postpub/postpub.go b/resources/postpub/postpub.go index 3a1dd2f8..85b4221f 100644 --- a/resources/postpub/postpub.go +++ b/resources/postpub/postpub.go @@ -108,7 +108,6 @@ func (r *PostPublishResource) GetFieldString(pattern string) (string, bool) { default: panic(fmt.Sprintf("unknown field accessor %q", fieldAccessor)) } - } func (r *PostPublishResource) fieldToString(receiver interface{}, path string) string { diff --git a/resources/resource.go b/resources/resource.go index acdf2d74..64f9f12f 100644 --- a/resources/resource.go +++ b/resources/resource.go @@ -276,7 +276,6 @@ func (l *genericResource) Publish() error { defer fw.Close() _, err = io.Copy(fw, fr) - }) return err @@ -435,7 +434,6 @@ func (l genericResource) clone() *genericResource { // returns an opened file or nil if nothing to write (it may already be published). func (l *genericResource) openDestinationsForWriting() (w io.WriteCloser, err error) { - l.publishInit.Do(func() { targetFilenames := l.getTargetFilenames() var changedFilenames []string @@ -456,11 +454,9 @@ func (l *genericResource) openDestinationsForWriting() (w io.WriteCloser, err er } w, err = helpers.OpenFilesForWriting(l.getSpec().BaseFs.PublishFs, changedFilenames...) - }) return - } func (r *genericResource) openPublishFileForWriting(relTargetPath string) (io.WriteCloser, error) { diff --git a/resources/resource/params.go b/resources/resource/params.go index 89da718e..c76eedea 100644 --- a/resources/resource/params.go +++ b/resources/resource/params.go @@ -30,5 +30,4 @@ func Param(r ResourceParamsProvider, fallback maps.Params, key interface{}) (int } return maps.GetNestedParam(keyStr, ".", r.Params(), fallback) - } diff --git a/resources/resource_cache.go b/resources/resource_cache.go index 6c4ba951..f498bb0c 100644 --- a/resources/resource_cache.go +++ b/resources/resource_cache.go @@ -69,8 +69,8 @@ func resourceKeyPartition(filename string) string { // Commonly used aliases and directory names used for some types. var extAliasKeywords = map[string][]string{ - "sass": []string{"scss"}, - "scss": []string{"sass"}, + "sass": {"scss"}, + "scss": {"sass"}, } // ResourceKeyPartitions resolves a ordered slice of partitions that is @@ -201,7 +201,6 @@ func (c *ResourceCache) getOrCreate(key string, f func() (interface{}, error)) ( c.set(key, r) return r, nil - } func (c *ResourceCache) getFilenames(key string) (string, string) { @@ -230,7 +229,6 @@ func (c *ResourceCache) getFromFile(key string) (filecache.ItemInfo, io.ReadClos fi, rc, _ := c.fileCache.Get(filenameContent) return fi, rc, meta, rc != nil - } // writeMeta writes the metadata to file and returns a writer for the content part. @@ -254,7 +252,6 @@ func (c *ResourceCache) writeMeta(key string, meta transformedResourceMetadata) fi, fc, err := c.fileCache.WriteCloser(filenameContent) return fi, fc, err - } func (c *ResourceCache) set(key string, r interface{}) { @@ -294,7 +291,6 @@ func (c *ResourceCache) DeletePartitions(partitions ...string) { delete(c.cache, k) } } - } func (c *ResourceCache) DeleteMatches(re *regexp.Regexp) { @@ -305,7 +301,5 @@ func (c *ResourceCache) DeleteMatches(re *regexp.Regexp) { if re.MatchString(k) { delete(c.cache, k) } - } - } diff --git a/resources/resource_factories/bundler/bundler.go b/resources/resource_factories/bundler/bundler.go index 1ea92bea..7de22822 100644 --- a/resources/resource_factories/bundler/bundler.go +++ b/resources/resource_factories/bundler/bundler.go @@ -130,7 +130,6 @@ func (c *Client) Concat(targetPath string, r resource.Resources) (resource.Resou } return newMultiReadSeekCloser(rcsources...), nil - } composite, err := c.rs.New( @@ -138,13 +137,12 @@ func (c *Client) Concat(targetPath string, r resource.Resources) (resource.Resou Fs: c.rs.FileCaches.AssetsCache().Fs, LazyPublish: true, OpenReadSeekCloser: concatr, - RelTargetFilename: filepath.Clean(targetPath)}) - + RelTargetFilename: filepath.Clean(targetPath), + }) if err != nil { return nil, err } return composite, nil }) - } diff --git a/resources/resource_factories/bundler/bundler_test.go b/resources/resource_factories/bundler/bundler_test.go index 16a5215b..17a74cc8 100644 --- a/resources/resource_factories/bundler/bundler_test.go +++ b/resources/resource_factories/bundler/bundler_test.go @@ -37,5 +37,4 @@ func TestMultiReadSeekCloser(t *testing.T) { _, err := rc.Seek(0, 0) c.Assert(err, qt.IsNil) } - } diff --git a/resources/resource_factories/create/create.go b/resources/resource_factories/create/create.go index 4ac20d36..1bba98d2 100644 --- a/resources/resource_factories/create/create.go +++ b/resources/resource_factories/create/create.go @@ -47,9 +47,9 @@ func (c *Client) Get(filename string) (resource.Resource, error) { return c.rs.New(resources.ResourceSourceDescriptor{ Fs: c.rs.BaseFs.Assets.Fs, LazyPublish: true, - SourceFilename: filename}) + SourceFilename: filename, + }) }) - } // Match gets the resources matching the given pattern from the assets filesystem. @@ -93,8 +93,8 @@ func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, erro OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return meta.Open() }, - RelTargetFilename: meta.Path()}) - + RelTargetFilename: meta.Path(), + }) if err != nil { return true, err } @@ -102,7 +102,6 @@ func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, erro res = append(res, r) return firstOnly, nil - } if err := hugofs.Glob(c.rs.BaseFs.Assets.Fs, pattern, handle); err != nil { @@ -110,7 +109,6 @@ func (c *Client) match(pattern string, firstOnly bool) (resource.Resources, erro } return res, nil - }) } @@ -124,8 +122,7 @@ func (c *Client) FromString(targetPath, content string) (resource.Resource, erro OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, - RelTargetFilename: filepath.Clean(targetPath)}) - + RelTargetFilename: filepath.Clean(targetPath), + }) }) - } diff --git a/resources/resource_metadata.go b/resources/resource_metadata.go index 7bf7479a..a0c232c6 100644 --- a/resources/resource_metadata.go +++ b/resources/resource_metadata.go @@ -16,6 +16,7 @@ package resources import ( "fmt" "strconv" + "strings" "github.com/gohugoio/hugo/hugofs/glob" "github.com/gohugoio/hugo/media" @@ -24,8 +25,6 @@ import ( "github.com/pkg/errors" "github.com/spf13/cast" - "strings" - "github.com/gohugoio/hugo/common/maps" ) diff --git a/resources/resource_metadata_test.go b/resources/resource_metadata_test.go index c79a5002..87a537f7 100644 --- a/resources/resource_metadata_test.go +++ b/resources/resource_metadata_test.go @@ -43,7 +43,6 @@ func TestAssignMetadata(t *testing.T) { c.Assert(logo1.Title(), qt.Equals, "My Resource") c.Assert(logo1.Name(), qt.Equals, "My Name") c.Assert(foo2.Name(), qt.Equals, "My Name") - }}, {[]map[string]interface{}{ { @@ -62,7 +61,6 @@ func TestAssignMetadata(t *testing.T) { c.Assert(foo2.Name(), qt.Equals, "My Name") c.Assert(foo3.Name(), qt.Equals, "My Name") c.Assert(foo3.Title(), qt.Equals, "My Resource") - }}, {[]map[string]interface{}{ { @@ -102,7 +100,6 @@ func TestAssignMetadata(t *testing.T) { c.Assert(icon1, qt.Equals, "logo") c.Assert(icon2, qt.Equals, "resource") - }}, {[]map[string]interface{}{ { @@ -126,7 +123,6 @@ func TestAssignMetadata(t *testing.T) { c.Assert(foo3.Title(), qt.Equals, "Resource #5") c.Assert(resources.GetMatch("logo name #1*"), qt.Equals, logo2) - }}, {[]map[string]interface{}{ { @@ -146,7 +142,6 @@ func TestAssignMetadata(t *testing.T) { c.Assert(logo2.Name(), qt.Equals, "Name #1") c.Assert(logo1.Title(), qt.Equals, "Other Logo #2") c.Assert(logo1.Name(), qt.Equals, "Name #2") - }}, {[]map[string]interface{}{ { @@ -166,7 +161,6 @@ func TestAssignMetadata(t *testing.T) { c.Assert(logo2.Name(), qt.Equals, "Name #1") c.Assert(logo1.Title(), qt.Equals, "Other Logo #2") c.Assert(logo1.Name(), qt.Equals, "Name #2") - }}, {[]map[string]interface{}{ { @@ -186,7 +180,6 @@ func TestAssignMetadata(t *testing.T) { c.Assert(logo2.Name(), qt.Equals, "Name #1") c.Assert(logo1.Title(), qt.Equals, "Logo #2") c.Assert(logo1.Name(), qt.Equals, "Name #2") - }}, {[]map[string]interface{}{ { @@ -195,7 +188,6 @@ func TestAssignMetadata(t *testing.T) { }, func(err error) { // Missing src c.Assert(err, qt.Not(qt.IsNil)) - }}, {[]map[string]interface{}{ { @@ -205,7 +197,6 @@ func TestAssignMetadata(t *testing.T) { }, func(err error) { // Invalid pattern c.Assert(err, qt.Not(qt.IsNil)) - }}, } { @@ -227,5 +218,4 @@ func TestAssignMetadata(t *testing.T) { this.assertFunc(AssignMetadata(this.metaData, resources...)) } - } diff --git a/resources/resource_spec.go b/resources/resource_spec.go index 0ca60fe3..1659332a 100644 --- a/resources/resource_spec.go +++ b/resources/resource_spec.go @@ -53,7 +53,6 @@ func NewSpec( errorHandler herrors.ErrorSender, outputFormats output.Formats, mimeTypes media.Types) (*Spec, error) { - imgConfig, err := images.DecodeConfig(s.Cfg.GetStringMap("imaging")) if err != nil { return nil, err @@ -96,12 +95,12 @@ func NewSpec( fileCaches.ImageCache(), s, - )} + ), + } rs.ResourceCache = newResourceCache(rs) return rs, nil - } type Spec struct { @@ -189,7 +188,6 @@ func (r *Spec) newGenericResource(sourceFs afero.Fs, baseFilename, mediaType, ) - } func (r *Spec) newGenericResourceWithBase( @@ -201,7 +199,6 @@ func (r *Spec) newGenericResourceWithBase( sourceFilename, baseFilename string, mediaType media.Type) *genericResource { - if osFileInfo != nil && osFileInfo.IsDir() { panic(fmt.Sprintf("dirs not supported resource types: %v", osFileInfo)) } @@ -250,7 +247,6 @@ func (r *Spec) newGenericResourceWithBase( } return g - } func (r *Spec) newResource(sourceFs afero.Fs, fd ResourceSourceDescriptor) (resource.Resource, error) { @@ -318,7 +314,6 @@ func (r *Spec) newResource(sourceFs afero.Fs, fd ResourceSourceDescriptor) (reso } return newResourceAdapter(gr.spec, fd.LazyPublish, gr), nil - } func (r *Spec) newResourceFor(fd ResourceSourceDescriptor) (resource.Resource, error) { diff --git a/resources/resource_test.go b/resources/resource_test.go index 7a0b8069..bf7a9452 100644 --- a/resources/resource_test.go +++ b/resources/resource_test.go @@ -39,7 +39,6 @@ func TestGenericResource(t *testing.T) { c.Assert(r.Permalink(), qt.Equals, "https://example.com/foo.css") c.Assert(r.RelPermalink(), qt.Equals, "/foo.css") c.Assert(r.ResourceType(), qt.Equals, "css") - } func TestGenericResourceWithLinkFacory(t *testing.T) { @@ -78,7 +77,6 @@ func TestNewResourceFromFilename(t *testing.T) { c.Assert(err, qt.IsNil) c.Assert(r, qt.Not(qt.IsNil)) c.Assert(r.ResourceType(), qt.Equals, "json") - } func TestNewResourceFromFilenameSubPathInBaseURL(t *testing.T) { @@ -96,7 +94,6 @@ func TestNewResourceFromFilenameSubPathInBaseURL(t *testing.T) { c.Assert(r.ResourceType(), qt.Equals, "image") c.Assert(r.RelPermalink(), qt.Equals, "/docs/a/b/logo.png") c.Assert(r.Permalink(), qt.Equals, "https://example.com/docs/a/b/logo.png") - } var pngType, _ = media.FromStringAndExt("image/png", "png") @@ -108,11 +105,11 @@ func TestResourcesByType(t *testing.T) { spec.newGenericResource(nil, nil, nil, "/a/foo1.css", "foo1.css", media.CSSType), spec.newGenericResource(nil, nil, nil, "/a/logo.png", "logo.css", pngType), spec.newGenericResource(nil, nil, nil, "/a/foo2.css", "foo2.css", media.CSSType), - spec.newGenericResource(nil, nil, nil, "/a/foo3.css", "foo3.css", media.CSSType)} + spec.newGenericResource(nil, nil, nil, "/a/foo3.css", "foo3.css", media.CSSType), + } c.Assert(len(resources.ByType("css")), qt.Equals, 3) c.Assert(len(resources.ByType("image")), qt.Equals, 1) - } func TestResourcesGetByPrefix(t *testing.T) { @@ -123,7 +120,8 @@ func TestResourcesGetByPrefix(t *testing.T) { spec.newGenericResource(nil, nil, nil, "/a/logo1.png", "logo1.png", pngType), spec.newGenericResource(nil, nil, nil, "/b/Logo2.png", "Logo2.png", pngType), spec.newGenericResource(nil, nil, nil, "/b/foo2.css", "foo2.css", media.CSSType), - spec.newGenericResource(nil, nil, nil, "/b/foo3.css", "foo3.css", media.CSSType)} + spec.newGenericResource(nil, nil, nil, "/b/foo3.css", "foo3.css", media.CSSType), + } c.Assert(resources.GetMatch("asdf*"), qt.IsNil) c.Assert(resources.GetMatch("logo*").RelPermalink(), qt.Equals, "/logo1.png") @@ -141,7 +139,6 @@ func TestResourcesGetByPrefix(t *testing.T) { c.Assert(logo.Params(), qt.Not(qt.IsNil)) c.Assert(logo.Name(), qt.Equals, "logo1.png") c.Assert(logo.Title(), qt.Equals, "logo1.png") - } func TestResourcesGetMatch(t *testing.T) { @@ -187,7 +184,6 @@ func TestResourcesGetMatch(t *testing.T) { // (it is possible for users to do a rename) // This is analogous to standing in a directory and doing "ls *.*". c.Assert(len(resources.Match("/c/**.css")), qt.Equals, 0) - } func BenchmarkResourcesMatch(b *testing.B) { @@ -218,7 +214,6 @@ func BenchmarkResourcesMatchA100(b *testing.B) { for i := 0; i < b.N; i++ { resources.Match(pattern) } - } func benchResources(b *testing.B) resource.Resources { @@ -242,7 +237,6 @@ func benchResources(b *testing.B) resource.Resources { } return resources - } func BenchmarkAssignMetadata(b *testing.B) { @@ -252,7 +246,7 @@ func BenchmarkAssignMetadata(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() var resources resource.Resources - var meta = []map[string]interface{}{ + meta := []map[string]interface{}{ { "title": "Foo #:counter", "name": "Foo Name #:counter", diff --git a/resources/resource_transformers/babel/babel.go b/resources/resource_transformers/babel/babel.go index a9d39d31..a7598f82 100644 --- a/resources/resource_transformers/babel/babel.go +++ b/resources/resource_transformers/babel/babel.go @@ -51,6 +51,7 @@ func DecodeOptions(m map[string]interface{}) (opts Options, err error) { err = mapstructure.WeakDecode(m, &opts) return } + func (opts Options) toArgs() []string { var args []string @@ -111,7 +112,6 @@ func (t *babelTransformation) Transform(ctx *resources.ResourceTransformationCtx // Try PATH binary = binaryName if _, err := exec.LookPath(binary); err != nil { - // This may be on a CI server etc. Will fall back to pre-built assets. return herrors.ErrFeatureNotAvailable } diff --git a/resources/resource_transformers/integrity/integrity.go b/resources/resource_transformers/integrity/integrity.go index 1b74de7e..bbd0b667 100644 --- a/resources/resource_transformers/integrity/integrity.go +++ b/resources/resource_transformers/integrity/integrity.go @@ -55,7 +55,6 @@ func (t *fingerprintTransformation) Key() internal.ResourceTransformationKey { // Transform creates a MD5 hash of the Resource content and inserts that hash before // the extension in the filename. func (t *fingerprintTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { - h, err := newHash(t.algo) if err != nil { return err diff --git a/resources/resource_transformers/integrity/integrity_test.go b/resources/resource_transformers/integrity/integrity_test.go index 3759e631..8a17fef7 100644 --- a/resources/resource_transformers/integrity/integrity_test.go +++ b/resources/resource_transformers/integrity/integrity_test.go @@ -24,7 +24,6 @@ import ( ) func TestHashFromAlgo(t *testing.T) { - for _, algo := range []struct { name string bits int @@ -35,7 +34,6 @@ func TestHashFromAlgo(t *testing.T) { {"sha512", 512}, {"shaman", -1}, } { - t.Run(algo.name, func(t *testing.T) { c := qt.New(t) h, err := newHash(algo.name) @@ -46,7 +44,6 @@ func TestHashFromAlgo(t *testing.T) { c.Assert(err, qt.Not(qt.IsNil)) c.Assert(err.Error(), qt.Contains, "use either md5, sha256, sha384 or sha512") } - }) } } diff --git a/resources/resource_transformers/js/options.go b/resources/resource_transformers/js/options.go index 925b1995..75daa0ca 100644 --- a/resources/resource_transformers/js/options.go +++ b/resources/resource_transformers/js/options.go @@ -212,12 +212,10 @@ func createBuildPlugins(c *Client, opts Options) ([]api.Plugin, error) { build.OnResolve(api.OnResolveOptions{Filter: `.*`}, func(args api.OnResolveArgs) (api.OnResolveResult, error) { return resolveImport(args) - }) build.OnLoad(api.OnLoadOptions{Filter: `.*`, Namespace: nsImportHugo}, func(args api.OnLoadArgs) (api.OnLoadResult, error) { b, err := ioutil.ReadFile(args.Path) - if err != nil { return api.OnLoadResult{}, errors.Wrapf(err, "failed to read %q", args.Path) } @@ -266,11 +264,9 @@ func createBuildPlugins(c *Client, opts Options) ([]api.Plugin, error) { } return []api.Plugin{importResolver, paramsPlugin}, nil - } func toBuildOptions(opts Options) (buildOptions api.BuildOptions, err error) { - var target api.Target switch opts.Target { case "", "esnext": @@ -336,8 +332,8 @@ func toBuildOptions(opts Options) (buildOptions api.BuildOptions, err error) { } // By default we only need to specify outDir and no outFile - var outDir = opts.outDir - var outFile = "" + outDir := opts.outDir + outFile := "" var sourceMap api.SourceMap switch opts.SourceMap { case "inline": @@ -381,5 +377,4 @@ func toBuildOptions(opts Options) (buildOptions api.BuildOptions, err error) { }, } return - } diff --git a/resources/resource_transformers/js/options_test.go b/resources/resource_transformers/js/options_test.go index ef8c203c..f07ccc26 100644 --- a/resources/resource_transformers/js/options_test.go +++ b/resources/resource_transformers/js/options_test.go @@ -76,7 +76,8 @@ func TestToBuildOptions(t *testing.T) { opts, err = toBuildOptions(Options{ Target: "es2018", Format: "cjs", Minify: true, mediaType: media.JavascriptType, - SourceMap: "inline"}) + SourceMap: "inline", + }) c.Assert(err, qt.IsNil) c.Assert(opts, qt.DeepEquals, api.BuildOptions{ Bundle: true, @@ -93,7 +94,8 @@ func TestToBuildOptions(t *testing.T) { opts, err = toBuildOptions(Options{ Target: "es2018", Format: "cjs", Minify: true, mediaType: media.JavascriptType, - SourceMap: "inline"}) + SourceMap: "inline", + }) c.Assert(err, qt.IsNil) c.Assert(opts, qt.DeepEquals, api.BuildOptions{ Bundle: true, @@ -107,5 +109,4 @@ func TestToBuildOptions(t *testing.T) { Loader: api.LoaderJS, }, }) - } diff --git a/resources/resource_transformers/minifier/minify.go b/resources/resource_transformers/minifier/minify.go index 060485e8..51a3f404 100644 --- a/resources/resource_transformers/minifier/minify.go +++ b/resources/resource_transformers/minifier/minify.go @@ -57,5 +57,4 @@ func (c *Client) Minify(res resources.ResourceTransformer) (resource.Resource, e rs: c.rs, m: c.m, }) - } diff --git a/resources/resource_transformers/minifier/minify_test.go b/resources/resource_transformers/minifier/minify_test.go index 38828c17..b0ebe317 100644 --- a/resources/resource_transformers/minifier/minify_test.go +++ b/resources/resource_transformers/minifier/minify_test.go @@ -39,5 +39,4 @@ func TestTransform(t *testing.T) { content, err := transformed.(resource.ContentProvider).Content() c.Assert(err, qt.IsNil) c.Assert(content, qt.Equals, "

Hugo Rocks!

") - } diff --git a/resources/resource_transformers/postcss/postcss.go b/resources/resource_transformers/postcss/postcss.go index daeb7212..8ba40ebd 100644 --- a/resources/resource_transformers/postcss/postcss.go +++ b/resources/resource_transformers/postcss/postcss.go @@ -19,6 +19,7 @@ import ( "encoding/hex" "io" "io/ioutil" + "os/exec" "path" "path/filepath" "regexp" @@ -36,8 +37,6 @@ import ( "github.com/gohugoio/hugo/hugofs" "github.com/pkg/errors" - "os/exec" - "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/common/herrors" @@ -139,7 +138,6 @@ func (t *postcssTransformation) Key() internal.ResourceTransformationKey { // npm install -g postcss-cli // npm install -g autoprefixer func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationCtx) error { - const localPostCSSPath = "node_modules/.bin/" const binaryName = "postcss" @@ -174,7 +172,6 @@ func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationC if configFile == "" && t.options.Config != "" { // Only fail if the user specificed config file is not found. return errors.Errorf("postcss config %q not found:", configFile) - } } @@ -271,7 +268,6 @@ func (imp *importResolver) importRecursive( lineNum int, content string, inPath string) (int, string, error) { - basePath := path.Dir(inPath) var replacements []string @@ -350,7 +346,6 @@ func (imp *importResolver) resolve() (io.Reader, error) { } return strings.NewReader(newContent), nil - } // See https://www.w3schools.com/cssref/pr_import_rule.asp diff --git a/resources/resource_transformers/postcss/postcss_test.go b/resources/resource_transformers/postcss/postcss_test.go index a49487c9..c5f85544 100644 --- a/resources/resource_transformers/postcss/postcss_test.go +++ b/resources/resource_transformers/postcss/postcss_test.go @@ -44,7 +44,6 @@ func TestDecodeOptions(t *testing.T) { c.Assert(err, qt.IsNil) c.Assert(opts2.NoMap, qt.Equals, true) - } func TestShouldImport(t *testing.T) { @@ -117,7 +116,6 @@ E_STYLE Offset: 1, Filename: "d.css", }) - } func BenchmarkImportResolver(b *testing.B) { diff --git a/resources/resource_transformers/tocss/scss/client_test.go b/resources/resource_transformers/tocss/scss/client_test.go index f9adac22..9dddd386 100644 --- a/resources/resource_transformers/tocss/scss/client_test.go +++ b/resources/resource_transformers/tocss/scss/client_test.go @@ -46,5 +46,4 @@ func TestReplaceRegularCSSImports(t *testing.T) { reverted := replaceRegularImportsOut(res) c.Assert(reverted, qt.Equals, scssWithImport) - } diff --git a/resources/resource_transformers/tocss/scss/tocss.go b/resources/resource_transformers/tocss/scss/tocss.go index fc7a19f3..f4f15fad 100644 --- a/resources/resource_transformers/tocss/scss/tocss.go +++ b/resources/resource_transformers/tocss/scss/tocss.go @@ -127,7 +127,7 @@ func (t *toCSSTransformation) Transform(ctx *resources.ResourceTransformationCtx // more correct for the main entry path (main.scss typically), but // it will mess up the import mappings. As a workaround, we do a replacement // in the source map itself (see below). - //options.InputPath = inputPath + // options.InputPath = inputPath options.to.SourceMapOptions.OutputPath = outName options.to.SourceMapOptions.Contents = true options.to.SourceMapOptions.OmitURL = false diff --git a/resources/testhelpers_test.go b/resources/testhelpers_test.go index 0462f7ec..32e4213e 100644 --- a/resources/testhelpers_test.go +++ b/resources/testhelpers_test.go @@ -1,15 +1,14 @@ package resources import ( - "path/filepath" - "testing" - "image" "io" "io/ioutil" "os" + "path/filepath" "runtime" "strings" + "testing" "github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/modules" @@ -51,11 +50,9 @@ func createTestCfg() *viper.Viper { cfg.Set("allModules", modules.Modules{mod}) return cfg - } func newTestResourceSpec(desc specDescriptor) *Spec { - baseURL := desc.baseURL if baseURL == "" { baseURL = "https://example.com/" @@ -133,7 +130,6 @@ func newTestResourceOsFs(c *qt.C) (*Spec, string) { c.Assert(err, qt.IsNil) return spec, workDir - } func fetchSunset(c *qt.C) resource.Image { diff --git a/resources/transform.go b/resources/transform.go index 354a20ee..d995bb46 100644 --- a/resources/transform.go +++ b/resources/transform.go @@ -293,7 +293,6 @@ func (r *resourceAdapter) publish() { r.spec.Logger.Errorf("Failed to publish Resource: %s", r.publisherErr) } }) - } func (r *resourceAdapter) TransformationKey() string { @@ -397,7 +396,6 @@ func (r *resourceAdapter) transform(publish, setContent bool) error { } newErr := func(err error) error { - msg := fmt.Sprintf("%s: failed to transform %q (%s)", strings.ToUpper(tr.Key().Name), tctx.InPath, tctx.InMediaType.Type()) if err == herrors.ErrFeatureNotAvailable { @@ -416,7 +414,6 @@ func (r *resourceAdapter) transform(publish, setContent bool) error { } return errors.Wrap(err, msg) - } var tryFileCache bool diff --git a/resources/transform_test.go b/resources/transform_test.go index b2dad221..488fefd6 100644 --- a/resources/transform_test.go +++ b/resources/transform_test.go @@ -385,11 +385,10 @@ func TestTransform(t *testing.T) { resizedNotPublished, err := img.Resize("50x50") c.Assert(err, qt.IsNil) c.Assert(resizedNotPublished.Height(), qt.Equals, 50) - //c.Assert(resized.RelPermalink(), qt.Equals, "/gopher.changed_hu2e827f5a78333ebc04166dd643235dea_1462_50x50_resize_linear_2.png") + // c.Assert(resized.RelPermalink(), qt.Equals, "/gopher.changed_hu2e827f5a78333ebc04166dd643235dea_1462_50x50_resize_linear_2.png") assertShouldExist(c, spec, "public/gopher.changed_hu2e827f5a78333ebc04166dd643235dea_1462_50x50_resize_linear_2.png", false) assertNoDuplicateWrites(c, spec) - }) c.Run("Concurrent", func(c *qt.C) { diff --git a/scripts/fork_go_templates/main.go b/scripts/fork_go_templates/main.go index 04202b25..c295ab73 100644 --- a/scripts/fork_go_templates/main.go +++ b/scripts/fork_go_templates/main.go @@ -35,7 +35,6 @@ func main() { goimports(htmlRoot) gofmt(forkRoot) - } const ( @@ -97,36 +96,41 @@ package parse } return content - } var goPackages = []goPackage{ - goPackage{srcPkg: "text/template", dstPkg: "texttemplate", - replacer: func(name, content string) string { return textTemplateReplacers.Replace(commonReplace(name, content)) }}, - goPackage{srcPkg: "html/template", dstPkg: "htmltemplate", replacer: func(name, content string) string { - if strings.HasSuffix(name, "content.go") { - // Remove template.HTML types. We need to use the Go types. - content = removeAll(`(?s)// Strings of content.*?\)\n`, content) - } - - content = commonReplace(name, content) - - return htmlTemplateReplacers.Replace(content) + { + srcPkg: "text/template", dstPkg: "texttemplate", + replacer: func(name, content string) string { return textTemplateReplacers.Replace(commonReplace(name, content)) }, }, + { + srcPkg: "html/template", dstPkg: "htmltemplate", replacer: func(name, content string) string { + if strings.HasSuffix(name, "content.go") { + // Remove template.HTML types. We need to use the Go types. + content = removeAll(`(?s)// Strings of content.*?\)\n`, content) + } + + content = commonReplace(name, content) + + return htmlTemplateReplacers.Replace(content) + }, rewriter: func(name string) { for _, s := range []string{"CSS", "HTML", "HTMLAttr", "JS", "JSStr", "URL", "Srcset"} { rewrite(name, fmt.Sprintf("%s -> htmltemplate.%s", s, s)) } rewrite(name, `"text/template/parse" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"`) - }}, - goPackage{srcPkg: "internal/fmtsort", dstPkg: "fmtsort", rewriter: func(name string) { + }, + }, + {srcPkg: "internal/fmtsort", dstPkg: "fmtsort", rewriter: func(name string) { rewrite(name, `"internal/fmtsort" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort"`) }}, - goPackage{srcPkg: "internal/testenv", dstPkg: "testenv", + { + srcPkg: "internal/testenv", dstPkg: "testenv", replacer: func(name, content string) string { return testEnvReplacers.Replace(content) }, rewriter: func(name string) { rewrite(name, `"internal/testenv" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/testenv"`) - }}, - goPackage{srcPkg: "internal/cfg", dstPkg: "cfg", rewriter: func(name string) { + }, + }, + {srcPkg: "internal/cfg", dstPkg: "cfg", rewriter: func(name string) { rewrite(name, `"internal/cfg" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/cfg"`) }}, } @@ -196,7 +200,6 @@ func doWithGoFiles(dir string, func removeAll(expression, content string) string { re := regexp.MustCompile(expression) return re.ReplaceAllString(content, "") - } func rewrite(filename, rule string) { diff --git a/source/fileInfo.go b/source/fileInfo.go index 849afa45..4e786631 100644 --- a/source/fileInfo.go +++ b/source/fileInfo.go @@ -232,7 +232,6 @@ func (sp *SourceSpec) NewFileInfoFrom(path, filename string) (*FileInfo, error) } func (sp *SourceSpec) NewFileInfo(fi hugofs.FileMetaInfo) (*FileInfo, error) { - m := fi.Meta() filename := m.Filename() @@ -290,5 +289,4 @@ func (sp *SourceSpec) NewFileInfo(fi hugofs.FileMetaInfo) (*FileInfo, error) { } return f, nil - } diff --git a/source/fileInfo_test.go b/source/fileInfo_test.go index 1c9da7e4..b8bb33cd 100644 --- a/source/fileInfo_test.go +++ b/source/fileInfo_test.go @@ -38,18 +38,15 @@ func TestFileInfo(t *testing.T) { c.Assert(f.Section(), qt.Equals, "b") c.Assert(f.TranslationBaseName(), qt.Equals, filepath.FromSlash("page")) c.Assert(f.BaseFileName(), qt.Equals, filepath.FromSlash("page")) - }}, {filepath.FromSlash("/a/"), filepath.FromSlash("/a/b/c/d/page.md"), func(f *FileInfo) { c.Assert(f.Section(), qt.Equals, "b") - }}, {filepath.FromSlash("/a/"), filepath.FromSlash("/a/b/page.en.MD"), func(f *FileInfo) { c.Assert(f.Section(), qt.Equals, "b") c.Assert(f.Path(), qt.Equals, filepath.FromSlash("b/page.en.MD")) c.Assert(f.TranslationBaseName(), qt.Equals, filepath.FromSlash("page")) c.Assert(f.BaseFileName(), qt.Equals, filepath.FromSlash("page.en")) - }}, } { path := strings.TrimPrefix(this.filename, this.base) @@ -57,5 +54,4 @@ func TestFileInfo(t *testing.T) { c.Assert(err, qt.IsNil) this.assert(f) } - } diff --git a/source/filesystem.go b/source/filesystem.go index ce62c15a..1cd75f03 100644 --- a/source/filesystem.go +++ b/source/filesystem.go @@ -102,11 +102,9 @@ func (f *Filesystem) captureFiles() error { }) return w.Walk() - } func (f *Filesystem) shouldRead(filename string, fi hugofs.FileMetaInfo) (bool, error) { - ignore := f.SourceSpec.IgnoreFile(fi.Meta().Filename()) if fi.IsDir() { diff --git a/source/filesystem_test.go b/source/filesystem_test.go index ec7a305d..5dc18797 100644 --- a/source/filesystem_test.go +++ b/source/filesystem_test.go @@ -74,7 +74,6 @@ func TestUnicodeNorm(t *testing.T) { t.Fatalf("file %q name in NFD form should be normalized (%s)", f.BaseFileName(), path.NFC) } } - } func newTestConfig() *viper.Viper { diff --git a/source/sourceSpec.go b/source/sourceSpec.go index 504a3a22..e8407a14 100644 --- a/source/sourceSpec.go +++ b/source/sourceSpec.go @@ -74,7 +74,6 @@ func NewSourceSpec(ps *helpers.PathSpec, fs afero.Fs) *SourceSpec { } return &SourceSpec{ignoreFilesRe: regexps, PathSpec: ps, SourceFs: fs, Languages: languages, DefaultContentLanguage: defaultLang, DisabledLanguages: disabledLangsSet} - } // IgnoreFile returns whether a given file should be ignored. diff --git a/tpl/cast/cast_test.go b/tpl/cast/cast_test.go index d3f8d973..c6219728 100644 --- a/tpl/cast/cast_test.go +++ b/tpl/cast/cast_test.go @@ -15,7 +15,6 @@ package cast import ( "html/template" - "testing" qt "github.com/frankban/quicktest" diff --git a/tpl/cast/docshelper.go b/tpl/cast/docshelper.go index a497f6e8..035db174 100644 --- a/tpl/cast/docshelper.go +++ b/tpl/cast/docshelper.go @@ -41,7 +41,6 @@ func init() { } return docshelper.DocProvider{"tpl": map[string]interface{}{"funcs": namespaces}} - } docshelper.AddDocProviderFunc(docsProvider) diff --git a/tpl/cast/init.go b/tpl/cast/init.go index 3aee6f03..3f1f3f25 100644 --- a/tpl/cast/init.go +++ b/tpl/cast/init.go @@ -51,7 +51,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/cast/init_test.go b/tpl/cast/init_test.go index 73d9d5ad..dd024b77 100644 --- a/tpl/cast/init_test.go +++ b/tpl/cast/init_test.go @@ -38,5 +38,4 @@ func TestInit(t *testing.T) { c.Assert(found, qt.Equals, true) c.Assert(ns.Context(), hqt.IsSameType, &Namespace{}) - } diff --git a/tpl/collections/append.go b/tpl/collections/append.go index 297328dc..50fafe3d 100644 --- a/tpl/collections/append.go +++ b/tpl/collections/append.go @@ -34,5 +34,4 @@ func (ns *Namespace) Append(args ...interface{}) (interface{}, error) { from := args[:len(args)-1] return collections.Append(to, from...) - } diff --git a/tpl/collections/append_test.go b/tpl/collections/append_test.go index a254601b..9dcc7d2b 100644 --- a/tpl/collections/append_test.go +++ b/tpl/collections/append_test.go @@ -40,9 +40,11 @@ func TestAppend(t *testing.T) { {"", []interface{}{[]string{"a", "b"}}, false}, {[]string{"a", "b"}, []interface{}{}, false}, // No string concatenation. - {"ab", + { + "ab", []interface{}{"c"}, - false}, + false, + }, } { errMsg := qt.Commentf("[%d]", i) @@ -62,5 +64,4 @@ func TestAppend(t *testing.T) { t.Fatalf("%s got\n%T: %v\nexpected\n%T: %v", errMsg, result, result, test.expected, test.expected) } } - } diff --git a/tpl/collections/apply.go b/tpl/collections/apply.go index 55d29d3a..86554def 100644 --- a/tpl/collections/apply.go +++ b/tpl/collections/apply.go @@ -52,7 +52,6 @@ func (ns *Namespace) Apply(seq interface{}, fname string, args ...interface{}) ( vv := seqv.Index(i) vvv, err := applyFnToThis(fnv, vv, args...) - if err != nil { return nil, err } diff --git a/tpl/collections/apply_test.go b/tpl/collections/apply_test.go index f9199b6b..98cb78b5 100644 --- a/tpl/collections/apply_test.go +++ b/tpl/collections/apply_test.go @@ -14,12 +14,11 @@ package collections import ( + "fmt" "io" "reflect" "testing" - "fmt" - qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/output" @@ -58,7 +57,6 @@ func (templateFinder) GetFunc(name string) (reflect.Value, bool) { } return reflect.ValueOf(fmt.Sprint), true - } func TestApply(t *testing.T) { @@ -88,5 +86,4 @@ func TestApply(t *testing.T) { if err == nil { t.Errorf("apply with unknown func should fail") } - } diff --git a/tpl/collections/collections.go b/tpl/collections/collections.go index d9046702..3521f9cd 100644 --- a/tpl/collections/collections.go +++ b/tpl/collections/collections.go @@ -18,7 +18,6 @@ package collections import ( "fmt" "html/template" - "math/rand" "net/url" "reflect" @@ -478,9 +477,9 @@ func (ns *Namespace) Seq(args ...interface{}) ([]int, error) { return nil, errors.New("invalid arguments to Seq") } - var inc = 1 + inc := 1 var last int - var first = intArgs[0] + first := intArgs[0] if len(intArgs) == 1 { last = first @@ -580,7 +579,6 @@ type intersector struct { } func (i *intersector) appendIfNotSeen(v reflect.Value) { - vi := v.Interface() if !i.seen[vi] { i.r = reflect.Append(i.r, v) @@ -729,7 +727,6 @@ func (ns *Namespace) Uniq(seq interface{}) (interface{}, error) { } return slice.Interface(), nil - } // KeyVals creates a key and values wrapper. diff --git a/tpl/collections/collections_test.go b/tpl/collections/collections_test.go index 21c8bfb5..a75ec9d1 100644 --- a/tpl/collections/collections_test.go +++ b/tpl/collections/collections_test.go @@ -17,7 +17,6 @@ import ( "errors" "fmt" "html/template" - "math/rand" "reflect" "testing" @@ -195,8 +194,10 @@ func TestDictionary(t *testing.T) { }{ {[]interface{}{"a", "b"}, map[string]interface{}{"a": "b"}}, {[]interface{}{[]string{"a", "b"}, "c"}, map[string]interface{}{"a": map[string]interface{}{"b": "c"}}}, - {[]interface{}{[]string{"a", "b"}, "c", []string{"a", "b2"}, "c2", "b", "c"}, - map[string]interface{}{"a": map[string]interface{}{"b": "c", "b2": "c2"}, "b": "c"}}, + { + []interface{}{[]string{"a", "b"}, "c", []string{"a", "b2"}, "c2", "b", "c"}, + map[string]interface{}{"a": map[string]interface{}{"b": "c", "b2": "c2"}, "b": "c"}, + }, {[]interface{}{"a", 12, "b", []int{4}}, map[string]interface{}{"a": 12, "b": []int{4}}}, // errors {[]interface{}{5, "b"}, false}, @@ -237,7 +238,6 @@ func TestReverse(t *testing.T) { c.Assert(reversed, qt.IsNil) _, err = ns.Reverse(43) c.Assert(err, qt.Not(qt.IsNil)) - } func TestEchoParam(t *testing.T) { @@ -369,8 +369,10 @@ func (p testPage) String() string { return "p-" + p.Title } -type pagesPtr []*testPage -type pagesVals []testPage +type ( + pagesPtr []*testPage + pagesVals []testPage +) var ( p1 = &testPage{"A"} @@ -716,7 +718,6 @@ func TestSlice(t *testing.T) { c.Assert(result, qt.DeepEquals, test.expected, errMsg) } - } func TestUnion(t *testing.T) { @@ -907,7 +908,6 @@ type TstParams struct { func (x TstParams) Params() maps.Params { return x.params - } type TstXIHolder struct { diff --git a/tpl/collections/complement_test.go b/tpl/collections/complement_test.go index d0e27353..7e8d695b 100644 --- a/tpl/collections/complement_test.go +++ b/tpl/collections/complement_test.go @@ -66,7 +66,8 @@ func TestComplement(t *testing.T) { {"error", []interface{}{[]string{"c", "d"}, []string{"a", "b"}}, false}, {[]string{"a", "b", "c"}, []interface{}{[][]string{{"c", "d"}}}, false}, { - []interface{}{[][]string{{"c", "d"}}}, []interface{}{[]string{"c", "d"}, []string{"a", "b"}}, + []interface{}{[][]string{{"c", "d"}}}, + []interface{}{[]string{"c", "d"}, []string{"a", "b"}}, []interface{}{[][]string{{"c", "d"}}}, }, } { @@ -93,5 +94,4 @@ func TestComplement(t *testing.T) { c.Assert(err, qt.Not(qt.IsNil)) _, err = ns.Complement([]string{"a", "b"}) c.Assert(err, qt.Not(qt.IsNil)) - } diff --git a/tpl/collections/index_test.go b/tpl/collections/index_test.go index 0c380d8d..c690fe64 100644 --- a/tpl/collections/index_test.go +++ b/tpl/collections/index_test.go @@ -52,7 +52,6 @@ func TestIndex(t *testing.T) { {[]int{0, 1}, []interface{}{nil}, nil, true}, {tstNoStringer{}, []interface{}{0}, nil, true}, } { - c.Run(fmt.Sprint(i), func(c *qt.C) { errMsg := qt.Commentf("[%d] %v", i, test) diff --git a/tpl/collections/merge_test.go b/tpl/collections/merge_test.go index 92c973cd..bde4d90b 100644 --- a/tpl/collections/merge_test.go +++ b/tpl/collections/merge_test.go @@ -43,7 +43,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"a": 42, "c": 3}, map[string]interface{}{"a": 1, "b": 2}, }, - map[string]interface{}{"a": 1, "b": 2, "c": 3}, false, + map[string]interface{}{"a": 1, "b": 2, "c": 3}, + false, }, { "multi", @@ -52,7 +53,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"a": 1, "b": 2}, map[string]interface{}{"a": 9, "c": 4, "d": 7}, }, - map[string]interface{}{"a": 9, "b": 2, "c": 4, "d": 7, "e": 11}, false, + map[string]interface{}{"a": 9, "b": 2, "c": 4, "d": 7, "e": 11}, + false, }, { "basic case insensitive", @@ -60,7 +62,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"A": 42, "c": 3}, map[string]interface{}{"a": 1, "b": 2}, }, - map[string]interface{}{"a": 1, "b": 2, "c": 3}, false, + map[string]interface{}{"a": 1, "b": 2, "c": 3}, + false, }, { "nested", @@ -68,7 +71,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"a": 42, "c": 3, "b": map[string]interface{}{"d": 55, "e": 66, "f": 3}}, map[string]interface{}{"a": 1, "b": map[string]interface{}{"d": 1, "e": 2}}, }, - map[string]interface{}{"a": 1, "b": map[string]interface{}{"d": 1, "e": 2, "f": 3}, "c": 3}, false, + map[string]interface{}{"a": 1, "b": map[string]interface{}{"d": 1, "e": 2, "f": 3}, "c": 3}, + false, }, { // https://github.com/gohugoio/hugo/issues/6633 @@ -77,7 +81,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"a": 42, "c": 3}, maps.Params{"a": 1, "b": 2}, }, - maps.Params{"a": int(1), "b": int(2), "c": int(3)}, false, + maps.Params{"a": int(1), "b": int(2), "c": int(3)}, + false, }, { "params dst, upper case src", @@ -85,7 +90,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"a": 42, "C": 3}, maps.Params{"a": 1, "b": 2}, }, - maps.Params{"a": int(1), "b": int(2), "c": int(3)}, false, + maps.Params{"a": int(1), "b": int(2), "c": int(3)}, + false, }, { "params src", @@ -93,7 +99,8 @@ func TestMerge(t *testing.T) { maps.Params{"a": 42, "c": 3}, map[string]interface{}{"a": 1, "c": 2}, }, - map[string]interface{}{"a": int(1), "c": int(2)}, false, + map[string]interface{}{"a": int(1), "c": int(2)}, + false, }, { "params src, upper case dst", @@ -101,7 +108,8 @@ func TestMerge(t *testing.T) { maps.Params{"a": 42, "c": 3}, map[string]interface{}{"a": 1, "C": 2}, }, - map[string]interface{}{"a": int(1), "C": int(2)}, false, + map[string]interface{}{"a": int(1), "C": int(2)}, + false, }, { "nested, params dst", @@ -109,7 +117,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"a": 42, "c": 3, "b": map[string]interface{}{"d": 55, "e": 66, "f": 3}}, maps.Params{"a": 1, "b": maps.Params{"d": 1, "e": 2}}, }, - maps.Params{"a": 1, "b": maps.Params{"d": 1, "e": 2, "f": 3}, "c": 3}, false, + maps.Params{"a": 1, "b": maps.Params{"d": 1, "e": 2, "f": 3}, "c": 3}, + false, }, { // https://github.com/gohugoio/hugo/issues/7899 @@ -118,7 +127,8 @@ func TestMerge(t *testing.T) { map[string]interface{}{"k": "v"}, map[string]interface{}{"k": map[string]interface{}{"k2": "v2"}}, }, - map[string]interface{}{"k": map[string]interface{}{"k2": "v2"}}, false, + map[string]interface{}{"k": map[string]interface{}{"k2": "v2"}}, + false, }, {"src nil", []interface{}{nil, simpleMap}, simpleMap, false}, // Error cases. diff --git a/tpl/collections/reflect_helpers.go b/tpl/collections/reflect_helpers.go index 3d73b70e..453d2f35 100644 --- a/tpl/collections/reflect_helpers.go +++ b/tpl/collections/reflect_helpers.go @@ -165,7 +165,6 @@ func convertNumber(v reflect.Value, to reflect.Kind) (reflect.Value, error) { } return n, nil - } func newSliceElement(items interface{}) interface{} { diff --git a/tpl/collections/sort_test.go b/tpl/collections/sort_test.go index 75e23fc7..4798b509 100644 --- a/tpl/collections/sort_test.go +++ b/tpl/collections/sort_test.go @@ -238,7 +238,6 @@ func TestSort(t *testing.T) { }, {nil, nil, "asc", false}, } { - t.Run(fmt.Sprintf("test%d", i), func(t *testing.T) { var result interface{} var err error @@ -261,6 +260,5 @@ func TestSort(t *testing.T) { } } }) - } } diff --git a/tpl/collections/symdiff.go b/tpl/collections/symdiff.go index 85a2076a..e61814e2 100644 --- a/tpl/collections/symdiff.go +++ b/tpl/collections/symdiff.go @@ -65,5 +65,4 @@ func (ns *Namespace) SymDiff(s2, s1 interface{}) (interface{}, error) { } return slice.Interface(), nil - } diff --git a/tpl/collections/symdiff_test.go b/tpl/collections/symdiff_test.go index ac40fda5..120dfaac 100644 --- a/tpl/collections/symdiff_test.go +++ b/tpl/collections/symdiff_test.go @@ -75,5 +75,4 @@ func TestSymDiff(t *testing.T) { c.Assert(err, qt.Not(qt.IsNil)) _, err = ns.Complement([]string{"a", "b"}) c.Assert(err, qt.Not(qt.IsNil)) - } diff --git a/tpl/collections/where_test.go b/tpl/collections/where_test.go index d6a1dd14..75ee109f 100644 --- a/tpl/collections/where_test.go +++ b/tpl/collections/where_test.go @@ -62,7 +62,6 @@ func TestWhere(t *testing.T) { } return testVariants - } for i, test := range []testt{ @@ -171,17 +170,17 @@ func TestWhere(t *testing.T) { }, key: "B", match: "b2", expect: []maps.Params{ - maps.Params{"a": "a2", "b": "b2"}, + {"a": "a2", "b": "b2"}, }, }, { seq: []maps.Params{ - maps.Params{ + { "a": map[string]interface{}{ "b": "b1", }, }, - maps.Params{ + { "a": map[string]interface{}{ "b": "b2", }, @@ -189,7 +188,7 @@ func TestWhere(t *testing.T) { }, key: "A.B", match: "b2", expect: []maps.Params{ - maps.Params{ + { "a": map[string]interface{}{ "b": "b2", }, diff --git a/tpl/compare/compare_test.go b/tpl/compare/compare_test.go index c21ca11b..76fe2698 100644 --- a/tpl/compare/compare_test.go +++ b/tpl/compare/compare_test.go @@ -44,8 +44,10 @@ var testT = &T{ NonEmptyInterfaceTypedNil: (*T)(nil), } -type tstEqerType1 string -type tstEqerType2 string +type ( + tstEqerType1 string + tstEqerType2 string +) func (t tstEqerType2) Eq(other interface{}) bool { return cast.ToString(t) == cast.ToString(other) @@ -397,7 +399,6 @@ func TestCase(t *testing.T) { c.Assert(n.Eq("az", "az"), qt.Equals, true) c.Assert(n.Eq("az", stringType("az")), qt.Equals, true) - } func TestStringType(t *testing.T) { diff --git a/tpl/compare/init.go b/tpl/compare/init.go index 3b9dc685..f96e382e 100644 --- a/tpl/compare/init.go +++ b/tpl/compare/init.go @@ -79,7 +79,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/crypto/init.go b/tpl/crypto/init.go index 9a958bd3..2c6e9429 100644 --- a/tpl/crypto/init.go +++ b/tpl/crypto/init.go @@ -59,7 +59,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/data/data.go b/tpl/data/data.go index 96484433..15d042e0 100644 --- a/tpl/data/data.go +++ b/tpl/data/data.go @@ -35,7 +35,6 @@ import ( // New returns a new instance of the data-namespaced template functions. func New(deps *deps.Deps) *Namespace { - return &Namespace{ deps: deps, cacheGetCSV: deps.FileCaches.GetCSVCache(), diff --git a/tpl/data/data_test.go b/tpl/data/data_test.go index e1839dd4..f9e8621f 100644 --- a/tpl/data/data_test.go +++ b/tpl/data/data_test.go @@ -109,7 +109,7 @@ func TestGetCSV(t *testing.T) { if _, ok := test.expect.(bool); ok { c.Assert(int(ns.deps.Log.LogCounters().ErrorCounter.Count()), qt.Equals, 1) - //c.Assert(err, msg, qt.Not(qt.IsNil)) + // c.Assert(err, msg, qt.Not(qt.IsNil)) c.Assert(got, qt.IsNil) continue } @@ -199,7 +199,7 @@ func TestGetJSON(t *testing.T) { if _, ok := test.expect.(bool); ok { c.Assert(int(ns.deps.Log.LogCounters().ErrorCounter.Count()), qt.Equals, 1) - //c.Assert(err, msg, qt.Not(qt.IsNil)) + // c.Assert(err, msg, qt.Not(qt.IsNil)) continue } diff --git a/tpl/data/resources.go b/tpl/data/resources.go index a7b8b3f4..ba98f12b 100644 --- a/tpl/data/resources.go +++ b/tpl/data/resources.go @@ -81,7 +81,6 @@ func (ns *Namespace) getRemote(cache *filecache.Cache, unmarshal func([]byte) (b } return nil, err - }) if !handled { @@ -100,7 +99,6 @@ func getLocal(url string, fs afero.Fs, cfg config.Provider) ([]byte, error) { } return afero.ReadFile(fs, filename) - } // getResource loads the content of a local or remote file and returns its content and the diff --git a/tpl/data/resources_test.go b/tpl/data/resources_test.go index 7350f82f..5ad0f097 100644 --- a/tpl/data/resources_test.go +++ b/tpl/data/resources_test.go @@ -69,7 +69,6 @@ func TestScpGetLocal(t *testing.T) { t.Errorf("\nExpected: %s\nActual: %s\n", string(test.content), string(c)) } } - } func getTestServer(handler func(w http.ResponseWriter, r *http.Request)) (*httptest.Server, *http.Client) { diff --git a/tpl/fmt/fmt.go b/tpl/fmt/fmt.go index 780add0d..713088b5 100644 --- a/tpl/fmt/fmt.go +++ b/tpl/fmt/fmt.go @@ -50,7 +50,6 @@ func (ns *Namespace) Print(a ...interface{}) string { // Printf returns a formatted string representation of the passed arguments. func (ns *Namespace) Printf(format string, a ...interface{}) string { return _fmt.Sprintf(format, a...) - } // Println returns string representation of the passed arguments ending with a newline. diff --git a/tpl/hugo/init.go b/tpl/hugo/init.go index 1556b759..c57d4a27 100644 --- a/tpl/hugo/init.go +++ b/tpl/hugo/init.go @@ -23,7 +23,6 @@ const name = "hugo" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { - h := d.Site.Hugo() ns := &internal.TemplateFuncsNamespace{ @@ -34,7 +33,6 @@ func init() { // We just add the Hugo struct as the namespace here. No method mappings. return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/images/init.go b/tpl/images/init.go index 299c7684..e9fd52e7 100644 --- a/tpl/images/init.go +++ b/tpl/images/init.go @@ -35,7 +35,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/inflect/init.go b/tpl/inflect/init.go index 3f258356..52b234df 100644 --- a/tpl/inflect/init.go +++ b/tpl/inflect/init.go @@ -54,7 +54,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/internal/go_templates/fmtsort/sort_test.go b/tpl/internal/go_templates/fmtsort/sort_test.go index 364c5bf6..189c693c 100644 --- a/tpl/internal/go_templates/fmtsort/sort_test.go +++ b/tpl/internal/go_templates/fmtsort/sort_test.go @@ -6,11 +6,12 @@ package fmtsort_test import ( "fmt" - "github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort" "math" "reflect" "strings" "testing" + + "github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort" ) var compareTests = [][]reflect.Value{ diff --git a/tpl/internal/go_templates/htmltemplate/content_test.go b/tpl/internal/go_templates/htmltemplate/content_test.go index b5de701d..f2c5c5ed 100644 --- a/tpl/internal/go_templates/htmltemplate/content_test.go +++ b/tpl/internal/go_templates/htmltemplate/content_test.go @@ -427,7 +427,7 @@ func TestStringer(t *testing.T) { if err := tmpl.Execute(b, s); err != nil { t.Fatal(err) } - var expect = "string=3" + expect := "string=3" if b.String() != expect { t.Errorf("expected %q got %q", expect, b.String()) } diff --git a/tpl/internal/go_templates/htmltemplate/css.go b/tpl/internal/go_templates/htmltemplate/css.go index eb92fc92..b006a071 100644 --- a/tpl/internal/go_templates/htmltemplate/css.go +++ b/tpl/internal/go_templates/htmltemplate/css.go @@ -210,8 +210,10 @@ var cssReplacementTable = []string{ '}': `\7d`, } -var expressionBytes = []byte("expression") -var mozBindingBytes = []byte("mozbinding") +var ( + expressionBytes = []byte("expression") + mozBindingBytes = []byte("mozbinding") +) // cssValueFilter allows innocuous CSS values in the output including CSS // quantities (10px or 25%), ID or class literals (#foo, .bar), keyword values diff --git a/tpl/internal/go_templates/htmltemplate/escape_test.go b/tpl/internal/go_templates/htmltemplate/escape_test.go index 075db4e1..ee5421cc 100644 --- a/tpl/internal/go_templates/htmltemplate/escape_test.go +++ b/tpl/internal/go_templates/htmltemplate/escape_test.go @@ -891,7 +891,6 @@ func TestEscapeSet(t *testing.T) { t.Errorf("want\n\t%q\ngot\n\t%q", test.want, got) } } - } func TestErrors(t *testing.T) { @@ -1088,7 +1087,6 @@ func TestErrors(t *testing.T) { // Check that we get the same error if we call Execute again. if err := tmpl.Execute(buf, nil); err == nil || err.Error() != got { t.Errorf("input=%q: unexpected error on second call %q", test.input, err) - } } } diff --git a/tpl/internal/go_templates/htmltemplate/example_test.go b/tpl/internal/go_templates/htmltemplate/example_test.go index a93b8d2f..ee1cbbb4 100644 --- a/tpl/internal/go_templates/htmltemplate/example_test.go +++ b/tpl/internal/go_templates/htmltemplate/example_test.go @@ -82,7 +82,6 @@ func Example() { //
no rows
// // - } func Example_autoescaping() { @@ -123,7 +122,6 @@ func Example_escape() { // \"Fran \u0026 Freddie\'s Diner\" \u003Ctasty@example.com\u003E // \"Fran \u0026 Freddie\'s Diner\"32\u003Ctasty@example.com\u003E // %22Fran+%26+Freddie%27s+Diner%2232%3Ctasty%40example.com%3E - } func ExampleTemplate_Delims() { diff --git a/tpl/internal/go_templates/htmltemplate/js.go b/tpl/internal/go_templates/htmltemplate/js.go index cfd41346..f19e774c 100644 --- a/tpl/internal/go_templates/htmltemplate/js.go +++ b/tpl/internal/go_templates/htmltemplate/js.go @@ -337,6 +337,7 @@ var jsStrNormReplacementTable = []string{ '<': `\u003c`, '>': `\u003e`, } + var jsRegexpReplacementTable = []string{ 0: `\u0000`, '\t': `\t`, diff --git a/tpl/internal/go_templates/htmltemplate/js_test.go b/tpl/internal/go_templates/htmltemplate/js_test.go index e15087f0..f7ee3cfa 100644 --- a/tpl/internal/go_templates/htmltemplate/js_test.go +++ b/tpl/internal/go_templates/htmltemplate/js_test.go @@ -206,7 +206,8 @@ func TestJSStrEscaper(t *testing.T) { {"", `--\u003e`}, // From https://code.google.com/p/doctype/wiki/ArticleUtf7 - {"+ADw-script+AD4-alert(1)+ADw-/script+AD4-", + { + "+ADw-script+AD4-alert(1)+ADw-/script+AD4-", `\u002bADw-script\u002bAD4-alert(1)\u002bADw-\/script\u002bAD4-`, }, // Invalid UTF-8 sequence diff --git a/tpl/internal/go_templates/htmltemplate/transition.go b/tpl/internal/go_templates/htmltemplate/transition.go index 06df6793..5ba7f801 100644 --- a/tpl/internal/go_templates/htmltemplate/transition.go +++ b/tpl/internal/go_templates/htmltemplate/transition.go @@ -41,8 +41,10 @@ var transitionFunc = [...]func(context, []byte) (context, int){ stateError: tError, } -var commentStart = []byte("") +var ( + commentStart = []byte("") +) // tText is the context transition function for the text state. func tText(c context, s []byte) (context, int) { diff --git a/tpl/internal/go_templates/htmltemplate/transition_test.go b/tpl/internal/go_templates/htmltemplate/transition_test.go index 00b0ff6c..c3257a83 100644 --- a/tpl/internal/go_templates/htmltemplate/transition_test.go +++ b/tpl/internal/go_templates/htmltemplate/transition_test.go @@ -42,7 +42,6 @@ func TestFindEndTag(t *testing.T) { } func BenchmarkTemplateSpecialTags(b *testing.B) { - r := struct { Name, Gift string }{"Aunt Mildred", "bone china tea set"} diff --git a/tpl/internal/go_templates/testenv/testenv.go b/tpl/internal/go_templates/testenv/testenv.go index 90044570..7c46089f 100644 --- a/tpl/internal/go_templates/testenv/testenv.go +++ b/tpl/internal/go_templates/testenv/testenv.go @@ -13,7 +13,6 @@ package testenv import ( "errors" "flag" - "github.com/gohugoio/hugo/tpl/internal/go_templates/cfg" "os" "os/exec" "path/filepath" @@ -22,6 +21,8 @@ import ( "strings" "sync" "testing" + + "github.com/gohugoio/hugo/tpl/internal/go_templates/cfg" ) // Builder reports the name of the builder running this test diff --git a/tpl/internal/go_templates/testenv/testenv_windows.go b/tpl/internal/go_templates/testenv/testenv_windows.go index eb8d6ac1..f9e7da5a 100644 --- a/tpl/internal/go_templates/testenv/testenv_windows.go +++ b/tpl/internal/go_templates/testenv/testenv_windows.go @@ -12,8 +12,10 @@ import ( "syscall" ) -var symlinkOnce sync.Once -var winSymlinkErr error +var ( + symlinkOnce sync.Once + winSymlinkErr error +) func initWinHasSymlink() { tmpdir, err := ioutil.TempDir("", "symtest") diff --git a/tpl/internal/go_templates/texttemplate/example_test.go b/tpl/internal/go_templates/texttemplate/example_test.go index f192cac4..09555c95 100644 --- a/tpl/internal/go_templates/texttemplate/example_test.go +++ b/tpl/internal/go_templates/texttemplate/example_test.go @@ -34,7 +34,7 @@ Josie Name, Gift string Attended bool } - var recipients = []Recipient{ + recipients := []Recipient{ {"Aunt Mildred", "bone china tea set", true}, {"Uncle John", "moleskin pants", false}, {"Cousin Rodney", "", false}, diff --git a/tpl/internal/go_templates/texttemplate/exec.go b/tpl/internal/go_templates/texttemplate/exec.go index 879cd088..db533d73 100644 --- a/tpl/internal/go_templates/texttemplate/exec.go +++ b/tpl/internal/go_templates/texttemplate/exec.go @@ -6,12 +6,13 @@ package template import ( "fmt" - "github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort" - "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" "io" "reflect" "runtime" "strings" + + "github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort" + "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" ) // maxExecDepth specifies the maximum stack depth of templates within diff --git a/tpl/internal/go_templates/texttemplate/exec_test.go b/tpl/internal/go_templates/texttemplate/exec_test.go index 940a1de6..cc79d214 100644 --- a/tpl/internal/go_templates/texttemplate/exec_test.go +++ b/tpl/internal/go_templates/texttemplate/exec_test.go @@ -318,12 +318,16 @@ var execTests = []execTest{ {"$.U.V", "{{$.U.V}}", "v", tVal, true}, {"declare in action", "{{$x := $.U.V}}{{$x}}", "v", tVal, true}, {"simple assignment", "{{$x := 2}}{{$x = 3}}{{$x}}", "3", tVal, true}, - {"nested assignment", + { + "nested assignment", "{{$x := 2}}{{if true}}{{$x = 3}}{{end}}{{$x}}", - "3", tVal, true}, - {"nested assignment changes the last declaration", + "3", tVal, true, + }, + { + "nested assignment changes the last declaration", "{{$x := 1}}{{if true}}{{$x := 2}}{{if true}}{{$x = 3}}{{end}}{{end}}{{$x}}", - "1", tVal, true}, + "1", tVal, true, + }, // Type with String method. {"V{6666}.String()", "-{{.V0}}-", "-<6666>-", tVal, true}, @@ -370,15 +374,21 @@ var execTests = []execTest{ {".Method3(nil constant)", "-{{.Method3 nil}}-", "-Method3: -", tVal, true}, {".Method3(nil value)", "-{{.Method3 .MXI.unset}}-", "-Method3: -", tVal, true}, {"method on var", "{{if $x := .}}-{{$x.Method2 .U16 $x.X}}{{end}}-", "-Method2: 16 x-", tVal, true}, - {"method on chained var", + { + "method on chained var", "{{range .MSIone}}{{if $.U.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}", - "true", tVal, true}, - {"chained method", + "true", tVal, true, + }, + { + "chained method", "{{range .MSIone}}{{if $.GetU.TrueFalse $.True}}{{$.U.TrueFalse $.True}}{{else}}WRONG{{end}}{{end}}", - "true", tVal, true}, - {"chained method on variable", + "true", tVal, true, + }, + { + "chained method on variable", "{{with $x := .}}{{with .SI}}{{$.GetU.TrueFalse $.True}}{{end}}{{end}}", - "true", tVal, true}, + "true", tVal, true, + }, {".NilOKFunc not nil", "{{call .NilOKFunc .PI}}", "false", tVal, true}, {".NilOKFunc nil", "{{call .NilOKFunc nil}}", "true", tVal, true}, {"method on nil value from slice", "-{{range .}}{{.Method1 1234}}{{end}}-", "-1234-", tSliceOfNil, true}, @@ -464,10 +474,14 @@ var execTests = []execTest{ {"printf lots", `{{printf "%d %s %g %s" 127 "hello" 7-3i .Method0}}`, "127 hello (7-3i) M0", tVal, true}, // HTML. - {"html", `{{html ""}}`, - "<script>alert("XSS");</script>", nil, true}, - {"html pipeline", `{{printf "" | html}}`, - "<script>alert("XSS");</script>", nil, true}, + { + "html", `{{html ""}}`, + "<script>alert("XSS");</script>", nil, true, + }, + { + "html pipeline", `{{printf "" | html}}`, + "<script>alert("XSS");</script>", nil, true, + }, {"html", `{{html .PS}}`, "a string", tVal, true}, {"html typed nil", `{{html .NIL}}`, "<nil>", tVal, true}, {"html untyped nil", `{{html .Empty0}}`, "<no value>", tVal, true}, @@ -825,7 +839,7 @@ var delimPairs = []string{ func TestDelims(t *testing.T) { const hello = "Hello, world" - var value = struct{ Str string }{hello} + value := struct{ Str string }{hello} for i := 0; i < len(delimPairs); i += 2 { text := ".Str" left := delimPairs[i+0] @@ -848,7 +862,7 @@ func TestDelims(t *testing.T) { if err != nil { t.Fatalf("delim %q text %q parse err %s", left, text, err) } - var b = new(bytes.Buffer) + b := new(bytes.Buffer) err = tmpl.Execute(b, value) if err != nil { t.Fatalf("delim %q exec err %s", left, err) @@ -949,7 +963,7 @@ const treeTemplate = ` ` func TestTree(t *testing.T) { - var tree = &Tree{ + tree := &Tree{ 1, &Tree{ 2, &Tree{ @@ -1195,7 +1209,7 @@ var cmpTests = []cmpTest{ func TestComparison(t *testing.T) { b := new(bytes.Buffer) - var cmpStruct = struct { + cmpStruct := struct { Uthree, Ufour uint NegOne, Three int Ptr, NilPtr *int diff --git a/tpl/internal/go_templates/texttemplate/hugo_template.go b/tpl/internal/go_templates/texttemplate/hugo_template.go index 7cd6df0f..0dc6331c 100644 --- a/tpl/internal/go_templates/texttemplate/hugo_template.go +++ b/tpl/internal/go_templates/texttemplate/hugo_template.go @@ -77,7 +77,6 @@ func (t *executer) Execute(p Preparer, wr io.Writer, data interface{}) error { } return tmpl.executeWithState(state, value) - } // Prepare returns a template ready for execution. diff --git a/tpl/internal/go_templates/texttemplate/hugo_template_test.go b/tpl/internal/go_templates/texttemplate/hugo_template_test.go index 98a2575e..90bb0931 100644 --- a/tpl/internal/go_templates/texttemplate/hugo_template_test.go +++ b/tpl/internal/go_templates/texttemplate/hugo_template_test.go @@ -85,5 +85,4 @@ Method: {{ .Hello1 "v1" }} c.Assert(got, qt.Contains, "hello hugo") c.Assert(got, qt.Contains, "Map: av") c.Assert(got, qt.Contains, "Method: v2 v1") - } diff --git a/tpl/internal/go_templates/texttemplate/multi_test.go b/tpl/internal/go_templates/texttemplate/multi_test.go index 7323be37..569a45db 100644 --- a/tpl/internal/go_templates/texttemplate/multi_test.go +++ b/tpl/internal/go_templates/texttemplate/multi_test.go @@ -11,8 +11,9 @@ package template import ( "bytes" "fmt" - "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" "testing" + + "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" ) const ( @@ -29,22 +30,32 @@ type multiParseTest struct { } var multiParseTests = []multiParseTest{ - {"empty", "", noError, + { + "empty", "", noError, nil, - nil}, - {"one", `{{define "foo"}} FOO {{end}}`, noError, + nil, + }, + { + "one", `{{define "foo"}} FOO {{end}}`, noError, []string{"foo"}, - []string{" FOO "}}, - {"two", `{{define "foo"}} FOO {{end}}{{define "bar"}} BAR {{end}}`, noError, + []string{" FOO "}, + }, + { + "two", `{{define "foo"}} FOO {{end}}{{define "bar"}} BAR {{end}}`, noError, []string{"foo", "bar"}, - []string{" FOO ", " BAR "}}, + []string{" FOO ", " BAR "}, + }, // errors - {"missing end", `{{define "foo"}} FOO `, hasError, + { + "missing end", `{{define "foo"}} FOO `, hasError, nil, - nil}, - {"malformed name", `{{define "foo}} FOO `, hasError, nil, - nil}, + }, + { + "malformed name", `{{define "foo}} FOO `, hasError, + nil, + nil, + }, } func TestMultiParse(t *testing.T) { @@ -400,7 +411,7 @@ func TestIssue19294(t *testing.T) { // by the contents of "stylesheet", but if the internal map associating // names with templates is built in the wrong order, the empty block // looks non-empty and this doesn't happen. - var inlined = map[string]string{ + inlined := map[string]string{ "stylesheet": `{{define "stylesheet"}}stylesheet{{end}}`, "xhtml": `{{block "stylesheet" .}}{{end}}`, } diff --git a/tpl/internal/go_templates/texttemplate/parse/node.go b/tpl/internal/go_templates/texttemplate/parse/node.go index 1c116ea6..dee67a2e 100644 --- a/tpl/internal/go_templates/texttemplate/parse/node.go +++ b/tpl/internal/go_templates/texttemplate/parse/node.go @@ -249,7 +249,6 @@ func (a *ActionNode) tree() *Tree { func (a *ActionNode) Copy() Node { return a.tr.newAction(a.Pos, a.Line, a.Pipe.CopyPipe()) - } // CommandNode holds a command (a pipeline inside an evaluating action). diff --git a/tpl/internal/go_templates/texttemplate/parse/parse.go b/tpl/internal/go_templates/texttemplate/parse/parse.go index c9b80f4a..7a58c578 100644 --- a/tpl/internal/go_templates/texttemplate/parse/parse.go +++ b/tpl/internal/go_templates/texttemplate/parse/parse.go @@ -453,7 +453,7 @@ func (t *Tree) parseControl(allowElseIf bool, context string) (pos Pos, line int var next Node list, next = t.itemList() switch next.Type() { - case nodeEnd: //done + case nodeEnd: // done case nodeElse: if allowElseIf { // Special case for "else if". If the "else" is followed immediately by an "if", diff --git a/tpl/internal/go_templates/texttemplate/parse/parse_test.go b/tpl/internal/go_templates/texttemplate/parse/parse_test.go index 79e7bb5a..97511190 100644 --- a/tpl/internal/go_templates/texttemplate/parse/parse_test.go +++ b/tpl/internal/go_templates/texttemplate/parse/parse_test.go @@ -178,70 +178,134 @@ const ( ) var parseTests = []parseTest{ - {"empty", "", noError, - ``}, - {"comment", "{{/*\n\n\n*/}}", noError, - ``}, - {"spaces", " \t\n", noError, - `" \t\n"`}, - {"text", "some text", noError, - `"some text"`}, - {"emptyAction", "{{}}", hasError, - `{{}}`}, - {"field", "{{.X}}", noError, - `{{.X}}`}, - {"simple command", "{{printf}}", noError, - `{{printf}}`}, - {"$ invocation", "{{$}}", noError, - "{{$}}"}, - {"variable invocation", "{{with $x := 3}}{{$x 23}}{{end}}", noError, - "{{with $x := 3}}{{$x 23}}{{end}}"}, - {"variable with fields", "{{$.I}}", noError, - "{{$.I}}"}, - {"multi-word command", "{{printf `%d` 23}}", noError, - "{{printf `%d` 23}}"}, - {"pipeline", "{{.X|.Y}}", noError, - `{{.X | .Y}}`}, - {"pipeline with decl", "{{$x := .X|.Y}}", noError, - `{{$x := .X | .Y}}`}, - {"nested pipeline", "{{.X (.Y .Z) (.A | .B .C) (.E)}}", noError, - `{{.X (.Y .Z) (.A | .B .C) (.E)}}`}, - {"field applied to parentheses", "{{(.Y .Z).Field}}", noError, - `{{(.Y .Z).Field}}`}, - {"simple if", "{{if .X}}hello{{end}}", noError, - `{{if .X}}"hello"{{end}}`}, - {"if with else", "{{if .X}}true{{else}}false{{end}}", noError, - `{{if .X}}"true"{{else}}"false"{{end}}`}, - {"if with else if", "{{if .X}}true{{else if .Y}}false{{end}}", noError, - `{{if .X}}"true"{{else}}{{if .Y}}"false"{{end}}{{end}}`}, - {"if else chain", "+{{if .X}}X{{else if .Y}}Y{{else if .Z}}Z{{end}}+", noError, - `"+"{{if .X}}"X"{{else}}{{if .Y}}"Y"{{else}}{{if .Z}}"Z"{{end}}{{end}}{{end}}"+"`}, - {"simple range", "{{range .X}}hello{{end}}", noError, - `{{range .X}}"hello"{{end}}`}, - {"chained field range", "{{range .X.Y.Z}}hello{{end}}", noError, - `{{range .X.Y.Z}}"hello"{{end}}`}, - {"nested range", "{{range .X}}hello{{range .Y}}goodbye{{end}}{{end}}", noError, - `{{range .X}}"hello"{{range .Y}}"goodbye"{{end}}{{end}}`}, - {"range with else", "{{range .X}}true{{else}}false{{end}}", noError, - `{{range .X}}"true"{{else}}"false"{{end}}`}, - {"range over pipeline", "{{range .X|.M}}true{{else}}false{{end}}", noError, - `{{range .X | .M}}"true"{{else}}"false"{{end}}`}, - {"range []int", "{{range .SI}}{{.}}{{end}}", noError, - `{{range .SI}}{{.}}{{end}}`}, - {"range 1 var", "{{range $x := .SI}}{{.}}{{end}}", noError, - `{{range $x := .SI}}{{.}}{{end}}`}, - {"range 2 vars", "{{range $x, $y := .SI}}{{.}}{{end}}", noError, - `{{range $x, $y := .SI}}{{.}}{{end}}`}, - {"constants", "{{range .SI 1 -3.2i true false 'a' nil}}{{end}}", noError, - `{{range .SI 1 -3.2i true false 'a' nil}}{{end}}`}, - {"template", "{{template `x`}}", noError, - `{{template "x"}}`}, - {"template with arg", "{{template `x` .Y}}", noError, - `{{template "x" .Y}}`}, - {"with", "{{with .X}}hello{{end}}", noError, - `{{with .X}}"hello"{{end}}`}, - {"with with else", "{{with .X}}hello{{else}}goodbye{{end}}", noError, - `{{with .X}}"hello"{{else}}"goodbye"{{end}}`}, + { + "empty", "", noError, + ``, + }, + { + "comment", "{{/*\n\n\n*/}}", noError, + ``, + }, + { + "spaces", " \t\n", noError, + `" \t\n"`, + }, + { + "text", "some text", noError, + `"some text"`, + }, + { + "emptyAction", "{{}}", hasError, + `{{}}`, + }, + { + "field", "{{.X}}", noError, + `{{.X}}`, + }, + { + "simple command", "{{printf}}", noError, + `{{printf}}`, + }, + { + "$ invocation", "{{$}}", noError, + "{{$}}", + }, + { + "variable invocation", "{{with $x := 3}}{{$x 23}}{{end}}", noError, + "{{with $x := 3}}{{$x 23}}{{end}}", + }, + { + "variable with fields", "{{$.I}}", noError, + "{{$.I}}", + }, + { + "multi-word command", "{{printf `%d` 23}}", noError, + "{{printf `%d` 23}}", + }, + { + "pipeline", "{{.X|.Y}}", noError, + `{{.X | .Y}}`, + }, + { + "pipeline with decl", "{{$x := .X|.Y}}", noError, + `{{$x := .X | .Y}}`, + }, + { + "nested pipeline", "{{.X (.Y .Z) (.A | .B .C) (.E)}}", noError, + `{{.X (.Y .Z) (.A | .B .C) (.E)}}`, + }, + { + "field applied to parentheses", "{{(.Y .Z).Field}}", noError, + `{{(.Y .Z).Field}}`, + }, + { + "simple if", "{{if .X}}hello{{end}}", noError, + `{{if .X}}"hello"{{end}}`, + }, + { + "if with else", "{{if .X}}true{{else}}false{{end}}", noError, + `{{if .X}}"true"{{else}}"false"{{end}}`, + }, + { + "if with else if", "{{if .X}}true{{else if .Y}}false{{end}}", noError, + `{{if .X}}"true"{{else}}{{if .Y}}"false"{{end}}{{end}}`, + }, + { + "if else chain", "+{{if .X}}X{{else if .Y}}Y{{else if .Z}}Z{{end}}+", noError, + `"+"{{if .X}}"X"{{else}}{{if .Y}}"Y"{{else}}{{if .Z}}"Z"{{end}}{{end}}{{end}}"+"`, + }, + { + "simple range", "{{range .X}}hello{{end}}", noError, + `{{range .X}}"hello"{{end}}`, + }, + { + "chained field range", "{{range .X.Y.Z}}hello{{end}}", noError, + `{{range .X.Y.Z}}"hello"{{end}}`, + }, + { + "nested range", "{{range .X}}hello{{range .Y}}goodbye{{end}}{{end}}", noError, + `{{range .X}}"hello"{{range .Y}}"goodbye"{{end}}{{end}}`, + }, + { + "range with else", "{{range .X}}true{{else}}false{{end}}", noError, + `{{range .X}}"true"{{else}}"false"{{end}}`, + }, + { + "range over pipeline", "{{range .X|.M}}true{{else}}false{{end}}", noError, + `{{range .X | .M}}"true"{{else}}"false"{{end}}`, + }, + { + "range []int", "{{range .SI}}{{.}}{{end}}", noError, + `{{range .SI}}{{.}}{{end}}`, + }, + { + "range 1 var", "{{range $x := .SI}}{{.}}{{end}}", noError, + `{{range $x := .SI}}{{.}}{{end}}`, + }, + { + "range 2 vars", "{{range $x, $y := .SI}}{{.}}{{end}}", noError, + `{{range $x, $y := .SI}}{{.}}{{end}}`, + }, + { + "constants", "{{range .SI 1 -3.2i true false 'a' nil}}{{end}}", noError, + `{{range .SI 1 -3.2i true false 'a' nil}}{{end}}`, + }, + { + "template", "{{template `x`}}", noError, + `{{template "x"}}`, + }, + { + "template with arg", "{{template `x` .Y}}", noError, + `{{template "x" .Y}}`, + }, + { + "with", "{{with .X}}hello{{end}}", noError, + `{{with .X}}"hello"{{end}}`, + }, + { + "with with else", "{{with .X}}hello{{else}}goodbye{{end}}", noError, + `{{with .X}}"hello"{{else}}"goodbye"{{end}}`, + }, // Trimming spaces. {"trim left", "x \r\n\t{{- 3}}", noError, `"x"{{3}}`}, {"trim right", "{{3 -}}\n\n\ty", noError, `{{3}}"y"`}, @@ -250,8 +314,10 @@ var parseTests = []parseTest{ {"comment trim left", "x \r\n\t{{- /* hi */}}", noError, `"x"`}, {"comment trim right", "{{/* hi */ -}}\n\n\ty", noError, `"y"`}, {"comment trim left and right", "x \r\n\t{{- /* */ -}}\n\n\ty", noError, `"x""y"`}, - {"block definition", `{{block "foo" .}}hello{{end}}`, noError, - `{{template "foo" .}}`}, + { + "block definition", `{{block "foo" .}}hello{{end}}`, noError, + `{{template "foo" .}}`, + }, // Errors. {"unclosed action", "hello{{range", hasError, ""}, {"unmatched end", "{{end}}", hasError, ""}, @@ -401,89 +467,143 @@ func TestErrorContextWithTreeCopy(t *testing.T) { // All failures, and the result is a string that must appear in the error message. var errorTests = []parseTest{ // Check line numbers are accurate. - {"unclosed1", + { + "unclosed1", "line1\n{{", - hasError, `unclosed1:2: unexpected unclosed action in command`}, - {"unclosed2", + hasError, `unclosed1:2: unexpected unclosed action in command`, + }, + { + "unclosed2", "line1\n{{define `x`}}line2\n{{", - hasError, `unclosed2:3: unexpected unclosed action in command`}, + hasError, `unclosed2:3: unexpected unclosed action in command`, + }, // Specific errors. - {"function", + { + "function", "{{foo}}", - hasError, `function "foo" not defined`}, - {"comment", + hasError, `function "foo" not defined`, + }, + { + "comment", "{{/*}}", - hasError, `unclosed comment`}, - {"lparen", + hasError, `unclosed comment`, + }, + { + "lparen", "{{.X (1 2 3}}", - hasError, `unclosed left paren`}, - {"rparen", + hasError, `unclosed left paren`, + }, + { + "rparen", "{{.X 1 2 3)}}", - hasError, `unexpected ")"`}, - {"space", + hasError, `unexpected ")"`, + }, + { + "space", "{{`x`3}}", - hasError, `in operand`}, - {"idchar", + hasError, `in operand`, + }, + { + "idchar", "{{a#}}", - hasError, `'#'`}, - {"charconst", + hasError, `'#'`, + }, + { + "charconst", "{{'a}}", - hasError, `unterminated character constant`}, - {"stringconst", + hasError, `unterminated character constant`, + }, + { + "stringconst", `{{"a}}`, - hasError, `unterminated quoted string`}, - {"rawstringconst", + hasError, `unterminated quoted string`, + }, + { + "rawstringconst", "{{`a}}", - hasError, `unterminated raw quoted string`}, - {"number", + hasError, `unterminated raw quoted string`, + }, + { + "number", "{{0xi}}", - hasError, `number syntax`}, - {"multidefine", + hasError, `number syntax`, + }, + { + "multidefine", "{{define `a`}}a{{end}}{{define `a`}}b{{end}}", - hasError, `multiple definition of template`}, - {"eof", + hasError, `multiple definition of template`, + }, + { + "eof", "{{range .X}}", - hasError, `unexpected EOF`}, - {"variable", + hasError, `unexpected EOF`, + }, + { + "variable", // Declare $x so it's defined, to avoid that error, and then check we don't parse a declaration. "{{$x := 23}}{{with $x.y := 3}}{{$x 23}}{{end}}", - hasError, `unexpected ":="`}, - {"multidecl", + hasError, `unexpected ":="`, + }, + { + "multidecl", "{{$a,$b,$c := 23}}", - hasError, `too many declarations`}, - {"undefvar", + hasError, `too many declarations`, + }, + { + "undefvar", "{{$a}}", - hasError, `undefined variable`}, - {"wrongdot", + hasError, `undefined variable`, + }, + { + "wrongdot", "{{true.any}}", - hasError, `unexpected . after term`}, - {"wrongpipeline", + hasError, `unexpected . after term`, + }, + { + "wrongpipeline", "{{12|false}}", - hasError, `non executable command in pipeline`}, - {"emptypipeline", + hasError, `non executable command in pipeline`, + }, + { + "emptypipeline", `{{ ( ) }}`, - hasError, `missing value for parenthesized pipeline`}, - {"multilinerawstring", + hasError, `missing value for parenthesized pipeline`, + }, + { + "multilinerawstring", "{{ $v := `\n` }} {{", - hasError, `multilinerawstring:2: unexpected unclosed action`}, - {"rangeundefvar", + hasError, `multilinerawstring:2: unexpected unclosed action`, + }, + { + "rangeundefvar", "{{range $k}}{{end}}", - hasError, `undefined variable`}, - {"rangeundefvars", + hasError, `undefined variable`, + }, + { + "rangeundefvars", "{{range $k, $v}}{{end}}", - hasError, `undefined variable`}, - {"rangemissingvalue1", + hasError, `undefined variable`, + }, + { + "rangemissingvalue1", "{{range $k,}}{{end}}", - hasError, `missing value for range`}, - {"rangemissingvalue2", + hasError, `missing value for range`, + }, + { + "rangemissingvalue2", "{{range $k, $v := }}{{end}}", - hasError, `missing value for range`}, - {"rangenotvariable1", + hasError, `missing value for range`, + }, + { + "rangenotvariable1", "{{range $k, .}}{{end}}", - hasError, `range can only initialize variables`}, - {"rangenotvariable2", + hasError, `range can only initialize variables`, + }, + { + "rangenotvariable2", "{{range $k, 123 := .}}{{end}}", - hasError, `range can only initialize variables`}, + hasError, `range can only initialize variables`, + }, } func TestErrors(t *testing.T) { diff --git a/tpl/internal/go_templates/texttemplate/template.go b/tpl/internal/go_templates/texttemplate/template.go index 9c6ba6df..755a8426 100644 --- a/tpl/internal/go_templates/texttemplate/template.go +++ b/tpl/internal/go_templates/texttemplate/template.go @@ -5,9 +5,10 @@ package template import ( - "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" "reflect" "sync" + + "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse" ) // common holds the information shared by related templates. diff --git a/tpl/internal/templatefuncsRegistry.go b/tpl/internal/templatefuncsRegistry.go index 99877dcc..6d58d8d2 100644 --- a/tpl/internal/templatefuncsRegistry.go +++ b/tpl/internal/templatefuncsRegistry.go @@ -83,7 +83,6 @@ func (t *TemplateFuncsNamespace) AddMethodMapping(m interface{}, aliases []strin Aliases: aliases, Examples: examples, } - } // TemplateFuncMethodMapping represents a mapping of functions to methods for a @@ -165,7 +164,6 @@ func (namespaces TemplateFuncsNamespaces) MarshalJSON() ([]byte, error) { } func (t *TemplateFuncsNamespace) toJSON() ([]byte, error) { - var buf bytes.Buffer godoc := getGetTplPackagesGoDoc()[t.Name] diff --git a/tpl/js/js.go b/tpl/js/js.go index b7a2fe06..d5d435be 100644 --- a/tpl/js/js.go +++ b/tpl/js/js.go @@ -62,5 +62,4 @@ func (ns *Namespace) Build(args ...interface{}) (resource.Resource, error) { } return ns.client.Process(r, m) - } diff --git a/tpl/lang/init.go b/tpl/lang/init.go index 6a23cdc4..520eccb8 100644 --- a/tpl/lang/init.go +++ b/tpl/lang/init.go @@ -45,7 +45,6 @@ func init() { }, ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/math/init.go b/tpl/math/init.go index e7f9114b..ddbd2fc7 100644 --- a/tpl/math/init.go +++ b/tpl/math/init.go @@ -114,7 +114,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/math/math.go b/tpl/math/math.go index ecaf61eb..2b2497c3 100644 --- a/tpl/math/math.go +++ b/tpl/math/math.go @@ -64,7 +64,6 @@ func (ns *Namespace) Floor(x interface{}) (float64, error) { // Log returns the natural logarithm of a number. func (ns *Namespace) Log(a interface{}) (float64, error) { af, err := cast.ToFloat64E(a) - if err != nil { return 0, errors.New("Log operator can't be used with non integer or float value") } @@ -76,7 +75,6 @@ func (ns *Namespace) Log(a interface{}) (float64, error) { // NOTE: will return for NaN for negative values of a func (ns *Namespace) Sqrt(a interface{}) (float64, error) { af, err := cast.ToFloat64E(a) - if err != nil { return 0, errors.New("Sqrt operator can't be used with non integer or float value") } diff --git a/tpl/math/math_test.go b/tpl/math/math_test.go index c48f7183..da59d793 100644 --- a/tpl/math/math_test.go +++ b/tpl/math/math_test.go @@ -197,7 +197,6 @@ func TestSqrt(t *testing.T) { result, err := ns.Sqrt(-1) c.Assert(err, qt.IsNil) c.Assert(result, qt.Satisfies, math.IsNaN) - } func TestMod(t *testing.T) { diff --git a/tpl/openapi/openapi3/init.go b/tpl/openapi/openapi3/init.go index 1e1a4ae0..4b4396ff 100644 --- a/tpl/openapi/openapi3/init.go +++ b/tpl/openapi/openapi3/init.go @@ -35,7 +35,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/openapi/openapi3/openapi3.go b/tpl/openapi/openapi3/openapi3.go index 7dfd2f6a..cc88f412 100644 --- a/tpl/openapi/openapi3/openapi3.go +++ b/tpl/openapi/openapi3/openapi3.go @@ -49,7 +49,6 @@ type Namespace struct { } func (ns *Namespace) Unmarshal(r resource.UnmarshableResource) (*kopenapi3.Swagger, error) { - key := r.Key() if key == "" { return nil, errors.New("no Key set in Resource") @@ -87,11 +86,9 @@ func (ns *Namespace) Unmarshal(r resource.UnmarshableResource) (*kopenapi3.Swagg return s, err }) - if err != nil { return nil, err } return v.(*kopenapi3.Swagger), nil - } diff --git a/tpl/os/init.go b/tpl/os/init.go index 3ef8702d..9d9b7547 100644 --- a/tpl/os/init.go +++ b/tpl/os/init.go @@ -56,7 +56,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/os/os.go b/tpl/os/os.go index eb31498a..21470659 100644 --- a/tpl/os/os.go +++ b/tpl/os/os.go @@ -28,7 +28,6 @@ import ( // New returns a new instance of the os-namespaced template functions. func New(d *deps.Deps) *Namespace { - var rfs afero.Fs if d.Fs != nil { rfs = d.Fs.WorkingDir @@ -80,7 +79,6 @@ func readFile(fs afero.Fs, filename string) (string, error) { return "", err } b, err := afero.ReadFile(fs, filename) - if err != nil { return "", err } diff --git a/tpl/partials/init.go b/tpl/partials/init.go index c2135bca..4666fa33 100644 --- a/tpl/partials/init.go +++ b/tpl/partials/init.go @@ -49,7 +49,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/partials/partials.go b/tpl/partials/partials.go index 8b545399..016e0423 100644 --- a/tpl/partials/partials.go +++ b/tpl/partials/partials.go @@ -159,7 +159,6 @@ func (ns *Namespace) Include(name string, contextList ...interface{}) (interface } return result, nil - } // IncludeCached executes and caches partial templates. The cache is created with name+variants as the key. diff --git a/tpl/partials/partials_test.go b/tpl/partials/partials_test.go index 60e9dd72..656ab2d5 100644 --- a/tpl/partials/partials_test.go +++ b/tpl/partials/partials_test.go @@ -37,5 +37,4 @@ func TestCreateKey(t *testing.T) { c.Assert(create("a", map[string]string{"a": "av"}), qt.Equals, partialCacheKey{name: "a", variant: "4809626101226749924"}) c.Assert(create("a", []string{"a", "b"}), qt.Equals, partialCacheKey{name: "a", variant: "2712570657419664240"}) } - } diff --git a/tpl/path/init.go b/tpl/path/init.go index 518dcad2..a7f65073 100644 --- a/tpl/path/init.go +++ b/tpl/path/init.go @@ -55,7 +55,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) } diff --git a/tpl/resources/init.go b/tpl/resources/init.go index df83cb3b..d0e20d0a 100644 --- a/tpl/resources/init.go +++ b/tpl/resources/init.go @@ -66,7 +66,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/resources/resources.go b/tpl/resources/resources.go index cdde6bd5..73f3743b 100644 --- a/tpl/resources/resources.go +++ b/tpl/resources/resources.go @@ -93,7 +93,6 @@ func (ns *Namespace) Get(filename interface{}) (resource.Resource, error) { filenamestr = filepath.Clean(filenamestr) return ns.createClient.Get(filenamestr) - } // GetMatch finds the first Resource matching the given pattern, or nil if none found. @@ -108,7 +107,6 @@ func (ns *Namespace) GetMatch(pattern interface{}) (resource.Resource, error) { } return ns.createClient.GetMatch(patternStr) - } // Match gets all resources matching the given base path prefix, e.g @@ -281,7 +279,6 @@ func (ns *Namespace) PostCSS(args ...interface{}) (resource.Resource, error) { func (ns *Namespace) PostProcess(r resource.Resource) (postpub.PostPublishedResource, error) { return ns.deps.ResourceSpec.PostProcess(r) - } // Babel processes the given Resource with Babel. @@ -300,5 +297,4 @@ func (ns *Namespace) Babel(args ...interface{}) (resource.Resource, error) { } return ns.babelClient.Process(r, options) - } diff --git a/tpl/safe/init.go b/tpl/safe/init.go index edb16ed8..becaf38f 100644 --- a/tpl/safe/init.go +++ b/tpl/safe/init.go @@ -74,7 +74,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/safe/safe_test.go b/tpl/safe/safe_test.go index d5288fef..e9160576 100644 --- a/tpl/safe/safe_test.go +++ b/tpl/safe/safe_test.go @@ -15,7 +15,6 @@ package safe import ( "html/template" - "testing" qt "github.com/frankban/quicktest" diff --git a/tpl/site/init.go b/tpl/site/init.go index 48713bb3..4dc93499 100644 --- a/tpl/site/init.go +++ b/tpl/site/init.go @@ -24,7 +24,6 @@ const name = "site" func init() { f := func(d *deps.Deps) *internal.TemplateFuncsNamespace { - s := d.Site ns := &internal.TemplateFuncsNamespace{ Name: name, @@ -38,7 +37,6 @@ func init() { // We just add the Site as the namespace here. No method mappings. return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/strings/truncate.go b/tpl/strings/truncate.go index ff863db7..6e3a50ed 100644 --- a/tpl/strings/truncate.go +++ b/tpl/strings/truncate.go @@ -17,7 +17,6 @@ import ( "errors" "html" "html/template" - "regexp" "unicode" "unicode/utf8" diff --git a/tpl/strings/truncate_test.go b/tpl/strings/truncate_test.go index b4aa1ffa..51743e93 100644 --- a/tpl/strings/truncate_test.go +++ b/tpl/strings/truncate_test.go @@ -15,7 +15,6 @@ package strings import ( "html/template" - "reflect" "strings" "testing" @@ -81,5 +80,4 @@ func TestTruncate(t *testing.T) { if err == nil { t.Errorf("Should have errored") } - } diff --git a/tpl/template.go b/tpl/template.go index 82d87754..73db9b3a 100644 --- a/tpl/template.go +++ b/tpl/template.go @@ -14,9 +14,8 @@ package tpl import ( - "reflect" - "io" + "reflect" "regexp" "github.com/gohugoio/hugo/output" diff --git a/tpl/templates/init.go b/tpl/templates/init.go index 8bc53ef4..4ae5c12c 100644 --- a/tpl/templates/init.go +++ b/tpl/templates/init.go @@ -31,13 +31,13 @@ func init() { ns.AddMethodMapping(ctx.Exists, nil, - [][2]string{{`{{ if (templates.Exists "partials/header.html") }}Yes!{{ end }}`, `Yes!`}, + [][2]string{ + {`{{ if (templates.Exists "partials/header.html") }}Yes!{{ end }}`, `Yes!`}, {`{{ if not (templates.Exists "partials/doesnotexist.html") }}No!{{ end }}`, `No!`}, }, ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/templates/templates.go b/tpl/templates/templates.go index 80eb2d37..e0053733 100644 --- a/tpl/templates/templates.go +++ b/tpl/templates/templates.go @@ -36,5 +36,4 @@ type Namespace struct { func (ns *Namespace) Exists(name string) bool { _, found := ns.deps.Tmpl().Lookup(name) return found - } diff --git a/tpl/time/init.go b/tpl/time/init.go index 7abb3663..23e5263b 100644 --- a/tpl/time/init.go +++ b/tpl/time/init.go @@ -91,7 +91,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/tplimpl/embedded/generate/generate.go b/tpl/tplimpl/embedded/generate/generate.go index df4de479..3f7cc025 100644 --- a/tpl/tplimpl/embedded/generate/generate.go +++ b/tpl/tplimpl/embedded/generate/generate.go @@ -25,7 +25,6 @@ import ( ) func main() { - templateFolder := filepath.Join("..", "templates") temlatePath := filepath.Join(".", templateFolder) @@ -92,7 +91,6 @@ var EmbeddedTemplates = [][2]string{ fmt.Fprint(file, " ", v, ",\n") } fmt.Fprint(file, "}\n") - } func nameValue(name, value string) string { diff --git a/tpl/tplimpl/shortcodes.go b/tpl/tplimpl/shortcodes.go index cc4d9949..789bc07d 100644 --- a/tpl/tplimpl/shortcodes.go +++ b/tpl/tplimpl/shortcodes.go @@ -80,7 +80,6 @@ func (s *shortcodeTemplates) fromVariantsSlice(variants []string) (shortcodeVari // calculate a weight for two string slices of same length. // higher value means "better match". func (s *shortcodeTemplates) compareVariants(a, b []string) int { - weight := 0 k := len(a) for i, av := range a { @@ -101,7 +100,6 @@ func templateVariants(name string) []string { } func templateNameAndVariants(name string) (string, []string) { - variants := make([]string, numTemplateVariants) parts := strings.Split(name, ".") diff --git a/tpl/tplimpl/shortcodes_test.go b/tpl/tplimpl/shortcodes_test.go index 4ef8c5cd..f97c7f27 100644 --- a/tpl/tplimpl/shortcodes_test.go +++ b/tpl/tplimpl/shortcodes_test.go @@ -20,14 +20,12 @@ import ( ) func TestShortcodesTemplate(t *testing.T) { - t.Run("isShortcode", func(t *testing.T) { c := qt.New(t) c.Assert(isShortcode("shortcodes/figures.html"), qt.Equals, true) c.Assert(isShortcode("_internal/shortcodes/figures.html"), qt.Equals, true) c.Assert(isShortcode("shortcodes\\figures.html"), qt.Equals, false) c.Assert(isShortcode("myshortcodes"), qt.Equals, false) - }) t.Run("variantsFromName", func(t *testing.T) { @@ -40,7 +38,6 @@ func TestShortcodesTemplate(t *testing.T) { name, variants := templateNameAndVariants("figure.html") c.Assert(name, qt.Equals, "figure") c.Assert(variants, qt.DeepEquals, []string{"", "html", "html"}) - }) t.Run("compareVariants", func(t *testing.T) { @@ -65,7 +62,6 @@ func TestShortcodesTemplate(t *testing.T) { w := s.compareVariants(templateVariants(test.name1), templateVariants(test.name2)) c.Assert(w, qt.Equals, test.expected) } - }) t.Run("indexOf", func(t *testing.T) { @@ -81,7 +77,6 @@ func TestShortcodesTemplate(t *testing.T) { c.Assert(s.indexOf([]string{"a", "b", "c"}), qt.Equals, 0) c.Assert(s.indexOf([]string{"a", "b", "d"}), qt.Equals, 1) c.Assert(s.indexOf([]string{"a", "b", "x"}), qt.Equals, -1) - }) t.Run("Name", func(t *testing.T) { @@ -92,6 +87,5 @@ func TestShortcodesTemplate(t *testing.T) { c.Assert(templateBaseName(templateShortcode, "shortcodes/test/foo.html"), qt.Equals, "test/foo.html") c.Assert(true, qt.Equals, true) - }) } diff --git a/tpl/tplimpl/template.go b/tpl/tplimpl/template.go index e3a4ce09..eb91ab83 100644 --- a/tpl/tplimpl/template.go +++ b/tpl/tplimpl/template.go @@ -167,7 +167,6 @@ func newTemplateExec(d *deps.Deps) (*templateExec, error) { if d.WithTemplate != nil { if err := d.WithTemplate(e); err != nil { return nil, err - } } @@ -246,7 +245,6 @@ func (t *templateExec) MarkReady() error { }) return err - } type templateHandler struct { @@ -345,7 +343,6 @@ func (t *templateHandler) LookupVariant(name string, variants tpl.TemplateVarian more := len(s.variants) > 1 return sv.ts, true, more - } // LookupVariants returns all variants of name, nil if none found. @@ -362,11 +359,9 @@ func (t *templateHandler) LookupVariants(name string) []tpl.Template { } return variants - } func (t *templateHandler) HasTemplate(name string) bool { - if _, found := t.baseof[name]; found { return true } @@ -501,7 +496,6 @@ func (t *templateHandler) addFileContext(templ tpl.Template, inerr error) error err, _ := checkFilename(ts.baseInfo, inerr) return err - } func (t *templateHandler) addShortcodeVariant(ts *templateState) { @@ -584,7 +578,6 @@ func (t *templateHandler) addTemplateFile(name, path string) error { t.applyTemplateTransformers(t.main, templ) return nil - } func (t *templateHandler) addTemplateTo(info templateInfo, to *templateNamespace) (*templateState, error) { @@ -716,7 +709,6 @@ func (t *templateHandler) loadTemplates() error { } return nil - } func (t *templateHandler) nameIsText(name string) (string, bool) { @@ -763,7 +755,6 @@ func (t *templateHandler) extractPartials(templ tpl.Template) error { } return nil - } func (t *templateHandler) postTransform() error { @@ -874,7 +865,6 @@ func (t *templateNamespace) newTemplateLookup(in *templateState) func(name strin return newTemplateState(templ, templateInfo{name: templ.Name()}) } return nil - } } @@ -933,7 +923,6 @@ func (t *templateState) isText() bool { func isText(templ tpl.Template) bool { _, isText := templ.(*texttemplate.Template) return isText - } type templateStateMap struct { @@ -1003,7 +992,6 @@ func removeLeadingBOM(s string) string { } return s - } // resolves _internal/shortcodes/param.html => param.html etc. @@ -1015,7 +1003,6 @@ func templateBaseName(typ templateType, name string) string { default: panic("not implemented") } - } func unwrap(templ tpl.Template) tpl.Template { @@ -1041,5 +1028,4 @@ func templates(in tpl.Template) []tpl.Template { } return templs - } diff --git a/tpl/tplimpl/template_ast_transformers.go b/tpl/tplimpl/template_ast_transformers.go index 015cf72a..de9b5424 100644 --- a/tpl/tplimpl/template_ast_transformers.go +++ b/tpl/tplimpl/template_ast_transformers.go @@ -73,7 +73,6 @@ func (c templateContext) getIfNotVisited(name string) *templateState { func newTemplateContext( t *templateState, lookupFn func(name string) *templateState) *templateContext { - return &templateContext{ t: t, lookupFn: lookupFn, @@ -86,7 +85,6 @@ func newTemplateContext( func applyTemplateTransformers( t *templateState, lookupFn func(name string) *templateState) (*templateContext, error) { - if t == nil { return nil, errors.New("expected template, but none provided") } @@ -117,9 +115,7 @@ const ( partialReturnWrapperTempl = `{{ $_hugo_dot := $ }}{{ $ := .Arg }}{{ with .Arg }}{{ $_hugo_dot.Set ("PLACEHOLDER") }}{{ end }}` ) -var ( - partialReturnWrapper *parse.ListNode -) +var partialReturnWrapper *parse.ListNode func init() { templ, err := texttemplate.New("").Parse(partialReturnWrapperTempl) @@ -127,7 +123,6 @@ func init() { panic(err) } partialReturnWrapper = templ.Tree.Root - } func (c *templateContext) wrapInPartialReturnWrapper(n *parse.ListNode) *parse.ListNode { @@ -142,7 +137,6 @@ func (c *templateContext) wrapInPartialReturnWrapper(n *parse.ListNode) *parse.L withNode.List.Nodes = append(n.Nodes, retn) return wrapper - } // applyTransformations do 2 things: @@ -275,7 +269,6 @@ func (c *templateContext) collectInner(n *parse.CommandNode) { break } } - } var partialRe = regexp.MustCompile(`^partial(Cached)?$|^partials\.Include(Cached)?$`) @@ -330,7 +323,6 @@ func (c *templateContext) collectReturnNode(n *parse.CommandNode) bool { c.returnNode.Args = c.returnNode.Args[1:] return false - } func findTemplateIn(name string, in tpl.Template) (tpl.Template, bool) { @@ -345,5 +337,4 @@ func findTemplateIn(name string, in tpl.Template) (tpl.Template, bool) { return templ, true } return nil, false - } diff --git a/tpl/tplimpl/template_ast_transformers_test.go b/tpl/tplimpl/template_ast_transformers_test.go index b3844623..56d970b2 100644 --- a/tpl/tplimpl/template_ast_transformers_test.go +++ b/tpl/tplimpl/template_ast_transformers_test.go @@ -44,7 +44,6 @@ func TestTransformRecursiveTemplate(t *testing.T) { newTestTemplateLookup(ts), ) ctx.applyTransformations(templ.Tree.Root) - } func newTestTemplate(templ tpl.Template) *templateState { @@ -78,7 +77,6 @@ func newTestTemplateLookup(in *templateState) func(name string) *templateState { } func TestCollectInfo(t *testing.T) { - configStr := `{ "version": 42 }` tests := []struct { @@ -114,11 +112,9 @@ func TestCollectInfo(t *testing.T) { c.Assert(ctx.t.parseInfo, qt.DeepEquals, test.expected) }) } - } func TestPartialReturn(t *testing.T) { - tests := []struct { name string tplString string @@ -159,8 +155,6 @@ func TestPartialReturn(t *testing.T) { // Just check that it doesn't fail in this test. We have functional tests // in hugoblib. c.Assert(err, qt.IsNil) - }) } - } diff --git a/tpl/tplimpl/template_funcs.go b/tpl/tplimpl/template_funcs.go index 25ace365..4b3abaad 100644 --- a/tpl/tplimpl/template_funcs.go +++ b/tpl/tplimpl/template_funcs.go @@ -60,8 +60,10 @@ import ( _ "github.com/gohugoio/hugo/tpl/urls" ) -var _ texttemplate.ExecHelper = (*templateExecHelper)(nil) -var zero reflect.Value +var ( + _ texttemplate.ExecHelper = (*templateExecHelper)(nil) + zero reflect.Value +) type templateExecHelper struct { running bool // whether we're in server mode. @@ -145,7 +147,6 @@ func newTemplateExecuter(d *deps.Deps) (texttemplate.Executer, map[string]reflec } func createFuncMap(d *deps.Deps) map[string]interface{} { - funcMap := template.FuncMap{} // Merge the namespace funcs @@ -172,5 +173,4 @@ func createFuncMap(d *deps.Deps) map[string]interface{} { } return funcMap - } diff --git a/tpl/tplimpl/template_funcs_test.go b/tpl/tplimpl/template_funcs_test.go index 852b6393..c142dd67 100644 --- a/tpl/tplimpl/template_funcs_test.go +++ b/tpl/tplimpl/template_funcs_test.go @@ -40,9 +40,7 @@ import ( "github.com/spf13/viper" ) -var ( - logger = loggers.NewErrorLogger() -) +var logger = loggers.NewErrorLogger() func newTestConfig() config.Provider { v := viper.New() @@ -188,7 +186,6 @@ func TestPartialCached(t *testing.T) { t.Fatalf("cache mismatch") } } - } func BenchmarkPartial(b *testing.B) { diff --git a/tpl/tplimpl/template_info_test.go b/tpl/tplimpl/template_info_test.go index 1324b458..db74c29a 100644 --- a/tpl/tplimpl/template_info_test.go +++ b/tpl/tplimpl/template_info_test.go @@ -38,7 +38,6 @@ func TestTemplateInfoShortcode(t *testing.T) { tti, ok := tt.(tpl.Info) c.Assert(ok, qt.Equals, true) c.Assert(tti.ParseInfo().IsInner, qt.Equals, true) - } // TODO(bep) move and use in other places @@ -55,5 +54,4 @@ func newD(c *qt.C) *deps.Deps { provider.Update(d) return d - } diff --git a/tpl/transform/init.go b/tpl/transform/init.go index 62cb0a9c..9e57c07f 100644 --- a/tpl/transform/init.go +++ b/tpl/transform/init.go @@ -46,13 +46,16 @@ func init() { [][2]string{ { `{{ htmlEscape "Cathal Garvey & The Sunshine Band " | safeHTML}}`, - `Cathal Garvey & The Sunshine Band <cathal@foo.bar>`}, + `Cathal Garvey & The Sunshine Band <cathal@foo.bar>`, + }, { `{{ htmlEscape "Cathal Garvey & The Sunshine Band "}}`, - `Cathal Garvey &amp; The Sunshine Band &lt;cathal@foo.bar&gt;`}, + `Cathal Garvey &amp; The Sunshine Band &lt;cathal@foo.bar&gt;`, + }, { `{{ htmlEscape "Cathal Garvey & The Sunshine Band " | htmlUnescape | safeHTML }}`, - `Cathal Garvey & The Sunshine Band `}, + `Cathal Garvey & The Sunshine Band `, + }, }, ) @@ -61,16 +64,20 @@ func init() { [][2]string{ { `{{ htmlUnescape "Cathal Garvey & The Sunshine Band <cathal@foo.bar>" | safeHTML}}`, - `Cathal Garvey & The Sunshine Band `}, + `Cathal Garvey & The Sunshine Band `, + }, { `{{"Cathal Garvey &amp; The Sunshine Band &lt;cathal@foo.bar&gt;" | htmlUnescape | htmlUnescape | safeHTML}}`, - `Cathal Garvey & The Sunshine Band `}, + `Cathal Garvey & The Sunshine Band `, + }, { `{{"Cathal Garvey &amp; The Sunshine Band &lt;cathal@foo.bar&gt;" | htmlUnescape | htmlUnescape }}`, - `Cathal Garvey & The Sunshine Band <cathal@foo.bar>`}, + `Cathal Garvey & The Sunshine Band <cathal@foo.bar>`, + }, { `{{ htmlUnescape "Cathal Garvey & The Sunshine Band <cathal@foo.bar>" | htmlEscape | safeHTML }}`, - `Cathal Garvey & The Sunshine Band <cathal@foo.bar>`}, + `Cathal Garvey & The Sunshine Band <cathal@foo.bar>`, + }, }, ) @@ -104,7 +111,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/transform/remarshal_test.go b/tpl/transform/remarshal_test.go index daf99fdb..eb5f4253 100644 --- a/tpl/transform/remarshal_test.go +++ b/tpl/transform/remarshal_test.go @@ -107,7 +107,6 @@ title: Test Metadata } } - } func TestRemarshalComments(t *testing.T) { @@ -168,7 +167,6 @@ func TestTestRemarshalError(t *testing.T) { _, err = ns.Remarshal("json", "asdf") c.Assert(err, qt.Not(qt.IsNil)) - } func TestTestRemarshalMapInput(t *testing.T) { diff --git a/tpl/transform/transform.go b/tpl/transform/transform.go index b168d2a5..82756ed9 100644 --- a/tpl/transform/transform.go +++ b/tpl/transform/transform.go @@ -98,7 +98,6 @@ func (ns *Namespace) Markdownify(s interface{}) (template.HTML, error) { } b, err := ns.deps.ContentSpec.RenderMarkdown([]byte(ss)) - if err != nil { return "", err } diff --git a/tpl/transform/transform_test.go b/tpl/transform/transform_test.go index b3f4206f..b98d82d2 100644 --- a/tpl/transform/transform_test.go +++ b/tpl/transform/transform_test.go @@ -15,7 +15,6 @@ package transform import ( "html/template" - "testing" "github.com/gohugoio/hugo/common/loggers" @@ -206,7 +205,6 @@ And then some. c.Assert(err, qt.IsNil) c.Assert(result, qt.Equals, template.HTML( "

#First

\n

This is some bold text.

\n

Second

\n

This is some more text.

\n

And then some.

\n")) - } func TestPlainify(t *testing.T) { diff --git a/tpl/transform/unmarshal.go b/tpl/transform/unmarshal.go index b606c870..aa84ca1f 100644 --- a/tpl/transform/unmarshal.go +++ b/tpl/transform/unmarshal.go @@ -39,7 +39,7 @@ func (ns *Namespace) Unmarshal(args ...interface{}) (interface{}, error) { } var data interface{} - var decoder = metadecoders.Default + decoder := metadecoders.Default if len(args) == 1 { data = args[0] diff --git a/tpl/transform/unmarshal_test.go b/tpl/transform/unmarshal_test.go index 183bdefd..ec81c316 100644 --- a/tpl/transform/unmarshal_test.go +++ b/tpl/transform/unmarshal_test.go @@ -79,7 +79,6 @@ func (t testContentResource) Key() string { } func TestUnmarshal(t *testing.T) { - v := viper.New() ns := New(newDeps(v)) c := qt.New(t) @@ -120,21 +119,17 @@ func TestUnmarshal(t *testing.T) { }}, {testContentResource{key: "r1", content: `a;b;c`, mime: media.CSVType}, map[string]interface{}{"delimiter": ";"}, func(r [][]string) { c.Assert([][]string{{"a", "b", "c"}}, qt.DeepEquals, r) - }}, {"a,b,c", nil, func(r [][]string) { c.Assert([][]string{{"a", "b", "c"}}, qt.DeepEquals, r) - }}, {"a;b;c", map[string]interface{}{"delimiter": ";"}, func(r [][]string) { c.Assert([][]string{{"a", "b", "c"}}, qt.DeepEquals, r) - }}, {testContentResource{key: "r1", content: ` % This is a comment a;b;c`, mime: media.CSVType}, map[string]interface{}{"DElimiter": ";", "Comment": "%"}, func(r [][]string) { c.Assert([][]string{{"a", "b", "c"}}, qt.DeepEquals, r) - }}, // errors {"thisisnotavaliddataformat", nil, false}, diff --git a/tpl/urls/init.go b/tpl/urls/init.go index debaaabf..0abe0d12 100644 --- a/tpl/urls/init.go +++ b/tpl/urls/init.go @@ -67,7 +67,6 @@ func init() { ) return ns - } internal.AddTemplateFuncsNamespace(f) diff --git a/tpl/urls/urls.go b/tpl/urls/urls.go index ee0e5550..652256f4 100644 --- a/tpl/urls/urls.go +++ b/tpl/urls/urls.go @@ -17,9 +17,7 @@ package urls import ( "errors" "fmt" - "html/template" - "net/url" "github.com/gohugoio/hugo/common/urls" diff --git a/transform/livereloadinject/livereloadinject.go b/transform/livereloadinject/livereloadinject.go index cc80d046..32ed55f6 100644 --- a/transform/livereloadinject/livereloadinject.go +++ b/transform/livereloadinject/livereloadinject.go @@ -30,19 +30,18 @@ type tag struct { } var tags = []tag{ - tag{markup: []byte(""), appendScript: true}, - tag{markup: []byte(""), appendScript: true}, - tag{markup: []byte("")}, - tag{markup: []byte("")}, + {markup: []byte(""), appendScript: true}, + {markup: []byte(""), appendScript: true}, + {markup: []byte("")}, + {markup: []byte("")}, } // New creates a function that can be used // to inject a script tag for the livereload JavaScript in a HTML document. func New(baseURL url.URL) transform.Transformer { - return func(ft transform.FromTo) error { b := ft.From().Bytes() - var idx = -1 + idx := -1 var match tag // We used to insert the livereload script right before the closing body. // This does not work when combined with tools such as Turbolinks. diff --git a/transform/livereloadinject/livereloadinject_test.go b/transform/livereloadinject/livereloadinject_test.go index 50fbb8b9..b2ec4483 100644 --- a/transform/livereloadinject/livereloadinject_test.go +++ b/transform/livereloadinject/livereloadinject_test.go @@ -61,5 +61,4 @@ func TestLiveReloadInject(t *testing.T) { c.Run("No match", func(c *qt.C) { c.Assert(apply("

No match

"), qt.Equals, "

No match

") }) - } diff --git a/transform/metainject/hugogenerator.go b/transform/metainject/hugogenerator.go index 5f3a8f63..20f05145 100644 --- a/transform/metainject/hugogenerator.go +++ b/transform/metainject/hugogenerator.go @@ -23,8 +23,10 @@ import ( "github.com/gohugoio/hugo/transform" ) -var metaTagsCheck = regexp.MustCompile(`(?i)`, hugo.CurrentVersion) +var ( + metaTagsCheck = regexp.MustCompile(`(?i)`, hugo.CurrentVersion) +) // HugoGenerator injects a meta generator tag for Hugo if none present. func HugoGenerator(ft transform.FromTo) error { @@ -51,5 +53,4 @@ func HugoGenerator(ft transform.FromTo) error { } return nil - } diff --git a/transform/metainject/hugogenerator_test.go b/transform/metainject/hugogenerator_test.go index ffb4c142..1d6d7c4b 100644 --- a/transform/metainject/hugogenerator_test.go +++ b/transform/metainject/hugogenerator_test.go @@ -57,5 +57,4 @@ func TestHugoGeneratorInject(t *testing.T) { t.Errorf("[%d] Expected \n%q got \n%q", i, this.expect, out.String()) } } - } diff --git a/transform/urlreplacers/absurlreplacer.go b/transform/urlreplacers/absurlreplacer.go index 7bac716f..a875e6fa 100644 --- a/transform/urlreplacers/absurlreplacer.go +++ b/transform/urlreplacers/absurlreplacer.go @@ -131,7 +131,6 @@ func (l *absurllexer) posAfterURL(q []byte) int { return bytes.IndexFunc(l.content[l.pos:], func(r rune) bool { return r == '>' || unicode.IsSpace(r) }) - } // handle URLs in srcset. @@ -188,7 +187,6 @@ func checkCandidateSrcset(l *absurllexer) { l.pos += len(section) l.start = l.pos - } // main loop @@ -231,12 +229,12 @@ func (l *absurllexer) replace() { } func doReplace(path string, ct transform.FromTo, quotes [][]byte) { - lexer := &absurllexer{ content: ct.From().Bytes(), w: ct.To(), path: []byte(path), - quotes: quotes} + quotes: quotes, + } lexer.replace() } @@ -249,7 +247,8 @@ type absURLReplacer struct { func newAbsURLReplacer() *absURLReplacer { return &absURLReplacer{ htmlQuotes: [][]byte{[]byte("\""), []byte("'")}, - xmlQuotes: [][]byte{[]byte("""), []byte("'")}} + xmlQuotes: [][]byte{[]byte("""), []byte("'")}, + } } func (au *absURLReplacer) replaceInHTML(path string, ct transform.FromTo) { diff --git a/transform/urlreplacers/absurlreplacer_test.go b/transform/urlreplacers/absurlreplacer_test.go index 8e8fdc56..f4aa8b8a 100644 --- a/transform/urlreplacers/absurlreplacer_test.go +++ b/transform/urlreplacers/absurlreplacer_test.go @@ -116,7 +116,8 @@ var ( srcsetXMLTests = []test{ {srcsetXMLBasic, srcsetXMLBasicCorrect}, {srcsetXMLSingleQuote, srcsetXMLSingleQuoteCorrect}, - {srcsetXMLVariations, srcsetXMLVariationsCorrect}} + {srcsetXMLVariations, srcsetXMLVariationsCorrect}, + } relurlTests = []test{{relPathVariations, relPathVariationsCorrect}} ) @@ -152,7 +153,6 @@ func TestAbsURL(t *testing.T) { tr := transform.New(NewAbsURLTransformer(testBaseURL)) apply(t.Errorf, tr, absURLTests) - } func TestAbsURLUnqoted(t *testing.T) { @@ -174,7 +174,6 @@ func TestRelativeURL(t *testing.T) { tr := transform.New(NewAbsURLTransformer(helpers.GetDottedRelativePath(filepath.FromSlash("/post/sub/")))) applyWithPath(t.Errorf, tr, relurlTests) - } func TestAbsURLSrcSet(t *testing.T) {