Skip to content

Commit

Permalink
Add task Create_Changelog_Branch (#381)
Browse files Browse the repository at this point in the history
  • Loading branch information
johlju committed May 29, 2022
1 parent 6e032d1 commit 2bfc9c0
Show file tree
Hide file tree
Showing 6 changed files with 443 additions and 6 deletions.
246 changes: 246 additions & 0 deletions .build/tasks/Create_Changelog_Branch.build.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
<#
.SYNOPSIS
This build task updates the changelog with the release and creates a branch
to merge.
.PARAMETER ProjectPath
The root path to the project. Defaults to $BuildRoot.
.PARAMETER OutputDirectory
The base directory of all output. Defaults to folder 'output' relative to
the $BuildRoot.
.PARAMETER BuiltModuleSubdirectory
The parent path of the module to be built.
.PARAMETER VersionedOutputDirectory
If the module should be built using a version folder, e.g. ./MyModule/1.0.0.
Defaults to $true.
.PARAMETER ProjectName
The project name.
.PARAMETER SourcePath
The path to the source folder.
.PARAMETER ChangelogPath
The path to and the name of the changelog file. Defaults to 'CHANGELOG.md'.
.PARAMETER GitConfigUserEmail
The user email to use when committing the changes.
.PARAMETER GitConfigUserName
The user name to use when committing the changes.
.PARAMETER ChangelogFilesToAdd
One or more files to the commit before pushing the changes. Defaults to
'CHANGELOG.md'.
.PARAMETER ChangelogUpdateChangelogOnPrerelease
If the changelog should be updated on pre-releases. Defaults to
$false.
.PARAMETER MainGitBranch
The name of the default branch. Defaults to 'main'. It is used to compare
and target the branch against.
.PARAMETER BasicAuthPAT
The personal access token to use to access the Azure DevOps Git repository.
If left out the task assumes the authentication works without an personal
access token, e.g Windows integrated security.
.PARAMETER BuildInfo
The build info object from ModuleBuilder. Defaults to an empty hashtable.
.NOTES
This is a build task that is primarily meant to be run by Invoke-Build but
wrapped by the Sampler project's build.ps1 (https://github.com/gaelcolas/Sampler).
#>
param
(
[Parameter()]
[System.String]
$ProjectPath = (property ProjectPath $BuildRoot),

[Parameter()]
[System.String]
$OutputDirectory = (property OutputDirectory (Join-Path $BuildRoot 'output')),

[Parameter()]
[System.String]
$BuiltModuleSubdirectory = (property BuiltModuleSubdirectory ''),

[Parameter()]
[System.Management.Automation.SwitchParameter]
$VersionedOutputDirectory = (property VersionedOutputDirectory $true),

[Parameter()]
[System.String]
$ProjectName = (property ProjectName ''),

[Parameter()]
[System.String]
$SourcePath = (property SourcePath ''),

[Parameter()]
$ChangelogPath = (property ChangelogPath 'CHANGELOG.md'),

[Parameter()]
[string]
$GitConfigUserEmail = (property GitConfigUserEmail ''),

[Parameter()]
[string]
$GitConfigUserName = (property GitConfigUserName ''),

[Parameter()]
$ChangelogFilesToAdd = (property ChangelogFilesToAdd @('CHANGELOG.md')),

[Parameter()]
$ChangelogUpdateChangelogOnPrerelease = (property ChangelogUpdateChangelogOnPrerelease $false),

[Parameter()]
$MainGitBranch = (property MainGitBranch 'main'),

[Parameter()]
$BasicAuthPAT = (property BasicAuthPAT ''),

[Parameter()]
$BuildInfo = (property BuildInfo @{ })
)

# Synopsis: Creates a branch to update the changelog with the released version
task Create_Changelog_Branch {
. Set-SamplerTaskVariable

$ChangelogPath = Get-SamplerAbsolutePath -Path $ChangelogPath -RelativeTo $ProjectPath
"`Changelog Path = '$ChangelogPath'"

foreach ($changelogConfigKey in @('UpdateChangelogOnPrerelease', 'FilesToAdd'))
{
$changelogConfigVariableName = 'Changelog{0}' -f $changelogConfigKey

if (-not (Get-Variable -Name $changelogConfigVariableName -ValueOnly -ErrorAction 'SilentlyContinue'))
{
# Variable is not set in context, use $BuildInfo.ChangelogConfig.<varName>
$configurationValue = $BuildInfo.ChangelogConfig.($changelogConfigKey)

Set-Variable -Name $changelogConfigVariableName -Value $configurationValue

Write-Build DarkGray "`t...Set property $changelogConfigVariableName to the value $configurationValue."
}
}

foreach ($gitConfigKey in @('UserName', 'UserEmail'))
{
$gitConfigVariableName = 'GitConfig{0}' -f $gitConfigKey

if (-not (Get-Variable -Name $gitConfigVariableName -ValueOnly -ErrorAction 'SilentlyContinue'))
{
# Variable is not set in context, use $BuildInfo.ChangelogConfig.<varName>
$configurationValue = $BuildInfo.GitConfig.($gitConfigKey)

Set-Variable -Name $gitConfigVariableName -Value $configurationValue

Write-Build DarkGray "`t...Set property $gitConfigVariableName to the value $configurationValue."
}
}

Write-Build DarkGray "`tSetting git configuration."

Sampler\Invoke-SamplerGit -Argument @('config', 'user.name', $GitConfigUserName)
Sampler\Invoke-SamplerGit -Argument @('config', 'user.email', $GitConfigUserEmail)
Sampler\Invoke-SamplerGit -Argument @('config', 'pull.rebase', 'true')

Write-Build DarkGray ("`tPulling latest commits and tags from branch '{0}'." -f $MainGitBranch)

$pullArguments = @()

if ($BasicAuthPAT)
{
Write-Build DarkGray "`t`tUsing personal access token to pull commits and tags."

$patBase64 = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(('{0}:{1}' -f 'PAT', $BasicAuthPAT)))

$pullArguments += @('-c', ('http.extraheader="AUTHORIZATION: basic {0}"' -f $patBase64))
}

# Track this branch on the remote 'origin
$pullArguments += @('-c', 'http.sslbackend="schannel"', 'pull', 'origin', $MainGitBranch, '--tag')

Sampler\Invoke-SamplerGit -Argument $pullArguments

# Make empty line in output
""

Write-Build DarkGray ("`tGetting HEAD commit for the default branch '{0}." -f $MainGitBranch)

$defaultBranchHeadCommit = Sampler\Invoke-SamplerGit -Argument @('rev-parse', "origin/$MainGitBranch")

Write-Build DarkGray ("`tGet tags at commit '{0}'." -f $defaultBranchHeadCommit)

$tagsAtCommit = Sampler\Invoke-SamplerGit -Argument @('tag', '-l', '--points-at', $defaultBranchHeadCommit)

Write-Build DarkGray ("`t`tFound tags: {0}" -f ($tagsAtCommit -join ' | '))

# Only Update changelog if last commit is a full release
if ($ChangelogUpdateChangelogOnPrerelease)
{
$tagVersion = [System.String] ($tagsAtCommit | Select-Object -First 1)

Write-Build Green "Updating Changelog for PRE-Release $tagVersion."
}
else
{
$tagVersion = [System.String] ($tagsAtCommit.Where{ $_ -notMatch 'v.*\-' })

if ($tagVersion)
{
Write-Build Green "Updating the Changelog for release $tagVersion."
}
else
{
Write-Build Yellow ("No release tag found to update the changelog from the available tags: {0}" -f ($tagsAtCommit -join ' | '))
return
}
}

# Make empty line in output
""

Write-Build DarkGray ('About to create the branch for module version ''{0}''.' -f $ModuleVersion)

$branchName = "updateChangelogAfter$tagVersion"

Write-Build DarkGray "`tCreating branch $branchName."

Sampler\Invoke-SamplerGit -Argument @('checkout', '-B', $branchName)

Write-Build DarkGray "`tUpdating Changelog file."

Update-Changelog -ReleaseVersion ($tagVersion -replace '^v') -LinkMode 'None' -Path $ChangelogPath -ErrorAction 'SilentlyContinue'

Sampler\Invoke-SamplerGit -Argument @('add', $ChangelogFilesToAdd)

Sampler\Invoke-SamplerGit -Argument @('commit', '-m', "Updating Changelog since $tagVersion +semver:skip")

Write-Build DarkGray ("`tPushing commit on branch '{0}' to the repository." -f $branchName)

$pushArguments = @()

if ($BasicAuthPAT)
{
Write-Build DarkGray "`t`tUsing personal access token to push the tag."

$patBase64 = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(('{0}:{1}' -f 'PAT', $BasicAuthPAT)))

$pushArguments += @('-c', ('http.extraheader="AUTHORIZATION: basic {0}"' -f $patBase64))
}

