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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
use crate::;
/// Source selection for inferred copies, in addition to deleted rename sources.
///
/// Use `Modified` when an added file may derive from a changed file's previous contents.
/// `ModifiedPostimage` serves consumers comparing against its new contents, but the result's
/// `source_id` still names the old content. Neither option searches unchanged source files.
///
/// ```
/// use std::sync::atomic::AtomicBool;
///
/// use girt::rewrites::{Copies, Kind, Options};
/// use girt::{EntryMode, InitKind, ObjectFormat, Repository, Tree, TreeEntry};
/// let directory = tempfile::tempdir()?;
/// let repo = Repository::init(
/// ObjectFormat::Sha1,
/// directory.path().join("r"),
/// InitKind::Bare,
/// )?;
/// let loose = repo.loose_objects();
/// let original = loose.write_blob(b"original content\n")?;
/// let edited = loose.write_blob(b"changed source\n")?;
/// let entry = |name: &[u8], id| TreeEntry {
/// name: name.to_vec(),
/// mode: EntryMode::Blob,
/// id,
/// };
/// let old = loose.write_tree(&Tree::new(
/// ObjectFormat::Sha1,
/// vec![entry(b"source", original)],
/// )?)?;
/// let new = loose.write_tree(&Tree::new(
/// ObjectFormat::Sha1,
/// vec![entry(b"source", edited), entry(b"copy", original)],
/// )?)?;
/// let copies = repo.objects(Default::default())?.detect_rewrites(
/// Some(old),
/// Some(new),
/// Options::default().with_copies(Copies::Modified),
/// Default::default(),
/// None,
/// &AtomicBool::new(false),
/// )?;
/// assert_eq!(copies.len(), 1);
/// assert_eq!(copies[0].kind, Kind::Copy);
/// assert_eq!(copies[0].source_id, original); // Scored against the source's preimage.
/// assert_eq!(copies[0].target, b"copy");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
/// Caller choices for inference, independent of repository configuration.
///
/// ```
/// use girt::rewrites::{Copies, Options};
/// let exact_copies = Options::default()
/// .with_similarity(100)
/// .with_copies(Copies::Modified)
/// .with_track_empty(true);
/// assert_eq!(exact_copies.similarity, 100); // Identity-only; no approximate scoring.
/// let bounded = Options::default().with_candidate_limit(0);
/// assert_eq!(bounded.candidate_limit, 0); // Skip edited matching if any counted pair remains.
/// ```
/// Resource bounds for a complete inference call, including its structural comparison.
///
/// Memory includes bounded tree comparison storage, retained blob bytes, at most one span per
/// payload byte, candidate pairs and output paths. Span keys have at most 64 bytes, with map-node
/// overhead; these bounds are not exact heap/RSS limits. Allocation failure follows Rust's
/// allocator behavior. No files are written and no handles remain owned by the result.
///
/// Exact-only fallback relaxes the candidate policy, not the independent byte, span, pair or work
/// budgets. Exact selection also charges [`Self::max_pairs`]; exhausting it returns an error from
/// both APIs, as this example demonstrates.
///
/// ```
/// use std::sync::atomic::AtomicBool;
///
/// use girt::rewrites::{Error, Limits, Options};
/// use girt::{EntryMode, InitKind, ObjectFormat, Repository, Tree, TreeEntry};
///
/// let directory = tempfile::tempdir()?;
/// let path = directory.path().join("r");
/// let repo = Repository::init(ObjectFormat::Sha1, path, InitKind::Bare)?;
///
/// let loose = repo.loose_objects();
/// let entry = |name: &[u8], id, mode| TreeEntry {
/// name: name.to_vec(),
/// id,
/// mode,
/// };
/// let tree = |entries| loose.write_tree(&Tree::new(ObjectFormat::Sha1, entries)?);
/// let cancel = AtomicBool::new(false);
///
/// let id = loose.write_blob(b"same")?;
/// let old = tree(vec![entry(b"old", id, EntryMode::Blob)])?;
/// let new = tree(vec![entry(b"new", id, EntryMode::Blob)])?;
/// let result = repo.objects(Default::default())?.detect_rewrites_or_exact(
/// Some(old),
/// Some(new),
/// Options::default().with_candidate_limit(0),
/// Limits::default().with_max_pairs(0),
/// None,
/// &cancel,
/// );
/// assert!(matches!(result, Err(Error::Limit("pairs"))));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
/// How an inferred source is used in this result.
/// One inferred relationship, ordered by destination raw path bytes in returned results.
///
/// Exact object IDs score 100. Edited content is split at LF or after 64 significant bytes;
/// equal spans contribute the minimum occurrence count times span length, divided by the larger
/// raw payload length. Ordering of spans is immaterial. For text (no NUL in the first 8000 bytes),
/// CR immediately preceding LF is omitted. Binary spans preserve CR and all other bytes.
/// Percentages are rounded down; threshold comparison uses the unrounded fraction.
///
/// This independent byte-equality heuristic follows observed Git span behavior, but does not
/// reproduce every observed Git score or pairing shortcut. The repeated-byte discrepancy
/// remains under investigation; its cause has not been established. A score of 100 for edited
/// content can mean reordered spans, not identical bytes. `Options::similarity == 100` requires
/// identity instead. No finite compatibility corpus establishes universal heuristic parity.
///
/// # Postimage copies retain the original source identity
///
/// When a source is edited and its new content is copied, postimage policy can infer the copy. Its
/// score describes the postimage comparison; `source_id` still points at the old source snapshot.
/// Do not use that identity to reconstruct the scored input under postimage policy.
///
/// ```
/// use std::sync::atomic::AtomicBool;
///
/// use girt::rewrites::{Copies, Kind, Options};
/// use girt::{EntryMode, InitKind, ObjectFormat, Repository, Tree, TreeEntry};
///
/// let directory = tempfile::tempdir()?;
/// let path = directory.path().join("r");
/// let repo = Repository::init(ObjectFormat::Sha1, path, InitKind::Bare)?;
///
/// let loose = repo.loose_objects();
/// let entry = |name: &[u8], id, mode| TreeEntry {
/// name: name.to_vec(),
/// id,
/// mode,
/// };
/// let tree = |entries| loose.write_tree(&Tree::new(ObjectFormat::Sha1, entries)?);
/// let cancel = AtomicBool::new(false);
///
/// let before = loose.write_blob(b"before")?;
/// let after = loose.write_blob(b"after")?;
/// let old = tree(vec![entry(b"source", before, EntryMode::Blob)])?;
/// let new = tree(vec![
/// entry(b"source", after, EntryMode::Blob),
/// entry(b"copy", after, EntryMode::Blob),
/// ])?;
/// let records = repo.objects(Default::default())?.detect_rewrites(
/// Some(old),
/// Some(new),
/// Options::default()
/// .with_copies(Copies::ModifiedPostimage)
/// .with_similarity(100),
/// Default::default(),
/// None,
/// &cancel,
/// )?;
/// assert_eq!(records[0].kind, Kind::Copy);
/// assert_eq!(records[0].similarity, 100);
/// assert_eq!(records[0].source_id, before);
/// assert_eq!(records[0].target_id, after);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
/// Inferred rewrites, with an explicit report when edited-content detection was skipped.
///
/// Returned by [`Objects::detect_rewrites_or_exact`](crate::Objects::detect_rewrites_or_exact).
///
/// Always inspect `inexact_skipped` before presenting the result as complete. A UI can retain
/// discovered pairs, leave all other additions/deletions unpaired, and offer a retry using
/// [`InexactSkipped::suggested_limit`]. The [fallback
/// example](crate::Objects::detect_rewrites_or_exact) shows the full lifecycle.
/// Edited-content detection was skipped because too many candidates remained after exact and
/// unique-basename matching.
///
/// Remaining destinations stay unpaired, even where an edited source would match.
/// Inference failed without returning partial records or modifying the repository.
///
/// Callers may raise an exhausted bound or retry cancellation with a cleared flag. Missing/corrupt
/// storage needs repair or a refreshed object view; retrying unchanged inputs does not repair it.
///
/// [`Error::Candidates`] is a policy refusal from the strict API; retry with a chosen larger
/// candidate limit or use [`crate::Objects::detect_rewrites_or_exact`] and report the skip.
/// [`Error::Limit`] instead means a resource budget failed, including during exact matching, and
/// neither API returns partial records. Invalid similarity is a caller error, not corrupt storage.
///
/// ```
/// use std::sync::atomic::AtomicBool;
///
/// use girt::rewrites::{Error, Limits, Options};
/// use girt::{InitKind, ObjectFormat, Repository};
/// let directory = tempfile::tempdir()?;
/// let repo = Repository::init(
/// ObjectFormat::Sha1,
/// directory.path().join("r"),
/// InitKind::Bare,
/// )?;
/// let result = repo.objects(Default::default())?.detect_rewrites(
/// None,
/// None,
/// Options::default().with_similarity(0),
/// Limits::default(),
/// None,
/// &AtomicBool::new(false),
/// );
/// assert!(matches!(result, Err(Error::Similarity(0))));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```