-
-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathsloccount.html
More file actions
1256 lines (1101 loc) · 51.3 KB
/
sloccount.html
File metadata and controls
1256 lines (1101 loc) · 51.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SLOCCount - Count Lines of Code</title>
<style>
* {
box-sizing: border-box;
}
body {
font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif;
max-width: 900px;
margin: 0 auto;
padding: 20px;
line-height: 1.6;
}
h1 {
margin-bottom: 10px;
font-size: 28px;
}
p {
margin-top: 0;
color: #666;
}
.tabs {
display: flex;
gap: 10px;
margin-bottom: 20px;
border-bottom: 2px solid #ddd;
}
.tab {
padding: 10px 20px;
cursor: pointer;
background: none;
border: none;
border-bottom: 3px solid transparent;
font-size: 16px;
color: #666;
transition: all 0.3s;
}
.tab.active {
color: #ffffff;
background-color: #007bff;
border-bottom-color: #007bff;
font-weight: 600;
}
.tab:hover:not(.active) {
color: #0056b3;
}
.tab.active:hover {
color: #ffffff;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 600;
color: #333;
}
input[type="text"], textarea {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
font-family: inherit;
}
textarea {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
min-height: 200px;
resize: vertical;
}
.input-group {
margin-bottom: 20px;
}
.button-group {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
button {
padding: 12px 24px;
cursor: pointer;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
font-weight: 500;
transition: background-color 0.3s;
}
button:hover:not(:disabled) {
background-color: #0056b3;
}
button:disabled {
background-color: #6c757d;
cursor: wait;
opacity: 0.7;
}
button.secondary {
background-color: #6c757d;
}
button.secondary:hover:not(:disabled) {
background-color: #545b62;
}
#status {
padding: 12px;
margin-bottom: 20px;
border-radius: 4px;
display: none;
}
#status.visible {
display: block;
}
#status.info {
background-color: #d1ecf1;
color: #0c5460;
border: 1px solid #bee5eb;
}
#status.error {
background-color: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
#status.success {
background-color: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
#results {
display: none;
}
#results.visible {
display: block;
}
.results-header {
background-color: #f8f9fa;
padding: 15px;
border-radius: 4px;
margin-bottom: 20px;
}
.results-header h2 {
margin: 0 0 10px 0;
font-size: 20px;
}
.summary {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 15px;
margin-bottom: 20px;
}
.summary-item {
background: white;
padding: 15px;
border-radius: 4px;
border: 1px solid #dee2e6;
text-align: center;
}
.summary-item .label {
font-size: 14px;
color: #666;
margin-bottom: 5px;
}
.summary-item .value {
font-size: 28px;
font-weight: bold;
color: #007bff;
}
.language-breakdown {
background: white;
border: 1px solid #dee2e6;
border-radius: 4px;
overflow: hidden;
}
.language-breakdown h3 {
margin: 0;
padding: 15px;
background-color: #f8f9fa;
font-size: 18px;
border-bottom: 1px solid #dee2e6;
}
.language-table {
width: 100%;
border-collapse: collapse;
}
.language-table th {
background-color: #f8f9fa;
padding: 12px;
text-align: left;
font-weight: 600;
border-bottom: 2px solid #dee2e6;
}
.language-table td {
padding: 12px;
border-bottom: 1px solid #dee2e6;
}
.language-table tr:last-child td {
border-bottom: none;
}
.language-table tr:hover {
background-color: #f8f9fa;
}
.language-name {
font-weight: 500;
}
.percentage {
color: #666;
font-size: 14px;
}
@media (max-width: 600px) {
body {
padding: 10px;
}
h1 {
font-size: 24px;
}
.tabs {
overflow-x: auto;
}
.tab {
padding: 8px 16px;
font-size: 14px;
}
.button-group {
flex-direction: column;
}
button {
width: 100%;
}
.summary {
grid-template-columns: 1fr 1fr;
}
.summary-item .value {
font-size: 24px;
}
.language-table {
font-size: 14px;
}
.language-table th,
.language-table td {
padding: 8px;
}
}
</style>
</head>
<body>
<h1>SLOCCount - Count Lines of Code</h1>
<p>Analyze source code to count physical Source Lines of Code (SLOC) using Perl and C programs running via WebAssembly</p>
<p style="font-size: 14px; margin-top: -10px;">Based on <a href="https://dwheeler.com/sloccount/">SLOCCount</a> by David A. Wheeler</p>
<div class="tabs">
<button class="tab active" data-tab="paste">Paste Code</button>
<button class="tab" data-tab="github">GitHub Repository</button>
<button class="tab" data-tab="zip">Upload ZIP</button>
</div>
<div id="paste-tab" class="tab-content active">
<div class="input-group">
<label for="code-input">Paste your code here:</label>
<textarea id="code-input" placeholder="Paste source code files here (supports multiple files)..."></textarea>
</div>
<div class="input-group">
<label for="filename-input">Filename (to detect language):</label>
<input type="text" id="filename-input" placeholder="e.g., main.py, app.js, index.html">
</div>
<div class="button-group">
<button id="analyze-paste-btn" disabled>Initializing...</button>
<button id="clear-paste-btn" class="secondary">Clear</button>
</div>
</div>
<div id="github-tab" class="tab-content">
<div class="input-group">
<label for="repo-input">GitHub Repository URL:</label>
<input type="text" id="repo-input" placeholder="https://github.com/owner/repo">
</div>
<div class="button-group">
<button id="analyze-repo-btn" disabled>Initializing...</button>
</div>
</div>
<div id="zip-tab" class="tab-content">
<div class="input-group">
<label for="zip-input">Upload ZIP file containing source code:</label>
<input type="file" id="zip-input" accept=".zip" style="padding: 10px; border: 2px dashed #ccc; border-radius: 4px; cursor: pointer;">
<p style="margin-top: 10px; font-size: 14px; color: #666;">
Useful for large repositories. Upload a ZIP file containing your source code.
</p>
</div>
<div class="button-group">
<button id="analyze-zip-btn" disabled>Initializing...</button>
</div>
</div>
<div id="status"></div>
<div id="results">
<div class="results-header">
<h2>Analysis Results</h2>
</div>
<div class="summary">
<div class="summary-item">
<div class="label">Total Lines</div>
<div class="value" id="total-lines">0</div>
</div>
<div class="summary-item">
<div class="label">Languages</div>
<div class="value" id="total-languages">0</div>
</div>
<div class="summary-item">
<div class="label">Files</div>
<div class="value" id="total-files">0</div>
</div>
<div class="summary-item">
<div class="label">Est. Cost (USD)<a href="#cost-estimates-info" style="text-decoration: none; color: #007bff; margin-left: 2px;"><sup>*</sup></a></div>
<div class="value" id="total-cost">$0</div>
</div>
<div class="summary-item">
<div class="label">Est. Person-Years<a href="#cost-estimates-info" style="text-decoration: none; color: #007bff; margin-left: 2px;"><sup>*</sup></a></div>
<div class="value" id="total-effort">0</div>
</div>
</div>
<div class="language-breakdown">
<h3>Language Breakdown</h3>
<table class="language-table" id="language-table">
<thead>
<tr>
<th>Language</th>
<th>Lines</th>
<th>Percentage</th>
<th>Files</th>
</tr>
</thead>
<tbody id="language-tbody">
</tbody>
</table>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js"></script>
<script src="./lib/webperl/webperl.js"></script>
<script>
console.log('Script starting...');
const tabs = document.querySelectorAll('.tab');
const pasteTab = document.getElementById('paste-tab');
const githubTab = document.getElementById('github-tab');
const zipTab = document.getElementById('zip-tab');
const codeInput = document.getElementById('code-input');
const filenameInput = document.getElementById('filename-input');
const repoInput = document.getElementById('repo-input');
const zipInput = document.getElementById('zip-input');
const analyzePasteBtn = document.getElementById('analyze-paste-btn');
const analyzeRepoBtn = document.getElementById('analyze-repo-btn');
const analyzeZipBtn = document.getElementById('analyze-zip-btn');
const clearPasteBtn = document.getElementById('clear-paste-btn');
const statusEl = document.getElementById('status');
const resultsEl = document.getElementById('results');
// Salary input is defined later in HTML, get it lazily
let salaryInputEl = null;
function getSalaryInput() {
if (!salaryInputEl) {
salaryInputEl = document.getElementById('salary-input');
}
return salaryInputEl;
}
// Store current analysis files for recalculation
let currentFiles = null;
let perlReady = false;
let slocScripts = {};
// Recalculate estimates with new salary
async function recalculateWithSalary() {
if (!currentFiles || currentFiles.length === 0) {
return; // No analysis to recalculate
}
const salary = parseInt(getSalaryInput().value) || 56286;
try {
showStatus('Recalculating with new salary...', 'info');
const results = await runSloccount(currentFiles, salary);
displayResults(results);
hideStatus();
} catch (error) {
showStatus('Recalculation failed: ' + error.message, 'error');
console.error('Recalculation error:', error);
}
}
// Tab switching
tabs.forEach(tab => {
tab.addEventListener('click', () => {
tabs.forEach(t => t.classList.remove('active'));
tab.classList.add('active');
const tabName = tab.dataset.tab;
pasteTab.classList.toggle('active', tabName === 'paste');
githubTab.classList.toggle('active', tabName === 'github');
zipTab.classList.toggle('active', tabName === 'zip');
});
});
// Clear button
clearPasteBtn.addEventListener('click', () => {
codeInput.value = '';
filenameInput.value = '';
hideResults();
});
// Status helpers
function showStatus(message, type = 'info', isHtml = false) {
if (isHtml) {
statusEl.innerHTML = message;
} else {
statusEl.textContent = message;
}
statusEl.className = `visible ${type}`;
}
function hideStatus() {
statusEl.className = '';
}
function showResults() {
resultsEl.classList.add('visible');
}
function hideResults() {
resultsEl.classList.remove('visible');
}
// Helper to dynamically load a script
function loadScript(url) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
// Initialize WebPerl and load sloccount
async function initializeWebPerl() {
try {
console.log('initializeWebPerl() starting...');
showStatus('Loading Perl WebAssembly runtime...', 'info');
// Wait for Perl to reach Running state (triggered by embedded script)
console.log('Waiting for Perl to be Running...');
while (Perl.state !== 'Running') {
console.log('Current Perl state:', Perl.state);
await new Promise(resolve => setTimeout(resolve, 100));
}
console.log('Perl is now Running!');
showStatus('Loading SLOCCount Perl scripts...', 'info');
// Load sloccount scripts from local zip file
const zipUrl = './lib/sloccount-perl.zip';
// Fetch the zip file
const response = await fetch(zipUrl);
if (!response.ok) {
throw new Error('Failed to fetch sloccount scripts');
}
const zipBlob = await response.blob();
const zip = await JSZip.loadAsync(zipBlob);
showStatus('Extracting Perl scripts...', 'info');
// Load ALL counter scripts (they all end with _count)
const scriptsToLoad = [
'python_count', 'perl_count', 'ruby_count', 'generic_count',
'javascript_count', 'sh_count', 'sql_count', 'lisp_count',
'asm_count', 'ada_count', 'awk_count', 'cobol_count', 'fortran_count',
'f90_count', 'haskell_count', 'makefile_count', 'modula3_count',
'objc_count', 'sed_count', 'tcl_count', 'vbasic_count', 'exp_count',
'csh_count', 'batch_count', 'vbscript_count', 'autohotkey_count',
'autoit_count', 'innosetup_count', 'lex_count'
];
for (const scriptName of scriptsToLoad) {
if (zip.files[scriptName]) {
const content = await zip.files[scriptName].async('text');
slocScripts[scriptName] = content;
}
}
console.log('Loaded', Object.keys(slocScripts).length, 'counter scripts from zip');
// Load modern language counter scripts from lib/sloc/
const modernScripts = [
'kotlin_count', 'swift_count', 'dart_count', 'scala_count',
'groovy_count', 'elixir_count', 'julia_count', 'fsharp_count',
'rust_count', 'go_count'
];
for (const scriptName of modernScripts) {
try {
const response = await fetch(`./lib/sloc/${scriptName}`);
if (response.ok) {
const content = await response.text();
slocScripts[scriptName] = content;
}
} catch (error) {
console.warn(`Failed to load ${scriptName}:`, error);
}
}
console.log('Total loaded:', Object.keys(slocScripts).length, 'counter scripts');
// Make scripts available to Perl via window object
window.counterScripts = slocScripts;
showStatus('Loading WebAssembly counters...', 'info');
// Load WASM modules for C-based counters
// We'll store their output in this array
window.wasmOutput = [];
// Load c_count WASM (used by many languages)
const c_count_module = await loadScript('./lib/wasm/c_count.js');
window.CCountModule = await createCCountModule({
print: (text) => { window.wasmOutput.push(text); },
printErr: (text) => { console.error('c_count WASM:', text); },
noInitialRun: true,
stdin: () => null,
// Disable prompts for input
prompt: () => null
});
console.log('Loaded c_count WASM module');
showStatus('WebAssembly counters loaded!', 'success');
perlReady = true;
analyzePasteBtn.textContent = 'Analyze Code';
analyzePasteBtn.disabled = false;
analyzeRepoBtn.textContent = 'Analyze Repository';
analyzeRepoBtn.disabled = false;
analyzeZipBtn.textContent = 'Analyze ZIP';
analyzeZipBtn.disabled = false;
// If ?repo= was provided, auto-run analysis now that assets are ready
if (repoParam) {
analyzeGitHubRepo();
} else {
showStatus('Ready to analyze code!', 'success');
setTimeout(hideStatus, 2000);
}
} catch (error) {
showStatus('Failed to initialize: ' + error.message, 'error');
console.error('Initialization error:', error);
}
}
// Run sloccount using REAL sloccount Perl scripts and WASM counters
// Run sloccount using REAL sloccount Perl scripts and WASM counters
async function runSloccount(files, salary = 56286) {
try {
// Map extensions to counter scripts and whether they need WASM
const extToCounter = {
'py': { counter: 'python_count', type: 'perl', lang: 'Python' },
'rb': { counter: 'ruby_count', type: 'perl', lang: 'Ruby' },
'pl': { counter: 'perl_count', type: 'perl', lang: 'Perl' },
'pm': { counter: 'perl_count', type: 'perl', lang: 'Perl' },
'sh': { counter: 'sh_count', type: 'wasm', lang: 'Shell' },
'bash': { counter: 'sh_count', type: 'wasm', lang: 'Shell' },
'js': { counter: 'javascript_count', type: 'wasm', lang: 'JavaScript' },
'ts': { counter: 'javascript_count', type: 'wasm', lang: 'TypeScript' },
'java': { counter: 'generic_count', type: 'wasm', lang: 'Java' },
'c': { counter: 'generic_count', type: 'wasm', lang: 'C' },
'h': { counter: 'generic_count', type: 'wasm', lang: 'C' },
'cpp': { counter: 'generic_count', type: 'wasm', lang: 'C++' },
'cc': { counter: 'generic_count', type: 'wasm', lang: 'C++' },
'cxx': { counter: 'generic_count', type: 'wasm', lang: 'C++' },
'hpp': { counter: 'generic_count', type: 'wasm', lang: 'C++' },
'go': { counter: 'go_count', type: 'perl', lang: 'Go' },
'rs': { counter: 'rust_count', type: 'perl', lang: 'Rust' },
'php': { counter: 'generic_count', type: 'wasm', lang: 'PHP' },
'sql': { counter: 'sql_count', type: 'perl', lang: 'SQL' },
// Modern languages (post-2001)
'kt': { counter: 'kotlin_count', type: 'perl', lang: 'Kotlin' },
'kts': { counter: 'kotlin_count', type: 'perl', lang: 'Kotlin' },
'swift': { counter: 'swift_count', type: 'perl', lang: 'Swift' },
'dart': { counter: 'dart_count', type: 'perl', lang: 'Dart' },
'scala': { counter: 'scala_count', type: 'perl', lang: 'Scala' },
'groovy': { counter: 'groovy_count', type: 'perl', lang: 'Groovy' },
'ex': { counter: 'elixir_count', type: 'perl', lang: 'Elixir' },
'exs': { counter: 'elixir_count', type: 'perl', lang: 'Elixir' },
'jl': { counter: 'julia_count', type: 'perl', lang: 'Julia' },
'fs': { counter: 'fsharp_count', type: 'perl', lang: 'F#' },
'fsx': { counter: 'fsharp_count', type: 'perl', lang: 'F#' },
};
// Group files by counter and language
const filesByCounter = {};
for (const file of files) {
const match = file.filename.match(/\.([^.]+)$/);
if (!match) continue;
const ext = match[1].toLowerCase();
const counterInfo = extToCounter[ext];
if (!counterInfo) continue;
const key = `${counterInfo.type}:${counterInfo.counter}:${counterInfo.lang}`;
if (!filesByCounter[key]) {
filesByCounter[key] = {
type: counterInfo.type,
counter: counterInfo.counter,
lang: counterInfo.lang,
files: []
};
}
filesByCounter[key].files.push(file);
}
const langStats = {};
let totalLines = 0;
// Process each counter group
for (const key in filesByCounter) {
const group = filesByCounter[key];
if (group.type === 'perl') {
// Run Perl counter script
const script = window.counterScripts[group.counter];
if (!script) {
console.warn(`Counter script ${group.counter} not found`);
continue;
}
// Write files to VFS
const filePaths = [];
for (const file of group.files) {
// Use just the basename to avoid directory issues
const basename = file.filename.split('/').pop();
const path = `/tmp/${basename}`;
// Store content in window for Perl to access
window._tempFileContent = file.content;
Perl.eval(`
use WebPerl qw/js/;
use File::Path qw(make_path);
my $path = '${path}';
my $content = js('window')->{_tempFileContent};
# Create parent directories if needed
if ($path =~ m{^(.+)/[^/]+$}) {
make_path($1);
}
open(my $fh, '>', $path) or die "Cannot write $path: $!";
print $fh $content;
close($fh);
`);
filePaths.push(path);
}
window._tempFileContent = null;
// Run counter and capture output
window.perlCounterOutput = '';
Perl.eval(`
use warnings;
use WebPerl qw/js/;
my $script = js('window')->{counterScripts}{'${group.counter}'};
@ARGV = (${filePaths.map(p => `'${p}'`).join(', ')});
my $output = '';
open(my $stdout_fh, '>', \\$output) or die "Cannot redirect: $!";
select $stdout_fh;
eval $script;
if ($@) {
$output .= "ERROR: $@";
}
select STDOUT;
close($stdout_fh);
js('window')->{perlCounterOutput} = $output;
`);
// Parse output
const output = window.perlCounterOutput;
const lines = output.split('\n');
let groupLines = 0;
let groupFiles = 0;
for (const line of lines) {
if (line.trim() && !line.startsWith('Total:')) {
const match = line.match(/^(\d+)\s+/);
if (match) {
groupLines += parseInt(match[1]);
groupFiles++;
}
}
}
if (!langStats[group.lang]) {
langStats[group.lang] = { lines: 0, files: 0 };
}
langStats[group.lang].lines += groupLines;
langStats[group.lang].files += groupFiles;
totalLines += groupLines;
} else if (group.type === 'wasm') {
// Run WASM c_count
const CCount = window.CCountModule;
if (!CCount) {
console.warn('c_count WASM module not loaded');
continue;
}
// Write files to WASM VFS
const filePaths = [];
for (const file of group.files) {
// Use just the basename to avoid directory issues
const basename = file.filename.split('/').pop();
const path = `/tmp/${basename}`;
CCount.FS.writeFile(path, file.content);
filePaths.push(path);
}
// Clear output and run
window.wasmOutput = [];
CCount.callMain(filePaths);
// Parse output
const output = window.wasmOutput.join('\n');
const lines = output.split('\n');
let groupLines = 0;
let groupFiles = 0;
for (const line of lines) {
if (line.trim() && !line.startsWith('Total:')) {
const match = line.match(/^(\d+)\s+/);
if (match) {
groupLines += parseInt(match[1]);
groupFiles++;
}
}
}
if (!langStats[group.lang]) {
langStats[group.lang] = { lines: 0, files: 0 };
}
langStats[group.lang].lines += groupLines;
langStats[group.lang].files += groupFiles;
totalLines += groupLines;
}
}
// Calculate COCOMO using editable values
const overheadCoeff = parseFloat(document.getElementById('overhead-input')?.value || 2.4);
const overheadMultiplier = parseFloat(document.getElementById('overhead-multiplier-input')?.value || 2.4);
const kloc = totalLines / 1000.0;
const effortMonths = overheadCoeff * Math.pow(kloc, 1.05);
const personYears = effortMonths / 12.0;
const totalCost = personYears * salary * overheadMultiplier;
const scheduleMonths = 2.5 * Math.pow(effortMonths, 0.38);
// Format results
const results = [];
for (const lang in langStats) {
results.push({
language: lang,
lines: langStats[lang].lines,
files: langStats[lang].files
});
}
results.cocomo = {
effort: personYears,
cost: totalCost,
schedule: scheduleMonths
};
return results;
} catch (error) {
console.error('runSloccount error:', error);
throw new Error('Failed to run sloccount: ' + error.message);
}
}
// Analyze pasted code
async function analyzePastedCode() {
const code = codeInput.value.trim();
const filename = filenameInput.value.trim();
if (!code) {
showStatus('Please paste some code to analyze', 'error');
return;
}
if (!filename) {
showStatus('Please provide a filename to detect the language', 'error');
return;
}
try {
analyzePasteBtn.disabled = true;
showStatus('Analyzing code with Perl sloccount...', 'info');
const files = [{ filename: filename, content: code }];
const salary = parseInt(getSalaryInput().value) || 56286;
const results = await runSloccount(files, salary);
currentFiles = files; // Store for recalculation
displayResults(results);
showStatus('Analysis complete!', 'success');
setTimeout(hideStatus, 3000);
} catch (error) {
showStatus('Analysis failed: ' + error.message, 'error');
console.error('Analysis error:', error);
} finally {
analyzePasteBtn.disabled = false;
}
}
// Analyze GitHub repository
async function analyzeGitHubRepo() {
let repoUrl = repoInput.value.trim();
if (!repoUrl) {
showStatus('Please provide a GitHub repository URL or owner/repo', 'error');
return;
}
let owner, repo;
// Try to parse as owner/repo shorthand first
const shorthandMatch = repoUrl.match(/^([^\/\s]+)\/([^\/\s]+)$/);
if (shorthandMatch) {
owner = shorthandMatch[1];
repo = shorthandMatch[2].replace('.git', '');
} else {
// Parse as full GitHub URL
const urlMatch = repoUrl.match(/github\.com\/([^\/]+)\/([^\/]+)/);
if (!urlMatch) {
showStatus('Invalid format. Use: owner/repo or https://github.com/owner/repo', 'error');
return;
}
owner = urlMatch[1];
repo = urlMatch[2].replace('.git', '');
}
try {
analyzeRepoBtn.disabled = true;
// Update URL bar with ?repo= parameter
const url = new URL(window.location);
url.searchParams.set('repo', repoUrl);
history.replaceState(null, '', url);
showStatus('Fetching repository information from GitHub API...', 'info');
// First, get the repository info to determine the default branch
const repoInfoUrl = `https://api.github.com/repos/${owner}/${repo}`;
const repoInfoResponse = await fetch(repoInfoUrl);
if (!repoInfoResponse.ok) {
if (repoInfoResponse.status === 404) {
throw new Error('Repository not found. Make sure the repository exists and is public.');
} else if (repoInfoResponse.status === 403) {
throw new Error('API rate limit exceeded. Please try again later.');
}
throw new Error(`Failed to fetch repository info: ${repoInfoResponse.statusText}`);
}
const repoInfo = await repoInfoResponse.json();
const defaultBranch = repoInfo.default_branch || 'main';
showStatus('Fetching repository tree from GitHub API...', 'info');
// Use GitHub Trees API to get all files
const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${defaultBranch}?recursive=1`;
const treeResponse = await fetch(treeUrl);
if (!treeResponse.ok) {
if (treeResponse.status === 404) {
throw new Error('Repository tree not found. Make sure the repository exists and is public.');
} else if (treeResponse.status === 403) {
throw new Error('API rate limit exceeded. Please try again later.');
}
throw new Error(`Failed to fetch repository tree: ${treeResponse.statusText}`);
}
const treeData = await treeResponse.json();
// Check if the tree was truncated by GitHub
if (treeData.truncated) {
const zipUrl = `https://github.com/${owner}/${repo}/archive/refs/heads/${defaultBranch}.zip`;
showStatus(`⚠️ This repository is too large and the GitHub API truncated the file list. Please download the full repository as a ZIP file and use the "Upload ZIP" tab instead: <a href="${zipUrl}" style="color: #004085; text-decoration: underline;">${zipUrl}</a>`, 'error', true);
return; // Stop processing - user must use ZIP upload
}
// Filter for code files only
const codeExtensions = /\.(c|h|cpp|cc|cxx|hpp|py|java|js|ts|rb|pl|pm|php|go|rs|cs|sh|bash|html|css|sql|r|swift|kt|kts|scala|lua|vim|dart|groovy|ex|exs|jl|fs|fsx)$/i;
const codeFiles = treeData.tree.filter(item =>
item.type === 'blob' && codeExtensions.test(item.path)
);
if (codeFiles.length === 0) {
throw new Error('No code files found in repository');
}
showStatus(`Fetching ${codeFiles.length} code files...`, 'info');
// Fetch files in batches to avoid overwhelming the browser
const files = [];
const batchSize = 10;
for (let i = 0; i < codeFiles.length; i += batchSize) {
const batch = codeFiles.slice(i, i + batchSize);
const batchPromises = batch.map(async (file) => {
try {
// Use raw.githubusercontent.com which has permissive CORS
const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${defaultBranch}/${file.path}`;
const response = await fetch(rawUrl);
if (response.ok) {
const content = await response.text();
return { filename: file.path, content: content };
}
return null;
} catch (error) {
console.warn(`Failed to fetch ${file.path}:`, error);
return null;
}
});
const batchResults = await Promise.all(batchPromises);
files.push(...batchResults.filter(f => f !== null));
// Update progress
const progress = Math.min(i + batchSize, codeFiles.length);
showStatus(`Fetched ${progress}/${codeFiles.length} files...`, 'info');
}
if (files.length === 0) {
throw new Error('Failed to fetch any code files from repository');
}
showStatus(`Analyzing ${files.length} files with Perl sloccount...`, 'info');
const salary = parseInt(getSalaryInput().value) || 56286;
const results = await runSloccount(files, salary);
currentFiles = files; // Store for recalculation
displayResults(results);
showStatus('Analysis complete!', 'success');
setTimeout(hideStatus, 3000);
} catch (error) {
showStatus('Analysis failed: ' + error.message, 'error');
console.error('Analysis error:', error);
} finally {
analyzeRepoBtn.disabled = false;
}
}
// Analyze uploaded ZIP file
let zipAnalysisInProgress = false;
async function analyzeZipFile() {
if (zipAnalysisInProgress) {
console.warn('Analysis already in progress, ignoring click');
return;
}
zipAnalysisInProgress = true;
const fileInput = zipInput.files[0];
if (!fileInput) {
showStatus('Please select a ZIP file to upload', 'error');
zipAnalysisInProgress = false;
return;
}
if (!fileInput.name.endsWith('.zip')) {
showStatus('Please upload a ZIP file', 'error');
zipAnalysisInProgress = false;
return;