-
Notifications
You must be signed in to change notification settings - Fork 0
/
golc.go
1087 lines (902 loc) · 31.6 KB
/
golc.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
package main
import (
"archive/zip"
"bufio"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/briandowns/spinner"
"github.com/colussim/GoLC/assets"
"github.com/colussim/GoLC/pkg/goloc"
"github.com/colussim/GoLC/pkg/devops/getazure"
getbibucket "github.com/colussim/GoLC/pkg/devops/getbitbucket/v2"
getbibucketdc "github.com/colussim/GoLC/pkg/devops/getbitbucketdc"
"github.com/colussim/GoLC/pkg/devops/getgithub"
"github.com/colussim/GoLC/pkg/devops/getgitlab"
"github.com/colussim/GoLC/pkg/utils"
)
type OrganizationData struct {
Organization string `json:"Organization"`
TotalLinesOfCode string `json:"TotalLinesOfCode"`
LargestRepository string `json:"LargestRepository"`
LinesOfCodeLargestRepo string `json:"LinesOfCodeLargestRepo"`
DevOpsPlatform string `json:"DevOpsPlatform"`
NumberRepos int `json:"NumberRepos"`
}
type Repository struct {
ID int `json:"id"`
Name string `json:"name"`
DefaultBranch string `json:"default_branch"`
Path string `json:"path"`
}
type Project struct {
KEY string `json:"key"`
ID int `json:"id"`
Name string `json:"name"`
Public bool `json:"public"`
Type string `json:"type"`
Links Links `json:"links"`
}
type Links struct {
Self []SelfLink `json:"self"`
}
type SelfLink struct {
Href string `json:"href"`
}
type Config struct {
Platforms map[string]interface{} `json:"platforms"`
}
type Report struct {
TotalFiles int `json:",omitempty"`
TotalLines int
TotalBlankLines int
TotalComments int
TotalCodeLines int
Results interface{}
}
type Result struct {
TotalFiles int `json:"TotalFiles"`
TotalLines int `json:"TotalLines"`
TotalBlankLines int `json:"TotalBlankLines"`
TotalComments int `json:"TotalComments"`
TotalCodeLines int `json:"TotalCodeLines"`
Results []LanguageRes `json:"Results"`
}
type LanguageRes struct {
Language string `json:"Language"`
Files int `json:"Files"`
Lines int `json:"Lines"`
BlankLines int `json:"BlankLines"`
Comments int `json:"Comments"`
CodeLines int `json:"CodeLines"`
}
type RepoParams struct {
ProjectKey string
Namespace string
RepoSlug string
MainBranch string
PathToScan string
}
const errorMessageRepo = "\n❌ Error Analyse Repositories: "
const errorMessageDi = "\r❌ Error deleting Repository Directory: %v\n"
const errorMessageAnalyse = "\r❌ No Analysis performed...\n"
const errorMessageRepos = "Error Get Info Repositories in organization '%s' : '%s'"
const directoryconf = "/config"
var logFile *os.File
func OpenLogFile(filename string) error {
file, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
logFile = file
return nil
}
// CloseLogFile closes the log file.
func CloseLogFile() {
if logFile != nil {
logFile.Close()
}
}
// LogError writes an error message to the log file along with additional context information.
func LogError(message string, err error) {
if logFile != nil {
logFile.WriteString(fmt.Sprintf("[%s] ERROR: %s - %v\n", time.Now().Format(time.RFC3339), message, err))
}
}
// Check Exclusion File Exist
func getFileNameIfExists(filePath string) string {
_, err := os.Stat(filePath)
if err != nil {
if os.IsNotExist(err) {
//The file does not exist
return "0"
} else {
// Check file
fmt.Printf("❌ Error check file exclusion: %v\n", err)
return "0"
}
} else {
return filePath
}
}
// Load Config File
func LoadConfig(filename string) (Config, error) {
var config Config
// Lire le contenu du fichier de configuration
data, err := os.ReadFile(filename)
if err != nil {
return config, fmt.Errorf("❌ failed to read config file: %w", err)
}
if err := json.Unmarshal(data, &config); err != nil {
return config, fmt.Errorf("❌ failed to parse config JSON: %w", err)
}
return config, nil
}
// Parse Result Files in JSON Format
func parseJSONFile(filePath, reponame string) int {
file, err := os.ReadFile(filePath)
if err != nil {
fmt.Println("❌ Error reading file:", err)
}
var report Report
err = json.Unmarshal(file, &report)
if err != nil {
fmt.Println("❌ Error parsing JSON:", err)
}
return report.TotalCodeLines
}
// Create a Bakup File for Result directory
func createBackup(sourceDir, pwd string) error {
backupDir := filepath.Join(pwd, "Saves")
backupFilePath := generateBackupFilePath(sourceDir, backupDir)
if err := createBackupDirectory(backupDir); err != nil {
return err
}
backupFile, err := os.Create(backupFilePath)
if err != nil {
return fmt.Errorf("error creating backup file: %s", err)
}
defer backupFile.Close()
zipWriter := zip.NewWriter(backupFile)
defer zipWriter.Close()
if err := addFilesToBackup(sourceDir, zipWriter); err != nil {
return err
}
fmt.Println("✅ Backup created successfully:", backupFilePath)
return nil
}
// Generate Backup File Name
func generateBackupFilePath(sourceDir, backupDir string) string {
backupFileName := fmt.Sprintf("%s_%s.zip", filepath.Base(sourceDir), time.Now().Format("2006-01-02_15-04-05"))
return filepath.Join(backupDir, backupFileName)
}
// Create a backup Directory
func createBackupDirectory(backupDir string) error {
if _, err := os.Stat(backupDir); os.IsNotExist(err) {
if err := os.MkdirAll(backupDir, 0755); err != nil {
return fmt.Errorf("error creating backup directory: %s", err)
}
}
return nil
}
// Add Files in backup
func addFilesToBackup(sourceDir string, zipWriter *zip.Writer) error {
return filepath.Walk(sourceDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if path == sourceDir {
return nil
}
relPath, err := filepath.Rel(sourceDir, path)
if err != nil {
return err
}
if err := addFileToZip(path, relPath, info, zipWriter); err != nil {
return err
}
return nil
})
}
func addFileToZip(filePath, relPath string, fileInfo os.FileInfo, zipWriter *zip.Writer) error {
zipFile, err := zipWriter.Create(relPath)
if err != nil {
return err
}
if !fileInfo.IsDir() {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(zipFile, file)
if err != nil {
return err
}
}
return nil
}
// Generic function to analyze repositories
func AnalyseReposList(DestinationResult string, platformConfig map[string]interface{}, repolist interface{}, analyseRepoFunc func(project interface{}, DestinationResult string, platformConfig map[string]interface{}, spin *spinner.Spinner, results chan int, count *int)) (cpt int) {
fmt.Print("\n🔎 Analysis of Repos ...\n")
spin := spinner.New(spinner.CharSets[35], 100*time.Millisecond)
spin.Color("green", "bold")
messageF := ""
spin.FinalMSG = messageF
// Create a channel to receive results
results := make(chan int)
count := 1
if platformConfig["Multithreading"].(bool) {
if len(repolist.([]interface{})) > int(platformConfig["NumberWorkerRepos"].(float64)) {
// Launch goroutines in batches of X
X := int(platformConfig["Workers"].(float64))
batches := len(repolist.([]interface{})) / X
remainder := len(repolist.([]interface{})) % X
for i := 0; i < batches; i++ {
for j := i * X; j < (i+1)*X; j++ {
go analyseRepoFunc(repolist.([]interface{})[j], DestinationResult, platformConfig, spin, results, &count)
}
waitForWorkers(X, results)
}
// Launch remaining goroutines
for i := batches * X; i < batches*X+remainder; i++ {
go analyseRepoFunc(repolist.([]interface{})[i], DestinationResult, platformConfig, spin, results, &count)
}
waitForWorkers(remainder, results)
} else {
// Launch goroutines for each repo
for _, project := range repolist.([]interface{}) {
go analyseRepoFunc(project, DestinationResult, platformConfig, spin, results, &count)
}
waitForWorkers(len(repolist.([]interface{})), results)
}
} else {
// Without multithreading
for _, project := range repolist.([]interface{}) {
// Execute the analysis synchronously
analyseRepoFunc(project, DestinationResult, platformConfig, spin, results, &count)
}
}
return len(repolist.([]interface{}))
}
// Analysis functions for different repository types
// Analysis functions for Bitbucket Cloud
func analyseBitCRepo(project interface{}, DestinationResult string, platformConfig map[string]interface{}, spin *spinner.Spinner, results chan int, count *int) {
p := project.(getbibucket.ProjectBranch)
params := RepoParams{
ProjectKey: p.ProjectKey,
Namespace: "",
RepoSlug: p.RepoSlug,
MainBranch: p.MainBranch,
PathToScan: fmt.Sprintf("%s://x-token-auth:%s@%s/%s/%s.git", platformConfig["Protocol"].(string), platformConfig["AccessToken"].(string), platformConfig["Baseapi"].(string), platformConfig["Workspace"].(string), p.RepoSlug),
}
performRepoAnalysis(params, DestinationResult, spin, results, count)
}
// Analysis functions for Bitbucket DC
func analyseBitSRVRepo(project interface{}, DestinationResult string, platformConfig map[string]interface{}, trimmedURL string, spin *spinner.Spinner, results chan int, count *int) {
p := project.(getbibucketdc.ProjectBranch)
params := RepoParams{
ProjectKey: p.ProjectKey,
Namespace: "",
RepoSlug: p.RepoSlug,
MainBranch: p.MainBranch,
PathToScan: fmt.Sprintf("%s://%s:%s@%sscm/%s/%s.git", platformConfig["Protocol"].(string), platformConfig["Users"].(string), platformConfig["AccessToken"].(string), trimmedURL, p.ProjectKey, p.RepoSlug),
}
performRepoAnalysis(params, DestinationResult, spin, results, count)
}
// Analysis functions for GitHub
func analyseGithubRepo(project interface{}, DestinationResult string, platformConfig map[string]interface{}, spin *spinner.Spinner, results chan int, count *int) {
p := project.(getgithub.ProjectBranch)
params := RepoParams{
ProjectKey: p.Org,
Namespace: "",
RepoSlug: p.RepoSlug,
MainBranch: p.MainBranch,
PathToScan: fmt.Sprintf("%s://%s:x-oauth-basic@%s/%s/%s.git", platformConfig["Protocol"].(string), platformConfig["AccessToken"].(string), platformConfig["Baseapi"].(string), p.Org, p.RepoSlug),
}
performRepoAnalysis(params, DestinationResult, spin, results, count)
}
// Analysis functions for GitLab
func analyseGitlabRepo(project interface{}, DestinationResult string, platformConfig map[string]interface{}, spin *spinner.Spinner, results chan int, count *int) {
p := project.(getgitlab.ProjectBranch)
params := RepoParams{
ProjectKey: p.Org,
Namespace: p.Namespace,
RepoSlug: p.RepoSlug,
MainBranch: p.MainBranch,
PathToScan: fmt.Sprintf("%s://gitlab-ci-token:%s@%s/%s.git", platformConfig["Protocol"].(string), platformConfig["AccessToken"].(string), "gitlab.com", p.Namespace),
}
performRepoAnalysis(params, DestinationResult, spin, results, count)
}
func analyseAzurebRepo(project interface{}, DestinationResult string, platformConfig map[string]interface{}, spin *spinner.Spinner, results chan int, count *int) {
p := project.(getazure.ProjectBranch)
params := RepoParams{
ProjectKey: p.ProjectKey,
Namespace: "",
RepoSlug: p.RepoSlug,
MainBranch: p.MainBranch,
PathToScan: fmt.Sprintf("%s://%s@%s/%s/%s/%s/%s", platformConfig["Protocol"].(string), platformConfig["AccessToken"].(string), "dev.azure.com", platformConfig["Organization"].(string), p.ProjectKey, "_git", p.RepoSlug),
}
performRepoAnalysis(params, DestinationResult, spin, results, count)
}
// Perform repository analysis (common logic)
func performRepoAnalysis(params RepoParams, DestinationResult string, spin *spinner.Spinner, results chan int, count *int) {
var outputFileName = ""
if len(params.Namespace) > 0 {
outputFileName = fmt.Sprintf("Result_%s_%s", params.Namespace, params.MainBranch)
} else {
outputFileName = fmt.Sprintf("Result_%s_%s_%s", params.ProjectKey, params.RepoSlug, params.MainBranch)
}
golocParams := goloc.Params{
Path: params.PathToScan,
ByFile: false,
ExcludePaths: []string{},
ExcludeExtensions: []string{},
IncludeExtensions: []string{},
OrderByLang: false,
OrderByFile: false,
OrderByCode: false,
OrderByLine: false,
OrderByBlank: false,
OrderByComment: false,
Order: "DESC",
OutputName: outputFileName,
OutputPath: DestinationResult,
ReportFormats: []string{"json"},
Branch: params.MainBranch,
}
MessB := fmt.Sprintf(" Extracting files from repo : %s ", params.RepoSlug)
spin.Suffix = MessB
spin.Start()
gc, err := goloc.NewGCloc(golocParams, assets.Languages)
if err != nil {
fmt.Println(errorMessageRepo, err)
return
}
gc.Run()
*count++
// Remove Repository Directory
err1 := os.RemoveAll(gc.Repopath)
if err1 != nil {
fmt.Printf(errorMessageDi, err1)
}
spin.Stop()
fmt.Printf("\r✅ %d The repository <%s> has been analyzed\n", *count, params.RepoSlug)
// Send result through channel
results <- 1
}
// Wait for all goroutines to complete
func waitForWorkers(numWorkers int, results chan int) {
for i := 0; i < numWorkers; i++ {
fmt.Printf("\r Waiting for workers...\n")
<-results
}
}
// Specific analysis functions calling the generic one
// Analysis function call for BitBucket Cloud
func AnalyseReposListBitC(DestinationResult string, platformConfig map[string]interface{}, repolist []getbibucket.ProjectBranch) (cpt int) {
repoInterfaces := make([]interface{}, len(repolist))
for i, v := range repolist {
repoInterfaces[i] = v
}
return AnalyseReposList(DestinationResult, platformConfig, repoInterfaces, analyseBitCRepo)
}
// Analysis function call for BitBucket DC
func AnalyseReposListBitSRV(DestinationResult string, platformConfig map[string]interface{}, repolist []getbibucketdc.ProjectBranch) (cpt int) {
URLcut := platformConfig["Protocol"].(string) + "://"
trimmedURL := strings.TrimPrefix(platformConfig["Url"].(string), URLcut)
repoInterfaces := make([]interface{}, len(repolist))
for i, v := range repolist {
repoInterfaces[i] = v
}
return AnalyseReposList(DestinationResult, platformConfig, repoInterfaces, func(project interface{}, DestinationResult string, platformConfig map[string]interface{}, spin *spinner.Spinner, results chan int, count *int) {
analyseBitSRVRepo(project, DestinationResult, platformConfig, trimmedURL, spin, results, count)
})
}
// Analysis function call for GitHub
func AnalyseReposListGithub(DestinationResult string, platformConfig map[string]interface{}, repolist []getgithub.ProjectBranch) (cpt int) {
repoInterfaces := make([]interface{}, len(repolist))
for i, v := range repolist {
repoInterfaces[i] = v
}
return AnalyseReposList(DestinationResult, platformConfig, repoInterfaces, analyseGithubRepo)
}
// Analysis function call for Gitlab
func AnalyseReposListGitlab(DestinationResult string, platformConfig map[string]interface{}, repolist []getgitlab.ProjectBranch) (cpt int) {
repoInterfaces := make([]interface{}, len(repolist))
for i, v := range repolist {
repoInterfaces[i] = v
}
return AnalyseReposList(DestinationResult, platformConfig, repoInterfaces, analyseGitlabRepo)
}
// Analysis function call for Gitlab
func AnalyseReposListAzure(DestinationResult string, platformConfig map[string]interface{}, repolist []getazure.ProjectBranch) (cpt int) {
repoInterfaces := make([]interface{}, len(repolist))
for i, v := range repolist {
repoInterfaces[i] = v
}
return AnalyseReposList(DestinationResult, platformConfig, repoInterfaces, analyseAzurebRepo)
}
/* ---------------- Analyse Directory ---------------- */
func AnalyseReposListFile(Listdirectorie, fileexclusionEX []string) {
fmt.Print("\n🔎 Analysis of Directories ...\n")
var wg sync.WaitGroup
wg.Add(len(Listdirectorie))
for _, Listdirectories := range Listdirectorie {
go func(dir string) {
defer wg.Done()
spin := spinner.New(spinner.CharSets[35], 100*time.Millisecond)
spin.Color("green", "bold")
messageF := ""
spin.FinalMSG = messageF
outputFileName := "Result_"
count := 1
params := goloc.Params{
Path: dir,
ByFile: false,
ExcludePaths: fileexclusionEX,
ExcludeExtensions: []string{},
IncludeExtensions: []string{},
OrderByLang: false,
OrderByFile: false,
OrderByCode: false,
OrderByLine: false,
OrderByBlank: false,
OrderByComment: false,
Order: "DESC",
OutputName: outputFileName,
OutputPath: "Results",
ReportFormats: []string{"json"},
Branch: "",
Token: "",
}
gc, err := goloc.NewGCloc(params, assets.Languages)
if err != nil {
fmt.Println(errorMessageRepo, err)
return
}
gc.Run()
spin.Stop()
fmt.Printf("\r\t✅ %d The directory <%s> has been analyzed\n", count, dir)
count++
}(Listdirectories)
}
wg.Wait()
}
/* ---------------- End Analyse Directory ---------------- */
func AnalyseRun(params goloc.Params, reponame string) {
gc, err := goloc.NewGCloc(params, assets.Languages)
if err != nil {
fmt.Println(errorMessageRepo, err)
os.Exit(1)
}
gc.Run()
}
func AnalyseRepo(DestinationResult string, Users string, AccessToken string, DevOps string, Organization string, reponame string) (cpt int) {
//pathToScan := fmt.Sprintf("git::https://%s@%s.com/%s/%s", AccessToken, DevOps, Organization, reponame)
pathToScan := fmt.Sprintf("https://%s:%s@%s.com/%s/%s", Users, AccessToken, DevOps, Organization, reponame)
outputFileName := fmt.Sprintf("Result_%s", reponame)
params := goloc.Params{
Path: pathToScan,
ByFile: false,
ExcludePaths: []string{},
ExcludeExtensions: []string{},
IncludeExtensions: []string{},
OrderByLang: false,
OrderByFile: false,
OrderByCode: false,
OrderByLine: false,
OrderByBlank: false,
OrderByComment: false,
Order: "DESC",
OutputName: outputFileName,
OutputPath: DestinationResult,
ReportFormats: []string{"json"},
}
gc, err := goloc.NewGCloc(params, assets.Languages)
if err != nil {
fmt.Println(errorMessageRepo, err)
os.Exit(1)
}
gc.Run()
cpt++
// Remove Repository Directory
err1 := os.RemoveAll(gc.Repopath)
if err != nil {
fmt.Printf(errorMessageDi, err1)
return
}
return cpt
}
// Function Read LoadFile for list of directories
func ReadLines(filename string) ([]string, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
var lines []string
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
return nil, err
}
return lines, nil
}
func displayLanguages() {
fmt.Printf("%-18s | %-78s | %-15s | %s\n", "Language", "Extensions", "Single Comments", "Multi Line Comments")
fmt.Println("-------------------+--------------------------------------------------------------------------------+-----------------+--------------------")
for lang, config := range assets.Languages {
extensions := strings.Join(config.Extensions, ", ") // Concatenate extensions with comma separator
singleComments := strings.Join(config.LineComments, ", ") // Concatenate single comments with comma separator
multiLineComments := ""
for _, comments := range config.MultiLineComments {
for _, comment := range comments {
multiLineComments += comment + " "
}
}
fmt.Printf("%-18s | %-78s | %-15s | %s\n", lang, extensions, singleComments, multiLineComments)
}
}
func main() {
var maxTotalCodeLines int
var maxProject, maxRepo string
var NumberRepos int
var startTime time.Time
var ListDirectory []string
var ListExclusion []string
var message3, message4, message5 string
var version = "1.0.3"
// Test command line Flags
devopsFlag := flag.String("devops", "", "Specify the DevOps platform")
fastFlag := flag.Bool("fast", false, "Enable fast mode (only for Github)")
helpFlag := flag.Bool("help", false, "Show help message")
languagesFlag := flag.Bool("languages", false, "Show all supported languages")
versionflag := flag.Bool("version", false, "Show version")
docker := flag.Bool("docker", false, "Run in Docker mode")
flag.Parse()
if *helpFlag {
fmt.Println("Usage: golc -devops [OPTIONS]")
fmt.Println("Options: <BitBucketSRV>||<BitBucket>||<Github>||<Gitlab>||<Azure>||<File>")
flag.PrintDefaults()
os.Exit(0)
}
if *languagesFlag {
displayLanguages()
os.Exit(0)
}
if *versionflag {
fmt.Printf("GoLC version: %s %s/%s\n", version, runtime.GOOS, runtime.GOARCH)
os.Exit(0)
}
if *devopsFlag == "" {
fmt.Println("\n❌ Please specify the DevOps platform using the -devops flag : <BitBucketSRV>||<BitBucket>||<Github>||<Gitlab>||<Azure>||<File>")
fmt.Println("✅ Example for BitBucket server : golc -devops BitBucketSRV")
os.Exit(1)
}
AppConfig, err := LoadConfig("config.json")
if err != nil {
log.Fatalf("\n❌ Failed to load config: %s", err)
os.Exit(1)
}
platformConfig, ok := AppConfig.Platforms[*devopsFlag].(map[string]interface{})
if !ok {
fmt.Printf("\n❌ Configuration for DevOps platform '%s' not found\n", *devopsFlag)
fmt.Println("✅ the -devops flag is : <BitBucketSRV>||<BitBucket>||<Github>||<Gitlab>||<Azure>||<File>")
os.Exit(1)
}
fmt.Printf("\n✅ Using configuration for DevOps platform '%s'\n", *devopsFlag)
// Test whether to delete the Results directory and save it before deleting.
pwd, err := os.Getwd()
if err != nil {
fmt.Println("Error:", err)
}
DestinationResult := pwd + "/Results"
if *docker {
fmt.Println("Running in Docker mode")
ConfigDirectory := DestinationResult + directoryconf
if err := os.MkdirAll(ConfigDirectory, os.ModePerm); err != nil {
panic(err)
}
} else {
_, err = os.Stat(DestinationResult)
if err == nil {
fmt.Printf("❗️ Directory <'%s'> already exists. Do you want to delete it? (y/n): ", DestinationResult)
var response string
fmt.Scanln(&response)
if response == "y" || response == "Y" {
fmt.Printf("❗️ Do you want to create a backup of the directory before deleting? (y/n): ")
var backupResponse string
fmt.Scanln(&backupResponse)
if backupResponse == "y" || backupResponse == "Y" {
// Créer la sauvegarde ZIP
err := createBackup(DestinationResult, pwd)
if err != nil {
fmt.Printf("❌ Error creating backup: %s\n", err)
os.Exit(1)
}
}
err := os.RemoveAll(DestinationResult)
if err != nil {
fmt.Printf("❌ Error deleting directory: %s\n", err)
os.Exit(1)
}
if err := os.MkdirAll(DestinationResult, os.ModePerm); err != nil {
panic(err)
}
ConfigDirectory := DestinationResult + directoryconf
if err := os.MkdirAll(ConfigDirectory, os.ModePerm); err != nil {
panic(err)
}
} else {
os.Exit(1)
}
} else if os.IsNotExist(err) {
if err := os.MkdirAll(DestinationResult, os.ModePerm); err != nil {
panic(err)
}
ConfigDirectory := DestinationResult + directoryconf
if err := os.MkdirAll(ConfigDirectory, os.ModePerm); err != nil {
panic(err)
}
}
}
fmt.Printf("\n")
// Create Global Report File
GlobalReport := DestinationResult + "/GlobalReport.txt"
file, err := os.Create(GlobalReport)
if err != nil {
fmt.Println("❌ Error creating file:", err)
return
}
defer file.Close()
// Open Logs
err = OpenLogFile("Results/Logs.log")
if err != nil {
fmt.Println("❌ Error opening log file:", err)
return
}
defer CloseLogFile()
// Select DevOps Platform
switch devops := platformConfig["DevOps"].(string); devops {
case "azure":
var fileexclusion = ".cloc_azure_ignore"
fileexclusionEX := getFileNameIfExists(fileexclusion)
startTime = time.Now()
gitproject, err := getazure.GetRepoAzureList(platformConfig, fileexclusionEX)
if err != nil {
fmt.Printf(errorMessageRepos, platformConfig["Organization"].(string), err)
return
}
if len(gitproject) == 0 {
fmt.Printf(errorMessageAnalyse)
os.Exit(1)
} else {
NumberRepos = AnalyseReposListAzure(DestinationResult, platformConfig, gitproject)
}
case "github":
var fileexclusion = ".cloc_github_ignore"
fileexclusionEX := getFileNameIfExists(fileexclusion)
var fast bool
startTime = time.Now()
if *fastFlag {
fmt.Println("🚀 Fast mode enabled for Github")
fast = true
err := getgithub.FastAnalys(platformConfig, fileexclusionEX)
if err != nil {
fmt.Printf("❌ Quick scan Analysis : '%s'", err)
os.Exit(0)
}
} else {
fast = false
repositories, err := getgithub.GetRepoGithubList(platformConfig, fileexclusionEX, fast)
if err != nil {
fmt.Printf(errorMessageRepos, platformConfig["Organization"].(string), err)
return
}
if len(repositories) == 0 {
fmt.Printf(errorMessageAnalyse)
os.Exit(1)
} else {
NumberRepos = AnalyseReposListGithub(DestinationResult, platformConfig, repositories)
}
}
case "gitlab":
var fileexclusion = ".cloc_gitlab_ignore"
fileexclusionEX := getFileNameIfExists(fileexclusion)
startTime = time.Now()
gitproject, err := getgitlab.GetRepoGitLabList(platformConfig, fileexclusionEX)
if err != nil {
fmt.Printf(errorMessageRepos, platformConfig["Organization"].(string), err)
return
}
if len(gitproject) == 0 {
fmt.Printf(errorMessageAnalyse)
os.Exit(1)
} else {
//os.Exit(1)
NumberRepos = AnalyseReposListGitlab(DestinationResult, platformConfig, gitproject)
}
case "bitbucket_dc":
var fileexclusion = platformConfig["FileExclusion"].(string)
fileexclusionEX := getFileNameIfExists(fileexclusion)
startTime = time.Now()
projects, err := getbibucketdc.GetProjectBitbucketList(platformConfig, fileexclusionEX)
if err != nil {
fmt.Printf("❌ Error Get Info Projects in Bitbucket server '%s' : ", err)
os.Exit(1)
}
if len(projects) == 0 {
fmt.Printf(errorMessageAnalyse)
os.Exit(1)
} else {
// Run scanning repositories
NumberRepos = AnalyseReposListBitSRV(DestinationResult, platformConfig, projects)
}
case "bitbucket":
var fileexclusion = platformConfig["FileExclusion"].(string)
fileexclusionEX := getFileNameIfExists(fileexclusion)
startTime = time.Now()
projects1, err := getbibucket.GetProjectBitbucketListCloud(platformConfig, fileexclusionEX)
if err != nil {
fmt.Printf("❌ Error Get Info Project(s) in Bitbucket cloud '%v' ", err)
return
}
if len(projects1) == 0 {
fmt.Printf(errorMessageAnalyse)
os.Exit(1)
} else {
// Run scanning repositories
NumberRepos = AnalyseReposListBitC(DestinationResult, platformConfig, projects1)
}
case "file":
fileexclusionEX := getFileNameIfExists(platformConfig["FileExclusion"].(string))
fileload := getFileNameIfExists(platformConfig["FileLoad"].(string))
if fileexclusionEX != "0" {
ListExclusion, err = ReadLines(fileexclusionEX)
if err != nil {
fmt.Println("❌ Error reading file <.cloc_file_ignore>:", err)
os.Exit(1)
}
} else {
ListExclusion = make([]string, 0)
}
if fileload != "0" {
ListDirectory, err = ReadLines(fileload)
if err != nil {
fmt.Println("❌ Error reading file <.cloc_file_file>:", err)
os.Exit(1)
}
if len(ListDirectory) == 0 {
ListDirectory = append(ListDirectory, platformConfig["Directory"].(string))
}
} else {
if len(platformConfig["Directory"].(string)) == 0 {
fmt.Println("❌ No analysis possible, no directory, specified file or specified loading file")
os.Exit(1)
} else {
ListDirectory = append(ListDirectory, platformConfig["Directory"].(string))
}
}
startTime = time.Now()
AnalyseReposListFile(ListDirectory, ListExclusion)
}
// Begin of report file analysis
fmt.Print("\n🔎 Analyse Report ...\n")
spin := spinner.New(spinner.CharSets[35], 100*time.Millisecond)
spin.Suffix = " Analyse Report..."
spin.Color("green", "bold")
spin.Start()
// List files in the directory
files, err := os.ReadDir(DestinationResult)
if err != nil {
fmt.Println("❌ Error listing files:", err)
os.Exit(1)
}
// Initialize the sum of TotalCodeLines
totalCodeLinesSum := 0
// Analyse All file
for _, file := range files {
// Check if the file is a JSON file
if !file.IsDir() && strings.HasSuffix(file.Name(), ".json") {
// Read contents of JSON file
filePath := filepath.Join(DestinationResult, file.Name())
jsonData, err := os.ReadFile(filePath)
if err != nil {
fmt.Printf("\n❌ Error reading file %s: %v\n", file.Name(), err)
continue
}
// Parse JSON content into a Result structure
var result Result
err = json.Unmarshal(jsonData, &result)
if err != nil {
fmt.Printf("\n❌ Error parsing JSON contents of file %s: %v\n", file.Name(), err)
continue
}
totalCodeLinesSum += result.TotalCodeLines
// Check if this repo has a higher TotalCodeLines than the current maximum
if result.TotalCodeLines > maxTotalCodeLines {
maxTotalCodeLines = result.TotalCodeLines