forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·9.7 MiB·37e985d·Tahinli·2 hours ago·363 commits
| 1 | use std::collections::HashSet; |
| 2 | use std::path::Path; |
| 3 | |
| 4 | use gix::bstr::ByteSlice; |
| 5 | use gix::objs::tree::EntryKind as GixEntryKind; |
| 6 | |
| 7 | use crate::error::{Error, Result}; |
| 8 | |
| 9 | const BINARY_PROBE_BYTES: usize = 8000; |
| 10 | const MAX_PATH_BYTES: usize = 4096; |
| 11 | |
| 12 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 13 | pub enum RefKind { |
| 14 | Branch, |
| 15 | Tag, |
| 16 | } |
| 17 | |
| 18 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 19 | pub struct RefInfo { |
| 20 | pub name: String, |
| 21 | pub full_name: String, |
| 22 | pub target: String, |
| 23 | pub kind: RefKind, |
| 24 | pub committer_time: i64, |
| 25 | } |
| 26 | |
| 27 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 28 | pub enum EntryKind { |
| 29 | Blob, |
| 30 | Executable, |
| 31 | Symlink, |
| 32 | Tree, |
| 33 | Submodule, |
| 34 | } |
| 35 | |
| 36 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 37 | pub struct TreeEntry { |
| 38 | pub name: String, |
| 39 | pub kind: EntryKind, |
| 40 | pub oid: String, |
| 41 | pub size: Option<u64>, |
| 42 | } |
| 43 | |
| 44 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 45 | pub struct BlobData { |
| 46 | pub oid: String, |
| 47 | pub kind: EntryKind, |
| 48 | pub size: u64, |
| 49 | pub data: Vec<u8>, |
| 50 | pub truncated: bool, |
| 51 | pub is_binary: bool, |
| 52 | } |
| 53 | |
| 54 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 55 | pub struct CommitInfo { |
| 56 | pub oid: String, |
| 57 | pub parents: Vec<String>, |
| 58 | pub author_name: String, |
| 59 | pub author_email: String, |
| 60 | pub author_time: i64, |
| 61 | pub committer_name: String, |
| 62 | pub committer_email: String, |
| 63 | pub committer_time: i64, |
| 64 | pub summary: String, |
| 65 | pub message: String, |
| 66 | } |
| 67 | |
| 68 | fn gerr(e: impl std::fmt::Display) -> Error { |
| 69 | Error::Failed(e.to_string()) |
| 70 | } |
| 71 | |
| 72 | fn open(repo: &Path) -> Result<gix::Repository> { |
| 73 | let options = gix::open::Options::isolated().config_overrides(["core.deltaBaseCacheLimit=16m"]); |
| 74 | gix::open_opts(repo, options).map_err(gerr) |
| 75 | } |
| 76 | |
| 77 | fn valid_ref_name(name: &str) -> bool { |
| 78 | if name.is_empty() || name.len() > 255 || name == "@" { |
| 79 | return false; |
| 80 | } |
| 81 | if name.starts_with('-') || name.starts_with('/') || name.ends_with('/') || name.ends_with('.') |
| 82 | { |
| 83 | return false; |
| 84 | } |
| 85 | if name.contains("..") || name.contains("@{") || name.contains("//") { |
| 86 | return false; |
| 87 | } |
| 88 | if name |
| 89 | .chars() |
| 90 | .any(|c| c.is_control() || " ~^:?*[\\".contains(c)) |
| 91 | { |
| 92 | return false; |
| 93 | } |
| 94 | name.split('/') |
| 95 | .all(|seg| !seg.is_empty() && !seg.starts_with('.') && !seg.ends_with(".lock")) |
| 96 | } |
| 97 | |
| 98 | fn valid_hex_prefix(s: &str) -> bool { |
| 99 | (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit()) |
| 100 | } |
| 101 | |
| 102 | fn parse_oid(hex: &str) -> Result<gix::ObjectId> { |
| 103 | gix::ObjectId::from_hex(hex.as_bytes()) |
| 104 | .map_err(|_| Error::InvalidInput(format!("not a full object id: {hex}"))) |
| 105 | } |
| 106 | |
| 107 | fn ref_commit(repo: &gix::Repository, name: &str) -> Result<Option<gix::ObjectId>> { |
| 108 | for prefix in ["refs/heads/", "refs/tags/"] { |
| 109 | let full = format!("{prefix}{name}"); |
| 110 | let Some(mut reference) = repo.try_find_reference(full.as_str()).map_err(gerr)? else { |
| 111 | continue; |
| 112 | }; |
| 113 | let id = reference.peel_to_id().map_err(gerr)?.detach(); |
| 114 | if is_commit(repo, id)? { |
| 115 | return Ok(Some(id)); |
| 116 | } |
| 117 | } |
| 118 | Ok(None) |
| 119 | } |
| 120 | |
| 121 | fn is_commit(repo: &gix::Repository, id: gix::ObjectId) -> Result<bool> { |
| 122 | Ok(matches!( |
| 123 | repo.try_find_header(id).map_err(gerr)?, |
| 124 | Some(h) if h.kind() == gix::objs::Kind::Commit |
| 125 | )) |
| 126 | } |
| 127 | |
| 128 | pub fn list_refs(repo: &Path) -> Result<Vec<RefInfo>> { |
| 129 | let repo = open(repo)?; |
| 130 | let refs = repo.references().map_err(gerr)?; |
| 131 | let mut out = Vec::new(); |
| 132 | let groups = [ |
| 133 | (RefKind::Branch, refs.local_branches().map_err(gerr)?), |
| 134 | (RefKind::Tag, refs.tags().map_err(gerr)?), |
| 135 | ]; |
| 136 | for (kind, iter) in groups { |
| 137 | for reference in iter { |
| 138 | let mut reference = reference.map_err(gerr)?; |
| 139 | let full_name = reference.name().as_bstr().to_str_lossy().into_owned(); |
| 140 | let name = reference.name().shorten().to_str_lossy().into_owned(); |
| 141 | let id = reference.peel_to_id().map_err(gerr)?.detach(); |
| 142 | if !is_commit(&repo, id)? { |
| 143 | continue; |
| 144 | } |
| 145 | let commit = repo.find_commit(id).map_err(gerr)?; |
| 146 | let committer_time = commit |
| 147 | .decode() |
| 148 | .map_err(gerr)? |
| 149 | .committer() |
| 150 | .map_err(gerr)? |
| 151 | .time() |
| 152 | .map_err(gerr)? |
| 153 | .seconds; |
| 154 | out.push(RefInfo { |
| 155 | name, |
| 156 | full_name, |
| 157 | target: id.to_hex().to_string(), |
| 158 | kind, |
| 159 | committer_time, |
| 160 | }); |
| 161 | } |
| 162 | } |
| 163 | Ok(out) |
| 164 | } |
| 165 | |
| 166 | pub fn default_branch_commit(repo: &Path, branch: &str) -> Result<Option<String>> { |
| 167 | if !valid_ref_name(branch) { |
| 168 | return Ok(None); |
| 169 | } |
| 170 | let repo = open(repo)?; |
| 171 | let full = format!("refs/heads/{branch}"); |
| 172 | let Some(mut reference) = repo.try_find_reference(full.as_str()).map_err(gerr)? else { |
| 173 | return Ok(None); |
| 174 | }; |
| 175 | let id = reference.peel_to_id().map_err(gerr)?.detach(); |
| 176 | Ok(is_commit(&repo, id)?.then(|| id.to_hex().to_string())) |
| 177 | } |
| 178 | |
| 179 | pub fn peel_to_commit(repo: &Path, oid: &str) -> Result<Option<String>> { |
| 180 | let repo = open(repo)?; |
| 181 | let Some(object) = repo.try_find_object(parse_oid(oid)?).map_err(gerr)? else { |
| 182 | return Ok(None); |
| 183 | }; |
| 184 | Ok(object |
| 185 | .peel_to_commit() |
| 186 | .ok() |
| 187 | .map(|c| c.id.to_hex().to_string())) |
| 188 | } |
| 189 | |
| 190 | pub fn resolve_commit(repo: &Path, rev: &str) -> Result<Option<String>> { |
| 191 | if valid_ref_name(rev) { |
| 192 | let repo = open(repo)?; |
| 193 | if let Some(id) = ref_commit(&repo, rev)? { |
| 194 | return Ok(Some(id.to_hex().to_string())); |
| 195 | } |
| 196 | if !valid_hex_prefix(rev) { |
| 197 | return Ok(None); |
| 198 | } |
| 199 | return resolve_hex(&repo, rev); |
| 200 | } |
| 201 | if valid_hex_prefix(rev) { |
| 202 | let repo = open(repo)?; |
| 203 | return resolve_hex(&repo, rev); |
| 204 | } |
| 205 | Ok(None) |
| 206 | } |
| 207 | |
| 208 | fn resolve_hex(repo: &gix::Repository, hex: &str) -> Result<Option<String>> { |
| 209 | let lower = hex.to_ascii_lowercase(); |
| 210 | let prefix = gix::hash::Prefix::from_hex(&lower).map_err(gerr)?; |
| 211 | let outcome = repo.objects.lookup_prefix(prefix, None).map_err(gerr)?; |
| 212 | match outcome { |
| 213 | Some(Ok(id)) if is_commit(repo, id)? && reachable(repo, id)? => { |
| 214 | Ok(Some(id.to_hex().to_string())) |
| 215 | } |
| 216 | _ => Ok(None), |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | const VISIBLE_REFS: [&str; 3] = ["refs/heads/", "refs/tags/", "refs/pull/"]; |
| 221 | |
| 222 | fn visible_tips(repo: &gix::Repository) -> Result<Vec<gix::ObjectId>> { |
| 223 | let refs = repo.references().map_err(gerr)?; |
| 224 | let mut tips = Vec::new(); |
| 225 | for prefix in VISIBLE_REFS { |
| 226 | for reference in refs.prefixed(prefix).map_err(gerr)? { |
| 227 | let mut reference = reference.map_err(gerr)?; |
| 228 | if let Ok(tip) = reference.peel_to_id() { |
| 229 | let tip = tip.detach(); |
| 230 | if is_commit(repo, tip)? { |
| 231 | tips.push(tip); |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | Ok(tips) |
| 237 | } |
| 238 | |
| 239 | fn reachable(repo: &gix::Repository, id: gix::ObjectId) -> Result<bool> { |
| 240 | let tips = visible_tips(repo)?; |
| 241 | if tips.contains(&id) { |
| 242 | return Ok(true); |
| 243 | } |
| 244 | if tips.is_empty() { |
| 245 | return Ok(false); |
| 246 | } |
| 247 | for info in repo.rev_walk(tips).all().map_err(gerr)? { |
| 248 | if info.map_err(gerr)?.id == id { |
| 249 | return Ok(true); |
| 250 | } |
| 251 | } |
| 252 | Ok(false) |
| 253 | } |
| 254 | |
| 255 | pub fn reachable_commits(repo: &Path, oids: &[String]) -> Result<HashSet<String>> { |
| 256 | let mut wanted: HashSet<gix::ObjectId> = |
| 257 | oids.iter().filter_map(|oid| parse_oid(oid).ok()).collect(); |
| 258 | let repo = open(repo)?; |
| 259 | let mut found = HashSet::new(); |
| 260 | wanted.retain(|id| matches!(repo.try_find_header(*id), Ok(Some(_)))); |
| 261 | let tips = visible_tips(&repo)?; |
| 262 | if wanted.is_empty() || tips.is_empty() { |
| 263 | return Ok(found); |
| 264 | } |
| 265 | for info in repo.rev_walk(tips).all().map_err(gerr)? { |
| 266 | let id = info.map_err(gerr)?.id; |
| 267 | if wanted.remove(&id) { |
| 268 | found.insert(id.to_hex().to_string()); |
| 269 | if wanted.is_empty() { |
| 270 | break; |
| 271 | } |
| 272 | } |
| 273 | } |
| 274 | Ok(found) |
| 275 | } |
| 276 | |
| 277 | pub fn commit_reachable(repo: &Path, oid: &str) -> Result<bool> { |
| 278 | let repo = open(repo)?; |
| 279 | let id = parse_oid(oid)?; |
| 280 | Ok(is_commit(&repo, id)? && reachable(&repo, id)?) |
| 281 | } |
| 282 | |
| 283 | pub fn split_ref_and_path(repo: &Path, rest: &str) -> Result<Option<(String, String, String)>> { |
| 284 | let segments: Vec<&str> = rest.split('/').collect(); |
| 285 | let repo = open(repo)?; |
| 286 | |
| 287 | for count in (1..=segments.len()).rev() { |
| 288 | let candidate = segments[..count].join("/"); |
| 289 | if !valid_ref_name(&candidate) { |
| 290 | continue; |
| 291 | } |
| 292 | if let Some(id) = ref_commit(&repo, &candidate)? { |
| 293 | let path = segments[count..].join("/"); |
| 294 | if validate_repo_path(&path).is_err() { |
| 295 | return Ok(None); |
| 296 | } |
| 297 | return Ok(Some((candidate, id.to_hex().to_string(), path))); |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | let first = segments[0]; |
| 302 | if valid_hex_prefix(first) |
| 303 | && let Some(oid) = resolve_hex(&repo, first)? |
| 304 | { |
| 305 | let path = segments[1..].join("/"); |
| 306 | if validate_repo_path(&path).is_err() { |
| 307 | return Ok(None); |
| 308 | } |
| 309 | return Ok(Some((first.to_string(), oid, path))); |
| 310 | } |
| 311 | Ok(None) |
| 312 | } |
| 313 | |
| 314 | fn map_kind(kind: GixEntryKind) -> EntryKind { |
| 315 | match kind { |
| 316 | GixEntryKind::Tree => EntryKind::Tree, |
| 317 | GixEntryKind::Blob => EntryKind::Blob, |
| 318 | GixEntryKind::BlobExecutable => EntryKind::Executable, |
| 319 | GixEntryKind::Link => EntryKind::Symlink, |
| 320 | GixEntryKind::Commit => EntryKind::Submodule, |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | fn commit_root<'r>(repo: &'r gix::Repository, commit: &str) -> Result<Option<gix::Tree<'r>>> { |
| 325 | let id = parse_oid(commit)?; |
| 326 | if !is_commit(repo, id)? { |
| 327 | return Ok(None); |
| 328 | } |
| 329 | Ok(Some( |
| 330 | repo.find_commit(id).map_err(gerr)?.tree().map_err(gerr)?, |
| 331 | )) |
| 332 | } |
| 333 | |
| 334 | fn tree_at<'r>( |
| 335 | repo: &'r gix::Repository, |
| 336 | commit: &str, |
| 337 | path: &str, |
| 338 | ) -> Result<Option<gix::Tree<'r>>> { |
| 339 | let Some(mut root) = commit_root(repo, commit)? else { |
| 340 | return Ok(None); |
| 341 | }; |
| 342 | if path.is_empty() { |
| 343 | return Ok(Some(root)); |
| 344 | } |
| 345 | let Some(entry) = root.peel_to_entry_by_path(path).map_err(gerr)? else { |
| 346 | return Ok(None); |
| 347 | }; |
| 348 | if entry.mode().kind() != gix::objs::tree::EntryKind::Tree { |
| 349 | return Ok(None); |
| 350 | } |
| 351 | let tree = entry |
| 352 | .object() |
| 353 | .map_err(gerr)? |
| 354 | .try_into_tree() |
| 355 | .map_err(gerr)?; |
| 356 | Ok(Some(tree)) |
| 357 | } |
| 358 | |
| 359 | pub fn read_tree(repo: &Path, commit: &str, path: &str) -> Result<Option<Vec<TreeEntry>>> { |
| 360 | validate_repo_path(path)?; |
| 361 | let repo = open(repo)?; |
| 362 | let Some(tree) = tree_at(&repo, commit, path)? else { |
| 363 | return Ok(None); |
| 364 | }; |
| 365 | |
| 366 | let mut entries = Vec::new(); |
| 367 | for entry in tree.iter() { |
| 368 | let entry = entry.map_err(gerr)?; |
| 369 | let kind = map_kind(entry.mode().kind()); |
| 370 | let oid = entry.object_id(); |
| 371 | let size = match kind { |
| 372 | EntryKind::Tree | EntryKind::Submodule => None, |
| 373 | _ => Some(repo.find_header(oid).map_err(gerr)?.size()), |
| 374 | }; |
| 375 | entries.push(TreeEntry { |
| 376 | name: entry.filename().to_str_lossy().into_owned(), |
| 377 | kind, |
| 378 | oid: oid.to_hex().to_string(), |
| 379 | size, |
| 380 | }); |
| 381 | } |
| 382 | entries.sort_by(|a, b| { |
| 383 | (a.kind != EntryKind::Tree, a.name.as_bytes()) |
| 384 | .cmp(&(b.kind != EntryKind::Tree, b.name.as_bytes())) |
| 385 | }); |
| 386 | Ok(Some(entries)) |
| 387 | } |
| 388 | |
| 389 | pub fn read_blob( |
| 390 | repo: &Path, |
| 391 | commit: &str, |
| 392 | path: &str, |
| 393 | max_bytes: usize, |
| 394 | ) -> Result<Option<BlobData>> { |
| 395 | blob_at(repo, commit, path, max_bytes, false) |
| 396 | } |
| 397 | |
| 398 | fn blob_at( |
| 399 | repo: &Path, |
| 400 | commit: &str, |
| 401 | path: &str, |
| 402 | max_bytes: usize, |
| 403 | text_only: bool, |
| 404 | ) -> Result<Option<BlobData>> { |
| 405 | validate_repo_path(path)?; |
| 406 | if path.is_empty() { |
| 407 | return Ok(None); |
| 408 | } |
| 409 | let repo = open(repo)?; |
| 410 | let Some(mut root) = commit_root(&repo, commit)? else { |
| 411 | return Ok(None); |
| 412 | }; |
| 413 | let Some(entry) = root.peel_to_entry_by_path(path).map_err(gerr)? else { |
| 414 | return Ok(None); |
| 415 | }; |
| 416 | let kind = map_kind(entry.mode().kind()); |
| 417 | let oid = entry.object_id(); |
| 418 | match kind { |
| 419 | EntryKind::Tree => Ok(None), |
| 420 | EntryKind::Submodule => Ok(Some(BlobData { |
| 421 | oid: oid.to_hex().to_string(), |
| 422 | kind, |
| 423 | size: 0, |
| 424 | data: Vec::new(), |
| 425 | truncated: false, |
| 426 | is_binary: false, |
| 427 | })), |
| 428 | EntryKind::Blob | EntryKind::Executable | EntryKind::Symlink => { |
| 429 | if text_only && repo.find_header(oid).map_err(gerr)?.size() > max_bytes as u64 { |
| 430 | return Ok(None); |
| 431 | } |
| 432 | let mut blob = repo.find_blob(oid).map_err(gerr)?; |
| 433 | let mut data = blob.take_data(); |
| 434 | let size = data.len() as u64; |
| 435 | let is_binary = data[..data.len().min(BINARY_PROBE_BYTES)].contains(&0); |
| 436 | let truncated = data.len() > max_bytes; |
| 437 | if truncated { |
| 438 | data.truncate(max_bytes); |
| 439 | data.shrink_to_fit(); |
| 440 | } |
| 441 | Ok(Some(BlobData { |
| 442 | oid: oid.to_hex().to_string(), |
| 443 | kind, |
| 444 | size, |
| 445 | data, |
| 446 | truncated, |
| 447 | is_binary, |
| 448 | })) |
| 449 | } |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | pub fn read_text_blob( |
| 454 | repo: &Path, |
| 455 | commit: &str, |
| 456 | path: &str, |
| 457 | max_bytes: usize, |
| 458 | ) -> Result<Option<String>> { |
| 459 | let Some(blob) = blob_at(repo, commit, path, max_bytes, true)? else { |
| 460 | return Ok(None); |
| 461 | }; |
| 462 | if blob.kind == EntryKind::Submodule || blob.is_binary { |
| 463 | return Ok(None); |
| 464 | } |
| 465 | Ok(String::from_utf8(blob.data).ok()) |
| 466 | } |
| 467 | |
| 468 | fn lossy(bytes: &[u8]) -> String { |
| 469 | String::from_utf8_lossy(bytes).into_owned() |
| 470 | } |
| 471 | |
| 472 | pub fn read_commit(repo: &Path, oid: &str) -> Result<Option<CommitInfo>> { |
| 473 | let repo = open(repo)?; |
| 474 | let id = parse_oid(oid)?; |
| 475 | if !is_commit(&repo, id)? { |
| 476 | return Ok(None); |
| 477 | } |
| 478 | let commit = repo.find_commit(id).map_err(gerr)?; |
| 479 | let decoded = commit.decode().map_err(gerr)?; |
| 480 | let author = decoded.author().map_err(gerr)?; |
| 481 | let committer = decoded.committer().map_err(gerr)?; |
| 482 | let message = lossy(commit.message_raw_sloppy()); |
| 483 | let summary = message.lines().next().unwrap_or_default().to_string(); |
| 484 | Ok(Some(CommitInfo { |
| 485 | oid: id.to_hex().to_string(), |
| 486 | parents: decoded.parents().map(|p| p.to_hex().to_string()).collect(), |
| 487 | author_name: lossy(author.name), |
| 488 | author_email: lossy(author.email), |
| 489 | author_time: author.time().map_err(gerr)?.seconds, |
| 490 | committer_name: lossy(committer.name), |
| 491 | committer_email: lossy(committer.email), |
| 492 | committer_time: committer.time().map_err(gerr)?.seconds, |
| 493 | summary, |
| 494 | message, |
| 495 | })) |
| 496 | } |
| 497 | |
| 498 | pub fn validate_repo_path(path: &str) -> Result<()> { |
| 499 | if path.len() > MAX_PATH_BYTES { |
| 500 | return Err(Error::InvalidInput("path too long".into())); |
| 501 | } |
| 502 | if path.contains('\0') { |
| 503 | return Err(Error::InvalidInput("path contains NUL".into())); |
| 504 | } |
| 505 | if path.is_empty() { |
| 506 | return Ok(()); |
| 507 | } |
| 508 | for seg in path.split('/') { |
| 509 | if seg.is_empty() || seg == "." || seg == ".." { |
| 510 | return Err(Error::InvalidInput(format!( |
| 511 | "invalid path segment in {path:?}" |
| 512 | ))); |
| 513 | } |
| 514 | } |
| 515 | Ok(()) |
| 516 | } |