src/tools/Get-DefectSuite.ps1

# [Nuget in Powershell](https://timatlee.com/post/nuget-in-powershell/)

Write-Host "Installing function in: $PSScriptRoot"
$dsFolderPath = [Environment]::GetEnvironmentVariable("DS_FOLDER_PATH", "User")
$debug = $true

# $hvalue = aws ssm get-parameter --name "$storeParameter" --with-decryption --query 'Parameter.Value' --output text
# $hvalue = Get-Secret -Name "RallyZSessionId" -Vault "Vertafore" -AsPlainText
$hvalue = [Environment]::GetEnvironmentVariable("ZSESSIONID", "User")
$header = @{"zsessionid"=$hvalue}

function dsDataToUUID(){
    param(
        [Parameter(ValueFromPipeline)] $dsData
    )
    $dsData.QueryResult.Results[0]._refObjectUUID
}
function dsDataToName(){
    param(
        [Parameter(ValueFromPipeline)] $dsData
    )
    $dsData.QueryResult.Results[0]._refObjectName
}
function dsDataToRefUrl(){
    param(
        [Parameter(ValueFromPipeline)] $dsData
    )
    $dsData.QueryResult.Results[0]._ref
}
function getDsDataFromDsId($dsId){
    Invoke-RestMethod -Uri "https://rally1.rallydev.com/slm/webservice/v2.0/DefectSuite?query=(FormattedID = $dsId)" -Headers $header | Select-Object QueryResult 
}
function getDsFullFromRefUrl(){
    param(
        [Parameter(ValueFromPipeline)] $refUrl
    )
    Invoke-RestMethod -Uri $refUrl -Headers $header | Select-Object DefectSuite
} 
# TODO: Create DS folder in $dsFolderPath, create _index.md and write Ds content in there
# TODO: Log operations to a file in the root $dsFolderPath
function createDsFolder(){
    param([Parameter(ValueFromPipeline)] $dsFullData)
    throw NotImplementedException
}
function postDefect(){
    param(
        [Parameter(ValueFromPipeline)] $defect
    )
    if($debug){
        Write-host "Would have posted this defect: $($defect | ConvertTo-Json -Depth 3)"
        return
    }
    Invoke-RestMethod -Method Post -Uri "https://rally1.rallydev.com/slm/webservice/v2.0/defect/create" -Headers $header -Body $defect
}

function dsFullToDefect(){
    param(
        [Parameter(ValueFromPipeline)] $dsFull
    )
    $ds = $dsFull.DefectSuite
    $ds | ConvertTo-Json -Depth 3 | Write-Host
    @{
        Name = $ds.Name
        Description = $ds.Description
        c_ApprovedProject = $ds.c_ApprovedProject
        c_FoundinVersion = $ds.c_FoundinVersion
        c_VerifiedinVersion = $ds.c_VerifiedinVersion
        c_Impact = $ds.c_Impact
        c_Likelihood = $ds.c_Likelihood
        Priority = $ds.Priority
        c_Product = $ds.c_Product
        c_Activity = $ds.c_Activity
        c_Workaround = $ds.c_Workaround
        Environment = $ds.Environment
        SalesforceCaseNumber = $ds.SalesforceCaseNumber
        Severity = $ds.Severity
        State = $ds.State
        Project = $ds.Project
        DefectSuites = $ds.DefectSuites
        Expedite = $ds.Expedite
        DisplayColor = $ds.DisplayColor
    }
}
function trimName(){
    param(
        [string] $name
    )
    if($name.IndexOfAny(":") -gt -1){
        $name = ($name -split ":")[1]
    }else{
        $dsNameArray = $name -split "-"
        if($dsNameArray.Length -gt 1){
            $name = $dsNameArray[-1].Trim()
        }
    }
    ($($name) -replace "[ #/]","_" -replace "QQCatalyst","_" -replace "Support","_" -replace "_{2,10}", "_" ).Trim("_").Substring(0,50)
    $name
}
function dsFullToYamlFile(){
    param(
        [Parameter(ValueFromPipeline)] $dsFull
    )
    $ds = $dsFull.DefectSuite
    $dsName = trimName($ds.Name)
    Write-Host "DsName: $dsName"
    $dsId = $($ds.FormattedID)
    $dsIdFolder = "$dsFolderPath/$dsId-$dsName"
    if(-not(Test-Path $dsIdFolder -PathType Container)){
        Write-Host "Creating directory: $dsIdFolder/"
        New-Item "$dsIdFolder" -ItemType Directory
    }
    $outFile = "$dsIdFolder/dsInfo.yml"
    Write-Host "Writing to: $outFile"
    $ds | ConvertTo-Yaml | Out-File $outFile -Force
    if(-not(Test-Path "$dsIdFolder/_index.md")){
        "# $dsName`n`n[$dsName]($($ds._ref))`n`n" `
        + $ds.Description `
        -replace "<p>&nbsp;</p>","" `
        -replace "<p>","" `
        -replace "</p>","`n" `
        -replace "`n{3,100}","`n`n" `
        | Out-File "$dsIdFolder/_index.md"
        
    }
}

