-
-
Couldn't load subscription status.
- Fork 1
Introduces subcommands, POSIX compliance, and detailed error messages, improving user experience #39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
…owerShell (#22) * Initial plan * Add comprehensive auto-completion support with documentation Co-authored-by: nataliagranato <[email protected]> --------- Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: nataliagranato <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
* Initial plan * Add version subcommand and refactor CLI structure with tests Co-authored-by: nataliagranato <[email protected]> * Update documentation with comprehensive subcommand examples Co-authored-by: nataliagranato <[email protected]> --------- Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: nataliagranato <[email protected]>
* Initial plan * Add comprehensive unit tests for scanner and kubernetes packages Co-authored-by: nataliagranato <[email protected]> * Enhanced CLI tests, documentation, and added CI workflow for automated testing Co-authored-by: nataliagranato <[email protected]> * Fix staticcheck linting issues in client_test.go Co-authored-by: nataliagranato <[email protected]> * Fix CI workflow: remove broken gosec action, keep govulncheck security scan Co-authored-by: nataliagranato <[email protected]> --------- Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: nataliagranato <[email protected]>
) * Initial plan * Improve CLI error messages and help text for better UX Co-authored-by: nataliagranato <[email protected]> * Add comprehensive integration tests and update documentation Co-authored-by: nataliagranato <[email protected]> * Fix syntax errors and update tests to match enhanced error messages Co-authored-by: nataliagranato <[email protected]> --------- Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: nataliagranato <[email protected]>
…ion (#37) * Initial plan * Implement POSIX-compliant CLI with comprehensive tests and documentation Co-authored-by: nataliagranato <[email protected]> --------- Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: nataliagranato <[email protected]>
…mples (#38) * Initial plan * Add KUBECONFIG environment variable example and improve Dockerfile Co-authored-by: nataliagranato <[email protected]> * feat: update Dockerfile to alpine:3.22.0 and add GitHub Packages pipeline Co-authored-by: nataliagranato <[email protected]> * fix: update GitHub Packages authentication to use USER_TOKEN Co-authored-by: nataliagranato <[email protected]> --------- Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: nataliagranato <[email protected]>
|
""" WalkthroughO pull request amplia e refatora o CLI do kubeprobes, modularizando comandos e lógica de scanner, adicionando novos comandos ( Changes
Sequence Diagram(s)sequenceDiagram
participant Usuário
participant CLI (cobra)
participant Comando Scan
participant Scanner
participant KubernetesClient (mock ou real)
Usuário->>CLI (cobra): Executa "kubeprobes scan [flags]"
CLI (cobra)->>Comando Scan: Inicializa comando scan
Comando Scan->>Scanner: Cria ProbeScanner (injeta KubernetesClient)
Scanner->>KubernetesClient: GetPods(ctx, namespace)
KubernetesClient-->>Scanner: Lista de pods ou erro
Scanner->>Scanner: Analisa probes em containers
Scanner-->>Comando Scan: Resultado (issues encontrados ou não)
Comando Scan-->>Usuário: Mensagens, recomendações, exit code
sequenceDiagram
participant Usuário
participant CLI (cobra)
participant Comando Version
Usuário->>CLI (cobra): Executa "kubeprobes version -o [formato]"
CLI (cobra)->>Comando Version: Inicializa comando version
Comando Version-->>Usuário: Exibe versão (default, short ou JSON)
Possibly related PRs
Poema
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
PR Reviewer Guide 🔍Here are some key observations to aid the review process:
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Summary of Changes
Hello @nataliagranato, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request introduces a suite of improvements aimed at enhancing the user experience, streamlining the development workflow, and bolstering the overall quality of the kubeprobes tool. It focuses on making the CLI more intuitive and informative, automating the Docker image build and release process, and providing comprehensive documentation and testing to support both users and contributors.
Highlights
- Improved User Guidance: User-facing error messages now include detailed troubleshooting tips, and the
scancommand provides actionable recommendations for missing probes, making the tool more intuitive and helpful. - Streamlined Build & Release: The project's build and release process has been automated for Docker images via
.goreleaser.yml, including multi-tagging and OCI labels. TheDockerfilehas also been optimized for smaller, more secure images by switching to Alpine and creating a dedicated non-root user. - Comprehensive Documentation: Extensive updates have been made to
README.mdandCONTRIBUTING.md, along with the addition of a newdocs/completion.mdfile, providing clearer usage instructions, contribution guidelines, and detailed auto-completion setup. - Strengthened Test Suite: A substantial number of new unit tests have been added for CLI commands and core scanning logic, including tests for POSIX compliance and enhanced error messages, significantly improving code quality and maintainability.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull Request Overview
This PR enriches the kubeprobes CLI and scanner with clearer error messages, POSIX-compliant flag handling, actionable recommendations, enhanced documentation, and expanded test coverage and CI/CD workflows.
- Improved scanner output with suggestions, summaries, and custom client interface
- Updated CLI commands (scan, version, root) for POSIX flags, examples, and auto-completion
- Extended documentation, Dockerfile, GitHub Actions, and contributing guidelines
Reviewed Changes
Copilot reviewed 21 out of 21 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| pkg/kubernetes/client_test.go | Added invalid-config tests for NewClient |
| internal/scanner/scanner.go | Switched to interface, improved error messages, added suggestions and summary output |
| internal/scanner/cmd.go | Enhanced scan command flags, examples, POSIX compliance, and flag completion |
| internal/cli/version.go | Improved version command descriptions, examples, and output flag completion |
| docs/docker.md | Expanded Docker usage docs with POSIX examples and improved headings |
| Dockerfile | Switched to Alpine base image, installed certificates, created non-root user |
| .github/workflows/release.yml | Added container registry login and Buildx steps for multi-platform Docker images |
| .github/workflows/ci.yml | Configured matrix testing, coverage enforcement, linting, builds, and security scans |
| CONTRIBUTING.md | Clarified test requirements, added lint and vet steps |
Comments suppressed due to low confidence (3)
pkg/kubernetes/client_test.go:102
- In TestClient_GetPods_NilClient, the
if client != nilguard prevents callingclient.GetPodson a nil pointer, so the panic is never exercised. Remove the conditional so the method is invoked unconditionally and the deferred recover can verify the expected panic.
if client != nil {
internal/scanner/cmd.go:89
- The flag name
kubeContextmixes camelCase with POSIX conventions. Consider renaming it tokube-context(and updating references) to follow standard kebab-case CLI flag naming.
cmd.Flags().StringP("kubeContext", "c", "", "Kubernetes context to use (defaults to current context)")
docs/docker.md:15
- [nitpick] The Docker documentation mixes Portuguese and English headings. For consistency, choose one language or clearly separate localized sections.
## Comandos Básicos
Co-authored-by: Copilot <[email protected]>
PR Code Suggestions ✨Explore these optional code suggestions:
|
|||||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request introduces subcommands, POSIX compliance, and detailed error messages, improving user experience. The test coverage is thorough. I've suggested improvements mainly concerning Docker build optimization, goreleaser configuration, and code duplication.
| if err != nil { | ||
| return fmt.Errorf("error listing pods: %w", err) | ||
| return fmt.Errorf("failed to retrieve pods from namespace '%s': %w\n\nTroubleshooting tips:\n - Verify the namespace exists: kubectl get namespaces\n - Check if you have permissions: kubectl auth can-i get pods --namespace %s\n - Ensure cluster connection is working: kubectl cluster-info", ps.namespace, err, ps.namespace) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The error message could be improved by including the namespace in the troubleshooting tips. This helps users quickly identify the source of the problem.
return fmt.Errorf("failed to retrieve pods from namespace '%s': %w\n\nTroubleshooting tips:\n - Verify the namespace exists: kubectl get namespaces\n - Check if you have permissions: kubectl auth can-i get pods --namespace %s\n - Ensure cluster connection is working: kubectl cluster-info", ps.namespace, err, ps.namespace)
internal/scanner/scanner.go
Outdated
| fmt.Fprintf(ps.writer, "ℹ️ No pods found in namespace '%s'\n\nSuggestions:\n - Check if pods exist: kubectl get pods --namespace %s\n - Try scanning a different namespace: kubeprobes scan --namespace <namespace>\n - List all namespaces: kubectl get namespaces\n", ps.namespace, ps.namespace) | ||
| return nil |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The message displayed when no pods are found could be more helpful by suggesting commands to verify pod existence and explore different namespaces.
fmt.Printf("ℹ️ No pods found in namespace '%s'\n\nSuggestions:\n - Check if pods exist: kubectl get pods --namespace %s\n - Try scanning a different namespace: kubeprobes scan --namespace <namespace>\n - List all namespaces: kubectl get namespaces\n", ps.namespace, ps.namespace)| fmt.Printf("⚠️ [MISSING LIVENESS PROBE] Pod %s/%s (container: %s)\n", | ||
| pod.Namespace, pod.Name, container.Name) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| fmt.Printf(" 💡 Recommendation: Add a liveness probe to detect if the container becomes unresponsive.\n") | ||
| fmt.Printf(" Example: HTTP check on /health endpoint or exec command like 'ps aux | grep myapp'\n") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The recommendation message could be improved by providing specific examples of health check implementations.
fmt.Printf(" 💡 Recommendation: Add a liveness probe to detect if the container becomes unresponsive.\n")
fmt.Printf(" Example: HTTP check on /health endpoint or exec command like 'ps aux | grep myapp'\n")Co-authored-by: qodo-merge-pro[bot] <151058649+qodo-merge-pro[bot]@users.noreply.github.com>
Co-authored-by: qodo-merge-pro[bot] <151058649+qodo-merge-pro[bot]@users.noreply.github.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 5
♻️ Duplicate comments (5)
.goreleaser.yml (2)
64-64: Plataforma hardcoded impede builds multi-arquitetura
70-70: Use a variável de template {{ .Date }} do GoReleaser para melhor reprodutibilidadeDockerfile (1)
9-10: Otimizar cache do Docker com cópia em etapasinternal/scanner/scanner.go (2)
47-47: Conversão redundante deprobeTypepara lowercase.O
probeTypeé convertido para lowercase aqui e novamente emNewProbeScannerWithClientna linha 69. Esta duplicação é desnecessária.Remova esta linha para evitar duplicação:
- probeType = strings.ToLower(probeType)
95-122: Chamadas diretas parafmt.Printfdificultam testes e reutilização.As chamadas diretas para
fmt.Printftornam a lógica difícil de testar e reutilizar. Considere usar o campowriterpara todas as saídas.Substitua todas as chamadas
fmt.Printfporfmt.Fprintf(ps.writer, ...):- fmt.Printf("⚠️ [MISSING LIVENESS PROBE] Pod %s/%s (container: %s)\n", + fmt.Fprintf(ps.writer, "⚠️ [MISSING LIVENESS PROBE] Pod %s/%s (container: %s)\n", pod.Namespace, pod.Name, container.Name) if ps.recommendation { - fmt.Printf(" 💡 Recommendation: Add a liveness probe to detect if the container becomes unresponsive.\n") - fmt.Printf(" Example: HTTP check on /health endpoint or exec command like 'ps aux | grep myapp'\n") + fmt.Fprintf(ps.writer, " 💡 Recommendation: Add a liveness probe to detect if the container becomes unresponsive.\n") + fmt.Fprintf(ps.writer, " Example: HTTP check on /health endpoint or exec command like 'ps aux | grep myapp'\n") }Aplique o mesmo padrão para todas as outras ocorrências de
fmt.Printfno método.
🧹 Nitpick comments (10)
internal/cli/version.go (1)
54-55: Sugerir melhoria na formatação JSON.Considere usar
json.Marshalpara formatação JSON mais robusta e escapar caracteres especiais adequadamente.+import ( + "encoding/json" + "fmt" + "runtime" + + "github.com/spf13/cobra" +) + +type versionInfo struct { + Version string `json:"version"` + Commit string `json:"commit"` + Date string `json:"date"` + GoVersion string `json:"goVersion"` +} - case "json": - cmd.Printf(`{"version":"%s","commit":"%s","date":"%s","goVersion":"%s"}%s`, - Version, Commit, Date, runtime.Version(), "\n") + case "json": + info := versionInfo{ + Version: Version, + Commit: Commit, + Date: Date, + GoVersion: runtime.Version(), + } + jsonBytes, err := json.Marshal(info) + if err != nil { + return fmt.Errorf("failed to marshal version info: %w", err) + } + cmd.Printf("%s\n", jsonBytes)docs/completion.md (1)
1-1: Corrigir grafia de "auto-completion".Em português, "auto-completion" deve ser escrito como uma palavra só: "autocompletion".
-# Auto-completion +# Autocompletion -O kubeprobes oferece suporte completo a auto-completion para bash, zsh, fish e PowerShell utilizando o framework Cobra. +O kubeprobes oferece suporte completo a autocompletion para bash, zsh, fish e PowerShell utilizando o framework Cobra. -O auto-completion permite que você use a tecla Tab para: +O autocompletion permite que você use a tecla Tab para:E assim por diante para todas as ocorrências.
Also applies to: 3-3, 7-7, 39-39, 85-85, 114-114, 148-148, 157-157
docs/docker.md (1)
108-108: Adicionar especificação de linguagem ao bloco de código.O bloco de código deve especificar a linguagem para melhor renderização e highlighting.
-``` +```text.github/workflows/ci.yml (2)
19-19: Corrigir problemas de formatação YAML.O arquivo tem espaços em branco no final de algumas linhas e falta uma nova linha no final do arquivo.
- strategy: + strategy:- runs-on: ubuntu-latest + runs-on: ubuntu-latestE adicionar uma nova linha no final do arquivo.
Also applies to: 72-72, 98-98, 128-128, 141-141
96-96: Ajustar indentação da seção exclude.A indentação está incorreta para a seção exclude do matrix.
- exclude: + exclude:internal/cli/version_test.go (1)
113-132: Melhore o tratamento de valores inválidos.O teste assume que valores inválidos para
--outputdevem ser tratados com fallback silencioso para o formato padrão. Considere se seria melhor retornar um erro explícito para orientar melhor o usuário.# Considere adicionar teste para erro explícito: { name: "invalid output format should show error", args: []string{"--output=invalid"}, expectError: true, errorMsg: "invalid output format", },pkg/kubernetes/client_test.go (1)
185-223: Adicione validação de tipos de erro específicos.O teste
TestClient_ErrorHandlingverifica apenas se um erro ocorre, mas não valida o tipo ou conteúdo específico do erro. Considere adicionar validações mais específicas.// Error should be descriptive if err != nil && len(err.Error()) == 0 { t.Error("Error message should not be empty") } + +// Verificar se o erro contém informações úteis +if err != nil { + errorMsg := err.Error() + if !strings.Contains(errorMsg, "kubeconfig") && !strings.Contains(errorMsg, "config") { + t.Errorf("Error message should provide context about configuration issue, got: %s", errorMsg) + } +}internal/scanner/cmd_test.go (1)
141-213: Adicione cobertura para casos de sucesso.Os testes de validação de flags focam principalmente em cenários de erro. Considere adicionar testes para casos de sucesso quando possível, mesmo que mockados.
// Adicionar teste para cenários de sucesso mockados { name: "valid probe type with mock success", args: []string{"--probe-type=liveness", "--dry-run"}, // se suportado expectError: false, errorMsg: "", },README.md (2)
281-346: Corrija a hifenização de "auto-completion".Baseado nas dicas de análise estática, "auto-completion" deveria ser escrito como uma palavra única "autocompletion" em português.
-## Auto-completion +## Autocompletion -O kubeprobes oferece suporte a auto-completion para bash, zsh, fish e PowerShell. +O kubeprobes oferece suporte a autocompletion para bash, zsh, fish e PowerShell. -consulte a [documentação de auto-completion](docs/completion.md). +consulte a [documentação de autocompletion](docs/completion.md).
231-257: Remova dois pontos dos títulos de seção.Baseado nas dicas de análise estática do markdownlint, os títulos de seção não devem terminar com dois pontos.
-#### Executar todos os testes: +#### Executar todos os testes -#### Executar testes com cobertura: +#### Executar testes com cobertura -#### Executar testes de um pacote específico: +#### Executar testes de um pacote específico -#### Executar testes em modo verboso: +#### Executar testes em modo verboso
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (21)
.dockerignore(2 hunks).github/workflows/ci.yml(1 hunks).github/workflows/release.yml(2 hunks).goreleaser.yml(1 hunks)CONTRIBUTING.md(1 hunks)Dockerfile(1 hunks)README.md(1 hunks)cmd/kubeprobes/main.go(1 hunks)docs/completion.md(1 hunks)docs/docker.md(3 hunks)internal/cli/root.go(2 hunks)internal/cli/root_test.go(1 hunks)internal/cli/scan.go(1 hunks)internal/cli/scan_test.go(1 hunks)internal/cli/version.go(1 hunks)internal/cli/version_test.go(1 hunks)internal/scanner/cmd.go(2 hunks)internal/scanner/cmd_test.go(1 hunks)internal/scanner/scanner.go(4 hunks)internal/scanner/scanner_test.go(1 hunks)pkg/kubernetes/client_test.go(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
internal/cli/root.go (3)
internal/scanner/cmd.go (1)
NewScanCommand(11-104)internal/cli/scan.go (1)
NewScanCommand(10-12)internal/cli/version.go (1)
NewVersionCommand(20-78)
internal/cli/scan_test.go (2)
internal/cli/scan.go (1)
NewScanCommand(10-12)internal/cli/root.go (1)
Execute(49-51)
internal/scanner/scanner_test.go (1)
internal/scanner/scanner.go (4)
NewProbeScanner(42-58)NewProbeScannerWithClient(61-72)ProbeIssuesFoundError(25-27)ProbeScanner(34-39)
pkg/kubernetes/client_test.go (1)
pkg/kubernetes/client.go (2)
NewClient(18-32)Client(13-15)
internal/scanner/scanner.go (1)
pkg/kubernetes/client.go (1)
NewClient(18-32)
🪛 GitHub Actions: CI
cmd/kubeprobes/main.go
[error] 7-7: golangci-lint: could not import kubeprobes/internal/scanner package
internal/scanner/scanner.go
[error] 82-82: Build error: 'ps.writer' undefined (type *ProbeScanner has no field or method writer)
🪛 GitHub Check: Lint
internal/cli/scan.go
[failure] 4-4:
could not import kubeprobes/internal/scanner (-: # kubeprobes/internal/scanner
internal/scanner/scanner.go
[failure] 82-82:
ps.writer undefined (type *ProbeScanner has no field or method writer) (typecheck)
[failure] 82-82:
ps.writer undefined (type *ProbeScanner has no field or method writer)) (typecheck)
[failure] 82-82:
ps.writer undefined (type *ProbeScanner has no field or method writer)) (typecheck)
🪛 markdownlint-cli2 (0.17.2)
docs/docker.md
108-108: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
README.md
231-231: Trailing punctuation in heading
Punctuation: ':'
(MD026, no-trailing-punctuation)
237-237: Trailing punctuation in heading
Punctuation: ':'
(MD026, no-trailing-punctuation)
244-244: Trailing punctuation in heading
Punctuation: ':'
(MD026, no-trailing-punctuation)
257-257: Trailing punctuation in heading
Punctuation: ':'
(MD026, no-trailing-punctuation)
🪛 LanguageTool
docs/completion.md
[misspelling] ~1-~1: Esta é uma palavra só.
Context: # Auto-completion O kubeprobes oferece suporte completo ...
(AUTO)
[misspelling] ~3-~3: Esta é uma palavra só.
Context: ...O kubeprobes oferece suporte completo a auto-completion para bash, zsh, fish e PowerShell utili...
(AUTO)
[misspelling] ~7-~7: Esta é uma palavra só.
Context: ...o framework Cobra. ## Como funciona O auto-completion permite que você use a tecla Tab para: ...
(AUTO)
[misspelling] ~39-~39: Esta é uma palavra só.
Context: ...# Pré-requisitos Certifique-se de que o auto-completion esteja habilitado no zsh: ```bash echo ...
(AUTO)
[misspelling] ~85-~85: Esta é uma palavra só.
Context: ...l do perfil: $PROFILE ## Recursos de Auto-completion ### Comandos - kubeprobes + Tab: mos...
(AUTO)
[misspelling] ~114-~114: Esta é uma palavra só.
Context: ...artup ``` ## Solução de problemas ### Auto-completion não funciona 1. **Verifique se o kubep...
(AUTO)
[misspelling] ~148-~148: Esta é uma palavra só.
Context: ...completions/kubeprobes.fish ``` ### Auto-completion parcial Se apenas alguns recursos de c...
(AUTO)
[misspelling] ~157-~157: Esta é uma palavra só.
Context: ...Desabilitando descrições Por padrão, o auto-completion inclui descrições dos comandos e flags....
(AUTO)
CONTRIBUTING.md
[grammar] ~57-~57: Segundo o Acordo Ortográfico de 45, os meses e as estações do ano devem ser capitalizados.
Context: ...2. Verifique a cobertura de testes (go test -coverprofile=coverage.out ./...) 3. Atualize a documentação se n...
(AO45_MONTHS_CASING)
README.md
[uncategorized] ~140-~140: Sinal de pontuação isolado.
Context: ...dos) ### Comandos Disponíveis - scan: Escaneia workloads do Kubernetes em bus...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~146-~146: Sinal de pontuação isolado.
Context: ...mando Scan - Flags - -k, --kubeconfig: Caminho para o arquivo kubeconfig (padr...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~170-~170: Sinal de pontuação isolado.
Context: ...omando Version - Flags - -o, --output: Formato de saída: default, short, ou js...
(UNLIKELY_OPENING_PUNCTUATION)
[grammar] ~265-~265: Esta palavra é hifenizada.
Context: ...ados em arquivos *_test.go ao lado do código fonte: - internal/cli/*_test.go - Testes p...
(PT_COMPOUNDS_PRE_REFORM_CÓDIGO_FONTE)
[misspelling] ~281-~281: Esta é uma palavra só.
Context: ... para evitar necessidade de cluster ## Auto-completion O kubeprobes oferece suporte a auto-co...
(AUTO)
[misspelling] ~283-~283: Esta é uma palavra só.
Context: ...pletion O kubeprobes oferece suporte a auto-completion para bash, zsh, fish e PowerShell. > P...
(AUTO)
[misspelling] ~285-~285: Esta é uma palavra só.
Context: ...nfiguração, consulte a documentação de auto-completion. ### Bash Para c...
(AUTO)
[misspelling] ~289-~289: Esta é uma palavra só.
Context: ...ompletion.md). ### Bash Para carregar auto-completion na sua sessão atual: ```bash source <(...
(AUTO)
[misspelling] ~295-~295: Esta é uma palavra só.
Context: ...bes completion bash) Para carregar auto-completion permanentemente: bash # Linux kubep...
(AUTO)
[misspelling] ~307-~307: Esta é uma palavra só.
Context: .../kubeprobes ### Zsh Para carregar auto-completion na sua sessão atual: bash source <(...
(AUTO)
[misspelling] ~313-~313: Esta é uma palavra só.
Context: ...obes completion zsh) Para carregar auto-completion permanentemente: bash # Linux kubep...
(AUTO)
[misspelling] ~325-~325: Esta é uma palavra só.
Context: ...kubeprobes ### Fish Para carregar auto-completion na sua sessão atual: bash kubeprobe...
(AUTO)
[misspelling] ~331-~331: Esta é uma palavra só.
Context: ...letion fish | source Para carregar auto-completion permanentemente: bash kubeprobes co...
(AUTO)
[misspelling] ~339-~339: Esta é uma palavra só.
Context: ...fish ### PowerShell Para carregar auto-completion na sua sessão atual: powershell kub...
(AUTO)
[misspelling] ~345-~345: Esta é uma palavra só.
Context: ... | Invoke-Expression ``` Para carregar auto-completion permanentemente, adicione a saída do co...
(AUTO)
🪛 YAMLlint (1.37.1)
.github/workflows/ci.yml
[error] 19-19: trailing spaces
(trailing-spaces)
[error] 72-72: trailing spaces
(trailing-spaces)
[warning] 96-96: wrong indentation: expected 8 but found 10
(indentation)
[error] 98-98: trailing spaces
(trailing-spaces)
[error] 128-128: trailing spaces
(trailing-spaces)
[error] 141-141: no new line character at the end of file
(new-line-at-end-of-file)
🪛 GitHub Check: Build (linux, arm64)
internal/scanner/scanner.go
[failure] 82-82:
ps.writer undefined (type *ProbeScanner has no field or method writer)
🪛 GitHub Check: Build (darwin, amd64)
internal/scanner/scanner.go
[failure] 82-82:
ps.writer undefined (type *ProbeScanner has no field or method writer)
🪛 GitHub Check: Test (1.22)
internal/scanner/scanner.go
[failure] 82-82:
ps.writer undefined (type *ProbeScanner has no field or method writer)
🪛 GitHub Check: Security Scan
internal/scanner/scanner.go
[failure] 82-82:
ps.writer undefined (type *ProbeScanner has no field or method writer)
🪛 GitHub Check: Build (darwin, arm64)
internal/scanner/scanner.go
[failure] 82-82:
ps.writer undefined (type *ProbeScanner has no field or method writer)
🪛 GitHub Check: Build (windows, amd64)
internal/scanner/scanner.go
[failure] 82-82:
ps.writer undefined (type *ProbeScanner has no field or method writer)
🪛 GitHub Check: Test (1.23)
internal/scanner/scanner.go
[failure] 82-82:
ps.writer undefined (type *ProbeScanner has no field or method writer)
🪛 GitHub Check: Build (linux, amd64)
internal/scanner/scanner.go
[failure] 82-82:
ps.writer undefined (type *ProbeScanner has no field or method writer)
🪛 GitHub Actions: PR #39
internal/scanner/scanner.go
[error] 82-82: Build failed: 'ps.writer' undefined (type *ProbeScanner has no field or method writer)
🔇 Additional comments (59)
cmd/kubeprobes/main.go (2)
16-17: Simplificação do tratamento de erro está correta.A remoção do
log.Fatalfe uso direto doos.Exit(1)é apropriada, pois o cobra já exibe mensagens de erro adequadas. Isso alinha com as práticas recomendadas do cobra.
6-7: Importação válida – nenhuma ação necessáriaO pacote
internal/scannerexiste eminternal/scanner/e ogo.moddefinemodule kubeprobes, portanto o caminho de importação"kubeprobes/internal/scanner"está correto..dockerignore (2)
11-11: Adição apropriada para exclusão de binários.A inclusão do diretório
bin/na lista de exclusões é uma boa prática para reduzir o contexto de build do Docker.
34-37: Excelente organização da seção Development.A nova seção Development com exclusões para
vendor/,*.tmp, e*.logmelhora significativamente a organização e reduz arquivos desnecessários no contexto de build.internal/cli/scan.go (2)
10-12: Padrão de wrapper bem implementado.A função
NewScanCommandcomo wrapper parascanner.NewScanCommand()é uma boa prática para separar responsabilidades entre a CLI e a lógica de scanner.
4-4: Importação dekubeprobes/internal/scannerestá correta
Após executargo mod tidye verificar o módulo (module kubeprobesem go.mod) e os módulos listados emgo list -m all, não há nenhum erro de importação estrutural. O caminhokubeprobes/internal/scanneré compatível com o módulo definido e resolve normalmente.Likely an incorrect or invalid review comment.
.github/workflows/release.yml (3)
7-7: Permissão necessária para operações Docker.A adição de
id-token: writeé apropriada para operações relacionadas ao Docker e publishing de imagens.
29-37: Configuração Docker bem estruturada.A configuração do login no GitHub Container Registry e setup do Docker Buildx são bem implementadas e necessárias para o build de imagens Docker.
34-34: Confirmar configuração do secret USER_TOKENUso de
secrets.USER_TOKENverificado de forma consistente nos workflows a seguir:
- .github/workflows/release.yml (password e variável de ambiente
GITHUB_TOKEN)- .github/workflows/trivy.yml (github-pat)
- .github/workflows/issue.yml (
GITHUB_TOKEN)Certifique-se de que o secret
USER_TOKENesteja criado nas configurações do repositório e possua as permissões necessárias.internal/cli/version.go (3)
10-17: Variáveis globais apropriadas para build-time values.O uso de variáveis globais para
Version,Commit, eDateé a abordagem padrão para informações definidas durante o build. Os valores padrão são apropriados para desenvolvimento.
49-61: Implementação robusta dos formatos de saída.A implementação dos três formatos de saída (default, short, json) está bem estruturada e fornece flexibilidade para diferentes casos de uso.
69-75: Excelente tratamento de erro não-fatal.O tratamento do erro de completion registration como warning em vez de falha fatal é uma excelente prática, permitindo que o comando funcione mesmo se a completion falhar.
Dockerfile (3)
2-2: Mudança de base image adequada para compatibilidadeA mudança de
cgr.dev/chainguard/go:1.24paragolang:1.24-alpineoferece melhor compatibilidade e suporte mais amplo, mantendo a segurança com a instalação explícita de certificados CA.
16-16: Base image Alpine apropriada para runtimeA mudança para
alpine:3.22.0como base do runtime é adequada, fornecendo um ambiente leve e seguro com os certificados CA necessários.
22-24: Configuração de usuário não-root bem implementadaA criação do usuário e grupo
kubeprobescom UID/GID 1001 segue as melhores práticas de segurança, evitando execução como root.internal/scanner/cmd.go (5)
15-23: Descrição aprimorada melhora a experiência do usuárioA descrição expandida explica claramente o propósito da ferramenta e a importância das probes de saúde, proporcionando melhor orientação aos usuários.
24-46: Exemplos abrangentes demonstram conformidade POSIXOs exemplos mostram diferentes sintaxes e casos de uso, incluindo flags agrupadas, ordem flexível e notação com equals, educando os usuários sobre as capacidades da CLI.
50-71: Mensagens de erro mais consistentes e clarasA mudança de "error getting" para "failed to read" torna as mensagens de erro mais consistentes e profissionais em todo o código.
94-101: Completion de shell bem implementadoA adição de completion personalizado para o flag
probe-typecom tratamento de erro não-fatal melhora a experiência do usuário sem comprometer a funcionalidade.
88-92: Descrições de flags mais detalhadasAs descrições expandidas dos flags incluem informações sobre padrões e comportamentos, tornando a ferramenta mais intuitiva.
internal/cli/root.go (3)
11-25: Descrição expandida e educativaA descrição detalhada explica a importância das probes de saúde no Kubernetes e enfatiza a conformidade POSIX, proporcionando excelente contexto educacional aos usuários.
26-45: Exemplos abrangentes demonstram capacidades da CLIOs exemplos cobrem cenários comuns de uso, incluindo sintaxe POSIX, diferentes tipos de flags e comandos, servindo como referência rápida para os usuários.
54-57: Estrutura de comandos bem organizadaA integração do comando version e o uso do wrapper CLI proporcionam uma arquitetura mais limpa e modular, facilitando manutenção e testes.
CONTRIBUTING.md (4)
17-21: Requisitos de qualidade bem definidosA adição de análise estática obrigatória, linters e cobertura mínima de 75% estabelece padrões claros de qualidade para contribuições.
22-53: Diretrizes de testes abrangentesAs seções detalhadas sobre tipos de testes obrigatórios, execução e padrões fornecem orientação clara para contribuidores, garantindo qualidade e consistência.
56-63: Processo de PR bem estruturadoO processo passo-a-passo com verificações de testes, cobertura e linting assegura que todas as contribuições mantenham os padrões de qualidade estabelecidos.
64-71: Checklist útil para completudeO checklist do PR serve como lembrete final para garantir que todos os aspectos importantes sejam verificados antes da submissão.
internal/cli/scan_test.go (3)
9-57: Testes bem estruturados para diferentes cenários.Os testes cobrem adequadamente os cenários de ajuda e erro, com captura correta de saída e verificação de erros. A estrutura table-driven está bem implementada.
59-76: Validação de flags está completa.O teste verifica a presença de todas as flags esperadas do comando scan, garantindo que a interface CLI esteja correta.
78-93: Teste de completion básico mas adequado.O teste verifica a existência da flag probe-type e seu texto de uso, o que é suficiente para validar o setup básico de completion.
docs/completion.md (1)
12-171: Documentação abrangente e bem estruturada.A documentação cobre todos os shells principais, fornece exemplos práticos claros e inclui uma seção de troubleshooting útil. O conteúdo está bem organizado e será muito útil para os usuários.
docs/docker.md (1)
15-156: Documentação Docker significativamente melhorada.A expansão da documentação inclui novos comandos (version, completion), exemplos mais abrangentes de uso do scan, e uma seção de dicas avançadas. A reorganização torna o conteúdo mais fácil de navegar e usar.
.github/workflows/ci.yml (1)
12-141: Workflow CI abrangente e bem estruturado.O workflow inclui todos os aspectos importantes: testes com múltiplas versões Go, linting, builds cross-platform, e scanning de segurança. O uso de cache e artefatos está bem implementado.
internal/scanner/scanner_test.go (6)
13-24: Mock client bem implementado.O mock client é simples e eficaz para os testes, permitindo simular tanto respostas de sucesso quanto erros.
26-88: Testes de validação abrangentes.Os testes cobrem todos os tipos de probe válidos, incluindo case-insensitive, e verificam adequadamente os cenários de erro com mensagens descritivas.
90-138: Validação de mensagens de erro aprimoradas.Os testes verificam que as mensagens de erro contêm informações úteis para troubleshooting, incluindo tipos válidos de probe e exemplos de uso.
140-213: Testes do constructor com client são completos.Os testes verificam adequadamente o comportamento do constructor, incluindo defaults de namespace, normalização de probe type e configuração de recommendations.
224-454: Testes de scanning cobrem todos os cenários críticos.Os testes incluem casos de pods não encontrados, erros de API, pods com todas as probes, pods com probes faltando, e múltiplos containers. A cobertura é excelente.
457-495: Função helper bem projetada.A função
createTestPodé flexível e permite criar pods de teste com diferentes configurações de probes, facilitando os testes.internal/cli/version_test.go (3)
10-80: Excelente cobertura de testes para diferentes formatos de saída!Os testes cobrem adequadamente os cenários principais do comando version, incluindo diferentes formatos de saída e validação de flags. A estrutura table-driven é apropriada e bem organizada.
82-111: Validação robusta de estrutura JSON.O teste
TestVersionCommandJsonOutputfaz uma validação adequada do formato JSON, incluindo unmarshalling e verificação de campos obrigatórios. Boa prática para garantir a integridade da saída JSON.
224-285: Excelente cobertura de conformidade POSIX.Os testes de conformidade POSIX são abrangentes e cobrem adequadamente diferentes sintaxes de flags. Esta é uma boa prática para garantir usabilidade consistente.
pkg/kubernetes/client_test.go (2)
11-67: Boa cobertura de cenários de configuração inválida.Os testes cobrem adequadamente diferentes cenários de falha na configuração do cliente Kubernetes, incluindo arquivos inexistentes e conteúdo inválido. As asserções de erro são apropriadas.
149-169: Teste de integração apropriadamente configurado.O teste de integração está corretamente marcado como skip por padrão, evitando falhas em ambientes sem cluster Kubernetes. Boa prática para testes que dependem de recursos externos.
internal/scanner/cmd_test.go (4)
13-35: Excelente estrutura básica de teste.O teste
TestNewScanCommandcobre adequadamente a criação e estrutura básica do comando, verificando propriedades essenciais como Use, Short, Long e RunE.
37-70: Boa validação de flags com dados estruturados.O teste de flags utiliza uma estrutura de dados bem organizada para validar todas as flags esperadas. A abordagem table-driven é apropriada e facilita a manutenção.
345-438: Excelente cobertura de conformidade POSIX.Os testes
TestPOSIXCommandLineSyntaxsão extremamente abrangentes e cobrem praticamente todos os cenários de sintaxe POSIX. Esta é uma implementação exemplar de testes de conformidade.
440-481: Boa validação de convenções de flags.O teste
TestPOSIXFlagConventionsverifica adequadamente as convenções de flags e detecta conflitos. A verificação de flags curtas duplicadas é uma boa prática.README.md (3)
62-73: Excelente adição de documentação sobre conformidade POSIX.A seção sobre sintaxe POSIX suportada é muito útil e bem estruturada. Os exemplos claramente demonstram diferentes formas de usar os comandos.
186-224: Seção de compatibilidade POSIX muito bem documentada.A seção "Compatibilidade POSIX" fornece informações valiosas sobre os benefícios e características suportadas. Os exemplos práticos ajudam os usuários a entender como usar efetivamente a ferramenta.
225-280: Seção de desenvolvimento bem estruturada.A seção "Desenvolvimento" fornece instruções claras sobre como executar testes e entender a estrutura do projeto. Informações sobre cobertura de testes são especialmente úteis.
internal/cli/root_test.go (4)
11-109: Excelente cobertura de testes para comando root.Os testes cobrem adequadamente diferentes aspectos do comando root, incluindo help, descrições melhoradas e exemplos. A estrutura table-driven é bem organizada.
111-137: Boa validação de disponibilidade de subcomandos.O teste
TestSubcommandAvailabilityverifica corretamente se os subcomandos esperados estão disponíveis. O comentário sobre comandos automaticamente adicionados pelo Cobra é útil.
216-296: Excelente cobertura de conformidade POSIX.Os testes de conformidade POSIX são muito abrangentes e cobrem diferentes cenários de uso de flags. A diferenciação entre flags de help e comandos de scan é bem implementada.
298-335: Boa validação de compatibilidade de flags.O teste
TestPOSIXFlagCompatibilityverifica corretamente se as flags curtas e longas correspondem ao mesmo objeto. Esta é uma validação importante para garantir consistência.internal/scanner/scanner.go (4)
19-23: Boa adição da interface para testabilidade!A criação da interface
KubernetesClienté uma excelente prática que permite injeção de dependência e facilita os testes unitários com mocks.
49-49: Excelente melhoria nas mensagens de erro!As mensagens de erro agora incluem explicações detalhadas, exemplos e dicas de troubleshooting, melhorando significativamente a experiência do usuário.
Also applies to: 54-55
87-91: Boa adição da contagem de containers!A contagem de containers escaneados fornece uma métrica útil para o usuário entender o escopo da verificação.
128-141: Excelente adição de sumário e dicas!O sumário com estatísticas, dicas sobre a flag
--recommendatione link para documentação melhoram significativamente a experiência do usuário e fornecem orientação clara sobre os próximos passos.
| func TestClient_GetPods_NilClient(t *testing.T) { | ||
| // Test the GetPods method signature and basic structure | ||
| // We can't test with a real client without a cluster, but we can test the structure | ||
|
|
||
| // This is more of a compilation test to ensure the method exists with correct signature | ||
| var client *Client | ||
|
|
||
| // This would panic with nil client, but that's expected behavior | ||
| // We're just testing that the method exists and has the right signature | ||
| defer func() { | ||
| if r := recover(); r != nil { | ||
| // Expected panic with nil client | ||
| t.Logf("Expected panic with nil client: %v", r) | ||
| } | ||
| }() | ||
|
|
||
| if client != nil { | ||
| _, err := client.GetPods(context.Background(), "default") | ||
| if err != nil { | ||
| t.Logf("GetPods method exists and returned error as expected: %v", err) | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Melhore a estrutura do teste de método GetPods.
O teste TestClient_GetPods_NilClient está usando defer para capturar panic, mas nunca chama o método que causaria o panic. Considere reestruturar para ser mais explícito sobre o que está sendo testado.
func TestClient_GetPods_NilClient(t *testing.T) {
- // Test the GetPods method signature and basic structure
- // We can't test with a real client without a cluster, but we can test the structure
-
- // This is more of a compilation test to ensure the method exists with correct signature
var client *Client
- // This would panic with nil client, but that's expected behavior
- // We're just testing that the method exists and has the right signature
- defer func() {
- if r := recover(); r != nil {
- // Expected panic with nil client
- t.Logf("Expected panic with nil client: %v", r)
- }
- }()
-
- if client != nil {
- _, err := client.GetPods(context.Background(), "default")
- if err != nil {
- t.Logf("GetPods method exists and returned error as expected: %v", err)
- }
- }
+ // Este é um teste de compilação para garantir que o método existe
+ // com a assinatura correta
+ if client == nil {
+ t.Log("Teste de compilação: método GetPods existe com assinatura correta")
+ }
}Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In pkg/kubernetes/client_test.go around lines 86 to 108, the test
TestClient_GetPods_NilClient uses defer to catch a panic but never actually
calls the GetPods method that would cause the panic. To fix this, remove the nil
check on client and explicitly call client.GetPods with a nil client inside the
deferred recover block to confirm the panic occurs, making the test more
explicit and meaningful.
| func TestRootCommand_Structure(t *testing.T) { | ||
| // Test that Execute function exists and can be called | ||
| // In a real scenario, this would execute the CLI | ||
|
|
||
| // This is a compilation test to ensure the function exists | ||
| // We don't actually call Execute() as it would try to run the CLI | ||
| t.Log("Execute function is available for use") | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Melhore o teste de estrutura do comando root.
O teste TestRootCommand_Structure é muito básico e não valida efetivamente a estrutura. Considere adicionar validação mais substantiva.
func TestRootCommand_Structure(t *testing.T) {
- // Test that Execute function exists and can be called
- // In a real scenario, this would execute the CLI
-
- // This is a compilation test to ensure the function exists
- // We don't actually call Execute() as it would try to run the CLI
- t.Log("Execute function is available for use")
+ // Criar comando root real para testar estrutura
+ cmd := &cobra.Command{
+ Use: "kubeprobes",
+ Short: "Kubeprobes is a CLI tool for scanning Kubernetes probes",
+ }
+
+ // Verificar propriedades básicas
+ if cmd.Use == "" {
+ t.Error("Comando root deve ter campo Use definido")
+ }
+ if cmd.Short == "" {
+ t.Error("Comando root deve ter descrição curta")
+ }
+
+ // Verificar que Execute existe (teste de compilação)
+ if cmd.Execute == nil {
+ t.Error("Comando root deve ter método Execute")
+ }
}Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In internal/cli/root_test.go around lines 139 to 146, the
TestRootCommand_Structure test is too basic and does not effectively validate
the root command structure. Enhance the test by actually creating an instance of
the root command, checking its properties such as name, usage, and available
subcommands, and verifying that the Execute function can be called without error
in a controlled manner. This will provide a more substantive validation of the
root command's structure.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
CI Feedback 🧐A test triggered by this PR failed. Here is an AI-generated analysis of the failure:
|
CI Feedback 🧐A test triggered by this PR failed. Here is an AI-generated analysis of the failure:
|
… antes do restante do código para otimizar o cache de camadas.
…ara maior flexibilidade e precisão nas informações da imagem Docker.
|
@copilot Resolva os comentários. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
♻️ Duplicate comments (1)
internal/scanner/scanner.go (1)
125-125: Corrigir return statement órfão.Há um
return nilórfão que ficou após o código malformado e precisa ser integrado corretamente na lógica do métodoScan.Este return statement deve fazer parte da lógica quando não há pods encontrados no namespace.
🧹 Nitpick comments (3)
.github/workflows/ci.yml (3)
19-19: Corrigir espaços em branco desnecessários no final das linhas.O YAMLlint detectou espaços em branco no final de várias linhas que devem ser removidos para manter a formatação limpa.
- +Aplique esta correção nas linhas 19, 72, 98 e 128.
Also applies to: 72-72, 98-98, 128-128
96-96: Corrigir indentação incorreta.A indentação está incorreta - esperado 8 espaços mas encontrado 10.
- - goos: windows - goarch: arm64 + - goos: windows + goarch: arm64
141-141: Adicionar nova linha no final do arquivo.O arquivo deve terminar com uma nova linha para seguir as convenções padrão.
govulncheck ./... +
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
.github/workflows/ci.yml(1 hunks).goreleaser.yml(1 hunks)Dockerfile(1 hunks)internal/cli/version_test.go(1 hunks)internal/scanner/scanner.go(4 hunks)
✅ Files skipped from review due to trivial changes (1)
- .goreleaser.yml
🚧 Files skipped from review as they are similar to previous changes (1)
- Dockerfile
🧰 Additional context used
🧬 Code Graph Analysis (1)
internal/scanner/scanner.go (1)
pkg/kubernetes/client.go (1)
NewClient(18-32)
🪛 YAMLlint (1.37.1)
.github/workflows/ci.yml
[error] 19-19: trailing spaces
(trailing-spaces)
[error] 72-72: trailing spaces
(trailing-spaces)
[warning] 96-96: wrong indentation: expected 8 but found 10
(indentation)
[error] 98-98: trailing spaces
(trailing-spaces)
[error] 128-128: trailing spaces
(trailing-spaces)
[error] 141-141: no new line character at the end of file
(new-line-at-end-of-file)
🪛 GitHub Check: Build (darwin, arm64)
internal/scanner/scanner.go
[failure] 125-125:
syntax error: non-declaration statement outside function body
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
🪛 GitHub Check: Build (linux, amd64)
internal/scanner/scanner.go
[failure] 125-125:
syntax error: non-declaration statement outside function body
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
🪛 GitHub Check: Security Scan
internal/scanner/scanner.go
[failure] 118-118:
undefined: kubeClient
[failure] 114-114:
undefined: os
[failure] 108-108:
undefined: io
[failure] 104-104:
undefined: kubeClient
[failure] 100-100:
undefined: io
[failure] 104-104:
expected ')', found KubernetesClient
[failure] 103-103:
missing parameter name
[failure] 103-103:
expected '(', found NewProbeScannerWithClient
[failure] 84-84:
expected statement, found 'package'
🪛 GitHub Check: Build (windows, amd64)
internal/scanner/scanner.go
[failure] 125-125:
syntax error: non-declaration statement outside function body
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
🪛 GitHub Check: Build (darwin, amd64)
internal/scanner/scanner.go
[failure] 125-125:
syntax error: non-declaration statement outside function body
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
🪛 GitHub Check: Build (linux, arm64)
internal/scanner/scanner.go
[failure] 125-125:
syntax error: non-declaration statement outside function body
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
🪛 GitHub Check: Test (1.23)
internal/scanner/scanner.go
[failure] 125-125:
syntax error: non-declaration statement outside function body
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
🪛 GitHub Check: Lint
internal/scanner/scanner.go
[failure] 84-84:
syntax error: unexpected keyword package, expected }
[failure] 125-125:
syntax error: non-declaration statement outside function body) (typecheck)
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
[failure] 125-125:
syntax error: non-declaration statement outside function body) (typecheck)
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
internal/cli/version_test.go
[failure] 192-192:
declared and not used: cmd (typecheck)
🪛 GitHub Check: Test (1.22)
internal/scanner/scanner.go
[failure] 125-125:
syntax error: non-declaration statement outside function body
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
🪛 GitHub Actions: CI
internal/scanner/scanner.go
[error] 84-84: syntax error: unexpected keyword package, expected }
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Analyze (go)
🔇 Additional comments (8)
internal/cli/version_test.go (8)
10-80: Boa cobertura de testes para o comando version!A implementação usa table-driven tests de forma eficaz, cobrindo diferentes formatos de saída e validações de ajuda.
82-111: Excelente validação da saída JSON!O teste valida corretamente a estrutura JSON e verifica a presença de todos os campos obrigatórios.
113-132: Bom teste de caso extremo!Verifica corretamente que o comando usa o formato padrão quando um formato inválido é especificado.
134-156: Validação completa das propriedades da flag!O teste verifica corretamente o shorthand, valor padrão e descrição da flag output.
158-172: Teste adequado dentro das limitações!O comentário documenta corretamente a limitação de testar a função de completion diretamente.
174-189: Boa validação da documentação de exemplos!Verifica que os exemplos estão presentes e contêm uso básico e formato de saída curto.
221-282: Excelente cobertura de conformidade POSIX!O teste verifica comprehensivamente diferentes sintaxes de flags POSIX, incluindo formato curto, longo e com igual.
284-315: Boa validação das convenções de flag!Verifica corretamente que a ajuda mostra tanto a forma curta quanto a longa das flags.
| // internal/scanner/scanner.go | ||
|
|
||
| package scanner | ||
|
|
||
| import ( | ||
| "io" | ||
| "os" | ||
| "strings" | ||
|
|
||
| // ... other imports ... | ||
| ) | ||
|
|
||
| // ProbeScanner handles the scanning logic | ||
| type ProbeScanner struct { | ||
| kubeClient KubernetesClient | ||
| namespace string | ||
| probeType string | ||
| recommendation bool | ||
| writer io.Writer | ||
| } | ||
|
|
||
| func NewProbeScannerWithClient( | ||
| kubeClient KubernetesClient, | ||
| namespace string, | ||
| probeType string, | ||
| recommendation bool, | ||
| writer io.Writer, | ||
| ) *ProbeScanner { | ||
| if namespace == "" { | ||
| namespace = "default" | ||
| } | ||
| if writer == nil { | ||
| writer = os.Stdout | ||
| } | ||
|
|
||
| return &ProbeScanner{ | ||
| kubeClient: kubeClient, | ||
| namespace: namespace, | ||
| probeType: strings.ToLower(probeType), | ||
| recommendation: recommendation, | ||
| writer: writer, | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Erro crítico: código duplicado malformado causando falhas de build.
Há um bloco de código duplicado e malformado inserido no meio do arquivo que está causando erros de sintaxe. Este código deve ser removido e as alterações necessárias devem ser aplicadas corretamente ao código original.
Remova todo o bloco de código duplicado das linhas 82-124 e aplique as seguintes correções ao código original:
- Adicione o campo
writerao structProbeScanner:
// ProbeScanner handles the scanning logic
type ProbeScanner struct {
kubeClient KubernetesClient
namespace string
probeType string
recommendation bool
+ writer io.Writer
}- Atualize o construtor
NewProbeScannerWithClientpara aceitar e inicializar o writer:
-func NewProbeScannerWithClient(kubeClient KubernetesClient, namespace, probeType string, recommendation bool) *ProbeScanner {
+func NewProbeScannerWithClient(kubeClient KubernetesClient, namespace, probeType string, recommendation bool, writer io.Writer) *ProbeScanner {
if namespace == "" {
namespace = "default"
}
+ if writer == nil {
+ writer = os.Stdout
+ }
return &ProbeScanner{
kubeClient: kubeClient,
namespace: namespace,
probeType: strings.ToLower(probeType),
recommendation: recommendation,
+ writer: writer,
}
}- Adicione as importações necessárias:
import (
"context"
"fmt"
+ "io"
+ "os"
"strings"
"kubeprobes/pkg/kubernetes"
corev1 "k8s.io/api/core/v1"
)- Atualize
NewProbeScannerpara passaros.Stdoutcomo writer:
- return NewProbeScannerWithClient(kubeClient, namespace, probeType, recommendation), nil
+ return NewProbeScannerWithClient(kubeClient, namespace, probeType, recommendation, os.Stdout), nil- Substitua todas as chamadas
fmt.Printfporfmt.Fprintf(ps.writer, ...)no métodoScan.
Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 GitHub Check: Build (darwin, arm64)
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
🪛 GitHub Check: Build (linux, amd64)
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
🪛 GitHub Check: Security Scan
[failure] 118-118:
undefined: kubeClient
[failure] 114-114:
undefined: os
[failure] 108-108:
undefined: io
[failure] 104-104:
undefined: kubeClient
[failure] 100-100:
undefined: io
[failure] 104-104:
expected ')', found KubernetesClient
[failure] 103-103:
missing parameter name
[failure] 103-103:
expected '(', found NewProbeScannerWithClient
[failure] 84-84:
expected statement, found 'package'
🪛 GitHub Check: Build (windows, amd64)
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
🪛 GitHub Check: Build (darwin, amd64)
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
🪛 GitHub Check: Build (linux, arm64)
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
🪛 GitHub Check: Test (1.23)
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
🪛 GitHub Check: Lint
[failure] 84-84:
syntax error: unexpected keyword package, expected }
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
🪛 GitHub Check: Test (1.22)
[failure] 86-86:
syntax error: unexpected keyword import, expected }
[failure] 84-84:
syntax error: unexpected keyword package, expected }
🪛 GitHub Actions: CI
[error] 84-84: syntax error: unexpected keyword package, expected }
🤖 Prompt for AI Agents
In internal/scanner/scanner.go from lines 82 to 124, remove the duplicated and
malformed code block causing build errors. Ensure the ProbeScanner struct
includes the writer field of type io.Writer. Modify the
NewProbeScannerWithClient constructor to accept a writer parameter and
initialize the writer field, defaulting to os.Stdout if nil. Add necessary
imports such as "io", "os", and "strings". Update the NewProbeScanner function
to call NewProbeScannerWithClient passing os.Stdout as the writer. Finally,
replace all fmt.Printf calls in the Scan method with fmt.Fprintf using the
ProbeScanner's writer field to direct output correctly.
| func TestVersionCommand_ErrorHandling(t *testing.T) { | ||
| cmd := NewVersionCommand() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Remova a declaração de variável não utilizada.
A variável cmd é declarada mas não utilizada, pois uma nova instância é criada dentro do loop de teste.
Aplique esta correção:
func TestVersionCommand_ErrorHandling(t *testing.T) {
- cmd := NewVersionCommand()
-
// Test with various edge cases🧰 Tools
🪛 GitHub Check: Lint
[failure] 192-192:
declared and not used: cmd (typecheck)
🤖 Prompt for AI Agents
In internal/cli/version_test.go around lines 191 to 192, the variable 'cmd' is
declared but never used because a new instance is created inside the test loop.
Remove the unused 'cmd' variable declaration to clean up the code and avoid
unnecessary declarations.
Add comprehensive CLI subcommands with version and improved scan
Implement extensive unit tests for all components
Enhance error messages with troubleshooting guidance
Add POSIX-compliant command line syntax support
Changes diagram
Changes walkthrough 📝
1 files
Simplify error handling in main function5 files
Add comprehensive CLI structure with subcommandsCreate scan command wrapperImplement version command with multiple output formatsEnhance scan command with POSIX complianceImprove scanner with better error messages6 files
Add comprehensive root command testsAdd scan command testsAdd comprehensive version command testsAdd extensive scanner command testsAdd comprehensive scanner logic testsAdd Kubernetes client tests5 files
Update dockerignore with development filesAdd comprehensive CI workflowEnhance release workflow with Docker supportAdd Docker image configurationImprove Docker image with Alpine base4 files
Add testing requirements and guidelinesAdd comprehensive documentation with POSIX examplesAdd auto-completion documentationEnhance Docker usage documentationSummary by CodeRabbit
Summary by CodeRabbit
Novos Recursos
Melhorias
Correções
Testes
Infraestrutura