feat: Implementa Git Auto-Sync com debounce e build automático
- Adiciona script git-auto-sync.ps1 com monitoramento em tempo real - Implementa debounce de 10 segundos para agrupar alterações - Adiciona build automático antes de commits - Melhora filtragem de arquivos ignorados - Atualiza .gitignore com mais padrões - Adiciona scripts npm para facilitar uso (git:sync e git:sync:nobuild) - Cria documentação completa em GIT-AUTO-SYNC.md - Atualiza README.md com informações do projeto
This commit is contained in:
parent
b5507a6002
commit
86874b7547
|
|
@ -7,11 +7,22 @@ yarn-error.log*
|
|||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# Dependencies
|
||||
node_modules
|
||||
|
||||
# Build outputs
|
||||
dist
|
||||
dist-ssr
|
||||
build
|
||||
*.local
|
||||
|
||||
# Environment variables
|
||||
.env
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
|
|
@ -22,3 +33,22 @@ dist-ssr
|
|||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
*.swp
|
||||
*~
|
||||
|
||||
# OS files
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
|
||||
# Cache and temporary files
|
||||
.cache
|
||||
.tmp
|
||||
.temp
|
||||
*.tmp
|
||||
*.temp
|
||||
|
||||
# Test coverage
|
||||
coverage
|
||||
*.lcov
|
||||
.nyc_output
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,179 @@
|
|||
# Git Auto-Sync - Documentação
|
||||
|
||||
## 📋 Visão Geral
|
||||
|
||||
O **Git Auto-Sync** é um sistema de automação que monitora alterações no projeto PlatformSistemas e realiza commits e push automáticos para o repositório Git remoto.
|
||||
|
||||
## 🎯 Características
|
||||
|
||||
- ✅ **Monitoramento em tempo real** de alterações nos arquivos
|
||||
- ✅ **Debounce inteligente** (aguarda 10 segundos após a última alteração)
|
||||
- ✅ **Build automático** antes de cada commit
|
||||
- ✅ **Filtragem inteligente** de arquivos (ignora node_modules, .git, dist, etc.)
|
||||
- ✅ **Mensagens de commit descritivas** com timestamp e contagem de arquivos
|
||||
- ✅ **Interface visual** com cores e feedback claro
|
||||
|
||||
## 🚀 Como Usar
|
||||
|
||||
### Método 1: Via NPM (Recomendado)
|
||||
|
||||
```bash
|
||||
# Com build automático (padrão)
|
||||
npm run git:sync
|
||||
|
||||
# Sem build automático (mais rápido para desenvolvimento)
|
||||
npm run git:sync:nobuild
|
||||
```
|
||||
|
||||
### Método 2: Via PowerShell Direto
|
||||
|
||||
```powershell
|
||||
# Com build automático
|
||||
.\git-auto-sync.ps1
|
||||
|
||||
# Sem build automático
|
||||
$env:BUILD_ENABLED='false'; .\git-auto-sync.ps1
|
||||
```
|
||||
|
||||
## ⚙️ Configurações
|
||||
|
||||
Você pode ajustar as configurações editando o arquivo `git-auto-sync.ps1`:
|
||||
|
||||
```powershell
|
||||
# Configurações (linhas 10-12)
|
||||
$BRANCH_NAME = "frontend_React" # Branch de destino
|
||||
$DEBOUNCE_SECONDS = 10 # Tempo de espera após última alteração
|
||||
$BUILD_ENABLED = $true # Executar build antes do commit
|
||||
```
|
||||
|
||||
### Parâmetros Configuráveis
|
||||
|
||||
| Parâmetro | Descrição | Valor Padrão |
|
||||
|-----------|-----------|--------------|
|
||||
| `BRANCH_NAME` | Branch do Git para push | `frontend_React` |
|
||||
| `DEBOUNCE_SECONDS` | Segundos de espera após última alteração | `10` |
|
||||
| `BUILD_ENABLED` | Executar build de produção antes do commit | `true` |
|
||||
|
||||
## 📁 Arquivos Ignorados
|
||||
|
||||
O script ignora automaticamente as seguintes pastas/arquivos:
|
||||
|
||||
- `node_modules/`
|
||||
- `.git/`
|
||||
- `dist/`
|
||||
- `.env`
|
||||
- `*.log`
|
||||
- `package-lock.json`
|
||||
- `.tmp/`
|
||||
- `.cache/`
|
||||
- `.vscode/`
|
||||
- `.idea/`
|
||||
- `*.swp`
|
||||
- `*~`
|
||||
|
||||
## 🔄 Fluxo de Trabalho
|
||||
|
||||
1. **Detecção de Alteração**: O script detecta quando um arquivo é modificado, criado, deletado ou renomeado
|
||||
2. **Debounce**: Aguarda 10 segundos para garantir que não há mais alterações pendentes
|
||||
3. **Verificação**: Confirma que há alterações reais para commitar
|
||||
4. **Build** (opcional): Executa `npm run build` para gerar a versão de produção
|
||||
5. **Stage**: Adiciona todos os arquivos alterados (`git add .`)
|
||||
6. **Commit**: Cria um commit com mensagem descritiva
|
||||
7. **Push**: Envia as alterações para o repositório remoto na branch `frontend_React`
|
||||
|
||||
## 📝 Formato das Mensagens de Commit
|
||||
|
||||
```
|
||||
Auto-deploy: 2026-01-13 09:20:45 | 3 arquivo(s) alterado(s) [Build included]
|
||||
```
|
||||
|
||||
- **Timestamp**: Data e hora do commit
|
||||
- **Contagem**: Número de arquivos alterados
|
||||
- **Build**: Indica se o build foi incluído
|
||||
|
||||
## 🛑 Como Parar
|
||||
|
||||
Para interromper o monitoramento, pressione `Ctrl+C` no terminal onde o script está rodando.
|
||||
|
||||
## 🔧 Troubleshooting
|
||||
|
||||
### Erro: "Execution Policy"
|
||||
|
||||
Se você receber um erro sobre política de execução, execute:
|
||||
|
||||
```powershell
|
||||
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
|
||||
```
|
||||
|
||||
### Erro no Build
|
||||
|
||||
Se o build falhar, o commit será abortado automaticamente. Verifique os erros no console e corrija-os antes de tentar novamente.
|
||||
|
||||
### Push Rejeitado
|
||||
|
||||
Se o push for rejeitado (ex: branch desatualizada), você precisará:
|
||||
|
||||
1. Parar o script (`Ctrl+C`)
|
||||
2. Fazer `git pull origin frontend_React`
|
||||
3. Resolver conflitos (se houver)
|
||||
4. Reiniciar o script
|
||||
|
||||
## 🎨 Interface Visual
|
||||
|
||||
O script exibe um banner informativo ao iniciar:
|
||||
|
||||
```
|
||||
╔════════════════════════════════════════════════════════════╗
|
||||
║ Git Auto-Sync - PlatformSistemas ║
|
||||
╠════════════════════════════════════════════════════════════╣
|
||||
║ Branch: frontend_React ║
|
||||
║ Remote: https://git.itguys.com.br/itguys_dev/Workspace ║
|
||||
║ Debounce: 10 segundos ║
|
||||
║ Build automático: Habilitado ║
|
||||
╠════════════════════════════════════════════════════════════╣
|
||||
║ Status: Monitorando alterações... ║
|
||||
║ Pressione Ctrl+C para parar ║
|
||||
╚════════════════════════════════════════════════════════════╝
|
||||
```
|
||||
|
||||
## 📊 Logs e Feedback
|
||||
|
||||
O script fornece feedback visual em tempo real:
|
||||
|
||||
- 🔵 **Azul escuro**: Alterações detectadas
|
||||
- 🟡 **Amarelo**: Processos em andamento
|
||||
- 🟢 **Verde**: Operações bem-sucedidas
|
||||
- 🔴 **Vermelho**: Erros
|
||||
|
||||
## 🔐 Segurança
|
||||
|
||||
- O script **não** commita arquivos sensíveis (`.env`, etc.)
|
||||
- Arquivos temporários e de cache são automaticamente ignorados
|
||||
- O `.gitignore` do projeto é respeitado
|
||||
|
||||
## 📌 Repositório
|
||||
|
||||
- **Remote**: https://git.itguys.com.br/itguys_dev/Workspace
|
||||
- **Branch**: frontend_React
|
||||
|
||||
## 💡 Dicas
|
||||
|
||||
1. **Desenvolvimento rápido**: Use `npm run git:sync:nobuild` para commits mais rápidos durante desenvolvimento
|
||||
2. **Produção**: Use `npm run git:sync` para garantir que o build está sempre atualizado
|
||||
3. **Múltiplas alterações**: O debounce agrupa alterações feitas em sequência em um único commit
|
||||
4. **Monitoramento**: Mantenha o terminal visível para acompanhar o status das sincronizações
|
||||
|
||||
## 🆘 Suporte
|
||||
|
||||
Em caso de problemas:
|
||||
|
||||
1. Verifique se o Git está configurado corretamente
|
||||
2. Confirme que você tem permissões de push na branch `frontend_React`
|
||||
3. Verifique se não há conflitos pendentes no repositório
|
||||
4. Revise os logs no console para identificar erros específicos
|
||||
|
||||
---
|
||||
|
||||
**Última atualização**: 2026-01-13
|
||||
**Versão**: 2.0
|
||||
**Autor**: Antigravity AI
|
||||
258
README.md
258
README.md
|
|
@ -1,73 +1,215 @@
|
|||
# React + TypeScript + Vite
|
||||
# PlatformSistemas
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
Sistema de gestão integrada desenvolvido em React + TypeScript + Vite.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
## 🚀 Repositório
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
- **Remote**: https://git.itguys.com.br/itguys_dev/Workspace
|
||||
- **Branch**: `frontend_React`
|
||||
|
||||
## React Compiler
|
||||
## 📋 Índice
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
- [Início Rápido](#início-rápido)
|
||||
- [Scripts Disponíveis](#scripts-disponíveis)
|
||||
- [Git Auto-Sync](#git-auto-sync)
|
||||
- [Estrutura do Projeto](#estrutura-do-projeto)
|
||||
- [Tecnologias](#tecnologias)
|
||||
- [Desenvolvimento](#desenvolvimento)
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
## 🎯 Início Rápido
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
### Pré-requisitos
|
||||
|
||||
```js
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
- Node.js (v18 ou superior)
|
||||
- npm ou yarn
|
||||
- Git
|
||||
|
||||
// Remove tseslint.configs.recommended and replace with this
|
||||
tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
tseslint.configs.stylisticTypeChecked,
|
||||
### Instalação
|
||||
|
||||
// Other configs...
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```bash
|
||||
# Clone o repositório
|
||||
git clone https://git.itguys.com.br/itguys_dev/Workspace.git
|
||||
cd PlatformSistemas
|
||||
|
||||
# Instale as dependências
|
||||
npm install
|
||||
|
||||
# Configure as variáveis de ambiente
|
||||
cp .env.example .env
|
||||
# Edite o arquivo .env com suas configurações
|
||||
|
||||
# Inicie o servidor de desenvolvimento
|
||||
npm run dev
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
## 📜 Scripts Disponíveis
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
```bash
|
||||
# Desenvolvimento
|
||||
npm run dev # Inicia o servidor de desenvolvimento
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
// Enable lint rules for React
|
||||
reactX.configs['recommended-typescript'],
|
||||
// Enable lint rules for React DOM
|
||||
reactDom.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
# Build
|
||||
npm run build # Gera build de produção
|
||||
npm run preview # Preview do build de produção
|
||||
|
||||
# Qualidade de Código
|
||||
npm run lint # Executa ESLint
|
||||
|
||||
# Git Auto-Sync
|
||||
npm run git:sync # Inicia monitoramento Git com build automático
|
||||
npm run git:sync:nobuild # Inicia monitoramento Git sem build automático
|
||||
```
|
||||
|
||||
## 🔄 Git Auto-Sync
|
||||
|
||||
O **Git Auto-Sync** é um sistema de automação que monitora alterações no projeto e realiza commits/push automáticos.
|
||||
|
||||
### Como Usar
|
||||
|
||||
```bash
|
||||
# Com build automático (recomendado para produção)
|
||||
npm run git:sync
|
||||
|
||||
# Sem build automático (mais rápido para desenvolvimento)
|
||||
npm run git:sync:nobuild
|
||||
```
|
||||
|
||||
### Características
|
||||
|
||||
- ✅ Monitoramento em tempo real de alterações
|
||||
- ✅ Debounce de 10 segundos (agrupa alterações)
|
||||
- ✅ Build automático antes de cada commit
|
||||
- ✅ Filtragem inteligente de arquivos
|
||||
- ✅ Mensagens de commit descritivas
|
||||
|
||||
### Documentação Completa
|
||||
|
||||
Para mais detalhes, consulte [GIT-AUTO-SYNC.md](./GIT-AUTO-SYNC.md)
|
||||
|
||||
## 📁 Estrutura do Projeto
|
||||
|
||||
```
|
||||
PlatformSistemas/
|
||||
├── src/
|
||||
│ ├── components/ # Componentes reutilizáveis
|
||||
│ │ ├── access/ # Componentes de acesso
|
||||
│ │ ├── admin/ # Componentes administrativos
|
||||
│ │ ├── layout/ # Componentes de layout
|
||||
│ │ └── ui/ # Componentes de UI
|
||||
│ ├── features/ # Features do sistema
|
||||
│ │ ├── fleet-v2/ # Gestão de frota
|
||||
│ │ └── ...
|
||||
│ ├── services/ # Serviços e APIs
|
||||
│ ├── hooks/ # Custom hooks
|
||||
│ ├── utils/ # Utilitários
|
||||
│ └── index.css # Estilos globais
|
||||
├── public/ # Arquivos públicos
|
||||
├── docs/ # Documentação
|
||||
├── .env # Variáveis de ambiente
|
||||
├── git-auto-sync.ps1 # Script de automação Git
|
||||
└── package.json # Dependências e scripts
|
||||
```
|
||||
|
||||
## 🛠️ Tecnologias
|
||||
|
||||
### Core
|
||||
- **React 19** - Biblioteca UI
|
||||
- **TypeScript** - Superset JavaScript
|
||||
- **Vite** - Build tool e dev server
|
||||
|
||||
### UI/UX
|
||||
- **TailwindCSS** - Framework CSS
|
||||
- **Radix UI** - Componentes acessíveis
|
||||
- **Framer Motion** - Animações
|
||||
- **Lucide React** - Ícones
|
||||
|
||||
### Estado e Formulários
|
||||
- **Zustand** - Gerenciamento de estado
|
||||
- **React Hook Form** - Formulários
|
||||
- **Zod** - Validação de schemas
|
||||
|
||||
### Roteamento e Requisições
|
||||
- **React Router DOM** - Roteamento
|
||||
- **Axios** - Cliente HTTP
|
||||
|
||||
### Gráficos
|
||||
- **Recharts** - Biblioteca de gráficos
|
||||
|
||||
## 💻 Desenvolvimento
|
||||
|
||||
### Variáveis de Ambiente
|
||||
|
||||
Copie `.env.example` para `.env` e configure:
|
||||
|
||||
```env
|
||||
VITE_API_URL=https://dev.workspace.itguys.com.br/api
|
||||
VITE_APP_NAME=PlatformSistemas
|
||||
```
|
||||
|
||||
### Padrões de Código
|
||||
|
||||
- **Componentes**: Use componentes funcionais com hooks
|
||||
- **Tipagem**: Sempre utilize TypeScript
|
||||
- **Estilos**: Prefira TailwindCSS
|
||||
- **Estado**: Use Zustand para estado global
|
||||
- **Formulários**: Use React Hook Form + Zod
|
||||
|
||||
### ESLint
|
||||
|
||||
O projeto usa ESLint para garantir qualidade de código:
|
||||
|
||||
```bash
|
||||
npm run lint
|
||||
```
|
||||
|
||||
### Estrutura de Componentes
|
||||
|
||||
```tsx
|
||||
// Exemplo de componente
|
||||
import { useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
interface MyComponentProps {
|
||||
title: string
|
||||
onAction?: () => void
|
||||
}
|
||||
|
||||
export function MyComponent({ title, onAction }: MyComponentProps) {
|
||||
const [state, setState] = useState(false)
|
||||
|
||||
return (
|
||||
<div className="p-4">
|
||||
<h2 className="text-xl font-bold">{title}</h2>
|
||||
<Button onClick={onAction}>Ação</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## 🔐 Segurança
|
||||
|
||||
- Nunca commite arquivos `.env` (já está no `.gitignore`)
|
||||
- Use variáveis de ambiente para dados sensíveis
|
||||
- Mantenha dependências atualizadas
|
||||
|
||||
## 📝 Documentação Adicional
|
||||
|
||||
- [Git Auto-Sync](./GIT-AUTO-SYNC.md) - Documentação completa do sistema de automação
|
||||
- [API Report](./RELATORIO_API.md) - Relatório de APIs utilizadas
|
||||
|
||||
## 🤝 Contribuindo
|
||||
|
||||
1. Crie uma branch para sua feature (`git checkout -b feature/MinhaFeature`)
|
||||
2. Faça commit das suas alterações (`git commit -m 'Adiciona MinhaFeature'`)
|
||||
3. Push para a branch (`git push origin feature/MinhaFeature`)
|
||||
4. Abra um Pull Request
|
||||
|
||||
Ou simplesmente use o **Git Auto-Sync** para automação completa! 🚀
|
||||
|
||||
## 📄 Licença
|
||||
|
||||
Este projeto é propriedade da ITGuys.
|
||||
|
||||
---
|
||||
|
||||
**Desenvolvido com ❤️ pela equipe ITGuys**
|
||||
|
|
|
|||
|
|
@ -1,42 +1,190 @@
|
|||
# Script de Automação Git para IntraNet
|
||||
# Este script monitora a pasta atual e realiza git commit/push automaticamente.
|
||||
# ============================================
|
||||
# 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 pastas de controle e log
|
||||
if ($path -match "node_modules" -or $path -match ".git") { return }
|
||||
# Ignora arquivos/pastas específicos
|
||||
if (Test-ShouldIgnoreFile -FilePath $path) { return }
|
||||
|
||||
Write-Host "Alteração detectada em $path ($changeType)" -ForegroundColor Cyan
|
||||
# Registra a alteração
|
||||
$relativePath = $path.Replace($PSScriptRoot, "").TrimStart("\")
|
||||
Write-Host "[$(Get-Date -Format 'HH:mm:ss')] $changeType : $relativePath" -ForegroundColor DarkCyan
|
||||
|
||||
try {
|
||||
Write-Host "Gerando build de produção..." -ForegroundColor Gray
|
||||
npm run build
|
||||
# Atualiza controle de debounce
|
||||
$script:LastChangeTime = Get-Date
|
||||
$script:PendingChanges = $true
|
||||
|
||||
git add .
|
||||
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
|
||||
git commit -m "Auto-deploy: $timestamp (Build included)"
|
||||
git push origin frontend
|
||||
Write-Host "Sincronização concluída com sucesso!" -ForegroundColor Green
|
||||
}
|
||||
catch {
|
||||
Write-Host "Erro ao sincronizar com o Git: $_" -ForegroundColor Red
|
||||
if ($script:ChangedFiles -notcontains $relativePath) {
|
||||
$script:ChangedFiles += $relativePath
|
||||
}
|
||||
}
|
||||
|
||||
Register-ObjectEvent $Watcher "Changed" -Action $Action
|
||||
Register-ObjectEvent $Watcher "Created" -Action $Action
|
||||
Register-ObjectEvent $Watcher "Deleted" -Action $Action
|
||||
Register-ObjectEvent $Watcher "Renamed" -Action $Action
|
||||
# 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
|
||||
|
||||
Write-Host "Monitoramento do Git iniciado na branch 'frontend'..." -ForegroundColor Yellow
|
||||
Write-Host "Pressione Ctrl+C para parar."
|
||||
# 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"
|
||||
|
||||
while ($true) { Start-Sleep -Seconds 5 }
|
||||
# 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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,9 @@
|
|||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
"preview": "vite preview",
|
||||
"git:sync": "powershell -ExecutionPolicy Bypass -File ./git-auto-sync.ps1",
|
||||
"git:sync:nobuild": "powershell -ExecutionPolicy Bypass -Command \"$env:BUILD_ENABLED='false'; .\\git-auto-sync.ps1\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^5.2.2",
|
||||
|
|
|
|||
Loading…
Reference in New Issue