-
-
Notifications
You must be signed in to change notification settings - Fork 245
/
formatters.go
1348 lines (1168 loc) · 40.2 KB
/
formatters.go
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
// SPDX-License-Identifier: MIT OR Unlicense
package processor
import (
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/mattn/go-runewidth"
glanguage "golang.org/x/text/language"
gmessage "golang.org/x/text/message"
"gopkg.in/yaml.v2"
)
var tabularShortBreak = "───────────────────────────────────────────────────────────────────────────────\n"
var tabularShortBreakCi = "-------------------------------------------------------------------------------\n"
var tabularShortFormatHead = "%-20s %9s %9s %8s %9s %8s %10s\n"
var tabularShortFormatBody = "%-20s %9d %9d %8d %9d %8d %10d\n"
var tabularShortFormatFile = "%s %9d %8d %9d %8d %10d\n"
var shortFormatFileTruncate = 29
var shortNameTruncate = 20
var tabularShortFormatHeadNoComplexity = "%-22s %11s %11s %10s %11s %9s\n"
var tabularShortFormatBodyNoComplexity = "%-22s %11d %11d %10d %11d %9d\n"
var tabularShortFormatFileNoComplexity = "%s %11d %10d %11d %9d\n"
var longNameTruncate = 22
var tabularWideBreak = "─────────────────────────────────────────────────────────────────────────────────────────────────────────────\n"
var tabularWideBreakCi = "-------------------------------------------------------------------------------------------------------------\n"
var tabularWideFormatHead = "%-33s %9s %9s %8s %9s %8s %10s %16s\n"
var tabularWideFormatBody = "%-33s %9d %9d %8d %9d %8d %10d %16.2f\n"
var tabularWideFormatFile = "%s %9d %8d %9d %8d %10d %16.2f\n"
var wideFormatFileTruncate = 42
var openMetricsMetadata = `# TYPE scc_files count
# HELP scc_files Number of sourcecode files.
# TYPE scc_lines count
# HELP scc_lines Number of lines.
# TYPE scc_code count
# HELP scc_code Number of lines of actual code.
# TYPE scc_comments count
# HELP scc_comments Number of comments.
# TYPE scc_blanks count
# HELP scc_blanks Number of blank lines.
# TYPE scc_complexity count
# HELP scc_complexity Code complexity.
# TYPE scc_bytes count
# UNIT scc_bytes bytes
# HELP scc_bytes Size in bytes.
`
var openMetricsSummaryRecordFormat = "scc_%s{language=\"%s\"} %d\n"
var openMetricsFileRecordFormat = "scc_%s{language=\"%s\",file=\"%s\"} %d\n"
func sortSummaryFiles(summary *LanguageSummary) {
switch {
case SortBy == "name" || SortBy == "names" || SortBy == "language" || SortBy == "languages":
sort.Slice(summary.Files, func(i, j int) bool {
return strings.Compare(summary.Files[i].Location, summary.Files[j].Location) < 0
})
case SortBy == "line" || SortBy == "lines":
sort.Slice(summary.Files, func(i, j int) bool {
return summary.Files[i].Lines > summary.Files[j].Lines
})
case SortBy == "blank" || SortBy == "blanks":
sort.Slice(summary.Files, func(i, j int) bool {
return summary.Files[i].Blank > summary.Files[j].Blank
})
case SortBy == "code" || SortBy == "codes":
sort.Slice(summary.Files, func(i, j int) bool {
return summary.Files[i].Code > summary.Files[j].Code
})
case SortBy == "comment" || SortBy == "comments":
sort.Slice(summary.Files, func(i, j int) bool {
return summary.Files[i].Comment > summary.Files[j].Comment
})
case SortBy == "complexity" || SortBy == "complexitys":
sort.Slice(summary.Files, func(i, j int) bool {
return summary.Files[i].Complexity > summary.Files[j].Complexity
})
default:
sort.Slice(summary.Files, func(i, j int) bool {
return summary.Files[i].Lines > summary.Files[j].Lines
})
}
}
// LanguageSummary to generate output like cloc
type languageSummaryCloc struct {
Name string `yaml:"name"`
Code int64 `yaml:"code"`
Comment int64 `yaml:"comment"`
Blank int64 `yaml:"blank"`
Count int64 `yaml:"nFiles"`
}
type summaryStruct struct {
Code int64 `yaml:"code"`
Comment int64 `yaml:"comment"`
Blank int64 `yaml:"blank"`
Count int64 `yaml:"nFiles"`
}
type headerStruct struct {
Url string `yaml:"url"`
Version string `yaml:"version"`
ElapsedSeconds float64 `yaml:"elapsed_seconds"`
NFiles int64 `yaml:"n_files"`
NLines int64 `yaml:"n_lines"`
FilesPerSecond float64 `yaml:"files_per_second"`
LinesPerSecond float64 `yaml:"lines_per_second"`
}
type languageReportStart struct {
Header headerStruct
}
type languageReportEnd struct {
Sum summaryStruct `yaml:"SUM"`
}
func getTabularShortBreak() string {
if Ci {
return tabularShortBreakCi
}
return tabularShortBreak
}
func getTabularWideBreak() string {
if Ci {
return tabularWideBreakCi
}
return tabularWideBreak
}
func toClocYAML(input chan *FileJob) string {
startTime := makeTimestampMilli()
languages := map[string]languageSummaryCloc{}
var sumFiles, sumLines, sumCode, sumComment, sumBlank, sumComplexity int64 = 0, 0, 0, 0, 0, 0
for res := range input {
sumFiles++
sumLines += res.Lines
sumCode += res.Code
sumComment += res.Comment
sumBlank += res.Blank
sumComplexity += res.Complexity
_, ok := languages[res.Language]
if !ok {
languages[res.Language] = languageSummaryCloc{
Name: res.Language,
Code: res.Code,
Comment: res.Comment,
Blank: res.Blank,
Count: 1,
}
} else {
tmp := languages[res.Language]
languages[res.Language] = languageSummaryCloc{
Name: res.Language,
Code: tmp.Code + res.Code,
Comment: tmp.Comment + res.Comment,
Blank: tmp.Blank + res.Blank,
Count: tmp.Count + 1,
}
}
}
es := float64(makeTimestampMilli()-startTimeMilli) * float64(0.001)
header := headerStruct{
Url: "https://github.com/boyter/scc/",
Version: Version,
NFiles: sumFiles,
NLines: sumLines,
ElapsedSeconds: es,
FilesPerSecond: float64(float64(sumFiles) / es),
LinesPerSecond: float64(float64(sumLines) / es),
}
summary := summaryStruct{
Blank: sumBlank,
Comment: sumComment,
Code: sumCode,
Count: sumFiles,
}
reportStart := languageReportStart{
Header: header,
}
reportEnd := languageReportEnd{
Sum: summary,
}
reportYaml, _ := yaml.Marshal(reportStart)
sumYaml, _ := yaml.Marshal(reportEnd)
languageYaml, _ := yaml.Marshal(languages)
yamlString := "# https://github.com/boyter/scc/\n" + string(reportYaml) + string(languageYaml) + string(sumYaml)
if Debug {
printDebug(fmt.Sprintf("milliseconds to build formatted string: %d", makeTimestampMilli()-startTime))
}
return yamlString
}
func toJSON(input chan *FileJob) string {
startTime := makeTimestampMilli()
language := aggregateLanguageSummary(input)
language = sortLanguageSummary(language)
jsonString, _ := json.Marshal(language)
if Debug {
printDebug(fmt.Sprintf("milliseconds to build formatted string: %d", makeTimestampMilli()-startTime))
}
return string(jsonString)
}
func toCSV(input chan *FileJob) string {
if Files {
return toCSVFiles(input)
}
return toCSVSummary(input)
}
func toCSVSummary(input chan *FileJob) string {
language := aggregateLanguageSummary(input)
language = sortLanguageSummary(language)
records := [][]string{}
for _, result := range language {
records = append(records, []string{
result.Name,
fmt.Sprint(result.Lines),
fmt.Sprint(result.Code),
fmt.Sprint(result.Comment),
fmt.Sprint(result.Blank),
fmt.Sprint(result.Complexity),
fmt.Sprint(result.Bytes)})
}
// Cater for the common case of adding plural even for those options that don't make sense
// as its quite common for those who English is not a first language to make a simple mistake
switch {
case SortBy == "name" || SortBy == "names" || SortBy == "language" || SortBy == "languages":
sort.Slice(records, func(i, j int) bool {
return strings.Compare(records[i][0], records[j][0]) < 0
})
case SortBy == "line" || SortBy == "lines":
sort.Slice(records, func(i, j int) bool {
i1, _ := strconv.ParseInt(records[i][1], 10, 64)
i2, _ := strconv.ParseInt(records[j][1], 10, 64)
return i1 > i2
})
case SortBy == "blank" || SortBy == "blanks":
sort.Slice(records, func(i, j int) bool {
i1, _ := strconv.ParseInt(records[i][4], 10, 64)
i2, _ := strconv.ParseInt(records[j][4], 10, 64)
return i1 > i2
})
case SortBy == "code" || SortBy == "codes":
sort.Slice(records, func(i, j int) bool {
i1, _ := strconv.ParseInt(records[i][2], 10, 64)
i2, _ := strconv.ParseInt(records[j][2], 10, 64)
return i1 > i2
})
case SortBy == "comment" || SortBy == "comments":
sort.Slice(records, func(i, j int) bool {
i1, _ := strconv.ParseInt(records[i][3], 10, 64)
i2, _ := strconv.ParseInt(records[j][3], 10, 64)
return i1 > i2
})
case SortBy == "complexity" || SortBy == "complexitys":
sort.Slice(records, func(i, j int) bool {
i1, _ := strconv.ParseInt(records[i][5], 10, 64)
i2, _ := strconv.ParseInt(records[j][5], 10, 64)
return i1 > i2
})
case SortBy == "byte" || SortBy == "bytes":
sort.Slice(records, func(i, j int) bool {
i1, _ := strconv.ParseInt(records[i][6], 10, 64)
i2, _ := strconv.ParseInt(records[j][6], 10, 64)
return i1 > i2
})
default:
sort.Slice(records, func(i, j int) bool {
i1, _ := strconv.ParseInt(records[i][1], 10, 64)
i2, _ := strconv.ParseInt(records[j][1], 10, 64)
return i1 > i2
})
}
recordsEnd := [][]string{{
"Language",
"Lines",
"Code",
"Comments",
"Blanks",
"Complexity",
"Bytes"},
}
recordsEnd = append(recordsEnd, records...)
b := &bytes.Buffer{}
w := csv.NewWriter(b)
_ = w.WriteAll(recordsEnd)
w.Flush()
return b.String()
}
func toCSVFiles(input chan *FileJob) string {
records := [][]string{}
for result := range input {
records = append(records, []string{
result.Language,
result.Location,
result.Filename,
fmt.Sprint(result.Lines),
fmt.Sprint(result.Code),
fmt.Sprint(result.Comment),
fmt.Sprint(result.Blank),
fmt.Sprint(result.Complexity),
fmt.Sprint(result.Bytes)})
}
// Cater for the common case of adding plural even for those options that don't make sense
// as its quite common for those who English is not a first language to make a simple mistake
switch {
case SortBy == "name" || SortBy == "names":
sort.Slice(records, func(i, j int) bool {
return strings.Compare(records[i][2], records[j][2]) < 0
})
case SortBy == "language" || SortBy == "languages":
sort.Slice(records, func(i, j int) bool {
return strings.Compare(records[i][0], records[j][0]) < 0
})
case SortBy == "line" || SortBy == "lines":
sort.Slice(records, func(i, j int) bool {
i1, _ := strconv.ParseInt(records[i][3], 10, 64)
i2, _ := strconv.ParseInt(records[j][3], 10, 64)
return i1 > i2
})
case SortBy == "blank" || SortBy == "blanks":
sort.Slice(records, func(i, j int) bool {
i1, _ := strconv.ParseInt(records[i][6], 10, 64)
i2, _ := strconv.ParseInt(records[j][6], 10, 64)
return i1 > i2
})
case SortBy == "code" || SortBy == "codes":
sort.Slice(records, func(i, j int) bool {
i1, _ := strconv.ParseInt(records[i][4], 10, 64)
i2, _ := strconv.ParseInt(records[j][4], 10, 64)
return i1 > i2
})
case SortBy == "comment" || SortBy == "comments":
sort.Slice(records, func(i, j int) bool {
i1, _ := strconv.ParseInt(records[i][5], 10, 64)
i2, _ := strconv.ParseInt(records[j][5], 10, 64)
return i1 > i2
})
case SortBy == "complexity" || SortBy == "complexitys":
sort.Slice(records, func(i, j int) bool {
i1, _ := strconv.ParseInt(records[i][7], 10, 64)
i2, _ := strconv.ParseInt(records[j][7], 10, 64)
return i1 > i2
})
case SortBy == "byte" || SortBy == "bytes":
sort.Slice(records, func(i, j int) bool {
i1, _ := strconv.ParseInt(records[i][8], 10, 64)
i2, _ := strconv.ParseInt(records[j][8], 10, 64)
return i1 > i2
})
default:
sort.Slice(records, func(i, j int) bool {
return records[i][2] > records[j][2]
})
}
recordsEnd := [][]string{{
"Language",
"Location",
"Filename",
"Lines",
"Code",
"Comments",
"Blanks",
"Complexity",
"Bytes"},
}
recordsEnd = append(recordsEnd, records...)
b := &bytes.Buffer{}
w := csv.NewWriter(b)
_ = w.WriteAll(recordsEnd)
w.Flush()
return b.String()
}
func toOpenMetrics(input chan *FileJob) string {
if Files {
return toOpenMetricsFiles(input)
}
return toOpenMetricsSummary(input)
}
func toOpenMetricsSummary(input chan *FileJob) string {
language := aggregateLanguageSummary(input)
language = sortLanguageSummary(language)
var sb strings.Builder
sb.WriteString(openMetricsMetadata)
for _, result := range language {
sb.WriteString(fmt.Sprintf(openMetricsSummaryRecordFormat, "files", result.Name, result.Count))
sb.WriteString(fmt.Sprintf(openMetricsSummaryRecordFormat, "lines", result.Name, result.Lines))
sb.WriteString(fmt.Sprintf(openMetricsSummaryRecordFormat, "code", result.Name, result.Code))
sb.WriteString(fmt.Sprintf(openMetricsSummaryRecordFormat, "comments", result.Name, result.Comment))
sb.WriteString(fmt.Sprintf(openMetricsSummaryRecordFormat, "blanks", result.Name, result.Blank))
sb.WriteString(fmt.Sprintf(openMetricsSummaryRecordFormat, "complexity", result.Name, result.Complexity))
sb.WriteString(fmt.Sprintf(openMetricsSummaryRecordFormat, "bytes", result.Name, result.Bytes))
}
return sb.String()
}
func toOpenMetricsFiles(input chan *FileJob) string {
var sb strings.Builder
sb.WriteString(openMetricsMetadata)
for file := range input {
var filename = strings.ReplaceAll(file.Location, "\\", "\\\\")
sb.WriteString(fmt.Sprintf(openMetricsFileRecordFormat, "lines", file.Language, filename, file.Lines))
sb.WriteString(fmt.Sprintf(openMetricsFileRecordFormat, "code", file.Language, filename, file.Code))
sb.WriteString(fmt.Sprintf(openMetricsFileRecordFormat, "comments", file.Language, filename, file.Comment))
sb.WriteString(fmt.Sprintf(openMetricsFileRecordFormat, "blanks", file.Language, filename, file.Blank))
sb.WriteString(fmt.Sprintf(openMetricsFileRecordFormat, "complexity", file.Language, filename, file.Complexity))
sb.WriteString(fmt.Sprintf(openMetricsFileRecordFormat, "bytes", file.Language, filename, file.Bytes))
}
sb.WriteString("# EOF")
return sb.String()
}
// For very large repositories CSV stream can be used which prints results out as they come in
// with the express idea of lowering memory usage, see https://github.com/boyter/scc/issues/210 for
// the background on why this might be needed
func toCSVStream(input chan *FileJob) string {
fmt.Println("Language,Location,Filename,Lines,Code,Comments,Blanks,Complexity,Bytes")
for result := range input {
fmt.Println(fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s",
result.Language,
result.Location,
result.Filename,
fmt.Sprint(result.Lines),
fmt.Sprint(result.Code),
fmt.Sprint(result.Comment),
fmt.Sprint(result.Blank),
fmt.Sprint(result.Complexity),
fmt.Sprint(result.Bytes),
))
}
return ""
}
func toHtml(input chan *FileJob) string {
return `<html lang="en"><head><meta charset="utf-8" /><title>scc html output</title><style>table { border-collapse: collapse; }td, th { border: 1px solid #999; padding: 0.5rem; text-align: left;}</style></head><body>` +
toHtmlTable(input) +
`</body></html>`
}
func toHtmlTable(input chan *FileJob) string {
languages := map[string]LanguageSummary{}
var sumFiles, sumLines, sumCode, sumComment, sumBlank, sumComplexity, sumBytes int64 = 0, 0, 0, 0, 0, 0, 0
for res := range input {
sumFiles++
sumLines += res.Lines
sumCode += res.Code
sumComment += res.Comment
sumBlank += res.Blank
sumComplexity += res.Complexity
sumBytes += res.Bytes
_, ok := languages[res.Language]
if !ok {
files := []*FileJob{}
files = append(files, res)
languages[res.Language] = LanguageSummary{
Name: res.Language,
Lines: res.Lines,
Code: res.Code,
Comment: res.Comment,
Blank: res.Blank,
Complexity: res.Complexity,
Count: 1,
Files: files,
Bytes: res.Bytes,
}
} else {
tmp := languages[res.Language]
files := append(tmp.Files, res)
languages[res.Language] = LanguageSummary{
Name: res.Language,
Lines: tmp.Lines + res.Lines,
Code: tmp.Code + res.Code,
Comment: tmp.Comment + res.Comment,
Blank: tmp.Blank + res.Blank,
Complexity: tmp.Complexity + res.Complexity,
Count: tmp.Count + 1,
Files: files,
Bytes: tmp.Bytes + res.Bytes,
}
}
}
language := []LanguageSummary{}
for _, summary := range languages {
language = append(language, summary)
}
language = sortLanguageSummary(language)
var str strings.Builder
str.WriteString(`<table id="scc-table">
<thead><tr>
<th>Language</th>
<th>Files</th>
<th>Lines</th>
<th>Blank</th>
<th>Comment</th>
<th>Code</th>
<th>Complexity</th>
<th>Bytes</th>
</tr></thead>
<tbody>`)
for _, r := range language {
str.WriteString(fmt.Sprintf(`<tr>
<th>%s</th>
<th>%d</th>
<th>%d</th>
<th>%d</th>
<th>%d</th>
<th>%d</th>
<th>%d</th>
<th>%d</th>
</tr>`, r.Name, len(r.Files), r.Lines, r.Blank, r.Comment, r.Code, r.Complexity, r.Bytes))
if Files {
sortSummaryFiles(&r)
for _, res := range r.Files {
str.WriteString(fmt.Sprintf(`<tr>
<td>%s</td>
<td></td>
<td>%d</td>
<td>%d</td>
<td>%d</td>
<td>%d</td>
<td>%d</td>
<td>%d</td>
</tr>`, res.Location, res.Lines, res.Blank, res.Comment, res.Code, res.Complexity, res.Bytes))
}
}
}
str.WriteString(fmt.Sprintf(`</tbody>
<tfoot><tr>
<th>Total</th>
<th>%d</th>
<th>%d</th>
<th>%d</th>
<th>%d</th>
<th>%d</th>
<th>%d</th>
<th>%d</th>
</tr></tfoot>
</table>`, sumFiles, sumLines, sumBlank, sumComment, sumCode, sumComplexity, sumBytes))
return str.String()
}
func toSqlInsert(input chan *FileJob) string {
var str strings.Builder
projectName := SQLProject
if projectName == "" {
projectName = strings.Join(DirFilePaths, ",")
}
str.WriteString("\nbegin transaction;")
count := 0
for res := range input {
count++
dir, _ := filepath.Split(res.Location)
str.WriteString(fmt.Sprintf("\ninsert into t values('%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, %d);",
projectName, res.Language, res.Location, dir, res.Filename, res.Bytes, res.Blank, res.Comment, res.Code, res.Complexity))
// every 1000 files commit and start a new transaction to avoid overloading
if count == 1000 {
str.WriteString("\ncommit;")
str.WriteString("\nbegin transaction;")
count = 0
}
}
if count != 1000 {
str.WriteString("\ncommit;")
}
currentTime := time.Now()
es := float64(makeTimestampMilli()-startTimeMilli) * 0.001
str.WriteString("\nbegin transaction;")
str.WriteString(fmt.Sprintf("\ninsert into metadata values('%s', '%s', %f);", currentTime.Format("2006-01-02 15:04:05"), projectName, es))
str.WriteString("\ncommit;")
return str.String()
}
func toSql(input chan *FileJob) string {
var str strings.Builder
str.WriteString(`create table metadata ( -- github.com/boyter/scc v ` + Version + `
timestamp text,
Project text,
elapsed_s real);
create table t (
Project text ,
Language text ,
File text ,
File_dirname text ,
File_basename text ,
nByte integer,
nBlank integer,
nComment integer,
nCode integer,
nComplexity integer );`)
str.WriteString(toSqlInsert(input))
return str.String()
}
func fileSummarize(input chan *FileJob) string {
if FormatMulti != "" {
return fileSummarizeMulti(input)
}
switch {
case More || strings.ToLower(Format) == "wide":
return fileSummarizeLong(input)
case strings.ToLower(Format) == "json":
return toJSON(input)
case strings.ToLower(Format) == "cloc-yaml" || strings.ToLower(Format) == "cloc-yml":
return toClocYAML(input)
case strings.ToLower(Format) == "csv":
return toCSV(input)
case strings.ToLower(Format) == "csv-stream":
return toCSVStream(input)
case strings.ToLower(Format) == "html":
return toHtml(input)
case strings.ToLower(Format) == "html-table":
return toHtmlTable(input)
case strings.ToLower(Format) == "sql":
return toSql(input)
case strings.ToLower(Format) == "sql-insert":
return toSqlInsert(input)
case strings.ToLower(Format) == "openmetrics":
return toOpenMetrics(input)
}
return fileSummarizeShort(input)
}
// Deals with the case of CI/CD where you might want to run with multiple outputs
// both to files and to stdout. Not the most efficient way to do it in terms of memory
// but seeing as the files are just summaries by this point it shouldn't be too bad
func fileSummarizeMulti(input chan *FileJob) string {
// collect all the results
var results []*FileJob
for res := range input {
results = append(results, res)
}
var str strings.Builder
// for each output pump the results into
for _, s := range strings.Split(FormatMulti, ",") {
t := strings.Split(s, ":")
if len(t) == 2 {
i := make(chan *FileJob, len(results))
for _, r := range results {
i <- r
}
close(i)
var val = ""
switch strings.ToLower(t[0]) {
case "tabular":
val = fileSummarizeShort(i)
case "wide":
val = fileSummarizeLong(i)
case "json":
val = toJSON(i)
case "cloc-yaml":
val = toClocYAML(i)
case "cloc-yml":
val = toClocYAML(i)
case "csv":
val = toCSV(i)
case "csv-stream":
val = toCSVStream(i)
// special case where we want to ignore writing to stdout ot disk as its already done
continue
case "html":
val = toHtml(i)
case "html-table":
val = toHtmlTable(i)
case "sql":
val = toSql(i)
case "sql-insert":
val = toSqlInsert(i)
case "openmetrics":
val = toOpenMetrics(i)
}
if t[1] == "stdout" {
str.WriteString(val)
str.WriteString("\n")
} else {
err := ioutil.WriteFile(t[1], []byte(val), 0600)
if err != nil {
fmt.Printf("%s unable to be written to for format %s: %s", t[1], t[0], err)
}
}
}
}
return str.String()
}
func fileSummarizeLong(input chan *FileJob) string {
var str strings.Builder
str.WriteString(getTabularWideBreak())
str.WriteString(fmt.Sprintf(tabularWideFormatHead, "Language", "Files", "Lines", "Blanks", "Comments", "Code", "Complexity", "Complexity/Lines"))
if !Files {
str.WriteString(getTabularWideBreak())
}
languages := map[string]LanguageSummary{}
var sumFiles, sumLines, sumCode, sumComment, sumBlank, sumComplexity, sumBytes int64 = 0, 0, 0, 0, 0, 0, 0
var sumWeightedComplexity float64
for res := range input {
sumFiles++
sumLines += res.Lines
sumCode += res.Code
sumComment += res.Comment
sumBlank += res.Blank
sumComplexity += res.Complexity
sumBytes += res.Bytes
var weightedComplexity float64
if res.Code != 0 {
weightedComplexity = (float64(res.Complexity) / float64(res.Code)) * 100
}
res.WeightedComplexity = weightedComplexity
sumWeightedComplexity += weightedComplexity
_, ok := languages[res.Language]
if !ok {
files := []*FileJob{}
files = append(files, res)
languages[res.Language] = LanguageSummary{
Name: res.Language,
Lines: res.Lines,
Code: res.Code,
Comment: res.Comment,
Blank: res.Blank,
Complexity: res.Complexity,
Count: 1,
WeightedComplexity: weightedComplexity,
Files: files,
}
} else {
tmp := languages[res.Language]
files := append(tmp.Files, res)
languages[res.Language] = LanguageSummary{
Name: res.Language,
Lines: tmp.Lines + res.Lines,
Code: tmp.Code + res.Code,
Comment: tmp.Comment + res.Comment,
Blank: tmp.Blank + res.Blank,
Complexity: tmp.Complexity + res.Complexity,
Count: tmp.Count + 1,
WeightedComplexity: tmp.WeightedComplexity + weightedComplexity,
Files: files,
}
}
}
language := []LanguageSummary{}
for _, summary := range languages {
language = append(language, summary)
}
// Cater for the common case of adding plural even for those options that don't make sense
// as its quite common for those who English is not a first language to make a simple mistake
switch {
case SortBy == "name" || SortBy == "names" || SortBy == "language" || SortBy == "languages":
sort.Slice(language, func(i, j int) bool {
return strings.Compare(language[i].Name, language[j].Name) < 0
})
case SortBy == "line" || SortBy == "lines":
sort.Slice(language, func(i, j int) bool {
return language[i].Lines > language[j].Lines
})
case SortBy == "blank" || SortBy == "blanks":
sort.Slice(language, func(i, j int) bool {
return language[i].Blank > language[j].Blank
})
case SortBy == "code" || SortBy == "codes":
sort.Slice(language, func(i, j int) bool {
return language[i].Code > language[j].Code
})
case SortBy == "comment" || SortBy == "comments":
sort.Slice(language, func(i, j int) bool {
return language[i].Comment > language[j].Comment
})
case SortBy == "complexity" || SortBy == "complexitys":
sort.Slice(language, func(i, j int) bool {
return language[i].Complexity > language[j].Complexity
})
default:
sort.Slice(language, func(i, j int) bool {
return language[i].Count > language[j].Count
})
}
startTime := makeTimestampMilli()
for _, summary := range language {
if Files {
str.WriteString(getTabularWideBreak())
}
trimmedName := summary.Name
if len(summary.Name) > longNameTruncate {
trimmedName = summary.Name[:longNameTruncate-1] + "…"
}
str.WriteString(fmt.Sprintf(tabularWideFormatBody, trimmedName, summary.Count, summary.Lines, summary.Blank, summary.Comment, summary.Code, summary.Complexity, summary.WeightedComplexity))
if Files {
sortSummaryFiles(&summary)
str.WriteString(getTabularWideBreak())
for _, res := range summary.Files {
tmp := unicodeAwareTrim(res.Location, wideFormatFileTruncate)
tmp = unicodeAwareRightPad(tmp, 43)
str.WriteString(fmt.Sprintf(tabularWideFormatFile, tmp, res.Lines, res.Blank, res.Comment, res.Code, res.Complexity, res.WeightedComplexity))
}
}
}
if Debug {
printDebug(fmt.Sprintf("milliseconds to build formatted string: %d", makeTimestampMilli()-startTime))
}
str.WriteString(getTabularWideBreak())
str.WriteString(fmt.Sprintf(tabularWideFormatBody, "Total", sumFiles, sumLines, sumBlank, sumComment, sumCode, sumComplexity, sumWeightedComplexity))
str.WriteString(getTabularWideBreak())
if !Cocomo {
if SLOCCountFormat {
calculateCocomoSLOCCount(sumCode, &str)
} else {
calculateCocomo(sumCode, &str)
}
}
if !Size {
calculateSize(sumBytes, &str)
str.WriteString(getTabularWideBreak())
}
return str.String()
}
// We need to trim the file display for tabular output formats which this does in a unicode aware way
// to avoid cutting bytes... note that it needs to be expanded to deal with longer display characters at some
// point in the future
func unicodeAwareTrim(tmp string, size int) string {
// iterate all the runes so we can cut off correctly and get the correct length
r := []rune(tmp)
if len(r) >= size {
for runewidth.StringWidth(tmp) > size {
// remove character one at a time till we get the length we want
tmp = string([]rune(tmp)[1:])
}
tmp = "~" + strings.TrimSpace(tmp)
}
return tmp
}
// Using %-30s in string format does not appear to be unicode aware with characters such as
// 文中 meaning the size is off... which is annoying, so we implement this ourselves to get it
// right
func unicodeAwareRightPad(tmp string, size int) string {
for runewidth.StringWidth(tmp) < size {
tmp += " "
}
return tmp
}
func fileSummarizeShort(input chan *FileJob) string {
var str strings.Builder
str.WriteString(getTabularShortBreak())
if !Complexity {
str.WriteString(fmt.Sprintf(tabularShortFormatHead, "Language", "Files", "Lines", "Blanks", "Comments", "Code", "Complexity"))
} else {
str.WriteString(fmt.Sprintf(tabularShortFormatHeadNoComplexity, "Language", "Files", "Lines", "Blanks", "Comments", "Code"))
}
if !Files {
str.WriteString(getTabularShortBreak())
}
languages := map[string]LanguageSummary{}
var sumFiles, sumLines, sumCode, sumComment, sumBlank, sumComplexity, sumBytes int64 = 0, 0, 0, 0, 0, 0, 0
for res := range input {
sumFiles++
sumLines += res.Lines
sumCode += res.Code
sumComment += res.Comment
sumBlank += res.Blank
sumComplexity += res.Complexity
sumBytes += res.Bytes
_, ok := languages[res.Language]
if !ok {
files := []*FileJob{}
files = append(files, res)
languages[res.Language] = LanguageSummary{
Name: res.Language,
Lines: res.Lines,
Code: res.Code,
Comment: res.Comment,
Blank: res.Blank,
Complexity: res.Complexity,
Count: 1,
Files: files,
}
} else {
tmp := languages[res.Language]
files := append(tmp.Files, res)
languages[res.Language] = LanguageSummary{
Name: res.Language,
Lines: tmp.Lines + res.Lines,
Code: tmp.Code + res.Code,