1use std::collections::{HashMap, HashSet, VecDeque};
7
8use git2::{Commit, DiffOptions, Oid, Repository};
9
10use crate::{
11 Error, GitContext, Result, SemanticVersion, Version, VersionFile, VersionFileRequirements,
12 VersionOptions, VersionPosition,
13};
14
15pub const MAXIMUM_VERSION_COMPONENT: u32 = 0xfffe;
17
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
20pub struct VersionHeightCalculation {
21 pub height: u32,
23 pub commit_id: Option<Oid>,
25}
26
27pub fn get_height(context: &GitContext) -> Result<u32> {
29 let start = selected_commit_id(context)?;
30 let mut tracker = HistoryTracker::new(context)?;
31 Ok(commit_height(&mut tracker, start, |_| Ok(true))?.height)
32}
33
34pub fn get_version_height(
39 context: &GitContext,
40 base_version: Option<&Version>,
41) -> Result<VersionHeightCalculation> {
42 let Some(start) = context.git_commit_id() else {
43 return Ok(VersionHeightCalculation {
44 height: 0,
45 commit_id: None,
46 });
47 };
48 let mut tracker = HistoryTracker::new(context)?;
49 let options = tracker.version_at(start)?;
50 let Some(options) = options else {
51 return Ok(VersionHeightCalculation {
52 height: 0,
53 commit_id: Some(start),
54 });
55 };
56 let expected = match base_version {
57 Some(version) => SemanticVersion::new(*version, "", "")?,
58 None => options
59 .version
60 .clone()
61 .unwrap_or_else(|| "0.0".parse().expect("0.0 is valid")),
62 };
63 let Some(position) = options.version_height_position() else {
64 return Ok(VersionHeightCalculation {
65 height: 0,
66 commit_id: Some(start),
67 });
68 };
69
70 commit_height(&mut tracker, start, |tracker| {
71 commit_matches_version(tracker.current_commit, &expected, position, tracker)
72 })
73}
74
75pub fn calculate_version_height(
77 context: &GitContext,
78 committed_version: Option<&VersionOptions>,
79 working_version: Option<&VersionOptions>,
80) -> Result<VersionHeightCalculation> {
81 if committed_version != working_version {
82 let committed = committed_version
83 .and_then(|options| options.version.as_ref())
84 .map(|version| version.version)
85 .unwrap_or_default();
86 let working = working_version
87 .and_then(|options| options.version.as_ref())
88 .map(|version| version.version);
89 if working != Some(committed) {
90 return Ok(VersionHeightCalculation {
91 height: 0,
92 commit_id: context.git_commit_id(),
93 });
94 }
95 }
96 get_version_height(context, None)
97}
98
99#[must_use]
101pub fn truncated_commit_id(commit_id: Oid) -> u16 {
102 u16::from_be_bytes([commit_id.as_bytes()[0], commit_id.as_bytes()[1]])
103}
104
105pub fn encode_version(
107 commit_id: Option<Oid>,
108 version_options: Option<&VersionOptions>,
109 version_height: u32,
110) -> Result<Version> {
111 let base = version_options
112 .and_then(|options| options.version.as_ref())
113 .map(|version| version.version)
114 .unwrap_or_default();
115 let mut build = base.build;
116 let mut revision = base.revision;
117 let height_position = version_options
118 .map(VersionOptions::version_height_position)
119 .unwrap_or(Some(VersionPosition::Build));
120 let commit_position = version_options
121 .map(VersionOptions::git_commit_id_position)
122 .unwrap_or(Some(VersionPosition::Revision));
123
124 if let Some(position) = height_position {
125 let adjusted = if version_height == 0 {
126 0
127 } else {
128 i64::from(version_height)
129 + i64::from(
130 version_options.map_or(0, VersionOptions::effective_version_height_offset),
131 )
132 };
133 if !(0..=i64::from(MAXIMUM_VERSION_COMPONENT)).contains(&adjusted) {
134 return Err(Error::InvalidOperation(format!(
135 "Git height {adjusted} is outside the allowed range 0..={MAXIMUM_VERSION_COMPONENT}."
136 )));
137 }
138 match position {
139 VersionPosition::Build => build = Some(adjusted as u32),
140 VersionPosition::Revision => revision = Some(adjusted as u32),
141 _ => {}
142 }
143 }
144
145 if commit_position == Some(VersionPosition::Revision) {
146 revision = Some(
147 commit_id
148 .map(|id| u32::from(truncated_commit_id(id)).min(MAXIMUM_VERSION_COMPONENT))
149 .unwrap_or(0),
150 );
151 }
152
153 Ok(Version {
154 major: base.major,
155 minor: base.minor,
156 build,
157 revision,
158 })
159}
160
161pub fn get_id_as_version(
167 context: &GitContext,
168 committed_version: Option<&VersionOptions>,
169 working_version: Option<&VersionOptions>,
170 version_height: VersionHeightCalculation,
171) -> Result<Version> {
172 let options = if committed_version != working_version {
173 working_version
174 } else {
175 committed_version
176 };
177 encode_version(
178 version_height.commit_id.or_else(|| context.git_commit_id()),
179 options,
180 version_height.height,
181 )
182}
183
184pub fn get_commits_from_version(context: &GitContext, version: &Version) -> Result<Vec<Oid>> {
186 let repository = context
187 .repository()
188 .ok_or_else(|| Error::InvalidOperation("No repository is available.".to_owned()))?;
189 let mut tracker = HistoryTracker::new(context)?;
190 let mut matches = Vec::new();
191 for commit_id in commits_reachable_from_refs(repository)? {
192 let Some(options) = tracker.version_at(commit_id)? else {
193 continue;
194 };
195 if !options
196 .version
197 .as_ref()
198 .is_some_and(|candidate| candidate.is_matching_version(version))
199 || commit_id_mismatch(version, &options, commit_id)?
200 || version_height_mismatch(version, &options, commit_id, &mut tracker)?
201 {
202 continue;
203 }
204 matches.push(commit_id);
205 }
206 Ok(matches)
207}
208
209pub fn get_commit_from_version(context: &GitContext, version: &Version) -> Result<Option<Oid>> {
213 let matches = get_commits_from_version(context, version)?;
214 match matches.as_slice() {
215 [] => Ok(None),
216 [commit] => Ok(Some(*commit)),
217 _ => Err(Error::InvalidOperation(format!(
218 "Version '{version}' matches more than one commit."
219 ))),
220 }
221}
222
223struct HistoryTracker<'context> {
224 context: &'context GitContext,
225 repository: &'context Repository,
226 versions: HashMap<Oid, Option<VersionOptions>>,
227 heights: HashMap<Oid, VersionHeightCalculation>,
228 current_commit: Oid,
229 ignore_case: Option<bool>,
230}
231
232impl<'context> HistoryTracker<'context> {
233 fn new(context: &'context GitContext) -> Result<Self> {
234 let repository = context
235 .repository()
236 .ok_or_else(|| Error::InvalidOperation("No repository is available.".to_owned()))?;
237 Ok(Self {
238 context,
239 repository,
240 versions: HashMap::new(),
241 heights: HashMap::new(),
242 current_commit: Oid::ZERO_SHA1,
243 ignore_case: None,
244 })
245 }
246
247 fn ignore_case(&mut self) -> Result<bool> {
248 if let Some(ignore_case) = self.ignore_case {
249 return Ok(ignore_case);
250 }
251 let ignore_case = self
252 .repository
253 .config()?
254 .get_bool("core.ignorecase")
255 .unwrap_or(false);
256 self.ignore_case = Some(ignore_case);
257 Ok(ignore_case)
258 }
259
260 fn version_at(&mut self, commit_id: Oid) -> Result<Option<VersionOptions>> {
261 if let Some(version) = self.versions.get(&commit_id) {
262 return Ok(version.clone());
263 }
264 let ignore_case = self.ignore_case()?;
265 let commit = self.repository.find_commit(commit_id)?;
266 version_at_commit(
267 self.context,
268 self.repository,
269 &mut self.versions,
270 &commit,
271 ignore_case,
272 )
273 }
274}
275
276fn version_at_commit(
277 context: &GitContext,
278 repository: &Repository,
279 versions: &mut HashMap<Oid, Option<VersionOptions>>,
280 commit: &Commit<'_>,
281 ignore_case: bool,
282) -> Result<Option<VersionOptions>> {
283 let commit_id = commit.id();
284 if let Some(version) = versions.get(&commit_id) {
285 return Ok(version.clone());
286 }
287 let version = VersionFile::new(context)
288 .get_version_from_commit(
289 repository,
290 commit,
291 ignore_case,
292 VersionFileRequirements::default(),
293 )
294 .map_err(|error| {
295 Error::InvalidOperation(format!(
296 "Unable to get version from commit {commit_id}: {error}"
297 ))
298 })?
299 .0;
300 versions.insert(commit_id, version.clone());
301 Ok(version)
302}
303
304fn selected_commit_id(context: &GitContext) -> Result<Oid> {
305 context
306 .git_commit_id()
307 .ok_or_else(|| Error::InvalidOperation("No commit is selected.".to_owned()))
308}
309
310fn commit_height<F>(
311 tracker: &mut HistoryTracker<'_>,
312 start: Oid,
313 mut continue_stepping: F,
314) -> Result<VersionHeightCalculation>
315where
316 F: FnMut(&mut HistoryTracker<'_>) -> Result<bool>,
317{
318 tracker.current_commit = start;
319 if !continue_stepping(tracker)? {
320 return Ok(VersionHeightCalculation {
321 height: 0,
322 commit_id: Some(start),
323 });
324 }
325
326 let mut stack = vec![start];
327 while let Some(&commit_id) = stack.last() {
328 if tracker.heights.contains_key(&commit_id) {
329 stack.pop();
330 continue;
331 }
332 let ignore_case = tracker.ignore_case()?;
333 let commit = tracker.repository.find_commit(commit_id)?;
334 let parent_ids: Vec<_> = commit.parent_ids().collect();
335 let mut missing_parent = false;
336 for parent_id in &parent_ids {
337 if tracker.heights.contains_key(parent_id) {
338 continue;
339 }
340 tracker.current_commit = *parent_id;
341 if continue_stepping(tracker)? {
342 stack.push(*parent_id);
343 missing_parent = true;
344 }
345 }
346 if missing_parent {
347 continue;
348 }
349
350 let mut best = VersionHeightCalculation {
351 height: 0,
352 commit_id: None,
353 };
354 for parent_id in parent_ids {
355 if let Some(parent) = tracker.heights.get(&parent_id)
356 && (parent.height > best.height
357 || (parent.height == best.height
358 && best.commit_id.is_none()
359 && parent.commit_id.is_some()))
360 {
361 best = *parent;
362 }
363 }
364 let options = version_at_commit(
365 tracker.context,
366 tracker.repository,
367 &mut tracker.versions,
368 &commit,
369 ignore_case,
370 )?;
371 let relevant = match options
372 .as_ref()
373 .and_then(|options| options.path_filters.as_ref())
374 {
375 Some(filters) => is_relevant_commit(tracker.repository, &commit, filters, ignore_case)?,
376 None => true,
377 };
378 let height = best.height + u32::from(relevant);
379 tracker.heights.insert(
380 commit_id,
381 VersionHeightCalculation {
382 height,
383 commit_id: if relevant {
384 Some(commit_id)
385 } else {
386 best.commit_id
387 },
388 },
389 );
390 stack.pop();
391 }
392 Ok(*tracker
393 .heights
394 .get(&start)
395 .expect("the starting commit was evaluated"))
396}
397
398fn commit_matches_version(
399 commit_id: Oid,
400 expected: &SemanticVersion,
401 precision: VersionPosition,
402 tracker: &mut HistoryTracker<'_>,
403) -> Result<bool> {
404 let Some(options) = tracker.version_at(commit_id)? else {
405 return Ok(false);
406 };
407 let Some(actual) = options.version.as_ref() else {
408 return Ok(false);
409 };
410 Ok(options.version_height_position() == Some(precision)
411 && !SemanticVersion::will_version_change_reset_version_height(actual, expected, precision)?)
412}
413
414fn is_relevant_commit(
415 repository: &Repository,
416 commit: &Commit<'_>,
417 filters: &[crate::FilterPath],
418 ignore_case: bool,
419) -> Result<bool> {
420 let tree = commit.tree()?;
421 if commit.parent_count() == 0 {
422 return diff_is_relevant(repository, None, &tree, filters, ignore_case);
423 }
424 for parent in commit.parents() {
425 let parent_tree = parent.tree()?;
426 if diff_is_relevant(repository, Some(&parent_tree), &tree, filters, ignore_case)? {
427 return Ok(true);
428 }
429 }
430 Ok(false)
431}
432
433fn diff_is_relevant(
434 repository: &Repository,
435 old_tree: Option<&git2::Tree<'_>>,
436 new_tree: &git2::Tree<'_>,
437 filters: &[crate::FilterPath],
438 ignore_case: bool,
439) -> Result<bool> {
440 let mut options = DiffOptions::new();
441 options.context_lines(0);
442 let diff = repository.diff_tree_to_tree(old_tree, Some(new_tree), Some(&mut options))?;
443 let has_includes = filters.iter().any(crate::FilterPath::is_include);
444 for delta in diff.deltas() {
445 for path in [delta.old_file().path(), delta.new_file().path()]
446 .into_iter()
447 .flatten()
448 {
449 let path = path.to_string_lossy().replace('\\', "/");
450 if (!has_includes
451 || filters
452 .iter()
453 .any(|filter| filter.includes(&path, ignore_case)))
454 && !filters
455 .iter()
456 .any(|filter| filter.excludes(&path, ignore_case))
457 {
458 return Ok(true);
459 }
460 }
461 }
462 Ok(false)
463}
464
465fn commits_reachable_from_refs(repository: &Repository) -> Result<Vec<Oid>> {
466 let mut queue = VecDeque::new();
467 if let Ok(head) = repository.head().and_then(|head| head.peel_to_commit()) {
468 queue.push_back(head.id());
469 }
470 for reference in repository.references()? {
471 let reference = reference?;
472 if let Ok(commit) = reference.peel_to_commit() {
473 queue.push_back(commit.id());
474 }
475 }
476 let mut visited = HashSet::new();
477 let mut commits = Vec::new();
478 while let Some(commit_id) = queue.pop_front() {
479 if !visited.insert(commit_id) {
480 continue;
481 }
482 let commit = repository.find_commit(commit_id)?;
483 commits.push(commit_id);
484 queue.extend(commit.parent_ids());
485 }
486 Ok(commits)
487}
488
489fn version_height_mismatch(
490 version: &Version,
491 options: &VersionOptions,
492 commit_id: Oid,
493 tracker: &mut HistoryTracker<'_>,
494) -> Result<bool> {
495 let Some(position) = options.version_height_position() else {
496 return Ok(false);
497 };
498 if position > VersionPosition::Revision {
499 return Ok(false);
500 }
501 let expected = read_version_position(*version, position)?;
502 let comparison_precision = match position {
503 VersionPosition::Major => return Ok(false),
504 VersionPosition::Minor => VersionPosition::Major,
505 VersionPosition::Build => VersionPosition::Minor,
506 VersionPosition::Revision => VersionPosition::Build,
507 _ => unreachable!(),
508 };
509 let calculation = commit_height(tracker, commit_id, |tracker| {
510 commit_matches_numeric_version(
511 tracker.current_commit,
512 version,
513 comparison_precision,
514 tracker,
515 )
516 })?;
517 let actual =
518 i64::from(calculation.height) + i64::from(options.effective_version_height_offset());
519 Ok(expected != actual)
520}
521
522fn commit_matches_numeric_version(
523 commit_id: Oid,
524 expected: &Version,
525 precision: VersionPosition,
526 tracker: &mut HistoryTracker<'_>,
527) -> Result<bool> {
528 let Some(options) = tracker.version_at(commit_id)? else {
529 return Ok(false);
530 };
531 let Some(actual) = options.version.as_ref() else {
532 return Ok(false);
533 };
534 for position in [
535 VersionPosition::Major,
536 VersionPosition::Minor,
537 VersionPosition::Build,
538 VersionPosition::Revision,
539 ]
540 .into_iter()
541 .take(precision as usize + 1)
542 {
543 if actual.read_version_position(position)? != read_version_position(*expected, position)? {
544 return Ok(false);
545 }
546 }
547 Ok(true)
548}
549
550fn commit_id_mismatch(version: &Version, options: &VersionOptions, commit_id: Oid) -> Result<bool> {
551 let Some(position) = options.git_commit_id_position() else {
552 return Ok(false);
553 };
554 if position > VersionPosition::Revision {
555 return Ok(false);
556 }
557 let expected = read_version_position(*version, position)?;
558 if expected < 0 {
559 return Ok(false);
560 }
561 let expected = u16::try_from(expected).map_err(|_| {
562 Error::InvalidFormat(format!("Commit ID component {expected} is not 16-bit."))
563 })?;
564 let bytes = commit_id.as_bytes();
565 let big = u16::from_be_bytes([bytes[0], bytes[1]]);
566 let little = u16::from_le_bytes([bytes[0], bytes[1]]);
567 let mask = if u32::from(expected) == MAXIMUM_VERSION_COMPONENT {
568 0xfffe
569 } else {
570 0xffff
571 };
572 Ok((big & mask) != expected && (little & mask) != expected)
573}
574
575fn read_version_position(version: Version, position: VersionPosition) -> Result<i64> {
576 match position {
577 VersionPosition::Major => Ok(i64::from(version.major)),
578 VersionPosition::Minor => Ok(i64::from(version.minor)),
579 VersionPosition::Build => Ok(version.build_or_unspecified()),
580 VersionPosition::Revision => Ok(version.revision_or_unspecified()),
581 _ => Err(Error::InvalidOperation(
582 "The position must be numeric.".to_owned(),
583 )),
584 }
585}
586
587#[cfg(test)]
588mod tests {
589 use std::fs;
590 use std::path::PathBuf;
591 use std::sync::atomic::{AtomicU64, Ordering};
592
593 use git2::{IndexAddOption, Signature};
594
595 use super::*;
596 use crate::GitEngine;
597
598 static NEXT_REPOSITORY: AtomicU64 = AtomicU64::new(0);
599
600 struct TestRepository {
601 path: PathBuf,
602 }
603
604 impl TestRepository {
605 fn new() -> Self {
606 let id = NEXT_REPOSITORY.fetch_add(1, Ordering::Relaxed);
607 let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
608 .join("target")
609 .join("test-repositories")
610 .join(format!("history-{}-{id}", std::process::id()));
611 let _ = fs::remove_dir_all(&path);
612 fs::create_dir_all(&path).unwrap();
613 Repository::init(&path).unwrap();
614 Self { path }
615 }
616
617 fn commit(&self, message: &str, parents: &[Oid]) -> Oid {
618 let repository = Repository::open(&self.path).unwrap();
619 let mut index = repository.index().unwrap();
620 index.add_all(["*"], IndexAddOption::DEFAULT, None).unwrap();
621 index.write().unwrap();
622 drop(index);
623 drop(repository);
624 self.commit_index(message, parents)
625 }
626
627 fn commit_index(&self, message: &str, parents: &[Oid]) -> Oid {
628 let repository = Repository::open(&self.path).unwrap();
629 let mut index = repository.index().unwrap();
630 let tree_id = index.write_tree().unwrap();
631 let tree = repository.find_tree(tree_id).unwrap();
632 let signature = Signature::now("Test", "test@example.com").unwrap();
633 let parents: Vec<_> = parents
634 .iter()
635 .map(|id| repository.find_commit(*id).unwrap())
636 .collect();
637 let commit = repository
638 .commit(
639 None,
640 &signature,
641 &signature,
642 message,
643 &tree,
644 &parents.iter().collect::<Vec<_>>(),
645 )
646 .unwrap();
647 repository
648 .reference("refs/heads/master", commit, true, "test")
649 .unwrap();
650 repository.set_head("refs/heads/master").unwrap();
651 commit
652 }
653
654 fn commit_head(&self, message: &str) -> Oid {
655 let repository = Repository::open(&self.path).unwrap();
656 let parents: Vec<_> = repository
657 .head()
658 .ok()
659 .and_then(|head| head.target())
660 .into_iter()
661 .collect();
662 drop(repository);
663 self.commit(message, &parents)
664 }
665
666 fn context(&self, commit: Oid, project: &str) -> GitContext {
667 let mut context =
668 GitContext::create(&self.path, Some(&commit.to_string()), GitEngine::ReadOnly)
669 .unwrap();
670 context
671 .set_repo_relative_project_directory(project)
672 .unwrap();
673 context
674 }
675 }
676
677 impl Drop for TestRepository {
678 fn drop(&mut self) {
679 let _ = fs::remove_dir_all(&self.path);
680 }
681 }
682
683 #[test]
684 fn height_uses_longest_merge_path_and_stops_each_path() {
685 let test = TestRepository::new();
686 let root = test.commit("root", &[]);
687 let short = test.commit("short", &[root]);
688 let long1 = test.commit("long1", &[root]);
689 let long2 = test.commit("long2", &[long1]);
690 let long3 = test.commit("long3", &[long2]);
691 let merge = test.commit("merge", &[short, long3]);
692 let context = test.context(merge, "");
693 assert_eq!(5, get_height(&context).unwrap());
694
695 let mut tracker = HistoryTracker::new(&context).unwrap();
696 let stopped = commit_height(&mut tracker, merge, |tracker| {
697 Ok(tracker.current_commit != long1 && tracker.current_commit != short)
698 })
699 .unwrap();
700 assert_eq!(3, stopped.height);
701 }
702
703 #[test]
704 fn version_changes_reset_height_and_working_copy_can_reset_to_zero() {
705 let test = TestRepository::new();
706 fs::write(test.path.join("version.json"), r#"{"version":"1.0"}"#).unwrap();
707 let first = test.commit_head("1.0");
708 let second = test.commit_head("more");
709 fs::write(test.path.join("version.json"), r#"{"version":"1.1"}"#).unwrap();
710 let third = test.commit_head("1.1");
711 assert_eq!(
712 2,
713 get_version_height(&test.context(second, ""), None)
714 .unwrap()
715 .height
716 );
717 let context = test.context(third, "");
718 assert_eq!(1, get_version_height(&context, None).unwrap().height);
719
720 let committed = VersionOptions::from_version(Version::new(1, 1), None).unwrap();
721 let working = VersionOptions::from_version(Version::new(1, 2), None).unwrap();
722 assert_eq!(
723 0,
724 calculate_version_height(&context, Some(&committed), Some(&working))
725 .unwrap()
726 .height
727 );
728 assert_ne!(first, third);
729 }
730
731 #[test]
732 fn filters_count_add_modify_delete_and_ignore_other_paths() {
733 let test = TestRepository::new();
734 fs::create_dir_all(test.path.join("project")).unwrap();
735 fs::write(
736 test.path.join("project/version.json"),
737 r#"{"version":"1.0","pathFilters":["./**",":!/project/excluded/**"]}"#,
738 )
739 .unwrap();
740 let one = test.commit_head("version");
741 fs::write(test.path.join("outside.txt"), "outside").unwrap();
742 let two = test.commit_head("outside");
743 fs::write(test.path.join("project/included.txt"), "included").unwrap();
744 let three = test.commit_head("included");
745 fs::create_dir_all(test.path.join("project/excluded")).unwrap();
746 fs::write(test.path.join("project/excluded/no.txt"), "excluded").unwrap();
747 let four = test.commit_head("excluded");
748 fs::remove_dir_all(test.path.join("project/excluded")).unwrap();
749 let five = test.commit_head("delete excluded directory");
750 fs::remove_file(test.path.join("project/included.txt")).unwrap();
751 let six = test.commit_head("delete included");
752
753 assert_eq!(
754 1,
755 get_version_height(&test.context(one, "project"), None)
756 .unwrap()
757 .height
758 );
759 assert_eq!(
760 1,
761 get_version_height(&test.context(two, "project"), None)
762 .unwrap()
763 .height
764 );
765 assert_eq!(
766 2,
767 get_version_height(&test.context(three, "project"), None)
768 .unwrap()
769 .height
770 );
771 assert_eq!(
772 2,
773 get_version_height(&test.context(four, "project"), None)
774 .unwrap()
775 .height
776 );
777 assert_eq!(
778 2,
779 get_version_height(&test.context(five, "project"), None)
780 .unwrap()
781 .height
782 );
783 assert_eq!(
784 3,
785 get_version_height(&test.context(six, "project"), None)
786 .unwrap()
787 .height
788 );
789 }
790
791 #[test]
792 fn only_exclude_filter_counts_deleting_an_included_file() {
793 let test = TestRepository::new();
794 fs::write(
795 test.path.join("version.json"),
796 r#"{"version":"1.2","pathFilters":[":!README.md"]}"#,
797 )
798 .unwrap();
799 test.commit_head("version");
800 fs::write(test.path.join("included.txt"), "included").unwrap();
801 let added = test.commit_head("add included file");
802 fs::remove_file(test.path.join("included.txt")).unwrap();
803 let deleted = test.commit_head("delete included file");
804
805 assert_eq!(
806 2,
807 get_version_height(&test.context(added, ""), None)
808 .unwrap()
809 .height
810 );
811 assert_eq!(
812 3,
813 get_version_height(&test.context(deleted, ""), None)
814 .unwrap()
815 .height
816 );
817 }
818
819 #[test]
820 fn included_file_mode_change_increases_height() {
821 let test = TestRepository::new();
822 fs::write(
823 test.path.join("version.json"),
824 r#"{"version":"1.2","pathFilters":["included.txt"]}"#,
825 )
826 .unwrap();
827 fs::write(test.path.join("included.txt"), "included").unwrap();
828 let added = test.commit_head("add included file");
829
830 let repository = Repository::open(&test.path).unwrap();
831 let mut index = repository.index().unwrap();
832 let mut entry = index
833 .get_path(std::path::Path::new("included.txt"), 0)
834 .unwrap();
835 entry.mode = 0o100755;
836 index.add(&entry).unwrap();
837 index.write().unwrap();
838 drop(index);
839 drop(repository);
840 let mode_changed = test.commit_index("make included file executable", &[added]);
841
842 assert_eq!(
843 1,
844 get_version_height(&test.context(added, ""), None)
845 .unwrap()
846 .height
847 );
848 assert_eq!(
849 2,
850 get_version_height(&test.context(mode_changed, ""), None)
851 .unwrap()
852 .height
853 );
854 }
855
856 #[test]
857 fn include_filter_honors_ignore_case() {
858 let test = TestRepository::new();
859 let repository = Repository::open(&test.path).unwrap();
860 repository
861 .config()
862 .unwrap()
863 .set_bool("core.ignorecase", true)
864 .unwrap();
865 drop(repository);
866 fs::write(
867 test.path.join("version.json"),
868 r#"{"version":"1.2","pathFilters":["SRC/INCLUDED.TXT"]}"#,
869 )
870 .unwrap();
871 fs::create_dir_all(test.path.join("src")).unwrap();
872 fs::write(test.path.join("src/included.txt"), "included").unwrap();
873 let commit = test.commit_head("add included file with different casing");
874
875 assert_eq!(
876 1,
877 get_version_height(&test.context(commit, ""), None)
878 .unwrap()
879 .height
880 );
881 }
882
883 #[test]
884 fn replacing_file_with_included_directory_increases_height() {
885 let test = TestRepository::new();
886 fs::write(
887 test.path.join("version.json"),
888 r#"{"version":"1.2","pathFilters":["target/included.txt"]}"#,
889 )
890 .unwrap();
891 fs::write(test.path.join("target"), "not included").unwrap();
892 let file = test.commit_head("add file outside filter");
893 fs::remove_file(test.path.join("target")).unwrap();
894 fs::create_dir(test.path.join("target")).unwrap();
895 fs::write(test.path.join("target/included.txt"), "included").unwrap();
896 let directory = test.commit_head("replace file with included directory");
897
898 assert_eq!(
899 0,
900 get_version_height(&test.context(file, ""), None)
901 .unwrap()
902 .height
903 );
904 assert_eq!(
905 1,
906 get_version_height(&test.context(directory, ""), None)
907 .unwrap()
908 .height
909 );
910 }
911
912 #[test]
913 fn replacing_included_directory_with_file_increases_height() {
914 let test = TestRepository::new();
915 fs::write(
916 test.path.join("version.json"),
917 r#"{"version":"1.2","pathFilters":["target/included.txt"]}"#,
918 )
919 .unwrap();
920 fs::create_dir(test.path.join("target")).unwrap();
921 fs::write(test.path.join("target/included.txt"), "included").unwrap();
922 let directory = test.commit_head("add included directory");
923 fs::remove_dir_all(test.path.join("target")).unwrap();
924 fs::write(test.path.join("target"), "not included").unwrap();
925 let file = test.commit_head("replace included directory with file");
926
927 assert_eq!(
928 1,
929 get_version_height(&test.context(directory, ""), None)
930 .unwrap()
931 .height
932 );
933 assert_eq!(
934 2,
935 get_version_height(&test.context(file, ""), None)
936 .unwrap()
937 .height
938 );
939 }
940
941 #[test]
942 fn wildcard_include_filter_counts_matching_path() {
943 let test = TestRepository::new();
944 fs::write(
945 test.path.join("version.json"),
946 r#"{"version":"1.2","pathFilters":["dir/*.txt"]}"#,
947 )
948 .unwrap();
949 fs::create_dir(test.path.join("dir")).unwrap();
950 fs::write(test.path.join("dir/value.txt"), "included").unwrap();
951 let commit = test.commit_head("add wildcard-matched file");
952
953 assert_eq!(
954 1,
955 get_version_height(&test.context(commit, ""), None)
956 .unwrap()
957 .height
958 );
959 }
960
961 #[test]
962 fn encoding_uses_big_endian_cap_offset_and_defaults() {
963 let id = Oid::from_str("ffff000000000000000000000000000000000000").unwrap();
964 let options: VersionOptions =
965 serde_json::from_str(r#"{"version":"1.2","versionHeightOffset":5}"#).unwrap();
966 assert_eq!(0xffff, truncated_commit_id(id));
967 assert_eq!(
968 Version::new_with_revision(1, 2, 8, 0xfffe),
969 encode_version(Some(id), Some(&options), 3).unwrap()
970 );
971 assert_eq!(
972 Version::new_with_revision(0, 0, 0, 0),
973 encode_version(None, None, 0).unwrap()
974 );
975 assert!(encode_version(Some(id), Some(&options), 0xffff).is_err());
976 assert!(
977 !commit_id_mismatch(
978 &Version::new_with_revision(1, 2, 3, 0xfffe),
979 &VersionOptions::from_version(Version::new(1, 2), None).unwrap(),
980 id,
981 )
982 .unwrap()
983 );
984 }
985
986 #[test]
987 fn reverse_lookup_accepts_both_endians_and_subdirectories() {
988 let test = TestRepository::new();
989 fs::create_dir_all(test.path.join("sub")).unwrap();
990 fs::write(test.path.join("version.json"), r#"{"version":"1.0"}"#).unwrap();
991 fs::write(test.path.join("sub/version.json"), r#"{"version":"2.0"}"#).unwrap();
992 let commit = test.commit_head("versions");
993 let root_context = test.context(commit, "");
994 let sub_context = test.context(commit, "sub");
995 let root_height = get_version_height(&root_context, None).unwrap();
996 let encoded = encode_version(
997 Some(commit),
998 VersionFile::new(&root_context)
999 .get_version(VersionFileRequirements::default())
1000 .unwrap()
1001 .0
1002 .as_ref(),
1003 root_height.height,
1004 )
1005 .unwrap();
1006 assert_eq!(
1007 Some(commit),
1008 get_commit_from_version(&root_context, &encoded).unwrap()
1009 );
1010 assert_eq!(
1011 None,
1012 get_commit_from_version(&sub_context, &encoded).unwrap()
1013 );
1014
1015 let swapped = Version::new_with_revision(
1016 encoded.major,
1017 encoded.minor,
1018 encoded.build.unwrap(),
1019 u32::from((encoded.revision.unwrap() as u16).swap_bytes()),
1020 );
1021 assert_eq!(
1022 Some(commit),
1023 get_commit_from_version(&root_context, &swapped).unwrap()
1024 );
1025 }
1026
1027 #[test]
1028 fn reverse_lookup_rejects_versions_missing_the_height_component() {
1029 for (version_json, version) in [
1030 (r#"{"version":"1.2"}"#, Version::new(1, 2)),
1031 (r#"{"version":"1.2.3"}"#, Version::new_with_build(1, 2, 3)),
1032 ] {
1033 let test = TestRepository::new();
1034 fs::write(test.path.join("version.json"), version_json).unwrap();
1035 let commit = test.commit_head("version");
1036 let context = test.context(commit, "");
1037 assert_eq!(None, get_commit_from_version(&context, &version).unwrap());
1038 }
1039 }
1040
1041 #[test]
1042 fn ambiguity_is_reported_but_all_matches_are_available() {
1043 let test = TestRepository::new();
1044 fs::write(test.path.join("version.json"), r#"{"version":"1.2.3.4"}"#).unwrap();
1045 let first = test.commit_head("first");
1046 let second = test.commit_head("second");
1047 let context = test.context(second, "");
1048 let version = Version::new_with_revision(1, 2, 3, 4);
1049 let matches = get_commits_from_version(&context, &version).unwrap();
1050 assert!(matches.contains(&first));
1051 assert!(matches.contains(&second));
1052 assert!(get_commit_from_version(&context, &version).is_err());
1053 }
1054
1055 #[test]
1056 fn missing_shallow_parent_is_an_error() {
1057 let test = TestRepository::new();
1058 fs::write(test.path.join("version.json"), r#"{"version":"1.0"}"#).unwrap();
1059 let parent = test.commit_head("parent");
1060 let child = test.commit_head("child");
1061 let repository = Repository::open(&test.path).unwrap();
1062 fs::write(repository.path().join("shallow"), format!("{parent}\n")).unwrap();
1063 let parent_path = repository
1064 .path()
1065 .join("objects")
1066 .join(&parent.to_string()[..2])
1067 .join(&parent.to_string()[2..]);
1068 drop(repository);
1069 if parent_path.exists() {
1070 fs::remove_file(parent_path).unwrap();
1071 }
1072 let error = get_version_height(&test.context(child, ""), None).unwrap_err();
1073 assert!(
1074 error.to_string().contains("object")
1075 || error.to_string().contains("commit")
1076 || error.to_string().contains("not found")
1077 );
1078 }
1079}