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

Generate shell completion scripts #36

Closed
wants to merge 1 commit into from

Conversation

romch007
Copy link

@romch007 romch007 commented Jan 13, 2025

This PR adds shell completion script generation using clap_complete, both at build time and runtime. There is now a new command line option:

--gen-completion <GEN_COMPLETION>
    Generate shell completion script [possible values: bash, elvish, fish, powershell, zsh]

The completion scripts will also be generated in target/debug/build/pest_fmt-xxxxxxxxxxxxxxx/out/

Summary by CodeRabbit

  • New Features

    • Added shell completion script generation for command-line interface.
    • Enhanced CLI with new command-line arguments for file formatting and shell completion options.
  • Chores

    • Updated project dependencies to support new CLI functionality.
    • Refactored command-line argument parsing mechanism.

Copy link

coderabbitai bot commented Jan 13, 2025

Walkthrough

The pull request introduces shell completion script generation for a command-line application. It adds the clap_complete dependency and modifies the project's CLI structure to enable automatic generation of completion scripts for various shell environments. The implementation includes updates to Cargo.toml for new dependencies, a build.rs script for generating completions, enhancements to cli.rs with new argument parsing capabilities, and modifications to main.rs to support the new completion generation feature.

Changes

File Change Summary
Cargo.toml Added clap_complete dependency in [dependencies] and [build-dependencies]; Repeated clap dependency in [build-dependencies]
build.rs Added main() function to generate shell completion scripts for different shell types
src/cli.rs Introduced Args struct with new command-line arguments; Added print_completions() function for generating shell completion scripts
src/main.rs Added cli module; Updated argument parsing to use cli::Args::parse(); Added support for shell completion generation

Sequence Diagram

sequenceDiagram
    participant Build as Build Script
    participant CLI as CLI Args
    participant Shell as Shell Environment
    
    Build->>CLI: Define Command Structure
    Build->>Build: Determine Output Directory
    Build->>Shell: Generate Completion Scripts
    Shell-->>Build: Save Completion Scripts
Loading

Poem

🐰 Behold, a CLI with rabbit's might,
Completions dancing, shell's delight!
With clap and magic, scripts unfurl,
Typing made easy, commands uncurl
A coding rabbit's playful art! 🚀


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: 3

🧹 Nitpick comments (3)
build.rs (1)

14-16: Add progress feedback during generation

Consider adding build script output to inform about the completion script generation progress.

     for &shell in Shell::value_variants() {
+        println!("cargo:warning=Generating {} completion script...", shell);
         generate_to(shell, &mut cmd, "pestfmt", &out_dir).unwrap();
     }
src/cli.rs (1)

7-9: Improve documentation for the file field

The documentation should clarify that "." means the current directory and that multiple files/paths can be provided.

-    /// The file or path to format
+    /// One or more files or directories to format
+    /// If a directory is specified, all .pest files in it will be formatted recursively
+    /// Defaults to the current directory (".")
Cargo.toml (1)

19-19: Consider using workspace dependencies

The clap and clap_complete dependencies are duplicated in both [dependencies] and [build-dependencies]. Consider using workspace dependencies to maintain consistent versions.

[workspace.dependencies]
clap = { version = "4.4.15", features = ["derive"] }
clap_complete = "4.5.42"

[dependencies]
-clap = { version = "4.4.15", features = ["derive"] }
-clap_complete = "4.5.42"
+clap = { workspace = true }
+clap_complete = { workspace = true }

[build-dependencies]
-clap = { version = "4.4.15", features = ["derive"] }
-clap_complete = "4.5.42"
+clap = { workspace = true }
+clap_complete = { workspace = true }

Also applies to: 27-29

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e9cb1f6 and dc39619.

📒 Files selected for processing (4)
  • Cargo.toml (1 hunks)
  • build.rs (1 hunks)
  • src/cli.rs (1 hunks)
  • src/main.rs (1 hunks)
🔇 Additional comments (1)
src/main.rs (1)

13-16: 🛠️ Refactor suggestion

Improve error handling for completion generation

