Skip to content
Merged
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
7 changes: 5 additions & 2 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 Expand Up @@ -632,7 +635,7 @@ ignore:
- ^docs\/
```
##### *Monorepo*
This ignore config can be used to filter only those commits that belong to a specific project in a monorepo.
This ignore config can be used to filter only those commits that belong to a specific project in a monorepo.
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`.
* Specific match on `/ProjectB/*`:
```yaml
Expand All @@ -655,7 +658,7 @@ A commit having changes only in `/ProjectB/*` path would be ignored. A commit ha
* `/ProductA/*` and `/ProductB/*` and `/LibraryC/*`

:::
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/`.
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/`.
:::

::: {.alert .alert-warning}
Expand Down
181 changes: 181 additions & 0 deletions docs/input/docs/reference/custom-formatting.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
---
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
assembly-informational-format: "{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
assembly-informational-format: "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

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

**Template Usage:**

```yaml
# Using format strings in templates
assembly-informational-format: "{Major}.{Minor}.{Patch}-{CommitsSinceVersionSource:0000}"
assembly-informational-format: "{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
assembly-informational-format: "{SemVer}-build-{CommitDate:yyyy-MM-dd}"
# Result: "1.2.3-build-2021-01-01"
```

### Numeric Formatting

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

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

# Thousands separator
assembly-informational-format: "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}"
```

### Environment Variable Integration

```yaml
# Using environment variables with fallbacks
assembly-informational-format: "{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.
7 changes: 5 additions & 2 deletions docs/input/docs/reference/mdsource/configuration.source.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,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 Expand Up @@ -233,7 +236,7 @@ ignore:
- ^docs\/
```
##### *Monorepo*
This ignore config can be used to filter only those commits that belong to a specific project in a monorepo.
This ignore config can be used to filter only those commits that belong to a specific project in a monorepo.
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`.
* Specific match on `/ProjectB/*`:
```yaml
Expand All @@ -256,7 +259,7 @@ A commit having changes only in `/ProjectB/*` path would be ignored. A commit ha
* `/ProductA/*` and `/ProductB/*` and `/LibraryC/*`

:::
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/`.
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/`.
:::

::: {.alert .alert-warning}
Expand Down
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 @@ -12,6 +12,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
@@ -1,5 +1,6 @@
using System.Globalization;
using GitVersion.Core.Tests.Helpers;
using GitVersion.Helpers;
using GitVersion.Formatting;

namespace GitVersion.Core.Tests;

Expand Down Expand Up @@ -244,4 +245,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", CultureInfo.InvariantCulture)
}
};
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));
}
}
31 changes: 31 additions & 0 deletions src/GitVersion.Core.Tests/Formatting/DateFormatterTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System.Globalization;
using GitVersion.Formatting;

namespace GitVersion.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, CultureInfo.InvariantCulture);
var sut = new DateFormatter();
var result = sut.TryFormat(date, format, out var formatted);
result.ShouldBeTrue();
formatted.ShouldBe(expected);
}
}
Loading
Loading