A tool crate to quickly build rust Command line application.
åœ¨ä½ çš„é¡¹ç›®ä¸æ·»åŠ ä¾èµ–如下:
toml
[dependencies]
falsework = "0.1.0"
```rust use std::error::Error; use falsework::{app, cmd};
fn main() {
// 通过falsework创建一个骨架
let mut app = falsework::app::new();
// 应用元数æ®ä¿¡æ¯
app.name("calculator")
.author("Leon Ding <ding@ibyte.me>")
.version("0.0.1")
.description("A calculator that only supports addition.");
// 构建命令行项
let mut command = cmd::CommandItem {
// run add命令所对应命令行逻辑代ç
run: |ctx| -> Result<(), Box<dyn Error>> {
// 通过上下文获å–flag绑定的数æ®
let x = ctx.value_of("--x").parse::<i32>().unwrap();
let y = ctx.value_of("--y").parse::<i32>().unwrap();
println!("{} + {} = {}", x, y, x + y);
// 如果处ç†å‘生了错误则调用 cmd::err_msg 会优雅的退出
// Err(cmd::err_msg("Application produce errorï¼"));
Ok(())
},
// 命令帮助信æ¯
long: "è¿™æ˜¯ä¸€ä¸ªåŠ æ³•è®¡ç®—ç¨‹åºéœ€è¦ä¸¤ä¸ªflagå‚æ•° --x --y",
// 命令介ç»
short: "åŠ æ³•è®¡ç®—",
// 通过add激活命令
r#use: "add",
}.build();
// 给add命令绑定flag
command.bound_flag("--x", "åŠ æ•°");
command.bound_flag("--y", "è¢«åŠ æ•°");
// å¾€app里é¢æ·»åŠ 一个命令集
app.add_cmd(command);
// 最åŽrun 程åºå¼€å§‹ç›‘å¬å‘½ä»¤è¡Œè¾“å…¥
app.run();
} ```
上é¢è¿™ä¸ªä¾‹åè¿è¡Œèµ·æ¥ç»“æžœ:
shell
$: ./calculator add --x=10 --y=10
10 + 10 = 20
到æ¤ä¸ºæ¢ä½ å°±å¿«é€Ÿæž„å»ºä¸€ä¸ªå‘½ä»¤è¡Œè®¡ç®—å™¨äº†ï¼Œä½ åªéœ€è¦å†™ä½ æ ¸å¿ƒé€»è¾‘ï¼Œå…¶ä»–æ“作falsework
å¸®åŠ©ä½ å®Œæˆã€‚
```shell $: ./calculator a
You need this command ?
add
a : The corresponding command set was not found!
``
2. å¯ä»¥çœ‹åˆ°ç¨‹åºæç¤ºä½ æœ‰ä¸€ä¸ªå¯¹åº”çš„
add命令å¯ä»¥ä½¿ç”¨ï¼Œå¦‚æžœä¸çŸ¥é“
add有啥å‚数,在åŽé¢
åŠ ä¸Š
--help`å³å¯èŽ·å¾—帮助信æ¯ï¼š
```shell $: ./calculator add --help
Help: è¿™æ˜¯ä¸€ä¸ªåŠ æ³•è®¡ç®—ç¨‹åºéœ€è¦ä¸¤ä¸ªflagå‚æ•° --x --y
Usage: calculator add [flags]
Flags: --y, è¢«åŠ æ•° --x, åŠ æ•° ``` 构建出æ¥ä¸»ç¨‹åºé¢„览:
```shell $: ./calculator
A calculator that only supports addition. calculator 0.0.1 Leon Ding ding@ibyte.me
Usage: calculator [command]
Available Commands: add åŠ æ³•è®¡ç®—
Flags: --help help for calculator
Use "calculator [command] --help" for more information about a command. ```
有多ç§æž„建方å¼ï¼Œä¾‹å¦‚下é¢çš„:
```rust #[test] fn testaddcommands() { let mut app = falsework::app::new();
app.name("calculator")
.author("Leon Ding <ding@ibyte.me>")
.version("0.0.2")
.description("A command line program built with Falsework.");
let command_list = vec![
cmd::CommandItem {
run: |_ctx| -> Result<(), Box<dyn Error>> {
// _ctx.args 获å–命令行å‚æ•°
println!("call foo command.");
Ok(())
},
long: "这是一个测试命令,使用foo将调用foo命令。",
short: "foo命令",
r#use: "foo",
},
cmd::CommandItem {
run: |_ctx| -> Result<(), Box<dyn Error>> {
println!("call bar command.");
Ok(())
},
long: "这是一个测试命令,使用bar将调用bar命令。",
short: "bar命令",
r#use: "bar",
},
].iter().map(|c| c.build()).collect();
app.commands(command_list);
println!("{:#?}", app);
}
```
本项目也是笔者一个练手写的crate
,看了åŠä¸ªæœˆçš„Rust
书,å¦äº†ç‚¹åŸºç¡€ï¼Œä¸çŸ¥é“写什么所以撸一个这个玩玩。。
å¦‚æžœå¯¹ä½ æœ‰å¸®åŠ©è®°å¾—star
,falsework
ç›®å‰æž„建一些command line application
问题ä¸å¤§ï¼Œä¸è¿‡æºä»£ç 写的有点挫。。。åŽé¢å†æ”¹è¿›å§ã€‚