From 04af6f2304c81ee42c71a2bb3c7335693a05ff22 Mon Sep 17 00:00:00 2001 From: Ryan Geary Date: Sun, 14 Jun 2020 17:28:50 -0400 Subject: Add one_indexed flag (#23) --- src/choice.rs | 39 +++++++++++++++++++++++++++++++++++++++ src/config.rs | 10 ++++++++++ src/opt.rs | 4 ++++ 3 files changed, 53 insertions(+) diff --git a/src/choice.rs b/src/choice.rs index b7a74de..5e6e679 100644 --- a/src/choice.rs +++ b/src/choice.rs @@ -1076,6 +1076,45 @@ mod tests { fn print_2_exclusive() { test_fn(vec!["choose", "2", "-x"], "a b c d", "c"); } + + #[test] + fn print_2_one_indexed() { + test_fn(vec!["choose", "2", "--one-indexed"], "a b c d", "b"); + } + + #[test] + fn print_2_to_4_one_indexed() { + test_fn(vec!["choose", "2:4", "--one-indexed"], "a b c d", "b c d"); + } + + #[test] + fn print_2_to_end_one_indexed() { + test_fn(vec!["choose", "2:", "--one-indexed"], "a b c d", "b c d"); + } + + #[test] + fn print_start_to_2_one_indexed() { + test_fn(vec!["choose", ":2", "--one-indexed"], "a b c d", "a b"); + } + + #[test] + fn print_2_to_4_one_indexed_exclusive() { + test_fn( + vec!["choose", "2:4", "--one-indexed", "-x"], + "a b c d", + "b c", + ); + } + + #[test] + fn print_4_to_2_one_indexed() { + test_fn(vec!["choose", "4:2", "--one-indexed"], "a b c d", "d c b"); + } + + #[test] + fn print_neg_4_to_2_one_indexed() { + test_fn(vec!["choose", "-4:2", "--one-indexed"], "a b c d", "a b"); + } } mod is_reverse_range_tests { diff --git a/src/config.rs b/src/config.rs index 53b3cfe..a279e24 100644 --- a/src/config.rs +++ b/src/config.rs @@ -22,6 +22,16 @@ impl Config { choice.end = choice.end - 1; } } + + if opt.one_indexed { + if choice.start > 0 { + choice.start -= 1; + } + + if choice.end > 0 { + choice.end -= 1; + } + } } let separator = match Regex::new(match &opt.field_separator { diff --git a/src/opt.rs b/src/opt.rs index d328191..94f1236 100644 --- a/src/opt.rs +++ b/src/opt.rs @@ -32,6 +32,10 @@ pub struct Opt { #[structopt(short, long)] pub non_greedy: bool, + /// Index from 1 instead of 0 + #[structopt(long)] + pub one_indexed: bool, + /// Specify output field separator #[structopt(short, long, parse(from_str = parse::output_field_separator))] pub output_field_separator: Option, -- cgit v1.2.3