Skip to content

Instantly share code, notes, and snippets.

@dereckson
Last active January 5, 2023 02:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dereckson/06e0477a104e6482248eeeb1e423ca60 to your computer and use it in GitHub Desktop.
Save dereckson/06e0477a104e6482248eeeb1e423ca60 to your computer and use it in GitHub Desktop.
Parse arguments in Rust with clap crate
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) {
// ...
}
// 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 {
// ...
}
// ...
}
@dereckson
Copy link
Author

The code is extracted from fantoir2db utility I'm currently writing.

Arguments are the current real ones. Output of ./fantoir2db --help is :

Import FANTOIR database into PostgreSQL

Usage: fantoir2db [OPTIONS] <FANTOIR_FILE> <FANTOIR_TABLE>

Arguments:
  <FANTOIR_FILE>   The FANTOIR file to import
  <FANTOIR_TABLE>  The name of the table to populate

Options:
  -c             Create table if it doesn't exist
  -t             Truncate table if it already exists, allowing the overwrite mode. If not specified, the script will fail if table exists
  -h, --help     Print help information
  -V, --version  Print version information

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment