Skip to content

Quality/gocyclo#363

Merged
cjimti merged 56 commits intomasterfrom
quality/gocyclo
Jan 6, 2026
Merged

Quality/gocyclo#363
cjimti merged 56 commits intomasterfrom
quality/gocyclo

Conversation

@cjimti
Copy link
Copy Markdown
Member

@cjimti cjimti commented Jan 6, 2026

Reduces cyclomatic complexity across the codebase to improve Go Report Card score and code maintainability. This PR refactors 5 high-complexity functions by extracting helper methods and consolidating switch statement handling.

Major Complexity Reductions

Function Before After Reduction
DetailModel.Update 87 13 85%
runCmd 82 15 82%
RootModel.Update 76 11 86%
SyncPodForwards 34 6 82%
AnalyzeHandler.Analyze 29 5 83%

Functions Over Threshold (15)

  • Before: 22 functions
  • After: 17 functions

Refactoring Techniques Used

  1. Extracted message handlers in Bubble Tea Update functions following MVU pattern
  2. Created helper methods for distinct responsibilities (e.g., handleKeyMsg, handleMouseMsg)
  3. Consolidated switch cases using dispatcher functions (handleComponentMessage, handleBrowseMessage)
  4. Separated concerns in service forwarding (e.g., isPodEligible, removeStaleForwards, syncNormalService)
  5. Extracted error classification and recommendation builders in analyze handler

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • Test improvement (new or updated tests)
  • Documentation update
  • Stability/performance improvement
  • Build/CI improvement

Note: New features are developed by maintainers only. See CONTRIBUTING.md for details.

Related Issues

Fixes # (Go Report Card gocyclo improvements)

Testing

  • Ran go test ./... locally (22 packages pass)
  • Tested manually with a Kubernetes cluster
  • Added new tests for changes (if applicable)

CI Verification

go test ./...     # 22 packages pass
go vet ./...      # No issues
golangci-lint     # 0 issues
gofmt -l .        # 0 files need formatting
go build          # Successful

Checklist

  • My code follows the project's style guidelines (go fmt, go vet)
  • I have read CONTRIBUTING.md
  • I have updated documentation if needed
  • This PR is focused and does not include unrelated changes

Files Changed

pkg/fwdtui/components/detail.go

  • Extracted handleKeyMsg, handleMouseMsg from Update
  • Added handleNumberKey, handleTabNavigation, handleYankKey
  • Added scroll handlers: handleHTTPScroll, handleVimScrollHTTP, handleVimScrollLogs

cmd/kubefwd/services/services.go

  • Extracted ~15 helper functions from runCmd:
    • validateEnvironment, detectAndConfigureIdleMode
    • initializeTUIMode, initializeAPIMode
    • setupHostsFile, handleStaleIPs
    • createNamespaceManager, wireUpAdapters
    • startAPIServer, runMainLoop, performShutdown

pkg/fwdtui/ui.go

  • Refactored RootModel.Update using dispatcher pattern
  • Added handleWindowSizeMsg, handleKeyMsg, handleMouseMsg
  • Added handleGlobalKeys, handleFocusedComponentKey
  • Added handleComponentMessage, handleBrowseMessage
  • Added message-specific handlers for metrics, events, logs, pod logs

pkg/fwdservice/fwdservice.go

  • Extracted from SyncPodForwards:
    • isPodEligible, scheduleRetry, getForwardInfos
    • removeStaleForwards, podStillEligible, findKeyToKeep
    • syncHeadlessService, syncNormalService, doSyncPods

pkg/fwdapi/handlers/analyze.go

  • Extracted from Analyze:
    • classifyError, buildIssues
    • buildRecommendations, buildActions
    • determineStatus, buildSummaryMessage, getUptime

Formatting Fixes

  • pkg/fwdapi/middleware/middleware.go
  • pkg/fwdns/manager_test.go

cjimti added 30 commits January 5, 2026 22:05
- Introduced a test case for `CheckRoot` to verify behavior when running as root and non-root.
- Introduced extensive test coverage for LogsHandler system-related endpoints, including `System` and `ClearSystem`.
- Added tests for KubernetesHandler endpoints covering pod logs, pod listing, events, and endpoints retrieval.
- Ensured robust handling of edge cases such as missing parameters, invalid input, and uninitialized states.
- Added test cases for `isPodReady` covering various pod phases and container readiness scenarios.
- Introduced tests for `CloseIdleHTTPConnections` to verify behavior with and without `CloseIdleConnections` support in custom transports.
- Introduced tests for `RemoveAllocatedHosts` covering scenarios with and without registered hostnames.
- Verified graceful handling of permission-related errors when accessing `/etc/hosts`.
- Ensured registry state cleanup before and after test execution.
- Added test cases for `GetCurrentContext` covering valid configurations, invalid paths, and empty config scenarios.
- Verified correct context retrieval and error handling for different inputs.
- Added test cases for multiple models, including `DetailModel`, `HeaderModel`, `HelpModel`, `LogsModel`, `ServicesModel`, and `StatusBarModel`.
- Verified initialization, setter functionalities, and rendering methods for different scenarios.
- Ensured coverage of edge cases and improved reliability of model behaviors.
- Comprehensive test coverage added for `DetailModel` update scenarios, including handling of new message types and keypress events.
- Extended tests for HTTP tab scrolling, pod log requests, snapshot handling, and connect string generation.
- Verified edge cases and ensured robustness of model behavior under various conditions.
- Added test cases for `GetRESTClient` covering scenarios with unreachable clusters and invalid or empty configurations.
- Verified proper error handling and ensured function executes without panicking under various conditions.
- Added coverage for `KubernetesDiscoveryHTTP` methods: pod logs, pod listing, events, endpoints, and pod details retrieval.
- Included tests for error-handling scenarios and specific behaviors under various conditions.
- Added unit tests for `AnalysisProviderHTTP`, `HTTPTrafficProviderHTTP`, and `HistoryProviderHTTP` methods.
- Added tests for `NamespaceManagerAdapter` lazy initialization and error handling when the manager is nil.
- Introduced test cases for `Manager` shutdown handling, namespace manager setters, and `Run` method behavior.
- Verified pod discovery methods, including pod logs, pod listing, events, and endpoints retrieval.
- Added tests for `ListNamespaces`, `ListServices`, `GetService`, `ListPods`, `GetPod`, `GetEvents`, and `GetEndpoints` in `KubernetesDiscoveryAdapter`.
- Verified functionalities with a fake Kubernetes client for namespaces, services, pods, events, and endpoints.
- Included tests for edge cases like non-existent resources, terminating pods, and filtered events.
…lModel` behaviors

- Added test cases covering keypress handling, window size adjustments, scrolling behaviors, filtering, and various edge scenarios.
- Verified interactions with auto-follow, filtering, navigation, and rendering across the models.
- Ensured robustness and error handling in model update methods.
- Added tests for `StopGlobalPodInformer` to verify it stops correctly without panicking.
- Introduced coverage for `ResetGlobalPodInformer`, ensuring proper state reset and cleanup after execution.
…aviors

- Added tests for `StopWatcher`, `StopAll`, `GetCurrentContext`, `SetClientSet`, and `GetClientSet` methods in `Manager`.
- Introduced coverage for `NamespaceWatcher` methods, including `Info`.
- Verified manager cleanup, watcher removal, and robustness under various conditions.
- Added tests for `handleSetupLocalDevPrompt`, `handleConnectionGuidePrompt`, `handleForwardNamespacePrompt`, `handleDebugServicePrompt`, `handleQuickConnectPrompt`, and `handleAnalyzeIssuesPrompt`.
- Verified prompt behavior for various argument combinations, including `namespace`, `context`, `service_name`, `language`, and `symptom`.
- Ensured proper handling of nil arguments and validated prompt descriptions, messages, and content.
…`, and `handleContextsResource`

