Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -692,9 +692,20 @@ Notes and operational guidance:
reuses a previously cached entry of the other kind. This mirrors the `generate-hashes --depEdgesFile`
/ `get-impacted-targets --depEdgesFile` flow used by the CLI.

* Working-tree integrity is checked on every full generation. `serve` switches revisions with
`git checkout --force`, which removes the files a revision no longer tracks but leaves untracked
and ignored files where they are, so a generated `BUILD` file left behind by an earlier run would
* Workspace cleanup is opt-in for `serve` and `serve-multi`. With `--cleanWorkspace`, the server
runs `git clean -fdx` before every checkout, even when HEAD already matches the revision.
This deletes untracked and ignored files, so use a dedicated workspace and keep caches outside
it. The configured `--seed-filepaths` list and the seed files it names are preserved automatically.
Preserve other files with `--cleanWorkspaceExclude MODULE.bazel.lock,local.bazelrc`.
The comma-separated entries are exact workspace-relative file paths, not glob patterns;
absolute paths, parent traversal and empty entries are rejected. The option requires
`--cleanWorkspace` and applies to each workspace in multi-repository mode.
Exclusions protect files from cleanup, not from changes made by checkout.
Nested Git repositories are not forcibly removed. Without `--cleanWorkspace`, and for
one-shot CLI commands, cleanup is not performed.

* Working-tree integrity is checked on every full generation. Without cleanup, an untracked
`BUILD` file left behind by an earlier run can
be loaded by `bazel query` at every revision and its targets cached under revisions that do not
contain them -- and reported as impacted to consumers whose checkout has no such package. After
the query, every main-repository package it returned must have its `BUILD` or `BUILD.bazel` in
Expand Down Expand Up @@ -1048,6 +1059,10 @@ Options:

--gitPath <GIT_PATH>
[default: git]
--cleanWorkspace
Remove untracked and ignored files before checkout; configured seeds are preserved
--cleanWorkspaceExclude <CLEAN_WORKSPACE_EXCLUDE>
Exact workspace-relative files to preserve during cleanup, separated by commas
--port <PORT>
[default: 8080]
--requestTimeout <REQUEST_TIMEOUT>
Expand Down Expand Up @@ -1162,6 +1177,10 @@ Options:

--gitPath <GIT_PATH>
[default: git]
--cleanWorkspace
Remove untracked and ignored files before checkout; configured seeds are preserved
--cleanWorkspaceExclude <CLEAN_WORKSPACE_EXCLUDE>
Exact workspace-relative files to preserve during cleanup, separated by commas
--port <PORT>
[default: 8080]
--requestTimeout <REQUEST_TIMEOUT>
Expand Down
93 changes: 93 additions & 0 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,58 @@ impl Git {
self.tree_index(&tree)
}

/// Cleans a server workspace before checkout, including when HEAD already equals `sha`.
pub fn checkout_clean(&self, sha: &str, preserved: &BTreeSet<PathBuf>) -> Result<()> {
let workspace = fs::canonicalize(&self.workspace)
.context("failed to resolve workspace for git clean")?;
let mut args = vec![OsString::from("clean"), OsString::from("-fdx")];
for path in preserved {
let path = if path.is_absolute() {
path.clone()
} else {
workspace.join(path)
};
let relative = workspace_relative_file(&workspace, &path).or_else(|| {
let relative = path.strip_prefix(&workspace).ok()?;
if !relative
.components()
.all(|component| matches!(component, std::path::Component::Normal(_)))
{
return None;
}
Some(relative.to_str()?.to_owned())
});
let Some(relative) = relative else {
if path.starts_with(&workspace) {
bail!(
"failed to resolve preserved path for git clean: {}",
path.display()
);
}
continue;
};
if path.is_dir() || relative.contains(['\n', '\r']) {
bail!("git clean exclusions must name files: {}", path.display());
}
let mut pattern = String::from("/");
for character in relative.chars() {
if matches!(character, '\\' | '*' | '?' | '[' | ']' | ' ') {
pattern.push('\\');
}
pattern.push(character);
}
args.extend([OsString::from("-e"), OsString::from(pattern)]);
}
let output = self.stdout(args)?;
if !output.is_empty() {
eprintln!(
"[Info] git clean: {}",
String::from_utf8_lossy(&output).trim()
);
}
self.checkout(sha)
}

