File: install-pdm.ps1

package info (click to toggle)
pdm 2.26.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,664 kB
  • sloc: python: 26,438; sh: 314; javascript: 34; makefile: 26
file content (400 lines) | stat: -rwxr-xr-x 11,402 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
#!/usr/bin/env pwsh
<#
.SYNOPSIS
    PDM Installer Script for Windows
    Downloads and installs PDM from GitHub released binaries

.DESCRIPTION
    This script downloads PDM binaries from GitHub releases, verifies checksums,
    and installs PDM on Windows systems.

.PARAMETER Version
    Specify the version to be installed (default: latest)

.PARAMETER InstallPath
    Specify the installation directory (default: $env:LOCALAPPDATA\Programs\pdm)

.PARAMETER SkipAddToPath
    Do not add binary to the PATH

.PARAMETER SkipChecksum
    Skip checksum verification

.EXAMPLE
    .\install-pdm.ps1
    Install latest version of PDM

.EXAMPLE
    .\install-pdm.ps1 -Version "2.26.1"
    Install specific version of PDM

.EXAMPLE
    .\install-pdm.ps1 -InstallPath "C:\Tools\pdm"
    Install to custom location

.EXAMPLE
    .\install-pdm.ps1 -SkipChecksum
    Skip checksum verification
#>

[CmdletBinding()]
param(
    [string]$Version = $env:PDM_VERSION,
    [string]$InstallPath = $env:PDM_HOME,
    [switch]$SkipAddToPath = [bool]$env:PDM_SKIP_ADD_TO_PATH,
    [switch]$SkipChecksum = [bool]$env:PDM_SKIP_CHECKSUM
)

# Set strict mode
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

# Configuration
$Repo = if ($env:PDM_REPO) { $env:PDM_REPO } else { "pdm-project/pdm" }
$DefaultInstallPath = "$env:LOCALAPPDATA\Programs\pdm"

# Color output - Use Windows-friendly approach
function Write-ColorOutput {
    param(
        [string]$Text,
        [string]$Color = "Cyan",
        [switch]$Bold
    )

    # Use PSStyle if available (PowerShell 7.2+)
    if (Get-Variable -Name PSStyle -ErrorAction SilentlyContinue) {
        $colorCode = switch ($Color) {
            "Green" { $PSStyle.Foreground.Green }
            "Yellow" { $PSStyle.Foreground.Yellow }
            "Cyan" { $PSStyle.Foreground.Cyan }
            "Red" { $PSStyle.Foreground.Red }
            default { $PSStyle.Foreground.Cyan }
        }

        if ($Bold) {
            Write-Host "${colorCode}$($PSStyle.Bold)$Text$($PSStyle.Reset)" -NoNewline
        } else {
            Write-Host "${colorCode}$Text$($PSStyle.Reset)" -NoNewline
        }
    } else {
        # Fallback to no colors for older PowerShell
        Write-Host $Text -NoNewline
    }
}

function Write-PDMLog {
    param([string]$Message)
    Write-ColorOutput -Text "PDM: " -Color Green -Bold
    Write-ColorOutput -Text $Message -Color Cyan
    Write-Host
}

function Write-PDMWarning {
    param([string]$Message)
    Write-ColorOutput "Warning: " -Color Yellow
    Write-Host $Message
}

function Write-PDMError {
    param([string]$Message)
    Write-ColorOutput "Error: " -Color Red
    Write-Host $Message
    exit 1
}

# Detect Windows platform and architecture
function Get-Platform {
    $arch = $env:PROCESSOR_ARCHITECTURE

    switch ($arch) {
        "AMD64" { $archName = "x86_64" }
        "ARM64" { $archName = "aarch64" }
        "x86" { $archName = "i686" }
        default { Write-PDMError "Unsupported architecture: $arch" }
    }

    # Windows target triple
    return "${archName}-pc-windows-msvc"
}

