Skip to content
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

feat: Improve command line argument handling #56

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

sitaowang1998
Copy link
Collaborator

@sitaowang1998 sitaowang1998 commented Jan 15, 2025

Description

spider_worker and spider_scheduler do not print help message when --help is required or no argument is provided. They also throw uncaught messages when value is missing or unknown argument is provided. Improve the command line argument handling to resolve #51.

Validation performed

  • GitHub workflow pass
  • Unit tests pass in dev container
  • Integration tests pass in dev container
  • spider_worker and spider_scheduler print help message when --help is provided
  • spider_worker and spider_scheduler print help message when no argument is provided
  • spider_worker and spider_scheduler print meaningful error message when argument or value missing
  • spider_worker and spider_scheduler print meaningful error message when unknown argument is provided

Summary by CodeRabbit

  • New Features

    • Enhanced argument parsing for scheduler and worker components.
    • Improved error handling for command-line arguments.
  • Bug Fixes

    • Streamlined argument validation process.
    • Added more robust error messaging for missing required parameters.
  • Refactor

    • Updated function signatures to directly populate configuration variables.
    • Simplified argument parsing logic in main functions.

Copy link

coderabbitai bot commented Jan 15, 2025

Walkthrough

The pull request modifies the argument parsing functions in both spider_scheduler and spider_worker components. The changes focus on improving command-line interface (CLI) argument handling by introducing more robust error checking, adding support for required arguments, and implementing usage information display. The modifications standardize the argument parsing approach across both components, enhancing user experience by providing clearer guidance when arguments are missing or incorrectly specified.

Changes

File Change Summary
src/spider/scheduler/scheduler.cpp - Updated parse_args function signature to accept host, port, and storage_url parameters
- Added boolean return type for argument parsing
- Improved error handling and usage information display
- Added <iostream> header
src/spider/worker/worker.cpp - Modified parse_args function to accept host, storage_url, and libs parameters
- Implemented boolean return type for argument parsing
- Enhanced error handling with usage information
- Added <iostream> header

Assessment against linked issues

