use std::path::{Path, PathBuf};
use indexmap::IndexMap;
use crate::scripts::{self, ScriptTexts};
use crate::support::{base_path, key_to_text, settings};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Language {
Rust,
Template,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Start {
Anywhere,
Call,
}
const PATTERNS: [(&str, Start, bool); 3] = [
("Text::get(", Start::Anywhere, true),
("text(", Start::Call, false),
("text!(", Start::Call, false),
];
pub fn extract_texts(content: &str, language: Language) -> IndexMap<String, String> {
let mut pairs = IndexMap::new();
for (needle, start, accepts_option) in PATTERNS {
for call in calls(content, needle, start) {
if let Some((key, Some(value))) = read_call(content, call, language, accepts_option) {
pairs.insert(key, value);
}
}
}
for (needle, start, accepts_option) in PATTERNS {
for call in calls(content, needle, start) {
if let Some((key, None)) = read_call(content, call, language, accepts_option)
&& !pairs.contains_key(&key)
{
let text = key_to_text(&key);
pairs.insert(key, text);
}
}
}
pairs
}
fn calls(content: &str, needle: &str, start: Start) -> Vec<usize> {
let mut offsets = Vec::new();
for (index, _) in content.match_indices(needle) {
let allowed = match start {
Start::Anywhere => true,
Start::Call => !content[..index]
.chars()
.next_back()
.is_some_and(|before| before == '.' || before.is_alphanumeric() || before == '_'),
};
if allowed {
offsets.push(index + needle.len());
}
}
offsets
}
fn skip_whitespace(content: &str, at: usize) -> usize {
content.len() - content[at..].trim_start_matches(char::is_whitespace).len()
}
fn read_call(
content: &str,
after_paren: usize,
language: Language,
accepts_option: bool,
) -> Option<(String, Option<String>)> {
let key_at = skip_whitespace(content, after_paren);
let (key, after_key) = key_literal(content, key_at, language)?;
let next = skip_whitespace(content, after_key);
if content[next..].starts_with(')') {
return Some((key, None));
}
if !content[next..].starts_with(',') {
return None;
}
let value_at = skip_whitespace(content, next + 1);
if accepts_option && let Some(after) = content[value_at..].strip_prefix("None") {
let following = skip_whitespace(content, content.len() - after.len());
return matches!(content[following..].chars().next(), Some(',' | ')')).then_some((key, None));
}
let (value_at, wrapped) = match content[value_at..].strip_prefix("Some(") {
Some(_) if accepts_option => (skip_whitespace(content, value_at + "Some(".len()), true),
_ => (value_at, false),
};
let (value, after_value) = value_literal(content, value_at, language)?;
let mut following = skip_whitespace(content, after_value);
if wrapped {
if !content[following..].starts_with(')') {
return None;
}
following = skip_whitespace(content, following + 1);
}
matches!(content[following..].chars().next(), Some(',' | ')')).then_some((key, Some(value)))
}
fn key_literal(content: &str, at: usize, language: Language) -> Option<(String, usize)> {
let quote = content[at..].chars().next()?;
let raw_prefix = if language == Language::Rust {
raw_start(&content[at..])
} else {
None
};
if let Some((hashes, open)) = raw_prefix {
let start = at + open;
let close = format!("\"{}", "#".repeat(hashes));
let end = content[start..].find(&close)? + start;
let key = &content[start..end];
return (!key.contains('\n') && !key.contains('\r')).then(|| (key.to_owned(), end + close.len()));
}
let allowed = match language {
Language::Rust => quote == '"',
Language::Template => matches!(quote, '"' | '\''),
};
if !allowed {
return None;
}
let start = at + 1;
let end = content[start..].find(quote)? + start;
let key = &content[start..end];
let forbidden: &[char] = match language {
Language::Rust => &['\n', '\r'],
Language::Template => &['\n', '\r', '"', '\''],
};
(!key.contains(forbidden)).then(|| (key.to_owned(), end + 1))
}
fn value_literal(content: &str, at: usize, language: Language) -> Option<(String, usize)> {
if language == Language::Rust
&& let Some((hashes, open)) = raw_start(&content[at..])
{
let start = at + open;
let close = format!("\"{}", "#".repeat(hashes));
let end = content[start..].find(&close)? + start;
return Some((content[start..end].to_owned(), end + close.len()));
}
let quote = content[at..].chars().next()?;
let allowed = match language {
Language::Rust => quote == '"',
Language::Template => matches!(quote, '"' | '\''),
};
if !allowed {
return None;
}
let start = at + 1;
let mut index = start;
loop {
let character = content[index..].chars().next()?;
if character == quote {
let raw = &content[start..index];
let value = match language {
Language::Rust => unescape_rust(raw),
Language::Template => scripts::unescape(raw),
};
return Some((value, index + 1));
}
if character == '\\' {
let escaped = content[index + 1..].chars().next()?;
index += 1 + escaped.len_utf8();
continue;
}
index += character.len_utf8();
}
}
fn raw_start(rest: &str) -> Option<(usize, usize)> {
let after = rest.strip_prefix('r')?;
let hashes = after.bytes().take_while(|byte| *byte == b'#').count();
after[hashes..].starts_with('"').then_some((hashes, 1 + hashes + 1))
}
pub fn unescape_rust(string: &str) -> String {
let mut result = String::with_capacity(string.len());
let mut characters = string.char_indices().peekable();
while let Some((index, character)) = characters.next() {
if character != '\\' {
result.push(character);
continue;
}
let Some((_, escaped)) = characters.next() else {
result.push('\\');
break;
};
match escaped {
'n' => result.push('\n'),
'r' => result.push('\r'),
't' => result.push('\t'),
'0' => result.push('\0'),
'\\' | '\'' | '"' => result.push(escaped),
'x' => {
let digits = string.get(index + 2..index + 4).unwrap_or_default();
match u8::from_str_radix(digits, 16) {
Ok(code) => {
result.push(char::from(code));
characters.next();
characters.next();
}
Err(_) => result.push('x'),
}
}
'u' if string[index + 2..].starts_with('{') => {
let close = string[index + 2..].find('}').map(|close| close + index + 2);
match close.and_then(|close| {
u32::from_str_radix(&string[index + 3..close], 16)
.ok()
.map(|code| (close, code))
}) {
Some((close, code)) => {
result.extend(char::from_u32(code));
while characters.peek().is_some_and(|(next, _)| *next <= close) {
characters.next();
}
}
None => result.push('u'),
}
}
'\n' | '\r' => {
while characters
.peek()
.is_some_and(|(_, next)| matches!(next, ' ' | '\t' | '\n' | '\r'))
{
characters.next();
}
}
other => result.push(other),
}
}
result
}
const EXCLUDED: [&str; 5] = ["vendor", "node_modules", "storage", "tests", "target"];
pub fn project_files(base: &Path) -> Vec<PathBuf> {
let mut files = Vec::new();
walk(base, base, &mut files, &|path| {
matches!(
path.extension().and_then(|extension| extension.to_str()),
Some("rs" | "html")
)
});
files.sort();
files
}
pub fn script_files() -> Option<Vec<(PathBuf, String)>> {
let (paths, extensions) = settings(|config| {
(
config.scan.scripts.paths.clone(),
config.scan.scripts.extensions.clone(),
)
});
let base = base_path();
let roots: Vec<PathBuf> = paths
.iter()
.map(|path| {
let path = Path::new(path);
if path.is_absolute() {
path.to_owned()
} else {
base.join(path)
}
})
.filter(|path| path.is_dir())
.collect();
if roots.is_empty() {
return None;
}
let extensions: Vec<String> = extensions
.iter()
.map(|extension| extension.trim_start_matches('.').to_owned())
.collect();
let mut files = Vec::new();
for root in &roots {
let mut found = Vec::new();
walk_scripts(root, &mut found, &|path| {
let name = path.file_name().and_then(|name| name.to_str()).unwrap_or_default();
!(name.ends_with(".d.ts") || name.ends_with(".min.js"))
&& path
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| extensions.iter().any(|wanted| wanted == extension))
});
for path in found {
let relative = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().into_owned();
files.push((path, relative));
}
}
files.sort();
Some(files)
}
fn walk(base: &Path, directory: &Path, files: &mut Vec<PathBuf>, wanted: &dyn Fn(&Path) -> bool) {
let Ok(entries) = std::fs::read_dir(directory) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with('.') {
continue;
}
let Ok(kind) = entry.file_type() else {
continue;
};
if kind.is_dir() {
let relative = path.strip_prefix(base).unwrap_or(&path);
if EXCLUDED.contains(&name.as_str()) || relative == Path::new("bootstrap/cache") {
continue;
}
walk(base, &path, files, wanted);
} else if kind.is_file() && wanted(&path) {
files.push(path);
}
}
}
fn walk_scripts(directory: &Path, files: &mut Vec<PathBuf>, wanted: &dyn Fn(&Path) -> bool) {
let Ok(entries) = std::fs::read_dir(directory) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with('.') {
continue;
}
let Ok(kind) = entry.file_type() else {
continue;
};
if kind.is_dir() {
if name != "node_modules" {
walk_scripts(&path, files, wanted);
}
} else if kind.is_file() && wanted(&path) {
files.push(path);
}
}
}
pub struct Scan {
pub texts: IndexMap<String, String>,
pub unreadable: Vec<(String, usize, String)>,
}
pub fn scan_project() -> Scan {
let mut texts: IndexMap<String, String> = IndexMap::new();
for path in project_files(&base_path()) {
let Ok(content) = std::fs::read_to_string(&path) else {
continue;
};
let language = if path.extension().is_some_and(|extension| extension == "rs") {
Language::Rust
} else {
Language::Template
};
for (key, text) in extract_texts(&content, language) {
texts.insert(key, text);
}
}
let mut unreadable = Vec::new();
if let Some(files) = script_files() {
let extractor = ScriptTexts::new(settings(|config| config.scan.scripts.functions.clone()));
for (path, relative) in files {
let Ok(bytes) = std::fs::read(&path) else {
continue;
};
let found = extractor.extract_bytes(&bytes);
for (key, text) in found.texts {
texts.insert(key, text);
}
for call in found.unreadable {
unreadable.push((relative.clone(), call.line, call.call));
}
}
}
Scan { texts, unreadable }
}