Skip to content

refactor: main.go to use cliFlags struct for flag parsing#31

Closed
mayurkr wants to merge 3 commits into
mainfrom
added-fixes-1
Closed

refactor: main.go to use cliFlags struct for flag parsing#31
mayurkr wants to merge 3 commits into
mainfrom
added-fixes-1

Conversation

@mayurkr
Copy link
Copy Markdown
Contributor

@mayurkr mayurkr commented Mar 7, 2026

This pull request refactors the cmd/main.go entrypoint and the ClusterScanReconciler to improve code organization, readability, and maintainability. The main function is broken into smaller, purpose-specific functions, and the ClusterScanReconciler logic is modularized into helper methods for each phase of the reconciliation process. These changes make the codebase easier to understand and extend.

Key changes include:

Entrypoint Refactoring (cmd/main.go):

  • Split the monolithic main() function into smaller functions: flag parsing (parseFlags), TLS options construction (buildTLSOpts), webhook and metrics server configuration (buildWebhookServer, buildMetricsOptions), and controller setup (setupControllers). This improves readability and maintainability. [1] [2] [3] [4]
  • Introduced a cliFlags struct to encapsulate all CLI flag values, reducing the number of top-level variables and simplifying flag handling.
  • Centralized controller registration in the new setupControllers function, replacing repeated controller setup blocks with a single call. [1] [2]

ClusterScanReconciler Refactoring (internal/controller/clusterscan_controller.go):

  • Broke down the Reconcile method into smaller helper methods for handling finalizers (handleFinalizer), suspension (handleSuspend), scan execution (executeScan), error handling (handleTargetResolutionError), scanner execution (runScanners), severity counting (incrementSeverityCount), and compliance evaluation (evaluateCompliance). This modularization clarifies the reconciliation flow and makes each concern easier to test and modify. [1] [2] [3] [4] [5] [6]
  • Added missing import for logr.Logger to support improved logging in helper methods.

These changes collectively enhance the maintainability and clarity of the operator's core logic, making it easier for future contributors to understand and extend.

…r functions for flag parsing and application setup.
Copilot AI review requested due to automatic review settings March 7, 2026 04:39
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, 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 significantly enhances the operator's codebase by refactoring several core components to improve code organization, readability, and maintainability. It achieves this by breaking down large, complex functions into smaller, more focused helper methods and encapsulating related logic within dedicated structs or functions. These changes streamline the main execution flow, making the system easier to understand, test, and extend for future development.

Highlights

  • Entrypoint Refactoring (cmd/main.go): The monolithic main() function was split into smaller, purpose-specific functions (parseFlags, buildTLSOpts, buildWebhookServer, buildMetricsOptions, setupControllers) to improve readability and maintainability. A cliFlags struct was introduced to encapsulate all CLI flag values, simplifying flag handling. Controller registration was centralized in the new setupControllers function.
  • ClusterScanReconciler Refactoring (internal/controller/clusterscan_controller.go): The Reconcile method was broken down into smaller helper methods for managing finalizers (handleFinalizer), suspension (handleSuspend), scan execution (executeScan), error handling (handleTargetResolutionError), scanner execution (runScanners), severity counting (incrementSeverityCount), compliance evaluation (evaluateCompliance), report creation (createScanReport), and final status updates (updateFinalStatus). This modularization clarifies the reconciliation flow and improves testability.
  • CostPolicyReconciler Refactoring (internal/controller/costpolicy_controller.go): The Reconcile method was refactored to extract logic for resolving target namespaces, evaluating rightsizing candidates, and updating the policy status into dedicated helper functions (resolveTargetNamespaces, evaluateRightsizing, podNeedsRightsizing, updateStatus).
  • SecurityPolicyReconciler Refactoring (internal/controller/securitypolicy_controller.go): The Reconcile method was modularized into helper functions (handlePodResolutionError, runPolicyScanners, ingestFindingsToCorrelator, updatePolicyStatus, recordScanConditions) to handle distinct phases of security policy reconciliation, enhancing clarity and maintainability.
  • GitOps Discovery Refactoring (internal/gitops/discovery/discovery.go): The Discover function was refactored by extracting the logic for categorizing files and appending raw sources into separate helper functions (categorizeFiles, appendRawSources), improving code organization.
  • Helm Source Parser Refactoring (internal/gitops/source/source.go): The HelmSourceParser.Parse method was refactored to extract the logic for classifying Helm chart files (Chart.yaml, values files, template files) into a dedicated helper function (classifyHelmFiles).
  • Pod Security Scanner Refactoring (internal/scanner/pod_security.go): The Scan method was broken down into smaller, focused helper functions (checkHostNamespaces, checkHostPaths, checkCapabilities, checkProcessSharing) to individually check different aspects of pod security, reducing complexity.
  • Privilege Escalation Scanner Refactoring (internal/scanner/privilege_escalation.go): The Scan method was refactored into helper functions (checkPodEscalation, checkContainerEscalation) to separate checks for pod-level and container-level privilege escalation vectors.
