Skip to content

Commit 38f41a7

Browse files
authored
Merge pull request #68 from dtolnay/clap
Switch to clap to parse command line
2 parents dee829f + c7e34dc commit 38f41a7

File tree

2 files changed

+21
-19
lines changed

2 files changed

+21
-19
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ publish = false
1111
repository = "https://github.com/dtolnay/rust-quiz"
1212

1313
[dependencies]
14+
clap = { version = "4", features = ["deprecated", "derive"] }
1415
futures = "0.3"
1516
http = "0.2"
1617
hyper = { version = "0.14", features = ["http1", "http2", "server", "tcp"] }

src/main.rs

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,28 +9,22 @@ mod render;
99
mod serve;
1010

1111
use crate::error::{Error, Result};
12+
use clap::{Parser as ClapParser, Subcommand as ClapSubcommand};
1213
use oqueue::{Color::Red, Sequencer};
13-
use std::env;
1414
use std::io::{self, Write};
1515
use std::process;
1616

17-
fn should_serve() -> bool {
18-
let mut args = env::args_os().skip(1);
19-
20-
let Some(arg) = args.next() else {
21-
return false;
22-
};
23-
24-
if arg == "serve" {
25-
true
26-
} else {
27-
let _ = writeln!(
28-
io::stderr(),
29-
"Unrecognized argument: `{}`",
30-
arg.to_string_lossy()
31-
);
32-
process::exit(1);
33-
}
17+
#[derive(ClapParser, Debug)]
18+
#[command(about = "Rust Quiz", version, author)]
19+
struct Opt {
20+
#[clap(subcommand)]
21+
serve: Option<Subcommand>,
22+
}
23+
24+
#[derive(ClapSubcommand, Debug)]
25+
enum Subcommand {
26+
/// Serve website over http at localhost:8000
27+
Serve,
3428
}
3529

3630
fn report(result: Result<()>) {
@@ -47,10 +41,17 @@ fn report(result: Result<()>) {
4741

4842
#[tokio::main]
4943
async fn main() {
44+
let opt = Opt::parse();
45+
5046
report(render::main());
5147

52-
if should_serve() {
48+
if opt.serve.is_some() {
5349
let _ = writeln!(io::stderr());
5450
report(serve::main().await);
5551
}
5652
}
53+
54+
#[test]
55+
fn test_cli() {
56+
<Opt as clap::CommandFactory>::command().debug_assert();
57+
}

0 commit comments

Comments
 (0)