Functions/New-Repo.ps1


function New-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 directory within which your repositories will be checked out (e.g. /src/).")]
        $Path = $GitTool.Directory,

        [switch]
        [Parameter(HelpMessage = "Open the repo once it has been created.")]
        $Open = $false
    )

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

    Write-Host -NoNewline "Creating "
    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 (-not $info.Exists) {
        New-Item -Path $info.Path -ItemType Container | Out-Null
    }

    Push-Location -Path $info.Path
    try {
        if (Test-Path -PathType Container -Path ".git") {
            Write-Error -Category ResourceExists -Message "The repository $Service/$Repo already exists." -RecommendedAction "Please use git to manage this repository directly."
            return
        }
        
        Write-Host -NoNewline "Running "
        Write-Host -ForegroundColor DarkGray "git init"
        git.exe init | Out-Null

        Write-Host -NoNewline "Running "
        Write-Host -ForegroundColor DarkGray "git remote add origin ${info.GitURL}"
        git.exe remote add origin $info.GitURL | Out-Null
    }
    finally {
        Pop-Location
    }

    if ($Open) {
        Open-Repo -Repo $Repo -Service $Service -Path $Path
    }

    return $info
}

Register-ArgumentCompleter -CommandName New-Repo -ParameterName Repo -ScriptBlock $Function:SuggestRepoPrefix