Objective Addressed Explanation
Print CLI usage info [#51]
Handle --help flag [#51]
Catch parsing exceptions [#51]
Provide clear error messages [#51]

Possibly related PRs

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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. (Beta)
  • @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.

Copy link

@coderabbitai coderabbitai bot left a comment

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)
src/spider/scheduler/scheduler.cpp (1)

41-44: Consider using std::format for usage message.

The usage message could benefit from using std::format for better maintainability, consistent with the project's use of fmt library elsewhere.

-char const* const cUsage
-        = "Usage: spider_scheduler --host <host> --port <port> --storage_url <url>";
+char const* const cUsage = std::format(
+        "Usage: {} --host <host> --port <port> --storage_url <url>",
+        "spider_scheduler");
src/spider/worker/worker.cpp (1)

53-55: Consider using std::format for usage message.

The usage message could benefit from using std::format for better maintainability, consistent with the project's use of fmt library elsewhere.

-char const* const cUsage = "Usage: spider_worker --host <host> --storage_url <storage_url> --libs <libs>";
+char const* const cUsage = std::format(
+        "Usage: {} --host <host> --storage_url <storage_url> --libs <libs>",
+        "spider_worker");
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between becbf55 and 3c5e18b.

📒 Files selected for processing (2)
  • src/spider/scheduler/scheduler.cpp (3 hunks)
  • src/spider/worker/worker.cpp (3 hunks)
🧰 Additional context used
🪛 cppcheck (2.10-2)
src/spider/worker/worker.cpp

[performance] 97-97: Variable 'id' is assigned in constructor body. Consider performing initialization in initialization list.

(useInitializationList)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: non-storage-unit-tests (ubuntu-24.04)
  • GitHub Check: non-storage-unit-tests (ubuntu-22.04)
  • GitHub Check: lint
🔇 Additional comments (6)
src/spider/scheduler/scheduler.cpp (3)

5-5: LGTM!

The addition of the <iostream> header is necessary for the new error output functionality.


172-172: LGTM!

The main function correctly uses the new parse_args signature.


45-96: Verify error handling for edge cases.

The argument parsing logic looks good, but let's verify the handling of edge cases:

  1. When only --help is provided
  2. When invalid port numbers are supplied
✅ Verification successful

Edge cases are properly handled in the argument parsing implementation

The code demonstrates robust handling of all key edge cases:

  • Help flag (--help) displays usage information and available options
  • Port validation is enforced through the unsigned short type
  • Missing or invalid arguments show clear error messages with usage instructions
  • Distinct error codes for different failure scenarios
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test cases covering argument parsing edge cases
rg -l "TestSchedulerArgParse|test.*parse.*args" -g "test_*.cpp"

Length of output: 214


Script:

#!/bin/bash
# Find test files
fd -e cpp -e hpp test

# Search for help flag handling
rg -A 5 "\"help\".*program_options"

# Search for port validation or error handling
rg -A 10 "port.*program_options::value"

Length of output: 549


Script:

#!/bin/bash
# Check scheduler test files content
cat tests/scheduler/test-SchedulerServer.cpp
cat tests/scheduler/test-SchedulerPolicy.cpp

# Look for main function implementation
rg -l "int\s+main\s*\(" --type cpp

Length of output: 11927


Script:

#!/bin/bash
# Find and check the main scheduler program file
fd -e cpp scheduler$ src/
cat src/spider/scheduler/scheduler.cpp

Length of output: 8522

src/spider/worker/worker.cpp (3)

8-8: LGTM!

The addition of the <iostream> header is necessary for the new error output functionality.


360-360: LGTM!

The main function correctly uses the new parse_args signature.


56-100: Verify handling of empty --libs argument.

The argument parsing logic looks good, but let's verify the handling of edge cases:

  1. When only --help is provided
  2. When --libs is provided without any values
🧰 Tools
🪛 cppcheck (2.10-2)

[performance] 97-97: Variable 'id' is assigned in constructor body. Consider performing initialization in initialization list.

(useInitializationList)

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
src/spider/worker/worker.cpp (4)

54-55: Enhance the usage message with more descriptive information.

The current usage message is concise but could be more helpful. Consider adding brief descriptions of what each argument expects.

-char const* const cUsage
-        = "Usage: spider_worker --host <host> --storage_url <storage_url> --libs <libs>";
+char const* const cUsage
+        = "Usage: spider_worker --host <host_address> --storage_url <mysql_url> --libs <path_to_libraries>\n"
+          "Example: spider_worker --host localhost:8080 --storage_url mysql://user:pass@localhost/spider --libs /path/to/lib1.so,/path/to/lib2.so";

103-108: Standardize error message format.

Error messages should follow a consistent format and provide clear guidance.

-        std::cerr << "spider_worker: " << e.what() << "\n";
-        std::cerr << cUsage << "\n";
-        std::cerr << "Try 'spider_worker --help' for more information.\n";
+        std::cerr << "Error: " << e.what() << "\n"
+                  << cUsage << "\n"
+                  << "For more information, run: spider_worker --help\n";

368-368: Maintain consistency in variable naming.

The variable worker_addr is used for the host parameter, which could be confusing. Consider using consistent naming throughout the codebase.

-    if (!parse_args(argc, argv, worker_addr, storage_url, libs)) {
+    if (!parse_args(argc, argv, host_addr, storage_url, libs)) {

Also update the variable declaration above:

-    std::string worker_addr;
+    std::string host_addr;

57-108: Consider implementing structured error handling.

The current error handling approach mixes concerns between argument parsing, validation, and error reporting. Consider implementing a dedicated error handling structure.

Suggestions:

  1. Create a dedicated ArgumentParser class to encapsulate parsing logic
  2. Define an ArgumentError class hierarchy for different types of errors
  3. Implement a separate error formatter for consistent error message formatting

This would improve maintainability and make it easier to add new argument validation rules in the future.

🧰 Tools
🪛 cppcheck (2.10-2)

[performance] 97-97: Variable 'id' is assigned in constructor body. Consider performing initialization in initialization list.

(useInitializationList)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3c5e18b and ff98aaf.

📒 Files selected for processing (1)
  • src/spider/worker/worker.cpp (3 hunks)
🧰 Additional context used
🪛 cppcheck (2.10-2)
src/spider/worker/worker.cpp

[performance] 97-97: Variable 'id' is assigned in constructor body. Consider performing initialization in initialization list.

(useInitializationList)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: non-storage-unit-tests (ubuntu-24.04)
  • GitHub Check: non-storage-unit-tests (ubuntu-22.04)
  • GitHub Check: lint

Comment on lines +93 to +99
if (!variables.contains("host") && !variables.contains("storage_url")
&& !variables.contains("libs"))
{
std::cout << cUsage << "\n";
std::cout << desc << "\n";
return false;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the argument presence check logic.

The current condition is incorrect as it checks if all arguments are missing. It should check if any required argument is missing.

-        if (!variables.contains("host") && !variables.contains("storage_url")
-            && !variables.contains("libs"))
+        if (variables.count("help")) {
+            std::cout << desc << "\n";
+            return false;
+        }
+
+        if (!variables.contains("host") || !variables.contains("storage_url")
+            || !variables.contains("libs"))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!variables.contains("host") && !variables.contains("storage_url")
&& !variables.contains("libs"))
{
std::cout << cUsage << "\n";
std::cout << desc << "\n";
return false;
}
if (variables.count("help")) {
std::cout << desc << "\n";
return false;
}
if (!variables.contains("host") || !variables.contains("storage_url")
|| !variables.contains("libs"))
{
std::cout << cUsage << "\n";
std::cout << desc << "\n";
return false;
}
🧰 Tools
🪛 cppcheck (2.10-2)

[performance] 97-97: Variable 'id' is assigned in constructor body. Consider performing initialization in initialization list.

(useInitializationList)

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.

spider_scheduler and spider_worker don't print CLI usage info
1 participant