Skip to content

refactor: simplify cli args handling - #744

Merged
gfyrag merged 2 commits into
mainfrom
refactor/flags-handling
Mar 6, 2025
Merged

refactor: simplify cli args handling#744
gfyrag merged 2 commits into
mainfrom
refactor/flags-handling

Conversation

@gfyrag

@gfyrag gfyrag commented Mar 6, 2025

Copy link
Copy Markdown
Contributor

No description provided.

@gfyrag
gfyrag requested a review from a team as a code owner March 6, 2025 13:09
@coderabbitai

coderabbitai Bot commented Mar 6, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes introduce a new generic function LoadConfig in the configuration file that leverages Viper to bind command-line flags and unmarshal them into a provided type. The serve command now uses a new ServeConfig struct, consolidating various configuration parameters while deprecated configuration methods have been removed. Similarly, worker configuration has been refactored to use an exported WorkerConfiguration type, with both serve and worker commands updating their error handling and configuration loading processes accordingly.

Changes

File(s) Change Summary
cmd/config.go Introduced LoadConfig[V any](cmd *cobra.Command) that encapsulates Viper initialization, flag binding, and configuration unmarshalling.
cmd/serve.go Added ServeConfig struct to consolidate server configuration parameters. Updated NewServeCommand to use LoadConfig[ServeConfig](cmd) and modified error handling for configuration loading. Deprecated certain flags for backward compatibility.
cmd/worker.go Introduced WorkerConfiguration type for worker configuration handling. Updated configuration loading to use LoadConfig[WorkerConfiguration](cmd) and improved error handling. Simplified instantiation of storage.NewFXModule.

Sequence Diagram(s)

sequenceDiagram
    participant CMD as Cobra Command
    participant LC as LoadConfig[ServeConfig]
    participant V as Viper & Unmarshal
    participant SC as ServeCommand Setup

    CMD->>LC: Call LoadConfig[ServeConfig](cmd)
    LC->>V: Bind flags and unmarshal config
    V-->>LC: Return ServeConfig or error
    LC-->>CMD: Return config/error
    CMD->>SC: Process configuration and setup command
Loading
sequenceDiagram
    participant CMD as Cobra Command
    participant LC as LoadConfig[WorkerConfiguration]
    participant V as Viper & Unmarshal
    participant WC as WorkerCommand Setup

    CMD->>LC: Call LoadConfig[WorkerConfiguration](cmd)
    LC->>V: Bind flags and unmarshal config
    V-->>LC: Return WorkerConfiguration or error
    LC-->>CMD: Return config/error
    CMD->>WC: Initialize worker with configuration values
Loading

Poem

I’m a rabbit, hopping through the code,
Discovering new functions on a bright, fresh road.
LoadConfig leads the way, precise and swift,
Serving and working with a magical gift.
My whiskers twitch with glee in every byte—
A happy hop in code, morning to night!
🐰✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@gfyrag
gfyrag force-pushed the refactor/flags-handling branch from 077e095 to cfc9431 Compare March 6, 2025 13:11

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
cmd/config.go (1)

9-21: Well-designed generic configuration loader function

This is a great use of Go generics to create a reusable configuration loading pattern. The function properly handles error cases and provides context in error messages.

A small suggestion for improved spacing: consider adding a space between the closing parenthesis and opening brace in the function signature.

-func LoadConfig[V any](cmd *cobra.Command) (*V, error){
+func LoadConfig[V any](cmd *cobra.Command) (*V, error) {
cmd/serve.go (1)

172-176: Clearly marked deprecated flags

It's good practice to mark deprecated flags with a comment. Consider adding explicit deprecation notices using cobra's MarkFlagDeprecated to provide more information to users.

 // Deprecated flags
 cmd.Flags().Bool(ExperimentalFeaturesFlag, false, "Enable features configurability")
+cmd.Flags().MarkDeprecated(ExperimentalFeaturesFlag, "This flag will be removed in a future version")
 cmd.Flags().Bool(NumscriptInterpreterFlag, false, "Enable experimental numscript rewrite")
+cmd.Flags().MarkDeprecated(NumscriptInterpreterFlag, "This flag will be removed in a future version")
 cmd.Flags().String(NumscriptInterpreterFlagsToPass, "", "Feature flags to pass to the experimental numscript interpreter")
+cmd.Flags().MarkDeprecated(NumscriptInterpreterFlagsToPass, "This flag will be removed in a future version")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 523ac1c and 077e095.

⛔ Files ignored due to path filters (3)
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum, !**/*.sum
  • tools/generator/go.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (3)
  • cmd/config.go (1 hunks)
  • cmd/serve.go (5 hunks)
  • cmd/worker.go (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Tests
🔇 Additional comments (8)
cmd/worker.go (3)

21-24: Good struct design for worker configuration

The struct fields use proper mapstructure tags that match the flag names defined as constants, making the mapping between CLI flags and configuration clear.


41-44: Improved error handling with LoadConfig

The refactored code uses the generic LoadConfig function to handle configuration, improving error handling with proper error wrapping.


52-56: Storage module configuration simplification

The storage module initialization has been simplified, and worker configuration is now properly sourced from the loaded config struct. This makes the code more maintainable.

cmd/serve.go (5)

40-54: Well-structured ServeConfig with embedded WorkerConfiguration

The ServeConfig struct effectively consolidates all configuration parameters with proper mapstructure tags. Embedding WorkerConfiguration is a good approach to reuse the worker settings.


78-81: Consistent error handling pattern

Good use of the generic LoadConfig function with proper error wrapping that follows the same pattern used in worker.go.


97-98: Configuration access is now more consistent

Configuration values are now consistently accessed from the cfg struct, making the code more maintainable and easier to understand.

Also applies to: 100-104, 109-110, 112-112, 117-119, 121-123


147-147: Server binding uses configuration value

The HTTP server binding address is now correctly accessed from the configuration struct.


154-156: Proper use of embedded WorkerConfiguration

The worker module correctly uses the HashLogsBlockCRONSpec and HashLogsBlockMaxSize from the embedded WorkerConfiguration structure.

@codecov

codecov Bot commented Mar 6, 2025

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 70.45455% with 13 lines in your changes missing coverage. Please review.

Project coverage is 81.96%. Comparing base (523ac1c) to head (7aa8c84).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
cmd/config.go 40.00% 4 Missing and 2 partials ⚠️
cmd/serve.go 85.18% 3 Missing and 1 partial ⚠️
cmd/worker.go 57.14% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #744      +/-   ##
==========================================
- Coverage   82.01%   81.96%   -0.06%     
==========================================
  Files         135      136       +1     
  Lines        7289     7263      -26     
==========================================
- Hits         5978     5953      -25     
  Misses       1006     1006              
+ Partials      305      304       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@gfyrag
gfyrag force-pushed the refactor/flags-handling branch 2 times, most recently from 4d96ad5 to c425e36 Compare March 6, 2025 13:45
@gfyrag
gfyrag force-pushed the refactor/flags-handling branch from c425e36 to ab4361d Compare March 6, 2025 13:46

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
cmd/serve.go (2)

52-54: Consider documenting experimental features

The experimental features flags such as NumscriptInterpreter, NumscriptInterpreterFlags, and ExperimentalFeaturesEnabled are included in the configuration struct, but it might be helpful to add comments explaining their purpose and implications.


171-173: Ensure deprecated flags are properly documented

These flags have been moved to the configuration struct but are still added directly to the command. Consider adding a deprecation notice using cmd.Flag(ExperimentalFeaturesFlag).Deprecated = "Use configuration file instead" to inform users about the preferred way to configure these features.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ab4361d and 1ae89f5.

📒 Files selected for processing (1)
  • cmd/serve.go (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Tests
🔇 Additional comments (6)
cmd/serve.go (6)

40-55: Well-structured configuration consolidation

The new ServeConfig struct nicely consolidates all configuration parameters into a single type, making the configuration management more maintainable and type-safe. The use of mapstructure tags ensures proper mapping between configuration keys and struct fields.


41-41: Good use of composition with WorkerConfiguration

Embedding the WorkerConfiguration struct with the squash option is a clean approach to reuse worker-related configuration without duplicating fields.


79-82: Improved configuration loading with type safety

The generic LoadConfig[ServeConfig] provides better type safety compared to manually retrieving flags. The error handling has also been improved with a more descriptive error message using fmt.Errorf.


98-99: Consistent use of configuration struct fields

The code now consistently uses fields from the configuration struct instead of directly accessing flags, which improves maintainability and reduces the chance of errors from mismatched flag names.

Also applies to: 101-103, 104-105, 110-111, 113-114, 118-120, 122-124


152-157: Clean conditional module inclusion

The worker module is conditionally included based on the configuration, which is a clean approach. The use of the embedded WorkerConfiguration fields is also consistent with the rest of the code.


127-136: Improved struct field formatting

The dependency injection parameter struct has better formatting with each field on its own line, which improves readability.

@gfyrag
gfyrag enabled auto-merge March 6, 2025 15:49
@gfyrag
gfyrag force-pushed the refactor/flags-handling branch from 1ae89f5 to 7aa8c84 Compare March 6, 2025 16:03

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
cmd/serve.go (1)

171-173: Appropriate handling of deprecated flags.

Keeping these flags while marking them as deprecated provides a good migration path for users. Consider adding deprecation notices in logs or documentation to encourage migration to the new configuration approach.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1ae89f5 and 7aa8c84.

⛔ Files ignored due to path filters (1)
  • go.mod is excluded by !**/*.mod
📒 Files selected for processing (1)
  • cmd/serve.go (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Tests
🔇 Additional comments (4)
cmd/serve.go (4)

40-55: Well-structured configuration consolidation.

This new ServeConfig struct nicely consolidates all configuration parameters into a single, coherent structure. The embedded WorkerConfiguration is a good use of composition, and the mapstructure tags ensure correct binding with Viper.


79-82: Good use of generics for type-safe configuration loading.

The implementation of the generic LoadConfig function improves type safety and reduces boilerplate code. The error handling is also improved with a more descriptive error message.


98-111: Consistent use of configuration object.

The code now consistently references the cfg object properties rather than accessing flags directly, which improves maintainability and readability.


152-157:

Details

❓ Verification inconclusive

Verify worker configuration mapping.

Ensure that the fields from embedded WorkerConfiguration correctly map to the worker module config. Consider adding a test to verify this mapping works as expected.


🏁 Script executed:

#!/bin/bash
# Check how WorkerConfiguration is defined and its relationship to worker.ModuleConfig
grep -r "type WorkerConfiguration" .

Length of output: 149


Review: Confirm Worker Configuration Mapping in cmd/serve.go

The current mapping from cfg.WorkerConfiguration to the worker.ModuleConfig inside cmd/serve.go (lines 152–157) appears to be correct—assigning HashLogsBlockCRONSpec to Schedule and HashLogsBlockMaxSize to MaxBlockSize. Note that the definition of WorkerConfiguration is present in both ./pkg/testserver/worker.go and ./cmd/worker.go; please ensure these definitions consistently include the expected fields.

As a safeguard against future regressions, consider adding a unit test that verifies any changes in the configuration are accurately reflected in the worker module configuration.

@gfyrag
gfyrag added this pull request to the merge queue Mar 6, 2025
Merged via the queue into main with commit 6ad3fce Mar 6, 2025
@gfyrag
gfyrag deleted the refactor/flags-handling branch March 6, 2025 16:11
@gfyrag gfyrag mentioned this pull request Mar 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

3 participants