Skip to content
Open
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
28 changes: 28 additions & 0 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,23 @@ pub async fn named_files(
Ok((commit, selected))
}

/// A repository-relative path as Git writes it, from a command-line value.
///
/// Windows shells and editors write `\` between path segments: `VS Code`'s
/// Copy Relative Path gives `src\main.rs`. Git separates segments with `/`
/// on every platform, and Git for Windows never checks out a path containing
/// `\`, so there each `\` becomes `/`. Elsewhere `\` is an ordinary file name
/// byte and the value is kept as written. Every other check is unchanged:
/// `.`, `..` and empty segments are still refused, and the result must still
/// name one exact tracked file.
pub fn repository_path(value: &str) -> String {
if cfg!(windows) {
value.replace('\\', "/")
} else {
value.to_owned()
}
}

/// The change one commit makes: the commit against its first parent.
pub async fn pushed_commit(dir: &Path, revision: &str) -> Result<PushedChange, GitError> {
let head_commit_sha = resolve(dir, revision).await?;
Expand Down Expand Up @@ -637,6 +654,17 @@ pub fn full_name(url: &str) -> Option<String> {
mod tests {
use super::*;

#[test]
fn repository_paths_use_git_separators_only_where_backslash_cannot_be_a_name() {
let path = repository_path(r".\nested\file.txt");
if cfg!(windows) {
assert_eq!(path, "./nested/file.txt");
} else {
assert_eq!(path, r".\nested\file.txt");
}
assert_eq!(repository_path("a/b.txt"), "a/b.txt");
}

#[test]
fn reads_owner_and_name_from_remote_urls() {
for url in [
Expand Down
15 changes: 13 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,11 @@ struct LocalSelectionArgs {
include_untracked: bool,
}

/// Reads a repository-relative path argument in Git's `/` form.
fn repository_path(value: &str) -> Result<String, std::convert::Infallible> {
Ok(git::repository_path(value))
}

#[derive(Debug, Args)]
struct ReviewArgs {
/// Print the JSON result schema without requesting or reading a review.
Expand All @@ -363,6 +368,7 @@ struct ReviewArgs {
commit: Option<String>,
/// Review the complete contents of up to twenty tracked files at --commit.
#[arg(long, value_name = "PATH", num_args = 1..=20, requires = "commit",
value_parser = repository_path,
conflicts_with_all = ["pr", "range", "staged", "include_untracked", "allow_path"])]
files: Vec<String>,
/// Review the change from BASE to HEAD, both pushed, BASE an ancestor of
Expand All @@ -375,7 +381,12 @@ struct ReviewArgs {
)]
range: Option<String>,
/// Review only this literal repository-relative file in the local patch.
#[arg(long, value_name = "PATH", conflicts_with_all = ["pr", "commit", "range", "files"])]
#[arg(
long,
value_name = "PATH",
value_parser = repository_path,
conflicts_with_all = ["pr", "commit", "range", "files"]
)]
path: Option<String>,
/// Re-verify these open findings of one pull request against the local
/// changes, and print each one's outcome. The outcome is local: the pull
Expand All @@ -400,7 +411,7 @@ struct ReviewArgs {
fail_on: Option<Severity>,
/// Include secret-shaped patch content from this exact repository-relative
/// path. Repeat for more paths; each override applies only to local review.
#[arg(long, value_name = "PATH", conflicts_with = "pr")]
#[arg(long, value_name = "PATH", value_parser = repository_path, conflicts_with = "pr")]
allow_path: Vec<String>,
#[command(flatten)]
repository: RepositoryArgs,
Expand Down
91 changes: 91 additions & 0 deletions tests/local_patch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1223,3 +1223,94 @@ async fn local_path_never_expands_a_file_replaced_by_a_directory() {
assert_eq!(checkout.index().await, index);
server.close().await;
}

/// Windows shells, `PowerShell` tab completion and editors' Copy Relative Path
/// write `\` between segments. Git for Windows never checks out a path that
/// contains `\`, so the same file must be selected, overridden or named as
/// with `/`, and the request must carry Git's `/` form.
#[cfg(windows)]
#[tokio::test]
async fn windows_backslash_paths_select_the_same_tracked_file() {
let github = format!("ghp_{}", "C".repeat(36));
let checkout = Checkout::new(&[
("nested/file.txt", "base\n"),
("other.txt", "base\n"),
("config/token.txt", "base\n"),
])
.await;
checkout.write("nested/file.txt", "changed\n").await;
checkout.write("other.txt", "excluded\n").await;
let server = Server::start(true).await;
let output = checkout
.review(&server, &[], &["--path", r"nested\file.txt"])
.await;
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
{
let uploads = server.fixture.uploads.lock().unwrap();
assert_eq!(uploads.len(), 1);
let patch = uploads[0]["patch"].as_str().unwrap();
assert!(patch.contains("diff --git a/nested/file.txt b/nested/file.txt"));
assert!(!patch.contains("excluded"), "{patch}");
}
server.close().await;

// Traversal, directories and `.` segments stay refused when written with
// `\`, exactly as they are with `/`.
let server = Server::start(true).await;
for path in [
r".\nested\file.txt",
r"..\file.txt",
r"nested\..\nested\file.txt",
"nested",
r"nested\",
] {
let output = checkout.review(&server, &[], &["--path", path]).await;
assert!(!output.status.success(), "{path}");
assert!(
String::from_utf8_lossy(&output.stderr)
.contains("exact repository-relative tracked file")
);
}
server.assert_no_requests();

// A `\` override allows exactly the file the refusal names with `/`.
checkout.write("other.txt", "base\n").await;
checkout
.write("config/token.txt", &format!("first\n{github}\n"))
.await;
let refused = checkout.review(&server, &[], &[]).await;
assert_refusal(&refused, "\"config/token.txt\":2 (new line)", &github);
server.assert_no_requests();
let allowed = checkout.review(&server, &[r"config\token.txt"], &[]).await;
assert!(
allowed.status.success(),
"{}",
String::from_utf8_lossy(&allowed.stderr)
);
assert_eq!(server.fixture.uploads.lock().unwrap().len(), 1);
server.close().await;

// Named whole files reach the server in Git's `/` form.
let server = Server::start(true).await;
let output = checkout
.review(
&server,
&[],
&["--commit", "HEAD", "--files", r"nested\file.txt"],
)
.await;
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(
*server.fixture.file_requests.lock().unwrap(),
vec![json!({ "commit_sha": checkout.base, "paths": ["nested/file.txt"] })]
);
server.close().await;
}