2021-09-03
|~2 min read
|377 words
I’m working on a project where it’s convenient to publish a new package of the project on every build. In order to facilitate the workflow, my first step was to create a powershell script that incremented the patch on each build:
$buildNumber = %build.number%
$json = (Get-Content ./package.json | ConvertFrom-Json)
$currentValue = $json.version
$patch = $currentValue.LastIndexOf(".")
$newValue = $currentValue.Substring(0,$patch) + "." + $buildNumber
Write-Host "Previous Version: " + $currentValue
Write-Host "New Version: " $newValue
$json.version = $newValue
$json | ConvertTo-Json | Set-Content "./package.json"
The quick review of what this Powershell script is doing:
version
from the package.json
in the project,patch
version to the buildNumber
version
key on the json
json
back to package.json
.This works pretty well. However, I wanted to go one step further and make a minor
version bump on every merge to main
. This would protect me from the major concern exposed by my current approach - consumers of the library had no way of knowing whether the version they were using was safe or not. By auto-incrementing minor
on each merge, I could communicate that the change was actually accepted and merged rather than just a temporary branch as part of the development process.
In order to do this, I needed to learn a few things:
Substring
API takes two arguments: the start and the length of the string. Notably this is not the start and end index, which was my initial supposition.[int]
prefix.$branch = %branch.name%
$buildNumber = %build.number%
$json = (Get-Content ./package.json | ConvertFrom-Json)
$currentValue = $json.version
$length = $currentValue.length
$minorDot = $currentValue.IndexOf(".")
$patchDot = $currentValue.LastIndexOf(".")
$currentMajor = $currentValue.Substring(0, $minorDot)
$currentMinor = [int]$currentValue.Substring($minorDot +1, $patchDot - $minorDot -1)
$currentPatch = $currentValue.Substring($patchDot +1, $length - $patchDot -1)
$newMinor = If ($branch -like "main") {$currentMinor +1} Else {$currentMinor}
$newValue = $currentMajor + "." + $newMinor + "." + $buildNumber
Write-Host "Previous Version: " + $currentValue
Write-Host "New Version: " $newValue
$json.version = $newValue
$json | ConvertTo-Json | Set-Content "./package.json"
And like that! I now have a dynamic solution that will update my version based on the branch! I love learning new things!
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!