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