updated pipelines zip and gdrive upload

This commit is contained in:
dzaitsev
2025-05-07 18:41:44 +03:00
parent 495268e56a
commit e6ec904657
+97 -116
View File
@@ -1,154 +1,135 @@
pipeline { pipeline {
agent { label 'Win10-BuildMachine' } agent { label 'Win10-BuildMachine' }
parameters {
string(name: 'buildPath', defaultValue: 'C:/Jenkins/workspace/Azaion/suite', description: 'Build directory to zip from')
string(name: 'GOOGLE_DRIVE_FOLDER', defaultValue: 'AzaionSuiteBuilds', description: 'Target folder on Google Drive')
}
tools { tools {
git 'Default' git 'Default'
} }
parameters {
string(name: 'GOOGLE_DRIVE_FOLDER', defaultValue: 'AzaionSuiteBuilds', description: 'The folder on Google Drive where the build will be uploaded.')
string(name: 'buildPath', defaultValue: 'C:/Jenkins/workspace/AzaionSuite/suite', description: 'Path to folder containing zip builds.')
}
environment { environment {
RCLONE_CONFIG = 'C:/Program Files/rclone/rclone.conf' SEVEN_ZIP_PATH = "C:/Program Files/7-Zip"
PATH = "${SEVEN_ZIP_PATH};${env.PATH}"
GOOGLE_DRIVE_UPLOAD_JOB_NAME = 'GDrive Upload'
} }
stages { stages {
stage('Initialize Workspace') { stage('Detect or Create Zip') {
steps {
echo 'Initializing workspace on Windows agent...'
powershell '''
$uploadDir = "temp_upload"
if (-Not (Test-Path $uploadDir)) {
New-Item -ItemType Directory -Path $uploadDir | Out-Null
}
'''
}
}
stage('Find Latest Zip') {
steps { steps {
script { script {
echo "Finding latest zip file in: ${params.buildPath}" echo "Starting 'Detect or Create Zip' stage."
echo "Using build path: ${params.buildPath}"
dir("${params.buildPath}") { dir("${params.buildPath}") {
def output = powershell(returnStdout: true, script: ''' powershell '''
$pattern = "AzaionSuite*-*-*.zip" $ErrorActionPreference = "Stop"
$zipFiles = Get-ChildItem -Filter $pattern | Sort-Object Name -Descending $sevenZipExe = "$env:SEVEN_ZIP_PATH\\7z.exe"
if ($zipFiles.Count -gt 0) { $exePattern = "AzaionSuite*.exe"
$latestZip = $zipFiles[0].Name $binPattern = "AzaionSuite*.bin"
Write-Output "::SET-ENV::LATEST_ZIP_FILENAME=$latestZip" $zipPattern = "AzaionSuite*.zip"
} else {
Write-Output "::SET-ENV::LATEST_ZIP_FILENAME="
}
''').trim()
def match = output =~ /::SET-ENV::LATEST_ZIP_FILENAME=(.+)/ if (-not (Test-Path $sevenZipExe)) {
if (!match || !match[0][1]?.trim()) { Write-Error "7-Zip not found at $sevenZipExe"
echo "⚠️ No ZIP files matching the pattern were found. Skipping upload and cleanup stages." exit 1
env.LATEST_ZIP_FILENAME = '' }
} else {
def zipFileName = match[0][1] $existingZips = Get-ChildItem -Path . -Filter $zipPattern | Sort-Object LastWriteTime -Descending
echo "✅ Latest zip file selected: ${zipFileName}" $zipFilename = ""
env.LATEST_ZIP_FILENAME = zipFileName
} if ($existingZips.Count -gt 0) {
$zipFilename = $existingZips[0].Name
Write-Host "Using existing zip file: $zipFilename"
$wasCreated = $false
} else {
$exeFile = Get-ChildItem -Recurse -Filter $exePattern | Select-Object -First 1
if (-not $exeFile) {
Write-Error "No EXE file found to create zip"
exit 1
}
$zipBaseFilename = $exeFile.BaseName
$timestamp = (Get-Date -Format "yyyyMMdd-HHmmss")
$zipFilename = "$zipBaseFilename-$timestamp.zip"
$filesToZip = Get-ChildItem -Recurse -Include $exePattern, $binPattern | Select-Object -ExpandProperty FullName
if ($filesToZip.Count -eq 0) {
Write-Error "No files found to zip."
exit 1
}
$args = @("a", "-tzip", "$zipFilename") + ($filesToZip | ForEach-Object { "`"$_`"" })
$process = Start-Process -FilePath $sevenZipExe -ArgumentList $args -Wait -NoNewWindow -PassThru
if ($process.ExitCode -ne 0) {
Write-Error "7-Zip failed with code $($process.ExitCode)"
exit $process.ExitCode
}
$wasCreated = $true
Write-Host "Created new zip file: $zipFilename"
}
Set-Content -Path "zipfilename.txt" -Value $zipFilename -Encoding ASCII
Set-Content -Path "zip_was_created.txt" -Value $wasCreated -Encoding ASCII
'''
def zipFilename = readFile('zipfilename.txt').trim()
def zipCreated = readFile('zip_was_created.txt').trim().toBoolean()
echo "Zip filename: ${zipFilename}"
echo "Was zip created this run? ${zipCreated}"
writeFile file: 'created_zip.txt', text: zipFilename
writeFile file: 'zip_was_created.txt', text: zipCreated.toString()
} }
} }
} }
} }
stage('Upload If Not Exists & Always Remove Local') { stage('Archive Zip File (if new)') {
when { when {
expression { return env.LATEST_ZIP_FILENAME?.trim() } expression {
def zipCreated = readFile("${params.buildPath}/zip_was_created.txt").trim().toBoolean()
return zipCreated
}
} }
steps { steps {
echo "Checking Google Drive for existing ZIP and uploading if needed..." script {
powershell """ echo "Archiving newly created zip file..."
\$fileName = "${env.LATEST_ZIP_FILENAME}" dir("${params.buildPath}") {
\$folder = "${params.GOOGLE_DRIVE_FOLDER}" def zipFilename = readFile('created_zip.txt').trim()
\$rcloneRemote = "AzaionGoogleDrive:\$folder" if (!fileExists(zipFilename)) {
\$localFilePath = "${params.buildPath}/\$fileName" error "Zip file '${zipFilename}' not found!"
}
Write-Output "Checking for existing files in: \$rcloneRemote" archiveArtifacts artifacts: "${zipFilename}", fingerprint: true
\$existingFiles = rclone lsf --files-only \$rcloneRemote
Write-Output "Existing files:"
Write-Output \$existingFiles
if (\$existingFiles -match "^\$fileName\$") {
Write-Output "File '\$fileName' already exists on Google Drive. Skipping upload."
} else {
Write-Output "Uploading '\$fileName' to Google Drive..."
rclone copy "\$localFilePath" \$rcloneRemote --progress --drive-chunk-size 64M
Write-Output "Upload complete."
} }
}
if (Test-Path \$localFilePath) {
Remove-Item -Force \$localFilePath
Write-Output "Local file deleted: \$localFilePath"
} else {
Write-Output "Local file already deleted or not found."
}
"""
} }
} }
stage('Cleanup Older Files on Google Drive') { stage('Trigger Google Drive Upload') {
when {
expression { return env.LATEST_ZIP_FILENAME?.trim() }
}
steps { steps {
echo "Cleaning up older files on Google Drive..." script {
powershell """ echo "Triggering Google Drive Upload pipeline: ${env.GOOGLE_DRIVE_UPLOAD_JOB_NAME}"
Write-Output "Listing all files in the folder ${params.GOOGLE_DRIVE_FOLDER} on Google Drive..." build job: env.GOOGLE_DRIVE_UPLOAD_JOB_NAME, parameters: [
\$files = rclone lsf --files-only AzaionGoogleDrive:${params.GOOGLE_DRIVE_FOLDER} string(name: 'buildPath', value: params.buildPath),
Write-Output "Files found on Google Drive:" string(name: 'GOOGLE_DRIVE_FOLDER', value: params.GOOGLE_DRIVE_FOLDER)
Write-Output \$files ]
}
\$filesArray = \$files -split "`n" | Where-Object { \$_ -ne "" }
if (\$filesArray.Count -gt 3) {
\$filesSorted = \$filesArray | Sort-Object -Descending
\$filesToDelete = \$filesSorted | Select-Object -Skip 3
Write-Output "Files to delete (older than 3 latest):"
Write-Output \$filesToDelete
if (\$filesToDelete.Count -gt 0) {
\$tempFile = [System.IO.Path]::GetTempFileName()
\$filesToDelete | Set-Content -Path \$tempFile -Encoding utf8
Write-Output "Contents of temporary delete list file (\$tempFile):"
Get-Content \$tempFile
foreach (\$file in \$filesToDelete) {
Write-Output "Deleting \$file..."
rclone deletefile AzaionGoogleDrive:${params.GOOGLE_DRIVE_FOLDER}/\$file
}
Remove-Item -Path \$tempFile
} else {
Write-Output "No files to delete."
}
} else {
Write-Output "No files found on Google Drive to clean up."
}
"""
} }
} }
} }
post { post {
always { success {
echo 'Executing post-build cleanup...' script {
powershell ''' def zipFilename = readFile("${params.buildPath}/created_zip.txt").trim()
$uploadDir = "temp_upload" echo "Pipeline completed successfully. Final zip: ${zipFilename}"
if (Test-Path $uploadDir) { }
Remove-Item -Recurse -Force $uploadDir
}
'''
} }
failure { failure {
echo 'Pipeline failed. Check logs for details.' echo "Pipeline failed."
} }
} }
} }