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