Skip to content

Commit a03ea4f

Browse files
committed
refactor(word): move literal quoting out of Word's Display
SonarCloud rust:S3776 flagged the cognitive complexity of Display::fmt on PR #244. The per-quoting literal case is now fmt_literal; output is unchanged (round-trip property test and Display unit test pass). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J4QvDfX8Xoq6vedAKdWBif
1 parent 9bdedb9 commit a03ea4f

1 file changed

Lines changed: 21 additions & 22 deletions

File tree

‎impl/rust-cli/src/word.rs‎

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -175,33 +175,32 @@ impl From<&str> for Word {
175175
}
176176
}
177177

178+
/// Write one literal piece back as source with its quoting.
179+
fn fmt_literal(f: &mut fmt::Formatter<'_>, text: &str, quote: Quote) -> fmt::Result {
180+
match quote {
181+
Quote::None => f.write_str(text),
182+
Quote::Backslash => text.chars().try_for_each(|ch| write!(f, "\\{ch}")),
183+
// `'` cannot appear inside single quotes.
184+
Quote::Single => write!(f, "'{}'", text.replace('\'', "'\\''")),
185+
Quote::Double => {
186+
let mut escaped = String::with_capacity(text.len() + 2);
187+
for ch in text.chars() {
188+
if matches!(ch, '"' | '$' | '`' | '\\') {
189+
escaped.push('\\');
190+
}
191+
escaped.push(ch);
192+
}
193+
write!(f, "\"{escaped}\"")
194+
}
195+
}
196+
}
197+
178198
/// Writes the word back as shell source that parses to the same word.
179199
impl fmt::Display for Word {
180200
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181201
for segment in &self.segments {
182202
match segment {
183-
Segment::Literal { text, quote } => match quote {
184-
Quote::None => f.write_str(text)?,
185-
Quote::Backslash => {
186-
for ch in text.chars() {
187-
write!(f, "\\{ch}")?;
188-
}
189-
}
190-
Quote::Single => {
191-
// `'` cannot appear inside single quotes.
192-
write!(f, "'{}'", text.replace('\'', "'\\''"))?
193-
}
194-
Quote::Double => {
195-
f.write_str("\"")?;
196-
for ch in text.chars() {
197-
if matches!(ch, '"' | '$' | '`' | '\\') {
198-
f.write_str("\\")?;
199-
}
200-
write!(f, "{ch}")?;
201-
}
202-
f.write_str("\"")?;
203-
}
204-
},
203+
Segment::Literal { text, quote } => fmt_literal(f, text, *quote)?,
205204
Segment::Parameter {
206205
expr,
207206
braced,

0 commit comments

Comments
 (0)