Skip to content

Commit 8bf31b8

Browse files
committed
ptx: handle invalid regex arguments gracefully instead of panicking
1 parent 3162c21 commit 8bf31b8

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

src/uu/ptx/src/ptx.rs

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -342,9 +342,15 @@ fn read_lines(
342342
}
343343

344344
/// Go through every lines in the input files and record each match occurrence as a `WordRef`.
345-
fn create_word_set(config: &Config, filter: &WordFilter, file_map: &FileMap) -> BTreeSet<WordRef> {
346-
let reg = Regex::new(&filter.word_regex).unwrap();
347-
let ref_reg = Regex::new(&config.context_regex).unwrap();
345+
fn create_word_set(
346+
config: &Config,
347+
filter: &WordFilter,
348+
file_map: &FileMap,
349+
) -> UResult<BTreeSet<WordRef>> {
350+
let reg = Regex::new(&filter.word_regex)
351+
.map_err(|e| USimpleError::new(1, format!("invalid regular expression: {}", e)))?;
352+
let ref_reg = Regex::new(&config.context_regex)
353+
.map_err(|e| USimpleError::new(1, format!("invalid regular expression: {}", e)))?;
348354
let mut word_set: BTreeSet<WordRef> = BTreeSet::new();
349355
for (file, lines) in file_map {
350356
let mut count: usize = 0;
@@ -383,7 +389,7 @@ fn create_word_set(config: &Config, filter: &WordFilter, file_map: &FileMap) ->
383389
count += 1;
384390
}
385391
}
386-
word_set
392+
Ok(word_set)
387393
}
388394

389395
fn get_reference(config: &Config, word_ref: &WordRef, line: &str, context_reg: &Regex) -> String {
@@ -925,7 +931,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
925931

926932
let word_filter = WordFilter::new(&matches, &config)?;
927933
let file_map = read_input(&input_files, &config).map_err_context(String::new)?;
928-
let word_set = create_word_set(&config, &word_filter, &file_map);
934+
let word_set = create_word_set(&config, &word_filter, &file_map)?;
929935
write_traditional_output(&mut config, &file_map, &word_set, &output_file)
930936
}
931937

tests/by-util/test_ptx.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,3 +338,19 @@ fn test_unicode_truncation_alignment() {
338338
.succeeds()
339339
.stdout_only(" / bar\n föö/\n");
340340
}
341+
342+
#[test]
343+
fn test_invalid_regex_word_trailing_backslash() {
344+
new_ucmd!()
345+
.args(&["-W", "bar\\"])
346+
.fails_with_code(1)
347+
.stderr_contains("ptx: invalid regular expression");
348+
}
349+
350+
#[test]
351+
fn test_invalid_regex_word_unclosed_group() {
352+
new_ucmd!()
353+
.args(&["-W", "(wrong"])
354+
.fails_with_code(1)
355+
.stderr_contains("ptx: invalid regular expression");
356+
}

0 commit comments

Comments
 (0)