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
80 changes: 45 additions & 35 deletions crates/socket-patch-cli/CLI_CONTRACT.md

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions crates/socket-patch-cli/src/commands/vendor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7885,8 +7885,12 @@ mod scope_and_hint_tests {
/// where it can: that file is no file of the pin it restores. A pin
/// of that entry alone is ejected only where the hub is the project's
/// one build, and is none of the pins of a project that Maven builds.
/// Whether a hub is a build is read with `SOCKET_NO_BAZEL` from the
/// environment, so the test holds it unset.
#[test]
#[serial_test::serial]
fn a_takeover_leaves_the_entry_of_a_bazel_hub() {
let _unset = crate::test_env::EnvGuard::unset(socket_patch_core::bazel::OFF_ENV);
let pin = |purl: &str, files: &[&str]| HostedPin {
purl: purl.to_string(),
uuid: "1d3c1fd2-7b4e-4c1a-9f0e-2a3b4c5d6e7f".to_string(),
Expand Down
4 changes: 4 additions & 0 deletions crates/socket-patch-cli/src/commands/vex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4316,8 +4316,12 @@ mod bazel_tests {
/// project's, changes nothing. Nor does a run with `--vex-no-bazel`,
/// whose document is about the installed tree: the step returns before
/// it asks about a package, and every set it was given is as it was.
/// The lookup of the workspace reads `SOCKET_NO_BAZEL` from the
/// environment, so the test holds it unset.
#[tokio::test]
#[serial_test::serial]
async fn the_bazel_step_finds_what_no_hub_builds_in_a_project_run_only() {
let _unset = crate::test_env::EnvGuard::unset(socket_patch_core::bazel::OFF_ENV);
let tmp = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(tmp.path()).unwrap();
let module = "module(name = \"shop\")\n\
Expand Down
6 changes: 6 additions & 0 deletions crates/socket-patch-cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ pub use socket_patch_core::hosted::memory as hosted_memory;
pub mod json_envelope;
pub mod path_scope;
pub(crate) mod telemetry_outcomes;
/// The core unit tests' env guard, compiled into this crate's unit tests
/// too: a test that judges by a variable holds it through the guard.
#[cfg(test)]
#[allow(dead_code)]
#[path = "../../socket-patch-core/src/test_env.rs"]
pub(crate) mod test_env;
pub mod ui;
pub mod update_notifier;

Expand Down
78 changes: 78 additions & 0 deletions crates/socket-patch-cli/tests/e2e_bazel_build/composer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1564,6 +1564,84 @@ fn vendored_mode_goes_on_outside_bazel_and_on_the_users_word() {
reverts(ALLOW);
}

/// Without a Bazel: a project that a release before the refusal vendored,
/// in a checkout with a Bazel workspace file that no Bazel builds it from.
/// Its lock names the copy of the patch of then, so the project uses
/// vendored mode already and is not declined: the scan in vendored mode
/// vendors a newer patch of the package in the place of the older one, and
/// the scan that names no mode, which such a pipeline runs, then finds the
/// project in sync.
#[test]
fn a_project_vendored_by_an_earlier_release_is_not_declined_a_newer_patch() {
let (flow, newer) = checkout(&[]);
let (cell, upstream) = (&flow.cell, &flow.upstream);
let older = Patched::new();
let then = registry(upstream);
grant(&then, upstream, &older, &older.package);
let earlier = socket_patch(cell, &then, API, &VENDORED);
assert_eq!(earlier.code, 0, "{}", earlier.dump);
cell.write("MODULE.bazel", "");
let named = |tree: &Tree| -> Value {
let lock: Value = serde_json::from_slice(&tree[&lock_of(API)]).expect("a lock");
lock["packages"][0]["dist"]["url"].clone()
};
assert_eq!(named(&cell.tree()), copy_of(&older).as_str());

let scan = socket_patch(cell, &flow.standin, API, &VENDORED);
let said = &scan.dump;
assert_eq!(scan.code, 0, "{said}");
assert_eq!(scan.envelope["status"], "success", "{said}");
let update = json!([{ "purl": PURL, "oldUuid": older.uuid, "newUuid": newer.uuid }]);
assert_eq!(scan.envelope["updates"], update, "{said}");
let vendored = cell.tree();
assert_eq!(named(&vendored), copy_of(&newer).as_str(), "{said}");
let source = |patch: &Patched| vendored.get(&format!("{API}/{}/{FILE}", copy_of(patch)));
let patched = newer.package.source.as_bytes();
assert_eq!(source(&newer).map(Vec::as_slice), Some(patched), "{said}");
assert_eq!(source(&older), None, "{said}");

let again = socket_patch(cell, &flow.standin, API, &["scan", "--yes"]);
assert_eq!(again.code, 0, "{}", again.dump);
assert_eq!(again.envelope["status"], "success", "{}", again.dump);
assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{}", again.dump);
}

/// Without a Bazel: a regular file named `workspace`, in lower case, at
/// the root of a checkout that has no Bazel file. On a disk that folds
/// case it is what a lookup of `WORKSPACE` finds, and vendored mode
/// declines the project; on a disk that does not, the project is vendored.
/// The test asks the disk which of the two it runs on and says so.
#[test]
fn a_file_named_workspace_in_lower_case_declines_where_the_disk_folds_case() {
let (flow, patch) = checkout(&["workspace"]);
let before = flow.cell.tree();
let folds = flow.cell.path("WORKSPACE").is_file();
if folds {
declines(&flow, API, &VENDORED, 1, "failed", &before);
} else {
vendors(&flow, API, &patch, &before, &[]);
}
let ran = ["does not fold case: vendored", "folds case: declined"][usize::from(folds)];
println!("a file named `workspace`: the disk {ran}");
}

/// Without a Bazel: with `SOCKET_NO_BAZEL=1` vendored mode is not declined
/// in a Bazel workspace. The scan vendors the package as it does in the
/// same checkout without the workspace file, to the byte.
#[test]
fn the_switch_makes_vendored_mode_the_one_of_a_checkout_without_bazel() {
let (flow, _patch) = checkout(&["MODULE.bazel"]);
let origin = flow.standin.origin();
let packagist = format!("{origin}/{PACKAGIST}");
let env = [
("SOCKET_PATCH_SERVER_URL", origin.as_str()),
("SOCKET_PACKAGIST_URL", packagist.as_str()),
];
let args = [&VENDORED[..], &["--cwd", API]].concat();
let declined = (flow.cell).off_is_without_bazel(&origin, &args, &env, &["MODULE.bazel"]);
assert_eq!(declined[0]["code"], 1, "{declined:#}");
}

/// Without a Bazel, a PHP or a Composer: the fixture's directories and the
/// legs of its workflow are those of its table. The fixture commits no
/// lock, no `vendor/` tree and no root `BUILD.bazel`: the run makes them.
Expand Down
26 changes: 26 additions & 0 deletions crates/socket-patch-cli/tests/e2e_bazel_build/go.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1115,6 +1115,32 @@ fn a_project_in_no_bazel_workspace_gets_no_bazelignore() {
}
}

/// Without a Bazel: with `SOCKET_NO_BAZEL=1` a run that keeps a copy of a
/// Go module in a Bazel workspace writes no `.bazelignore` and says
/// nothing of one: it is the run of the same checkout without its
/// `MODULE.bazel`, to the byte, in vendored and in agent mode. What an
/// earlier run wrote is still undone with the variable set: the revert of
/// a copy takes its pair, and the file that was made for it, away.
#[test]
fn the_switch_adds_no_bazelignore_line_and_still_takes_one_away() {
let (cell, with) = (checkout("", "MODULE.bazel"), Patching::new(&[]));
let modcache = with.modcache.path().to_str().expect("a UTF-8 path");
let (origin, env) = (with.standin.origin(), [("GOMODCACHE", modcache)]);
let before = cell.tree();
for mode in [Kept::Vendored, Kept::Agent] {
let beside = cell.off_is_without_bazel(&origin, &mode.scan(), &env, &["MODULE.bazel"]);
let ignored = beside[0]["files"][".bazelignore"].as_str();
assert_eq!(ignored, Some(mode.ignored("").as_str()), "{beside:#}");
}

with.run(&cell, &Kept::Vendored.scan());
assert!(cell.tree().contains_key(".bazelignore"));
let off = [env[0], ("SOCKET_NO_BAZEL", "1")];
let undo = cell.socket_patch(&origin, &["vendor", "--revert", "--yes"], &off);
assert_eq!(undo.code, 0, "{}", undo.dump);
assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", undo.dump);
}

/// Without a Bazel: a project that is in no git checkout looks no further
/// than its own directory. Below a Bazel root it is patched as anywhere
/// else, and gets no line and no warning: nothing above it is read, not
Expand Down
179 changes: 179 additions & 0 deletions crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1249,6 +1249,140 @@ impl Cell {
json!([run(&["--json"]), run(&[])])
}

/// What of the workspace copy its regular files ([`Cell::tree`]) do not
/// make anew, each by its path from the copy: a link, a directory that
/// holds nothing, a file with a permission bit to run it, and whatever
/// is neither a file nor a directory.
fn not_made_by_its_files(&self) -> Vec<String> {
use std::os::unix::fs::PermissionsExt;
fn walk(dir: &Path, odd: &mut Vec<PathBuf>) {
let entries = std::fs::read_dir(dir).expect("a directory of the copy");
let entries: Vec<_> = entries.flatten().map(|entry| entry.path()).collect();
if entries.is_empty() {
odd.push(dir.to_path_buf());
}
for path in entries {
let meta = std::fs::symlink_metadata(&path).expect("an entry of the copy");
if meta.is_dir() {
walk(&path, odd);
} else if !meta.is_file() || meta.permissions().mode() & 0o111 != 0 {
odd.push(path);
}
}
}
let (base, mut odd) = (&self.scratch.workspace, Vec::new());
walk(base, &mut odd);
odd.retain(|path| path != base);
let shown = |path: &PathBuf| match path.strip_prefix(base) {
Ok(from) => from.display().to_string(),
Err(_) => path.display().to_string(),
};
let mut odd: Vec<String> = odd.iter().map(shown).collect();
odd.sort();
odd
}

/// The workspace copy with the files `files` and nothing else: every
/// file as a new one, with the permission bits of any new file, and no
/// directory but those the files are in.
fn remake(&self, files: &Tree) {
let entries = std::fs::read_dir(&self.scratch.workspace).expect("the workspace copy");
for entry in entries.flatten() {
let path = entry.path();
let gone = match entry.file_type().is_ok_and(|kind| kind.is_dir()) {
true => std::fs::remove_dir_all(&path),
false => std::fs::remove_file(&path),
};
gone.unwrap_or_else(|e| panic!("remove {}: {e}", path.display()));
}
for (rel, bytes) in files {
self.write(rel, bytes);
}
}

/// `SOCKET_NO_BAZEL=1` makes `socket-patch <args>` in this checkout the
/// run of the same checkout without its Bazel files `bazel`, to a
/// script (`--json`) and to a person: the exit code, both streams byte
/// for byte, and every file the run left but those ([`undated`]). Each
/// run starts in the checkout as it is now, made anew from its regular
/// files, and the checkout is left so. A checkout that those files do
/// not make anew is refused, with what it holds beside them
/// ([`Cell::not_made_by_its_files`]): a link, an empty directory or an
/// executable file would be gone from the second run on, and the runs
/// would not start alike. The run without the Bazel files passes.
/// Without the variable the same command gives something else in the
/// workspace, which is what this gives: the comparison is of a run that
/// the workspace changes.
pub fn off_is_without_bazel(
&self,
api: &str,
args: &[&str],
env: &[(&str, &str)],
bazel: &[&str],
) -> Value {
self.without_and_beside(api, args, env, bazel).1
}

/// [`Cell::off_is_without_bazel`], with what the run without the Bazel
/// files gave before what the run beside them gave: for a test that
/// also holds what the run with the variable did, which is the first.
pub fn without_and_beside(
&self,
api: &str,
args: &[&str],
env: &[(&str, &str)],
bazel: &[&str],
) -> (Value, Value) {
let odd = self.not_made_by_its_files();
assert_eq!(
odd,
Vec::<String>::new(),
"{}: the regular files of this checkout do not make it anew",
self.test
);
let files = self.tree();
let mut plain = files.clone();
plain.retain(|rel, _| !bazel.contains(&rel.as_str()));
let gives = |start: &Tree, env: &[(&str, &str)]| {
let run = |form: &[&str]| {
self.remake(start);
let mut cmd = self.socket_patch_command(api, &[args, form].concat(), env);
let out = cmd.output().expect("spawn socket-patch");
let text = |bytes: Vec<u8>| String::from_utf8_lossy(&bytes).into_owned();
let mut left = undated(&self.tree());
left.retain(|rel, _| !bazel.contains(&rel.as_str()));
let left: BTreeMap<String, String> = left
.into_iter()
.map(|(rel, bytes)| (rel, text(bytes)))
.collect();
json!({
"code": out.status.code(),
"stdout": text(out.stdout),
"stderr": text(out.stderr),
"files": left,
})
};
json!([run(&["--json"]), run(&[])])
};
let off = [env, &[("SOCKET_NO_BAZEL", "1")]].concat();
let without = gives(&plain, env);
let (switched, beside) = (gives(&files, &off), gives(&files, env));
self.remake(&files);
let test = &self.test;
let codes = [&without[0]["code"], &without[1]["code"]];
assert_eq!(
codes,
[&json!(0), &json!(0)],
"{test}: {args:?}: {without:#}"
);
assert_eq!(switched, without, "{test}: {args:?} with SOCKET_NO_BAZEL=1");
assert_ne!(
beside, without,
"{test}: {args:?} is no other run in the workspace"
);
(without, beside)
}

/// Where a flow has `socket-patch` write the VEX document `name`:
/// beside the workspace copy, so it is no file of the checkout, and no
/// comparison of the checkout's files sees it.
Expand Down Expand Up @@ -1708,6 +1842,51 @@ fn a_downloader_config_is_named_by_the_option_of_the_release() {
}
}

/// Without a Bazel: the comparison of a run with the switch
/// ([`Cell::off_is_without_bazel`]) makes the checkout anew from its
/// regular files before each run, so it refuses a checkout that holds
/// what those files do not carry. A link, an empty directory and an
/// executable file are each named, and no run is started.
#[test]
fn a_checkout_its_files_do_not_make_anew_is_refused() {
use std::os::unix::fs::PermissionsExt;
let cell = cell_without_bazel("9.3.2");
cell.write("MODULE.bazel", "");
cell.write("dir/file", "x");
assert_eq!(cell.not_made_by_its_files(), NOTHING);
std::os::unix::fs::symlink("file", cell.path("dir/link")).expect("a link");
std::fs::create_dir(cell.path("empty")).expect("a directory");
cell.write("run.sh", "#!/bin/sh\n");
let runs = std::fs::Permissions::from_mode(0o755);
std::fs::set_permissions(cell.path("run.sh"), runs).expect("the permission bits");
let odd = ["dir/link", "empty", "run.sh"];
assert_eq!(cell.not_made_by_its_files(), odd);
let compare = || cell.off_is_without_bazel("http://127.0.0.1:9", &["list"], &[], &[]);
let refused = std::panic::catch_unwind(std::panic::AssertUnwindSafe(compare));
assert!(refused.is_err(), "it ran in a checkout it cannot make anew");
// Nothing was made anew: the three are where they were.
assert_eq!(cell.not_made_by_its_files(), odd);
// Each one alone is enough.
for (keep, gone) in [(0, [1, 2]), (1, [0, 2]), (2, [0, 1])] {
let other = cell_without_bazel("9.3.2");
other.write("dir/file", "x");
std::os::unix::fs::symlink("file", other.path("dir/link")).expect("a link");
std::fs::create_dir(other.path("empty")).expect("a directory");
other.write("run.sh", "#!/bin/sh\n");
let runs = std::fs::Permissions::from_mode(0o755);
std::fs::set_permissions(other.path("run.sh"), runs).expect("the permission bits");
for at in gone {
let path = other.path(odd[at]);
let removed = match path.is_dir() && !path.is_symlink() {
true => std::fs::remove_dir(&path),
false => std::fs::remove_file(&path),
};
removed.expect("remove it");
}
assert_eq!(other.not_made_by_its_files(), [odd[keep]]);
}
}

/// Without a Bazel: a document is no file of the checkout it is about, nor
/// of a checkout made from it, which has documents of its own.
#[test]
Expand Down
Loading
Loading