- Added test cases for `handleStatusResource`, including scenarios with healthy states, states with errors, and no active services.
- Added tests for `handleHTTPTrafficResource`, covering HTTP traffic snapshots, nil metrics, and no traffic scenarios.
- Added tests for `handleContextsResource`, verifying Kubernetes context listing behavior with mock discovery, including error and success cases.
- Added tests for `SetAnalysisProvider`, `SetHTTPTrafficProvider`, and `SetHistoryProvider`.
- Verified initial nil states and behavior when setting nil providers.
- Added test cases for `boundedSize`, covering various scenarios, including zero size, negative size, below/at/above limit, and extreme values.
- Verified expected behavior and proper limit enforcement.
- Introduced `TestBoundedSize` to validate the behavior of the `boundedSize` helper function.
- Covered scenarios with zero, negative, below/at/above limit, and extreme sizes to ensure proper enforcement of size limits.
- Added tests for `handleGetConnectionInfo`, including state fallback scenarios, namespace/context filtering, and service-not-found cases.
- Introduced tests for `handleFindServices` with various filters (namespace, port, query) and their combinations.
- Added tests for HTTP traffic, analysis, quick status, and history handlers with mock providers to validate responses and edge cases.
- Ensured proper handling of nil providers, missing keys, and default parameter values.
- Introduced `TestManager_SetCallbacks_WithModel` to verify proper handling of callback setters with both nil and non-nil values.
- Ensured no panics and correct behavior for `SetErroredServicesReconnector` and `SetRemoveForwardCallback`.
…space`

- Added tests to validate success and error paths for `loadServices`, ensuring proper handling of service discovery and errors.
- Covered scenarios for `forwardService`, including correct forwarding and error handling during conflicts.
- Introduced tests for `forwardNamespace` to verify namespace forwarding behavior, service counts, and error handling.
- Introduced tests for `ServiceForwardedMsg`, `NamespaceForwardedMsg`, and `BrowseContextsLoadedMsg` to validate forwarding behavior and error handling.
- Added tests for user interactions, including key presses (`Tab`, `?`, `Enter`), mouse clicks, and wheel events to confirm focus switching and functionality in logs and services views.
- Verified log streaming error handling and detail panel visibility during pod and service updates.
- Covered edge cases for nil streamers, missing selections, and context loading with default values.
…nostics adapters

- Introduced tests for `ServiceControllerAdapter` methods (`Reconnect`, `Sync`, and `ReconnectAll`) to validate error handling and behavior.
- Added `KubernetesDiscoveryAdapter` tests for `ListPods` with filters (service name, field selector, and label selector).
- Covered `DiagnosticsProviderAdapter` methods (`GetServiceDiagnostic` and `GetForwardDiagnostic`) under various scenarios, including active, error, partial states, and missing services/forwards.
- Introduced tests for `GetPod` covering pod states: terminating with waiting containers, running containers.
- Validated container state handling for `Terminating`, `Waiting`, and `Running` scenarios, including state reasons, last states, and container statuses.
- Introduced tests for `ReconnectErroredMsg`, `OpenDetailMsg`, `RemoveForwardMsg`, and various `KeyMsg` scenarios.
- Validated behavior for reconnecting errored services, opening detail panels, removing forwards with and without callbacks, and keypress handling (e.g., `r`, `q`, `/`).
- Covered edge cases like empty keys, nil commands, and filtering states.
- Added tests for `GetEvents` with specified limits and default limits.
- Validated behavior with event sorting by timestamp and handling of empty event lists.
cjimti and others added 26 commits January 6, 2026 00:48
- Add tests for addServiceHandler with valid and headless services
- Add tests for deleteServiceHandler with valid service
- Add tests for updateServiceHandler with selector/port changes
- Add tests for removeNamespaceServices with services in registry
- Add tests for NamespaceWatcher.Info not running state
- Add tests for Manager.StopWatcher with empty context
- Add tests for Manager.ListWatchers with watchers
- Add tests for parsePortMap with port mappings
- Add tests for splitPortMapping edge cases
- Add tests for lazy namespace manager adapter with real manager
- Add test for Manager.Run with missing state reader
- Coverage: fwdns 55.7% → 61.9%, total 77.3% → 77.6%

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Replace unused func parameters with _ (blank identifier)
- Fix mock implementations in browse_test.go, components_test.go
- Fix handler functions in events_test.go
- Fix manager_test.go mock implementations
- Fix fuzz_test.go, fwdhost_test.go, fwdpub_test.go unused params
- Fix cmd/kubefwd.go and cmd/mcp.go cobra callback params

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Convert if-else chains to switch statements throughout codebase
- Fix assignOp: use += instead of = ... +
- Fix singleCaseSwitch: convert single-case switches to if statements
- Standardize status calculation pattern across:
  - pkg/fwdapi/adapters.go
  - pkg/fwdapi/handlers/analyze.go
  - pkg/fwdapi/handlers/http_traffic.go
  - pkg/fwdapi/handlers/services.go
  - pkg/fwdmcp/resources.go
  - pkg/fwdmcp/tools.go
  - pkg/fwdtui/components/browse.go
  - pkg/fwdtui/components/detail.go
  - pkg/fwdtui/components/header.go
  - pkg/fwdtui/components/statusbar.go
  - cmd/kubefwd/services/services.go

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
…eir rules

- Added `gocritic`, `revive`, `predeclared`, and `nilnil` linters.
- Enabled specific tags and disabled noisy checks for `gocritic`.
- Configured selective rules for `revive` with customized severities.
- Increased issue limits per linter and for duplicate issues to improve coverage.
- Added exclusions for test files to relax unused parameters checks.
- Replace `0644` with `0o644` for explicit octal file permissions.
- Rename variables (`state` → `stateReader`, `events` → `eventItems`) for better readability and consistency.
- Update `http.NewRequest` to use `http.NoBody` instead of `nil` for clarity.
- Simplify and improve event sorting and limiting logic in `adapters.go`.
- Rename variables (`state` → `stateReader`, `context` → `k8sContext`) to improve readability and disambiguate semantics.
- Use `strings.EqualFold` for case-insensitive string comparisons in log filtering.
- Simplify context handling in multiple methods, ensuring proper fallback to the current context when absent.
- Update test variable names for improved readability (e.g., `events` → `eventList`, `count = 0` → `count`).
- Use `http.NoBody` instead of `nil` in `httptest.NewRequest` for explicit intent.
- Replace numeric file permissions (`0644`, `0755`) with explicit octal literals (`0o644`, `0o755`) for clarity.
- Improve file content comparison by using `bytes.Equal`.
…es and test-specific exclusions

- Disable `shadow`, `nestingReduce`, `evalOrder`, `deferUnlambda`, and `exposedSyncMutex` to reduce noise and false positives.
- Add `nilnil` to test-specific linters for common return patterns.
- Configure exclusions for test files, interfaces, and intentional patterns in `pkg` code.
…ce` methods in `adapters_test.go`.