# Get the download URL from GitHub API
function Get-DownloadUrl {
    param(
        [string]$Version,
        [string]$Platform
    )

    $headers = @{}
    if ($env:GITHUB_TOKEN) {
        $headers["Authorization"] = "token $env:GITHUB_TOKEN"
    }

    if ($Version -eq "latest" -or -not $Version) {
        $apiUrl = "https://api.github.com/repos/$Repo/releases/latest"
    } else {
        $apiUrl = "https://api.github.com/repos/$Repo/releases/tags/$Version"
    }

    try {
        $releaseInfo = Invoke-RestMethod -Uri $apiUrl -Headers $headers
    } catch {
        Write-PDMError "Failed to fetch release info: $_"
    }

    # Find the asset matching our platform
    $pattern = "pdm-.*-$Platform\.tar\.gz"
    $asset = $releaseInfo.assets | Where-Object { $_.name -match $pattern } | Select-Object -First 1

    if (-not $asset) {
        Write-PDMError "No binary found for platform $Platform"
    }

    return $asset.browser_download_url
}

# Download a file with progress
function Invoke-Download {
    param(
        [string]$Url,
        [string]$OutputPath
    )

    Write-PdmLog "Downloading from $Url"

    try {
        # Use Invoke-WebRequest with progress
        $progressPreference = 'Continue'
        Invoke-WebRequest -Uri $Url -OutFile $OutputPath -UseBasicParsing
        $progressPreference = 'SilentlyContinue'
    } catch {
        Write-PDMError "Download failed: $_"
    }
}

# Verify checksum using PowerShell's Get-FileHash
function Test-Checksum {
    param(
        [string]$ChecksumFile,
        [string]$FilePath
    )

    if ($SkipChecksum) {
        Write-PDMLog "Checksum verification skipped (--skip-checksum)"
        return $true
    }

    if (-not (Test-Path $ChecksumFile)) {
        Write-PDMLog "No checksum file found. Skipping verification."
        return $true
    }

    Write-PDMLog "Verifying checksum..."

    # Read expected checksum
    $expectedChecksum = (Get-Content $ChecksumFile -Raw).Trim().Split()[0]

    if (-not $expectedChecksum) {
        Write-PDMLog "No checksum found in file. Skipping verification."
        return $true
    }

    # Calculate actual checksum
    $actualChecksum = (Get-FileHash -Path $FilePath -Algorithm SHA256).Hash.ToLower()
    $expectedChecksum = $expectedChecksum.ToLower()

    if ($expectedChecksum -eq $actualChecksum) {
        Write-PDMLog "Checksum verification passed."
        return $true
    } else {
        Write-PDMError "Checksum verification failed!`nExpected: $expectedChecksum`nActual:   $actualChecksum"
    }
}

# Extract tar.gz archive
function Expand-TarGz {
    param(
        [string]$ArchivePath,
        [string]$DestinationPath
    )

    Write-PDMLog "Extracting to $DestinationPath"

    # Check if tar is available (Git for Windows, WSL, etc.)
    $tar = Get-Command tar -ErrorAction SilentlyContinue
    if ($tar) {
        try {
            & $tar -xzf $ArchivePath -C $DestinationPath
            return
        } catch {
            Write-PDMWarning "tar extraction failed, trying alternative method"
        }
    }

    # Fallback: Extract in memory using .NET
    try {
        Add-Type -AssemblyName System.IO.Compression.FileSystem

        # This is a simple approach - for tar.gz we'd need more complex handling
        # Since PDM ships as .tar.gz, we'll use the windows tar if available
        # or suggest installing it
        Write-PDMError "This script requires 'tar' to extract .tar.gz files. Please install Git for Windows or Windows Subsystem for Linux."
    } catch {
        Write-PDMError "Failed to extract archive: $_"
    }
}

# Add directory to PATH in registry
function Add-ToPath {
    param([string]$BinPath)

    if ($SkipAddToPath) {
        Write-PDMLog "Skipping PATH modification (--skip-add-to-path)"
        return
    }

    Write-PDMLog "Adding $BinPath to user PATH..."

    try {
        $regPath = "Registry::HKEY_CURRENT_USER\Environment"
        $currentPath = (Get-ItemProperty -Path $regPath -Name PATH -ErrorAction SilentlyContinue).PATH

        # Check if already in PATH
        if ($currentPath -and $currentPath -split ';' -contains $BinPath) {
            Write-PDMLog "Already in PATH"
            return
        }

        # Add to PATH
        if ($currentPath) {
            $newPath = $currentPath + ";" + $BinPath
        } else {
            $newPath = $BinPath
        }

        Set-ItemProperty -Path $regPath -Name PATH -Value $newPath

        Write-Host
        Write-ColorOutput -Color Yellow -Text "Note: "
        Write-ColorOutput -Color Cyan -Text "Please restart your terminal or run:"
        Write-Host "    `$env:PATH = '$BinPath;' + `$env:PATH"
        Write-Host
    } catch {
        Write-PDMWarning "Failed to add to PATH: $_"
        Write-PDMLog "Please manually add '$BinPath' to your PATH"
    }
}

