Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vks custom error #646

Merged
merged 5 commits into from
Sep 5, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ sudo: false
language: rust
rust:
- nightly
- nightly-2016-07-20
- nightly-2016-09-04
- beta
- stable
# Only while clippy is failing
matrix:
allow_failures:
- rust: nightly
- rust: beta
before_script:
- |
pip install 'travis-cargo<0.2' --user &&
Expand Down
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ libc = { version = "~0.2.9", optional = true }
ansi_term = { version = "~0.8.0", optional = true }
strsim = { version = "~0.5.1", optional = true }
yaml-rust = { version = "~0.3.2", optional = true }
clippy = { version = "~0.0.85", optional = true }
clippy = { version = "~0.0.88", optional = true }
unicode-width = "~0.1.3"
unicode-segmentation = "~0.1.2"
term_size = { version = "~0.1.0", optional = true }
term_size = { version = "~0.2.0", optional = true }

[dev-dependencies]
regex = "~0.1.69"
Expand Down
112 changes: 63 additions & 49 deletions src/app/help.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
use std::io::{self, Cursor, Read, Write};
use std::collections::BTreeMap;
use std::fmt::Display;
use std::cmp;
use std::usize;
// Std

use vec_map::VecMap;
use unicode_segmentation::UnicodeSegmentation;

use errors::{Error, Result as ClapResult};
// Internal

use args::{AnyArg, ArgSettings, DispOrder};
use app::{App, AppSettings};
use app::parser::Parser;
use args::{AnyArg, ArgSettings, DispOrder};
use errors::{Error, Result as ClapResult};
use fmt::{Format, Colorizer};
use std::cmp;
use std::collections::BTreeMap;
use std::fmt::Display;
use std::io::{self, Cursor, Read, Write};
use std::usize;

#[cfg(feature = "wrap_help")]
use term_size;
use unicode_segmentation::UnicodeSegmentation;

