Last active
January 5, 2023 02:02
-
-
Save dereckson/06e0477a104e6482248eeeb1e423ca60 to your computer and use it in GitHub Desktop.
Parse arguments in Rust with clap crate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use clap::Parser; | |
#[derive(Parser,Default,Debug)] | |
#[clap(author="Nasqueron project", version, about="Import FANTOIR database into PostgreSQL")] | |
struct Arguments { | |
/// Create table if it doesn't exist | |
#[arg(short = 'c')] | |
create_table: bool, | |
/// Truncate table if it already exists, allowing the overwrite mode. | |
/// If not specified, the script will fail if table exists. | |
#[arg(short = 't')] | |
overwrite_table: bool, | |
/// The FANTOIR file to import | |
fantoir_file: String, | |
/// The name of the table to populate | |
fantoir_table: String, | |
} | |
fn main() { | |
let args = Arguments::parse(); // Will exit if argument is missing or --help --version provided. | |
let database_url = ...; | |
import(&args.fantoir_file, &database_url, &args.fantoir_table); | |
} | |
fn import(file: &str, database_url: &str, table: &str) { | |
// ... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Same struct Arguments | |
// But pass all the struct to the main helper function, and show how to read it. | |
fn main() { | |
let args = Arguments::parse(); // Will exit if argument is missing or --help --version provided. | |
let database_url = ...; | |
import(&args, &database_url); | |
} | |
fn import(args: &Arguments, database_url: &str) { | |
let fd = File::open(&args.fantoir_file).expect("Can't open file."); | |
// ... | |
if args.create_table { | |
// ... | |
} | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The code is extracted from fantoir2db utility I'm currently writing.
Arguments are the current real ones. Output of
./fantoir2db --help
is :To simplify the gist and focus on arguments parsing, the code has been written as synchronous, whereas fantoir2db uses async code for I/O and database access, but that's not in the scope of this example.
Another simplification is the use of &str for filename argument, where we can allow more generic types for a path.