Skip to content

Commit

Permalink
feat(cli): 🎸 Add command completion via clap_completion
Browse files Browse the repository at this point in the history
- Add init command
  • Loading branch information
kamack38 committed Feb 8, 2024
1 parent 96478ec commit 4567565
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 4 deletions.
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@ path = "src/main.rs"

[dependencies]
clap = { version = "4.4.18", features = ["derive"] }
clap_complete = "4.5.0"
thiserror = "1.0.52"
22 changes: 18 additions & 4 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,18 @@ use ram_machine::{
parser::ParserError,
};

use clap::{Parser as ClapParser, Subcommand};
use clap::{Command, CommandFactory, Parser as ClapParser, Subcommand, ValueHint};
use clap_complete::{generate, Generator, Shell};

#[derive(ClapParser, Debug)]
#[command(author, version, about, long_about = None)]
#[command(name = "ram", author, version, about, long_about = None)]
struct Cli {
/// Specifies the path to the input file from which data will be read (input passed from the command line takes precedence)
#[arg(short, long, value_name = "FILE")]
#[arg(short, long, value_name = "FILE", value_hint = ValueHint::FilePath)]
input_file: Option<PathBuf>,

/// Specifies the path to the output file where the results will be written
#[arg(short, long, value_name = "FILE")]
#[arg(short, long, value_name = "FILE", value_hint = ValueHint::FilePath)]
output_file: Option<PathBuf>,

/// Don't pass code output to STDOUT
Expand All @@ -39,6 +40,9 @@ pub enum Commands {

/// Validates ram code syntax of a given file
Check { file: PathBuf },

/// Generate a shell completion file
Init { shell: Shell },
// Repl,
// Debug,
}
Expand Down Expand Up @@ -67,8 +71,13 @@ pub enum RuntimeError {
CheckFileError(ParserErrorChain),
}

fn print_completions<G: Generator>(gen: G, cmd: &mut Command) {
generate(gen, cmd, cmd.get_name().to_string(), &mut io::stdout());
}

pub fn app() -> Result<(), RuntimeError> {
let cli = Cli::parse();

match cli.command {
Commands::Run { file, input } => {
let mut input = input;
Expand Down Expand Up @@ -132,6 +141,11 @@ pub fn app() -> Result<(), RuntimeError> {
return Err(RuntimeError::CheckFileError(errors));
}
}
Commands::Init { shell } => {
let mut cmd = Cli::command();
eprintln!("Generating completion file for {shell:?}...");
print_completions(shell, &mut cmd)
}
};
Ok(())
}

0 comments on commit 4567565

Please sign in to comment.