diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index a14c8e681..9d06206e9 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1945,7 +1945,7 @@ Agent runs fetch patch content as per-file blobs (v5.0 removed `--download-mode` **Vendored artifact repair (v5.0)**: `repair` checks the committed artifact and downloads a replacement for the same UUID into a temporary location. Before replacement it checks transfer integrity, patched-member hashes, and the original ledger's SHA-256 and size (file artifacts) or complete file inventory (directory artifacts). JVM repair also reproduces and checks the recorded repository metadata. Different downloaded bytes or inventories are refused; the old files, ledger and lockfiles remain intact. No installed package or patch blobs are required, and none are used to construct a replacement. Missing directory inventories cannot establish an exact replacement and require explicit re-vendoring. -Successful redownloads retain the JSON `rebuilt` action and `summary.rebuilt` for compatibility, with `details.redownloaded`. Dry runs report `details.wouldRedownload` without writing. Human output says “Redownloaded”. Failed repair downloads report `vendor_artifact_redownload_failed`; the same failure during `vendor` reports `vendor_redownload_failed`. Offline repair refuses missing or corrupt artifacts even if installed copies and patch blobs exist. Revert and explicitly vendor again to adopt different bytes; repair never refreshes fingerprints or rewrites lockfiles to accept them. +Successful redownloads retain the JSON `rebuilt` action and `summary.rebuilt` for compatibility, with `details.redownloaded`. Dry runs report `details.wouldRedownload` without writing. Human output says “Redownloaded”, from `repair` and from the `vendor` run that restores a copy before it reports the package as already vendored. A wet run that redownloaded an artifact, or wrote the `.gitignore` / `.gitattributes` beside one (`vendor_git_metadata_written`), left files under `.socket/vendor/` that are not committed yet: `repair` ends with a “Next steps:” block that names that commit, and so does a `vendor` run that vendored nothing new, whose summary then reads “restored … files under .socket/vendor/” where it would say “nothing to do”. Failed repair downloads report `vendor_artifact_redownload_failed`; the same failure during `vendor` reports `vendor_redownload_failed`. Offline repair refuses missing or corrupt artifacts even if installed copies and patch blobs exist. Revert and explicitly vendor again to adopt different bytes; repair never refreshes fingerprints or rewrites lockfiles to accept them. **The ledger is not rebuilt from lockfiles (v5.0).** A lockfile reference to `.socket/vendor///...` with NO ledger entry (state.json deleted or never committed) @@ -2918,6 +2918,7 @@ command's integration tests check its output. | `redirect_yarn_classic_dep_manifest_unlocked` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` depends on a descriptor no `yarn.lock` block is keyed by and that the sub-maps of the registry blocks being pinned don't already name (yarn keys those by the packument's ranges, #1578). yarn 1 installs only what the lock names, so a pin would install the patched package without that dependency (#591). The dep is not pinned and never confirmed; the lock is left as it was. The served tarball is read on every run, so a pin an earlier release wrote without this check (#1462) gets the same warning and is never confirmed either; it stays in the lock until the dependency is locked or the pin is rolled back. Same remedy as `vendor_dep_manifest_unlocked`. | | `redirect_yarn_classic_dep_manifest_rewritten` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` declares other dependencies than the pinned block's sub-maps, every descriptor already locked; the block's `dependencies:` / `optionalDependencies:` sub-maps are rewritten to match, in the shape yarn 1 writes for that manifest (#591, #1558). | | `vendor_artifact_gitignored` | `failed` | vendor (vlt, the npm-family tarball flavors — npm, pnpm, bun, yarn classic, yarn berry — NuGet, every PyPI flavor, gems, and the JVM trees of Maven, Gradle, sbt and scala-cli): inside a git work tree, `git check-ignore --no-index` reports the new artifact's uuid directory (JVM: its tree root, such as `.socket/vendor/maven2`) as ignored by a rule its own `.gitignore` cannot override (such as a root `.socket/` or `vendor/` rule; the detail names the rule). Remedy: drop that rule for `.socket/vendor/`. Refused before any write, dry run included. A file rule such as `*.tgz`, `*.nupkg`, `*.whl` or `*.jar` is overridden by the `!*` `.gitignore` vendoring writes into the uuid dir or tree root (PyPI's uuid dir also gets the `.gitattributes` that unsets a `*.whl filter=lfs` rule); if a written tarball, directory payload, nupkg or wheel, or a file of a gem's copy, still reads as ignored, the run refuses and removes the uuid dir it created. | +| `vendor_git_metadata_written` | `skipped` (advisory; human: `Note: …`) | vendor / scan / get `--mode vendored` (gem) and `repair` (gem and the npm family): a run over a copy that was already in place wrote its `/.gitignore` or `/.gitattributes`, which were missing (a gem that 5.1 or earlier vendored has neither) or changed. The detail names both files. The package is still reported as already vendored; the human summary says files were restored instead of "nothing to do", and "Next steps:" names the commit of `.socket/vendor/`. A dry run writes nothing and reports nothing. | | `vendor_gem_copy_gitignored` | warning | vendor (a gem vendored as its own directory by 5.1 or earlier): the in-sync run that writes the missing `/.gitignore` and `.gitattributes` asks git about every file of the copy, and a `.gitignore` the gem ships, which that release kept as shipped, still keeps a file out of the commit (the detail names the rule and the file), so a fresh clone would fail `vendor --check` with `vendor_inventory_mismatch`. The copy and the ledger are left as they are. Remedy: `git add -f ` and commit. Said once, by the run that writes the pair. | | `vendor_gem_gitignore_neutralized` | warning | vendor / scan / get `--mode vendored` (gem): the patched gem ships a `.gitignore` inside its own tree whose rules would keep git from committing files of the vendored copy, so the run emptied it in the copy: every one in a platform gem's tree, and in a gem's own tree each one whose rules match a file of the copy. The detail names the gem and the emptied files (three, then a count of the rest). The gem is vendored; commit the copy. | | `vendor_artifact_gitignore_unchecked` | warning | vendor (vlt, the npm-family tarball flavors, NuGet, every PyPI flavor and gems): git is installed but could not answer the ignore check for the written vendored directory (it failed to start, ran past 30 s, or `rev-parse` / `check-ignore` exited with an error); the package is vendored and the detail names what failed. Remedy: make sure no ignore rule covers `.socket/` before committing. Git absent, or a project outside any work tree, raises nothing. | diff --git a/crates/socket-patch-cli/src/commands/repair.rs b/crates/socket-patch-cli/src/commands/repair.rs index 25871f02c..64a8b133c 100644 --- a/crates/socket-patch-cli/src/commands/repair.rs +++ b/crates/socket-patch-cli/src/commands/repair.rs @@ -519,6 +519,24 @@ fn format_cleanup_summary(results: &[(ArtifactNoun, CleanupResult)], dry_run: bo format_all_in_use(&checked, total) } +/// Did the vendored leg of a wet run restore files under `.socket/vendor/` +/// (`events` are its own)? A vendored artifact downloaded again (a +/// `rebuilt` event with `details.redownloaded`, which a dry run never +/// records), or the `.gitignore` / `.gitattributes` beside one (the +/// `vendor_git_metadata_written` advisory). Either leaves files to commit. +/// The other `rebuilt` events (a stray file swept from a JVM tree, a Bun +/// workspace member's copy) are no such restore. +fn restored_vendor_files(events: &[PatchEvent]) -> bool { + events.iter().any(|e| { + let redownloaded = || { + let details = e.details.as_ref(); + details.is_some_and(|d| d["redownloaded"] == serde_json::json!(true)) + }; + (e.action == PatchAction::Rebuilt && redownloaded()) + || e.error_code.as_deref() == Some(socket_patch_core::vendor::GIT_METADATA_WRITTEN) + }) +} + /// The closing line of a human repair run. `offline_unrestored` counts the /// missing or corrupt blobs `--offline` left as they were. `other_failure` /// is a failure recorded elsewhere in the run (a vendored artifact that @@ -893,6 +911,14 @@ async fn repair_inner( } println!("{line}"); } + // Files restored under `.socket/vendor/` are in this checkout + // alone until they are committed: a fresh clone still fails + // `vendor --check` (#2471). + if restored_vendor_files(&env.events[vendored_since..]) { + for line in crate::ui::next_steps_restored() { + println!("{line}"); + } + } } // Translate the aggregate counts into envelope events. `repair` @@ -1508,6 +1534,29 @@ mod tests { ); } + /// #2471: the commit step follows a run whose vendored leg restored + /// files, and no other. + #[test] + fn restored_vendor_files_reads_rebuilds_and_written_metadata() { + let purl = "pkg:gem/rack@3.2.9"; + let rebuilt = PatchEvent::new(PatchAction::Rebuilt, purl) + .with_details(serde_json::json!({"path": "p", "redownloaded": true})); + // A stray file swept from a JVM tree: nothing restored. + let swept = PatchEvent::new(PatchAction::Rebuilt, purl) + .with_details(serde_json::json!({"unindexedRemoved": ["x"]})); + let written = PatchEvent::new(PatchAction::Skipped, purl).with_reason( + socket_patch_core::vendor::GIT_METADATA_WRITTEN, + "restored the pair", + ); + let preview = PatchEvent::new(PatchAction::Verified, purl); + let other = + PatchEvent::new(PatchAction::Skipped, purl).with_reason("cargo_version_tagged", "x"); + assert!(restored_vendor_files(std::slice::from_ref(&rebuilt))); + assert!(restored_vendor_files(&[other.clone(), written])); + assert!(!restored_vendor_files(&[preview, other, swept])); + assert!(!restored_vendor_files(&[])); + } + #[test] fn final_line_reflects_failures_and_dry_run() { assert_eq!(format_final_line(0, 0, false, false), "Repair complete."); diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index fa7cdac29..6a26e1fb2 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -840,7 +840,8 @@ fn advisory_tier(code: &str) -> AdvisoryTier { | "vendor_would_revert_redirect" | "vendor_takeover_reverted_redirect" | "cargo_wiring_migrated" - | "cargo_version_tagged" => AdvisoryTier::Note, + | "cargo_version_tagged" + | vendor::GIT_METADATA_WRITTEN => AdvisoryTier::Note, _ => AdvisoryTier::Warning, } } @@ -928,6 +929,26 @@ fn vendored_packages(env: &Envelope) -> u32 { })) } +/// The packages whose files under `.socket/vendor/` a wet run restored +/// without vendoring them anew: a copy the run downloaded again (the +/// `rebuilt` event), or the uuid dir's `.gitignore` / `.gitattributes` +/// (the `vendor_git_metadata_written` advisory). Both leave files to +/// commit behind a package the run reports as already vendored (#2471). +/// The events of one package carry one purl, so each counts once. +fn restored_packages(env: &Envelope) -> u32 { + let restored = |e: &&PatchEvent| { + e.action == PatchAction::Rebuilt + || e.error_code.as_deref() == Some(vendor::GIT_METADATA_WRITTEN) + }; + let purls: HashSet<&str> = env + .events + .iter() + .filter(restored) + .filter_map(|e| e.purl.as_deref()) + .collect(); + purls.len() as u32 +} + /// Per-outcome counts behind the human vendor summary line. #[derive(Debug, Default, Clone, PartialEq, Eq)] struct VendorTally { @@ -940,6 +961,11 @@ struct VendorTally { /// Every other skip. skipped: u32, failed: u32, + /// Packages whose files under `.socket/vendor/` this run restored + /// without vendoring them anew ([`restored_packages`]). They are + /// counted by their outcome as well (as a rule, already vendored), and + /// the summary must not call the run a no-op. + restored: u32, } impl VendorTally { @@ -977,6 +1003,7 @@ impl VendorTally { .summary .failed .saturating_sub(repeats(PatchAction::Failed)), + restored: restored_packages(env), } } } @@ -991,7 +1018,15 @@ fn format_vendor_summary(dry_run: bool, t: &VendorTally) -> String { } else { format!("All {} packages are", t.already) }; - return format!("{all} already vendored; nothing to do."); + // A run that restored files of a vendored copy did something, + // and left files to commit. + return match t.restored { + 0 => format!("{all} already vendored; nothing to do."), + _ if t.already == 1 => { + format!("{all} already vendored; restored its files under .socket/vendor/.") + } + n => format!("{all} already vendored; restored files of {n} under .socket/vendor/."), + }; } let verb = if dry_run { "Would vendor" } else { "Vendored" }; let mut line = format!( @@ -1008,6 +1043,13 @@ fn format_vendor_summary(dry_run: bool, t: &VendorTally) -> String { line.push_str(&format!("; {n} {what}")); } } + // A clause of its own: the package may be one the run then failed. + if t.restored > 0 { + line.push_str(&format!( + "; restored files of {} under .socket/vendor/", + t.restored + )); + } line.push('.'); line } @@ -4814,6 +4856,16 @@ pub(crate) async fn vendor_records_reusing( for warning in &warnings { record_warning(env, candidate, warning, common); } + // Said as `repair` says it: the package is + // reported as already vendored below, and the + // files this put back are to be committed (#2471). + if !common.json && !common.silent { + println!( + "Redownloaded {} ({})", + normalize_purl(candidate), + entry.artifact.path + ); + } env.record(PatchEvent::new(PatchAction::Rebuilt, candidate.clone()).with_details(serde_json::json!({"redownloaded": true, "path": entry.artifact.path}))); } Err(detail) => { @@ -5409,6 +5461,16 @@ fn print_vendor_closing( println!("{line}"); } } + // Nothing was vendored anew, but files of a vendored copy were + // restored: the lockfiles and the installed packages are as they were, + // and the restored files still have to be committed (#2471). A run + // that vendored something names `.socket/vendor/` in its own commit + // step below. + if env.summary.applied == 0 && tally.restored > 0 && !common.dry_run && next_steps { + for line in crate::ui::next_steps_restored() { + println!("{line}"); + } + } if env.summary.applied > 0 && !common.dry_run && next_steps { // pnpm >=11 reads `overrides` ONLY from pnpm-workspace.yaml (the // package.json `pnpm.overrides` mirror is ignored), so pnpm-wired @@ -9557,9 +9619,106 @@ mod ui_format_tests { not_installed, skipped, failed, + restored: 0, } } + /// #2471: a run that restored files of a copy that was already vendored + /// (its uuid dir's git metadata, or the copy downloaded again) is not + /// a no-op: the summary says what it restored, in every shape of the + /// line. + #[test] + fn vendor_summary_names_restored_files_instead_of_nothing_to_do() { + let restored = |already, restored| VendorTally { + restored, + ..tally(0, already, 0, 0, 0) + }; + assert_eq!( + format_vendor_summary(false, &restored(3, 3)), + "All 3 packages are already vendored; restored files of 3 under .socket/vendor/." + ); + assert_eq!( + format_vendor_summary(false, &restored(3, 1)), + "All 3 packages are already vendored; restored files of 1 under .socket/vendor/." + ); + assert_eq!( + format_vendor_summary(false, &restored(1, 1)), + "1 package is already vendored; restored its files under .socket/vendor/." + ); + let mixed = VendorTally { + restored: 1, + ..tally(1, 2, 0, 0, 1) + }; + assert_eq!( + format_vendor_summary(false, &mixed), + "Vendored 1 package; 2 already vendored; 1 failed; restored files of 1 under \ + .socket/vendor/." + ); + // Restored, then refused: no package is in sync, and the restore + // is still said. + let failed = VendorTally { + restored: 1, + ..tally(0, 0, 0, 0, 1) + }; + assert_eq!( + format_vendor_summary(false, &failed), + "Vendored 0 packages; 1 failed; restored files of 1 under .socket/vendor/." + ); + } + + /// The tally counts a package once however many of its events say + /// files were restored: the `rebuilt` event of a copy downloaded again + /// and the advisory for the uuid dir's git metadata. A gem vendored as + /// platform gems carries both under the patch it was vendored through. + #[test] + fn tally_counts_each_package_with_restored_files_once() { + let written = |env: &mut Envelope, purl: &str| { + let detail = vendor::git_metadata_written_detail(".socket/vendor/gem/u", "x@1"); + push_advisory_event( + env, + purl, + &VendorWarning::new(vendor::GIT_METADATA_WRITTEN, detail), + ); + }; + let in_sync = |env: &mut Envelope, purl: &str| { + env.record( + PatchEvent::new(PatchAction::Skipped, purl) + .with_reason("already_vendored", "in sync"), + ); + }; + let mut env = Envelope::new(Command::Vendor); + // Downloaded again and given its metadata: one package. + env.record(PatchEvent::new(PatchAction::Rebuilt, "pkg:gem/a@1")); + written(&mut env, "pkg:gem/a@1"); + in_sync(&mut env, "pkg:gem/a@1"); + // Metadata alone. + written(&mut env, "pkg:gem/b@1"); + in_sync(&mut env, "pkg:gem/b@1"); + // Untouched. + in_sync(&mut env, "pkg:gem/c@1"); + let counted = VendorTally::from_envelope(&env, false, 0); + assert_eq!( + counted, + VendorTally { + restored: 2, + ..tally(0, 3, 0, 0, 0) + } + ); + assert_eq!( + format_vendor_summary(false, &counted), + "All 3 packages are already vendored; restored files of 2 under .socket/vendor/." + ); + } + + /// The advisory is a note (the run did its job), not a warning. + #[test] + fn git_metadata_written_prints_as_a_note() { + let detail = vendor::git_metadata_written_detail(".socket/vendor/gem/u", "rack@3.2.9"); + let line = format_advisory(vendor::GIT_METADATA_WRITTEN, &detail, false).unwrap(); + assert!(line.starts_with("Note: restored .socket/vendor/gem/u/.gitignore and ")); + assert!(line.ends_with("Commit them with the rest of .socket/vendor/")); + } + #[test] fn vendor_summary_singular_plural_and_zero() { assert_eq!( diff --git a/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs b/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs index 4a2056dd7..771082349 100644 --- a/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs +++ b/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs @@ -518,22 +518,39 @@ impl VendoredBackend<'_> { && (health == ArtifactHealth::Healthy || health.is_workspace_copy_issue()) { let metadata = async { - vendor::redownload::restore_npm_uuid_metadata(&entry, &common.cwd).await?; - vendor::redownload::restore_gem_uuid_metadata(&entry, &common.cwd).await + let npm = + vendor::redownload::restore_npm_uuid_metadata(&entry, &common.cwd).await?; + let gem = + vendor::redownload::restore_gem_uuid_metadata(&entry, &common.cwd).await?; + Ok::(npm || gem) + }; + let written = match metadata.await { + Ok(written) => written, + Err(e) => { + fail( + env, + common.json, + purl, + "vendor_artifact_unrepairable", + format!("cannot restore the vendored dir's git metadata: {e}"), + ); + continue; + } }; - if let Err(e) = metadata.await { - fail( - env, - common.json, - purl, - "vendor_artifact_unrepairable", - format!("cannot restore the vendored dir's git metadata: {e}"), - ); - continue; - } if !npm_artifact_committable(common, env, purl, &entry).await { continue; } + // Two files the project has yet to commit, behind an + // artifact that is otherwise healthy: named, or the run + // reads as one that changed nothing (#2471). Said once git + // is known to commit them. + let uuid_dir = vendor::path::vendor_uuid_dir_rel(&entry.ecosystem, &entry.uuid); + if let (true, Some(uuid_dir)) = (written, uuid_dir) { + let detail = + vendor::git_metadata_written_detail(&uuid_dir, &normalize_purl(purl)); + let written = VendorWarning::new(vendor::GIT_METADATA_WRITTEN, detail); + record_warning(env, purl, &written, common); + } } if health == ArtifactHealth::Healthy || health.is_workspace_copy_issue() { let mut healed = entry.clone(); diff --git a/crates/socket-patch-cli/src/ui/mod.rs b/crates/socket-patch-cli/src/ui/mod.rs index c04662c60..1b0ce4b6f 100644 --- a/crates/socket-patch-cli/src/ui/mod.rs +++ b/crates/socket-patch-cli/src/ui/mod.rs @@ -33,8 +33,8 @@ pub use prompt::{select_from, select_one, SelectError}; pub(crate) use status::StatusLine; pub(crate) use text::{ agent_next_steps, folded, manifest_error_message, next_steps, next_steps_installed, - package_names, plural, printable, sentence_case, shell_word, short_uuid, sweep_failure, - truncate, worst_and_ids, + next_steps_restored, package_names, plural, printable, sentence_case, shell_word, short_uuid, + sweep_failure, truncate, worst_and_ids, }; /// [`text::no_patches_message`] for this run: the manifest path is named diff --git a/crates/socket-patch-cli/src/ui/text.rs b/crates/socket-patch-cli/src/ui/text.rs index eb67e05ec..e42010cc0 100644 --- a/crates/socket-patch-cli/src/ui/text.rs +++ b/crates/socket-patch-cli/src/ui/text.rs @@ -112,6 +112,19 @@ pub(crate) fn next_steps_installed(commit: &str, installed: &str, extra: &[Strin numbered_next_steps(&steps) } +/// What a run commits when it restored files under `.socket/vendor/` and +/// changed nothing else: a copy `vendor` or `repair` downloaded again, or +/// the `.gitignore` / `.gitattributes` beside one (#2471). +pub(crate) const COMMIT_RESTORED_VENDOR_FILES: &str = + "Commit .socket/vendor/: the files this run restored there are not in the repository yet."; + +/// The "Next steps:" block of a vendored run that vendored nothing new +/// but restored files under `.socket/vendor/`: the commit alone, since +/// the lockfiles and the installed packages are as they were. +pub(crate) fn next_steps_restored() -> Vec { + numbered_next_steps(&[COMMIT_RESTORED_VENDOR_FILES.to_string()]) +} + /// `Next steps:` over `steps`, numbered from 1. fn numbered_next_steps(steps: &[String]) -> Vec { let mut out = vec!["Next steps:".to_string()]; diff --git a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs index 79487a879..e7e9f8166 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -4148,28 +4148,30 @@ fn git(cwd: &Path, args: &[&str]) -> String { String::from_utf8_lossy(&out.stdout).into_owned() } -/// A project whose `.gitignore` has a rule that matches a file the gem -/// ships: diff-lcs 1.5.1 ships `.rspec`, which GitHub's stock -/// `Rails.gitignore` names. The vendoring checkout holds the file either -/// way, so the proof is a real `git commit` and `git clone`: the clone -/// holds the whole copy, `vendor --check` passes there as it does in the -/// checkout that vendored, and a frozen `bundle install` loads the patched -/// gem. -#[test] -#[ignore = "host capstone: shells out to a real bundler >= 1.17; the unpinned `test` job \ - skips it, the e2e job runs it with a pinned toolchain via --ignored"] -fn gem_vendor_file_a_project_rule_ignores_reaches_a_git_clone() { - const GEM: &str = "diff-lcs"; - const VERSION: &str = "1.5.1"; - const RB: &str = "lib/diff/lcs.rb"; - // Lines of GitHub's `Rails.gitignore`, and the gem home of this test. +/// diff-lcs 1.5.1, which ships a `.rspec`: a file GitHub's stock +/// `Rails.gitignore` names. +const LCS: &str = "diff-lcs"; +const LCS_VERSION: &str = "1.5.1"; +const LCS_RB: &str = "lib/diff/lcs.rb"; + +/// A git checkout whose `.gitignore` (lines of GitHub's `Rails.gitignore`, +/// and the gem home of the test) has a rule that matches a file the gem +/// ships, with diff-lcs installed, patched and vendored. `None` (message +/// printed) without a bundler, git or the registry. +struct VendoredLcs { + tmp: tempfile::TempDir, + proj: PathBuf, + /// `bundle config set --local path vendor/bundle`, as this bundler + /// spells it. + path_config: Vec, +} + +fn vendored_lcs_project(tag: &str) -> Option { const RULES: &str = "*.rbc\n.rspec\n/log/*\n/coverage/\n/vendor/bundle\n"; - let Some(bundler) = gate("gitignored-file") else { - return; - }; + let bundler = gate(tag)?; if Command::new("git").arg("--version").output().is_err() { println!("SKIP e2e_vendor_gem_build: no git on PATH"); - return; + return None; } let tmp = tempfile::tempdir().unwrap(); @@ -4177,7 +4179,7 @@ fn gem_vendor_file_a_project_rule_ignores_reaches_a_git_clone() { std::fs::create_dir_all(&proj).unwrap(); std::fs::write( proj.join("Gemfile"), - format!("source \"https://rubygems.org\"\n\ngem \"{GEM}\", \"{VERSION}\"\n"), + format!("source \"https://rubygems.org\"\n\ngem \"{LCS}\", \"{LCS_VERSION}\"\n"), ) .unwrap(); let path_config = argv(&bundler.config_local_args("path", "vendor/bundle")) @@ -4188,11 +4190,11 @@ fn gem_vendor_file_a_project_rule_ignores_reaches_a_git_clone() { let install = bundle(&proj, &["install"], false); if !config.status.success() || !install.status.success() { println!( - "SKIP e2e_vendor_gem_build: could not install {GEM} {VERSION} (registry \ + "SKIP e2e_vendor_gem_build: could not install {LCS} {LCS_VERSION} (registry \ unreachable?):\n{}", String::from_utf8_lossy(&install.stderr) ); - return; + return None; } git(&proj, &["init", "-q"]); std::fs::write(proj.join(".gitignore"), RULES).unwrap(); @@ -4206,18 +4208,18 @@ fn gem_vendor_file_a_project_rule_ignores_reaches_a_git_clone() { .join("vendor/bundle/ruby") .join(&api) .join("gems") - .join(format!("{GEM}-{VERSION}")); + .join(format!("{LCS}-{LCS_VERSION}")); assert!( gem_dir.join(".rspec").is_file(), - "{GEM} {VERSION} ships .rspec (test premise)" + "{LCS} {LCS_VERSION} ships .rspec (test premise)" ); - let orig = std::fs::read(gem_dir.join(RB)).expect("the installed file"); + let orig = std::fs::read(gem_dir.join(LCS_RB)).expect("the installed file"); let marker = format!( "\nmodule Diff\n module LCS\n SOCKET_PATCH_VENDOR_E2E = \"{UUID}\"\n end\nend\n" ); let patched: Vec = [orig.as_slice(), marker.as_bytes()].concat(); - let purl = format!("pkg:gem/{GEM}@{VERSION}"); - stage_patch_with_vuln(&proj, &purl, RB, &orig, &patched); + let purl = format!("pkg:gem/{LCS}@{LCS_VERSION}"); + stage_patch_with_vuln(&proj, &purl, LCS_RB, &orig, &patched); let cwd = proj.to_str().unwrap(); let (code, stdout, stderr) = @@ -4228,6 +4230,35 @@ fn gem_vendor_file_a_project_rule_ignores_reaches_a_git_clone() { ); let env = parse_json_envelope(&stdout); assert_eq!(env["summary"]["applied"], 1, "one package vendored: {env}"); + Some(VendoredLcs { + tmp, + proj, + path_config, + }) +} + +/// A project whose `.gitignore` has a rule that matches a file the gem +/// ships ([`vendored_lcs_project`]). The vendoring checkout holds the file +/// either way, so the proof is a real `git commit` and `git clone`: the +/// clone holds the whole copy, `vendor --check` passes there as it does in +/// the checkout that vendored, and a frozen `bundle install` loads the +/// patched gem. +#[test] +#[ignore = "host capstone: shells out to a real bundler >= 1.17; the unpinned `test` job \ + skips it, the e2e job runs it with a pinned toolchain via --ignored"] +fn gem_vendor_file_a_project_rule_ignores_reaches_a_git_clone() { + const GEM: &str = LCS; + const VERSION: &str = LCS_VERSION; + const RB: &str = LCS_RB; + let Some(VendoredLcs { + tmp, + proj, + path_config, + }) = vendored_lcs_project("gitignored-file") + else { + return; + }; + let cwd = proj.to_str().unwrap(); // What the vendoring checkout says: every file of the copy is one git // commits, and the check passes. @@ -4313,6 +4344,169 @@ fn gem_vendor_file_a_project_rule_ignores_reaches_a_git_clone() { ); } +/// #2471: a copy that 5.1.0 vendored has no `.gitignore` or +/// `.gitattributes` in its uuid dir, and a fresh clone of it lacks the +/// files a project rule ignored. The next `vendor` (the run behind `scan +/// --mode vendored`) or `repair` restores them, and each must say so: the +/// two files by name, a summary that is not "nothing to do", and the +/// commit step, on the run that wrote them and on no later one. After the +/// commit they name, a clone passes `vendor --check`. +#[test] +#[ignore = "host capstone: shells out to a real bundler >= 1.17; the unpinned `test` job \ + skips it, the e2e job runs it with a pinned toolchain via --ignored"] +fn gem_vendor_and_repair_name_the_files_they_restore_and_the_commit() { + const COMMIT: &str = "Commit .socket/vendor/: the files this run restored there"; + let Some(VendoredLcs { tmp, proj, .. }) = vendored_lcs_project("restored-files") else { + return; + }; + let cwd = proj.to_str().unwrap(); + let uuid_dir = format!(".socket/vendor/gem/{UUID}"); + let copy_rel = format!("{uuid_dir}/{LCS}-{LCS_VERSION}"); + let metadata = [".gitignore", ".gitattributes"].map(|file| format!("{uuid_dir}/{file}")); + // The tree as 5.1.0 left it: no metadata in the uuid dir. + let drop_metadata = || { + for file in &metadata { + std::fs::remove_file(proj.join(file)).unwrap(); + } + }; + let assert_restored = |what: &str, stdout: &str, stderr: &str| { + for file in &metadata { + assert!(proj.join(file).is_file(), "{what}: {file} is back"); + assert!( + stderr.contains(&format!("restored {}", metadata[0])) && stderr.contains(file), + "{what} names {file}.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + } + assert!( + stdout.contains("Next steps:") && stdout.contains(COMMIT), + "{what} names the commit.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert!( + !stdout.contains("nothing to do"), + "{what} did something.\nstdout:\n{stdout}" + ); + }; + let assert_quiet = |what: &str, stdout: &str, stderr: &str| { + assert!( + !stdout.contains("Next steps:") && !stderr.contains("restored "), + "{what} restored nothing.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + }; + + // ── vendor: the metadata alone ─────────────────────────────────────── + drop_metadata(); + let (code, stdout, stderr) = run_socket(&proj, &["vendor", "--offline", "--cwd", cwd]); + assert_eq!( + code, 0, + "vendor re-run.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert_restored("the vendor re-run", &stdout, &stderr); + assert!( + stdout.contains("1 package is already vendored; restored its files under .socket/vendor/."), + "{stdout}" + ); + // `--json` carries the same advisory, uncounted. + drop_metadata(); + let (code, stdout, stderr) = + run_socket(&proj, &["vendor", "--json", "--offline", "--cwd", cwd]); + assert_eq!( + code, 0, + "vendor --json.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env = parse_json_envelope(&stdout); + let events = env["events"].as_array().unwrap(); + let written: Vec<_> = events + .iter() + .filter(|e| e["errorCode"] == "vendor_git_metadata_written") + .collect(); + assert_eq!(written.len(), 1, "{env}"); + assert_eq!(env["summary"]["applied"], 0, "{env}"); + // In sync: nothing restored, nothing to commit. + let (code, stdout, stderr) = run_socket(&proj, &["vendor", "--offline", "--cwd", cwd]); + assert_eq!( + code, 0, + "in-sync vendor.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert_quiet("the in-sync vendor", &stdout, &stderr); + assert!( + stdout.contains("1 package is already vendored; nothing to do."), + "{stdout}" + ); + + // ── vendor: a file git left out of the clone, downloaded again ─────── + drop_metadata(); + std::fs::remove_file(proj.join(©_rel).join(".rspec")).unwrap(); + let (code, stdout, stderr) = run_socket(&proj, &["vendor", "--offline", "--cwd", cwd]); + assert_eq!( + code, 0, + "vendor rebuild.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert!( + proj.join(©_rel).join(".rspec").is_file(), + "the file is back" + ); + assert!( + stdout.contains(&format!( + "Redownloaded pkg:gem/{LCS}@{LCS_VERSION} ({copy_rel})" + )), + "the rebuild names the copy.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert!( + stdout.contains("Next steps:") && stdout.contains(COMMIT), + "the rebuild names the commit.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert!(!stdout.contains("nothing to do"), "{stdout}"); + + // ── repair: the same two cases ─────────────────────────────────────── + drop_metadata(); + let (code, stdout, stderr) = run_socket(&proj, &["repair", "--offline", "--cwd", cwd]); + assert_eq!(code, 0, "repair.\nstdout:\n{stdout}\nstderr:\n{stderr}"); + assert_restored("repair", &stdout, &stderr); + let (code, stdout, stderr) = run_socket(&proj, &["repair", "--offline", "--cwd", cwd]); + assert_eq!( + code, 0, + "in-sync repair.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert_quiet("the in-sync repair", &stdout, &stderr); + std::fs::remove_file(proj.join(©_rel).join(".rspec")).unwrap(); + let (code, stdout, stderr) = run_socket(&proj, &["repair", "--offline", "--cwd", cwd]); + assert_eq!( + code, 0, + "repair redownload.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert!( + stdout.contains("Redownloaded") && stdout.contains(COMMIT), + "the redownload names the commit.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + // A dry run restores nothing and names no commit. + drop_metadata(); + let (code, stdout, stderr) = + run_socket(&proj, &["repair", "--dry-run", "--offline", "--cwd", cwd]); + assert_eq!( + code, 0, + "repair --dry-run.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert_quiet("the dry run", &stdout, &stderr); + assert!( + !proj.join(&metadata[0]).exists(), + "a dry run writes nothing" + ); + let (code, stdout, stderr) = run_socket(&proj, &["repair", "--offline", "--cwd", cwd]); + assert_eq!(code, 0, "repair.\nstdout:\n{stdout}\nstderr:\n{stderr}"); + + // The commit the run names is what a clone needs. + git(&proj, &["add", "-A"]); + git(&proj, &["commit", "-q", "-m", "vendor"]); + let clone = tmp.path().join("clone"); + git(tmp.path(), &["clone", "-q", cwd, clone.to_str().unwrap()]); + let clone_cwd = clone.to_str().unwrap(); + let (code, stdout, stderr) = run_socket(&clone, &["vendor", "--check", "--cwd", clone_cwd]); + assert_eq!( + code, 0, + "vendor --check in a clone of the commit.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); +} + /// #2435: a gem vendored as platform gems without the patch of the ruby /// gem (not offered to the run) is vendored through the patch of the first /// platform the lock names, whose uuid names its directory. When that diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index f8652d939..ae0daf378 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -1324,16 +1324,32 @@ pub async fn vendor_gem_builds<'a>( let mut warnings: Vec = Vec::new(); if !dry_run { match restore_uuid_metadata(uuid_dir).await { - // The pair was missing: a copy of the gem's own tree - // that an earlier release vendored may still hold a - // `.gitignore` the gem ships, which the pair does not - // override. Said once, with the run that writes it. - Ok(true) if platforms.is_empty() => { - if let Some(warning) = shipped_rules_warning(project_root, copy_rel).await { - warnings.push(warning); + // The pair was missing or changed, and the project has + // two files to commit from a run that vendored nothing: + // the run says so (#2471). + Ok(true) => { + let uuid_dir_rel = + copy_rel.rsplit_once('/').map_or(copy_rel, |(dir, _)| dir); + warnings.push(VendorWarning::new( + super::GIT_METADATA_WRITTEN, + super::git_metadata_written_detail( + uuid_dir_rel, + &format!("{name}@{version}"), + ), + )); + // A copy of the gem's own tree that an earlier + // release vendored may still hold a `.gitignore` + // the gem ships, which the pair does not override. + // Said once, with the run that writes the pair. + if platforms.is_empty() { + if let Some(warning) = + shipped_rules_warning(project_root, copy_rel).await + { + warnings.push(warning); + } } } - Ok(_) => {} + Ok(false) => {} Err(e) => warnings.push(VendorWarning::new( super::npm_dir::GITIGNORE_UNCHECKED, super::npm_dir::gitignore_unchecked_detail( @@ -13076,9 +13092,11 @@ mod tests { let (again, entry, warnings) = unwrap_done(vendor(&root, &record, &cfg, false).await); assert!(again.success && entry.is_none(), "{:?}", again.error); - let [warning] = warnings.as_slice() else { - panic!("one advisory: {warnings:?}"); + // The pair the run wrote (#2471), then the file still hidden. + let [written, warning] = warnings.as_slice() else { + panic!("two advisories: {warnings:?}"); }; + assert_eq!(written.code, crate::vendor::GIT_METADATA_WRITTEN); assert_eq!(warning.code, "vendor_gem_copy_gitignored"); let hidden = format!("{}/Gemfile.lock", copy_rel()); assert!(warning.detail.contains(&hidden), "{warning:?}"); @@ -13157,7 +13175,19 @@ mod tests { let (again, rerun_entry, warnings) = unwrap_done(vendor(&root, &record, &cfg, false).await); assert!(again.success, "{:?}", again.error); - assert!(rerun_entry.is_none() && warnings.is_empty(), "{warnings:?}"); + // The run that writes the pair names both files and the commit + // (#2471); the in-sync run after it has nothing to say. + assert!(rerun_entry.is_none(), "the ledger entry stays as it is"); + let codes: Vec<&str> = warnings.iter().map(|w| w.code).collect(); + assert_eq!(codes, [crate::vendor::GIT_METADATA_WRITTEN]); + let uuid_rel = format!(".socket/vendor/gem/{}", record.uuid); + for want in [ + format!("{uuid_rel}/.gitignore"), + format!("{uuid_rel}/.gitattributes"), + "Commit them with the rest of .socket/vendor/".to_string(), + ] { + assert!(warnings[0].detail.contains(&want), "{}", warnings[0].detail); + } for (file, want) in metadata() { assert_eq!( text(uuid_dir(&root).join(file)).await, @@ -13166,6 +13196,9 @@ mod tests { ); } assert_eq!(ts::request_count(&server).await, requests); + let (_, in_sync_entry, in_sync) = + unwrap_done(vendor(&root, &record, &cfg, false).await); + assert!(in_sync_entry.is_none() && in_sync.is_empty(), "{in_sync:?}"); drop_metadata(); tokio::fs::remove_dir_all(copy(&root)).await.unwrap(); @@ -14631,7 +14664,10 @@ mod tests { let (again, entry_again, warnings) = unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); assert!(again.success, "{:?}", again.error); - assert!(entry_again.is_none() && warnings.is_empty(), "{warnings:?}"); + // Platform gems name the pair they wrote too (#2471). + assert!(entry_again.is_none(), "the ledger entry stays as it is"); + let codes: Vec<&str> = warnings.iter().map(|w| w.code).collect(); + assert_eq!(codes, [crate::vendor::GIT_METADATA_WRITTEN]); for (file, text_of) in metadata { assert_eq!(text(uuid_dir.join(file)).await, text_of, "re-run: {file}"); } diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 9cc7e8ba0..096fefd80 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -810,6 +810,21 @@ impl RevertOpts { } } +/// A run over a copy that was already in place wrote the uuid dir's +/// `.gitignore` or `.gitattributes` (missing, as on a copy an earlier +/// release vendored, or changed): files the project has yet to commit, +/// from a run that otherwise had nothing to do (#2471). +pub const GIT_METADATA_WRITTEN: &str = "vendor_git_metadata_written"; + +/// `uuid_dir_rel` is the uuid dir, `what` the vendored package. +pub fn git_metadata_written_detail(uuid_dir_rel: &str, what: &str) -> String { + format!( + "restored {uuid_dir_rel}/.gitignore and {uuid_dir_rel}/.gitattributes (one or both \ + were missing or changed): they keep the project's ignore rules and filters off the \ + vendored copy of {what}. Commit them with the rest of .socket/vendor/" + ) +} + /// Warning code for a recorded lock entry that no longer exists at revert /// time (the dependency was removed). See [`RevertOutcome::lock_entry_removed`]. pub const LOCK_ENTRY_REMOVED_CODE: &str = "vendor_lock_entry_removed"; diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 1425438fa..c892ddc1d 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5796,7 +5796,9 @@ before anything is downloaded, and so is a gem with a file git would still leave the copy is written. A gem that an earlier release vendored has neither file. The next vendored run, or -`repair`, writes them; commit them with the rest of `.socket/vendor/`. Such a copy also +`repair`, writes them; commit them with the rest of `.socket/vendor/`. The run names the two +files (`vendor_git_metadata_written`) and ends with that commit as its next step, as does a +run that downloads a copy again to restore files git left out of a clone. Such a copy also keeps the gem's own `.gitignore` as shipped. When that still hides a file, the run that writes the two files says so (`vendor_gem_copy_gitignored`); `git add -f` on the directory it names commits the whole copy.