From ed2e5facae0b46fc17198f59847c4dc1723123b7 Mon Sep 17 00:00:00 2001
From: Jochen Sprickerhof <jspricke@debian.org>
Date: Sun, 1 Jun 2025 17:53:40 +0200
Subject: [PATCH] Run apt-get distclean by default if available

This improves reproducibility as debrebuild can't recreate the apt
cache. It only works in trixie and currently makes autodep8 (#961138),
some R packages via dh-r (#1089197) and blends (#1104515) FTBFS. All
bugs have at least a proposed patch.
---
 lib/Sbuild/Build.pm | 12 ++++++++++++
 lib/Sbuild/Conf.pm  |  8 ++++++++
 2 files changed, 20 insertions(+)

diff --git a/lib/Sbuild/Build.pm b/lib/Sbuild/Build.pm
index 9798018e..82f0948c 100644
--- a/lib/Sbuild/Build.pm
+++ b/lib/Sbuild/Build.pm
@@ -2569,6 +2569,18 @@ sub build {
 		}
 	}
 
+	if (!$self->get_conf('DONT_CLEAN_APT_CACHE')) {
+		$self->log_subsubsection("clean up apt cache");
+		$session->run_command({
+			COMMAND => ["apt-get", "distclean"],
+			USER    => 'root',
+		});
+		if ($?) {
+			$self->log_error("cleaning the apt cache failed with $?\n");
+		   # Don't fail as distclean was only introduced in apt 2.7.8 (trixie).
+		}
+	}
+
 	$self->log_subsubsection("Check disk space");
 	chomp(my $current_usage
 		  = $session->read_command(
diff --git a/lib/Sbuild/Conf.pm b/lib/Sbuild/Conf.pm
index 941040e4..debb2265 100644
--- a/lib/Sbuild/Conf.pm
+++ b/lib/Sbuild/Conf.pm
@@ -975,6 +975,14 @@ $unshare_mmdebstrap_extra_args = [
 			DEFAULT => 0,
 			HELP    =>
 'Run in split mode?  In split mode, apt-get and dpkg are run on the host system, rather than inside the chroot.'
+		},
+		'DONT_CLEAN_APT_CACHE' => {
+			TYPE    => 'BOOL',
+			VARNAME => 'dont_clean_apt_cache',
+			GROUP   => 'Build options',
+			DEFAULT => 0,
+			HELP    =>
+'sbuild runs apt-get distclean by default to clean the apt package cache if the command is available. This makes sure that the build environment is not polluted by extra information but means that you need to run apt update before manually installing packages for debugging. You can disable this to save the extra call but remember to not use the informaiton from the apt cache. Also note that this silently files when the command is not available to be compatible with older releases.'
 		},
 		'CHECK_SPACE' => {
 			TYPE    => 'BOOL',
-- 
2.49.0

