Skip to content

Commit

Permalink
First try with adding parsing of args in env-var.
Browse files Browse the repository at this point in the history
  • Loading branch information
purew committed Nov 4, 2016
1 parent a7659ce commit 49de025
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ mod help;
use std::borrow::Borrow;
use std::env;
use std::ffi::OsString;
use osstringext::OsStrExt2;
use std::fmt;
use std::io::{self, BufRead, BufWriter, Write};
use std::path::Path;
Expand Down Expand Up @@ -1227,6 +1228,32 @@ impl<'a, 'b> App<'a, 'b> {
self.get_matches_from_safe(&mut env::args_os())
}

/// Similar to [`App::get_matches`] but also reads args from
/// env-var `env_var_name`.
///
/// Defaults to read from "VAR" if `env_var_name` is `None`.
pub fn get_matches_with_env(self, env_var_name: Option<String>)
-> ArgMatches<'a> {
let mut env_var = "VAR".to_string();
if let Some(name) = env_var_name {
env_var = name;
}
// Build `args` by chaining `args_os()` and `var_os()`
let mut args: Vec<OsString> = env::args_os().collect();
// Handle first env-format:
// VAR="--option1=val1 --option2=val2" ./prog
if let Some(vargs) = env::var_os(&env_var) {
// TODO: Split on space below is ugly. How to split on all
// utf-8-whitespace? Must use regex?
args = args.into_iter()
.chain(vargs.split(0x20)
.into_iter()
.map(|s| s.to_os_string()))
.collect();
}
self.get_matches_from(&mut args.into_iter())
}

/// Starts the parsing process. Like [`App::get_matches`] this method does not return a [`clap::Result`]
/// and will automatically exit with an error message. This method, however, lets you specify
/// what iterator to use when performing matches, such as a [`Vec`] of your making.
Expand Down

0 comments on commit 49de025

Please sign in to comment.