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.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.cursor_path)
 81        .await;
 82
 83    if let Err(error) = result
 84        && !error.is::<LanguageNotFound>()
 85    {
 86        return Err(error);
 87    }
 88
 89    let worktree = project.read_with(cx, |project, cx| {
 90        project
 91            .visible_worktrees(cx)
 92            .next()
 93            .context("No visible worktrees")
 94    })??;
 95
 96    let cursor_path = RelPath::new(&example.cursor_path, PathStyle::Posix)
 97        .context("Failed to create RelPath")?
 98        .into_arc();
 99    let cursor_buffer = project
100        .update(cx, |project, cx| {
101            project.open_buffer(
102                ProjectPath {
103                    worktree_id: worktree.read(cx).id(),
104                    path: cursor_path,
105                },
106                cx,
107            )
108        })?
109        .await?;
110    let cursor_offset_within_excerpt = example
111        .cursor_position
112        .find(CURSOR_MARKER)
113        .context("missing cursor marker")?;
114    let mut cursor_excerpt = example.cursor_position.clone();
115    cursor_excerpt.replace_range(
116        cursor_offset_within_excerpt..(cursor_offset_within_excerpt + CURSOR_MARKER.len()),
117        "",
118    );
119    let excerpt_offset = cursor_buffer.read_with(cx, |buffer, _cx| {
120        let text = buffer.text();
121
122        let mut matches = text.match_indices(&cursor_excerpt);
123        let (excerpt_offset, _) = matches.next().with_context(|| {
124            format!(
125                "\nExcerpt:\n\n{cursor_excerpt}\nBuffer text:\n{text}\n.Example: {}\nCursor excerpt did not exist in buffer.",
126                example.name
127            )
128        })?;
129        anyhow::ensure!(matches.next().is_none(), "More than one cursor position match found for {}", &example.name);
130        Ok(excerpt_offset)
131    })??;
132
133    let cursor_offset = excerpt_offset + cursor_offset_within_excerpt;
134    let cursor_anchor =
135        cursor_buffer.read_with(cx, |buffer, _| buffer.anchor_after(cursor_offset))?;
136
137    Ok((cursor_buffer, cursor_anchor))
138}
139
140async fn setup_project(
141    example: &mut Example,
142    app_state: &Arc<EpAppState>,
143    step_progress: &StepProgress,
144    cx: &mut AsyncApp,
145) -> Result<Entity<Project>> {
146    let ep_store = cx
147        .update(|cx| EditPredictionStore::try_global(cx))?
148        .context("Store should be initialized at init")?;
149
150    let worktree_path = setup_worktree(example, step_progress).await?;
151
152    if let Some(project) = app_state.project_cache.get(&example.repository_url) {
153        ep_store.update(cx, |ep_store, _| {
154            ep_store.clear_history_for_project(&project);
155        })?;
156        let buffer_store = project.read_with(cx, |project, _| project.buffer_store().clone())?;
157        let buffers = buffer_store.read_with(cx, |buffer_store, _| {
158            buffer_store.buffers().collect::<Vec<_>>()
159        })?;
160        for buffer in buffers {
161            buffer
162                .update(cx, |buffer, cx| buffer.reload(cx))?
163                .await
164                .ok();
165        }
166        return Ok(project);
167    }
168
169    let project = cx.update(|cx| {
170        Project::local(
171            app_state.client.clone(),
172            app_state.node_runtime.clone(),
173            app_state.user_store.clone(),
174            app_state.languages.clone(),
175            app_state.fs.clone(),
176            None,
177            cx,
178        )
179    })?;
180
181    project
182        .update(cx, |project, cx| {
183            project.disable_worktree_scanner(cx);
184            project.create_worktree(&worktree_path, true, cx)
185        })?
186        .await?;
187
188    app_state
189        .project_cache
190        .insert(example.repository_url.clone(), project.clone());
191
192    let buffer_store = project.read_with(cx, |project, _| project.buffer_store().clone())?;
193    cx.subscribe(&buffer_store, {
194        let project = project.clone();
195        move |_, event, cx| match event {
196            BufferStoreEvent::BufferAdded(buffer) => {
197                ep_store.update(cx, |store, cx| store.register_buffer(&buffer, &project, cx));
198            }
199            _ => {}
200        }
201    })?
202    .detach();
203
204    Ok(project)
205}
206
207async fn setup_worktree(example: &Example, step_progress: &StepProgress) -> Result<PathBuf> {
208    let (repo_owner, repo_name) = example.repo_name().context("failed to get repo name")?;
209    let repo_dir = REPOS_DIR.join(repo_owner.as_ref()).join(repo_name.as_ref());
210    let worktree_path = WORKTREES_DIR
211        .join(repo_owner.as_ref())
212        .join(repo_name.as_ref());
213    let repo_lock = lock_repo(&repo_dir).await;
214
215    if !repo_dir.is_dir() {
216        step_progress.set_substatus(format!("cloning {}", repo_name));
217        fs::create_dir_all(&repo_dir)?;
218        run_git(&repo_dir, &["init"]).await?;
219        run_git(
220            &repo_dir,
221            &["remote", "add", "origin", &example.repository_url],
222        )
223        .await?;
224    }
225
226    // Resolve the example to a revision, fetching it if needed.
227    let revision = run_git(
228        &repo_dir,
229        &["rev-parse", &format!("{}^{{commit}}", example.revision)],
230    )
231    .await;
232    let revision = if let Ok(revision) = revision {
233        revision
234    } else {
235        step_progress.set_substatus("fetching");
236        if run_git(
237            &repo_dir,
238            &["fetch", "--depth", "1", "origin", &example.revision],
239        )
240        .await
241        .is_err()
242        {
243            run_git(&repo_dir, &["fetch", "origin"]).await?;
244        }
245        let revision = run_git(&repo_dir, &["rev-parse", "FETCH_HEAD"]).await?;
246        revision
247    };
248
249    // Create the worktree for this example if needed.
250    step_progress.set_substatus("preparing worktree");
251    if worktree_path.is_dir() {
252        run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
253        run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
254        run_git(&worktree_path, &["checkout", revision.as_str()]).await?;
255    } else {
256        let worktree_path_string = worktree_path.to_string_lossy();
257        run_git(
258            &repo_dir,
259            &["branch", "-f", &example.name, revision.as_str()],
260        )
261        .await?;
262        run_git(
263            &repo_dir,
264            &[
265                "worktree",
266                "add",
267                "-f",
268                &worktree_path_string,
269                &example.name,
270            ],
271        )
272        .await?;
273    }
274    drop(repo_lock);
275
276    // Apply the uncommitted diff for this example.
277    if !example.uncommitted_diff.is_empty() {
278        step_progress.set_substatus("applying diff");
279        let mut apply_process = smol::process::Command::new("git")
280            .current_dir(&worktree_path)
281            .args(&["apply", "-"])
282            .stdin(std::process::Stdio::piped())
283            .spawn()?;
284
285        let mut stdin = apply_process.stdin.take().context("Failed to get stdin")?;
286        stdin.write_all(example.uncommitted_diff.as_bytes()).await?;
287        stdin.close().await?;
288        drop(stdin);
289
290        let apply_result = apply_process.output().await?;
291        anyhow::ensure!(
292            apply_result.status.success(),
293            "Failed to apply uncommitted diff patch with status: {}\nstderr:\n{}\nstdout:\n{}",
294            apply_result.status,
295            String::from_utf8_lossy(&apply_result.stderr),
296            String::from_utf8_lossy(&apply_result.stdout),
297        );
298    }
299
300    step_progress.clear_substatus();
301    Ok(worktree_path)
302}
303
304async fn apply_edit_history(
305    example: &Example,
306    project: &Entity<Project>,
307    cx: &mut AsyncApp,
308) -> Result<OpenedBuffers> {
309    edit_prediction::udiff::apply_diff(&example.edit_history, project, cx).await
310}
311
312thread_local! {
313    static REPO_LOCKS: RefCell<HashMap<PathBuf, Arc<Mutex<()>>>> = RefCell::new(HashMap::default());
314}
315
316#[must_use]
317pub async fn lock_repo(path: impl AsRef<Path>) -> OwnedMutexGuard<()> {
318    REPO_LOCKS
319        .with(|cell| {
320            cell.borrow_mut()
321                .entry(path.as_ref().to_path_buf())
322                .or_default()
323                .clone()
324        })
325        .lock_owned()
326        .await
327}
328
329async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
330    let output = smol::process::Command::new("git")
331        .current_dir(repo_path)
332        .args(args)
333        .output()
334        .await?;
335
336    anyhow::ensure!(
337        output.status.success(),
338        "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
339        args.join(" "),
340        repo_path.display(),
341        output.status,
342        String::from_utf8_lossy(&output.stderr),
343        String::from_utf8_lossy(&output.stdout),
344    );
345    Ok(String::from_utf8(output.stdout)?.trim().to_string())
346}