summaryrefslogtreecommitdiffstats
path: root/helpers/general_test.go
AgeCommit message (Collapse)Author
2024-05-14Create pages from _content.gotmplBjørn Erik Pedersen
Closes #12427 Closes #12485 Closes #6310 Closes #5074
2024-01-27all: Rework page store, add a dynacache, improve partial rebuilds, and some ↵develop2024Bjørn Erik Pedersen
general spring cleaning There are some breaking changes in this commit, see #11455. Closes #11455 Closes #11549 This fixes a set of bugs (see issue list) and it is also paying some technical debt accumulated over the years. We now build with Staticcheck enabled in the CI build. The performance should be about the same as before for regular sized Hugo sites, but it should perform and scale much better to larger data sets, as objects that uses lots of memory (e.g. rendered Markdown, big JSON files read into maps with transform.Unmarshal etc.) will now get automatically garbage collected if needed. Performance on partial rebuilds when running the server in fast render mode should be the same, but the change detection should be much more accurate. A list of the notable new features: * A new dependency tracker that covers (almost) all of Hugo's API and is used to do fine grained partial rebuilds when running the server. * A new and simpler tree document store which allows fast lookups and prefix-walking in all dimensions (e.g. language) concurrently. * You can now configure an upper memory limit allowing for much larger data sets and/or running on lower specced PCs. We have lifted the "no resources in sub folders" restriction for branch bundles (e.g. sections). Memory Limit * Hugos will, by default, set aside a quarter of the total system memory, but you can set this via the OS environment variable HUGO_MEMORYLIMIT (in gigabytes). This is backed by a partitioned LRU cache used throughout Hugo. A cache that gets dynamically resized in low memory situations, allowing Go's Garbage Collector to free the memory. New Dependency Tracker: Hugo has had a rule based coarse grained approach to server rebuilds that has worked mostly pretty well, but there have been some surprises (e.g. stale content). This is now revamped with a new dependency tracker that can quickly calculate the delta given a changed resource (e.g. a content file, template, JS file etc.). This handles transitive relations, e.g. $page -> js.Build -> JS import, or $page1.Content -> render hook -> site.GetPage -> $page2.Title, or $page1.Content -> shortcode -> partial -> site.RegularPages -> $page2.Content -> shortcode ..., and should also handle changes to aggregated values (e.g. site.Lastmod) effectively. This covers all of Hugo's API with 2 known exceptions (a list that may not be fully exhaustive): Changes to files loaded with template func os.ReadFile may not be handled correctly. We recommend loading resources with resources.Get Changes to Hugo objects (e.g. Page) passed in the template context to lang.Translate may not be detected correctly. We recommend having simple i18n templates without too much data context passed in other than simple types such as strings and numbers. Note that the cachebuster configuration (when A changes then rebuild B) works well with the above, but we recommend that you revise that configuration, as it in most situations should not be needed. One example where it is still needed is with TailwindCSS and using changes to hugo_stats.json to trigger new CSS rebuilds. Document Store: Previously, a little simplified, we split the document store (where we store pages and resources) in a tree per language. This worked pretty well, but the structure made some operations harder than they needed to be. We have now restructured it into one Radix tree for all languages. Internally the language is considered to be a dimension of that tree, and the tree can be viewed in all dimensions concurrently. This makes some operations re. language simpler (e.g. finding translations is just a slice range), but the idea is that it should also be relatively inexpensive to add more dimensions if needed (e.g. role). Fixes #10169 Fixes #10364 Fixes #10482 Fixes #10630 Fixes #10656 Fixes #10694 Fixes #10918 Fixes #11262 Fixes #11439 Fixes #11453 Fixes #11457 Fixes #11466 Fixes #11540 Fixes #11551 Fixes #11556 Fixes #11654 Fixes #11661 Fixes #11663 Fixes #11664 Fixes #11669 Fixes #11671 Fixes #11807 Fixes #11808 Fixes #11809 Fixes #11815 Fixes #11840 Fixes #11853 Fixes #11860 Fixes #11883 Fixes #11904 Fixes #7388 Fixes #7425 Fixes #7436 Fixes #7544 Fixes #7882 Fixes #7960 Fixes #8255 Fixes #8307 Fixes #8863 Fixes #8927 Fixes #9192 Fixes #9324
2023-07-05Add titleCaseStyle none and firstupperBjørn Erik Pedersen
Fixes #11204
2023-06-18Replace the old log setup, with structured logging etc.Bjørn Erik Pedersen
Fixes #11124
2023-05-16Create a struct with all of Hugo's config optionsBjørn Erik Pedersen
Primary motivation is documentation, but it will also hopefully simplify the code. Also, * Lower case the default output format names; this is in line with the custom ones (map keys) and how it's treated all the places. This avoids doing `stringds.EqualFold` everywhere. Closes #10896 Closes #10620
2023-03-14commands: Fix data race in testBjørn Erik Pedersen
Note that this is a test fix only.
2023-01-25Only invoke a given cached partial onceBjørn Erik Pedersen
Note that this is backed by a LRU cache (which we soon shall see more usage of), so if you're a heavy user of cached partials it may be evicted and refreshed if needed. But in most cases every partial is only invoked once. This commit also adds a timeout (the global `timeout` config option) to make infinite recursion in partials easier to reason about. ``` name old time/op new time/op delta IncludeCached-10 8.92ms ± 0% 8.48ms ± 1% -4.87% (p=0.016 n=4+5) name old alloc/op new alloc/op delta IncludeCached-10 6.65MB ± 0% 5.17MB ± 0% -22.32% (p=0.002 n=6+6) name old allocs/op new allocs/op delta IncludeCached-10 117k ± 0% 71k ± 0% -39.44% (p=0.002 n=6+6) ``` Closes #4086 Updates #9588
2022-04-08Rework the Destination filesystem to make --renderStaticToDisk workBjørn Erik Pedersen
See #9626
2022-01-27general: Fix issue causing log threads to hang indefinitely when print() panicsEphex2
The function printIfNotPrinted() defined for DistinctLogger unlocked the mutex within the logger only after the print() function ran. If print panics, the mutex would stay locked and future attempts to read or write from the logger mutex would cause the goroutine to hang indefinitely. Deferred the unlocking of the mutex to prevent this. Also, put l.m[key] before the print() call since this will prevent another bug where the same warning potentially gets logged multiple times if the print() call panics. Fixes #9380
2022-01-04Remove mmarkBjørn Erik Pedersen
Closes #9350
2021-12-16Add some basic security policies with sensible defaultsBjørn Erik Pedersen
This ommmit contains some security hardening measures for the Hugo build runtime. There are some rarely used features in Hugo that would be good to have disabled by default. One example would be the "external helpers". For `asciidoctor` and some others we use Go's `os/exec` package to start a new process. These are a predefined set of binary names, all loaded from `PATH` and with a predefined set of arguments. Still, if you don't use `asciidoctor` in your project, you might as well have it turned off. You can configure your own in the new `security` configuration section, but the defaults are configured to create a minimal amount of site breakage. And if that do happen, you will get clear instructions in the loa about what to do. The default configuration is listed below. Note that almost all of these options are regular expression _whitelists_ (a string or a slice); the value `none` will block all. ```toml [security] enableInlineShortcodes = false [security.exec] allow = ['^dart-sass-embedded$', '^go$', '^npx$', '^postcss$'] osEnv = ['(?i)^(PATH|PATHEXT|APPDATA|TMP|TEMP|TERM)$'] [security.funcs] getenv = ['^HUGO_'] [security.http] methods = ['(?i)GET|POST'] urls = ['.*'] ```
2021-06-14Misc config loading fixesBjørn Erik Pedersen
The main motivation behind this is simplicity and correctnes, but the new small config library is also faster: ``` BenchmarkDefaultConfigProvider/Viper-16 252418 4546 ns/op 2720 B/op 30 allocs/op BenchmarkDefaultConfigProvider/Custom-16 450756 2651 ns/op 1008 B/op 6 allocs/op ``` Fixes #8633 Fixes #8618 Fixes #8630 Updates #8591 Closes #6680 Closes #5192
2020-12-03all: Format code with gofumptBjørn Erik Pedersen
See https://github.com/mvdan/gofumpt
2020-06-25Rework external asciidoctor integration Derk Muenchhausen
This commit solves the relative path problem with asciidoctor tooling. An include will resolve relatively, so you can refer easily to files in the same folder. Also `asciidoctor-diagram` and PlantUML rendering works now, because the created temporary files will be placed in the correct folder. This patch covers just the Ruby version of asciidoctor. The old AsciiDoc CLI EOLs in Jan 2020, so this variant is removed from code. The configuration is completely rewritten and now available in `config.toml` under the key `[markup.asciidocext]`: ```toml [markup.asciidocext] extensions = ["asciidoctor-html5s", "asciidoctor-diagram"] workingFolderCurrent = true trace = true [markup.asciidocext.attributes] my-base-url = "https://example.com/" my-attribute-name = "my value" ``` - backends, safe-modes, and extensions are now whitelisted to the popular (ruby) extensions and valid values. - the default for extensions is to not enable any, because they're all external dependencies so the build would break if the user didn't install them beforehand. - the default backend is html5 because html5s is an external gem dependency. - the default safe-mode is safe, explanations of the modes: https://asciidoctor.org/man/asciidoctor/ - the config is namespaced under asciidocext_config and the parser looks at asciidocext to allow a future native Go asciidoc. - `uglyUrls=true` option and `--source` flag are supported - `--destination` flag is required Follow the updated documentation under `docs/content/en/content-management/formats.md`. This patch would be a breaking change, because you need to correct all your absolute include pathes to relative paths, so using relative paths must be configured explicitly by setting `workingFolderCurrent = true`.
2019-12-03tpl/partials: Allow any key type in partialCachedBjørn Erik Pedersen
Fixes #6572
2019-11-23Add Goldmark as the new default markdown handlerBjørn Erik Pedersen
This commit adds the fast and CommonMark compliant Goldmark as the new default markdown handler in Hugo. If you want to continue using BlackFriday as the default for md/markdown extensions, you can use this configuration: ```toml [markup] defaultMarkdownHandler="blackfriday" ``` Fixes #5963 Fixes #1778 Fixes #6355
2019-08-12tests: Convert from testify to quicktestBjørn Erik Pedersen
2019-07-24Add Hugo ModulesBjørn Erik Pedersen
This commit implements Hugo Modules. This is a broad subject, but some keywords include: * A new `module` configuration section where you can import almost anything. You can configure both your own file mounts nd the file mounts of the modules you import. This is the new recommended way of configuring what you earlier put in `configDir`, `staticDir` etc. And it also allows you to mount folders in non-Hugo-projects, e.g. the `SCSS` folder in the Bootstrap GitHub project. * A module consists of a set of mounts to the standard 7 component types in Hugo: `static`, `content`, `layouts`, `data`, `assets`, `i18n`, and `archetypes`. Yes, Theme Components can now include content, which should be very useful, especially in bigger multilingual projects. * Modules not in your local file cache will be downloaded automatically and even "hot replaced" while the server is running. * Hugo Modules supports and encourages semver versioned modules, and uses the minimal version selection algorithm to resolve versions. * A new set of CLI commands are provided to manage all of this: `hugo mod init`, `hugo mod get`, `hugo mod graph`, `hugo mod tidy`, and `hugo mod vendor`. All of the above is backed by Go Modules. Fixes #5973 Fixes #5996 Fixes #6010 Fixes #5911 Fixes #5940 Fixes #6074 Fixes #6082 Fixes #6092
2019-03-23Make Page an interfaceBjørn Erik Pedersen
The main motivation of this commit is to add a `page.Page` interface to replace the very file-oriented `hugolib.Page` struct. This is all a preparation step for issue #5074, "pages from other data sources". But this also fixes a set of annoying limitations, especially related to custom output formats, and shortcodes. Most notable changes: * The inner content of shortcodes using the `{{%` as the outer-most delimiter will now be sent to the content renderer, e.g. Blackfriday. This means that any markdown will partake in the global ToC and footnote context etc. * The Custom Output formats are now "fully virtualized". This removes many of the current limitations. * The taxonomy list type now has a reference to the `Page` object. This improves the taxonomy template `.Title` situation and make common template constructs much simpler. See #5074 Fixes #5763 Fixes #5758 Fixes #5090 Fixes #5204 Fixes #4695 Fixes #5607 Fixes #5707 Fixes #5719 Fixes #3113 Fixes #5706 Fixes #5767 Fixes #5723 Fixes #5769 Fixes #5770 Fixes #5771 Fixes #5759 Fixes #5776 Fixes #5777 Fixes #5778
2018-12-23tpl/transform: Add transform.Unmarshal funcBjørn Erik Pedersen
Fixes #5428
2018-06-10Add support for theme composition and inheritanceBjørn Erik Pedersen
This commit adds support for theme composition and inheritance in Hugo. With this, it helps thinking about a theme as a set of ordered components: ```toml theme = ["my-shortcodes", "base-theme", "hyde"] ``` The theme definition example above in `config.toml` creates a theme with the 3 components with presedence from left to right. So, Hugo will, for any given file, data entry etc., look first in the project, and then in `my-shortcode`, `base-theme` and lastly `hyde`. Hugo uses two different algorithms to merge the filesystems, depending on the file type: * For `i18n` and `data` files, Hugo merges deeply using the translation id and data key inside the files. * For `static`, `layouts` (templates) and `archetypes` files, these are merged on file level. So the left-most file will be chosen. The name used in the `theme` definition above must match a folder in `/your-site/themes`, e.g. `/your-site/themes/my-shortcodes`. There are plans to improve on this and get a URL scheme so this can be resolved automatically. Also note that a component that is part of a theme can have its own configuration file, e.g. `config.toml`. There are currently some restrictions to what a theme component can configure: * `params` (global and per language) * `menu` (global and per language) * `outputformats` and `mediatypes` The same rules apply here: The left-most param/menu etc. with the same ID will win. There are some hidden and experimental namespace support in the above, which we will work to improve in the future, but theme authors are encouraged to create their own namespaces to avoid naming conflicts. A final note: Themes/components can also have a `theme` definition in their `config.toml` and similar, which is the "inheritance" part of this commit's title. This is currently not supported by the Hugo theme site. We will have to wait for some "auto dependency" feature to be implemented for that to happen, but this can be a powerful feature if you want to create your own theme-variant based on others. Fixes #4460 Fixes #4450
2017-12-28helpers: Avoid writing the last MD5 buff part twiceBjørn Erik Pedersen
2017-12-28resource: Use MD5 to identify image filesBjørn Erik Pedersen
But only a set of byte chunks spread around in the image file to calculate the fingerprint, which is much faster than reading the whole file: ```bash BenchmarkMD5FromFileFast/full=false-4 300000 4356 ns/op 240 B/op 5 allocs/op BenchmarkMD5FromFileFast/full=true-4 30000 42899 ns/op 32944 B/op 5 allocs/op ``` Fixes #4186
2017-11-30Add Pandoc support, refactor external helpersBrian Chen
Recognize the Pandoc format under the file extension .pandoc or .pdc, and shell out to pandoc as an external helper to format Pandoc content. Refactor out repeated code with external helpers. Change the error output formatting. I did not see any of the external helpers print the string "<input>" to represent stdin as a file; just prepending the file name to error output is more general and doesn't sacrifice that much in terms of readability. Closes #234
2017-07-31Make the title case style guide configurableBjørn Erik Pedersen
This works for the `title` func and the other places where Hugo makes title case. * AP style (new default) * Chicago style * Go style (what we have today) Fixes #989
2017-07-04hugolib: Extend the sections APIBjørn Erik Pedersen
This commit adds some section related methods that have been asked for: * .CurrentSection * .IsDescendant * .IsAncestor Fixes #3591
2017-04-30tpl: Add template function namespacesCameron Moore
This commit moves almost all of the template functions into separate packages under tpl/ and adds a namespace framework. All changes should be backward compatible for end users, as all existing function names in the template funcMap are left intact. Seq and DoArithmatic have been moved out of the helpers package and into template namespaces. Most of the tests involved have been refactored, and many new tests have been written. There's still work to do, but this is a big improvement. I got a little overzealous and added some new functions along the way: - strings.Contains - strings.ContainsAny - strings.HasSuffix - strings.TrimPrefix - strings.TrimSuffix Documentation is forthcoming. Fixes #3042
2017-02-21all: Add org-mode supportChase Adams
Fixes #1483 See #936
2016-10-16Fix case issue Viper vs Blackfriday configBjørn Erik Pedersen
There are still work to be done in the case department, but that will have to be another day. Fixes #2581 See https://github.com/spf13/viper/issues/261
2016-06-25helpers: Remove ToReader funcsCameron Moore
Remove StringToReader and BytesToReader in favor of using the stdlib directly.
2016-03-14helpers: Remove unused codeBjørn Erik Pedersen
2015-12-10Add copyright header to that source files that don’t have one.Anthony Fok
See #1646
2015-11-23Improve "watching for ..." loggingBjørn Erik Pedersen
2015-11-19Remove some superficial testsBjørn Erik Pedersen
2015-05-28Support `Fish and Chips` sectionbep
Section names are also used as the title of the list pages, but naming section folders as `Fish and Chips` and similar didn't work very well. This commit fixes that. This commit also changes the title casing of the section titles. Some may argue that this is a breaking change, but the old behaviour was also pretty broken, even for languages that use title capitalizations, as it didn't follow any particular style guide, `fish and chips` became `Fish And Chips` etc. Now it just turns the first letter into upper case, so `Fish and Chips` will be left as `Fish and Chips`. People wanting the good old behaviour can use the `title` template func. Fixes #1176
2015-05-08Update test logs for uniformity and consistencybep
Many minor fixes to make test logs more consistent and correct a mispelling. Standardize on "[%i] got X but expected Y" for log messages. Using a consistent layout makes it easier to read the test results. This was mostly changing "Got" to "got". Swapped the order of values on several calls to bring them in line with the convention. A few log messages had a sequence number added to identify the exact scenario that failed. Otherwise, there would be no way to ascertain which failed When there are many scenarios. Correct spelling of "expected." Fixes #1028 Merged be2097e1ad789eca5d893805a059d94defbe5c48 [close #1040]
2015-05-08Very experimental support for mmarkAnthony Fok
Either name the content files as `*.mmark`, or add `markup = "mmark"` in the front matter of your `*.md` content files.
2015-04-03helpers: fix some go vet errorsbep
2015-03-30Add some more corner tests for ReaderContainsbep
2015-03-29Handle views in combo with Ace base templatesbep
As views looks like a regular template, but doesn't need a base template, we have to look inside it. Altough really not needed by this commit, reading the full file content into memory just to do a substring search is a waste. So this commit implements a `ReaderContains` func that in most cases should be much faster than doing an `ioutil.ReadAll` and `bytes.Contains`: ``` benchmark old ns/op new ns/op delta BenchmarkReaderContains 78452 20260 -74.18% benchmark old allocs new allocs delta BenchmarkReaderContains 46 20 -56.52% benchmark old bytes new bytes delta BenchmarkReaderContains 46496 1258 -97.29% ``` Fixes #999
2015-03-18Comment out shaky Seq testbep
2015-03-18Improve type handling in Seqbep
2015-03-12Add Seq template funcbep
Very similar to GNU's seq. Fixes #552 Conflicts: tpl/template.go
2015-03-12Experimental AsciiDoc support with external helpersAnthony Fok
See #470 * Based on existing support for reStructuredText files * Handles content files with extensions `.asciidoc` and `.ad` * Pipes content through `asciidoctor --safe -`. If `asciidoctor` is not installed, then `asciidoc --safe -`. * To make sure `asciidoctor` or `asciidoc` is found, after adding a piece of AsciiDoc content, run `hugo` with the `-v` flag and look for this message: INFO: 2015/01/23 Rendering with /usr/bin/asciidoctor ... Caveats: * The final "Last updated" timestamp is currently not stripped. * When `hugo` is run with `-v`, you may see a lot of these messages INFO: 2015/01/23 Rendering with /usr/bin/asciidoctor ... if you have lots of `*.ad`, `*.adoc` or `*.asciidoc` files. * Some versions of `asciidoc` may have trouble with its safe mode. To test if you are affected, try this: $ echo "Hello" | asciidoc --safe - asciidoc: ERROR: unsafe: ifeval invalid asciidoc: FAILED: ifeval invalid safe document If so, I recommend that you install `asciidoctor` instead. Feedback and patches welcome! Ideally, we should be using https://github.com/VonC/asciidocgo, @VonC's wonderful Go implementation of Asciidoctor. However, there is still a bit of work needed for asciidocgo to expose its API so that Hugo can actually use it. Until then, hope this "experimental AsciiDoc support through external helpers" can serve as a stopgap solution for our community. :-) 2015-01-30: Updated for the replaceShortcodeTokens() syntax change 2015-02-21: Add `.adoc` extension as suggested by @Fale Conflicts: helpers/content.go
2015-03-07helpers: apply some Golint rulesbep
2015-03-06Fix errors reported by Go Vetbep
2015-01-31Add writable context to Nodebep
The variable scope in the Go templates makes it hard, if possible at all, to write templates with counter variables or similar state. This commit fixes that by adding a writable context to Node, backed by a map: Scratch. This context has three methods, Get, Set and Add. The Add is tailored for counter variables, but can be used for any built-in numeric values or strings.
2015-01-20Add more tests to general helperbep
2015-01-09Moved a test regarding a content.go function to a new test file content_test.go.Marek Stanley
Added some tests for general helpers, especially as a way to document the expected behavior, and as a warm-up welcome contribution.
2014-11-04Added the general modules test filesOwen Waller
Added the new general module's test file, general_test.go. This replaces the helpers_test.go file. There is also a minor defect fix in general.go's StripHTML function. The correct xhtml tag for a break is <br /> not </br>. I've also removed the unnecessary spaces before the replacement "\n". The new test module also reflects this change. Conflicts: helpers/general.go