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
10 changes: 5 additions & 5 deletions crates/repo/src/private.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ impl Repo {
}
}
let mut skipped = Vec::new();
for (path, (blob_id, _mode, perms)) in &target {
for (path, (blob_id, mode, perms)) in &target {
if !sparse.matches(path) {
continue;
}
Expand All @@ -404,7 +404,7 @@ impl Repo {
if let Some(parent) = full.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&full, &pt[..])?;
worktree::write_file(&full, &pt[..], *mode)?;
}
Err(_) => {
// KEK recipient without path access: skip, never
Expand All @@ -422,7 +422,7 @@ impl Repo {
if let Some(parent) = full.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&full, &bytes[..])?;
worktree::write_file(&full, &bytes[..], *mode)?;
}
}
Ok(skipped)
Expand Down Expand Up @@ -1335,11 +1335,11 @@ impl Repo {
wrapped: fm.wrapped_carry.clone(),
};
match crate::protect::decrypt_with(&f.bytes, &id, &[&prots], sk, &f.path) {
Ok(pt) => std::fs::write(&full, &pt[..])?,
Ok(pt) => worktree::write_file(&full, &pt[..], f.mode)?,
Err(_) => continue, // undecryptable: leave prior state
}
} else {
std::fs::write(&full, &f.bytes)?;
worktree::write_file(&full, &f.bytes, f.mode)?;
}
}
for (name, bytes) in &fm.sidecars {
Expand Down
4 changes: 2 additions & 2 deletions crates/repo/src/repo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1974,12 +1974,12 @@ impl Repo {
&self.layout,
&sidecars.iter().map(|(r, _)| r.clone()).collect::<Vec<_>>(),
)?;
for (path, bytes, _mode, _recipients) in to_encrypt {
for (path, bytes, mode, _recipients) in to_encrypt {
let full = worktree::safe_join(&self.layout.root, path)?;
if let Some(parent) = full.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(full, bytes)?;
worktree::write_file(&full, bytes, *mode)?;
}
for (rel, bytes) in sidecars {
let full = self.layout.root.join(rel);
Expand Down
40 changes: 37 additions & 3 deletions crates/repo/src/worktree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,40 @@ fn tracked_under(tracked: &BTreeSet<String>, dir: &str) -> bool {
.is_some_and(|p| p.starts_with(&prefix))
}

/// Write `bytes` to `path` and lay down the recorded `mode`'s executable bit,
/// the one place checkout-style writes go through so `read_worktree` (which
/// reads the mode back from the filesystem) round-trips. EXEC adds an execute
/// bit wherever the file already has a read bit (the umask-respecting default
/// stays); FILE clears any execute bits an existing file had. A no-op off unix;
/// a filesystem that refuses the chmod (no mode bits) is not an error.
pub(crate) fn write_file(path: &Path, bytes: &[u8], mode: FileMode) -> std::io::Result<()> {
std::fs::write(path, bytes)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let cur = std::fs::metadata(path)?.permissions().mode();
let want = if mode.0 & 0o111 != 0 {
cur | ((cur & 0o444) >> 2)
} else {
cur & !0o111
};
if want != cur {
match std::fs::set_permissions(path, std::fs::Permissions::from_mode(want)) {
Err(e)
if e.kind() != std::io::ErrorKind::Unsupported
&& e.kind() != std::io::ErrorKind::PermissionDenied =>
Comment on lines +158 to +160

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not silently ignore failed mode changes

On Unix filesystems where the checkout can write a file but cannot chmod it (for example, an ACL-writable file owned by another user or some NFS/CIFS mounts), set_permissions returns PermissionDenied and this branch reports success despite leaving the executable bit unchanged. The switch/merge can then advance its ref with a dirty working tree, and a subsequent commit may record the stale mode; only ignore a genuinely unsupported operation, or verify that the resulting executable bits match before returning success.

Useful? React with 👍 / 👎.

{
return Err(e)
}
_ => {}
}
}
}
#[cfg(not(unix))]
let _ = mode;
Ok(())
}

#[cfg(unix)]
fn file_mode(path: &Path) -> FileMode {
use std::os::unix::fs::PermissionsExt;
Expand Down Expand Up @@ -888,7 +922,7 @@ pub(crate) fn materialize_with_old_view(
}
}
let mut skipped = Vec::new();
for (path, (blob_id, _mode, perms)) in &target {
for (path, (blob_id, mode, perms)) in &target {
if !sparse.matches(path) {
continue;
}
Expand Down Expand Up @@ -916,7 +950,7 @@ pub(crate) fn materialize_with_old_view(
if let Some(parent) = full.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&full, &pt[..])?;
write_file(&full, &pt[..], *mode)?;
// Record a randomized entry's cache entry right after the
// write (P33): without this, the next `diff_worktree`/
// `status` on this exact, unmodified plaintext has no
Expand Down Expand Up @@ -950,7 +984,7 @@ pub(crate) fn materialize_with_old_view(
if let Some(parent) = full.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&full, &bytes[..])?;
write_file(&full, &bytes[..], *mode)?;
}
}
// The removal walk above covered the replaced view, and the tree is now
Expand Down
195 changes: 195 additions & 0 deletions crates/repo/tests/exec_bit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
//! #237: every checkout-style write restores the recorded executable bit and
//! clears a stale one, so `read_worktree` (which reads the mode back from the
//! filesystem) round-trips EXEC and FILE through switch, merge, rebase,
//! sparse set, clone and `sc ws` checkouts.
#![cfg(unix)]

use scl_core::FileMode;
use scl_repo::{worktree, Repo};
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};

/// A scratch directory removed (and checked gone) when the test ends.
struct Tmp(PathBuf);

impl std::ops::Deref for Tmp {
type Target = Path;
fn deref(&self) -> &Path {
&self.0
}
}

impl AsRef<Path> for Tmp {
fn as_ref(&self) -> &Path {
&self.0
}
}

impl Drop for Tmp {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
if !std::thread::panicking() {
assert!(!self.0.exists());
}
}
}

