Skip to main content

nerdbank_gitversioning/
history.rs

1// Copyright (c) .NET Foundation and Contributors. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
4//! Git history traversal and the numeric version encoding derived from it.
5
6use 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
15/// The largest build or revision value accepted by the CLR and Windows version resources.
16pub const MAXIMUM_VERSION_COMPONENT: u32 = 0xfffe;
17
18/// A version height and the commit that most recently contributed to it.
19#[derive(Clone, Copy, Debug, Eq, PartialEq)]
20pub struct VersionHeightCalculation {
21    /// The number of relevant commits on the longest ancestry path.
22    pub height: u32,
23    /// The commit that most recently contributed to `height`.
24    pub commit_id: Option<Oid>,
25}
26
27/// Calculates the longest single ancestry path, including the selected commit.
28pub 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
34/// Calculates version height at the selected commit.
35///
36/// When `base_version` is omitted, the selected commit's version is used. The walk stops
37/// independently on each ancestry path as soon as a version change resets height.
38pub 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
75/// Applies working-copy reset rules before calculating committed version height.
76pub 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/// Returns the first two object-ID bytes interpreted in network byte order.
100#[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
105/// Encodes version height and commit identity in a four-component numeric version.
106pub 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
161/// Selects committed or working options and encodes a completed height calculation.
162///
163/// When path filtering left the selected commit irrelevant, the ID of the most recent
164/// relevant commit is encoded while the full selected commit ID remains available from
165/// [`GitContext`].
166pub 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
184/// Finds all commits reachable from named references that could have produced `version`.
185pub 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
209/// Finds the unique reachable commit that could have produced `version`.
210///
211/// An ambiguous version is an error rather than an arbitrary match.
212pub 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            let tree_id = index.write_tree().unwrap();
623            let tree = repository.find_tree(tree_id).unwrap();
624            let signature = Signature::now("Test", "test@example.com").unwrap();
625            let parents: Vec<_> = parents
626                .iter()
627                .map(|id| repository.find_commit(*id).unwrap())
628                .collect();
629            let commit = repository
630                .commit(
631                    None,
632                    &signature,
633                    &signature,
634                    message,
635                    &tree,
636                    &parents.iter().collect::<Vec<_>>(),
637                )
638                .unwrap();
639            repository
640                .reference("refs/heads/master", commit, true, "test")
641                .unwrap();
642            repository.set_head("refs/heads/master").unwrap();
643            commit
644        }
645
646        fn commit_head(&self, message: &str) -> Oid {
647            let repository = Repository::open(&self.path).unwrap();
648            let parents: Vec<_> = repository
649                .head()
650                .ok()
651                .and_then(|head| head.target())
652                .into_iter()
653                .collect();
654            drop(repository);
655            self.commit(message, &parents)
656        }
657
658        fn context(&self, commit: Oid, project: &str) -> GitContext {
659            let mut context =
660                GitContext::create(&self.path, Some(&commit.to_string()), GitEngine::ReadOnly)
661                    .unwrap();
662            context
663                .set_repo_relative_project_directory(project)
664                .unwrap();
665            context
666        }
667    }
668
669    impl Drop for TestRepository {
670        fn drop(&mut self) {
671            let _ = fs::remove_dir_all(&self.path);
672        }
673    }
674
675    #[test]
676    fn height_uses_longest_merge_path_and_stops_each_path() {
677        let test = TestRepository::new();
678        let root = test.commit("root", &[]);
679        let short = test.commit("short", &[root]);
680        let long1 = test.commit("long1", &[root]);
681        let long2 = test.commit("long2", &[long1]);
682        let long3 = test.commit("long3", &[long2]);
683        let merge = test.commit("merge", &[short, long3]);
684        let context = test.context(merge, "");
685        assert_eq!(5, get_height(&context).unwrap());
686
687        let mut tracker = HistoryTracker::new(&context).unwrap();
688        let stopped = commit_height(&mut tracker, merge, |tracker| {
689            Ok(tracker.current_commit != long1 && tracker.current_commit != short)
690        })
691        .unwrap();
692        assert_eq!(3, stopped.height);
693    }
694
695    #[test]
696    fn version_changes_reset_height_and_working_copy_can_reset_to_zero() {
697        let test = TestRepository::new();
698        fs::write(test.path.join("version.json"), r#"{"version":"1.0"}"#).unwrap();
699        let first = test.commit_head("1.0");
700        let second = test.commit_head("more");
701        fs::write(test.path.join("version.json"), r#"{"version":"1.1"}"#).unwrap();
702        let third = test.commit_head("1.1");
703        assert_eq!(
704            2,
705            get_version_height(&test.context(second, ""), None)
706                .unwrap()
707                .height
708        );
709        let context = test.context(third, "");
710        assert_eq!(1, get_version_height(&context, None).unwrap().height);
711
712        let committed = VersionOptions::from_version(Version::new(1, 1), None).unwrap();
713        let working = VersionOptions::from_version(Version::new(1, 2), None).unwrap();
714        assert_eq!(
715            0,
716            calculate_version_height(&context, Some(&committed), Some(&working))
717                .unwrap()
718                .height
719        );
720        assert_ne!(first, third);
721    }
722
723    #[test]
724    fn filters_count_add_modify_delete_and_ignore_other_paths() {
725        let test = TestRepository::new();
726        fs::create_dir_all(test.path.join("project")).unwrap();
727        fs::write(
728            test.path.join("project/version.json"),
729            r#"{"version":"1.0","pathFilters":["./**",":!/project/excluded/**"]}"#,
730        )
731        .unwrap();
732        let one = test.commit_head("version");
733        fs::write(test.path.join("outside.txt"), "outside").unwrap();
734        let two = test.commit_head("outside");
735        fs::write(test.path.join("project/included.txt"), "included").unwrap();
736        let three = test.commit_head("included");
737        fs::create_dir_all(test.path.join("project/excluded")).unwrap();
738        fs::write(test.path.join("project/excluded/no.txt"), "excluded").unwrap();
739        let four = test.commit_head("excluded");
740        fs::remove_file(test.path.join("project/included.txt")).unwrap();
741        let five = test.commit_head("delete included");
742
743        assert_eq!(
744            1,
745            get_version_height(&test.context(one, "project"), None)
746                .unwrap()
747                .height
748        );
749        assert_eq!(
750            1,
751            get_version_height(&test.context(two, "project"), None)
752                .unwrap()
753                .height
754        );
755        assert_eq!(
756            2,
757            get_version_height(&test.context(three, "project"), None)
758                .unwrap()
759                .height
760        );
761        assert_eq!(
762            2,
763            get_version_height(&test.context(four, "project"), None)
764                .unwrap()
765                .height
766        );
767        assert_eq!(
768            3,
769            get_version_height(&test.context(five, "project"), None)
770                .unwrap()
771                .height
772        );
773    }
774
775    #[test]
776    fn encoding_uses_big_endian_cap_offset_and_defaults() {
777        let id = Oid::from_str("ffff000000000000000000000000000000000000").unwrap();
778        let options: VersionOptions =
779            serde_json::from_str(r#"{"version":"1.2","versionHeightOffset":5}"#).unwrap();
780        assert_eq!(0xffff, truncated_commit_id(id));
781        assert_eq!(
782            Version::new_with_revision(1, 2, 8, 0xfffe),
783            encode_version(Some(id), Some(&options), 3).unwrap()
784        );
785        assert_eq!(
786            Version::new_with_revision(0, 0, 0, 0),
787            encode_version(None, None, 0).unwrap()
788        );
789        assert!(encode_version(Some(id), Some(&options), 0xffff).is_err());
790        assert!(
791            !commit_id_mismatch(
792                &Version::new_with_revision(1, 2, 3, 0xfffe),
793                &VersionOptions::from_version(Version::new(1, 2), None).unwrap(),
794                id,
795            )
796            .unwrap()
797        );
798    }
799
800    #[test]
801    fn reverse_lookup_accepts_both_endians_and_subdirectories() {
802        let test = TestRepository::new();
803        fs::create_dir_all(test.path.join("sub")).unwrap();
804        fs::write(test.path.join("version.json"), r#"{"version":"1.0"}"#).unwrap();
805        fs::write(test.path.join("sub/version.json"), r#"{"version":"2.0"}"#).unwrap();
806        let commit = test.commit_head("versions");
807        let root_context = test.context(commit, "");
808        let sub_context = test.context(commit, "sub");
809        let root_height = get_version_height(&root_context, None).unwrap();
810        let encoded = encode_version(
811            Some(commit),
812            VersionFile::new(&root_context)
813                .get_version(VersionFileRequirements::default())
814                .unwrap()
815                .0
816                .as_ref(),
817            root_height.height,
818        )
819        .unwrap();
820        assert_eq!(
821            Some(commit),
822            get_commit_from_version(&root_context, &encoded).unwrap()
823        );
824        assert_eq!(
825            None,
826            get_commit_from_version(&sub_context, &encoded).unwrap()
827        );
828
829        let swapped = Version::new_with_revision(
830            encoded.major,
831            encoded.minor,
832            encoded.build.unwrap(),
833            u32::from((encoded.revision.unwrap() as u16).swap_bytes()),
834        );
835        assert_eq!(
836            Some(commit),
837            get_commit_from_version(&root_context, &swapped).unwrap()
838        );
839    }
840
841    #[test]
842    fn reverse_lookup_rejects_versions_missing_the_height_component() {
843        for (version_json, version) in [
844            (r#"{"version":"1.2"}"#, Version::new(1, 2)),
845            (r#"{"version":"1.2.3"}"#, Version::new_with_build(1, 2, 3)),
846        ] {
847            let test = TestRepository::new();
848            fs::write(test.path.join("version.json"), version_json).unwrap();
849            let commit = test.commit_head("version");
850            let context = test.context(commit, "");
851            assert_eq!(None, get_commit_from_version(&context, &version).unwrap());
852        }
853    }
854
855    #[test]
856    fn ambiguity_is_reported_but_all_matches_are_available() {
857        let test = TestRepository::new();
858        fs::write(test.path.join("version.json"), r#"{"version":"1.2.3.4"}"#).unwrap();
859        let first = test.commit_head("first");
860        let second = test.commit_head("second");
861        let context = test.context(second, "");
862        let version = Version::new_with_revision(1, 2, 3, 4);
863        let matches = get_commits_from_version(&context, &version).unwrap();
864        assert!(matches.contains(&first));
865        assert!(matches.contains(&second));
866        assert!(get_commit_from_version(&context, &version).is_err());
867    }
868
869    #[test]
870    fn missing_shallow_parent_is_an_error() {
871        let test = TestRepository::new();
872        fs::write(test.path.join("version.json"), r#"{"version":"1.0"}"#).unwrap();
873        let parent = test.commit_head("parent");
874        let child = test.commit_head("child");
875        let repository = Repository::open(&test.path).unwrap();
876        fs::write(repository.path().join("shallow"), format!("{parent}\n")).unwrap();
877        let parent_path = repository
878            .path()
879            .join("objects")
880            .join(&parent.to_string()[..2])
881            .join(&parent.to_string()[2..]);
882        drop(repository);
883        if parent_path.exists() {
884            fs::remove_file(parent_path).unwrap();
885        }
886        let error = get_version_height(&test.context(child, ""), None).unwrap_err();
887        assert!(
888            error.to_string().contains("object")
889                || error.to_string().contains("commit")
890                || error.to_string().contains("not found")
891        );
892    }
893}