- Add unit tests for `splitLogLines` with various newline scenarios.
- Add tests for `GetPodLogs` handling invalid `sinceTime`, non-existent pods, extreme `tailLines`, and valid options.
- Add scenario for `AddService` with a `nil` namespace manager.
…t.go`

- Include tests for `StreamNilStreamer`, `StreamClosedChannel`, `StreamWithTypeFilter`, and event-to-response mapping.
- Add coverage for optional and empty fields in `mapEventToResponse`.
- Verify event type parsing for all valid and default scenarios.
…rAdapter`

- Add tests for `ListNamespaces` and `GetNamespace` (non-existent case) in `NamespaceManagerAdapter`.
- Validate behavior with a nil manager in `LazyNamespaceManagerAdapter`, including error cases for `AddNamespace`, `RemoveNamespace`, and `GetNamespace`.
…l_test.go`

- Add tests for service generation (`KFT1Services`, `KFT2Services`) and snapshot creation with/without headless services.
- Include tests for forwarding snapshot generation and store population methods (`PopulateStore`, `PopulateStoreKFT1`, `PopulateStoreKFT2`).
- Expand test coverage for IP formatting, integer-to-string conversion, and store assertions (e.g., empty store, service/forward existence).
- Validate namespace-specific service and forward counts.
- Cover scenarios including successful dialing, error handling, nil metrics, and multiple protocols.
- Ensure proper wrapping of connections with `MetricsConnection` when metrics are provided.
- Cover scenarios for stream creation (data streams, error streams, nil metrics).
- Include tests for connection operations: `Close`, `CloseChan`, `SetIdleTimeout`, and `RemoveStreams`.
- Validate correct wrapping and unwrapping of streams.
…nused parameters

- Standardize signatures in mock methods by replacing unused parameters with `_`.
- Update relevant test cases to ensure consistency and readability.
- Add new test cases for `RemoveEmptyKey` in `handlers_test.go` and service snapshot functionality in `registry_test.go`.
- Replace `int` with `int32` for `TargetPort` in test service definitions.
- Enhance assertion behavior by replacing `t.Error` with `t.Fatal` for critical test failures.
Resolved merge conflicts in test files:
- pkg/fwdapi/manager_test.go: Use t.Fatal for nil checks, keep additional tests
- pkg/fwdapi/adapters_test.go: Use t.Fatal for nil checks, intstr.FromInt32, keep tests
- pkg/fwdapi/handlers/handlers_test.go: Keep event streaming tests
- .gitignore: Keep coverage.html entry

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
…determination, and recommendation generation logic.

- Introduced `classifyError`, `determineStatus`, `buildSummaryMessage`, `buildIssues`, and `buildRecommendations` to simplify `Analyze` method logic.
- Improved readability and maintainability by reducing nested loops and conditions.
- Enhanced testability with smaller, focused functions for error handling and analysis steps.
- Extracted specific handlers (`handleKeyMsg`, `handleMouseMsg`, `handleClearCopied`, etc.) to simplify `Update` method.
- Improved readability and maintainability by grouping behavior into focused methods.
- Enhanced key and mouse event handling with clearer responsibilities for scroll, tab navigation, and clipboard operations.
- Extracted specific handlers (`handleKeyMsg`, `handleMouseMsg`, `handleClearCopied`, etc.) to simplify `Update` method.
- Improved readability and maintainability by grouping behavior into focused methods.
- Enhanced key and mouse event handling with clearer responsibilities for scroll, tab navigation, and clipboard operations.
…zation, signal handling, and namespace management logic

- Extracted `validateEnvironment`, `setupSignalHandler`, `createNamespaceManager`, and other focused functions to simplify `runCmd`.
- Improved readability and maintainability by grouping responsibilities into modular methods.
- Enhanced namespace and context resolution logic with clearer separation of concerns.
- Extracted specific handlers (`handleKeyMsg`, `handleMouseMsg`, `handleBrowseMessage`, etc.) to simplify `Update` method.
- Improved readability and maintainability by grouping behavior into smaller, focused methods.
- Enhanced message handling with clearer separation of responsibilities for components and global operations.
@cjimti cjimti self-assigned this Jan 6, 2026
@cjimti cjimti merged commit dd8a3d2 into master Jan 6, 2026
10 checks passed
@cjimti cjimti deleted the quality/gocyclo branch January 6, 2026 21:39
@codecov
Copy link
Copy Markdown

codecov bot commented Jan 6, 2026

Codecov Report

❌ Patch coverage is 57.10754% with 347 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.48%. Comparing base (6ad2509) to head (05e9240).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
cmd/kubefwd/services/services.go 0.00% 222 Missing ⚠️
pkg/fwdtui/ui.go 80.91% 47 Missing and 3 partials ⚠️
pkg/fwdtui/components/detail.go 75.30% 30 Missing and 10 partials ⚠️
pkg/fwdservice/fwdservice.go 58.82% 22 Missing and 6 partials ⚠️
pkg/fwdapi/handlers/analyze.go 92.63% 5 Missing and 2 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master     #363      +/-   ##
==========================================
+ Coverage   77.71%   80.48%   +2.76%     
==========================================
  Files          70       70              
  Lines       12491    12620     +129     
==========================================
+ Hits         9708    10157     +449     
+ Misses       2377     2050     -327     
- Partials      406      413       +7     
Files with missing lines Coverage Δ
pkg/fwdapi/handlers/analyze.go 90.29% <92.63%> (+0.18%) ⬆️
pkg/fwdservice/fwdservice.go 77.21% <58.82%> (+0.78%) ⬆️
pkg/fwdtui/components/detail.go 75.64% <75.30%> (-0.21%) ⬇️
pkg/fwdtui/ui.go 75.41% <80.91%> (+2.08%) ⬆️
cmd/kubefwd/services/services.go 11.40% <0.00%> (-1.55%) ⬇️

... and 11 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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.

1 participant