|
| 1 | +//! Authenticated remote branch management for Projects repositories. |
| 2 | +
|
| 3 | +use super::project_git::first_output_line; |
| 4 | +use super::project_git_diff::clean_commit; |
| 5 | +use super::project_git_exec::{ |
| 6 | + build_git_auth_config, clean_branch, run_git, validate_workspace_clone_url, GitAuthConfig, |
| 7 | +}; |
| 8 | +use crate::app_state::AppState; |
| 9 | +use serde::Serialize; |
| 10 | +use tauri::State; |
| 11 | + |
| 12 | +#[derive(Serialize)] |
| 13 | +pub struct ProjectRepoBranchResult { |
| 14 | + pub branch: String, |
| 15 | + pub commit: String, |
| 16 | + pub message: String, |
| 17 | +} |
| 18 | + |
| 19 | +fn normalize_branch(value: &str, label: &str) -> Result<String, String> { |
| 20 | + let value = value.trim(); |
| 21 | + if value.starts_with("refs/") && !value.starts_with("refs/heads/") { |
| 22 | + return Err(format!("Invalid {label} branch.")); |
| 23 | + } |
| 24 | + let branch = |
| 25 | + clean_branch(Some(value.to_string())).ok_or_else(|| format!("Invalid {label} branch."))?; |
| 26 | + if branch.ends_with('.') |
| 27 | + || branch.ends_with(".lock") |
| 28 | + || branch.contains("//") |
| 29 | + || branch |
| 30 | + .split('/') |
| 31 | + .any(|component| component.starts_with('.')) |
| 32 | + { |
| 33 | + return Err(format!("Invalid {label} branch.")); |
| 34 | + } |
| 35 | + Ok(branch) |
| 36 | +} |
| 37 | + |
| 38 | +fn normalize_commit(value: &str, label: &str) -> Result<String, String> { |
| 39 | + clean_commit(Some(value.trim().to_ascii_lowercase())) |
| 40 | + .ok_or_else(|| format!("Invalid {label} commit.")) |
| 41 | +} |
| 42 | + |
| 43 | +fn remote_head_branch(output: &str) -> Option<String> { |
| 44 | + output.lines().find_map(|line| { |
| 45 | + let target = line.strip_prefix("ref: ")?.strip_suffix("\tHEAD")?; |
| 46 | + let branch = target.strip_prefix("refs/heads/")?; |
| 47 | + clean_branch(Some(branch.to_string())) |
| 48 | + }) |
| 49 | +} |
| 50 | + |
| 51 | +fn create_remote_branch_blocking( |
| 52 | + clone_url: &str, |
| 53 | + source_branch: &str, |
| 54 | + expected_commit: &str, |
| 55 | + new_branch: &str, |
| 56 | + auth: &GitAuthConfig, |
| 57 | +) -> Result<ProjectRepoBranchResult, String> { |
| 58 | + let temp_dir = tempfile::tempdir().map_err(|error| format!("create temp dir: {error}"))?; |
| 59 | + let repo_dir = temp_dir.path().join("repo.git"); |
| 60 | + let repo_path = repo_dir |
| 61 | + .to_str() |
| 62 | + .ok_or_else(|| "temporary repository path is not UTF-8".to_string())?; |
| 63 | + run_git(&["init", "--bare", "--", repo_path], None, auth)?; |
| 64 | + run_git( |
| 65 | + &["remote", "add", "--", "origin", clone_url], |
| 66 | + Some(&repo_dir), |
| 67 | + auth, |
| 68 | + )?; |
| 69 | + run_git( |
| 70 | + &[ |
| 71 | + "fetch", |
| 72 | + "--quiet", |
| 73 | + "--depth=1", |
| 74 | + "--no-tags", |
| 75 | + "--end-of-options", |
| 76 | + "origin", |
| 77 | + format!("refs/heads/{source_branch}").as_str(), |
| 78 | + ], |
| 79 | + Some(&repo_dir), |
| 80 | + auth, |
| 81 | + )?; |
| 82 | + let source_commit = run_git(&["rev-parse", "FETCH_HEAD"], Some(&repo_dir), auth) |
| 83 | + .ok() |
| 84 | + .and_then(|output| first_output_line(&output)) |
| 85 | + .ok_or_else(|| "Could not resolve the source branch.".to_string())? |
| 86 | + .to_ascii_lowercase(); |
| 87 | + if source_commit != expected_commit { |
| 88 | + return Err( |
| 89 | + "The source branch changed. Refresh the repository before creating a branch." |
| 90 | + .to_string(), |
| 91 | + ); |
| 92 | + } |
| 93 | + let lease = format!("--force-with-lease=refs/heads/{new_branch}:"); |
| 94 | + let refspec = format!("{source_commit}:refs/heads/{new_branch}"); |
| 95 | + run_git( |
| 96 | + &[ |
| 97 | + "push", |
| 98 | + lease.as_str(), |
| 99 | + "--end-of-options", |
| 100 | + "origin", |
| 101 | + refspec.as_str(), |
| 102 | + ], |
| 103 | + Some(&repo_dir), |
| 104 | + auth, |
| 105 | + )?; |
| 106 | + |
| 107 | + Ok(ProjectRepoBranchResult { |
| 108 | + branch: new_branch.to_string(), |
| 109 | + commit: source_commit, |
| 110 | + message: format!("Created branch {new_branch} from {source_branch}."), |
| 111 | + }) |
| 112 | +} |
| 113 | + |
| 114 | +fn delete_remote_branch_blocking( |
| 115 | + clone_url: &str, |
| 116 | + branch: &str, |
| 117 | + expected_commit: &str, |
| 118 | + auth: &GitAuthConfig, |
| 119 | +) -> Result<ProjectRepoBranchResult, String> { |
| 120 | + let head_output = run_git( |
| 121 | + &[ |
| 122 | + "ls-remote", |
| 123 | + "--symref", |
| 124 | + "--exit-code", |
| 125 | + "--end-of-options", |
| 126 | + clone_url, |
| 127 | + "HEAD", |
| 128 | + ], |
| 129 | + None, |
| 130 | + auth, |
| 131 | + )?; |
| 132 | + if remote_head_branch(&head_output).as_deref() == Some(branch) { |
| 133 | + return Err("The repository's default branch cannot be deleted.".to_string()); |
| 134 | + } |
| 135 | + |
| 136 | + let temp_dir = tempfile::tempdir().map_err(|error| format!("create temp dir: {error}"))?; |
| 137 | + let repo_dir = temp_dir.path().join("repo.git"); |
| 138 | + let repo_path = repo_dir |
| 139 | + .to_str() |
| 140 | + .ok_or_else(|| "temporary repository path is not UTF-8".to_string())?; |
| 141 | + run_git(&["init", "--bare", "--", repo_path], None, auth)?; |
| 142 | + run_git( |
| 143 | + &["remote", "add", "--", "origin", clone_url], |
| 144 | + Some(&repo_dir), |
| 145 | + auth, |
| 146 | + )?; |
| 147 | + let lease = format!("--force-with-lease=refs/heads/{branch}:{expected_commit}"); |
| 148 | + let refspec = format!(":refs/heads/{branch}"); |
| 149 | + run_git( |
| 150 | + &[ |
| 151 | + "push", |
| 152 | + lease.as_str(), |
| 153 | + "--end-of-options", |
| 154 | + "origin", |
| 155 | + refspec.as_str(), |
| 156 | + ], |
| 157 | + Some(&repo_dir), |
| 158 | + auth, |
| 159 | + )?; |
| 160 | + |
| 161 | + Ok(ProjectRepoBranchResult { |
| 162 | + branch: branch.to_string(), |
| 163 | + commit: expected_commit.to_string(), |
| 164 | + message: format!("Deleted branch {branch}."), |
| 165 | + }) |
| 166 | +} |
| 167 | + |
| 168 | +#[tauri::command] |
| 169 | +pub async fn create_project_remote_branch( |
| 170 | + clone_url: String, |
| 171 | + source_branch: String, |
| 172 | + expected_commit: String, |
| 173 | + new_branch: String, |
| 174 | + state: State<'_, AppState>, |
| 175 | +) -> Result<ProjectRepoBranchResult, String> { |
| 176 | + validate_workspace_clone_url(&clone_url, &state)?; |
| 177 | + let source_branch = normalize_branch(&source_branch, "source")?; |
| 178 | + let expected_commit = normalize_commit(&expected_commit, "source")?; |
| 179 | + let new_branch = normalize_branch(&new_branch, "new")?; |
| 180 | + if new_branch == source_branch { |
| 181 | + return Err("The new branch must have a different name.".to_string()); |
| 182 | + } |
| 183 | + let auth = build_git_auth_config(&state)?; |
| 184 | + |
| 185 | + tauri::async_runtime::spawn_blocking(move || { |
| 186 | + create_remote_branch_blocking( |
| 187 | + &clone_url, |
| 188 | + &source_branch, |
| 189 | + &expected_commit, |
| 190 | + &new_branch, |
| 191 | + &auth, |
| 192 | + ) |
| 193 | + }) |
| 194 | + .await |
| 195 | + .map_err(|error| format!("branch creation task failed: {error}"))? |
| 196 | +} |
| 197 | + |
| 198 | +#[tauri::command] |
| 199 | +pub async fn delete_project_remote_branch( |
| 200 | + clone_url: String, |
| 201 | + branch: String, |
| 202 | + expected_commit: String, |
| 203 | + state: State<'_, AppState>, |
| 204 | +) -> Result<ProjectRepoBranchResult, String> { |
| 205 | + validate_workspace_clone_url(&clone_url, &state)?; |
| 206 | + let branch = normalize_branch(&branch, "branch")?; |
| 207 | + let expected_commit = normalize_commit(&expected_commit, "branch")?; |
| 208 | + let auth = build_git_auth_config(&state)?; |
| 209 | + |
| 210 | + tauri::async_runtime::spawn_blocking(move || { |
| 211 | + delete_remote_branch_blocking(&clone_url, &branch, &expected_commit, &auth) |
| 212 | + }) |
| 213 | + .await |
| 214 | + .map_err(|error| format!("branch deletion task failed: {error}"))? |
| 215 | +} |
| 216 | + |
| 217 | +#[cfg(test)] |
| 218 | +mod tests { |
| 219 | + use super::{ |
| 220 | + create_remote_branch_blocking, delete_remote_branch_blocking, normalize_branch, |
| 221 | + normalize_commit, remote_head_branch, |
| 222 | + }; |
| 223 | + use crate::commands::project_git_exec::{build_test_git_auth_config, run_git}; |
| 224 | + |
| 225 | + #[test] |
| 226 | + fn branch_inputs_use_conservative_git_validation() { |
| 227 | + assert_eq!( |
| 228 | + normalize_branch("refs/heads/feature/demo", "source"), |
| 229 | + Ok("feature/demo".to_string()) |
| 230 | + ); |
| 231 | + assert!(normalize_branch("--upload-pack=/tmp/evil", "new").is_err()); |
| 232 | + assert!(normalize_branch("feature/../main", "new").is_err()); |
| 233 | + assert!(normalize_branch("refs/tags/v1", "new").is_err()); |
| 234 | + assert!(normalize_branch("feature//demo", "new").is_err()); |
| 235 | + assert!(normalize_branch("feature/.hidden", "new").is_err()); |
| 236 | + assert!(normalize_branch("feature/demo.lock", "new").is_err()); |
| 237 | + } |
| 238 | + |
| 239 | + #[test] |
| 240 | + fn commit_inputs_accept_sha1_and_sha256() { |
| 241 | + assert_eq!( |
| 242 | + normalize_commit(&"A".repeat(40), "source"), |
| 243 | + Ok("a".repeat(40)) |
| 244 | + ); |
| 245 | + assert_eq!( |
| 246 | + normalize_commit(&"B".repeat(64), "branch"), |
| 247 | + Ok("b".repeat(64)) |
| 248 | + ); |
| 249 | + assert!(normalize_commit("not-a-commit", "source").is_err()); |
| 250 | + } |
| 251 | + |
| 252 | + #[test] |
| 253 | + fn remote_head_parser_only_accepts_branch_symrefs() { |
| 254 | + assert_eq!( |
| 255 | + remote_head_branch( |
| 256 | + "ref: refs/heads/main\tHEAD\n0123456789012345678901234567890123456789\tHEAD\n" |
| 257 | + ), |
| 258 | + Some("main".to_string()) |
| 259 | + ); |
| 260 | + assert_eq!(remote_head_branch("0123\tHEAD\n"), None); |
| 261 | + assert_eq!(remote_head_branch("ref: refs/tags/v1\tHEAD\n"), None); |
| 262 | + } |
| 263 | + |
| 264 | + #[test] |
| 265 | + fn remote_branch_create_and_delete_round_trip() { |
| 266 | + let auth = build_test_git_auth_config().expect("build test git config"); |
| 267 | + let root = tempfile::tempdir().expect("create test directory"); |
| 268 | + let remote = root.path().join("remote.git"); |
| 269 | + let worktree = root.path().join("worktree"); |
| 270 | + let remote_path = remote.to_str().expect("remote path"); |
| 271 | + let worktree_path = worktree.to_str().expect("worktree path"); |
| 272 | + |
| 273 | + run_git(&["init", "--bare", "--", remote_path], None, &auth).expect("init remote"); |
| 274 | + run_git(&["init", "--", worktree_path], None, &auth).expect("init worktree"); |
| 275 | + std::fs::write(worktree.join("README.md"), "branch test\n").expect("write fixture"); |
| 276 | + run_git(&["add", "README.md"], Some(&worktree), &auth).expect("stage fixture"); |
| 277 | + run_git( |
| 278 | + &[ |
| 279 | + "-c", |
| 280 | + "user.name=Buzz Test", |
| 281 | + "-c", |
| 282 | + |
| 283 | + "commit", |
| 284 | + "-m", |
| 285 | + "Initial commit", |
| 286 | + ], |
| 287 | + Some(&worktree), |
| 288 | + &auth, |
| 289 | + ) |
| 290 | + .expect("commit fixture"); |
| 291 | + run_git(&["branch", "-M", "main"], Some(&worktree), &auth).expect("rename branch"); |
| 292 | + run_git( |
| 293 | + &["remote", "add", "origin", remote_path], |
| 294 | + Some(&worktree), |
| 295 | + &auth, |
| 296 | + ) |
| 297 | + .expect("add remote"); |
| 298 | + run_git(&["push", "origin", "main"], Some(&worktree), &auth).expect("push main"); |
| 299 | + run_git( |
| 300 | + &[ |
| 301 | + format!("--git-dir={remote_path}").as_str(), |
| 302 | + "symbolic-ref", |
| 303 | + "HEAD", |
| 304 | + "refs/heads/main", |
| 305 | + ], |
| 306 | + None, |
| 307 | + &auth, |
| 308 | + ) |
| 309 | + .expect("set remote HEAD"); |
| 310 | + let commit = run_git(&["rev-parse", "HEAD"], Some(&worktree), &auth) |
| 311 | + .expect("resolve fixture commit") |
| 312 | + .trim() |
| 313 | + .to_string(); |
| 314 | + |
| 315 | + let created = |
| 316 | + create_remote_branch_blocking(remote_path, "main", &commit, "feature/demo", &auth) |
| 317 | + .expect("create remote branch"); |
| 318 | + assert_eq!(created.branch, "feature/demo"); |
| 319 | + assert!(run_git( |
| 320 | + &[ |
| 321 | + format!("--git-dir={remote_path}").as_str(), |
| 322 | + "show-ref", |
| 323 | + "--verify", |
| 324 | + "refs/heads/feature/demo", |
| 325 | + ], |
| 326 | + None, |
| 327 | + &auth, |
| 328 | + ) |
| 329 | + .is_ok()); |
| 330 | + |
| 331 | + delete_remote_branch_blocking(remote_path, "feature/demo", &commit, &auth) |
| 332 | + .expect("delete remote branch"); |
| 333 | + assert!(run_git( |
| 334 | + &[ |
| 335 | + format!("--git-dir={remote_path}").as_str(), |
| 336 | + "show-ref", |
| 337 | + "--verify", |
| 338 | + "refs/heads/feature/demo", |
| 339 | + ], |
| 340 | + None, |
| 341 | + &auth, |
| 342 | + ) |
| 343 | + .is_err()); |
| 344 | + assert!(delete_remote_branch_blocking(remote_path, "main", &commit, &auth).is_err()); |
| 345 | + } |
| 346 | +} |
0 commit comments