Elffuss BraidHub

utopia-ia/elffuss-braid public

356f55034aff · 11.1 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Making a changeset without a working copy, reverting one, and landing
5//! one.
6//!
7//! An agent that knows which files it wants to change does not need a
8//! checkout: it names the base, the new contents and the deletions, and can
9//! state what it expects the base to hold at each path, so that it never
10//! overwrites an edit it did not see.
11
12use braid_engine::{EMPTY_TREE, LandOutcome, REVERTS, diff, entry_at, land, read_changeset};
13use braid_format::{Change, ChangeOp, EntryKind, Kind, ObjectId, Objects, validate_path};
14use braid_store::{RefUpdate, Store, TransactError};
15
16use crate::error::Error;
17use crate::identity::Identity;
18use crate::workspace::{LandReport, Landed, Placed, describe_landing};
19
20/// What the base must hold at a path.
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum Expect {
23 /// A file, executable or symlink with this blob.
24 Blob(ObjectId),
25 /// Nothing: no file and no directory.
26 Absent,
27}
28
29/// A changeset to make.
30#[derive(Clone, Debug)]
31pub struct ChangeRequest {
32 /// The changeset to build on; `None` for a first changeset.
33 pub base: Option<ObjectId>,
34 /// Paths to set, with their new contents. A path that is an executable
35 /// in the base stays executable.
36 pub sets: Vec<(Vec<u8>, Vec<u8>)>,
37 /// Paths to delete.
38 pub deletes: Vec<Vec<u8>>,
39 /// What the base must hold, checked before anything is stored.
40 pub expects: Vec<(Vec<u8>, Expect)>,
41 /// The message.
42 pub message: Vec<u8>,
43 /// The author, who also commits it.
44 pub author: Identity,
45 /// The label of the agent making it, recorded as its
46 /// [`AGENT`](braid_engine::AGENT) field.
47 pub agent: String,
48}
49
50/// Checks the expectations against the base, stores the contents and the
51/// changeset, makes it durable, and returns its id.
52pub fn create_change(store: &Store, request: &ChangeRequest) -> Result<ObjectId, Error> {
53 let base_root = match request.base {
54 Some(base) => read_changeset(store, base)?.root,
55 None => EMPTY_TREE,
56 };
57 for path in request
58 .sets
59 .iter()
60 .map(|(path, _)| path)
61 .chain(&request.deletes)
62 .chain(request.expects.iter().map(|(path, _)| path))
63 {
64 validate_path(path).map_err(|error| Error::InvalidPath {
65 path: path.clone(),
66 error,
67 })?;
68 }
69 for (path, expect) in &request.expects {
70 let found = entry_at(store, base_root, path)?;
71 let matches = match (expect, &found) {
72 (Expect::Absent, None) => true,
73 (
74 Expect::Blob(want),
75 Some(
76 EntryKind::File { blob, .. }
77 | EntryKind::Executable { blob, .. }
78 | EntryKind::Symlink { blob, .. },
79 ),
80 ) => want == blob,
81 _ => false,
82 };
83 if !matches {
84 return Err(Error::ExpectationFailed {
85 path: path.clone(),
86 expected: match expect {
87 Expect::Blob(id) => id.to_hex(),
88 Expect::Absent => "absent".to_owned(),
89 },
90 found: describe(found.as_ref()),
91 });
92 }
93 }
94 let mut changes = Vec::with_capacity(request.sets.len() + request.deletes.len());
95 for (path, content) in &request.sets {
96 let blob = store.put(Kind::Blob, content)?;
97 let size = content.len() as u64;
98 let executable = matches!(
99 entry_at(store, base_root, path)?,
100 Some(EntryKind::Executable { .. })
101 );
102 changes.push(Change {
103 path: path.clone(),
104 op: if executable {
105 ChangeOp::Executable { blob, size }
106 } else {
107 ChangeOp::File { blob, size }
108 },
109 });
110 }
111 for path in &request.deletes {
112 changes.push(Change {
113 path: path.clone(),
114 op: ChangeOp::Delete,
115 });
116 }
117 let signature = request.author.now();
118 let id = braid_engine::commit(
119 store,
120 request.base.into_iter().collect(),
121 changes,
122 signature.clone(),
123 signature,
124 request.message.clone(),
125 crate::rebase::agent_extras(&request.agent),
126 )?;
127 store.sync()?;
128 Ok(id)
129}
130
131/// A revert to make: a changeset that undoes another.
132#[derive(Clone, Debug)]
133pub struct RevertRequest {
134 /// The changeset to undo.
135 pub culprit: ObjectId,
136 /// Whether the changeset is a merge to revert against its first parent:
137 /// the revert undoes what the merge brought in. A merge is refused
138 /// without it, and anything but a merge with it.
139 pub mainline: bool,
140 /// The author, who also commits it.
141 pub author: Identity,
142 /// The label of the agent making it, recorded as its
143 /// [`AGENT`](braid_engine::AGENT) field.
144 pub agent: String,
145}
146
147/// Makes the revert of `request.culprit` (C), and returns its id: a
148/// changeset whose only parent is C, whose changes turn C's tree back into
149/// its first parent's, modes, symlinks and gitlinks included, with the
150/// message `Revert "<C's subject>"` and a [`REVERTS`] field naming C.
151///
152/// It is stored but not landed. [`land_change`] lands it like any change:
153/// on a branch that moved past C, the rebase merges each path with C as the
154/// base, the head as ours and C's parent as theirs, which is what undoing C
155/// on top of later work means; a later change to the same lines is a
156/// conflict.
157///
158/// A changeset without parents, one that changes nothing, and a merge
159/// unless [`RevertRequest::mainline`] says so, are refused, as is
160/// [`RevertRequest::mainline`] for a changeset that is not a merge.
161pub fn create_revert(store: &Store, request: &RevertRequest) -> Result<ObjectId, Error> {
162 let culprit = request.culprit;
163 let changeset = read_changeset(store, culprit)?;
164 let mut message = format!("Revert \"{}\"", subject(&changeset.message)).into_bytes();
165 message.extend_from_slice(format!("\n\nThis reverts changeset {culprit}.\n").as_bytes());
166 create_revert_with_message(store, request, &message)
167}
168
169/// Makes the revert of `request.culprit` as [`create_revert`] does, with the
170/// same parent, changes, extra fields and refusals, but with `message` for
171/// its message.
172pub fn create_revert_with_message(
173 store: &Store,
174 request: &RevertRequest,
175 message: &[u8],
176) -> Result<ObjectId, Error> {
177 let culprit = request.culprit;
178 let changeset = read_changeset(store, culprit)?;
179 let parent = match changeset.parents.as_slice() {
180 [] => return Err(Error::RevertRoot(culprit)),
181 [_] if request.mainline => return Err(Error::NotAMerge(culprit)),
182 [parent] => *parent,
183 [parent, ..] if request.mainline => *parent,
184 parents => {
185 return Err(Error::RevertMerge {
186 changeset: culprit,
187 parents: parents.len(),
188 });
189 }
190 };
191 let parent_root = read_changeset(store, parent)?.root;
192 let changes = diff(store, changeset.root, parent_root)?;
193 if changes.is_empty() {
194 return Err(Error::NothingToRevert(culprit));
195 }
196 let mut extras = crate::rebase::agent_extras(&request.agent);
197 extras.push((REVERTS.to_vec(), culprit.to_hex().into_bytes()));
198 let signature = request.author.now();
199 let id = braid_engine::commit(
200 store,
201 vec![culprit],
202 changes,
203 signature.clone(),
204 signature,
205 message.to_vec(),
206 extras,
207 )?;
208 store.sync()?;
209 Ok(id)
210}
211
212/// The first line of a message that is not blank, trimmed.
213fn subject(message: &[u8]) -> String {
214 String::from_utf8_lossy(message)
215 .lines()
216 .map(str::trim)
217 .find(|line| !line.is_empty())
218 .unwrap_or("")
219 .to_owned()
220}
221
222fn describe(entry: Option<&EntryKind>) -> String {
223 match entry {
224 None => "absent".to_owned(),
225 Some(EntryKind::Tree { .. }) => "a directory".to_owned(),
226 Some(EntryKind::Gitlink { .. }) => "a gitlink".to_owned(),
227 Some(
228 EntryKind::File { blob, .. }
229 | EntryKind::Executable { blob, .. }
230 | EntryKind::Symlink { blob, .. },
231 ) => blob.to_hex(),
232 }
233}
234
235/// Lands `change` on `branch` in one op log transaction: the engine
236/// fast-forwards or rebases it onto the head, and the branch moves with a
237/// compare-and-swap. The operation says how it went, as a workspace's
238/// landing does. With conflicts, or when the branch already has it, the
239/// branch does not move and no operation is recorded.
240pub fn land_change(
241 store: &Store,
242 branch: &str,
243 change: ObjectId,
244 agent: &str,
245 committer: &Identity,
246) -> Result<LandReport, Error> {
247 let signature = committer.now();
248 let mut head_before = None;
249 let mut landed = Landed::Nothing;
250 let mut merged = Vec::new();
251 let prefix = format!("land changeset on {branch}");
252 let result = store.transact_with(agent, |refs| {
253 let head = refs.get(branch);
254 head_before = head;
255 let (new, outcome) =
256 match land(store, head, change, signature).map_err(|err| Some(err.into()))? {
257 LandOutcome::FastForward(id) => {
258 landed = Landed::FastForward(id);
259 (id, "fast-forward")
260 }
261 LandOutcome::Rebased {
262 changeset,
263 merged_paths,
264 } => {
265 landed = Landed::Rebased(changeset);
266 merged = merged_paths;
267 (changeset, "rebased")
268 }
269 LandOutcome::AlreadyApplied => {
270 landed = Landed::AlreadyApplied;
271 return Err(None);
272 }
273 LandOutcome::Conflicts(conflicts) => {
274 landed = Landed::Conflicts { change, conflicts };
275 return Err(None);
276 }
277 };
278 let placed = [Placed {
279 from: change,
280 to: Some(new),
281 }];
282 let description = describe_landing(&prefix, outcome, &placed, merged.len());
283 Ok((vec![RefUpdate::new(branch, head, Some(new))], description))
284 });
285 let operation = match result {
286 Ok(op) => Some(op.seq),
287 // The branch stays where it is.
288 Err(TransactError::Aborted(None)) => None,
289 Err(TransactError::Aborted(Some(err))) => return Err(err),
290 Err(TransactError::Store(err)) => return Err(err.into()),
291 };
292 let to = match &landed {
293 Landed::FastForward(id) | Landed::Rebased(id) => Some(*id),
294 _ => None,
295 };
296 Ok(LandReport {
297 branch: branch.to_owned(),
298 head_before,
299 landed,
300 operation,
301 placed: vec![Placed { from: change, to }],
302 merged_paths: merged,
303 updated_paths: Vec::new(),
304 })
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310
311 #[test]
312 fn describing_entries() {
313 assert_eq!(describe(None), "absent");
314 assert_eq!(subject(b"\n Fix the parser \nmore\n"), "Fix the parser");
315 assert_eq!(subject(b""), "");
316 let blob = ObjectId::hash(Kind::Blob, b"x");
317 assert_eq!(
318 describe(Some(&EntryKind::File { blob, size: 1 })),
319 blob.to_hex()
320 );
321 }
322}