-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
333 lines (279 loc) · 10.3 KB
/
main.rs
File metadata and controls
333 lines (279 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
use anyhow::{Context, Result};
use chardetng::EncodingDetector;
use dialoguer::{theme::ColorfulTheme, Select};
use encoding_rs::Encoding;
use ignore::WalkBuilder;
use rayon::prelude::*;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
const CONFIG_FILE: &str = "rsfe.conf";
const COMMON_ENCODINGS: &[&str] = &[
"UTF-8",
"UTF-16LE",
"UTF-16BE",
"ISO-8859-1",
"WINDOWS-1252",
"AUTO",
];
#[derive(Debug, Clone)]
struct EncodingRule {
pattern: glob::Pattern,
encoding: String,
}
#[derive(Debug)]
struct Config {
rules: Vec<EncodingRule>,
default_encoding: String,
}
impl Config {
fn load(config_path: &Path) -> Result<Self> {
let content = fs::read_to_string(config_path)
.with_context(|| format!("Falha ao ler arquivo de configuração: {:?}", config_path))?;
let mut rules = Vec::new();
let mut default_encoding = String::from("UTF-8");
for (line_num, line) in content.lines().enumerate() {
let line = line.trim();
// Ignora linhas vazias e comentários
if line.is_empty() || line.starts_with('#') {
continue;
}
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() != 2 {
eprintln!("Aviso: Linha {} ignorada (formato inválido): {}", line_num + 1, line);
continue;
}
let pattern_str = parts[0];
let encoding = parts[1].to_uppercase();
// Valida encoding
if encoding != "AUTO" && Encoding::for_label(encoding.as_bytes()).is_none() {
eprintln!("Aviso: Encoding desconhecido '{}' na linha {}", encoding, line_num + 1);
continue;
}
if pattern_str == "**" {
default_encoding = encoding.clone();
} else {
match glob::Pattern::new(pattern_str) {
Ok(pattern) => rules.push(EncodingRule { pattern, encoding }),
Err(e) => {
eprintln!("Aviso: Padrão inválido '{}' na linha {}: {}", pattern_str, line_num + 1, e);
}
}
}
}
Ok(Config {
rules,
default_encoding,
})
}
fn get_encoding_for_file(&self, file_path: &Path) -> &str {
// Primeiro tenta usar o caminho relativo ao cwd
let path_str = if file_path.is_absolute() {
std::env::current_dir()
.ok()
.and_then(|cwd| file_path.strip_prefix(&cwd).ok())
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|| file_path.to_string_lossy().to_string())
} else {
file_path.to_string_lossy().to_string()
};
for rule in &self.rules {
if rule.pattern.matches(&path_str) {
return &rule.encoding;
}
}
&self.default_encoding
}
}
fn detect_encoding(content: &[u8]) -> Option<&'static Encoding> {
let mut detector = EncodingDetector::new();
detector.feed(content, true);
Some(detector.guess(None, true))
}
fn convert_encoding(
file_path: &Path,
target_encoding_name: &str,
) -> Result<bool> {
let content = fs::read(file_path)
.with_context(|| format!("Falha ao ler arquivo: {:?}", file_path))?;
// Se arquivo está vazio, não precisa converter
if content.is_empty() {
return Ok(false);
}
let target_encoding = if target_encoding_name == "AUTO" {
detect_encoding(&content).unwrap_or(encoding_rs::UTF_8)
} else {
Encoding::for_label(target_encoding_name.as_bytes())
.unwrap_or(encoding_rs::UTF_8)
};
// Detecta o encoding atual
let current_encoding = detect_encoding(&content).unwrap_or(encoding_rs::UTF_8);
// Tenta decodificar o arquivo com o encoding alvo para verificar se já está correto
let (decoded_target, _, had_errors_target) = target_encoding.decode(&content);
if !had_errors_target {
// Verifica se ao recodificar obtemos exatamente o mesmo conteúdo
let (reencoded, _, _) = target_encoding.encode(&decoded_target);
// Se o conteúdo é idêntico E o encoding detectado é compatível com o alvo,
// considera que já está no encoding correto
if reencoded.as_ref() == content {
// Verifica se o encoding atual é realmente o mesmo do alvo
// (evita falsos positivos com encodings compatíveis)
let is_same_encoding = current_encoding.name() == target_encoding.name() ||
(target_encoding.name() == "windows-1252" && current_encoding.name().starts_with("windows")) ||
(target_encoding.name().starts_with("ISO-8859") && current_encoding.name().starts_with("ISO-8859"));
if is_same_encoding {
return Ok(false);
}
}
}
// Decodifica do encoding detectado
let (decoded, _, had_errors) = current_encoding.decode(&content);
if had_errors {
eprintln!(
"Aviso: Erros ao decodificar {:?} de {:?}",
file_path, current_encoding.name()
);
}
// Codifica para o encoding alvo
let (encoded, _, encode_errors) = target_encoding.encode(&decoded);
if encode_errors {
eprintln!(
"Aviso: Erros ao codificar {:?} para {:?}",
file_path, target_encoding.name()
);
}
// Escreve o arquivo convertido
let mut file = fs::File::create(file_path)
.with_context(|| format!("Falha ao criar arquivo: {:?}", file_path))?;
file.write_all(&encoded)
.with_context(|| format!("Falha ao escrever arquivo: {:?}", file_path))?;
println!(
"✓ Convertido: {:?} ({:?} → {:?})",
file_path,
current_encoding.name(),
target_encoding.name()
);
Ok(true)
}
fn prompt_default_encoding() -> Result<String> {
println!("\nArquivo de configuração 'rsfe.conf' não encontrado.");
println!("Selecione o encoding padrão para os arquivos do projeto:\n");
let selection = Select::with_theme(&ColorfulTheme::default())
.items(COMMON_ENCODINGS)
.default(0)
.interact()?;
Ok(COMMON_ENCODINGS[selection].to_string())
}
fn get_staged_files() -> Result<Vec<PathBuf>> {
// Tenta obter arquivos do stage do git
let output = std::process::Command::new("git")
.args(&["diff", "--cached", "--name-only", "--diff-filter=ACM"])
.output();
match output {
Ok(output) if output.status.success() => {
let files = String::from_utf8_lossy(&output.stdout)
.lines()
.map(|s| PathBuf::from(s.trim()))
.filter(|p| p.exists() && p.is_file())
.collect();
Ok(files)
}
_ => {
// Se não estiver em um repositório git ou não houver arquivos staged,
// processa todos os arquivos do projeto
Ok(Vec::new())
}
}
}
fn collect_files(base_path: &Path, specific_files: Option<Vec<PathBuf>>) -> Vec<PathBuf> {
if let Some(files) = specific_files {
if !files.is_empty() {
return files;
}
}
// Usa ignore/WalkBuilder para respeitar .gitignore
WalkBuilder::new(base_path)
.hidden(false)
.git_ignore(true)
.filter_entry(|entry| {
let path = entry.path();
// Ignora diretórios comuns
if path.is_dir() {
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
return !matches!(
name,
"node_modules" | "target" | "dist" | "build" | ".git" | ".idea" | ".vscode"
);
}
true
})
.build()
.filter_map(|entry| entry.ok())
.filter(|entry| entry.path().is_file())
.map(|entry| entry.path().to_path_buf())
.collect()
}
fn process_files(config: &Config, files: Vec<PathBuf>) -> Result<()> {
let results: Vec<_> = files
.par_iter()
.filter_map(|file_path| {
// Ignora arquivos binários comuns
if let Some(ext) = file_path.extension() {
let ext = ext.to_string_lossy().to_lowercase();
if matches!(
ext.as_str(),
"png" | "jpg" | "jpeg" | "gif" | "pdf" | "zip" | "tar" | "gz" | "exe" | "dll" | "so" | "dylib"
) {
return None;
}
}
let target_encoding = config.get_encoding_for_file(file_path);
match convert_encoding(file_path, target_encoding) {
Ok(converted) => Some((file_path.clone(), target_encoding.to_string(), converted)),
Err(e) => {
eprintln!("Erro ao processar {:?}: {}", file_path, e);
None
}
}
})
.collect();
let converted_count: usize = results.iter().map(|(_, _, converted)| if *converted { 1 } else { 0 }).sum();
println!(
"\n{} arquivo(s) convertido(s) de {} processado(s)",
converted_count,
results.len()
);
Ok(())
}
fn main() -> Result<()> {
println!("🔍 RSFE - Rust Source File Encoding Fixer\n");
let current_dir = std::env::current_dir()?;
let config_path = current_dir.join(CONFIG_FILE);
let config = if config_path.exists() {
println!("📋 Carregando configuração de: {:?}\n", config_path);
Config::load(&config_path)?
} else {
let default_encoding = prompt_default_encoding()?;
println!("\n✓ Usando encoding padrão: {}\n", default_encoding);
Config {
rules: Vec::new(),
default_encoding,
}
};
// Tenta obter arquivos staged do git
let staged_files = get_staged_files()?;
let files = if !staged_files.is_empty() {
println!("📦 Processando {} arquivo(s) staged para commit\n", staged_files.len());
staged_files
} else {
println!("📂 Processando todos os arquivos do projeto\n");
collect_files(¤t_dir, None)
};
if files.is_empty() {
println!("ℹ️ Nenhum arquivo para processar");
return Ok(());
}
process_files(&config, files)?;
println!("\n✅ Processamento concluído!");
Ok(())
}