[ruff] Provide a way to get an owned Stylist

This makes it easier to test with in some cases and generally shouldn't
cost anything.
This commit is contained in:
Andrew Gallant 2025-09-10 15:05:06 -04:00 committed by Andrew Gallant
parent 880a867696
commit a47a50e6e2

View file

@ -1,5 +1,6 @@
//! Detect code style from Python source code. //! Detect code style from Python source code.
use std::borrow::Cow;
use std::cell::OnceCell; use std::cell::OnceCell;
use std::ops::Deref; use std::ops::Deref;
@ -10,34 +11,43 @@ use ruff_text_size::Ranged;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Stylist<'a> { pub struct Stylist<'a> {
source: &'a str, source: Cow<'a, str>,
indentation: Indentation, indentation: Indentation,
quote: Quote, quote: Quote,
line_ending: OnceCell<LineEnding>, line_ending: OnceCell<LineEnding>,
} }
impl<'a> Stylist<'a> { impl<'a> Stylist<'a> {
pub fn indentation(&'a self) -> &'a Indentation { pub fn indentation(&self) -> &Indentation {
&self.indentation &self.indentation
} }
pub fn quote(&'a self) -> Quote { pub fn quote(&self) -> Quote {
self.quote self.quote
} }
pub fn line_ending(&'a self) -> LineEnding { pub fn line_ending(&self) -> LineEnding {
*self.line_ending.get_or_init(|| { *self.line_ending.get_or_init(|| {
find_newline(self.source) find_newline(&self.source)
.map(|(_, ending)| ending) .map(|(_, ending)| ending)
.unwrap_or_default() .unwrap_or_default()
}) })
} }
pub fn into_owned(self) -> Stylist<'static> {
Stylist {
source: Cow::Owned(self.source.into_owned()),
indentation: self.indentation,
quote: self.quote,
line_ending: self.line_ending,
}
}
pub fn from_tokens(tokens: &Tokens, source: &'a str) -> Self { pub fn from_tokens(tokens: &Tokens, source: &'a str) -> Self {
let indentation = detect_indentation(tokens, source); let indentation = detect_indentation(tokens, source);
Self { Self {
source, source: Cow::Borrowed(source),
indentation, indentation,
quote: detect_quote(tokens), quote: detect_quote(tokens),
line_ending: OnceCell::default(), line_ending: OnceCell::default(),