Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

acp_thread: Render Git-quoted and relative patch paths (#65855)

Ben Brandt3c11d49cbf1f
diff --git a/crates/acp_thread/src/diff.rs b/crates/acp_thread/src/diff.rs
index da751ed9872..a8c991fb8fa 100644
--- a/crates/acp_thread/src/diff.rs
+++ b/crates/acp_thread/src/diff.rs
@@ -13,6 +13,7 @@ use markdown::Markdown;
use multi_buffer::{MultiBuffer, PathKey, excerpt_context_lines};
use std::{cmp::Reverse, ops::Range, path::Path, sync::Arc};
use util::ResultExt;
+use util::paths::PathStyle;
#[derive(Debug)]
pub struct DiffPatch {
@@ -133,15 +134,28 @@ impl DiffPatch {
} else {
paths
};
- let index = change_indices
- .get(&paths)
- .copied()
+ let index = if let Some(index) = change_indices.get(&paths) {
+ *index
+ } else if [paths.0, paths.1]
+ .into_iter()
.flatten()
- .ok_or_else(|| {
- anyhow!(
- "patch paths are ambiguous or do not match the reported file changes"
- )
- })?;
+ .any(|path| !PathStyle::Windows.has_root(path))
+ {
+ // Relative Git paths have no declared root. Only associate a
+ // hunk when both sides identify one reported file operation.
+ let mut matches = change_indices.iter().filter(|(reported, _)| {
+ patch_path_matches(paths.0, reported.0)
+ && patch_path_matches(paths.1, reported.1)
+ });
+ let index = matches.next().and_then(|(_, index)| *index);
+ ensure!(matches.next().is_none(), "ambiguous relative patch paths");
+ index
+ } else {
+ None
+ }
+ .ok_or_else(|| {
+ anyhow!("patch paths are ambiguous or do not match the reported file changes")
+ })?;
ensure!(seen.insert(index), "repeated patch file");
let change = source
.changes
@@ -151,7 +165,7 @@ impl DiffPatch {
matches!(change.file_type, None | Some(acp_v2::DiffFileType::Text)),
"text patch supplied for a non-text file"
);
- if anonymous && let Some((old, new)) = diff_change_paths(change) {
+ if let Some((old, new)) = diff_change_paths(change) {
file.old_path = old.map(|path| path.to_string_lossy().into_owned());
file.new_path = new.map(|path| path.to_string_lossy().into_owned());
}
@@ -168,6 +182,15 @@ impl DiffPatch {
}
}
+fn patch_path_matches(patch: Option<&Path>, reported: Option<&Path>) -> bool {
+ match (patch, reported) {
+ (None, None) => true,
+ (Some(patch), Some(reported)) if PathStyle::Windows.has_root(patch) => patch == reported,
+ (Some(patch), Some(reported)) => reported.ends_with(patch),
+ _ => false,
+ }
+}
+
impl DiffPatchHunk {
fn new(
hunk: patch::PatchHunk,
@@ -746,6 +769,63 @@ mod tests {
))
.is_ok()
);
+ for (patch, changes, expected) in [
+ (
+ "--- a/src/one.rs\n+++ b/src/one.rs\n@@ -1 +1 @@\n-old\n+new\n",
+ json!([
+ {"operation": "modify", "path": "/project/src/one.rs"},
+ {"operation": "modify", "path": "/project/src/two.rs"}
+ ]),
+ Some((0, Some("/project/src/one.rs"), Some("/project/src/one.rs"))),
+ ),
+ (
+ "--- old.rs\n+++ new.rs\n@@ -1 +1 @@\n-old\n+new\n",
+ json!([
+ {"operation": "move", "oldPath": "/project/old.rs", "path": "/project/new.rs"},
+ {"operation": "move", "oldPath": "/other/old.rs", "path": "/other/different.rs"}
+ ]),
+ Some((0, Some("/project/old.rs"), Some("/project/new.rs"))),
+ ),
+ (
+ "--- /dev/null\n+++ b/added.rs\n@@ -0,0 +1 @@\n+new\n",
+ json!([{"operation": "add", "path": "/project/added.rs"}]),
+ Some((0, None, Some("/project/added.rs"))),
+ ),
+ (
+ "--- a/deleted.rs\n+++ /dev/null\n@@ -1 +0,0 @@\n-old\n",
+ json!([{"operation": "delete", "path": "/project/deleted.rs"}]),
+ Some((0, Some("/project/deleted.rs"), None)),
+ ),
+ (
+ "--- one.rs\n+++ one.rs\n@@ -1 +1 @@\n-old\n+new\n",
+ json!([
+ {"operation": "modify", "path": "/project/one.rs"},
+ {"operation": "modify", "path": "/other/one.rs"}
+ ]),
+ None,
+ ),
+ (
+ "--- src/one.rs\n+++ src/one.rs\n@@ -1 +1 @@\n-old\n+new\n",
+ json!([{"operation": "modify", "path": "/project/not-src/one.rs"}]),
+ None,
+ ),
+ (
+ "--- old.rs\n+++ wrong.rs\n@@ -1 +1 @@\n-old\n+new\n",
+ json!([{"operation": "copy", "oldPath": "/project/old.rs", "path": "/project/new.rs"}]),
+ None,
+ ),
+ ] {
+ let parsed = DiffPatch::parse(&source(patch, changes));
+ if let Some((index, old, new)) = expected {
+ let parsed = parsed.expect("unique relative paths");
+ assert_eq!(parsed.len(), 1);
+ assert_eq!(parsed[0].0, index);
+ assert_eq!(parsed[0].1.old_path.as_deref(), old);
+ assert_eq!(parsed[0].1.new_path.as_deref(), new);
+ } else {
+ assert!(parsed.is_err(), "{patch}");
+ }
+ }
}
#[test]
@@ -823,7 +903,7 @@ mod tests {
#[gpui::test]
async fn test_patch_hunks_render_read_only_snippets(cx: &mut TestAppContext) {
- let patch = indoc! {"
+ let patch = indoc! {r#"
diff --git /one /one
--- /one
+++ /one
@@ -844,7 +924,25 @@ mod tests {
+++ /added
@@ -0,0 +1 @@
+added
- "};
+ diff --git "/project/\303\251t\303\251.rs" "/project/\346\226\260.rs"
+ similarity index 75%
+ rename from "/project/\303\251t\303\251.rs"
+ rename to "/project/\346\226\260.rs"
+ --- "/project/\303\251t\303\251.rs"
+ +++ "/project/\346\226\260.rs"
+ @@ -1 +1 @@
+ -old
+ +new
+ diff --git /source /copy
+ similarity index 75%
+ copy from /source
+ copy to /copy
+ --- a/source
+ +++ b/copy
+ @@ -1 +1 @@
+ -before
+ +after
+ "#};
let source = source(
patch,
json!([
@@ -852,7 +950,9 @@ mod tests {
{"operation": "delete", "path": "/deleted"},
{"operation": "add", "path": "/added"},
{"operation": "modify", "path": "/image", "fileType": "binary"},
- {"operation": "move", "oldPath": "/old", "path": "/new"}
+ {"operation": "move", "oldPath": "/old", "path": "/new"},
+ {"operation": "move", "oldPath": "/project/été.rs", "path": "/project/新.rs"},
+ {"operation": "copy", "oldPath": "/source", "path": "/copy"}
]),
);
let render = cx.update(|cx| {
@@ -863,7 +963,7 @@ mod tests {
assert!(render.fallback.is_none());
assert_eq!(
render.files.len(),
- 5,
+ 7,
"patchless files must remain represented"
);
assert_eq!(render.files[0].hunks.len(), 2);
@@ -879,6 +979,8 @@ mod tests {
(0, "context\nbefore\nafter\n"),
(1, "deleted\n"),
(2, "added\n"),
+ (5, "old\nnew\n"),
+ (6, "before\nafter\n"),
] {
let buffer = render.files[file_index].hunks[0].buffer.read(cx);
assert!(buffer.read_only());
diff --git a/crates/acp_thread/src/diff/patch.rs b/crates/acp_thread/src/diff/patch.rs
index 2ba41c2dc97..7ab2eec4254 100644
--- a/crates/acp_thread/src/diff/patch.rs
+++ b/crates/acp_thread/src/diff/patch.rs
@@ -1,7 +1,6 @@
use anyhow::{Context as _, Result, ensure};
use diffy::{Line, Patch};
-use std::path::Path;
-use util::paths::PathStyle;
+use std::borrow::Cow;
#[derive(Debug, PartialEq, Eq)]
pub(super) struct PatchFile {
@@ -36,7 +35,8 @@ pub(super) fn parse_patch(text: &str) -> Result<Vec<PatchFile>> {
for section in boundaries.windows(2) {
let section = &text[section[0]..section[1]];
check_coordinate_bounds(section)?;
- let patch = Patch::from_str(section).context("invalid Git patch")?;
+ let section = normalize_quoted_paths(section)?;
+ let patch = Patch::from_str(&section).context("invalid Git patch")?;
if patch.hunks().is_empty() {
// File operations, including binary and rename-only changes, come from ACP's
// structured changes. They do not need to be inferred from Git's preamble.
@@ -88,6 +88,88 @@ pub(super) fn parse_patch(text: &str) -> Result<Vec<PatchFile>> {
Ok(files)
}
+fn normalize_quoted_paths(section: &str) -> Result<Cow<'_, str>> {
+ if section.starts_with("@@ ") {
+ return Ok(Cow::Borrowed(section));
+ }
+ let header_end = section
+ .find("\n@@ ")
+ .map_or(section.len(), |offset| offset + 1);
+ let (headers, hunks) = section.split_at(header_end);
+ if !headers.contains("--- \"") && !headers.contains("+++ \"") {
+ return Ok(Cow::Borrowed(section));
+ }
+
+ // diffy understands escaped quotes, backslashes and whitespace, but not Git's
+ // octal byte escapes or \a, \b, \f and \v. Normalize only filename headers.
+ let mut normalized = Vec::with_capacity(section.len());
+ for line in headers.split_inclusive('\n') {
+ let Some((prefix, filename)) = line.split_once(' ').filter(|(prefix, filename)| {
+ matches!(*prefix, "---" | "+++") && filename.starts_with('"')
+ }) else {
+ normalized.extend_from_slice(line.as_bytes());
+ continue;
+ };
+ let filename_end = filename.find(['\t', '\n']).unwrap_or(filename.len());
+ let (filename, suffix) = filename.split_at(filename_end);
+ let filename = filename
+ .strip_prefix('"')
+ .and_then(|filename| filename.strip_suffix('"'))
+ .context("unterminated quoted patch filename")?;
+ normalized.extend_from_slice(prefix.as_bytes());
+ normalized.extend_from_slice(b" \"");
+ let mut bytes = filename.bytes();
+ while let Some(byte) = bytes.next() {
+ if byte != b'\\' {
+ normalized.push(byte);
+ continue;
+ }
+ let byte = match bytes.next().context("unterminated patch filename escape")? {
+ digit @ b'0'..=b'7' => {
+ let mut value = digit - b'0';
+ for _ in 0..2 {
+ let digit = bytes
+ .next()
+ .filter(|digit| matches!(digit, b'0'..=b'7'))
+ .context("invalid octal patch filename escape")?
+ - b'0';
+ value = value
+ .checked_mul(8)
+ .and_then(|value| value.checked_add(digit))
+ .context("octal patch filename escape exceeds one byte")?;
+ }
+ value
+ }
+ b'a' => 0x07,
+ b'b' => 0x08,
+ b'f' => 0x0c,
+ b'v' => 0x0b,
+ b'n' => b'\n',
+ b'r' => b'\r',
+ b't' => b'\t',
+ b'\\' => b'\\',
+ b'"' => b'"',
+ _ => anyhow::bail!("invalid patch filename escape"),
+ };
+ match byte {
+ b'\0' => normalized.extend_from_slice(b"\\0"),
+ b'\n' => normalized.extend_from_slice(b"\\n"),
+ b'\r' => normalized.extend_from_slice(b"\\r"),
+ b'\t' => normalized.extend_from_slice(b"\\t"),
+ b'\\' => normalized.extend_from_slice(b"\\\\"),
+ b'"' => normalized.extend_from_slice(b"\\\""),
+ byte => normalized.push(byte),
+ }
+ }
+ normalized.push(b'"');
+ normalized.extend_from_slice(suffix.as_bytes());
+ }
+ normalized.extend_from_slice(hunks.as_bytes());
+ Ok(Cow::Owned(
+ String::from_utf8(normalized).context("patch filename is not UTF-8")?,
+ ))
+}
+
fn patch_path(path: Option<&str>, prefix: &str) -> Result<Option<String>> {
let path = path.context("missing patch filename")?;
if path == "/dev/null" {
@@ -95,8 +177,8 @@ fn patch_path(path: Option<&str>, prefix: &str) -> Result<Option<String>> {
}
let path = path.strip_prefix(prefix).unwrap_or(path);
ensure!(
- PathStyle::Windows.has_root(Path::new(path)),
- "patch path must have root: {path}"
+ !path.is_empty() && !path.split(['/', '\\']).any(|component| component == ".."),
+ "empty patch path or parent traversal"
);
ensure!(!path.contains('\0'), "patch path contains NUL");
Ok(Some(path.to_owned()))
@@ -186,7 +268,7 @@ mod tests {
}
#[test]
- fn delegates_quoted_and_spaced_paths_to_diffy() {
+ fn parses_git_quoted_paths_and_file_operations() {
let files = parse_patch(indoc! {r#"
diff --git "a//project/a\tfile" "b//project/a\tfile"
--- "a//project/a\tfile"
@@ -200,20 +282,69 @@ mod tests {
@@ -1 +1 @@
-old
+new
+ diff --git "/project/\303\251t\303\251.rs" "/project/\346\226\260.rs"
+ similarity index 75%
+ rename from "/project/\303\251t\303\251.rs"
+ rename to "/project/\346\226\260.rs"
+ --- "/project/\303\251t\303\251.rs"
+ +++ "/project/\346\226\260.rs"
+ @@ -1 +1 @@
+ -old
+ +new
+ diff --git /project/source /project/copy
+ similarity index 75%
+ copy from /project/source
+ copy to /project/copy
+ --- /project/source
+ +++ /project/copy
+ @@ -1 +1 @@
+ --- "this is hunk text, not a filename"
+ +new
+ diff --git "/project/\a\b\f\n\r\t\v\\\"\303\251" "/project/\a\b\f\n\r\t\v\\\"\303\251"
+ --- "/project/\a\b\f\n\r\t\v\\\"\303\251"
+ +++ "/project/\007\010\014\012\015\011\013\134\042\303\251"
+ @@ -1 +1 @@
+ -old
+ +new
+ diff --git a/src/file.rs b/src/file.rs
+ --- a/src/file.rs
+ +++ b/src/file.rs
+ @@ -1 +1 @@
+ -old
+ +new
"#})
.expect("quoted and spaced paths");
assert_eq!(files[0].old_path.as_deref(), Some("/project/a\tfile"));
assert_eq!(files[1].old_path.as_deref(), Some("/project/a file"));
+ assert_eq!(files[2].old_path.as_deref(), Some("/project/été.rs"));
+ assert_eq!(files[2].new_path.as_deref(), Some("/project/新.rs"));
+ assert_eq!(files[3].old_path.as_deref(), Some("/project/source"));
+ assert_eq!(files[3].new_path.as_deref(), Some("/project/copy"));
+ assert_eq!(
+ files[3].hunks[0].old_text,
+ "-- \"this is hunk text, not a filename\"\n"
+ );
+ assert_eq!(
+ files[4].old_path.as_deref(),
+ Some("/project/\u{7}\u{8}\u{c}\n\r\t\u{b}\\\"é")
+ );
+ assert_eq!(files[4].new_path, files[4].old_path);
+ assert_eq!(files[5].old_path.as_deref(), Some("src/file.rs"));
+ assert_eq!(files[5].new_path.as_deref(), Some("src/file.rs"));
}
#[test]
fn leaves_nontext_operations_to_structured_changes() {
assert!(
parse_patch(indoc! {"
- diff --git a//old b//new
+ diff --git /old /new
similarity index 100%
rename from /old
rename to /new
+ diff --git /source /copy
+ similarity index 100%
+ copy from /source
+ copy to /copy
diff --git a//image b//image
Binary files a//image and b//image differ
"})
@@ -234,6 +365,9 @@ mod tests {
(None, None)
);
assert_eq!(files[0].hunks[0].old_start, 10);
+ let files = parse_patch("@@ -1 +1 @@\n--- \"not a header\"\n+after\n")
+ .expect("bare hunk with header-like content");
+ assert_eq!(files[0].hunks[0].old_text, "-- \"not a header\"\n");
}
#[test]
@@ -265,11 +399,14 @@ mod tests {
"commit abc\ndiff --git /old /new\n",
"diff --git /old /new\n--- /old\n+++ /new\n@@ -1,2 +1 @@\n-old\n+new\n",
"diff --git /old /new\n--- /old\n+++ /new\n@@ -2 +2 @@\n-a\n+b\n@@ -1 +1 @@\n-c\n+d\n",
- "diff --git a/relative b/relative\n--- a/relative\n+++ b/relative\n@@ -1 +1 @@\n-a\n+b\n",
+ "diff --git a/../relative b/../relative\n--- a/../relative\n+++ b/../relative\n@@ -1 +1 @@\n-a\n+b\n",
"diff --git /old /new\n--- /old\n+++ /new\n@@ -1 +1 @@\n-a\n+b\ntrailing garbage\n",
"diff --git /old /new\n--- /old\n+++ /new\n@@ -18446744073709551615 +1 @@\n-a\n+b\n@@ -2 +2 @@\n-c\n+d\n",
"diff --git /old /new\n--- /old\n+++ /new\n@@ -0 +0 @@\n-a\n+b\n",
- "diff --git /old /new\n--- \"a//\\303\\251\"\n+++ /new\n@@ -1 +1 @@\n-a\n+b\n",
+ "diff --git /old /new\n--- \"a//\\377\"\n+++ /new\n@@ -1 +1 @@\n-a\n+b\n",
+ "diff --git /old /new\n--- \"a//\\777\"\n+++ /new\n@@ -1 +1 @@\n-a\n+b\n",
+ "diff --git /old /new\n--- \"a//\\30\"\n+++ /new\n@@ -1 +1 @@\n-a\n+b\n",
+ "diff --git /old /new\n--- \"a//\\000\"\n+++ /new\n@@ -1 +1 @@\n-a\n+b\n",
] {
assert!(parse_patch(patch).is_err(), "{patch}");
}