list_worktrees_tool.rs

 1use std::sync::Arc;
 2
 3use anyhow::{anyhow, Result};
 4use assistant_tool::Tool;
 5use gpui::{App, Task, WeakEntity};
 6use project::Project;
 7use schemars::JsonSchema;
 8use serde::{Deserialize, Serialize};
 9
10#[derive(Debug, Serialize, Deserialize, JsonSchema)]
11pub struct ListWorktreesToolInput {}
12
13pub struct ListWorktreesTool;
14
15impl Tool for ListWorktreesTool {
16    fn name(&self) -> String {
17        "list-worktrees".into()
18    }
19
20    fn description(&self) -> String {
21        "Lists all worktrees in the current project. Use this tool when you need to find available worktrees and their IDs.".into()
22    }
23
24    fn input_schema(&self) -> serde_json::Value {
25        serde_json::json!(
26            {
27                "type": "object",
28                "properties": {},
29                "required": []
30            }
31        )
32    }
33
34    fn run(
35        self: Arc<Self>,
36        _input: serde_json::Value,
37        project: WeakEntity<Project>,
38        cx: &mut App,
39    ) -> Task<Result<String>> {
40        let Some(project) = project.upgrade() else {
41            return Task::ready(Err(anyhow!("project dropped")));
42        };
43
44        cx.spawn(|cx| async move {
45            cx.update(|cx| {
46                #[derive(Debug, Serialize)]
47                struct WorktreeInfo {
48                    id: usize,
49                    root_name: String,
50                    root_dir: Option<String>,
51                }
52
53                let worktrees = project.update(cx, |project, cx| {
54                    project
55                        .visible_worktrees(cx)
56                        .map(|worktree| {
57                            worktree.read_with(cx, |worktree, _cx| WorktreeInfo {
58                                id: worktree.id().to_usize(),
59                                root_dir: worktree
60                                    .root_dir()
61                                    .map(|root_dir| root_dir.to_string_lossy().to_string()),
62                                root_name: worktree.root_name().to_string(),
63                            })
64                        })
65                        .collect::<Vec<_>>()
66                });
67
68                if worktrees.is_empty() {
69                    return Ok("No worktrees found in the current project.".to_string());
70                }
71
72                let mut result = String::from("Worktrees in the current project:\n\n");
73                for worktree in worktrees {
74                    result.push_str(&serde_json::to_string(&worktree)?);
75                }
76
77                Ok(result)
78            })?
79        })
80    }
81}