bhylu.com

Advertisements

Git Force with Lease

A deliberate history rewrite may need a forced remote reference update. An explicit lease rejects that update if the remote tip is no longer the commit you expected.

How it works

The lab records the expected remote main ID, amends a private teaching commit and advances the remote from another local clone. A push with the old explicit lease must fail. The remote file is checked afterward to prove concurrent work was preserved. This exercise never performs an unconditional force push.

Run the disposable lab

Use Windows PowerShell 5.1 or later and Git 2.28 or later. The reviewed CLI is Git for Windows 2.53.0.windows.2. These are PowerShell examples, not Git Bash commands. Save the download as force-with-lease.ps1 in a separate empty learning folder and run it in a separate process: powershell -NoProfile -ExecutionPolicy Bypass -File .\force-with-lease.ps1. The execution-policy option applies to that process, not your machine policy.

The script creates bhylu-git-force-with-lease and refuses an existing folder. It supplies two fictional seed files and repository-local settings, then runs the lesson commands. The literal separator is quoted as '--' so PowerShell passes it through the guard. A guard function named git calls the real CLI and stops on unexpected failures; Expect-GitFailure checks deliberately refused operations. Child-process configuration isolates your personal Git settings. File transports are allowed only for owned local remotes; internet transports are disabled in this lab. No hosting account, Apache or MySQL service is required. There is no Git playground. Leave the generated folder for inspection; choose another empty parent to run again.

Download the complete force-with-lease.ps1 lab

Example

force-with-lease.ps1

# Bhylu Git lab: Force with Lease
# Run in a separate PowerShell process, in an empty learning folder.
# Existing lab folders are refused; nothing is pushed to an internet host.
$ErrorActionPreference = 'Stop'
$script:GitExe = (Get-Command git -CommandType Application | Select-Object -First 1).Source
$script:LabRoot = Join-Path (Get-Location) 'bhylu-git-force-with-lease'
if (Test-Path -LiteralPath $script:LabRoot) { throw 'Lab folder already exists. Choose another empty parent folder.' }
New-Item -ItemType Directory -Path $script:LabRoot | Out-Null
$env:GIT_CONFIG_NOSYSTEM = '1'
$env:GIT_CONFIG_GLOBAL = Join-Path $script:LabRoot 'empty-global-config'
[IO.File]::WriteAllText($env:GIT_CONFIG_GLOBAL, '')
$env:GIT_TERMINAL_PROMPT = '0'
$env:GIT_EDITOR = 'true'
$env:GIT_SEQUENCE_EDITOR = 'true'
$env:GIT_AUTHOR_DATE = '2026-01-10T10:00:00+00:00'
$env:GIT_COMMITTER_DATE = $env:GIT_AUTHOR_DATE
function git {
    & $script:GitExe -c protocol.allow=never -c protocol.file.allow=always @args
    if ($LASTEXITCODE -ne 0) { throw "Git exited with code $LASTEXITCODE" }
}
function Expect-GitFailure {
    & $script:GitExe -c protocol.allow=never -c protocol.file.allow=always @args
    if ($LASTEXITCODE -eq 0) { throw 'Expected Git to refuse this operation' }
}
function Assert-Equal($Actual, $Expected) {
    if ((($Actual | Out-String).Trim()) -cne (($Expected | Out-String).Trim())) { throw "Expected [$Expected], got [$Actual]" }
}
function Write-LabFile([string]$Name, [string]$Text) {
    $target = [IO.Path]::GetFullPath((Join-Path (Get-Location) $Name))
    if (!$target.StartsWith($script:LabRoot + [IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase)) { throw 'Path outside lab' }
    [IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($target)) | Out-Null
    [IO.File]::WriteAllText($target, ($Text.Replace('\n', "`n") + "`n"), (New-Object Text.UTF8Encoding($false)))
}
function New-LabRepo([string]$Name) {
    New-Item -ItemType Directory -Path $Name | Out-Null
    Push-Location $Name
    try {
        git init --initial-branch=main
        git config --local user.name 'Repair Lab'
        git config --local user.email 'repair@example.invalid'
        git config --local core.autocrlf false
        git config --local commit.gpgSign false
        git config --local tag.gpgSign false
        git config --local core.hooksPath (Join-Path $script:LabRoot 'empty-hooks')
        Write-LabFile 'notes.md' 'Inspect hinge'
        Write-LabFile 'tasks.txt' 'desk=open'
        git add '--' notes.md tasks.txt
        git commit -m 'Record initial repair plan'
    } finally { Pop-Location }
}
Push-Location $script:LabRoot
try {
    New-LabRepo 'desk'
    Set-Location desk
    git init --bare --initial-branch=main ../shared.git
    git remote add origin ../shared.git
    git push -u origin main
    $expected = git rev-parse origin/main
    git clone ../shared.git ../writer
    git -C ../writer config user.name 'Repair Lab'
    git -C ../writer config user.email 'repair@example.invalid'
    Push-Location ../writer
    try {
        Write-LabFile 'concurrent.txt' 'Another writer was here'
        git add '--' 'concurrent.txt'
        git commit -m 'Record concurrent update'
        git push origin main
    } finally { Pop-Location }
    git commit --amend -m 'Rewrite private teaching root'
    Expect-GitFailure push "--force-with-lease=refs/heads/main:$expected" origin main
    Assert-Equal (git --git-dir=../shared.git show main:concurrent.txt) @('Another writer was here')
    Write-Output 'Verified: force-with-lease'
} finally { Pop-Location }

Focus on the lesson commands

This excerpt omits the seed repository and guard helpers. Use the complete download to run it.

Lesson excerpt

git init --bare --initial-branch=main ../shared.git
git remote add origin ../shared.git
git push -u origin main
$expected = git rev-parse origin/main
git clone ../shared.git ../writer
git -C ../writer config user.name 'Repair Lab'
git -C ../writer config user.email 'repair@example.invalid'
Push-Location ../writer
try {
    Write-LabFile 'concurrent.txt' 'Another writer was here'
    git add '--' 'concurrent.txt'
    git commit -m 'Record concurrent update'
    git push origin main
} finally { Pop-Location }
git commit --amend -m 'Rewrite private teaching root'
Expect-GitFailure push "--force-with-lease=refs/heads/main:$expected" origin main
Assert-Equal (git --git-dir=../shared.git show main:concurrent.txt) @('Another writer was here')

Expected result

The stale lease refuses the rewrite and the remote keeps concurrent.txt.

The complete script ends with Verified: force-with-lease only after its checks pass. Object IDs, temporary paths and progress output can differ.

An explicit expected object ID states what you reviewed. A bare --force-with-lease can depend on remote-tracking refs updated by background fetches, so understand that difference. Even a successful lease is not proof that every collaborator approved the rewrite.

Advertisements