use {anyhow::Result, once_cell::sync::Lazy};
static RE_CODING: Lazy<regex::bytes::Regex> = Lazy::new(|| {
regex::bytes::Regex::new(r"^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)").unwrap()
});
pub fn python_source_encoding(source: &[u8]) -> Vec<u8> {
let lines = source.split(|v| v == &b'\n');
for (i, line) in lines.enumerate() {
if i > 1 {
break;
}
if let Some(m) = RE_CODING.find(line) {
return m.as_bytes().to_vec();
}
}
b"utf-8".to_vec()
}
pub fn has_dunder_file(source: &[u8]) -> Result<bool> {
let encoding = python_source_encoding(source);
let encoder = match encoding_rs::Encoding::for_label(&encoding) {
Some(encoder) => encoder,
None => encoding_rs::UTF_8,
};
let (source, ..) = encoder.decode(source);
Ok(source.contains("__file__"))
}