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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
//! Read and publish individual compressed Git objects.
//!
//! Use [`LooseObjects`] when writing individual blobs, trees, commits, and annotated tags, or when
//! inspecting loose storage specifically. Each file contains a zlib-compressed Git header and
//! payload. Its path is derived from its identity. For general reads use [`crate::Objects`], which
//! also searches packs and configured alternates. A loose-only read can report absence after a
//! repository is packed.
//!
//! # Store bytes without a complete repository
//!
//! ```
//! use girt::{LooseObjects, ObjectFormat};
//! let directory = tempfile::tempdir()?;
//! let objects = LooseObjects::new(directory.path(), ObjectFormat::Sha256);
//! let id = objects.write_blob(b"binary\0payload\xff")?;
//! assert_eq!(objects.read_blob(id, 1024)?, b"binary\0payload\xff");
//! # Ok::<(), girt::loose::Error>(())
//! ```
//!
//! Supply the correct format: the object directory itself carries no format metadata. Repository
//! callers should obtain this handle from [`crate::Repository::loose_objects`]. Writes publish
//! objects without changing refs or the working tree. Duplicate writes compare existing content;
//! they do not silently overwrite a conflicting object.
//!
//! # Errors and filesystem assumptions
//!
//! [`Error`] distinguishes I/O, malformed framing, wrong kind, hash mismatch, size limits, and
//! payload parsing. A payload-size refusal calls for an explicit budget decision; a hash mismatch
//! calls for investigation of storage, not a larger limit. For a missing packed-only object, use
//! the combined reader. Typed reads parse payloads but retain each codec's separate validation
//! contract.
//!
//! Operations block the calling thread. Reads allocate up to the selected payload limit; writes
//! encode and compress caller bytes. The directory and ancestors must be trusted against hostile
//! replacement. Publishing needs a rename that refuses to replace an existing path, or hard links
//! where the platform lacks one; it does not promise power-loss durability and does not implement
//! Git's shared-repository permission policy. See [`LooseObjects`] for the full
//! storage contract.
#![warn(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::unreachable,
clippy::indexing_slicing,
reason = "parses untrusted repository or network input (#103)"
)]
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read, Write};
use std::path::PathBuf;
use flate2::write::ZlibEncoder;
use flate2::{Compression, Decompress, FlushDecompress, Status};
use tempfile::{NamedTempFile, PersistError};
use crate::object::object_header;
/// zlib level for new loose objects: best speed, Git's default when neither `core.looseCompression`
/// nor `core.compression` is set. Loose objects are short-lived until a repack recompresses them.
const LOOSE_COMPRESSION: Compression = Compression::fast();
use crate::{
Commit, CommitError, ObjectFormat, ObjectId, ObjectKind, Tag, TagError, Tree, TreeError,
};
/// Reads and writes loose blobs, trees, commits, and tags beneath an explicitly selected
/// object directory.
///
/// This owns the path to an object directory, usually `.git/objects`. Callers select the directory
/// and supply its known object format; no repository configuration is inspected. Operations are
/// synchronous and block the calling thread.
///
/// # Example
///
/// ```
/// use girt::{LooseObjects, ObjectFormat, ObjectId};
///
/// // A disposable object directory; no repository discovery or Git executable is needed.
/// let directory = tempfile::tempdir()?;
/// let objects = LooseObjects::new(directory.path(), ObjectFormat::Sha1);
/// let bytes = b"hello\0Git\xff";
/// let id = objects.write_blob(bytes)?;
/// assert_eq!(id, ObjectId::for_blob(girt::ObjectFormat::Sha1, bytes));
/// assert_eq!(objects.read_blob(id, 1024)?, bytes);
/// # Ok::<(), girt::loose::Error>(())
/// ```
///
/// # Supported storage
///
/// SHA-1 and SHA-256 loose blobs, trees, commits, and tags are supported.
/// Packs and alternates are not searched, so a packed-only object appears missing. Reads validate
/// canonical headers, lengths, zlib completion and checksum, and object identity. The caller
/// supplies a maximum payload size to bound decompressed allocation. Writes compare existing
/// content before accepting a duplicate and publish complete files without replacing existing
/// objects.
///
/// # Filesystem assumptions
///
/// The object directory and its ancestors must be trusted. This API does not protect against
/// symlink replacement or hostile concurrent filesystem mutation. Writes need a rename that refuses
/// to replace an existing path, or hard-link support where the platform lacks one. They do not
/// promise power-loss durability or honor Git's shared-repository permission settings.
#[derive(Clone, Debug)]
pub struct LooseObjects {
directory: PathBuf,
format: ObjectFormat,
}
impl LooseObjects {
/// Selects an object directory without accessing or creating it.
///
/// The caller supplies the known object format. A directory alone carries no object-format
/// metadata; passing [`ObjectFormat::Sha1`] does not validate repository configuration.
///
/// Both closed object formats are supported; construction performs no I/O.
///
/// ```
/// let directory = tempfile::tempdir()?;
/// let objects = girt::LooseObjects::new(directory.path(), girt::ObjectFormat::Sha1);
/// let id = objects.write_blob(b"standalone storage")?;
/// assert_eq!(objects.read_blob(id, 1024)?, b"standalone storage");
/// # Ok::<(), girt::loose::Error>(())
/// ```
pub fn new(directory: impl Into<PathBuf>, object_format: ObjectFormat) -> Self {
Self {
directory: directory.into(),
format: object_format,
}
}
/// The explicitly selected storage format.
pub fn object_format(&self) -> ObjectFormat {
self.format
}
/// Reads a loose blob, validating its encoding and identity before returning owned content.
///
/// `max_size` limits blob bytes, excluding the header. Decompression retains at most that limit
/// plus a small header and fixed-size scratch buffer. Compressed input is read incrementally.
///
/// # Errors
///
/// Returns [`Error::Io`] for filesystem failures (including missing objects),
/// [`Error::TooLarge`] for oversized content, [`Error::UnsupportedObjectType`] for other
/// recognized types, [`Error::UnknownObjectType`] for unknown kinds, or [`Error::Corrupt`]
/// for malformed headers, incomplete or trailing compressed
/// data, or identity mismatches.
/// Foreign-format IDs return [`Error::ObjectFormat`] before any filesystem access.
///
/// ```
/// let directory = tempfile::tempdir()?;
/// let objects = girt::LooseObjects::new(directory.path(), girt::ObjectFormat::Sha1);
/// let id = objects.write_blob(b"hello\0Git")?;
/// assert_eq!(objects.read_blob(id, 1024)?, b"hello\0Git");
/// // A size refusal leaves the stored object intact.
/// assert!(objects.read_blob(id, 1).is_err());
/// # Ok::<(), girt::loose::Error>(())
/// ```
pub fn read_blob(&self, id: ObjectId, max_size: usize) -> Result<Vec<u8>, Error> {
self.read_object(id, max_size, "blob")
}
/// Reads and parses a loose tree after verifying its framing and selected-format identity.
///
/// Preserves all payloads supported by [`Tree::parse`], including invalid names, duplicates,
/// and unsorted entries. Call [`Tree::validate`] separately when those rules are required.
/// References are not resolved or checked against storage.
///
/// `max_size` bounds decompressed payload bytes, excluding the header. Parsing additionally
/// allocates owned entries and names proportional to that payload; this is not a total heap
/// limit. Compressed input is read incrementally.
///
/// # Errors
///
/// Returns the storage errors documented by [`Self::read_blob`], including
/// [`Error::UnsupportedObjectType`] for a non-tree object, or [`Error::Tree`] when the
/// verified payload cannot be parsed.
///
/// ```
/// let directory = tempfile::tempdir()?;
/// let objects = girt::LooseObjects::new(directory.path(), girt::ObjectFormat::Sha1);
/// let tree = girt::Tree::new(girt::ObjectFormat::Sha1, vec![])?;
/// let id = objects.write_tree(&tree)?;
/// assert_eq!(objects.read_tree(id, 1024)?.id(), tree.id());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn read_tree(&self, id: ObjectId, max_size: usize) -> Result<Tree, Error> {
let payload = self.read_object(id, max_size, "tree")?;
Ok(Tree::parse(self.format, &payload)?)
}
/// Reads a loose commit after verifying framing, size, zlib completion, and selected-format
/// identity.
///
/// Preserves the exact supported payload; does not call [`Commit::validate`] or resolve IDs.
/// `max_size` bounds decompressed payload bytes, not total heap use. Parsing additionally owns
/// the payload and decoded fields. Compressed input is read incrementally.
///
/// # Errors
///
/// Returns the storage errors of [`Self::read_blob`], including wrong object type, or
/// [`Error::Commit`] if the verified payload cannot be parsed.
///
/// ```
/// use girt::{Commit, CommitFields, ObjectFormat, Signature, Tree};
///
/// let person = Signature {
/// name: b"A. Writer".to_vec(),
/// email: b"a@example.com".to_vec(),
/// seconds: 1_700_000_000,
/// offset_minutes: 0,
/// };
/// let commit = Commit::new(CommitFields {
/// tree: Tree::new(ObjectFormat::Sha1, vec![])?.id(),
/// parents: vec![],
/// author: person.clone(),
/// committer: person,
/// extra_headers: vec![],
/// message: b"Initial snapshot\n".to_vec(),
/// })?;
///
/// let directory = tempfile::tempdir()?;
/// let objects = girt::LooseObjects::new(directory.path(), girt::ObjectFormat::Sha1);
/// let id = objects.write_commit(&commit)?;
///
/// assert_eq!(
/// objects.read_commit(id, 4096)?.message(),
/// b"Initial snapshot\n"
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn read_commit(&self, id: ObjectId, max_size: usize) -> Result<Commit, Error> {
let payload = self.read_object(id, max_size, "commit")?;
Ok(Commit::parse(self.format, &payload)?)
}
/// Reads a loose tag after verifying framing, size, zlib completion, and selected-format
/// identity.
///
/// Preserves supported payloads without calling [`Tag::validate`] or resolving targets.
/// `max_size` bounds payload bytes, not total heap use; parsing owns the payload and fields.
/// Compressed input is read incrementally.
///
/// # Errors
///
/// Returns the storage errors of [`Self::read_blob`], including wrong object type, or
/// [`Error::Tag`] if the verified payload cannot be parsed.
///
/// ```
/// use girt::{ObjectFormat, ObjectId, ObjectKind, Tag, TagFields};
///
/// let tag = Tag::new(TagFields {
/// target: ObjectId::for_blob(ObjectFormat::Sha1, b"manifest"),
/// target_kind: ObjectKind::Blob,
/// name: b"v1".to_vec(),
/// tagger: None,
/// extra_headers: vec![],
/// message: b"Release manifest\n".to_vec(),
/// })?;
///
/// let directory = tempfile::tempdir()?;
/// let objects = girt::LooseObjects::new(directory.path(), girt::ObjectFormat::Sha1);
/// let id = objects.write_tag(&tag)?;
/// assert_eq!(objects.read_tag(id, 4096)?.target(), tag.target());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn read_tag(&self, id: ObjectId, max_size: usize) -> Result<Tag, Error> {
let payload = self.read_object(id, max_size, "tag")?;
Ok(Tag::parse(self.format, &payload)?)
}
fn read_object(
&self,
id: ObjectId,
max_size: usize,
expected_kind: &str,
) -> Result<Vec<u8>, Error> {
Ok(self
.decode_raw(id, max_size, Some(expected_kind))?
.into_data())
}
pub(crate) fn read_raw(&self, id: ObjectId, max_size: usize) -> Result<crate::Object, Error> {
self.decode_raw(id, max_size, None)
}
/// Locates a retention candidate by its canonical header without decoding its payload.
pub(crate) fn locate(&self, id: ObjectId) -> Result<(ObjectKind, u64), Error> {
id.require_format(self.format)?;
let file = File::open(self.object_path(id))?;
let mut decoder = flate2::read::ZlibDecoder::new(file);
let mut header = Vec::new();
for _ in 0..32 {
let mut byte = [0];
decoder.read_exact(&mut byte)?;
if byte[0] == 0 {
let text = std::str::from_utf8(&header)
.map_err(|_| Error::Corrupt("invalid loose header"))?;
let (kind, length) = text
.split_once(' ')
.ok_or(Error::Corrupt("invalid loose header"))?;
let kind = match kind {
"blob" => ObjectKind::Blob,
"tree" => ObjectKind::Tree,
"commit" => ObjectKind::Commit,
"tag" => ObjectKind::Tag,
_ => return Err(Error::UnknownObjectType),
};
let size: u64 = length
.parse()
.map_err(|_| Error::Corrupt("invalid loose size"))?;
if size.to_string() != length {
return Err(Error::Corrupt("noncanonical loose size"));
}
return Ok((kind, size));
}
header.push(byte[0]);
}
Err(Error::Corrupt("loose header limit"))
}
fn decode_raw(
&self,
id: ObjectId,
max_size: usize,
expected_kind: Option<&str>,
) -> Result<crate::Object, Error> {
#[cfg(feature = "tracing")]
let span = tracing::trace_span!(
target: "girt",
"loose.read",
object_format = %self.format,
outcome = "incomplete",
failure_class = tracing::field::Empty,
effects = tracing::field::Empty,
max_bytes = max_size,
);
let operation = || {
id.require_format(self.format)?;
let file = File::open(self.object_path(id))?;
let mut encoded = decompress(file, max_size.saturating_add(32))?;
let (kind, content) = split_header(&encoded, expected_kind)?;
if content.len() > max_size {
return Err(Error::TooLarge);
}
if self.format.hash_object(kind, content) != id {
return Err(Error::Corrupt("object identity mismatch"));
}
let header_len = encoded.len() - content.len();
encoded.drain(..header_len);
Ok(crate::Object {
kind,
format: self.format,
data: encoded.into(),
})
};
#[cfg(feature = "tracing")]
let result = span.in_scope(operation);
#[cfg(not(feature = "tracing"))]
let result = { operation }();
#[cfg(feature = "tracing")]
crate::trace::finish(&span, &result, crate::trace::loose);
result
}
/// Writes exact blob bytes and returns their selected-format identity.
///
/// An existing object is read and compared first, so rewriting stored content costs one
/// decompression and no filesystem writes. Otherwise compresses at zlib's best-speed level,
/// as Git does by default, to a private temporary file in the destination directory, creating
/// that directory if missing. It then publishes with a rename that cannot replace an existing
/// path (`renameat2` on Linux, `renamex_np` on macOS), or a hard link and unlink where that
/// rename is unavailable. Concurrent writers of identical content can succeed. Corrupt or
/// conflicting objects are left untouched. Temporary files are removed on normal error
/// paths.
///
/// # Errors
///
/// Returns read errors when an existing object cannot be validated,
/// [`Error::ConflictingObject`] when existing content differs, or [`Error::Io`] on
/// filesystem/compression failures (including filesystems that support neither publishing
/// method).
/// Failed operations may leave created directories. No directory synchronization is
/// performed, so success does not guarantee power-loss durability.
///
/// ```
/// use girt::{LooseObjects, ObjectFormat, ObjectId};
/// let directory = tempfile::tempdir()?;
/// let objects = LooseObjects::new(directory.path(), ObjectFormat::Sha1);
/// let first = objects.write_blob(b"hello\0Git")?;
/// let second = objects.write_blob(b"hello\0Git")?;
/// assert_eq!(first, second); // Publishing identical content is idempotent.
/// assert_eq!(first, ObjectId::for_blob(ObjectFormat::Sha1, b"hello\0Git"));
/// assert_ne!(first, objects.write_blob(b"hello Git")?);
/// # Ok::<(), girt::loose::Error>(())
/// ```
pub fn write_blob(&self, bytes: &[u8]) -> Result<ObjectId, Error> {
self.write_object(self.format, ObjectKind::Blob, bytes)
}
/// Writes a tree's exact encoded payload and returns its selected-format identity.
///
/// Preserves parsed entries even when [`Tree::validate`] would reject them. Does not validate
/// names, reorder entries, or resolve references. Use [`Tree::new`] to construct a validated
/// tree. Allocates a payload buffer before compression.
///
/// Publication, duplicate comparison, concurrency, cleanup, and filesystem assumptions are
/// identical to [`Self::write_blob`].
///
/// # Errors
///
/// Returns [`Error::ObjectFormat`] for a foreign-format tree before filesystem access.
/// Returns the storage errors documented by [`Self::write_blob`]. Existing corrupt objects
/// remain untouched; failed writes may leave created directories.
///
/// ```
/// use girt::{EntryMode, LooseObjects, ObjectFormat, Tree, TreeEntry};
///
/// let directory = tempfile::tempdir()?;
/// let objects = LooseObjects::new(directory.path(), ObjectFormat::Sha1);
/// let blob = objects.write_blob(b"notes\n")?;
///
/// let tree = Tree::new(
/// ObjectFormat::Sha1,
/// vec![TreeEntry {
/// mode: EntryMode::Blob,
/// name: b"notes.txt".to_vec(),
/// id: blob,
/// }],
/// )?;
///
/// let id = objects.write_tree(&tree)?;
/// assert_eq!(id, tree.id()); // Child storage precedes publishing a complete snapshot.
/// assert_eq!(objects.read_tree(id, 4096)?.entries()[0].id, blob);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn write_tree(&self, tree: &Tree) -> Result<ObjectId, Error> {
self.write_object(tree.object_format(), ObjectKind::Tree, &tree.encode())
}
/// Writes a commit's exact payload and returns its selected-format identity without normalizing
/// it.
///
/// Does not validate fields, resolve references, or verify signatures. Use [`Commit::new`] for
/// construction validation. Publication, duplicate checking, concurrent writers, cleanup, and
/// filesystem assumptions are identical to [`Self::write_blob`].
///
/// # Errors
///
/// Returns [`Error::ObjectFormat`] for a foreign-format commit before filesystem access.
/// Returns the storage errors of [`Self::write_blob`]. Existing corrupt files remain untouched;
/// failed writes may leave created directories. Success does not promise power-loss durability.
///
/// ```
/// # use girt::{Commit, CommitFields, ObjectFormat, Signature, Tree};
/// # let person = Signature { name: b"A. Writer".to_vec(), email: b"a@example.com".to_vec(),
/// # seconds: 1_700_000_000, offset_minutes: 0 };
/// # let commit = Commit::new(CommitFields {
/// # tree: Tree::new(ObjectFormat::Sha1, vec![])?.id(), parents: vec![],
/// # author: person.clone(), committer: person,
/// # extra_headers: vec![], message: b"Initial snapshot\n".to_vec(),
/// # })?;
/// let directory = tempfile::tempdir()?;
/// let objects = girt::LooseObjects::new(directory.path(), ObjectFormat::Sha1);
/// let id = objects.write_commit(&commit)?;
/// assert_eq!(id, commit.id());
/// // Storing a commit neither creates its referenced tree nor publishes a branch.
/// assert!(objects.read_tree(commit.tree(), 4096).is_err());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn write_commit(&self, commit: &Commit) -> Result<ObjectId, Error> {
self.write_object(
commit.object_format(),
ObjectKind::Commit,
commit.as_bytes(),
)
}
/// Writes a tag's exact payload and returns its selected-format identity without normalization.
///
/// Does not validate fields, resolve targets, verify signatures, or create a tag reference.
/// Uses the publication, concurrency, and cleanup behavior of [`Self::write_blob`].
///
/// # Errors
///
/// Returns [`Error::ObjectFormat`] for a foreign-format tag before filesystem access.
/// Returns the same storage failures as [`Self::write_blob`]. Failed writes can leave created
/// directories; existing corrupt files are preserved and temporary files are cleaned up.
///
/// ```
/// # use girt::{ObjectFormat, ObjectId, ObjectKind, Tag, TagFields};
/// # let tag = Tag::new(TagFields {
/// # target: ObjectId::for_blob(ObjectFormat::Sha1, b"manifest"),
/// # target_kind: ObjectKind::Blob, name: b"v1".to_vec(), tagger: None,
/// # extra_headers: vec![], message: b"Release manifest\n".to_vec(),
/// # })?;
/// let directory = tempfile::tempdir()?;
/// let objects = girt::LooseObjects::new(directory.path(), ObjectFormat::Sha1);
/// let id = objects.write_tag(&tag)?;
/// assert_eq!(id, tag.id());
/// // No reference is created, and the target is not fetched or written implicitly.
/// assert!(objects.read_blob(tag.target(), 4096).is_err());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn write_tag(&self, tag: &Tag) -> Result<ObjectId, Error> {
self.write_object(tag.object_format(), ObjectKind::Tag, tag.as_bytes())
}
pub(crate) fn write_object(
&self,
format: ObjectFormat,
kind: ObjectKind,
bytes: &[u8],
) -> Result<ObjectId, Error> {
#[cfg(feature = "tracing")]
let span = tracing::trace_span!(
target: "girt",
"loose.write",
object_format = %self.format,
outcome = "incomplete",
failure_class = tracing::field::Empty,
effects = tracing::field::Empty,
bytes = bytes.len(),
);
let operation = || {
ObjectId::null(format).require_format(self.format)?;
let id = self.format.hash_object(kind, bytes);
// Rewriting content that is already stored is common (jj re-derives merge trees on
// every read command), and inflating the existing copy costs far less than deflating
// and linking a new one.
match self.read_existing(id, kind, bytes) {
Err(Error::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {}
existing => return existing.map(|()| id),
}
let path = self.object_path(id);
let parent = path
.parent()
.ok_or(Error::Corrupt("object path has no parent directory"))?;
// Fan-out directories usually exist already, so create one only when it is missing.
let mut temporary = match NamedTempFile::new_in(parent) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
fs::create_dir_all(parent)?;
NamedTempFile::new_in(parent)?
}
temporary => temporary?,
};
let mut encoder = ZlibEncoder::new(temporary.as_file_mut(), LOOSE_COMPRESSION);
encoder.write_all(object_header(kind.as_str(), bytes.len()).as_bytes())?;
encoder.write_all(bytes)?;
encoder.finish()?;
// One no-replace rename where the platform has it, otherwise a hard link and unlink.
let published = match temporary.persist_noclobber(&path) {
Ok(_) => Ok(()),
// Some filesystems refuse an exclusive rename but still support hard links. The
// temporary file is removed when `file` drops.
Err(PersistError { error, file })
if error.kind() == std::io::ErrorKind::Unsupported =>
{
fs::hard_link(file.path(), &path)
}
Err(PersistError { error, .. }) => Err(error),
};
match published {
Ok(()) => Ok(id),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
self.read_existing(id, kind, bytes).map(|()| id)
}
Err(error) => Err(error.into()),
}
};
#[cfg(feature = "tracing")]
let result = span.in_scope(operation);
#[cfg(not(feature = "tracing"))]
let result = { operation }();
#[cfg(feature = "tracing")]
crate::trace::finish(&span, &result, crate::trace::loose);
result
}
/// Reports whether a loose file exists for `id`, without reading it.
pub(crate) fn contains(&self, id: ObjectId) -> Result<bool, Error> {
id.require_format(self.format)?;
match fs::metadata(self.object_path(id)) {
Ok(_) => Ok(true),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error.into()),
}
}
/// Checks that the stored copy of `id` holds exactly `bytes` of `kind`.
fn read_existing(&self, id: ObjectId, kind: ObjectKind, bytes: &[u8]) -> Result<(), Error> {
if self.read_object(id, bytes.len(), kind.as_str())? != bytes {
return Err(Error::ConflictingObject);
}
Ok(())
}
fn object_path(&self, id: ObjectId) -> PathBuf {
let hex = id.to_string();
self.directory.join(&hex[..2]).join(&hex[2..])
}
}
/// A failure to read or publish a loose object.
///
/// A wrong-kind refusal means the object exists but the chosen typed operation is unsuitable.
/// Inspect its kind through [`crate::Objects::read`] before selecting a parser. A loose
/// [`Self::Io`] with [`std::io::ErrorKind::NotFound`] can mean the object is packed;
/// [`crate::Objects`] searches both representations. Preserve corruption and other I/O causes
/// rather than converting them to absence.
///
/// ```
/// use girt::loose::Error;
/// use girt::{InitKind, ObjectFormat, ObjectKind, PackLimits, ReadLimits, Repository};
///
/// let directory = tempfile::tempdir()?;
/// let repo = Repository::init(
/// ObjectFormat::Sha1,
/// directory.path().join("r.git"),
/// InitKind::Bare,
/// )?;
///
/// let loose = repo.loose_objects();
/// let id = loose.write_blob(b"release notes\n")?;
/// assert!(matches!(
/// loose.read_commit(id, 4096),
/// Err(Error::UnsupportedObjectType)
/// ));
///
/// let object = repo
/// .objects_with(PackLimits::default())?
/// .read_with(id, ReadLimits::default())?
/// .ok_or("object absent")?;
/// assert_eq!(object.kind(), ObjectKind::Blob);
/// assert_eq!(object.data(), b"release notes\n");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// An identity or structured object differs from this store's format.
/// Use the store format for both requested IDs and structured payloads.
#[error(transparent)]
ObjectFormat(#[from] crate::ObjectFormatError),
/// A filesystem operation failed. Missing loose objects use [`std::io::ErrorKind::NotFound`].
/// Inspect the operating-system source. For NotFound, try the combined Objects reader if the
/// object may be packed.
#[error("loose object I/O")]
Io(#[from] std::io::Error),
/// A loose object has a different type from the requested operation.
/// Choose the typed read matching the stored kind; do not parse a blob as another object.
#[error("object type does not match the requested operation")]
UnsupportedObjectType,
/// The stored header names an unrecognized Git object kind.
/// Report unsupported stored framing; ordinary Git object kinds are blob, tree, commit, and
/// tag.
#[error("unrecognized loose object type")]
UnknownObjectType,
/// The zlib stream, header, length, or requested identity is invalid.
/// Retain the damaged object for diagnosis and recover verified bytes from a trusted source.
#[error("corrupt loose object: {0}")]
Corrupt(&'static str),
/// Decompressed content exceeds the caller's maximum payload size.
/// Choose a larger payload budget only after assessing trust and resource cost.
#[error("object exceeds the size limit")]
TooLarge,
/// The verified tree payload cannot be parsed; preserves the underlying parsing failure.
/// Inspect the nested tree parser error; storage identity verification did not validate its
/// payload.
#[error("invalid tree payload")]
Tree(#[from] TreeError),
/// The verified commit payload cannot be parsed; preserves the underlying cause.
/// Inspect the nested commit parser error; recover graph-readable data without inventing
/// fields.
#[error("invalid commit payload")]
Commit(#[from] CommitError),
/// The verified tag payload cannot be parsed; preserves the underlying cause.
/// Inspect the nested tag parser error and preserve the original bytes.
#[error("invalid tag payload")]
Tag(#[from] TagError),
/// An existing valid object has the same identity but different content.
/// Stop publication and inspect both copies. The writer refuses to overwrite an existing
/// conflicting object.
#[error("existing object has different content")]
ConflictingObject,
}
// Use the low-level inflater to require StreamEnd explicitly. A Read wrapper alone can accept EOF
// before the zlib trailer; validating content length would not detect that truncation.
/// Splits an inflated loose object into its kind and exactly sized, canonically declared payload.
///
/// A kind other than `expected_kind` is reported before any length error.
pub(crate) fn split_header<'a>(
encoded: &'a [u8],
expected_kind: Option<&str>,
) -> Result<(ObjectKind, &'a [u8]), Error> {
let (header, content) =
crate::bytes::split_once(encoded, 0).ok_or(Error::Corrupt("missing header terminator"))?;
let (kind, length) =
crate::bytes::split_once(header, b' ').ok_or(Error::Corrupt("invalid header"))?;
let kind = match kind {
b"blob" => ObjectKind::Blob,
b"tree" => ObjectKind::Tree,
b"commit" => ObjectKind::Commit,
b"tag" => ObjectKind::Tag,
_ => return Err(Error::UnknownObjectType),
};
if expected_kind.is_some_and(|expected| kind.as_str() != expected) {
return Err(Error::UnsupportedObjectType);
}
if length != content.len().to_string().as_bytes() {
return Err(Error::Corrupt("noncanonical or mismatched length"));
}
Ok((kind, content))
}
pub(crate) fn decompress(file: impl Read, limit: usize) -> Result<Vec<u8>, Error> {
let mut reader = BufReader::new(file);
let mut inflater = Decompress::new(true);
let mut encoded = Vec::new();
let mut output = [0; 8192];
loop {
let input = reader.fill_buf()?;
let before_in = inflater.total_in();
let before_out = inflater.total_out();
let status = inflater
.decompress(input, &mut output, FlushDecompress::None)
.map_err(|_| Error::Corrupt("invalid zlib stream"))?;
let consumed = (inflater.total_in() - before_in) as usize;
let produced = (inflater.total_out() - before_out) as usize;
reader.consume(consumed);
if produced > limit.saturating_sub(encoded.len()) {
return Err(Error::TooLarge);
}
encoded.extend_from_slice(
output
.get(..produced)
.ok_or(Error::Corrupt("invalid zlib stream"))?,
);
if status == Status::StreamEnd {
if !reader.fill_buf()?.is_empty() {
return Err(Error::Corrupt("trailing compressed data"));
}
return Ok(encoded);
}
if consumed == 0 && produced == 0 {
return Err(Error::Corrupt("incomplete zlib stream"));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn distinguishes_unknown_header_kind_from_wrong_requested_kind() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = ObjectId::for_blob(ObjectFormat::Sha1, b"");
install(&objects, id, b"future 0\0");
assert!(matches!(
objects.read_blob(id, 100),
Err(Error::UnknownObjectType)
));
assert!(matches!(
objects.read_raw(id, 100),
Err(Error::UnknownObjectType)
));
}
#[rstest::rstest]
#[case::no_terminator(b"blob 0".as_slice(), "missing header terminator")]
#[case::no_space(b"blob\0", "invalid header")]
#[case::empty_header(b"\0", "invalid header")]
fn rejects_header_without_terminator_or_space(#[case] encoded: &[u8], #[case] expected: &str) {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = ObjectId::for_blob(ObjectFormat::Sha1, b"");
install(&objects, id, encoded);
assert!(matches!(
objects.read_raw(id, 100),
Err(Error::Corrupt(message)) if message == expected
));
}
/// Construction selects a path lazily: reading a missing object fails without creating storage.
#[test]
fn selects_sha1_without_creating_the_directory() {
let root = tempfile::tempdir().unwrap();
let directory = root.path().join("objects");
let objects = LooseObjects::new(&directory, ObjectFormat::Sha1);
let id = ObjectId::for_blob(crate::ObjectFormat::Sha1, b"");
assert!(matches!(objects.read_blob(id, 0), Err(Error::Io(error))
if error.kind() == std::io::ErrorKind::NotFound));
assert!(!directory.exists());
}
#[test]
fn selects_sha256_without_creating_the_directory() {
let root = tempfile::tempdir().unwrap();
let directory = root.path().join("objects");
let objects = LooseObjects::new(&directory, ObjectFormat::Sha256);
assert_eq!(objects.object_format(), ObjectFormat::Sha256);
assert!(!directory.exists());
}
fn tree_fixture() -> Tree {
let tree = Tree::new(
crate::ObjectFormat::Sha1,
vec![crate::TreeEntry {
mode: crate::EntryMode::Blob,
name: b"file".to_vec(),
id: ObjectId::for_blob(crate::ObjectFormat::Sha1, b"contents"),
}],
);
tree.unwrap()
}
/// Installs independently framed bytes to test failures before tree parsing.
fn install(objects: &LooseObjects, id: ObjectId, encoded: &[u8]) {
let path = objects.object_path(id);
fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
encoder.write_all(encoded).unwrap();
fs::write(path, encoder.finish().unwrap()).unwrap();
}
#[rstest::rstest]
#[case::empty(Tree::new(crate::ObjectFormat::Sha1, vec![]).unwrap())]
#[case::one_entry(tree_fixture())]
fn reads_tree_at_exact_payload_limit(#[case] tree: Tree) {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = objects.write_tree(&tree).unwrap();
assert_eq!(id, tree.id());
assert_eq!(objects.read_tree(id, tree.encode().len()).unwrap(), tree);
}
#[test]
fn rejects_tree_one_byte_over_limit() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let tree = tree_fixture();
let id = objects.write_tree(&tree).unwrap();
assert!(matches!(
objects.read_tree(id, tree.encode().len() - 1),
Err(Error::TooLarge)
));
}
#[test]
fn bounds_tree_decompression_before_parsing() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let payload = vec![0; 20000];
let id = ObjectId::for_object("tree", &payload);
install(
&objects,
id,
&[b"tree 20000\0".as_slice(), &payload].concat(),
);
assert!(matches!(objects.read_tree(id, 10), Err(Error::TooLarge)));
}
#[test]
fn rejects_blob_through_tree_reader() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = objects.write_blob(b"").unwrap();
assert!(matches!(
objects.read_tree(id, 0),
Err(Error::UnsupportedObjectType)
));
}
#[test]
fn reports_unexpected_kind_before_malformed_length() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = ObjectId::for_object("blob", b"x");
install(&objects, id, b"blob 9\0x");
assert!(matches!(
objects.read_tree(id, 10),
Err(Error::UnsupportedObjectType)
));
assert!(matches!(objects.read_blob(id, 10), Err(Error::Corrupt(_))));
}
#[rstest::rstest]
#[case::missing_terminator(b"tree 0")]
#[case::missing_length(b"tree\0")]
#[case::leading_zero(b"tree 00\0")]
#[case::mismatched_length(b"tree 1\0")]
#[case::wrong_identity(b"tree 1\0x")]
fn rejects_corrupt_tree_framing(#[case] encoded: &[u8]) {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = Tree::new(crate::ObjectFormat::Sha1, vec![]).unwrap().id();
install(&objects, id, encoded);
assert!(matches!(objects.read_tree(id, 100), Err(Error::Corrupt(_))));
}
#[rstest::rstest]
#[case::missing_mode(b"100644", TreeError::MissingModeDelimiter)]
#[case::missing_name(b"100644 a", TreeError::MissingNameDelimiter)]
#[case::truncated_id(b"100644 a\0", TreeError::TruncatedObjectId)]
fn reports_tree_parse_error_after_identity_verification(
#[case] payload: &[u8],
#[case] expected: TreeError,
) {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = ObjectId::for_object("tree", payload);
let encoded = [object_header("tree", payload.len()).as_bytes(), payload].concat();
install(&objects, id, &encoded);
let Error::Tree(error) = objects.read_tree(id, payload.len()).unwrap_err() else {
panic!("expected tree parsing error");
};
assert_eq!(error, expected);
}
#[test]
fn reports_missing_tree_without_creating_storage() {
let root = tempfile::tempdir().unwrap();
let directory = root.path().join("objects");
let objects = LooseObjects::new(&directory, ObjectFormat::Sha1);
assert!(
matches!(objects.read_tree(tree_fixture().id(), 1024), Err(Error::Io(error))
if error.kind() == std::io::ErrorKind::NotFound)
);
assert!(!directory.exists());
}
#[test]
fn duplicate_tree_preserves_file_and_cleans_temporary() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let tree = tree_fixture();
let id = objects.write_tree(&tree).unwrap();
let path = objects.object_path(id);
let original = fs::read(&path).unwrap();
assert_eq!(objects.write_tree(&tree).unwrap(), id);
assert_eq!(fs::read(&path).unwrap(), original);
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1);
}
#[test]
fn tree_write_preserves_corrupt_file_and_cleans_temporary() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let tree = tree_fixture();
let path = objects.object_path(tree.id());
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, b"invalid zlib").unwrap();
assert!(matches!(objects.write_tree(&tree), Err(Error::Corrupt(_))));
assert_eq!(fs::read(&path).unwrap(), b"invalid zlib");
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1);
}
#[test]
fn concurrent_tree_writes_publish_one_object() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let tree = tree_fixture();
std::thread::scope(|scope| {
for _ in 0..8 {
let objects = &objects;
let tree = &tree;
scope.spawn(move || assert_eq!(objects.write_tree(tree).unwrap(), tree.id()));
}
});
let path = objects.object_path(tree.id());
assert_eq!(objects.read_tree(tree.id(), 1024).unwrap(), tree);
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1);
}
#[test]
fn failed_tree_publication_cleans_temporary() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let tree = tree_fixture();
let path = objects.object_path(tree.id());
fs::create_dir_all(&path).unwrap();
assert!(objects.write_tree(&tree).is_err());
assert!(path.is_dir());
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1);
}
}
#[cfg(test)]
mod commit_storage_tests {
use super::*;
fn commit_fixture() -> Commit {
Commit::parse(crate::ObjectFormat::Sha1, b"tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\nauthor A <a> 1 +0000\ncommitter C <c> 2 -0700\n\nmessage\n").unwrap()
}
/// Installs independently framed bytes to test failures before commit parsing.
fn install(objects: &LooseObjects, id: ObjectId, encoded: &[u8]) {
let path = objects.object_path(id);
fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
encoder.write_all(encoded).unwrap();
fs::write(path, encoder.finish().unwrap()).unwrap();
}
#[rstest::rstest]
#[case::root(commit_fixture())]
fn reads_commit_at_exact_payload_limit(#[case] commit: Commit) {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = objects.write_commit(&commit).unwrap();
assert_eq!(id, commit.id());
assert_eq!(
objects.read_commit(id, commit.encode().len()).unwrap(),
commit
);
}
#[test]
fn rejects_commit_one_byte_over_limit() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let commit = commit_fixture();
let id = objects.write_commit(&commit).unwrap();
assert!(matches!(
objects.read_commit(id, commit.encode().len() - 1),
Err(Error::TooLarge)
));
}
#[test]
fn bounds_commit_decompression_before_parsing() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let payload = vec![0; 20000];
let id = ObjectId::for_object("commit", &payload);
install(
&objects,
id,
&[b"commit 20000\0".as_slice(), &payload].concat(),
);
assert!(matches!(objects.read_commit(id, 10), Err(Error::TooLarge)));
}
#[test]
fn rejects_blob_through_commit_reader() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = objects.write_blob(b"").unwrap();
assert!(matches!(
objects.read_commit(id, 0),
Err(Error::UnsupportedObjectType)
));
}
#[rstest::rstest]
#[case::missing_terminator(b"commit 0")]
#[case::missing_length(b"commit\0")]
#[case::leading_zero(b"commit 00\0")]
#[case::mismatched_length(b"commit 1\0")]
#[case::wrong_identity(b"commit 1\0x")]
fn rejects_corrupt_commit_framing(#[case] encoded: &[u8]) {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = commit_fixture().id();
install(&objects, id, encoded);
assert!(matches!(
objects.read_commit(id, 100),
Err(Error::Corrupt(_))
));
}
#[rstest::rstest]
#[case::separator(b"tree abc", CommitError::RequiredHeader)]
#[case::identity(b"tree abc\n\n", CommitError::InvalidObjectId)]
fn reports_commit_parse_error_after_identity_verification(
#[case] payload: &[u8],
#[case] expected: CommitError,
) {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = ObjectId::for_object("commit", payload);
let encoded = [object_header("commit", payload.len()).as_bytes(), payload].concat();
install(&objects, id, &encoded);
let Error::Commit(error) = objects.read_commit(id, payload.len()).unwrap_err() else {
panic!("expected commit parsing error");
};
assert_eq!(error, expected);
}
#[test]
fn reports_missing_commit_without_creating_storage() {
let root = tempfile::tempdir().unwrap();
let directory = root.path().join("objects");
let objects = LooseObjects::new(&directory, ObjectFormat::Sha1);
assert!(
matches!(objects.read_commit(commit_fixture().id(), 1024), Err(Error::Io(error))
if error.kind() == std::io::ErrorKind::NotFound)
);
assert!(!directory.exists());
}
#[test]
fn duplicate_commit_preserves_file_and_cleans_temporary() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let commit = commit_fixture();
let id = objects.write_commit(&commit).unwrap();
let path = objects.object_path(id);
let original = fs::read(&path).unwrap();
assert_eq!(objects.write_commit(&commit).unwrap(), id);
assert_eq!(fs::read(&path).unwrap(), original);
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1);
}
#[test]
fn commit_write_preserves_corrupt_file_and_cleans_temporary() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let commit = commit_fixture();
let path = objects.object_path(commit.id());
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, b"invalid zlib").unwrap();
assert!(matches!(
objects.write_commit(&commit),
Err(Error::Corrupt(_))
));
assert_eq!(fs::read(&path).unwrap(), b"invalid zlib");
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1);
}
#[test]
fn concurrent_commit_writes_publish_one_object() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let commit = commit_fixture();
std::thread::scope(|scope| {
for _ in 0..8 {
let objects = &objects;
let commit = &commit;
scope.spawn(move || assert_eq!(objects.write_commit(commit).unwrap(), commit.id()));
}
});
let path = objects.object_path(commit.id());
assert_eq!(objects.read_commit(commit.id(), 1024).unwrap(), commit);
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1);
}
#[test]
fn failed_commit_publication_cleans_temporary() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let commit = commit_fixture();
let path = objects.object_path(commit.id());
fs::create_dir_all(&path).unwrap();
assert!(objects.write_commit(&commit).is_err());
assert!(path.is_dir());
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1);
}
}
#[cfg(test)]
mod tag_storage_tests {
use super::*;
fn tag_fixture() -> Tag {
Tag::parse(crate::ObjectFormat::Sha1, b"object e69de29bb2d1d6434b8b29ae775ad8c2e48c5391\ntype blob\ntag v1\ntagger A <a> 1 +0000\n\nmessage\n").unwrap()
}
/// Installs independently framed bytes to test failures before tag parsing.
fn install(objects: &LooseObjects, id: ObjectId, encoded: &[u8]) {
let path = objects.object_path(id);
fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
encoder.write_all(encoded).unwrap();
fs::write(path, encoder.finish().unwrap()).unwrap();
}
#[rstest::rstest]
#[case::annotated(tag_fixture())]
fn reads_tag_at_exact_payload_limit(#[case] tag: Tag) {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = objects.write_tag(&tag).unwrap();
assert_eq!(id, tag.id());
assert_eq!(objects.read_tag(id, tag.encode().len()).unwrap(), tag);
}
#[test]
fn rejects_tag_one_byte_over_limit() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let tag = tag_fixture();
let id = objects.write_tag(&tag).unwrap();
assert!(matches!(
objects.read_tag(id, tag.encode().len() - 1),
Err(Error::TooLarge)
));
}
#[test]
fn bounds_tag_decompression_before_parsing() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let payload = vec![0; 20000];
let id = ObjectId::for_object("tag", &payload);
install(
&objects,
id,
&[b"tag 20000\0".as_slice(), &payload].concat(),
);
assert!(matches!(objects.read_tag(id, 10), Err(Error::TooLarge)));
}
#[test]
fn rejects_blob_through_tag_reader() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = objects.write_blob(b"").unwrap();
assert!(matches!(
objects.read_tag(id, 0),
Err(Error::UnsupportedObjectType)
));
}
#[rstest::rstest]
#[case::missing_terminator(b"tag 0")]
#[case::missing_length(b"tag\0")]
#[case::leading_zero(b"tag 00\0")]
#[case::mismatched_length(b"tag 1\0")]
#[case::wrong_identity(b"tag 1\0x")]
fn rejects_corrupt_tag_framing(#[case] encoded: &[u8]) {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = tag_fixture().id();
install(&objects, id, encoded);
assert!(matches!(objects.read_tag(id, 100), Err(Error::Corrupt(_))));
}
#[rstest::rstest]
#[case::separator(b"object abc", TagError::UnterminatedHeader)]
#[case::identity(b"object abc\n\n", TagError::InvalidObjectId)]
fn reports_tag_parse_error_after_identity_verification(
#[case] payload: &[u8],
#[case] expected: TagError,
) {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = ObjectId::for_object("tag", payload);
let encoded = [object_header("tag", payload.len()).as_bytes(), payload].concat();
install(&objects, id, &encoded);
let Error::Tag(error) = objects.read_tag(id, payload.len()).unwrap_err() else {
panic!("expected tag parsing error");
};
assert_eq!(error, expected);
}
#[test]
fn reports_missing_tag_without_creating_storage() {
let root = tempfile::tempdir().unwrap();
let directory = root.path().join("objects");
let objects = LooseObjects::new(&directory, ObjectFormat::Sha1);
assert!(
matches!(objects.read_tag(tag_fixture().id(), 1024), Err(Error::Io(error))
if error.kind() == std::io::ErrorKind::NotFound)
);
assert!(!directory.exists());
}
#[test]
fn duplicate_tag_preserves_file_and_cleans_temporary() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let tag = tag_fixture();
let id = objects.write_tag(&tag).unwrap();
let path = objects.object_path(id);
let original = fs::read(&path).unwrap();
assert_eq!(objects.write_tag(&tag).unwrap(), id);
assert_eq!(fs::read(&path).unwrap(), original);
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1);
}
#[test]
fn tag_write_preserves_corrupt_file_and_cleans_temporary() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let tag = tag_fixture();
let path = objects.object_path(tag.id());
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, b"invalid zlib").unwrap();
assert!(matches!(objects.write_tag(&tag), Err(Error::Corrupt(_))));
assert_eq!(fs::read(&path).unwrap(), b"invalid zlib");
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1);
}
#[test]
fn concurrent_tag_writes_publish_one_object() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let tag = tag_fixture();
std::thread::scope(|scope| {
for _ in 0..8 {
let objects = &objects;
let tag = &tag;
scope.spawn(move || assert_eq!(objects.write_tag(tag).unwrap(), tag.id()));
}
});
let path = objects.object_path(tag.id());
assert_eq!(objects.read_tag(tag.id(), 1024).unwrap(), tag);
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1);
}
#[test]
fn failed_tag_publication_cleans_temporary() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let tag = tag_fixture();
let path = objects.object_path(tag.id());
fs::create_dir_all(&path).unwrap();
assert!(objects.write_tag(&tag).is_err());
assert!(path.is_dir());
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1);
}
}
#[cfg(test)]
mod format_boundary_tests {
use super::*;
#[test]
fn rejects_sha256_before_accessing_missing_storage() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join("missing");
let objects = LooseObjects::new(&path, ObjectFormat::Sha1);
assert!(matches!(
objects.read_blob(ObjectId::Sha256([1; 32]), 100),
Err(Error::ObjectFormat(_))
));
assert!(!path.exists());
}
}
#[cfg(test)]
mod dual_format_tests {
use rstest::rstest;
use super::*;
#[rstest]
#[case::sha1(ObjectFormat::Sha1, ObjectFormat::Sha256)]
#[case::sha256(ObjectFormat::Sha256, ObjectFormat::Sha1)]
fn foreign_objects_fail_before_creating_storage(
#[case] format: ObjectFormat,
#[case] foreign: ObjectFormat,
) {
let root = tempfile::tempdir().unwrap();
let directory = root.path().join("objects");
let objects = LooseObjects::new(&directory, format);
let tree = Tree::new(foreign, vec![]).unwrap();
let payload = format!(
"tree {}\nauthor A <a> -1 +0000\ncommitter A <a> 1 +0000\n\n",
tree.id()
);
let commit = Commit::parse(foreign, payload.as_bytes()).unwrap();
let payload = format!("object {}\ntype commit\ntag v1\n\n", commit.id());
let tag = Tag::parse(foreign, payload.as_bytes()).unwrap();
assert!(matches!(
objects.write_tree(&tree),
Err(Error::ObjectFormat(_))
));
assert!(matches!(
objects.write_commit(&commit),
Err(Error::ObjectFormat(_))
));
assert!(matches!(
objects.write_tag(&tag),
Err(Error::ObjectFormat(_))
));
assert!(matches!(
objects.read_blob(ObjectId::null(foreign), 0),
Err(Error::ObjectFormat(_))
));
assert!(!directory.exists());
}
#[rstest]
#[case::sha1(ObjectFormat::Sha1)]
#[case::sha256(ObjectFormat::Sha256)]
fn limits_duplicates_corruption_and_cleanup(#[case] format: ObjectFormat) {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), format);
let id = objects.write_blob(b"content").unwrap();
let path = objects.object_path(id);
let encoded = fs::read(&path).unwrap();
assert_eq!(objects.read_blob(id, 7).unwrap(), b"content");
assert!(matches!(objects.read_blob(id, 6), Err(Error::TooLarge)));
assert_eq!(objects.write_blob(b"content").unwrap(), id);
assert_eq!(fs::read(&path).unwrap(), encoded);
fs::write(&path, b"corrupt existing object").unwrap();
assert!(objects.write_blob(b"content").is_err());
assert_eq!(fs::read(&path).unwrap(), b"corrupt existing object");
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn rewriting_a_stored_object_writes_nothing() {
use std::os::unix::fs::PermissionsExt;
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = objects.write_blob(b"content").unwrap();
let parent = objects.object_path(id).parent().unwrap().to_owned();
// A read-only fan-out directory refuses temporary files and links, so success shows
// that a duplicate is compared against the stored copy without publishing again.
fs::set_permissions(&parent, fs::Permissions::from_mode(0o555)).unwrap();
if fs::write(parent.join("probe"), b"").is_ok() {
// Privileged processes ignore directory permissions, so this check proves nothing.
fs::set_permissions(&parent, fs::Permissions::from_mode(0o755)).unwrap();
return;
}
let rewritten = objects.write_blob(b"content");
fs::set_permissions(&parent, fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(rewritten.unwrap(), id);
assert_eq!(fs::read_dir(&parent).unwrap().count(), 1);
}
/// New objects use zlib's best-speed level, Git's default for loose objects, whose zlib
/// header is `78 01`.
#[test]
fn writes_at_gits_default_loose_compression() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = objects.write_blob(&[b'x'; 4096]).unwrap();
assert_eq!(
fs::read(objects.object_path(id)).unwrap()[..2],
[0x78, 0x01]
);
}
#[rstest]
#[case::sha1(ObjectFormat::Sha1)]
#[case::sha256(ObjectFormat::Sha256)]
fn failed_publication_preserves_destination(#[case] format: ObjectFormat) {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), format);
let id = ObjectId::for_blob(format, b"content");
let path = objects.object_path(id);
fs::create_dir_all(&path).unwrap();
fs::write(path.join("sentinel"), b"keep").unwrap();
assert!(objects.write_blob(b"content").is_err());
assert_eq!(fs::read(path.join("sentinel")).unwrap(), b"keep");
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 1);
}
#[rstest]
#[case::sha1(ObjectFormat::Sha1)]
#[case::sha256(ObjectFormat::Sha256)]
fn concurrent_publication_returns_same_identity(#[case] format: ObjectFormat) {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), format);
let other = objects.clone();
let worker = std::thread::spawn(move || other.write_blob(b"concurrent").unwrap());
let id = objects.write_blob(b"concurrent").unwrap();
assert_eq!(worker.join().unwrap(), id);
assert_eq!(objects.read_blob(id, 10).unwrap(), b"concurrent");
assert_eq!(
fs::read_dir(objects.object_path(id).parent().unwrap())
.unwrap()
.count(),
1
);
}
#[test]
fn foreign_commit_payload_is_not_reinterpreted() {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha256);
let payload = format!(
"tree {}\nauthor A <a> 1 +0000\ncommitter A <a> 1 +0000\n\n",
ObjectId::Sha1([1; 20])
);
let id = objects
.write_object(ObjectFormat::Sha256, ObjectKind::Commit, payload.as_bytes())
.unwrap();
assert!(matches!(
objects.read_commit(id, 1000),
Err(Error::Commit(CommitError::InvalidObjectId))
));
}
#[rstest::rstest]
#[case::sha1(ObjectFormat::Sha1)]
#[case::sha256(ObjectFormat::Sha256)]
fn retention_location_does_not_validate_blob_payload(#[case] format: ObjectFormat) {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), format);
let id = objects.write_blob(b"original").unwrap();
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
encoder.write_all(b"blob 8\0different").unwrap();
fs::write(objects.object_path(id), encoder.finish().unwrap()).unwrap();
assert_eq!(objects.locate(id).unwrap(), (ObjectKind::Blob, 8));
assert!(matches!(objects.read_blob(id, 100), Err(Error::Corrupt(_))));
}
#[rstest::rstest]
#[case::leading_zero(b"blob 08\0original")]
#[case::negative(b"blob -8\0original")]
#[case::missing_kind(b" 8\0original")]
#[case::unterminated(b"blob 8")]
fn retention_location_rejects_malformed_headers(#[case] encoded: &[u8]) {
let root = tempfile::tempdir().unwrap();
let objects = LooseObjects::new(root.path(), ObjectFormat::Sha1);
let id = objects.write_blob(b"original").unwrap();
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
encoder.write_all(encoded).unwrap();
fs::write(objects.object_path(id), encoder.finish().unwrap()).unwrap();
assert!(objects.locate(id).is_err());
}
}