/// Checks `sha` out, clearing a stale `index.lock` a killed git left behind once.
pub fn checkout(&self, sha: &str) -> Result<()> {
if let Ok(output) = self.output(["rev-parse", "HEAD"]) {
Expand Down Expand Up @@ -414,6 +466,47 @@ mod tests {
assert!(missing_binary.output::<[&str; 0], &str>([]).is_err());
}

#[test]
fn checkout_clean_removes_untracked_and_ignored_files_at_same_revision() {
let (repo, git) = repository();
let head = git.resolve_sha("HEAD").unwrap();
fs::create_dir_all(repo.path().join("ignored/package")).unwrap();
fs::write(repo.path().join("ignored/package/BUILD"), "").unwrap();
fs::write(repo.path().join("untracked.txt"), "").unwrap();
git.checkout_clean(&head, &BTreeSet::new()).unwrap();
assert!(!repo.path().join("ignored").exists());
assert!(!repo.path().join("untracked.txt").exists());
assert_eq!(
fs::read_to_string(repo.path().join("file.txt")).unwrap(),
"one"
);
assert_eq!(git.resolve_sha("HEAD").unwrap(), head);
}

#[test]
fn checkout_clean_preserves_only_exact_seed_paths_and_propagates_cancellation() {
let (repo, git) = repository();
fs::create_dir_all(repo.path().join("ignored")).unwrap();
let seed = repo.path().join("ignored/seed[1]*.txt");
fs::write(&seed, "seed").unwrap();
fs::write(repo.path().join("ignored/seed1other.txt"), "remove").unwrap();
fs::write(repo.path().join("seed-list.txt"), "ignored/seed[1]*.txt").unwrap();
let preserved = BTreeSet::from([seed.clone(), PathBuf::from("seed-list.txt")]);
let head = git.resolve_sha("HEAD").unwrap();
git.checkout_clean(&head, &preserved).unwrap();
assert!(seed.exists());
assert!(repo.path().join("seed-list.txt").exists());
assert!(!repo.path().join("ignored/seed1other.txt").exists());
let token = Arc::new(Cancellation::new());
token.cancel();
fs::write(repo.path().join("not-cleaned.txt"), "").unwrap();
assert!(git
.with_cancellation(Some(token))
.checkout_clean(&head, &preserved)
.is_err());
assert!(repo.path().join("not-cleaned.txt").exists());
}

#[test]
fn working_tree_snapshot_matches_head_when_clean_and_captures_edits() {
let (repo, git) = repository();
Expand Down
90 changes: 90 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,18 @@ struct ServeArgs {
#[arg(long = "gitPath", default_value = "git")]
git_path: PathBuf,

/// Remove untracked and ignored files before checkout; configured seeds are preserved
#[arg(long = "cleanWorkspace")]
clean_workspace: bool,

/// Exact workspace-relative files to preserve during cleanup, separated by commas
#[arg(
long = "cleanWorkspaceExclude",
value_delimiter = ',',
requires = "clean_workspace"
)]
clean_workspace_exclude: Vec<PathBuf>,

#[arg(long, default_value_t = 8080)]
port: u16,

Expand Down Expand Up @@ -1366,6 +1378,15 @@ impl ServeArgs {
hash_options,
repositories,
git_path: self.git_path.clone(),
clean_workspace: self.clean_workspace,
clean_workspace_exclude: self.clean_workspace_exclude.iter().cloned().collect(),
seed_filepaths_file: self
.hashing
.seed_filepaths
.as_ref()
.map(fs::canonicalize)
.transpose()
.context("failed to resolve seed file list")?,
port: self.port,
request_timeout: Duration::from_secs(self.request_timeout),
cache_dir: self.cache_dir.clone(),
Expand Down Expand Up @@ -1413,6 +1434,7 @@ impl ServeArgs {
compute_slot_demand_average_window,
};
bazel_diff::server::validate_partial_graph(&config)?;
bazel_diff::server::validate_workspace_clean(&config)?;
bazel_diff::server::repositories(&config)?;
Ok(config)
}
Expand Down Expand Up @@ -1863,6 +1885,74 @@ mod tests {
.is_err());
}

#[test]
fn serve_config_parses_opt_in_cleanup_and_comma_separated_exclusions() {
for multi in [false, true] {
let mut arguments = if multi {
vec!["bazel-diff", "serve-multi", "--repo", "test=/tmp/ws"]
} else {
vec!["bazel-diff", "serve", "--workspacePath", "/tmp/ws"]
};
arguments.extend(["--cacheDir", "/tmp/cache"]);
let config = match parse(&arguments).command {
Commands::Serve(args) => args.to_config(false).unwrap(),
Commands::ServeMulti(args) => args
.serve
.to_config_with_repositories(false, args.repositories)
.unwrap(),
_ => panic!("expected serve"),
};
assert!(!config.clean_workspace);
assert!(config.clean_workspace_exclude.is_empty());
arguments.extend([
"--cleanWorkspace",
"--cleanWorkspaceExclude",
"MODULE.bazel.lock,local.bazelrc",
]);
let config = match parse(&arguments).command {
Commands::Serve(args) => args.to_config(false).unwrap(),
Commands::ServeMulti(args) => args
.serve
.to_config_with_repositories(false, args.repositories)
.unwrap(),
_ => panic!("expected serve"),
};
assert!(config.clean_workspace);
assert_eq!(
config.clean_workspace_exclude,
BTreeSet::from([
PathBuf::from("MODULE.bazel.lock"),
PathBuf::from("local.bazelrc"),
])
);
}
}

#[test]
fn serve_config_rejects_invalid_cleanup_exclusions() {
let base = [
"bazel-diff",
"serve",
"--workspacePath",
"/tmp/ws",
"--cacheDir",
"/tmp/cache",
];
let mut without_cleanup = base.to_vec();
without_cleanup.extend(["--cleanWorkspaceExclude", "MODULE.bazel.lock"]);
assert!(Cli::try_parse_from(without_cleanup).is_err());
for value in ["/tmp/file", "../file", "dir/../file", ".", "dir/", "a,,b"] {
let mut arguments = base.to_vec();
arguments.extend(["--cleanWorkspace", "--cleanWorkspaceExclude", value]);
if let Ok(cli) = Cli::try_parse_from(arguments) {
let Commands::Serve(args) = cli.command else {
panic!("expected serve");
};
assert!(args.to_config(false).is_err(), "{value}");
}
}
}

#[test]
fn serve_config_parses_pruning_s3_and_tracking_flags() {
let cli = parse(&[
Expand Down
80 changes: 79 additions & 1 deletion src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@ pub struct ServerConfig {
/// `hash_options.bazel.workspace`, named [`DEFAULT_REPOSITORY`].
pub repositories: Vec<Repository>,
pub git_path: PathBuf,
pub clean_workspace: bool,
/// Exact workspace-relative file paths, not Git ignore patterns.
pub clean_workspace_exclude: BTreeSet<PathBuf>,
/// The seed list itself, retained alongside its inputs when cleaning the workspace.
pub seed_filepaths_file: Option<PathBuf>,
pub port: u16,
pub request_timeout: Duration,
pub cache_dir: PathBuf,
Expand Down Expand Up @@ -1259,6 +1264,7 @@ pub fn serve(config: &ServerConfig) -> Result<()> {
bail!("serve does not support --isolatedDependencyRoot={root}");
}
validate_partial_graph(config)?;
validate_workspace_clean(config)?;
let repositories = repositories(config)?;
fs::create_dir_all(&config.cache_dir)?;
let remote = RemoteCache::new(config)?;
Expand Down Expand Up @@ -2376,7 +2382,36 @@ fn classify_revisions(
}

fn checkout(state: &State, sha: &str) -> Result<()> {
state.git().checkout(sha)
if !state.config.clean_workspace {
return state.git().checkout(sha);
}
validate_workspace_clean(&state.config)?;
let mut preserved = state.config.hash_options.seed_filepaths.clone();
preserved.extend(state.config.seed_filepaths_file.iter().cloned());
preserved.extend(state.config.clean_workspace_exclude.iter().cloned());
state.git().checkout_clean(sha, &preserved)
}

pub fn validate_workspace_clean(config: &ServerConfig) -> Result<()> {
if !config.clean_workspace && !config.clean_workspace_exclude.is_empty() {
bail!("--cleanWorkspaceExclude requires --cleanWorkspace");
}
for path in &config.clean_workspace_exclude {
if path.as_os_str().is_empty()
|| path
.to_str()
.is_none_or(|value| value.ends_with('/') || value.contains(['\n', '\r']))
|| !path
.components()
.all(|component| matches!(component, std::path::Component::Normal(_)))
{
bail!(
"--cleanWorkspaceExclude expects workspace-relative file paths without '.' or '..': {}",
path.display()
);
}
}
Ok(())
}

fn git(state: &State, args: &[String]) -> Result<()> {
Expand Down Expand Up @@ -2651,6 +2686,9 @@ mod tests {
},
repositories: Vec::new(),
git_path: PathBuf::from("git"),
clean_workspace: false,
clean_workspace_exclude: BTreeSet::new(),
seed_filepaths_file: None,
port: 0,
request_timeout: Duration::ZERO,
cache_dir: PathBuf::from("."),
Expand Down Expand Up @@ -4478,6 +4516,46 @@ esac
assert!(git_output(&bad, &[]).is_err());
}

#[test]
fn server_checkout_cleans_same_revision_and_preserves_seed_list_and_inputs() {
let (repo, _, second) = initialize_git_repo();
let cache = tempfile::tempdir().unwrap();
let mut state = state_for_repo(repo.path(), cache.path(), false);
let seed_list = repo.path().join("seed-list.txt");
let seed = repo.path().join("seed.txt");
fs::write(&seed_list, "seed.txt").unwrap();
fs::write(&seed, "seed").unwrap();
fs::write(repo.path().join("stale.txt"), "remove").unwrap();
let config = &mut Arc::get_mut(&mut state).unwrap().config;
config.seed_filepaths_file = Some(seed_list.clone());
config.clean_workspace = true;
config.hash_options.seed_filepaths.insert(seed.clone());
let lockfile = repo.path().join("MODULE.bazel.lock");
fs::write(&lockfile, "{}").unwrap();
config
.clean_workspace_exclude
.insert(PathBuf::from("MODULE.bazel.lock"));
config
.clean_workspace_exclude
.insert(PathBuf::from("not-created-yet/file.txt"));
checkout(&state, &second).unwrap();
assert!(seed_list.exists());
assert!(seed.exists());
assert!(lockfile.exists());
assert!(!repo.path().join("stale.txt").exists());
}

#[test]
fn server_checkout_without_cleanup_keeps_untracked_files() {
let (repo, _, second) = initialize_git_repo();
let cache = tempfile::tempdir().unwrap();
let state = state_for_repo(repo.path(), cache.path(), false);
let file = repo.path().join("stale.txt");
fs::write(&file, "keep").unwrap();
checkout(&state, &second).unwrap();
assert!(file.exists());
}

#[test]
fn targeted_fetch_tries_each_remote_and_handles_missing_remotes() {
let root = tempfile::tempdir().unwrap();
Expand Down
Loading
Loading