diff --git a/docs/second-example.md b/docs/second-example.md new file mode 100644 index 0000000..84ff1cc --- /dev/null +++ b/docs/second-example.md @@ -0,0 +1,21 @@ +# Another Example Document + +This document is written to show various issues that can be found by a linter. + +## Introduction +The system is designed to be used by all users. It is important that the instructions are followed carefully. + +## Setup +The configuration file is located in the root directory. It is necessary to open it and modify the settings. The server must be restarted after changes are made. + +### Steps +1. The repository is cloned. +2. Dependencies are installed. +3. The database is set up. + +> **Note:** The database should be backed up regularly. + +## Troubleshooting +Errors are logged to `/var/log/app.log`. "Permission Denied" errors are often caused by incorrect file permissions. + +[Click here for more help](#support) diff --git a/docs/third-example.md b/docs/third-example.md new file mode 100644 index 0000000..b6f281a --- /dev/null +++ b/docs/third-example.md @@ -0,0 +1,28 @@ +# Deployment Guidelines + +This document outlines how the application is deployed to production. + +## Prerequisites + +Before the installation is started, the following requirements must be met: + +Node.js: It is required that Node.js v18 is installed. + +Database: A PostgreSQL instance must be provisioned by the infrastructure team. + +Permissions: Root access is needed for the initial setup. + +## Installation Steps + +The repository can be cloned using the standard Git command. +Once the files are downloaded, the dependencies are installed by running npm install. + +. Note: The environment variables must be configured before the application is started. + +## Configuration + +The configuration file config.yaml is found in the root directory. +Changes can be made to this file to adjust the port settings. +If an error is encountered, the logs should be checked immediately. + +[Click here for more details]() \ No newline at end of file diff --git a/scripts/revisor_docs.py b/scripts/revisor_docs.py index 6a4b9b0..06b5c12 100644 --- a/scripts/revisor_docs.py +++ b/scripts/revisor_docs.py @@ -2,134 +2,126 @@ import sys import anthropic from github import Github +from github import Auth def corrigir_frase(texto_original, client_anthropic): """ - Envia a frase para o Claude para verificar voz passiva. - Retorna o texto corrigido ou o original se não houver mudança. + Envia a frase para o Claude. Retorna o texto original se der erro ou se não houver mudança. """ - # Ignora linhas muito curtas, títulos, blocos de código ou itens de lista simples - if len(texto_original.strip()) < 10 or texto_original.strip().startswith(('#', '```', '![', '<')): + # Ignora linhas curtas, títulos, ou linhas que parecem código/comentários + if len(texto_original.strip()) < 10 or texto_original.strip().startswith(('#', '```', '![', '<', '>', '-')): return texto_original prompt = f""" - Atue como um Editor Técnico (Technical Writer). - Analise a frase abaixo. Se ela estiver na VOZ PASSIVA, reescreva para VOZ ATIVA. - Assuma que o sujeito é "you" (o usuário/leitor) se estiver oculto. + Atue como um Editor Técnico. Analise a frase abaixo. + Se estiver na VOZ PASSIVA, reescreva para VOZ ATIVA (assuma "you" como sujeito). - Regras CRÍTICAS: - 1. Se a frase já estiver na voz ativa, retorne EXATAMENTE o texto original, sem mudar nada. - 2. Se mudar, retorne APENAS o novo texto corrigido. - 3. Mantenha a formatação Markdown (negrito, itálico, links) INTACTA. + Regras: + 1. Se já estiver na voz ativa, retorne EXATAMENTE o texto original. + 2. Mantenha formatação Markdown. + 3. NÃO explique, apenas retorne o texto. Frase: "{texto_original.strip()}" """ try: + # MUDANÇA: Usando Claude 3 Haiku (versão estável e universalmente disponível) message = client_anthropic.messages.create( - model="claude-3-5-sonnet-latest", + model="claude-3-haiku-20240307", max_tokens=300, temperature=0, messages=[{"role": "user", "content": prompt}] ) texto_novo = message.content[0].text.strip() - # Validação extra: se o texto for igual, retorna original + # Se a IA devolver o mesmo texto (ou vazio), ignoramos if texto_novo == texto_original.strip(): return texto_original return texto_novo except Exception as e: - print(f"⚠️ Erro ao consultar Claude: {e}") + # Se der erro na API, apenas logamos e seguimos sem quebrar o script + print(f"⚠️ [Claude API Error] Linha ignorada: {e}") return texto_original def main(): - # 1. Validar Variáveis de Ambiente github_token = os.getenv("GITHUB_TOKEN") anthropic_key = os.getenv("ANTHROPIC_API_KEY") repo_name = os.getenv("GITHUB_REPOSITORY") pr_number = os.getenv("PR_NUMBER") - # O arquivo vem como argumento do comando python if len(sys.argv) < 2: print("❌ Erro: Caminho do arquivo não fornecido.") sys.exit(1) - arquivo_path = sys.argv[1] if not (github_token and anthropic_key and repo_name and pr_number): - print("❌ Erro: Variáveis de ambiente faltando (GITHUB_TOKEN, ANTHROPIC_API_KEY, PR_NUMBER).") + print("❌ Erro: Variáveis de ambiente faltando.") sys.exit(1) print(f"🔍 Iniciando análise de: {arquivo_path}") - # 2. Inicializar Clientes + # Autenticação robusta + auth = Auth.Token(github_token) + gh = Github(auth=auth) + try: - gh = Github(github_token) repo = gh.get_repo(repo_name) pr = repo.get_pull(int(pr_number)) claude = anthropic.Anthropic(api_key=anthropic_key) - # Pega o último commit para atrelar o comentário a ele - # Isso garante que o comentário apareça na versão atual do PR + # Pega o último commit para comentar na versão correta do PR commits = list(pr.get_commits()) last_commit = commits[-1] except Exception as e: - print(f"❌ Erro ao conectar com GitHub: {e}") + print(f"❌ Erro ao conectar GitHub: {e}") sys.exit(1) - # 3. Ler o arquivo try: with open(arquivo_path, 'r', encoding='utf-8') as f: linhas = f.readlines() except FileNotFoundError: - print(f"❌ Arquivo não encontrado no disco: {arquivo_path}") + print(f"❌ Arquivo local não encontrado: {arquivo_path}") sys.exit(1) - # 4. Processar Linha a Linha - sugestoes_feitas = 0 + sugestoes = 0 for i, linha in enumerate(linhas): linha_limpa = linha.strip() - - # Pula linhas vazias - if not linha_limpa: + if not linha_limpa: continue novo_texto = corrigir_frase(linha, claude) - # Se houve correção + # Só comentamos se houver diferença REAL if novo_texto != linha_limpa: - print(f"💡 Sugestão na linha {i+1}:") + print(f"💡 Sugestão Linha {i+1}:") print(f" 🔴 {linha_limpa}") print(f" 🟢 {novo_texto}") - body_suggestion = f""" + body = f""" **Sugestão de Voz Ativa (AI)** 🤖 - ```suggestion {novo_texto} ``` """ try: - # Tenta postar o comentário na linha específica - # create_review_comment exige commit_id, path e line (ou position) + # Usa 'commit' em vez de 'commit_id' pr.create_review_comment( - body=body_suggestion, - commit_id=last_commit, + body=body, + commit=last_commit, path=arquivo_path, - line=i + 1 # GitHub lines são 1-based + line=i + 1 ) - sugestoes_feitas += 1 + sugestoes += 1 + print(" ✅ Comentário postado.") except Exception as e: - # O GitHub só permite comentar em linhas que foram alteradas no PR (no diff). - # Se a linha não faz parte do diff, ele retorna erro. Isso é normal. - print(f"⚠️ Pulei a linha {i+1} (provavelmente não foi alterada neste PR): {e}") + print(f" ⚠️ Não postado (Linha não alterada no PR ou erro API): {e}") - if sugestoes_feitas == 0: - print("✅ Nenhuma correção aplicável encontrada nas linhas alteradas.") + if sugestoes == 0: + print("✅ Nenhuma sugestão necessária.") else: - print(f"🚀 {sugestoes_feitas} comentários postados com sucesso!") + print(f"🚀 {sugestoes} sugestões enviadas para o PR!") if __name__ == "__main__": main() \ No newline at end of file