Skip to main content

nerdbank_gitversioning/
version_file.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//! Discovery, inheritance, and mutation of `version.json` and `version.txt` files.
5
6use std::fs;
7use std::path::{Path, PathBuf};
8use std::str;
9
10use bitflags::bitflags;
11use git2::{Commit, ObjectType, Repository, Tree};
12
13use crate::{Error, GitContext, GitContextKind, Result, VersionOptions};
14
15/// The legacy version filename.
16pub const VERSION_TXT_FILE_NAME: &str = "version.txt";
17
18/// The JSON version filename.
19pub const VERSION_JSON_FILE_NAME: &str = "version.json";
20
21/// The JSON schema shipped with this crate.
22pub const VERSION_SCHEMA: &str = include_str!("version.schema.json");
23
24bitflags! {
25    /// Controls which version file is returned and whether inheritance is merged.
26    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
27    pub struct VersionFileRequirements: u8 {
28        /// Return one file rather than a merged inheritance result.
29        const NON_MERGED_RESULT = 0x1;
30        /// Require the returned file to specify `version`.
31        const VERSION_SPECIFIED = 0x2;
32        /// Permit returning an inheriting file.
33        const ACCEPT_INHERITING_FILE = 0x4;
34    }
35}
36
37/// Absolute locations discovered while resolving version files.
38#[derive(Clone, Debug, Default, Eq, PartialEq)]
39pub struct VersionFileLocations {
40    /// The first directory containing a non-inheriting version file.
41    pub non_inheriting_version_directory: Option<PathBuf>,
42    /// The first directory containing a file that specifies `version`.
43    pub version_specifying_version_directory: Option<PathBuf>,
44}
45
46/// Reads and writes version files for a Git context.
47pub struct VersionFile<'context> {
48    context: &'context GitContext,
49}
50
51impl<'context> VersionFile<'context> {
52    /// Creates a version-file accessor.
53    #[must_use]
54    pub const fn new(context: &'context GitContext) -> Self {
55        Self { context }
56    }
57
58    /// Returns whether a version file is defined at the context's selected commit.
59    pub fn is_version_defined(&self) -> Result<bool> {
60        Ok(self
61            .get_version(VersionFileRequirements::default())?
62            .0
63            .is_some())
64    }
65
66    /// Reads from the selected Git commit, or from disk when no commit is selected.
67    pub fn get_version(
68        &self,
69        requirements: VersionFileRequirements,
70    ) -> Result<(Option<VersionOptions>, VersionFileLocations)> {
71        self.validate_requirements(requirements)?;
72        match self.context.kind() {
73            GitContextKind::Disabled => Ok((None, VersionFileLocations::default())),
74            GitContextKind::Repository if self.context.git_commit_id().is_some() => {
75                self.get_committed_version(requirements)
76            }
77            GitContextKind::Repository | GitContextKind::NoRepository => {
78                self.get_working_copy_version(requirements)
79            }
80        }
81    }
82
83    /// Reads version files from the working copy, including uncommitted changes.
84    pub fn get_working_copy_version(
85        &self,
86        requirements: VersionFileRequirements,
87    ) -> Result<(Option<VersionOptions>, VersionFileLocations)> {
88        self.validate_requirements(requirements)?;
89        let root = self.context.working_tree_path();
90        let start = self.context.absolute_project_directory();
91        let relative = start.strip_prefix(root).map_err(|_| {
92            Error::InvalidFormat(format!(
93                "Project directory '{}' is not within '{}'.",
94                start.display(),
95                root.display()
96            ))
97        })?;
98        let start = path_to_git(relative);
99        self.read_search_chain(
100            &start,
101            requirements,
102            |directory, filename| {
103                let path = root.join(git_path_to_native(directory)).join(filename);
104                match fs::read(path) {
105                    Ok(content) => Ok(Some(content)),
106                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
107                    Err(error) => Err(error.into()),
108                }
109            },
110            |directory| root.join(git_path_to_native(directory)),
111        )
112    }
113
114    /// Writes `version.json`, or preserves an existing `version.txt` when it can represent
115    /// all the supplied options.
116    pub fn set_version(
117        &self,
118        project_directory: impl AsRef<Path>,
119        version: &VersionOptions,
120        include_schema_property: bool,
121    ) -> Result<PathBuf> {
122        let project_directory = project_directory.as_ref();
123        if version.version.is_none() && !version.inherit {
124            return Err(Error::InvalidFormat(
125                "'version' must be set for a non-inheriting version file.".to_owned(),
126            ));
127        }
128        fs::create_dir_all(project_directory)?;
129
130        let version_txt_path = project_directory.join(VERSION_TXT_FILE_NAME);
131        if version_txt_path.exists() {
132            if is_version_only(version) {
133                let semantic_version = version.version.as_ref().expect("version-only options");
134                let mut content = semantic_version.version.to_string();
135                content.push('\n');
136                content.push_str(&semantic_version.prerelease);
137                fs::write(&version_txt_path, content)?;
138                return Ok(version_txt_path);
139            }
140            fs::remove_file(&version_txt_path)?;
141        }
142
143        let relative = project_directory
144            .strip_prefix(self.context.working_tree_path())
145            .map(path_to_git)
146            .map_err(|_| {
147                Error::InvalidFormat(format!(
148                    "Project directory '{}' is not within '{}'.",
149                    project_directory.display(),
150                    self.context.working_tree_path().display()
151                ))
152            })?;
153        let mut serialized = version.clone();
154        serialized.schema =
155            include_schema_property.then(|| VersionOptions::schema_url().to_owned());
156        let json = serialized.to_json(&relative)?;
157        let version_json_path = project_directory.join(VERSION_JSON_FILE_NAME);
158        fs::write(&version_json_path, json)?;
159        Ok(version_json_path)
160    }
161
162    fn get_committed_version(
163        &self,
164        requirements: VersionFileRequirements,
165    ) -> Result<(Option<VersionOptions>, VersionFileLocations)> {
166        let repository = self.context.repository().ok_or_else(|| {
167            Error::InvalidOperation("No repository is available for commit lookup.".to_owned())
168        })?;
169        let commit_id = self.context.git_commit_id().ok_or_else(|| {
170            Error::InvalidOperation("No commit is selected for commit lookup.".to_owned())
171        })?;
172        let commit = repository.find_commit(commit_id)?;
173        let tree = commit.tree()?;
174        let ignore_case = repository
175            .config()?
176            .get_bool("core.ignorecase")
177            .unwrap_or(false);
178        self.get_version_from_tree(repository, &tree, ignore_case, requirements)
179    }
180
181    pub(crate) fn get_version_from_commit(
182        &self,
183        repository: &Repository,
184        commit: &Commit<'_>,
185        ignore_case: bool,
186        requirements: VersionFileRequirements,
187    ) -> Result<(Option<VersionOptions>, VersionFileLocations)> {
188        self.validate_requirements(requirements)?;
189        let tree = commit.tree()?;
190        self.get_version_from_tree(repository, &tree, ignore_case, requirements)
191    }
192
193    fn get_version_from_tree(
194        &self,
195        repository: &Repository,
196        tree: &Tree<'_>,
197        ignore_case: bool,
198        requirements: VersionFileRequirements,
199    ) -> Result<(Option<VersionOptions>, VersionFileLocations)> {
200        let start = path_to_git(self.context.repo_relative_project_directory());
201        let root = self.context.working_tree_path();
202        self.read_search_chain(
203            &start,
204            requirements,
205            |directory, filename| {
206                let path = join_git_path(directory, filename);
207                read_blob(repository, tree, &path, ignore_case)
208            },
209            |directory| root.join(git_path_to_native(directory)),
210        )
211    }
212
213    fn read_search_chain<ReadFile, Location>(
214        &self,
215        starting_directory: &str,
216        requirements: VersionFileRequirements,
217        mut read_file: ReadFile,
218        location: Location,
219    ) -> Result<(Option<VersionOptions>, VersionFileLocations)>
220    where
221        ReadFile: FnMut(&str, &str) -> Result<Option<Vec<u8>>>,
222        Location: Fn(&str) -> PathBuf,
223    {
224        let mut directory = normalize_git_directory(starting_directory);
225        let mut locations = VersionFileLocations::default();
226        let mut overlays: Vec<(VersionOptions, String)> = Vec::new();
227
228        loop {
229            if let Some(content) = read_file(&directory, VERSION_TXT_FILE_NAME)? {
230                let mut options = read_version_txt(&content).map_err(|error| {
231                    file_error(&join_git_path(&directory, VERSION_TXT_FILE_NAME), error)
232                })?;
233                apply_locations(&options, location(&directory), &mut locations);
234                if !requirements.contains(VersionFileRequirements::NON_MERGED_RESULT) {
235                    for (overlay, _) in overlays.iter().rev() {
236                        options.merge_inheriting(overlay)?;
237                    }
238                }
239                return Ok((
240                    satisfies_requirements(&options, requirements).then_some(options),
241                    locations,
242                ));
243            }
244
245            if let Some(content) = read_file(&directory, VERSION_JSON_FILE_NAME)? {
246                let json = str::from_utf8(&content).map_err(|error| {
247                    Error::InvalidFormat(format!(
248                        "Failure while reading '{}': {error}",
249                        join_git_path(&directory, VERSION_JSON_FILE_NAME)
250                    ))
251                })?;
252                let options = VersionOptions::from_json(json, &directory).map_err(|error| {
253                    file_error(&join_git_path(&directory, VERSION_JSON_FILE_NAME), error)
254                })?;
255                apply_locations(&options, location(&directory), &mut locations);
256
257                if satisfies_requirements(&options, requirements)
258                    && (overlays.is_empty()
259                        || options.inherit
260                        || requirements.contains(VersionFileRequirements::NON_MERGED_RESULT))
261                {
262                    return Ok((Some(options), locations));
263                }
264                if !options.inherit {
265                    if overlays.is_empty()
266                        || requirements.contains(VersionFileRequirements::NON_MERGED_RESULT)
267                    {
268                        return Ok((
269                            satisfies_requirements(&options, requirements).then_some(options),
270                            locations,
271                        ));
272                    }
273                    let mut merged = options;
274                    for (overlay, _) in overlays.iter().rev() {
275                        merged.merge_inheriting(overlay)?;
276                    }
277                    return Ok((
278                        satisfies_requirements(&merged, requirements).then_some(merged),
279                        locations,
280                    ));
281                }
282                overlays.push((options, directory.clone()));
283            }
284
285            let Some(parent) = parent_git_directory(&directory) else {
286                if let Some((_, inheriting_directory)) = overlays.first() {
287                    return Err(Error::InvalidOperation(format!(
288                        "'{}' inherits from an ancestor version.json file, but none exists.",
289                        join_git_path(inheriting_directory, VERSION_JSON_FILE_NAME)
290                    )));
291                }
292                return Ok((None, locations));
293            };
294            directory = parent;
295        }
296    }
297
298    fn validate_requirements(&self, requirements: VersionFileRequirements) -> Result<()> {
299        if requirements.contains(VersionFileRequirements::ACCEPT_INHERITING_FILE)
300            && !requirements.contains(VersionFileRequirements::NON_MERGED_RESULT)
301        {
302            return Err(Error::InvalidFormat(
303                "ACCEPT_INHERITING_FILE requires NON_MERGED_RESULT.".to_owned(),
304            ));
305        }
306        Ok(())
307    }
308}
309
310fn satisfies_requirements(options: &VersionOptions, requirements: VersionFileRequirements) -> bool {
311    (!requirements.contains(VersionFileRequirements::VERSION_SPECIFIED)
312        || options.version.is_some())
313        && (!options.inherit
314            || requirements.contains(VersionFileRequirements::ACCEPT_INHERITING_FILE))
315}
316
317fn apply_locations(
318    options: &VersionOptions,
319    directory: PathBuf,
320    locations: &mut VersionFileLocations,
321) {
322    if options.version.is_some() && locations.version_specifying_version_directory.is_none() {
323        locations.version_specifying_version_directory = Some(directory.clone());
324    }
325    if !options.inherit && locations.non_inheriting_version_directory.is_none() {
326        locations.non_inheriting_version_directory = Some(directory);
327    }
328}
329
330fn read_version_txt(content: &[u8]) -> Result<VersionOptions> {
331    let content = str::from_utf8(content)
332        .map_err(|error| Error::InvalidFormat(format!("version.txt is not UTF-8: {error}")))?;
333    let mut lines = content.lines();
334    let version = lines.next().unwrap_or_default().trim_end_matches('\r');
335    let prerelease = lines
336        .next()
337        .unwrap_or_default()
338        .trim_end_matches('\r')
339        .trim();
340    let combined = if prerelease.is_empty() || prerelease.starts_with('-') {
341        format!("{version}{prerelease}")
342    } else {
343        format!("{version}-{prerelease}")
344    };
345    let version = combined
346        .parse()
347        .map_err(|_| Error::InvalidFormat(format!("Unrecognized version format '{combined}'.")))?;
348    Ok(VersionOptions {
349        version: Some(version),
350        ..VersionOptions::default()
351    })
352}
353
354fn is_version_only(options: &VersionOptions) -> bool {
355    if options.version.is_none() {
356        return false;
357    }
358    let mut value = match serde_json::to_value(options) {
359        Ok(value) => value,
360        Err(_) => return false,
361    };
362    let Some(object) = value.as_object_mut() else {
363        return false;
364    };
365    object.remove("$schema");
366    object.len() == 1 && object.contains_key("version")
367}
368
369fn read_blob(
370    repository: &Repository,
371    root: &Tree<'_>,
372    path: &str,
373    ignore_case: bool,
374) -> Result<Option<Vec<u8>>> {
375    let mut tree = root.clone();
376    let segments: Vec<_> = path
377        .split('/')
378        .filter(|segment| !segment.is_empty())
379        .collect();
380    for (index, segment) in segments.iter().enumerate() {
381        let entry = {
382            let entry = tree.get_name(segment).or_else(|| {
383                ignore_case.then(|| {
384                    tree.iter().find(|entry| {
385                        entry
386                            .name()
387                            .is_ok_and(|name| name.eq_ignore_ascii_case(segment))
388                    })
389                })?
390            });
391            entry.map(|entry| (entry.id(), entry.kind()))
392        };
393        let Some((id, kind)) = entry else {
394            return Ok(None);
395        };
396        if index + 1 == segments.len() {
397            if kind != Some(ObjectType::Blob) {
398                return Ok(None);
399            }
400            return Ok(Some(repository.find_blob(id)?.content().to_vec()));
401        }
402        if kind != Some(ObjectType::Tree) {
403            return Ok(None);
404        }
405        tree = repository.find_tree(id)?;
406    }
407    Ok(None)
408}
409
410fn normalize_git_directory(path: &str) -> String {
411    let mut path = path.replace('\\', "/").trim_matches('/').to_owned();
412    while path.ends_with("/.") {
413        path.truncate(path.len() - 2);
414    }
415    if path == "." {
416        path.clear();
417    }
418    path
419}
420
421fn path_to_git(path: &Path) -> String {
422    path.components()
423        .filter_map(|component| {
424            let value = component.as_os_str().to_string_lossy();
425            (value != ".").then(|| value.into_owned())
426        })
427        .collect::<Vec<_>>()
428        .join("/")
429}
430
431fn git_path_to_native(path: &str) -> PathBuf {
432    path.split('/')
433        .filter(|segment| !segment.is_empty())
434        .collect()
435}
436
437fn join_git_path(directory: &str, filename: &str) -> String {
438    if directory.is_empty() {
439        filename.to_owned()
440    } else {
441        format!("{directory}/{filename}")
442    }
443}
444
445fn parent_git_directory(directory: &str) -> Option<String> {
446    if directory.is_empty() {
447        None
448    } else {
449        Some(
450            directory
451                .rsplit_once('/')
452                .map_or("", |(parent, _)| parent)
453                .to_owned(),
454        )
455    }
456}
457
458fn file_error(path: &str, error: Error) -> Error {
459    Error::InvalidFormat(format!("Failure while reading '{path}': {error}"))
460}
461
462#[cfg(test)]
463mod tests {
464    use std::sync::atomic::{AtomicU64, Ordering};
465
466    use git2::{IndexAddOption, Signature};
467
468    use super::*;
469    use crate::{GitEngine, SemanticVersion, VersionPrecision};
470
471    static NEXT_REPOSITORY: AtomicU64 = AtomicU64::new(0);
472
473    struct TestRepository {
474        path: PathBuf,
475    }
476
477    impl TestRepository {
478        fn new() -> Self {
479            let id = NEXT_REPOSITORY.fetch_add(1, Ordering::Relaxed);
480            let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
481                .join("target")
482                .join("test-repositories")
483                .join(format!("version-file-{}-{id}", std::process::id()));
484            let _ = fs::remove_dir_all(&path);
485            fs::create_dir_all(&path).unwrap();
486            Repository::init(&path).unwrap();
487            Self { path }
488        }
489
490        fn commit(&self, message: &str) -> git2::Oid {
491            let repository = Repository::open(&self.path).unwrap();
492            let mut index = repository.index().unwrap();
493            index.add_all(["*"], IndexAddOption::DEFAULT, None).unwrap();
494            index.write().unwrap();
495            let tree_id = index.write_tree().unwrap();
496            let tree = repository.find_tree(tree_id).unwrap();
497            let signature = Signature::now("Test", "test@example.com").unwrap();
498            let parent = repository
499                .head()
500                .ok()
501                .and_then(|head| head.target())
502                .map(|id| repository.find_commit(id).unwrap());
503            repository
504                .commit(
505                    Some("HEAD"),
506                    &signature,
507                    &signature,
508                    message,
509                    &tree,
510                    &parent.iter().collect::<Vec<_>>(),
511                )
512                .unwrap()
513        }
514    }
515
516    impl Drop for TestRepository {
517        fn drop(&mut self) {
518            let _ = fs::remove_dir_all(&self.path);
519        }
520    }
521
522    fn version(value: &str) -> VersionOptions {
523        VersionOptions {
524            version: Some(value.parse::<SemanticVersion>().unwrap()),
525            ..VersionOptions::default()
526        }
527    }
528
529    #[test]
530    fn working_copy_prefers_version_txt() {
531        let test = TestRepository::new();
532        fs::write(
533            test.path.join(VERSION_JSON_FILE_NAME),
534            r#"{"version":"1.0"}"#,
535        )
536        .unwrap();
537        fs::write(test.path.join(VERSION_TXT_FILE_NAME), "2.3\nbeta").unwrap();
538        let context = GitContext::create(&test.path, None, GitEngine::ReadOnly).unwrap();
539        let (actual, _) = VersionFile::new(&context)
540            .get_working_copy_version(VersionFileRequirements::default())
541            .unwrap();
542        assert_eq!("2.3-beta", actual.unwrap().version.unwrap().to_string());
543    }
544
545    #[test]
546    fn inheritance_merges_and_resolves_relative_filters() {
547        let test = TestRepository::new();
548        fs::write(
549            test.path.join(VERSION_JSON_FILE_NAME),
550            r#"{"version":"1.2","pathFilters":["./root.txt"],"versionHeightOffset":3}"#,
551        )
552        .unwrap();
553        fs::create_dir(test.path.join("child")).unwrap();
554        fs::write(
555            test.path.join("child").join(VERSION_JSON_FILE_NAME),
556            r#"{"inherit":true,"prerelease":"beta","pathFilters":["./child.txt"]}"#,
557        )
558        .unwrap();
559        let context =
560            GitContext::create(test.path.join("child"), None, GitEngine::ReadOnly).unwrap();
561        let (actual, locations) = VersionFile::new(&context)
562            .get_working_copy_version(VersionFileRequirements::default())
563            .unwrap();
564        let actual = actual.unwrap();
565        assert_eq!("1.2-beta", actual.version.unwrap().to_string());
566        assert_eq!(Some(3), actual.version_height_offset);
567        assert_eq!(
568            "child/child.txt",
569            actual.path_filters.unwrap()[0].repo_relative_path()
570        );
571        assert_eq!(
572            Some(test.path.clone()),
573            locations.non_inheriting_version_directory
574        );
575    }
576
577    #[test]
578    fn multilevel_inheritance_matches_managed_merge_semantics() {
579        let test = TestRepository::new();
580        fs::write(
581            test.path.join(VERSION_JSON_FILE_NAME),
582            r#"{"version":"14.2","assemblyVersion":{"precision":"major"}}"#,
583        )
584        .unwrap();
585        fs::create_dir_all(test.path.join("foo/bar")).unwrap();
586        fs::write(
587            test.path.join("foo/version.json"),
588            r#"{"inherit":true,"assemblyVersion":{"precision":"minor"},"prerelease":"beta"}"#,
589        )
590        .unwrap();
591        fs::write(
592            test.path.join("foo/bar/version.json"),
593            r#"{"inherit":true,"versionHeightOffset":1}"#,
594        )
595        .unwrap();
596
597        let context =
598            GitContext::create(test.path.join("foo/bar"), None, GitEngine::ReadOnly).unwrap();
599        let (actual, locations) = VersionFile::new(&context)
600            .get_working_copy_version(VersionFileRequirements::default())
601            .unwrap();
602        let actual = actual.unwrap();
603        assert_eq!("14.2-beta", actual.version.as_ref().unwrap().to_string());
604        assert_eq!(
605            VersionPrecision::Minor,
606            actual.assembly_version_or_default().precision_or_default()
607        );
608        assert_eq!(Some(1), actual.version_height_offset);
609        assert!(!actual.inherit);
610        assert_eq!(None, actual.prerelease);
611        assert_eq!(
612            Some(test.path.clone()),
613            locations.non_inheriting_version_directory
614        );
615        assert_eq!(
616            Some(test.path.clone()),
617            locations.version_specifying_version_directory
618        );
619    }
620
621    #[test]
622    fn requirements_can_return_inheriting_file() {
623        let test = TestRepository::new();
624        fs::write(
625            test.path.join(VERSION_JSON_FILE_NAME),
626            r#"{"version":"1.0"}"#,
627        )
628        .unwrap();
629        fs::create_dir(test.path.join("child")).unwrap();
630        fs::write(
631            test.path.join("child").join(VERSION_JSON_FILE_NAME),
632            r#"{"inherit":true}"#,
633        )
634        .unwrap();
635        let context =
636            GitContext::create(test.path.join("child"), None, GitEngine::ReadOnly).unwrap();
637        let requirements = VersionFileRequirements::NON_MERGED_RESULT
638            | VersionFileRequirements::ACCEPT_INHERITING_FILE;
639        let (actual, _) = VersionFile::new(&context)
640            .get_working_copy_version(requirements)
641            .unwrap();
642        assert!(actual.unwrap().inherit);
643    }
644
645    #[test]
646    fn historical_lookup_and_ignore_case() {
647        let test = TestRepository::new();
648        fs::create_dir(test.path.join("MyProject")).unwrap();
649        fs::write(
650            test.path.join("MyProject").join(VERSION_JSON_FILE_NAME),
651            r#"{"version":"1.2.3"}"#,
652        )
653        .unwrap();
654        test.commit("version");
655        let repository = Repository::open(&test.path).unwrap();
656        repository
657            .config()
658            .unwrap()
659            .set_bool("core.ignorecase", true)
660            .unwrap();
661        drop(repository);
662
663        let mut context =
664            GitContext::create(&test.path, Some("HEAD"), GitEngine::ReadOnly).unwrap();
665        context
666            .set_repo_relative_project_directory("myproject")
667            .unwrap();
668        let (actual, _) = VersionFile::new(&context)
669            .get_version(VersionFileRequirements::default())
670            .unwrap();
671        assert_eq!("1.2.3", actual.unwrap().version.unwrap().to_string());
672    }
673
674    #[test]
675    fn historical_lookup_uses_selected_commit() {
676        let test = TestRepository::new();
677        fs::write(
678            test.path.join(VERSION_JSON_FILE_NAME),
679            r#"{"version":"1.0"}"#,
680        )
681        .unwrap();
682        let first = test.commit("first");
683        fs::write(
684            test.path.join(VERSION_JSON_FILE_NAME),
685            r#"{"version":"2.0"}"#,
686        )
687        .unwrap();
688        test.commit("second");
689
690        let context =
691            GitContext::create(&test.path, Some(&first.to_string()), GitEngine::ReadOnly).unwrap();
692        let (actual, _) = VersionFile::new(&context)
693            .get_version(VersionFileRequirements::default())
694            .unwrap();
695        assert_eq!("1.0", actual.unwrap().version.unwrap().to_string());
696    }
697
698    #[test]
699    fn historical_lookup_can_use_existing_repository_and_commit() {
700        let test = TestRepository::new();
701        fs::write(
702            test.path.join(VERSION_JSON_FILE_NAME),
703            r#"{"version":"1.0"}"#,
704        )
705        .unwrap();
706        let first = test.commit("first");
707        fs::write(
708            test.path.join(VERSION_JSON_FILE_NAME),
709            r#"{"version":"2.0"}"#,
710        )
711        .unwrap();
712        test.commit("second");
713
714        let context = GitContext::create(&test.path, Some("HEAD"), GitEngine::ReadOnly).unwrap();
715        let repository = context.repository().unwrap();
716        let commit = repository.find_commit(first).unwrap();
717        let (actual, _) = VersionFile::new(&context)
718            .get_version_from_commit(
719                repository,
720                &commit,
721                false,
722                VersionFileRequirements::default(),
723            )
724            .unwrap();
725        assert_eq!("1.0", actual.unwrap().version.unwrap().to_string());
726        assert_ne!(Some(first), context.git_commit_id());
727    }
728
729    #[test]
730    fn set_version_serializes_schema_and_contextual_filters() {
731        let test = TestRepository::new();
732        let context = GitContext::create(&test.path, None, GitEngine::ReadOnly).unwrap();
733        let child = test.path.join("child");
734        let mut options = version("3.4");
735        options.path_filters = Some(vec![crate::FilterPath::new("./source", "").unwrap()]);
736        let path = VersionFile::new(&context)
737            .set_version(&child, &options, true)
738            .unwrap();
739        let content = fs::read_to_string(path).unwrap();
740        assert!(content.contains(VersionOptions::schema_url()));
741        assert!(content.contains("../source"));
742    }
743
744    #[test]
745    fn managed_json_compatibility_forms_round_trip_to_canonical_output() {
746        let options = VersionOptions::from_json(
747            r#"{"version":"2.3","assemblyVersion":{"version":"2.2","precision":"revision"},"buildNumberOffset":-1,"publicReleaseRefSpec":["refs/heads/master"]}"#,
748            "",
749        )
750        .unwrap();
751        let serialized: serde_json::Value =
752            serde_json::from_str(&options.to_json("").unwrap()).unwrap();
753        assert_eq!(serialized["version"], "2.3");
754        assert_eq!(serialized["assemblyVersion"]["version"], "2.2");
755        assert_eq!(serialized["assemblyVersion"]["precision"], "revision");
756        assert_eq!(serialized["versionHeightOffset"], -1);
757        assert!(serialized.get("buildNumberOffset").is_none());
758        assert_eq!(
759            serialized["publicReleaseRefSpec"],
760            serde_json::json!(["refs/heads/master"])
761        );
762    }
763
764    #[test]
765    fn existing_version_txt_is_preserved_or_upgraded() {
766        let test = TestRepository::new();
767        fs::write(test.path.join(VERSION_TXT_FILE_NAME), "1.0").unwrap();
768        let context = GitContext::create(&test.path, None, GitEngine::ReadOnly).unwrap();
769        let accessor = VersionFile::new(&context);
770        let txt = accessor
771            .set_version(&test.path, &version("2.0-beta"), false)
772            .unwrap();
773        assert_eq!(VERSION_TXT_FILE_NAME, txt.file_name().unwrap());
774        let mut complex = version("3.0");
775        complex.version_height_offset = Some(5);
776        let json = accessor.set_version(&test.path, &complex, false).unwrap();
777        assert_eq!(VERSION_JSON_FILE_NAME, json.file_name().unwrap());
778        assert!(!test.path.join(VERSION_TXT_FILE_NAME).exists());
779    }
780
781    #[test]
782    fn missing_parent_and_bad_prerelease_are_errors() {
783        let test = TestRepository::new();
784        fs::write(
785            test.path.join(VERSION_JSON_FILE_NAME),
786            r#"{"inherit":true,"prerelease":"beta"}"#,
787        )
788        .unwrap();
789        let context = GitContext::create(&test.path, None, GitEngine::ReadOnly).unwrap();
790        let error = VersionFile::new(&context)
791            .get_working_copy_version(VersionFileRequirements::default())
792            .unwrap_err();
793        assert!(error.to_string().contains("none exists"));
794
795        fs::write(
796            test.path.join(VERSION_JSON_FILE_NAME),
797            r#"{"version":"1.0"}"#,
798        )
799        .unwrap();
800        fs::create_dir(test.path.join("child")).unwrap();
801        fs::write(
802            test.path.join("child").join(VERSION_JSON_FILE_NAME),
803            r#"{"version":"1.0-alpha","inherit":true,"prerelease":"beta"}"#,
804        )
805        .unwrap();
806        let context =
807            GitContext::create(test.path.join("child"), None, GitEngine::ReadOnly).unwrap();
808        let error = VersionFile::new(&context)
809            .get_working_copy_version(VersionFileRequirements::default())
810            .unwrap_err();
811        assert!(error.to_string().contains("already includes a prerelease"));
812    }
813
814    #[test]
815    fn schema_asset_is_valid_json() {
816        let schema: serde_json::Value = serde_json::from_str(VERSION_SCHEMA).unwrap();
817        assert_eq!(
818            Some("Nerdbank.GitVersioning version.json schema"),
819            schema["title"].as_str()
820        );
821    }
822}