Skip to content
Merged
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
12 changes: 7 additions & 5 deletions crates/socket-patch-cli/CLI_CONTRACT.md

Large diffs are not rendered by default.

174 changes: 142 additions & 32 deletions crates/socket-patch-cli/src/commands/gem_refresh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,10 +375,13 @@ fn display_list(paths: &[PathBuf]) -> String {
.join(", ")
}

/// How a refresh that did not happen is retried.
/// How a refresh that did not happen is retried. An unwind can't be: its
/// first run removed the wiring a second one would look for.
fn retry_hint(direction: Direction, why: Option<&Why>) -> &'static str {
match (why, direction) {
(Some(Why::Disabled), _) => "Re-run without `--no-gem-install-refresh`, or ",
(Some(Why::Disabled), Direction::Patched) => {
"Re-run without `--no-gem-install-refresh`, or "
}
(Some(Why::Failed(_)), Direction::Patched) => "Re-run `socket-patch scan` to retry, or ",
_ => "",
}
Expand Down Expand Up @@ -711,35 +714,24 @@ pub(crate) fn report(
out
}

/// The stale materializations of the gems a hosted unwind just put back on
/// their upstream entries, judged like the hosted scan's guard, with the
/// roles swapped: an installed copy (ruby platform) is stale when the
/// archive RubyGems installed it from, `<home>/cache/<leaf>.gem`, is
/// readable and is not the upstream one, and so is such an archive in
/// Bundler's cache dir. `upstream` is each purl's upstream sha256; a purl
/// without one is not judged.
async fn stale_after_restore(
common: &GlobalArgs,
upstream: &BTreeMap<String, String>,
) -> Vec<StaleGem> {
/// The installed copies (ruby platform) of `purls` in the gem homes Bundler
/// installs the project's gems into, each with the archive RubyGems
/// installed it from, `<home>/cache/<leaf>.gem`.
async fn installed_with_archives(common: &GlobalArgs, purls: &[String]) -> Vec<InstalledCopy> {
use socket_patch_core::crawlers::types::CrawlerOptions;
use socket_patch_core::crawlers::RubyCrawler;
use socket_patch_core::vendor::file_sha256_hex;

let purls: Vec<String> = upstream.keys().cloned().collect();
let crawler = RubyCrawler::new();
let options = CrawlerOptions {
cwd: common.cwd.clone(),
global: common.global,
global_prefix: common.global_prefix.clone(),
};
let app_cache =
socket_patch_core::crawlers::ruby_crawler::bundler_app_cache_dir(&common.cwd).await;
let mut out = Vec::new();
for home in crawler.bundler_install_homes(&options).await {
let found = crawler.find_each_by_purl(&home.gems_dir, &purls).await;
let found = crawler.find_each_by_purl(&home.gems_dir, purls).await;
for (purl, pkg) in purls.iter().zip(found) {
let (Some(pkg), Some(sha)) = (pkg, upstream.get(purl)) else {
let Some(pkg) = pkg else {
continue;
};
let Some((_, name, version)) = socket_patch_core::utils::purl::purl_parts(purl) else {
Expand All @@ -754,18 +746,72 @@ async fn stale_after_restore(
let Some(archive) = home_cache_archive(&pkg.path) else {
continue;
};
match file_sha256_hex(&archive).await {
Some(got) if &got != sha => out.push(StaleGem {
purl: purl.clone(),
leaf,
installed: Some((pkg.path.clone(), home.project_local)),
cache_archive: None,
in_place: false,
}),
_ => {}
}
out.push(InstalledCopy {
purl: purl.clone(),
leaf,
dir: pkg.path.clone(),
project_local: home.project_local,
archive,
});
}
}
out
}

/// One installed copy [`installed_with_archives`] found.
struct InstalledCopy {
purl: String,
leaf: String,
dir: PathBuf,
project_local: bool,
archive: PathBuf,
}

/// Which materializations an unwind's refresh covers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Scope {
/// Installed copies and the archives in Bundler's cache dir.
All,
/// Installed copies only.
Installed,
}

/// The stale materializations of the gems an unwind just put back on
/// their upstream entries, judged like the hosted scan's guard, with the
/// roles swapped: an installed copy (ruby platform) is stale when the
/// archive RubyGems installed it from, `<home>/cache/<leaf>.gem`, is
/// readable and is not the upstream one, and so is (in [`Scope::All`])
/// such an archive in Bundler's cache dir. `upstream` is each purl's
/// upstream sha256; a purl without one is not judged.
async fn stale_after_restore(
common: &GlobalArgs,
upstream: &BTreeMap<String, String>,
scope: Scope,
) -> Vec<StaleGem> {
use socket_patch_core::vendor::file_sha256_hex;

let purls: Vec<String> = upstream.keys().cloned().collect();
let mut out = Vec::new();
for copy in installed_with_archives(common, &purls).await {
let Some(sha) = upstream.get(&copy.purl) else {
continue;
};
match file_sha256_hex(&copy.archive).await {
Some(got) if &got != sha => out.push(StaleGem {
purl: copy.purl,
leaf: copy.leaf,
installed: Some((copy.dir, copy.project_local)),
cache_archive: None,
in_place: false,
}),
_ => {}
}
}
if scope == Scope::Installed {
return out;
}
let app_cache =
socket_patch_core::crawlers::ruby_crawler::bundler_app_cache_dir(&common.cwd).await;
for (purl, sha) in upstream {
let Some((_, name, version)) = socket_patch_core::utils::purl::purl_parts(purl) else {
continue;
Expand All @@ -786,7 +832,8 @@ async fn stale_after_restore(
out
}

/// What the hosted unwind's refresh did, for [`crate::commands::hosted_unwind`].
/// What an unwind's refresh did, for [`crate::commands::hosted_unwind`]
/// and the vendored unwind ([`crate::commands::vendored_backend`]).
#[derive(Debug, Default)]
pub(crate) struct RestoreRefresh {
pub(crate) report: Report,
Expand All @@ -808,6 +855,43 @@ pub(crate) async fn after_restore(
common: &GlobalArgs,
restored: &[String],
staged: &BTreeMap<String, Option<String>>,
) -> RestoreRefresh {
refresh_restored(common, restored, staged, Scope::All).await
}

/// After a wet vendored unwind put the gems `unwound` back on their
/// upstream entries (the lock on disk says so): Bundler loads their
/// installed copies again, and a copy that a hosted scan replaced with the
/// patched build before the gem was vendored is still that build (#2083).
/// Those copies are brought back to the upstream gem exactly as
/// [`after_restore`] does it. An archive in Bundler's cache dir is not
/// touched: the vendored unwind names it (`upstream_gem_stale_cache`).
///
/// Only a gem the lock now resolves from rubygems.org is judged. A gem
/// with no installed copy to judge costs no registry lookup: a vendored
/// unwind then needs no network, as before.
pub(crate) async fn after_vendored_unwind(
common: &GlobalArgs,
unwound: &[String],
) -> RestoreRefresh {
let installed: BTreeSet<String> = installed_with_archives(common, unwound)
.await
.into_iter()
.filter(|copy| copy.archive.is_file())
.map(|copy| copy.purl)
.collect();
if installed.is_empty() {
return RestoreRefresh::default();
}
let installed: Vec<String> = installed.into_iter().collect();
refresh_restored(common, &installed, &BTreeMap::new(), Scope::Installed).await
}

async fn refresh_restored(
common: &GlobalArgs,
restored: &[String],
staged: &BTreeMap<String, Option<String>>,
scope: Scope,
) -> RestoreRefresh {
use socket_patch_core::patch::redirect::upstream::gem_upstream_archive;

Expand All @@ -822,14 +906,23 @@ pub(crate) async fn after_restore(
if let Some((sha, url)) =
gem_upstream_archive(&common.cwd, staged, purl, common.offline).await
{
// A vendored revert does not prove where the lock resolves the
// gem from: an entry vendored over hosted wiring before v5
// reverts to its hosted pin, whose `CHECKSUMS` sha256 is the
// patched gem's (the hosted unwind restores that pin next, and
// refreshes then). Only a gem the lock resolves from
// rubygems.org is known to be back on its upstream entry.
if scope == Scope::Installed && url.is_none() {
continue;
}
shas.insert(purl.clone(), sha);
urls.insert(purl.clone(), url);
}
}
if shas.is_empty() {
return RestoreRefresh::default();
}
let stale = stale_after_restore(common, &shas).await;
let stale = stale_after_restore(common, &shas, scope).await;
if stale.is_empty() {
return RestoreRefresh::default();
}
Expand All @@ -849,7 +942,7 @@ pub(crate) async fn after_restore(
};
let pass = attempt(&stale, wanted, &source, &policy, direction).await;
let still = if pass.changed(&policy) {
stale_after_restore(common, &shas).await
stale_after_restore(common, &shas, scope).await
} else {
stale
};
Expand Down Expand Up @@ -1264,5 +1357,22 @@ mod tests {
"{}",
out.warnings[1].1
);

// An unwind names no re-run: nothing is left for one to unwind.
let out = report(Direction::Upstream, &gems, &tried, &policy_off);
assert!(
out.warnings[1]
.1
.contains("`--no-gem-install-refresh` is set")
&& !out.warnings[1].1.contains("Re-run")
&& out.warnings[1].1.contains("and run `bundle install`"),
"{}",
out.warnings[1].1
);
let summary = out.summary.expect("stale gems").paragraph();
assert!(
!summary.contains("Re-run without") && summary.contains("Run `rm -f "),
"{summary}"
);
}
}
13 changes: 13 additions & 0 deletions crates/socket-patch-cli/src/commands/remove.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1411,6 +1411,7 @@ async fn revert_vendored_matches(
for RevertedEntry {
key,
warnings,
progress,
step,
..
} in reverted
Expand Down Expand Up @@ -1516,6 +1517,12 @@ async fn revert_vendored_matches(
);
}
VendorRevertStep::LedgerWriteFailed(e) => {
// The revert landed, and so did the gem refresh after it.
if loud {
for line in &progress {
println!("{line}");
}
}
emit_error_envelope(
args.common.json,
args.common.dry_run,
Expand All @@ -1525,6 +1532,12 @@ async fn revert_vendored_matches(
return Err(1);
}
}
if loud {
for line in &progress {
println!("{line}");
leg.printed = true;
}
}
}
Ok(leg)
}
Expand Down
16 changes: 16 additions & 0 deletions crates/socket-patch-cli/src/commands/rollback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1002,6 +1002,10 @@ struct VendoredLegOutcome {
/// could not be saved.
failed: Vec<(String, &'static str, String)>,
warnings: Vec<(String, String)>,
/// The gems (ledger keys) whose installed copies the unwind brought
/// back to the upstream build: nothing of theirs is left for a
/// reinstall.
refreshed_installs: std::collections::BTreeSet<String>,
/// `removed` / `vendor_orphan_removed` events for the orphan uuid
/// dirs (no ledger entry) swept, also on dry-run.
orphans_removed: Vec<PatchEvent>,
Expand Down Expand Up @@ -1033,10 +1037,15 @@ async fn run_vendored_leg(
for RevertedEntry {
key,
warnings,
progress,
gem_install_refreshed,
step,
..
} in reverted
{
if gem_install_refreshed {
out.refreshed_installs.insert(key.clone());
}
for w in &warnings {
if loud {
eprintln!("Warning: {}", w.detail);
Expand Down Expand Up @@ -1097,6 +1106,11 @@ async fn run_vendored_leg(
out.failed.push((key, "vendor_state_write_failed", why));
}
}
if loud {
for line in &progress {
println!("{line}");
}
}
}
out
}
Expand Down Expand Up @@ -2844,6 +2858,7 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 {
// A gem the hosted leg already brought back to
// its upstream build.
&& !hosted_leg.refreshed_installs.contains(key.as_str())
&& !vendored_leg.refreshed_installs.contains(key.as_str())
})
.count();
if still_patched > 0 {
Expand Down Expand Up @@ -6675,6 +6690,7 @@ mod tests {
"boom".to_string(),
)],
warnings: Vec::new(),
refreshed_installs: Default::default(),
orphans_removed: Vec::new(),
};
let hosted = HostedLegOutcome {
Expand Down
15 changes: 15 additions & 0 deletions crates/socket-patch-cli/src/commands/vendor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,16 @@ fn takeover_detail(code: &str, detail: &str) -> String {
}
}

/// A reverted entry's progress lines ([`RevertedEntry::progress`]), for a
/// human run.
fn print_progress(common: &GlobalArgs, lines: &[String]) {
if !common.silent && !common.json {
for line in lines {
println!("{line}");
}
}
}

pub(crate) fn record_warning(
env: &mut Envelope,
purl: &str,
Expand Down Expand Up @@ -4713,6 +4723,7 @@ pub(crate) async fn reconcile_dropped(
for RevertedEntry {
key: purl,
warnings,
progress,
step,
..
} in reverted
Expand Down Expand Up @@ -4778,6 +4789,7 @@ pub(crate) async fn reconcile_dropped(
);
}
}
print_progress(common, &progress);
}
(had_error, Ok(state))
}
Expand Down Expand Up @@ -4820,7 +4832,9 @@ async fn run_revert(args: &VendorArgs, env: &mut Envelope) -> i32 {
key: purl,
flavor,
warnings,
progress,
step,
..
} in reverted
{
let purl = &purl;
Expand Down Expand Up @@ -4875,6 +4889,7 @@ async fn run_revert(args: &VendorArgs, env: &mut Envelope) -> i32 {
);
}
}
print_progress(common, &progress);
}

// `--revert` returns to UPSTREAM: a package vendored over hosted wiring
Expand Down
Loading
Loading