| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | | use super::{RepoError, StateCache}; |
| 6 | | use oxy_core::hash::{ChangeHash, KeyId}; |
| 7 | | use oxy_core::objects::{Change, NodeKind}; |
| 8 | | use oxy_core::repo::{BlameLine, FileDiff, Repo, SignatureStatus}; |
| 9 | | use oxy_core::state::{FileContent, Snapshot}; |
| 10 | | use oxy_core::tree::TreeConflict; |
| 11 | | use std::collections::{BTreeMap, BTreeSet, HashMap}; |
| 12 | |
|
| 13 | | type Result<T> = std::result::Result<T, RepoError>; |
| 14 | |
|
| 15 | 2× | fn fail(msg: impl Into<String>) -> RepoError { |
| 16 | 2× | RepoError::Oxy(oxy_core::repo::RepoError::Msg(msg.into())) |
| 17 | 2× | } |
| 18 | |
|
| 19 | |
|
| 20 | |
|
| 21 | | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 22 | | pub enum RefKind { |
| 23 | | Bookmark, |
| 24 | | Tag, |
| 25 | | Change, |
| 26 | | } |
| 27 | |
|
| 28 | |
|
| 29 | | #[derive(Clone, Debug)] |
| 30 | | pub struct RefTarget { |
| 31 | | |
| 32 | | pub label: String, |
| 33 | | pub kind: RefKind, |
| 34 | | pub heads: Vec<ChangeHash>, |
| 35 | | } |
| 36 | |
|
| 37 | |
|
| 38 | | pub const MAX_STATE_HEADS: usize = 32; |
| 39 | |
|
| 40 | | impl RefTarget { |
| 41 | | |
| 42 | | |
| 43 | 43× | pub fn short_label(&self) -> String { |
| 44 | 43× | match self.kind { |
| 45 | | RefKind::Change => { |
| 46 | 5× | let mut parts = self.label.split('+'); |
| 47 | 5× | let first: String = parts.next().unwrap_or("").chars().take(12).collect(); |
| 48 | 5× | match parts.count() { |
| 49 | 2× | 0 => first, |
| 50 | 3× | n => format!("{first} +{n}"), |
| 51 | | } |
| 52 | | } |
| 53 | 38× | _ => self.label.clone(), |
| 54 | | } |
| 55 | 43× | } |
| 56 | |
|
| 57 | | |
| 58 | | |
| 59 | 17× | pub fn permalink(&self) -> Option<String> { |
| 60 | 17× | state_spec(&self.heads) |
| 61 | 17× | } |
| 62 | | } |
| 63 | |
|
| 64 | |
|
| 65 | 32× | pub fn state_spec(heads: &[ChangeHash]) -> Option<String> { |
| 66 | 32× | if heads.is_empty() || heads.len() > MAX_STATE_HEADS { |
| 67 | 6× | return None; |
| 68 | 26× | } |
| 69 | 55× | let mut hex: Vec<String> = heads.iter().map(|h| h.to_hex()).collect(); |
| 70 | 26× | hex.sort(); |
| 71 | 26× | hex.dedup(); |
| 72 | 26× | Some(hex.join("+")) |
| 73 | 32× | } |
| 74 | |
|
| 75 | |
|
| 76 | |
|
| 77 | 223× | pub fn resolve(repo: &Repo, cache: &StateCache, spec: &str) -> Result<RefTarget> { |
| 78 | 223× | if spec.contains('+') { |
| 79 | 3× | let parts: Vec<&str> = spec.split('+').collect(); |
| 80 | 3× | if parts.len() > MAX_STATE_HEADS { |
| 81 | 0× | return Err(fail(format!("a state address has at most {MAX_STATE_HEADS} heads"))); |
| 82 | 3× | } |
| 83 | 3× | let mut heads = Vec::with_capacity(parts.len()); |
| 84 | 10× | for p in parts { |
| 85 | 10× | match ChangeHash::from_hex(p) { |
| 86 | 10× | Some(h) if p.len() == 64 && repo.store().has(&h) => heads.push(h), |
| 87 | 0× | _ => return Err(fail(format!("{p:?} is not a change of this repository"))), |
| 88 | | } |
| 89 | | } |
| 90 | 3× | heads.sort(); |
| 91 | 3× | heads.dedup(); |
| 92 | 3× | let label = state_spec(&heads).unwrap_or_default(); |
| 93 | 3× | return Ok(RefTarget { label, kind: RefKind::Change, heads }); |
| 94 | 220× | } |
| 95 | 220× | let view = repo.view()?; |
| 96 | 220× | if let Some(heads) = view.bookmarks.get(spec).map(|st| repo.store().get_state(st).map(|s| s.heads)).transpose()? { |
| 97 | 211× | return Ok(RefTarget { label: spec.into(), kind: RefKind::Bookmark, heads }); |
| 98 | 9× | } |
| 99 | 9× | if let Some(heads) = repo.tag_heads(spec)? { |
| 100 | 2× | return Ok(RefTarget { label: spec.into(), kind: RefKind::Tag, heads }); |
| 101 | 7× | } |
| 102 | 7× | let hash = resolve_change(repo, cache, spec)?; |
| 103 | 5× | Ok(RefTarget { label: hash.to_hex(), kind: RefKind::Change, heads: vec![hash] }) |
| 104 | 223× | } |
| 105 | |
|
| 106 | |
|
| 107 | |
|
| 108 | 1× | fn stand_in(repo: &Repo) -> Result<Option<String>> { |
| 109 | 1× | let view = repo.view()?; |
| 110 | 1× | let names: Vec<&String> = view.bookmarks.keys().collect(); |
| 111 | 1× | Ok(["main", "master"] |
| 112 | 1× | .iter() |
| 113 | 2× | .find(|n| names.iter().any(|b| b == *n)) |
| 114 | 1× | .map(|n| n.to_string()) |
| 115 | 1× | .or_else(|| names.iter().min().map(|b| b.to_string()))) |
| 116 | 1× | } |
| 117 | |
|
| 118 | |
|
| 119 | |
|
| 120 | 25× | pub fn resolve_change(repo: &Repo, cache: &StateCache, spec: &str) -> Result<ChangeHash> { |
| 121 | 25× | let spec = spec.trim_start_matches('#'); |
| 122 | 1364× | if spec.len() < 4 || !spec.chars().all(|c| c.is_ascii_hexdigit()) { |
| 123 | 2× | return Err(fail(format!("{spec:?} is not a bookmark, tag or change of this repository"))); |
| 124 | 23× | } |
| 125 | 23× | if let Some(h) = ChangeHash::from_hex(spec) { |
| 126 | 21× | if repo.store().has(&h) { |
| 127 | 21× | return Ok(h); |
| 128 | 0× | } |
| 129 | 2× | } |
| 130 | 2× | let heads = all_heads(repo)?; |
| 131 | 2× | let loaded = cache.load(repo, &heads)?; |
| 132 | 4× | let matches: Vec<ChangeHash> = loaded.state.changes().map(|(h, _)| *h).filter(|h| h.starts_with_hex(spec)).collect(); |
| 133 | 2× | match matches.len() { |
| 134 | 2× | 1 => Ok(matches[0]), |
| 135 | 0× | 0 => Err(fail(format!("no change matches {spec:?}"))), |
| 136 | 0× | _ => Err(fail(format!("{spec:?} is ambiguous"))), |
| 137 | | } |
| 138 | 25× | } |
| 139 | |
|
| 140 | |
|
| 141 | 25× | pub fn all_heads(repo: &Repo) -> Result<Vec<ChangeHash>> { |
| 142 | 25× | let mut set = BTreeSet::new(); |
| 143 | 45× | for b in repo.bookmarks()? { |
| 144 | 45× | set.extend(b.heads); |
| 145 | 45× | } |
| 146 | 25× | Ok(set.into_iter().collect()) |
| 147 | 25× | } |
| 148 | |
|
| 149 | |
|
| 150 | |
|
| 151 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 152 | | pub struct AuthorView { |
| 153 | | pub name: String, |
| 154 | | pub email: String, |
| 155 | | pub key: String, |
| 156 | | |
| 157 | | pub unknown: bool, |
| 158 | | |
| 159 | | pub account: Option<String>, |
| 160 | | } |
| 161 | |
|
| 162 | 479× | pub fn author(repo: &Repo, key: &KeyId, message: &str) -> AuthorView { |
| 163 | 479× | if key.is_zero() { |
| 164 | | |
| 165 | 152× | let line = message.lines().rev().find_map(|l| l.strip_prefix("Git-Author: ")).unwrap_or("unknown"); |
| 166 | 138× | let (name, email) = match line.split_once('<') { |
| 167 | 0× | Some((n, e)) => (n.trim().to_string(), e.trim_end_matches('>').trim().to_string()), |
| 168 | 138× | None => (line.trim().to_string(), String::new()), |
| 169 | | }; |
| 170 | 138× | return AuthorView { name, email, key: String::new(), unknown: true, account: None }; |
| 171 | 341× | } |
| 172 | 341× | match repo.store().get_identity(key) { |
| 173 | 341× | Ok(id) => AuthorView { name: id.name, email: id.email, key: key.to_hex(), unknown: false, account: None }, |
| 174 | 0× | Err(_) => AuthorView { name: key.short(12), email: String::new(), key: key.to_hex(), unknown: true, account: None }, |
| 175 | | } |
| 176 | 479× | } |
| 177 | |
|
| 178 | |
|
| 179 | |
|
| 180 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 181 | | pub enum SigView { |
| 182 | | Unsigned, |
| 183 | | Valid { key: String, name: String, sealed: bool, revoked: bool }, |
| 184 | | Invalid(String), |
| 185 | | } |
| 186 | |
|
| 187 | | impl SigView { |
| 188 | 75× | pub fn glyph(&self) -> &'static str { |
| 189 | 75× | match self { |
| 190 | 11× | SigView::Unsigned => "○", |
| 191 | 0× | SigView::Valid { revoked: true, .. } => "⊘", |
| 192 | 12× | SigView::Valid { sealed: true, .. } => "◈", |
| 193 | 52× | SigView::Valid { .. } => "✔", |
| 194 | 0× | SigView::Invalid(_) => "✘", |
| 195 | | } |
| 196 | 75× | } |
| 197 | |
|
| 198 | 75× | pub fn class(&self) -> &'static str { |
| 199 | 75× | match self { |
| 200 | 11× | SigView::Unsigned => "sig-unsigned", |
| 201 | 0× | SigView::Valid { revoked: true, .. } => "sig-revoked", |
| 202 | 64× | SigView::Valid { .. } => "sig-valid", |
| 203 | 0× | SigView::Invalid(_) => "sig-invalid", |
| 204 | | } |
| 205 | 75× | } |
| 206 | |
|
| 207 | 89× | pub fn title(&self) -> String { |
| 208 | 89× | match self { |
| 209 | 14× | SigView::Unsigned => "unsigned".into(), |
| 210 | 15× | SigView::Valid { name, sealed: true, revoked: false, .. } => format!("sealed by {name}"), |
| 211 | 0× | SigView::Valid { name, revoked: true, .. } => format!("signed by {name}, key revoked"), |
| 212 | 60× | SigView::Valid { name, .. } => format!("signed by {name}"), |
| 213 | 0× | SigView::Invalid(why) => format!("INVALID: {why}"), |
| 214 | | } |
| 215 | 89× | } |
| 216 | | } |
| 217 | |
|
| 218 | |
|
| 219 | |
|
| 220 | 426× | pub fn signature(repo: &Repo, hash: &ChangeHash) -> SigView { |
| 221 | 426× | match repo.authenticate_change(hash) { |
| 222 | 119× | Ok(SignatureStatus::Unsigned) => SigView::Unsigned, |
| 223 | 307× | Ok(SignatureStatus::Valid { key, name, sealed, revoked, .. }) => SigView::Valid { key: key.to_hex(), name, sealed, revoked }, |
| 224 | 0× | Ok(SignatureStatus::Invalid(why)) => SigView::Invalid(why), |
| 225 | 0× | Err(e) => SigView::Invalid(e.to_string()), |
| 226 | | } |
| 227 | 426× | } |
| 228 | |
|
| 229 | |
|
| 230 | |
|
| 231 | |
|
| 232 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 233 | | pub struct ViaView { |
| 234 | | pub name: String, |
| 235 | | pub email: String, |
| 236 | | pub key: String, |
| 237 | | pub short: String, |
| 238 | | |
| 239 | | pub scope: String, |
| 240 | | pub expires_ms: Option<u64>, |
| 241 | | |
| 242 | | |
| 243 | | pub revoked: bool, |
| 244 | | |
| 245 | | |
| 246 | | |
| 247 | | pub certified: bool, |
| 248 | | } |
| 249 | |
|
| 250 | | impl ViaView { |
| 251 | | |
| 252 | 5× | pub fn delegation(&self) -> String { |
| 253 | 5× | if self.certified { |
| 254 | 1× | return format!("keyless, under your grant for {}", self.scope); |
| 255 | 4× | } |
| 256 | 4× | if self.revoked { |
| 257 | 0× | return "delegation revoked".into(); |
| 258 | 4× | } |
| 259 | 4× | match self.expires_ms { |
| 260 | 0× | Some(e) => format!("delegate for {}, until {}", self.scope, when_utc(e)), |
| 261 | 4× | None => format!("delegate for {}", self.scope), |
| 262 | | } |
| 263 | 5× | } |
| 264 | |
|
| 265 | | |
| 266 | 30× | pub fn title(&self) -> String { |
| 267 | 30× | let until = match self.expires_ms { |
| 268 | 1× | Some(e) => format!(", until {}", when_utc(e)), |
| 269 | 29× | None => String::new(), |
| 270 | | }; |
| 271 | 30× | if self.certified { |
| 272 | 1× | format!( |
| 273 | | "sealed by {} with a short-lived key the hub certified under the author's grant ({}), key {}", |
| 274 | | self.name, self.scope, self.short |
| 275 | | ) |
| 276 | 29× | } else if self.revoked { |
| 277 | 0× | format!("signed by {} as a delegate of the author; that delegation has since been revoked", self.name) |
| 278 | | } else { |
| 279 | 29× | format!("signed by {} as a delegate of the author ({}{until}), key {}", self.name, self.scope, self.short) |
| 280 | | } |
| 281 | 30× | } |
| 282 | | } |
| 283 | |
|
| 284 | |
|
| 285 | 1× | fn when_utc(ms: u64) -> String { |
| 286 | 1× | time::OffsetDateTime::from_unix_timestamp_nanos(ms as i128 * 1_000_000) |
| 287 | 1× | .ok() |
| 288 | 1× | .and_then(|t| t.format(&time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]Z")).ok()) |
| 289 | 1× | .unwrap_or_else(|| ms.to_string()) |
| 290 | 1× | } |
| 291 | |
|
| 292 | |
|
| 293 | 419× | pub fn via(repo: &Repo, author: &KeyId, sig: &SigView) -> Option<ViaView> { |
| 294 | 419× | let SigView::Valid { key, name, revoked, .. } = sig else { return None }; |
| 295 | 301× | if author.is_zero() || *key == author.to_hex() { |
| 296 | 174× | return None; |
| 297 | 127× | } |
| 298 | 127× | let signer = KeyId::from_hex(key)?; |
| 299 | 127× | let email = repo.store().get_identity(&signer).map(|i| i.email).unwrap_or_default(); |
| 300 | | |
| 301 | | |
| 302 | 127× | if let Some(cert) = certificate(repo, &signer) { |
| 303 | 3× | return Some(ViaView { |
| 304 | 3× | name: name.clone(), |
| 305 | 3× | email, |
| 306 | 3× | key: key.clone(), |
| 307 | 3× | short: signer.short(12), |
| 308 | 3× | scope: cert.scope.to_string(), |
| 309 | 3× | expires_ms: Some(cert.expires), |
| 310 | 3× | revoked: *revoked, |
| 311 | 3× | certified: true, |
| 312 | 3× | }); |
| 313 | 124× | } |
| 314 | 124× | let entry = repo.store().get_identity(author).ok().and_then(|a| a.delegate(&signer).copied()); |
| 315 | | Some(ViaView { |
| 316 | 124× | name: name.clone(), |
| 317 | 124× | email, |
| 318 | 124× | key: key.clone(), |
| 319 | 124× | short: signer.short(12), |
| 320 | 124× | scope: entry.map(|d| d.scope.to_string()).unwrap_or_else(|| "changes".into()), |
| 321 | 124× | expires_ms: entry.and_then(|d| d.expires), |
| 322 | 124× | revoked: *revoked || entry.is_none(), |
| 323 | | certified: false, |
| 324 | | }) |
| 325 | 419× | } |
| 326 | |
|
| 327 | |
|
| 328 | 130× | fn certificate(repo: &Repo, key: &KeyId) -> Option<oxy_core::cert::Certificate> { |
| 329 | 130× | let r = repo.store().certificate_of(key).ok()??; |
| 330 | 4× | repo.store().get_certificate(&r).ok().map(|c| c.cert) |
| 331 | 130× | } |
| 332 | |
|
| 333 | |
|
| 334 | |
|
| 335 | 27× | fn sealer(repo: &Repo, hash: &ChangeHash, author: &KeyId) -> Option<KeyId> { |
| 336 | 27× | let seals = repo.store().seals_for(hash).ok()?; |
| 337 | 27× | seals.iter().find_map(|a| repo.store().signatures(a).ok()?.into_iter().map(|s| s.key).find(|k| k != author)) |
| 338 | 27× | } |
| 339 | |
|
| 340 | |
|
| 341 | | #[derive(Clone, Debug)] |
| 342 | | pub struct ChangeView { |
| 343 | | pub hash: String, |
| 344 | | pub short: String, |
| 345 | | pub title: String, |
| 346 | | pub body: String, |
| 347 | | pub author: AuthorView, |
| 348 | | pub when_ms: u64, |
| 349 | | pub deps: Vec<String>, |
| 350 | | pub head: bool, |
| 351 | | pub resolution: bool, |
| 352 | | pub signature: SigView, |
| 353 | | |
| 354 | | pub via: Option<ViaView>, |
| 355 | | |
| 356 | | pub labels: Vec<Label>, |
| 357 | | } |
| 358 | |
|
| 359 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 360 | | pub struct Label { |
| 361 | | pub name: String, |
| 362 | | pub kind: RefKind, |
| 363 | | } |
| 364 | |
|
| 365 | 419× | pub fn split_message(message: &str) -> (String, String) { |
| 366 | 419× | let mut lines = message.lines(); |
| 367 | 419× | let title = lines.next().unwrap_or("").trim().to_string(); |
| 368 | 419× | let body = lines.collect::<Vec<_>>().join("\n").trim().to_string(); |
| 369 | 419× | (title, body) |
| 370 | 419× | } |
| 371 | |
|
| 372 | |
|
| 373 | 373× | pub fn head_labels(repo: &Repo) -> Result<HashMap<ChangeHash, Vec<Label>>> { |
| 374 | 373× | let mut out: HashMap<ChangeHash, Vec<Label>> = HashMap::new(); |
| 375 | 977× | for b in repo.bookmarks()? { |
| 376 | 2313× | for h in b.heads { |
| 377 | 2313× | out.entry(h).or_default().push(Label { name: b.name.clone(), kind: RefKind::Bookmark }); |
| 378 | 2313× | } |
| 379 | | } |
| 380 | 373× | for t in repo.tags()? { |
| 381 | 32× | for h in t.heads { |
| 382 | 32× | out.entry(h).or_default().push(Label { name: t.name.clone(), kind: RefKind::Tag }); |
| 383 | 32× | } |
| 384 | | } |
| 385 | 373× | Ok(out) |
| 386 | 373× | } |
| 387 | |
|
| 388 | 235× | pub fn change_view_pub( |
| 389 | 235× | repo: &Repo, |
| 390 | 235× | hash: &ChangeHash, |
| 391 | 235× | meta: &oxy_core::state::ChangeMeta, |
| 392 | 235× | head: bool, |
| 393 | 235× | labels: &HashMap<ChangeHash, Vec<Label>>, |
| 394 | 235× | ) -> ChangeView { |
| 395 | 235× | change_view(repo, hash, meta, head, labels) |
| 396 | 235× | } |
| 397 | |
|
| 398 | 419× | fn change_view( |
| 399 | 419× | repo: &Repo, |
| 400 | 419× | hash: &ChangeHash, |
| 401 | 419× | meta: &oxy_core::state::ChangeMeta, |
| 402 | 419× | head: bool, |
| 403 | 419× | labels: &HashMap<ChangeHash, Vec<Label>>, |
| 404 | 419× | ) -> ChangeView { |
| 405 | 419× | let (title, body) = split_message(&meta.message); |
| 406 | 419× | let signature = signature(repo, hash); |
| 407 | 419× | let via = via(repo, &meta.author, &signature); |
| 408 | | ChangeView { |
| 409 | 419× | hash: hash.to_hex(), |
| 410 | 419× | short: hash.short(12), |
| 411 | 419× | title, |
| 412 | 419× | body, |
| 413 | 419× | author: author(repo, &meta.author, &meta.message), |
| 414 | 419× | when_ms: meta.hlc.wall_ms, |
| 415 | 419× | deps: meta.deps.iter().map(|d| d.to_hex()).collect(), |
| 416 | 419× | head, |
| 417 | 419× | resolution: meta.kind == oxy_core::objects::ChangeKind::Resolution, |
| 418 | 419× | signature, |
| 419 | 419× | via, |
| 420 | 419× | labels: labels.get(hash).cloned().unwrap_or_default(), |
| 421 | | } |
| 422 | 419× | } |
| 423 | |
|
| 424 | |
|
| 425 | |
|
| 426 | | #[derive(Clone, Debug)] |
| 427 | | pub struct History { |
| 428 | | pub target: RefTarget, |
| 429 | | pub entries: Vec<ChangeView>, |
| 430 | | pub total: usize, |
| 431 | | pub offset: usize, |
| 432 | | pub has_more: bool, |
| 433 | | pub path: Option<String>, |
| 434 | | } |
| 435 | |
|
| 436 | |
|
| 437 | 22× | pub fn history(repo: &Repo, cache: &StateCache, target: RefTarget, path: Option<&str>, offset: usize, limit: usize) -> Result<History> { |
| 438 | 22× | let loaded = cache.load(repo, &target.heads)?; |
| 439 | 22× | let head_set: BTreeSet<ChangeHash> = loaded.state.heads().into_iter().collect(); |
| 440 | 22× | let mut entries: Vec<(ChangeHash, oxy_core::state::ChangeMeta)> = match path { |
| 441 | 7× | Some(p) => { |
| 442 | 7× | let Some(node) = loaded.snapshot.files.get(p).map(|f| f.node) else { return Err(fail(format!("{p} is not in that state"))) }; |
| 443 | 7× | loaded |
| 444 | 7× | .state |
| 445 | 7× | .changes() |
| 446 | 14× | .filter(|(h, _)| { |
| 447 | | |
| 448 | 14× | repo.store() |
| 449 | 14× | .get_change_lazy(h) |
| 450 | 14× | .map(|(c, _)| c.tree_ops.iter().any(|o| o.node() == node) || c.edits.iter().any(|x| x.node() == node)) |
| 451 | 14× | .unwrap_or(false) |
| 452 | 14× | }) |
| 453 | 8× | .map(|(h, m)| (*h, m.clone())) |
| 454 | 7× | .collect() |
| 455 | | } |
| 456 | 53× | None => loaded.state.changes().map(|(h, m)| (*h, m.clone())).collect(), |
| 457 | | }; |
| 458 | 106× | entries.sort_by(|a, b| b.1.hlc.cmp(&a.1.hlc).then(b.0.cmp(&a.0))); |
| 459 | 22× | let total = entries.len(); |
| 460 | 22× | let labels = head_labels(repo)?; |
| 461 | 22× | let window: Vec<ChangeView> = |
| 462 | 61× | entries.iter().skip(offset).take(limit).map(|(h, m)| change_view(repo, h, m, head_set.contains(h), &labels)).collect(); |
| 463 | 22× | Ok(History { target, entries: window, total, offset, has_more: offset + limit < total, path: path.map(String::from) }) |
| 464 | 22× | } |
| 465 | |
|
| 466 | |
|
| 467 | |
|
| 468 | |
|
| 469 | |
|
| 470 | 4× | pub fn history_revset(repo: &Repo, cache: &StateCache, target: RefTarget, revset: &str, offset: usize, limit: usize) -> Result<History> { |
| 471 | 4× | let loaded = cache.load(repo, &target.heads)?; |
| 472 | 4× | let head_set: BTreeSet<ChangeHash> = loaded.state.heads().into_iter().collect(); |
| 473 | 4× | let selected = repo.revset_with_budget(revset, std::time::Duration::from_secs(2))?; |
| 474 | 2× | let total = selected.hashes.len(); |
| 475 | 2× | let labels = head_labels(repo)?; |
| 476 | 2× | let window: Vec<ChangeView> = selected |
| 477 | 2× | .hashes |
| 478 | 2× | .iter() |
| 479 | 2× | .skip(offset) |
| 480 | 2× | .take(limit) |
| 481 | 2× | .filter_map(|h| selected.metas.get(h).map(|m| change_view(repo, h, m, head_set.contains(h), &labels))) |
| 482 | 2× | .collect(); |
| 483 | 2× | Ok(History { target, entries: window, total, offset, has_more: offset + limit < total, path: None }) |
| 484 | 4× | } |
| 485 | |
|
| 486 | |
|
| 487 | |
|
| 488 | | #[derive(Clone, Debug)] |
| 489 | | pub struct ChangeDetail { |
| 490 | | pub view: ChangeView, |
| 491 | | pub dependents: Vec<ChangeView>, |
| 492 | | pub deps: Vec<ChangeView>, |
| 493 | | pub files: Vec<FileDiff>, |
| 494 | | |
| 495 | | pub bases: BTreeMap<String, Vec<u8>>, |
| 496 | | pub in_bookmarks: Vec<String>, |
| 497 | | pub in_tags: Vec<String>, |
| 498 | | pub atoms: usize, |
| 499 | | pub tree_ops: usize, |
| 500 | | } |
| 501 | |
|
| 502 | 19× | pub fn change(repo: &Repo, cache: &StateCache, hash: &ChangeHash) -> Result<ChangeDetail> { |
| 503 | 19× | let c: Change = repo.store().get_change(hash)?; |
| 504 | 19× | let labels = head_labels(repo)?; |
| 505 | 19× | let heads = all_heads(repo)?; |
| 506 | 19× | let loaded = cache.load(repo, &heads)?; |
| 507 | 19× | let state = &loaded.state; |
| 508 | 19× | let is_head = state.heads().contains(hash); |
| 509 | 19× | let meta = oxy_core::state::ChangeMeta::of(&c); |
| 510 | 19× | let view = change_view(repo, hash, &meta, is_head, &labels); |
| 511 | 19× | let deps = c.deps.iter().filter_map(|d| state.get(d).map(|m| change_view(repo, d, m, state.heads().contains(d), &labels))).collect(); |
| 512 | 19× | let mut dependents: Vec<ChangeView> = state |
| 513 | 19× | .changes() |
| 514 | 63× | .filter(|(_, m)| m.deps.contains(hash)) |
| 515 | 19× | .map(|(h, m)| change_view(repo, h, m, state.heads().contains(h), &labels)) |
| 516 | 19× | .collect(); |
| 517 | 19× | dependents.sort_by_key(|c| std::cmp::Reverse(c.when_ms)); |
| 518 | 19× | let base = cache.load(repo, &c.deps)?; |
| 519 | 19× | let files = crate::render::diff::change_files(&c, &base.state, &base.snapshot); |
| 520 | 19× | let base_snapshot = &base.snapshot; |
| 521 | 19× | let mut bases = BTreeMap::new(); |
| 522 | 20× | for f in &files { |
| 523 | 20× | let old = f.from.as_deref().unwrap_or(&f.path); |
| 524 | 20× | if let Some(FileContent::Text { bytes, .. }) = base_snapshot.files.get(old).map(|s| &s.content) { |
| 525 | 9× | bases.insert(f.path.clone(), bytes.clone()); |
| 526 | 11× | } |
| 527 | | } |
| 528 | 19× | let mut in_bookmarks = Vec::new(); |
| 529 | 36× | for b in repo.bookmarks()? { |
| 530 | 36× | if cache.summary(repo, &b.heads)?.changes.contains(hash) { |
| 531 | 19× | in_bookmarks.push(b.name); |
| 532 | 19× | } |
| 533 | | } |
| 534 | 19× | let mut in_tags = Vec::new(); |
| 535 | 19× | for t in repo.tags()? { |
| 536 | 2× | if cache.summary(repo, &t.heads)?.changes.contains(hash) { |
| 537 | 2× | in_tags.push(t.name); |
| 538 | 2× | } |
| 539 | | } |
| 540 | 19× | Ok(ChangeDetail { view, dependents, deps, files, bases, in_bookmarks, in_tags, atoms: c.edits.len(), tree_ops: c.tree_ops.len() }) |
| 541 | 19× | } |
| 542 | |
|
| 543 | |
|
| 544 | |
|
| 545 | | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 546 | | pub enum EntryKind { |
| 547 | | Dir, |
| 548 | | File, |
| 549 | | Symlink, |
| 550 | | Subrepo, |
| 551 | | } |
| 552 | |
|
| 553 | | #[derive(Clone, Debug)] |
| 554 | | pub struct Entry { |
| 555 | | pub name: String, |
| 556 | | pub path: String, |
| 557 | | pub kind: EntryKind, |
| 558 | | pub exec: bool, |
| 559 | | pub size: Option<u64>, |
| 560 | | pub conflicted: bool, |
| 561 | | } |
| 562 | |
|
| 563 | | #[derive(Clone, Debug)] |
| 564 | | pub struct Tree { |
| 565 | | pub target: RefTarget, |
| 566 | | pub path: String, |
| 567 | | pub entries: Vec<Entry>, |
| 568 | | |
| 569 | | pub crumbs: Vec<(String, String)>, |
| 570 | | pub readme: Option<Readme>, |
| 571 | | } |
| 572 | |
|
| 573 | | #[derive(Clone, Debug)] |
| 574 | | pub struct Readme { |
| 575 | | pub path: String, |
| 576 | | pub text: String, |
| 577 | | } |
| 578 | |
|
| 579 | 88× | pub fn crumbs(path: &str) -> Vec<(String, String)> { |
| 580 | 88× | let mut out = Vec::new(); |
| 581 | 88× | let mut so_far = String::new(); |
| 582 | 94× | for part in path.split('/').filter(|p| !p.is_empty()) { |
| 583 | 40× | if !so_far.is_empty() { |
| 584 | 6× | so_far.push('/'); |
| 585 | 34× | } |
| 586 | 40× | so_far.push_str(part); |
| 587 | 40× | out.push((part.to_string(), so_far.clone())); |
| 588 | | } |
| 589 | 88× | out |
| 590 | 88× | } |
| 591 | |
|
| 592 | 64× | fn entry_of(path: &str, name: &str, f: &oxy_core::state::FileState) -> Entry { |
| 593 | 64× | let kind = match f.kind { |
| 594 | 20× | NodeKind::Dir => EntryKind::Dir, |
| 595 | 44× | NodeKind::File => EntryKind::File, |
| 596 | 0× | NodeKind::Symlink => EntryKind::Symlink, |
| 597 | 0× | NodeKind::Subrepo => EntryKind::Subrepo, |
| 598 | | }; |
| 599 | 64× | let size = match &f.content { |
| 600 | 44× | FileContent::Text { bytes, .. } => Some(bytes.len() as u64), |
| 601 | 20× | _ => None, |
| 602 | | }; |
| 603 | 64× | Entry { name: name.to_string(), path: path.to_string(), kind, exec: f.mode.exec, size, conflicted: f.is_conflicted() } |
| 604 | 64× | } |
| 605 | |
|
| 606 | |
|
| 607 | 4× | pub fn tree(repo: &Repo, cache: &StateCache, target: RefTarget, dir: &str) -> Result<Tree> { |
| 608 | 4× | let loaded = cache.load(repo, &target.heads)?; |
| 609 | 4× | tree_of(repo, target, &loaded.snapshot, dir) |
| 610 | 4× | } |
| 611 | |
|
| 612 | 57× | pub fn tree_of(_repo: &Repo, target: RefTarget, snapshot: &Snapshot, dir: &str) -> Result<Tree> { |
| 613 | 57× | let dir = dir.trim_matches('/'); |
| 614 | 57× | if !dir.is_empty() { |
| 615 | 3× | match snapshot.files.get(dir) { |
| 616 | 2× | Some(f) if f.kind == NodeKind::Dir => {} |
| 617 | 1× | _ => return Err(RepoError::NotFound), |
| 618 | | } |
| 619 | 54× | } |
| 620 | 56× | let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") }; |
| 621 | 56× | let mut entries: Vec<Entry> = snapshot |
| 622 | 56× | .files |
| 623 | 56× | .iter() |
| 624 | 92× | .filter(|(p, _)| p.starts_with(&prefix) && !p[prefix.len()..].contains('/')) |
| 625 | 64× | .map(|(p, f)| entry_of(p, &p[prefix.len()..], f)) |
| 626 | 56× | .collect(); |
| 627 | 56× | entries.sort_by(|a, b| { |
| 628 | 40× | (a.kind != EntryKind::Dir).cmp(&(b.kind != EntryKind::Dir)).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())) |
| 629 | 40× | }); |
| 630 | 56× | let readme = entries |
| 631 | 56× | .iter() |
| 632 | 61× | .find(|e| { |
| 633 | 61× | e.kind == EntryKind::File && matches!(e.name.to_lowercase().as_str(), "readme.md" | "readme" | "readme.txt" | "readme.markdown") |
| 634 | 61× | }) |
| 635 | 56× | .and_then(|e| match &snapshot.files.get(&e.path)?.content { |
| 636 | 13× | FileContent::Text { bytes, .. } => Some(Readme { path: e.path.clone(), text: String::from_utf8_lossy(bytes).into_owned() }), |
| 637 | 0× | _ => None, |
| 638 | 13× | }); |
| 639 | 56× | Ok(Tree { target, path: dir.to_string(), entries, crumbs: crumbs(dir), readme }) |
| 640 | 57× | } |
| 641 | |
|
| 642 | |
|
| 643 | |
|
| 644 | | #[derive(Clone, Debug)] |
| 645 | | pub enum FileBody { |
| 646 | | Text(String), |
| 647 | | Binary, |
| 648 | | TooLarge, |
| 649 | | } |
| 650 | |
|
| 651 | |
|
| 652 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 653 | | pub struct SideEntry { |
| 654 | | pub name: String, |
| 655 | | pub path: String, |
| 656 | | pub depth: usize, |
| 657 | | pub dir: bool, |
| 658 | | |
| 659 | | pub on_path: bool, |
| 660 | | |
| 661 | | pub more: bool, |
| 662 | | } |
| 663 | |
|
| 664 | |
|
| 665 | | const SIDEBAR_PER_DIR: usize = 200; |
| 666 | |
|
| 667 | |
|
| 668 | |
|
| 669 | 32× | pub fn sidebar(snapshot: &Snapshot, path: &str) -> Vec<SideEntry> { |
| 670 | 71× | sidebar_in(&snapshot.files, |f| f.kind == NodeKind::Dir, path) |
| 671 | 32× | } |
| 672 | |
|
| 673 | |
|
| 674 | 34× | pub fn sidebar_in<V>(files: &BTreeMap<String, V>, is_dir: impl Fn(&V) -> bool + Copy, path: &str) -> Vec<SideEntry> { |
| 675 | 34× | let mut out = Vec::new(); |
| 676 | 34× | sidebar_dir(files, is_dir, "", path, 0, &mut out); |
| 677 | 34× | out |
| 678 | 34× | } |
| 679 | |
|
| 680 | 43× | fn sidebar_dir<V>( |
| 681 | 43× | files: &BTreeMap<String, V>, |
| 682 | 43× | is_dir: impl Fn(&V) -> bool + Copy, |
| 683 | 43× | dir: &str, |
| 684 | 43× | target: &str, |
| 685 | 43× | depth: usize, |
| 686 | 43× | out: &mut Vec<SideEntry>, |
| 687 | 43× | ) { |
| 688 | 43× | let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") }; |
| 689 | 43× | let mut children: Vec<(&str, bool)> = files |
| 690 | 43× | .range(prefix.clone()..) |
| 691 | 615× | .take_while(|(p, _)| p.starts_with(&prefix)) |
| 692 | 614× | .filter(|(p, _)| !p[prefix.len()..].contains('/')) |
| 693 | 330× | .map(|(p, f)| (p.as_str(), is_dir(f))) |
| 694 | 43× | .collect(); |
| 695 | 295× | children.sort_by(|a, b| (!a.1).cmp(&!b.1).then_with(|| a.0.to_lowercase().cmp(&b.0.to_lowercase()))); |
| 696 | 43× | let total = children.len(); |
| 697 | 330× | for (i, (p, dir_entry)) in children.into_iter().enumerate() { |
| 698 | 330× | let on_path = target == p || target.starts_with(&format!("{p}/")); |
| 699 | | |
| 700 | 330× | if i >= SIDEBAR_PER_DIR && !on_path { |
| 701 | 49× | continue; |
| 702 | 281× | } |
| 703 | 281× | out.push(SideEntry { name: p[prefix.len()..].to_string(), path: p.to_string(), depth, dir: dir_entry, on_path, more: false }); |
| 704 | 281× | if dir_entry && on_path && p != target { |
| 705 | 9× | sidebar_dir(files, is_dir, p, target, depth + 1, out); |
| 706 | 272× | } |
| 707 | | } |
| 708 | 43× | if total > SIDEBAR_PER_DIR { |
| 709 | 1× | out.push(SideEntry { |
| 710 | 1× | name: format!("{} more", total - SIDEBAR_PER_DIR), |
| 711 | 1× | path: dir.to_string(), |
| 712 | 1× | depth, |
| 713 | 1× | dir: true, |
| 714 | 1× | on_path: false, |
| 715 | 1× | more: true, |
| 716 | 1× | }); |
| 717 | 42× | } |
| 718 | 43× | } |
| 719 | |
|
| 720 | | #[derive(Clone, Debug)] |
| 721 | | pub struct FileView { |
| 722 | | pub target: RefTarget, |
| 723 | | pub path: String, |
| 724 | | pub name: String, |
| 725 | | pub crumbs: Vec<(String, String)>, |
| 726 | | pub kind: EntryKind, |
| 727 | | pub exec: bool, |
| 728 | | pub size: u64, |
| 729 | | pub body: FileBody, |
| 730 | | pub conflicted: bool, |
| 731 | | |
| 732 | | pub bytes: Vec<u8>, |
| 733 | | pub last_change: Option<ChangeView>, |
| 734 | | pub sidebar: Vec<SideEntry>, |
| 735 | | } |
| 736 | |
|
| 737 | 34× | pub fn file(repo: &Repo, cache: &StateCache, target: RefTarget, path: &str, render_limit: u64) -> Result<FileView> { |
| 738 | 34× | let loaded = cache.load(repo, &target.heads)?; |
| 739 | 34× | let snapshot = &loaded.snapshot; |
| 740 | 34× | let path = path.trim_matches('/'); |
| 741 | 34× | let Some(f) = snapshot.files.get(path) else { return Err(RepoError::NotFound) }; |
| 742 | 32× | let (kind, bytes) = match (&f.kind, &f.content) { |
| 743 | 0× | (NodeKind::Dir, _) => return Err(RepoError::NotFound), |
| 744 | 0× | (NodeKind::Symlink, FileContent::Text { bytes, .. }) => (EntryKind::Symlink, bytes.clone()), |
| 745 | 0× | (NodeKind::Subrepo, FileContent::Text { bytes, .. }) => (EntryKind::Subrepo, bytes.clone()), |
| 746 | 29× | (_, FileContent::Text { bytes, .. }) => (EntryKind::File, bytes.clone()), |
| 747 | 3× | (_, FileContent::Opaque { blobs }) => { |
| 748 | 3× | let bytes = match blobs.first() { |
| 749 | 3× | Some(b) => repo.read_blob(b)?, |
| 750 | 0× | None => Vec::new(), |
| 751 | | }; |
| 752 | 3× | (EntryKind::File, bytes) |
| 753 | | } |
| 754 | 0× | (_, FileContent::Dir) => return Err(RepoError::NotFound), |
| 755 | | }; |
| 756 | 32× | let size = bytes.len() as u64; |
| 757 | 32× | let body = if size > render_limit { |
| 758 | 0× | FileBody::TooLarge |
| 759 | 32× | } else if is_binary(&bytes) { |
| 760 | 3× | FileBody::Binary |
| 761 | | } else { |
| 762 | 29× | FileBody::Text(String::from_utf8_lossy(&bytes).into_owned()) |
| 763 | | }; |
| 764 | 32× | let labels = head_labels(repo)?; |
| 765 | 32× | let last_change = last_change_of(repo, &loaded.state, &target.heads, path) |
| 766 | 32× | .and_then(|h| loaded.state.get(&h).map(|meta| change_view(repo, &h, meta, loaded.state.heads().contains(&h), &labels))); |
| 767 | 32× | let name = path.rsplit('/').next().unwrap_or(path).to_string(); |
| 768 | 32× | Ok(FileView { |
| 769 | 32× | target, |
| 770 | 32× | path: path.to_string(), |
| 771 | 32× | name, |
| 772 | 32× | crumbs: crumbs(path), |
| 773 | 32× | kind, |
| 774 | 32× | exec: f.mode.exec, |
| 775 | 32× | size, |
| 776 | 32× | body, |
| 777 | 32× | conflicted: f.is_conflicted(), |
| 778 | 32× | bytes, |
| 779 | 32× | last_change, |
| 780 | 32× | sidebar: sidebar(snapshot, path), |
| 781 | 32× | }) |
| 782 | 34× | } |
| 783 | |
|
| 784 | |
|
| 785 | 14× | pub fn raw(repo: &Repo, cache: &StateCache, target: &RefTarget, path: &str) -> Result<(String, Vec<u8>)> { |
| 786 | 14× | let loaded = cache.load(repo, &target.heads)?; |
| 787 | 14× | let path = path.trim_matches('/'); |
| 788 | 14× | let Some(f) = loaded.snapshot.files.get(path) else { return Err(RepoError::NotFound) }; |
| 789 | 14× | let bytes = match (&f.kind, &f.content) { |
| 790 | 0× | (NodeKind::Dir, _) | (_, FileContent::Dir) => return Err(RepoError::NotFound), |
| 791 | 12× | (_, FileContent::Text { bytes, .. }) => bytes.clone(), |
| 792 | 2× | (_, FileContent::Opaque { blobs }) => match blobs.first() { |
| 793 | 2× | Some(b) => repo.read_blob(b)?, |
| 794 | 0× | None => Vec::new(), |
| 795 | | }, |
| 796 | | }; |
| 797 | 14× | Ok((path.rsplit('/').next().unwrap_or(path).to_string(), bytes)) |
| 798 | 14× | } |
| 799 | |
|
| 800 | |
|
| 801 | |
|
| 802 | 36× | fn state_path_key(tag: &[u8], heads: &[ChangeHash], path: &str) -> [u8; 32] { |
| 803 | 36× | let mut sorted: Vec<&ChangeHash> = heads.iter().collect(); |
| 804 | 36× | sorted.sort(); |
| 805 | 88× | let joined: Vec<u8> = sorted.iter().flat_map(|h| h.to_hex().into_bytes()).collect(); |
| 806 | 36× | crate::render::cache::key(&[tag, &joined, path.as_bytes()]) |
| 807 | 36× | } |
| 808 | |
|
| 809 | | struct Last(Option<ChangeHash>); |
| 810 | |
|
| 811 | | impl crate::render::cache::Weigh for Last { |
| 812 | 14× | fn weight(&self) -> usize { |
| 813 | 14× | 64 |
| 814 | 14× | } |
| 815 | | } |
| 816 | |
|
| 817 | |
|
| 818 | 32× | pub fn last_change_of(repo: &Repo, state: &oxy_core::state::State, heads: &[ChangeHash], path: &str) -> Option<ChangeHash> { |
| 819 | | static C: std::sync::OnceLock<crate::render::cache::Lru<Last>> = std::sync::OnceLock::new(); |
| 820 | 32× | let cache = C.get_or_init(|| crate::render::cache::Lru::new(4 << 20)); |
| 821 | 32× | let key = state_path_key(b"last1", heads, path); |
| 822 | 32× | cache.get_or(key, || Last(repo.log_for_path_of(state, path, Some(1)).ok().and_then(|l| l.into_iter().next()).map(|e| e.hash))).0 |
| 823 | 32× | } |
| 824 | |
|
| 825 | | struct BlameLines(Vec<BlameLine>); |
| 826 | |
|
| 827 | | impl crate::render::cache::Weigh for BlameLines { |
| 828 | 4× | fn weight(&self) -> usize { |
| 829 | 13× | self.0.iter().map(|l| l.text.len() + l.author.len() + 128).sum::<usize>() + 32 |
| 830 | 4× | } |
| 831 | | } |
| 832 | |
|
| 833 | |
|
| 834 | 4× | fn blame_cached(repo: &Repo, cache_state: &StateCache, heads: &[ChangeHash], path: &str) -> Result<Vec<BlameLine>> { |
| 835 | | static C: std::sync::OnceLock<crate::render::cache::Lru<BlameLines>> = std::sync::OnceLock::new(); |
| 836 | 4× | let cache = C.get_or_init(|| crate::render::cache::Lru::new(64 << 20)); |
| 837 | 4× | let key = state_path_key(b"blame1", heads, path); |
| 838 | 4× | let mut failure = None; |
| 839 | 4× | let lines = cache.get_or(key, || { |
| 840 | 4× | match cache_state |
| 841 | 4× | .load(repo, heads) |
| 842 | 4× | .map_err(|e| oxy_core::repo::RepoError::Msg(e.to_string())) |
| 843 | 4× | .and_then(|loaded| repo.blame_of(&loaded.state, &loaded.snapshot.tree, path)) |
| 844 | | { |
| 845 | 4× | Ok(l) => BlameLines(l), |
| 846 | 0× | Err(e) => { |
| 847 | 0× | failure = Some(e); |
| 848 | 0× | BlameLines(Vec::new()) |
| 849 | | } |
| 850 | | } |
| 851 | 4× | }); |
| 852 | 4× | if let Some(e) = failure { |
| 853 | 0× | return Err(RepoError::Oxy(e)); |
| 854 | 4× | } |
| 855 | 4× | Ok(lines.0.clone()) |
| 856 | 4× | } |
| 857 | |
|
| 858 | 112× | pub fn is_binary(bytes: &[u8]) -> bool { |
| 859 | 112× | let head = &bytes[..bytes.len().min(8192)]; |
| 860 | 112× | head.contains(&0) |
| 861 | 109× | || std::str::from_utf8(head).is_err() |
| 862 | 0× | && head.iter().filter(|b| **b < 0x20 && !matches!(**b, b'\n' | b'\r' | b'\t')).count() > head.len() / 20 |
| 863 | 112× | } |
| 864 | |
|
| 865 | |
|
| 866 | |
|
| 867 | |
|
| 868 | 1× | pub fn last_changes(repo: &Repo, cache: &StateCache, heads: &[ChangeHash], paths: &[String]) -> Result<Vec<(String, ChangeView)>> { |
| 869 | 1× | let labels = head_labels(repo)?; |
| 870 | 1× | let loaded = cache.load(repo, heads)?; |
| 871 | 1× | let state = &loaded.state; |
| 872 | 1× | let snapshot = &loaded.snapshot; |
| 873 | | |
| 874 | 1× | let mut newest: HashMap<oxy_core::ids::NodeId, (ChangeHash, u64)> = HashMap::new(); |
| 875 | 2× | for e in repo.log_of(state) { |
| 876 | 2× | let Ok((c, _)) = repo.store().get_change_lazy(&e.hash) else { continue }; |
| 877 | 2× | let when = e.change.hlc.wall_ms; |
| 878 | 11× | for node in c.tree_ops.iter().map(|o| o.node()).chain(c.edits.iter().map(|x| x.node())) { |
| 879 | 11× | newest.entry(node).or_insert((e.hash, when)); |
| 880 | 11× | } |
| 881 | | } |
| 882 | 1× | let mut out = Vec::new(); |
| 883 | 2× | for p in paths { |
| 884 | 2× | let Some(f) = snapshot.files.get(p) else { continue }; |
| 885 | 2× | let best = if f.kind == NodeKind::Dir { |
| 886 | 1× | let prefix = format!("{p}/"); |
| 887 | 1× | snapshot |
| 888 | 1× | .files |
| 889 | 1× | .iter() |
| 890 | 5× | .filter(|(q, _)| q.starts_with(&prefix)) |
| 891 | 1× | .filter_map(|(_, g)| newest.get(&g.node)) |
| 892 | 1× | .chain(newest.get(&f.node)) |
| 893 | 1× | .max_by_key(|(_, when)| *when) |
| 894 | 1× | .copied() |
| 895 | | } else { |
| 896 | 1× | newest.get(&f.node).copied() |
| 897 | | }; |
| 898 | 2× | if let Some((hash, _)) = best { |
| 899 | 2× | if let Some(m) = state.get(&hash) { |
| 900 | 2× | out.push((p.clone(), change_view(repo, &hash, m, state.heads().contains(&hash), &labels))); |
| 901 | 2× | } |
| 902 | 0× | } |
| 903 | | } |
| 904 | 1× | Ok(out) |
| 905 | 1× | } |
| 906 | |
|
| 907 | |
|
| 908 | |
|
| 909 | | #[derive(Clone, Debug)] |
| 910 | | pub struct Blame { |
| 911 | | pub file: FileView, |
| 912 | | pub lines: Vec<BlameLine>, |
| 913 | | |
| 914 | | |
| 915 | | pub before: HashMap<ChangeHash, Option<String>>, |
| 916 | | } |
| 917 | |
|
| 918 | 4× | pub fn blame(repo: &Repo, cache: &StateCache, target: RefTarget, path: &str, render_limit: u64) -> Result<Blame> { |
| 919 | 4× | let heads = target.heads.clone(); |
| 920 | 4× | let file = file(repo, cache, target, path, render_limit)?; |
| 921 | 4× | let lines = blame_cached(repo, cache, &heads, path)?; |
| 922 | 4× | let mut before = HashMap::new(); |
| 923 | 13× | for l in &lines { |
| 924 | 13× | before.entry(l.hash).or_insert_with(|| repo.store().get_change_meta(&l.hash).ok().and_then(|c| state_spec(&c.deps))); |
| 925 | | } |
| 926 | 4× | Ok(Blame { file, lines, before }) |
| 927 | 4× | } |
| 928 | |
|
| 929 | |
|
| 930 | |
|
| 931 | | #[derive(Clone, Debug)] |
| 932 | | pub struct BookmarkView { |
| 933 | | pub name: String, |
| 934 | | pub heads: Vec<String>, |
| 935 | | pub changes: usize, |
| 936 | | pub default: bool, |
| 937 | | pub conflicted: bool, |
| 938 | | pub latest_ms: u64, |
| 939 | | } |
| 940 | |
|
| 941 | | #[derive(Clone, Debug)] |
| 942 | | pub struct TagView { |
| 943 | | pub name: String, |
| 944 | | pub heads: Vec<String>, |
| 945 | | pub message: String, |
| 946 | | pub signer: Option<String>, |
| 947 | | } |
| 948 | |
|
| 949 | |
|
| 950 | | #[derive(Clone, Debug)] |
| 951 | | pub struct WithdrawnView { |
| 952 | | pub name: String, |
| 953 | | pub heads: Vec<String>, |
| 954 | | pub reason: String, |
| 955 | | pub signer: Option<String>, |
| 956 | | pub when_ms: i64, |
| 957 | | } |
| 958 | |
|
| 959 | | #[derive(Clone, Debug)] |
| 960 | | pub struct Overview { |
| 961 | | pub tree: Tree, |
| 962 | | pub changes: usize, |
| 963 | | pub heads: usize, |
| 964 | | pub bookmarks: Vec<BookmarkView>, |
| 965 | | pub tags: Vec<TagView>, |
| 966 | | pub latest: Option<ChangeView>, |
| 967 | | pub conflicted: bool, |
| 968 | | pub license: Option<String>, |
| 969 | | pub policy: PolicyBadge, |
| 970 | | pub contributors: Vec<Contributor>, |
| 971 | | pub languages: Vec<LanguageShare>, |
| 972 | | |
| 973 | | |
| 974 | | |
| 975 | | pub standing_in: Option<String>, |
| 976 | | } |
| 977 | |
|
| 978 | | impl Overview { |
| 979 | | |
| 980 | | |
| 981 | 53× | pub fn recent_bookmarks(&self) -> Vec<&BookmarkView> { |
| 982 | 53× | let mut list: Vec<&BookmarkView> = self.bookmarks.iter().collect(); |
| 983 | 53× | list.sort_by(|a, b| b.default.cmp(&a.default).then(b.latest_ms.cmp(&a.latest_ms)).then_with(|| a.name.cmp(&b.name))); |
| 984 | 53× | list.truncate(10); |
| 985 | 53× | list |
| 986 | 53× | } |
| 987 | | } |
| 988 | |
|
| 989 | |
|
| 990 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 991 | | pub struct Contributor { |
| 992 | | pub name: String, |
| 993 | | |
| 994 | | pub key: String, |
| 995 | | pub changes: usize, |
| 996 | | |
| 997 | | pub account: Option<String>, |
| 998 | | |
| 999 | | |
| 1000 | | pub via: Vec<(String, usize)>, |
| 1001 | | |
| 1002 | | pub hub: bool, |
| 1003 | | } |
| 1004 | |
|
| 1005 | |
|
| 1006 | | #[derive(Clone, Debug, PartialEq)] |
| 1007 | | pub struct LanguageShare { |
| 1008 | | pub name: String, |
| 1009 | | pub bytes: u64, |
| 1010 | | pub percent: f64, |
| 1011 | | pub colour: String, |
| 1012 | | } |
| 1013 | |
|
| 1014 | |
|
| 1015 | |
|
| 1016 | |
|
| 1017 | 53× | pub fn contributors(repo: &Repo, state: &oxy_core::state::State) -> Vec<Contributor> { |
| 1018 | 53× | let mut by: HashMap<String, Contributor> = HashMap::new(); |
| 1019 | 53× | let mut names: HashMap<KeyId, String> = HashMap::new(); |
| 1020 | 58× | for (hash, meta) in state.changes() { |
| 1021 | 58× | let a = author(repo, &meta.author, &meta.message); |
| 1022 | 58× | let id = if a.key.is_empty() { format!("git:{}", a.email.to_lowercase()) } else { a.key.clone() }; |
| 1023 | | |
| 1024 | 58× | let name = |
| 1025 | 58× | if a.key.is_empty() && a.email.is_empty() && a.name == "unknown" { "Unattributed changes".to_string() } else { a.name.clone() }; |
| 1026 | 58× | let entry = by.entry(id).or_insert_with(|| Contributor { |
| 1027 | 33× | name, |
| 1028 | 33× | key: a.key.clone(), |
| 1029 | | changes: 0, |
| 1030 | 33× | account: None, |
| 1031 | 33× | via: Vec::new(), |
| 1032 | | hub: false, |
| 1033 | 33× | }); |
| 1034 | 58× | entry.changes += 1; |
| 1035 | 58× | if !meta.author.is_zero() { |
| 1036 | | |
| 1037 | 38× | let signer = repo |
| 1038 | 38× | .store() |
| 1039 | 38× | .signatures(hash) |
| 1040 | 38× | .ok() |
| 1041 | 38× | .and_then(|s| s.first().map(|s| s.key)) |
| 1042 | 38× | .filter(|k| *k != meta.author) |
| 1043 | 38× | .or_else(|| sealer(repo, hash, &meta.author)); |
| 1044 | 38× | if let Some(k) = signer { |
| 1045 | 12× | let who = names |
| 1046 | 12× | .entry(k) |
| 1047 | 12× | .or_insert_with(|| match certificate(repo, &k) { |
| 1048 | 1× | Some(c) => c.subject, |
| 1049 | 2× | None => repo.store().get_identity(&k).map(|i| i.name).unwrap_or_else(|_| k.short(12)), |
| 1050 | 3× | }) |
| 1051 | 12× | .clone(); |
| 1052 | 12× | match entry.via.iter_mut().find(|(n, _)| *n == who) { |
| 1053 | 9× | Some((_, n)) => *n += 1, |
| 1054 | 3× | None => entry.via.push((who, 1)), |
| 1055 | | } |
| 1056 | 26× | } |
| 1057 | 20× | } |
| 1058 | | } |
| 1059 | 53× | let mut out: Vec<Contributor> = by.into_values().collect(); |
| 1060 | 53× | for c in &mut out { |
| 1061 | 33× | c.via.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); |
| 1062 | | } |
| 1063 | 53× | out.sort_by(|a, b| b.changes.cmp(&a.changes).then(a.name.cmp(&b.name))); |
| 1064 | 53× | out |
| 1065 | 53× | } |
| 1066 | |
|
| 1067 | |
|
| 1068 | |
|
| 1069 | |
|
| 1070 | 68× | pub fn language_of(path: &str) -> Option<&'static str> { |
| 1071 | 68× | let lower = path.to_ascii_lowercase(); |
| 1072 | 68× | let name = lower.rsplit('/').next().unwrap_or(&lower); |
| 1073 | 68× | let skip_dirs = ["vendor/", "node_modules/", "target/", "dist/", "third_party/", ".git/"]; |
| 1074 | 399× | if skip_dirs.iter().any(|d| lower.starts_with(d) || lower.contains(&format!("/{d}"))) { |
| 1075 | 2× | return None; |
| 1076 | 66× | } |
| 1077 | 66× | if name.ends_with(".lock") |
| 1078 | 65× | || name == "package-lock.json" |
| 1079 | 65× | || name.ends_with(".min.js") |
| 1080 | 65× | || name.ends_with(".min.css") |
| 1081 | 65× | || name.ends_with(".d.ts") |
| 1082 | | { |
| 1083 | 1× | return None; |
| 1084 | 65× | } |
| 1085 | 65× | let ext = name.rsplit_once('.').map(|(_, e)| e).unwrap_or(""); |
| 1086 | 65× | let by_ext = match ext { |
| 1087 | 65× | "s" | "asm" | "a65" | "a80" | "z80" | "inc" | "65s" => Some("Assembly"), |
| 1088 | 64× | "toml" => Some("TOML"), |
| 1089 | 63× | "ts" | "tsx" | "mts" | "cts" => Some("TypeScript"), |
| 1090 | 63× | "kdl" => Some("KDL"), |
| 1091 | 58× | "sh" | "bash" | "zsh" => Some("Shell"), |
| 1092 | 52× | "h" => Some("C"), |
| 1093 | 50× | "hpp" | "hh" | "cc" | "cxx" => Some("C++"), |
| 1094 | 50× | "vue" => Some("Vue"), |
| 1095 | 50× | "svelte" => Some("Svelte"), |
| 1096 | 50× | "zig" => Some("Zig"), |
| 1097 | 50× | "nix" => Some("Nix"), |
| 1098 | 50× | "md" | "markdown" | "txt" | "rst" | "adoc" | "json" | "csv" | "svg" | "xml" => return None, |
| 1099 | 15× | _ => None, |
| 1100 | | }; |
| 1101 | 30× | if by_ext.is_some() { |
| 1102 | 15× | return by_ext; |
| 1103 | 15× | } |
| 1104 | 15× | let lang = crate::render::highlight::language(path)?; |
| 1105 | 12× | Some(match lang { |
| 1106 | 12× | "Bourne Again Shell (bash)" | "Shell-Unix-Generic" => "Shell", |
| 1107 | 12× | "Plain Text" | "Markdown" | "MultiMarkdown" | "JSON" | "Git Ignore" | "Git Attributes" | "Git Config" => return None, |
| 1108 | 12× | l => l, |
| 1109 | | }) |
| 1110 | 68× | } |
| 1111 | |
|
| 1112 | |
|
| 1113 | 23× | pub fn language_colour(name: &str) -> String { |
| 1114 | 23× | let known = match name { |
| 1115 | 23× | "Rust" => "#dea584", |
| 1116 | 15× | "Python" => "#3572a5", |
| 1117 | 15× | "Shell" => "#89e051", |
| 1118 | 10× | "Makefile" => "#427819", |
| 1119 | 10× | "C" => "#555555", |
| 1120 | 7× | "C++" => "#f34b7d", |
| 1121 | 7× | "C#" => "#178600", |
| 1122 | 7× | "Assembly" => "#6e4c13", |
| 1123 | 7× | "JavaScript" => "#f1e05a", |
| 1124 | 7× | "TypeScript" => "#3178c6", |
| 1125 | 7× | "HTML" => "#e34c26", |
| 1126 | 7× | "CSS" => "#663399", |
| 1127 | 7× | "Go" => "#00add8", |
| 1128 | 7× | "Java" => "#b07219", |
| 1129 | 7× | "TOML" => "#9c4221", |
| 1130 | 7× | "YAML" => "#cb171e", |
| 1131 | 7× | "SQL" => "#e38c00", |
| 1132 | 7× | "Lua" => "#000080", |
| 1133 | 7× | "Ruby" => "#701516", |
| 1134 | 7× | "PHP" => "#4f5d95", |
| 1135 | 7× | "Haskell" => "#5e5086", |
| 1136 | 7× | "KDL" => "#ffb3b3", |
| 1137 | 2× | "Dockerfile" => "#384d54", |
| 1138 | 2× | "Vue" => "#41b883", |
| 1139 | 2× | "Zig" => "#ec915c", |
| 1140 | 2× | "Nix" => "#7e7eff", |
| 1141 | 2× | _ => "", |
| 1142 | | }; |
| 1143 | 23× | if !known.is_empty() { |
| 1144 | 21× | return known.to_string(); |
| 1145 | 2× | } |
| 1146 | 2× | let h = blake3::hash(name.as_bytes()); |
| 1147 | 2× | let b = h.as_bytes(); |
| 1148 | 2× | format!("#{:02x}{:02x}{:02x}", 64 + b[0] / 2, 64 + b[1] / 2, 64 + b[2] / 2) |
| 1149 | 23× | } |
| 1150 | |
|
| 1151 | |
|
| 1152 | 53× | pub fn languages(snapshot: &Snapshot) -> Vec<LanguageShare> { |
| 1153 | 53× | let mut by: HashMap<&'static str, u64> = HashMap::new(); |
| 1154 | 81× | for (path, f) in &snapshot.files { |
| 1155 | 81× | if let FileContent::Text { bytes, .. } = &f.content { |
| 1156 | 59× | if let Some(l) = language_of(path) { |
| 1157 | 22× | *by.entry(l).or_default() += bytes.len() as u64; |
| 1158 | 37× | } |
| 1159 | 22× | } |
| 1160 | | } |
| 1161 | 53× | let total: u64 = by.values().sum(); |
| 1162 | 53× | if total == 0 { |
| 1163 | 40× | return vec![]; |
| 1164 | 13× | } |
| 1165 | 13× | let mut list: Vec<(&str, u64)> = by.into_iter().collect(); |
| 1166 | 13× | list.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); |
| 1167 | 13× | let mut out: Vec<LanguageShare> = Vec::new(); |
| 1168 | 13× | let mut other = 0u64; |
| 1169 | 20× | for (name, bytes) in list { |
| 1170 | 20× | if (bytes as f64) * 100.0 / (total as f64) < 1.0 || out.len() >= 8 { |
| 1171 | 0× | other += bytes; |
| 1172 | 20× | } else { |
| 1173 | 20× | out.push(LanguageShare { |
| 1174 | 20× | name: name.to_string(), |
| 1175 | 20× | bytes, |
| 1176 | 20× | percent: bytes as f64 * 100.0 / total as f64, |
| 1177 | 20× | colour: language_colour(name), |
| 1178 | 20× | }); |
| 1179 | 20× | } |
| 1180 | | } |
| 1181 | 13× | if other > 0 { |
| 1182 | 0× | out.push(LanguageShare { |
| 1183 | 0× | name: "Other".into(), |
| 1184 | 0× | bytes: other, |
| 1185 | 0× | percent: other as f64 * 100.0 / total as f64, |
| 1186 | 0× | colour: "#8592ad".into(), |
| 1187 | 0× | }); |
| 1188 | 13× | } |
| 1189 | 13× | out |
| 1190 | 53× | } |
| 1191 | |
|
| 1192 | | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 1193 | | pub enum PolicyBadge { |
| 1194 | | None, |
| 1195 | | Active, |
| 1196 | | Expired, |
| 1197 | | } |
| 1198 | |
|
| 1199 | 73× | pub fn bookmarks(repo: &Repo, cache: &StateCache, default: &str) -> Result<Vec<BookmarkView>> { |
| 1200 | 73× | let list = repo.bookmarks()?; |
| 1201 | 98× | let briefs = cache.briefs(repo, &list.iter().map(|b| b.heads.clone()).collect::<Vec<_>>())?; |
| 1202 | 73× | let mut out = Vec::new(); |
| 1203 | 98× | for (b, s) in list.iter().zip(briefs) { |
| 1204 | 98× | out.push(BookmarkView { |
| 1205 | 98× | name: b.name.clone(), |
| 1206 | 105× | heads: b.heads.iter().map(|h| h.to_hex()).collect(), |
| 1207 | 98× | changes: s.changes, |
| 1208 | 98× | default: b.name == default, |
| 1209 | 98× | conflicted: s.conflicted, |
| 1210 | 98× | latest_ms: s.latest_ms, |
| 1211 | | }); |
| 1212 | | } |
| 1213 | 73× | out.sort_by(|a, b| b.default.cmp(&a.default).then_with(|| a.name.cmp(&b.name))); |
| 1214 | 73× | Ok(out) |
| 1215 | 73× | } |
| 1216 | |
|
| 1217 | 85× | pub fn tags(repo: &Repo) -> Result<Vec<TagView>> { |
| 1218 | 85× | let mut out: Vec<TagView> = repo |
| 1219 | 85× | .tags()? |
| 1220 | 85× | .into_iter() |
| 1221 | 85× | .map(|t| TagView { name: t.name, heads: t.heads.iter().map(|h| h.to_hex()).collect(), message: t.message, signer: t.signer }) |
| 1222 | 85× | .collect(); |
| 1223 | 85× | out.sort_by(|a, b| b.name.cmp(&a.name)); |
| 1224 | 85× | Ok(out) |
| 1225 | 85× | } |
| 1226 | |
|
| 1227 | |
|
| 1228 | 9× | pub fn withdrawn_tags(repo: &Repo) -> Result<Vec<WithdrawnView>> { |
| 1229 | 9× | let mut out: Vec<WithdrawnView> = repo |
| 1230 | 9× | .remote_refs()? |
| 1231 | | .withdrawn |
| 1232 | 9× | .into_iter() |
| 1233 | 9× | .filter_map(|t| { |
| 1234 | 4× | let sa = t.attestation?; |
| 1235 | 4× | let oxy_core::attest::AttestBody::Untag { reason, .. } = &sa.attest.body else { return None }; |
| 1236 | | Some(WithdrawnView { |
| 1237 | 4× | name: t.name, |
| 1238 | 4× | heads: t.heads.iter().map(|h| h.to_hex()).collect(), |
| 1239 | 4× | reason: reason.clone(), |
| 1240 | 4× | signer: sa.sigs.first().and_then(|s| repo.store().get_identity(&s.key).ok()).map(|i| i.name), |
| 1241 | 4× | when_ms: sa.attest.hlc.wall_ms as i64, |
| 1242 | | }) |
| 1243 | 4× | }) |
| 1244 | 9× | .collect(); |
| 1245 | 9× | out.sort_by_key(|w| std::cmp::Reverse(w.when_ms)); |
| 1246 | 9× | Ok(out) |
| 1247 | 9× | } |
| 1248 | |
|
| 1249 | 53× | pub fn policy_badge(repo: &Repo) -> PolicyBadge { |
| 1250 | 53× | match repo.current_policy() { |
| 1251 | 1× | Ok(Some((_, sp))) => { |
| 1252 | 1× | if sp.policy.expires != 0 && (sp.policy.expires as i64) < crate::db::now_ms() { |
| 1253 | 0× | PolicyBadge::Expired |
| 1254 | | } else { |
| 1255 | 1× | PolicyBadge::Active |
| 1256 | | } |
| 1257 | | } |
| 1258 | 52× | _ => PolicyBadge::None, |
| 1259 | | } |
| 1260 | 53× | } |
| 1261 | |
|
| 1262 | |
|
| 1263 | |
|
| 1264 | 53× | pub fn overview(repo: &Repo, cache: &StateCache, default_bookmark: &str, shown: &str) -> Result<Overview> { |
| 1265 | 53× | let missing = || RefTarget { label: shown.into(), kind: RefKind::Bookmark, heads: vec![] }; |
| 1266 | 53× | let (target, standing_in) = match resolve(repo, cache, shown) { |
| 1267 | 52× | Ok(t) => (t, None), |
| 1268 | | |
| 1269 | | |
| 1270 | 1× | Err(_) if shown == default_bookmark => match stand_in(repo)? { |
| 1271 | 1× | Some(b) => (resolve(repo, cache, &b)?, Some(b)), |
| 1272 | 0× | None => (missing(), None), |
| 1273 | | }, |
| 1274 | 0× | Err(_) => (missing(), None), |
| 1275 | | }; |
| 1276 | 53× | let heads = target.heads.len(); |
| 1277 | | |
| 1278 | | |
| 1279 | 53× | let loaded = cache.load(repo, &target.heads)?; |
| 1280 | 53× | let state = &loaded.state; |
| 1281 | 53× | let snapshot = &loaded.snapshot; |
| 1282 | 53× | let changes = state.len(); |
| 1283 | 53× | let conflicted = snapshot.is_conflicted(); |
| 1284 | 53× | let labels = head_labels(repo)?; |
| 1285 | 53× | let latest = state |
| 1286 | 53× | .changes() |
| 1287 | 53× | .max_by(|(ha, a), (hb, b)| a.hlc.cmp(&b.hlc).then(ha.cmp(hb))) |
| 1288 | 53× | .map(|(h, m)| change_view(repo, h, m, state.heads().contains(h), &labels)); |
| 1289 | 53× | let tree = tree_of(repo, target, snapshot, "")?; |
| 1290 | 53× | let license = tree |
| 1291 | 53× | .entries |
| 1292 | 53× | .iter() |
| 1293 | 61× | .find(|e| matches!(e.name.to_lowercase().as_str(), "license" | "license.md" | "license.txt" | "licence" | "copying")) |
| 1294 | 53× | .map(|e| e.path.clone()); |
| 1295 | | Ok(Overview { |
| 1296 | 53× | tree, |
| 1297 | 53× | changes, |
| 1298 | 53× | heads, |
| 1299 | 53× | bookmarks: bookmarks(repo, cache, default_bookmark)?, |
| 1300 | 53× | tags: tags(repo)?, |
| 1301 | 53× | latest, |
| 1302 | 53× | conflicted, |
| 1303 | 53× | license, |
| 1304 | 53× | policy: policy_badge(repo), |
| 1305 | 53× | contributors: contributors(repo, state), |
| 1306 | 53× | languages: languages(snapshot), |
| 1307 | 53× | standing_in, |
| 1308 | | }) |
| 1309 | 53× | } |
| 1310 | |
|
| 1311 | |
|
| 1312 | |
|
| 1313 | | #[derive(Clone, Debug)] |
| 1314 | | pub struct Compare { |
| 1315 | | pub base: RefTarget, |
| 1316 | | pub head: RefTarget, |
| 1317 | | |
| 1318 | | pub added: Vec<ChangeView>, |
| 1319 | | |
| 1320 | | pub missing: usize, |
| 1321 | | pub files: Vec<FileDiff>, |
| 1322 | | pub bases: BTreeMap<String, Vec<u8>>, |
| 1323 | | } |
| 1324 | |
|
| 1325 | 5× | pub fn compare(repo: &Repo, cache: &StateCache, base: RefTarget, head: RefTarget) -> Result<Compare> { |
| 1326 | 5× | let base_loaded = cache.load(repo, &base.heads)?; |
| 1327 | 5× | let head_loaded = cache.load(repo, &head.heads)?; |
| 1328 | 5× | let base_state = &base_loaded.state; |
| 1329 | 5× | let head_state = &head_loaded.state; |
| 1330 | 5× | let labels = head_labels(repo)?; |
| 1331 | 5× | let mut added: Vec<ChangeView> = head_state |
| 1332 | 5× | .changes() |
| 1333 | 9× | .filter(|(h, _)| !base_state.contains(h)) |
| 1334 | 5× | .map(|(h, m)| change_view(repo, h, m, head_state.heads().contains(h), &labels)) |
| 1335 | 5× | .collect(); |
| 1336 | 5× | added.sort_by_key(|c| std::cmp::Reverse(c.when_ms)); |
| 1337 | 6× | let missing = base_state.changes().filter(|(h, _)| !head_state.contains(h)).count(); |
| 1338 | 5× | let (files, bases) = crate::render::diff::snapshot_diff(&base_loaded.snapshot, &head_loaded.snapshot); |
| 1339 | 5× | Ok(Compare { base, head, added, missing, files, bases }) |
| 1340 | 5× | } |
| 1341 | |
|
| 1342 | |
|
| 1343 | |
|
| 1344 | | #[derive(Clone, Debug)] |
| 1345 | | pub struct ConflictView { |
| 1346 | | pub bookmark: String, |
| 1347 | | pub path: String, |
| 1348 | | pub kind: String, |
| 1349 | | |
| 1350 | | pub marked: Option<String>, |
| 1351 | | pub contributors: Vec<ChangeView>, |
| 1352 | | } |
| 1353 | |
|
| 1354 | 9× | pub fn conflicts(repo: &Repo, cache: &StateCache) -> Result<Vec<ConflictView>> { |
| 1355 | 9× | let list = repo.bookmarks()?; |
| 1356 | 51× | let briefs = cache.briefs(repo, &list.iter().map(|b| b.heads.clone()).collect::<Vec<_>>())?; |
| 1357 | 9× | let mut out = Vec::new(); |
| 1358 | 51× | for (b, brief) in list.iter().zip(briefs) { |
| 1359 | | |
| 1360 | 51× | if !brief.conflicted { |
| 1361 | 47× | continue; |
| 1362 | 4× | } |
| 1363 | 4× | let loaded = cache.load(repo, &b.heads)?; |
| 1364 | 4× | out.extend(conflicts_in(repo, &loaded, &b.name)); |
| 1365 | | } |
| 1366 | 9× | Ok(out) |
| 1367 | 9× | } |
| 1368 | |
|
| 1369 | |
|
| 1370 | 18× | pub fn conflicts_in(repo: &Repo, loaded: &super::cache::Loaded, bookmark: &str) -> Vec<ConflictView> { |
| 1371 | 18× | let labels = head_labels(repo).unwrap_or_default(); |
| 1372 | 18× | let mut out = Vec::new(); |
| 1373 | | { |
| 1374 | 18× | let b_name = bookmark.to_string(); |
| 1375 | 18× | let state = &loaded.state; |
| 1376 | 18× | let snapshot = &loaded.snapshot; |
| 1377 | 18× | for c in &snapshot.tree.conflicts { |
| 1378 | 4× | let (path, kind) = describe_tree_conflict(snapshot, c); |
| 1379 | 4× | out.push(ConflictView { bookmark: b_name.clone(), path, kind, marked: None, contributors: vec![] }); |
| 1380 | 4× | } |
| 1381 | 70× | for (path, f) in &snapshot.files { |
| 1382 | 70× | if !f.is_conflicted() { |
| 1383 | 56× | continue; |
| 1384 | 14× | } |
| 1385 | 14× | let (kind, marked, contributors) = match &f.content { |
| 1386 | | FileContent::Text { .. } => { |
| 1387 | 10× | let (bytes, _) = state.render_file(&f.node); |
| 1388 | 10× | let regions = state.conflict_regions(&f.node); |
| 1389 | 10× | let contributors: Vec<ChangeView> = regions |
| 1390 | 10× | .contributors |
| 1391 | 10× | .iter() |
| 1392 | 20× | .filter_map(|h| state.get(h).map(|m| change_view(repo, h, m, state.heads().contains(h), &labels))) |
| 1393 | 10× | .collect(); |
| 1394 | 10× | ("lines".to_string(), Some(String::from_utf8_lossy(&bytes).into_owned()), contributors) |
| 1395 | | } |
| 1396 | 4× | FileContent::Opaque { blobs } => (format!("replace ({} candidates)", blobs.len()), None, vec![]), |
| 1397 | 0× | FileContent::Dir => continue, |
| 1398 | | }; |
| 1399 | 14× | out.push(ConflictView { bookmark: b_name.clone(), path: path.clone(), kind, marked, contributors }); |
| 1400 | | } |
| 1401 | | } |
| 1402 | 18× | out |
| 1403 | 18× | } |
| 1404 | |
|
| 1405 | 4× | fn describe_tree_conflict(snapshot: &Snapshot, c: &TreeConflict) -> (String, String) { |
| 1406 | 4× | let by_node = snapshot.tree.by_node(); |
| 1407 | 4× | let path_of = |n: &oxy_core::ids::NodeId| by_node.get(n).map(|e| e.path.clone()).unwrap_or_else(|| n.short(8)); |
| 1408 | 4× | match c { |
| 1409 | 4× | TreeConflict::Name { name, nodes, parent } => { |
| 1410 | 4× | let path = if parent.is_root() { name.clone() } else { format!("{}/{name}", path_of(parent)) }; |
| 1411 | 4× | (path, format!("name: {} entries want this name", nodes.len())) |
| 1412 | | } |
| 1413 | 0× | TreeConflict::MultiPlacement { node, placements } => (path_of(node), format!("placement: {} places", placements.len())), |
| 1414 | 0× | TreeConflict::Orphan { node, .. } => (path_of(node), "orphan: parent directory was removed".into()), |
| 1415 | 0× | TreeConflict::Cycle { node } => (path_of(node), "cycle: directory moved into itself".into()), |
| 1416 | 0× | other => (String::new(), format!("{other:?}")), |
| 1417 | | } |
| 1418 | 4× | } |
| 1419 | |
|
| 1420 | |
|
| 1421 | |
|
| 1422 | | #[derive(Clone, Debug)] |
| 1423 | | pub struct KeyView { |
| 1424 | | pub key: String, |
| 1425 | | pub short: String, |
| 1426 | | pub name: String, |
| 1427 | | pub email: String, |
| 1428 | | } |
| 1429 | |
|
| 1430 | | #[derive(Clone, Debug)] |
| 1431 | | pub struct RuleView { |
| 1432 | | pub pattern: String, |
| 1433 | | pub keys: Vec<KeyView>, |
| 1434 | | pub threshold: u32, |
| 1435 | | pub require: String, |
| 1436 | | pub allow_conflicts: bool, |
| 1437 | | } |
| 1438 | |
|
| 1439 | | #[derive(Clone, Debug)] |
| 1440 | | pub struct PolicyView { |
| 1441 | | pub serial: u64, |
| 1442 | | pub expires_ms: u64, |
| 1443 | | pub expired: bool, |
| 1444 | | pub roots: Vec<KeyView>, |
| 1445 | | pub root_threshold: u32, |
| 1446 | | pub rules: Vec<RuleView>, |
| 1447 | | pub revoked: Vec<KeyView>, |
| 1448 | | pub signatures: usize, |
| 1449 | | pub history: usize, |
| 1450 | | } |
| 1451 | |
|
| 1452 | | #[derive(Clone, Debug, Default)] |
| 1453 | | pub struct Verification { |
| 1454 | | pub total: usize, |
| 1455 | | pub signed: usize, |
| 1456 | | pub sealed: usize, |
| 1457 | | pub unsigned: usize, |
| 1458 | | pub revoked: usize, |
| 1459 | | pub invalid: Vec<(String, String)>, |
| 1460 | | } |
| 1461 | |
|
| 1462 | | #[derive(Clone, Debug)] |
| 1463 | | pub struct Trust { |
| 1464 | | pub policy: Option<PolicyView>, |
| 1465 | | pub verification: Verification, |
| 1466 | | pub hub_key: String, |
| 1467 | | pub hub_delegated_by: Vec<KeyView>, |
| 1468 | | } |
| 1469 | |
|
| 1470 | 2× | fn key_view(repo: &Repo, ids: &[oxy_core::identity::Identity], key: &KeyId) -> KeyView { |
| 1471 | 4× | let found = ids.iter().find(|i| i.hash() == *key).cloned().or_else(|| repo.store().get_identity(key).ok()); |
| 1472 | 2× | match found { |
| 1473 | 2× | Some(i) => KeyView { key: key.to_hex(), short: key.short(12), name: i.name, email: i.email }, |
| 1474 | 0× | None => KeyView { key: key.to_hex(), short: key.short(12), name: String::new(), email: String::new() }, |
| 1475 | | } |
| 1476 | 2× | } |
| 1477 | |
|
| 1478 | 4× | pub fn verification(repo: &Repo, cache: &StateCache) -> Result<Verification> { |
| 1479 | 4× | let heads = all_heads(repo)?; |
| 1480 | 4× | let loaded = cache.load(repo, &heads)?; |
| 1481 | 4× | let state = &loaded.state; |
| 1482 | 4× | let mut v = Verification::default(); |
| 1483 | 7× | for (h, _) in state.changes() { |
| 1484 | 7× | v.total += 1; |
| 1485 | 7× | match signature(repo, h) { |
| 1486 | 1× | SigView::Unsigned => v.unsigned += 1, |
| 1487 | 6× | SigView::Valid { sealed, revoked, .. } => { |
| 1488 | 6× | if revoked { |
| 1489 | 0× | v.revoked += 1; |
| 1490 | 6× | } |
| 1491 | 6× | if sealed { |
| 1492 | 0× | v.sealed += 1 |
| 1493 | | } else { |
| 1494 | 6× | v.signed += 1 |
| 1495 | | } |
| 1496 | | } |
| 1497 | 0× | SigView::Invalid(why) => v.invalid.push((h.to_hex(), why)), |
| 1498 | | } |
| 1499 | | } |
| 1500 | 4× | Ok(v) |
| 1501 | 4× | } |
| 1502 | |
|
| 1503 | 3× | pub fn trust(repo: &Repo, cache: &StateCache, hub_key: &KeyId) -> Result<Trust> { |
| 1504 | 3× | let policy = match repo.current_policy()? { |
| 1505 | 1× | Some((_, sp)) => { |
| 1506 | 1× | let p = &sp.policy; |
| 1507 | 1× | let ids = &p.identities; |
| 1508 | 1× | let require = |r: &oxy_core::policy::Require| match r { |
| 1509 | 0× | oxy_core::policy::Require::Signed => "signed", |
| 1510 | 0× | oxy_core::policy::Require::Sealed => "sealed", |
| 1511 | 1× | oxy_core::policy::Require::Any => "any", |
| 1512 | 1× | }; |
| 1513 | | Some(PolicyView { |
| 1514 | 1× | serial: p.serial, |
| 1515 | 1× | expires_ms: p.expires, |
| 1516 | 1× | expired: p.expires != 0 && (p.expires as i64) < crate::db::now_ms(), |
| 1517 | 1× | roots: p.roots.iter().map(|k| key_view(repo, ids, k)).collect(), |
| 1518 | 1× | root_threshold: p.root_threshold, |
| 1519 | 1× | rules: p |
| 1520 | 1× | .rules |
| 1521 | 1× | .iter() |
| 1522 | 1× | .map(|r| RuleView { |
| 1523 | 1× | pattern: r.pattern.clone(), |
| 1524 | 1× | keys: r.keys.iter().map(|k| key_view(repo, ids, k)).collect(), |
| 1525 | 1× | threshold: r.threshold, |
| 1526 | 1× | require: require(&r.require).into(), |
| 1527 | 1× | allow_conflicts: r.allow_conflicts, |
| 1528 | 1× | }) |
| 1529 | 1× | .collect(), |
| 1530 | 1× | revoked: p.revoked.iter().map(|k| key_view(repo, ids, k)).collect(), |
| 1531 | 1× | signatures: sp.sigs.len(), |
| 1532 | 1× | history: repo.policy_history().map(|h| h.len()).unwrap_or(0), |
| 1533 | | }) |
| 1534 | | } |
| 1535 | 2× | None => None, |
| 1536 | | }; |
| 1537 | | |
| 1538 | | |
| 1539 | 3× | let mut delegated = Vec::new(); |
| 1540 | 3× | if let Some(p) = repo.current_policy()?.map(|(_, sp)| sp.policy) { |
| 1541 | 2× | for i in &p.identities { |
| 1542 | 2× | if i.delegate(hub_key).is_some() { |
| 1543 | 1× | delegated.push(KeyView { key: i.hash().to_hex(), short: i.hash().short(12), name: i.name.clone(), email: i.email.clone() }); |
| 1544 | 1× | } |
| 1545 | | } |
| 1546 | 2× | } |
| 1547 | 3× | Ok(Trust { policy, verification: verification(repo, cache)?, hub_key: hub_key.to_hex(), hub_delegated_by: delegated }) |
| 1548 | 3× | } |
| 1549 | |
|
| 1550 | | #[cfg(test)] |
| 1551 | | mod language_tests { |
| 1552 | | use super::*; |
| 1553 | |
|
| 1554 | | #[test] |
| 1555 | 1× | fn languages_are_detected_and_prose_is_left_out() { |
| 1556 | 1× | assert_eq!(language_of("src/main.rs"), Some("Rust")); |
| 1557 | 1× | assert_eq!(language_of("boot/start.s"), Some("Assembly")); |
| 1558 | 1× | assert_eq!(language_of("build.sh"), Some("Shell")); |
| 1559 | 1× | assert_eq!(language_of("Makefile"), Some("Makefile")); |
| 1560 | 1× | assert_eq!(language_of("Cargo.toml"), Some("TOML")); |
| 1561 | 1× | assert_eq!(language_of("README.md"), None); |
| 1562 | 1× | assert_eq!(language_of("Cargo.lock"), None); |
| 1563 | 1× | assert_eq!(language_of("web/node_modules/x/index.js"), None); |
| 1564 | 1× | assert_eq!(language_of("vendor/lib.c"), None); |
| 1565 | 1× | assert_eq!(language_colour("Rust"), "#dea584"); |
| 1566 | 1× | assert_eq!(language_colour("Befunge"), language_colour("Befunge"), "stable"); |
| 1567 | 1× | } |
| 1568 | | } |
| 1569 | |
|
| 1570 | | #[cfg(test)] |
| 1571 | | mod tests { |
| 1572 | | use super::*; |
| 1573 | |
|
| 1574 | 2× | fn tree(paths: &[&str]) -> BTreeMap<String, bool> { |
| 1575 | 2× | let mut m = BTreeMap::new(); |
| 1576 | 256× | for p in paths { |
| 1577 | 256× | let mut end = 0; |
| 1578 | 256× | let parts: Vec<&str> = p.split('/').collect(); |
| 1579 | 512× | for (i, part) in parts.iter().enumerate() { |
| 1580 | 512× | end += part.len(); |
| 1581 | 512× | m.insert(p[..end].to_string(), i + 1 < parts.len()); |
| 1582 | 512× | end += 1; |
| 1583 | 512× | } |
| 1584 | | } |
| 1585 | 2× | m |
| 1586 | 2× | } |
| 1587 | |
|
| 1588 | | #[test] |
| 1589 | 1× | fn sidebar_expands_the_path_only() { |
| 1590 | 1× | let files = tree(&["README.md", "src/main.rs", "src/lib/a.rs", "src/lib/b.rs", "docs/guide.md", "Zeta.txt"]); |
| 1591 | 1× | let rows: Vec<(String, usize, bool, bool)> = |
| 1592 | 8× | sidebar_in(&files, |d| *d, "src/lib/b.rs").into_iter().map(|e| (e.path, e.depth, e.dir, e.on_path)).collect(); |
| 1593 | 1× | let want = [ |
| 1594 | 1× | ("docs", 0, true, false), |
| 1595 | 1× | ("src", 0, true, true), |
| 1596 | 1× | ("src/lib", 1, true, true), |
| 1597 | 1× | ("src/lib/a.rs", 2, false, false), |
| 1598 | 1× | ("src/lib/b.rs", 2, false, true), |
| 1599 | 1× | ("src/main.rs", 1, false, false), |
| 1600 | 1× | ("README.md", 0, false, false), |
| 1601 | 1× | ("Zeta.txt", 0, false, false), |
| 1602 | 1× | ]; |
| 1603 | 8× | assert_eq!(rows, want.iter().map(|(p, d, dir, on)| (p.to_string(), *d, *dir, *on)).collect::<Vec<_>>()); |
| 1604 | 1× | } |
| 1605 | |
|
| 1606 | | #[test] |
| 1607 | 1× | fn sidebar_cuts_long_directories_but_keeps_the_file() { |
| 1608 | 250× | let names: Vec<String> = (0..250).map(|i| format!("big/f{i:03}.txt")).collect(); |
| 1609 | 1× | let refs: Vec<&str> = names.iter().map(String::as_str).collect(); |
| 1610 | 1× | let files = tree(&refs); |
| 1611 | 1× | let rows = sidebar_in(&files, |d| *d, "big/f240.txt"); |
| 1612 | 203× | let listed: Vec<&SideEntry> = rows.iter().filter(|e| e.depth == 1 && !e.more).collect(); |
| 1613 | 1× | assert_eq!(listed.len(), SIDEBAR_PER_DIR + 1, "the limit plus the file itself"); |
| 1614 | 1× | assert!(listed.last().unwrap().on_path); |
| 1615 | 1× | let more = rows.iter().find(|e| e.more).unwrap(); |
| 1616 | 1× | assert_eq!((more.name.as_str(), more.path.as_str()), ("50 more", "big")); |
| 1617 | 1× | } |
| 1618 | |
|
| 1619 | | #[test] |
| 1620 | 1× | fn state_addresses_are_sorted_and_bounded() { |
| 1621 | 1× | let a = ChangeHash::from_hex(&"a".repeat(64)).unwrap(); |
| 1622 | 1× | let b = ChangeHash::from_hex(&"b".repeat(64)).unwrap(); |
| 1623 | 1× | assert_eq!(state_spec(&[b, a, b]).unwrap(), format!("{}+{}", "a".repeat(64), "b".repeat(64))); |
| 1624 | 1× | assert_eq!(state_spec(&[]), None); |
| 1625 | 1× | assert_eq!(state_spec(&vec![a; MAX_STATE_HEADS + 1]), None); |
| 1626 | 1× | let t = RefTarget { label: state_spec(&[a, b]).unwrap(), kind: RefKind::Change, heads: vec![a, b] }; |
| 1627 | 1× | assert_eq!(t.short_label(), format!("{} +1", "a".repeat(12))); |
| 1628 | 1× | assert_eq!(RefTarget { label: "main".into(), kind: RefKind::Bookmark, heads: vec![a] }.short_label(), "main"); |
| 1629 | 1× | } |
| 1630 | | } |