fn tmp(tag: &str) -> Tmp {
let p = std::env::temp_dir().join(format!("scl-exec-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&p);
Tmp(p)
}

fn put(root: &Path, rel: &str, body: &str, exec: bool) {
let full = root.join(rel);
std::fs::create_dir_all(full.parent().unwrap()).unwrap();
std::fs::write(&full, body).unwrap();
let mode = if exec { 0o755 } else { 0o644 };
std::fs::set_permissions(&full, std::fs::Permissions::from_mode(mode)).unwrap();
}

fn on_disk_exec(root: &Path, rel: &str) -> bool {
std::fs::metadata(root.join(rel))
.unwrap()
.permissions()
.mode()
& 0o111
!= 0
}

/// The mode the current tip records for `rel`.
fn committed(repo: &Repo, rel: &str) -> FileMode {
let tip = repo.head_tip().unwrap().unwrap();
let store = repo.vfs().store();
let mut store = store.lock().unwrap();
let root = store.get_snapshot(&tip).unwrap().root;
worktree::tree_file_entries(&mut store, root).unwrap()[rel].1
}

/// Status is clean, and a follow-up commit (touching `touch`) keeps `rel` EXEC/FILE.
fn assert_round_trips(repo: &Repo, root: &Path, rel: &str, exec: bool, touch: &str) {
assert_eq!(on_disk_exec(root, rel), exec, "{rel} on disk");
let st = repo.status().unwrap();
assert!(
st.added.is_empty() && st.modified.is_empty() && st.deleted.is_empty(),
"status not clean: {st:?}"
);
std::fs::write(root.join(touch), format!("touch-{}", rand_tag(repo))).unwrap();
repo.commit("t", "touch").unwrap();
let want = if exec { FileMode::EXEC } else { FileMode::FILE };
assert_eq!(committed(repo, rel), want, "{rel} committed");
}

fn rand_tag(repo: &Repo) -> String {
repo.head_tip().unwrap().unwrap().short().to_string()
}

fn base(tag: &str) -> (Repo, Tmp) {
let root = tmp(tag);
let repo = Repo::init(&root).unwrap();
put(&root, "seed.txt", "seed", false);
repo.commit("t", "seed").unwrap();
(repo, root)
}

#[test]
fn switch_restores_exec_and_clears_it_for_plain_files() {
let (repo, root) = base("switch");
put(&root, "run.sh", "#!/bin/sh\n", true);
put(&root, "data.txt", "d", false);
repo.commit("t", "add").unwrap();
repo.branch("plain").unwrap();
repo.switch("plain").unwrap();
// On `plain` the same path is an ordinary file (content differs).
put(&root, "run.sh", "not a script\n", false);
repo.commit("t", "demote").unwrap();

repo.switch("main").unwrap();
assert_round_trips(&repo, &root, "run.sh", true, "data.txt");
assert_round_trips(&repo, &root, "data.txt", false, "seed.txt");
// EXEC -> FILE: the stale bit is cleared on the existing file.
repo.switch("plain").unwrap();
assert_round_trips(&repo, &root, "run.sh", false, "data.txt");
// And back again.
repo.switch("main").unwrap();
assert_round_trips(&repo, &root, "run.sh", true, "data.txt");
}

#[test]
fn merge_creates_exec_file_with_its_bit() {
let (repo, root) = base("merge");
repo.branch("feat").unwrap();
repo.switch("feat").unwrap();
put(&root, "run.sh", "#!/bin/sh\n", true);
repo.commit("t", "script").unwrap();
repo.switch("main").unwrap();
put(&root, "m.txt", "m", false);
repo.commit("t", "m").unwrap();
assert!(!root.join("run.sh").exists());

repo.merge("feat", "t").unwrap();
assert_round_trips(&repo, &root, "run.sh", true, "m.txt");
}

#[test]
fn rebase_creates_exec_file_with_its_bit() {
let (repo, root) = base("rebase");
repo.branch("feat").unwrap();
repo.switch("feat").unwrap();
put(&root, "f.txt", "f", false);
repo.commit("t", "f").unwrap();
repo.switch("main").unwrap();
put(&root, "run.sh", "#!/bin/sh\n", true);
repo.commit("t", "script").unwrap();
repo.switch("feat").unwrap();
assert!(!root.join("run.sh").exists());

repo.rebase("main", "t", None).unwrap();
assert_round_trips(&repo, &root, "run.sh", true, "f.txt");
}

#[test]
fn sparse_set_lays_out_exec_files_with_their_bit() {
let (repo, root) = base("sparse");
put(&root, "a/run.sh", "#!/bin/sh\n", true);
put(&root, "b/x.txt", "x", false);
repo.commit("t", "tree").unwrap();

repo.set_sparse(&["b".to_string()], None).unwrap();
assert!(!root.join("a/run.sh").exists());
// Widening lays a/run.sh out afresh.
repo.set_sparse(&["a".to_string(), "b".to_string()], None)
.unwrap();
assert_round_trips(&repo, &root, "a/run.sh", true, "b/x.txt");
}

#[test]
fn clone_keeps_exec_bit() {
let (repo, root) = base("clone-src");
put(&root, "run.sh", "#!/bin/sh\n", true);
put(&root, "plain.txt", "p", false);
repo.commit("t", "add").unwrap();

let dst = tmp("clone-dst");
let cloned = Repo::clone_to(&root, &dst).unwrap();
assert_round_trips(&cloned, &dst, "run.sh", true, "plain.txt");
assert!(!on_disk_exec(&dst, "seed.txt"));
}

#[test]
fn ws_checkout_keeps_exec_bit() {
let (repo, root) = base("ws");
put(&root, "run.sh", "#!/bin/sh\n", true);
put(&root, "plain.txt", "p", false);
repo.commit("t", "add").unwrap();

let session = repo.ws_fork(1, "t", None).unwrap();
let dir = &session.workspaces[0].dir;
assert!(on_disk_exec(dir, "run.sh"));
assert!(!on_disk_exec(dir, "plain.txt"));
// Harvesting an edit of another file must not demote the script.
std::fs::write(dir.join("plain.txt"), "edited").unwrap();
repo.ws_harvest(None, "t", None).unwrap();
assert_eq!(committed(&repo, "run.sh"), FileMode::EXEC);
assert_eq!(committed(&repo, "plain.txt"), FileMode::FILE);
}
30 changes: 30 additions & 0 deletions crates/vfs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,36 @@ mod tests {
assert!(!dest.exists());
}

#[cfg(unix)]
#[test]
fn checkout_restores_exec_bit_and_not_on_plain_files() {
use std::os::unix::fs::PermissionsExt;
let r = repo();
let snap = r
.commit_files(
&[
("run.sh".into(), b"#!/bin/sh\n".to_vec(), FileMode::EXEC),
("plain.txt".into(), b"x".to_vec(), FileMode::FILE),
],
"t",
"m",
)
.unwrap();
let wt = r.fork(snap, "a").unwrap();
let dest = std::env::temp_dir().join(format!("scl-co-exec-{}", std::process::id()));
wt.checkout(&dest).unwrap();
let mode = |p: &str| {
std::fs::metadata(dest.join(p))
.unwrap()
.permissions()
.mode()
};
assert_ne!(mode("run.sh") & 0o111, 0);
assert_eq!(mode("plain.txt") & 0o111, 0);
std::fs::remove_dir_all(&dest).unwrap();
assert!(!dest.exists());
}

#[test]
fn commit_overlay_produces_new_snapshot() {
let r = repo();
Expand Down
Loading