Skip to main content

nerdbank_gitversioning/
version_options.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
4use std::fmt;
5use std::str::FromStr;
6
7use serde::de::{self, MapAccess, Visitor};
8use serde::ser::SerializeStruct;
9use serde::{Deserialize, Deserializer, Serialize, Serializer};
10
11use crate::{Error, FilterPath, Result as CrateResult, SemanticVersion, Version, VersionPosition};
12
13/// The default last component controlled in an assembly version.
14pub const DEFAULT_VERSION_PRECISION: VersionPrecision = VersionPrecision::Minor;
15
16/// The placeholder that identifies where version height appears in a semantic version.
17pub const VERSION_HEIGHT_PLACEHOLDER: &str = "{height}";
18
19/// The default fixed length of an abbreviated Git commit ID.
20pub const DEFAULT_GIT_COMMIT_ID_SHORT_FIXED_LENGTH: u32 = 10;
21
22const DEFAULT_SEMVER1_NUMERIC_IDENTIFIER_PADDING: u32 = 4;
23const VERSION_SCHEMA_URL: &str = "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/main/src/NerdBank.GitVersioning/version.schema.json";
24
25/// The last component to control in a four-integer version.
26#[derive(Clone, Copy, Debug, Default, Deserialize, Hash, PartialEq, Eq, Serialize)]
27#[serde(rename_all = "camelCase")]
28pub enum VersionPrecision {
29    /// The first integer is the last number set; the rest are zero.
30    Major,
31    /// The second integer is the last number set; the rest are zero.
32    #[default]
33    Minor,
34    /// The third integer is the last number set; the fourth is zero.
35    Build,
36    /// All four integers are set.
37    Revision,
38}
39
40/// The conditions under which a commit ID is included in a cloud build number.
41#[derive(Clone, Copy, Debug, Default, Deserialize, Hash, PartialEq, Eq, Serialize)]
42#[serde(rename_all = "camelCase")]
43pub enum CloudBuildNumberCommitWhen {
44    /// Always include commit information.
45    Always,
46    /// Include commit information only for non-public releases.
47    #[default]
48    NonPublicReleaseOnly,
49    /// Never include commit information.
50    Never,
51}
52
53/// The position at which a commit ID appears in a cloud build number.
54#[derive(Clone, Copy, Debug, Default, Deserialize, Hash, PartialEq, Eq, Serialize)]
55#[serde(rename_all = "camelCase")]
56pub enum CloudBuildNumberCommitWhere {
57    /// Put the commit ID in build metadata, for example `+ga1b2c3`.
58    #[default]
59    BuildMetadata,
60    /// Use the first 15 bits of the commit ID as the fourth version component.
61    FourthVersionComponent,
62}
63
64/// The component incremented after creating a release branch.
65#[derive(Clone, Copy, Debug, Default, Deserialize, Hash, PartialEq, Eq, Serialize)]
66#[serde(rename_all = "camelCase")]
67pub enum ReleaseVersionIncrement {
68    /// Increment the major version.
69    Major,
70    /// Increment the minor version.
71    #[default]
72    Minor,
73    /// Increment the build component.
74    Build,
75}
76
77/// Describes the versions and policies used by a build.
78///
79/// Optional fields deliberately retain the distinction between an omitted value and an
80/// explicitly configured default. This is required when an inheriting `version.json` is merged
81/// over an ancestor's options.
82#[derive(Clone, Debug, Default, Deserialize, Serialize)]
83#[serde(rename_all = "camelCase")]
84pub struct VersionOptions {
85    /// The schema URI written to a `version.json` file.
86    #[serde(rename = "$schema", default, skip_serializing_if = "Option::is_none")]
87    pub schema: Option<String>,
88
89    /// The version used as the basis for version calculations.
90    #[serde(
91        default,
92        skip_serializing_if = "Option::is_none",
93        deserialize_with = "deserialize_optional_from_string",
94        serialize_with = "serialize_optional_as_string"
95    )]
96    pub version: Option<SemanticVersion>,
97
98    /// The version used for an assembly version instead of `version`.
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub assembly_version: Option<AssemblyVersionOptions>,
101
102    /// The prefix for Git commit IDs in non-public versions.
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub git_commit_id_prefix: Option<String>,
105
106    /// A number added to Git height when calculating version height.
107    ///
108    /// `buildNumberOffset`, used by older files, is accepted as an alias.
109    #[serde(
110        default,
111        alias = "buildNumberOffset",
112        skip_serializing_if = "Option::is_none"
113    )]
114    pub version_height_offset: Option<i32>,
115
116    /// The version to which `versionHeightOffset` applies.
117    #[serde(
118        default,
119        skip_serializing_if = "Option::is_none",
120        deserialize_with = "deserialize_optional_from_string",
121        serialize_with = "serialize_optional_as_string"
122    )]
123    pub version_height_offset_applies_to: Option<SemanticVersion>,
124
125    /// The minimum number of digits used for numeric SemVer 1 identifiers.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub sem_ver1_numeric_identifier_padding: Option<u32>,
128
129    /// The fixed number of characters used for abbreviated Git commit IDs.
130    #[serde(default, skip_serializing_if = "Option::is_none")]
131    pub git_commit_id_short_fixed_length: Option<u32>,
132
133    /// The minimum length used when Git chooses an unambiguous abbreviated commit ID.
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub git_commit_id_short_auto_minimum: Option<u32>,
136
137    /// Whether dirty Git commit IDs are suffixed with `-dirty`.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub git_commit_id_include_dirty: Option<bool>,
140
141    /// Options controlling generated NuGet package versions.
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub nuget_package_version: Option<NuGetPackageVersionOptions>,
144
145    /// Regular expressions for refs that should default to public releases.
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub public_release_ref_spec: Option<Vec<String>>,
148
149    /// Options applicable specifically to cloud builds.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub cloud_build: Option<CloudBuildOptions>,
152
153    /// Settings for release preparation and tagging.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub release: Option<ReleaseOptions>,
156
157    /// Pathspec-like filters used when calculating version height.
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub path_filters: Option<Vec<FilterPath>>,
160
161    /// Whether unset values should be inherited from an ancestor `version.json`.
162    #[serde(default, skip_serializing_if = "is_false")]
163    pub inherit: bool,
164
165    /// A prerelease tag to apply to an inherited version.
166    ///
167    /// An empty string explicitly suppresses an inherited prerelease tag, while `None` leaves it
168    /// unchanged.
169    #[serde(default, skip_serializing_if = "Option::is_none")]
170    pub prerelease: Option<String>,
171}
172
173impl VersionOptions {
174    /// The default last component controlled in an assembly version.
175    pub const DEFAULT_VERSION_PRECISION: VersionPrecision = DEFAULT_VERSION_PRECISION;
176
177    /// The placeholder that identifies where version height appears in a semantic version.
178    pub const VERSION_HEIGHT_PLACEHOLDER: &'static str = VERSION_HEIGHT_PLACEHOLDER;
179
180    /// The default fixed length of an abbreviated Git commit ID.
181    pub const DEFAULT_GIT_COMMIT_ID_SHORT_FIXED_LENGTH: u32 =
182        DEFAULT_GIT_COMMIT_ID_SHORT_FIXED_LENGTH;
183
184    /// Creates options with the specified version and optional prerelease tag.
185    ///
186    /// The prerelease tag follows `SemanticVersion` conventions and includes its leading `-`.
187    pub fn from_version(version: Version, prerelease: Option<&str>) -> CrateResult<Self> {
188        Ok(Self {
189            version: Some(SemanticVersion::new(
190                version,
191                prerelease.unwrap_or_default(),
192                "",
193            )?),
194            ..Self::default()
195        })
196    }
197
198    /// Deserializes options while resolving relative path filters against a repository directory.
199    ///
200    /// Use this instead of plain `serde_json::from_str` when the `version.json` file is below the
201    /// repository root.
202    pub fn from_json(json: &str, repo_relative_base_directory: &str) -> CrateResult<Self> {
203        let mut value: serde_json::Value = serde_json::from_str(json)?;
204        let path_filters = value
205            .as_object_mut()
206            .and_then(|object| object.remove("pathFilters"));
207        let mut options: Self = serde_json::from_value(value)?;
208        if let Some(path_filters) = path_filters {
209            let serde_json::Value::Array(path_filters) = path_filters else {
210                return Err(Error::InvalidFormat(
211                    "'pathFilters' must be an array of strings.".to_owned(),
212                ));
213            };
214            options.path_filters = Some(
215                path_filters
216                    .into_iter()
217                    .map(|path_filter| {
218                        let serde_json::Value::String(path_filter) = path_filter else {
219                            return Err(Error::InvalidFormat(
220                                "Each path filter must be a string.".to_owned(),
221                            ));
222                        };
223                        FilterPath::new(&path_filter, repo_relative_base_directory)
224                    })
225                    .collect::<CrateResult<Vec<_>>>()?,
226            );
227        }
228        Ok(options)
229    }
230
231    /// Serializes options with path filters relative to a repository directory.
232    pub fn to_json(&self, repo_relative_base_directory: &str) -> CrateResult<String> {
233        let mut without_path_filters = self.clone();
234        without_path_filters.path_filters = None;
235        let mut value = serde_json::to_value(without_path_filters)?;
236        if let Some(path_filters) = &self.path_filters {
237            let path_filters = path_filters
238                .iter()
239                .map(|filter| {
240                    filter
241                        .to_path_spec(repo_relative_base_directory)
242                        .map(serde_json::Value::String)
243                })
244                .collect::<CrateResult<Vec<_>>>()?;
245            let Some(object) = value.as_object_mut() else {
246                return Err(Error::InvalidOperation(
247                    "VersionOptions did not serialize as an object.".to_owned(),
248                ));
249            };
250            object.insert(
251                "pathFilters".to_owned(),
252                serde_json::Value::Array(path_filters),
253            );
254        }
255        Ok(serde_json::to_string_pretty(&value)?)
256    }
257
258    /// Returns the schema URI used by Nerdbank.GitVersioning.
259    #[must_use]
260    pub const fn schema_url() -> &'static str {
261        VERSION_SCHEMA_URL
262    }
263
264    /// Returns the configured assembly-version options or their defaults.
265    #[must_use]
266    pub fn assembly_version_or_default(&self) -> AssemblyVersionOptions {
267        self.assembly_version.clone().unwrap_or_default()
268    }
269
270    /// Returns the configured version-height offset, defaulting to zero.
271    #[must_use]
272    pub fn version_height_offset_or_default(&self) -> i32 {
273        self.version_height_offset.unwrap_or(0)
274    }
275
276    /// Returns the effective version-height offset.
277    ///
278    /// The configured offset becomes ineffective when the version has changed in a component
279    /// that resets height relative to `versionHeightOffsetAppliesTo`.
280    #[must_use]
281    pub fn effective_version_height_offset(&self) -> i32 {
282        if let (Some(applies_to), Some(version), Some(position)) = (
283            &self.version_height_offset_applies_to,
284            &self.version,
285            self.version_height_position(),
286        ) && SemanticVersion::will_version_change_reset_version_height(
287            applies_to, version, position,
288        )
289        .unwrap_or(true)
290        {
291            return 0;
292        }
293
294        self.version_height_offset_or_default()
295    }
296
297    /// Returns the position in a computed version where version height should appear.
298    #[must_use]
299    pub fn version_height_position(&self) -> Option<VersionPosition> {
300        self.version
301            .as_ref()
302            .and_then(SemanticVersion::version_height_position)
303    }
304
305    /// Returns where commit-ID bits should appear in the numeric version, if anywhere.
306    #[must_use]
307    pub fn git_commit_id_position(&self) -> Option<VersionPosition> {
308        self.version
309            .as_ref()
310            .and_then(SemanticVersion::git_commit_id_position)
311    }
312
313    /// Returns the minimum SemVer 1 numeric identifier width.
314    #[must_use]
315    pub fn sem_ver1_numeric_identifier_padding_or_default(&self) -> u32 {
316        self.sem_ver1_numeric_identifier_padding
317            .unwrap_or(DEFAULT_SEMVER1_NUMERIC_IDENTIFIER_PADDING)
318    }
319
320    /// Returns the fixed abbreviated Git commit ID length.
321    #[must_use]
322    pub fn git_commit_id_short_fixed_length_or_default(&self) -> u32 {
323        self.git_commit_id_short_fixed_length
324            .unwrap_or(DEFAULT_GIT_COMMIT_ID_SHORT_FIXED_LENGTH)
325    }
326
327    /// Returns the automatic abbreviated Git commit ID minimum, defaulting to zero.
328    #[must_use]
329    pub fn git_commit_id_short_auto_minimum_or_default(&self) -> u32 {
330        self.git_commit_id_short_auto_minimum.unwrap_or(0)
331    }
332
333    /// Returns whether dirty Git commit IDs are marked, defaulting to `false`.
334    #[must_use]
335    pub fn git_commit_id_include_dirty_or_default(&self) -> bool {
336        self.git_commit_id_include_dirty.unwrap_or(false)
337    }
338
339    /// Returns the configured NuGet package options or their defaults.
340    #[must_use]
341    pub fn nuget_package_version_or_default(&self) -> NuGetPackageVersionOptions {
342        self.nuget_package_version.clone().unwrap_or_default()
343    }
344
345    /// Returns the configured cloud-build options or their defaults.
346    #[must_use]
347    pub fn cloud_build_or_default(&self) -> CloudBuildOptions {
348        self.cloud_build.clone().unwrap_or_default()
349    }
350
351    /// Returns the configured release options or their defaults.
352    #[must_use]
353    pub fn release_or_default(&self) -> ReleaseOptions {
354        self.release.clone().unwrap_or_default()
355    }
356
357    /// Returns the public-release ref specifications, or an empty slice when none were configured.
358    #[must_use]
359    pub fn public_release_ref_spec_or_default(&self) -> &[String] {
360        self.public_release_ref_spec.as_deref().unwrap_or_default()
361    }
362
363    /// Overlays explicitly configured values from an inheriting file onto these options.
364    ///
365    /// This is the serde equivalent of populating an existing options object in the .NET
366    /// implementation. An absent optional value leaves the inherited value unchanged.
367    pub fn merge_from(&mut self, overlay: &Self) {
368        macro_rules! replace_some {
369            ($field:ident) => {
370                if overlay.$field.is_some() {
371                    self.$field = overlay.$field.clone();
372                }
373            };
374        }
375
376        replace_some!(schema);
377        replace_some!(version);
378        replace_some!(assembly_version);
379        replace_some!(git_commit_id_prefix);
380        replace_some!(version_height_offset);
381        replace_some!(version_height_offset_applies_to);
382        replace_some!(sem_ver1_numeric_identifier_padding);
383        replace_some!(git_commit_id_short_fixed_length);
384        replace_some!(git_commit_id_short_auto_minimum);
385        replace_some!(git_commit_id_include_dirty);
386        replace_some!(nuget_package_version);
387        replace_some!(public_release_ref_spec);
388        replace_some!(cloud_build);
389        replace_some!(release);
390        replace_some!(path_filters);
391        replace_some!(prerelease);
392        self.inherit = overlay.inherit;
393    }
394
395    /// Merges an inheriting file and converts the result into complete options.
396    ///
397    /// In addition to overlaying explicitly configured values, this applies the inheriting file's
398    /// standalone `prerelease` property and clears `inherit`.
399    pub fn merge_inheriting(&mut self, overlay: &Self) -> CrateResult<()> {
400        self.merge_from(overlay);
401        self.apply_prerelease()?;
402        self.inherit = false;
403        Ok(())
404    }
405
406    /// Applies the standalone `prerelease` property to the semantic version.
407    pub fn apply_prerelease(&mut self) -> CrateResult<()> {
408        let Some(prerelease) = self.prerelease.clone() else {
409            return Ok(());
410        };
411        let Some(version) = &self.version else {
412            return Err(Error::InvalidOperation(
413                "The 'prerelease' property cannot be used without a 'version' property.".to_owned(),
414            ));
415        };
416
417        if prerelease.is_empty() {
418            if !version.prerelease.is_empty() {
419                self.version = Some(SemanticVersion::new(
420                    version.version,
421                    "",
422                    version.build_metadata.clone(),
423                )?);
424            }
425            self.prerelease = None;
426            return Ok(());
427        }
428        if !version.prerelease.is_empty() {
429            return Err(Error::InvalidOperation(
430                "The 'prerelease' property cannot be used when the 'version' property already includes a prerelease tag.".to_owned(),
431            ));
432        }
433
434        let prerelease = if prerelease.starts_with('-') {
435            prerelease
436        } else {
437            format!("-{prerelease}")
438        };
439        self.version = Some(SemanticVersion::new(
440            version.version,
441            prerelease,
442            version.build_metadata.clone(),
443        )?);
444        self.prerelease = None;
445        Ok(())
446    }
447}
448
449impl PartialEq for VersionOptions {
450    fn eq(&self, other: &Self) -> bool {
451        self.schema == other.schema
452            && self.version == other.version
453            && self.assembly_version_or_default() == other.assembly_version_or_default()
454            && self.git_commit_id_prefix == other.git_commit_id_prefix
455            && self.version_height_offset == other.version_height_offset
456            && self.version_height_offset_applies_to == other.version_height_offset_applies_to
457            && self.sem_ver1_numeric_identifier_padding == other.sem_ver1_numeric_identifier_padding
458            && self.git_commit_id_short_fixed_length == other.git_commit_id_short_fixed_length
459            && self.git_commit_id_short_auto_minimum == other.git_commit_id_short_auto_minimum
460            && self.git_commit_id_include_dirty == other.git_commit_id_include_dirty
461            && self.nuget_package_version_or_default() == other.nuget_package_version_or_default()
462            && self.public_release_ref_spec == other.public_release_ref_spec
463            && self.cloud_build_or_default() == other.cloud_build_or_default()
464            && self.release_or_default() == other.release_or_default()
465            && self.path_filters == other.path_filters
466            && self.inherit == other.inherit
467            && self.prerelease == other.prerelease
468    }
469}
470
471/// Details of how an assembly version is calculated.
472#[derive(Clone, Debug, Default)]
473pub struct AssemblyVersionOptions {
474    /// The explicit assembly version, with two to four components.
475    pub version: Option<Version>,
476    /// The additional precision copied from the calculated file version.
477    pub precision: Option<VersionPrecision>,
478}
479
480impl AssemblyVersionOptions {
481    /// Creates options with an explicit assembly version.
482    #[must_use]
483    pub const fn new(version: Version) -> Self {
484        Self {
485            version: Some(version),
486            precision: None,
487        }
488    }
489
490    /// Returns the configured precision, defaulting to `minor`.
491    #[must_use]
492    pub fn precision_or_default(&self) -> VersionPrecision {
493        self.precision.unwrap_or(DEFAULT_VERSION_PRECISION)
494    }
495}
496
497impl PartialEq for AssemblyVersionOptions {
498    fn eq(&self, other: &Self) -> bool {
499        self.version == other.version && self.precision_or_default() == other.precision_or_default()
500    }
501}
502
503impl Eq for AssemblyVersionOptions {}
504
505impl Serialize for AssemblyVersionOptions {
506    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
507    where
508        S: Serializer,
509    {
510        if self.precision_or_default() == DEFAULT_VERSION_PRECISION
511            && let Some(version) = &self.version
512        {
513            return serializer.serialize_str(&version.to_string());
514        }
515
516        let field_count =
517            usize::from(self.version.is_some()) + usize::from(self.precision.is_some());
518        let mut state = serializer.serialize_struct("AssemblyVersionOptions", field_count)?;
519        if let Some(version) = &self.version {
520            state.serialize_field("version", &AsString(version))?;
521        }
522        if let Some(precision) = self.precision {
523            state.serialize_field("precision", &precision)?;
524        }
525        state.end()
526    }
527}
528
529impl<'de> Deserialize<'de> for AssemblyVersionOptions {
530    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
531    where
532        D: Deserializer<'de>,
533    {
534        struct AssemblyVersionVisitor;
535
536        impl<'de> Visitor<'de> for AssemblyVersionVisitor {
537            type Value = AssemblyVersionOptions;
538
539            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
540                formatter.write_str("an assembly version string or assemblyVersion object")
541            }
542
543            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
544            where
545                E: de::Error,
546            {
547                let version = Version::from_str(value).map_err(E::custom)?;
548                Ok(AssemblyVersionOptions::new(version))
549            }
550
551            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
552            where
553                M: MapAccess<'de>,
554            {
555                let mut version = None;
556                let mut precision = None;
557                while let Some(key) = map.next_key::<String>()? {
558                    match key.as_str() {
559                        "version" => {
560                            if version.is_some() {
561                                return Err(de::Error::duplicate_field("version"));
562                            }
563                            let text = map.next_value::<String>()?;
564                            version = Some(Version::from_str(&text).map_err(de::Error::custom)?);
565                        }
566                        "precision" => {
567                            if precision.is_some() {
568                                return Err(de::Error::duplicate_field("precision"));
569                            }
570                            precision = Some(map.next_value()?);
571                        }
572                        _ => return Err(de::Error::unknown_field(&key, &["version", "precision"])),
573                    }
574                }
575
576                Ok(AssemblyVersionOptions { version, precision })
577            }
578        }
579
580        deserializer.deserialize_any(AssemblyVersionVisitor)
581    }
582}
583
584/// Settings controlling generated NuGet package versions.
585#[derive(Clone, Debug, Default, Deserialize, Serialize)]
586#[serde(rename_all = "camelCase")]
587pub struct NuGetPackageVersionOptions {
588    /// The SemVer generation mode, normally `1` or `2`.
589    #[serde(default, skip_serializing_if = "Option::is_none")]
590    pub sem_ver: Option<f32>,
591    /// The number of version components included in the package version.
592    #[serde(default, skip_serializing_if = "Option::is_none")]
593    pub precision: Option<VersionPrecision>,
594}
595
596impl NuGetPackageVersionOptions {
597    /// The default number of components included in a package version.
598    pub const DEFAULT_PRECISION: VersionPrecision = VersionPrecision::Build;
599
600    /// Returns the configured SemVer mode, defaulting to `1`.
601    #[must_use]
602    pub fn sem_ver_or_default(&self) -> f32 {
603        self.sem_ver.unwrap_or(1.0)
604    }
605
606    /// Returns the configured precision, defaulting to `build`.
607    #[must_use]
608    pub fn precision_or_default(&self) -> VersionPrecision {
609        self.precision.unwrap_or(Self::DEFAULT_PRECISION)
610    }
611}
612
613impl PartialEq for NuGetPackageVersionOptions {
614    fn eq(&self, other: &Self) -> bool {
615        self.sem_ver_or_default() == other.sem_ver_or_default()
616            && self.precision_or_default() == other.precision_or_default()
617    }
618}
619
620/// Options applicable specifically to cloud builds.
621#[derive(Clone, Debug, Default, Deserialize, Serialize)]
622#[serde(rename_all = "camelCase")]
623pub struct CloudBuildOptions {
624    /// Whether all build properties are elevated to `NBGV_` cloud variables.
625    #[serde(default, skip_serializing_if = "Option::is_none")]
626    pub set_all_variables: Option<bool>,
627    /// Whether selected calculated version properties are elevated to cloud variables.
628    #[serde(default, skip_serializing_if = "Option::is_none")]
629    pub set_version_variables: Option<bool>,
630    /// Settings for overriding the cloud build number.
631    #[serde(default, skip_serializing_if = "Option::is_none")]
632    pub build_number: Option<CloudBuildNumberOptions>,
633}
634
635impl CloudBuildOptions {
636    /// Returns whether all build properties are elevated, defaulting to `false`.
637    #[must_use]
638    pub fn set_all_variables_or_default(&self) -> bool {
639        self.set_all_variables.unwrap_or(false)
640    }
641
642    /// Returns whether version properties are elevated, defaulting to `true`.
643    #[must_use]
644    pub fn set_version_variables_or_default(&self) -> bool {
645        self.set_version_variables.unwrap_or(true)
646    }
647
648    /// Returns build-number settings or their defaults.
649    #[must_use]
650    pub fn build_number_or_default(&self) -> CloudBuildNumberOptions {
651        self.build_number.clone().unwrap_or_default()
652    }
653}
654
655impl PartialEq for CloudBuildOptions {
656    fn eq(&self, other: &Self) -> bool {
657        self.set_all_variables_or_default() == other.set_all_variables_or_default()
658            && self.set_version_variables_or_default() == other.set_version_variables_or_default()
659            && self.build_number_or_default() == other.build_number_or_default()
660    }
661}
662
663impl Eq for CloudBuildOptions {}
664
665/// Settings for overriding a cloud build number with version information.
666#[derive(Clone, Debug, Default, Deserialize, Serialize)]
667#[serde(rename_all = "camelCase")]
668pub struct CloudBuildNumberOptions {
669    /// Whether to override the preset cloud build number.
670    #[serde(default, skip_serializing_if = "Option::is_none")]
671    pub enabled: Option<bool>,
672    /// When and where commit information is included.
673    #[serde(default, skip_serializing_if = "Option::is_none")]
674    pub include_commit_id: Option<CloudBuildNumberCommitIdOptions>,
675}
676
677impl CloudBuildNumberOptions {
678    /// Returns whether build-number overriding is enabled, defaulting to `false`.
679    #[must_use]
680    pub fn enabled_or_default(&self) -> bool {
681        self.enabled.unwrap_or(false)
682    }
683
684    /// Returns commit-ID settings or their defaults.
685    #[must_use]
686    pub fn include_commit_id_or_default(&self) -> CloudBuildNumberCommitIdOptions {
687        self.include_commit_id.clone().unwrap_or_default()
688    }
689}
690
691impl PartialEq for CloudBuildNumberOptions {
692    fn eq(&self, other: &Self) -> bool {
693        self.enabled_or_default() == other.enabled_or_default()
694            && self.include_commit_id_or_default() == other.include_commit_id_or_default()
695    }
696}
697
698impl Eq for CloudBuildNumberOptions {}
699
700/// Describes when and where commit information appears in a cloud build number.
701#[derive(Clone, Debug, Default, Deserialize, Serialize)]
702#[serde(rename_all = "camelCase")]
703pub struct CloudBuildNumberCommitIdOptions {
704    /// The conditions under which the commit ID is included.
705    #[serde(default, skip_serializing_if = "Option::is_none")]
706    pub when: Option<CloudBuildNumberCommitWhen>,
707    /// The position at which the commit ID is included.
708    #[serde(default, skip_serializing_if = "Option::is_none")]
709    pub r#where: Option<CloudBuildNumberCommitWhere>,
710}
711
712impl CloudBuildNumberCommitIdOptions {
713    /// Returns the inclusion condition, defaulting to non-public releases only.
714    #[must_use]
715    pub fn when_or_default(&self) -> CloudBuildNumberCommitWhen {
716        self.when.unwrap_or_default()
717    }
718
719    /// Returns the inclusion position, defaulting to build metadata.
720    #[must_use]
721    pub fn where_or_default(&self) -> CloudBuildNumberCommitWhere {
722        self.r#where.unwrap_or_default()
723    }
724}
725
726impl PartialEq for CloudBuildNumberCommitIdOptions {
727    fn eq(&self, other: &Self) -> bool {
728        self.when_or_default() == other.when_or_default()
729            && self.where_or_default() == other.where_or_default()
730    }
731}
732
733impl Eq for CloudBuildNumberCommitIdOptions {}
734
735/// Settings for the `prepare-release` and `tag` commands.
736#[derive(Clone, Debug, Default, Deserialize, Serialize)]
737#[serde(rename_all = "camelCase", deny_unknown_fields)]
738pub struct ReleaseOptions {
739    /// The template for release tag names.
740    #[serde(default, skip_serializing_if = "Option::is_none")]
741    pub tag_name: Option<String>,
742    /// The template for release branch names.
743    #[serde(default, skip_serializing_if = "Option::is_none")]
744    pub branch_name: Option<String>,
745    /// The component incremented while preparing a release.
746    #[serde(default, skip_serializing_if = "Option::is_none")]
747    pub version_increment: Option<ReleaseVersionIncrement>,
748    /// The first/default prerelease tag for new versions.
749    #[serde(default, skip_serializing_if = "Option::is_none")]
750    pub first_unstable_tag: Option<String>,
751}
752
753impl ReleaseOptions {
754    /// Returns the tag-name template, defaulting to `v{version}`.
755    #[must_use]
756    pub fn tag_name_or_default(&self) -> &str {
757        self.tag_name.as_deref().unwrap_or("v{version}")
758    }
759
760    /// Returns the branch-name template, defaulting to `v{version}`.
761    #[must_use]
762    pub fn branch_name_or_default(&self) -> &str {
763        self.branch_name.as_deref().unwrap_or("v{version}")
764    }
765
766    /// Returns the release increment, defaulting to `minor`.
767    #[must_use]
768    pub fn version_increment_or_default(&self) -> ReleaseVersionIncrement {
769        self.version_increment.unwrap_or_default()
770    }
771
772    /// Returns the first unstable tag, defaulting to `alpha`.
773    #[must_use]
774    pub fn first_unstable_tag_or_default(&self) -> &str {
775        self.first_unstable_tag.as_deref().unwrap_or("alpha")
776    }
777}
778
779impl PartialEq for ReleaseOptions {
780    fn eq(&self, other: &Self) -> bool {
781        self.tag_name_or_default() == other.tag_name_or_default()
782            && self.branch_name_or_default() == other.branch_name_or_default()
783            && self.version_increment_or_default() == other.version_increment_or_default()
784            && self.first_unstable_tag_or_default() == other.first_unstable_tag_or_default()
785    }
786}
787
788impl Eq for ReleaseOptions {}
789
790struct AsString<'a, T>(&'a T);
791
792impl<T: fmt::Display> Serialize for AsString<'_, T> {
793    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
794    where
795        S: Serializer,
796    {
797        serializer.serialize_str(&self.0.to_string())
798    }
799}
800
801fn deserialize_optional_from_string<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
802where
803    D: Deserializer<'de>,
804    T: FromStr,
805    T::Err: fmt::Display,
806{
807    Option::<String>::deserialize(deserializer)?
808        .map(|value| T::from_str(&value).map_err(de::Error::custom))
809        .transpose()
810}
811
812fn serialize_optional_as_string<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
813where
814    S: Serializer,
815    T: fmt::Display,
816{
817    match value {
818        Some(value) => serializer.serialize_some(&value.to_string()),
819        None => serializer.serialize_none(),
820    }
821}
822
823const fn is_false(value: &bool) -> bool {
824    !*value
825}
826
827#[cfg(test)]
828mod tests {
829    use super::*;
830    use serde_json::{Value, json};
831
832    #[test]
833    fn defaults_match_schema() {
834        let options = VersionOptions::default();
835        assert_eq!(options.version_height_offset_or_default(), 0);
836        assert_eq!(options.sem_ver1_numeric_identifier_padding_or_default(), 4);
837        assert_eq!(options.git_commit_id_short_fixed_length_or_default(), 10);
838        assert!(!options.git_commit_id_include_dirty_or_default());
839        assert_eq!(
840            options.assembly_version_or_default().precision_or_default(),
841            VersionPrecision::Minor
842        );
843        assert_eq!(
844            options
845                .nuget_package_version_or_default()
846                .precision_or_default(),
847            VersionPrecision::Build
848        );
849        assert!(
850            options
851                .cloud_build_or_default()
852                .set_version_variables_or_default()
853        );
854        assert_eq!(
855            options.release_or_default().first_unstable_tag_or_default(),
856            "alpha"
857        );
858    }
859
860    #[test]
861    fn exact_camel_case_json_and_defaults_are_omitted() {
862        let options = VersionOptions {
863            git_commit_id_short_fixed_length: Some(12),
864            cloud_build: Some(CloudBuildOptions {
865                set_all_variables: Some(true),
866                ..Default::default()
867            }),
868            release: Some(ReleaseOptions {
869                first_unstable_tag: Some("beta".to_owned()),
870                ..Default::default()
871            }),
872            ..Default::default()
873        };
874
875        let value = serde_json::to_value(options).unwrap();
876        assert_eq!(
877            value,
878            json!({
879                "gitCommitIdShortFixedLength": 12,
880                "cloudBuild": { "setAllVariables": true },
881                "release": { "firstUnstableTag": "beta" }
882            })
883        );
884    }
885
886    #[test]
887    fn path_filters_are_resolved_relative_to_version_file() {
888        let options =
889            VersionOptions::from_json(r#"{"pathFilters":["src/**",":^temp"]}"#, "eng").unwrap();
890        let filters = options.path_filters.as_ref().unwrap();
891        assert_eq!(filters[0].repo_relative_path(), "eng/src/**");
892        assert_eq!(filters[1].repo_relative_path(), "eng/temp");
893
894        let value: Value = serde_json::from_str(&options.to_json("eng").unwrap()).unwrap();
895        assert_eq!(value["pathFilters"], json!(["./src/**", ":!temp"]));
896    }
897
898    #[test]
899    fn assembly_version_accepts_shorthand_and_object_forms() {
900        let shorthand: VersionOptions =
901            serde_json::from_value(json!({ "assemblyVersion": "1.2.3.4" })).unwrap();
902        assert_eq!(
903            shorthand
904                .assembly_version
905                .as_ref()
906                .unwrap()
907                .precision_or_default(),
908            VersionPrecision::Minor
909        );
910        assert_eq!(
911            serde_json::to_value(&shorthand).unwrap(),
912            json!({ "assemblyVersion": "1.2.3.4" })
913        );
914
915        let object: VersionOptions = serde_json::from_value(json!({
916            "assemblyVersion": { "version": "1.2", "precision": "revision" }
917        }))
918        .unwrap();
919        assert_eq!(
920            object.assembly_version.as_ref().unwrap().precision,
921            Some(VersionPrecision::Revision)
922        );
923        assert_eq!(
924            serde_json::to_value(object).unwrap(),
925            json!({
926                "assemblyVersion": { "version": "1.2", "precision": "revision" }
927            })
928        );
929    }
930
931    #[test]
932    fn nested_equality_compares_effective_defaults() {
933        assert_eq!(
934            AssemblyVersionOptions::default(),
935            AssemblyVersionOptions {
936                precision: Some(VersionPrecision::Minor),
937                ..Default::default()
938            }
939        );
940        assert_eq!(
941            NuGetPackageVersionOptions::default(),
942            NuGetPackageVersionOptions {
943                sem_ver: Some(1.0),
944                precision: Some(VersionPrecision::Build),
945            }
946        );
947        assert_eq!(
948            CloudBuildOptions::default(),
949            CloudBuildOptions {
950                set_all_variables: Some(false),
951                set_version_variables: Some(true),
952                build_number: Some(CloudBuildNumberOptions::default()),
953            }
954        );
955        assert_eq!(
956            ReleaseOptions::default(),
957            ReleaseOptions {
958                tag_name: Some("v{version}".to_owned()),
959                branch_name: Some("v{version}".to_owned()),
960                version_increment: Some(ReleaseVersionIncrement::Minor),
961                first_unstable_tag: Some("alpha".to_owned()),
962            }
963        );
964    }
965
966    #[test]
967    fn merge_only_replaces_explicit_values() {
968        let mut parent = VersionOptions {
969            git_commit_id_prefix: Some("g".to_owned()),
970            version_height_offset: Some(7),
971            cloud_build: Some(CloudBuildOptions {
972                set_version_variables: Some(true),
973                ..Default::default()
974            }),
975            ..Default::default()
976        };
977        let child = VersionOptions {
978            version_height_offset: Some(0),
979            prerelease: Some(String::new()),
980            inherit: true,
981            ..Default::default()
982        };
983
984        parent.merge_from(&child);
985        assert_eq!(parent.git_commit_id_prefix.as_deref(), Some("g"));
986        assert_eq!(parent.version_height_offset, Some(0));
987        assert_eq!(parent.prerelease.as_deref(), Some(""));
988        assert!(parent.inherit);
989    }
990
991    #[test]
992    fn merging_inheriting_options_applies_prerelease() {
993        let mut parent: VersionOptions =
994            serde_json::from_value(json!({ "version": "1.2" })).unwrap();
995        let child: VersionOptions =
996            serde_json::from_value(json!({ "inherit": true, "prerelease": "beta" })).unwrap();
997
998        parent.merge_inheriting(&child).unwrap();
999        assert_eq!(parent.version.unwrap().to_string(), "1.2-beta");
1000        assert_eq!(parent.prerelease, None);
1001        assert!(!parent.inherit);
1002
1003        let mut suppress: VersionOptions =
1004            serde_json::from_value(json!({ "version": "1.2-alpha" })).unwrap();
1005        let child: VersionOptions =
1006            serde_json::from_value(json!({ "inherit": true, "prerelease": "" })).unwrap();
1007        suppress.merge_inheriting(&child).unwrap();
1008        assert_eq!(suppress.version.unwrap().to_string(), "1.2");
1009    }
1010
1011    #[test]
1012    fn obsolete_offset_name_is_accepted_but_modern_name_is_written() {
1013        let options: VersionOptions =
1014            serde_json::from_value(json!({ "buildNumberOffset": -3 })).unwrap();
1015        assert_eq!(options.version_height_offset, Some(-3));
1016        let value = serde_json::to_value(options).unwrap();
1017        assert_eq!(value.get("versionHeightOffset"), Some(&Value::from(-3)));
1018        assert!(value.get("buildNumberOffset").is_none());
1019    }
1020
1021    #[test]
1022    fn effective_offset_stops_applying_after_height_reset() {
1023        let options: VersionOptions = serde_json::from_value(json!({
1024            "version": "2.0",
1025            "versionHeightOffset": 42,
1026            "versionHeightOffsetAppliesTo": "1.0"
1027        }))
1028        .unwrap();
1029        assert_eq!(options.effective_version_height_offset(), 0);
1030
1031        let compatible: VersionOptions = serde_json::from_value(json!({
1032            "version": "1.0-beta",
1033            "versionHeightOffset": 42,
1034            "versionHeightOffsetAppliesTo": "1.0-alpha"
1035        }))
1036        .unwrap();
1037        assert_eq!(compatible.effective_version_height_offset(), 42);
1038    }
1039}