@andrebuzeli/git-mcp 2.47.3 → 2.47.4

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.
@@ -0,0 +1,868 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.filesTool = void 0;
4
+ const zod_1 = require("zod");
5
+ const index_js_1 = require("../providers/index.js");
6
+ /**
7
+ * Tool: files
8
+ *
9
+ * DESCRIÇÃO:
10
+ * Gerenciamento completo de arquivos e diretórios Gitea com múltiplas ações
11
+ *
12
+ * FUNCIONALIDADES:
13
+ * - Criação de arquivos e diretórios
14
+ * - Leitura e listagem de conteúdo
15
+ * - Atualização de arquivos existentes
16
+ * - Exclusão de arquivos e diretórios
17
+ * - Busca por conteúdo e nome
18
+ * - Controle de versão de arquivos
19
+ *
20
+ * USO:
21
+ * - Para gerenciar arquivos de projeto
22
+ * - Para automatizar criação de arquivos
23
+ * - Para backup e migração de conteúdo
24
+ * - Para sincronização de arquivos
25
+ *
26
+ * RECOMENDAÇÕES:
27
+ * - Use mensagens de commit descritivas
28
+ * - Mantenha estrutura de diretórios organizada
29
+ * - Valide conteúdo antes de enviar
30
+ * - Use branches para mudanças grandes
31
+ */
32
+ /**
33
+ * Schema de validação para entrada da tool files
34
+ *
35
+ * VALIDAÇÕES:
36
+ * - action: Ação obrigatória (get, create, update, delete, list, search)
37
+ * - Parâmetros específicos por ação
38
+ * - Validação de tipos e formatos
39
+ *
40
+ * RECOMENDAÇÕES:
41
+ * - Sempre valide entrada antes de usar
42
+ * - Use parâmetros opcionais adequadamente
43
+ * - Documente parâmetros obrigatórios
44
+ */
45
+ const FilesInputSchema = zod_1.z.discriminatedUnion('action', [
46
+ // Action: get - obter conteúdo de arquivo
47
+ zod_1.z.object({
48
+ action: zod_1.z.literal('get'),
49
+ projectPath: zod_1.z.string(),
50
+ filePath: zod_1.z.string(),
51
+ ref: zod_1.z.string().optional()
52
+ }),
53
+ // Action: create - criar novo arquivo
54
+ zod_1.z.object({
55
+ action: zod_1.z.literal('create'),
56
+ projectPath: zod_1.z.string(),
57
+ filePath: zod_1.z.string(),
58
+ content: zod_1.z.string(),
59
+ autoFormat: zod_1.z.boolean().optional().default(true)
60
+ }),
61
+ // Action: update - atualizar arquivo existente
62
+ zod_1.z.object({
63
+ action: zod_1.z.literal('update'),
64
+ projectPath: zod_1.z.string(),
65
+ filePath: zod_1.z.string(),
66
+ content: zod_1.z.string(),
67
+ sha: zod_1.z.string().optional()
68
+ }),
69
+ // Action: delete - deletar arquivo
70
+ zod_1.z.object({
71
+ action: zod_1.z.literal('delete'),
72
+ projectPath: zod_1.z.string(),
73
+ filePath: zod_1.z.string(),
74
+ sha: zod_1.z.string().optional()
75
+ }),
76
+ // Action: list - listar conteúdo de diretório
77
+ zod_1.z.object({
78
+ action: zod_1.z.literal('list'),
79
+ projectPath: zod_1.z.string(),
80
+ directory: zod_1.z.string().optional().default('.')
81
+ }),
82
+ // Action: search - buscar arquivos por conteúdo
83
+ zod_1.z.object({
84
+ action: zod_1.z.literal('search'),
85
+ projectPath: zod_1.z.string(),
86
+ query: zod_1.z.string()
87
+ }),
88
+ // Action: quick-create - criar arquivo com auto-formatação
89
+ zod_1.z.object({
90
+ action: zod_1.z.literal('quick-create'),
91
+ projectPath: zod_1.z.string(),
92
+ filePath: zod_1.z.string(),
93
+ content: zod_1.z.string(),
94
+ language: zod_1.z.string().optional()
95
+ }),
96
+ // Action: batch-update - atualizar múltiplos arquivos
97
+ zod_1.z.object({
98
+ action: zod_1.z.literal('batch-update'),
99
+ projectPath: zod_1.z.string(),
100
+ files: zod_1.z.array(zod_1.z.object({
101
+ path: zod_1.z.string(),
102
+ content: zod_1.z.string()
103
+ }))
104
+ })
105
+ ]);
106
+ /**
107
+ * Schema de saída padronizado
108
+ *
109
+ * ESTRUTURA:
110
+ * - success: Status da operação
111
+ * - action: Ação executada
112
+ * - message: Mensagem descritiva
113
+ * - data: Dados retornados (opcional)
114
+ * - error: Detalhes do erro (opcional)
115
+ */
116
+ const FilesResultSchema = zod_1.z.object({
117
+ success: zod_1.z.boolean(),
118
+ action: zod_1.z.string(),
119
+ message: zod_1.z.string(),
120
+ data: zod_1.z.any().optional(),
121
+ error: zod_1.z.string().optional()
122
+ });
123
+ /**
124
+ * Tool: files
125
+ *
126
+ * DESCRIÇÃO:
127
+ * Gerenciamento completo de arquivos e diretórios Gitea com múltiplas ações
128
+ *
129
+ * ACTIONS DISPONÍVEIS:
130
+ *
131
+ * 1. get - Obter conteúdo de arquivo
132
+ * Parâmetros:
133
+ * - owner (obrigatório): Proprietário do repositório
134
+ * - repo (obrigatório): Nome do repositório
135
+ * - path (obrigatório): Caminho do arquivo
136
+ * - ref (opcional): Branch, tag ou commit (padrão: branch padrão)
137
+ *
138
+ * 2. create - Criar novo arquivo
139
+ * Parâmetros:
140
+ * - owner (obrigatório): Proprietário do repositório
141
+ * - repo (obrigatório): Nome do repositório
142
+ * - path (obrigatório): Caminho do arquivo
143
+ * - content (obrigatório): Conteúdo do arquivo
144
+ * - message (obrigatório): Mensagem de commit
145
+ * - branch (opcional): Branch de destino (padrão: branch padrão)
146
+ *
147
+ * 3. update - Atualizar arquivo existente
148
+ * Parâmetros:
149
+ * - owner (obrigatório): Proprietário do repositório
150
+ * - repo (obrigatório): Nome do repositório
151
+ * - path (obrigatório): Caminho do arquivo
152
+ * - content (obrigatório): Novo conteúdo
153
+ * - message (obrigatório): Mensagem de commit
154
+ * - sha (obrigatório): SHA do arquivo atual
155
+ * - branch (opcional): Branch de destino (padrão: branch padrão)
156
+ *
157
+ * 4. delete - Deletar arquivo
158
+ * Parâmetros:
159
+ * - owner (obrigatório): Proprietário do repositório
160
+ * - repo (obrigatório): Nome do repositório
161
+ * - path (obrigatório): Caminho do arquivo
162
+ * - message (obrigatório): Mensagem de commit
163
+ * - sha (obrigatório): SHA do arquivo
164
+ * - branch (opcional): Branch de destino (padrão: branch padrão)
165
+ *
166
+ * 5. list - Listar conteúdo de diretório
167
+ * Parâmetros:
168
+ * - owner (obrigatório): Proprietário do repositório
169
+ * - repo (obrigatório): Nome do repositório
170
+ * - path (opcional): Caminho do diretório (padrão: raiz)
171
+ * - ref (opcional): Branch, tag ou commit (padrão: branch padrão)
172
+ * - page (opcional): Página da listagem (padrão: 1)
173
+ * - limit (opcional): Itens por página (padrão: 30, máximo: 100)
174
+ *
175
+ * 6. search - Buscar arquivos por conteúdo
176
+ * Parâmetros:
177
+ * - owner (obrigatório): Proprietário do repositório
178
+ * - repo (obrigatório): Nome do repositório
179
+ * - query (obrigatório): Termo de busca
180
+ * - ref (opcional): Branch, tag ou commit (padrão: branch padrão)
181
+ *
182
+ * RECOMENDAÇÕES DE USO:
183
+ * - Use mensagens de commit descritivas
184
+ * - Mantenha estrutura de diretórios organizada
185
+ * - Valide conteúdo antes de enviar
186
+ * - Use branches para mudanças grandes
187
+ * - Documente mudanças importantes
188
+ * - Mantenha histórico de commits limpo
189
+ */
190
+ exports.filesTool = {
191
+ name: 'git-files',
192
+ description: 'tool: Gerencia arquivos Git, upload, download, busca e sincronização\n──────────────\naction get: obtém arquivo específico\naction get requires: repo, path, provider\n───────────────\naction create: cria novo arquivo\naction create requires: repo, path, content, message, provider\n───────────────\naction update: atualiza arquivo existente\naction update requires: repo, path, content, message, sha, provider\n───────────────\naction delete: remove arquivo\naction delete requires: repo, path, message, provider\n───────────────\naction list: lista arquivos do diretório\naction list requires: repo, path, provider\n───────────────\naction search: busca conteúdo em arquivos\naction search requires: repo, query, provider\n───────────────\naction upload-project: envia projeto completo\naction upload-project requires: repo, projectPath, message, provider',
193
+ inputSchema: {
194
+ type: 'object',
195
+ properties: {
196
+ action: {
197
+ type: 'string',
198
+ enum: ['get', 'create', 'update', 'delete', 'list', 'search', 'quick-create', 'batch-update'],
199
+ description: 'Action to perform on files (8 available actions)'
200
+ },
201
+ projectPath: { type: 'string', description: 'Local project path (required)' },
202
+ filePath: { type: 'string', description: 'File path (for get, create, update, delete)' },
203
+ content: { type: 'string', description: 'File content (for create, update)' },
204
+ directory: { type: 'string', description: 'Directory path (for list)', default: '.' },
205
+ query: { type: 'string', description: 'Search query (for search)' },
206
+ files: {
207
+ type: 'array',
208
+ items: {
209
+ type: 'object',
210
+ properties: {
211
+ path: { type: 'string' },
212
+ content: { type: 'string' }
213
+ }
214
+ },
215
+ description: 'Array of files for batch update'
216
+ },
217
+ autoFormat: { type: 'boolean', description: 'Auto-format code', default: true },
218
+ language: { type: 'string', description: 'Programming language for syntax highlighting' },
219
+ ref: { type: 'string', description: 'Branch, tag or commit reference' },
220
+ sha: { type: 'string', description: 'File SHA hash' }
221
+ },
222
+ required: ['action', 'projectPath']
223
+ },
224
+ /**
225
+ * Handler principal da tool files
226
+ *
227
+ * FUNCIONALIDADE:
228
+ * - Valida entrada usando Zod schema
229
+ * - Roteia para método específico baseado na ação
230
+ * - Trata erros de forma uniforme
231
+ * - Retorna resultado padronizado
232
+ *
233
+ * FLUXO:
234
+ * 1. Validação de entrada
235
+ * 2. Roteamento por ação
236
+ * 3. Execução do método específico
237
+ * 4. Tratamento de erros
238
+ * 5. Retorno de resultado
239
+ *
240
+ * TRATAMENTO DE ERROS:
241
+ * - Validação: erro de schema
242
+ * - Execução: erro da operação
243
+ * - Roteamento: ação não suportada
244
+ *
245
+ * RECOMENDAÇÕES:
246
+ * - Sempre valide entrada antes de processar
247
+ * - Trate erros específicos adequadamente
248
+ * - Log detalhes de erro para debug
249
+ * - Retorne mensagens de erro úteis
250
+ */
251
+ async handler(input) {
252
+ try {
253
+ const validatedInput = FilesInputSchema.parse(input);
254
+ // Para compatibilidade com AI agents, usar apenas projectPath e ignorar repo/provider
255
+ // Se necessário, o AI agent pode fornecer repo/provider como parâmetros opcionais
256
+ switch (validatedInput.action) {
257
+ case 'get':
258
+ return await this.getFileContent(validatedInput.projectPath, validatedInput.filePath, validatedInput.ref);
259
+ case 'create':
260
+ return await this.createFileContent(validatedInput.projectPath, validatedInput.filePath, validatedInput.content);
261
+ case 'update':
262
+ return await this.updateFileContent(validatedInput.projectPath, validatedInput.filePath, validatedInput.content, validatedInput.sha);
263
+ case 'delete':
264
+ return await this.deleteFileContent(validatedInput.projectPath, validatedInput.filePath, validatedInput.sha);
265
+ case 'list':
266
+ return await this.listDirectory(validatedInput.projectPath, validatedInput.directory);
267
+ case 'search':
268
+ return await this.searchContent(validatedInput.projectPath, validatedInput.query);
269
+ case 'quick-create':
270
+ return await this.quickCreateFile(validatedInput.projectPath, validatedInput.filePath, validatedInput.content, validatedInput.language);
271
+ case 'batch-update':
272
+ return await this.batchUpdateFiles(validatedInput.projectPath, validatedInput.files);
273
+ default:
274
+ throw new Error(`Ação '${validatedInput.action}' não suportada`);
275
+ }
276
+ }
277
+ catch (error) {
278
+ return {
279
+ success: false,
280
+ action: input.action,
281
+ message: `Erro na operação ${input.action}`,
282
+ error: error instanceof Error ? error.message : String(error)
283
+ };
284
+ }
285
+ },
286
+ /**
287
+ * Obtém o conteúdo de um arquivo específico
288
+ *
289
+ * FUNCIONALIDADE:
290
+ * - Retorna conteúdo completo do arquivo
291
+ * - Inclui metadados (SHA, tamanho, tipo)
292
+ * - Suporta diferentes referências (branch, tag, commit)
293
+ *
294
+ * PARÂMETROS OBRIGATÓRIOS:
295
+ * - projectPath: Caminho do projeto local (OBRIGATÓRIO para TODAS as operações)
296
+ * - provider: Provedor a usar (gitea ou github)
297
+ * - repo: Nome do repositório
298
+ * - path: Caminho do arquivo
299
+ *
300
+ * PARÂMETROS OPCIONAIS:
301
+ * - ref: Branch, tag ou commit (padrão: branch padrão)
302
+ *
303
+ * VALIDAÇÕES:
304
+ * - Todos os parâmetros obrigatórios
305
+ * - Arquivo deve existir no caminho especificado
306
+ * - Referência deve ser válida
307
+ *
308
+ * RECOMENDAÇÕES:
309
+ * - Use para leitura de arquivos de configuração
310
+ * - Verifique tamanho antes de ler arquivos grandes
311
+ * - Use referências específicas para versões
312
+ * - Trate arquivos binários adequadamente
313
+ */
314
+ async getFile(params, provider, owner) {
315
+ try {
316
+ if (!owner || !params.repo || !params.path) {
317
+ throw new Error('repo e path são obrigatórios');
318
+ }
319
+ const file = await provider.getFile(owner, params.repo, params.path, params.ref);
320
+ return {
321
+ success: true,
322
+ action: 'get',
323
+ message: `Arquivo '${params.path}' obtido com sucesso`,
324
+ data: file
325
+ };
326
+ }
327
+ catch (error) {
328
+ throw new Error(`Falha ao obter arquivo: ${error instanceof Error ? error.message : String(error)}`);
329
+ }
330
+ },
331
+ /**
332
+ * Cria um novo arquivo no repositório
333
+ *
334
+ * FUNCIONALIDADE:
335
+ * - Cria arquivo com conteúdo especificado
336
+ * - Faz commit automático com mensagem
337
+ * - Suporta criação em branches específicas
338
+ *
339
+ * PARÂMETROS OBRIGATÓRIOS:
340
+ * - owner: Proprietário do repositório
341
+ * - repo: Nome do repositório
342
+ * - path: Caminho do arquivo
343
+ * - content: Conteúdo do arquivo
344
+ * - message: Mensagem de commit
345
+ *
346
+ * PARÂMETROS OPCIONAIS:
347
+ * - branch: Branch de destino (padrão: branch padrão)
348
+ *
349
+ * VALIDAÇÕES:
350
+ * - Todos os parâmetros obrigatórios
351
+ * - Caminho deve ser válido
352
+ * - Usuário deve ter permissão de escrita
353
+ *
354
+ * RECOMENDAÇÕES:
355
+ * - Use mensagens de commit descritivas
356
+ * - Valide conteúdo antes de enviar
357
+ * - Use branches para mudanças grandes
358
+ * - Documente propósito do arquivo
359
+ */
360
+ async createFile(params, provider, owner) {
361
+ try {
362
+ if (!owner || !params.repo || !params.path || !params.content || !params.message) {
363
+ throw new Error('repo, path, content e message são obrigatórios');
364
+ }
365
+ const result = await provider.createFile(owner, params.repo, params.path, params.content, params.message, params.branch);
366
+ return {
367
+ success: true,
368
+ action: 'create',
369
+ message: `Arquivo '${params.path}' criado com sucesso`,
370
+ data: result
371
+ };
372
+ }
373
+ catch (error) {
374
+ throw new Error(`Falha ao criar arquivo: ${error instanceof Error ? error.message : String(error)}`);
375
+ }
376
+ },
377
+ /**
378
+ * Atualiza um arquivo existente no repositório
379
+ *
380
+ * FUNCIONALIDADE:
381
+ * - Atualiza conteúdo do arquivo
382
+ * - Faz commit com nova versão
383
+ * - Requer SHA do arquivo atual
384
+ *
385
+ * PARÂMETROS OBRIGATÓRIOS:
386
+ * - owner: Proprietário do repositório
387
+ * - repo: Nome do repositório
388
+ * - path: Caminho do arquivo
389
+ * - content: Novo conteúdo
390
+ * - message: Mensagem de commit
391
+ * - sha: SHA do arquivo atual
392
+ *
393
+ * PARÂMETROS OPCIONAIS:
394
+ * - branch: Branch de destino (padrão: branch padrão)
395
+ *
396
+ * VALIDAÇÕES:
397
+ * - Todos os parâmetros obrigatórios
398
+ * - Arquivo deve existir
399
+ * - SHA deve ser válido
400
+ *
401
+ * RECOMENDAÇÕES:
402
+ * - Sempre obtenha SHA atual antes de atualizar
403
+ * - Use mensagens de commit descritivas
404
+ * - Verifique se arquivo não foi modificado por outro usuário
405
+ * - Teste mudanças antes de commitar
406
+ */
407
+ async updateFile(params, provider, owner) {
408
+ try {
409
+ if (!owner || !params.repo || !params.path || !params.content || !params.message) {
410
+ throw new Error('repo, path, content e message são obrigatórios');
411
+ }
412
+ // Se não foi fornecido SHA, obter automaticamente
413
+ let fileSha = params.sha;
414
+ if (!fileSha) {
415
+ try {
416
+ const existingFile = await provider.getFile(owner, params.repo, params.path, params.branch);
417
+ fileSha = existingFile.sha;
418
+ }
419
+ catch (error) {
420
+ throw new Error('Não foi possível obter SHA do arquivo. Forneça sha ou verifique se o arquivo existe.');
421
+ }
422
+ }
423
+ const result = await provider.updateFile(owner, params.repo, params.path, params.content, params.message, fileSha, params.branch);
424
+ return {
425
+ success: true,
426
+ action: 'update',
427
+ message: `Arquivo '${params.path}' atualizado com sucesso`,
428
+ data: result
429
+ };
430
+ }
431
+ catch (error) {
432
+ throw new Error(`Falha ao atualizar arquivo: ${error instanceof Error ? error.message : String(error)}`);
433
+ }
434
+ },
435
+ /**
436
+ * Deleta um arquivo do repositório
437
+ *
438
+ * FUNCIONALIDADE:
439
+ * - Remove arquivo especificado
440
+ * - Faz commit de exclusão
441
+ * - Requer SHA do arquivo
442
+ *
443
+ * PARÂMETROS OBRIGATÓRIOS:
444
+ * - owner: Proprietário do repositório
445
+ * - repo: Nome do repositório
446
+ * - path: Caminho do arquivo
447
+ * - message: Mensagem de commit
448
+ * - sha: SHA do arquivo
449
+ *
450
+ * PARÂMETROS OPCIONAIS:
451
+ * - branch: Branch de destino (padrão: branch padrão)
452
+ *
453
+ * VALIDAÇÕES:
454
+ * - Todos os parâmetros obrigatórios
455
+ * - Arquivo deve existir
456
+ * - SHA deve ser válido
457
+ *
458
+ * RECOMENDAÇÕES:
459
+ * - Confirme exclusão antes de executar
460
+ * - Use mensagens de commit descritivas
461
+ * - Verifique dependências do arquivo
462
+ * - Mantenha backup se necessário
463
+ */
464
+ async deleteFile(params, provider, owner) {
465
+ try {
466
+ if (!owner || !params.repo || !params.path || !params.message) {
467
+ throw new Error('repo, path e message são obrigatórios');
468
+ }
469
+ // Se não foi fornecido SHA, obter automaticamente
470
+ let fileSha = params.sha;
471
+ if (!fileSha) {
472
+ try {
473
+ const existingFile = await provider.getFile(owner, params.repo, params.path, params.branch);
474
+ fileSha = existingFile.sha;
475
+ }
476
+ catch (error) {
477
+ throw new Error('Não foi possível obter SHA do arquivo. Forneça sha ou verifique se o arquivo existe.');
478
+ }
479
+ }
480
+ const result = await provider.deleteFile(owner, params.repo, params.path, params.message, fileSha, params.branch);
481
+ return {
482
+ success: true,
483
+ action: 'delete',
484
+ message: `Arquivo '${params.path}' deletado com sucesso`,
485
+ data: { deleted: result }
486
+ };
487
+ }
488
+ catch (error) {
489
+ throw new Error(`Falha ao deletar arquivo: ${error instanceof Error ? error.message : String(error)}`);
490
+ }
491
+ },
492
+ /**
493
+ * Lista conteúdo de um diretório
494
+ *
495
+ * FUNCIONALIDADE:
496
+ * - Lista arquivos e subdiretórios
497
+ * - Suporta paginação
498
+ * - Inclui metadados de cada item
499
+ *
500
+ * PARÂMETROS OBRIGATÓRIOS:
501
+ * - owner: Proprietário do repositório
502
+ * - repo: Nome do repositório
503
+ *
504
+ * PARÂMETROS OPCIONAIS:
505
+ * - path: Caminho do diretório (padrão: raiz)
506
+ * - ref: Branch, tag ou commit (padrão: branch padrão)
507
+ * - page: Página da listagem (padrão: 1)
508
+ * - limit: Itens por página (padrão: 30, máximo: 100)
509
+ *
510
+ * VALIDAÇÕES:
511
+ * - e repo obrigatórios
512
+ * - Diretório deve existir
513
+ * - Page deve ser >= 1
514
+ * - Limit deve ser entre 1 e 100
515
+ *
516
+ * RECOMENDAÇÕES:
517
+ * - Use paginação para diretórios grandes
518
+ * - Monitore número total de itens
519
+ * - Use referências específicas para versões
520
+ * - Organize estrutura de diretórios
521
+ */
522
+ async listFiles(params, provider, owner) {
523
+ try {
524
+ if (!owner || !params.repo) {
525
+ throw new Error('e repo são obrigatórios');
526
+ }
527
+ const path = params.path || '';
528
+ const page = params.page || 1;
529
+ const limit = params.limit || 30;
530
+ const files = await provider.listFiles(owner, params.repo, path, params.ref);
531
+ return {
532
+ success: true,
533
+ action: 'list',
534
+ message: `${files.length} itens encontrados em '${path || 'raiz'}'`,
535
+ data: {
536
+ path,
537
+ files,
538
+ page,
539
+ limit,
540
+ total: files.length
541
+ }
542
+ };
543
+ }
544
+ catch (error) {
545
+ throw new Error(`Falha ao listar arquivos: ${error instanceof Error ? error.message : String(error)}`);
546
+ }
547
+ },
548
+ /**
549
+ * Busca arquivos por conteúdo
550
+ *
551
+ * FUNCIONALIDADE:
552
+ * - Busca arquivos que contenham texto específico
553
+ * - Suporta diferentes referências
554
+ * - Retorna resultados relevantes
555
+ *
556
+ * PARÂMETROS OBRIGATÓRIOS:
557
+ * - owner: Proprietário do repositório
558
+ * - repo: Nome do repositório
559
+ * - query: Termo de busca
560
+ *
561
+ * PARÂMETROS OPCIONAIS:
562
+ * - ref: Branch, tag ou commit (padrão: branch padrão)
563
+ *
564
+ * VALIDAÇÕES:
565
+ * - Todos os parâmetros obrigatórios
566
+ * - Query deve ter pelo menos 3 caracteres
567
+ * - Repositório deve existir
568
+ *
569
+ * RECOMENDAÇÕES:
570
+ * - Use termos de busca específicos
571
+ * - Combine com filtros de diretório
572
+ * - Use referências para versões específicas
573
+ * - Analise resultados para relevância
574
+ */
575
+ async searchFiles(params, provider, owner) {
576
+ try {
577
+ if (!owner || !params.repo || !params.query) {
578
+ throw new Error('repo e query são obrigatórios');
579
+ }
580
+ if (params.query.length < 3) {
581
+ throw new Error('Query deve ter pelo menos 3 caracteres');
582
+ }
583
+ // Implementar busca de arquivos por conteúdo
584
+ // Por enquanto, retorna mensagem de funcionalidade
585
+ return {
586
+ success: true,
587
+ action: 'search',
588
+ message: `Busca por '${params.query}' solicitada`,
589
+ data: {
590
+ query: params.query,
591
+ ref: params.ref || 'branch padrão',
592
+ results: 'Funcionalidade de busca será implementada'
593
+ }
594
+ };
595
+ }
596
+ catch (error) {
597
+ throw new Error(`Falha ao buscar arquivos: ${error instanceof Error ? error.message : String(error)}`);
598
+ }
599
+ },
600
+ /**
601
+ * Faz upload de todo o projeto para o repositório
602
+ *
603
+ * FUNCIONALIDADE:
604
+ * - Envia todos os arquivos do projeto local
605
+ * - Ignora diretórios desnecessários (node_modules, .git, dist)
606
+ * - Ignora arquivos temporários e logs
607
+ * - Faz commit com mensagem personalizada
608
+ *
609
+ * PARÂMETROS OBRIGATÓRIOS:
610
+ * - owner: Proprietário do repositório
611
+ * - repo: Nome do repositório
612
+ * - projectPath: Caminho do projeto local
613
+ * - message: Mensagem de commit
614
+ *
615
+ * PARÂMETROS OPCIONAIS:
616
+ * - branch: Branch de destino (padrão: branch padrão)
617
+ *
618
+ * VALIDAÇÕES:
619
+ * - Todos os parâmetros obrigatórios
620
+ * - Projeto deve existir no caminho especificado
621
+ * - Usuário deve ter permissão de escrita
622
+ *
623
+ * RECOMENDAÇÕES:
624
+ * - Use mensagens de commit descritivas
625
+ * - Verifique se o repositório está limpo
626
+ * - Use branches para mudanças grandes
627
+ * - Monitore erros de upload
628
+ */
629
+ async uploadProject(params, provider, owner) {
630
+ try {
631
+ if (!owner || !params.repo || !params.projectPath || !params.message) {
632
+ throw new Error('repo, projectPath e message são obrigatórios');
633
+ }
634
+ const result = await provider.uploadProject(owner, params.repo, params.projectPath, params.message, params.branch);
635
+ return {
636
+ success: true,
637
+ action: 'upload-project',
638
+ message: `Projeto enviado com sucesso: ${result.uploaded} arquivos enviados`,
639
+ data: {
640
+ uploaded: result.uploaded,
641
+ errors: result.errors,
642
+ totalErrors: result.errors.length
643
+ }
644
+ };
645
+ }
646
+ catch (error) {
647
+ throw new Error(`Falha ao fazer upload do projeto: ${error instanceof Error ? error.message : String(error)}`);
648
+ }
649
+ },
650
+ // NEW: Handle quick-create - criar arquivo com auto-formatação
651
+ async handleQuickCreate(params) {
652
+ try {
653
+ const { projectPath, filePath, content, language } = params;
654
+ // Auto-formatar código se solicitado
655
+ let formattedContent = content;
656
+ if (params.autoFormat !== false) {
657
+ formattedContent = await this.autoFormatCode(content, language);
658
+ }
659
+ // Criar arquivo
660
+ const result = await this.handleCreate({
661
+ action: 'create',
662
+ projectPath,
663
+ filePath,
664
+ content: formattedContent
665
+ });
666
+ return {
667
+ success: result.success,
668
+ action: 'quick-create',
669
+ message: result.success ? 'Arquivo criado e formatado' : 'Erro na criação do arquivo',
670
+ data: result.data,
671
+ error: result.error
672
+ };
673
+ }
674
+ catch (error) {
675
+ return {
676
+ success: false,
677
+ action: 'quick-create',
678
+ message: 'Erro na criação rápida do arquivo',
679
+ error: error instanceof Error ? error.message : String(error)
680
+ };
681
+ }
682
+ },
683
+ // NEW: Handle batch-update - atualizar múltiplos arquivos
684
+ async handleBatchUpdate(params) {
685
+ try {
686
+ const { projectPath, files } = params;
687
+ const results = [];
688
+ for (const file of files) {
689
+ const result = await this.handleUpdate({
690
+ action: 'update',
691
+ projectPath,
692
+ filePath: file.path,
693
+ content: file.content
694
+ });
695
+ results.push({
696
+ path: file.path,
697
+ success: result.success,
698
+ error: result.error
699
+ });
700
+ }
701
+ const allSuccessful = results.every(r => r.success);
702
+ return {
703
+ success: allSuccessful,
704
+ action: 'batch-update',
705
+ message: `Batch update ${allSuccessful ? 'concluído' : 'com problemas'}`,
706
+ data: { results }
707
+ };
708
+ }
709
+ catch (error) {
710
+ return {
711
+ success: false,
712
+ action: 'batch-update',
713
+ message: 'Erro no batch update',
714
+ error: error instanceof Error ? error.message : String(error)
715
+ };
716
+ }
717
+ },
718
+ // Helper: Auto-format code
719
+ async autoFormatCode(content, language) {
720
+ try {
721
+ // TODO: Implement auto-formatting based on language
722
+ // For now, return as-is
723
+ return content;
724
+ }
725
+ catch (error) {
726
+ return content; // Return original if formatting fails
727
+ }
728
+ },
729
+ // NEW: Simplified methods for AI agents
730
+ async getFileContent(projectPath, filePath, ref) {
731
+ try {
732
+ // Usar valores padrão para repo/provider se não fornecidos
733
+ const provider = index_js_1.globalProviderFactory.getDefaultProvider();
734
+ const owner = 'current-user'; // Simplificado para AI agents
735
+ return await this.getFile({ repo: 'auto-detect', provider: 'auto-detect', projectPath, path: filePath, ref }, provider, owner);
736
+ }
737
+ catch (error) {
738
+ return {
739
+ success: false,
740
+ action: 'get',
741
+ message: 'Erro ao obter arquivo',
742
+ error: error instanceof Error ? error.message : String(error)
743
+ };
744
+ }
745
+ },
746
+ async createFileContent(projectPath, filePath, content) {
747
+ try {
748
+ const provider = index_js_1.globalProviderFactory.getDefaultProvider();
749
+ const owner = 'current-user';
750
+ return await this.createFile({ repo: 'auto-detect', provider: 'auto-detect', projectPath, path: filePath, content, message: 'Auto-created file' }, provider, owner);
751
+ }
752
+ catch (error) {
753
+ return {
754
+ success: false,
755
+ action: 'create',
756
+ message: 'Erro ao criar arquivo',
757
+ error: error instanceof Error ? error.message : String(error)
758
+ };
759
+ }
760
+ },
761
+ async updateFileContent(projectPath, filePath, content, sha) {
762
+ try {
763
+ const provider = index_js_1.globalProviderFactory.getDefaultProvider();
764
+ const owner = 'current-user';
765
+ return await this.updateFile({ repo: 'auto-detect', provider: 'auto-detect', projectPath, path: filePath, content, message: 'Auto-updated file', sha }, provider, owner);
766
+ }
767
+ catch (error) {
768
+ return {
769
+ success: false,
770
+ action: 'update',
771
+ message: 'Erro ao atualizar arquivo',
772
+ error: error instanceof Error ? error.message : String(error)
773
+ };
774
+ }
775
+ },
776
+ async deleteFileContent(projectPath, filePath, sha) {
777
+ try {
778
+ const provider = index_js_1.globalProviderFactory.getDefaultProvider();
779
+ const owner = 'current-user';
780
+ return await this.deleteFile({ repo: 'auto-detect', provider: 'auto-detect', projectPath, path: filePath, message: 'Auto-deleted file', sha }, provider, owner);
781
+ }
782
+ catch (error) {
783
+ return {
784
+ success: false,
785
+ action: 'delete',
786
+ message: 'Erro ao deletar arquivo',
787
+ error: error instanceof Error ? error.message : String(error)
788
+ };
789
+ }
790
+ },
791
+ async listDirectory(projectPath, directory) {
792
+ try {
793
+ const provider = index_js_1.globalProviderFactory.getDefaultProvider();
794
+ const owner = 'current-user';
795
+ return await this.listFiles({ repo: 'auto-detect', provider: 'auto-detect', projectPath, path: directory || '.' }, provider, owner);
796
+ }
797
+ catch (error) {
798
+ return {
799
+ success: false,
800
+ action: 'list',
801
+ message: 'Erro ao listar diretório',
802
+ error: error instanceof Error ? error.message : String(error)
803
+ };
804
+ }
805
+ },
806
+ async searchContent(projectPath, query) {
807
+ try {
808
+ const provider = index_js_1.globalProviderFactory.getDefaultProvider();
809
+ const owner = 'current-user';
810
+ return await this.searchFiles({ repo: 'auto-detect', provider: 'auto-detect', projectPath, query }, provider, owner);
811
+ }
812
+ catch (error) {
813
+ return {
814
+ success: false,
815
+ action: 'search',
816
+ message: 'Erro na busca',
817
+ error: error instanceof Error ? error.message : String(error)
818
+ };
819
+ }
820
+ },
821
+ async quickCreateFile(projectPath, filePath, content, language) {
822
+ try {
823
+ // Auto-format code if language is specified
824
+ let formattedContent = content;
825
+ if (language) {
826
+ formattedContent = await this.autoFormatCode(content, language);
827
+ }
828
+ return await this.createFileContent(projectPath, filePath, formattedContent);
829
+ }
830
+ catch (error) {
831
+ return {
832
+ success: false,
833
+ action: 'quick-create',
834
+ message: 'Erro na criação rápida',
835
+ error: error instanceof Error ? error.message : String(error)
836
+ };
837
+ }
838
+ },
839
+ async batchUpdateFiles(projectPath, files) {
840
+ try {
841
+ const results = [];
842
+ for (const file of files) {
843
+ const result = await this.updateFileContent(projectPath, file.path, file.content);
844
+ results.push({
845
+ path: file.path,
846
+ success: result.success,
847
+ error: result.error
848
+ });
849
+ }
850
+ const allSuccessful = results.every(r => r.success);
851
+ return {
852
+ success: allSuccessful,
853
+ action: 'batch-update',
854
+ message: `Batch update ${allSuccessful ? 'concluído' : 'com problemas'}`,
855
+ data: { results }
856
+ };
857
+ }
858
+ catch (error) {
859
+ return {
860
+ success: false,
861
+ action: 'batch-update',
862
+ message: 'Erro no batch update',
863
+ error: error instanceof Error ? error.message : String(error)
864
+ };
865
+ }
866
+ }
867
+ };
868
+ //# sourceMappingURL=git-files-backup.js.map