Save/Save-AppsInRepository.ps1

<#
 .Synopsis
   Save-AppsInRepository is a function that saves apps in a repository.
 .Description
   This function takes in several parameters, performs operations like removing old app files, copying new ones, updating the version in AppSourceCop.json files, and creating a pull request in Azure DevOps.
 .Parameter PRName
   The name of the pull request to be created.
 .Parameter branchName
   The name of the branch where changes will be made.
 .Parameter appNames
   A comma-separated string of app names. These names are used to identify the app files to be removed and copied.
 .Parameter pathToPreviousapps
   The path to the directory where the previous versions of the apps are stored.
 .Parameter pathToArtifacts
   The path to the directory where the new versions of the apps are stored.
 .Parameter version
   This is the new version to be set in the AppSourceCop.json files.
 .Parameter folderNamesToChangeVersion
   This variable accepts comma-separated folder names in which the version should be changed.
  .Parameter buildRepositoryName
    This variable is responsible for the name of the repository in which the pull request will be created.
    By default, it is set to the same repository from which the pipeline is triggered.
 .Example
   Save-AppsInRepository -PRName "Update apps" -branchName "update-apps" -appNames "App1,App2" -pathToPreviousapps "./previousApps" -pathToArtifacts "./artifacts" -version "1.0" -folderNamesToChangeVersion "App1"
#>

function Save-AppsInRepository {
    param (
        [Parameter(Mandatory=$true)]
        [string]$PRName,
        [Parameter(Mandatory=$true)]
        [string]$branchName,
        [Parameter(Mandatory=$true)]
        [string]$appNames,
        [Parameter(Mandatory=$true)]
        [string]$pathToPreviousapps,
        [Parameter(Mandatory=$true)]
        [string]$pathToArtifacts,
        [Parameter(Mandatory=$true)]
        [string]$version,
        [string]$folderNamesToChangeVersion,
        [string]$buildRepositoryName
    )

    cd $env:BUILD_SOURCESDIRECTORY

    if (-not $PSBoundParameters.ContainsKey('buildRepositoryName')) {
        $buildRepositoryName = $env:BUILD_REPOSITORY_NAME
    }
    else {
        $doNotChangeVersion = $True
    }

    az devops configure --defaults organization="$env:SYSTEM_COLLECTIONURI" project="$env:SYSTEM_TEAMPROJECT" --use-git-aliases true
    git config user.email "hosted.agent@dev.azure.com"
    git config user.name "Azure Pipeline"
    git fetch origin master
    git checkout master
    git checkout -b $branchName

    $appPaths = @($appNames.Split(',').Trim() | Foreach-Object { 
        Get-ChildItem -Path (Join-Path $pathToPreviousapps ("*_"+$_+"_*.app"))| Remove-Item -Force -Recurse
    })

    $appPaths = @($appNames.Split(',').Trim() | Foreach-Object { 
        Get-ChildItem -Path (Join-Path $pathToArtifacts ("*_"+$_+"_*.app")) | Copy-Item -Destination $pathToPreviousapps
    })

    $targetFolders = if ($folderNamesToChangeVersion) { $folderNamesToChangeVersion.Split(',') } else { $null }
    
    $appDirectories = Get-ChildItem -Path "$env:BUILD_SOURCESDIRECTORY" -Recurse -Directory -ErrorAction SilentlyContinue
    
    if ($doNotChangeVersion -ne $True) {
        foreach ($directory in $appDirectories) {
            $currentFolderName = Split-Path -Leaf $directory.FullName
            if ($targetFolders -eq $null -or $currentFolderName -in $targetFolders) {
                $jsonFilePaths = Join-Path -Path $directory.FullName -ChildPath AppSourceCop.json
                $jsonFileFound = $false

                if (Test-Path -Path $jsonFilePaths) {
                    $jsonFileFound = $true
                } else {
                    $subDirectories = Get-ChildItem -Path $directory.FullName -Recurse -Directory -ErrorAction SilentlyContinue
                    foreach ($subDir in $subDirectories) {
                        $jsonFilePaths = Join-Path -Path $subDir.FullName -ChildPath AppSourceCop.json
                        if (Test-Path -Path $jsonFilePaths) {
                            $jsonFileFound = $true
                            break
                        }
                    }
                }

                if ($jsonFileFound) {
                    try {
                        $jsonContent = Get-Content -Path $jsonFilePaths | ConvertFrom-Json
                        if ($jsonContent.PSObject.Properties.Name -notcontains 'version') {
                            throw "The 'version' line is missing in the folder $jsonFilePaths"
                        }
                        $jsonContent.version = "$version"
                        $jsonContent | ConvertTo-Json | Set-Content -Path $jsonFilePaths
                        Write-Output "Changed version to $version in the file $jsonFilePaths"
                    } catch {
                        Write-Output "Error: $($_.Exception.Message)"
                    }
                } else {
                    Write-Output "AppSourceCop.json not found in $directory.FullName or its subdirectories."
                }
            }
        }
    }

    foreach ($folder in $targetFolders) {
        if (-not (Test-Path $folder)) {
            Write-Host "Error: Folder '$folder' was not found in the repository."
        }
    }

    git add .
    git commit -m $PRName
    git push origin $branchName

    $env:AZURE_DEVOPS_EXT_PAT = "$env:SystemAccessToken"
    az devops login --organization "$env:SYSTEM_COLLECTIONURI"
    az repos pr create --repository $buildRepositoryName --source-branch $branchName --target-branch master --title $PRName --description $PRName
}