ReCrutch.GitLab.psm1

function Set-ReCrGitLabSettings($apiUrl, $prj, $privTokenEnvVarName, $privTokenScripts, $privTokenValue)
{
    $ReCr.GitLab = @{
        ApiUrl = $apiUrl
        Prj = $prj
        PrivateToken = @{
            EnvVarName = $privTokenEnvVarName
            Scripts = $privTokenScripts
            PrivateToken = $privTokenValue
        }
    }
}

function Get-ReCrGitLabPrivateToken()
{
    try
    {
        $settings = $ReCr.GitLab.PrivateToken
        if($settings.PrivateToken -ne $null)
        {
            return $settings.PrivateToken
        }
        
        if($settings.EnvVarName -ne $null)
        {
            $pt = [System.Environment]::GetEnvironmentVariable($settings.EnvVarName)
            if($pt -ne $null)
            {
                return $pt
            }
        }

        if($settings.Scripts -ne $null)
        {
            foreach($script in $settings.Scripts)
            {
                if((Test-Path $script) -eq $true)
                {
                    . $script
                    if($settings.PrivateToken -ne $null)
                    {
                        return $settings.PrivateToken
                    }
                }
            }
        }

        if($settings.PrivateToken -eq $null)
        {
            $settings.PrivateToken = Read-Host -Prompt 'Input private token for accsess GitLab'
        }

        return $settings.PrivateToken
    }
    catch
    {
        Show-ReCrError "$($MyInvocation.MyCommand)" $_.Exception
        throw new-object System.Exception ("$($MyInvocation.MyCommand) error", $_.Exception)
    }
}

