### Initialize GitVersion Configuration Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/build-servers/appveyor.md Run this command in the terminal to start the interactive setup process for build servers. ```bash GitVersion init ``` -------------------------------- ### Basic BitBucket Pipelines Integration Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/build-servers/bitbucket-pipelines.md This example shows the basic setup for using GitVersion in a BitBucket Pipeline. Ensure `clone:depth` is set to `full` to avoid shallow clones, which cause GitVersion errors. The `dotnet-gitversion /output buildserver` command detects the BitBucket environment and generates a `gitversion.properties` file. ```yml image: mcr.microsoft.com/dotnet/sdk:8.0 clone: depth: full pipelines: default: - step: name: Version and build script: - export PATH="$PATH:/root/.dotnet/tools" - dotnet tool install --global GitVersion.Tool - dotnet-gitversion /output buildserver - source gitversion.properties - echo Building with semver $GITVERSION_FULLSEMVER - dotnet build ``` -------------------------------- ### Install GitVersion as a .NET Global Tool Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/usage/cli/installation.md Installs the tool globally for use across the system. ```shell dotnet tool install --global GitVersion.Tool ``` -------------------------------- ### Display GitVersion Version Source: https://github.com/gittools/gitversion/blob/main/new-cli/command.md Use this command to display the installed GitVersion version. No setup is required. ```sh gitversion --version ``` -------------------------------- ### Install GitVersion via Homebrew Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/usage/cli/installation.md Installs the GitVersion formula on macOS or Linux systems. ```shell brew install gitversion ``` -------------------------------- ### Feature Branch Versioning Example Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/learn/branching-strategies/gitflow/index.md Illustrates the version format for feature branches. This format is used for builds that are not in strict adherence to SemVer. ```txt {major}.{minor}.{patch}-{pre-release} Branch:'{branchName}' Sha:'{sha}' 1.2.3-alpha.feature-a682956d Branch:'feature1' Sha:'a682956dccae752aa24597a0f5cd939f93614509' ``` -------------------------------- ### Run GitVersion Global Tool Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/usage/cli/installation.md Executes the globally installed GitVersion tool. ```shell dotnet-gitversion ``` -------------------------------- ### Install GitVersion via Chocolatey Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/usage/cli/installation.md Installs the portable GitVersion package on Windows systems. ```shell choco install GitVersion.Portable ``` -------------------------------- ### Install GitVersion as a .NET Local Tool Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/usage/cli/installation.md Sets up a local tool manifest in the project root to ensure consistent versions across team members. ```shell dotnet new tool-manifest # if you don't already have a manifest file dotnet tool install GitVersion.Tool ``` -------------------------------- ### Basic GitVersion.yml Configuration Source: https://context7.com/gittools/gitversion/llms.txt Configure GitVersion's behavior using a GitVersion.yml file. This example sets the workflow, versioning scheme, and includes branch-specific settings. ```yaml # Use GitHubFlow workflow as base workflow: GitHubFlow/v1 # Global settings mode: ContinuousDelivery tag-prefix: '[vV]?' next-version: 2.0.0 commit-message-incrementing: Enabled update-build-number: true # Version bump message patterns major-version-bump-message: '\+semver:\s?(breaking|major)' minor-version-bump-message: '\+semver:\s?(feature|minor)' patch-version-bump-message: '\+semver:\s?(fix|patch)' no-bump-message: '\+semver:\s?(none|skip)' # Assembly versioning assembly-versioning-scheme: MajorMinorPatch assembly-file-versioning-scheme: MajorMinorPatch assembly-informational-format: '{InformationalVersion}' assembly-file-versioning-format: '{Major}.{Minor}.{Patch}.{env:BUILD_NUMBER ?? 0}' # Ignore specific commits or paths ignore: sha: - e7bc24c0f34728a25c9187b8d0b041d935763e3a commits-before: 2023-01-01T00:00:00 paths: - ^docs/ - ^\.github/ # Branch-specific configuration branches: main: label: '' increment: Patch is-main-branch: true prevent-increment: of-merged-branch: true release: regex: ^releases?[/-](?.+) mode: ManualDeployment label: beta increment: Patch is-release-branch: true feature: regex: ^features?[/-](?.+) mode: ManualDeployment label: '{BranchName}' increment: Inherit source-branches: - main - release pull-request: regex: ^(pull-requests|pull|pr)[/-](?\d*) mode: ContinuousDelivery label: 'PullRequest{Number}' increment: Inherit # Custom merge message format merge-message-formats: tfs: '^Merged (?:PR (?\d+)): Merge (?.+) to (?.+)' ``` -------------------------------- ### Display GitVersion Help Information Source: https://github.com/gittools/gitversion/blob/main/new-cli/command.md Use this command to display the help message for GitVersion, outlining available commands and options. No setup is required. ```sh gitversion --help ``` -------------------------------- ### Install GitVersion.MsBuild via Package Manager Console Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/usage/msbuild.md Use this command in the Package Manager Console to add the GitVersion.MsBuild NuGet package to your project. ```shell Install-Package GitVersion.MsBuild ``` -------------------------------- ### Access GitVersion Variables Source: https://context7.com/gittools/gitversion/llms.txt Example of the JSON output structure containing calculated versioning metadata. ```json { "Major": 3, "Minor": 22, "Patch": 11, "PreReleaseLabel": "beta", "PreReleaseLabelWithDash": "-beta", "PreReleaseNumber": 99, "PreReleaseTag": "beta.99", "PreReleaseTagWithDash": "-beta.99", "SemVer": "3.22.11-beta.99", "FullSemVer": "3.22.11-beta.99+88", "MajorMinorPatch": "3.22.11", "AssemblySemVer": "3.22.11.0", "AssemblySemFileVer": "3.22.11.0", "InformationalVersion": "3.22.11-beta.99+88.Branch.release/3.22.11.Sha.28c853...", "BranchName": "release/3.22.11", "EscapedBranchName": "release-3.22.11", "Sha": "28c853159a46b5a87e6cc9c4f6e940c59d6bc68a", "ShortSha": "28c8531", "CommitDate": "2024-01-15", "VersionSourceSha": "abc123...", "VersionSourceDistance": 7, "VersionSourceIncrement": "Minor", "WeightedPreReleaseNumber": 30099, "UncommittedChanges": 0, "BuildMetaData": 88, "FullBuildMetaData": "88.Branch.release/3.22.11.Sha.28c853..." } ``` -------------------------------- ### Format Assembly File Versioning Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/mdsource/configuration.source.md Examples of using format strings with variables or environment variables to define the assembly file version. ```yaml # use a variable if non-null or a fallback value otherwise assembly-file-versioning-format: '{Major}.{Minor}.{Patch}.{WeightedPreReleaseNumber ?? 0}' # use an environment variable or raise an error if not available assembly-file-versioning-format: '{Major}.{Minor}.{Patch}.{env:BUILD_NUMBER}' # use an environment variable if available or a fallback value otherwise assembly-file-versioning-format: '{Major}.{Minor}.{Patch}.{env:BUILD_NUMBER ?? 42}' ``` -------------------------------- ### GitFlow Workflow Configuration Example Source: https://context7.com/gittools/gitversion/llms.txt Example YAML configuration for GitVersion using the GitFlow branching strategy. This defines settings for develop, release, and hotfix branches. ```yaml # Configuration for GitFlow workflow workflow: GitFlow # Define branches and their configurations branches: master: prevent-increment: true track-merge-target: true is-main-branch: true develop: increment: Patch track-merge-target: true release: regex: ^releases?[ ](?.+) mode: ContinuousDeployment tag-number-pattern: '\d+' increment: Patch prevent-increment: true track-release-branches: true hotfix: regex: ^hotfix[ ](?.+) mode: ContinuousDeployment tag-number-pattern: '\d+' increment: Patch prevent-increment: true track-release-branches: true feature: regex: ^features?[ ](?.+) mode: ContinuousDeployment increment: Inherit source-branches: [develop] pull-request: regex: ^(pull-requests|pull|pr)[ ](?\d*) mode: ContinuousDelivery tag-number-pattern: '\d+' increment: Inherit ``` -------------------------------- ### Configure GitVersion in a Buildkite Pipeline Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/build-servers/buildkite.md Example pipeline configuration using the GitVersion Docker image and Buildkite meta-data to share version information. ```yaml env: BUILDKITE_GIT_FETCH_FLAGS: "-v --tags" steps: - label: "Calculate version" command: buildkite-agent meta-data set "GitVersion_SemVer" $(./dotnet-gitversion -showvariable SemVer) plugins: - docker#v3.9.0: image: "gittools/gitversion" environment: - "BUILDKITE" - "BUILDKITE_BRANCH" - "BUILDKITE_PULL_REQUEST" - wait - label: "Use calculated version" command: echo "Calculated version is $(buildkite-agent meta-data get "GitVersion_SemVer")" ``` -------------------------------- ### Set GitVersion Meta-data via Buildkite Hooks Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/build-servers/buildkite.md Example of using a post-checkout hook to automatically set all GitVersion variables as Buildkite meta-data. ```shell eval $(gitversion | jq -r 'to_entries[] | "buildkite-agent meta-data set GitVersion_\(.key) \(.value)"') ``` -------------------------------- ### GitVersion Assembly Versioning Format Example Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/configuration.md Specifies custom formats for AssemblyFileVersion and AssemblyVersion using variables or environment variables. ```yaml assembly-file-versioning-format: '{Major}.{Minor}.{Patch}.{WeightedPreReleaseNumber ?? 0}' ``` ```yaml assembly-file-versioning-format: '{Major}.{Minor}.{Patch}.{env:BUILD_NUMBER}' ``` ```yaml assembly-file-versioning-format: '{Major}.{Minor}.{Patch}.{env:BUILD_NUMBER ?? 42}' ``` -------------------------------- ### Verify invariant culture formatting outputs Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/custom-formatting.md Examples of how numeric and date values are rendered consistently across all environments. ```csharp // All environments produce the same output: // {VersionSourceDistance:N0} → "1,234" // {CommitDate:MMM dd, yyyy} → "Mar 15, 2024" // {Major:C} → "¤1.00" (generic currency symbol) ``` -------------------------------- ### GitVersion Branch Configuration Example Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/configuration.md Defines branch-specific versioning strategies, including modes, labels, increment types, and source branch tracking. ```yaml branches: main: mode: ContinuousDeployment label: '' increment: Patch prevent-increment: of-merged-branch: true track-merge-target: false track-merge-message: true regex: "^master$|^main$" source-branches: [] is-source-branch-for: [] tracks-release-branches: false is-release-branch: false is-main-branch: true pre-release-weight: 55000 feature: mode: ContinuousDelivery label: "{BranchName}" increment: Minor prevent-increment: when-current-commit-tagged: false track-merge-message: true regex: "^features?[\/-](?.+)" source-branches: - main is-source-branch-for: [] is-main-branch: false pre-release-weight: 30000 hotfix: mode: ContinuousDelivery label: "{BranchName}" increment: Patch prevent-increment: when-current-commit-tagged: false regex: "^hotfix(es)?[\/-](?.+)" source-branches: - main is-source-branch-for: [] is-release-branch: true is-main-branch: false pre-release-weight: 30000 pull-request: mode: ContinuousDelivery label: "PullRequest{Number}" increment: Inherit prevent-increment: of-merged-branch: true when-current-commit-tagged: false track-merge-message: true regex: "^(pull-requests|pull|pr)[\/-](?\d*)" source-branches: - main - feature - hotfix is-source-branch-for: [] pre-release-weight: 30000 unknown: increment: Patch prevent-increment: when-current-commit-tagged: false regex: "(?.+)" source-branches: - main is-source-branch-for: [] pre-release-weight: 30000 ignore: sha: [] paths: [] ``` -------------------------------- ### Illustrating Branch Configuration Inheritance Behavior Source: https://github.com/gittools/gitversion/blob/main/BREAKING_CHANGES.md This log example demonstrates how GitVersion now generates versions on feature branches, considering the source branch's configuration for a more intuitive versioning scheme. Previously, the version generated was different. ```log * 1f1cfb4 52 minutes ago (HEAD -> feature/just-a-test) * 1f9654d 54 minutes ago (release/1.1.0) * be72411 56 minutes ago (develop) * 14800ff 58 minutes ago (tag: 1.0.0, main) ``` -------------------------------- ### Continuous Deployment Versioning Log Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/version-increments.md Example output showing how GitVersion increments versions per commit in continuous deployment mode. ```log e137e9 -> 1.0.0+0 a5f6c5 -> 1.0.1-ci.1 adb29a -> 1.0.1-feature-foo.1 (PR #5 Version: `1.0.1-PullRequest.5+2`) 7c2438 -> 1.0.1-feature-foo.2 (PR #5 Version: `1.0.1-PullRequest.5+3`) 5f413b -> 1.0.1-ci.4 d6155b -> 2.0.0-rc.1+4 (Before and after tag) d53ab6 -> 2.0.0-rc.2 (If there was another commit on the release branch it would be 2.0.0-rc.3) b5d142 -> 2.0.0-ci.0 (2.0.0 branch was merged, so main is now at 2.0.0) ``` -------------------------------- ### Configuration Override Examples Source: https://context7.com/gittools/gitversion/llms.txt Override GitVersion configuration options at runtime without modifying the GitVersion.yml file. This is useful for CI scenarios with different versioning requirements. ```bash # Override tag prefix gitversion /output json /overrideconfig tag-prefix=custom ``` ```bash # Override assembly versioning scheme gitversion /output json /overrideconfig assembly-versioning-scheme=MajorMinor ``` ```bash # Override next version (force major bump) gitversion /output json /overrideconfig next-version=6 ``` ```bash # Multiple overrides gitversion /output json /overrideconfig tag-prefix=v /overrideconfig mode=ContinuousDelivery ``` ```bash # Override with environment variable fallback gitversion /output json /overrideconfig assembly-versioning-format="{Major}.{Minor}.{Patch}.{env:BUILD_NUMBER ?? 0}" ``` -------------------------------- ### Numeric Formatting Examples: Currency, Percentage, and Thousands Separator Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/custom-formatting.md Demonstrates various numeric formatting options including currency (invariant culture), percentage, and thousands separators for version components. ```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-{VersionSourceDistance:N0}" # Result: "Build-1,234" ``` -------------------------------- ### Sample build script Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/build-servers/octopus-deploy.md Initializes paths for GitVersion, Octo, and NuGet tools in a build script. ```powershell [CmdletBinding()] param() $ErrorActionPreference = "Stop" trap { Pop-Location Write-Error "$_" Exit 1 } Push-Location $PSScriptRoot # Tools $gitversion = "tools\GitVersion\GitVersion.exe" $octo = "tools\Octo\Octo.exe" $nuget = "tools\NuGet\NuGet.exe" ``` -------------------------------- ### Run GitVersion for MyGet Build Services Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/build-servers/myget.md Execute GitVersion with the /output buildserver argument in a pre-build script. This sets the %PackageVersion% environment variable for MyGet. ```bash gitversion /output buildserver ``` -------------------------------- ### Build and Preview Documentation (Shell) Source: https://github.com/gittools/gitversion/blob/main/docs/readme.md These commands are used to build and preview the GitVersion documentation locally. They are applicable on Windows, macOS, and Linux. ```shell ./build.ps1 -Stage build -Target BuildPrepare ./build.ps1 -Stage build -Target Build ./build.ps1 -Stage docs -Target PreviewDocs ``` -------------------------------- ### Configure GitHubFlow Workflow Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/mdsource/configuration.source.md Example of overriding the default tag prefix when using the GitHubFlow workflow. ```yaml workflow: GitHubFlow/v1 tag-prefix: '[abc]' ``` -------------------------------- ### Execute Build and Test Commands Source: https://github.com/gittools/gitversion/blob/main/AGENTS.md Standard CLI commands for building, testing, and formatting the legacy and new GitVersion solutions. ```bash # --- src/ (legacy CLI) --- # Build the solution dotnet build ./src/GitVersion.slnx # Run all tests dotnet test ./src/GitVersion.slnx # Run tests for a single project dotnet test --project ./src/GitVersion.Core.Tests/GitVersion.Core.Tests.csproj # Run the legacy CLI locally dotnet run --project src/GitVersion.App # Format code dotnet format ./src/GitVersion.slnx # Verify formatting (CI-friendly, non-zero exit if changes needed) dotnet format --verify-no-changes ./src/GitVersion.slnx # --- new-cli/ (new CLI) --- # Build the new CLI solution dotnet build ./new-cli/GitVersion.slnx # Run tests for the new CLI dotnet test ./new-cli/GitVersion.slnx # Run the new CLI locally dotnet run --project new-cli/GitVersion.Cli ``` -------------------------------- ### Preview Documentation Locally Source: https://github.com/gittools/gitversion/blob/main/CONTRIBUTING.md Runs the build script to generate and preview documentation changes. ```powershell ./build.ps1 -Stage docs -Target PreviewDocs ``` -------------------------------- ### Configure Pull Request Branching Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/configuration.md Example configuration for handling pull request branches, including label patterns and increment strategies. ```yaml branches: pull-request: mode: ContinuousDelivery label: PullRequest{Number} increment: Inherit prevent-increment: of-merged-branch: true when-current-commit-tagged: false track-merge-message: true regex: ^(pull-requests|pull|pr)[\/-](?\d*) source-branches: - main - release - feature is-source-branch-for: [] pre-release-weight: 30000 ``` -------------------------------- ### Create GitVersion configuration Source: https://github.com/gittools/gitversion/blob/main/CONTRIBUTING.md Initializes a GitVersion configuration builder using the GitFlow strategy. ```csharp var configurationBuilder = GitFlowConfigurationBuilder.New; ``` -------------------------------- ### Customize and build GitVersion configuration Source: https://github.com/gittools/gitversion/blob/main/CONTRIBUTING.md Customizes the GitVersion configuration by setting the deployment mode and next version, then builds the configuration object. ```csharp var configuration = configurationBuilder .WithDeploymentMode(DeploymentMode.ContinuousDeployment) .WithNextVersion("1.0.0") .Build(); ``` -------------------------------- ### Use EmptyRepositoryFixture Source: https://github.com/gittools/gitversion/blob/main/CONTRIBUTING.md Initializes an empty Git repository for testing purposes using the EmptyRepositoryFixture. ```csharp using var repo = new EmptyRepositoryFixture(); ``` -------------------------------- ### Enable GitHubFlow Workflow Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/learn/branching-strategies/githubflow/examples.md To enable the GitHubFlow workflow, reference the builtin template GitHubFlow/v1 in the configuration. This example shows the basic configuration. ```yaml workflow: GitHubFlow/v1 mode: ContinuousDelivery ``` -------------------------------- ### Generate Build and Documentation Schemas Source: https://github.com/gittools/gitversion/blob/main/AGENTS.md Commands to prepare the build environment and regenerate configuration schemas after schema changes. ```bash ./build.ps1 -Stage build -Target BuildPrepare ./build.ps1 -Stage docs -Target GenerateSchemas ``` -------------------------------- ### Zero-Padded Commit Count Formatting Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/custom-formatting.md Example showing zero-padded formatting for the version source distance, ensuring it always displays with four digits. ```yaml # Zero-padded commit count assembly-informational-format: "{Major}.{Minor}.{Patch}-{VersionSourceDistance:0000}" # Result: "1.2.3-0042" ``` -------------------------------- ### Initialize GitVersion Configuration Source: https://github.com/gittools/gitversion/blob/main/new-cli/command.md Initializes a GitVersion.yml configuration file in the current directory. This is the first step to customize GitVersion's behavior. ```sh gitversion config init ``` -------------------------------- ### Write GitVersion integration test scenario Source: https://github.com/gittools/gitversion/blob/main/CONTRIBUTING.md Demonstrates creating tagged commits, branches, and making commits to simulate a Git history for testing GitVersion's output. ```csharp fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("feature-test"); fixture.Repository.Checkout("feature-test"); fixture.Repository.MakeACommit(); fixture.Repository.MakeCommits(4); ``` -------------------------------- ### Basic GitVersion Command Line Usage in TeamCity Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/build-servers/teamcity.md Use this command line configuration in TeamCity to execute GitVersion.exe with specified parameters for outputting build server information and updating assembly info. ```bash GitVersion.exe /output buildserver /updateassemblyinfo true ``` -------------------------------- ### Create a release script with GitVersion Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/build-servers/octopus-deploy.md Automates tagging and pushing a stable version by calculating the version using GitVersion. ```powershell [CmdletBinding()] param() ##### Config ##### # Path to GitVersion.exe $gitversion = "tools\GitVersion\GitVersion.exe" function Create-AdditionalReleaseArtifacts { param( [string]$Version ) # Put any custom release logic here (like generating release notes?) } ### END Config ### $ErrorActionPreference = "Stop" trap { Pop-Location Write-Error "$_" Exit 1 } Push-Location $PSScriptRoot # Make sure there are no pending changes $pendingChanges = & git status --porcelain if ($pendingChanges -ne $null) { throw 'You have pending changes, aborting release' } # Pull latest, fast-forward only so that it git stops if there is an error & git fetch origin & git checkout main & git merge origin/main --ff-only # Determine version to release $output = & $gitversion /output json $versionInfoJson = $output -join "`n" $versionInfo = $versionInfoJson | ConvertFrom-Json $stableVersion = $versionInfo.MajorMinorPatch # Create release Create-AdditionalReleaseArtifacts $stableVersion # Always create a new commit because some CI servers cannot be triggered by just pushing a tag & git commit -Am "Create release $stableVersion" --allow-empty & git tag $stableVersion if ($LASTEXITCODE -ne 0) { & git reset --hard HEAD^ throw "No changes detected since last release" } & git push origin main --tags Pop-Location ``` -------------------------------- ### Format Version with Padded Build Number and Branch Name Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/custom-formatting.md Example of using format strings in templates to include a padded version source distance and a lowercase branch name. ```yaml assembly-informational-format: "{Major}.{Minor}.{Patch}-{VersionSourceDistance:0000}" assembly-informational-format: "{SemVer}-{BranchName:l}" ``` -------------------------------- ### GitHub Actions Workflow for GitVersion Integration Source: https://context7.com/gittools/gitversion/llms.txt Integrate GitVersion into your GitHub Actions CI/CD pipeline. Requires a full repository checkout and specific GitTools actions for setup and execution. ```yaml name: Build on: [push, pull_request] jobs: build: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 with: fetch-depth: 0 # Required: full history for GitVersion - name: Install GitVersion uses: gittools/actions/gitversion/setup@v0 with: versionSpec: '6.x' - name: Determine Version id: gitversion uses: gittools/actions/gitversion/execute@v0 with: useConfigFile: true - name: Display Version run: | echo "SemVer: ${{ steps.gitversion.outputs.semVer }}" echo "NuGet: ${{ steps.gitversion.outputs.nuGetVersion }}" echo "Full: ${{ steps.gitversion.outputs.fullSemVer }}" - name: Build with Version run: dotnet build -p:Version=${{ steps.gitversion.outputs.semVer }} - name: Create NuGet Package run: dotnet pack -p:PackageVersion=${{ steps.gitversion.outputs.nuGetVersion }} ``` -------------------------------- ### Run GitVersion on Linux Build Host Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/build-servers/bamboo.md This script executes the GitVersion global tool on a Linux build host and processes its output into a key-value format for Bamboo. ```bash ~/.dotnet/tools/dotnet-gitversion > gitversion.txt sed -i '1d;$ d;s/ //;s/"//g;s/,//;s/:/=/' gitversion.txt ``` -------------------------------- ### Format Commit Date in Assembly Informational String Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/custom-formatting.md Apply standard .NET date and time format specifiers to version properties like 'CommitDate'. This example formats the commit date as 'yyyy-MM-dd'. ```yaml assembly-informational-format: "Build-{SemVer}-{CommitDate:yyyy-MM-dd}" ``` -------------------------------- ### Configure GitVersion.MsBuild with PackageReference Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/usage/msbuild.md When using PackageReference, add `all` to the GitVersion.MsBuild dependency to prevent it from becoming a dependency of your package. ```xml All ``` -------------------------------- ### Output Version to Wix Files Source: https://github.com/gittools/gitversion/blob/main/new-cli/command.md Reads version variables from standard input and writes them to globbed .wxi files. This is used for updating Windows Installer XML (WIX) source files with version information. ```sh cat gitversion.json | gitversion output wix --path ./**/*.wxi ``` -------------------------------- ### Filter Version Variables by Regex in Dotenv Format Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/usage/cli/output.md Filter the Dotenv output using a regular expression to select multiple version variables. This example selects 'major', 'sha', and 'prerelease' related variables. ```bash gitversion /output dotenv | grep -iE "major|sha=|_prerelease" ``` -------------------------------- ### Configure Trunk-Based Development Source: https://context7.com/gittools/gitversion/llms.txt Sets up an experimental trunk-based workflow using the Mainline strategy. ```yaml # Trunk-based workflow (experimental) workflow: TrunkBased/preview1 branches: main: mode: ContinuousDeployment label: '' increment: Patch is-main-branch: true regex: ^master$|^main$ feature: mode: ContinuousDelivery label: '{BranchName}' increment: Minor regex: ^features?[\/\-](?.+) source-branches: - main hotfix: mode: ContinuousDelivery label: '{BranchName}' increment: Patch is-release-branch: true regex: ^hotfix(es)?[\/\-](?.+) source-branches: - main # Use mainline strategy for simple increment strategies: - ConfiguredNextVersion - Mainline ``` -------------------------------- ### Format PreRelease Label to Lowercase and Pad Version Distance Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/custom-formatting.md Combine string case formatters with numeric padding. This example formats the pre-release label to lowercase and pads the version source distance to four digits. ```yaml assembly-informational-format: "{Major}.{Minor}.{Patch}-{PreReleaseLabel:l}.{VersionSourceDistance:0000}" ``` -------------------------------- ### EffectiveBranchConfiguration Methods Source: https://github.com/gittools/gitversion/blob/main/src/GitVersion.Core/PublicAPI.Shipped.txt Documentation for cloning and equality comparison of EffectiveBranchConfiguration. ```APIDOC ## GitVersion.Configuration.EffectiveBranchConfiguration Methods ### Description Provides methods for cloning, retrieving the equality contract type, comparing for equality, and printing members of an EffectiveBranchConfiguration object. ### Method virtual ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **EffectiveBranchConfiguration** - A clone of the object. - **Type** - The equality contract type. - **bool** - True if the objects are equal, false otherwise. - **bool** - True if members were successfully printed, false otherwise. #### Response Example ```csharp var clonedConfig = effectiveBranchConfig.Clone$(); var type = effectiveBranchConfig.EqualityContract; var isEqual = effectiveBranchConfig.Equals(otherConfig); var printed = effectiveBranchConfig.PrintMembers(builder); ``` ``` -------------------------------- ### Illustrating Fallback Branch Configuration Inheritance Source: https://github.com/gittools/gitversion/blob/main/BREAKING_CHANGES.md This log example shows the hierarchy of branch configuration inheritance. The hotfix branch configuration overrides the main branch configuration, which in turn overrides the root fallback configuration. ```log * 1f1cfb4 52 minutes ago (HEAD -> hotfix/just-a-test) * 14800ff 58 minutes ago (tag: 1.0.0, main) ``` -------------------------------- ### EffectiveConfiguration Methods Source: https://github.com/gittools/gitversion/blob/main/src/GitVersion.Core/PublicAPI.Shipped.txt Documentation for cloning and equality comparison of EffectiveConfiguration. ```APIDOC ## GitVersion.Configuration.EffectiveConfiguration Methods ### Description Provides methods for cloning, retrieving the equality contract type, comparing for equality, and printing members of an EffectiveConfiguration object. ### Method virtual ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **EffectiveConfiguration** - A clone of the object. - **Type** - The equality contract type. - **bool** - True if the objects are equal, false otherwise. - **bool** - True if members were successfully printed, false otherwise. #### Response Example ```csharp var clonedConfig = effectiveConfig.Clone$(); var type = effectiveConfig.EqualityContract; var isEqual = effectiveConfig.Equals(otherConfig); var printed = effectiveConfig.PrintMembers(builder); ``` ``` -------------------------------- ### Apply Numeric Formatting to Patch Version Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/custom-formatting.md Use standard .NET numeric format strings like 'F2' for fixed-point formatting on version components. This example formats the patch version to two decimal places. ```yaml # GitVersion.yml assembly-informational-format: "{Major}.{Minor}.{Patch:F2}-{PreReleaseLabel}" ``` -------------------------------- ### Override multiple configuration options Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/usage/cli/arguments.md Demonstrates applying multiple configuration overrides in a single command execution. ```bash GitVersion.exe /output json /overrideconfig tag-prefix=custom /overrideconfig assembly-versioning-scheme=MajorMinor ``` -------------------------------- ### ConfigurationInfo Methods Source: https://github.com/gittools/gitversion/blob/main/src/GitVersion.Core/PublicAPI.Shipped.txt Documentation for cloning and equality comparison of ConfigurationInfo. ```APIDOC ## GitVersion.ConfigurationInfo Methods ### Description Provides methods for cloning, retrieving the equality contract type, comparing for equality, and printing members of a ConfigurationInfo object. ### Method virtual ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **ConfigurationInfo** - A clone of the object. - **Type** - The equality contract type. - **bool** - True if the objects are equal, false otherwise. - **bool** - True if members were successfully printed, false otherwise. #### Response Example ```csharp var clonedConfig = configurationInfo.Clone$(); var type = configurationInfo.EqualityContract; var isEqual = configurationInfo.Equals(otherConfig); var printed = configurationInfo.PrintMembers(builder); ``` ``` -------------------------------- ### Configure pull request branch with label and regex Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/mdsource/configuration.source.md This example shows how to configure a `pull-request` branch, including setting a custom label using a named capture group `Number` from the regex, and disabling increment when the current commit is tagged. ```yaml branches: pull-request: mode: ContinuousDelivery label: PullRequest{Number} increment: Inherit prevent-increment: of-merged-branch: true when-current-commit-tagged: false track-merge-message: true regex: ^(pull-requests|pull|pr)[/-](?\d*) source-branches: - main - release - feature is-source-branch-for: [] pre-release-weight: 30000 ``` -------------------------------- ### Settings Source: https://github.com/gittools/gitversion/blob/main/src/GitVersion.Core/PublicAPI.Shipped.txt Configuration settings for GitVersion execution behavior. ```APIDOC ## Settings ### Description Defines operational settings that control how GitVersion interacts with the repository. ### Properties - **AllowShallow** (bool) - Whether to allow shallow clones. - **NoCache** (bool) - Disables caching. - **NoFetch** (bool) - Disables fetching from remote. - **NoNormalize** (bool) - Disables repository normalization. - **OnlyTrackedBranches** (bool) - Limits operations to tracked branches only. ``` -------------------------------- ### GitVersion.Settings Methods Source: https://github.com/gittools/gitversion/blob/main/src/GitVersion.Core/PublicAPI.Shipped.txt Details the virtual methods available for the Settings class. ```APIDOC ## GitVersion.Settings ### Description Represents the settings for GitVersion. ### Methods - `Clone$()`: Creates a clone of the Settings. - `EqualityContract.get`: Gets the equality contract type. - `Equals(GitVersion.Settings? other)`: Checks if two Settings objects are equal. - `PrintMembers(System.Text.StringBuilder! builder)`: Prints the members of the Settings to a StringBuilder. ``` -------------------------------- ### Configure Diagnostic and Logging Options Source: https://context7.com/gittools/gitversion/llms.txt CLI flags to enable detailed logging, verbosity levels, and configuration inspection for troubleshooting. ```bash # Enable diagnostic mode with console logging gitversion /diag /l console # Write logs to file gitversion /diag /l /path/to/gitversion.log # Set verbosity level gitversion /verbosity Diagnostic # Levels: Quiet, Minimal, Normal, Verbose, Diagnostic # Show effective configuration (defaults + overrides) gitversion /showconfig # Bypass version cache gitversion /nocache # Allow running on shallow clones (not recommended) gitversion /allowshallow ``` -------------------------------- ### Restore and Run .NET Local Tools Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/usage/cli/installation.md Commands for restoring project-specific tools and executing them via the dotnet CLI. ```shell dotnet tool restore ``` ```shell dotnet gitversion ``` ```shell dotnet tool exec GitVersion.Tool # or using the shorthand alias dotnet dnx GitVersion.Tool # or even shorter dnx GitVersion.Tool ``` -------------------------------- ### GitVersion Configuration Interfaces Source: https://github.com/gittools/gitversion/blob/main/src/GitVersion.Core/PublicAPI.Shipped.txt Details on interfaces for configuring GitVersion, including version patterns, strategies, and ignore rules. ```APIDOC ## GitVersion Configuration Interfaces ### IGitVersionConfiguration Represents the main configuration for GitVersion. - **VersionInBranchPattern**: `string?` - The pattern used to determine the version within a branch. - **VersionStrategy**: `GitVersion.VersionCalculation.VersionStrategies` - The version calculation strategy to use. - **Workflow**: `string?` - The workflow definition. ### IIgnoreConfiguration Configuration for ignoring specific Git references or paths. - **Before**: `System.DateTimeOffset?` - Ignore references before this date. - **IsEmpty**: `bool` - Checks if the ignore configuration is empty. - **Paths**: `System.Collections.Generic.IReadOnlySet` - A set of paths to ignore. - **Shas**: `System.Collections.Generic.IReadOnlySet` - A set of commit SHAs to ignore. ### IPreventIncrementConfiguration Configuration for preventing version increments under certain conditions. - **OfMergedBranch**: `bool?` - Prevent incrementing if the branch is merged. - **WhenBranchMerged**: `bool?` - Prevent incrementing when a branch is merged. - **WhenCurrentCommitTagged**: `bool?` - Prevent incrementing if the current commit is tagged. ``` -------------------------------- ### TrunkBased Workflow Configuration (Preview) Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/reference/configuration.md This YAML configuration outlines the experimental settings for the TrunkBased workflow. It includes versioning strategies and branch handling. ```yaml mode: ContinuousDelivery label: "{BranchName}" increment: Inherit prevent-increment: of-merged-branch: false when-branch-merged: false when-current-commit-tagged: true track-merge-target: false track-merge-message: true commit-message-incrementing: Enabled regex: '' source-branches: [] is-source-branch-for: [] tracks-release-branches: false is-release-branch: false is-main-branch: false assembly-versioning-scheme: MajorMinorPatch assembly-file-versioning-scheme: MajorMinorPatch tag-prefix: "[vV]?" version-in-branch-pattern: "(?[vV]?\d+(\.\d+)?(\.\d+)?).*" major-version-bump-message: "\+semver:\s?(breaking|major)" minor-version-bump-message: "\+semver:\s?(feature|minor)" patch-version-bump-message: "\+semver:\s?(fix|patch)" no-bump-message: "\+semver:\s?(none|skip)" tag-pre-release-weight: 60000 commit-date-format: yyyy-MM-dd merge-message-formats: {} update-build-number: true semantic-version-format: Strict strategies: ``` -------------------------------- ### Run GitVersion in Docker Source: https://github.com/gittools/gitversion/blob/main/docs/input/docs/usage/docker.md Executes GitVersion for the current working directory on Linux/Unix or Windows. ```sh docker run --rm -v "$(pwd):/repo" gittools/gitversion:{tag} /repo ``` ```sh docker run --rm -v "%CD%:/repo" gittools/gitversion:{tag} /repo ``` -------------------------------- ### Integrate GitVersion with MSBuild Source: https://context7.com/gittools/gitversion/llms.txt Configuration for the GitVersion.MsBuild NuGet package to automate assembly versioning and expose version properties in .NET builds. ```xml net8.0 All false true true true ``` -------------------------------- ### Asserting SemVer in GitVersion Integration Tests Source: https://github.com/gittools/gitversion/blob/main/AGENTS.md Use the EmptyRepositoryFixture to simulate repository states and verify calculated versions with AssertFullSemver. ```csharp using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("feature/my-feature"); fixture.Checkout("feature/my-feature"); // use fixture.Checkout(), not fixture.Repository.Checkout() fixture.Repository.MakeACommit(); var configuration = GitFlowConfigurationBuilder.New.Build(); fixture.AssertFullSemver("1.0.1-my-feature.1", configuration); ```