Skip to content

Support C# format strings in config #4605

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/input/docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,9 @@ while still updating the `AssemblyFileVersion` and `AssemblyInformationVersion`
attributes. Valid values: `MajorMinorPatchTag`, `MajorMinorPatch`, `MajorMinor`,
`Major`, `None`.

For information on using format strings in these properties, see
[Format Strings](/docs/reference/custom-formatting).

### assembly-file-versioning-scheme

When updating assembly info, `assembly-file-versioning-scheme` tells GitVersion
Expand Down
252 changes: 252 additions & 0 deletions docs/input/docs/reference/custom-formatting.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
---
title: Format Strings
description: Using C# format strings in GitVersion configuration
---

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.

## Overview

The custom formatter functionality introduces several new formatters that can be used in GitVersion configuration files and templates:

- **FormattableFormatter**: Supports standard .NET format strings for numeric values, dates, and implements `IFormattable`
- **NumericFormatter**: Handles numeric formatting with culture-aware output
- **DateTimeFormatter**: Provides date and time formatting with standard and custom format specifiers
- **String Case Formatters**: Provides text case transformations with custom format specifiers

## Standard .NET Format Strings

### Numeric Formatting

You can now use standard .NET numeric format strings with version components:

```yaml
# GitVersion.yml
template: "{Major}.{Minor}.{Patch:F2}-{PreReleaseLabel}"
```

**Supported Numeric Formats:**

- `F` or `f` (Fixed-point): `{Patch:F2}` → `"1.23"`
- `N` or `n` (Number): `{BuildMetadata:N0}` → `"1,234"`
- `C` or `c` (Currency): `{Major:C}` → `"¤1.00"`
- `P` or `p` (Percent): `{CommitsSinceVersionSource:P}` → `"12,345.60 %"`
- `D` or `d` (Decimal): `{Major:D4}` → `"0001"`
- `X` or `x` (Hexadecimal): `{Patch:X}` → `"FF"`

### Date and Time Formatting

When working with date-related properties like `CommitDate`:

```yaml
template: "Build-{SemVer}-{CommitDate:yyyy-MM-dd}"
```

**Common Date Format Specifiers:**

- `yyyy-MM-dd` → `"2024-03-15"`
- `HH:mm:ss` → `"14:30:22"`
- `MMM dd, yyyy` → `"Mar 15, 2024"`
- `yyyy-MM-dd'T'HH:mm:ss'Z'` → `"2024-03-15T14:30:22Z"`

## Custom String Case Formatters

GitVersion introduces custom format specifiers for string case transformations that can be used in templates:

### Available Case Formats

| Format | Description | Example Input | Example Output |
|--------|-------------|---------------|----------------|
| `u` | **Uppercase** - Converts entire string to uppercase | `feature-branch` | `FEATURE-BRANCH` |
| `l` | **Lowercase** - Converts entire string to lowercase | `Feature-Branch` | `feature-branch` |
| `t` | **Title Case** - Capitalizes first letter of each word | `feature-branch` | `Feature-Branch` |
| `s` | **Sentence Case** - Capitalizes only the first letter | `feature-branch` | `Feature-branch` |
| `c` | **PascalCase** - Removes separators and capitalizes each word | `feature-branch` | `FeatureBranch` |

### Usage Examples

```yaml
# GitVersion.yml configuration
branches:
feature:
label: "{BranchName:c}" # Converts to PascalCase

template: "{Major}.{Minor}.{Patch}-{PreReleaseLabel:l}.{CommitsSinceVersionSource:0000}"
```

**Template Usage:**

```yaml
# Using format strings in templates
assembly-informational-format: "{Major}.{Minor}.{Patch}-{CommitsSinceVersionSource:0000}"
template: "{SemVer}-{BranchName:l}"
```

## Examples

Based on actual test cases from the implementation:

### Zero-Padded Numeric Formatting

```yaml
# Zero-padded commit count
assembly-informational-format: "{Major}.{Minor}.{Patch}-{CommitsSinceVersionSource:0000}"
# Result: "1.2.3-0042"
```

### String Case Transformations

```yaml
branches:
feature:
label: "{BranchName:c}" # PascalCase: "feature-branch" → "FeatureBranch"
hotfix:
label: "hotfix-{BranchName:l}" # Lowercase: "HOTFIX-BRANCH" → "hotfix-branch"
```

### Date and Time Formatting

```yaml
template: "{SemVer}-build-{CommitDate:yyyy-MM-dd}"
# Result: "1.2.3-build-2021-01-01"
```

### Numeric Formatting

```yaml
# Currency format (uses InvariantCulture)
template: "Cost-{Major:C}" # Result: "Cost-¤1.00"

# Percentage format
template: "Progress-{Minor:P}" # Result: "Progress-200.00 %"

# Thousands separator
template: "Build-{CommitsSinceVersionSource:N0}" # Result: "Build-1,234"
```

## Configuration Integration

