Skip to content

Instantly share code, notes, and snippets.

@pvandervelde
Created June 26, 2024 22:47
Show Gist options
  • Save pvandervelde/ac8e8d308774984690235fd4a1259dab to your computer and use it in GitHub Desktop.
Save pvandervelde/ac8e8d308774984690235fd4a1259dab to your computer and use it in GitHub Desktop.
A powershell script to create a working directory for working with git work trees
# Create a git worktree base folder for a repository
#
# Based on: https://morgan.cugerone.com/blog/workarounds-to-git-worktree-using-bare-repository-and-cannot-fetch-remote-branches/
#
# This script will clone a repository as a bare repository into the
# <TARGETFOLDER>/.bare directory, create a .git file and update the origin fetch
# settings so that we can fetch remote branches.
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$repositoryUrl,
[string]$targetFolder = $null
)
# Examples of call:
# Git-CloneForWorktrees git@github.com:name/repo.git
# => Clones to a /repo directory
#
# Git-CloneForWorktrees git@github.com:name/repo.git my-repo
# => Clones to a /my-repo directory
if ($targetFolder -eq $null) {
$targetFolder = $repositoryUrl.Split("/")[-1].Replace(".git", "")
}
if (![System.IO.Path]::IsPathRooted($targetFolder)) {
$targetFolder = Join-Path $PWD $targetFolder
}
if (Test-Path $targetFolder) {
Write-Output "Folder $targetFolder already exists. Exiting."
exit
}
Create-Item -Path $targetFolder -ItemType Directory | Out-Null
# Clone the repository as a bare repository
Set-Location $targetFolder
git clone --bare $repositoryUrl .bare
Set-Content -Path .git -Value "gitdir: .bare"
# Update the fetch settings
git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
# Fetch the remote branches
git fetch origin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment