Backtestshugorun-20261024-162305#14937

Issue #14937 Merged fix PR #15377 Run 24 Oct 2026 · run-20261024-162305 gohugoio/hugo

Add build.cleanDestinationDir config option

Better

Our patch was judged better than the merged fix.

In this judgment, Patch A = our agent, Patch B = the merged fix.

Both patches add build.cleanDestinationDir with an enable switch plus keep patterns, and both pass all four independent tests, so the decision rests on design risk, docs, and craft. Patch A is additive: the existing hardcoded rules (.gitignore/.gitattributes, dot-directories) stay, the new `keep` globs are checked first against the slash-normalized path relative to publishDir, the root cleanDestinationDir key and flag keep working via isCleanDestinationDir, and a bool shorthand is decoded. It ships unit tests for decoding/glob matching/clone isolation/invalid-glob errors, a testscript covering bool shorthand, keep with and without static/, and keep combined with the flag, and it updates the configuration docs and docs.yaml. Patch B goes further than the issue asks: it deletes RootConfig.CleanDestinationDir, remaps the CLI flag to build.cleanDestinationDir.enable, adds a deprecation, and turns the built-in keep rules into default globs with negation support. Some of that is nice (keeping `.git` files by default covers the worktree case), but it introduces a real footgun that its own test exposes: setting keepFiles = ['.domains','_redirects'] replaces the defaults, so .gitignore/.gitattributes and dot-directories are suddenly deleted (scenario 4 output drops .gitignore and .hidden/). A user following the issue's use case would lose files Hugo previously always preserved. B also adds no documentation for the new keys or the deprecation, and the broader refactor (removing a root config field, changing flag mapping) adds migration risk with no benefit to the reported problem. A resolves the issue with less risk, better tests, and complete docs.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

1h 25m

Wall-clock time in the container

Full test suite

No new failures

2,241 passed · 6 skipped · 2,277 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

297vs 194 merged

Changed lines, ours vs merged

<!-- Describe this new feature. Think about if it really belongs in the Hugo core module; you may want to discuss it on https://discourse.gohugo.io/ first. -->

Usecase

I'm using Codeberg Pages to host my website, you can find the repostitory at https://codeberg.org/ilovelinux/pages

I have two branches:

  • main: hugo project
  • pages: hugo build (output of public/)

Since I'm using Codeberg Pages with a custom domain, I also need a .domains file[^codebergDomains] to be pushed in the pages branch.

When I

  • Have files in the static/ directory.
  • Switch to main branch.
  • Create the public/ folder using a git worktree of the pages branch.
  • Run hugo build --cleanDestinationDir.

I need

  • To remove outdated content
  • To retain:
  • .git file created by git worktree[^gitWorktreeFile].
  • .domains file used by Codeberg Pages in order to allow custom domains[^codebergDomains].
  • _redirects file for redirects (however I'm not using it yet)[^codebergRedirects].

Instead

  • The files I need to be retained are deleted.

Proposal

Add a configuration field to list relative file paths to public/ that should be retained when using --cleanDestinationDir.

Example

 filesToRetain:
  - .git
  - .domains
  - _redirects
  - foo/bar/.mysecretfile

Files retained:

  • public/.git
  • public/.domains
  • public/_redirects
  • public/foo/bar/.mysecretfile

[!NOTE]
I'm not suggesting to use filesToRetain as configuration field, but I couldn't think of a better name.

Notes

[!IMPORTANT]
--cleanDestinationDir does nothing when when the static/ directory doesn't exist since its value is used inside the copyStaticTo function.
https://github.com/gohugoio/hugo/blob/c4bbc2805c7092deafabae01e71ff2dda37bd877/commands/hugobuilder.go#L481

Workaround

[!WARNING]
This approach is error-prone.

I implemented a workaround in my Makefile that:

Related issues & PR

[^gitWorktreeFile]: https://git-scm.com/docs/git-worktree#_details
[^gitSubmoduleFile]: https://git-scm.com/docs/git-submodule#Documentation/git-submodule.txt-absorbgitdirs
[^codebergDomains]: https://docs.codeberg.org/codeberg-pages/using-custom-domain/
[^codebergRedirects]: https://docs.codeberg.org/codeberg-pages/redirects/

The two patches

Our patch+289 −8
commands/hugobuilder.goindex a9cacaada..1818d6a70 100644@@ -467,14 +467,18 @@ func (c *hugoBuilder) copyStaticTo(sourceFs *filesystems.SourceFilesystem) (uint 	fs := &countingStatFs{Fs: sourceFs.Fs}  	syncer := fsync.NewSyncer()-	var clean bool+	var (+		clean    bool+		cleanCfg config.CleanDestinationDir+	) 	c.withConf(func(conf *commonConfig) { 		syncer.NoTimes = conf.configs.Base.NoTimes 		syncer.NoChmod = conf.configs.Base.NoChmod 		syncer.ChmodFilter = chmodFilter  		syncer.DestFs = conf.fs.PublishDirStatic-		clean = conf.configs.Base.CleanDestinationDir+		clean = isCleanDestinationDir(conf)+		cleanCfg = conf.configs.Base.Build.CleanDestinationDir 	})  	syncer.SrcFs = fs@@ -494,7 +498,12 @@ func (c *hugoBuilder) copyStaticTo(sourceFs *filesystems.SourceFilesystem) (uint 	if clean { 		infol.Logf("removing stale files from destination") -		keep := func(f fsync.FileInfo) bool {+		keep := func(path string, f fsync.FileInfo) bool {+			// Keep files and directories matching build.cleanDestinationDir.keep.+			if cleanCfg.ShouldKeep(filepath.ToSlash(path)) {+				return true+			}+ 			name := f.Name()  			// Keep git metadata files anywhere.@@ -519,10 +528,18 @@ func (c *hugoBuilder) copyStaticTo(sourceFs *filesystems.SourceFilesystem) (uint 	return numFiles, nil } +// isCleanDestinationDir reports whether stale files should be removed from the+// destination directory, set either via the cleanDestinationDir flag or via+// build.cleanDestinationDir in the configuration.+func isCleanDestinationDir(conf *commonConfig) bool {+	return conf.configs.Base.CleanDestinationDir || conf.configs.Base.Build.CleanDestinationDir.Enable+}+ // removeStale removes entries in dstDir on dst that keep reports as false and // that don't exist in srcDir on src. Unlike fsync's delete pass, it applies // keep at every level, so kept files survive inside stale directories.-func removeStale(dst, src afero.Fs, dstDir, srcDir string, keep func(fsync.FileInfo) bool) error {+// keep receives the path of the entry in dst and its file info.+func removeStale(dst, src afero.Fs, dstDir, srcDir string, keep func(string, fsync.FileInfo) bool) error { 	entries, err := afero.ReadDir(dst, dstDir) 	if err != nil { 		if herrors.IsNotExist(err) {@@ -531,10 +548,10 @@ func removeStale(dst, src afero.Fs, dstDir, srcDir string, keep func(fsync.FileI 		return err 	} 	for _, entry := range entries {-		if keep(entry) {+		dstPath := filepath.Join(dstDir, entry.Name())+		if keep(dstPath, entry) { 			continue 		}-		dstPath := filepath.Join(dstDir, entry.Name()) 		srcPath := filepath.Join(srcDir, entry.Name()) 		if _, err := src.Stat(srcPath); err == nil { 			if entry.IsDir() {@@ -644,7 +661,7 @@ func (c *hugoBuilder) fullBuild(noBuildLock bool) error { 	// and it does so at the end of copyStatic() call. 	var cleanDestinationDir bool 	c.withConf(func(conf *commonConfig) {-		cleanDestinationDir = conf.configs.Base.CleanDestinationDir+		cleanDestinationDir = isCleanDestinationDir(conf) 	}) 	if cleanDestinationDir { 		if err := copyStaticFunc(); err != nil {config/commonConfig.goindex dae0ed905..91821c27e 100644@@ -112,6 +112,59 @@ type BuildConfig struct {  	// Can used to control how the resource cache gets evicted on rebuilds. 	CacheBusters []CacheBuster++	// Configures the removal of stale files from the destination directory.+	// Can also be set to a bool, which is the same as setting Enable.+	CleanDestinationDir CleanDestinationDir+}++// CleanDestinationDir configures the removal of stale files from the+// destination directory (see also the --cleanDestinationDir flag).+type CleanDestinationDir struct {+	// Whether to remove files from the destination directory that do not+	// exist in the static directories.+	Enable bool++	// Glob patterns of files and directories to keep when cleaning the+	// destination directory, e.g. ".git", ".domains" or "{,**/}.htaccess".+	// The patterns are matched against the slash-separated path relative+	// to the destination directory root.+	Keep []string++	compiledKeep []*glob.Pattern+}++// CompileConfig compiles the Keep glob patterns.+func (c *CleanDestinationDir) CompileConfig() error {+	if c.compiledKeep != nil {+		return nil+	}+	compiled := make([]*glob.Pattern, 0, len(c.Keep))+	for _, pattern := range c.Keep {+		g, err := glob.Compile(normalizeCleanDestinationDirPath(pattern), '/')+		if err != nil {+			return fmt.Errorf("failed to compile build.cleanDestinationDir.keep glob %q: %w", pattern, err)+		}+		compiled = append(compiled, g)+	}+	c.compiledKeep = compiled+	return nil+}++// ShouldKeep reports whether the file or directory with the given+// slash-separated path, relative to the destination directory root, matches one of the Keep patterns.+func (c CleanDestinationDir) ShouldKeep(path string) bool {+	path = normalizeCleanDestinationDirPath(path)+	for _, g := range c.compiledKeep {+		if g.Match(path) {+			return true+		}+	}+	return false+}++func normalizeCleanDestinationDirPath(s string) string {+	return strings.Trim(s, "/") }  // BuildStats configures if and what to write to the hugo_stats.json file.@@ -131,6 +184,8 @@ func (w BuildStats) Enabled() bool {  func (b BuildConfig) clone() BuildConfig { 	b.CacheBusters = slices.Clone(b.CacheBusters)+	b.CleanDestinationDir.Keep = slices.Clone(b.CleanDestinationDir.Keep)+	b.CleanDestinationDir.compiledKeep = slices.Clone(b.CleanDestinationDir.compiledKeep) 	return b } @@ -174,6 +229,9 @@ func (b *BuildConfig) CompileConfig(logger loggers.Logger) error { 		} 		b.CacheBusters[i] = cb 	}+	if err := b.CleanDestinationDir.CompileConfig(); err != nil {+		return err+	} 	return nil } @@ -192,6 +250,13 @@ func DecodeBuildConfig(cfg Provider) BuildConfig { 		} 	} +	// cleanDestinationDir can be set to a bool as a shorthand for enable.+	if cleanDestinationDir, ok := m["cleandestinationdir"]; ok {+		if bb, ok := cleanDestinationDir.(bool); ok {+			m["cleandestinationdir"] = map[string]any{"enable": bb}+		}+	}+ 	err := mapstructure.WeakDecode(m, &b) 	if err != nil { 		return bconfig/commonConfig_test.goindex 05ba185e3..2f1a2c3e5 100644@@ -195,3 +195,60 @@ func TestBuildConfigCacheBusterstTailwindSetup(t *testing.T) { 	c.Assert(err, qt.IsNil) 	c.Assert(m("css"), qt.IsTrue) }++func TestBuildCleanDestinationDir(t *testing.T) {+	c := qt.New(t)++	v := New()+	b := DecodeBuildConfig(v)+	c.Assert(b.CleanDestinationDir.Enable, qt.IsFalse)+	c.Assert(b.CleanDestinationDir.Keep, qt.HasLen, 0)++	// Bool shorthand.+	v.Set("build", map[string]any{+		"cleanDestinationDir": true,+	})+	b = DecodeBuildConfig(v)+	c.Assert(b.CleanDestinationDir.Enable, qt.IsTrue)+	c.Assert(b.CompileConfig(loggers.NewDefault()), qt.IsNil)+	c.Assert(b.CleanDestinationDir.ShouldKeep(".git"), qt.IsFalse)++	v.Set("build", map[string]any{+		"cleanDestinationDir": map[string]any{+			"enable": true,+			"keep":   []any{".git", ".domains", "_redirects", "foo/bar/.mysecretfile", "**/*.keep", "/rooted.txt", "{,**/}.htaccess"},+		},+	})+	b = DecodeBuildConfig(v)+	c.Assert(b.CleanDestinationDir.Enable, qt.IsTrue)+	c.Assert(b.CompileConfig(loggers.NewDefault()), qt.IsNil)++	keep := b.CleanDestinationDir+	c.Assert(keep.ShouldKeep(".git"), qt.IsTrue)+	c.Assert(keep.ShouldKeep("/.git"), qt.IsTrue)+	c.Assert(keep.ShouldKeep(".domains"), qt.IsTrue)+	c.Assert(keep.ShouldKeep("_redirects"), qt.IsTrue)+	c.Assert(keep.ShouldKeep("foo/bar/.mysecretfile"), qt.IsTrue)+	c.Assert(keep.ShouldKeep("a/b/c.keep"), qt.IsTrue)+	c.Assert(keep.ShouldKeep("rooted.txt"), qt.IsTrue)+	c.Assert(keep.ShouldKeep(".htaccess"), qt.IsTrue)+	c.Assert(keep.ShouldKeep("a/b/.htaccess"), qt.IsTrue)+	c.Assert(keep.ShouldKeep("x.htaccess"), qt.IsFalse)+	c.Assert(keep.ShouldKeep("sub/.git"), qt.IsFalse)+	c.Assert(keep.ShouldKeep("foo/.mysecretfile"), qt.IsFalse)+	c.Assert(keep.ShouldKeep("index.html"), qt.IsFalse)++	// Cloning must not share the Keep slice.+	clone := b.clone()+	clone.CleanDestinationDir.Keep[0] = "changed"+	c.Assert(b.CleanDestinationDir.Keep[0], qt.Equals, ".git")++	// Invalid glob.+	v.Set("build", map[string]any{+		"cleanDestinationDir": map[string]any{+			"keep": []any{"[abc"},+		},+	})+	b = DecodeBuildConfig(v)+	c.Assert(b.CompileConfig(loggers.NewDefault()), qt.ErrorMatches, `.*build.cleanDestinationDir.keep.*`)+}docs/content/en/configuration/all.mdindex 842465254..097713d99 100644@@ -46,7 +46,7 @@ aliases: [/getting-started/configuration/] : See [configure cascade][].  `cleanDestinationDir`-: (`bool`) Whether to remove files from the [`publishDir`](#publishdir) that do not exist in the [`staticDir`](#staticdir). Hugo performs this cleanup before rendering, so the current build's rendered output is unaffected. If the `staticDir` does not exist, the cleanup does not run. Note that `.gitignore` and `.gitattributes` files are always preserved, as are directories whose names begin with a dot, provided their parent directory also survives. Default is `false`.+: (`bool`) Whether to remove files from the [`publishDir`](#publishdir) that do not exist in the [`staticDir`](#staticdir). Hugo performs this cleanup before rendering, so the current build's rendered output is unaffected. Note that `.gitignore` and `.gitattributes` files are always preserved, as are directories whose names begin with a dot, provided their parent directory also survives. To keep other files and directories, see [`build.cleanDestinationDir`](/configuration/build/#clean-destination-directory). Default is `false`.  `contentDir` : (`string`) The designated directory for content files. Default is `content`. {{% module-mounts-note %}}docs/content/en/configuration/build.mdindex 6a7924301..18a88199b 100644@@ -17,6 +17,9 @@ This is the default configuration: `cachebusters` : See the [cache busters](#cache-busters) section below. +`cleanDestinationDir`+: See the [clean destination directory](#clean-destination-directory) section below.+ `noJSConfigInAssets` : (`bool`) Whether to disable writing a `jsconfig.json` in your `assets` directory with mapping of imports from running [js.Build][]. This file is intended to help with intellisense/navigation inside code editors such as [VS Code][]. Note that if you do not use `js.Build`, no file will be written. @@ -55,6 +58,26 @@ When `buildStats` is enabled, Hugo writes a `hugo_stats.json` file on each build `target` : (`string`) A [regular expression](g) matching the keys in the resource cache that should be expired when `source` changes. You can use the matching regexp groups from `source` in the expression, e.g. `$1`. +## Clean destination directory++{{< code-toggle config=build.cleanDestinationDir />}}++`enable`+: (`bool`) Whether to remove files from the [`publishDir`][] that do not exist in the `static` directories, the same as passing the `--cleanDestinationDir` flag. Setting `cleanDestinationDir` to a boolean value is a shorthand for setting `enable`. Default is `false`.++`keep`+: (`[]string`) A list of [glob patterns](g) matching files and directories to keep when cleaning the destination directory, regardless of whether the `enable` setting or the `--cleanDestinationDir` flag enabled cleaning. The patterns are matched against the slash-separated path relative to the root of the `publishDir`. Note that `**/.htaccess` does not match an `.htaccess` file in the root of the `publishDir`; use `{,**/}.htaccess` to match it at any depth. A matching directory is kept with all of its contents. Regardless of these patterns, Hugo always keeps `.gitignore` and `.gitattributes` files, as well as directories whose names start with a dot, provided their parent directory also survives.++For example, to keep the `.git` file created by `git worktree`, plus files used by your hosting provider:++{{< code-toggle file=hugo >}}+[build.cleanDestinationDir]+enable = true+keep = ['.git', '.domains', '_redirects', 'foo/bar/.mysecretfile', '{,**/}.htaccess']+{{< /code-toggle >}}++[`publishDir`]: /configuration/all/#publishdir+ ## Build stats  {{< code-toggle config=build.buildStats />}}docs/data/docs.yamlindex 6d2578339..e262f9a0e 100644@@ -1336,6 +1336,9 @@ config:     cacheBusters:     - source: '(postcss|tailwind)\.config\.(js|mjs|cjs)'       target: (css|styles|scss|sass)+    cleanDestinationDir:+      enable: false+      keep: null     noJSConfigInAssets: false     useResourceCacheWhen: fallback   buildDrafts: falsetestscripts/commands/hugo__clean_destination_dir_keep.txtnew file mode 100644index 000000000..be73543a9@@ -0,0 +1,116 @@+# Test the build.cleanDestinationDir configuration option.++# --- Scenario 1: Enabled in config using the bool shorthand, without static directory ---++cpr golden_public public++hugo --config hugo_bool.toml+tree public+cmp stdout bool_clean_build.txt++# --- Scenario 2: Enabled in config with keep patterns, without static directory ---++rm public+cpr golden_public public++hugo --config hugo_keep.toml+tree public+cmp stdout keep_clean_build.txt++# --- Scenario 3: Keep patterns with the cleanDestinationDir flag and a static directory ---++rm public+cpr golden_public public+cpr golden_static static++hugo --config hugo_keep_disabled.toml+tree public+cmp stdout keep_disabled_default_build.txt++hugo --config hugo_keep_disabled.toml --cleanDestinationDir+tree public+cmp stdout keep_flag_clean_build.txt++# Files++-- hugo_bool.toml --+disableKinds = ['page','rss','section','sitemap','taxonomy','term']+[build]+cleanDestinationDir = true+-- hugo_keep.toml --+disableKinds = ['page','rss','section','sitemap','taxonomy','term']+[build.cleanDestinationDir]+enable = true+keep = ['.git', '.domains', '_redirects', 'foo/bar/.mysecretfile', '**/*.keep']+-- hugo_keep_disabled.toml --+disableKinds = ['page','rss','section','sitemap','taxonomy','term']+[build.cleanDestinationDir]+keep = ['.git', '.domains', '_redirects', 'foo/bar/.mysecretfile', '**/*.keep']+-- content/_index.md --+---+title: home+---+-- layouts/home.html --+{{ .Title }}++-- golden_public/.git --+gitdir: /path/to/repo/.git/worktrees/pages+-- golden_public/.domains --+-- golden_public/_redirects --+-- golden_public/c.txt --+-- golden_public/foo/bar/.mysecretfile --+-- golden_public/foo/bar/other.txt --+-- golden_public/foo/.mysecretfile --+-- golden_public/dir-a/b.keep --+-- golden_public/dir-a/b.txt --+-- golden_public/dir-b/.git --++-- golden_static/l.txt --+-- golden_static/dir-a/m.txt --++-- bool_clean_build.txt --+.+└─index.html+-- keep_clean_build.txt --+.+└─.domains+└─.git+└─_redirects+└─dir-a/+  └─b.keep+└─foo/+  └─bar/+    └─.mysecretfile+└─index.html+-- keep_disabled_default_build.txt --+.+└─.domains+└─.git+└─_redirects+└─c.txt+└─dir-a/+  └─b.keep+  └─b.txt+  └─m.txt+└─dir-b/+  └─.git+└─foo/+  └─.mysecretfile+  └─bar/+    └─.mysecretfile+    └─other.txt+└─index.html+└─l.txt+-- keep_flag_clean_build.txt --+.+└─.domains+└─.git+└─_redirects+└─dir-a/+  └─b.keep+  └─m.txt+└─foo/+  └─bar/+    └─.mysecretfile+└─index.html+└─l.txt 
Merged fix · PR #15377+165 −29
commands/helpers.goindex fbe1d362a..16555b6c4 100644@@ -76,9 +76,10 @@ func flagsToCfgWithAdditionalConfigBase(cd *simplecobra.Commandeer, cfg config.P  	// Flags with a different name in the config. 	keyMap := map[string]string{-		"minify":      "minify.minifyOutput",-		"destination": "publishDir",-		"editor":      "newContentEditor",+		"minify":              "minify.minifyOutput",+		"destination":         "publishDir",+		"editor":              "newContentEditor",+		"cleanDestinationDir": "build.cleanDestinationDir.enable", 	}  	// Flags that we for some reason don't want to expose in the project config.commands/hugobuilder.goindex a9cacaada..963db35c2 100644@@ -467,14 +467,14 @@ func (c *hugoBuilder) copyStaticTo(sourceFs *filesystems.SourceFilesystem) (uint 	fs := &countingStatFs{Fs: sourceFs.Fs}  	syncer := fsync.NewSyncer()-	var clean bool+	var clean config.CleanDestinationDir 	c.withConf(func(conf *commonConfig) { 		syncer.NoTimes = conf.configs.Base.NoTimes 		syncer.NoChmod = conf.configs.Base.NoChmod 		syncer.ChmodFilter = chmodFilter  		syncer.DestFs = conf.fs.PublishDirStatic-		clean = conf.configs.Base.CleanDestinationDir+		clean = conf.configs.Base.Build.CleanDestinationDir 	})  	syncer.SrcFs = fs@@ -491,22 +491,9 @@ func (c *hugoBuilder) copyStaticTo(sourceFs *filesystems.SourceFilesystem) (uint 		return 0, err 	} -	if clean {+	if clean.Enable { 		infol.Logf("removing stale files from destination")--		keep := func(f fsync.FileInfo) bool {-			name := f.Name()--			// Keep git metadata files anywhere.-			if name == ".gitignore" || name == ".gitattributes" {-				return true-			}--			// Keep dot-directories anywhere.-			return f.IsDir() && strings.HasPrefix(name, ".")-		}--		if err := removeStale(syncer.DestFs, sourceFs.Fs, publishDir, helpers.FilePathSeparator, keep); err != nil {+		if err := removeStale(syncer.DestFs, sourceFs.Fs, publishDir, helpers.FilePathSeparator, clean.Keep); err != nil { 			return 0, err 		} 	}@@ -522,7 +509,8 @@ func (c *hugoBuilder) copyStaticTo(sourceFs *filesystems.SourceFilesystem) (uint // removeStale removes entries in dstDir on dst that keep reports as false and // that don't exist in srcDir on src. Unlike fsync's delete pass, it applies // keep at every level, so kept files survive inside stale directories.-func removeStale(dst, src afero.Fs, dstDir, srcDir string, keep func(fsync.FileInfo) bool) error {+// keep gets the slash separated path relative to srcDir's root, e.g. "dir/.gitignore".+func removeStale(dst, src afero.Fs, dstDir, srcDir string, keep func(path string, isDir bool) bool) error { 	entries, err := afero.ReadDir(dst, dstDir) 	if err != nil { 		if herrors.IsNotExist(err) {@@ -531,11 +519,11 @@ func removeStale(dst, src afero.Fs, dstDir, srcDir string, keep func(fsync.FileI 		return err 	} 	for _, entry := range entries {-		if keep(entry) {-			continue-		} 		dstPath := filepath.Join(dstDir, entry.Name()) 		srcPath := filepath.Join(srcDir, entry.Name())+		if keep(strings.TrimPrefix(filepath.ToSlash(srcPath), "/"), entry.IsDir()) {+			continue+		} 		if _, err := src.Stat(srcPath); err == nil { 			if entry.IsDir() { 				if err := removeStale(dst, src, dstPath, srcPath, keep); err != nil {@@ -644,7 +632,7 @@ func (c *hugoBuilder) fullBuild(noBuildLock bool) error { 	// and it does so at the end of copyStatic() call. 	var cleanDestinationDir bool 	c.withConf(func(conf *commonConfig) {-		cleanDestinationDir = conf.configs.Base.CleanDestinationDir+		cleanDestinationDir = conf.configs.Base.Build.CleanDestinationDir.Enable 	}) 	if cleanDestinationDir { 		if err := copyStaticFunc(); err != nil {config/allconfig/allconfig.goindex 806cedc71..a84545edb 100644@@ -785,10 +785,6 @@ type RootConfig struct { 	// Don't sync modification time of files for the static mounts. 	NoChmod bool -	// Clean the destination folder before a new build.-	// This currently only handles static files.-	CleanDestinationDir bool- 	// A Glob pattern of module paths to ignore in the _vendor folder. 	IgnoreVendorPaths string config/allconfig/load.goindex bc35af9d6..76eb65703 100644@@ -198,6 +198,13 @@ func (l configLoader) normalizeCfg(cfg config.Provider) error { 		} 	} +	if b, ok := cfg.Get("cleanDestinationDir").(bool); ok {+		hugo.Deprecate("project config cleanDestinationDir", "Use build.cleanDestinationDir.enable instead.", "v0.167.0")+		if b {+			cfg.Set("build.cleanDestinationDir.enable", true)+		}+	}+ 	return nil } config/commonConfig.goindex dae0ed905..cadfcb5ef 100644@@ -25,7 +25,9 @@ import ( 	"github.com/gobwas/glob" 	"github.com/gohugoio/hugo/common/hstrings" 	"github.com/gohugoio/hugo/common/loggers"+	"github.com/gohugoio/hugo/common/predicate" 	"github.com/gohugoio/hugo/common/types"+	"github.com/gohugoio/hugo/hugofs/hglob"  	"github.com/gohugoio/hugo/common/herrors" 	"github.com/mitchellh/mapstructure"@@ -86,6 +88,10 @@ type LoadConfigResult struct { var defaultBuild = BuildConfig{ 	UseResourceCacheWhen: "fallback", 	BuildStats:           BuildStats{},+	CleanDestinationDir: CleanDestinationDir{+		KeepFiles: []string{"{**/,}.{git,gitignore,gitattributes}"},+		KeepDirs:  []string{"{**/,}.*"},+	},  	CacheBusters: []CacheBuster{ 		{@@ -112,6 +118,42 @@ type BuildConfig struct {  	// Can used to control how the resource cache gets evicted on rebuilds. 	CacheBusters []CacheBuster++	// Removes files from the publish directory that are not found in the static source.+	CleanDestinationDir CleanDestinationDir+}++// CleanDestinationDir configures the removal of stale files from the publish directory.+type CleanDestinationDir struct {+	// Whether to remove stale files. Can also be enabled with the --cleanDestinationDir flag.+	Enable bool++	// Glob patterns of files to keep, matched against the slash separated path relative to the publish directory, e.g. "dir/.gitignore".+	// A pattern prefixed with "! " is a negation.+	KeepFiles []string++	// Glob patterns of directories to keep with all of their content.+	KeepDirs []string++	keepFiles predicate.P[string]+	keepDirs  predicate.P[string]+}++// Keep reports whether path, relative to the publish directory, should be kept.+func (c CleanDestinationDir) Keep(path string, isDir bool) bool {+	if isDir {+		return c.keepDirs(path)+	}+	return c.keepFiles(path)+}++func (c *CleanDestinationDir) compile() error {+	var err error+	if c.keepFiles, err = predicate.NewStringPredicateFromGlobs(c.KeepFiles, hglob.GetGlob); err != nil {+		return err+	}+	c.keepDirs, err = predicate.NewStringPredicateFromGlobs(c.KeepDirs, hglob.GetGlob)+	return err }  // BuildStats configures if and what to write to the hugo_stats.json file.@@ -131,6 +173,8 @@ func (w BuildStats) Enabled() bool {  func (b BuildConfig) clone() BuildConfig { 	b.CacheBusters = slices.Clone(b.CacheBusters)+	b.CleanDestinationDir.KeepFiles = slices.Clone(b.CleanDestinationDir.KeepFiles)+	b.CleanDestinationDir.KeepDirs = slices.Clone(b.CleanDestinationDir.KeepDirs) 	return b } @@ -174,6 +218,9 @@ func (b *BuildConfig) CompileConfig(logger loggers.Logger) error { 		} 		b.CacheBusters[i] = cb 	}+	if err := b.CleanDestinationDir.compile(); err != nil {+		return fmt.Errorf("failed to compile build.cleanDestinationDir: %w", err)+	} 	return nil } testscripts/commands/hugo__clean_destination_dir.txtindex 9191c77e9..c3273227e 100644@@ -37,24 +37,76 @@ hugo --cleanDestinationDir tree public cmp stdout mismatch_clean_build.txt +# --- Scenario 4: Custom keepFiles and keepDirs ---++rm public static++cpr golden_public_keep public++hugo --config hugo_keep.toml+tree public+cmp stdout keep_clean_build.txt++# --- Scenario 5: Negated keepFiles ---++rm public++cpr golden_public_keep public++hugo --config hugo_keep_negate.toml+tree public+cmp stdout keep_negate_clean_build.txt++# --- Scenario 6: Deprecated root cleanDestinationDir key with default keep patterns ---++rm public++cpr golden_public_keep public++hugo --config hugo_legacy.toml+tree public+cmp stdout legacy_clean_build.txt+ # Files  -- hugo.toml -- disableKinds = ['page','rss','section','sitemap','taxonomy','term']+-- hugo_keep.toml --+disableKinds = ['page','rss','section','sitemap','taxonomy','term']+[build.cleanDestinationDir]+enable = true+keepFiles = ['.domains', '_redirects']+keepDirs = ['keep-me']+-- hugo_keep_negate.toml --+disableKinds = ['page','rss','section','sitemap','taxonomy','term']+# Render home as JSON so no HTML gets rendered.+[outputs]+home = ['json']+[build.cleanDestinationDir]+enable = true+# Remove all HTML files, keep everything else.+keepFiles = ['! **.html']+-- hugo_legacy.toml --+disableKinds = ['page','rss','section','sitemap','taxonomy','term']+cleanDestinationDir = true -- content/_index.md -- --- title: home --- -- layouts/home.html -- {{ .Title }}+-- layouts/home.json --+{{ .Title | jsonify }}  -- golden_public/.dir-a/a.txt -- -- golden_public/.b.txt --+-- golden_public/.git -- -- golden_public/.gitattributes -- -- golden_public/.gitignore -- -- golden_public/c.txt -- -- golden_public/dir-b/.dir-c/d.txt -- -- golden_public/dir-b/.e.txt --+-- golden_public/dir-b/.git -- -- golden_public/dir-b/.gitignore -- -- golden_public/dir-b/f.txt -- -- golden_public/dir-d/g.txt --@@ -68,6 +120,16 @@ title: home -- golden_static/dir-e/.m.txt -- -- golden_static/dir-e/n.txt -- +-- golden_public_keep/.domains --+-- golden_public_keep/.gitignore --+-- golden_public_keep/.hidden/x.txt --+-- golden_public_keep/_redirects --+-- golden_public_keep/a.html --+-- golden_public_keep/b.txt --+-- golden_public_keep/dir/.domains --+-- golden_public_keep/keep-me/x.html --+-- golden_public_keep/keep-me/y.txt --+ -- golden_public_mismatch/type-a/x.txt -- -- golden_public_mismatch/type-b -- @@ -79,6 +141,7 @@ title: home └─.b.txt └─.dir-a/   └─a.txt+└─.git └─.gitattributes └─.gitignore └─c.txt@@ -86,6 +149,7 @@ title: home   └─.dir-c/     └─d.txt   └─.e.txt+  └─.git   └─.gitignore   └─f.txt └─dir-d/@@ -101,11 +165,13 @@ title: home . └─.dir-a/   └─a.txt+└─.git └─.gitattributes └─.gitignore └─dir-b/   └─.dir-c/     └─d.txt+  └─.git   └─.gitignore └─dir-e/   └─.dir-f/@@ -117,6 +183,7 @@ title: home └─.b.txt └─.dir-a/   └─a.txt+└─.git └─.gitattributes └─.gitignore └─.k.txt@@ -125,6 +192,7 @@ title: home   └─.dir-c/     └─d.txt   └─.e.txt+  └─.git   └─.gitignore   └─f.txt └─dir-d/@@ -143,12 +211,14 @@ title: home . └─.dir-a/   └─a.txt+└─.git └─.gitattributes └─.gitignore └─.k.txt └─dir-b/   └─.dir-c/     └─d.txt+  └─.git   └─.gitignore └─dir-e/   └─.dir-f/@@ -164,3 +234,30 @@ title: home └─type-a └─type-b/   └─y.txt+-- keep_clean_build.txt --+.+└─.domains+└─_redirects+└─index.html+└─keep-me/+  └─x.html+  └─y.txt+-- keep_negate_clean_build.txt --+.+└─.domains+└─.gitignore+└─.hidden/+  └─x.txt+└─_redirects+└─b.txt+└─dir/+  └─.domains+└─index.json+└─keep-me/+  └─y.txt+-- legacy_clean_build.txt --+.+└─.gitignore+└─.hidden/+  └─x.txt+└─index.html