Skip to content

Commit f84ce3a

Browse files
authored
Merge pull request #4605 from 9swampy/SupportFormatStringsInConfig
Support C# format strings in config
2 parents d145da0 + 5f509d8 commit f84ce3a

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+1459
-81
lines changed

docs/input/docs/reference/configuration.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,9 @@ while still updating the `AssemblyFileVersion` and `AssemblyInformationVersion`
477477
attributes. Valid values: `MajorMinorPatchTag`, `MajorMinorPatch`, `MajorMinor`,
478478
`Major`, `None`.
479479

480+
For information on using format strings in these properties, see
481+
[Format Strings](/docs/reference/custom-formatting).
482+
480483
### assembly-file-versioning-scheme
481484

482485
When updating assembly info, `assembly-file-versioning-scheme` tells GitVersion
@@ -632,7 +635,7 @@ ignore:
632635
- ^docs\/
633636
```
634637
##### *Monorepo*
635-
This ignore config can be used to filter only those commits that belong to a specific project in a monorepo.
638+
This ignore config can be used to filter only those commits that belong to a specific project in a monorepo.
636639
As an example, consider a monorepo consisting of subdirectories for `ProjectA`, `ProjectB` and a shared `LibraryC`. For GitVersion to consider only commits that are part of `projectA` and shared library `LibraryC`, a regex that matches all paths except those starting with `ProjectA` or `LibraryC` can be used. Either one of the following configs would filter out `ProjectB`.
637640
* Specific match on `/ProjectB/*`:
638641
```yaml
@@ -655,7 +658,7 @@ A commit having changes only in `/ProjectB/*` path would be ignored. A commit ha
655658
* `/ProductA/*` and `/ProductB/*` and `/LibraryC/*`
656659

657660
:::
658-
Note: The `ignore.paths` configuration is case-sensitive. This can lead to unexpected behavior on case-insensitive file systems, such as Windows. To ensure consistent matching regardless of case, you can prefix your regular expressions with the case-insensitive flag `(?i)`. For example, `(?i)^docs\/` will match both `docs/` and `Docs/`.
661+
Note: The `ignore.paths` configuration is case-sensitive. This can lead to unexpected behavior on case-insensitive file systems, such as Windows. To ensure consistent matching regardless of case, you can prefix your regular expressions with the case-insensitive flag `(?i)`. For example, `(?i)^docs\/` will match both `docs/` and `Docs/`.
659662
:::
660663

661664
::: {.alert .alert-warning}
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
---
2+
title: Format Strings
3+
description: Using C# format strings in GitVersion configuration
4+
---
5+
6+
GitVersion supports C# format strings in configuration, allowing you to apply standard .NET formatting and custom transformations to version properties. This enhancement provides more flexibility and control over how version information is displayed and used throughout your build process.
7+
8+
## Overview
9+
10+
The custom formatter functionality introduces several new formatters that can be used in GitVersion configuration files and templates:
11+
12+
- **FormattableFormatter**: Supports standard .NET format strings for numeric values, dates, and implements `IFormattable`
13+
- **NumericFormatter**: Handles numeric formatting with culture-aware output
14+
- **DateTimeFormatter**: Provides date and time formatting with standard and custom format specifiers
15+
- **String Case Formatters**: Provides text case transformations with custom format specifiers
16+
17+
## Standard .NET Format Strings
18+
19+
### Numeric Formatting
20+
21+
You can now use standard .NET numeric format strings with version components:
22+
23+
```yaml
24+
# GitVersion.yml
25+
assembly-informational-format: "{Major}.{Minor}.{Patch:F2}-{PreReleaseLabel}"
26+
```
27+
28+
**Supported Numeric Formats:**
29+
30+
- `F` or `f` (Fixed-point): `{Patch:F2}` → `"1.23"`
31+
- `N` or `n` (Number): `{BuildMetadata:N0}` → `"1,234"`
32+
- `C` or `c` (Currency): `{Major:C}` → `"¤1.00"`
33+
- `P` or `p` (Percent): `{CommitsSinceVersionSource:P}` → `"12,345.60 %"`
34+
- `D` or `d` (Decimal): `{Major:D4}` → `"0001"`
35+
- `X` or `x` (Hexadecimal): `{Patch:X}` → `"FF"`
36+
37+
### Date and Time Formatting
38+
39+
When working with date-related properties like `CommitDate`:
40+
41+
```yaml
42+
assembly-informational-format: "Build-{SemVer}-{CommitDate:yyyy-MM-dd}"
43+
```
44+
45+
**Common Date Format Specifiers:**
46+
47+
- `yyyy-MM-dd` → `"2024-03-15"`
48+
- `HH:mm:ss` → `"14:30:22"`
49+
- `MMM dd, yyyy` → `"Mar 15, 2024"`
50+
- `yyyy-MM-dd'T'HH:mm:ss'Z'` → `"2024-03-15T14:30:22Z"`
51+
52+
## Custom String Case Formatters
53+
54+
GitVersion introduces custom format specifiers for string case transformations that can be used in templates:
55+
56+
### Available Case Formats
57+
58+
| Format | Description | Example Input | Example Output |
59+
|--------|---------------------------------------------------------------|------------------|------------------|
60+
| `u` | **Uppercase** - Converts entire string to uppercase | `feature-branch` | `FEATURE-BRANCH` |
61+
| `l` | **Lowercase** - Converts entire string to lowercase | `Feature-Branch` | `feature-branch` |
62+
| `t` | **Title Case** - Capitalizes first letter of each word | `feature-branch` | `Feature-Branch` |
63+
| `s` | **Sentence Case** - Capitalizes only the first letter | `feature-branch` | `Feature-branch` |
64+
| `c` | **PascalCase** - Removes separators and capitalizes each word | `feature-branch` | `FeatureBranch` |
65+
66+
### Usage Examples
67+
68+
```yaml
69+
# GitVersion.yml configuration
70+
branches:
71+
feature:
72+
label: "{BranchName:c}" # Converts to PascalCase
73+
74+
assembly-informational-format: "{Major}.{Minor}.{Patch}-{PreReleaseLabel:l}.{CommitsSinceVersionSource:0000}"
75+
```
76+
77+
**Template Usage:**
78+
79+
```yaml
80+
# Using format strings in templates
81+
assembly-informational-format: "{Major}.{Minor}.{Patch}-{CommitsSinceVersionSource:0000}"
82+
assembly-informational-format: "{SemVer}-{BranchName:l}"
83+
```
84+
85+
## Examples
86+
87+
Based on actual test cases from the implementation:
88+
89+
### Zero-Padded Numeric Formatting
90+
91+
```yaml
92+
# Zero-padded commit count
93+
assembly-informational-format: "{Major}.{Minor}.{Patch}-{CommitsSinceVersionSource:0000}"
94+
# Result: "1.2.3-0042"
95+
```
96+
97+
### String Case Transformations
98+
99+
```yaml
100+
branches:
101+
feature:
102+
label: "{BranchName:c}" # PascalCase: "feature-branch" → "FeatureBranch"
103+
hotfix:
104+
label: "hotfix-{BranchName:l}" # Lowercase: "HOTFIX-BRANCH" → "hotfix-branch"
105+
```
106+
107+
### Date and Time Formatting
108+
109+
```yaml
110+
assembly-informational-format: "{SemVer}-build-{CommitDate:yyyy-MM-dd}"
111+
# Result: "1.2.3-build-2021-01-01"
112+
```
113+
114+
### Numeric Formatting
115+
116+
```yaml
117+
# Currency format (uses InvariantCulture)
118+
assembly-informational-format: "Cost-{Major:C}" # Result: "Cost-¤1.00"
119+
120+
# Percentage format
121+
assembly-informational-format: "Progress-{Minor:P}" # Result: "Progress-200.00 %"
122+
123+
# Thousands separator
124+
assembly-informational-format: "Build-{CommitsSinceVersionSource:N0}" # Result: "Build-1,234"
125+
```
126+
127+
## Configuration Integration
128+
129+
The format strings are used in GitVersion configuration files through various formatting properties:
130+
131+
### Assembly Version Formatting
132+
133+
```yaml
134+
# GitVersion.yml
135+
assembly-informational-format: "{Major}.{Minor}.{Patch}-{CommitsSinceVersionSource:0000}"
136+
assembly-versioning-format: "{Major}.{Minor}.{Patch}.{env:BUILD_NUMBER}"
137+
assembly-file-versioning-format: "{MajorMinorPatch}.{CommitsSinceVersionSource}"
138+
```
139+
140+
### Environment Variable Integration
141+
142+
```yaml
143+
# Using environment variables with fallbacks
144+
assembly-informational-format: "{Major}.{Minor}.{Patch}-{env:RELEASE_STAGE ?? 'dev'}"
145+
assembly-informational-format: "{SemVer}+{env:BUILD_ID ?? 'local'}"
146+
```
147+
148+
### Real-World Integration Examples
149+
150+
Based on the actual test implementation:
151+
152+
```yaml
153+
# Example from VariableProviderTests.cs
154+
assembly-informational-format: "{Major}.{Minor}.{Patch}-{CommitsSinceVersionSource:0000}"
155+
# Result: "1.2.3-0042" when CommitsSinceVersionSource = 42
156+
157+
# Branch-specific formatting
158+
branches:
159+
feature:
160+
label: "{BranchName:c}" # PascalCase conversion
161+
hotfix:
162+
label: "hotfix.{CommitsSinceVersionSource:00}"
163+
```
164+
165+
## Invariant Culture Formatting
166+
167+
The formatting system uses `CultureInfo.InvariantCulture` by default through the chained `TryFormat` overload implementation. This provides:
168+
169+
- **Consistent results** across all environments and systems
170+
- **Predictable numeric formatting** with period (.) as decimal separator and comma (,) as thousands separator
171+
- **Standard date formatting** using English month names and formats
172+
- **No localization variations** regardless of system locale
173+
174+
```csharp
175+
// All environments produce the same output:
176+
// {CommitsSinceVersionSource:N0} → "1,234"
177+
// {CommitDate:MMM dd, yyyy} → "Mar 15, 2024"
178+
// {Major:C} → "¤1.00" (generic currency symbol)
179+
```
180+
181+
This ensures that version strings generated by GitVersion are consistent across different build environments, developer machines, and CI/CD systems.

docs/input/docs/reference/mdsource/configuration.source.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,9 @@ while still updating the `AssemblyFileVersion` and `AssemblyInformationVersion`
7878
attributes. Valid values: `MajorMinorPatchTag`, `MajorMinorPatch`, `MajorMinor`,
7979
`Major`, `None`.
8080

81+
For information on using format strings in these properties, see
82+
[Format Strings](/docs/reference/custom-formatting).
83+
8184
### assembly-file-versioning-scheme
8285

8386
When updating assembly info, `assembly-file-versioning-scheme` tells GitVersion
@@ -233,7 +236,7 @@ ignore:
233236
- ^docs\/
234237
```
235238
##### *Monorepo*
236-
This ignore config can be used to filter only those commits that belong to a specific project in a monorepo.
239+
This ignore config can be used to filter only those commits that belong to a specific project in a monorepo.
237240
As an example, consider a monorepo consisting of subdirectories for `ProjectA`, `ProjectB` and a shared `LibraryC`. For GitVersion to consider only commits that are part of `projectA` and shared library `LibraryC`, a regex that matches all paths except those starting with `ProjectA` or `LibraryC` can be used. Either one of the following configs would filter out `ProjectB`.
238241
* Specific match on `/ProjectB/*`:
239242
```yaml
@@ -256,7 +259,7 @@ A commit having changes only in `/ProjectB/*` path would be ignored. A commit ha
256259
* `/ProductA/*` and `/ProductB/*` and `/LibraryC/*`
257260

258261
:::
259-
Note: The `ignore.paths` configuration is case-sensitive. This can lead to unexpected behavior on case-insensitive file systems, such as Windows. To ensure consistent matching regardless of case, you can prefix your regular expressions with the case-insensitive flag `(?i)`. For example, `(?i)^docs\/` will match both `docs/` and `Docs/`.
262+
Note: The `ignore.paths` configuration is case-sensitive. This can lead to unexpected behavior on case-insensitive file systems, such as Windows. To ensure consistent matching regardless of case, you can prefix your regular expressions with the case-insensitive flag `(?i)`. For example, `(?i)^docs\/` will match both `docs/` and `Docs/`.
260263
:::
261264

262265
::: {.alert .alert-warning}

docs/input/docs/reference/variables.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,4 +74,8 @@ within a [supported build server][build-servers]), the above version variables
7474
may be exposed automatically as **environment variables** in the format
7575
`GitVersion_FullSemVer`.
7676

77+
## Formatting Variables
78+
79+
GitVersion variables can be formatted using C# format strings. See [Format Strings](/docs/reference/custom-formatting) for details.
80+
7781
[build-servers]: ./build-servers/

docs/input/docs/usage/cli/arguments.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ GitVersion [path]
3838
- will output `1.2.3+beta.4`
3939
/format Used in conjunction with /output json, will output a format
4040
containing version variables.
41+
Supports C# format strings - see [Format Strings](/docs/reference/custom-formatting) for details.
4142
E.g. /output json /format {SemVer} - will output `1.2.3+beta.4`
4243
/output json /format {Major}.{Minor} - will output `1.2`
4344
/l Path to logfile.

docs/input/docs/usage/msbuild.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,8 @@ Now, when you build:
9898
appended to it.
9999
* `AssemblyInformationalVersion` will be set to the `InformationalVersion` variable.
100100

101+
Assembly version formatting can use C# format strings. See [Format Strings](/docs/reference/custom-formatting) for available options.
102+
101103
#### Other injected Variables
102104

103105
All other [variables](/docs/reference/variables) will be injected into an

new-cli/GitVersion.Common/GitVersion.Common.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
<Compile Include="..\..\src\GitVersion.Core\Extensions\DictionaryExtensions.cs" Link="%(Filename)%(Extension)" />
1313
<Compile Include="..\..\src\GitVersion.Core\Extensions\StringExtensions.cs" Link="Extensions\StringExtensions.cs" />
1414
<Compile Include="..\..\src\GitVersion.Core\Extensions\CommonExtensions.cs" Link="Extensions\CommonExtensions.cs" />
15+
<Compile Include="..\..\src\GitVersion.Core\Formatting\*.cs" Link="Formatting\%(Filename)%(Extension)" />
1516
<Compile Include="..\..\src\GitVersion.Core\Helpers\*.cs" Link="Helpers\%(Filename)%(Extension)" />
1617
<Compile Include="..\..\src\GitVersion.Core\Git\*.cs" Link="Git\%(Filename)%(Extension)" />
1718
<Compile Include="..\..\src\GitVersion.Core\SemVer\*.cs" Link="SemVer\%(Filename)%(Extension)" />
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
namespace GitVersion.Core.Tests.Extensions;
2+
3+
public static class ShouldlyExtensions
4+
{
5+
/// <summary>
6+
/// Asserts that the action throws an exception of type TException
7+
/// with the expected message.
8+
/// </summary>
9+
public static void ShouldThrowWithMessage<TException>(this Action action, string expectedMessage) where TException : Exception
10+
{
11+
var ex = Should.Throw<TException>(action);
12+
ex.Message.ShouldBe(expectedMessage);
13+
}
14+
15+
/// <summary>
16+
/// Asserts that the action throws an exception of type TException,
17+
/// and allows further assertion on the exception instance.
18+
/// </summary>
19+
public static void ShouldThrow<TException>(this Action action, Action<TException> additionalAssertions) where TException : Exception
20+
{
21+
var ex = Should.Throw<TException>(action);
22+
additionalAssertions(ex);
23+
}
24+
}

src/GitVersion.Core.Tests/Extensions/StringFormatWithExtensionTests.cs

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1+
using System.Globalization;
12
using GitVersion.Core.Tests.Helpers;
2-
using GitVersion.Helpers;
3+
using GitVersion.Formatting;
34

45
namespace GitVersion.Core.Tests;
56

@@ -244,4 +245,29 @@ public void FormatProperty_NullObject_WithFallback_QuotedAndEmpty()
244245
var actual = target.FormatWith(propertyObject, this.environment);
245246
Assert.That(actual, Is.EqualTo(""));
246247
}
248+
249+
[Test]
250+
public void FormatAssemblyInformationalVersionWithSemanticVersionCustomFormattedCommitsSinceVersionSource()
251+
{
252+
var semanticVersion = new SemanticVersion
253+
{
254+
Major = 1,
255+
Minor = 2,
256+
Patch = 3,
257+
PreReleaseTag = new SemanticVersionPreReleaseTag(string.Empty, 9, true),
258+
BuildMetaData = new SemanticVersionBuildMetaData("Branch.main")
259+
{
260+
Branch = "main",
261+
VersionSourceSha = "versionSourceSha",
262+
Sha = "commitSha",
263+
ShortSha = "commitShortSha",
264+
CommitsSinceVersionSource = 42,
265+
CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z", CultureInfo.InvariantCulture)
266+
}
267+
};
268+
const string target = "{Major}.{Minor}.{Patch}-{CommitsSinceVersionSource:0000}";
269+
const string expected = "1.2.3-0042";
270+
var actual = target.FormatWith(semanticVersion, this.environment);
271+
Assert.That(actual, Is.EqualTo(expected));
272+
}
247273
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
using System.Globalization;
2+
using GitVersion.Formatting;
3+
4+
namespace GitVersion.Tests.Formatting;
5+
6+
[TestFixture]
7+
public class DateFormatterTests
8+
{
9+
[Test]
10+
public void Priority_ShouldBe2() => new DateFormatter().Priority.ShouldBe(2);
11+
12+
[Test]
13+
public void TryFormat_NullValue_ReturnsFalse()
14+
{
15+
var sut = new DateFormatter();
16+
var result = sut.TryFormat(null, "yyyy-MM-dd", out var formatted);
17+
result.ShouldBeFalse();
18+
formatted.ShouldBeEmpty();
19+
}
20+
21+
[TestCase("2021-01-01", "yyyy-MM-dd", "2021-01-01")]
22+
[TestCase("2021-01-01T12:00:00Z", "yyyy-MM-ddTHH:mm:ssZ", "2021-01-01T12:00:00Z")]
23+
public void TryFormat_ValidDateFormats_ReturnsExpectedResult(string input, string format, string expected)
24+
{
25+
var date = DateTime.Parse(input, CultureInfo.InvariantCulture);
26+
var sut = new DateFormatter();
27+
var result = sut.TryFormat(date, format, out var formatted);
28+
result.ShouldBeTrue();
29+
formatted.ShouldBe(expected);
30+
}
31+
}

0 commit comments

Comments
 (0)