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'"
            ]
        }
    ]
}






Git: Merging a branch and Prioritizing Current Branch

In a local git repo, I was working on a branch. I had to merge with main. During the merge I wanted the changes made in my branch to be prioritized over any changes in main. On some projects, I'm just an arrogant sod that way.

This is the git command that merged branch, main, with my current branch and prioritizes the. current branch with the merge:

git merge -s ours main

The result of the following command will be to:

  • Ignores all changes from branch, main.
  • Keeps all the changes from the current branch which means any changes made to the main branch will be discarded.

Thursday, August 1, 2024

Windows 11: Remove Microsoft News Widget

I will not make negative comments in my blog. Here is the command to uninstall the Microsoft News widget on Windows 11:

winget uninstall MicrosoftWindows.Client.WebExperience_cw5n1h2txyewy 



Sunday, July 28, 2024

Git: get remote URL of local Git Repo

From a console window where the current folder corresponds to a local git repo, run the following from a console:

git remote -v

An example output from this command is as follows:

origin  https://softwarepronto.visualstudio.com/Blog/_git/Scratch (push)






Wednesday, April 10, 2024

PowerShell: Folder Diff

With a new git repo, I after push the source code and then re-pull to a new local repo. To verify the .gitignore is correct, I diff the original folder containing the source code against the git clone just created. The following PowerShell is what I use to dif the folders:

param(
    [Parameter(Mandatory=$true)]
    [string] $folderSource,
    [Parameter(Mandatory=$true)]
    [string] $folderDestination
)

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-RelativeFilePaths {
    param(
        [Parameter(Mandatory=$true)]
        [string] $folderPath
    )

    [string] $resolvedFolderPath = 
        (Resolve-Path -Path $folderPath -ErrorAction Stop).Path + '\'

    return (
        Get-ChildItem `
            -Path $folderPath `
            -Recurse `
            -File `
            -ErrorAction Stop).
            FullName.
                Replace($resolvedFolderPath, '')
}

try {
    [string[]] $sourceFiles = `
                 Get-RelativeFilePaths $folderSource
    [string[]] $destinationFiles = `
                 Get-RelativeFilePaths $folderDestination
    
    Compare-Object `
        -ReferenceObject $sourceFiles `
        -DifferenceObject $destinationFiles `
        -ErrorAction Stop    
}

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 launch.json is as followings when running from Visual Studio Code:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Compare-Folders",
            "type": "PowerShell",
            "request": "launch",
            "script": "${workspaceRoot}/Compare-Folders.ps1",
            "cwd": "${workspaceRoot}",
            "args": [
                "-FolderSource",
                <source folder>,
                "-FolderDestination",
                <destination folder>
            ]
        }
    ]
}


Wednesday, April 3, 2024

Visual Studio Code: Error Generation Bicep Template from Existing Azure Resource

The latest version of Microsoft's Bicep Extension (v0.26.54) for Visual Studio Code has a new behavior that causes an error message to be generated under certain circumstances. The Bicep Extension was covered in a blog post eighteen months ago (November 26, 2022: Azure: Generate a Bicep Template from an Existing Azure Resource using Visual Studio Code) and the manifesting of the following error message is a newish behavior in the extension:

Caught exception fetching resource: The ChainedTokenCredential failed to retrieve a token from the included credentials. - Please run 'az login' to set up account - Please run 'Connect-AzAccount' to set up account.

The error message above is generated while attempting to use the command, Bicep: Insert Resource (F1 displays the command palette or CTRL-SHIFT-P on Windows or CMD-SHIFT-P on Mac):


The error message is generated when a valid resource ID is entered for the Bicep: Insert Resource command and OK is clicked on in order to extract the Bicep template for an existing resource. The error message (see below) suggests a solution, logging in using Azure CLI (az login) or PowerShell (Connect-AzAccount):



At the time the error is generated, the Visual Studio Code Azure Extension is logged into a valid Azure Subscription:



Visual Studio Code's accounts show that the correct Microsoft account is logged in:


The solution is to log in to Azure via the Visual Studio Code Terminal window (displayed using CTRL-`):




There Terminal window above is PowerShell, so Azure will be logged into using Connect-AzAccount (note: Azure CLI's az login could also have been used):


Once the Terminal window is used to log in to, Azure the Bicep: Insert Resource command will run successfully meaning a Bicep template will be extracted from an existing Azure resource.







Tuesday, April 2, 2024

Visual Studio Code: Azure Extension Pack error "Expected value to be neither null nor undefined"

This post presents a solution to the following error displayed in Visual Studio Code when using the Azure Tools Extension Pack:

Internal error: Expected value to be neither null nor undefined: resourceGroup for grouping item

The Azure Tools Extension Pack (Azure Tools) is critical to Azure developers who use Visual Studio Code (see the A below):

When signed in to a subscription, the Azure Tools Extension displays Azure resources by default, grouped by resource group. For some subscriptions (not all) the following error is displayed by Visual Studio Code when group by is set to "Group by Resource Group":


The fix to this issue is to click on the group by icon:


This displays the following context menu:


From the context menu, select the menu item "Group by Resource Type." This has change causes the error to no longer be raised. For subscriptions experiencing this error, there seems to be no way to select the Group By menu item "Group by Resource Group" without generating an error.