1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Replay one commit onto an explicit destination, without changing repository state.
//!
//! Cherry-pick compares the source with its selected parent; revert reverses that comparison.
//! Both use the rename-aware [`crate::merge`] engine. Results retain generated objects and original
//! conflict sides. Callers install objects and publish references separately.
//!
//! ```
//! use std::sync::atomic::AtomicBool;
//!
//! use girt::replay::{EmptyPolicy, Options, Status};
//! use girt::{Commit, InitKind, ObjectFormat, Repository, Signature, Tree};
//!
//! let temporary = tempfile::tempdir()?;
//! let repo = Repository::init(
//! ObjectFormat::Sha1,
//! temporary.path().join("repo"),
//! InitKind::Bare,
//! )?;
//! let loose = repo.loose_objects();
//! let tree = loose.write_tree(&Tree::new(ObjectFormat::Sha1, vec![])?)?;
//! let writer = Signature {
//! name: b"Writer".to_vec(),
//! email: b"writer@example.com".to_vec(),
//! seconds: 1_700_000_000,
//! offset_minutes: 0,
//! };
//! let source = loose.write_commit(&Commit::builder(tree, writer.clone(), b"empty\n").build()?)?;
//! let mut options = Options::default();
//! options.originally_empty = EmptyPolicy::Keep;
//! let replay =
//! repo.objects()?
//! .cherry_pick(source, source, writer, options, &AtomicBool::new(false))?;
//! assert!(matches!(replay.status, Status::KeptEmpty(_)));
//! for (_, bytes) in &replay.result.blobs {
//! loose.write_blob(bytes)?;
//! }
//! for tree in &replay.result.trees {
//! loose.write_tree(tree)?;
//! }
//! let proposed = replay.commit.expect("kept empty commit");
//! let id = loose.write_commit(&proposed)?;
//! assert_eq!(repo.objects()?.read_commit(id)?.parents(), &[source]);
//! // Installing the object does not move a reference.
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! Empty policy distinguishes an originally empty source (`--allow-empty`) from a nonempty source
//! made redundant by the destination (`--keep-redundant-commits`). Set both policies to keep for
//! the latter Git behavior. Stop and skip retain the candidate tree but propose no commit. Merge
//! limitations and per-comparison bounds are inherited from [`Objects::merge_trees_with`].
use std::num::NonZeroUsize;
use std::sync::atomic::AtomicBool;
mod autosquash;
pub use autosquash::AutosquashError;
mod rebase;
pub mod todo;
mod todo_execute;
pub use rebase::{Rebase, RebaseError, RebaseOptions, RebasedCommit};
pub use todo_execute::{HookError, TodoExecutionError, TodoHooks, TodoRun, TodoStop};
use crate::merge::{TreeMerge, TreeMergeOptions};
use crate::{Commit, ObjectId, Objects, Signature};
/// What to do when a clean replay produces no tree change.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum EmptyPolicy {
/// Return an empty outcome without proposing a commit.
#[default]
Stop,
/// Propose a commit even though its tree equals the destination tree.
Keep,
/// Return a skipped outcome without proposing a commit.
Skip,
}
/// Replay comparison and empty-result policy.
#[derive(Clone, Copy, Debug, Default)]
#[non_exhaustive]
pub struct Options {
/// One-based parent for a merge source. Required for commits with several parents.
pub mainline: Option<NonZeroUsize>,
/// Append Git's cherry-pick provenance line. Ignored for revert.
pub record_origin: bool,
/// Policy for a source whose tree equals its selected parent's tree.
pub originally_empty: EmptyPolicy,
/// Policy for a nonempty source whose replay changes nothing.
pub redundant: EmptyPolicy,
/// Rename-aware merge policy and resource bounds.
pub trees: TreeMergeOptions,
}
/// Why no new tree changes result.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum EmptyKind {
/// The original commit changed no entries relative to the selected parent.
Original,
/// Destination already contains the effect being replayed.
Redundant,
}
/// Replay state, independent of object installation or reference publication.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Status {
/// A clean, nonempty commit is proposed.
Ready,
/// Original merge sides remain available for caller resolution.
Conflicted,
/// Empty policy kept the proposed commit.
KeptEmpty(EmptyKind),
/// Empty policy requires a caller decision.
Empty(EmptyKind),
/// Empty policy skipped this source.
Skipped(EmptyKind),
}
/// Candidate objects and commit metadata from replaying a source onto a destination.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Replay {
/// Original source commit.
pub source: ObjectId,
/// Destination commit, which becomes the proposed commit's sole parent.
pub destination: ObjectId,
/// Candidate tree and original conflict sides, never implicitly installed.
pub result: TreeMerge,
/// Disposition under the selected empty policy.
pub status: Status,
/// Proposed unsigned commit, present only for ready or kept-empty results.
pub commit: Option<Commit>,
}
/// Replay failed without installing objects or changing repository state.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// An input commit could not be read.
#[error("reading replay commit")]
Read(#[from] crate::ReadCommitError),
/// Source metadata or proposed commit is invalid.
#[error("constructing replay commit")]
Commit(#[from] crate::CommitError),
/// Rename-aware merge computation failed.
#[error("merging replay trees")]
Merge(#[from] crate::merge::RenameError),
/// A merge source requires a selected parent.
#[error("merge source requires a mainline parent")]
MainlineRequired,
/// The selected one-based parent does not exist.
#[error("mainline parent is outside the source parent list")]
InvalidMainline,
}
impl Objects {
/// Computes a cherry-pick using source author and explicit new committer metadata.
///
/// Source signatures and opaque headers are not copied. Message bytes are retained, with an
/// optional provenance paragraph. Root sources use an empty base. Merge sources require a
/// one-based mainline. Conflicts never propose a commit; empty policy is applied only after a
/// clean merge. No objects, refs, index or working files are written.
///
/// # Errors
///
/// Returns [`Error`] for invalid mainline, unreadable inputs, invalid metadata or merge
/// failure.
pub fn cherry_pick(
&self,
source: ObjectId,
destination: ObjectId,
committer: Signature,
options: Options,
cancel: &AtomicBool,
) -> Result<Replay, Error> {
self.replay(
[source, destination],
committer,
options,
cancel,
false,
None,
)
}
/// Computes the inverse of a commit, using the supplied identity as author and committer.
///
/// Uses [`Self::cherry_pick`]'s computation and publication contract. The message uses Git's
/// `Revert "subject"` title (`Reapply` when reverting a revert) and full source identity. For
/// merge sources the explanation also names the selected parent. The original commit is the
/// merge base; its parent supplies the inverse side. Root reverts select an empty inverse
/// side.
///
/// # Errors
///
/// Returns [`Error`] for invalid mainline, unreadable inputs, invalid metadata or merge
/// failure.
pub fn revert(
&self,
source: ObjectId,
destination: ObjectId,
committer: Signature,
options: Options,
cancel: &AtomicBool,
) -> Result<Replay, Error> {
self.replay(
[source, destination],
committer,
options,
cancel,
true,
None,
)
}
/// Computes cherry-pick with caller-owned per-path attribute/content policy.
///
/// Uses [`Self::cherry_pick`]'s metadata, bounds and publication contract. No attribute
/// snapshot or external process is selected implicitly; driver side effects remain
/// caller-owned.
///
/// # Errors
///
/// Returns [`Error`], preserving content-driver failures through the merge error source.
pub fn cherry_pick_with_driver(
&self,
source: ObjectId,
destination: ObjectId,
committer: Signature,
options: Options,
cancel: &AtomicBool,
driver: &mut dyn crate::merge::TreeDriver,
) -> Result<Replay, Error> {
self.replay(
[source, destination],
committer,
options,
cancel,
false,
Some(driver),
)
}
/// Computes revert with caller-owned per-path attribute/content policy.
///
/// Uses [`Self::revert`]'s metadata, bounds and publication contract. Driver inputs use the
/// reversed base/side roles; callback side effects remain caller-owned.
///
/// # Errors
///
/// Returns [`Error`], retaining original path-driver failures as merge error sources.
pub fn revert_with_driver(
&self,
source: ObjectId,
destination: ObjectId,
committer: Signature,
options: Options,
cancel: &AtomicBool,
driver: &mut dyn crate::merge::TreeDriver,
) -> Result<Replay, Error> {
self.replay(
[source, destination],
committer,
options,
cancel,
true,
Some(driver),
)
}
fn replay(
&self,
tips: [ObjectId; 2],
committer: Signature,
options: Options,
cancel: &AtomicBool,
reverse: bool,
driver: Option<&mut dyn crate::merge::TreeDriver>,
) -> Result<Replay, Error> {
let [source, destination] = tips;
let original = self.read_commit(source)?;
let onto = self.read_commit(destination)?;
let operation = Operation {
source,
original: &original,
onto: &onto,
committer,
options,
reverse,
};
operation.compute(
self,
cancel,
&mut crate::merge::ReplayTrees::default(),
driver,
)
}
}
struct Operation<'a> {
source: ObjectId,
original: &'a Commit,
onto: &'a Commit,
committer: Signature,
options: Options,
reverse: bool,
}
impl Operation<'_> {
fn compute<'a, 'd>(
self,
objects: &'a Objects,
cancel: &'a AtomicBool,
memory: &'a mut crate::merge::ReplayTrees,
driver: Option<&'a mut (dyn crate::merge::TreeDriver + 'd)>,
) -> Result<Replay, Error> {
let Self {
source,
original,
onto,
committer,
options,
reverse,
} = self;
let destination = onto.id();
let parent = match options.mainline {
Some(number) => Some(
*original
.parents()
.get(number.get() - 1)
.ok_or(Error::InvalidMainline)?,
),
None if original.parents().len() > 1 => return Err(Error::MainlineRequired),
None => original.parents().first().copied(),
};
let parent_tree = parent
.map(|id| objects.read_commit(id).map(|commit| commit.tree()))
.transpose()?;
let empty = crate::Tree::new(objects.object_format(), vec![])
.map_err(crate::merge::TreeError::from)
.map_err(crate::merge::RenameError::from)?;
let parent_tree = parent_tree.unwrap_or(empty.id());
let originally_empty = parent_tree == original.tree();
let (base, theirs) = if reverse {
(original.tree(), parent_tree)
} else {
(parent_tree, original.tree())
};
let result = memory.merge(
objects,
[base, onto.tree(), theirs],
empty,
options.trees,
cancel,
driver,
)?;
let empty_kind = if originally_empty {
EmptyKind::Original
} else {
EmptyKind::Redundant
};
let policy = if originally_empty {
options.originally_empty
} else {
options.redundant
};
let status = if !result.is_clean() {
Status::Conflicted
} else if result.tree.id() != onto.tree() {
Status::Ready
} else {
match policy {
EmptyPolicy::Keep => Status::KeptEmpty(empty_kind),
EmptyPolicy::Stop => Status::Empty(empty_kind),
EmptyPolicy::Skip => Status::Skipped(empty_kind),
}
};
let commit = if matches!(status, Status::Ready | Status::KeptEmpty(_)) {
let author = if reverse {
committer.clone()
} else {
original.to_fields()?.author
};
let message = replay_message(original, source, parent, options.record_origin, reverse);
Some(
Commit::builder(result.tree.id(), author, message)
.parent(destination)
.committer(committer)
.build()?,
)
} else {
None
};
Ok(Replay {
source,
destination,
result,
status,
commit,
})
}
}
fn replay_message(
original: &Commit,
source: ObjectId,
parent: Option<ObjectId>,
origin: bool,
reverse: bool,
) -> Vec<u8> {
if reverse {
let subject = original.subject();
let reverted = subject
.strip_prefix(b"Revert \"")
.and_then(|subject| subject.strip_suffix(b"\""));
let (prefix, subject): (&[u8], &[u8]) = if let Some(subject) = reverted {
(b"Reapply \"", subject)
} else {
(b"Revert \"", &subject)
};
let mut message = prefix.to_vec();
message.extend_from_slice(subject);
message.extend_from_slice(b"\"\n\n");
if original.parents().len() > 1 {
message.extend_from_slice(
format!(
"This reverts commit {source}, reversing\nchanges made to {}.\n",
parent.expect("mainline validated")
)
.as_bytes(),
);
} else {
message.extend_from_slice(format!("This reverts commit {source}.\n").as_bytes());
}
message
} else {
let mut message = original.message().to_vec();
if origin {
while message.last() == Some(&b'\n') {
message.pop();
}
let separator: &[u8] = if has_trailer_footer(&message) {
b"\n"
} else {
b"\n\n"
};
message.extend_from_slice(separator);
message.extend_from_slice(format!("(cherry picked from commit {source})\n").as_bytes());
}
message
}
}
// Git's default footer convention keeps provenance beside trailers. Configuration-specific
// trailer tokens and message cleanup remain caller policy.
fn has_trailer_footer(message: &[u8]) -> bool {
let Some(start) = message.windows(2).rposition(|bytes| bytes == b"\n\n") else {
return false;
};
let paragraph = &message[start + 2..];
let mut lines = 0usize;
let mut trailers = 0usize;
let mut known = false;
let mut continuation = false;
for line in paragraph.split(|&b| b == b'\n') {
lines += 1;
if line.starts_with(b" ") || line.starts_with(b"\t") {
if continuation {
trailers += 1;
}
continue;
}
let cherry = line.starts_with(b"(cherry picked from commit ") && line.ends_with(b")");
let colon = line.iter().position(|&b| b == b':');
let trailer = colon.is_some_and(|colon| {
colon > 0
&& line[..colon]
.iter()
.all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-')
});
continuation = trailer || cherry;
if continuation {
trailers += 1;
}
known |= cherry
|| line
.get(..14)
.is_some_and(|token| token.eq_ignore_ascii_case(b"Signed-off-by:"));
}
trailers == lines || (known && trailers.saturating_mul(4) >= lines)
}