Skip to content

Instantly share code, notes, and snippets.

@ap0llo
Last active February 12, 2022 15:54
Show Gist options
  • Save ap0llo/9d7cab3a4d05bb3b43720d2997c03d9f to your computer and use it in GitHub Desktop.
Save ap0llo/9d7cab3a4d05bb3b43720d2997c03d9f to your computer and use it in GitHub Desktop.
# https://gist.github.com/ap0llo/9d7cab3a4d05bb3b43720d2997c03d9f
function Set-LocationToRepository([Parameter(Mandatory = $false)][string]$Name) {
if (-not $RepositoriesDirectory) {
$RepositoriesDirectory = Join-Path $env:USERPROFILE "source\repos"
}
if (-not (Test-Path -Path $RepositoriesDirectory -PathType Container)) {
throw "Repositories directory '$RepositoriesDirectory' does not exist."
}
if (($Name -eq "/") -or ($Name -eq "\")) {
Push-Location -Path $RepositoriesDirectory
return
}
$repositories = Get-Repository
# if a repo name was specified, filter the repository list
if ($Name) {
$matchingRepositories = $repositories | Where-Object { $PSItem.Name -eq $Name }
$count = ($matchingRepositories | Measure-Object).Count
if ($count -ne 1) {
$matchingRepositories = $repositories | Where-Object { $PSItem.Name -like "*$Name*" }
}
$repositories = $matchingRepositories
}
$count = ($repositories | Measure-Object).Count
switch ($count) {
0 {
throw "No repositories matching the search criteria found in '$RepositoriesDirectory'"
}
1 {
Push-Location $repositories.FullName
}
Default {
Write-Host " "
$i = 0
foreach ($repo in $repositories) {
$relativePath = $repo.FullName.Replace($RepositoriesDirectory, "").Replace("\", "/").Trim("/")
Write-Host " $i - $relativePath"
$i = $i + 1
}
Write-Host " "
while ($true) {
$selection = Read-Host "Select repository index"
$index = $selection -as [int]
if (($null -ne $index) -and ($index -lt $count) -and ($index -ge 0)) {
Push-Location -Path ($repositories[$index]).FullName
break
}
else {
Write-Error "Invalid input '$selection' "
}
}
}
}
}
Set-Alias cdr Set-LocationToRepository
function Test-Repository($Path) {
return Test-Path (Join-Path $Path ".git") -PathType Container
}
function Get-Repository($Path) {
if (-not $RepositoriesDirectory) {
$RepositoriesDirectory = Join-Path $env:USERPROFILE "source\repos"
}
if (-not $Path) {
$Path = $RepositoriesDirectory
}
foreach ($dir in Get-ChildItem -Path $Path -Directory) {
if ($dir.Name -eq "node_modules") {
continue
}
if ($dir.Name -eq ".store") {
continue
}
if (Test-Repository $dir.FullName) {
#Write-Host "$($dir.FullName) is a git repository"
Write-Output $dir
}
else {
Get-Repository $dir.FullName | Write-Output
}
}
}
Register-ArgumentCompleter -CommandName Set-LocationToRepository -ParameterName Name -ScriptBlock {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
Get-Repository | Where-Object { $PSItem.Name -like "$wordToComplete*" } | Select-Object -ExpandProperty Name
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment