[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.
use std::borrow::Cow;
use std::cell::OnceCell;
use std::ops::Deref;
@ -10,34 +11,43 @@ use ruff_text_size::Ranged;
#[derive(Debug, Clone)]
pub struct Stylist<'a> {
source: &'a str,
source: Cow<'a, str>,
indentation: Indentation,
quote: Quote,
line_ending: OnceCell<LineEnding>,
}
impl<'a> Stylist<'a> {
pub fn indentation(&'a self) -> &'a Indentation {
pub fn indentation(&self) -> &Indentation {
&self.indentation
}
pub fn quote(&'a self) -> Quote {
pub fn quote(&self) -> Quote {
self.quote
}
pub fn line_ending(&'a self) -> LineEnding {
pub fn line_ending(&self) -> LineEnding {
*self.line_ending.get_or_init(|| {
find_newline(self.source)
find_newline(&self.source)
.map(|(_, ending)| ending)
.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 {
let indentation = detect_indentation(tokens, source);
Self {
source,
source: Cow::Borrowed(source),
indentation,
quote: detect_quote(tokens),
line_ending: OnceCell::default(),