load_project.rs

  1use crate::{
  2    example::{Example, ExampleBuffer, ExampleState},
  3    headless::EpAppState,
  4    paths::{REPOS_DIR, WORKTREES_DIR},
  5    progress::{InfoStyle, Progress, Step, StepProgress},
  6};
  7use anyhow::{Context as _, Result};
  8use collections::HashMap;
  9use edit_prediction::EditPredictionStore;
 10use edit_prediction::udiff::OpenedBuffers;
 11use futures::{
 12    AsyncWriteExt as _,
 13    lock::{Mutex, OwnedMutexGuard},
 14};
 15use gpui::{AsyncApp, Entity};
 16use language::{Anchor, Buffer, LanguageNotFound, ToOffset, ToPoint};
 17use project::buffer_store::BufferStoreEvent;
 18use project::{Project, ProjectPath};
 19use std::{
 20    cell::RefCell,
 21    fs,
 22    path::{Path, PathBuf},
 23    sync::Arc,
 24};
 25use util::{paths::PathStyle, rel_path::RelPath};
 26use zeta_prompt::CURSOR_MARKER;
 27
 28pub async fn run_load_project(
 29    example: &mut Example,
 30    app_state: Arc<EpAppState>,
 31    mut cx: AsyncApp,
 32) -> Result<()> {
 33    if example.state.is_some() {
 34        return Ok(());
 35    }
 36
 37    let progress = Progress::global().start(Step::LoadProject, &example.spec.name);
 38
 39    let project = setup_project(example, &app_state, &progress, &mut cx).await?;
 40
 41    let _open_buffers = apply_edit_history(example, &project, &mut cx).await?;
 42
 43    let (buffer, cursor_position) = cursor_position(example, &project, &mut cx).await?;
 44    let (example_buffer, language_name) = buffer.read_with(&cx, |buffer, _cx| {
 45        let cursor_point = cursor_position.to_point(&buffer);
 46        let language_name = buffer
 47            .language()
 48            .map(|l| l.name().to_string())
 49            .unwrap_or_else(|| "Unknown".to_string());
 50        (
 51            ExampleBuffer {
 52                content: buffer.text(),
 53                cursor_row: cursor_point.row,
 54                cursor_column: cursor_point.column,
 55                cursor_offset: cursor_position.to_offset(&buffer),
 56            },
 57            language_name,
 58        )
 59    })?;
 60
 61    progress.set_info(language_name, InfoStyle::Normal);
 62
 63    example.buffer = Some(example_buffer);
 64    example.state = Some(ExampleState {
 65        buffer,
 66        project,
 67        cursor_position,
 68        _open_buffers,
 69    });
 70    Ok(())
 71}
 72
 73async fn cursor_position(
 74    example: &Example,
 75    project: &Entity<Project>,
 76    cx: &mut AsyncApp,
 77) -> Result<(Entity<Buffer>, Anchor)> {
 78    let language_registry = project.read_with(cx, |project, _| project.languages().clone())?;
 79    let result = language_registry
 80        .load_language_for_file_path(&example.spec.cursor_path)
 81        .await;
 82
 83    if let Err(error) = result
 84        && !error.is::<LanguageNotFound>()
 85    {
 86        return Err(error);
 87    }
 88
 89    let cursor_path = project
 90        .read_with(cx, |project, cx| {
 91            project.find_project_path(&example.spec.cursor_path, cx)
 92        })?
 93        .with_context(|| {
 94            format!(
 95                "failed to find cursor path {}",
 96                example.spec.cursor_path.display()
 97            )
 98        })?;
 99    let cursor_buffer = project
100        .update(cx, |project, cx| project.open_buffer(cursor_path, cx))?
101        .await?;
102    let cursor_offset_within_excerpt = example
103        .spec
104        .cursor_position
105        .find(CURSOR_MARKER)
106        .context("missing cursor marker")?;
107    let mut cursor_excerpt = example.spec.cursor_position.clone();
108    cursor_excerpt.replace_range(
109        cursor_offset_within_excerpt..(cursor_offset_within_excerpt + CURSOR_MARKER.len()),
110        "",
111    );
112    let excerpt_offset = cursor_buffer.read_with(cx, |buffer, _cx| {
113        let text = buffer.text();
114
115        let mut matches = text.match_indices(&cursor_excerpt);
116        let (excerpt_offset, _) = matches.next().with_context(|| {
117            format!(
118                "\nExcerpt:\n\n{cursor_excerpt}\nBuffer text:\n{text}\n.Example: {}\nCursor excerpt did not exist in buffer.",
119                example.spec.name
120            )
121        })?;
122        anyhow::ensure!(
123            matches.next().is_none(),
124            "More than one cursor position match found for {}",
125            &example.spec.name
126        );
127        Ok(excerpt_offset)
128    })??;
129
130    let cursor_offset = excerpt_offset + cursor_offset_within_excerpt;
131    let cursor_anchor =
132        cursor_buffer.read_with(cx, |buffer, _| buffer.anchor_after(cursor_offset))?;
133
134    Ok((cursor_buffer, cursor_anchor))
135}
136
137async fn setup_project(
138    example: &mut Example,
139    app_state: &Arc<EpAppState>,
140    step_progress: &StepProgress,
141    cx: &mut AsyncApp,
142) -> Result<Entity<Project>> {
143    let ep_store = cx
144        .update(|cx| EditPredictionStore::try_global(cx))?
145        .context("Store should be initialized at init")?;
146
147    let worktree_path = setup_worktree(example, step_progress).await?;
148
149    if let Some(project) = app_state.project_cache.get(&example.spec.repository_url) {
150        ep_store.update(cx, |ep_store, _| {
151            ep_store.clear_history_for_project(&project);
152        })?;
153        let buffer_store = project.read_with(cx, |project, _| project.buffer_store().clone())?;
154        let buffers = buffer_store.read_with(cx, |buffer_store, _| {
155            buffer_store.buffers().collect::<Vec<_>>()
156        })?;
157        for buffer in buffers {
158            buffer
159                .update(cx, |buffer, cx| buffer.reload(cx))?
160                .await
161                .ok();
162        }
163        return Ok(project);
164    }
165
166    let project = cx.update(|cx| {
167        Project::local(
168            app_state.client.clone(),
169            app_state.node_runtime.clone(),
170            app_state.user_store.clone(),
171            app_state.languages.clone(),
172            app_state.fs.clone(),
173            None,
174            false,
175            cx,
176        )
177    })?;
178
179    project
180        .update(cx, |project, cx| {
181            project.disable_worktree_scanner(cx);
182            project.create_worktree(&worktree_path, true, cx)
183        })?
184        .await?;
185
186    app_state
187        .project_cache
188        .insert(example.spec.repository_url.clone(), project.clone());
189
190    let buffer_store = project.read_with(cx, |project, _| project.buffer_store().clone())?;
191    cx.subscribe(&buffer_store, {
192        let project = project.clone();
193        move |_, event, cx| match event {
194            BufferStoreEvent::BufferAdded(buffer) => {
195                ep_store.update(cx, |store, cx| store.register_buffer(&buffer, &project, cx));
196            }
197            _ => {}
198        }
199    })?
200    .detach();
201
202    Ok(project)
203}
204
205async fn setup_worktree(example: &Example, step_progress: &StepProgress) -> Result<PathBuf> {
206    let (repo_owner, repo_name) = example.repo_name().context("failed to get repo name")?;
207    let repo_dir = REPOS_DIR.join(repo_owner.as_ref()).join(repo_name.as_ref());
208    let worktree_path = WORKTREES_DIR
209        .join(repo_owner.as_ref())
210        .join(repo_name.as_ref());
211    let repo_lock = lock_repo(&repo_dir).await;
212
213    if !repo_dir.is_dir() {
214        step_progress.set_substatus(format!("cloning {}", repo_name));
215        fs::create_dir_all(&repo_dir)?;
216        run_git(&repo_dir, &["init"]).await?;
217        run_git(
218            &repo_dir,
219            &["remote", "add", "origin", &example.spec.repository_url],
220        )
221        .await?;
222    }
223
224    // Resolve the example to a revision, fetching it if needed.
225    let revision = run_git(
226        &repo_dir,
227        &[
228            "rev-parse",
229            &format!("{}^{{commit}}", example.spec.revision),
230        ],
231    )
232    .await;
233    let revision = if let Ok(revision) = revision {
234        revision
235    } else {
236        step_progress.set_substatus("fetching");
237        if run_git(
238            &repo_dir,
239            &["fetch", "--depth", "1", "origin", &example.spec.revision],
240        )
241        .await
242        .is_err()
243        {
244            run_git(&repo_dir, &["fetch", "origin"]).await?;
245        }
246        let revision = run_git(&repo_dir, &["rev-parse", "FETCH_HEAD"]).await?;
247        revision
248    };
249
250    // Create the worktree for this example if needed.
251    step_progress.set_substatus("preparing worktree");
252    if worktree_path.is_dir() {
253        run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
254        run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
255        run_git(&worktree_path, &["checkout", revision.as_str()]).await?;
256    } else {
257        let worktree_path_string = worktree_path.to_string_lossy();
258        run_git(
259            &repo_dir,
260            &["branch", "-f", &example.spec.name, revision.as_str()],
261        )
262        .await?;
263        run_git(
264            &repo_dir,
265            &[
266                "worktree",
267                "add",
268                "-f",
269                &worktree_path_string,
270                &example.spec.name,
271            ],
272        )
273        .await?;
274    }
275    drop(repo_lock);
276
277    // Apply the uncommitted diff for this example.
278    if !example.spec.uncommitted_diff.is_empty() {
279        step_progress.set_substatus("applying diff");
280        let mut apply_process = smol::process::Command::new("git")
281            .current_dir(&worktree_path)
282            .args(&["apply", "-"])
283            .stdin(std::process::Stdio::piped())
284            .spawn()?;
285
286        let mut stdin = apply_process.stdin.take().context("Failed to get stdin")?;
287        stdin
288            .write_all(example.spec.uncommitted_diff.as_bytes())
289            .await?;
290        stdin.close().await?;
291        drop(stdin);
292
293        let apply_result = apply_process.output().await?;
294        anyhow::ensure!(
295            apply_result.status.success(),
296            "Failed to apply uncommitted diff patch with status: {}\nstderr:\n{}\nstdout:\n{}",
297            apply_result.status,
298            String::from_utf8_lossy(&apply_result.stderr),
299            String::from_utf8_lossy(&apply_result.stdout),
300        );
301    }
302
303    step_progress.clear_substatus();
304    Ok(worktree_path)
305}
306
307async fn apply_edit_history(
308    example: &Example,
309    project: &Entity<Project>,
310    cx: &mut AsyncApp,
311) -> Result<OpenedBuffers> {
312    edit_prediction::udiff::apply_diff(&example.spec.edit_history, project, cx).await
313}
314
315thread_local! {
316    static REPO_LOCKS: RefCell<HashMap<PathBuf, Arc<Mutex<()>>>> = RefCell::new(HashMap::default());
317}
318
319#[must_use]
320pub async fn lock_repo(path: impl AsRef<Path>) -> OwnedMutexGuard<()> {
321    REPO_LOCKS
322        .with(|cell| {
323            cell.borrow_mut()
324                .entry(path.as_ref().to_path_buf())
325                .or_default()
326                .clone()
327        })
328        .lock_owned()
329        .await
330}
331
332async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
333    let output = smol::process::Command::new("git")
334        .current_dir(repo_path)
335        .args(args)
336        .output()
337        .await?;
338
339    anyhow::ensure!(
340        output.status.success(),
341        "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
342        args.join(" "),
343        repo_path.display(),
344        output.status,
345        String::from_utf8_lossy(&output.stderr),
346        String::from_utf8_lossy(&output.stdout),
347    );
348    Ok(String::from_utf8(output.stdout)?.trim().to_string())
349}