Module/GIT/Compare-BCSGitBranches.ps1

<#
.SYNOPSIS
  Compare 2 branches against each other
.DESCRIPTION
  Clones a repository and checksout 2 branches from a project repository and compares them using WinMerge
 
.PARAMETER BaseURI
  Base URI to DevOps Organisation, default = https://dev.azure.com/BrightComSolutions/
 
.PARAMETER Project
  DevOps Project
 
.PARAMETER Repository
  DevOps Repository
 
.PARAMETER TargetBranch
  Target branch
 
.PARAMETER CompareBranch
  Branch to Compare against
 
.EXAMPLE
  Compare-GitBranches -Project Rusta -Repository Rusta -TargetBranch main -CompareBranch feature/feature1
 
.NOTES
    Author: Mathias Stjernfelt
    Website: http://www.brightcom.se
#>

function Compare-BCSGitBranches {
  [CmdletBinding(SupportsShouldProcess = $true)]
  Param(
    [Parameter(Mandatory = $false)]
    [String] $BaseURI = 'https://dev.azure.com/BrightComSolutions/',
    [Parameter(Mandatory = $true)]
    [String] $Project,
    [Parameter(Mandatory = $true)]
    [String] $Repository,
    [Parameter(Mandatory = $true)]
    [String] $TargetBranch,
    [Parameter(Mandatory = $true)]
    [String] $CompareBranch
  )
  try {
    $OriginalFolder = Get-Location;
    
    $CompareBranchLeaf = Split-Path -Path $CompareBranch -Leaf
    $TargetBranchLeaf = Split-Path -Path $TargetBranch -Leaf
    
    $RepositoryURI = ('{0}/{1}/_git/{2}' -f $BaseURI, $Project, $Repository)
    $Workfolder = ('{0}\{1}\{2}' -f $env:TEMP, $Project, $Repository);
    
    if (Test-Path -Path $Workfolder) {
      Remove-Item -Path $Workfolder -Recurse -Force;
    }
    
    $RepositoryCloneFolder = ('{0}\{1}' -f $Workfolder, '.Repo');
    $TargetBranchWorkFolder = ('{0}\{1}' -f $Workfolder, $TargetBranchLeaf);
    $CompareBranchWorkFolder = ('{0}\{1}' -f $Workfolder, $CompareBranchLeaf);
    
    git clone $RepositoryURI $RepositoryCloneFolder;
    Set-Location $RepositoryCloneFolder 
    
    git checkout "remotes/origin/$TargetBranch";
    Copy-Item -Path $RepositoryCloneFolder -Destination $TargetBranchWorkFolder -Recurse -Force;
    Remove-Item ('{0}\.git\' -f $TargetBranchWorkFolder) -Force -Recurse
    
    git checkout -q --track "remotes/origin/$CompareBranch"
    Copy-Item -Path $RepositoryCloneFolder -Destination $CompareBranchWorkFolder -Recurse -Force
    Remove-Item ('{0}\.git\' -f $CompareBranchWorkFolder) -Force -Recurse
    
    winmergeU /r $TargetBranchWorkFolder $CompareBranchWorkFolder
    
    Set-Location $OriginalFolder        
  }
  catch {
    throw "An error occured: $_.Exception";
  }
}

Export-ModuleMember -Function Compare-BCSGitBranches