Repository: astral-sh/uv
File: crates/uv-workspace/src/pyproject_mut.rs (Rust)

Code before:

impl fmt::Display for PyProjectTomlMut {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.doc.fmt(f)
    }
}

fn try_parse_requirement(req: &str) -> Option<Requirement> {
    Requirement::from_str(req).ok()
}

/// Reformats a TOML array to multi line while trying to preserve all comments
/// and move them around. This also formats the array to have a trailing comma.
fn reformat_array_multiline(deps: &mut Array) {
    fn find_comments(s: Option<&RawString>) -> Box<dyn Iterator<Item = Comment> + '_> {
        let iter = s
            .and_then(|x| x.as_str())
            .unwrap_or("")
            .lines()
            .scan(
                (false, false),
                |(prev_line_was_empty, prev_line_was_comment), line| {
                    let trimmed_line = line.trim();

                    if let Some(index) = line.find('#') {
                        let comment_text = line[index..].trim().to_string();

                        let comment_kind = if (*prev_line_was_empty) || (*prev_line_was_comment) {
                            CommentType::OwnLine
                        } else {
                            let before = &line[..index];
                            let leading_whitespace = before[before.trim_end().len()..].to_string();
                            CommentType::EndOfLine { leading_whitespace }
                        };

                        *prev_line_was_empty = trimmed_line.is_empty();
                        *prev_line_was_comment = true;

                        Some(Some(Comment {
                            text: comment_text,
                            kind: comment_kind,
                        }))
                    } else {
                        *prev_line_was_empty = trimmed_line.is_empty();
                        *prev_line_was_comment = false;
                        Some(None)
                    }
                },
            )
            .flatten();


Review comment (bug):
Sorry for coming up with this only now, but can we make those safer by using e.g. `split_once`? Indexing can panic, and it's easy to get logic such as this wrong, so we try to use non-indexing versions where they aren't too inconvenient or too slow.

Code after:

impl fmt::Display for PyProjectTomlMut {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.doc.fmt(f)
    }
}

fn try_parse_requirement(req: &str) -> Option<Requirement> {
    Requirement::from_str(req).ok()
}

/// Reformats a TOML array to multi line while trying to preserve all comments
/// and move them around. This also formats the array to have a trailing comma.
fn reformat_array_multiline(deps: &mut Array) {
    fn find_comments(s: Option<&RawString>) -> Box<dyn Iterator<Item = Comment> + '_> {
        let iter = s
            .and_then(|x| x.as_str())
            .unwrap_or("")
            .lines()
            .scan(
                (false, false),
                |(prev_line_was_empty, prev_line_was_comment), line| {
                    let trimmed_line = line.trim();

                    if let Some((before, comment)) = line.split_once('#') {
                        let comment_text = format!("#{}", comment.trim_end());

                        let comment_kind = if (*prev_line_was_empty) || (*prev_line_was_comment) {
                            CommentType::OwnLine
                        } else {
                            CommentType::EndOfLine {
                                leading_whitespace: before
                                    .chars()
                                    .rev()
                                    .take_while(|c| c.is_whitespace())
                                    .collect::<String>()
                                    .chars()
                                    .rev()
                                    .collect(),
                            }
                        };

                        *prev_line_was_empty = trimmed_line.is_empty();
                        *prev_line_was_comment = true;

                        Some(Some(Comment {
                            text: comment_text,
                            kind: comment_kind,
                        }))
                    } else {
                        *prev_line_was_empty = trimmed_line.is_empty();