1use crate::error::ObjectError;
8use std::collections::HashSet;
9
10use crate::change_id::ChangeId;
11use crate::error::Error;
12use crate::fsck_standalone::{tree_entry_mode_allowed, MAX_TREE_ENTRY_LEN};
13use crate::gitmodules::tree_entry_reserved_dot_symlink;
14use crate::ident::Signature;
15use crate::objects::{tree_name_cmp, CommitData, HashAlgo, ObjectId, ObjectKind, TreeEntry};
16use crate::odb::Odb;
17use crate::path_validate::{audit_tree_entry_name, PathComponentError, ProtectOptions};
18
19const MODE_TREE: u32 = 0o040000;
20const MODE_GITLINK: u32 = 0o160000;
21
22#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
27#[non_exhaustive]
28pub enum TreeEntryError {
29 #[error("invalid tree entry name '{}': {reason}", String::from_utf8_lossy(.name))]
31 InvalidName {
32 name: Vec<u8>,
34 reason: PathComponentError,
36 },
37 #[error(
39 "tree entry name of {} bytes exceeds the {max}-byte limit",
40 .name.len()
41 )]
42 NameTooLong {
43 name: Vec<u8>,
45 max: usize,
47 },
48 #[error("tree entry '{}' has unsupported mode {mode:o}", String::from_utf8_lossy(.name))]
50 InvalidMode {
51 name: Vec<u8>,
53 mode: u32,
55 },
56 #[error("tree entry '{}' points at the null object id", String::from_utf8_lossy(.name))]
58 NullObjectId {
59 name: Vec<u8>,
61 },
62 #[error(
64 "tree entry '{}' has a {} object id in a {} repository",
65 String::from_utf8_lossy(.name),
66 .actual.name(),
67 .expected.name()
68 )]
69 HashAlgoMismatch {
70 name: Vec<u8>,
72 expected: HashAlgo,
74 actual: HashAlgo,
76 },
77 #[error("tree lists '{}' more than once", String::from_utf8_lossy(.name))]
79 DuplicateName {
80 name: Vec<u8>,
82 },
83 #[error(
85 "tree entry '{}' must not be a symlink to {reserved_file}",
86 String::from_utf8_lossy(.name)
87 )]
88 ForbiddenDotSymlink {
89 name: Vec<u8>,
91 reserved_file: &'static str,
93 },
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
98pub struct WriteTreeOptions {
99 pub allow_missing: bool,
102}
103
104pub(crate) fn canonical_tree_entries(
114 entries: impl IntoIterator<Item = TreeEntry>,
115 algo: HashAlgo,
116) -> Result<Vec<TreeEntry>, TreeEntryError> {
117 let mut entries: Vec<TreeEntry> = entries.into_iter().collect();
118 for entry in &entries {
119 validate_tree_entry(entry, algo)?;
120 }
121 entries
122 .sort_by(|a, b| tree_name_cmp(&a.name, a.mode == MODE_TREE, &b.name, b.mode == MODE_TREE));
123 let mut seen = HashSet::with_capacity(entries.len());
124 if let Some(dup) = entries.iter().find(|e| !seen.insert(e.name.as_slice())) {
125 return Err(TreeEntryError::DuplicateName {
126 name: dup.name.clone(),
127 });
128 }
129 Ok(entries)
130}
131
132pub(crate) fn validate_tree_entry_stored_kinds(
139 odb: &Odb,
140 entries: &[TreeEntry],
141 allow_missing: bool,
142) -> Result<(), Error> {
143 for entry in entries {
144 validate_one_tree_entry_stored_kind(odb, entry, allow_missing)?;
145 }
146 Ok(())
147}
148
149fn expected_kind_for_tree_mode(mode: u32) -> ObjectKind {
150 match mode {
151 MODE_TREE => ObjectKind::Tree,
152 MODE_GITLINK => ObjectKind::Commit,
153 _ => ObjectKind::Blob,
154 }
155}
156
157fn validate_one_tree_entry_stored_kind(
158 odb: &Odb,
159 entry: &TreeEntry,
160 allow_missing: bool,
161) -> Result<(), Error> {
162 let expected = expected_kind_for_tree_mode(entry.mode);
163 let stored = odb.stored_object_kind(&entry.oid)?;
164 if entry.mode == MODE_GITLINK {
165 if let Some(actual) = stored {
166 if actual != ObjectKind::Commit {
167 return Err(Error::Object(ObjectError::UnexpectedKind {
168 oid: entry.oid,
169 expected: ObjectKind::Commit,
170 actual,
171 }));
172 }
173 }
174 return Ok(());
175 }
176 let Some(actual) = stored else {
177 if allow_missing {
178 return Ok(());
179 }
180 return Err(Error::Object(ObjectError::NotFound {
181 name: entry.oid.to_hex(),
182 }));
183 };
184 if actual != expected {
185 return Err(Error::Object(ObjectError::UnexpectedKind {
186 oid: entry.oid,
187 expected,
188 actual,
189 }));
190 }
191 Ok(())
192}
193
194fn validate_tree_entry(entry: &TreeEntry, algo: HashAlgo) -> Result<(), TreeEntryError> {
195 audit_tree_entry_name(&entry.name, ProtectOptions::fsck())
196 .first_error()
197 .map_err(|reason| TreeEntryError::InvalidName {
198 name: entry.name.clone(),
199 reason,
200 })?;
201 if entry.name.len() > MAX_TREE_ENTRY_LEN {
202 return Err(TreeEntryError::NameTooLong {
203 name: entry.name.clone(),
204 max: MAX_TREE_ENTRY_LEN,
205 });
206 }
207 if !tree_entry_mode_allowed(entry.mode) {
208 return Err(TreeEntryError::InvalidMode {
209 name: entry.name.clone(),
210 mode: entry.mode,
211 });
212 }
213 if entry.oid.algo() != algo {
214 return Err(TreeEntryError::HashAlgoMismatch {
215 name: entry.name.clone(),
216 expected: algo,
217 actual: entry.oid.algo(),
218 });
219 }
220 if entry.oid.is_zero() {
221 return Err(TreeEntryError::NullObjectId {
222 name: entry.name.clone(),
223 });
224 }
225 if let Some(reserved_file) = tree_entry_reserved_dot_symlink(entry.mode, &entry.name) {
226 return Err(TreeEntryError::ForbiddenDotSymlink {
227 name: entry.name.clone(),
228 reserved_file,
229 });
230 }
231 Ok(())
232}
233
234#[derive(Debug, Clone, PartialEq, Eq)]
267pub struct NewCommit {
268 tree: ObjectId,
269 parents: Vec<ObjectId>,
270 author: Signature,
271 committer: Signature,
272 message: String,
273 change_id: Option<ChangeId>,
274}
275
276impl NewCommit {
277 #[must_use]
285 pub fn new(
286 tree: ObjectId,
287 author: Signature,
288 committer: Signature,
289 message: impl Into<String>,
290 ) -> Self {
291 Self {
292 tree,
293 parents: Vec::new(),
294 author,
295 committer,
296 message: message.into(),
297 change_id: None,
298 }
299 }
300
301 #[must_use]
303 pub fn with_parents(mut self, parents: impl IntoIterator<Item = ObjectId>) -> Self {
304 self.parents = parents.into_iter().collect();
305 self
306 }
307
308 #[must_use]
314 pub fn with_change_id(mut self, id: ChangeId) -> Self {
315 self.change_id = Some(id);
316 self
317 }
318
319 pub(crate) fn change_id(&self) -> Option<&ChangeId> {
321 self.change_id.as_ref()
322 }
323
324 pub(crate) fn tree_and_parents(&self) -> (&ObjectId, &[ObjectId]) {
326 (&self.tree, &self.parents)
327 }
328
329 pub(crate) fn signatures(&self) -> [&Signature; 2] {
331 [&self.author, &self.committer]
332 }
333
334 pub(crate) fn to_commit_data(&self) -> CommitData {
336 let mut message = self.message.clone();
337 if !message.is_empty() && !message.ends_with('\n') {
338 message.push('\n');
339 }
340 CommitData {
341 tree: self.tree,
342 parents: self.parents.clone(),
343 author: self.author.header_line(),
344 committer: self.committer.header_line(),
345 author_raw: Vec::new(),
346 committer_raw: Vec::new(),
347 encoding: None,
348 message,
349 raw_message: None,
350 extra_headers: Vec::new(),
351 }
352 }
353}
354
355#[cfg(test)]
356mod tests {
357 use super::*;
358 use crate::objects::HashAlgo;
359 use time::OffsetDateTime;
360
361 fn oid(byte: u8) -> ObjectId {
362 ObjectId::from_bytes(&[byte; 20]).unwrap()
363 }
364
365 fn entry(mode: u32, name: &[u8], byte: u8) -> TreeEntry {
366 TreeEntry {
367 mode,
368 name: name.to_vec(),
369 oid: oid(byte),
370 }
371 }
372
373 #[test]
374 fn sorts_into_git_tree_order() {
375 let sorted = canonical_tree_entries(
376 [
377 entry(0o100644, b"foo.c", 1),
378 entry(MODE_TREE, b"foo", 2),
379 entry(0o100644, b"foo-bar", 3),
380 entry(0o100644, b"a", 4),
381 ],
382 HashAlgo::Sha1,
383 )
384 .unwrap();
385 let names: Vec<&[u8]> = sorted.iter().map(|e| e.name.as_slice()).collect();
386 assert_eq!(
387 names,
388 [&b"a"[..], &b"foo-bar"[..], &b"foo.c"[..], &b"foo"[..]]
389 );
390 }
391
392 #[test]
393 fn rejects_file_and_directory_with_the_same_name() {
394 let err = canonical_tree_entries(
395 [
396 entry(0o100644, b"foo", 1),
397 entry(0o100644, b"foo.c", 2),
398 entry(MODE_TREE, b"foo", 3),
399 ],
400 HashAlgo::Sha1,
401 )
402 .unwrap_err();
403 assert_eq!(
404 err,
405 TreeEntryError::DuplicateName {
406 name: b"foo".to_vec()
407 }
408 );
409 }
410
411 #[test]
412 fn rejects_bad_names_modes_and_ids() {
413 let cases: [(TreeEntry, TreeEntryError); 7] = [
414 (
415 entry(0o100644, &[b'x'; MAX_TREE_ENTRY_LEN + 1], 1),
416 TreeEntryError::NameTooLong {
417 name: vec![b'x'; MAX_TREE_ENTRY_LEN + 1],
418 max: MAX_TREE_ENTRY_LEN,
419 },
420 ),
421 (
422 entry(0o100644, b"", 1),
423 TreeEntryError::InvalidName {
424 name: Vec::new(),
425 reason: PathComponentError::Empty,
426 },
427 ),
428 (
429 entry(0o100644, b"a/b", 1),
430 TreeEntryError::InvalidName {
431 name: b"a/b".to_vec(),
432 reason: PathComponentError::ContainsSlash,
433 },
434 ),
435 (
436 entry(0o100644, b"..", 1),
437 TreeEntryError::InvalidName {
438 name: b"..".to_vec(),
439 reason: PathComponentError::DotDot,
440 },
441 ),
442 (
443 entry(MODE_TREE, b".GIT", 1),
444 TreeEntryError::InvalidName {
445 name: b".GIT".to_vec(),
446 reason: PathComponentError::DotGit,
447 },
448 ),
449 (
450 entry(0o100664, b"a", 1),
451 TreeEntryError::InvalidMode {
452 name: b"a".to_vec(),
453 mode: 0o100664,
454 },
455 ),
456 (
457 entry(0o100644, b"a", 0),
458 TreeEntryError::NullObjectId {
459 name: b"a".to_vec(),
460 },
461 ),
462 ];
463 for (input, expected) in cases {
464 assert_eq!(
465 canonical_tree_entries([input], HashAlgo::Sha1).unwrap_err(),
466 expected
467 );
468 }
469 }
470
471 #[test]
472 fn rejects_object_ids_of_the_other_hash_algorithm() {
473 let err = canonical_tree_entries([entry(0o100644, b"a", 1)], HashAlgo::Sha256).unwrap_err();
474 assert!(matches!(
475 err,
476 TreeEntryError::HashAlgoMismatch {
477 expected: HashAlgo::Sha256,
478 actual: HashAlgo::Sha1,
479 ..
480 }
481 ));
482 }
483
484 #[test]
485 fn commit_data_terminates_message_and_renders_signatures() {
486 let when = OffsetDateTime::from_unix_timestamp(1_700_000_000).unwrap();
487 let sig = Signature::new("A U Thor", "a@example.com", when).unwrap();
488 let data = NewCommit::new(oid(1), sig.clone(), sig, "subject")
489 .with_parents([oid(2)])
490 .to_commit_data();
491 assert_eq!(data.message, "subject\n");
492 assert_eq!(data.parents, vec![oid(2)]);
493 assert_eq!(data.author, "A U Thor <a@example.com> 1700000000 +0000");
494 assert!(data.extra_headers.is_empty());
495 }
496}