Skip to main content
1 of 2

Create release package from git tag with powershell?

In my deployment I need to generate a zip file from a git repo

I have the basic work done with how to pull the latest tag and create the zip file. I ended wanting to update the files that are pulled down to have the last modified of the last commit instead of when I just checked them out.

the script

# Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
param(
    [string] $tag = "",
    [string] $gitURI = "https://github.com/jquery/jquery.git",
    [string] $checkForNewTagsOnly = "Y" #if yes then it will exit if the folder already exists
)
$Currentlocation = "C:\_Builds"
New-Item -ItemType Directory -Force -Path $Currentlocation

Set-Location $Currentlocation
if( $checkForNewTagsOnly -eq "Y"){
    git clone $gitURI --depth 1 master --single-branch
    Set-Location $Currentlocation\master
    git fetch --tags
    $tag = git describe --tags $(git rev-list --tags --max-count=1)
    $tag = $tag|split-path -leaf
}

if([string]::IsNullOrWhiteSpace($tag)){($tag = Read-Host "Enter the tag")}

if( $checkForNewTagsOnly -eq "Y" -and (Test-path $Currentlocation\$tag)){
    Write-Host "$tag already exists, nothing to do"
    exit
}

New-Item -ItemType Directory -Force -Path $Currentlocation
If (Test-path $Currentlocation\$tag) {Remove-item $Currentlocation\$tag}

Set-Location $Currentlocation
git clone $gitURI --recurse-submodules --single-branch --shallow-submodules --branch $tag $tag
Set-Location $Currentlocation\$tag

Write-Host "$tag checked out, running clean up on $Currentlocation"
Get-ChildItem -filter *test* -Directory -recurse -force | remove-item -force -recurse

$ToDelete = "*.gitignore","*.gitattributes","*.gitmodules"
FOREACH ($Item IN $ToDelete) {
    FOREACH ($File IN (Get-ChildItem -recurse | Where-Object {$_.name -like "$Item"})) {
        $FullName = $File.FullName
        Write-Host "Deleting $FullName" -ForegroundColor Green
        Remove-Item $File.FullName
    }
}

Write-Host "fixing the file dates, since git doesn't keep the dates, let's update it the last commit date"
FOREACH ($File IN (Get-ChildItem -recurse)) {
    $FullName = $File.FullName
    $lastModifiedDate = git log -1 --date=short --format=%cd "$FullName"
    $File.LastWriteTime = $lastModifiedDate
    $File.CreationTime = $lastModifiedDate
}

Get-ChildItem -Include .git -recurse -force | remove-item -force -recurse

Write-Host "$tag cleaned, creating zip file"
If (Test-path $Currentlocation\$tag.zip) {Remove-item $Currentlocation\$tag.zip}

Compress-Archive -Path $Currentlocation\$tag -DestinationPath $Currentlocation\$tag.zip

Write-Host "Good Job, the package is created $tag.zip"