# Verify PDM installation
function Test-PdmInstall {
    param([string]$PdmPath)

    Write-PDMLog "Verifying installation..."

    if (-not (Test-Path $PdmPath)) {
        Write-PDMError "PDM binary not found at $PdmPath"
    }

    try {
        $versionOutput = & $PdmPath --version 2>&1
        if ($LASTEXITCODE -eq 0) {
            return $versionOutput
        } else {
            Write-PDMError "PDM verification failed: $versionOutput"
        }
    } catch {
        Write-PDMError "PDM verification failed: $_"
    }
}

# Main installation function
function Install-Pdm {
    Write-ColorOutput -Color Green -Bold -Text "PDM Installer for Windows"
    Write-Host

    # Detect platform
    $platform = Get-Platform
    Write-PDMLog "Detected platform: $platform"

    # Get download URL
    $downloadUrl = Get-DownloadUrl -Version $Version -Platform $platform
    Write-PDMLog "Download URL: $downloadUrl"

    # Determine install directory
    if (-not $InstallPath) {
        $InstallPath = $DefaultInstallPath
    }
    Write-PDMLog "Install directory: $InstallPath"

    # Create temp directory
    $tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ([System.IO.Path]::GetRandomFileName())
    New-Item -ItemType Directory -Path $tempDir -Force | Out-Null

    try {
        # Download files
        $archivePath = Join-Path $tempDir "pdm.tar.gz"
        $checksumPath = Join-Path $tempDir "pdm.tar.gz.sha256"

        # Download checksum first (optional)
        if (-not $SkipChecksum) {
            try {
                Invoke-Download -Url "$downloadUrl.sha256" -OutputPath $checksumPath
            } catch {
                Write-PDMLog "No checksum file available, skipping verification"
                $SkipChecksum = $true
            }
        }

        # Download binary
        Invoke-Download -Url $downloadUrl -OutputPath $archivePath

        # Verify checksum if available
        if ((Test-Path $checksumPath) -and -not $SkipChecksum) {
            if (-not (Test-Checksum -ChecksumFile $checksumPath -FilePath $archivePath)) {
                return
            }
        }

        # Extract archive
        Expand-TarGz -ArchivePath $archivePath -DestinationPath $tempDir

        # Find and copy binary
        $binary = Get-ChildItem -Path $tempDir -Filter "pdm.exe" -Recurse | Select-Object -First 1
        if (-not $binary) {
            Write-PDMError "PDM binary not found in archive"
        }

        # Create install directory
        $binPath = Join-Path $InstallPath "bin"
        $null = New-Item -ItemType Directory -Path $binPath -Force

        # Copy binary
        $pdmPath = Join-Path $binPath "pdm.exe"
        Copy-Item -Path $binary.FullName -Destination $pdmPath -Force

        Write-PDMLog "Successfully installed PDM"

        # Verify installation
        $version = Test-PdmInstall -PdmPath $pdmPath
        Write-Host
        Write-ColorOutput -Color Green -Bold -Text "Successfully installed: "
        Write-ColorOutput -Color Green -Text "PDM"
        Write-ColorOutput -Color Yellow -Text " ($version)"
        Write-ColorOutput -Color Cyan -Text " at "
        Write-ColorOutput -Color Green -Text $pdmPath
        Write-Host

        # Add to PATH
        Add-ToPath -BinPath $binPath

        Write-PDMLog "Installation completed successfully!"

    } finally {
        # Cleanup
        if (Test-Path $tempDir) {
            Remove-Item -Path $tempDir -Recurse -Force
        }
    }
}

# Run installation
Install-Pdm