# Track this branch on the remote 'origin
$pushArguments += @('-c', 'http.sslbackend="schannel"', 'push', '-u', 'origin', $BranchName)

Sampler\Invoke-SamplerGit -Argument $pushArguments

Write-Build Green ('Created and pushed the changelog branch ''{0}''.' -f $BranchName)
}
8 changes: 4 additions & 4 deletions .build/tasks/Create_Release_Git_Tag.build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
.PARAMETER MainGitBranch
The name of the default branch. Defaults to 'main'.
.PARAMETER RepositoryPAT
.PARAMETER BasicAuthPAT
The personal access token used for accessing hte Git repository.
.PARAMETER BuildInfo
Expand Down Expand Up @@ -80,7 +80,7 @@ param
$MainGitBranch = (property MainGitBranch 'main'),

[Parameter()]
$RepositoryPAT = (property RepositoryPAT ''),
$BasicAuthPAT = (property BasicAuthPAT ''),

[Parameter()]
[string]
Expand Down Expand Up @@ -159,11 +159,11 @@ task Create_Release_Git_Tag {

$pushArguments = @()

if ($RepositoryPAT)
if ($BasicAuthPAT)
{
Write-Build DarkGray "`t`tUsing personal access token to push the tag."

$patBase64 = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(('{0}:{1}' -f 'PAT', $RepositoryPAT)))
$patBase64 = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(('{0}:{1}' -f 'PAT', $BasicAuthPAT)))

