1use crate::{
2 example::{Example, ExampleBuffer, ExampleState},
3 git,
4 headless::EpAppState,
5 progress::{InfoStyle, Progress, Step, StepProgress},
6};
7use anyhow::{Context as _, Result};
8use edit_prediction::EditPredictionStore;
9use edit_prediction::udiff::{OpenedBuffers, refresh_worktree_entries};
10use futures::AsyncWriteExt as _;
11use gpui::{AsyncApp, Entity};
12use language::{Anchor, Buffer, LanguageNotFound, ToOffset, ToPoint};
13use project::Project;
14use project::buffer_store::BufferStoreEvent;
15use std::{fs, path::PathBuf, sync::Arc};
16
17pub async fn run_load_project(
18 example: &mut Example,
19 app_state: Arc<EpAppState>,
20 mut cx: AsyncApp,
21) -> Result<()> {
22 if example.state.is_some() {
23 return Ok(());
24 }
25
26 let progress = Progress::global().start(Step::LoadProject, &example.spec.name);
27
28 let project = setup_project(example, &app_state, &progress, &mut cx).await?;
29
30 let open_buffers = apply_edit_history(example, &project, &mut cx).await?;
31
32 let (buffer, cursor_position) =
33 cursor_position(example, &project, &open_buffers, &mut cx).await?;
34 let (example_buffer, language_name) = buffer.read_with(&cx, |buffer, _cx| {
35 let cursor_point = cursor_position.to_point(&buffer);
36 let language_name = buffer
37 .language()
38 .map(|l| l.name().to_string())
39 .unwrap_or_else(|| "Unknown".to_string());
40 (
41 ExampleBuffer {
42 content: buffer.text(),
43 cursor_row: cursor_point.row,
44 cursor_column: cursor_point.column,
45 cursor_offset: cursor_position.to_offset(&buffer),
46 },
47 language_name,
48 )
49 })?;
50
51 progress.set_info(language_name, InfoStyle::Normal);
52
53 example.buffer = Some(example_buffer);
54 example.state = Some(ExampleState {
55 buffer,
56 project,
57 cursor_position,
58 _open_buffers: open_buffers,
59 });
60 Ok(())
61}
62
63async fn cursor_position(
64 example: &Example,
65 project: &Entity<Project>,
66 open_buffers: &OpenedBuffers,
67 cx: &mut AsyncApp,
68) -> Result<(Entity<Buffer>, Anchor)> {
69 let language_registry = project.read_with(cx, |project, _| project.languages().clone())?;
70 let result = language_registry
71 .load_language_for_file_path(&example.spec.cursor_path)
72 .await;
73
74 if let Err(error) = result
75 && !error.is::<LanguageNotFound>()
76 {
77 return Err(error);
78 }
79
80 let cursor_path_str = example.spec.cursor_path.to_string_lossy();
81 // We try open_buffers first because the file might be new and not saved to disk
82 let cursor_buffer = if let Some(buffer) = open_buffers.get(&cursor_path_str) {
83 buffer.clone()
84 } else {
85 // Since the worktree scanner is disabled, manually refresh entries for the cursor path.
86 if let Some(worktree) = project.read_with(cx, |project, cx| project.worktrees(cx).next())? {
87 refresh_worktree_entries(&worktree, [&*example.spec.cursor_path], cx).await?;
88 }
89
90 let cursor_path = project
91 .read_with(cx, |project, cx| {
92 project.find_project_path(&example.spec.cursor_path, cx)
93 })?
94 .with_context(|| {
95 format!(
96 "failed to find cursor path {}",
97 example.spec.cursor_path.display()
98 )
99 })?;
100
101 project
102 .update(cx, |project, cx| project.open_buffer(cursor_path, cx))?
103 .await?
104 };
105
106 let (cursor_excerpt, cursor_offset_within_excerpt) = example.spec.cursor_excerpt()?;
107
108 let excerpt_offset = cursor_buffer.read_with(cx, |buffer, _cx| {
109 let text = buffer.text();
110
111 let mut matches = text.match_indices(&cursor_excerpt);
112 let (excerpt_offset, _) = matches.next().with_context(|| {
113 format!(
114 "\nExcerpt:\n\n{cursor_excerpt}\nBuffer text:\n{text}\n.Example: {}\nCursor excerpt did not exist in buffer.",
115 example.spec.name
116 )
117 })?;
118 anyhow::ensure!(
119 matches.next().is_none(),
120 "More than one cursor position match found for {}",
121 &example.spec.name
122 );
123 Ok(excerpt_offset)
124 })??;
125
126 let cursor_offset = excerpt_offset + cursor_offset_within_excerpt;
127 let cursor_anchor =
128 cursor_buffer.read_with(cx, |buffer, _| buffer.anchor_after(cursor_offset))?;
129
130 Ok((cursor_buffer, cursor_anchor))
131}
132
133async fn setup_project(
134 example: &mut Example,
135 app_state: &Arc<EpAppState>,
136 step_progress: &StepProgress,
137 cx: &mut AsyncApp,
138) -> Result<Entity<Project>> {
139 let ep_store = cx
140 .update(|cx| EditPredictionStore::try_global(cx))?
141 .context("Store should be initialized at init")?;
142
143 let worktree_path = setup_worktree(example, step_progress).await?;
144
145 if let Some(project) = app_state.project_cache.get(&example.spec.repository_url) {
146 ep_store.update(cx, |ep_store, _| {
147 ep_store.clear_history_for_project(&project);
148 })?;
149 let buffer_store = project.read_with(cx, |project, _| project.buffer_store().clone())?;
150 let buffers = buffer_store.read_with(cx, |buffer_store, _| {
151 buffer_store.buffers().collect::<Vec<_>>()
152 })?;
153 for buffer in buffers {
154 buffer
155 .update(cx, |buffer, cx| buffer.reload(cx))?
156 .await
157 .ok();
158 }
159 return Ok(project);
160 }
161
162 let project = cx.update(|cx| {
163 Project::local(
164 app_state.client.clone(),
165 app_state.node_runtime.clone(),
166 app_state.user_store.clone(),
167 app_state.languages.clone(),
168 app_state.fs.clone(),
169 None,
170 false,
171 cx,
172 )
173 })?;
174
175 project
176 .update(cx, |project, cx| {
177 project.disable_worktree_scanner(cx);
178 project.create_worktree(&worktree_path, true, cx)
179 })?
180 .await?;
181
182 app_state
183 .project_cache
184 .insert(example.spec.repository_url.clone(), project.clone());
185
186 let buffer_store = project.read_with(cx, |project, _| project.buffer_store().clone())?;
187 cx.subscribe(&buffer_store, {
188 let project = project.clone();
189 move |_, event, cx| match event {
190 BufferStoreEvent::BufferAdded(buffer) => {
191 ep_store.update(cx, |store, cx| store.register_buffer(&buffer, &project, cx));
192 }
193 _ => {}
194 }
195 })?
196 .detach();
197
198 Ok(project)
199}
200
201async fn setup_worktree(example: &Example, step_progress: &StepProgress) -> Result<PathBuf> {
202 let repo_name = example.repo_name().context("failed to get repo name")?;
203 let repo_dir = git::repo_path_for_url(&example.spec.repository_url)?;
204 let worktree_path = repo_name.worktree_path();
205 let repo_lock = git::lock_repo(&repo_dir).await;
206
207 if !repo_dir.is_dir() {
208 step_progress.set_substatus(format!("cloning {}", repo_name.name));
209 fs::create_dir_all(&repo_dir)?;
210 git::run_git(&repo_dir, &["init"]).await?;
211 git::run_git(
212 &repo_dir,
213 &["remote", "add", "origin", &example.spec.repository_url],
214 )
215 .await?;
216 }
217
218 // Resolve the example to a revision, fetching it if needed.
219 step_progress.set_substatus("fetching");
220 let revision = git::fetch_if_needed(&repo_dir, &example.spec.revision).await?;
221
222 // Create the worktree for this example if needed.
223 step_progress.set_substatus("preparing worktree");
224 if worktree_path.is_dir() {
225 git::run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
226 git::run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
227 git::run_git(&worktree_path, &["checkout", revision.as_str()]).await?;
228 } else {
229 let worktree_path_string = worktree_path.to_string_lossy();
230 let branch_name = example.spec.filename();
231 git::run_git(
232 &repo_dir,
233 &["branch", "-f", &branch_name, revision.as_str()],
234 )
235 .await?;
236 git::run_git(
237 &repo_dir,
238 &["worktree", "add", "-f", &worktree_path_string, &branch_name],
239 )
240 .await?;
241 }
242 drop(repo_lock);
243
244 // Apply the uncommitted diff for this example.
245 if !example.spec.uncommitted_diff.is_empty() {
246 step_progress.set_substatus("applying diff");
247 let mut apply_process = smol::process::Command::new("git")
248 .current_dir(&worktree_path)
249 .args(&["apply", "-"])
250 .stdin(std::process::Stdio::piped())
251 .spawn()?;
252
253 let mut stdin = apply_process.stdin.take().context("Failed to get stdin")?;
254 stdin
255 .write_all(example.spec.uncommitted_diff.as_bytes())
256 .await?;
257 stdin.close().await?;
258 drop(stdin);
259
260 let apply_result = apply_process.output().await?;
261 anyhow::ensure!(
262 apply_result.status.success(),
263 "Failed to apply uncommitted diff patch with status: {}\nstderr:\n{}\nstdout:\n{}",
264 apply_result.status,
265 String::from_utf8_lossy(&apply_result.stderr),
266 String::from_utf8_lossy(&apply_result.stdout),
267 );
268 }
269
270 step_progress.clear_substatus();
271 Ok(worktree_path)
272}
273
274async fn apply_edit_history(
275 example: &Example,
276 project: &Entity<Project>,
277 cx: &mut AsyncApp,
278) -> Result<OpenedBuffers> {
279 edit_prediction::udiff::apply_diff(&example.spec.edit_history, project, cx).await
280}