Changelog
  • cmd/main.go
    • Introduced a cliFlags struct to centralize command-line flag values.
    • Created parseFlags function to handle CLI flag registration and parsing.
    • Extracted TLS options construction into a buildTLSOpts function.
    • Created buildWebhookServer and buildMetricsOptions functions for configuring respective servers.
    • Introduced setupControllers function to centralize the registration of all Kubernetes controllers.
    • Updated the main function to utilize the newly created helper functions and the cliFlags struct.
    • Removed the //nolint:gocyclo directive due to improved cyclomatic complexity.
  • internal/controller/clusterscan_controller.go
    • Added an import for github.com/go-logr/logr to support improved logging.
    • Removed the //nolint:gocyclo directive from the Reconcile method.
    • Refactored the Reconcile method into several helper functions: handleFinalizer, handleSuspend, executeScan, handleTargetResolutionError, runScanners, incrementSeverityCount, evaluateCompliance, createScanReport, and updateFinalStatus.
  • internal/controller/costpolicy_controller.go
    • Removed the //nolint:gocyclo directive from the Reconcile method.
    • Refactored the Reconcile method into resolveTargetNamespaces, evaluateRightsizing, podNeedsRightsizing, and updateStatus helper functions.
  • internal/controller/securitypolicy_controller.go
    • Added an import for github.com/go-logr/logr to support improved logging.
    • Removed the //nolint:gocyclo directive from the Reconcile method.
    • Refactored the Reconcile method into several helper functions: handlePodResolutionError, runPolicyScanners, ingestFindingsToCorrelator, updatePolicyStatus, and recordScanConditions.
    • Replaced a manual min calculation with the standard min function.
  • internal/gitops/discovery/discovery.go
    • Removed the //nolint:gocyclo directive from the Discover function.
    • Refactored the Discover function by extracting file categorization into categorizeFiles and raw source appending into appendRawSources.
  • internal/gitops/source/source.go
    • Removed the //nolint:gocyclo directive from the HelmSourceParser.Parse method.
    • Refactored the HelmSourceParser.Parse method by extracting file classification logic into a classifyHelmFiles helper function.
  • internal/scanner/pod_security.go
    • Removed the //nolint:gocyclo directive from the Scan method.
    • Refactored the Scan method into helper functions: checkHostNamespaces, checkHostPaths, checkCapabilities, and checkProcessSharing.
  • internal/scanner/privilege_escalation.go
    • Removed the //nolint:gocyclo directive from the Scan method.
    • Refactored the Scan method into helper functions: checkPodEscalation and checkContainerEscalation.
Activity
  • No specific activity from reviewers or comments has been recorded for this pull request yet.
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 by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

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 pull request 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 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. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

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

  1. 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.

Copy link
Copy Markdown
Contributor

Copilot AI left a 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 refactors the operator entrypoint and several controllers/scanners to improve readability by extracting complex logic into focused helper functions, while keeping behavior largely consistent.

Changes:

  • Refactors cmd/main.go to centralize flag parsing into a cliFlags struct and move setup logic into parseFlags, TLS/metrics/webhook builders, and setupControllers.
  • Modularizes reconciliation logic in ClusterScanReconciler, SecurityPolicyReconciler, and CostPolicyReconciler into smaller helper methods.
  • Splits scanner logic in PrivilegeEscalationScanner and PodSecurityScanner into pod-level/container-level helper checks.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
