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