Skip to main content

routa_server/api/
worktrees.rs

1use axum::{
2    extract::{Path, Query, State},
3    routing::{get, post},
4    Json, Router,
5};
6use serde::Deserialize;
7use std::collections::HashMap;
8use std::sync::Arc;
9use tokio::sync::Mutex;
10
11use crate::error::ServerError;
12use crate::git;
13use crate::models::worktree::Worktree;
14use crate::state::AppState;
15
16/// Per-repository mutex for serializing git worktree operations.
17type RepoLocks = Arc<Mutex<HashMap<String, Arc<Mutex<()>>>>>;
18
19lazy_static::lazy_static! {
20    static ref REPO_LOCKS: RepoLocks = Arc::new(Mutex::new(HashMap::new()));
21}
22
23/// Get the global repo locks map (for reuse in codebase deletion).
24pub fn get_repo_locks() -> &'static RepoLocks {
25    &REPO_LOCKS
26}
27
28async fn get_repo_lock(repo_path: &str) -> Arc<Mutex<()>> {
29    let mut locks = REPO_LOCKS.lock().await;
30    locks
31        .entry(repo_path.to_string())
32        .or_insert_with(|| Arc::new(Mutex::new(())))
33        .clone()
34}
35
36pub fn router() -> Router<AppState> {
37    Router::new()
38        .route(
39            "/workspaces/{workspace_id}/codebases/{codebase_id}/worktrees",
40            get(list_worktrees).post(create_worktree),
41        )
42        .route("/worktrees/{id}", get(get_worktree).delete(delete_worktree))
43        .route("/worktrees/{id}/validate", post(validate_worktree))
44}
45
46// ─── List Worktrees ─────────────────────────────────────────────────────
47
48async fn list_worktrees(
49    State(state): State<AppState>,
50    Path((workspace_id, codebase_id)): Path<(String, String)>,
51) -> Result<Json<serde_json::Value>, ServerError> {
52    // Validate codebase belongs to the workspace
53    let codebase = state
54        .codebase_store
55        .get(&codebase_id)
56        .await?
57        .ok_or_else(|| ServerError::NotFound(format!("Codebase {} not found", codebase_id)))?;
58    if codebase.workspace_id != workspace_id {
59        return Err(ServerError::NotFound(format!(
60            "Codebase {} not found",
61            codebase_id
62        )));
63    }
64
65    let worktrees = state.worktree_store.list_by_codebase(&codebase_id).await?;
66    Ok(Json(serde_json::json!({ "worktrees": worktrees })))
67}
68
69// ─── Create Worktree ────────────────────────────────────────────────────
70
71#[derive(Debug, Deserialize)]
72#[serde(rename_all = "camelCase")]
73struct CreateWorktreeRequest {
74    branch: Option<String>,
75    base_branch: Option<String>,
76    label: Option<String>,
77}
78
79async fn create_worktree(
80    State(state): State<AppState>,
81    Path((workspace_id, codebase_id)): Path<(String, String)>,
82    Json(body): Json<CreateWorktreeRequest>,
83) -> Result<Json<serde_json::Value>, ServerError> {
84    let codebase = state
85        .codebase_store
86        .get(&codebase_id)
87        .await?
88        .ok_or_else(|| ServerError::NotFound(format!("Codebase {} not found", codebase_id)))?;
89
90    // Validate codebase belongs to the workspace
91    if codebase.workspace_id != workspace_id {
92        return Err(ServerError::NotFound(format!(
93            "Codebase {} not found",
94            codebase_id
95        )));
96    }
97
98    let repo_path = &codebase.repo_path;
99    let base_branch = body.base_branch.unwrap_or_else(|| {
100        codebase
101            .branch
102            .clone()
103            .unwrap_or_else(|| "main".to_string())
104    });
105
106    let uuid_str = uuid::Uuid::new_v4().to_string();
107    let short_id = &uuid_str[..8];
108    let branch = body.branch.unwrap_or_else(|| {
109        let suffix = body
110            .label
111            .as_ref()
112            .map(|l| git::branch_to_safe_dir_name(l))
113            .unwrap_or_else(|| short_id.to_string());
114        format!("wt/{}", suffix)
115    });
116
117    // Acquire repo lock BEFORE branch check + DB insert to prevent races
118    let lock = get_repo_lock(repo_path).await;
119    let _guard = lock.lock().await;
120
121    // Check if branch already used by another worktree (inside lock)
122    if let Some(existing) = state
123        .worktree_store
124        .find_by_branch(&codebase_id, &branch)
125        .await?
126    {
127        return Err(ServerError::Conflict(format!(
128            "Branch '{}' is already in use by worktree {}",
129            branch, existing.id
130        )));
131    }
132
133    // Compute worktree path
134    let worktree_path = git::get_worktree_base_dir()
135        .join(&codebase.workspace_id)
136        .join(&codebase_id)
137        .join(git::branch_to_safe_dir_name(&branch));
138
139    // Ensure parent directory exists
140    if let Some(parent) = worktree_path.parent() {
141        std::fs::create_dir_all(parent).map_err(|e| {
142            ServerError::Internal(format!("Failed to create worktree parent dir: {}", e))
143        })?;
144    }
145
146    let worktree_path_str = worktree_path.to_string_lossy().to_string();
147
148    // Create DB record
149    let worktree = Worktree::new(
150        uuid::Uuid::new_v4().to_string(),
151        codebase_id.clone(),
152        codebase.workspace_id.clone(),
153        worktree_path_str.clone(),
154        branch.clone(),
155        base_branch.clone(),
156        body.label,
157    );
158    state.worktree_store.save(&worktree).await?;
159
160    // Prune stale references
161    let _ = git::worktree_prune(repo_path);
162
163    // Check if branch already exists
164    let branch_already_exists = git::branch_exists(repo_path, &branch);
165
166    let result = if branch_already_exists {
167        git::worktree_add(repo_path, &worktree_path_str, &branch, &base_branch, false)
168    } else {
169        git::worktree_add(repo_path, &worktree_path_str, &branch, &base_branch, true)
170    };
171
172    match result {
173        Ok(()) => {
174            state
175                .worktree_store
176                .update_status(&worktree.id, "active", None)
177                .await?;
178            let updated = state
179                .worktree_store
180                .get(&worktree.id)
181                .await?
182                .unwrap_or(worktree);
183            Ok(Json(serde_json::json!({ "worktree": updated })))
184        }
185        Err(err) => {
186            state
187                .worktree_store
188                .update_status(&worktree.id, "error", Some(&err))
189                .await?;
190            Err(ServerError::Internal(format!(
191                "Failed to create worktree: {}",
192                err
193            )))
194        }
195    }
196}
197
198// ─── Get Worktree ───────────────────────────────────────────────────────
199
200async fn get_worktree(
201    State(state): State<AppState>,
202    Path(id): Path<String>,
203) -> Result<Json<serde_json::Value>, ServerError> {
204    let worktree = state
205        .worktree_store
206        .get(&id)
207        .await?
208        .ok_or_else(|| ServerError::NotFound(format!("Worktree {} not found", id)))?;
209    Ok(Json(serde_json::json!({ "worktree": worktree })))
210}
211
212// ─── Delete Worktree ────────────────────────────────────────────────────
213
214#[derive(Debug, Deserialize, Default)]
215#[serde(rename_all = "camelCase")]
216struct DeleteWorktreeQuery {
217    delete_branch: Option<bool>,
218}
219
220async fn delete_worktree(
221    State(state): State<AppState>,
222    Path(id): Path<String>,
223    Query(query): Query<DeleteWorktreeQuery>,
224) -> Result<Json<serde_json::Value>, ServerError> {
225    let worktree = state
226        .worktree_store
227        .get(&id)
228        .await?
229        .ok_or_else(|| ServerError::NotFound(format!("Worktree {} not found", id)))?;
230
231    let codebase = state.codebase_store.get(&worktree.codebase_id).await?;
232
233    if let Some(codebase) = codebase {
234        let repo_path = &codebase.repo_path;
235        let lock = get_repo_lock(repo_path).await;
236        let _guard = lock.lock().await;
237
238        state
239            .worktree_store
240            .update_status(&id, "removing", None)
241            .await?;
242
243        // Remove worktree from disk
244        let _ = git::worktree_remove(repo_path, &worktree.worktree_path, true);
245        let _ = git::worktree_prune(repo_path);
246
247        // Optionally delete the branch
248        if query.delete_branch.unwrap_or(false) {
249            let _ = std::process::Command::new("git")
250                .args(["branch", "-D", &worktree.branch])
251                .current_dir(repo_path)
252                .output();
253        }
254    }
255
256    state.worktree_store.delete(&id).await?;
257    Ok(Json(serde_json::json!({ "deleted": true })))
258}
259
260// ─── Validate Worktree ──────────────────────────────────────────────────
261
262async fn validate_worktree(
263    State(state): State<AppState>,
264    Path(id): Path<String>,
265) -> Result<Json<serde_json::Value>, ServerError> {
266    let worktree = state
267        .worktree_store
268        .get(&id)
269        .await?
270        .ok_or_else(|| ServerError::NotFound(format!("Worktree {} not found", id)))?;
271
272    let path = std::path::Path::new(&worktree.worktree_path);
273    if !path.exists() {
274        state
275            .worktree_store
276            .update_status(&id, "error", Some("Worktree directory missing"))
277            .await?;
278        return Ok(Json(
279            serde_json::json!({ "healthy": false, "error": "Worktree directory missing" }),
280        ));
281    }
282
283    let git_file = path.join(".git");
284    if !git_file.exists() {
285        state
286            .worktree_store
287            .update_status(
288                &id,
289                "error",
290                Some("Not a valid worktree (.git file missing)"),
291            )
292            .await?;
293        return Ok(Json(
294            serde_json::json!({ "healthy": false, "error": "Not a valid worktree (.git file missing)" }),
295        ));
296    }
297
298    // Restore to active if was in error state
299    if worktree.status == "error" {
300        state
301            .worktree_store
302            .update_status(&id, "active", None)
303            .await?;
304    }
305
306    Ok(Json(serde_json::json!({ "healthy": true })))
307}