Skip to content

Commit 2b85f6f

Browse files
fold: parse the obsolete -WIDTH form the way GNU does (#14248)
* fold: parse the obsolete -WIDTH form the way GNU does `handle_obsolete` scanned every argument for `-DIGITS` and pulled the first match out, without checking whether that argument was already spoken for. Five GNU incompatibilities followed: fold -w -1 FILE reported FILE as the invalid width, not -1, because -1 was taken as the obsolete form and -w then bound to the file name. Same for -bw, -sw and --width. fold -w3 -5 folded at 3; GNU folds at 5, since it reads options left to right and the last width wins. fold -3 -5 failed with "unexpected argument '-5'", as only the first obsolete width was consumed. fold -w 3 -w 5 failed with "cannot be used multiple times". fold -- -3 read stdin, swallowing the width past the -- that should have made it a file name. Rewrite the obsolete form into --width=N in place instead, leaving the order intact, and let clap pick the last one via args_override_self. Arguments that are the value of -w/--width, and anything after --, are no longer eligible. The remaining difference on `fold -w 0` ("Result too large" against GNU's "Numerical result out of range") is a separate wording issue and is left alone. * Apply suggestion from @sylvestre * fold: compare find('w') against checked_sub directly * fold: cover the bare - operand with a test The underflow fixed in the previous commit had no test behind it. This pins `-` as an operand in each position, including as the value of -w where GNU rejects it as a width. * fold: fix a false positive in the -w-takes-a-value check `takes_width_value` decided a trailing `w` by comparing `find('w')` to `len().checked_sub(1)`. For a bare `-` (short = ""), both sides are `None` -- "no 'w' found" and "length underflowed" are different reasons, but the comparison can't tell them apart, so it reported a match: $ fold - -5 <<< hello error: unexpected argument '-5' found # uutils, before hello # GNU, and uutils after That made the `-` operand swallow whatever followed it as a width value instead of leaving it for the obsolete-width scan, so `fold - -5` failed to parse where GNU folds normally. `ends_with('w')` is false on an empty string, so it doesn't share the bug. Found while investigating an unrelated CI failure in this PR (a broken pipe in test_dash_operand_reads_stdin, which turned out to be a flaky cross-compiled job, not this) -- this bug doesn't explain that failure, but turned up real and worth fixing while looking at this function. --------- Co-authored-by: arbelonson-source <[email protected]> Co-authored-by: Sylvestre Ledru <[email protected]>
1 parent 5f3aa7b commit 2b85f6f

2 files changed

Lines changed: 163 additions & 13 deletions

File tree

‎src/uu/fold/src/fold.rs‎

Lines changed: 71 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -54,16 +54,13 @@ struct FoldContext<'a, W: Write> {
5454
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
5555
let args = args.collect_lossy();
5656

57-
let (args, obs_width) = handle_obsolete(&args[..]);
57+
let args = handle_obsolete(&args[..]);
5858
let matches = uucore::clap_localization::handle_clap_result(uu_app(), args)?;
5959

6060
let bytes = matches.get_flag(options::BYTES);
6161
let characters = matches.get_flag(options::CHARACTERS);
6262
let spaces = matches.get_flag(options::SPACES);
63-
let poss_width = match matches.get_one::<String>(options::WIDTH) {
64-
Some(v) => Some(v.clone()),
65-
None => obs_width,
66-
};
63+
let poss_width = matches.get_one::<String>(options::WIDTH).cloned();
6764

6865
let width = match poss_width {
6966
Some(inp_width) => match inp_width.parse::<usize>() {
@@ -105,6 +102,8 @@ pub fn uu_app() -> Command {
105102
.override_usage(format_usage(&translate!("fold-usage")))
106103
.about(translate!("fold-about"))
107104
.infer_long_args(true)
105+
// GNU lets a later width override an earlier one, e.g. `fold -w3 -w5`.
106+
.args_override_self(true)
108107
.arg(
109108
Arg::new(options::BYTES)
110109
.long(options::BYTES)
@@ -143,16 +142,75 @@ pub fn uu_app() -> Command {
143142
)
144143
}
145144

146-
fn handle_obsolete(args: &[String]) -> (Vec<String>, Option<String>) {
147-
for (i, arg) in args.iter().enumerate() {
148-
let slice = &arg;
149-
if slice.starts_with('-') && slice.chars().nth(1).is_some_and(|c| c.is_ascii_digit()) {
150-
let mut v = args.to_vec();
151-
v.remove(i);
152-
return (v, Some(slice[1..].to_owned()));
145+
/// Whether `arg` is the obsolete `-WIDTH` form, such as `-5`.
146+
///
147+
/// The check is deliberately loose: GNU rejects `-5x` with
148+
/// `invalid number of columns: '5x'` rather than treating it as a file, so
149+
/// anything starting with a digit is taken as a (possibly invalid) width.
150+
fn is_obsolete_width(arg: &str) -> bool {
151+
arg.strip_prefix('-')
152+
.and_then(|rest| rest.chars().next())
153+
.is_some_and(|c| c.is_ascii_digit())
154+
}
155+
156+
/// Whether `arg` is a `-w`/`--width` spelling that consumes the *next*
157+
/// argument as its value.
158+
fn takes_width_value(arg: &str) -> bool {
159+
if let Some(long) = arg.strip_prefix("--") {
160+
// `--width=5` carries its own value. A bare `--width`, or an
161+
// unambiguous abbreviation of it (`infer_long_args` is enabled),
162+
// takes the following argument.
163+
!long.is_empty() && !long.contains('=') && options::WIDTH.starts_with(long)
164+
} else if let Some(short) = arg.strip_prefix('-') {
165+
// Only a trailing `w` takes the next argument: in `-sw` it does, but
166+
// in `-w3` and `-wb` the value is attached to the flag instead. A
167+
// bare `-` has no trailing `w` either -- `ends_with` on an empty
168+
// string is false, where comparing two `find`/`checked_sub` failures
169+
// (both `None`) would wrongly call it a match.
170+
short.ends_with('w')
171+
} else {
172+
false
173+
}
174+
}
175+
176+
/// Rewrite the obsolete `-WIDTH` syntax into the equivalent `--width=WIDTH`.
177+
///
178+
/// GNU processes options left to right, so the last width given wins no matter
179+
/// which spelling was used (`fold -w3 -5` folds at 5). Rewriting in place keeps
180+
/// that ordering and lets clap apply the same last-one-wins rule, via
181+
/// `args_override_self`.
182+
///
183+
/// An argument is only the obsolete form when it is not already being consumed
184+
/// as the value of `-w`/`--width`, and has not been placed after a `--`
185+
/// terminator. Otherwise `fold -w -1` would misreport the file name as the
186+
/// invalid width, and `fold -- -3` would silently read stdin instead of
187+
/// failing to open the file named `-3`.
188+
fn handle_obsolete(args: &[String]) -> Vec<String> {
189+
let mut result = Vec::with_capacity(args.len());
190+
let mut iter = args.iter();
191+
192+
// argv[0] is the program name, never an option.
193+
if let Some(program) = iter.next() {
194+
result.push(program.clone());
195+
}
196+
197+
let mut end_of_options = false;
198+
let mut expecting_width = false;
199+
for arg in iter {
200+
if end_of_options || expecting_width {
201+
expecting_width = false;
202+
} else if arg == "--" {
203+
end_of_options = true;
204+
} else if is_obsolete_width(arg) {
205+
result.push(format!("--{}={}", options::WIDTH, &arg[1..]));
206+
continue;
207+
} else {
208+
expecting_width = takes_width_value(arg);
153209
}
210+
result.push(arg.clone());
154211
}
155-
(args.to_vec(), None)
212+
213+
result
156214
}
157215

158216
fn fold(

‎tests/by-util/test_fold.rs‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1110,3 +1110,95 @@ fn test_width_overflow() {
11101110
"fold: invalid number of columns: '999999999999999999999': Numerical result out of range\n",
11111111
);
11121112
}
1113+
1114+
#[test]
1115+
fn test_negative_width_as_separate_value() {
1116+
// GNU consumes the argument after `-w` as its value even when it looks
1117+
// like an option, and reports that value as the invalid one. Passing a
1118+
// file too, because the width used to be mistaken for the obsolete
1119+
// `-WIDTH` form, leaving the file name to be read as the width.
1120+
for args in [
1121+
vec!["-w", "-1"],
1122+
vec!["--width", "-1"],
1123+
vec!["-bw", "-1"],
1124+
vec!["-sw", "-1"],
1125+
] {
1126+
new_ucmd!()
1127+
.args(&args)
1128+
.arg("lorem_ipsum.txt")
1129+
.fails_with_code(1)
1130+
.stderr_is("fold: invalid number of columns: '-1'\n");
1131+
}
1132+
}
1133+
1134+
#[test]
1135+
fn test_obsolete_width_after_double_dash_is_a_file() {
1136+
// After `--` there are no more options, so `-3` names a file.
1137+
new_ucmd!()
1138+
.arg("--")
1139+
.arg("-3")
1140+
.fails_with_code(1)
1141+
.stderr_is("fold: -3: No such file or directory\n");
1142+
}
1143+
1144+
#[test]
1145+
fn test_last_width_wins() {
1146+
// GNU processes options left to right, so the last width given wins,
1147+
// regardless of which spelling each one used.
1148+
for args in [
1149+
vec!["-w3", "-5"],
1150+
vec!["-3", "-5"],
1151+
vec!["-w", "3", "-w", "5"],
1152+
vec!["-w3", "-w5"],
1153+
vec!["-5", "-w", "5"],
1154+
] {
1155+
new_ucmd!()
1156+
.args(&args)
1157+
.pipe_in("aaaaaaaaaa\n")
1158+
.succeeds()
1159+
.stdout_is("aaaaa\naaaaa\n");
1160+
}
1161+
1162+
// ...and an obsolete width is overridden by a later `-w` just the same.
1163+
new_ucmd!()
1164+
.args(&["-5", "-w", "3"])
1165+
.pipe_in("aaaaaa\n")
1166+
.succeeds()
1167+
.stdout_is("aaa\naaa\n");
1168+
}
1169+
1170+
#[test]
1171+
fn test_dash_operand_reads_stdin() {
1172+
// A bare `-` names stdin and leaves nothing after the dash for the
1173+
// width-value scan to index, which used to abort before reading input.
1174+
new_ucmd!()
1175+
.arg("-")
1176+
.pipe_in("hello\n")
1177+
.succeeds()
1178+
.stdout_is("hello\n");
1179+
1180+
// ...in every position, including as the value of -w, where GNU rejects
1181+
// it as a width rather than treating it as the operand.
1182+
new_ucmd!()
1183+
.args(&["-w", "3", "-"])
1184+
.pipe_in("hello\n")
1185+
.succeeds()
1186+
.stdout_is("hel\nlo\n");
1187+
new_ucmd!()
1188+
.args(&["-w", "-"])
1189+
.pipe_in("hello\n")
1190+
.fails()
1191+
.stderr_contains("invalid number of columns: '-'");
1192+
}
1193+
1194+
/// A bare `-` has no trailing `w`, so it must not be mistaken for one of the
1195+
/// short spellings that consumes the next argument as its width -- that once
1196+
/// swallowed whatever followed the `-` operand instead of scanning it.
1197+
#[test]
1198+
fn test_dash_operand_does_not_swallow_the_next_argument() {
1199+
new_ucmd!()
1200+
.args(&["-", "-5"])
1201+
.pipe_in("hello\n")
1202+
.succeeds()
1203+
.stdout_is("hello\n");
1204+
}

0 commit comments

Comments
 (0)