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
47 changes: 47 additions & 0 deletions crates/socket-patch-cli/tests/e2e_sbt_vendor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -853,6 +853,53 @@ fn vendor_takeover_of_a_hosted_sbt_pin_dry_and_wet() {
);
}

/// A `pom.xml` beside the sbt build that hosted mode pinned too. The eject
/// restores the pin in every file that wires it, and vendoring wires the
/// sbt build alone: the pom is the upstream one again, so the Maven build
/// is no longer patched, and the run says that the pom is not wired.
#[test]
fn vendor_takeover_beside_a_pinned_pom_restores_the_pom_and_says_so() {
let tmp = tempfile::tempdir().unwrap();
let fx = Fixture::new(tmp.path(), &[(GSON, GSON_UUID)]);
write_hosted_pin(&fx.proj(), GSON_UUID);
// The core fixture `sbt/redirect/pom-also-present`, respelled for gson.
let gson = |rel: &str| {
let case = "../socket-patch-core/tests/fixtures/sbt/redirect/pom-also-present";
std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join(case).join(rel))
.unwrap()
.replace("org.apache.commons", GSON.group)
.replace("org/apache/commons", &GSON.group_path())
.replace("commons-lang3", GSON.artifact)
.replace("3.11", GSON.version)
.replace("abcdef12-0000-4000-8000-000000000001", GSON_UUID)
.replace("abcdef12", &GSON_UUID[..8])
};
let pinned = [
"pom.xml",
".mvn/maven.config",
".mvn/checksums/checksums.sha256",
];
for rel in pinned {
let path = fx.proj().join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, gson(&format!("expected/{rel}"))).unwrap();
}
let (_rt, server) = mock_gson_api();
let uri = server.uri();
let mut args = vec!["vendor"];
args.extend(api_flags(&uri));
let env = fx.ok(&args);
assert!(env.to_string().contains("vendor_sbt_pom_ignored"), "{env}");
assert_eq!(
std::fs::read_to_string(fx.proj().join("pom.xml")).unwrap(),
gson("input/pom.xml")
);
for rel in &pinned[1..] {
assert!(!fx.proj().join(rel).exists(), "{rel}: {env}");
}
assert!(!fx.proj().join(HOSTED_FILE).exists() && fx.generated().contains(GSON_UUID));
}

/// A mock patch API serving gson's patch record by `GSON_UUID`: plain
/// `vendor` over a hosted pin ejects it, fetching the pinned record from
/// the API (the agent manifest is not its input). Returns the runtime that
Expand Down
100 changes: 85 additions & 15 deletions crates/socket-patch-core/src/patch/redirect/upstream/maven.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1695,30 +1695,100 @@ mod tests {
assert_eq!(read_tree(tmp.path()), wired, "nothing changed");
}