$pushArguments += @('-c', ('http.extraheader="AUTHORIZATION: basic {0}"' -f $patBase64))
}
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Tests now run in Pester 5.
- Added task `Create_Release_Git_Tag` to create a Git tag for a preview release.
Fixes [#351](https://github.com/gaelcolas/Sampler/issues/351)
- Added task `Create_Release_Branch` to push a branch containing the updated
change log after release. Fixes [#351](https://github.com/gaelcolas/Sampler/issues/351)

### Changed

Expand Down
82 changes: 82 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1451,6 +1451,88 @@ the same name as the module.

## Tasks

### `Create_Changelog_Branch`

This build task creates pushes a branch with the changelog updated with
the current release version.

This is an example of how to use the task in the _azure-pipelines.yml_ file:

```yaml
- task: PowerShell@2
name: sendChangelogPR
displayName: 'Send Changelog PR'
inputs:
filePath: './build.ps1'
arguments: '-tasks Create_Changelog_Branch'
pwsh: true
env:
MainGitBranch: 'main'
BasicAuthPAT: $(BASICAUTHPAT)
```
This can be use in conjunction with the `Create_Release_Git_Tag` task
that creates the release tag.

```yaml
publish:
- Create_Release_Git_Tag
- Create_Changelog_Branch
```

#### Task parameters

Some task parameters are vital for the resource to work. See comment based
help for the description for each available parameter. Below is the most
important.

#### Task configuration

The build configuration (_build.yaml_) can be used to control the behavior
of the build task.

```yaml
####################################################
# Changelog Configuration #
####################################################
ChangelogConfig:
FilesToAdd:
- 'CHANGELOG.md'
UpdateChangelogOnPrerelease: false
####################################################
# Git Configuration #
####################################################
GitConfig:
UserName: bot
UserEmail: bot@company.local
```

#### Section ChangelogConfig

##### Property FilesToAdd

This specifies one or more files to add to the commit when creating the
PR branch. If left out it will default to the one file _CHANGELOG.md_.

##### Property UpdateChangelogOnPrerelease

- `true`: Always create a changelog PR, even on preview releases.
- `false`: Only create a changelog PR for full releases. Default.

#### Section GitConfig

This configures git. user name and e-mail address of the user before task pushes the
tag.

##### Property UserName

User name of the user that should push the tag.

##### Property UserEmail

E-mail address of the user that should push the tag.

### `Create_Release_Git_Tag`

This build task creates and pushes a preview release tag to the default branch.
Expand Down
Loading

0 comments on commit 2bfc9c0

Please sign in to comment.