-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
1252 lines (1056 loc) · 33.3 KB
/
main.go
File metadata and controls
1252 lines (1056 loc) · 33.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
package main
import (
"context"
"errors"
"fmt"
"net"
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/spf13/pflag"
)
// Dependencies interfaces for better testability and modularity
// FileSystem abstracts file system operations for better testability
type FileSystem interface {
Open(name string) (*os.File, error)
Stat(name string) (os.FileInfo, error)
MkdirAll(path string, perm os.FileMode) error
UserHomeDir() (string, error)
Getenv(key string) string
}
// CommandRunner abstracts command execution for better testability
type CommandRunner interface {
LookPath(file string) (string, error)
Run(ctx context.Context, name string, args ...string) error
RunWithOutput(ctx context.Context, name string, args ...string) ([]byte, error)
}
// GitCloner abstracts git cloning operations for better testability
type GitCloner interface {
Clone(ctx context.Context, repository, targetDir string, quiet, shallow bool) error
}
// DirectoryChecker abstracts directory existence checking for better testability
type DirectoryChecker interface {
IsNotEmpty(name string) bool
}
// Environment abstracts environment operations
type Environment interface {
UserHomeDir() (string, error)
Getenv(key string) string
}
// Dependencies holds all external dependencies for the application
type Dependencies struct {
FS FileSystem
CmdRun CommandRunner
GitClone GitCloner
DirCheck DirectoryChecker
Env Environment
}
// Default implementations for production use
// DefaultFileSystem provides real file system operations
type DefaultFileSystem struct{}
func (fs *DefaultFileSystem) Open(name string) (*os.File, error) {
return os.Open(name)
}
func (fs *DefaultFileSystem) Stat(name string) (os.FileInfo, error) {
return os.Stat(name)
}
func (fs *DefaultFileSystem) MkdirAll(path string, perm os.FileMode) error {
return os.MkdirAll(path, perm)
}
func (fs *DefaultFileSystem) UserHomeDir() (string, error) {
return os.UserHomeDir()
}
func (fs *DefaultFileSystem) Getenv(key string) string {
return os.Getenv(key)
}
// DefaultCommandRunner provides real command execution
type DefaultCommandRunner struct{}
func (cr *DefaultCommandRunner) LookPath(file string) (string, error) {
return exec.LookPath(file)
}
func (cr *DefaultCommandRunner) Run(ctx context.Context, name string, args ...string) error {
cmd := exec.CommandContext(ctx, name, args...)
return cmd.Run()
}
func (cr *DefaultCommandRunner) RunWithOutput(ctx context.Context, name string, args ...string) ([]byte, error) {
cmd := exec.CommandContext(ctx, name, args...)
return cmd.Output()
}
// DefaultGitCloner provides real git cloning functionality
type DefaultGitCloner struct{}
func (gc *DefaultGitCloner) Clone(ctx context.Context, repository, targetDir string, quiet, shallow bool) error {
return secureGitClone(ctx, repository, targetDir, quiet, shallow)
}
// DefaultDirectoryChecker provides real directory checking functionality
type DefaultDirectoryChecker struct {
cache *DirCache
}
func NewDefaultDirectoryChecker(fs FileSystem) *DefaultDirectoryChecker {
return &DefaultDirectoryChecker{
cache: NewDirCache(DefaultCacheConfig(), fs),
}
}
func NewDirectoryCheckerWithConfig(fs FileSystem, config *CacheConfig) *DefaultDirectoryChecker {
return &DefaultDirectoryChecker{
cache: NewDirCache(config, fs),
}
}
func (dc *DefaultDirectoryChecker) IsNotEmpty(name string) bool {
return dc.cache.IsDirectoryNotEmpty(name)
}
// DefaultEnvironment provides real environment operations
type DefaultEnvironment struct{}
func (env *DefaultEnvironment) UserHomeDir() (string, error) {
return os.UserHomeDir()
}
func (env *DefaultEnvironment) Getenv(key string) string {
return os.Getenv(key)
}
// NewDefaultDependencies creates a new Dependencies instance with default implementations
func NewDefaultDependencies() *Dependencies {
fs := &DefaultFileSystem{}
return &Dependencies{
FS: fs,
CmdRun: &DefaultCommandRunner{},
GitClone: &DefaultGitCloner{},
DirCheck: NewDefaultDirectoryChecker(fs),
Env: &DefaultEnvironment{},
}
}
// NewDependenciesWithCacheConfig creates a new Dependencies instance with custom cache configuration
func NewDependenciesWithCacheConfig(cacheConfig *CacheConfig) *Dependencies {
fs := &DefaultFileSystem{}
return &Dependencies{
FS: fs,
CmdRun: &DefaultCommandRunner{},
GitClone: &DefaultGitCloner{},
DirCheck: NewDirectoryCheckerWithConfig(fs, cacheConfig),
Env: &DefaultEnvironment{},
}
}
var (
version = "dev"
commit = "none"
date = "unknown"
)
// Config holds the configuration for the application
type Config struct {
ShowCommandHelp bool
ShowVersionInfo bool
Quiet bool
ShallowClone bool
Workers int
RepositoryArgs []string
Dependencies *Dependencies
CacheConfig *CacheConfig
}
// ProcessingResult holds the result of repository processing
type ProcessingResult struct {
LastSuccessfulProjectDir string
ProcessedCount int
FailedCount int
}
// RepositoryJob represents a job for cloning a repository
type RepositoryJob struct {
Repository string
Index int // Original position in the arguments list
}
// WorkerResult represents the result of processing a repository job
type WorkerResult struct {
Job RepositoryJob
ProjectDir string
Success bool
Error error
}
// WorkerPool manages parallel repository cloning
type WorkerPool struct {
config *Config
jobs chan RepositoryJob
results chan WorkerResult
done chan struct{}
shutdown chan struct{}
shutdownOnce sync.Once
workerCount int32
}
// NewWorkerPool creates a new worker pool for parallel repository cloning
func NewWorkerPool(config *Config) *WorkerPool {
return &WorkerPool{
config: config,
jobs: make(chan RepositoryJob, len(config.RepositoryArgs)),
results: make(chan WorkerResult, len(config.RepositoryArgs)),
done: make(chan struct{}),
shutdown: make(chan struct{}),
}
}
// worker is the worker goroutine that processes repository cloning jobs
func (wp *WorkerPool) worker(workerID int) {
atomic.AddInt32(&wp.workerCount, 1)
defer atomic.AddInt32(&wp.workerCount, -1)
for {
select {
case job, ok := <-wp.jobs:
if !ok {
return // Jobs channel is closed
}
wp.processJob(job, workerID)
case <-wp.shutdown:
return // Shutdown requested
}
}
}
// processOneRepository validates, resolves, and clones a single repository.
// Returns the project directory and an error if any step fails.
func processOneRepository(parentCtx context.Context, config *Config, repository string) (string, error) {
if err := validateRepositoryURL(repository); err != nil {
return "", fmt.Errorf("invalid repository URL '%s': %w", repository, err)
}
projectDir, err := getProjectDir(repository, config.Dependencies.Env)
if err != nil {
return "", fmt.Errorf("failed to determine project directory for '%s': %w", repository, err)
}
if config.Dependencies.DirCheck.IsNotEmpty(projectDir) {
if !config.Quiet {
fmt.Fprintf(os.Stderr, "repository already exists: %s\n", projectDir)
}
return projectDir, nil
}
if err := config.Dependencies.FS.MkdirAll(filepath.Dir(projectDir), 0750); err != nil {
return "", fmt.Errorf("failed create directory: %w", err)
}
ctx, cancel := context.WithTimeout(parentCtx, 10*time.Minute)
defer cancel()
if err := config.Dependencies.GitClone.Clone(ctx, repository, filepath.Dir(projectDir), config.Quiet, config.ShallowClone); err != nil {
return "", fmt.Errorf("failed clone repository '%s': %w", repository, err)
}
if !config.Quiet {
fmt.Fprintln(os.Stderr)
}
return projectDir, nil
}
func (wp *WorkerPool) processJob(job RepositoryJob, _ int) {
result := WorkerResult{Job: job}
ctx, cancel := context.WithCancel(context.Background())
go func() {
select {
case <-wp.shutdown:
cancel()
case <-ctx.Done():
}
}()
projectDir, err := processOneRepository(ctx, wp.config, job.Repository)
cancel()
if err != nil {
result.Error = err
wp.results <- result
return
}
result.ProjectDir = projectDir
result.Success = true
wp.results <- result
}
// Start starts the worker pool and processes all repositories
func (wp *WorkerPool) Start() *ProcessingResult {
// Start workers
for i := 0; i < wp.config.Workers; i++ {
go wp.worker(i)
}
// Send jobs to workers
go func() {
defer close(wp.jobs)
for i, repository := range wp.config.RepositoryArgs {
job := RepositoryJob{
Repository: strings.TrimSpace(repository),
Index: i,
}
select {
case wp.jobs <- job:
case <-wp.shutdown:
return // Shutdown requested, stop sending jobs
}
}
}()
// Collect results
result := &ProcessingResult{}
processedCount := 0
expectedJobs := len(wp.config.RepositoryArgs)
for processedCount < expectedJobs {
select {
case workerResult := <-wp.results:
result.ProcessedCount++
processedCount++
if workerResult.Success {
result.LastSuccessfulProjectDir = workerResult.ProjectDir
} else {
result.FailedCount++
if workerResult.Error != nil {
prntf(workerResult.Error.Error())
}
}
case <-wp.shutdown:
wp.gracefulShutdown()
wp.waitForWorkers()
// Drain remaining results from in-flight jobs
for {
select {
case workerResult := <-wp.results:
result.ProcessedCount++
processedCount++
if workerResult.Success {
result.LastSuccessfulProjectDir = workerResult.ProjectDir
} else {
result.FailedCount++
if workerResult.Error != nil {
prntf(workerResult.Error.Error())
}
}
default:
return result
}
}
}
}
// Signal completion and wait for workers to finish
close(wp.done)
wp.waitForWorkers()
return result
}
// gracefulShutdown signals all workers to shut down
func (wp *WorkerPool) gracefulShutdown() {
wp.shutdownOnce.Do(func() {
close(wp.shutdown)
})
}
// waitForWorkers waits for all workers to finish gracefully
func (wp *WorkerPool) waitForWorkers() {
// Wait with timeout to avoid hanging indefinitely
timeout := time.After(30 * time.Second)
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if atomic.LoadInt32(&wp.workerCount) == 0 {
return // All workers have finished
}
case <-timeout:
// Force shutdown after timeout
return
}
}
}
// StartWithSignalHandling starts the worker pool with signal handling for graceful shutdown
func (wp *WorkerPool) StartWithSignalHandling() *ProcessingResult {
// Set up signal handling
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
// Start worker pool in a goroutine
resultChan := make(chan *ProcessingResult, 1)
go func() {
resultChan <- wp.Start()
}()
// Wait for either completion or signal
select {
case result := <-resultChan:
// Normal completion
signal.Stop(signalChan)
return result
case sig := <-signalChan:
// Signal received, initiate graceful shutdown
if !wp.config.Quiet {
fmt.Fprintf(os.Stderr, "\nReceived signal %v, initiating graceful shutdown...\n", sig)
}
wp.gracefulShutdown()
// Wait for result with timeout
select {
case result := <-resultChan:
if !wp.config.Quiet {
fmt.Fprintf(os.Stderr, "Graceful shutdown completed.\n")
}
return result
case <-time.After(45 * time.Second):
// Force shutdown if graceful shutdown takes too long
if !wp.config.Quiet {
fmt.Fprintf(os.Stderr, "Graceful shutdown timeout, forcing exit.\n")
}
os.Exit(1)
return nil // Never reached
}
}
}
// getDefaultWorkers returns the default number of workers based on CPU count
func getDefaultWorkers() int {
cpuCount := runtime.NumCPU()
if cpuCount > 4 {
return 4
}
return cpuCount
}
// RegexType represents different types of repository URL patterns
type RegexType int
const (
RegexHTTPS RegexType = iota
RegexSSH
RegexGit
RegexGeneric
)
var (
httpsRegex = regexp.MustCompile(`^https?://([^/]+)/(.+?)(?:\.git)?/?$`)
sshRegex = regexp.MustCompile(`^(?:ssh://)?([^@]+)@([^/:]+)(?::(\d+))?[:/](.+?)(?:\.git)?/?$`)
gitRegex = regexp.MustCompile(`^git://([^/]+)/(.+?)(?:\.git)?/?$`)
genericRegex = regexp.MustCompile(`^(?:.*://)?(?:[^@]+@)?([^:/]+)(?::\d+)?[/:]?(.*)$`)
)
// CacheConfig holds configuration parameters for directory cache
type CacheConfig struct {
TTL time.Duration
CleanupInterval time.Duration
MaxEntries int
EnablePeriodicCleanup bool
}
// DefaultCacheConfig returns default cache configuration
func DefaultCacheConfig() *CacheConfig {
return &CacheConfig{
TTL: 60 * time.Second, // Increased from 30s to 1 minute
CleanupInterval: 5 * time.Minute,
MaxEntries: 1000,
EnablePeriodicCleanup: true,
}
}
type cacheEntry struct {
exists bool
timestamp time.Time
lastAccess time.Time
}
type DirCache struct {
cache map[string]cacheEntry
mutex sync.RWMutex
config *CacheConfig
fs FileSystem
stopCleanup chan struct{}
cleanupOnce sync.Once
}
// Security validation functions
var (
// Allowed URL schemes for git repositories
allowedSchemes = map[string]bool{
"https": true,
"http": true,
"ssh": true,
"git": true,
}
// Dangerous characters that could be used for command injection
dangerousChars = regexp.MustCompile(`[;&|$\x60<>(){}[\]!*?]`)
// Valid hostname pattern - more restrictive than RFC but safer
validHostname = regexp.MustCompile(`^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*$`)
// Valid path characters for Git repositories
validRepoPath = regexp.MustCompile(`^[a-zA-Z0-9._/~-]+$`)
)
// validateRepositoryURL performs comprehensive security validation of repository URLs
func validateRepositoryURL(repo string) error {
if repo == "" {
return errors.New("repository URL cannot be empty")
}
// Check for dangerous characters that could indicate command injection
if dangerousChars.MatchString(repo) {
return errors.New("repository URL contains dangerous characters")
}
// Handle SSH URLs like git@github.com:user/repo.git
if strings.Contains(repo, "@") && strings.Contains(repo, ":") && !strings.Contains(repo, "://") {
return validateSSHURL(repo)
}
// Parse as regular URL
parsedURL, err := url.Parse(repo)
if err != nil {
return fmt.Errorf("invalid URL format: %w", err)
}
// Validate scheme
if parsedURL.Scheme != "" && !allowedSchemes[parsedURL.Scheme] {
return fmt.Errorf("unsupported URL scheme: %s", parsedURL.Scheme)
}
// Validate hostname (strip port if present)
if parsedURL.Host != "" {
host := parsedURL.Host
if strings.Contains(host, ":") {
var err error
host, _, err = net.SplitHostPort(host)
if err != nil {
return fmt.Errorf("invalid host:port: %s", parsedURL.Host)
}
}
if !validHostname.MatchString(host) {
return fmt.Errorf("invalid hostname: %s", host)
}
}
// Validate path for traversal attacks
if err := validatePath(parsedURL.Path); err != nil {
return err
}
return nil
}
// validateSSHURL validates SSH-style Git URLs (git@host:path)
func validateSSHURL(repo string) error {
parts := strings.SplitN(repo, "@", 2)
if len(parts) != 2 {
return errors.New("invalid SSH URL format")
}
hostPath := parts[1]
hostPathParts := strings.SplitN(hostPath, ":", 2)
if len(hostPathParts) != 2 {
return errors.New("invalid SSH URL format - missing colon separator")
}
host := hostPathParts[0]
path := hostPathParts[1]
// Validate hostname
if !validHostname.MatchString(host) {
return fmt.Errorf("invalid hostname in SSH URL: %s", host)
}
// Validate path
if err := validatePath(path); err != nil {
return err
}
return nil
}
// validatePath checks for path traversal attacks and invalid characters
func validatePath(path string) error {
if path == "" {
return nil // Empty path is acceptable
}
// Check for path traversal attempts
if strings.Contains(path, "..") {
return errors.New("path traversal detected in URL")
}
// Check for absolute paths that could escape intended directory
if len(path) > 0 && path[0] == '/' {
// Remove leading slash for validation but allow it
path = path[1:]
}
// Allow tilde for user directories but validate the rest
if len(path) > 0 && path[0] == '~' {
path = path[1:]
if len(path) > 0 && path[0] == '/' {
path = path[1:]
}
}
// Validate remaining path characters (allow common Git repo path characters)
if path != "" && !validRepoPath.MatchString(path) {
return fmt.Errorf("invalid characters in repository path: %s", path)
}
return nil
}
// secureGitClone performs git clone with additional security measures
func secureGitClone(ctx context.Context, repository, targetDir string, quiet, shallow bool) error {
if err := validateRepositoryURL(repository); err != nil {
return fmt.Errorf("security validation failed: %w", err)
}
cleanTargetDir := filepath.Clean(targetDir)
if strings.Contains(cleanTargetDir, "..") {
return errors.New("target directory contains path traversal")
}
args := []string{"clone"}
if shallow {
args = append(args, "--depth=1")
}
args = append(args, "--", repository)
cmd := exec.CommandContext(ctx, "git", args...)
// Set working directory
cmd.Dir = cleanTargetDir
// Configure output
if !quiet {
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
}
// Execute with timeout protection
if err := cmd.Run(); err != nil {
if ctx.Err() == context.DeadlineExceeded {
return fmt.Errorf("git clone operation timed out after 10 minutes: %s", repository)
}
return err
}
return nil
}
// parseArgs parses command line arguments and returns configuration
func parseArgs() (*Config, error) {
cacheConfig := DefaultCacheConfig()
config := &Config{
Dependencies: NewDependenciesWithCacheConfig(cacheConfig),
CacheConfig: cacheConfig,
Workers: getDefaultWorkers(),
}
pflag.BoolVarP(&config.ShowCommandHelp, "help", "h", false, "Show this help message and exit")
pflag.BoolVarP(&config.ShowVersionInfo, "version", "v", false, "Show the version number and exit")
pflag.BoolVarP(&config.Quiet, "quiet", "q", false, "Suppress output")
pflag.BoolVarP(&config.ShallowClone, "shallow", "s", false, "Perform shallow clone with --depth=1")
pflag.IntVarP(&config.Workers, "workers", "w", getDefaultWorkers(), "Number of parallel workers for cloning")
pflag.Parse()
config.RepositoryArgs = pflag.Args()
// Validate workers count
if config.Workers < 1 {
return nil, errors.New("workers count must be at least 1")
}
if config.Workers > 32 {
return nil, errors.New("workers count cannot exceed 32")
}
// Validate that we have arguments (unless help or version is requested)
if !config.ShowCommandHelp && !config.ShowVersionInfo && len(config.RepositoryArgs) == 0 {
return nil, errors.New("no repository URLs provided")
}
// Validate each argument is not empty
for i, arg := range config.RepositoryArgs {
if strings.TrimSpace(arg) == "" {
return nil, fmt.Errorf("argument %d is empty", i+1)
}
}
return config, nil
}
// validateDependencies checks if required dependencies are available
func validateDependencies(deps *Dependencies) error {
// Check git availability with better error message
if _, err := deps.CmdRun.LookPath("git"); err != nil {
return errors.New("git command not found in PATH. Please install git: https://git-scm.com/downloads")
}
return nil
}
// processRepositories processes all repository arguments using worker pool and returns the result
func processRepositories(config *Config) *ProcessingResult {
// For single repository or single worker, use sequential processing to avoid overhead
if len(config.RepositoryArgs) == 1 || config.Workers == 1 {
return processRepositoriesSequential(config)
}
// Use worker pool for multiple repositories with multiple workers
wp := NewWorkerPool(config)
return wp.StartWithSignalHandling()
}
func processRepositoriesSequential(config *Config) *ProcessingResult {
result := &ProcessingResult{}
for _, arg := range config.RepositoryArgs {
repository := strings.TrimSpace(arg)
result.ProcessedCount++
projectDir, err := processOneRepository(context.Background(), config, repository)
if err != nil {
prntf("%s", err)
result.FailedCount++
continue
}
result.LastSuccessfulProjectDir = projectDir
}
return result
}
// printSummary prints the final summary and handles output/exit logic
func printSummary(config *Config, result *ProcessingResult) {
// Print summary if multiple repositories were processed
if result.ProcessedCount > 1 && !config.Quiet {
successCount := result.ProcessedCount - result.FailedCount
prntf("processed %d repositories: %d successful, %d failed",
result.ProcessedCount, successCount, result.FailedCount)
}
// Print the last successfully processed project directory
if result.LastSuccessfulProjectDir != "" {
abs, err := filepath.Abs(result.LastSuccessfulProjectDir)
if err != nil {
prntf("failed to get absolute path for %s: %s", result.LastSuccessfulProjectDir, err)
fmt.Println(result.LastSuccessfulProjectDir) // fallback to relative path
} else {
fmt.Println(abs)
}
} else {
// No successful repositories processed
if !config.Quiet {
prntf("no repositories were successfully processed")
}
os.Exit(1)
}
}
func main() {
// Parse command line arguments
config, err := parseArgs()
if err != nil {
prntf("error: %s", err)
usage()
os.Exit(1)
}
// Handle help command
if config.ShowCommandHelp {
usage()
return
}
// Handle version command
if config.ShowVersionInfo {
if commit != "none" {
fmt.Printf("gclone version %s, commit %s, built at %s\n", version, commit, date)
} else {
fmt.Printf("gclone version %s\n", version)
}
return
}
// Validate dependencies
if err := validateDependencies(config.Dependencies); err != nil {
prntf("error: %s", err)
os.Exit(1)
}
// Process repositories
result := processRepositories(config)
// Print summary and handle exit
printSummary(config, result)
}
// URLCache provides caching for normalized URLs to avoid repeated parsing
type URLCache struct {
cache map[string]string
mutex sync.RWMutex
maxEntries int
}
var urlCache = &URLCache{
cache: make(map[string]string),
maxEntries: 1000,
}
// Get retrieves a cached normalized URL
func (uc *URLCache) Get(key string) (string, bool) {
uc.mutex.RLock()
defer uc.mutex.RUnlock()
value, exists := uc.cache[key]
return value, exists
}
// Set stores a normalized URL in cache
func (uc *URLCache) Set(key, value string) {
uc.mutex.Lock()
defer uc.mutex.Unlock()
// Simple eviction strategy: clear cache when full
if len(uc.cache) >= uc.maxEntries {
uc.cache = make(map[string]string)
}
uc.cache[key] = value
}
// Clear removes all entries from the URLCache for test isolation
func (uc *URLCache) Clear() {
uc.mutex.Lock()
defer uc.mutex.Unlock()
uc.cache = make(map[string]string)
}
// detectRegexType determines the best regex pattern for the given URL
func detectRegexType(repo string) RegexType {
// Check for HTTPS/HTTP URLs first
if strings.HasPrefix(repo, "https://") || strings.HasPrefix(repo, "http://") {
return RegexHTTPS
}
// Check for Git protocol URLs
if strings.HasPrefix(repo, "git://") {
return RegexGit
}
// Check for SSH URLs (ssh:// prefix or git@host:path format)
if strings.HasPrefix(repo, "ssh://") {
return RegexSSH
}
if strings.Contains(repo, "@") && strings.Contains(repo, ":") && !strings.Contains(repo, "://") {
return RegexSSH
}
return RegexGeneric
}
func regexForType(regexType RegexType) *regexp.Regexp {
switch regexType {
case RegexHTTPS:
return httpsRegex
case RegexSSH:
return sshRegex
case RegexGit:
return gitRegex
default:
return genericRegex
}
}
func normalize(repo string) (string, error) {
if repo == "" {
return "", errors.New("repository URL is empty")
}
if cached, exists := urlCache.Get(repo); exists {
return cached, nil
}
regexType := detectRegexType(repo)
r := regexForType(regexType)
var host, path string
switch regexType {
case RegexHTTPS, RegexGit:
match := r.FindStringSubmatch(repo)
if len(match) != 3 {
return "", errors.New("failed to parse HTTPS/Git repository URL format")
}
host, path = match[1], match[2]
case RegexSSH:
match := r.FindStringSubmatch(repo)
if len(match) != 5 {
return "", errors.New("failed to parse SSH repository URL format")
}
// match[1] = user, match[2] = host, match[3] = port (optional), match[4] = path
// For hostname validation, we only use the host part (without port)
host, path = match[2], match[4]
default: // RegexGeneric
match := r.FindStringSubmatch(repo)
if len(match) != 3 {
return "", errors.New("failed to parse repository URL format")
}
host, path = match[1], match[2]
}
// Security: Validate host component
if !validHostname.MatchString(host) {
return "", fmt.Errorf("invalid hostname: %s", host)
}
// Security: Sanitize path to prevent traversal attacks
sanitizedPath, err := sanitizePathWithError(path)
if err != nil {
return "", fmt.Errorf("invalid repository path: %w", err)
}
// Security: Validate final path doesn't contain dangerous patterns
if strings.Contains(sanitizedPath, "..") || strings.Contains(sanitizedPath, "//") {
return "", errors.New("repository path contains dangerous patterns")
}
result := filepath.Join(host, sanitizedPath)
// Cache the result
urlCache.Set(repo, result)
return result, nil
}
// sanitizePathWithError cleans and validates repository paths against security threats
// Returns error for better error handling instead of empty string
func sanitizePathWithError(path string) (string, error) {
if path == "" {
return "", nil // Empty path is acceptable
}
originalPath := path
// Remove dangerous prefixes and suffixes with optimized string operations
// Use string slicing to avoid multiple allocations
for {
originalLen := len(path)
// Remove leading slashes and tildes
if len(path) > 0 && (path[0] == '/' || path[0] == '~') {
path = path[1:]
continue
}
// Remove trailing slashes
if len(path) > 0 && path[len(path)-1] == '/' {
path = path[:len(path)-1]
continue
}
// Remove .git suffix
if len(path) >= 4 && path[len(path)-4:] == ".git" {
path = path[:len(path)-4]
continue
}