/// A pin is one patch of one package in every file that wires it, and
/// a checkout that two builds read is wired in a file of each: here
/// `pom.xml` beside the `socket-patch.sbt` of an sbt build (the Gradle
/// index and the block of a Bazel hub in `MODULE.bazel` are the
/// others). Each restorer takes the pin out of its own files, so the
/// pom comes back whatever else the pin lists.
#[tokio::test]
async fn a_pin_another_build_wires_too_is_restored_in_its_pom() {
/// The fixture `sbt/redirect/pom-also-present` under `root` as a hosted
/// scan leaves it: one pin, in `pom.xml` and in the `socket-patch.sbt`
/// of the sbt build beside it. The tree before the scan.
fn pom_beside_sbt(root: &std::path::Path) -> BTreeMap<String, String> {
let case = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/sbt/redirect/pom-also-present");
let before = read_tree(&case.join("input"));
let tmp = tempfile::tempdir().unwrap();
for tree in [&before, &read_tree(&case.join("expected"))] {
let files: Vec<(&str, String)> = tree
.iter()
.map(|(rel, text)| (rel.as_str(), text.clone()))
.collect();
write_tree(tmp.path(), &files);
write_tree(root, &files);
}
before
}

/// A pin is one patch of one package in every file that wires it, and
/// a checkout that two builds read is wired in a file of each: `pom.xml`
/// beside the `socket-patch.sbt` of an sbt build, or beside the hosted
/// index of a Gradle build. Each restorer takes the pin out of its own
/// files, so the pom comes back whatever else the pin lists.
#[tokio::test]
async fn a_pin_another_build_wires_too_is_restored_in_its_pom() {
let sbt = tempfile::tempdir().unwrap();
let before_sbt = pom_beside_sbt(sbt.path());

let gradle = tempfile::tempdir().unwrap();
let slf4j = "org.slf4j:slf4j-api:1.7.36";
let build = format!("dependencies {{ implementation '{slf4j}' }}\n");
let files = [
("pom.xml", fixture("basic", "input", "pom.xml")),
("settings.gradle", "rootProject.name = 'app'\n".to_string()),
("build.gradle", build),
("gradle.lockfile", format!("{slf4j}=runtimeClasspath\n")),
];
write_tree(gradle.path(), &files);
let before_gradle = read_tree(gradle.path());
let scanned = scan(gradle.path(), UUID, &[("pom.xml", Ok("1.7.36"))]);
assert!(scanned.confirmed_gradle_uuids.contains(UUID));

for (root, wired_in, before) in [
(sbt.path(), ["pom.xml", "socket-patch.sbt"], before_sbt),
(
gradle.path(),
[".socket/gradle/hosted-index.tsv", "pom.xml"],
before_gradle,
),
] {
let case = wired_in.join(" and ");
let pins = discovered(root).await;
assert_eq!(pins.len(), 1, "{case}: {pins:?}");
assert_eq!(pins[0].files, wired_in);
roll_back(&case, root).await;
assert_eq!(read_tree(root), before, "{case}");
}
}

/// Two restorers act on such a pin, and a pin is restored in every
/// file that wires it or in none. Whichever of the two refuses, the
/// pin is refused and nothing is written: not `pom.xml` and the `.mvn`
/// files when `socket-patch.sbt` was edited, and not `socket-patch.sbt`
/// when the pom names the patched version where no scan put it. (The
/// pin is read before the edit: discovery does not list an edited
/// `socket-patch.sbt`.)
#[tokio::test]
async fn a_pin_one_of_two_builds_refuses_is_restored_in_neither() {
let named = "</dependencies>\n <build>\n <finalName>app-3.11-socket.abcdef12</finalName>\n </build>";
for (rel, from, to, needle) in [
("socket-patch.sbt", "Do not edit", "Do edit", "was edited"),
(
"pom.xml",
"</dependencies>",
named,
"outside a <dependency> version",
),
] {
let tmp = tempfile::tempdir().unwrap();
pom_beside_sbt(tmp.path());
let pins = discovered(tmp.path()).await;
assert_eq!(pins[0].files, ["pom.xml", "socket-patch.sbt"]);
let edited = read_tree(tmp.path())[rel].replace(from, to);
assert!(edited.contains(to), "{rel}");
std::fs::write(tmp.path().join(rel), edited).unwrap();
let wired = read_tree(tmp.path());
let opts = RestoreOptions {
offline: true,
..RestoreOptions::default()
};
let outcome = restore_upstream(tmp.path(), &pins, &opts).await;
let why = refusal(&outcome);
assert!(why.contains(needle), "{rel}: {why}");
assert_eq!(read_tree(tmp.path()), wired, "{rel}: nothing changed");
}
let pins = discovered(tmp.path()).await;
assert_eq!(pins.len(), 1, "{pins:?}");
assert_eq!(pins[0].files, ["pom.xml", "socket-patch.sbt"]);
roll_back("a pom beside an sbt build", tmp.path()).await;
assert_eq!(read_tree(tmp.path()), before);
}

/// An earlier release's pin is read by its shape only in a single pom.
Expand Down
66 changes: 29 additions & 37 deletions crates/socket-patch-core/tests/redirect_sbt_golden.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@
//! restore over `input/` and expects `expected/` to be the whole restored
//! `socket-patch.sbt` (absent = deleted).
//!
//! Every wiring case that creates `socket-patch.sbt` is also restored: its
//! confirmed pins out again must delete the file (no other bytes changed).
//! Every wiring case that creates `socket-patch.sbt` is also restored: with
//! the pins discovery finds in the wired tree out again, the tree is
//! `input/` (the file deleted, a `pom.xml` the run wired too put back).
//!
//! This harness is separate from the TS-authored `redirect_golden.rs`; the
//! Socket backend port of these cases is a follow-up.
Expand Down Expand Up @@ -152,26 +153,30 @@ fn run(case: &Path) -> (BTreeMap<String, String>, RewriteResult) {
(files, result)
}

async fn restore(input: &BTreeMap<String, String>, pins: &[HostedPin]) -> Option<String> {
/// The tree after the upstream restore of `pins` over `input`. With no
/// pins given, of the pins discovery finds there, in every file that wires
/// them, as `rollback` restores them.
async fn restore(
input: &BTreeMap<String, String>,
pins: Option<Vec<HostedPin>>,
) -> BTreeMap<String, String> {
let tmp = tempfile::tempdir().unwrap();
write_tree(tmp.path(), input);
let pins = match pins {
Some(pins) => pins,
None => HostedPin::all(&socket_patch_core::vex::discover_patched_refs(tmp.path()).await),
};
let out = restore_upstream(
tmp.path(),
pins,
&pins,
&RestoreOptions {
offline: true,
..Default::default()
},
)
.await;
assert_eq!(out.refused().count(), 0, "restore refused: {:?}", out.pins);
let after = tree(tmp.path());
for (rel, text) in input {
if rel != HOSTED_FILE {
assert_eq!(after.get(rel), Some(text), "restore touched {rel}");
}
}
after.get(HOSTED_FILE).cloned()
tree(tmp.path())
}

async fn run_restore_case(case: &Path) {
Expand All @@ -186,11 +191,11 @@ async fn run_restore_case(case: &Path) {
files: vec![HOSTED_FILE.to_string()],
})
.collect();
let left = restore(&input, &pins).await;
let got: BTreeMap<String, String> = left
.into_iter()
.map(|t| (HOSTED_FILE.to_string(), t))
.collect();
let mut after = restore(&input, Some(pins)).await;
let got: BTreeMap<String, String> = after.remove_entry(HOSTED_FILE).into_iter().collect();
let mut rest = input;
rest.remove(HOSTED_FILE);
assert_eq!(after, rest, "{}: restore touched more", case.display());
expect_tree(case, &got);
}

Expand Down Expand Up @@ -295,30 +300,17 @@ async fn redirect_sbt_golden_cases_match() {
);
}

