A tool crate to quickly build rust command line application.

Overview

Falsework

https://img.shields.io/badge/falsework-Rust%20CLI-brightgreen Go codecov https://img.shields.io/github/repo-size/auula/falsework https://img.shields.io/crates/v/falsework License

A tool crate to quickly build rust command line application.

导入依赖

在你的项目中添加依赖如下:

[dependencies]
falsework = "0.1.0"

快速构建

") .version("0.0.1") .description("A calculator that only supports addition."); // 构建命令行项 let mut command = cmd::CommandItem { // run add命令所对应命令行逻辑代码 run: |ctx| -> Result<(), Box> { // 通过上下文获取flag绑定的数据 let x = ctx.value_of("--x").parse::().unwrap(); let y = ctx.value_of("--y").parse::().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(); } ">
use std::error::Error;
use falsework::{app, cmd};

fn main() {
    
    // 通过falsework创建一个骨架
    let mut app = falsework::app::new();
    
    
    // 应用元数据信息
    app.name("calculator")
        .author("Leon Ding ")
        .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();
}

上面这个例子运行起来结果:

$: ./calculator add --x=10 --y=10
10 + 10 = 20

到此为止你就快速构建一个命令行计算器了,你只需要写你核心逻辑,其他操作falsework帮助你完成。

  1. 例如如果我不记得了命令了,只记得一个单词或者字母,程序会帮助你修复:
$: ./calculator a

You need this command ?
	add
a : The corresponding command set was not found!
  1. 可以看到程序提示你有一个对应的add命令可以使用,如果不知道add有啥参数,在后面 加上--help即可获得帮助信息:
$: ./calculator add --help

Help:
  这是一个加法计算程序需要两个flag参数 --x --y

Usage:
  calculator add [flags]

Flags:
  --y, 被加数
  --x, 加数

构建出来主程序预览:

$: ./calculator


A calculator that only supports addition.
calculator 0.0.1 Leon Ding <[email protected]>

Usage:
  calculator  [command]

Available Commands:
  add	加法计算

Flags:
  --help   help for calculator

Use "calculator [command] --help" for more information about a command.

其他操作

有多种构建方式,例如下面的:

") .version("0.0.2") .description("A command line program built with Falsework."); let command_list = vec![ cmd::CommandItem { run: |_ctx| -> Result<(), Box> { // _ctx.args 获取命令行参数 println!("call foo command."); Ok(()) }, long: "这是一个测试命令,使用foo将调用foo命令。", short: "foo命令", r#use: "foo", }, cmd::CommandItem { run: |_ctx| -> Result<(), Box> { 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); } ">
    #[test]
    fn test_add_commands() {
        let mut app = falsework::app::new();

        app.name("calculator")
            .author("Leon Ding ")
            .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书,学了点基础,不知道写什么所以撸一个这个玩玩。。 如果对你有帮助记得starfalsework目前构建一些command line application问题不大,不过源代码写的有点挫。。。后面再改进吧。

You might also like...
This is a simple command line application to convert bibtex to json written in Rust and Python

bibtex-to-json This is a simple command line application to convert bibtex to json written in Rust and Python. Why? To enable you to convert very big

Command line application for searching
Command line application for searching

maven_search_rs Command line application for searching in https://search.maven.org Usage Non-interactive $ maven-search -f maven wicket-core The abov

Application microframework with command-line option parsing, configuration, error handling, logging, and shell interactions
Application microframework with command-line option parsing, configuration, error handling, logging, and shell interactions

Abscissa is a microframework for building Rust applications (either CLI tools or network/web services), aiming to provide a large number of features w

A command line application which sets your wall paper with new image generating pollens once they arrive.

pollenwall Table of Contents pollenwall About Installation Binary releases Build from source Usage Command Line Arguments Running as a service MacOS L

omekasy is a command line application that converts alphanumeric characters in your input to various styles defined in Unicode.

omekasy is a command line application that converts alphanumeric characters in your input to various styles defined in Unicode. omekasy means "dress up" in Japanese.

A robust, customizable, blazingly-fast, efficient and easy-to-use command line application to uwu'ify your text!
A robust, customizable, blazingly-fast, efficient and easy-to-use command line application to uwu'ify your text!

uwuifyy A robust, customizable, blazingly-fast, efficient and easy-to-use command line application to uwu'ify your text! Logo Credits: Jade Nelson Tab

Fast command-line application to show the moon phase

moon-phases Command-line application to show the moon phase for a given date and time, as a text string, emoji, or numeric value. It can also show the

A git command to quickly save your local changes in case of earthquake !

git-eq (aka git earthquake) Earthquakes are part of the daily life in many countries like in Taiwan. git-eq is a simple git command to quickly save yo

Command-line HTTP client for sending a POST request to specified URI on each stdin line.

line2httppost Simple tool to read lines from stdin and post each line as separate POST request to a specified URL (TCP connection is reused though). G

Owner
Leon Ding
Jokes are truth.
Leon Ding
A command line tool written in Rust and designed to be a modern build tool + package manager for C/C++ projects.

CCake CCake is a command line tool written in Rust and designed to be a modern build tool + package manager for C/C++ projects. Goals To be easily und

Boston Vanseghi 4 Oct 24, 2022
rpsc is a *nix command line tool to quickly search for file systems items matching varied criterions like permissions, extended attributes and much more.

rpsc rpsc is a *nix command line tool to quickly search for file systems items matching varied criterions like permissions, extended attributes and mu

null 3 Dec 15, 2022
tmplt is a command-line interface tool that allows you to quickly and easily set up project templates for various programming languages and frameworks

tmplt A User Friendly CLI Tool For Creating New Projects With Templates About tmplt is a command-line tool that lets users quickly create new projects

Humble Penguin 35 Apr 8, 2023
Lightweight command line tool to quickly navigate across folders.

slingshot 0.3.0 Slingshot is a lightweight tool to browse files in the terminal. It allows the user to quickly filter through files in any directory,

Caio Ishikawa 40 Sep 17, 2023
Small command-line tool to switch monitor inputs from command line

swmon Small command-line tool to switch monitor inputs from command line Installation git clone https://github.com/cr1901/swmon cargo install --path .

William D. Jones 5 Aug 20, 2022
Rust command line utility to quickly display useful secrets in a Kubernetes namespace

kube-secrets This is a command line utility for quickly looking at secrets in a Kubernetes namespace that are typically looked at by humans. It specif

Frank Wiles 8 Feb 10, 2022
Quickly build cool CLI apps in Rust.

QuiCLI Quickly build cool CLI apps in Rust. Getting started Read the Getting Started guide! Thanks This is only possible because of all the awesome li

Pascal Hertleif 538 Dec 5, 2022
Build Abstract Syntax Trees and tree-walking models quickly in Rust.

astmaker Build Abstract Syntax Trees and tree-walking models quickly in Rust. Example This example creates an AST for simple math expressions, and an

David Delassus 100 Jun 5, 2023
Pink is a command-line tool inspired by the Unix man command.

Pink is a command-line tool inspired by the Unix man command. It displays custom-formatted text pages in the terminal using a subset of HTML-like tags.

null 3 Nov 2, 2023
A small command-line application to view images from the terminal written in Rust.

A small command-line application to view images from the terminal written in Rust. It is basically the front-end of viuer

Atanas Yankov 1.9k Jan 3, 2023