The format strings are used in GitVersion configuration files through various formatting properties:

### Assembly Version Formatting

```yaml
# GitVersion.yml
assembly-informational-format: "{Major}.{Minor}.{Patch}-{CommitsSinceVersionSource:0000}"
assembly-versioning-format: "{Major}.{Minor}.{Patch}.{env:BUILD_NUMBER}"
assembly-file-versioning-format: "{MajorMinorPatch}.{CommitsSinceVersionSource}"
```

### Template-Based Configuration

```yaml
# Global template for consistent formatting across all variables
template: "{SemVer}-{BranchName:l}-{ShortSha}"

branches:
main:
label: ""
feature:
label: "{BranchName:c}.{CommitsSinceVersionSource}"
increment: Minor
release:
label: "rc-{CommitsSinceVersionSource:000}"
increment: None
```

### Environment Variable Integration

```yaml
# Using environment variables with fallbacks
template: "{Major}.{Minor}.{Patch}-{env:RELEASE_STAGE ?? 'dev'}"
assembly-informational-format: "{SemVer}+{env:BUILD_ID ?? 'local'}"
```

### Real-World Integration Examples

Based on the actual test implementation:

```yaml
# Example from VariableProviderTests.cs
assembly-informational-format: "{Major}.{Minor}.{Patch}-{CommitsSinceVersionSource:0000}"
# Result: "1.2.3-0042" when CommitsSinceVersionSource = 42

# Branch-specific formatting
branches:
feature:
label: "{BranchName:c}" # PascalCase conversion
hotfix:
label: "hotfix.{CommitsSinceVersionSource:00}"
```

## Invariant Culture Formatting

The formatting system uses `CultureInfo.InvariantCulture` by default through the chained `TryFormat` overload implementation. This provides:

- **Consistent results** across all environments and systems
- **Predictable numeric formatting** with period (.) as decimal separator and comma (,) as thousands separator
- **Standard date formatting** using English month names and formats
- **No localization variations** regardless of system locale

```csharp
// All environments produce the same output:
// {CommitsSinceVersionSource:N0} → "1,234"
// {CommitDate:MMM dd, yyyy} → "Mar 15, 2024"
// {Major:C} → "¤1.00" (generic currency symbol)
```

This ensures that version strings generated by GitVersion are consistent across different build environments, developer machines, and CI/CD systems.

## Verified Examples

The following examples are verified by actual unit tests in the GitVersion codebase:

### Zero-Padded Numeric Formatting

```yaml
assembly-informational-format: "{Major}.{Minor}.{Patch}-{CommitsSinceVersionSource:0000}"
```

**Test**: `VariableProviderTests.Format_Allows_CSharp_FormatStrings()`
**Input**: `CommitsSinceVersionSource = 42`
**Output**: `"1.2.3-0042"`

### String Case Transformations

```csharp
// From StringFormatterTests.cs
[TestCase("hello world", "c", "HelloWorld")] // PascalCase
[TestCase("hello", "u", "HELLO")] // Uppercase
[TestCase("HELLO", "l", "hello")] // Lowercase
[TestCase("hello world", "t", "Hello World")] // Title Case
[TestCase("hELLO", "s", "Hello")] // Sentence Case
```

### Numeric Format Specifiers

```csharp
// From NumericFormatterTests.cs
[TestCase("1234.5678", "n", "1,234.57")] // Number format
[TestCase("1234.5678", "f2", "1234.57")] // Fixed-point format
[TestCase("1234.5678", "f0", "1235")] // No decimals
```

### Date Formatting

```csharp
// From DateFormatterTests.cs
[TestCase("2021-01-01", "yyyy-MM-dd", "2021-01-01")]
[TestCase("2021-01-01T12:00:00Z", "yyyy-MM-ddTHH:mm:ssZ", "2021-01-01T12:00:00Z")]
```

### Currency and Percentage (InvariantCulture)

```csharp
// From FormattableFormatterTests.cs
[TestCase(123.456, "C", "¤123.46")] // Generic currency symbol
[TestCase(123.456, "P", "12,345.60 %")] // Percentage format
[TestCase(1234567890, "N0", "1,234,567,890")] // Thousands separators
```

[reference-configuration]: /docs/reference/configuration
[variables]: /docs/reference/variables
4 changes: 4 additions & 0 deletions docs/input/docs/reference/variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,8 @@ within a [supported build server][build-servers]), the above version variables
may be exposed automatically as **environment variables** in the format
`GitVersion_FullSemVer`.

## Formatting Variables

GitVersion variables can be formatted using C# format strings. See [Format Strings](/docs/reference/custom-formatting) for details.

