| 1 | package load |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "runtime" |
| 7 | "sync" |
| 8 | |
| 9 | "github.com/isacikgoz/gitbatch/internal/git" |
| 10 | "golang.org/x/sync/semaphore" |
| 11 | ) |
| 12 | |
| 13 | // AsyncAdd is interface to caller |
| 14 | type AsyncAdd func(r *git.Repository) |
| 15 | |
| 16 | // SyncLoad initializes the go-git's repository objects with given |
| 17 | // slice of paths. since this job is done parallel, the order of the directories |
| 18 | // is not kept |
| 19 | func SyncLoad(directories []string) (entities []*git.Repository, err error) { |
| 20 | entities = make([]*git.Repository, 0) |
| 21 | |
| 22 | var wg sync.WaitGroup |
| 23 | var mu sync.Mutex |
| 24 | |
| 25 | for _, dir := range directories { |
| 26 | // increment wait counter by one because we run a single goroutine |
| 27 | // below |
| 28 | wg.Add(1) |
| 29 | go func(d string) { |
| 30 | // decrement the wait counter by one, we call it in a defer so it's |
| 31 | // called at the end of this goroutine |
| 32 | defer wg.Done() |
| 33 | entity, err := git.InitializeRepo(d) |
| 34 | if err != nil { |
| 35 | return |
| 36 | } |
| 37 | // lock so we don't get a race if multiple go routines try to add |
| 38 | // to the same entities |
| 39 | mu.Lock() |
| 40 | entities = append(entities, entity) |
| 41 | mu.Unlock() |
| 42 | }(dir) |
| 43 | } |
| 44 | // wait until the wait counter is zero, this happens if all goroutines have |
| 45 | // finished |
| 46 | wg.Wait() |
| 47 | if len(entities) == 0 { |
| 48 | return entities, fmt.Errorf("there are no git repositories at given path(s)") |
| 49 | } |
| 50 | return entities, nil |
| 51 | } |
| 52 | |
| 53 | // AsyncLoad asynchronously adds to AsyncAdd function |
| 54 | func AsyncLoad(directories []string, add AsyncAdd, d chan bool) error { |
| 55 | ctx := context.TODO() |
| 56 | |
| 57 | var ( |
| 58 | maxWorkers = runtime.GOMAXPROCS(0) |
| 59 | sem = semaphore.NewWeighted(int64(maxWorkers)) |
| 60 | ) |
| 61 | |
| 62 | var mx sync.Mutex |
| 63 | |
| 64 | // Compute the output using up to maxWorkers goroutines at a time. |
| 65 | for _, dir := range directories { |
| 66 | if err := sem.Acquire(ctx, 1); err != nil { |
| 67 | break |
| 68 | } |
| 69 | |
| 70 | go func(d string) { |
| 71 | |
| 72 | defer sem.Release(1) |
| 73 | entity, err := git.InitializeRepo(d) |
| 74 | if err != nil { |
| 75 | return |
| 76 | } |
| 77 | // lock so we don't get a race if multiple go routines try to add |
| 78 | // to the same entities |
| 79 | mx.Lock() |
| 80 | add(entity) |
| 81 | mx.Unlock() |
| 82 | }(dir) |
| 83 | } |
| 84 | // Acquire all of the tokens to wait for any remaining workers to finish. |
| 85 | if err := sem.Acquire(ctx, int64(maxWorkers)); err != nil { |
| 86 | return err |
| 87 | } |
| 88 | d <- true |
| 89 | sem = nil |
| 90 | return nil |
| 91 | } |