I was trying to set up some command-line arguments and came across this method with clap. I don't mind to use something else, but let me explain my problem. Here is the code I have now:
fn main() {
use std::process;
use std::process::{Command, Stdio};
use clap::{Arg, App};
let matches = App::new("Test")
.version("0.1.0")
.author("me <somebody@mail.ru>")
.about("DevOps In Rust")
.arg(Arg::with_name("File")
.short("f")
.takes_value(true)
.help("Path to file of hosts."))
.arg(Arg::with_name("Execute")
.short("e")
.takes_value(true)
.help("Commands to be quotes. Use quotes for muliple commands."))
.arg(Arg::with_name("Host")
.short("l")
.takes_value(true)
.help("Ip or domain of host"))
.arg(Arg::with_name("User")
.short("u")
.takes_value(true)
.help("Username. Should have sudo, but not enforced."))
.arg(Arg::with_name("Port")
.short("p")
.takes_value(true)
.help("Specify port if different from 22."))
.arg(Arg::with_name("Password")
.short("w")
.takes_value(true)
.help("Password if SSH keys are not configured."))
.get_matches();
let user = matches.value_of("User").unwrap();
println!("{}", user);
let host = matches.value_of("Host").unwrap();
println!("{}", host);
let password = matches.value_of("Password").unwrap();
println!("{}", password);
let file = matches.value_of("File").unwrap();
println!("{}", file);
let exec = matches.value_of("Execute").unwrap();
println!("{}", exec);
let port = matches.value_of("Port").unwrap();
println!("{}", port);
}
If I run it with all arguments set from the command-line it runs as expected right now:
$ ./target/release/system -u user -l localhost -w Cheese -f file -e date -p 22
user
localhost
Cheese
file
date
22
If you run this without all the arguments right now it will fail as Rust shouldn't t print it out an unset value. I wanted to perform a check if arguments are set and perform different actions depending on what the user chose. I found some stuff about using is_empty() and tried using the following:
if !Port.is_empty() {
let port = matches.value_of("Port").unwrap();
println!("{}", port);
}
When I tried and if statement with "!Port.is_empty();" I got an error that Port wasn't in scope with that line.
$ cargo build --release
Compiling system v0.1.0 (/home/user/rust/system)
error[E0425]: cannot find value `Port` in this scope
--> src/main.rs:90:9
|
90 | if !Port.is_empty() {
| ^^^^ not found in this scope
I'm unsure how this could be out of scope as without the if around those same lines Port is found just fine.
Happy to hear anyone's suggestions.
Thanks!