// A run that created the file is undone by restoring its pins.
// A run that created the file is undone by restoring the pins
// discovery finds in what it wrote: the tree is the input again,
// whichever other build's file (a `pom.xml`) the run wired too.
if let (None, Some(_)) = (files.get(HOSTED_FILE), result.files.get(HOSTED_FILE)) {
let mut wired = tree(&case.join("input"));
let input = tree(&case.join("input"));
let mut wired = input.clone();
wired.extend(result.files.clone());
let overrides: Vec<DepOverride> =
serde_json::from_value(read_json(&case.join("overrides.json"))).unwrap();
let pins: Vec<HostedPin> = overrides
.iter()
.filter(|o| result.confirmed_sbt_uuids.contains(&o.patch_uuid))
.map(|o| HostedPin {
purl: format!(
"pkg:maven/{}/{}@{}",
o.namespace.as_deref().unwrap_or_default(),
o.name,
o.version
),
uuid: o.patch_uuid.clone(),
files: vec![HOSTED_FILE.to_string()],
})
.collect();
assert_eq!(
restore(&wired, &pins).await,
None,
"{}: restoring every pin must delete {HOSTED_FILE}",
restore(&wired, None).await,
input,
"{}: restoring every pin must put the input back",
case.display()
);
}
Expand Down
Loading