Skip to content

Instantly share code, notes, and snippets.

@deviousasti
Last active November 10, 2020 15:36
Show Gist options
  • Save deviousasti/b23160ef21d16faa3b8668ae11a20ed2 to your computer and use it in GitHub Desktop.
Save deviousasti/b23160ef21d16faa3b8668ae11a20ed2 to your computer and use it in GitHub Desktop.
Adds submodules looking at entries from .gitmodules
function Get-Submodules {
function lookup($key, $defaultValue = "") {
$value = git config --file $gitmodules --get "$key" 2>&1
if($LASTEXITCODE -ne 0) { $defaultValue } else { $value }
}
function all {
(git config --file $gitmodules --list) -split "\n"
}
if (!(Test-Path $gitmodules)) {
echo "No gitmodules file found in $root"
exit -1
}
all |
foreach { $_ -split "submodule.\S+.path\=" | select -Index 1 } |
select -Unique |
foreach {[pscustomobject]@{
Path = lookup "submodule.$_.path";
Url = lookup "submodule.$_.url";
Branch = lookup "submodule.$_.branch" "master";
}} |
where { $_.Path -ne "" }
}
function Sync-Submodules {
$gitmodules = ".gitmodules"
$root = $pwd
$modules = Get-Submodules
"Submodules found:"
$modules
"`n`nCloning:"
foreach ($sub in $modules) {
cd $root
$path = $sub.Path
if(Test-Path $path) {
"$($path) already exists, ignoring."
} else {
git submodule add $sub.Url $sub.Path 2>&1 | foreach { "$_" }
git submodule set-branch --branch $sub.Branch $path 2>&1 | foreach { "$_" }
cd $path
git submodule checkout $sub.Branch 2>&1 | foreach { "$_" }
}
}
"Done."
}
@deviousasti
Copy link
Author

Usage:

cd to path with .gitmodules
Sync-Submodules

@rLindorfer
Copy link

Thank you very much for your powershell script!

I have a small problem with my submodules, because one of my submodule name contains a dot (".").
As a result, the foreach with the integrated --split parameter with "." fails in line 18.

Do you have possible a solution for this problem?

@deviousasti
Copy link
Author

Can you try replacing it with:

 foreach { $_ -split "submodule.\S+.path\="  | select -Index 1 }

@rLindorfer
Copy link

rLindorfer commented Nov 6, 2020

Thank you very much, this Regex works perfectly!

UPDATE:
I added missing backslashes, because dots "\." must be escaped:

foreach { $_ -split "submodule\.\S+\.path\=" | select -Index 1 } |

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment