diff --git a/ApiGit/Mirrors/CheckGitlabCommits.ps1 b/ApiGit/Mirrors/CheckGitlabCommits.ps1 index 0c2f401..3cb34e8 100644 --- a/ApiGit/Mirrors/CheckGitlabCommits.ps1 +++ b/ApiGit/Mirrors/CheckGitlabCommits.ps1 @@ -15,7 +15,7 @@ $mainStopWatch = [system.diagnostics.stopwatch]::StartNew() #contatore ciclo do while $projectCount = 1 #numero massimo di progetti da analizzare -$projectNumber = 250 +$projectNumber = 300 #conteggio progetti trovati $projectsFound = 0 #conteggio progetti con commit negli ultimi giorni diff --git a/ApiGit/Mirrors/CheckGitlabMirroring.ps1 b/ApiGit/Mirrors/CheckGitlabMirroring.ps1 index 24ab53a..7882040 100644 --- a/ApiGit/Mirrors/CheckGitlabMirroring.ps1 +++ b/ApiGit/Mirrors/CheckGitlabMirroring.ps1 @@ -15,7 +15,7 @@ $mainStopWatch = [system.diagnostics.stopwatch]::StartNew() #contatore ciclo do while $projectCount = 1 #numero massimo di progetti da analizzare -$projectNumber = 300 +$projectNumber = 250 #conteggio progetti trovati $existingProjects = 0 #conteggio mirroring in errore @@ -58,12 +58,12 @@ do { $parsedResponse = $Response.Content | ConvertFrom-Json #scrivo il numero del progetto nel terminale e su file foreach ($item in $parsedResponse) { - #verifico se i mirroring trovati per il progetto corrente hanno status "finished" + #verifico se i mirroring trovati per il progetto corrente hanno status "finished" e scrivo log if ($item.update_status.Equals("finished")) { WriteLogOutput $logFile 2 "Mirror: $($item.url) - Status: $($item.update_status) - Last Success: $($item.last_successful_update_at)" $mirrorSuccessCount = $mirrorSuccessCount + 1 } - #i mirroring che non hanno status "finished" vengono loggati con relativo errore + #per i mirroring che non hanno status "finished" scrivo log con relativo errore else { WriteLogOutput $logFile 1 "Mirror: $($item.url) - Status: $($item.update_status) - Last Success: $($item.last_successful_update_at) - Last Attempt: $($item.last_update_started_at)" WriteLogOutput $logFile 1 "Error: $($item.last_error)" diff --git a/ApiGit/Mirrors/GitlabCreateMissingMirrors.ps1 b/ApiGit/Mirrors/GitlabCreateMissingMirrors.ps1 index 5a302e8..601f995 100644 --- a/ApiGit/Mirrors/GitlabCreateMissingMirrors.ps1 +++ b/ApiGit/Mirrors/GitlabCreateMissingMirrors.ps1 @@ -17,7 +17,7 @@ $projectCount = 200 #numero massimo di progetti da analizzare $projectNumber = 250 #nome file di log -$logFile = "GiteaNewMirrors.log" +$logFile = "NewMirrorsCreation.log" #creazione folder di Log se non già esistente if (Test-Path $logFolder) { diff --git a/ApiGit/Mirrors/GitlabForcePushMirror.ps1 b/ApiGit/Mirrors/GitlabForcePushMirror.ps1 index 5bc7b04..d15eaba 100644 --- a/ApiGit/Mirrors/GitlabForcePushMirror.ps1 +++ b/ApiGit/Mirrors/GitlabForcePushMirror.ps1 @@ -14,7 +14,7 @@ $mainStopWatch = [system.diagnostics.stopwatch]::StartNew() #contatore ciclo do while $projectCount = 1 #numero massimo di progetti -$projectNumber = 250 +$projectNumber = 300 #conteggio progetti trovati $existingProjects = 0 #contatore mirror trovati diff --git a/ApiGit/Misc/CheckGitlabProtectedBranches.ps1 b/ApiGit/Misc/CheckGitlabProtectedBranches.ps1 index 1ababd4..1fb19c5 100644 --- a/ApiGit/Misc/CheckGitlabProtectedBranches.ps1 +++ b/ApiGit/Misc/CheckGitlabProtectedBranches.ps1 @@ -13,7 +13,7 @@ $startTime = (Get-Date).toString("yyyy/MM/dd HH:mm:ss") # avvio stopwatch $mainStopWatch = [system.diagnostics.stopwatch]::StartNew() #contatore ciclo do while -$projectCount = 200 +$projectCount = 1 #numero massimo di progetti da analizzare $projectNumber = 300 #conteggio progetti trovati @@ -25,19 +25,6 @@ $deleteProtection = 1 #nome file di log $logFile = "GitlabProtectedBranches.log" -#specifica quale installazione di gitlab va controllata -$remote = "Nembro" -#$remote = "Azzano" - -if ($remote -eq "Nembro"){ -$gitlabIstance = $destinationNembro -$head = $nembroHead -} -if ($remote -eq "Azzano"){ -$gitlabIstance = $destinationAzzano -$head = $azzanoHead -} - #creazione folder di Log se non già esistente if (Test-Path $logFolder) { } @@ -60,42 +47,62 @@ WriteLogOutput $logFile 0 "Inizio Esecuzione Script: $startTime" WriteLogOutput $logFile 0 "" WriteLogOutput $logFile 0 "Gitlab di Destinazione: $gitlabIstance" -#ciclo principale do/while che cicla da 1 a N projectNumber -do { - #chiamata api che restituisce informazioni sullo stato dei mirror - $callUrl = "https://" + $gitlabIstance + "/api/v4/projects/" + $projectCount + "/protected_branches" - try { - #parsing della risposta api convertita da json - $Response = Invoke-WebRequest -URI $callUrl -Headers $head -ContentType "application/json" -UseBasicParsing - $parsedResponse = $Response.Content | ConvertFrom-Json - #scrivo il numero del progetto - WriteLogOutput $logFile 1 "" - WriteLogOutput $logFile 1 "--------------------" - WriteLogOutput $logFile 1 "**PROGETTO $projectCount**" - foreach ($item in $parsedResponse) { - WriteLogOutput $logFile 1 "Protected Branch Name: $($item.name) - Allow Force Push: $($item.allow_force_push)" - $protectedProjects = $protectedProjects + 1 - if ($deleteProtection -eq 1) { - #nuovo URL x delete - $callUrlDelete = "https://" + $gitlabIstance + "/api/v4/projects/" + $projectCount + "/protected_branches/" + $item.name - #chiamo method DELETE - Invoke-WebRequest -Method Delete -URI $callUrlDelete -Headers $head -ContentType "application/json" -UseBasicParsing +#specifica quale installazione di gitlab va controllata +#$remote = "Nembro" +#$remote = "Azzano" + +$locations = @('Nembro','Azzano') + +#ciclo for per lavorare su gitlab nembro e poi su gitlab azzano +for ( $i = 0; $i -le 1; $i++) +{ + $projectCount = 1 + $remote = $locations[$i] + if ($remote -eq "Nembro"){ + $gitlabIstance = $destinationNembro + $head = $nembroHead + } + if ($remote -eq "Azzano"){ + $gitlabIstance = $destinationAzzano + $head = $azzanoHead + } + #ciclo principale do/while che cicla da 1 a N projectNumber + do { + #chiamata api che restituisce informazioni sullo stato dei mirror + $callUrl = "https://" + $gitlabIstance + "/api/v4/projects/" + $projectCount + "/protected_branches" + try { + #parsing della risposta api convertita da json + $Response = Invoke-WebRequest -URI $callUrl -Headers $head -ContentType "application/json" -UseBasicParsing + $parsedResponse = $Response.Content | ConvertFrom-Json + #scrivo il numero del progetto + WriteLogOutput $logFile 1 "" + WriteLogOutput $logFile 1 "--------------------" + WriteLogOutput $logFile 1 "**PROGETTO $projectCount**" + foreach ($item in $parsedResponse) { + WriteLogOutput $logFile 1 "Protected Branch Name: $($item.name) - Allow Force Push: $($item.allow_force_push)" + $protectedProjects = $protectedProjects + 1 + if ($deleteProtection -eq 1) { + #nuovo URL x delete + $callUrlDelete = "https://" + $gitlabIstance + "/api/v4/projects/" + $projectCount + "/protected_branches/" + $item.name + #chiamo method DELETE + Invoke-WebRequest -Method Delete -URI $callUrlDelete -Headers $head -ContentType "application/json" -UseBasicParsing + } } + $existingProjects = $existingProjects + 1 } - $existingProjects = $existingProjects + 1 + #scrivo se trovo un errore durante il try/catch + catch { + $parsedError = $_ | ConvertFrom-Json + WriteLogOutput $logFile 3 "" + WriteLogOutput $logFile 3 "--------------------" + WriteLogOutput $logFile 3 "**ERRORE NEL PROGETTO $projectCount**" + WriteLogOutput $logFile 3 $($parsedError.message) + } + $projectCount = $projectCount + 1 } - #scrivo se trovo un errore durante il try/catch - catch { - $parsedError = $_ | ConvertFrom-Json - WriteLogOutput $logFile 3 "" - WriteLogOutput $logFile 3 "--------------------" - WriteLogOutput $logFile 3 "**ERRORE NEL PROGETTO $projectCount**" - WriteLogOutput $logFile 3 $($parsedError.message) - } - $projectCount = $projectCount + 1 + #fine ciclo principale + while ($projectCount -le $projectNumber) } -#fine ciclo principale -while ($projectCount -le $projectNumber) # fermo stopwatch e calcolo durata script $mainStopWatch.Stop() diff --git a/ApiGit/ReposCreation/ReposCreationAzzanoNembro.ps1 b/ApiGit/ReposCreation/ReposCreationAzzanoNembro.ps1 index 591e95f..955c725 100644 --- a/ApiGit/ReposCreation/ReposCreationAzzanoNembro.ps1 +++ b/ApiGit/ReposCreation/ReposCreationAzzanoNembro.ps1 @@ -15,13 +15,13 @@ $mainStopWatch = [system.diagnostics.stopwatch]::StartNew() #contatore ciclo do while $projectCount = 200 #numero massimo di progetti da analizzare (messo a 1 per "sicura inserita" siccome questo script è potenzialmente pericoloso) -$projectNumber = 300 +$projectNumber = 250 #nome file di log $logFile = "AzzanoNembroReposCreation.log" #specifica quale installazione di gitlab va controllata -$remote = "Nembro" -#$remote = "Azzano" +#$remote = "Nembro" +$remote = "Azzano" if ($remote -eq "Nembro"){ $gitlabIstance = $destinationNembro diff --git a/GitLocalUtils/CheckLocalGitStatus.ps1 b/GitLocalUtils/CheckLocalGitStatus.ps1 new file mode 100644 index 0000000..820725b --- /dev/null +++ b/GitLocalUtils/CheckLocalGitStatus.ps1 @@ -0,0 +1,130 @@ +# CheckLocalGitStatus +# +# Verifica di un set di repo GIT locali rispetto al server origin remoto +# per stabilire quali necessitino di aggiornamento +# +# esempio chiamata: + +# parametri in ingresso +param ( + [string]$RootPath = "C:\Users\samuele.steamw\source", # Default alla cartella dei sorgenti, da passare invocando il comando + [switch]$SwitchToMain, + [string]$OutputFile = "$PSScriptRoot\outdated_repos.txt", + [switch]$Help +) + +$branchesToCheck = @("main", "master") +$outdatedRepos = @() + +# Mostra help message se --help or -h passato come argomento +if ($Help -or $args -contains "--help" -or $args -contains "-h") { + Write-Host @" +Usage: .\Check-GitRepos.ps1 [-RootPath ] [-SwitchToMain] [-OutputFile ] [--help] + +Checks all Git repositories under the specified folder and compares their main/master branch +with the remote origin. Optionally switches to main/master to perform the check. + +Parameters: + -RootPath Path to the root folder containing Git repositories (default: current script path) + -SwitchToMain Temporarily switch to main/master branch to perform the check + -OutputFile Path to the output file listing outdated repositories + --help, -h Show this help message + +Examples: + .\Check-GitRepos.ps1 -RootPath "D:\Dev\Projects" + .\Check-GitRepos.ps1 -SwitchToMain + .\Check-GitRepos.ps1 -RootPath "C:\Code" -SwitchToMain -OutputFile "C:\outdated.txt" +"@ -ForegroundColor Cyan + exit +} + + +# Function to check Git status +function Check-GitStatus { + param ( + [string]$repoPath, + [string]$OutputFile + ) + + Write-Host "`nChecking repository at: $repoPath" -ForegroundColor Cyan + Push-Location $repoPath + + if (-not (Test-Path ".git")) { + Write-Host "Not a Git repository." -ForegroundColor Yellow + "$((Get-Date).ToString('yyyy-MM-dd HH:mm:ss')) - Not a Git repository." | Out-File -FilePath $OutputFile -Append -Encoding UTF8 + Pop-Location + return + } + + git fetch origin *> $null 2>&1 + + $originalBranch = git rev-parse --abbrev-ref HEAD 2>$null + + $remoteBranches = git ls-remote --heads origin | ForEach-Object { + ($_ -split "\s+")[1] -replace "refs/heads/", "" + } + + $targetBranch = $branchesToCheck | Where-Object { $remoteBranches -contains $_ } | Select-Object -First 1 + + if (-not $targetBranch) { + $message = "$((Get-Date).ToString('yyyy-MM-dd HH:mm:ss')) - MISSING | $repoPath No 'main' or 'master' branch found on remote." + Write-Host $message -ForegroundColor Red + $message | Out-File -FilePath $OutputFile -Append -Encoding UTF8 + Pop-Location + return + } + + if ($SwitchToMain -and $originalBranch -ne $targetBranch) { + git stash push -u -m "Temp stash before switching branches" *> $null 2>&1 + git checkout $targetBranch *> $null 2>&1 + } + + $status = git status -sb 2>$null + $aheadBehind = git rev-list --left-right --count origin/$targetBranch...HEAD 2>$null + + if ($aheadBehind) { + $parts = $aheadBehind -split "`t" + $behind = [int]$parts[0] + $ahead = [int]$parts[1] + + if ($ahead -gt 0 -or $behind -gt 0) { + $message = "$((Get-Date).ToString('yyyy-MM-dd HH:mm:ss')) - UPDATE | $repoPath is not up to date with origin/$targetBranch (ahead: $ahead, behind: $behind)" + Write-Host $message -ForegroundColor Yellow + $message | Out-File -FilePath $OutputFile -Append -Encoding UTF8 + $script:hasOutdated = $true + } else { + Write-Host "✅ Repo is up to date with origin/$targetBranch" -ForegroundColor Green + } + } + + if ($SwitchToMain -and $originalBranch -ne $targetBranch) { + git checkout $originalBranch *> $null 2>&1 + git stash pop *> $null 2>&1 + } + + Pop-Location +} + +# Get all subdirectories containing .git folders +$repos = Get-ChildItem -Path $RootPath -Recurse -Directory | Where-Object { + Test-Path "$($_.FullName)\.git" +} + +# Clear or create output file +"" | Out-File -FilePath $OutputFile -Encoding UTF8 +$script:hasOutdated = $false + +# Check each repository +foreach ($repo in $repos) { + Check-GitStatus -repoPath $repo.FullName -OutputFile $OutputFile +} + +# Final summary +if ($script:hasOutdated) { + Write-Host "`n📄 Outdated repositories saved to: $OutputFile" -ForegroundColor Cyan +} else { + $msg = "🎉 All repositories are up to date!" + Write-Host "`n$msg" -ForegroundColor Green + $msg = "$((Get-Date).ToString('yyyy-MM-dd HH:mm:ss')) - 🎉 All repositories are up to date!" + $msg | Out-File -FilePath $OutputFile -Append -Encoding UTF8 +}