Elffuss BraidHub

utopia-ia/elffuss-braid public

2da7deeea818 · 10.5 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 a merge may be reverted. Its revert undoes what it brought
137 /// in against its first parent.
138 pub allow_merge: bool,
139 /// The author, who also commits it.
140 pub author: Identity,
141 /// The label of the agent making it, recorded as its
142 /// [`AGENT`](braid_engine::AGENT) field.
143 pub agent: String,
144}
145
146/// Makes the revert of `request.culprit` (C), and returns its id: a
147/// changeset whose only parent is C, whose changes turn C's tree back into
148/// its first parent's, modes, symlinks and gitlinks included, with the
149/// message `Revert "<C's subject>"` and a [`REVERTS`] field naming C.
150///
151/// It is stored but not landed. [`land_change`] lands it like any change:
152/// on a branch that moved past C, the rebase merges each path with C as the
153/// base, the head as ours and C's parent as theirs, which is what undoing C
154/// on top of later work means; a later change to the same lines is a
155/// conflict.
156///
157/// A changeset without parents, one that changes nothing, and a merge
158/// unless [`RevertRequest::allow_merge`] says so, are refused.
159pub fn create_revert(store: &Store, request: &RevertRequest) -> Result<ObjectId, Error> {
160 let culprit = request.culprit;
161 let changeset = read_changeset(store, culprit)?;
162 let parent = match changeset.parents.as_slice() {
163 [] => return Err(Error::RevertRoot(culprit)),
164 [parent] => *parent,
165 [parent, ..] if request.allow_merge => *parent,
166 parents => {
167 return Err(Error::RevertMerge {
168 changeset: culprit,
169 parents: parents.len(),
170 });
171 }
172 };
173 let parent_root = read_changeset(store, parent)?.root;
174 let changes = diff(store, changeset.root, parent_root)?;
175 if changes.is_empty() {
176 return Err(Error::NothingToRevert(culprit));
177 }
178 let mut message = format!("Revert \"{}\"", subject(&changeset.message)).into_bytes();
179 message.extend_from_slice(format!("\n\nThis reverts changeset {culprit}.\n").as_bytes());
180 let mut extras = crate::rebase::agent_extras(&request.agent);
181 extras.push((REVERTS.to_vec(), culprit.to_hex().into_bytes()));
182 let signature = request.author.now();
183 let id = braid_engine::commit(
184 store,
185 vec![culprit],
186 changes,
187 signature.clone(),
188 signature,
189 message,
190 extras,
191 )?;
192 store.sync()?;
193 Ok(id)
194}
195
196/// The first line of a message that is not blank, trimmed.
197fn subject(message: &[u8]) -> String {
198 String::from_utf8_lossy(message)
199 .lines()
200 .map(str::trim)
201 .find(|line| !line.is_empty())
202 .unwrap_or("")
203 .to_owned()
204}
205
206fn describe(entry: Option<&EntryKind>) -> String {
207 match entry {
208 None => "absent".to_owned(),
209 Some(EntryKind::Tree { .. }) => "a directory".to_owned(),
210 Some(EntryKind::Gitlink { .. }) => "a gitlink".to_owned(),
211 Some(
212 EntryKind::File { blob, .. }
213 | EntryKind::Executable { blob, .. }
214 | EntryKind::Symlink { blob, .. },
215 ) => blob.to_hex(),
216 }
217}
218
219/// Lands `change` on `branch` in one op log transaction: the engine
220/// fast-forwards or rebases it onto the head, and the branch moves with a
221/// compare-and-swap. The operation says how it went, as a workspace's
222/// landing does. With conflicts, or when the branch already has it, the
223/// branch does not move and no operation is recorded.
224pub fn land_change(
225 store: &Store,
226 branch: &str,
227 change: ObjectId,
228 agent: &str,
229 committer: &Identity,
230) -> Result<LandReport, Error> {
231 let signature = committer.now();
232 let mut head_before = None;
233 let mut landed = Landed::Nothing;
234 let mut merged = Vec::new();
235 let prefix = format!("land changeset on {branch}");
236 let result = store.transact_with(agent, |refs| {
237 let head = refs.get(branch);
238 head_before = head;
239 let (new, outcome) =
240 match land(store, head, change, signature).map_err(|err| Some(err.into()))? {
241 LandOutcome::FastForward(id) => {
242 landed = Landed::FastForward(id);
243 (id, "fast-forward")
244 }
245 LandOutcome::Rebased {
246 changeset,
247 merged_paths,
248 } => {
249 landed = Landed::Rebased(changeset);
250 merged = merged_paths;
251 (changeset, "rebased")
252 }
253 LandOutcome::AlreadyApplied => {
254 landed = Landed::AlreadyApplied;
255 return Err(None);
256 }
257 LandOutcome::Conflicts(conflicts) => {
258 landed = Landed::Conflicts { change, conflicts };
259 return Err(None);
260 }
261 };
262 let placed = [Placed {
263 from: change,
264 to: Some(new),
265 }];
266 let description = describe_landing(&prefix, outcome, &placed, merged.len());
267 Ok((vec![RefUpdate::new(branch, head, Some(new))], description))
268 });
269 let operation = match result {
270 Ok(op) => Some(op.seq),
271 // The branch stays where it is.
272 Err(TransactError::Aborted(None)) => None,
273 Err(TransactError::Aborted(Some(err))) => return Err(err),
274 Err(TransactError::Store(err)) => return Err(err.into()),
275 };
276 let to = match &landed {
277 Landed::FastForward(id) | Landed::Rebased(id) => Some(*id),
278 _ => None,
279 };
280 Ok(LandReport {
281 branch: branch.to_owned(),
282 head_before,
283 landed,
284 operation,
285 placed: vec![Placed { from: change, to }],
286 merged_paths: merged,
287 updated_paths: Vec::new(),
288 })
289}
290
291#[cfg(test)]
292mod tests {
293 use super::*;
294
295 #[test]
296 fn describing_entries() {
297 assert_eq!(describe(None), "absent");
298 assert_eq!(subject(b"\n Fix the parser \nmore\n"), "Fix the parser");
299 assert_eq!(subject(b""), "");
300 let blob = ObjectId::hash(Kind::Blob, b"x");
301 assert_eq!(
302 describe(Some(&EntryKind::File { blob, size: 1 })),
303 blob.to_hex()
304 );
305 }
306}