Skip to content

Commit 8745e27

Browse files
committed
refactor(frontmatter): Extract strip_ws_lines
1 parent 84cc6ce commit 8745e27

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

src/cargo/util/frontmatter.rs

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -26,16 +26,9 @@ impl<'s> ScriptSource<'s> {
2626
let mut rest = source.content;
2727

2828
// Whitespace may precede a frontmatter but must end with a newline
29-
let trimmed = rest.trim_start_matches(is_whitespace);
30-
if trimmed.len() != rest.len() {
31-
let trimmed_len = rest.len() - trimmed.len();
32-
let last_trimmed_index = trimmed_len - 1;
33-
if rest.as_bytes()[last_trimmed_index] != b'\n' {
34-
// either not a frontmatter or invalid opening
35-
return Ok(source);
36-
}
29+
if let Some(nl_end) = strip_ws_lines(rest) {
30+
rest = &rest[nl_end..];
3731
}
38-
rest = trimmed;
3932

4033
// Opens with a line that starts with 3 or more `-` followed by an optional identifier
4134
const FENCE_CHAR: char = '-';
@@ -133,6 +126,18 @@ pub fn strip_shebang(input: &str) -> Option<usize> {
133126
None
134127
}
135128

129+
/// Returns the index after any lines with only whitespace, if present
130+
pub fn strip_ws_lines(input: &str) -> Option<usize> {
131+
let ws_end = input.find(|c| !is_whitespace(c)).unwrap_or(input.len());
132+
if ws_end == 0 {
133+
return None;
134+
}
135+
136+
let nl_start = input[0..ws_end].rfind('\n')?;
137+
let nl_end = nl_start + 1;
138+
Some(nl_end)
139+
}
140+
136141
/// True if `c` is considered a whitespace according to Rust language definition.
137142
/// See [Rust language reference](https://doc.rust-lang.org/reference/whitespace.html)
138143
/// for definitions of these classes.

0 commit comments

Comments
 (0)