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