Skip to content

Commit e148c3d

Browse files
committed
refactor(embedded): Extract shebang splitting
This is intended to make the code more closely match rustc
1 parent fbd2993 commit e148c3d

File tree

1 file changed

+22
-21
lines changed

1 file changed

+22
-21
lines changed

src/cargo/util/toml/embedded.rs

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -140,27 +140,8 @@ impl<'s> ScriptSource<'s> {
140140
content: input,
141141
};
142142

143-
// See rust-lang/rust's compiler/rustc_lexer/src/lib.rs's `strip_shebang`
144-
// Shebang must start with `#!` literally, without any preceding whitespace.
145-
// For simplicity we consider any line starting with `#!` a shebang,
146-
// regardless of restrictions put on shebangs by specific platforms.
147-
if let Some(rest) = source.content.strip_prefix("#!") {
148-
// Ok, this is a shebang but if the next non-whitespace token is `[`,
149-
// then it may be valid Rust code, so consider it Rust code.
150-
//
151-
// NOTE: rustc considers line and block comments to be whitespace but to avoid
152-
// any more awareness of Rust grammar, we are excluding it.
153-
if rest.trim_start().starts_with('[') {
154-
return Ok(source);
155-
}
156-
157-
// No other choice than to consider this a shebang.
158-
let newline_end = source
159-
.content
160-
.find('\n')
161-
.map(|pos| pos + 1)
162-
.unwrap_or(source.content.len());
163-
let (shebang, content) = source.content.split_at(newline_end);
143+
if let Some(shebang_end) = strip_shebang(source.content) {
144+
let (shebang, content) = source.content.split_at(shebang_end);
164145
source.shebang = Some(shebang);
165146
source.content = content;
166147
}
@@ -235,6 +216,26 @@ impl<'s> ScriptSource<'s> {
235216
}
236217
}
237218

219+
fn strip_shebang(input: &str) -> Option<usize> {
220+
// See rust-lang/rust's compiler/rustc_lexer/src/lib.rs's `strip_shebang`
221+
// Shebang must start with `#!` literally, without any preceding whitespace.
222+
// For simplicity we consider any line starting with `#!` a shebang,
223+
// regardless of restrictions put on shebangs by specific platforms.
224+
if let Some(rest) = input.strip_prefix("#!") {
225+
// Ok, this is a shebang but if the next non-whitespace token is `[`,
226+
// then it may be valid Rust code, so consider it Rust code.
227+
//
228+
// NOTE: rustc considers line and block comments to be whitespace but to avoid
229+
// any more awareness of Rust grammar, we are excluding it.
230+
if !rest.trim_start().starts_with('[') {
231+
// No other choice than to consider this a shebang.
232+
let newline_end = input.find('\n').map(|pos| pos + 1).unwrap_or(input.len());
233+
return Some(newline_end);
234+
}
235+
}
236+
None
237+
}
238+
238239
#[cfg(test)]
239240
mod test_expand {
240241
use snapbox::assert_data_eq;

0 commit comments

Comments
 (0)