clear-target-dir-if-larger-than.ps1

 1param (
 2    [Parameter(Mandatory = $true)]
 3    [int]$MAX_SIZE_IN_GB,
 4    [Parameter(Mandatory = $false)]
 5    [int]$SMALL_CLEAN_SIZE_IN_GB = -1
 6)
 7
 8$ErrorActionPreference = "Stop"
 9$PSNativeCommandUseErrorActionPreference = $true
10$ProgressPreference = "SilentlyContinue"
11
12if (-Not (Test-Path -Path "target")) {
13    Write-Host "target directory does not exist yet"
14    exit 0
15}
16
17if ($SMALL_CLEAN_SIZE_IN_GB -ge 0 -and $SMALL_CLEAN_SIZE_IN_GB -ge $MAX_SIZE_IN_GB) {
18    Write-Host "error: small clean threshold (${SMALL_CLEAN_SIZE_IN_GB}GB) must be smaller than max size (${MAX_SIZE_IN_GB}GB)"
19    exit 1
20}
21
22$current_size_gb = (Get-ChildItem -Recurse -Force -File -Path "target" | Measure-Object -Property Length -Sum).Sum / 1GB
23
24Write-Host "target directory size: ${current_size_gb}GB. max size: ${MAX_SIZE_IN_GB}GB"
25
26if ($current_size_gb -gt $MAX_SIZE_IN_GB) {
27    Write-Host "clearing target directory"
28    Remove-Item -Recurse -Force -Path "target\*" -ErrorAction SilentlyContinue
29} elseif ($SMALL_CLEAN_SIZE_IN_GB -ge 0 -and $current_size_gb -gt $SMALL_CLEAN_SIZE_IN_GB) {
30    Write-Host "running cargo clean --workspace (size above small clean threshold of ${SMALL_CLEAN_SIZE_IN_GB}GB)"
31    cargo clean --workspace
32}