captrack-pgo 0.1.0

Profile-guided capacity optimization for Rust collections — measure with dhat or captrack, propose data-driven Vec::with_capacity(N) values, apply in-place.
//! `string-reuse` subcommand — orchestrates `cargo dylint --fix` with
//! `CAPTRACK_PGO_STRING_REUSE=1` to rewrite `String` bindings that are fully
//! reassigned inside a loop into buffer-reusing `clear()` + `push_str(...)`
//! form.
//!
//! ## What it does
//!
//! 1. Pre-flight checks (cargo-dylint available, lint-path valid, workspace
//!    Cargo.toml exists).
//! 2. Snapshot all `.rs` files in the workspace before the run.
//! 3. Run:
//!    ```text
//!    CAPTRACK_PGO_STRING_REUSE=1 cargo dylint --path <lint-path> [--fix] \
//!        -- --manifest-path <workspace/Cargo.toml> [--allow-dirty]
//!    ```
//!    `CAPTRACK_PGO_PROFILE` and `CAPTRACK_PGO_INSTRUMENT` are explicitly
//!    removed from the child env so the capacity / instrument passes stay
//!    dormant and only the string-reuse pass fires.
//! 4. Diff before/after snapshots, write
//!    `target/captrack-pgo/last-string-reuse.json`.
//!
//! `--dry-run` runs `cargo dylint` WITHOUT `--fix` (suggestions appear in
//! stderr as warnings; files are not modified; no manifest is written).
//!
//! ## Note on suggestion applicability
//!
//! The string-reuse lint emits `MaybeIncorrect` suggestions (the rewrite is
//! correct under the lint's guards but warrants human review — e.g. RHS side
//! effects the reader relies on).  `cargo fix` (which `cargo dylint --fix`
//! wraps) applies `MachineApplicable` suggestions only by default; to apply
//! `MaybeIncorrect` ones it needs the nightly `--broken-code` behaviour.  In
//! practice run `--dry-run` first, review the suggestions, and apply them by
//! hand or with an editor; the manifest still records whatever `--fix`
//! changed so `undo` can revert it.

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,
};

// ──────────────────────────────────────────────────────────────────────────────
// Public arguments struct
// ──────────────────────────────────────────────────────────────────────────────

/// Arguments for the `string-reuse` subcommand, already resolved (paths
/// canonicalized, defaults applied).
pub struct LintStringReuseArgs {
    pub lint_path: PathBuf,
    pub workspace_root: PathBuf,
    pub dry_run: bool,
    pub allow_dirty: bool,
}

/// Manifest path for a `string-reuse` run:
/// `target/captrack-pgo/last-string-reuse.json`.
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")
}

/// Resolve the `--lint-path` argument for the `string-reuse` subcommand.
/// Delegates to the shared resolver from `lint_apply`.
pub fn resolve_lint_path(lint_path: Option<PathBuf>) -> Result<PathBuf> {
    match lint_path {
        Some(p) => Ok(p),
        None => resolve_default_lint_path(),
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// Core command
// ──────────────────────────────────────────────────────────────────────────────

/// Run the `string-reuse` subcommand.
pub fn run_lint_string_reuse(args: LintStringReuseArgs) -> Result<()> {
    // ── 1. Pre-flight ────────────────────────────────────────────────────────
    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()
        ));
    }

    // ── 2. Snapshot before ───────────────────────────────────────────────────
    let before_snapshots =
        snapshot_rs_files(&args.workspace_root).context("snapshot workspace before dylint")?;

    // ── 3. Build and (optionally) run cargo 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);
    // `--all-targets` ensures the lint runs on every compilation unit (lib,
    // bins, tests, benches, examples), not just the default lib/bin set —
    // mirrors `lint_instrument.rs`/`lint_apply.rs` (kept in sync
    // deliberately, see the fuller explanation there).
    cmd.arg("--all-targets");
    // `--allow-dirty` is a cargo-fix flag (consumed by the inner `cargo fix`
    // invocation, not by `cargo dylint`), so it MUST follow `--`.
    if args.allow_dirty {
        cmd.arg("--allow-dirty");
    }

    // Activate only the string-reuse pass; keep the other two dormant.
    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(());
    }

    // ── 4. Snapshot after and build manifest ─────────────────────────────────
    let (changed_files, total_bytes_changed): (Vec<LintFileEntry>, i64) =
        diff_snapshots(&before_snapshots);

    // Reuse the `Instrument` operation discriminant so `undo` (which is generic
    // over any `LintRunManifest`) can revert a string-reuse run out of the box.
    let manifest = LintRunManifest {
        version: 1,
        operation: Operation::Instrument,
        files: changed_files.clone(),
    };

    // ── 5. Write manifest ────────────────────────────────────────────────────
    let manifest_path = default_string_reuse_manifest_path(&args.workspace_root);
    write_manifest(&manifest, &manifest_path)?;

    // ── 6. Report ─────────────────────────────────────────────────────────────
    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(())
}