use vec_map::VecMap;
#[cfg(not(feature = "wrap_help"))]
mod term_size {
pub fn dimensions() -> Option<(usize, usize)> {
Expand Down Expand Up @@ -90,19 +93,21 @@ pub struct Help<'a> {
// Public Functions
impl<'a> Help<'a> {
/// Create a new `Help` instance.
pub fn new(w: &'a mut Write, next_line_help: bool, hide_pv: bool, color: bool, cizer: Colorizer, term_w: Option<usize>) -> Self {
pub fn new(w: &'a mut Write,
next_line_help: bool,
hide_pv: bool,
color: bool,
cizer: Colorizer,
term_w: Option<usize>)
-> Self {
debugln!("fn=Help::new;");
Help {
writer: w,
next_line_help: next_line_help,
hide_pv: hide_pv,
term_w: match term_w {
Some(width) => if width == 0 {
usize::MAX
} else {
width
},
None => term_size::dimensions().map_or(120, |(w, _)| w),
Some(width) => if width == 0 { usize::MAX } else { width },
None => term_size::dimensions().map_or(120, |(w, _)| w),
},
color: color,
cizer: cizer,
Expand Down Expand Up @@ -312,7 +317,8 @@ impl<'a> Help<'a> {
let nlh = self.next_line_help || arg.is_set(ArgSettings::NextLineHelp);
let width = self.term_w;
let taken = (longest + 12) + str_width(&*spec_vals);
let force_next_line = !nlh && width >= taken && str_width(h) > (width - taken) && (taken as f32 / width as f32) > 0.25;
let force_next_line = !nlh && width >= taken && str_width(h) > (width - taken) &&
(taken as f32 / width as f32) > 0.25;

if arg.has_switch() {
if !(nlh || force_next_line) {
Expand Down Expand Up @@ -400,9 +406,13 @@ impl<'a> Help<'a> {

// We calculate with longest+12 since if it's already NLH we don't care
let taken = (longest + 12) + str_width(&*spec_vals);
let force_next_line = !nlh && width >= taken && str_width(h) > (width - taken) && (taken as f32 / width as f32) > 0.25;
let force_next_line = !nlh && width >= taken && str_width(h) > (width - taken) &&
(taken as f32 / width as f32) > 0.25;
debugln!("Force Next Line...{:?}", force_next_line);
debugln!("Force Next Line math (help_len > (width - flags/opts/spcs))...{} > ({} - {})", str_width(h), width, taken);
debugln!("Force Next Line math (help_len > (width - flags/opts/spcs))...{} > ({} - {})",
str_width(h),
width,
taken);

let spcs = if nlh || force_next_line {
8 // "tab" + "tab"
Expand Down Expand Up @@ -488,9 +498,9 @@ impl<'a> Help<'a> {
if self.color {
format!(" [values: {}]",
pv.iter()
.map(|v| format!("{}", self.cizer.good(v)))
.collect::<Vec<_>>()
.join(", "))
.map(|v| format!("{}", self.cizer.good(v)))
.collect::<Vec<_>>()
.join(", "))
} else {
format!(" [values: {}]", pv.join(", "))
}
Expand All @@ -501,24 +511,24 @@ impl<'a> Help<'a> {
} else if let Some(ref aliases) = a.aliases() {
debugln!("Writing aliases");
return format!(" [aliases: {}]",
if self.color {
aliases.iter()
.map(|v| format!("{}", self.cizer.good(v)))
.collect::<Vec<_>>()
.join(", ")
} else {
aliases.join(", ")
});
if self.color {
aliases.iter()
.map(|v| format!("{}", self.cizer.good(v)))
.collect::<Vec<_>>()
.join(", ")
} else {
aliases.join(", ")
});
} else if !self.hide_pv {
debugln!("Writing values");
if let Some(pv) = a.possible_vals() {
debugln!("Possible vals...{:?}", pv);
return if self.color {
format!(" [values: {}]",
pv.iter()
.map(|v| format!("{}", self.cizer.good(v)))
.collect::<Vec<_>>()
.join(", "))
.map(|v| format!("{}", self.cizer.good(v)))
.collect::<Vec<_>>()
.join(", "))
} else {
format!(" [values: {}]", pv.join(", "))
};
Expand Down Expand Up @@ -547,16 +557,16 @@ impl<'a> Help<'a> {

if unified_help && (flags || opts) {
let opts_flags = parser.iter_flags()
.map(as_arg_trait)
.chain(parser.iter_opts().map(as_arg_trait));
.map(as_arg_trait)
.chain(parser.iter_opts().map(as_arg_trait));
try!(color!(self, "OPTIONS:\n", warning));
try!(self.write_args(opts_flags));
first = false;
} else {
if flags {
try!(color!(self, "FLAGS:\n", warning));
try!(self.write_args(parser.iter_flags()
.map(as_arg_trait)));
.map(as_arg_trait)));
first = false;
}
if opts {
Expand Down Expand Up @@ -826,11 +836,11 @@ impl<'a> Help<'a> {
_ => continue,
};

debugln!("iter;tag_buf={};", unsafe {
String::from_utf8_unchecked(tag_buf.get_ref()[0..tag_length]
.iter()
.map(|&i|i)
.collect::<Vec<_>>())
debugln!("iter;tag_buf={};", unsafe {
String::from_utf8_unchecked(tag_buf.get_ref()[0..tag_length]
.iter()
.map(|&i| i)
.collect::<Vec<_>>())
});
match &tag_buf.get_ref()[0..tag_length] {
b"?" => {
Expand Down Expand Up @@ -862,21 +872,21 @@ impl<'a> Help<'a> {
}
b"unified" => {
let opts_flags = parser.iter_flags()
.map(as_arg_trait)
.chain(parser.iter_opts().map(as_arg_trait));
.map(as_arg_trait)
.chain(parser.iter_opts().map(as_arg_trait));
try!(self.write_args(opts_flags));
}
b"flags" => {
try!(self.write_args(parser.iter_flags()
.map(as_arg_trait)));
.map(as_arg_trait)));
}
b"options" => {
try!(self.write_args(parser.iter_opts()
.map(as_arg_trait)));
.map(as_arg_trait)));
}
b"positionals" => {
try!(self.write_args(parser.iter_positionals()
.map(as_arg_trait)));
.map(as_arg_trait)));
}
b"subcommands" => {
try!(self.write_subcommands(&parser));
Expand Down Expand Up @@ -904,7 +914,9 @@ impl<'a> Help<'a> {

#[cfg_attr(feature = "lints", allow(explicit_counter_loop))]
fn wrap_help(help: &mut String, longest_w: usize, avail_chars: usize) {
debugln!("fn=wrap_help;longest_w={},avail_chars={}", longest_w, avail_chars);
debugln!("fn=wrap_help;longest_w={},avail_chars={}",
longest_w,
avail_chars);
debug!("Enough space to wrap...");
if longest_w < avail_chars {
sdebugln!("Yes");
Expand All @@ -913,9 +925,11 @@ fn wrap_help(help: &mut String, longest_w: usize, avail_chars: usize) {
let mut i = 0;
for (idx, g) in (&*help.clone()).grapheme_indices(true) {
debugln!("iter;idx={},g={}", idx, g);
if g != " " { continue; }
if g != " " {
continue;
}
if str_width(&help[j..idx + (2 * i)]) < avail_chars {
debugln!("Still enough space...");
debugln!("Still enough space...");
prev_space = idx;
continue;
}
Expand Down
6 changes: 4 additions & 2 deletions src/app/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,10 @@ macro_rules! validate_multiples {
($_self:ident, $a:ident, $m:ident) => {
debugln!("macro=validate_multiples!;");
if $m.contains(&$a.name) && !$a.settings.is_set(ArgSettings::Multiple) {
// Not the first time, and we don't allow multiples
return Err(Error::unexpected_multiple_usage($a, &*$_self.create_current_usage($m), $_self.color()))
// Not the first time, and we don't allow multiples
return Err(Error::unexpected_multiple_usage($a,
&*$_self.create_current_usage($m),
$_self.color()))
}
};
}
Expand Down
52 changes: 30 additions & 22 deletions src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,31 @@ pub mod parser;
mod meta;
mod help;

pub use self::settings::AppSettings;
// Std


// Internal
use app::help::Help;
use app::parser::Parser;
use args::{AnyArg, Arg, ArgGroup, ArgMatcher, ArgMatches, ArgSettings};
use errors::Error;
use errors::Result as ClapResult;
pub use self::settings::AppSettings;
use shell::Shell;
use std::borrow::Borrow;
use std::env;
use std::ffi::OsString;
use std::fmt;
use std::io::{self, BufRead, BufWriter, Write};
use std::path::Path;
use std::process;
use std::ffi::OsString;
use std::borrow::Borrow;
use std::result::Result as StdResult;
use std::rc::Rc;
use std::fmt;
use std::result::Result as StdResult;

// Third Party
use vec_map::VecMap;
#[cfg(feature = "yaml")]
use yaml_rust::Yaml;
use vec_map::VecMap;

use args::{AnyArg, Arg, ArgGroup, ArgMatcher, ArgMatches, ArgSettings};
use app::parser::Parser;
use app::help::Help;
use errors::Error;
use errors::Result as ClapResult;
use shell::Shell;

/// Used to create a representation of a command line program and all possible command line
/// arguments. Application settings are set using the "builder pattern" with the
Expand Down Expand Up @@ -1086,7 +1089,10 @@ impl<'a, 'b> App<'a, 'b> {
/// `<project>/target/debug/build/myapp-<hash>/out/myapp.bash-completion`.
///
/// Fish shell completions will use the file format `{bin_name}.fish`
pub fn gen_completions<T: Into<OsString>, S: Into<String>>(&mut self, bin_name: S, for_shell: Shell, out_dir: T) {
pub fn gen_completions<T: Into<OsString>, S: Into<String>>(&mut self,
bin_name: S,
for_shell: Shell,
out_dir: T) {
self.p.meta.bin_name = Some(bin_name.into());
self.p.gen_completions(for_shell, out_dir.into());
}
Expand Down Expand Up @@ -1124,7 +1130,10 @@ impl<'a, 'b> App<'a, 'b> {
/// ```shell
/// $ myapp generate-bash-completions > /etc/bash_completion.d/myapp
/// ```
pub fn gen_completions_to<W: Write, S: Into<String>>(&mut self, bin_name: S, for_shell: Shell, buf: &mut W) {
pub fn gen_completions_to<W: Write, S: Into<String>>(&mut self,
bin_name: S,
for_shell: Shell,
buf: &mut W) {
self.p.meta.bin_name = Some(bin_name.into());
self.p.gen_completions_to(for_shell, buf);
}
Expand Down Expand Up @@ -1342,11 +1351,7 @@ impl<'a> From<&'a Yaml> for App<'a, 'a> {
is_sc = Some(yaml_hash.get(sc_key).unwrap());
App::new(sc_key.as_str().unwrap())
};
yaml = if let Some(sc) = is_sc {
sc
} else {
yaml
};
yaml = if let Some(sc) = is_sc { sc } else { yaml };

macro_rules! yaml_str {
($a:ident, $y:ident, $i:ident) => {
Expand Down Expand Up @@ -1402,7 +1407,9 @@ impl<'a> From<&'a Yaml> for App<'a, 'a> {
if let Some(v) = yaml["global_settings"].as_vec() {
for ys in v {
if let Some(s) = ys.as_str() {
a = a.global_setting(s.parse().ok().expect("unknown AppSetting found in YAML file"));
a = a.global_setting(s.parse()
.ok()
.expect("unknown AppSetting found in YAML file"));
}
}
} else {
Expand Down Expand Up @@ -1531,7 +1538,8 @@ impl<'n, 'e> AnyArg<'n, 'e> for App<'n, 'e> {
}
fn aliases(&self) -> Option<Vec<&'e str>> {
if let Some(ref aliases) = self.p.meta.aliases {
let vis_aliases: Vec<_> = aliases.iter().filter_map(|&(n,v)| if v { Some(n) } else {None}).collect();
let vis_aliases: Vec<_> =
aliases.iter().filter_map(|&(n, v)| if v { Some(n) } else { None }).collect();
if vis_aliases.is_empty() {
None
} else {
Expand Down
Loading