Functions/Get-Repo.ps1


function Get-Repo {
    param(
        [string]
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, HelpMessage = "The name of the repository that you wish to synchronize (e.g. Namespace/RepoName)")]
        $Repo,

        [string]
        [Parameter(HelpMessage = "The service hosting your repository (e.g. github.com)")]
        [ValidateSet("github.com", "dev.azure.com", "gitlab.com", "bitbucket.org")]
        $Service = "github.com",

        [string]
        [Parameter(HelpMessage = "The branch to checkout and update (optional).")]
        $Branch = $null,

        [string]
        [Parameter(HelpMessage = "The directory within which your repositories will be checked out (e.g. /src/)")]
        $Path = $GitTool.Directory,

        [switch]
        [Parameter(HelpMessage = "Reconfigure existing local repositories to ensure they use the correct remotes.")]
        $Reconfigure = $false
    )

    $info = Get-RepoInfo -Repo $Repo -Service $Service -Path $Path

    Write-Host -NoNewline "Synchronizing "
    Write-Host -ForegroundColor Blue $info.WebURL
    Write-Host -NoNewline " - Git URL: "
    Write-Host -ForegroundColor Red $info.GitURL
    Write-Host -NoNewline " - Target: "
    Write-Host -ForegroundColor Green $info.Path

    if ($info.Exists) {
        Push-Location -Path $info.Path
        try {
            if ($Reconfigure) {
                Write-Host -NoNewline "Running "
                Write-Host -ForegroundColor DarkGray "git remote set-url origin ${info.GitURL}"
                git.exe remote set-url origin $info.GitURL
            }
            
            Write-Host -NoNewline "Running "
            Write-Host -ForegroundColor DarkGray "git pull"
            git.exe pull

            if ("" -ne "$Branch") {
                Write-Host -NoNewline "Running "
                Write-Host -ForegroundColor DarkGray "git checkout $Branch"
                git.exe checkout $Branch
            }
        }
        finally {
            Pop-Location
        }
    }
    else {
        Write-Host -NoNewline "Running "
        Write-Host -ForegroundColor DarkGray "git clone ${info.GitURL} ${info.Path}"
        git.exe clone $info.GitURL $info.Path
    }

    return $info
}

Register-ArgumentCompleter -CommandName Get-Repo -ParameterName Repo -ScriptBlock $Function:SuggestRepoName