use std::path::PathBuf;
use anyhow::{anyhow, Context, Result};
use crate::lint_apply::{
check_cargo_dylint_available, check_lint_path, diff_snapshots, resolve_default_lint_path,
snapshot_rs_files, write_manifest, LintFileEntry, LintRunManifest, Operation,
};
pub struct LintStringReuseArgs {
pub lint_path: PathBuf,
pub workspace_root: PathBuf,
pub dry_run: bool,
pub allow_dirty: bool,
}
pub fn default_string_reuse_manifest_path(workspace_root: &std::path::Path) -> PathBuf {
workspace_root
.join("target")
.join("captrack-pgo")
.join("last-string-reuse.json")
}
pub fn resolve_lint_path(lint_path: Option<PathBuf>) -> Result<PathBuf> {
match lint_path {
Some(p) => Ok(p),
None => resolve_default_lint_path(),
}
}
pub fn run_lint_string_reuse(args: LintStringReuseArgs) -> Result<()> {
check_lint_path(&args.lint_path)?;
check_cargo_dylint_available()?;
let workspace_cargo_toml = args.workspace_root.join("Cargo.toml");
if !workspace_cargo_toml.is_file() {
return Err(anyhow!(
"workspace root '{}' does not contain a Cargo.toml",
args.workspace_root.display()
));
}
let before_snapshots =
snapshot_rs_files(&args.workspace_root).context("snapshot workspace before dylint")?;
let mut cmd = std::process::Command::new("cargo");
cmd.arg("dylint");
cmd.arg("--path");
cmd.arg(&args.lint_path);
if !args.dry_run {
cmd.arg("--fix");
}
cmd.arg("--");
cmd.arg("--manifest-path");
cmd.arg(&workspace_cargo_toml);
cmd.arg("--all-targets");
if args.allow_dirty {
cmd.arg("--allow-dirty");
}
cmd.env("CAPTRACK_PGO_STRING_REUSE", "1");
cmd.env_remove("CAPTRACK_PGO_PROFILE");
cmd.env_remove("CAPTRACK_PGO_INSTRUMENT");
cmd.stdin(std::process::Stdio::null());
if args.dry_run {
println!("captrack-pgo: dry-run — running without --fix (suggestions appear in stderr):");
println!(
" CAPTRACK_PGO_STRING_REUSE=1 cargo dylint --path {} -- --manifest-path {}",
args.lint_path.display(),
workspace_cargo_toml.display()
);
}
let status = cmd
.status()
.context("spawn cargo dylint — is cargo-dylint installed?")?;
if !status.success() {
return Err(anyhow!(
"cargo dylint exited with non-zero status: {:?}\n\
Files NOT modified; manifest NOT written.",
status.code()
));
}
if args.dry_run {
println!("(dry-run complete — no files modified, manifest not written)");
return Ok(());
}
let (changed_files, total_bytes_changed): (Vec<LintFileEntry>, i64) =
diff_snapshots(&before_snapshots);
let manifest = LintRunManifest {
version: 1,
operation: Operation::Instrument,
files: changed_files.clone(),
};
let manifest_path = default_string_reuse_manifest_path(&args.workspace_root);
write_manifest(&manifest, &manifest_path)?;
let n = changed_files.len();
println!(
"string-reuse: modified {} file{}, net {} byte{} changed",
n,
if n == 1 { "" } else { "s" },
total_bytes_changed,
if total_bytes_changed.abs() == 1 {
""
} else {
"s"
}
);
println!(" manifest: {}", manifest_path.display());
println!(
" revert with: captrack-pgo undo --manifest {}",
manifest_path.display()
);
Ok(())
}