MCPcopy Create free account
hub / github.com/astral-sh/ruff / choose_quotes

Method choose_quotes

crates/ruff_python_formatter/src/string/normalize.rs:193–234  ·  view source on GitHub ↗

Computes the strings preferred quotes.

(&self, string: StringLikePart)

Source from the content-addressed store, hash-verified

191
192 /// Computes the strings preferred quotes.
193 pub(crate) fn choose_quotes(&self, string: StringLikePart) -> QuoteSelection {
194 let raw_content = &self.context.source()[string.content_range()];
195 let first_quote_or_normalized_char_offset = raw_content
196 .bytes()
197 .position(|b| matches!(b, b'\\' | b'"' | b'\'' | b'\r'));
198 let string_flags = string.flags();
199 let preferred_style = self.preferred_quote_style(string);
200
201 let new_kind = match (
202 Quote::try_from(preferred_style),
203 first_quote_or_normalized_char_offset,
204 ) {
205 // The string contains no quotes so it's safe to use the preferred quote style
206 (Ok(preferred_quote), None) => string_flags.with_quote_style(preferred_quote),
207
208 // The preferred quote style is single or double quotes, and the string contains a quote or
209 // another character that may require escaping
210 (Ok(preferred_quote), Some(first_quote_or_normalized_char_offset)) => {
211 let metadata = if string.is_interpolated_string() {
212 QuoteMetadata::from_part(string, self.context, preferred_quote)
213 } else {
214 QuoteMetadata::from_str(
215 &raw_content[first_quote_or_normalized_char_offset..],
216 string.flags(),
217 preferred_quote,
218 )
219 };
220
221 let quote = metadata.choose(preferred_quote);
222
223 string_flags.with_quote_style(quote)
224 }
225
226 // The preferred quote style is to preserve the quotes, so let's do that.
227 (Err(()), _) => string_flags,
228 };
229
230 QuoteSelection {
231 flags: new_kind,
232 first_quote_or_normalized_char_offset,
233 }
234 }
235
236 /// Computes the strings preferred quotes and normalizes its content.
237 pub(crate) fn normalize(&self, string: StringLikePart) -> NormalizedString<'src> {

Callers 3

normalizeMethod · 0.80
fmt_fieldsMethod · 0.80
fmt_fieldsMethod · 0.80

Calls 9

bytesMethod · 0.80
preferred_quote_styleMethod · 0.80
chooseMethod · 0.80
sourceMethod · 0.45
content_rangeMethod · 0.45
positionMethod · 0.45
flagsMethod · 0.45
with_quote_styleMethod · 0.45

Tested by

no test coverage detected