load_project.rs

  1use crate::{
  2    example::{Example, ExampleState},
  3    git,
  4    headless::EpAppState,
  5    progress::{ExampleProgress, InfoStyle, Step, StepProgress},
  6};
  7use anyhow::{Context as _, Result};
  8use edit_prediction::{
  9    EditPredictionStore,
 10    cursor_excerpt::compute_excerpt_ranges,
 11    udiff::{OpenedBuffers, refresh_worktree_entries, strip_diff_path_prefix},
 12};
 13use futures::AsyncWriteExt as _;
 14use gpui::{AsyncApp, Entity};
 15use language::{Anchor, Buffer, LanguageNotFound, ToOffset, ToPoint};
 16use project::{Project, ProjectPath, buffer_store::BufferStoreEvent};
 17use std::{fs, path::PathBuf, sync::Arc};
 18use zeta_prompt::ZetaPromptInput;
 19
 20pub async fn run_load_project(
 21    example: &mut Example,
 22    app_state: Arc<EpAppState>,
 23    example_progress: &ExampleProgress,
 24    mut cx: AsyncApp,
 25) -> Result<()> {
 26    if example.state.is_some() {
 27        return Ok(());
 28    }
 29
 30    let progress = example_progress.start(Step::LoadProject);
 31
 32    let project = setup_project(example, &app_state, &progress, &mut cx).await?;
 33
 34    progress.set_substatus("applying edit history");
 35    let open_buffers = apply_edit_history(example, &project, &mut cx).await?;
 36
 37    let ep_store = cx
 38        .update(|cx| EditPredictionStore::try_global(cx))
 39        .context("EditPredictionStore not initialized")?;
 40
 41    let recent_paths: Vec<ProjectPath> = open_buffers
 42        .buffers()
 43        .filter_map(|buffer| {
 44            buffer.read_with(&cx, |buffer, cx| {
 45                buffer
 46                    .file()
 47                    .map(|file| ProjectPath::from_file(file.as_ref(), cx))
 48            })
 49        })
 50        .collect();
 51
 52    ep_store.update(&mut cx, |store, cx| {
 53        store.set_recent_paths_for_project(&project, recent_paths, cx);
 54    });
 55
 56    progress.set_substatus("resolving cursor");
 57    let (buffer, cursor_position) =
 58        cursor_position(example, &project, &open_buffers, &mut cx).await?;
 59    buffer
 60        .read_with(&cx, |buffer, _| buffer.parsing_idle())
 61        .await;
 62
 63    let events: Vec<Arc<zeta_prompt::Event>> = ep_store.update(&mut cx, |store, cx| {
 64        store
 65            .edit_history_for_project(&project, cx)
 66            .into_iter()
 67            .map(|e| e.event)
 68            .collect()
 69    });
 70
 71    let existing_related_files = example
 72        .prompt_inputs
 73        .take()
 74        .map(|inputs| inputs.related_files)
 75        .unwrap_or_default();
 76
 77    let (prompt_inputs, language_name) = buffer.read_with(&cx, |buffer, _cx| {
 78        let snapshot = buffer.snapshot();
 79        let cursor_point = cursor_position.to_point(&snapshot);
 80        let cursor_offset = cursor_position.to_offset(&snapshot);
 81        let language_name = buffer
 82            .language()
 83            .map(|l| l.name().to_string())
 84            .unwrap_or_else(|| "Unknown".to_string());
 85
 86        let (full_context_point_range, full_context_offset_range, excerpt_ranges) =
 87            compute_excerpt_ranges(cursor_point, &snapshot);
 88
 89        let cursor_excerpt: Arc<str> = buffer
 90            .text_for_range(full_context_offset_range.clone())
 91            .collect::<String>()
 92            .into();
 93        let cursor_offset_in_excerpt = cursor_offset - full_context_offset_range.start;
 94        let excerpt_start_row = Some(full_context_point_range.start.row);
 95
 96        (
 97            ZetaPromptInput {
 98                cursor_path: example.spec.cursor_path.clone(),
 99                cursor_excerpt,
100                cursor_offset_in_excerpt,
101                excerpt_start_row,
102                events,
103                related_files: existing_related_files,
104                excerpt_ranges,
105                in_open_source_repo: false,
106                can_collect_data: false,
107                experiment: None,
108            },
109            language_name,
110        )
111    });
112
113    progress.set_info(language_name, InfoStyle::Normal);
114
115    example.prompt_inputs = Some(prompt_inputs);
116    example.state = Some(ExampleState {
117        buffer,
118        project,
119        cursor_position,
120        _open_buffers: open_buffers,
121    });
122    Ok(())
123}
124
125async fn cursor_position(
126    example: &Example,
127    project: &Entity<Project>,
128    open_buffers: &OpenedBuffers,
129    cx: &mut AsyncApp,
130) -> Result<(Entity<Buffer>, Anchor)> {
131    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
132    let result = language_registry
133        .load_language_for_file_path(&example.spec.cursor_path)
134        .await;
135
136    if let Err(error) = result
137        && !error.is::<LanguageNotFound>()
138    {
139        return Err(error);
140    }
141
142    let cursor_path_str = example.spec.cursor_path.to_string_lossy();
143    // Also try cursor path with first component stripped - old examples may have
144    // paths like "zed/crates/foo.rs" instead of "crates/foo.rs".
145    let cursor_path_without_prefix: PathBuf =
146        example.spec.cursor_path.components().skip(1).collect();
147    let cursor_path_without_prefix_str = cursor_path_without_prefix.to_string_lossy();
148
149    // We try open_buffers first because the file might be new and not saved to disk
150    let cursor_buffer = if let Some(buffer) = open_buffers.get(cursor_path_str.as_ref()) {
151        buffer.clone()
152    } else if let Some(buffer) = open_buffers.get(cursor_path_without_prefix_str.as_ref()) {
153        buffer.clone()
154    } else {
155        // Since the worktree scanner is disabled, manually refresh entries for the cursor path.
156        if let Some(worktree) = project.read_with(cx, |project, cx| project.worktrees(cx).next()) {
157            refresh_worktree_entries(&worktree, [&*example.spec.cursor_path], cx).await?;
158        }
159
160        let cursor_path = project
161            .read_with(cx, |project, cx| {
162                project
163                    .find_project_path(&example.spec.cursor_path, cx)
164                    .or_else(|| project.find_project_path(&cursor_path_without_prefix, cx))
165            })
166            .with_context(|| {
167                format!(
168                    "failed to find cursor path {}",
169                    example.spec.cursor_path.display()
170                )
171            })?;
172
173        project
174            .update(cx, |project, cx| project.open_buffer(cursor_path, cx))
175            .await?
176    };
177
178    let (cursor_excerpt, cursor_offset_within_excerpt) = example.spec.cursor_excerpt()?;
179
180    let excerpt_offset = cursor_buffer.read_with(&*cx, |buffer, _cx| {
181        let text = buffer.text();
182
183        let mut matches = text.match_indices(&cursor_excerpt);
184        let (excerpt_offset, _) = matches.next().with_context(|| {
185            format!("Cursor excerpt did not exist in buffer:\n\n{cursor_excerpt}\n",)
186        })?;
187        anyhow::ensure!(
188            matches.next().is_none(),
189            "More than one cursor position match found",
190        );
191        Ok(excerpt_offset)
192    })?;
193
194    let cursor_offset = excerpt_offset + cursor_offset_within_excerpt;
195    let cursor_anchor =
196        cursor_buffer.read_with(&*cx, |buffer, _| buffer.anchor_after(cursor_offset));
197
198    Ok((cursor_buffer, cursor_anchor))
199}
200
201async fn setup_project(
202    example: &mut Example,
203    app_state: &Arc<EpAppState>,
204    step_progress: &StepProgress,
205    cx: &mut AsyncApp,
206) -> Result<Entity<Project>> {
207    let ep_store = cx
208        .update(|cx| EditPredictionStore::try_global(cx))
209        .context("Store should be initialized at init")?;
210
211    let worktree_path = setup_worktree(example, step_progress).await?;
212
213    let project = cx.update(|cx| {
214        Project::local(
215            app_state.client.clone(),
216            app_state.node_runtime.clone(),
217            app_state.user_store.clone(),
218            app_state.languages.clone(),
219            app_state.fs.clone(),
220            None,
221            project::LocalProjectFlags {
222                init_worktree_trust: false,
223                watch_global_configs: false,
224            },
225            cx,
226        )
227    });
228
229    project
230        .update(cx, |project, cx| {
231            project.disable_worktree_scanner(cx);
232            project.create_worktree(&worktree_path, true, cx)
233        })
234        .await?;
235
236    let buffer_store = project.read_with(cx, |project, _| project.buffer_store().clone());
237    cx.subscribe(&buffer_store, {
238        let project = project.downgrade();
239        let ep_store = ep_store.downgrade();
240        move |_, event, cx| match event {
241            BufferStoreEvent::BufferAdded(buffer) => {
242                let Some(project) = project.upgrade() else {
243                    return;
244                };
245                ep_store
246                    .update(cx, |store, cx| store.register_buffer(&buffer, &project, cx))
247                    .ok();
248            }
249            _ => {}
250        }
251    })
252    .detach();
253
254    Ok(project)
255}
256
257async fn setup_worktree(example: &Example, step_progress: &StepProgress) -> Result<PathBuf> {
258    let repo_name = example.repo_name().context("failed to get repo name")?;
259    let repo_dir = git::repo_path_for_url(&example.spec.repository_url)?;
260    let worktree_path = repo_name.worktree_path();
261    let repo_lock = git::lock_repo(&repo_dir).await;
262
263    // Clean up any stale git lock files from previous crashed runs.
264    // Safe-ish since we have our own lock.
265    // WARNING: Can corrupt worktrees if multiple processes of the CLI are running.
266    let worktree_git_dir = repo_dir
267        .join(".git/worktrees")
268        .join(repo_name.name.as_ref());
269    for lock_file in &["index.lock", "HEAD.lock", "config.lock"] {
270        let worktree_lock_path = worktree_git_dir.join(lock_file);
271        let repo_lock_path = repo_dir.join(".git").join(lock_file);
272        if worktree_lock_path.exists() {
273            fs::remove_file(&worktree_lock_path).ok();
274        }
275        if repo_lock_path.exists() {
276            fs::remove_file(&repo_lock_path).ok();
277        }
278    }
279
280    let mut git_repo_exists = false;
281    if repo_dir.is_dir() {
282        if git::run_git(&repo_dir, &["remote", "get-url", "origin"])
283            .await
284            .map_or(false, |origin| origin.trim() == example.spec.repository_url)
285        {
286            git_repo_exists = true;
287        } else {
288            fs::remove_dir_all(&repo_dir).ok();
289        }
290    }
291
292    if !git_repo_exists {
293        step_progress.set_substatus(format!("cloning {}", repo_name.name));
294        fs::create_dir_all(&repo_dir)?;
295        git::run_git(&repo_dir, &["init"]).await?;
296        git::run_git(
297            &repo_dir,
298            &["remote", "add", "origin", &example.spec.repository_url],
299        )
300        .await?;
301    }
302
303    // Resolve the example to a revision, fetching it if needed.
304    step_progress.set_substatus("fetching");
305    let revision = git::fetch_if_needed(&repo_dir, &example.spec.revision).await?;
306
307    // Clean up any stale worktree registrations from previous crashed runs.
308    git::run_git(&repo_dir, &["worktree", "prune"]).await.ok();
309
310    // Create the worktree for this example if needed.
311    step_progress.set_substatus("preparing worktree");
312
313    // Check if worktree exists and is valid (not just a directory from a crashed run).
314    let worktree_valid = worktree_path.is_dir()
315        && git::run_git(&worktree_path, &["rev-parse", "--git-dir"])
316            .await
317            .is_ok();
318
319    if worktree_valid {
320        git::run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
321        git::run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
322        git::run_git(&worktree_path, &["checkout", revision.as_str()]).await?;
323    } else {
324        let worktree_path_string = worktree_path.to_string_lossy();
325
326        // Clean up invalid worktree directory and registration if they exist.
327        if worktree_path.exists() {
328            fs::remove_dir_all(&worktree_path).ok();
329        }
330        git::run_git(
331            &repo_dir,
332            &["worktree", "remove", "--force", &worktree_path_string],
333        )
334        .await
335        .ok();
336
337        let branch_name = example.spec.filename();
338        git::run_git(
339            &repo_dir,
340            &["branch", "-f", &branch_name, revision.as_str()],
341        )
342        .await?;
343        git::run_git(
344            &repo_dir,
345            &["worktree", "add", "-f", &worktree_path_string, &branch_name],
346        )
347        .await?;
348    }
349    drop(repo_lock);
350
351    if !example.spec.uncommitted_diff.is_empty() {
352        step_progress.set_substatus("applying diff");
353
354        // old examples had full paths in the uncommitted diff.
355        let uncommitted_diff =
356            strip_diff_path_prefix(&example.spec.uncommitted_diff, &repo_name.name);
357
358        let mut apply_process = smol::process::Command::new("git")
359            .current_dir(&worktree_path)
360            .args(&["apply", "-"])
361            .stdin(std::process::Stdio::piped())
362            .spawn()?;
363
364        let mut stdin = apply_process.stdin.take().context("Failed to get stdin")?;
365        stdin.write_all(uncommitted_diff.as_bytes()).await?;
366        stdin.close().await?;
367        drop(stdin);
368
369        let apply_result = apply_process.output().await?;
370        anyhow::ensure!(
371            apply_result.status.success(),
372            "Failed to apply uncommitted diff patch with status: {}\nstderr:\n{}\nstdout:\n{}",
373            apply_result.status,
374            String::from_utf8_lossy(&apply_result.stderr),
375            String::from_utf8_lossy(&apply_result.stdout),
376        );
377    }
378
379    step_progress.clear_substatus();
380    Ok(worktree_path)
381}
382
383async fn apply_edit_history(
384    example: &Example,
385    project: &Entity<Project>,
386    cx: &mut AsyncApp,
387) -> Result<OpenedBuffers> {
388    edit_prediction::udiff::apply_diff(&example.spec.edit_history, project, cx).await
389}