-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2693 lines (2303 loc) · 98.9 KB
/
Copy pathscript.js
File metadata and controls
2693 lines (2303 loc) · 98.9 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Melhorias de UX/Perf/A11y
- Botão de Download integrado ao header já suportado em downloadRepository()
- Tema: sincroniza ícone e aria-pressed; ciclo light/dark/auto
- Repositórios: clique no cartão seleciona para download; enter/space aciona
- Debounce utilitário compartilhado; throttling para scroll
*/
// Estado global da aplicação
const app = {
selectedFiles: [],
credentials: null,
logs: [],
currentSection: 'main-menu',
repositories: [],
userInfo: null,
dashboardData: null,
settings: {
autoGitignore: true,
autoReadme: true,
compressImages: false,
maxFileSize: 25,
defaultBranch: 'main',
autoCommitMessage: true,
commitPrefix: '✨ ',
scanSecrets: true,
encryptCredentials: true,
sessionTimeout: 60,
theme: 'light',
language: 'pt-BR',
animations: true,
autoSync: false,
syncInterval: 30
},
selectedTemplate: null,
templates: {
'web-basic': {
name: 'Site Básico',
description: 'HTML, CSS e JavaScript básico',
files: {
'index.html': '<!DOCTYPE html>\n<html lang="pt-BR">\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n <title>Meu Site</title>\n <link rel="stylesheet" href="style.css">\n</head>\n<body>\n <h1>Bem-vindo ao meu site!</h1>\n <script src="script.js"></script>\n</body>\n</html>',
'style.css': 'body {\n font-family: Arial, sans-serif;\n margin: 0;\n padding: 20px;\n background: #f5f5f5;\n}\n\nh1 {\n color: #333;\n text-align: center;\n}',
'script.js': 'console.log("Site carregado com sucesso!");'
}
},
'react-app': {
name: 'React App',
description: 'Aplicação React com estrutura completa',
files: {
'package.json': '{\n "name": "minha-app-react",\n "version": "1.0.0",\n "dependencies": {\n "react": "^18.0.0",\n "react-dom": "^18.0.0"\n },\n "scripts": {\n "start": "react-scripts start",\n "build": "react-scripts build"\n }\n}',
'src/App.js': 'import React from "react";\nimport "./App.css";\n\nfunction App() {\n return (\n <div className="App">\n <h1>Minha App React</h1>\n <p>Bem-vindo à sua nova aplicação!</p>\n </div>\n );\n}\n\nexport default App;',
'src/App.css': '.App {\n text-align: center;\n padding: 20px;\n}\n\nh1 {\n color: #61dafb;\n}',
'public/index.html': '<!DOCTYPE html>\n<html>\n<head>\n <title>React App</title>\n</head>\n<body>\n <div id="root"></div>\n</body>\n</html>'
}
},
'python-flask': {
name: 'Flask API',
description: 'API REST com Python e Flask',
files: {
'app.py': 'from flask import Flask, jsonify\n\napp = Flask(__name__)\n\n@app.route("/")\ndef home():\n return jsonify({"message": "Bem-vindo à minha API Flask!"})\n\n@app.route("/api/status")\ndef status():\n return jsonify({"status": "OK", "version": "1.0.0"})\n\nif __name__ == "__main__":\n app.run(debug=True, host="0.0.0.0", port=5000)',
'requirements.txt': 'Flask==2.3.3\nFlask-CORS==4.0.0',
'config.py': 'import os\n\nclass Config:\n SECRET_KEY = os.environ.get("SECRET_KEY") or "dev-secret-key"\n DEBUG = True'
}
},
'node-express': {
name: 'Node.js + Express',
description: 'Servidor backend com Express',
files: {
'package.json': '{\n "name": "meu-servidor-express",\n "version": "1.0.0",\n "main": "server.js",\n "dependencies": {\n "express": "^4.18.0",\n "cors": "^2.8.5"\n },\n "scripts": {\n "start": "node server.js",\n "dev": "nodemon server.js"\n }\n}',
'server.js': 'const express = require("express");\nconst cors = require("cors");\n\nconst app = express();\nconst PORT = process.env.PORT || 5000;\n\napp.use(cors());\napp.use(express.json());\n\napp.get("/", (req, res) => {\n res.json({ message: "Servidor Express funcionando!" });\n});\n\napp.get("/api/status", (req, res) => {\n res.json({ status: "OK", timestamp: new Date().toISOString() });\n});\n\napp.listen(PORT, "0.0.0.0", () => {\n console.log(`Servidor rodando na porta ${PORT}`);\n});'
}
},
'portfolio': {
name: 'Portfólio',
description: 'Site portfólio responsivo',
files: {
'index.html': '<!DOCTYPE html>\n<html lang="pt-BR">\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n <title>Meu Portfólio</title>\n <link rel="stylesheet" href="style.css">\n</head>\n<body>\n <nav>\n <h1>Meu Nome</h1>\n <ul>\n <li><a href="#sobre">Sobre</a></li>\n <li><a href="#projetos">Projetos</a></li>\n <li><a href="#contato">Contato</a></li>\n </ul>\n </nav>\n \n <section id="hero">\n <h2>Desenvolvedor Full Stack</h2>\n <p>Criando soluções digitais incríveis</p>\n </section>\n \n <section id="sobre">\n <h2>Sobre Mim</h2>\n <p>Desenvolvedor apaixonado por tecnologia...</p>\n </section>\n \n <section id="projetos">\n <h2>Meus Projetos</h2>\n <div class="projetos-grid">\n <div class="projeto">\n <h3>Projeto 1</h3>\n <p>Descrição do projeto...</p>\n </div>\n </div>\n </section>\n \n <footer id="contato">\n <h2>Contato</h2>\n <p>email@exemplo.com</p>\n </footer>\n</body>\n</html>',
'style.css': '* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nbody {\n font-family: Arial, sans-serif;\n line-height: 1.6;\n color: #333;\n}\n\nnav {\n background: #333;\n color: white;\n padding: 1rem;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\nnav ul {\n display: flex;\n list-style: none;\n gap: 2rem;\n}\n\nnav a {\n color: white;\n text-decoration: none;\n}\n\n#hero {\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: white;\n text-align: center;\n padding: 5rem 2rem;\n}\n\nsection {\n padding: 3rem 2rem;\n max-width: 1200px;\n margin: 0 auto;\n}\n\n.projetos-grid {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));\n gap: 2rem;\n margin-top: 2rem;\n}\n\n.projeto {\n background: #f4f4f4;\n padding: 2rem;\n border-radius: 8px;\n}\n\nfooter {\n background: #333;\n color: white;\n text-align: center;\n padding: 2rem;\n}'
}
},
'documentation': {
name: 'Documentação',
description: 'Site de documentação com Markdown',
files: {
'index.html': '<!DOCTYPE html>\n<html lang="pt-BR">\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n <title>Documentação</title>\n <link rel="stylesheet" href="style.css">\n</head>\n<body>\n <nav class="sidebar">\n <h1>Documentação</h1>\n <ul>\n <li><a href="#introducao">Introdução</a></li>\n <li><a href="#instalacao">Instalação</a></li>\n <li><a href="#uso">Como Usar</a></li>\n <li><a href="#api">Referência API</a></li>\n </ul>\n </nav>\n \n <main class="content">\n <section id="introducao">\n <h1>Introdução</h1>\n <p>Bem-vindo à documentação do projeto...</p>\n </section>\n \n <section id="instalacao">\n <h1>Instalação</h1>\n <pre><code>npm install meu-projeto</code></pre>\n </section>\n \n <section id="uso">\n <h1>Como Usar</h1>\n <p>Exemplo básico de uso...</p>\n </section>\n \n <section id="api">\n <h1>Referência API</h1>\n <p>Documentação completa da API...</p>\n </section>\n </main>\n</body>\n</html>',
'style.css': '* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nbody {\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n display: flex;\n min-height: 100vh;\n}\n\n.sidebar {\n width: 250px;\n background: #2c3e50;\n color: white;\n padding: 2rem;\n position: fixed;\n height: 100vh;\n overflow-y: auto;\n}\n\n.sidebar h1 {\n margin-bottom: 2rem;\n color: #3498db;\n}\n\n.sidebar ul {\n list-style: none;\n}\n\n.sidebar li {\n margin-bottom: 1rem;\n}\n\n.sidebar a {\n color: #ecf0f1;\n text-decoration: none;\n padding: 0.5rem;\n display: block;\n border-radius: 4px;\n transition: background 0.3s;\n}\n\n.sidebar a:hover {\n background: #34495e;\n}\n\n.content {\n margin-left: 250px;\n padding: 2rem;\n max-width: 800px;\n line-height: 1.6;\n}\n\n.content h1 {\n color: #2c3e50;\n margin-bottom: 1rem;\n border-bottom: 2px solid #3498db;\n padding-bottom: 0.5rem;\n}\n\n.content p {\n margin-bottom: 1rem;\n}\n\npre {\n background: #f8f9fa;\n padding: 1rem;\n border-radius: 4px;\n overflow-x: auto;\n margin: 1rem 0;\n}\n\ncode {\n background: #f8f9fa;\n padding: 0.2rem 0.4rem;\n border-radius: 3px;\n font-family: "Courier New", monospace;\n}',
'README.md': '# Documentação do Projeto\n\n## Sobre\n\nEsta é a documentação completa do projeto.\n\n## Estrutura\n\n- `index.html` - Página principal\n- `style.css` - Estilos da documentação\n- `README.md` - Este arquivo\n\n## Como contribuir\n\n1. Fork o projeto\n2. Crie uma branch para sua feature\n3. Commit suas mudanças\n4. Push para a branch\n5. Abra um Pull Request'
}
}
}
};
// Inicialização
document.addEventListener('DOMContentLoaded', function() {
initializeApp();
// Acessibilidade: navegação por teclado para botões principais
document.querySelectorAll('button, a, [role="button"]').forEach(el => {
el.addEventListener('keyup', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
e.target.click();
}
});
});
// Melhor UX: habilitar atalho "s" para focar busca nos repositórios
document.addEventListener('keydown', (e) => {
if (e.key.toLowerCase() === 's' && app.currentSection === 'repos-section' && !['INPUT','TEXTAREA','SELECT'].includes(document.activeElement.tagName)) {
const input = document.getElementById('repo-search');
if (input) {
input.focus();
e.preventDefault();
}
}
});
// Throttle de rolagem para evitar trabalho excessivo
// const onScroll = throttle(() => {
// // reservado para futuras leituras de posição sem repaints
// }, 150);
// window.addEventListener('scroll', onScroll, { passive: true });
});
function initializeApp() {
loadCredentials();
loadLogs();
setupFileUpload();
runSystemCheck();
updateConnectionStatus();
// Log de inicialização
addLog('info', 'Sistema inicializado com sucesso');
}
/* Gerenciamento de seções */
function showSection(sectionId) {
// Evitar retrabalho se já estiver na seção
if (app.currentSection === sectionId) return;
// Esconder todas as seções e aplicar inert para acessibilidade
const sections = document.querySelectorAll('.section, .menu-section');
sections.forEach(section => {
section.classList.remove('active');
section.style.display = 'none';
section.setAttribute('aria-hidden', 'true');
section.setAttribute('inert', '');
});
// Mostrar seção selecionada
const targetSection = document.getElementById(sectionId);
if (targetSection) {
targetSection.style.display = 'block';
targetSection.classList.add('active');
targetSection.setAttribute('aria-hidden', 'false');
targetSection.removeAttribute('inert');
app.currentSection = sectionId;
// Enviar foco para o título da seção para acessibilidade
const focusableHeading = targetSection.querySelector('h2, h1');
if (focusableHeading) {
focusableHeading.setAttribute('tabindex', '-1');
// usar rAF para garantir render antes do foco
requestAnimationFrame(() => {
try { focusableHeading.focus({ preventScroll: false }); } catch(e) {}
});
}
}
// Ações específicas por seção
switch (sectionId) {
case 'verify-section':
runSystemCheck();
break;
case 'logs-section':
displayLogs();
break;
case 'config-section':
loadSavedCredentials();
break;
case 'repos-section':
loadRepositories();
break;
case 'dashboard-section':
loadDashboard();
break;
}
}
// Configuração do upload de arquivos
function setupFileUpload() {
const uploadArea = document.getElementById('upload-area');
const fileInput = document.getElementById('file-input');
// Eventos de drag and drop
uploadArea.addEventListener('dragover', function(e) {
e.preventDefault();
uploadArea.classList.add('dragover');
});
uploadArea.addEventListener('dragleave', function(e) {
e.preventDefault();
uploadArea.classList.remove('dragover');
});
uploadArea.addEventListener('drop', function(e) {
e.preventDefault();
uploadArea.classList.remove('dragover');
const files = Array.from(e.dataTransfer.files);
handleFileSelection(files);
});
// Evento de clique
uploadArea.addEventListener('click', function() {
this.style.transform = 'scale(0.98)';
setTimeout(() => {
this.style.transform = '';
}, 150);
fileInput.click();
});
// Evento de seleção de arquivo
fileInput.addEventListener('change', function() {
const files = Array.from(this.files);
handleFileSelection(files);
});
}
function handleFileSelection(files) {
app.selectedFiles = files;
displaySelectedFiles();
// Sugerir nome do repositório baseado no primeiro arquivo/pasta
if (files.length > 0) {
const firstPath = files[0].webkitRelativePath || files[0].name;
const folderName = firstPath.split('/')[0];
const repoNameInput = document.getElementById('repo-name');
if (!repoNameInput.value) {
repoNameInput.value = folderName.toLowerCase().replace(/[^a-z0-9-]/g, '-');
}
}
// Habilitar botão de upload
const uploadBtn = document.getElementById('upload-btn');
uploadBtn.disabled = files.length === 0;
addLog('info', `${files.length} arquivos selecionados`);
}
function displaySelectedFiles() {
const fileList = document.getElementById('file-list');
const filesPreview = document.getElementById('files-preview');
if (app.selectedFiles.length === 0) {
fileList.style.display = 'none';
return;
}
fileList.style.display = 'block';
filesPreview.innerHTML = '';
// Agrupar arquivos por tipo
const fileTypes = {};
let totalSize = 0;
app.selectedFiles.forEach(file => {
const ext = file.name.split('.').pop().toLowerCase();
if (!fileTypes[ext]) {
fileTypes[ext] = { count: 0, size: 0 };
}
fileTypes[ext].count++;
fileTypes[ext].size += file.size;
totalSize += file.size;
});
// Exibir resumo
const summary = document.createElement('div');
summary.className = 'files-summary';
summary.innerHTML = `
<p><strong>Total:</strong> ${app.selectedFiles.length} arquivos (${formatFileSize(totalSize)})</p>
`;
filesPreview.appendChild(summary);
// Exibir tipos de arquivo
Object.entries(fileTypes).forEach(([ext, info]) => {
const fileItem = document.createElement('div');
fileItem.className = 'file-item';
fileItem.innerHTML = `
<i class="fas fa-file"></i>
<span>.${ext} files: ${info.count} (${formatFileSize(info.size)})</span>
`;
filesPreview.appendChild(fileItem);
});
// Mostrar alguns arquivos individuais se houver poucos
if (app.selectedFiles.length <= 10) {
const separator = document.createElement('hr');
separator.style.margin = '15px 0';
filesPreview.appendChild(separator);
app.selectedFiles.forEach(file => {
const fileItem = document.createElement('div');
fileItem.className = 'file-item';
fileItem.innerHTML = `
<i class="fas fa-file"></i>
<span>${file.webkitRelativePath || file.name} (${formatFileSize(file.size)})</span>
`;
filesPreview.appendChild(fileItem);
});
}
}
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// Credenciais
function saveCredentials() {
const token = document.getElementById('github-token').value.trim();
const username = document.getElementById('github-username').value.trim();
if (!token || !username) {
showNotification('Preencha todos os campos', 'error');
return;
}
// Feedback de carregamento no botão
const btn = document.getElementById('save-credentials-btn');
if (btn) {
btn.setAttribute('aria-busy', 'true');
btn.disabled = true;
}
app.credentials = { token, username };
localStorage.setItem('git-automatico-credentials', JSON.stringify(app.credentials));
showNotification('Credenciais salvas com sucesso!', 'success');
updateConnectionStatus();
addLog('info', 'Credenciais atualizadas');
if (btn) {
btn.setAttribute('aria-busy', 'false');
btn.disabled = false;
}
}
function loadCredentials() {
const saved = localStorage.getItem('git-automatico-credentials');
if (saved) {
app.credentials = JSON.parse(saved);
updateConnectionStatus();
}
}
function loadSavedCredentials() {
if (app.credentials) {
document.getElementById('github-token').value = app.credentials.token;
document.getElementById('github-username').value = app.credentials.username;
}
}
async function testCredentials() {
if (!app.credentials) {
showNotification('Configure as credenciais primeiro', 'warning');
return;
}
try {
showNotification('Testando conexão...', 'info');
const response = await fetch('https://api.github.com/user', {
headers: {
'Authorization': `token ${app.credentials.token}`,
'Accept': 'application/vnd.github.v3+json'
}
});
if (response.ok) {
const user = await response.json();
showNotification(`Conectado como ${user.login}`, 'success');
addLog('success', `Autenticação bem-sucedida para ${user.login}`);
updateConnectionStatus(true);
} else {
const msg = response.status === 401 ? 'Token inválido ou expirado' : 'Falha na autenticação';
showNotification(msg, 'error');
addLog('error', `${msg} (HTTP ${response.status})`);
updateConnectionStatus(false);
}
} catch (error) {
showNotification('Erro de conexão', 'error');
addLog('error', `Erro de conexão: ${error.message}`);
updateConnectionStatus(false);
}
}
// Upload do projeto
async function uploadProject() {
if (!app.credentials) {
showNotification('Configure as credenciais primeiro', 'error');
showSection('config-section');
return;
}
if (app.selectedFiles.length === 0) {
showNotification('Selecione os arquivos primeiro', 'error');
return;
}
const repoName = document.getElementById('repo-name').value.trim();
const repoDescription = document.getElementById('repo-description').value.trim();
const isPrivate = document.getElementById('private-repo').checked;
if (!repoName) {
showNotification('Insira o nome do repositório', 'error');
return;
}
// Validar nome do repositório
if (!/^[a-zA-Z0-9._-]+$/.test(repoName)) {
showNotification('Nome do repositório deve conter apenas letras, números, pontos, hífens e underscores', 'error');
return;
}
try {
showProgressSection(true);
updateProgress(10, 'Criando repositório...');
addLog('info', `Iniciando upload do projeto: ${repoName}`);
// Criar repositório
const repo = await createRepository(repoName, repoDescription, isPrivate);
updateProgress(30, 'Repositório criado! Preparando arquivos...');
addLog('success', `Repositório ${repoName} criado com sucesso`);
// Preparar arquivos
const files = await prepareFiles();
updateProgress(50, 'Enviando arquivos...');
// Enviar arquivos
await uploadFiles(repo, files);
updateProgress(90, 'Finalizando...');
updateProgress(100, 'Concluído!');
addLog('success', `Projeto enviado com sucesso para: ${repo.html_url}`);
setTimeout(() => {
showNotification(`Projeto enviado! <a href="${repo.html_url}" target="_blank">Ver no GitHub</a>`, 'success');
showProgressSection(false);
resetUploadForm();
}, 1000);
} catch (error) {
addLog('error', `Erro no upload: ${error.message}`);
showNotification(`Erro: ${error.message}`, 'error');
showProgressSection(false);
}
}
async function createRepository(name, description, isPrivate) {
const response = await fetch('https://api.github.com/user/repos', {
method: 'POST',
headers: {
'Authorization': `token ${app.credentials.token}`,
'Accept': 'application/vnd.github.v3+json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: name,
description: description || `Projeto criado com Git Automático Web`,
private: isPrivate,
auto_init: true
})
});
if (!response.ok) {
let error;
try {
error = await response.json();
} catch {
error = {};
}
if (response.status === 422 && (error?.errors?.some(e => String(e.message || '').includes('already exists')) || String(error?.message || '').includes('already exists'))) {
throw new Error(`Repositório "${name}" já existe. Use um nome diferente.`);
}
if (response.status === 401) {
throw new Error('Não autorizado. Verifique o token do GitHub.');
}
throw new Error(error?.message || 'Erro ao criar repositório');
}
return await response.json();
}
async function prepareFiles() {
const files = {};
for (const file of app.selectedFiles) {
const path = file.webkitRelativePath || file.name;
// Pular arquivos muito grandes (>25MB - limite do GitHub)
if (file.size > 25 * 1024 * 1024) {
addLog('warning', `Arquivo ${path} muito grande (${formatFileSize(file.size)}) - pulando`);
continue;
}
// Pular arquivos binários comuns que não precisam estar no repo
const skipExtensions = ['.exe', '.dll', '.so', '.dylib', '.bin'];
const ext = path.split('.').pop().toLowerCase();
if (skipExtensions.includes(`.${ext}`)) {
addLog('info', `Pulando arquivo binário: ${path}`);
continue;
}
try {
const content = await readFileAsBase64(file);
files[path] = {
content: content,
encoding: 'base64'
};
} catch (error) {
addLog('warning', `Erro ao ler arquivo ${path}: ${error.message}`);
}
}
// Criar .gitignore se não existir
if (!files['.gitignore']) {
files['.gitignore'] = {
content: btoa(generateGitignore()),
encoding: 'base64'
};
}
return files;
}
function readFileAsBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const base64 = reader.result.split(',')[1];
resolve(base64);
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
async function uploadFiles(repo, files) {
const fileEntries = Object.entries(files);
const batchSize = 5; // Enviar 5 arquivos por vez
let uploaded = 0;
for (let i = 0; i < fileEntries.length; i += batchSize) {
const batch = fileEntries.slice(i, i + batchSize);
const results = await Promise.allSettled(
batch.map(([path, fileData]) => uploadSingleFile(repo, path, fileData))
);
// Contabilizar sucesso/erro do batch
results.forEach((res, idx) => {
const fileName = batch[idx][0];
if (res.status === 'fulfilled') {
uploaded++;
} else {
addLog('error', `Falha ao enviar: ${fileName} - ${res.reason?.message || res.reason}`);
}
});
const progress = 50 + (uploaded / fileEntries.length) * 40;
updateProgress(progress, `Enviando arquivos... (${uploaded}/${fileEntries.length})`);
// Pausa breve para não sobrecarregar a API
if (i + batchSize < fileEntries.length) {
await new Promise(resolve => setTimeout(resolve, 250));
}
}
// Mensagem final de resumo
addLog('info', `Upload finalizado: ${uploaded}/${fileEntries.length} arquivos enviados`);
}
async function uploadSingleFile(repo, path, fileData) {
// Retry com backoff exponencial simples + respeito a X-RateLimit-Reset
const maxRetries = 3;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
const response = await fetch(`https://api.github.com/repos/${repo.full_name}/contents/${encodeURIComponent(path)}`, {
method: 'PUT',
headers: {
'Authorization': `token ${app.credentials.token}`,
'Accept': 'application/vnd.github.v3+json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: `${app.settings.autoCommitMessage ? app.settings.commitPrefix : ''}Add ${path}`,
content: fileData.content,
encoding: fileData.encoding,
branch: app.settings.defaultBranch || 'main'
})
});
if (response.ok) {
addLog('info', `Arquivo enviado: ${path}`);
return;
}
// Lidar com rate limit
if (response.status === 403) {
const reset = response.headers.get('X-RateLimit-Reset');
if (reset) {
const waitMs = Math.max(0, parseInt(reset, 10) * 1000 - Date.now());
if (waitMs > 0 && attempt < maxRetries) {
addLog('warning', `Rate limit atingido. Aguardando ${Math.ceil(waitMs/1000)}s antes de tentar novamente...`);
await new Promise(r => setTimeout(r, Math.min(waitMs, 15000))); // aguarda até 15s
continue;
}
}
}
// 429/5xx -> tentar novamente com backoff
if ([429, 500, 502, 503, 504].includes(response.status) && attempt < maxRetries) {
const wait = 500 * Math.pow(2, attempt);
await new Promise(r => setTimeout(r, wait));
continue;
}
// Outras falhas: lançar erro detalhado
let errorText = 'Erro ao enviar arquivo';
try {
const error = await response.json();
errorText = error.message || errorText;
} catch {}
throw new Error(`Erro ao enviar ${path}: ${errorText} (HTTP ${response.status})`);
}
}
function generateGitignore() {
return `# Git Automatico Web - Gitignore Automático
# Arquivos de sistema
.DS_Store
Thumbs.db
*.log
# Dependências
node_modules/
vendor/
venv/
env/
# Arquivos de build
dist/
build/
*.min.js
*.min.css
# IDEs
.vscode/
.idea/
*.swp
*.swo
# Temporários
*.tmp
*.temp
`;
}
// Interface de progresso
function showProgressSection(show) {
const progressSection = document.getElementById('progress-section');
progressSection.style.display = show ? 'block' : 'none';
}
function updateProgress(percent, text) {
const progressFill = document.getElementById('progress-fill');
const progressText = document.getElementById('progress-text');
progressFill.style.width = `${percent}%`;
progressText.textContent = text;
}
function resetUploadForm() {
app.selectedFiles = [];
document.getElementById('repo-name').value = '';
document.getElementById('repo-description').value = '';
document.getElementById('private-repo').checked = false;
document.getElementById('file-list').style.display = 'none';
document.getElementById('upload-btn').disabled = true;
}
// Sistema de verificação
async function runSystemCheck() {
const checks = {
'browser-status': checkBrowserCompatibility,
'github-connection': checkGitHubConnection,
'credentials-status': checkCredentials,
'fileapi-status': checkFileAPISupport
};
for (const [elementId, checkFunction] of Object.entries(checks)) {
const element = document.getElementById(elementId);
element.textContent = 'Verificando...';
element.className = 'verify-status';
try {
const result = await checkFunction();
element.textContent = result.message;
element.className = `verify-status ${result.status}`;
} catch (error) {
element.textContent = `Erro: ${error.message}`;
element.className = 'verify-status error';
}
}
}
function checkBrowserCompatibility() {
const isCompatible =
window.File &&
window.FileReader &&
window.FileList &&
window.Blob &&
window.fetch;
return {
status: isCompatible ? 'success' : 'error',
message: isCompatible ? '✅ Compatível' : '❌ Navegador não suportado'
};
}
async function checkGitHubConnection() {
try {
const response = await fetch('https://api.github.com/octocat', {
method: 'GET',
mode: 'cors'
});
return {
status: response.ok ? 'success' : 'error',
message: response.ok ? '✅ Conectado' : '❌ Sem conexão'
};
} catch (error) {
return {
status: 'error',
message: '❌ Erro de rede'
};
}
}
function checkCredentials() {
const hasCredentials = app.credentials && app.credentials.token && app.credentials.username;
return {
status: hasCredentials ? 'success' : 'warning',
message: hasCredentials ? '✅ Configuradas' : '⚠️ Não configuradas'
};
}
function checkFileAPISupport() {
const hasSupport = 'webkitdirectory' in document.createElement('input');
return {
status: hasSupport ? 'success' : 'warning',
message: hasSupport ? '✅ Suportado' : '⚠️ Limitado'
};
}
// Status de conexão
function updateConnectionStatus(connected = null) {
const connectionStatus = document.getElementById('connection-status');
const githubStatus = document.getElementById('github-status');
// Status de internet
const online = navigator.onLine;
connectionStatus.className = `status-item ${online ? 'online' : 'offline'}`;
connectionStatus.innerHTML = `<i class="fas fa-wifi"></i><span>${online ? 'Online' : 'Offline'}</span>`;
// Status do GitHub
if (connected === true) {
githubStatus.className = 'status-item online';
githubStatus.innerHTML = '<i class="fab fa-github"></i><span>GitHub: Conectado</span>';
} else if (connected === false) {
githubStatus.className = 'status-item offline';
githubStatus.innerHTML = '<i class="fab fa-github"></i><span>GitHub: Erro</span>';
} else if (app.credentials) {
githubStatus.className = 'status-item';
githubStatus.innerHTML = '<i class="fab fa-github"></i><span>GitHub: Configurado</span>';
} else {
githubStatus.className = 'status-item';
githubStatus.innerHTML = '<i class="fab fa-github"></i><span>GitHub: Não configurado</span>';
}
}
// Sistema de logs
function addLog(level, message) {
const timestamp = new Date().toLocaleString('pt-BR');
const logEntry = {
timestamp,
level,
message
};
app.logs.unshift(logEntry);
// Manter apenas os últimos 200 logs para histórico maior
if (app.logs.length > 200) {
app.logs = app.logs.slice(0, 200);
}
// Persistir de forma debounced para reduzir operações no localStorage
debounceSaveLogs();
// Atualizar display se estiver na seção de logs
if (app.currentSection === 'logs-section') {
displayLogs();
}
}
function displayLogs() {
const logsContent = document.getElementById('logs-content');
if (app.logs.length === 0) {
logsContent.innerHTML = '<div class="log-entry info">Nenhum log disponível</div>';
return;
}
logsContent.innerHTML = app.logs
.map(log => `<div class="log-entry ${log.level}">[${log.timestamp}] [${log.level.toUpperCase()}] ${log.message}</div>`)
.join('');
}
function clearLogs() {
if (confirm('Deseja realmente limpar todos os logs?')) {
app.logs = [];
saveLogs();
displayLogs();
addLog('info', 'Logs limpos pelo usuário');
}
}
function downloadLogs() {
const logsText = app.logs
.map(log => `[${log.timestamp}] [${log.level.toUpperCase()}] ${log.message}`)
.join('\n');
const blob = new Blob([logsText], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `git-automatico-logs-${new Date().toISOString().split('T')[0]}.txt`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
addLog('info', 'Logs baixados');
}
function saveLogs() {
localStorage.setItem('git-automatico-logs', JSON.stringify(app.logs));
}
// Debounce simples para persistência de logs
const debounceSaveLogs = (function() {
let t;
return function() {
clearTimeout(t);
t = setTimeout(saveLogs, 300);
};
})();
function loadLogs() {
const saved = localStorage.getItem('git-automatico-logs');
if (saved) {
app.logs = JSON.parse(saved);
}
}
// Limpeza de dados
function clearData() {
if (confirm('Deseja realmente limpar todos os dados salvos?\n\nIsso incluirá:\n- Credenciais\n- Logs\n- Configurações')) {
localStorage.removeItem('git-automatico-credentials');
localStorage.removeItem('git-automatico-logs');
app.credentials = null;
app.logs = [];
updateConnectionStatus();
showNotification('Dados limpos com sucesso!', 'success');
addLog('info', 'Dados do sistema limpos');
// Limpar formulários
document.getElementById('github-token').value = '';
document.getElementById('github-username').value = '';
}
}
// Sistema de notificações
function showNotification(message, type = 'info') {
const notification = document.getElementById('notification');
const notificationText = notification.querySelector('.notification-text');
notificationText.innerHTML = message;
notification.className = `notification ${type}`;
notification.style.display = 'block';
// Anunciar via ARIA
notification.setAttribute('aria-live', type === 'error' ? 'assertive' : 'polite');
// Auto-esconder após 5 segundos
clearTimeout(showNotification._timeout);
showNotification._timeout = setTimeout(() => {
hideNotification();
}, 5000);
}
function hideNotification() {
const notification = document.getElementById('notification');
notification.style.display = 'none';
}
// Gerenciamento de Repositórios
async function loadRepositories() {
if (!app.credentials) {
showNotification('Configure as credenciais primeiro', 'warning');
showSection('config-section');
return;
}
// Mostrar skeleton loading
showRepositorySkeleton();
// Ocultar estatísticas durante o carregamento
const stats = document.getElementById('repos-stats');
stats.style.display = 'none';
try {
const response = await fetch('https://api.github.com/user/repos?per_page=100&sort=updated', {
headers: {
'Authorization': `token ${app.credentials.token}`,
'Accept': 'application/vnd.github.v3+json'
}
});
if (!response.ok) {
throw new Error('Erro ao carregar repositórios');
}
app.repositories = await response.json();
// Pequeno delay para mostrar o skeleton
setTimeout(() => {
displayRepositories(app.repositories);
updateRepositoriesStats();
addLog('info', `${app.repositories.length} repositórios carregados`);
}, 500);
} catch (error) {
const container = document.getElementById('repos-container');
container.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">❌</div>
<div class="empty-state-title">Erro ao carregar repositórios</div>
<div class="empty-state-description">
${error.message}
</div>
</div>
`;
addLog('error', `Erro ao carregar repositórios: ${error.message}`);
}
}
function displayRepositories(repos) {
const container = document.getElementById('repos-container');
if (!container) return;
const searchInput = document.getElementById('repo-search');
const searchQuery = (searchInput && searchInput.value ? searchInput.value : '').toLowerCase();
const downloadBtn = document.getElementById('download-selected-btn');
// Resetar seleção e botão de download (compatibilidade)
app.credentials = app.credentials || {};
app.credentials.repository = null;
if (downloadBtn) {
downloadBtn.disabled = true;
downloadBtn.setAttribute('aria-disabled', 'true');
}
if (!Array.isArray(repos) || repos.length === 0) {
container.innerHTML = `
<div class="empty-state" role="status" aria-live="polite">
<div class="empty-state-icon">📁</div>
<div class="empty-state-title">Nenhum repositório encontrado</div>
<div class="empty-state-description">
Tente ajustar os filtros de busca ou criar um novo repositório
</div>