├── .gitignore ├── GitVersion.yml ├── LICENSE.md ├── README.md ├── appveyor.yml ├── dotnet-setversion.sln ├── src └── dotnet-setversion │ ├── Options.cs │ ├── Program.cs │ ├── Properties │ └── AssemblyInfo.cs │ ├── VersionModel.cs │ └── dotnet-setversion.csproj └── test └── integration ├── SetVersion.cs ├── TestHelper.cs └── integration.csproj /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/visualstudio 3 | 4 | ### VisualStudio ### 5 | ## Ignore Visual Studio temporary files, build results, and 6 | ## files generated by popular Visual Studio add-ons. 7 | ## 8 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 9 | 10 | # User-specific files 11 | *.suo 12 | *.user 13 | *.userosscache 14 | *.sln.docstates 15 | 16 | # User-specific files (MonoDevelop/Xamarin Studio) 17 | *.userprefs 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | bld/ 27 | [Bb]in/ 28 | [Oo]bj/ 29 | [Ll]og/ 30 | 31 | # Visual Studio 2015 cache/options directory + VS Code 32 | .vs/ 33 | .vscode/ 34 | # Uncomment if you have tasks that create the project's static files in wwwroot 35 | #wwwroot/ 36 | 37 | # MSTest test Results 38 | [Tt]est[Rr]esult*/ 39 | [Bb]uild[Ll]og.* 40 | 41 | # NUNIT 42 | *.VisualState.xml 43 | TestResult.xml 44 | 45 | # Build Results of an ATL Project 46 | [Dd]ebugPS/ 47 | [Rr]eleasePS/ 48 | dlldata.c 49 | 50 | # .NET Core 51 | project.lock.json 52 | project.fragment.lock.json 53 | artifacts/ 54 | **/Properties/launchSettings.json 55 | 56 | *_i.c 57 | *_p.c 58 | *_i.h 59 | *.ilk 60 | *.meta 61 | *.obj 62 | *.pch 63 | *.pdb 64 | *.pgc 65 | *.pgd 66 | *.rsp 67 | *.sbr 68 | *.tlb 69 | *.tli 70 | *.tlh 71 | *.tmp 72 | *.tmp_proj 73 | *.log 74 | *.vspscc 75 | *.vssscc 76 | .builds 77 | *.pidb 78 | *.svclog 79 | *.scc 80 | 81 | # Chutzpah Test files 82 | _Chutzpah* 83 | 84 | # Visual C++ cache files 85 | ipch/ 86 | *.aps 87 | *.ncb 88 | *.opendb 89 | *.opensdf 90 | *.sdf 91 | *.cachefile 92 | *.VC.db 93 | *.VC.VC.opendb 94 | 95 | # Visual Studio profiler 96 | *.psess 97 | *.vsp 98 | *.vspx 99 | *.sap 100 | 101 | # TFS 2012 Local Workspace 102 | $tf/ 103 | 104 | # Guidance Automation Toolkit 105 | *.gpState 106 | 107 | # ReSharper is a .NET coding add-in 108 | _ReSharper*/ 109 | *.[Rr]e[Ss]harper 110 | *.DotSettings.user 111 | 112 | # JustCode is a .NET coding add-in 113 | .JustCode 114 | 115 | # TeamCity is a build add-in 116 | _TeamCity* 117 | 118 | # DotCover is a Code Coverage Tool 119 | *.dotCover 120 | 121 | # Visual Studio code coverage results 122 | *.coverage 123 | *.coveragexml 124 | 125 | # NCrunch 126 | _NCrunch_* 127 | .*crunch*.local.xml 128 | nCrunchTemp_* 129 | 130 | # MightyMoose 131 | *.mm.* 132 | AutoTest.Net/ 133 | 134 | # Web workbench (sass) 135 | .sass-cache/ 136 | 137 | # Installshield output folder 138 | [Ee]xpress/ 139 | 140 | # DocProject is a documentation generator add-in 141 | DocProject/buildhelp/ 142 | DocProject/Help/*.HxT 143 | DocProject/Help/*.HxC 144 | DocProject/Help/*.hhc 145 | DocProject/Help/*.hhk 146 | DocProject/Help/*.hhp 147 | DocProject/Help/Html2 148 | DocProject/Help/html 149 | 150 | # Click-Once directory 151 | publish/ 152 | 153 | # Publish Web Output 154 | *.[Pp]ublish.xml 155 | *.azurePubxml 156 | # TODO: Comment the next line if you want to checkin your web deploy settings 157 | # but database connection strings (with potential passwords) will be unencrypted 158 | *.pubxml 159 | *.publishproj 160 | 161 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 162 | # checkin your Azure Web App publish settings, but sensitive information contained 163 | # in these scripts will be unencrypted 164 | PublishScripts/ 165 | 166 | # NuGet Packages 167 | *.nupkg 168 | # The packages folder can be ignored because of Package Restore 169 | **/packages/* 170 | # except build/, which is used as an MSBuild target. 171 | !**/packages/build/ 172 | # Uncomment if necessary however generally it will be regenerated when needed 173 | #!**/packages/repositories.config 174 | # NuGet v3's project.json files produces more ignorable files 175 | *.nuget.props 176 | *.nuget.targets 177 | 178 | # Microsoft Azure Build Output 179 | csx/ 180 | *.build.csdef 181 | 182 | # Microsoft Azure Emulator 183 | ecf/ 184 | rcf/ 185 | 186 | # Windows Store app package directories and files 187 | AppPackages/ 188 | BundleArtifacts/ 189 | Package.StoreAssociation.xml 190 | _pkginfo.txt 191 | 192 | # Visual Studio cache files 193 | # files ending in .cache can be ignored 194 | *.[Cc]ache 195 | # but keep track of directories ending in .cache 196 | !*.[Cc]ache/ 197 | 198 | # Others 199 | ClientBin/ 200 | ~$* 201 | *~ 202 | *.dbmdl 203 | *.dbproj.schemaview 204 | *.jfm 205 | *.pfx 206 | *.publishsettings 207 | orleans.codegen.cs 208 | 209 | # Since there are multiple workflows, uncomment next line to ignore bower_components 210 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 211 | #bower_components/ 212 | 213 | # RIA/Silverlight projects 214 | Generated_Code/ 215 | 216 | # Backup & report files from converting an old project file 217 | # to a newer Visual Studio version. Backup files are not needed, 218 | # because we have git ;-) 219 | _UpgradeReport_Files/ 220 | Backup*/ 221 | UpgradeLog*.XML 222 | UpgradeLog*.htm 223 | 224 | # SQL Server files 225 | *.mdf 226 | *.ldf 227 | 228 | # Business Intelligence projects 229 | *.rdl.data 230 | *.bim.layout 231 | *.bim_*.settings 232 | 233 | # Microsoft Fakes 234 | FakesAssemblies/ 235 | 236 | # GhostDoc plugin setting file 237 | *.GhostDoc.xml 238 | 239 | # Node.js Tools for Visual Studio 240 | .ntvs_analysis.dat 241 | node_modules/ 242 | 243 | # Typescript v1 declaration files 244 | typings/ 245 | 246 | # Visual Studio 6 build log 247 | *.plg 248 | 249 | # Visual Studio 6 workspace options file 250 | *.opt 251 | 252 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 253 | *.vbw 254 | 255 | # Visual Studio LightSwitch build output 256 | **/*.HTMLClient/GeneratedArtifacts 257 | **/*.DesktopClient/GeneratedArtifacts 258 | **/*.DesktopClient/ModelManifest.xml 259 | **/*.Server/GeneratedArtifacts 260 | **/*.Server/ModelManifest.xml 261 | _Pvt_Extensions 262 | 263 | # Paket dependency manager 264 | .paket/paket.exe 265 | paket-files/ 266 | 267 | # FAKE - F# Make 268 | .fake/ 269 | 270 | # JetBrains Rider 271 | .idea/ 272 | *.sln.iml 273 | 274 | # CodeRush 275 | .cr/ 276 | 277 | # Python Tools for Visual Studio (PTVS) 278 | __pycache__/ 279 | *.pyc 280 | 281 | # Cake - Uncomment if you are using it 282 | # tools/** 283 | # !tools/packages.config 284 | 285 | # End of https://www.gitignore.io/api/visualstudio 286 | 287 | # User-added 288 | test/docker/*/NuGet.Config 289 | .github_changelog_generator -------------------------------------------------------------------------------- /GitVersion.yml: -------------------------------------------------------------------------------- 1 | next-version: 3.1.0 2 | branches: 3 | main: 4 | increment: None 5 | release: 6 | increment: None 7 | feature: 8 | increment: None 9 | pull-request: 10 | increment: None 11 | hotfix: 12 | increment: None 13 | support: 14 | increment: None 15 | develop: 16 | increment: None -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 ThymineC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **dotnet-setversion** is a simple .NET Core CLI tool used to update the version information within .NET Core `*.csproj` files. 2 | 3 | It is based on [dotnet-gitversion](https://github.com/ah-/dotnet-gitversion), but is updated to work for the new `*.csproj` format instead of project.json, and relies on the version information being passed to it. 4 | 5 | [![NuGet](https://img.shields.io/nuget/v/dotnet-setversion.svg)](https://www.nuget.org/packages/dotnet-setversion) 6 | [![Build status](https://ci.appveyor.com/api/projects/status/5e4apspa6wg86t9n/branch/master?svg=true)](https://ci.appveyor.com/project/TAGC/dotnet-setversion/branch/master) 7 | 8 | ## Usage 9 | 10 | Install **dotnet-setversion** as a global tool using the dotnet CLI: 11 | 12 | ``` 13 | $ dotnet tool install -g dotnet-setversion 14 | ``` 15 | 16 | If the command completed successfully, you're able to invoke **dotnet-setversion** in any directory like this: 17 | 18 | ``` 19 | $ setversion 0.1.2-beta0001 20 | ``` 21 | 22 | You can also update the version information of a specific project file by invoking like this: 23 | 24 | ``` 25 | $ setversion 0.1.2-beta0001 MyProject.csproj 26 | ``` 27 | 28 | ### Recursive updates 29 | 30 | If you happen to have a rather big repo including several project files and you want to update them all at once, you can use the `--recursive` option. 31 | This will update any project file in and below the current working directory. 32 | 33 | ``` 34 | $ setversion -r 0.1.2-beta0001 35 | ``` 36 | 37 | ### Extracting the version from a file 38 | 39 | As well as passing the version directly, you can specify a file to extract the version number from. This is done by prefixing the version argument with an `@` symbol. For example, the following command will make the tool try to extract the version from a file in the working directory called "sem.ver". 40 | 41 | ``` 42 | $ setversion @sem.ver 43 | ``` 44 | 45 | The file should represent the version either as a simple string (i.e. in the same format you'd ordinarily provide directly to the tool, such as `0.1.2`) or in JSON format using a schema like this: 46 | 47 | ```json 48 | { 49 | "Version": { 50 | "Major": 0, 51 | "Minor": 1, 52 | "Patch": 2 53 | } 54 | } 55 | ``` 56 | 57 | Bear in mind that the JSON format does not support metadata extensions (e.g. `-beta0001`). 58 | 59 | ### Further notes 60 | 61 | For each example, replace '0.1.2-beta0001' with any valid version string or, when having [GitVersion](https://github.com/GitTools/GitVersion) installed, with `$(GitVersion -ShowVariable NuGetVersionV2)` to use your current version automatically. 62 | 63 | This (or something similar) can of course be done during a continuous integration build, which is the main intention behind developing this project. This tool depends on itself for its own version management during CI builds, so you can use it as a reference. 64 | 65 | ## Migrating from 1.* to 2.* 66 | 67 | **dotnet-setversion** used to be a [per-project tool](https://docs.microsoft.com/en-us/dotnet/core/tools/extensibility#per-project-based-extensibility), but has now been reworked as a [.NET Core Global Tool](https://docs.microsoft.com/en-us/dotnet/core/tools/global-tools). 68 | As a consequence of this, you have to remove the `` element referencing **dotnet-setversion** or you'll get an error when running `dotnet restore`. 69 | 70 | Depending on your build strategy, you have to install **setversion** once on your build agent (see [Usage](#usage)) or integrate the install command into your build script. 71 | 72 | Finally you have to change the way to invoke the program from `dotnet setversion` to `setversion`. 73 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | image: Visual Studio 2022 2 | branches: 3 | only: 4 | - master 5 | - develop 6 | - /release\/.+/ 7 | install: 8 | - choco install gitversion.portable -y 9 | - ps: dotnet tool install --global dotnet-setversion 10 | before_build: 11 | - nuget restore 12 | - ps: | 13 | if ($env:APPVEYOR_REPO_BRANCH -eq 'master') { 14 | $env:VERSION = (gitversion /showvariable MajorMinorPatch) 15 | } else { 16 | $env:VERSION = (gitversion /showvariable FullSemVer) 17 | } 18 | - ps: cp README.md src/dotnet-setversion/README.md 19 | build_script: 20 | - ps: dotnet restore 21 | - ps: cd src/dotnet-setversion; setversion $env:VERSION; dotnet pack -c Release -o release/; cd ../.. 22 | before_test: 23 | - ps: cd test/integration; 24 | test_script: 25 | - ps: dotnet test -c Release; 26 | after_test: 27 | - ps: cd ../.. 28 | artifacts: 29 | path: src/dotnet-setversion/release/*.nupkg 30 | name: NuGet packages 31 | deploy: 32 | provider: NuGet 33 | skip_symbols: false 34 | api_key: 35 | secure: KAu0YxpiSIMsKj+Rpy3rc1AGN/WYljKE2Mt8f72UbMzvaLPGllHUFw8UDZ9rwsUY 36 | artifact: NuGet packages 37 | on: 38 | branch: master -------------------------------------------------------------------------------- /dotnet-setversion.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26228.9 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{FE23C2A7-75C4-4071-B555-0AEB678A9770}" 7 | ProjectSection(SolutionItems) = preProject 8 | appveyor.yml = appveyor.yml 9 | docker-compose.yml = docker-compose.yml 10 | GitVersion.yml = GitVersion.yml 11 | EndProjectSection 12 | EndProject 13 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{3E276529-6591-44A4-9CB5-E913BCB5EBEE}" 14 | EndProject 15 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{2DC259B3-4ADB-4566-B424-2148BDF5B507}" 16 | EndProject 17 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "dotnet-setversion", "src\dotnet-setversion\dotnet-setversion.csproj", "{4CEC4F68-49E1-4B0A-B154-722B1C96E829}" 18 | EndProject 19 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "integration", "test\integration\integration.csproj", "{FEE152BC-1F28-4BAE-98F1-E838622FF6CF}" 20 | EndProject 21 | Global 22 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 23 | Debug|Any CPU = Debug|Any CPU 24 | Release|Any CPU = Release|Any CPU 25 | EndGlobalSection 26 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 27 | {4CEC4F68-49E1-4B0A-B154-722B1C96E829}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {4CEC4F68-49E1-4B0A-B154-722B1C96E829}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {4CEC4F68-49E1-4B0A-B154-722B1C96E829}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {4CEC4F68-49E1-4B0A-B154-722B1C96E829}.Release|Any CPU.Build.0 = Release|Any CPU 31 | {FEE152BC-1F28-4BAE-98F1-E838622FF6CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {FEE152BC-1F28-4BAE-98F1-E838622FF6CF}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {FEE152BC-1F28-4BAE-98F1-E838622FF6CF}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {FEE152BC-1F28-4BAE-98F1-E838622FF6CF}.Release|Any CPU.Build.0 = Release|Any CPU 35 | EndGlobalSection 36 | GlobalSection(SolutionProperties) = preSolution 37 | HideSolutionNode = FALSE 38 | EndGlobalSection 39 | GlobalSection(NestedProjects) = preSolution 40 | {4CEC4F68-49E1-4B0A-B154-722B1C96E829} = {3E276529-6591-44A4-9CB5-E913BCB5EBEE} 41 | {FEE152BC-1F28-4BAE-98F1-E838622FF6CF} = {2DC259B3-4ADB-4566-B424-2148BDF5B507} 42 | EndGlobalSection 43 | GlobalSection(ExtensibilityGlobals) = postSolution 44 | SolutionGuid = {0975BA37-A42F-4032-8A10-F7F3E54ACF75} 45 | EndGlobalSection 46 | EndGlobal 47 | -------------------------------------------------------------------------------- /src/dotnet-setversion/Options.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CommandLine; 3 | using CommandLine.Text; 4 | 5 | namespace dotnet_setversion 6 | { 7 | public class Options 8 | { 9 | [Option('r', "recursive", Default = false, HelpText = 10 | "Recursively search the current directory for csproj files and apply the given version to all files found. " + 11 | "Mutually exclusive to the csprojFile argument.")] 12 | public bool Recursive { get; set; } 13 | 14 | /* 15 | { 16 | "Version": { 17 | "Major": 2, 18 | "Minor": 2, 19 | "Patch": 0 20 | } 21 | } */ 22 | [Value(0, MetaName = "version", HelpText = "The version to apply to the given csproj file(s). A filename " + 23 | "can also be referenced by prepending an @filename to read the version number from the file." + 24 | "The file is expected to contain either a simple version or a JSON value in the following format:" + 25 | "{Version: {Major:Value, Minor:Value, Patch:Value}}", 26 | Required = true)] 27 | public string Version { get; set; } 28 | 29 | [Value(1, MetaName = "csprojFile", Required = false, HelpText = 30 | "Path to a csproj file to apply the given version. Mutually exclusive to the --recursive option.")] 31 | public string CsprojFile { get; set; } 32 | 33 | [Option('p', "prefix", Default = false, HelpText = 34 | "Set version using the VersionPrefix element for csproj files.")] 35 | public bool VersionPrefix { get; set; } 36 | 37 | [Usage(ApplicationAlias = "setversion")] 38 | public static IEnumerable Examples 39 | { 40 | get 41 | { 42 | yield return new Example("Directory with a single csproj file", new Options {Version = "1.2.3"}); 43 | yield return new Example("Explicitly specifying a csproj file", 44 | new Options {Version = "1.2.3", CsprojFile = "MyProject.csproj"}); 45 | yield return new Example("Large repo with multiple csproj files in nested directories", 46 | new UnParserSettings {PreferShortName = true}, new Options {Version = "1.2.3", Recursive = true}); 47 | yield return new Example("Pulling the version from a file", new Options {Version = "@sem.ver"}); 48 | } 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /src/dotnet-setversion/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Text.Json; 5 | using System.Xml.Linq; 6 | using CommandLine; 7 | 8 | namespace dotnet_setversion 9 | { 10 | internal static class Program 11 | { 12 | internal const int ExitSuccess = 0; 13 | internal const int ExitFailure = 1; 14 | internal static bool UseVersionPrefix = false; 15 | 16 | internal static int Main(params string[] args) 17 | { 18 | return Parser.Default.ParseArguments(args) 19 | .MapResult(Run, errs => int.MinValue); 20 | } 21 | 22 | private static int Run(Options options) 23 | { 24 | if (options.Recursive && options.CsprojFile != null) 25 | { 26 | Console.WriteLine("The --recursive option and csprojFile argument are mutually exclusive."); 27 | return ExitFailure; 28 | } 29 | 30 | UseVersionPrefix = options.VersionPrefix; 31 | 32 | return options.Recursive ? RunRecursive(options.Version) : Run(options.Version, options.CsprojFile); 33 | } 34 | 35 | private static int Run(string version, string csprojFile) 36 | { 37 | if (csprojFile == null) 38 | { 39 | var csprojFiles = GetCsprojFiles(recursive: false); 40 | if (!CheckCsprojFiles(csprojFiles, allowMultiple: false)) 41 | return ExitFailure; 42 | 43 | csprojFile = csprojFiles[0]; 44 | } 45 | 46 | if (!File.Exists(csprojFile)) 47 | { 48 | Console.WriteLine($"Project file '{csprojFile}' does not exist."); 49 | return ExitFailure; 50 | } 51 | 52 | if (ShouldExtractVersionFromFile(version, out var versionFile) && 53 | !TryExtractVersionFromFile(versionFile, out version)) 54 | { 55 | return ExitFailure; 56 | } 57 | 58 | SetVersion(version, csprojFile); 59 | PrintSuccessString(version, csprojFile); 60 | return ExitSuccess; 61 | } 62 | 63 | private static int RunRecursive(string version) 64 | { 65 | var csprojFiles = GetCsprojFiles(recursive: true); 66 | if (!CheckCsprojFiles(csprojFiles, allowMultiple: true)) 67 | return ExitFailure; 68 | 69 | if (ShouldExtractVersionFromFile(version, out var versionFile) && 70 | !TryExtractVersionFromFile(versionFile, out version)) 71 | { 72 | return ExitFailure; 73 | } 74 | 75 | foreach (var csprojFile in csprojFiles) 76 | { 77 | SetVersion(version, csprojFile); 78 | } 79 | 80 | PrintSuccessString(version, csprojFiles); 81 | return ExitSuccess; 82 | } 83 | 84 | private static string[] GetCsprojFiles(bool recursive) => Directory 85 | .EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*.csproj", 86 | recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).ToArray(); 87 | 88 | private static bool CheckCsprojFiles(string[] csprojFiles, bool allowMultiple) 89 | { 90 | if (csprojFiles.Length == 0) 91 | { 92 | Console.WriteLine("Specify a project file. The current working directory does not contain a project file."); 93 | return false; 94 | } 95 | 96 | if (!allowMultiple && csprojFiles.Length > 1) 97 | { 98 | Console.WriteLine("Specify which project file to use because this folder contains more than one project file."); 99 | return false; 100 | } 101 | 102 | return true; 103 | } 104 | 105 | private static bool ShouldExtractVersionFromFile(string version, out string versionFile) 106 | { 107 | if (version.StartsWith("@")) 108 | { 109 | versionFile = version.Substring(1); 110 | return true; 111 | } 112 | 113 | versionFile = null; 114 | return false; 115 | } 116 | 117 | private static bool TryExtractVersionFromFile(string filename, out string version) 118 | { 119 | if (!File.Exists(filename)) 120 | { 121 | Console.WriteLine($"The specified file to extract the version from was not found: {filename}"); 122 | version = null; 123 | return false; 124 | } 125 | 126 | var versionFileText = File.ReadAllText(filename).Trim(); 127 | 128 | try 129 | { 130 | var versionModel = JsonSerializer.Deserialize(versionFileText); 131 | version = versionModel.ToString(); 132 | } 133 | catch (JsonException) 134 | { 135 | // Simple Version Number 136 | version = versionFileText; 137 | } 138 | 139 | return true; 140 | } 141 | 142 | private static void SetVersion(string version, string csprojFile) 143 | { 144 | if (version == null) throw new ArgumentNullException(nameof(version)); 145 | if (csprojFile == null) throw new ArgumentNullException(nameof(csprojFile)); 146 | 147 | var versionElement = UseVersionPrefix ? "VersionPrefix" : "Version"; 148 | 149 | var document = XDocument.Load(csprojFile); 150 | var projectNode = document.GetOrCreateElement("Project"); 151 | var versionNode = projectNode 152 | .Elements("PropertyGroup") 153 | .SelectMany(it => it.Elements(versionElement)) 154 | .SingleOrDefault() ?? projectNode 155 | .GetOrCreateElement("PropertyGroup") 156 | .GetOrCreateElement(versionElement); 157 | versionNode.SetValue(version); 158 | File.WriteAllText(csprojFile, document.ToString()); 159 | } 160 | 161 | private static void PrintSuccessString(string version, string file) 162 | { 163 | Console.WriteLine($"Set version to {version} in {file}"); 164 | } 165 | 166 | private static void PrintSuccessString(string version, params string[] files) 167 | { 168 | Console.WriteLine($"Set version to {version} in:"); 169 | 170 | foreach (var file in files) 171 | { 172 | Console.WriteLine($"\t> {file}"); 173 | } 174 | } 175 | } 176 | 177 | public static class Extensions 178 | { 179 | /// 180 | /// Source: http://stackoverflow.com/a/14892813/1636276 181 | /// 182 | public static XElement GetOrCreateElement(this XContainer container, string name) 183 | { 184 | var element = container.Element(name); 185 | if (element != null) return element; 186 | element = new XElement(name); 187 | container.Add(element); 188 | return element; 189 | } 190 | } 191 | } -------------------------------------------------------------------------------- /src/dotnet-setversion/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | [assembly:InternalsVisibleTo("integration")] -------------------------------------------------------------------------------- /src/dotnet-setversion/VersionModel.cs: -------------------------------------------------------------------------------- 1 | namespace dotnet_setversion 2 | { 3 | public class VersionModel 4 | { 5 | public VersionModelDetail Version { get; set; } 6 | 7 | public override string ToString() 8 | { 9 | if (Version != null) 10 | { 11 | return $"{Version.Major}.{Version.Minor}.{Version.Patch}"; 12 | } 13 | 14 | return string.Empty; 15 | } 16 | } 17 | 18 | public class VersionModelDetail 19 | { 20 | public int Major { get; set; } 21 | public int Minor { get; set; } 22 | public int Patch { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/dotnet-setversion/dotnet-setversion.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | A CLI tool to set/update the Version property in csproj files 4 | Exe 5 | net6.0;net7.0;net8.0;net9.0 6 | true 7 | true 8 | setversion 9 | ThymineC 10 | Copyright 2018 ThymineC 11 | ThymineC; Skulblaka 12 | https://opensource.org/licenses/MIT 13 | https://github.com/TAGC/dotnet-setversion 14 | git@github.com:TAGC/dotnet-setversion.git 15 | README.md 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /test/integration/SetVersion.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using dotnet_setversion; 3 | using Xunit; 4 | 5 | namespace integration 6 | { 7 | public class SetVersion 8 | { 9 | private readonly TestHelper _testHelper = new TestHelper(); 10 | 11 | [Fact] 12 | public void ApplyingVersion_WithoutSpecifyingCsprojFile() 13 | { 14 | const string version = "1.2.3"; 15 | var workingDirectory = _testHelper.ChangeToRandomDirectory(); 16 | var csprojFile = Path.Combine(workingDirectory, "Project.csproj"); 17 | _testHelper.CopyExampleFile(csprojFile); 18 | 19 | var exitCode = Program.Main(version); 20 | 21 | Assert.Equal(0, exitCode); 22 | _testHelper.CheckCsprojFileForVersionElement(version, csprojFile); 23 | } 24 | 25 | [Fact] 26 | public void DirectoryWithoutCsproj_ReturnsNonZero() 27 | { 28 | _testHelper.ChangeToRandomDirectory(); 29 | 30 | var exitCode = Program.Main("1.2.3"); 31 | 32 | Assert.NotEqual(0, exitCode); 33 | } 34 | 35 | [Fact] 36 | public void DirectoryWithMultipleCsproj_ReturnsNonZero_WhenNoFileIsSpecified() 37 | { 38 | _testHelper.ChangeToRandomDirectory(); 39 | _testHelper.CopyExampleFile("Project A.csproj"); 40 | _testHelper.CopyExampleFile("Project B.csproj"); 41 | 42 | var exitCode = Program.Main("1.2.3"); 43 | 44 | Assert.NotEqual(0, exitCode); 45 | } 46 | 47 | [Fact] 48 | public void ApplyingVersion_WithSpecifyingExistingFile() 49 | { 50 | var csprojFile = Path.GetTempFileName(); 51 | _testHelper.CopyExampleFile(csprojFile, true); 52 | const string version = "1.2.3"; 53 | 54 | var exitCode = Program.Main(version, csprojFile); 55 | 56 | Assert.Equal(0, exitCode); 57 | _testHelper.CheckCsprojFileForVersionElement(version, csprojFile); 58 | } 59 | 60 | [Fact] 61 | public void ApplyingVersion_WithVersionPrefix() 62 | { 63 | var csprojFile = Path.GetTempFileName(); 64 | _testHelper.CopyExampleFile(csprojFile, true); 65 | const string version = "1.2.3-123"; 66 | 67 | var exitCode = Program.Main(version, csprojFile, "-p"); 68 | 69 | Assert.Equal(0, exitCode); 70 | _testHelper.CheckCsprojFileForVersionPrefixElement(version, csprojFile); 71 | } 72 | 73 | [Fact] 74 | public void ApplyingVersions_WithMultipleProjectFilesInCurrentDirectory_WhenSpecifyingProjectFile() 75 | { 76 | const string csprojFileA = "Project A.csproj"; 77 | const string csprojFileB = "Project B.csproj"; 78 | const string version = "1.2.3"; 79 | _testHelper.ChangeToRandomDirectory(); 80 | _testHelper.CopyExampleFile(csprojFileA); 81 | _testHelper.CopyExampleFile(csprojFileB); 82 | 83 | var exitCode = Program.Main(version, csprojFileA); 84 | 85 | Assert.Equal(0, exitCode); 86 | _testHelper.CheckCsprojFileForVersionElement(version, csprojFileA); 87 | // check the other file remains untouched. 88 | Assert.Equal(_testHelper.ExampleCsprojFile, File.ReadAllText(csprojFileB)); 89 | } 90 | 91 | [Fact] 92 | public void DirectoryContainingNoCsproj_ReturnsNonZero_WhenRecursive() 93 | { 94 | _testHelper.ChangeToRandomDirectory(); 95 | 96 | var exitCode = Program.Main("-r", "1.2.3"); 97 | 98 | Assert.NotEqual(0, exitCode); 99 | } 100 | 101 | [Fact] 102 | public void ApplyingVersionToAllFiles_WhenRecursive() 103 | { 104 | const string projectA = "Project A.csproj"; 105 | const string projectB = "Project B.csproj"; 106 | const string moduleA = "Module A"; 107 | const string moduleB = "Module B"; 108 | const string version = "1.2.3"; 109 | var moduleFileA = Path.Combine(moduleA, moduleA + ".csproj"); 110 | var moduleFileB = Path.Combine(moduleB, moduleB + ".csproj"); 111 | _testHelper.ChangeToRandomDirectory(); 112 | _testHelper.CopyExampleFile(projectA); 113 | _testHelper.CopyExampleFile(projectB); 114 | Directory.CreateDirectory(moduleA); 115 | Directory.CreateDirectory(moduleB); 116 | _testHelper.CopyExampleFile(moduleFileA); 117 | _testHelper.CopyExampleFile(moduleFileB); 118 | 119 | var exitCode = Program.Main("-r", version); 120 | 121 | Assert.Equal(0, exitCode); 122 | _testHelper.CheckCsprojFileForVersionElement(version, projectA); 123 | _testHelper.CheckCsprojFileForVersionElement(version, projectB); 124 | _testHelper.CheckCsprojFileForVersionElement(version, moduleFileA); 125 | _testHelper.CheckCsprojFileForVersionElement(version, moduleFileB); 126 | } 127 | 128 | [Fact] 129 | public void ApplyingVersionPrefixToAllFiles_WhenRecursive() 130 | { 131 | const string projectA = "Project A.csproj"; 132 | const string projectB = "Project B.csproj"; 133 | const string moduleA = "Module A"; 134 | const string moduleB = "Module B"; 135 | const string version = "1.2.3-123"; 136 | var moduleFileA = Path.Combine(moduleA, moduleA + ".csproj"); 137 | var moduleFileB = Path.Combine(moduleB, moduleB + ".csproj"); 138 | _testHelper.ChangeToRandomDirectory(); 139 | _testHelper.CopyExampleFile(projectA); 140 | _testHelper.CopyExampleFile(projectB); 141 | Directory.CreateDirectory(moduleA); 142 | Directory.CreateDirectory(moduleB); 143 | _testHelper.CopyExampleFile(moduleFileA); 144 | _testHelper.CopyExampleFile(moduleFileB); 145 | 146 | var exitCode = Program.Main("-r", "-p", version); 147 | 148 | Assert.Equal(0, exitCode); 149 | _testHelper.CheckCsprojFileForVersionPrefixElement(version, projectA); 150 | _testHelper.CheckCsprojFileForVersionPrefixElement(version, projectB); 151 | _testHelper.CheckCsprojFileForVersionPrefixElement(version, moduleFileA); 152 | _testHelper.CheckCsprojFileForVersionPrefixElement(version, moduleFileB); 153 | } 154 | 155 | [Fact] 156 | public void SetVersion_ReturnsNonZero_WhenRecursiveAndSpecifyingProjectFile() 157 | { 158 | var exitCode = Program.Main("-r", "1.2.3", "void.csproj"); 159 | 160 | Assert.NotEqual(0, exitCode); 161 | } 162 | 163 | [Fact] 164 | public void ApplyingVersion_WithoutSpecifyingCsprojFileWithSimpleVersionFromFile() 165 | { 166 | const string version = "1.2.3"; 167 | const string versionFilename = "@sem.ver"; 168 | var workingDirectory = _testHelper.ChangeToRandomDirectory(); 169 | using (var semFileWriter = File.CreateText(Path.Combine(workingDirectory, "sem.ver"))) 170 | { 171 | semFileWriter.Write(version); 172 | } 173 | var csprojFile = Path.Combine(workingDirectory, "Project.csproj"); 174 | _testHelper.CopyExampleFile(csprojFile); 175 | 176 | var exitCode = Program.Main(versionFilename); 177 | 178 | Assert.Equal(0, exitCode); 179 | _testHelper.CheckCsprojFileForVersionElement(version, csprojFile); 180 | } 181 | 182 | [Fact] 183 | public void ApplyingVersion_WithSimpleVersionFromFile_WithTrailingNewLine() 184 | { 185 | const string version = "1.2.3\n"; 186 | const string versionFilename = "@sem.ver"; 187 | var workingDirectory = _testHelper.ChangeToRandomDirectory(); 188 | using (var semFileWriter = File.CreateText(Path.Combine(workingDirectory, "sem.ver"))) 189 | { 190 | semFileWriter.Write(version); 191 | } 192 | var csprojFile = Path.Combine(workingDirectory, "Project.csproj"); 193 | _testHelper.CopyExampleFile(csprojFile); 194 | 195 | var exitCode = Program.Main(versionFilename); 196 | 197 | Assert.Equal(0, exitCode); 198 | _testHelper.CheckCsprojFileForVersionElement("1.2.3", csprojFile); 199 | } 200 | 201 | [Fact] 202 | public void ApplyingVersion_WithoutSpecifyingCsprojFileWithVersionFromJsonFile() 203 | { 204 | const string version = "1.2.3"; 205 | const string versionFilename = "@sem.ver"; 206 | var workingDirectory = _testHelper.ChangeToRandomDirectory(); 207 | var csprojFile = Path.Combine(workingDirectory, "Project.csproj"); 208 | _testHelper.CopyExampleFile(csprojFile); 209 | _testHelper.CopyExampleSemVerFile("sem.ver"); 210 | var exitCode = Program.Main(versionFilename); 211 | 212 | Assert.Equal(0, exitCode); 213 | _testHelper.CheckCsprojFileForVersionElement(version, csprojFile); 214 | } 215 | 216 | [Fact] 217 | public void SetVersion_ReturnsNonZero_WhenExtractingVersionFromNonExistentFile() 218 | { 219 | var workingDirectory = _testHelper.ChangeToRandomDirectory(); 220 | var csprojFile = Path.Combine(workingDirectory, "Project.csproj"); 221 | _testHelper.CopyExampleFile(csprojFile); 222 | 223 | var exitCode = Program.Main("@non_existent_file"); 224 | 225 | Assert.NotEqual(0, exitCode); 226 | } 227 | } 228 | } -------------------------------------------------------------------------------- /test/integration/TestHelper.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using Xunit; 3 | 4 | namespace integration 5 | { 6 | public class TestHelper 7 | { 8 | public string ExampleCsprojFile { get; } = @" 9 | 10 | An example csproj file. 11 | net9.0 12 | 13 | "; 14 | 15 | public string ExampleSemVerFile { get; } = @"{ 16 | ""Version"": { 17 | ""Major"": 1, 18 | ""Minor"": 2, 19 | ""Patch"": 3 20 | } 21 | }"; 22 | 23 | public void CopyExampleFile(string path, bool overwrite = false) 24 | { 25 | File.WriteAllText(path, ExampleCsprojFile); 26 | } 27 | 28 | public void CopyExampleSemVerFile(string path, bool overwrite = false) 29 | { 30 | File.WriteAllText(path, ExampleSemVerFile); 31 | } 32 | 33 | public void CheckCsprojFileForVersionElement(string version, params string[] files) 34 | { 35 | foreach (var file in files) 36 | { 37 | var content = File.ReadAllText(file); 38 | Assert.Contains($"{version}", content); 39 | } 40 | } 41 | 42 | public void CheckCsprojFileForVersionPrefixElement(string version, params string[] files) 43 | { 44 | foreach (var file in files) 45 | { 46 | var content = File.ReadAllText(file); 47 | Assert.Contains($"{version}", content); 48 | } 49 | } 50 | 51 | public string GetRandomDirectory() 52 | { 53 | var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); 54 | Directory.CreateDirectory(path); 55 | return path; 56 | } 57 | 58 | public string ChangeToRandomDirectory() 59 | { 60 | var path = GetRandomDirectory(); 61 | Directory.SetCurrentDirectory(path); 62 | return path; 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /test/integration/integration.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0;net7.0;net8.0;net9.0 5 | false 6 | integration 7 | integration 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | all 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | --------------------------------------------------------------------------------