[build-servers]: ./build-servers/
1 change: 1 addition & 0 deletions docs/input/docs/usage/cli/arguments.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ GitVersion [path]
- will output `1.2.3+beta.4`
/format Used in conjunction with /output json, will output a format
containing version variables.
Supports C# format strings - see [Format Strings](/docs/reference/custom-formatting) for details.
E.g. /output json /format {SemVer} - will output `1.2.3+beta.4`
/output json /format {Major}.{Minor} - will output `1.2`
/l Path to logfile.
Expand Down
2 changes: 2 additions & 0 deletions docs/input/docs/usage/msbuild.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ Now, when you build:
appended to it.
* `AssemblyInformationalVersion` will be set to the `InformationalVersion` variable.

Assembly version formatting can use C# format strings. See [Format Strings](/docs/reference/custom-formatting) for available options.

#### Other injected Variables

All other [variables](/docs/reference/variables) will be injected into an
Expand Down
1 change: 1 addition & 0 deletions new-cli/GitVersion.Common/GitVersion.Common.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<Compile Include="..\..\src\GitVersion.Core\Extensions\DictionaryExtensions.cs" Link="%(Filename)%(Extension)" />
<Compile Include="..\..\src\GitVersion.Core\Extensions\StringExtensions.cs" Link="Extensions\StringExtensions.cs" />
<Compile Include="..\..\src\GitVersion.Core\Extensions\CommonExtensions.cs" Link="Extensions\CommonExtensions.cs" />
<Compile Include="..\..\src\GitVersion.Core\Formatting\*.cs" Link="Formatting\%(Filename)%(Extension)" />
<Compile Include="..\..\src\GitVersion.Core\Helpers\*.cs" Link="Helpers\%(Filename)%(Extension)" />
<Compile Include="..\..\src\GitVersion.Core\Git\*.cs" Link="Git\%(Filename)%(Extension)" />
<Compile Include="..\..\src\GitVersion.Core\SemVer\*.cs" Link="SemVer\%(Filename)%(Extension)"/>
Expand Down
24 changes: 24 additions & 0 deletions src/GitVersion.Core.Tests/Extensions/ShouldlyExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
namespace GitVersion.Core.Tests.Extensions;

public static class ShouldlyExtensions
{
/// <summary>
/// Asserts that the action throws an exception of type TException
/// with the expected message.
/// </summary>
public static void ShouldThrowWithMessage<TException>(this Action action, string expectedMessage) where TException : Exception
{
var ex = Should.Throw<TException>(action);
ex.Message.ShouldBe(expectedMessage);
}

/// <summary>
/// Asserts that the action throws an exception of type TException,
/// and allows further assertion on the exception instance.
/// </summary>
public static void ShouldThrow<TException>(this Action action, Action<TException> additionalAssertions) where TException : Exception
{
var ex = Should.Throw<TException>(action);
additionalAssertions(ex);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -244,4 +244,29 @@ public void FormatProperty_NullObject_WithFallback_QuotedAndEmpty()
var actual = target.FormatWith(propertyObject, this.environment);
Assert.That(actual, Is.EqualTo(""));
}

[Test]
public void FormatAssemblyInformationalVersionWithSemanticVersionCustomFormattedCommitsSinceVersionSource()
{
var semanticVersion = new SemanticVersion
{
Major = 1,
Minor = 2,
Patch = 3,
PreReleaseTag = new SemanticVersionPreReleaseTag(string.Empty, 9, true),
BuildMetaData = new SemanticVersionBuildMetaData("Branch.main")
{
Branch = "main",
VersionSourceSha = "versionSourceSha",
Sha = "commitSha",
ShortSha = "commitShortSha",
CommitsSinceVersionSource = 42,
CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z")
}
};
const string target = "{Major}.{Minor}.{Patch}-{CommitsSinceVersionSource:0000}";
const string expected = "1.2.3-0042";
var actual = target.FormatWith(semanticVersion, this.environment);
Assert.That(actual, Is.EqualTo(expected));
}
}
30 changes: 30 additions & 0 deletions src/GitVersion.Core.Tests/Formatting/DateFormatterTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using GitVersion.Formatting;

namespace GitVersion.Core.Tests.Formatting;

[TestFixture]
public class DateFormatterTests
{
[Test]
public void Priority_ShouldBe2() => new DateFormatter().Priority.ShouldBe(2);

[Test]
public void TryFormat_NullValue_ReturnsFalse()
{
var sut = new DateFormatter();
var result = sut.TryFormat(null, "yyyy-MM-dd", out var formatted);
result.ShouldBeFalse();
formatted.ShouldBeEmpty();
}

[TestCase("2021-01-01", "yyyy-MM-dd", "2021-01-01")]
[TestCase("2021-01-01T12:00:00Z", "yyyy-MM-ddTHH:mm:ssZ", "2021-01-01T12:00:00Z")]
public void TryFormat_ValidDateFormats_ReturnsExpectedResult(string input, string format, string expected)
{
var date = DateTime.Parse(input);
var sut = new DateFormatter();
var result = sut.TryFormat(date, format, out var formatted);
result.ShouldBeTrue();
formatted.ShouldBe(expected);
}
}
Loading