<#
    .SYNOPSIS
        Provides SRE-specific handling of Rally Tickets
    .DESCRIPTION
        Manage Default Suites and defects using the following commands
    .PARAMETER defectSuite
        Required default Defect Suite id
    .PARAMETER copyUrlToClipboard
        Copy the DS URL to the Windows Clipboard for pasting anywhere
    .PARAMETER copyLongLinkToClipboard
        Copy Id and Name to HTML fragment
    .PARAMETER copyShortLinkToClipboard
        Copy Id to HTML fragment
    .PARAMETER triageHighPriority
    .PARAMETER triageHighPriority
    .PARAMETER triageLowPriority
    .PARAMETER divertToDev
    .PARAMETER syncPriorityToDefects
    .PARAMETER triageUnshieldedProductDS
     
    .PARAMETER openInBrowser
        Open browser window and navigate to Defect Suite in Rally
    .PARAMETER calculateCycleTimes
    .PARAMETER dsDataToUUID
     
    .EXAMPLE
  
#>

function Get-DefectSuite {
    [CmdletBinding()]
    param(
        [Parameter(Position=0,Mandatory=$true)]
        [string][alias("ds")] $dsId,
        [switch][alias("cu")] $copyUrlToClipboard,
        [switch][alias("clong")] $copyLongLinkToClipboard,
        [switch][alias("cshort")] $copyShortLinkToClipboard, 
        [switch][alias("thp")] $triageHighPriority,
        [switch][alias("tlp")] $triageLowPriority,
        [switch][alias("dd")] $divertToDev,
        [switch][alias("sync")] $syncPriorityToDefects,
        [switch][alias("tu")] $triageUnshieldedProductDS,
        [switch][alias("web")] $openInBrowser,
        [switch][alias("calc")] $calculateCycleTimes,
        [switch][alias("uuid")] $dsDataToUUID,
        [switch][alias("pull")] $pullDsData,
        [switch][alias("h")] $help
    )
    
    $dsId = $dsId.ToUpper()
    if(-not $dsId  -match "DS\d{3,5}"){
        return Write-Host "Defect Suite id must match pattern 'DS\d{3,5}"
    }

    # Lookup Defect Suite
    if($dsId){
        getDsDataFromDsId($dsId) | dsDataToName
    }
    if($dsDataToUUID){
        getDsDataFromDsId($dsId) | dsDataToUUID
    }
    if($copyUrlToClipboard){
        $uuid = getDsDataFromDsId($dsId) | dsDataToUUID
        "https://rally1.rallydev.com/#/detail/defectsuite/$uuid"  | clip
    }
    if($openInBrowser){
        $uuid = getDsDataFromDsId($dsId) | dsDataToUUID
        Start-Process "https://rally1.rallydev.com/#/detail/defectsuite/$uuid"
    }
    if($copyLongLinkToClipboard){
        $dsData = getDsDataFromDsId($dsId) 
        $linkUrl = "https://rally1.rallydev.com/#/detail/defectsuite/$($dsData | dsDataToUUID)"
        $linkText = "$dsId - $($dsData | dsDataToName )"
        $linkHtml = "
            <html>
            <body>
            <!--StartFragment-->
            <a href='$linkUrl'>$linkText</a>
            <!--EndFragment-->
            </body>
            </html>"

        $linkHtml | clip
    }
    if($copyShortLinkToClipboard){
        $dsData = getDsDataFromDsId($dsId) 
        $linkUrl = "https://rally1.rallydev.com/#/detail/defectsuite/$($dsData | dsDataToUUID)"
        $linkHtml = "
            <html>
            <body>
            <!--StartFragment-->
            <a href='$linkUrl'>$dsId</a>
            <!--EndFragment-->
            </body>
            </html>"

        $linkHtml | clip
    }
    if($triageHighPriority){
        getDsDataFromDsId($dsId) 
        | dsDataToRefUrl 
        | getDsFullFromRefUrl 
        | dsFullToDefect 
        | postDefect
    }
    if($pullDsData){
        getDsDataFromDsId($dsId) 
        | dsDataToRefUrl 
        | getDsFullFromRefUrl 
        | dsFullToYamlFile 
    }
    if($triageLowPriority){
        
    }
    if($divertToDev){
        
    }
    if($syncPriorityToDefects){

    }
    if($triageUnshieldedProductDS){

    }
    if($help){
        Get-Help Get-DefectSuite
    }
}