docs/generated/contracts.mdgenerated from code
Reference · 4 min read
protect
Contracts: protect.
Read as
Source: crates/lvcs-doc/src/paths/protect.rs.
1/// The protected-path rule in force (discussion:owner/122 and discussion:owner/378): which files2/// change only as an approval says.3///4/// A file is protected when lvcs-doc's `paths::protected()`5/// (`DEFAULT_PROTECTED`) matches it, or the policy's lines do: each path6/// an action in force runs (`lvcs_action::config::Actions::runs`), as a7/// literal rooted at the project, and each `[protect] paths` line of main's8/// approved `lvcs.toml`. Both match ASCII case-insensitively against `path`9/// with each `/`-separated segment in NFKC and then lowercased (10/// discussion:owner/130), because a filesystem that folds Unicode case resolves `build.rſ`11/// (U+017F) or `Cargo.loc` with U+212A (KELVIN SIGN) to the protected12/// file. A segment whose fold is not a name (`.`, `..`, or holding a `/`,13/// as U+2024 ONE DOT LEADER and U+FF0F FULLWIDTH SOLIDUS can make it) keeps14/// its own spelling, since no filesystem resolves it as its fold, so the15/// path keeps its segments and every path the ASCII rule protects stays16/// protected. [`Protected::default`] is the defaults alone.17#[derive(Debug, Clone, Default)]18pub struct Protected {19 /// The policy's lines, `None` when it has none.20 policy: Option<PathSet>,21}2223impl Protected {24 /// The defaults with `runs`, each a plain relative path, and `lines`,25 /// gitignore lines.26 ///27 /// # Errors28 ///29 /// When a line of `lines` isn't gitignore syntax.30 pub fn new<'a>(31 runs: impl IntoIterator<Item = &'a str>,32 lines: &[String],33 ) -> Result<Self, PathSetError> {34 let all: Vec<String> = runs35 .into_iter()36 .map(|path| format!("/{}", escape(&fold(path))))37 .chain(lines.iter().cloned())38 .collect();39 if all.is_empty() {40 return Ok(Self::default());41 }42 Ok(Self {43 policy: Some(PathSet::new(all, true)?),44 })45 }4647 /// Whether the file at `path` is protected.48 #[must_use]49 pub fn matches(&self, path: &str) -> bool {50 let folded = fold(path);51 paths::protected().matches(&folded)52 || self53 .policy54 .as_ref()55 .is_some_and(|policy| policy.matches(&folded))56 }57}5859/// `path` as a gitignore line's text matching only itself: each character60/// gitignore gives a meaning is escaped.61fn escape(path: &str) -> String {62 let mut line = String::with_capacity(path.len());63 for c in path.chars() {64 if matches!(c, '*' | '?' | '[' | ']' | '\\' | '!' | '#' | ' ') {65 line.push('\\');66 }67 line.push(c);68 }69 line70}7172/// What the gate decides one render of a protected path to one tree from.73#[derive(Debug, Clone, PartialEq, Eq)]74pub struct GateInput {75 /// The render's heads.76 pub render_heads: Vec<ChangeId>,77 /// The path's approved heads, or `None` when it has none.78 pub approved: Option<Vec<ChangeId>>,79 /// The signers of every change beyond the approved heads.80 pub signers_beyond: BTreeSet<PeerKey>,81 /// A change beyond the approved heads names no author id82 /// (`ReadAtOutcome::Read.unattributed`, or one the shell can't map).83 pub unattributed: bool,84 /// The tree's author.85 pub tree_file_author: PeerKey,86}8788/// What the shell sends the tree in place of the render.89#[derive(Debug, Clone, Copy, PartialEq, Eq)]90pub enum GateDecision {91 /// The render itself.92 Deliver,93 /// A render at the approved heads, carrying the gated render's `after`.94 Release,95 /// A `Held`, carrying the gated render's `after`.96 Hold,97}9899/// discussion:owner/122's gate over one render of a protected path to one tree.100///101/// `Hold` when `approved` is `None` or `unattributed` is set; `Deliver`102/// when `render_heads` equals `approved` (as sets of heads), or when every103/// signer beyond the approved heads is `tree_file_author`; `Release` when none of them is `tree_file_author`; otherwise `Hold`.104#[must_use]105pub fn gate(input: &GateInput) -> GateDecision {106 let listed = match &input.approved {107 Some(listed) if !input.unattributed => listed,108 _ => return GateDecision::Hold,109 };110 let approved: BTreeSet<&ChangeId> = listed.iter().collect();111 let render: BTreeSet<&ChangeId> = input.render_heads.iter().collect();112 let author = &input.tree_file_author;113 let authors_own = input.signers_beyond.iter().all(|signer| signer == author);114 if render == approved || authors_own {115 GateDecision::Deliver116 } else if !input.signers_beyond.contains(author) {117 GateDecision::Release118 } else {119 GateDecision::Hold120 }121}122123/// The peers a gate decision on one protected path holds on one tree124/// (row 425): on `Hold` or `Release`, each signer beyond the approved125/// heads but the tree's author, with the span of its changes there;126/// none on `Deliver`.127#[must_use]128pub fn holding(129 decision: GateDecision,130 spans: &BTreeMap<PeerKey, TimeSpan>,131 tree_file_author: &PeerKey,132) -> BTreeMap<PeerKey, TimeSpan> {133 match decision {134 GateDecision::Deliver => BTreeMap::new(),135 GateDecision::Hold | GateDecision::Release => spans136 .iter()137 .filter(|(signer, _)| *signer != tree_file_author)138 .map(|(signer, span)| (*signer, *span))139 .collect(),140 }141}142143/// Row 425's windows on one tree: for each peer some protected path144/// holds there, the span from its earliest held change less `QUIET_MS`145/// to its latest plus `QUIET_MS`, over every path's `holding`.146#[must_use]147pub fn windows<'a>(148 holding: impl IntoIterator<Item = &'a BTreeMap<PeerKey, TimeSpan>>,149) -> BTreeMap<PeerKey, TimeSpan> {150 let quiet = i64::try_from(QUIET_MS).unwrap_or(i64::MAX);151 let mut windows: BTreeMap<PeerKey, TimeSpan> = BTreeMap::new();152 for (signer, span) in holding.into_iter().flatten() {153 let wide = TimeSpan {154 first_ms: span.first_ms.saturating_sub(quiet),155 last_ms: span.last_ms.saturating_add(quiet),156 };157 windows158 .entry(*signer)159 .and_modify(|window| {160 window.first_ms = window.first_ms.min(wide.first_ms);161 window.last_ms = window.last_ms.max(wide.last_ms);162 })163 .or_insert(wide);164 }165 windows166}167168/// The cuts an unprotected file renders at on a tree with `windows`169/// (row 425): one per signer, over its window.170#[must_use]171pub fn cuts(windows: &BTreeMap<PeerKey, TimeSpan>) -> Vec<Cut> {172 windows173 .iter()174 .map(|(signer, window)| Cut {175 authors: BTreeSet::from([*signer]),176 from_ms: window.first_ms,177 to_ms: window.last_ms,178 })179 .collect()180}