The completion generation should handle potential errors from print_completions.

     if let Some(generator) = cli.gen_completion {
         let mut cmd = cli::Args::command();
-        cli::print_completions(generator, &mut cmd);
+        cli::print_completions(generator, &mut cmd)
+            .map_err(|e| format!("Failed to generate completion script: {}", e))?;
     } else if cli.stdin {

Likely invalid or redundant comment.

build.rs Show resolved Hide resolved
build.rs Show resolved Hide resolved
src/cli.rs Outdated
Comment on lines 19 to 23
pub fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
generate(gen, cmd, cmd.get_name().to_string(), &mut std::io::stdout());
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider error handling in print_completions

The function writes directly to stdout without handling potential I/O errors.

-pub fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
+pub fn print_completions<G: Generator>(gen: G, cmd: &mut Command) -> std::io::Result<()> {
-    generate(gen, cmd, cmd.get_name().to_string(), &mut std::io::stdout());
+    generate(gen, cmd, cmd.get_name().to_string(), &mut std::io::stdout())?;
+    Ok(())
}
📝 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
pub fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
generate(gen, cmd, cmd.get_name().to_string(), &mut std::io::stdout());
}
pub fn print_completions<G: Generator>(gen: G, cmd: &mut Command) -> std::io::Result<()> {
generate(gen, cmd, cmd.get_name().to_string(), &mut std::io::stdout())?;
Ok(())
}

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 (1)
src/cli.rs (1)

4-17: Add missing documentation for the stdin field.

While the file and gen_completion fields have documentation comments, the stdin field lacks documentation. Consider adding a doc comment to maintain consistency and improve code documentation.

     #[arg(default_value = ".")]
     pub file: Vec<String>,
 
+    /// Read from standard input instead of files
     #[clap(long, short, default_value = "false")]
     pub stdin: bool,
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dc39619 and 20b307c.

📒 Files selected for processing (4)
  • Cargo.toml (1 hunks)
  • build.rs (1 hunks)
  • src/cli.rs (1 hunks)
  • src/main.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • build.rs
  • Cargo.toml
🔇 Additional comments (3)
src/cli.rs (2)

1-2: LGTM! Appropriate imports for CLI and completion generation.

The imports correctly bring in the necessary components from clap and clap_complete for argument parsing and shell completion generation.


19-23: Consider error handling in print_completions

The function writes directly to stdout without handling potential I/O errors.

Consider making the binary name configurable.

The binary name "pestfmt" is hardcoded in the completion generation. Consider making it configurable or deriving it from the package metadata to ensure it stays in sync with the actual binary name.

-pub fn print_completions<G: Generator>(gen: G) {
+pub fn print_completions<G: Generator>(gen: G, binary_name: &str) -> std::io::Result<()> {
     let mut cmd = Args::command();
 
-    generate(gen, &mut cmd, "pestfmt", &mut std::io::stdout());
+    generate(gen, &mut cmd, binary_name, &mut std::io::stdout())?;
+    Ok(())
 }
src/main.rs (1)

1-2: LGTM! Clean integration of completion generation.

The new completion generation feature is well-integrated into the existing codebase without disrupting the current functionality. The command-line argument parsing changes are minimal and maintain backward compatibility.

Also applies to: 11-15

Comment on lines +11 to +15
let cli = cli::Args::parse();

if cli.stdin {
if let Some(generator) = cli.gen_completion {
cli::print_completions(generator);
} else if cli.stdin {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure consistent error handling for completion generation.

The completion generation branch doesn't propagate potential I/O errors, unlike other branches that use the ? operator. This could lead to silent failures when generating completions.

     let cli = cli::Args::parse();
 
     if let Some(generator) = cli.gen_completion {
-        cli::print_completions(generator);
+        cli::print_completions(generator)?;
     } else if cli.stdin {
📝 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
let cli = cli::Args::parse();
if cli.stdin {
if let Some(generator) = cli.gen_completion {
cli::print_completions(generator);
} else if cli.stdin {
let cli = cli::Args::parse();
if let Some(generator) = cli.gen_completion {
cli::print_completions(generator)?;
} else if cli.stdin {

@tomtau tomtau requested review from huacnlee and a team January 14, 2025 00:46
@huacnlee
Copy link
Member

I think this feature is unnecessary. The pestfmt function is quite simple. There is no need to introduce this feature to increase maintenance complexity.

We should not add it just for the sake of adding it.

@tomtau
Copy link
Contributor

tomtau commented Jan 16, 2025

@romch007 thank you for your contribution. As @huacnlee noted, the tradeoff of extra code maintenance vs utility it gives isn't likely worth adding it at this time.
If anyone else is interested in this feature, feel free to open an issue to discuss potentially re-visiting this PR: https://github.com/pest-parser/pest-fmt/issues/new

@tomtau tomtau closed this Jan 16, 2025
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.

3 participants