Skip to content

Instantly share code, notes, and snippets.

@msftrncs
Last active April 15, 2022 00:22
Show Gist options
  • Save msftrncs/983f7d7adb673010961be794af84b769 to your computer and use it in GitHub Desktop.
Save msftrncs/983f7d7adb673010961be794af84b769 to your computer and use it in GitHub Desktop.
PowerShell functions to automate Git `safe.directory` submission
function Find-GitDirectory {
param (
[string[]] $Path = '.',
[switch] $Recurse
)
$gciParams = @{
Recurse = $Recurse
Force = $true
}
foreach ($dir in $Path) {
Get-Item $dir | Get-ChildItem -Include .git @gciParams | ForEach-Object { Get-Item $_.Parent }
}
}
# to use:
# Find-GitDirectory | Add-GitSafeDirectory
filter Add-GitSafeDirectory {
begin {
$ExistingSafeDirectories = git config --global --get-all safe.directory
}
process {
$PathToAdd = $(
if (!$_.PSDrive.Root) {
"%(prefix)/$($_.FullName)"
} elseif (!$_.PSDrive.DisplayRoot) {
$_.FullName
} else {
"%(prefix)/$(Join-Path $_.PSDrive.DisplayRoot $_.FullName.Substring($_.Root.FullName.Length))"
}).Replace([char]'\', [char]'/')
if ($PathToAdd -notin $ExistingSafeDirectories) {
git config --global --add safe.directory $PathToAdd
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment