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