191 lines
7.6 KiB
PowerShell
191 lines
7.6 KiB
PowerShell
# ============================================
|
|
# Script de Automação Git para PlatformSistemas
|
|
# Branch: frontend_React
|
|
# Remote: https://git.itguys.com.br/itguys_dev/Workspace
|
|
# ============================================
|
|
# Este script monitora alterações no projeto e realiza commits/push automáticos.
|
|
# Inclui debounce, filtragem inteligente e build automático.
|
|
|
|
# Configurações
|
|
$BRANCH_NAME = "frontend_React"
|
|
$DEBOUNCE_SECONDS = 10 # Aguarda 10 segundos após última alteração antes de commitar
|
|
$BUILD_ENABLED = $true # Define se deve executar build antes do commit
|
|
|
|
# Variáveis de controle de debounce
|
|
$script:LastChangeTime = Get-Date
|
|
$script:PendingChanges = $false
|
|
$script:ChangedFiles = @()
|
|
|
|
# Configuração do FileSystemWatcher
|
|
$Watcher = New-Object IO.FileSystemWatcher
|
|
$Watcher.Path = $PSScriptRoot
|
|
$Watcher.Filter = "*.*"
|
|
$Watcher.IncludeSubdirectories = $true
|
|
$Watcher.EnableRaisingEvents = $true
|
|
$Watcher.NotifyFilter = [System.IO.NotifyFilters]::FileName -bor
|
|
[System.IO.NotifyFilters]::DirectoryName -bor
|
|
[System.IO.NotifyFilters]::LastWrite
|
|
|
|
# Função para verificar se o arquivo deve ser ignorado
|
|
function Test-ShouldIgnoreFile {
|
|
param([string]$FilePath)
|
|
|
|
$ignorePatterns = @(
|
|
"node_modules",
|
|
".git",
|
|
"dist",
|
|
".env",
|
|
".log",
|
|
"package-lock.json",
|
|
".tmp",
|
|
".cache",
|
|
".vscode",
|
|
".idea",
|
|
"*.swp",
|
|
"*~"
|
|
)
|
|
|
|
foreach ($pattern in $ignorePatterns) {
|
|
if ($FilePath -match [regex]::Escape($pattern)) {
|
|
return $true
|
|
}
|
|
}
|
|
|
|
return $false
|
|
}
|
|
|
|
# Função para processar commit e push
|
|
function Invoke-GitSync {
|
|
if (-not $script:PendingChanges) { return }
|
|
|
|
Write-Host "`n========================================" -ForegroundColor Cyan
|
|
Write-Host "Iniciando sincronização Git..." -ForegroundColor Cyan
|
|
Write-Host "========================================" -ForegroundColor Cyan
|
|
|
|
try {
|
|
# Verifica se há alterações para commitar
|
|
$gitStatus = git status --porcelain
|
|
if ([string]::IsNullOrWhiteSpace($gitStatus)) {
|
|
Write-Host "Nenhuma alteração para commitar." -ForegroundColor Yellow
|
|
$script:PendingChanges = $false
|
|
$script:ChangedFiles = @()
|
|
return
|
|
}
|
|
|
|
Write-Host "`nArquivos alterados:" -ForegroundColor Gray
|
|
$script:ChangedFiles | ForEach-Object { Write-Host " - $_" -ForegroundColor DarkGray }
|
|
|
|
# Build de produção (se habilitado)
|
|
if ($BUILD_ENABLED) {
|
|
Write-Host "`nGerando build de produção..." -ForegroundColor Yellow
|
|
$buildOutput = npm run build 2>&1
|
|
if ($LASTEXITCODE -ne 0) {
|
|
Write-Host "Erro no build! Abortando commit." -ForegroundColor Red
|
|
Write-Host $buildOutput -ForegroundColor Red
|
|
return
|
|
}
|
|
Write-Host "Build concluído com sucesso!" -ForegroundColor Green
|
|
}
|
|
|
|
# Git add
|
|
Write-Host "`nAdicionando arquivos ao stage..." -ForegroundColor Yellow
|
|
git add .
|
|
|
|
# Git commit
|
|
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
|
|
$fileCount = ($script:ChangedFiles | Measure-Object).Count
|
|
$commitMessage = "Auto-deploy: $timestamp | $fileCount arquivo(s) alterado(s)"
|
|
|
|
if ($BUILD_ENABLED) {
|
|
$commitMessage += " [Build included]"
|
|
}
|
|
|
|
Write-Host "Criando commit..." -ForegroundColor Yellow
|
|
git commit -m $commitMessage
|
|
|
|
if ($LASTEXITCODE -ne 0) {
|
|
Write-Host "Nada para commitar ou erro no commit." -ForegroundColor Yellow
|
|
$script:PendingChanges = $false
|
|
$script:ChangedFiles = @()
|
|
return
|
|
}
|
|
|
|
# Git push
|
|
Write-Host "Enviando para o repositório remoto (branch: $BRANCH_NAME)..." -ForegroundColor Yellow
|
|
git push origin $BRANCH_NAME
|
|
|
|
if ($LASTEXITCODE -eq 0) {
|
|
Write-Host "`n✓ Sincronização concluída com sucesso!" -ForegroundColor Green
|
|
Write-Host "========================================`n" -ForegroundColor Cyan
|
|
}
|
|
else {
|
|
Write-Host "`n✗ Erro ao fazer push para o repositório remoto!" -ForegroundColor Red
|
|
Write-Host "========================================`n" -ForegroundColor Cyan
|
|
}
|
|
|
|
}
|
|
catch {
|
|
Write-Host "`n✗ Erro ao sincronizar com o Git: $_" -ForegroundColor Red
|
|
Write-Host "========================================`n" -ForegroundColor Cyan
|
|
}
|
|
finally {
|
|
$script:PendingChanges = $false
|
|
$script:ChangedFiles = @()
|
|
}
|
|
}
|
|
|
|
# Action para eventos do FileSystemWatcher
|
|
$Action = {
|
|
$path = $Event.SourceEventArgs.FullPath
|
|
$changeType = $Event.SourceEventArgs.ChangeType
|
|
|
|
# Ignora arquivos/pastas específicos
|
|
if (Test-ShouldIgnoreFile -FilePath $path) { return }
|
|
|
|
# Registra a alteração
|
|
$relativePath = $path.Replace($PSScriptRoot, "").TrimStart("\")
|
|
Write-Host "[$(Get-Date -Format 'HH:mm:ss')] $changeType : $relativePath" -ForegroundColor DarkCyan
|
|
|
|
# Atualiza controle de debounce
|
|
$script:LastChangeTime = Get-Date
|
|
$script:PendingChanges = $true
|
|
|
|
if ($script:ChangedFiles -notcontains $relativePath) {
|
|
$script:ChangedFiles += $relativePath
|
|
}
|
|
}
|
|
|
|
# Registra os eventos
|
|
Register-ObjectEvent $Watcher "Changed" -Action $Action | Out-Null
|
|
Register-ObjectEvent $Watcher "Created" -Action $Action | Out-Null
|
|
Register-ObjectEvent $Watcher "Deleted" -Action $Action | Out-Null
|
|
Register-ObjectEvent $Watcher "Renamed" -Action $Action | Out-Null
|
|
|
|
# Banner inicial
|
|
Write-Host "`n" -NoNewline
|
|
Write-Host "╔════════════════════════════════════════════════════════════╗" -ForegroundColor Green
|
|
Write-Host "║ Git Auto-Sync - PlatformSistemas ║" -ForegroundColor Green
|
|
Write-Host "╠════════════════════════════════════════════════════════════╣" -ForegroundColor Green
|
|
Write-Host "║ Branch: $BRANCH_NAME ║" -ForegroundColor Cyan
|
|
Write-Host "║ Remote: https://git.itguys.com.br/itguys_dev/Workspace ║" -ForegroundColor Cyan
|
|
Write-Host "║ Debounce: $DEBOUNCE_SECONDS segundos ║" -ForegroundColor Cyan
|
|
Write-Host "║ Build automático: $(if($BUILD_ENABLED){'Habilitado'}else{'Desabilitado'}) ║" -ForegroundColor Cyan
|
|
Write-Host "╠════════════════════════════════════════════════════════════╣" -ForegroundColor Green
|
|
Write-Host "║ Status: Monitorando alterações... ║" -ForegroundColor Yellow
|
|
Write-Host "║ Pressione Ctrl+C para parar ║" -ForegroundColor Yellow
|
|
Write-Host "╚════════════════════════════════════════════════════════════╝" -ForegroundColor Green
|
|
Write-Host "`n"
|
|
|
|
# Loop principal com debounce
|
|
while ($true) {
|
|
Start-Sleep -Seconds 1
|
|
|
|
if ($script:PendingChanges) {
|
|
$timeSinceLastChange = (Get-Date) - $script:LastChangeTime
|
|
|
|
if ($timeSinceLastChange.TotalSeconds -ge $DEBOUNCE_SECONDS) {
|
|
Invoke-GitSync
|
|
}
|
|
}
|
|
}
|