Skip to main content

surjection_core/store/
trailers.rs

1//! `Surjection-*` git trailers on store commits (SPEC 9.2):
2//!
3//! ```text
4//! server: update github (env.GITHUB_TOOLSETS)
5//!
6//! Surjection-Op: server.update
7//! Surjection-Entity: server/github
8//! Surjection-Scope: system
9//! Surjection-Machine: <machine-id> (<label>)
10//! Surjection-Client: surject-cli/0.1.0
11//! Surjection-Apply: <apply-id> ok
12//! ```
13//!
14//! A bulk change lists one `Surjection-Entity` per entity. Unknown `Surjection-*`
15//! trailers from a newer build are kept in [`Trailers::other`].
16
17use std::fmt;
18
19use crate::brand::TRAILER_PREFIX;
20use crate::model::applied::ApplyOutcome;
21
22const OP: &str = "Op";
23const ENTITY: &str = "Entity";
24const SCOPE: &str = "Scope";
25const MACHINE: &str = "Machine";
26const CLIENT: &str = "Client";
27const APPLY: &str = "Apply";
28
29/// The layer a commit changed.
30#[derive(Debug, Clone, PartialEq, Eq, Hash)]
31pub enum Scope {
32    /// User-wide desired state (`system`).
33    System,
34    /// One project (`project/<id>`).
35    Project(String),
36    /// A value this build does not know, kept as written.
37    Other(String),
38}
39
40impl Scope {
41    pub fn parse(text: &str) -> Self {
42        if text == "system" {
43            return Self::System;
44        }
45        match text.split_once('/') {
46            Some(("project", id)) if !id.is_empty() => Self::Project(id.to_owned()),
47            _ => Self::Other(text.to_owned()),
48        }
49    }
50}
51
52impl fmt::Display for Scope {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        match self {
55            Self::System => f.write_str("system"),
56            Self::Project(id) => write!(f, "project/{id}"),
57            Self::Other(text) => f.write_str(text),
58        }
59    }
60}
61
62/// `Surjection-Machine: <machine-id> (<label>)`.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct MachineRef {
65    pub id: String,
66    pub label: String,
67}
68
69/// `Surjection-Apply: <apply-id> <outcome>`.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct ApplyRef {
72    pub id: String,
73    pub outcome: ApplyOutcome,
74}
75
76/// The `Surjection-*` trailers of one commit.
77#[derive(Debug, Clone, Default, PartialEq, Eq)]
78pub struct Trailers {
79    /// Operation (`server.add`, `store.init`).
80    pub op: Option<String>,
81    /// Changed entities (`server/github`), one per trailer line.
82    pub entities: Vec<String>,
83    pub scope: Option<Scope>,
84    pub machine: Option<MachineRef>,
85    /// Program and version that made the change (`surject-cli/0.1.0`).
86    pub client: Option<String>,
87    pub apply: Option<ApplyRef>,
88    /// Other `Surjection-*` trailers in order, keys without the prefix.
89    pub other: Vec<(String, String)>,
90}
91
92impl Trailers {
93    /// Trailer lines (`Surjection-Op: server.add`), each ending in `\n`.
94    /// Line breaks inside values become spaces.
95    pub fn format(&self) -> String {
96        let mut lines: Vec<(&str, String)> = Vec::new();
97        if let Some(op) = &self.op {
98            lines.push((OP, op.clone()));
99        }
100        for entity in &self.entities {
101            lines.push((ENTITY, entity.clone()));
102        }
103        if let Some(scope) = &self.scope {
104            lines.push((SCOPE, scope.to_string()));
105        }
106        if let Some(machine) = &self.machine {
107            lines.push((MACHINE, format!("{} ({})", machine.id, machine.label)));
108        }
109        if let Some(client) = &self.client {
110            lines.push((CLIENT, client.clone()));
111        }
112        if let Some(apply) = &self.apply {
113            lines.push((
114                APPLY,
115                format!("{} {}", apply.id, outcome_str(apply.outcome)),
116            ));
117        }
118        for (key, value) in &self.other {
119            lines.push((key, value.clone()));
120        }
121        lines
122            .into_iter()
123            .map(|(key, value)| format!("{TRAILER_PREFIX}{key}: {}\n", one_line(&value)))
124            .collect()
125    }
126
127    /// Reads the `Surjection-*` trailers (and the `Loadout-*` ones of 1.0.x
128    /// commits) from the last paragraph of a commit
129    /// message. Other trailers are ignored; a message without a trailer
130    /// paragraph yields empty trailers.
131    pub fn parse(message: &str) -> Self {
132        let mut trailers = Self::default();
133        for (key, value) in trailer_block(message) {
134            let Some(key) = key
135                .strip_prefix(TRAILER_PREFIX)
136                .or_else(|| key.strip_prefix(crate::brand::legacy::TRAILER_PREFIX))
137            else {
138                continue;
139            };
140            match key {
141                OP if trailers.op.is_none() => trailers.op = Some(value.to_owned()),
142                ENTITY => trailers.entities.push(value.to_owned()),
143                SCOPE if trailers.scope.is_none() => trailers.scope = Some(Scope::parse(value)),
144                MACHINE if trailers.machine.is_none() => {
145                    trailers.machine = Some(parse_machine(value));
146                }
147                CLIENT if trailers.client.is_none() => trailers.client = Some(value.to_owned()),
148                APPLY if trailers.apply.is_none() && parse_apply(value).is_some() => {
149                    trailers.apply = parse_apply(value);
150                }
151                _ => trailers.other.push((key.to_owned(), value.to_owned())),
152            }
153        }
154        trailers
155    }
156
157    pub fn is_empty(&self) -> bool {
158        *self == Self::default()
159    }
160}
161
162/// A full commit message: `summary`, a blank line and the trailers.
163pub fn compose_message(summary: &str, trailers: &Trailers) -> String {
164    let summary = one_line(summary);
165    if trailers.is_empty() {
166        format!("{summary}\n")
167    } else {
168        format!("{summary}\n\n{}", trailers.format())
169    }
170}
171
172/// The first line of a commit message.
173pub fn message_summary(message: &str) -> &str {
174    message.lines().next().unwrap_or("").trim_end()
175}
176
177fn one_line(value: &str) -> String {
178    value
179        .split(['\r', '\n'])
180        .filter(|part| !part.is_empty())
181        .collect::<Vec<_>>()
182        .join(" ")
183}
184
185const fn outcome_str(outcome: ApplyOutcome) -> &'static str {
186    match outcome {
187        ApplyOutcome::Ok => "ok",
188        ApplyOutcome::Partial => "partial",
189        ApplyOutcome::Blocked => "blocked",
190        ApplyOutcome::Failed => "failed",
191    }
192}
193
194fn parse_machine(value: &str) -> MachineRef {
195    let (id, rest) = value.split_once(' ').unwrap_or((value, ""));
196    let rest = rest.trim();
197    let label = rest
198        .strip_prefix('(')
199        .and_then(|rest| rest.strip_suffix(')'))
200        .unwrap_or(rest);
201    MachineRef {
202        id: id.to_owned(),
203        label: label.to_owned(),
204    }
205}
206
207fn parse_apply(value: &str) -> Option<ApplyRef> {
208    let (id, outcome) = value.split_once(' ')?;
209    let outcome = [
210        ApplyOutcome::Ok,
211        ApplyOutcome::Partial,
212        ApplyOutcome::Blocked,
213        ApplyOutcome::Failed,
214    ]
215    .into_iter()
216    .find(|candidate| outcome_str(*candidate) == outcome.trim())?;
217    Some(ApplyRef {
218        id: id.to_owned(),
219        outcome,
220    })
221}
222
223/// `(key, value)` pairs of the trailer paragraph: the last paragraph, when it
224/// is not the summary and every line is `Token: value`.
225fn trailer_block(message: &str) -> Vec<(&str, &str)> {
226    let lines: Vec<&str> = message.lines().map(str::trim_end).collect();
227    let end = lines
228        .iter()
229        .rposition(|line| !line.is_empty())
230        .map_or(0, |i| i + 1);
231    let start = lines[..end]
232        .iter()
233        .rposition(|line| line.is_empty())
234        .map_or(0, |i| i + 1);
235    if start == 0 {
236        return Vec::new();
237    }
238    lines[start..end]
239        .iter()
240        .map(|line| {
241            let (key, value) = line.split_once(':')?;
242            let token =
243                !key.is_empty() && key.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-');
244            token.then(|| (key, value.trim()))
245        })
246        .collect::<Option<Vec<_>>>()
247        .unwrap_or_default()
248}