example.rs

  1use std::{
  2    borrow::Cow,
  3    cell::RefCell,
  4    env,
  5    fmt::{self, Display},
  6    fs,
  7    io::Write,
  8    mem,
  9    ops::Range,
 10    path::{Path, PathBuf},
 11    sync::Arc,
 12};
 13
 14use anyhow::{Context as _, Result};
 15use clap::ValueEnum;
 16use collections::{HashMap, HashSet};
 17use futures::{
 18    AsyncWriteExt as _,
 19    lock::{Mutex, OwnedMutexGuard},
 20};
 21use gpui::{AsyncApp, Entity, http_client::Url};
 22use language::Buffer;
 23use project::{Project, ProjectPath};
 24use pulldown_cmark::CowStr;
 25use serde::{Deserialize, Serialize};
 26
 27const UNCOMMITTED_DIFF_HEADING: &str = "Uncommitted Diff";
 28const EDIT_HISTORY_HEADING: &str = "Edit History";
 29const CURSOR_POSITION_HEADING: &str = "Cursor Position";
 30const EXPECTED_PATCH_HEADING: &str = "Expected Patch";
 31const EXPECTED_EXCERPTS_HEADING: &str = "Expected Excerpts";
 32const REPOSITORY_URL_FIELD: &str = "repository_url";
 33const REVISION_FIELD: &str = "revision";
 34
 35#[derive(Debug, Clone)]
 36pub struct NamedExample {
 37    pub name: String,
 38    pub example: Example,
 39}
 40
 41#[derive(Clone, Debug, Serialize, Deserialize)]
 42pub struct Example {
 43    pub repository_url: String,
 44    pub revision: String,
 45    pub uncommitted_diff: String,
 46    pub cursor_path: PathBuf,
 47    pub cursor_position: String,
 48    pub edit_history: String,
 49    pub expected_patch: String,
 50    pub expected_excerpts: Vec<ExpectedExcerpt>,
 51}
 52
 53pub type ExpectedExcerpt = Excerpt;
 54pub type ActualExcerpt = Excerpt;
 55
 56#[derive(Clone, Debug, Serialize, Deserialize)]
 57pub struct Excerpt {
 58    pub path: PathBuf,
 59    pub text: String,
 60}
 61
 62#[derive(ValueEnum, Debug, Clone)]
 63pub enum ExampleFormat {
 64    Json,
 65    Toml,
 66    Md,
 67}
 68
 69impl NamedExample {
 70    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
 71        let path = path.as_ref();
 72        let content = std::fs::read_to_string(path)?;
 73        let ext = path.extension();
 74
 75        match ext.and_then(|s| s.to_str()) {
 76            Some("json") => Ok(Self {
 77                name: path.file_stem().unwrap_or_default().display().to_string(),
 78                example: serde_json::from_str(&content)?,
 79            }),
 80            Some("toml") => Ok(Self {
 81                name: path.file_stem().unwrap_or_default().display().to_string(),
 82                example: toml::from_str(&content)?,
 83            }),
 84            Some("md") => Self::parse_md(&content),
 85            Some(_) => {
 86                anyhow::bail!("Unrecognized example extension: {}", ext.unwrap().display());
 87            }
 88            None => {
 89                anyhow::bail!(
 90                    "Failed to determine example type since the file does not have an extension."
 91                );
 92            }
 93        }
 94    }
 95
 96    pub fn parse_md(input: &str) -> Result<Self> {
 97        use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Parser, Tag, TagEnd};
 98
 99        let parser = Parser::new(input);
