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
2 changes: 1 addition & 1 deletion crates/openshell-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1919,7 +1919,7 @@ enum SandboxCommands {

/// Destination path in the sandbox (defaults to its working directory).
///
/// For an unfiltered single-file upload, an existing directory or a
/// For a single-file upload, an existing directory or a
/// trailing slash places the file inside that directory. A missing
/// nested path without a trailing slash renames the file.
dest: Option<String>,
Expand Down
280 changes: 232 additions & 48 deletions crates/openshell-cli/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@ pub use openshell_core::forward::{

#[derive(Debug, PartialEq, Eq)]
pub(crate) enum SandboxUploadPlan {
GitFilteredFile {
local_path: PathBuf,
git_basename: String,
},
GitAware {
base_dir: PathBuf,
files: Vec<String>,
Expand Down Expand Up @@ -5753,10 +5757,14 @@ pub fn git_sync_files(local_path: &Path) -> Result<(PathBuf, Vec<String>)> {
.into_diagnostic()
.wrap_err("failed to canonicalize local upload path")?;
let repo_root = git_repo_root(&local_path)?;
git_sync_files_in_repo(&local_path, &repo_root)
git_sync_files_in_repo(&local_path, &repo_root, local_path.is_file())
}

fn git_sync_files_in_repo(local_path: &Path, repo_root: &Path) -> Result<(PathBuf, Vec<String>)> {
fn git_sync_files_in_repo(
local_path: &Path,
repo_root: &Path,
is_file: bool,
) -> Result<(PathBuf, Vec<String>)> {
let repo_root = std::fs::canonicalize(repo_root)
.into_diagnostic()
.wrap_err("failed to canonicalize git repository root")?;
Expand All @@ -5771,27 +5779,55 @@ fn git_sync_files_in_repo(local_path: &Path, repo_root: &Path) -> Result<(PathBu
)
})?;

let is_file = local_path.is_file();
let base_dir = if is_file {
local_path
let listing = git_upload_listing(&repo_root, relative_path, &[])?;
if is_file {
let base_dir = local_path
.parent()
.map(Path::to_path_buf)
.ok_or_else(|| miette::miette!("path has no parent: {}", local_path.display()))?
} else {
local_path.to_path_buf()
};
let pathspec = if relative_path.as_os_str().is_empty() {
None
} else {
Some(relative_path.to_string_lossy().into_owned())
};
.ok_or_else(|| miette::miette!("path has no parent: {}", local_path.display()))?;
let basename = git_selected_file_basename(&repo_root, relative_path, &listing)?;
return Ok((base_dir, basename.into_iter().collect()));
}

let mut files = Vec::new();
for entry in listing
.split_terminator('\0')
.filter(|entry| !entry.is_empty())
{
let path = Path::new(entry)
.strip_prefix(relative_path)
.into_diagnostic()?;
if !path.as_os_str().is_empty() {
files.push(path.to_string_lossy().into_owned());
}
}

Ok((local_path.to_path_buf(), files))
}

fn git_upload_listing(
repo_root: &Path,
relative_path: &Path,
git_options: &[&str],
) -> Result<String> {
let pathspec = (!relative_path.as_os_str().is_empty()).then_some(relative_path);

let mut command = Command::new("git");
scrub_git_env(&mut command);
let output = command
.args(["ls-files", "-co", "--exclude-standard", "-z"])
.args(pathspec.as_deref())
.current_dir(&repo_root)
.env_remove("GIT_GLOB_PATHSPECS")
.env_remove("GIT_ICASE_PATHSPECS")
.args(git_options)
.args([
"--literal-pathspecs",
Comment thread
gator-review-bot[bot] marked this conversation as resolved.
Resolved
"ls-files",
"-co",
"--exclude-standard",
"-z",
"--",
])
.args(pathspec)
.current_dir(repo_root)
.output()
.into_diagnostic()
.wrap_err("failed to run git ls-files")?;
Expand All @@ -5803,34 +5839,64 @@ fn git_sync_files_in_repo(local_path: &Path, repo_root: &Path) -> Result<(PathBu
));
}

let mut files = Vec::new();
for entry in output.stdout.split(|byte| *byte == 0) {
if entry.is_empty() {
continue;
}
let repo_relative = Path::new(std::str::from_utf8(entry).into_diagnostic()?);
let path = if is_file {
repo_relative
.file_name()
.map(PathBuf::from)
.ok_or_else(|| {
miette::miette!("path has no file name: {}", repo_relative.display())
})?
} else if relative_path.as_os_str().is_empty() {
repo_relative.to_path_buf()
} else {
repo_relative
.strip_prefix(relative_path)
.into_diagnostic()?
.to_path_buf()
};
if path.as_os_str().is_empty() {
continue;
String::from_utf8(output.stdout).into_diagnostic()
}

fn git_selected_file_basename(
repo_root: &Path,
relative_path: &Path,
listing: &str,
) -> Result<Option<String>> {
let depth = relative_path.components().count();
// Deeper matches are stale index entries below a directory replaced by the source file.
let mut matches = listing
.split_terminator('\0')
.map(Path::new)
.filter(|path| path.components().count() == depth);
let Some(git_path) = matches.next() else {
return Ok(None);
};
if matches.any(|path| path != git_path) {
return Err(miette::miette!(
"Git returned multiple paths for {}",
relative_path.display()
));
}

if git_path != relative_path && !git_path_names_source(repo_root, git_path, relative_path) {
// The normalized match can name a different directory entry. Use Git's
// exact filename lookup to establish eligibility for the source.
let exact_listing = git_upload_listing(
repo_root,
relative_path,
&["-c", "core.precomposeunicode=false"],
)?;
if !exact_listing
.split_terminator('\0')
.any(|path| Path::new(path) == relative_path)
{
return Ok(None);
}
files.push(path.to_string_lossy().into_owned());
}

Ok((base_dir, files))
let basename = git_path
.file_name()
.ok_or_else(|| miette::miette!("path has no file name: {}", git_path.display()))?;
Ok(Some(basename.to_string_lossy().into_owned()))
}

fn git_path_names_source(repo_root: &Path, git_path: &Path, relative_path: &Path) -> bool {
let mut joined_path = repo_root.to_path_buf();
for component in git_path.components() {
joined_path.push(component);
// A symlink can resolve to the source while referring to a different Git entry.
if !std::fs::symlink_metadata(&joined_path)
.is_ok_and(|metadata| !metadata.file_type().is_symlink())
{
return false;
}
}
std::fs::canonicalize(joined_path).is_ok_and(|path| path == repo_root.join(relative_path))
}

fn sandbox_upload_plan(local_path: &Path, git_ignore: bool) -> Result<SandboxUploadPlan> {
Expand All @@ -5849,7 +5915,7 @@ fn sandbox_upload_plan(local_path: &Path, git_ignore: bool) -> Result<SandboxUpl
return Ok(SandboxUploadPlan::Regular);
}

let plan = git_filtered_upload_plan(local_path).wrap_err_with(|| {
let plan = git_filtered_upload_plan(local_path, metadata.is_file()).wrap_err_with(|| {
format!(
"Git filtering failed for {}; upload stopped.\nUse --no-git-ignore to upload intentionally without filtering",
local_path.display(),
Expand All @@ -5866,7 +5932,7 @@ fn sandbox_upload_plan(local_path: &Path, git_ignore: bool) -> Result<SandboxUpl
Ok(plan)
}

fn git_filtered_upload_plan(local_path: &Path) -> Result<SandboxUploadPlan> {
fn git_filtered_upload_plan(local_path: &Path, is_file: bool) -> Result<SandboxUploadPlan> {
let canonical_path = std::fs::canonicalize(local_path)
.into_diagnostic()
.wrap_err("failed to canonicalize local upload path")?;
Expand All @@ -5877,7 +5943,14 @@ fn git_filtered_upload_plan(local_path: &Path) -> Result<SandboxUploadPlan> {
);
return Ok(SandboxUploadPlan::Regular);
};
let (base_dir, files) = git_sync_files_in_repo(&canonical_path, &repo_root)?;
let (base_dir, files) = git_sync_files_in_repo(&canonical_path, &repo_root, is_file)?;
if is_file && let Some(name) = files.first() {
// Git may normalize the basename to a spelling that names a different local file.
return Ok(SandboxUploadPlan::GitFilteredFile {
local_path: canonical_path,
Comment thread
gator-review-bot[bot] marked this conversation as resolved.
Resolved
git_basename: name.clone(),
});
}
Ok(SandboxUploadPlan::GitAware { base_dir, files })
}

Expand Down Expand Up @@ -9367,16 +9440,110 @@ mod tests {
fs::create_dir_all(repo.join("nested")).expect("create repo");
init_git_repo(&repo);

fs::write(repo.join("tracked.txt"), "tracked").expect("write tracked.txt");
let source = repo.join("config[1].txt");
fs::write(&source, "selected").expect("write literal filename");
fs::write(repo.join("config1.txt"), "other").expect("write glob-matched sibling");
fs::write(repo.join("nested/other.txt"), "other").expect("write other.txt");

let result = git_sync_files(&repo.join("tracked.txt"));
let result = git_sync_files(&source);
let (base_dir, files) = result.expect("git_sync_files should succeed");
assert_eq!(
base_dir,
fs::canonicalize(&repo).expect("canonicalize repo path")
);
assert_eq!(files, vec!["tracked.txt"]);
assert_eq!(files, vec!["config[1].txt"]);
assert_eq!(
sandbox_upload_plan(&source, true).expect("plan a Git-filtered file upload"),
super::SandboxUploadPlan::GitFilteredFile {
local_path: fs::canonicalize(&source).expect("canonicalize upload path"),
git_basename: "config[1].txt".into(),
}
);
}

#[cfg(target_os = "macos")]
#[test]
fn sandbox_upload_plan_keeps_local_path_with_git_precomposed_basename() {
let repo = tempfile::tempdir().expect("create repo");
init_git_repo(repo.path());
let mut config = Command::new("git");
super::scrub_git_env(&mut config);
assert!(
config
.args(["config", "core.precomposeunicode", "true"])
.current_dir(repo.path())
.status()
.expect("set Git filename normalization")
.success()
);
let source_directory = repo.path().join("cafe\u{301}");
fs::create_dir(&source_directory).expect("create decomposed directory name");
let source = source_directory.join("cafe\u{301}.txt");
fs::write(&source, "selected").expect("write decomposed filename");
let local_path = fs::canonicalize(&source).expect("canonicalize upload path");

assert_eq!(
sandbox_upload_plan(&source, true).expect("plan a Git-filtered file upload"),
super::SandboxUploadPlan::GitFilteredFile {
local_path,
git_basename: "caf\u{e9}.txt".into(),
}
);
}

#[test]
fn git_sync_files_rechecks_source_when_git_match_names_another_entry() {
let repo = tempfile::tempdir().expect("create repo");
init_git_repo(repo.path());
let repo_root = fs::canonicalize(repo.path()).expect("canonicalize repo path");
let requested = "cafe\u{301}.txt";
let git_match = repo_root.join("git-name.txt");
fs::write(repo_root.join(requested), "requested").expect("write requested file");
fs::write(&git_match, "other").expect("write a different file");
fs::write(repo_root.join(".gitignore"), format!("/{requested}\n"))
.expect("ignore requested file");

let git = |args: &[&str]| {
let mut command = Command::new("git");
super::scrub_git_env(&mut command);
assert!(
command
.args(args)
.current_dir(&repo_root)
.status()
.expect("run Git fixture command")
.success(),
"git {args:?} failed"
);
};
git(&["config", "core.precomposeunicode", "true"]);
git(&["add", "-f", "--", "git-name.txt"]);
// Use a distinct pathname to exercise the fallback even on APFS.
let git_listing = "git-name.txt\0";
let selected =
|| super::git_selected_file_basename(&repo_root, Path::new(requested), git_listing);

assert_eq!(selected().expect("check distinct Git entry"), None);
fs::remove_file(&git_match).expect("leave an index-only Git entry");
assert_eq!(selected().expect("check index-only Git entry"), None);
#[cfg(unix)]
{
std::os::unix::fs::symlink(requested, &git_match).expect("link to requested file");
assert_eq!(selected().expect("check symlink Git entry"), None);
}

git(&[
"-c",
"core.precomposeunicode=false",
"add",
"-f",
"--",
requested,
]);
assert_eq!(
selected().expect("check exact tracked source"),
Some("git-name.txt".into())
);
}

#[test]
Expand Down Expand Up @@ -9470,10 +9637,27 @@ mod tests {

fs::create_dir(repo.join("empty")).expect("create empty directory");

let replaced = repo.join("replaced");
fs::create_dir(&replaced).expect("create directory to replace");
fs::write(replaced.join("tracked.txt"), "tracked").expect("write tracked child");
let mut add = Command::new("git");
super::scrub_git_env(&mut add);
assert!(
add.args(["add", "replaced/tracked.txt"])
.current_dir(&repo)
.status()
.expect("stage tracked child")
.success()
);
fs::remove_dir_all(&replaced).expect("remove directory with tracked child");
fs::write(&replaced, "ignored").expect("replace directory with a regular file");
fs::write(repo.join(".gitignore"), "runs/\n/replaced\n").expect("write ignore rules");

for path in [
repo.join("runs"),
repo.join("runs/test.json"),
repo.join("empty"),
replaced,
] {
let err =
sandbox_upload_plan(&path, true).expect_err("empty selection must stop upload");
Expand Down
7 changes: 7 additions & 0 deletions crates/openshell-cli/src/ssh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1549,6 +1549,13 @@ pub(crate) async fn sandbox_upload_planned(
) -> Result<Option<String>> {
use crate::run::SandboxUploadPlan;
let source = match plan {
SandboxUploadPlan::GitFilteredFile {
local_path,
git_basename,
} => UploadSource::SinglePath {
local_path,
tar_name: git_basename.into(),
},
SandboxUploadPlan::GitAware { files, .. } if files.is_empty() => return Ok(None),
SandboxUploadPlan::GitAware { base_dir, files } => UploadSource::FileList {
base_dir,
Expand Down
Loading
Loading