Is there a way to make clap override the [ -h | --help ] flags help text? - rust

I'm following the sample code from Rust Clap Package's docs but can't find any reference regarding help text for auto-generated flags [-h and --help].
extern crate clap;
use clap::{App, Arg, SubCommand};
fn main() {
let matches = App::new("Command One")
.version("1.0")
.author("Some Author <the_account#provider.com>")
.about("DescripciĆ³n del comando.")
.arg(Arg::with_name("config")
.short("c")
.long("config")
.value_name("FILE")
.help("Sets a custom config file")
.takes_value(true))
.arg(Arg::with_name("INPUT")
.help("Sets the input file to use")
.required(true)
.index(1))
.arg(Arg::with_name("v")
.short("v")
.multiple(true)
.help("Sets the level of verbosity"))
// *** I'm trying this ***
.arg(Arg::with_name("help")
.short("h")
.long("help")
.help("A new help text."))
// ***********
.subcommand(SubCommand::with_name("test")
.about("controls testing features")
.version("1.3")
.author("Someone E. <someone_else#other.com>")
.arg(Arg::with_name("debug")
.short("d")
.help("print debug information verbosely")))
.get_matches();
let config = matches.value_of("config").unwrap_or("default.conf");
println!("Value for config: {}", config);
println!("Using input file: {}", matches.value_of("INPUT").unwrap());
match matches.occurrences_of("v") {
0 => println!("No verbose info"),
1 => println!("Some verbose info"),
2 => println!("Tons of verbose info"),
3 | _ => println!("Don't be crazy"),
}
if let Some(matches) = matches.subcommand_matches("test") {
if matches.is_present("debug") {
println!("Printing debug info...");
} else {
println!("Printing normally...");
}
}
}

To change the description of the -h/--help parameter in the help text, use the help_message method. Likewise, to change the description of -V/--version, use version_message.
extern crate clap;
use clap::App;
fn main() {
let matches = App::new("app")
.help_message("this is the help command")
.version_message("this is the version command")
.get_matches_from(&["app", "--help"]);
}
Output:
app
USAGE:
app
FLAGS:
-h, --help this is the help command
-V, --version this is the version command

Related

Can't build RustDesk - Android

