Wednesday, November 13, 2024

PowerShell: Create a git branch for an issue (type, number and title)

 On a project the branches used take the following form where issues are of type Bug, Task, etc:

<issue type>/<user name>/<issue number>-<title>

Example branch names are:

bug/jdnarkiewicz/1234-Fix-bearer-token-authorization
task/jdnarkiewicz/6789-Add-clean-up-code-for-employee-tables

The code to create the branch name and perform a "git checkout -b" to create the branch locally is as follows (script New-Branch.ps1):

param(
    [Parameter(Mandatory=$true)]
    [string] $issueType,
    [Parameter(Mandatory=$true)]
    [string] $issueNumber,
    [Parameter(Mandatory=$true)]
    [string] $issueTitle
)

Set-StrictMode -Version 3.0
$ErrorActionPreference = 'Stop'
Set-PSDebug -Off
# Set-PSDebug -Trace 1

[int] $exitCodeSuccess = 0

[int] $exitCodeError = 1

[int] $exitCode = $exitCodeSuccess

function Get-UserNameCore {
    [string] $userName = (whoami)
    [int] $lastBackslashIndex = $userName.LastIndexOf('\')

    if ($lastBackslashIndex -ge 0) {
        $userName = $userName.Substring($lastBackslashIndex + 1)
    }

    return $userName
}

function Get-BranchCore {
    param(
        [Parameter(Mandatory=$true)]
        [string] $issueTitle
    )

    return ($issueTitle -replace '[ ,./:\\=]', '-').Trim()
}

try {
    [string] $userName = Get-UserNameCore
    [string] $branchBody = Get-BranchCore $issueTitle
    [string] $branchName = "$issueType/$userName/$issueNumber-$branchBody"

    $gitResult = git checkout -b $branchName 2>&1
    if ($LASTEXITCODE -ne 0) {
        throw "Failed to create branch: $branchName. Error: $gitResult"
    }
    
    Write-Host "Created: $branchName"
}

catch {
    [System.Management.Automation.ErrorRecord] $errorRecord = $PSItem

    $exitCode = $exitCodeError
    Write-Host $errorRecord
    Write-Host `
        "Exception Message: $($errorRecord.Exception.Message), " + `
        "Stacktrace: $($errorRecord.Exception.StackTrace)"
}

return $exitCode

The corresponding launch.json is follows:


{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "New-Branch",
            "type": "PowerShell",
            "request": "launch",
            "script": "${workspaceRoot}\\New-Branch.ps1",
            "args": [
                "-issueType", "bug",
                "-issueNumber", "1234",
                "-issueTitle", "'Clean up code formatting'"
            ]
        }
    ]
}






No comments :

Post a Comment