diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..90488c6 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,88 @@ +version: 2 +updates: + # GitHub Actions dependencies + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + day: "monday" + time: "09:00" + open-pull-requests-limit: 5 + labels: + - "dependencies" + - "github-actions" + commit-message: + prefix: "chore" + prefix-development: "chore" + include: "scope" + + # npm/JavaScript dependencies (if package.json exists) + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "weekly" + day: "monday" + time: "09:00" + open-pull-requests-limit: 10 + versioning-strategy: increase + labels: + - "dependencies" + - "javascript" + commit-message: + prefix: "chore" + prefix-development: "chore" + include: "scope" + ignore: + # Ignore major version updates for now + - dependency-name: "*" + update-types: ["version-update:semver-major"] + + # Python dependencies (if requirements.txt, setup.py, or pyproject.toml exists) + - package-ecosystem: "pip" + directory: "/" + schedule: + interval: "weekly" + day: "monday" + time: "09:00" + open-pull-requests-limit: 10 + labels: + - "dependencies" + - "python" + commit-message: + prefix: "chore" + prefix-development: "chore" + include: "scope" + ignore: + # Ignore major version updates for now + - dependency-name: "*" + update-types: ["version-update:semver-major"] + + # Docker dependencies (if Dockerfile exists) + - package-ecosystem: "docker" + directory: "/" + schedule: + interval: "weekly" + day: "monday" + time: "09:00" + open-pull-requests-limit: 5 + labels: + - "dependencies" + - "docker" + commit-message: + prefix: "chore" + include: "scope" + + # Go dependencies (if go.mod exists) + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + day: "monday" + time: "09:00" + open-pull-requests-limit: 10 + labels: + - "dependencies" + - "golang" + commit-message: + prefix: "chore" + include: "scope" diff --git a/.github/markdown-link-check-config.json b/.github/markdown-link-check-config.json new file mode 100644 index 0000000..c6608a8 --- /dev/null +++ b/.github/markdown-link-check-config.json @@ -0,0 +1,12 @@ +{ + "ignorePatterns": [ + { + "pattern": "^http://localhost" + } + ], + "timeout": "20s", + "retryOn429": true, + "retryCount": 3, + "fallbackRetryDelay": "30s", + "aliveStatusCodes": [200, 206, 301, 302, 307, 308, 403, 429] +} diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..70febbc --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,71 @@ +## 📋 Descrição + + + +### O que mudou? + + + +### Por quê? + + + +## ✅ Checklist + + + +- [ ] O código segue os padrões do projeto +- [ ] Testes foram executados e estão passando +- [ ] Documentação foi atualizada (se aplicável) +- [ ] Commits seguem o padrão [Conventional Commits](https://www.conventionalcommits.org/pt-br/) +- [ ] Não há conflitos com a branch base +- [ ] Revisão própria do código foi realizada +- [ ] Comentários foram adicionados em áreas complexas (se necessário) + +## 🔗 Issue Relacionada + + + +Closes # +Relates to # + +## 🎯 Impacto Esperado + + + +### Áreas Afetadas + +- [ ] Documentação +- [ ] Automação/Scripts +- [ ] Templates +- [ ] CI/CD +- [ ] Configuração do Projeto +- [ ] Outro: ___________ + +### Impacto de Risco + +- [ ] **Baixo** - Mudanças isoladas, sem impacto em funcionalidades existentes +- [ ] **Médio** - Alterações que podem afetar funcionalidades existentes +- [ ] **Alto** - Mudanças significativas que requerem atenção especial + +## 📸 Capturas de Tela (se aplicável) + + + +## 🧪 Como Testar + + + +1. +2. +3. + +## 📝 Notas Adicionais + + + +## 🔍 Revisores Sugeridos + + + +@ diff --git a/.github/workflows/auto-label.yml b/.github/workflows/auto-label.yml new file mode 100644 index 0000000..6706bd4 --- /dev/null +++ b/.github/workflows/auto-label.yml @@ -0,0 +1,141 @@ +name: Auto Label PRs + +on: + pull_request: + types: [opened, edited, reopened] + +permissions: + contents: read + pull-requests: write + issues: write + +jobs: + auto-label: + name: Automatically Label Pull Requests + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Auto-label based on PR content + uses: actions/github-script@v7 + with: + script: | + const prTitle = context.payload.pull_request.title.toLowerCase(); + const prBody = (context.payload.pull_request.body || '').toLowerCase(); + const prContent = `${prTitle} ${prBody}`; + + // Define label mapping with keywords + const labelMappings = { + 'enhancement': ['feat', 'feature', 'add', 'implement', 'enhance', 'new'], + 'bugfix': ['fix', 'bug', 'resolve', 'correct', 'patch', 'repair'], + 'documentation': ['docs', 'documentation', 'readme', 'guide', 'comment'], + 'refactor': ['refactor', 'cleanup', 'restructure', 'optimize', 'improve'] + }; + + // Additional labels for special cases + const specialLabels = { + 'dependencies': ['dependency', 'dependencies', 'dependabot', 'upgrade', 'update package'], + 'ci': ['ci', 'workflow', 'github actions', 'pipeline', 'automation'], + 'security': ['security', 'vulnerability', 'cve', 'exploit'], + 'breaking-change': ['breaking change', 'breaking', 'major version'] + }; + + // Combine all label mappings + const allMappings = { ...labelMappings, ...specialLabels }; + + const labelsToAdd = new Set(); + + // Check for matching keywords + for (const [label, keywords] of Object.entries(allMappings)) { + for (const keyword of keywords) { + if (prContent.includes(keyword)) { + labelsToAdd.add(label); + break; + } + } + } + + // Convert Set to Array + const labels = Array.from(labelsToAdd); + + // If no labels matched, add 'needs-triage' + if (labels.length === 0) { + labels.push('needs-triage'); + } + + // Get current labels + const currentLabels = context.payload.pull_request.labels.map(l => l.name); + + // Only add labels that don't already exist + const newLabels = labels.filter(l => !currentLabels.includes(l)); + + if (newLabels.length > 0) { + console.log(`Adding labels: ${newLabels.join(', ')}`); + + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.payload.pull_request.number, + labels: newLabels + }); + } else { + console.log('No new labels to add'); + } + + - name: Add size label + uses: actions/github-script@v7 + with: + script: | + // Get PR diff stats + const pr = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.payload.pull_request.number + }); + + const additions = pr.data.additions; + const deletions = pr.data.deletions; + const totalChanges = additions + deletions; + + let sizeLabel = ''; + + if (totalChanges < 10) { + sizeLabel = 'size/XS'; + } else if (totalChanges < 50) { + sizeLabel = 'size/S'; + } else if (totalChanges < 200) { + sizeLabel = 'size/M'; + } else if (totalChanges < 500) { + sizeLabel = 'size/L'; + } else { + sizeLabel = 'size/XL'; + } + + // Remove existing size labels + const currentLabels = context.payload.pull_request.labels; + const sizeLabelsToRemove = currentLabels + .filter(l => l.name.startsWith('size/')) + .map(l => l.name); + + for (const label of sizeLabelsToRemove) { + await github.rest.issues.removeLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.payload.pull_request.number, + name: label + }).catch(() => { + // Ignore errors if label doesn't exist + }); + } + + // Add new size label + console.log(`Adding size label: ${sizeLabel} (${totalChanges} changes)`); + + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.payload.pull_request.number, + labels: [sizeLabel] + }); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..7023160 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,162 @@ +name: CI + +on: + pull_request: + branches: + - main + - develop + push: + branches: + - main + - develop + +permissions: + contents: read + pull-requests: read + +jobs: + # Job to detect what package managers are present + detect-package-managers: + name: Detect Package Managers + runs-on: ubuntu-latest + outputs: + has-npm: ${{ steps.detect.outputs.has-npm }} + has-python: ${{ steps.detect.outputs.has-python }} + has-go: ${{ steps.detect.outputs.has-go }} + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Detect package managers + id: detect + run: | + echo "has-npm=$(test -f package.json && echo 'true' || echo 'false')" >> $GITHUB_OUTPUT + echo "has-python=$(test -f requirements.txt -o -f setup.py -o -f pyproject.toml && echo 'true' || echo 'false')" >> $GITHUB_OUTPUT + echo "has-go=$(test -f go.mod && echo 'true' || echo 'false')" >> $GITHUB_OUTPUT + + # Conditional Node.js/npm checks + node-checks: + name: Node.js Checks + runs-on: ubuntu-latest + needs: detect-package-managers + if: needs.detect-package-managers.outputs.has-npm == 'true' + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'npm' + + - name: Install dependencies + run: npm ci + + - name: Run linter + if: hashFiles('.eslintrc*', 'eslint.config.*') != '' + run: npm run lint --if-present + continue-on-error: true + + - name: Run tests + if: hashFiles('**/*.test.js', '**/*.spec.js', '**/*.test.ts', '**/*.spec.ts') != '' + run: npm test --if-present + + - name: Build project + run: npm run build --if-present + + # Conditional Python checks + python-checks: + name: Python Checks + runs-on: ubuntu-latest + needs: detect-package-managers + if: needs.detect-package-managers.outputs.has-python == 'true' + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: '3.x' + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + if [ -f requirements.txt ]; then pip install -r requirements.txt; fi + if [ -f requirements-dev.txt ]; then pip install -r requirements-dev.txt; fi + + - name: Run linter (flake8) + run: | + pip install flake8 + flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics + continue-on-error: true + + - name: Run tests (pytest) + if: hashFiles('**/*test*.py') != '' + run: | + pip install pytest + pytest + continue-on-error: true + + # Conditional Go checks + go-checks: + name: Go Checks + runs-on: ubuntu-latest + needs: detect-package-managers + if: needs.detect-package-managers.outputs.has-go == 'true' + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Go + uses: actions/setup-go@v5 + with: + go-version: '1.21' + + - name: Build + run: go build -v ./... + + - name: Test + run: go test -v ./... + + # General file checks (always run) + general-checks: + name: General Checks + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Check for trailing whitespace + run: | + ! git grep -I --line-number --perl-regexp '\s+$' -- ':!*.md' || { + echo "Error: Trailing whitespace found" + git grep -I --line-number --perl-regexp '\s+$' -- ':!*.md' + exit 1 + } + continue-on-error: true + + - name: Check YAML files + uses: ibiqlik/action-yamllint@v3 + with: + file_or_dir: .github/ + config_file: .github/yamllint-config.yml + strict: false + continue-on-error: true + + - name: Validate workflows + run: | + echo "Checking workflow syntax..." + for workflow in .github/workflows/*.yml .github/workflows/*.yaml; do + if [ -f "$workflow" ]; then + echo "Checking $workflow" + # Basic YAML syntax check + python3 -c "import yaml; yaml.safe_load(open('$workflow'))" || exit 1 + fi + done diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..30fcd90 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,50 @@ +name: CodeQL Security Analysis + +on: + pull_request: + branches: + - main + - develop + push: + branches: + - main + - develop + schedule: + # Run at 00:00 UTC every Monday + - cron: '0 0 * * 1' + +permissions: + actions: read + contents: read + security-events: write + +jobs: + analyze: + name: Analyze Code + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + # Define languages to analyze + # Supported: 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby', 'swift' + language: ['javascript', 'python'] + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + # If you want to specify queries, uncomment below + # queries: security-and-quality + + - name: Autobuild + uses: github/codeql-action/autobuild@v3 + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 + with: + category: "/language:${{matrix.language}}" diff --git a/.github/workflows/markdown-lint.yml b/.github/workflows/markdown-lint.yml new file mode 100644 index 0000000..ab33434 --- /dev/null +++ b/.github/workflows/markdown-lint.yml @@ -0,0 +1,47 @@ +name: Markdown Lint + +on: + pull_request: + branches: + - main + - develop + paths: + - '**.md' + push: + branches: + - main + - develop + paths: + - '**.md' + +permissions: + contents: read + pull-requests: read + +jobs: + markdown-lint: + name: Lint Markdown Files + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Run markdownlint + uses: DavidAnson/markdownlint-cli2-action@v16 + with: + globs: | + **/*.md + !node_modules + !.git + + - name: Check markdown links + uses: gaurav-nelson/github-action-markdown-link-check@v1 + with: + use-quiet-mode: 'yes' + use-verbose-mode: 'no' + config-file: '.github/markdown-link-check-config.json' + check-modified-files-only: 'yes' + continue-on-error: true diff --git a/.github/yamllint-config.yml b/.github/yamllint-config.yml new file mode 100644 index 0000000..de23593 --- /dev/null +++ b/.github/yamllint-config.yml @@ -0,0 +1,12 @@ +--- +extends: default + +rules: + line-length: + max: 120 + level: warning + document-start: disable + truthy: + check-keys: false + comments: + min-spaces-from-content: 1 diff --git a/.markdownlint.json b/.markdownlint.json new file mode 100644 index 0000000..d505e01 --- /dev/null +++ b/.markdownlint.json @@ -0,0 +1,18 @@ +{ + "default": true, + "MD013": { + "line_length": 120, + "heading_line_length": 120, + "code_block_line_length": 120, + "code_blocks": true, + "tables": false, + "headings": true, + "strict": false, + "stern": false + }, + "MD033": false, + "MD041": false, + "MD024": { + "siblings_only": true + } +} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..919ef02 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,257 @@ +# Guia de Contribuição + +Obrigado por seu interesse em contribuir para o Digital Transform Kit! Este documento fornece diretrizes para ajudá-lo a colaborar de forma eficaz. + +## 📋 Índice + +- [Como Abrir um Pull Request](#como-abrir-um-pull-request) +- [Padrões de Commit](#padrões-de-commit) +- [Fluxo de Revisão e Aprovação](#fluxo-de-revisão-e-aprovação) +- [Regras de Branches](#regras-de-branches) +- [Processo de Desenvolvimento](#processo-de-desenvolvimento) + +## 🔄 Como Abrir um Pull Request + +1. **Fork o repositório** e clone-o localmente +2. **Crie uma branch** seguindo as [regras de branches](#regras-de-branches) +3. **Faça suas alterações** seguindo os [padrões de commit](#padrões-de-commit) +4. **Execute os testes** e validações (se aplicável) +5. **Push sua branch** para seu fork +6. **Abra um Pull Request** usando o template fornecido +7. **Aguarde a revisão** e responda aos comentários + +### Checklist antes de abrir um PR + +- [ ] O código segue os padrões do projeto +- [ ] Os testes foram executados e estão passando +- [ ] A documentação foi atualizada (se necessário) +- [ ] O commit segue o padrão Conventional Commits +- [ ] Não há conflitos com a branch base + +## 📝 Padrões de Commit + +Este projeto utiliza [Conventional Commits](https://www.conventionalcommits.org/pt-br/) para manter um histórico de commits claro e consistente. + +### Formato + +``` +[escopo opcional]: + +[corpo opcional] + +[rodapé opcional] +``` + +### Tipos Principais + +- **feat**: Nova funcionalidade +- **fix**: Correção de bug +- **docs**: Alterações na documentação +- **style**: Formatação, espaços em branco, etc (sem mudança de código) +- **refactor**: Refatoração de código (sem adicionar funcionalidade ou corrigir bugs) +- **perf**: Melhorias de performance +- **test**: Adição ou correção de testes +- **chore**: Tarefas de manutenção, configuração, etc +- **ci**: Alterações em arquivos de CI/CD + +### Exemplos + +```bash +feat: adicionar template de PR +fix: corrigir validação de formulário +docs: atualizar guia de contribuição +chore: configurar GitHub Actions +ci: adicionar workflow de markdown lint +``` + +### Commits com Breaking Changes + +Para mudanças que quebram compatibilidade, adicione `!` após o tipo ou `BREAKING CHANGE:` no rodapé: + +```bash +feat!: alterar estrutura de API +``` + +ou + +```bash +feat: alterar estrutura de API + +BREAKING CHANGE: o endpoint /api/v1 foi removido +``` + +## 🔍 Fluxo de Revisão e Aprovação + +### Processo de Revisão + +1. **Submissão**: Contribuidor abre um PR +2. **Revisão Automática**: GitHub Actions executa verificações +3. **Revisão por Pares**: Mantenedores revisam o código +4. **Correções**: Contribuidor ajusta conforme feedback +5. **Aprovação**: PR é aprovado por pelo menos um mantenedor +6. **Merge**: PR é mesclado na branch apropriada + +### Critérios de Aprovação + +- ✅ Todas as verificações automáticas passaram +- ✅ Código revisado e aprovado por pelo menos 1 mantenedor +- ✅ Sem conflitos com a branch base +- ✅ Documentação atualizada (se aplicável) +- ✅ Commits seguem o padrão estabelecido + +### Tempo de Resposta + +- **Primeira resposta**: Até 3 dias úteis +- **Revisão completa**: Até 7 dias úteis +- **Urgências**: Identificadas com label `priority:high` + +## 🌿 Regras de Branches + +### Estrutura de Branches + +- **`main`**: Branch de produção + - Sempre estável e pronta para deploy + - Protegida contra push direto + - Requer aprovação de PR + +- **`develop`**: Branch de desenvolvimento + - Integração de funcionalidades + - Base para criar feature branches + - Merge para `main` em releases + +- **`feature/*`**: Novas funcionalidades + - Formato: `feature/nome-da-funcionalidade` + - Exemplo: `feature/add-automation-script` + - Base: `develop` + +- **`bugfix/*`**: Correções de bugs + - Formato: `bugfix/descrição-do-bug` + - Exemplo: `bugfix/fix-validation-error` + - Base: `develop` + +- **`hotfix/*`**: Correções urgentes em produção + - Formato: `hotfix/descrição-do-problema` + - Exemplo: `hotfix/critical-security-fix` + - Base: `main` + +- **`docs/*`**: Alterações em documentação + - Formato: `docs/descrição-da-alteração` + - Exemplo: `docs/update-contributing-guide` + - Base: `develop` + +- **`refactor/*`**: Refatorações + - Formato: `refactor/descrição-da-refatoração` + - Exemplo: `refactor/improve-code-structure` + - Base: `develop` + +### Nomenclatura + +- Use kebab-case (palavras separadas por hífen) +- Seja descritivo mas conciso +- Use inglês ou português de forma consistente +- Evite abreviações obscuras + +### Exemplos de Nomes de Branches + +✅ **Bom:** +- `feature/add-pr-template` +- `bugfix/fix-markdown-linting` +- `docs/update-readme` +- `hotfix/security-vulnerability` + +❌ **Evite:** +- `my-branch` +- `test` +- `fix` +- `update` + +## 🚀 Processo de Desenvolvimento + +### 1. Setup Inicial + +```bash +# Clone o repositório +git clone https://github.com/danielnovais-tech/digital-transform-kit.git +cd digital-transform-kit + +# Configure o remote upstream (se for um fork) +git remote add upstream https://github.com/danielnovais-tech/digital-transform-kit.git +``` + +### 2. Criar Nova Branch + +```bash +# Atualize sua branch develop +git checkout develop +git pull upstream develop + +# Crie uma nova feature branch +git checkout -b feature/minha-funcionalidade +``` + +### 3. Desenvolvimento + +```bash +# Faça suas alterações +# Execute testes localmente (se aplicável) + +# Adicione os arquivos alterados +git add . + +# Commit com mensagem seguindo o padrão +git commit -m "feat: adicionar nova funcionalidade" +``` + +### 4. Sincronizar com Upstream + +```bash +# Antes de abrir o PR, sincronize com develop +git checkout develop +git pull upstream develop + +# Rebase sua branch (ou merge, conforme preferência) +git checkout feature/minha-funcionalidade +git rebase develop +``` + +### 5. Push e PR + +```bash +# Push para seu fork +git push origin feature/minha-funcionalidade + +# Abra um PR no GitHub +# Preencha o template de PR completamente +``` + +## 🏷️ Labels e Categorização + +Os PRs serão automaticamente categorizados com labels baseados em palavras-chave: + +- **`enhancement`**: Novas funcionalidades ou melhorias +- **`bugfix`**: Correções de bugs +- **`documentation`**: Alterações em documentação +- **`refactor`**: Refatorações de código + +### Palavras-chave para Labels Automáticos + +- **enhancement**: feat, feature, add, implement, enhance +- **bugfix**: fix, bug, resolve, correct +- **documentation**: docs, documentation, readme +- **refactor**: refactor, cleanup, restructure + +## 📞 Dúvidas e Suporte + +Se você tiver dúvidas sobre como contribuir: + +1. Verifique a [documentação existente](README.md) +2. Procure em [issues abertas](https://github.com/danielnovais-tech/digital-transform-kit/issues) +3. Abra uma [nova issue](https://github.com/danielnovais-tech/digital-transform-kit/issues/new) com sua dúvida + +## 🙏 Reconhecimento + +Todas as contribuições são valorizadas e reconhecidas. Obrigado por ajudar a melhorar o Digital Transform Kit! + +--- + +*Última atualização: Janeiro 2026* diff --git a/README.md b/README.md index 9ae28dc..36e8993 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,26 @@ Digital Transform Kit #1 is designed for: - **Measurable Results**: Track progress with clear metrics and KPIs - **Sustainable Change**: Build capabilities for continuous innovation +## Contributing + +We welcome contributions! This project includes comprehensive automation and quality tools to ensure high standards. + +### How to Contribute + +Please read our [Contributing Guide](CONTRIBUTING.md) for detailed information on: +- Opening Pull Requests +- Commit message standards (Conventional Commits) +- Branch naming conventions +- Review process + +### Automated Checks + +This repository includes several automated quality checks: +- **CodeQL Security Analysis**: Scans for security vulnerabilities +- **Markdown Linting**: Ensures documentation quality +- **Automated PR Labeling**: Categorizes PRs based on content +- **Dependabot**: Keeps dependencies up-to-date + ## Support For questions, feedback, or support requests, please open an issue in this repository. diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md new file mode 100644 index 0000000..44570b7 --- /dev/null +++ b/docs/AUTOMATION.md @@ -0,0 +1,300 @@ +# Repository Automation and Quality Tools + +This document describes the automated quality and hygiene tools configured for this repository. + +## 📋 Table of Contents + +- [Overview](#overview) +- [Contribution Guidelines](#contribution-guidelines) +- [Pull Request Process](#pull-request-process) +- [Automated Workflows](#automated-workflows) +- [Code Review Tools](#code-review-tools) +- [Labels and Categorization](#labels-and-categorization) +- [Dependency Management](#dependency-management) + +## Overview + +This repository includes comprehensive automation to maintain code quality, security, and consistency. All checks run automatically on pull requests. + +## Contribution Guidelines + +Full contribution guidelines are available in [CONTRIBUTING.md](../CONTRIBUTING.md) (in Portuguese). Key points: + +- **Commit Standards**: Use [Conventional Commits](https://www.conventionalcommits.org/) +- **Branching**: Follow the branch naming conventions (`feature/*`, `bugfix/*`, etc.) +- **PR Template**: Fill out all sections of the PR template +- **Reviews**: At least one approval required for merging + +## Pull Request Process + +### 1. Creating a Pull Request + +When you open a PR, use the provided template which includes: +- **Description**: What changed and why +- **Checklist**: Pre-merge requirements +- **Related Issue**: Links to associated issues +- **Impact Assessment**: Areas affected by changes + +### 2. Automated Checks + +All PRs trigger automated workflows: + +``` +PR Opened + ├── Auto-labeling (instant) + ├── Markdown Lint (if .md files changed) + ├── CI Checks (conditional based on project type) + └── CodeQL Security Scan +``` + +### 3. Review and Approval + +- Automated checks must pass +- At least 1 maintainer approval required +- All conversations must be resolved + +## Automated Workflows + +### CI Workflow (`.github/workflows/ci.yml`) + +**Triggers**: Pull requests and pushes to `main` or `develop` + +**What it does**: +1. **Detects Package Managers**: Automatically identifies project type (Node.js, Python, Go) +2. **Conditional Checks**: Runs appropriate linters and tests based on detected technologies +3. **General Checks**: Always runs basic file validation + +**Jobs**: +- `detect-package-managers`: Identifies project technologies +- `node-checks`: Runs npm install, lint, test, build (if package.json exists) +- `python-checks`: Runs pip install, flake8, pytest (if Python files exist) +- `go-checks`: Runs go build and test (if go.mod exists) +- `general-checks`: Validates YAML files and checks for trailing whitespace + +**Permissions**: `contents: read`, `pull-requests: read` + +### Markdown Lint Workflow (`.github/workflows/markdown-lint.yml`) + +**Triggers**: Pull requests and pushes affecting `*.md` files + +**What it does**: +1. **Markdown Linting**: Validates markdown syntax and formatting using markdownlint-cli2 +2. **Link Checking**: Verifies all links in markdown files are valid + +**Configuration**: +- Line length limit: 120 characters (`.markdownlint.json`) +- Link timeout: 20 seconds with retry on 429 (rate limiting) + +**Permissions**: `contents: read`, `pull-requests: read` + +### CodeQL Security Analysis (`.github/workflows/codeql.yml`) + +**Triggers**: +- Pull requests to `main` or `develop` +- Pushes to `main` or `develop` +- Weekly schedule (Mondays at 00:00 UTC) + +**What it does**: +- Scans code for security vulnerabilities +- Analyzes JavaScript and Python code +- Reports findings to Security tab + +**Languages**: JavaScript, Python (automatically detected) + +**Permissions**: `actions: read`, `contents: read`, `security-events: write` + +### Auto-Label Workflow (`.github/workflows/auto-label.yml`) + +**Triggers**: PR opened, edited, or reopened + +**What it does**: +1. **Content-Based Labeling**: Analyzes PR title and body for keywords +2. **Size Labeling**: Calculates PR size based on changes (XS/S/M/L/XL) + +**Label Mappings**: +- `enhancement`: feat, feature, add, implement, enhance, new +- `bugfix`: fix, bug, resolve, correct, patch, repair +- `documentation`: docs, documentation, readme, guide, comment +- `refactor`: refactor, cleanup, restructure, optimize, improve +- `dependencies`: dependency, dependencies, dependabot, upgrade +- `ci`: ci, workflow, github actions, pipeline, automation +- `security`: security, vulnerability, cve, exploit +- `breaking-change`: breaking change, breaking, major version + +**Size Thresholds**: +- `size/XS`: < 10 changes +- `size/S`: 10-49 changes +- `size/M`: 50-199 changes +- `size/L`: 200-499 changes +- `size/XL`: 500+ changes + +**Permissions**: `contents: read`, `pull-requests: write`, `issues: write` + +## Code Review Tools + +### CodeQL + +- **Purpose**: Automated security vulnerability detection +- **Languages**: JavaScript, Python +- **Frequency**: Every PR + weekly scans +- **Results**: Available in the Security tab + +### Manual Code Review + +- Required for all PRs +- At least 1 approval needed +- Focus on logic, design, and maintainability + +## Labels and Categorization + +### Automatic Labels + +Applied by the auto-label workflow based on PR content: + +| Label | Description | Keywords | +|-------|-------------|----------| +| `enhancement` | New features or improvements | feat, feature, add, implement | +| `bugfix` | Bug fixes | fix, bug, resolve, correct | +| `documentation` | Documentation changes | docs, documentation, readme | +| `refactor` | Code refactoring | refactor, cleanup, restructure | +| `dependencies` | Dependency updates | dependency, dependabot, upgrade | +| `ci` | CI/CD changes | ci, workflow, github actions | +| `security` | Security-related changes | security, vulnerability, cve | +| `breaking-change` | Breaking changes | breaking change, major version | +| `size/XS` to `size/XL` | PR size indicator | Automatically calculated | + +### Manual Labels + +These should be added manually when needed: + +- `priority:high` - Urgent issues +- `priority:medium` - Important but not urgent +- `priority:low` - Nice to have +- `needs-triage` - Requires initial review +- `good-first-issue` - Good for new contributors +- `help-wanted` - Looking for contributors + +## Dependency Management + +### Dependabot Configuration (`.github/dependabot.yml`) + +**What it does**: +- Automatically checks for dependency updates +- Creates PRs for outdated dependencies +- Supports multiple package ecosystems + +**Ecosystems Monitored**: +1. **GitHub Actions** - Workflow dependencies +2. **npm** - JavaScript/Node.js packages +3. **pip** - Python packages +4. **Docker** - Container images +5. **Go modules** - Go dependencies + +**Schedule**: Weekly on Mondays at 09:00 UTC + +**Limits**: +- GitHub Actions: Max 5 open PRs +- npm/pip/Go: Max 10 open PRs +- Docker: Max 5 open PRs + +**Strategy**: +- Major version updates are ignored by default (can be manually updated) +- Uses `increase` versioning strategy for npm +- All updates labeled with `dependencies` + ecosystem-specific label +- Commit messages follow Conventional Commits format + +**Commit Message Format**: +``` +chore(deps): update from X.Y.Z to X.Y.Z +``` + +## Configuration Files + +### `.markdownlint.json` + +Configures markdown linting rules: +- Line length: 120 characters (warning) +- Allows HTML in markdown +- Allows duplicate headings if they're siblings + +### `.github/yamllint-config.yml` + +Configures YAML linting: +- Line length: 120 characters (warning) +- Disables document-start requirement +- Allows less strict truthy checking + +### `.github/markdown-link-check-config.json` + +Configures link checking: +- Timeout: 20 seconds +- Retry on 429 (rate limiting) +- Retry count: 3 +- Fallback delay: 30 seconds + +## Best Practices + +### For Contributors + +1. **Before Opening a PR**: + - Ensure all automated checks pass locally where possible + - Follow the commit message format + - Fill out the PR template completely + +2. **During Review**: + - Respond to review comments promptly + - Make requested changes as separate commits + - Keep the PR focused on a single concern + +3. **After Approval**: + - Ensure all checks still pass + - Resolve any merge conflicts + - Squash commits if requested + +### For Maintainers + +1. **Reviewing PRs**: + - Check that automated checks passed + - Verify the PR follows guidelines + - Test changes locally if needed + - Provide constructive feedback + +2. **Merging PRs**: + - Ensure all required approvals are present + - Verify no merge conflicts + - Use appropriate merge strategy (squash, merge, or rebase) + +## Troubleshooting + +### Common Issues + +**Problem**: Markdown lint fails +- **Solution**: Check `.markdownlint.json` for rules, ensure line length < 120 chars + +**Problem**: Auto-labeling doesn't work +- **Solution**: Ensure PR title or body contains recognized keywords + +**Problem**: CI checks are skipped +- **Solution**: CI only runs when relevant package manager files exist (package.json, requirements.txt, go.mod) + +**Problem**: CodeQL fails +- **Solution**: Check Security tab for details, may indicate a real security issue + +### Getting Help + +- Open an issue with the `question` label +- Check existing issues for similar problems +- Review [CONTRIBUTING.md](../CONTRIBUTING.md) for guidelines + +## Future Enhancements + +Potential additions (not yet implemented): + +- **Codecov**: Code coverage reporting (requires test infrastructure) +- **SonarCloud**: Advanced code quality analysis (requires external setup) +- **Semantic Release**: Automated versioning and changelog generation +- **Conventional PR**: Validate PR titles follow Conventional Commits + +--- + +*Last updated: January 2026* diff --git a/docs/IMPLEMENTATION_SUMMARY.md b/docs/IMPLEMENTATION_SUMMARY.md new file mode 100644 index 0000000..2902a0c --- /dev/null +++ b/docs/IMPLEMENTATION_SUMMARY.md @@ -0,0 +1,173 @@ +# Implementation Summary: Repository Hygiene & Automation + +## Overview + +This document provides a quick summary of the repository hygiene and automation features that have been implemented. + +## Files Created + +### Documentation +- `CONTRIBUTING.md` - Portuguese contribution guide with: + - PR process and standards + - Conventional Commits format + - Review and approval workflow + - Branching strategy (main, develop, feature/*, bugfix/*, hotfix/*, docs/*, refactor/*) + +- `docs/AUTOMATION.md` - Comprehensive documentation of all automation tools + +- `README.md` - Updated with Contributing section + +### GitHub Configuration Files + +#### Workflows (`.github/workflows/`) +1. **ci.yml** - General CI pipeline + - Detects package managers automatically (npm, pip, Go) + - Conditionally runs linters, tests, and builds + - Always validates YAML and checks formatting + +2. **markdown-lint.yml** - Markdown quality checks + - Lints all markdown files + - Checks for broken links + - Runs only when .md files are changed + +3. **codeql.yml** - Security scanning + - Analyzes JavaScript and Python code + - Runs on every PR and weekly + - Reports to Security tab + +4. **auto-label.yml** - Automatic PR labeling + - Labels PRs based on title/body keywords + - Adds size labels (XS/S/M/L/XL) based on changes + - No external services required + +#### Templates +- `.github/pull_request_template.md` - PR template with: + - Description section + - Pre-merge checklist + - Related issue links + - Impact assessment + - Testing instructions + +#### Configuration +- `.github/dependabot.yml` - Dependency updates + - Monitors: GitHub Actions, npm, pip, Docker, Go modules + - Weekly updates on Mondays + - Follows Conventional Commits format + +- `.github/yamllint-config.yml` - YAML linting rules +- `.github/markdown-link-check-config.json` - Link checking configuration +- `.markdownlint.json` - Markdown linting rules + +## Key Features + +### 1. Contribution Guidelines ✅ +- Comprehensive Portuguese guide +- Clear branching strategy +- Conventional Commits standard +- Review process defined + +### 2. PR Templates ✅ +- Structured template with all required fields +- Checklist for contributors +- Impact assessment section +- Testing guidelines + +### 3. Automated Checks ✅ +- **Conditional CI**: Only runs checks when relevant files exist +- **Markdown Linting**: Ensures documentation quality +- **YAML Validation**: Prevents configuration errors +- **Security Scanning**: CodeQL for vulnerability detection +- **Resilient Design**: Doesn't fail if tooling is missing + +### 4. Code Review Tools ✅ +- CodeQL integrated for security analysis +- Dependabot configured for all major ecosystems +- Codecov and SonarCloud documented as future enhancements + +### 5. Labels & Workflow ✅ +- Automated labeling based on PR content +- Size labels (XS/S/M/L/XL) +- Standard labels defined: + - `enhancement` - New features + - `bugfix` - Bug fixes + - `documentation` - Docs changes + - `refactor` - Code refactoring + - `dependencies` - Dependency updates + - `ci` - CI/CD changes + - `security` - Security fixes + - `breaking-change` - Breaking changes + +## Acceptance Criteria Status + +| Criteria | Status | Notes | +|----------|--------|-------| +| CONTRIBUTING.md added | ✅ | In Portuguese with all required sections | +| PR template created | ✅ | Comprehensive template at `.github/pull_request_template.md` | +| GitHub Actions workflows | ✅ | 4 workflows in `.github/workflows/` | +| Workflows run on pull_request | ✅ | All workflows configured to trigger on PRs | +| Dependabot config | ✅ | At `.github/dependabot.yml` with sensible defaults | +| Label automation present | ✅ | Auto-label workflow with keyword detection | +| Correct YAML syntax | ✅ | All files validated | +| Least-privilege permissions | ✅ | All workflows use minimal required permissions | + +## Workflow Permissions + +All workflows use least-privilege permissions: + +- **CI**: `contents: read`, `pull-requests: read` +- **Markdown Lint**: `contents: read`, `pull-requests: read` +- **CodeQL**: `actions: read`, `contents: read`, `security-events: write` +- **Auto-Label**: `contents: read`, `pull-requests: write`, `issues: write` + +## Testing + +### YAML Validation +All YAML files have been validated using Python's yaml library: +- ✅ ci.yml +- ✅ markdown-lint.yml +- ✅ codeql.yml +- ✅ auto-label.yml +- ✅ dependabot.yml +- ✅ yamllint-config.yml + +### JSON Validation +All JSON files validated: +- ✅ .markdownlint.json +- ✅ markdown-link-check-config.json + +## How to Use + +### For Contributors +1. Read `CONTRIBUTING.md` for guidelines +2. Create a branch following naming conventions +3. Make changes using Conventional Commits +4. Open PR using the template +5. Automated checks will run +6. Address review feedback +7. Merge after approval + +### For Maintainers +1. Review PR using automated check results +2. Verify labels are correctly applied +3. Check CodeQL findings if any +4. Approve and merge when ready +5. Monitor Dependabot PRs for updates + +## Next Steps + +1. **Create Initial Labels**: Create the standard labels in the repository +2. **Test Workflows**: Open a test PR to verify all workflows execute correctly +3. **Monitor Dependabot**: Review and merge dependency update PRs +4. **CodeQL Setup**: Verify CodeQL is scanning correctly in the Security tab + +## Future Enhancements + +Not included in this implementation but documented for future consideration: +- Codecov integration (requires test coverage infrastructure) +- SonarCloud setup (requires external account and configuration) +- Semantic release automation +- PR title validation + +--- + +*Implementation completed: January 2026*