claiss 1.1.6 → 1.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +24 -2
- data/lib/claiss/version.rb +1 -1
- data/lib/claiss.rb +231 -39
- metadata +1 -1
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA256:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: 3c3930d146c451e61732c1decad285dcedf966e9203d96c7b9566fda7fc0f927
|
4
|
+
data.tar.gz: 2194f5f1e491c3e332da0d8097f113636db9deee184b09d59b9771acf6a037bb
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: fd0230b487e14d9993b1963705bb3206091924d63cdff8f714fb1dfe9bc4d19db9390ade541d0916b99c77165dc7d6c6a7337b34ed4c30cf805abe9e952b495b
|
7
|
+
data.tar.gz: e5302f23687c15e282067bd6666810538874dae561b3db2446df01bc22a502de730e2bbc0f79c373fad04cc67c8779b2476e5fcf7b6ab9de57c937a39a68e5eb
|
data/README.md
CHANGED
@@ -59,6 +59,7 @@ $ claiss refactor <project_path> <json_file> [options]
|
|
59
59
|
**Options:**
|
60
60
|
- `--destination, -d`: Specify output directory (default: in-place)
|
61
61
|
- `--dry-run`: Preview changes without modifying files
|
62
|
+
- `--debug`: Show detailed debug messages during processing
|
62
63
|
|
63
64
|
**Example:**
|
64
65
|
```bash
|
@@ -201,14 +202,35 @@ $ claiss refactor <caminho_do_projeto> <arquivo_json> [opções]
|
|
201
202
|
**Opções:**
|
202
203
|
- `--destination, -d`: Especifica o diretório de saída (padrão: no local)
|
203
204
|
- `--dry-run`: Visualiza as alterações sem modificar os arquivos
|
205
|
+
- `--debug`: Mostra mensagens detalhadas de depuração durante o processamento
|
204
206
|
|
205
|
-
**
|
207
|
+
**Exemplos:**
|
206
208
|
```bash
|
207
|
-
|
209
|
+
# Modo normal
|
210
|
+
$ claiss refactor meu_projeto ~/.claiss/regras.json
|
211
|
+
|
212
|
+
# Especificando diretório de destino
|
213
|
+
$ claiss refactor meu_projeto ~/.claiss/regras.json --destination pasta_destino
|
214
|
+
|
215
|
+
# Modo debug (mostra mensagens detalhadas)
|
216
|
+
$ claiss refactor meu_projeto ~/.claiss/regras.json --debug
|
217
|
+
|
218
|
+
# Todas as opções juntas
|
219
|
+
$ claiss refactor meu_projeto ~/.claiss/regras.json --destination pasta_destino --debug
|
208
220
|
```
|
209
221
|
|
210
222
|
#### Formato do Dicionário JSON
|
211
223
|
|
224
|
+
O arquivo de regras pode estar em qualquer local, mas se estiver no diretório `~/.claiss/`, você pode usar apenas o nome do arquivo. Exemplo:
|
225
|
+
|
226
|
+
```bash
|
227
|
+
# Se o arquivo estiver em ~/.claiss/regras.json
|
228
|
+
$ claiss refactor meu_projeto regras.json
|
229
|
+
|
230
|
+
# Ou especifique o caminho completo
|
231
|
+
$ claiss refactor meu_projeto /caminho/completo/para/regras.json
|
232
|
+
```
|
233
|
+
|
212
234
|
Crie um arquivo JSON com pares chave-valor para as substituições:
|
213
235
|
|
214
236
|
```json
|
data/lib/claiss/version.rb
CHANGED
data/lib/claiss.rb
CHANGED
@@ -33,22 +33,44 @@ module CLAISS
|
|
33
33
|
option :destination, type: :string, desc: 'Destination path for refactored files'
|
34
34
|
|
35
35
|
example [
|
36
|
-
'path/to/project
|
37
|
-
'path/to/project
|
36
|
+
'path/to/project rules_file',
|
37
|
+
'path/to/project rules_file --destination path/to/output',
|
38
|
+
'path/to/project rules_file --debug',
|
39
|
+
'path/to/project rules_file --destination path/to/output --debug'
|
38
40
|
]
|
39
41
|
|
40
|
-
def call(path:, rules:, destination: nil, **)
|
42
|
+
def call(path:, rules:, destination: nil, debug: false, **)
|
43
|
+
@debug = debug
|
41
44
|
origin_path = File.expand_path(path)
|
42
45
|
destination_path = destination ? File.expand_path(destination) : nil
|
43
46
|
|
44
|
-
|
47
|
+
# Primeiro tenta carregar o arquivo como está (pode ser caminho completo)
|
48
|
+
json_file = rules.end_with?('.json') ? rules : "#{rules}.json"
|
49
|
+
|
50
|
+
debug_puts("\n[DEBUG] Iniciando refatoração")
|
51
|
+
debug_puts("[DEBUG] Origem: #{origin_path}")
|
52
|
+
debug_puts("[DEBUG] Destino: #{destination_path || 'Não especificado'}")
|
53
|
+
debug_puts("[DEBUG] Arquivo de regras: #{json_file}")
|
54
|
+
|
55
|
+
# Tenta carregar o dicionário
|
45
56
|
dict = load_dictionary(json_file)
|
46
|
-
|
57
|
+
|
58
|
+
if dict.empty?
|
59
|
+
puts "[ERRO] O dicionário de substituição está vazio. Nenhuma alteração será feita."
|
60
|
+
return
|
61
|
+
end
|
62
|
+
|
63
|
+
debug_puts("[DEBUG] Dicionário carregado com #{dict.size} entradas")
|
64
|
+
|
65
|
+
# Obtém a lista de arquivos para processar
|
47
66
|
files = get_files_to_process(origin_path)
|
67
|
+
debug_puts("[DEBUG] Encontrados #{files.size} arquivos para processar")
|
68
|
+
|
69
|
+
# Processa os arquivos
|
48
70
|
process_files_in_parallel(files, dict, origin_path, destination_path)
|
49
|
-
|
50
|
-
|
51
|
-
|
71
|
+
|
72
|
+
puts "\n[SUCESSO] Processamento concluído!"
|
73
|
+
puts "Arquivos processados: #{files.size}"
|
52
74
|
target_path = destination_path || origin_path
|
53
75
|
remove_empty_directories(target_path)
|
54
76
|
|
@@ -72,7 +94,20 @@ module CLAISS
|
|
72
94
|
binary_extensions.any? { |ext| file_name.downcase.end_with?(ext) }
|
73
95
|
end
|
74
96
|
|
97
|
+
def debug_puts(message)
|
98
|
+
puts message if @debug
|
99
|
+
end
|
100
|
+
|
75
101
|
def process_files_in_parallel(files, dict, origin_path, destination_path)
|
102
|
+
debug_puts("Diretório de trabalho atual: #{Dir.pwd}")
|
103
|
+
puts "\n=== Iniciando processamento de #{files.size} arquivos em paralelo ==="
|
104
|
+
puts "Dicionário de substituição: #{dict.inspect}"
|
105
|
+
puts "Diretório de origem: #{origin_path}"
|
106
|
+
puts "Diretório de destino: #{destination_path || 'Mesmo que origem'}"
|
107
|
+
|
108
|
+
# Log do diretório de trabalho atual
|
109
|
+
puts "Diretório de trabalho atual: #{Dir.pwd}"
|
110
|
+
|
76
111
|
progress_bar = ProgressBar.create(
|
77
112
|
total: files.size,
|
78
113
|
format: "%a %b\u{15E7}%i %p%% %t",
|
@@ -80,39 +115,100 @@ module CLAISS
|
|
80
115
|
remainder_mark: "\u{FF65}"
|
81
116
|
)
|
82
117
|
|
83
|
-
Parallel.each(files, in_threads: Parallel.processor_count) do |file_name|
|
84
|
-
|
118
|
+
Parallel.each(files, in_threads: [2, Parallel.processor_count].min) do |file_name|
|
119
|
+
next if File.directory?(file_name)
|
120
|
+
|
121
|
+
debug_puts("\n=== Processando arquivo: #{file_name} ===")
|
122
|
+
debug_puts("Arquivo existe? #{File.exist?(file_name) ? 'Sim' : 'NÃO'}")
|
123
|
+
|
124
|
+
begin
|
125
|
+
if is_binary_file?(file_name)
|
126
|
+
debug_puts("[BINÁRIO] Iniciando processamento de: #{file_name}")
|
127
|
+
process_binary_file_rename(file_name, dict, origin_path, destination_path)
|
128
|
+
debug_puts("[BINÁRIO] Finalizado: #{file_name}")
|
129
|
+
else
|
130
|
+
debug_puts("[TEXTO] Iniciando processamento de: #{file_name}")
|
131
|
+
refactor_file(file_name, dict, origin_path, destination_path)
|
132
|
+
debug_puts("[TEXTO] Finalizado: #{file_name}")
|
133
|
+
end
|
134
|
+
rescue StandardError => e
|
135
|
+
puts "[ERRO] Erro ao processar #{file_name}: #{e.message}"
|
136
|
+
puts e.backtrace.join("\n")
|
137
|
+
LOGGER.error("Error processing #{file_name}: #{e.message}")
|
138
|
+
LOGGER.error(e.backtrace.join("\n")) if LOGGER.debug?
|
139
|
+
end
|
140
|
+
|
85
141
|
progress_bar.increment
|
86
142
|
end
|
143
|
+
|
144
|
+
puts "\n=== Processamento concluído ==="
|
87
145
|
end
|
88
146
|
|
89
147
|
def load_dictionary(json_file)
|
148
|
+
debug_puts("\n[DEBUG] 1. Iniciando load_dictionary")
|
149
|
+
debug_puts("[DEBUG] 2. Diretório de trabalho atual: #{Dir.pwd}")
|
150
|
+
debug_puts("[DEBUG] 3. Arquivo JSON informado: #{json_file.inspect}")
|
151
|
+
|
90
152
|
if json_file
|
91
153
|
# Procura o arquivo no diretório atual e no ~/.claiss
|
92
154
|
possible_paths = [
|
93
155
|
json_file,
|
94
156
|
File.expand_path(json_file),
|
157
|
+
File.join(Dir.home, '.claiss', json_file),
|
95
158
|
File.expand_path("~/.claiss/#{json_file}")
|
96
|
-
]
|
159
|
+
].uniq
|
160
|
+
|
161
|
+
debug_puts("[DEBUG] 4. Procurando arquivo nos seguintes locais:")
|
162
|
+
possible_paths.each_with_index do |path, i|
|
163
|
+
exists = File.exist?(path) ? 'EXISTE' : 'não encontrado'
|
164
|
+
debug_puts(" #{i+1}. #{path} (#{exists})")
|
165
|
+
if exists == 'EXISTE'
|
166
|
+
debug_puts(" Permissões: #{File.stat(path).mode.to_s(8)}")
|
167
|
+
debug_puts(" Tamanho: #{File.size(path)} bytes")
|
168
|
+
end
|
169
|
+
end
|
97
170
|
|
98
171
|
found_file = possible_paths.find { |path| File.exist?(path) }
|
99
172
|
|
100
173
|
if found_file
|
174
|
+
debug_puts("[DEBUG] 5. Arquivo encontrado em: #{found_file}")
|
101
175
|
begin
|
102
|
-
|
103
|
-
|
176
|
+
debug_puts("[DEBUG] 6. Lendo conteúdo do arquivo...")
|
177
|
+
file_content = File.read(found_file)
|
178
|
+
debug_puts("[DEBUG] 7. Tamanho do conteúdo: #{file_content.length} bytes")
|
179
|
+
debug_puts("[DEBUG] 8. Conteúdo do arquivo (início):\n#{file_content[0..200].inspect}...")
|
180
|
+
|
181
|
+
dict = JSON.parse(file_content)
|
182
|
+
debug_puts("[DEBUG] 9. Dicionário carregado com sucesso!")
|
183
|
+
debug_puts("[DEBUG] 10. Número de entradas: #{dict.size}")
|
184
|
+
debug_puts("[DEBUG] 11. Primeiras 3 entradas: #{dict.first(3).to_h.inspect}") if dict.any?
|
185
|
+
|
104
186
|
return dict
|
105
187
|
rescue JSON::ParserError => e
|
106
|
-
puts "
|
188
|
+
puts "[ERRO] O arquivo JSON não está no formato correto. Erro: #{e.message}"
|
189
|
+
debug_puts("[ERRO] Linha do erro: #{e.backtrace.find { |l| l.include?('parse') }}")
|
190
|
+
rescue StandardError => e
|
191
|
+
puts "[ERRO] Erro ao ler o arquivo: #{e.class}: #{e.message}"
|
192
|
+
debug_puts("[ERRO] Backtrace: #{e.backtrace.join("\n")}")
|
107
193
|
end
|
108
194
|
else
|
109
|
-
puts '
|
195
|
+
puts '[ERRO] Não consegui encontrar o arquivo em nenhum dos locais:'
|
110
196
|
possible_paths.each { |path| puts " - #{path}" }
|
197
|
+
|
198
|
+
# Verifica se o diretório .claiss existe
|
199
|
+
claiss_dir = File.join(Dir.home, '.claiss')
|
200
|
+
if Dir.exist?(claiss_dir)
|
201
|
+
debug_puts("[DEBUG] Conteúdo do diretório #{claiss_dir}:")
|
202
|
+
Dir.entries(claiss_dir).each { |f| debug_puts(" - #{f}") }
|
203
|
+
else
|
204
|
+
debug_puts("[DEBUG] Diretório #{claiss_dir} não existe!")
|
205
|
+
end
|
111
206
|
end
|
112
207
|
|
113
|
-
puts 'Vamos usar o dicionário interativo em vez disso, tá
|
208
|
+
puts '[AVISO] Vamos usar o dicionário interativo em vez disso, tá bem?'
|
114
209
|
interactive_dictionary
|
115
210
|
else
|
211
|
+
debug_puts('[DEBUG] Nenhum arquivo JSON informado, usando dicionário interativo')
|
116
212
|
interactive_dictionary
|
117
213
|
end
|
118
214
|
end
|
@@ -199,34 +295,130 @@ module CLAISS
|
|
199
295
|
end
|
200
296
|
|
201
297
|
def process_binary_file_rename(file_name, dict, origin_path, destination_path)
|
202
|
-
|
203
|
-
|
204
|
-
|
205
|
-
|
206
|
-
|
207
|
-
|
208
|
-
|
209
|
-
|
210
|
-
|
211
|
-
|
212
|
-
|
213
|
-
|
214
|
-
|
215
|
-
|
216
|
-
|
217
|
-
|
218
|
-
|
219
|
-
|
220
|
-
|
298
|
+
debug_puts("[DEBUG] Iniciando process_binary_file_rename")
|
299
|
+
debug_puts("[DEBUG] Arquivo: #{file_name}")
|
300
|
+
debug_puts("[DEBUG] Origem: #{origin_path}")
|
301
|
+
debug_puts("[DEBUG] Destino: #{destination_path || 'Não especificado'}")
|
302
|
+
debug_puts("[DEBUG] Dicionário: #{dict.inspect}")
|
303
|
+
|
304
|
+
begin
|
305
|
+
relative_path = Pathname.new(file_name).relative_path_from(Pathname.new(origin_path)).to_s
|
306
|
+
|
307
|
+
debug_puts("[DEBUG] Caminho relativo: #{relative_path}")
|
308
|
+
|
309
|
+
new_relative_path = replace_in_path(relative_path, dict)
|
310
|
+
debug_puts("[DEBUG] Novo caminho relativo: #{new_relative_path}")
|
311
|
+
|
312
|
+
new_file_name = if destination_path
|
313
|
+
File.join(destination_path, new_relative_path)
|
314
|
+
else
|
315
|
+
File.join(origin_path, new_relative_path)
|
316
|
+
end
|
317
|
+
|
318
|
+
debug_puts("[DEBUG] Novo caminho completo: #{new_file_name}")
|
319
|
+
|
320
|
+
if new_file_name != file_name
|
321
|
+
new_dir = File.dirname(new_file_name)
|
322
|
+
|
323
|
+
debug_puts("[DEBUG] Criando diretório: #{new_dir}")
|
324
|
+
|
325
|
+
unless File.directory?(new_dir)
|
326
|
+
debug_puts("[DEBUG] Diretório não existe, criando: #{new_dir}")
|
327
|
+
FileUtils.mkdir_p(new_dir)
|
328
|
+
end
|
329
|
+
|
330
|
+
debug_puts("[DEBUG] Movendo arquivo de:\n #{file_name}\n para:\n #{new_file_name}")
|
331
|
+
|
332
|
+
FileUtils.mv(file_name, new_file_name, force: true)
|
333
|
+
|
334
|
+
unless destination_path
|
335
|
+
debug_puts("[DEBUG] Removendo arquivo original: #{file_name}")
|
336
|
+
File.delete(file_name) if File.exist?(file_name)
|
337
|
+
end
|
338
|
+
|
339
|
+
debug_puts("[DEBUG] Arquivo movido com sucesso!")
|
340
|
+
else
|
341
|
+
debug_puts("[DEBUG] Nenhuma alteração necessária para o arquivo")
|
342
|
+
end
|
343
|
+
|
344
|
+
true
|
345
|
+
rescue StandardError => e
|
346
|
+
puts "[ERRO] Erro ao processar arquivo binário #{file_name}: #{e.message}"
|
347
|
+
debug_puts("[ERRO] Backtrace: #{e.backtrace.join("\n")}")
|
348
|
+
false
|
349
|
+
ensure
|
350
|
+
debug_puts("[DEBUG] Finalizando process_binary_file_rename\n")
|
351
|
+
puts "[ERRO CRÍTICO] Erro ao processar #{file_name}: #{e.message}"
|
352
|
+
puts e.backtrace.join("\n")
|
353
|
+
LOGGER.error("Error renaming binary file #{file_name}: #{e.message}")
|
354
|
+
LOGGER.error(e.backtrace.join("\n")) if LOGGER.debug?
|
221
355
|
end
|
222
|
-
rescue StandardError => e
|
223
|
-
LOGGER.error("Error renaming binary file #{file_name}: #{e.message}")
|
224
356
|
end
|
225
357
|
|
226
358
|
def replace_in_path(path, dict)
|
227
|
-
|
228
|
-
|
359
|
+
debug_puts("[DEBUG] Iniciando replace_in_path")
|
360
|
+
debug_puts("[DEBUG] Caminho original: #{path}")
|
361
|
+
debug_puts("[DEBUG] Dicionário: #{dict.inspect}")
|
362
|
+
|
363
|
+
return path if dict.empty? || path.nil? || path.empty?
|
364
|
+
|
365
|
+
# Ordena as chaves por tamanho (maior primeiro) para evitar substituições parciais
|
366
|
+
sorted_dict = dict.sort_by { |k, _| -k.size }.to_h
|
367
|
+
debug_puts("[DEBUG] Dicionário ordenado: #{sorted_dict.inspect}")
|
368
|
+
|
369
|
+
new_path = path.dup
|
370
|
+
|
371
|
+
sorted_dict.each do |search, replace|
|
372
|
+
debug_puts("[DEBUG] Buscando: '#{search}'")
|
373
|
+
debug_puts("[DEBUG] Substituindo por: '#{replace}'")
|
374
|
+
debug_puts("[DEBUG] Caminho atual: #{new_path}")
|
375
|
+
|
376
|
+
# Verifica se o caminho contém o termo de busca
|
377
|
+
if new_path.include?(search)
|
378
|
+
# Separa diretório e nome do arquivo
|
379
|
+
dirname = File.dirname(new_path)
|
380
|
+
basename = File.basename(new_path)
|
381
|
+
debug_puts("[DEBUG] Diretório: #{dirname}")
|
382
|
+
debug_puts("[DEBUG] Nome do arquivo: #{basename}")
|
383
|
+
|
384
|
+
# Aplica a substituição apenas no nome do arquivo
|
385
|
+
new_basename = basename.gsub(search, replace)
|
386
|
+
debug_puts("[DEBUG] Novo nome do arquivo: #{new_basename}")
|
387
|
+
|
388
|
+
# Reconstrói o caminho
|
389
|
+
if dirname == '.'
|
390
|
+
new_path = new_basename
|
391
|
+
else
|
392
|
+
new_path = File.join(dirname, new_basename)
|
393
|
+
end
|
394
|
+
|
395
|
+
# Se o diretório também precisar ser substituído
|
396
|
+
dirname_parts = dirname.split(File::SEPARATOR)
|
397
|
+
new_dirname_parts = dirname_parts.map do |part|
|
398
|
+
if part.include?(search)
|
399
|
+
new_part = part.gsub(search, replace)
|
400
|
+
debug_puts("[DEBUG] Substituição no diretório: '#{part}' -> '#{new_part}'")
|
401
|
+
new_part
|
402
|
+
else
|
403
|
+
part
|
404
|
+
end
|
405
|
+
end
|
406
|
+
|
407
|
+
# Reconstrói o caminho completo com o diretório atualizado
|
408
|
+
new_path = File.join(*new_dirname_parts, File.basename(new_path))
|
409
|
+
|
410
|
+
debug_puts("[DEBUG] Caminho após substituição: #{new_path}")
|
411
|
+
end
|
412
|
+
end
|
413
|
+
|
414
|
+
if new_path != path
|
415
|
+
debug_puts("[DEBUG] Caminho alterado de:\n #{path}\n para:\n #{new_path}")
|
416
|
+
else
|
417
|
+
debug_puts("[DEBUG] Nenhuma substituição foi feita no caminho")
|
229
418
|
end
|
419
|
+
|
420
|
+
debug_puts("[DEBUG] Finalizando replace_in_path\n")
|
421
|
+
new_path
|
230
422
|
end
|
231
423
|
|
232
424
|
def remove_empty_directories(origin_path)
|