I tried to build RustDesk project following documentation at documentation - android build
After executing:
VCPKG_ROOT=/opt/vcpkg ANDROID_NDK_HOME=/opt/android-ndk-r22b flutter/ndk_arm64.sh
I cp-ed vcpkg and android-ndk-r22b from home to /opt to make sure that path is right
I'm getting this one error message:
[2023-01-13T09:59:47Z INFO cargo_ndk::cli] Using NDK at path: /opt/android-ndk-r22b (ANDROID_NDK_HOME)
[2023-01-13T09:59:47Z INFO cargo_ndk::cli] NDK API level: 21
[2023-01-13T09:59:47Z INFO cargo_ndk::cli] Building targets: arm64-v8a
[2023-01-13T09:59:47Z INFO cargo_ndk::cli] Building arm64-v8a (aarch64-linux-android)
warning: function `patch` is never used
--> libs/hbb_common/src/config.rs:239:4
|
239 | fn patch(path: PathBuf) -> PathBuf {
| ^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: `hbb_common` (lib) generated 1 warning
Compiling rustdesk v1.2.0 (/home/mwitek/rustdesk)
error: failed to run custom build command for `rustdesk v1.2.0 (/home/mwitek/rustdesk)`
Caused by:
process didn't exit successfully: `/home/mwitek/rustdesk/target/release/build/rustdesk-9caa4dac4ffa2754/build-script-build` (exit status: 101)
--- stdout
cargo:rustc-link-search=/opt/vcpkg/installed/arm64-android/lib
cargo:rustc-link-lib=oboe
cargo:rustc-link-lib=c++
cargo:rustc-link-lib=OpenSLES
cargo:rerun-if-changed=src/flutter_ffi.rs
--- stderr
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Failed to run build_runner for /home/mwitek/rustdesk/flutter: ', build.rs:108:56
stack backtrace:
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
And to be honest I don't know how to get rid of it, I already tried to understand what is wrong from code-side but I can only find this section in build.rs:
fn install_oboe() {
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
if target_os != "android" {
return;
}
let mut target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap();
if target_arch == "x86_64" {
target_arch = "x64".to_owned();
} else if target_arch == "aarch64" {
target_arch = "arm64".to_owned();
} else {
target_arch = "arm".to_owned();
}
let target = format!("{}-android", target_arch);
let vcpkg_root = std::env::var("VCPKG_ROOT").unwrap();
let mut path: std::path::PathBuf = vcpkg_root.into();
path.push("installed");
path.push(target);
println!(
"{}",
format!(
"cargo:rustc-link-search={}",
path.join("lib").to_str().unwrap()
)
);
println!("cargo:rustc-link-lib=oboe");
println!("cargo:rustc-link-lib=c++");
println!("cargo:rustc-link-lib=OpenSLES");
// I always got some strange link error with oboe, so as workaround, put oboe.cc into oboe src: src/common/AudioStreamBuilder.cpp
// also to avoid libc++_shared not found issue, cp ndk's libc++_shared.so to jniLibs, e.g.
// ./flutter_hbb/android/app/src/main/jniLibs/arm64-v8a/libc++_shared.so
// let include = path.join("include");
//cc::Build::new().file("oboe.cc").include(include).compile("oboe_wrapper");
}
But it doesn't look like anything for me
Also here is function that's generating exception:
fn gen_flutter_rust_bridge() {
let llvm_path = match std::env::var("LLVM_HOME") {
Ok(path) => Some(vec![path]),
Err(_) => None,
};
// Tell Cargo that if the given file changes, to rerun this build script.
println!("cargo:rerun-if-changed=src/flutter_ffi.rs");
// settings for fbr_codegen
let opts = lib_flutter_rust_bridge_codegen::Opts {
// Path of input Rust code
rust_input: "src/flutter_ffi.rs".to_string(),
// Path of output generated Dart code
dart_output: "flutter/lib/generated_bridge.dart".to_string(),
// Path of output generated C header
c_output: Some(vec!["flutter/macos/Runner/bridge_generated.h".to_string()]),
// for other options lets use default
llvm_path,
..Default::default()
};
// run fbr_codegen
lib_flutter_rust_bridge_codegen::frb_codegen(opts).unwrap();
}
Where it's last line is the one that throws this error.
lib_flutter_rust_bridge_codegen::frb_codegen(opts).unwrap();
I know this question really specific but documentation and self-investigation does not helping.
Also my OS properties: Ubuntu 20.04 x64 [Freshly installed]

rust clap, use enum for separate flags

I have this example:
use clap::Parser;
#[derive(clap::ValueEnum, Clone, Debug)]
enum InfoType {
All,
Headers,
Metadata,
}
#[derive(Parser, Debug)]
#[clap(version)]
#[clap(about = "Prints out metadata for each file")]
struct Args {
#[clap(long)]
#[clap(help = "What to print")]
#[clap(value_enum, default_value_t=InfoType::All)]
info: InfoType,
#[clap(value_parser, required(true))]
#[clap(help = "file(s)")]
files: Vec<String>,
}
fn main() {
let args = Args::parse();
println!("args {:?}", args)
}
Here the cli interface becomes almost but not quite what I want
USAGE:
my_test [OPTIONS] <FILES>...
ARGS:
<FILES>... file(s)
OPTIONS:
-h, --help Print help information
--info <INFO> What to print [default: all] [possible values: all, headers, metadata]
-V, --version Print version information
Now this can be run as e.g.
my_test /path/file1 /path/file2 # enables the --info all by default
my_test --info headers /path/file1 /path/file2
What I would like instead is to have the --info <INFO> flag just as --metadata , --all etc. So I can run
my_test /path/file1 /path/file2 # enables the --all all by default
my_test --info /path/file1 /path/file2
But still parsing those flags to the same enum variable - how would I set up this with clap ?

Getting error while using #[js_export] from crate stdweb

I need to read client file in a rust-wasm program and I am trying two solution given on stackoverflow https://stackoverflow.com/a/51231915 and https://stackoverflow.com/a/69305956/4466255. Both these solutions are accepted and given bounties so I am assuming they work.
both of these have used following code
use stdweb::js_export
#[js_export]
But when i try to compile these codes I got following error
error[E0425]: cannot find function `__web_free` in module `stdweb::private`
--> src/lib.rs:14:1
|
14 | #[js_export]
| ^^^^^^^^^^^^ not found in `stdweb::private`
|
= note: this error originates in the attribute macro `js_export` (in Nightly builds, run with -Z macro-backtrace for more info)
What I am missing. How can we make it work?
My current code, which I have taken from stackoverflow https://stackoverflow.com/a/51231915, in lib.rs is
#[macro_use]
extern crate stdweb;
use stdweb::js_export;
use stdweb::web::FileReader;
use stdweb::web::FileReaderResult;
#[js_export]
fn print_result(file_reader: FileReader) -> String {
match file_reader.result() {
Some(value) => match value {
FileReaderResult::String(value) => value,
_ => String::from("not a text"),
}
None => String::from("empty")
}
}
pub fn test_reader() {
stdweb::initialize();
stdweb::event_loop();
}
and the Cargo.toml file is
[package]
name = "read-file2"
version = "0.1.0"
authors = ["kushdesh"]
edition = "2018"
[lib]
crate-type = ["cdylib", "rlib"]
[features]
default = ["console_error_panic_hook"]
[dependencies]
wasm-bindgen = "0.2.63"
stdweb = "0.4.20"
console_error_panic_hook = { version = "0.1.6", optional = true }
wee_alloc = { version = "0.4.5", optional = true }
[dev-dependencies]
wasm-bindgen-test = "0.3.13"
[profile.release]
# Tell `rustc` to optimize for small code size.
opt-level = "s"

How use hex::encode in Substrate offchain worker?

I'm calling hex::encode from offchain worker, but compilation fails with:
state.serialize_field("account_id", &hex::encode( self.account_id.encode().as_slice() ) )?;
| ^^^^^^ not found in `hex`
My Cargo.toml contains:
[features]
default = ['std']
std = [
...
'hex/std'
]
[dependencies]
hex = { version='0.4.3', default-features=false }
How to fix this?
Adding the "alloc" feature to Cargo.toml solved the problem:
hex = { version='0.4.3', default-features=false, features = ['alloc'] }

How to obtain the value of a configuration flag?

Is there a way of obtaining the value of a configuration flag? For example, I would like to get the value of target_os as str/String, without resorting to the following if-else-if chain:
if cfg!(target_os = "windows") {
"windows"
} else if cfg!(target_os = "linux") {
"linux"
// ...
} else {
"unknown"
}
No. You can get some of them by tricking Cargo into telling you. If you place the following into a build script:
use std::env;
fn main() {
for (key, value) in env::vars() {
if key.starts_with("CARGO_CFG_") {
println!("{}: {:?}", key, value);
}
}
panic!("stop and dump stdout");
}
...it will display the cfg flags Cargo is aware of. The panic! is just there as an easy way to get Cargo to actually show the output instead of hiding it. For reference, the output this produces looks like this:
Compiling dump-cfg v0.1.0 (file:///F:/Programming/Rust/sandbox/cargo-test/dump-cfg)
error: failed to run custom build command for `dump-cfg v0.1.0 (file:///F:/Programming/Rust/sandbox/cargo-test/dump-cfg)`
process didn't exit successfully: `F:\Programming\Rust\sandbox\cargo-test\dump-cfg\target\debug\build\dump-cfg-8b04f9ac3818f82a\build-script-build` (exit code: 101)
--- stdout
CARGO_CFG_TARGET_POINTER_WIDTH: "64"
CARGO_CFG_TARGET_ENV: "msvc"
CARGO_CFG_TARGET_OS: "windows"
CARGO_CFG_TARGET_ENDIAN: "little"
CARGO_CFG_TARGET_FAMILY: "windows"
CARGO_CFG_TARGET_ARCH: "x86_64"
CARGO_CFG_TARGET_HAS_ATOMIC: "16,32,64,8,ptr"
CARGO_CFG_TARGET_FEATURE: "sse,sse2"
CARGO_CFG_WINDOWS: ""
CARGO_CFG_TARGET_VENDOR: "pc"
CARGO_CFG_DEBUG_ASSERTIONS: ""
--- stderr
thread 'main' panicked at 'stop', build.rs:9
note: Run with `RUST_BACKTRACE=1` for a backtrace.
You can extract the values you're interested in from this list, and dump them to a generated source file, which you can then import (using #[path] or include!) into your package's source.
For target_os specifically, and also for just target_family and target_arch, there are corresponding &str constants in std::env::consts::{OS, FAMILY, ARCH}.

Resources