function Invoke-ReCrGitLabRestApi($method, [string]$url, $urlParameters, $if404ToNull)
{
    $oldSecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol;
    try
    {
        $settings = $ReCr.GitLab

        $pt = Get-ReCrGitLabPrivateToken

        [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;
        $urlParametersStr = ""
        if($urlParameters -ne $null)
        {
            $urlParametersStr = ($urlParameters.Keys | ForEach-Object {
                "{0}={1}" -f [System.Uri]::EscapeDataString($_), [System.Uri]::EscapeDataString($urlParameters[$_])
                }) -join "&"
        }

        $con = ""
        if([string]::IsNullOrEmpty($urlParametersStr) -ne $true -and $url.Contains("?") -ne $true -and $url.Contains("&") -ne $true)
        {
            $con = "?"
        }
        elseif([string]::IsNullOrEmpty($urlParametersStr) -ne $true -and $url.EndsWith("?") -eq $true)
        {
            $con = ""
        }
        elseif([string]::IsNullOrEmpty($urlParametersStr) -ne $true -and $url.EndsWith("&") -eq $true)
        {
            $con = ""
        }
        elseif([string]::IsNullOrEmpty($urlParametersStr) -ne $true -and $url.Contains("?") -eq $true)
        {
            $con = "&"
        }

        $fullUrl = "$($settings.ApiUrl)/projects/$([System.Web.HttpUtility]::UrlEncode($settings.Prj))$($url)$con$($urlParametersStr)"
        $resp = Invoke-WebRequest -Uri $fullUrl -Method $method -Headers @{
            "PRIVATE-TOKEN" = $pt
            "Content-Type" = "application/json;charset=utf-8"
        }
        $str=[system.Text.Encoding]::UTF8.GetString($resp.RawContentStream.ToArray());
        return ConvertFrom-Json $str
    }
    catch
    {
        if($if404ToNull -eq $true -and $_.Exception.GetType() -eq [System.Net.WebException])
        {
            if($_.Exception.Response.StatusCode -eq 404)
            {
                return $null
            }
        }

        throw new-object System.Exception ("$fullUrl", $_.Exception)
    }
    finally
    {
        [System.Net.ServicePointManager]::SecurityProtocol = $oldSecurityProtocol
    }
}

function Invoke-ReCrGitLabRestApiGet([string]$url, $urlParameters, $if404ToNull)
{
    return Invoke-ReCrGitLabRestApi Get $url $urlParameters $if404ToNull
}

function Invoke-ReCrGitLabRestApiPost([string]$url, $urlParameters, $if404ToNull)
{
    return Invoke-ReCrGitLabRestApi Post $url $urlParameters $if404ToNull
}

function New-ReCrGitLabLabel($labelName, $color)
{
    try
    {
        if([string]::IsNullOrEmpty($labelName) -eq $true)
        {
            throw [System.Exception] "`$labelName requery"
        }

        $labels = Invoke-ReCrGitLabRestApiGet "/labels" @{ per_page = 1000 }
        $label = $labels | where name -eq $labelName
        if($label -ne $null)
        {
            return $label
        }

        $label = Invoke-ReCrGitLabRestApiPost "/labels/" @{
            name = $labelName
            color = $color
        }

        return $label
    }
    catch
    {
        Show-ReCrError "$($MyInvocation.MyCommand)" $_.Exception
        throw new-object System.Exception ("$($MyInvocation.MyCommand) error", $_.Exception)
    }
}

function New-ReCrGitLabTag($branch, $tagName, $buildPath)
{
    <#if([string]::IsNullOrEmpty($tagName) -eq $true)
    {
        throw [System.Exception] "`$tagName requery"
    }#>


    #$tagName = "1"
    #$r = BuildGLRestGet "/repository/tags/" @{ per_page = 1000 } #?per_page=3&page=2&sort=commit.committed_date
    <#
    $r = $r | Sort-Object { $_.commit.committed_date } -Descending
    $r | Select-Object { $_.name; $_.commit.committed_date } | Format-Table
    $lastTag = $r[0]
    [Regex]::Matches($lastTag.name, "(?<stend>/)")
    $g = [Regex]::Matches($lastTag.name, "(?<stend>^\S[^/]+)/v(?<v1>\d+).(?<v2>\d+).(?<v3>\d+)")
    $g[0].Groups
    $nextVer = [int]::Parse($g[0].Groups["v2"].Value) + 1
    $newTagName = "$($g[0].Groups["stend"].Value)/v$($g[0].Groups["v1"].Value).$nextVer.$($g[0].Groups["v3"].Value)"
    #>


    <#$tag = BuildGLRestGet "/repository/tags/$tagName" -if404ToNull:true
 
    if($tag -ne $null)
    {
        throw [System.Exception] "Tag $tagName ��� ����������"
    }
 
 
    $issues = BuildGLRestGet "/issues" @{ labels = "$tagName"; state = "opened" }
    $issues = $issues | sort iid
    $issues.Count
    $issues | Format-Table iid, title
 
    $release_description = ""
    foreach ($issue in $issues)
    {
        $release_description += "* #$($issue.iid)
"
    }
 
    $newtag = BuildGLRestPost "/repository/tags/" @{
        tag_name = $tagName
        ref = $branch
        message = "$buildPath"
        release_description = $release_description
    }
    #>

}

function Set-ReCrGitLabLabelIssue($labelName)
{
    <#BuildGLCreateLabel $labelName
 
    $issues = BuildGLRestGet "/issues" @{ labels = "Need to deploy"; state = "opened" }
    $issues = $issues | sort iid
    $issues.Count
    $issues | Format-Table iid, title
 
    foreach ($issue in $issues)
    {
        if($buildOptions.gitLab.Developers -notcontains $issue.assignee.username)
        {
            Write-Host "no Task dev $($issue.iid) $($issue.assignee.username) $($issue.title)" -ForegroundColor Red
            continue
        }
 
        $newNote = BuildGLRestPost "/issues/$($issue.iid)/notes" @{
            body = "@a.butorin **����� ���������� �� ����� ������������**
���� ���: [$labelName](/../tags/$([System.Uri]::EscapeDataString($labelName)))
 
/label ~`"$labelName`"
"
        }
    }
    #>

}