100
101        let mut named = NamedExample {
102            name: String::new(),
103            example: Example {
104                repository_url: String::new(),
105                revision: String::new(),
106                uncommitted_diff: String::new(),
107                cursor_path: PathBuf::new(),
108                cursor_position: String::new(),
109                edit_history: String::new(),
110                expected_patch: String::new(),
111                expected_excerpts: Vec::new(),
112            },
113        };
114
115        let mut text = String::new();
116        let mut current_section = String::new();
117        let mut block_info: CowStr = "".into();
118
119        for event in parser {
120            match event {
121                Event::Text(line) => {
122                    text.push_str(&line);
123
124                    if !named.name.is_empty()
125                        && current_section.is_empty()
126                        // in h1 section
127                        && let Some((field, value)) = line.split_once('=')
128                    {
129                        match field.trim() {
130                            REPOSITORY_URL_FIELD => {
131                                named.example.repository_url = value.trim().to_string();
132                            }
133                            REVISION_FIELD => {
134                                named.example.revision = value.trim().to_string();
135                            }
136                            _ => {
137                                eprintln!("Warning: Unrecognized field `{field}`");
138                            }
139                        }
140                    }
141                }
142                Event::End(TagEnd::Heading(HeadingLevel::H1)) => {
143                    if !named.name.is_empty() {
144                        anyhow::bail!(
145                            "Found multiple H1 headings. There should only be one with the name of the example."
146                        );
147                    }
148                    named.name = mem::take(&mut text);
149                }
150                Event::End(TagEnd::Heading(HeadingLevel::H2)) => {
151                    current_section = mem::take(&mut text);
152                }
153                Event::End(TagEnd::Heading(level)) => {
154                    anyhow::bail!("Unexpected heading level: {level}");
155                }
156                Event::Start(Tag::CodeBlock(kind)) => {
157                    match kind {
158                        CodeBlockKind::Fenced(info) => {
159                            block_info = info;
160                        }
161                        CodeBlockKind::Indented => {
162                            anyhow::bail!("Unexpected indented codeblock");
163                        }
164                    };
165                }
166                Event::Start(_) => {
167                    text.clear();
168                    block_info = "".into();
169                }
170                Event::End(TagEnd::CodeBlock) => {
171                    let block_info = block_info.trim();
172                    if current_section.eq_ignore_ascii_case(UNCOMMITTED_DIFF_HEADING) {
173                        named.example.uncommitted_diff = mem::take(&mut text);
174                    } else if current_section.eq_ignore_ascii_case(EDIT_HISTORY_HEADING) {
175                        named.example.edit_history.push_str(&mem::take(&mut text));
176                    } else if current_section.eq_ignore_ascii_case(CURSOR_POSITION_HEADING) {
177                        named.example.cursor_path = block_info.into();
178                        named.example.cursor_position = mem::take(&mut text);
179                    } else if current_section.eq_ignore_ascii_case(EXPECTED_PATCH_HEADING) {
180                        named.example.expected_patch = mem::take(&mut text);
181                    } else if current_section.eq_ignore_ascii_case(EXPECTED_EXCERPTS_HEADING) {
182                        // TODO: "…" should not be a part of the excerpt
183                        named.example.expected_excerpts.push(ExpectedExcerpt {
184                            path: block_info.into(),
185                            text: mem::take(&mut text),
186                        });
187                    } else {
188                        eprintln!("Warning: Unrecognized section `{current_section:?}`")
189                    }
190                }
191                _ => {}
192            }
193        }
194
195        if named.example.cursor_path.as_path() == Path::new("")
196            || named.example.cursor_position.is_empty()
197        {
198            anyhow::bail!("Missing cursor position codeblock");
199        }
200
201        Ok(named)
202    }
203
204    pub fn write(&self, format: ExampleFormat, mut out: impl Write) -> Result<()> {
205        match format {
206            ExampleFormat::Json => Ok(serde_json::to_writer(out, &self.example)?),
207            ExampleFormat::Toml => {
208                Ok(out.write_all(toml::to_string_pretty(&self.example)?.as_bytes())?)
209            }
210            ExampleFormat::Md => Ok(write!(out, "{}", self)?),
211        }
212    }
213
214    pub async fn setup_worktree(&self) -> Result<PathBuf> {
215        let (repo_owner, repo_name) = self.repo_name()?;
216        let file_name = self.file_name();
217
218        let worktrees_dir = env::current_dir()?.join("target").join("zeta-worktrees");
219        let repos_dir = env::current_dir()?.join("target").join("zeta-repos");
220        fs::create_dir_all(&repos_dir)?;
221        fs::create_dir_all(&worktrees_dir)?;
222
223        let repo_dir = repos_dir.join(repo_owner.as_ref()).join(repo_name.as_ref());
224        let repo_lock = lock_repo(&repo_dir).await;
225
226        if !repo_dir.is_dir() {
227            fs::create_dir_all(&repo_dir)?;
228            run_git(&repo_dir, &["init"]).await?;
229            run_git(
230                &repo_dir,
231                &["remote", "add", "origin", &self.example.repository_url],
232            )
233            .await?;
234        }
235
236        // Resolve the example to a revision, fetching it if needed.
237        let revision = run_git(&repo_dir, &["rev-parse", &self.example.revision]).await;
238        let revision = if let Ok(revision) = revision {
239            revision
240        } else {
241            run_git(
242                &repo_dir,
243                &["fetch", "--depth", "1", "origin", &self.example.revision],
244            )
245            .await?;
246            let revision = run_git(&repo_dir, &["rev-parse", "FETCH_HEAD"]).await?;
247            if revision != self.example.revision {
248                run_git(&repo_dir, &["tag", &self.example.revision, &revision]).await?;
249            }
250            revision
251        };
252
253        // Create the worktree for this example if needed.
254        let worktree_path = worktrees_dir.join(&file_name);
255        if worktree_path.is_dir() {
256            run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
257            run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
258            run_git(&worktree_path, &["checkout", revision.as_str()]).await?;
259        } else {
260            let worktree_path_string = worktree_path.to_string_lossy();
261            run_git(&repo_dir, &["branch", "-f", &file_name, revision.as_str()]).await?;
262            run_git(
263                &repo_dir,
264                &["worktree", "add", "-f", &worktree_path_string, &file_name],
265            )
266            .await?;
267        }
268        drop(repo_lock);
269
270        // Apply the uncommitted diff for this example.
271        if !self.example.uncommitted_diff.is_empty() {
272            let mut apply_process = smol::process::Command::new("git")
273                .current_dir(&worktree_path)
274                .args(&["apply", "-"])
275                .stdin(std::process::Stdio::piped())
276                .spawn()?;
277
278            let mut stdin = apply_process.stdin.take().unwrap();
279            stdin
280                .write_all(self.example.uncommitted_diff.as_bytes())
281                .await?;
282            stdin.close().await?;
283            drop(stdin);
284
285            let apply_result = apply_process.output().await?;
286            if !apply_result.status.success() {
287                anyhow::bail!(
288                    "Failed to apply uncommitted diff patch with status: {}\nstderr:\n{}\nstdout:\n{}",
289                    apply_result.status,
290                    String::from_utf8_lossy(&apply_result.stderr),
291                    String::from_utf8_lossy(&apply_result.stdout),
292                );
293            }
294        }
295
296        Ok(worktree_path)
297    }
298
299    fn file_name(&self) -> String {
300        self.name
301            .chars()
302            .map(|c| {
303                if c.is_whitespace() {
304                    '-'
305                } else {
306                    c.to_ascii_lowercase()
307                }
308            })
309            .collect()
310    }
311
312    #[allow(unused)]
313    fn repo_name(&self) -> Result<(Cow<'_, str>, Cow<'_, str>)> {
314        // git@github.com:owner/repo.git
315        if self.example.repository_url.contains('@') {
316            let (owner, repo) = self
317                .example
318                .repository_url
319                .split_once(':')
320                .context("expected : in git url")?
321                .1
322                .split_once('/')
323                .context("expected / in git url")?;
324            Ok((
325                Cow::Borrowed(owner),
326                Cow::Borrowed(repo.trim_end_matches(".git")),
327            ))
328        // http://github.com/owner/repo.git
329        } else {
330            let url = Url::parse(&self.example.repository_url)?;
331            let mut segments = url.path_segments().context("empty http url")?;
332            let owner = segments
333                .next()
334                .context("expected owner path segment")?
335                .to_string();
336            let repo = segments
337                .next()
338                .context("expected repo path segment")?
339                .trim_end_matches(".git")
340                .to_string();
341            assert!(segments.next().is_none());
342
343            Ok((owner.into(), repo.into()))
344        }
345    }
346
347    #[must_use]
348    pub async fn apply_edit_history(
349        &self,
350        project: &Entity<Project>,
351        cx: &mut AsyncApp,
352    ) -> Result<HashSet<Entity<Buffer>>> {
353        apply_diff(&self.example.edit_history, project, cx).await
354    }
355}
356
357async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
358    let output = smol::process::Command::new("git")
359        .current_dir(repo_path)
360        .args(args)
361        .output()
362        .await?;
363
364    anyhow::ensure!(
365        output.status.success(),
366        "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
367        args.join(" "),
368        repo_path.display(),
369        output.status,
370        String::from_utf8_lossy(&output.stderr),
371        String::from_utf8_lossy(&output.stdout),
372    );
373    Ok(String::from_utf8(output.stdout)?.trim().to_string())
374}
375
376impl Display for NamedExample {
377    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
378        write!(f, "# {}\n\n", self.name)?;
379        write!(
380            f,
381            "{REPOSITORY_URL_FIELD} = {}\n",
382            self.example.repository_url
383        )?;
384        write!(f, "{REVISION_FIELD} = {}\n\n", self.example.revision)?;
385
386        write!(f, "## {UNCOMMITTED_DIFF_HEADING}\n\n")?;
387        write!(f, "`````diff\n")?;
388        write!(f, "{}", self.example.uncommitted_diff)?;
389        write!(f, "`````\n")?;
390
391        if !self.example.edit_history.is_empty() {
392            write!(f, "`````diff\n{}`````\n", self.example.edit_history)?;
393        }
394
395        write!(
396            f,
397            "## {CURSOR_POSITION_HEADING}\n\n`````{}\n{}`````\n",
398            self.example.cursor_path.display(),
399            self.example.cursor_position
400        )?;
401        write!(f, "## {EDIT_HISTORY_HEADING}\n\n")?;
402
403        if !self.example.expected_patch.is_empty() {
404            write!(
405                f,
406                "\n## {EXPECTED_PATCH_HEADING}\n\n`````diff\n{}`````\n",
407                self.example.expected_patch
408            )?;
409        }
410
411        if !self.example.expected_excerpts.is_empty() {
412            write!(f, "\n## {EXPECTED_EXCERPTS_HEADING}\n\n")?;
413
414            for excerpt in &self.example.expected_excerpts {
415                write!(
416                    f,
417                    "`````{}{}\n{}`````\n\n",
418                    excerpt
419                        .path
420                        .extension()
421                        .map(|ext| format!("{} ", ext.to_string_lossy()))
422                        .unwrap_or_default(),
423                    excerpt.path.display(),
424                    excerpt.text
425                )?;
426            }
427        }
428
429        Ok(())
430    }
431}
432
433thread_local! {
434    static REPO_LOCKS: RefCell<HashMap<PathBuf, Arc<Mutex<()>>>> = RefCell::new(HashMap::default());
435}
436
437#[must_use]
438pub async fn lock_repo(path: impl AsRef<Path>) -> OwnedMutexGuard<()> {
439    REPO_LOCKS
440        .with(|cell| {
441            cell.borrow_mut()
442                .entry(path.as_ref().to_path_buf())
443                .or_default()
444                .clone()
445        })
446        .lock_owned()
447        .await
448}
449
450#[must_use]
451pub async fn apply_diff(
452    diff: &str,
453    project: &Entity<Project>,
454    cx: &mut AsyncApp,
455) -> Result<HashSet<Entity<Buffer>>> {
456    use cloud_llm_client::udiff::DiffLine;
457    use std::fmt::Write;
458
459    #[derive(Debug, Default)]
460    struct HunkState {
461        context: String,
462        edits: Vec<Edit>,
463    }
464
465    #[derive(Debug)]
466    struct Edit {
467        range: Range<usize>,
468        text: String,
469    }
470
471    let mut old_path = None;
472    let mut new_path = None;
473    let mut hunk = HunkState::default();
474    let mut diff_lines = diff.lines().map(DiffLine::parse).peekable();
475    let mut open_buffers = HashSet::default();
476
477    while let Some(diff_line) = diff_lines.next() {
478        match diff_line {
479            DiffLine::OldPath { path } => old_path = Some(path),
480            DiffLine::NewPath { path } => {
481                if old_path.is_none() {
482                    anyhow::bail!(
483                        "Found a new path header (`+++`) before an (`---`) old path header"
484                    );
485                }
486                new_path = Some(path)
487            }
488            DiffLine::Context(ctx) => {
489                writeln!(&mut hunk.context, "{ctx}")?;
490            }
491            DiffLine::Deletion(del) => {
492                let range = hunk.context.len()..hunk.context.len() + del.len() + '\n'.len_utf8();
493                if let Some(last_edit) = hunk.edits.last_mut()
494                    && last_edit.range.end == range.start
495                {
496                    last_edit.range.end = range.end;
497                } else {
498                    hunk.edits.push(Edit {
499                        range,
500                        text: String::new(),
501                    });
502                }
503                writeln!(&mut hunk.context, "{del}")?;
504            }
505            DiffLine::Addition(add) => {
506                let range = hunk.context.len()..hunk.context.len();
507                if let Some(last_edit) = hunk.edits.last_mut()
508                    && last_edit.range.end == range.start
509                {
510                    writeln!(&mut last_edit.text, "{add}").unwrap();
511                } else {
512                    hunk.edits.push(Edit {
513                        range,
514                        text: format!("{add}\n"),
515                    });
516                }
517            }
518            DiffLine::HunkHeader(_) | DiffLine::Garbage(_) => {}
519        }
520
521        let at_hunk_end = match diff_lines.peek() {
522            Some(DiffLine::OldPath { .. }) | Some(DiffLine::HunkHeader(_)) | None => true,
523            _ => false,
524        };
525
526        if at_hunk_end {
527            let hunk = mem::take(&mut hunk);
528
529            let Some(old_path) = old_path.as_deref() else {
530                anyhow::bail!("Missing old path (`---`) header")
531            };
532
533            let Some(new_path) = new_path.as_deref() else {
534                anyhow::bail!("Missing new path (`+++`) header")
535            };
536
537            let buffer = project
538                .update(cx, |project, cx| {
539                    let project_path = project
540                        .find_project_path(old_path, cx)
541                        .context("Failed to find old_path in project")?;
542
543                    anyhow::Ok(project.open_buffer(project_path, cx))
544                })??
545                .await?;
546            open_buffers.insert(buffer.clone());
547
548            if old_path != new_path {
549                project
550                    .update(cx, |project, cx| {
551                        let project_file = project::File::from_dyn(buffer.read(cx).file()).unwrap();
552                        let new_path = ProjectPath {
553                            worktree_id: project_file.worktree_id(cx),
554                            path: project_file.path.clone(),
555                        };
556                        project.rename_entry(project_file.entry_id.unwrap(), new_path, cx)
557                    })?
558                    .await?;
559            }
560
561            // TODO is it worth using project search?
562            buffer.update(cx, |buffer, cx| {
563                let context_offset = if hunk.context.is_empty() {
564                    0
565                } else {
566                    let text = buffer.text();
567                    if let Some(offset) = text.find(&hunk.context) {
568                        if text[offset + 1..].contains(&hunk.context) {
569                            anyhow::bail!("Context is not unique enough:\n{}", hunk.context);
570                        }
571                        offset
572                    } else {
573                        anyhow::bail!(
574                            "Failed to match context:\n{}\n\nBuffer:\n{}",
575                            hunk.context,
576                            text
577                        );
578                    }
579                };
580
581                buffer.edit(
582                    hunk.edits.into_iter().map(|edit| {
583                        (
584                            context_offset + edit.range.start..context_offset + edit.range.end,
585                            edit.text,
586                        )
587                    }),
588                    None,
589                    cx,
590                );
591
592                anyhow::Ok(())
593            })??;
594        }
595    }
596
597    anyhow::Ok(open_buffers)
598}
599
600#[cfg(test)]
601mod tests {
602    use super::*;
603    use ::fs::FakeFs;
604    use gpui::TestAppContext;
605    use indoc::indoc;
606    use pretty_assertions::assert_eq;
607    use project::Project;
608    use serde_json::json;
609    use settings::SettingsStore;
610    use util::path;
611
612    #[gpui::test]
613    async fn test_apply_diff_successful(cx: &mut TestAppContext) {
614        let buffer_1_text = indoc! {r#"
615            one
616            two
617            three
618            four
619            five
620        "# };
621
622        let buffer_1_text_final = indoc! {r#"
623            3
624            4
625            5
626        "# };
627
628        let buffer_2_text = indoc! {r#"
629            six
630            seven
631            eight
632            nine
633            ten
634        "# };
635
636        let buffer_2_text_final = indoc! {r#"
637            5
638            six
639            seven
640            7.5
641            eight
642            nine
643            ten
644            11
645        "# };
646
647        cx.update(|cx| {
648            let settings_store = SettingsStore::test(cx);
649            cx.set_global(settings_store);
650            Project::init_settings(cx);
651            language::init(cx);
652        });
653
654        let fs = FakeFs::new(cx.background_executor.clone());
655        fs.insert_tree(
656            path!("/root"),
657            json!({
658                "file1": buffer_1_text,
659                "file2": buffer_2_text,
660            }),
661        )
662        .await;
663
664        let project = Project::test(fs, [path!("/root").as_ref()], cx).await;
665
666        let diff = indoc! {r#"
667            --- a/root/file1
668            +++ b/root/file1
669             one
670             two
671            -three
672            +3
673             four
674             five
675            --- a/root/file1
676            +++ b/root/file1
677             3
678            -four
679            -five
680            +4
681            +5
682            --- a/root/file1
683            +++ b/root/file1
684            -one
685            -two
686             3
687             4
688            --- a/root/file2
689            +++ b/root/file2
690            +5
691             six
692            --- a/root/file2
693            +++ b/root/file2
694             seven
695            +7.5
696             eight
697            --- a/root/file2
698            +++ b/root/file2
699             ten
700            +11
701        "#};
702
703        let _buffers = apply_diff(diff, &project, &mut cx.to_async())
704            .await
705            .unwrap();
706        let buffer_1 = project
707            .update(cx, |project, cx| {
708                let project_path = project.find_project_path(path!("/root/file1"), cx).unwrap();
709                project.open_buffer(project_path, cx)
710            })
711            .await
712            .unwrap();
713
714        buffer_1.read_with(cx, |buffer, _cx| {
715            assert_eq!(buffer.text(), buffer_1_text_final);
716        });
717        let buffer_2 = project
718            .update(cx, |project, cx| {
719                let project_path = project.find_project_path(path!("/root/file2"), cx).unwrap();
720                project.open_buffer(project_path, cx)
721            })
722            .await
723            .unwrap();
724
725        buffer_2.read_with(cx, |buffer, _cx| {
726            assert_eq!(buffer.text(), buffer_2_text_final);
727        });
728    }
729
730    #[gpui::test]
731    async fn test_apply_diff_non_unique(cx: &mut TestAppContext) {
732        let buffer_1_text = indoc! {r#"
733            one
734            two
735            three
736            four
737            five
738            one
739            two
740            three
741            four
742            five
743        "# };
744
745        cx.update(|cx| {
746            let settings_store = SettingsStore::test(cx);
747            cx.set_global(settings_store);
748            Project::init_settings(cx);
749            language::init(cx);
750        });
751
752        let fs = FakeFs::new(cx.background_executor.clone());
753        fs.insert_tree(
754            path!("/root"),
755            json!({
756                "file1": buffer_1_text,
757            }),
758        )
759        .await;
760
761        let project = Project::test(fs, [path!("/root").as_ref()], cx).await;
762
763        let diff = indoc! {r#"
764            --- a/root/file1
765            +++ b/root/file1
766             one
767             two
768            -three
769            +3
770             four
771             five
772        "#};
773
774        apply_diff(diff, &project, &mut cx.to_async())
775            .await
776            .expect_err("Non-unique edits should fail");
777    }
778
779    #[gpui::test]
780    async fn test_apply_diff_unique_via_previous_context(cx: &mut TestAppContext) {
781        let start = indoc! {r#"
782            one
783            two
784            three
785            four
786            five
787
788            four
789            five
790        "# };
791
792        let end = indoc! {r#"
793            one
794            two
795            3
796            four
797            5
798
799            four
800            five
801        "# };
802
803        cx.update(|cx| {
804            let settings_store = SettingsStore::test(cx);
805            cx.set_global(settings_store);
806            Project::init_settings(cx);
807            language::init(cx);
808        });
809
810        let fs = FakeFs::new(cx.background_executor.clone());
811        fs.insert_tree(
812            path!("/root"),
813            json!({
814                "file1": start,
815            }),
816        )
817        .await;
818
819        let project = Project::test(fs, [path!("/root").as_ref()], cx).await;
820
821        let diff = indoc! {r#"
822            --- a/root/file1
823            +++ b/root/file1
824             one
825             two
826            -three
827            +3
828             four
829            -five
830            +5
831        "#};
832
833        let _buffers = apply_diff(diff, &project, &mut cx.to_async())
834            .await
835            .unwrap();
836
837        let buffer_1 = project
838            .update(cx, |project, cx| {
839                let project_path = project.find_project_path(path!("/root/file1"), cx).unwrap();
840                project.open_buffer(project_path, cx)
841            })
842            .await
843            .unwrap();
844
845        buffer_1.read_with(cx, |buffer, _cx| {
846            assert_eq!(buffer.text(), end);
847        });
848    }
849}