cmd/main.go Refactors main into flag parsing + builder helpers and central controller registration.
internal/controller/clusterscan_controller.go Breaks Reconcile into helper phases (finalizer, suspend, execute, reporting).
internal/controller/securitypolicy_controller.go Extracts scanner execution, correlator ingestion, and status updates into helpers.
internal/controller/costpolicy_controller.go Extracts namespace resolution, rightsizing evaluation, and status updates into helpers.
internal/scanner/privilege_escalation.go Splits pod vs container privilege-escalation checks into helper methods.
internal/scanner/pod_security.go Splits host namespace/path/capability/process-sharing checks into helper methods.
internal/gitops/source/source.go Extracts Helm file classification into classifyHelmFiles.
internal/gitops/discovery/discovery.go Splits discovery scanning vs raw-source appending into helper functions.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 57 to 60
// Scan implements Scanner.
//
//nolint:gocyclo // Scanner logic evaluates multiple interrelated pod fields
// Scan implements Scanner.
func (s *PodSecurityScanner) Scan(_ context.Context, pods []corev1.Pod, _ map[string]string) ([]Finding, error) {
Copy link

Copilot AI Mar 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Scan doc comment is duplicated (// Scan implements Scanner. appears twice). This is probably accidental; remove the redundant comment (or reintroduce the previous nolint explanation if you meant to keep a second comment line).

Copilot uses AI. Check for mistakes.

if err := r.Status().Update(ctx, scan); err != nil {
return ctrl.Result{}, fmt.Errorf("updating status: %w", err)
log.Error(err, "Failed to update ClusterScan status")
Copy link

Copilot AI Mar 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updateFinalStatus logs and continues when the ClusterScan status update fails. That means the reconcile will still emit a "ScanCompleted" event and increment success metrics even though the status write didn't persist, and it also skips controller-runtime retry/backoff behavior. Consider returning the status update error (and only recording completion events/metrics after a successful status update) so failures are retried promptly and metrics remain accurate.

Suggested change
log.Error(err, "Failed to update ClusterScan status")
log.Error(err, "Failed to update ClusterScan status")
// Record a failed reconcile for visibility and avoid emitting
// successful completion events/metrics when the status update
// itself did not persist.
aotmetrics.ReconcileTotal.WithLabelValues("clusterscan", "error").Inc()
return

Copilot uses AI. Check for mistakes.
// Scan implements Scanner.
//
//nolint:gocyclo // Container iteration involves multiple contextual checks
// Scan implements Scanner.
Copy link

Copilot AI Mar 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Scan doc comment is duplicated (// Scan implements Scanner. appears twice). This ends up in generated docs and is likely accidental; remove the redundant comment (or restore the prior nolint comment if that was the intent).

Suggested change
// Scan implements Scanner.

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a 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 primarily focuses on extensive code refactoring across multiple Go files to improve modularity, readability, and maintainability, specifically targeting functions with high cyclomatic complexity. In cmd/main.go, command-line flag parsing, TLS option building, webhook server creation, metrics options configuration, and controller setup logic have all been extracted into dedicated helper functions and a cliFlags struct. Similarly, in internal/controller/clusterscan_controller.go, costpolicy_controller.go, and securitypolicy_controller.go, the Reconcile methods have been broken down into smaller, more focused helper functions to manage finalizers, suspension, target resolution, scanning, compliance evaluation, report creation, and status updates. The //nolint:gocyclo comments were removed from these refactored functions, indicating a successful reduction in complexity. Further refactoring occurred in internal/gitops/discovery/discovery.go and internal/gitops/source/source.go to modularize file categorization and Helm chart parsing. Finally, internal/scanner/pod_security.go and internal/scanner/privilege_escalation.go saw their Scan methods refactored into specific check functions for host namespaces, paths, capabilities, process sharing, and privilege escalation vectors.

@mayurkr
Copy link
Copy Markdown
Contributor Author

mayurkr commented Apr 12, 2026

Closing — all 8 files have diverged significantly after 6 merged PRs (including v1.0 cloud expansion). The refactoring intent is still valid (all 8 //nolint:gocyclo directives remain), but rebasing would be more work than a fresh PR against current main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants