Introduce ConcurrentMap util

This commit is contained in:
Jesse Duffield 2023-10-05 18:43:12 +11:00
parent 86bb73cff1
commit 16369dc3c2
3 changed files with 52 additions and 29 deletions

View file

@ -568,38 +568,26 @@ func (self *CommitLoader) getMergeBase(refName string) string {
}
func (self *CommitLoader) getExistingMainBranches() []string {
var existingBranches []string
var wg sync.WaitGroup
mainBranches := self.UserConfig.Git.MainBranches
existingBranches = make([]string, len(mainBranches))
for i, branchName := range mainBranches {
wg.Add(1)
i := i
branchName := branchName
go utils.Safe(func() {
defer wg.Done()
existingBranches := utils.ConcurrentMap(mainBranches, func(mainBranch string) string {
// Try to determine upstream of local main branch
if ref, err := self.cmd.New(
NewGitCmd("rev-parse").Arg("--symbolic-full-name", mainBranch+"@{u}").ToArgv(),
).DontLog().RunWithOutput(); err == nil {
return strings.TrimSpace(ref)
}
// Try to determine upstream of local main branch
if ref, err := self.cmd.New(
NewGitCmd("rev-parse").Arg("--symbolic-full-name", branchName+"@{u}").ToArgv(),
).DontLog().RunWithOutput(); err == nil {
existingBranches[i] = strings.TrimSpace(ref)
return
}
// If this failed, fallback to the local branch
ref := "refs/heads/" + mainBranch
if err := self.cmd.New(
NewGitCmd("rev-parse").Arg("--verify", "--quiet", ref).ToArgv(),
).DontLog().Run(); err == nil {
return ref
}
// If this failed, fallback to the local branch
ref := "refs/heads/" + branchName
if err := self.cmd.New(
NewGitCmd("rev-parse").Arg("--verify", "--quiet", ref).ToArgv(),
).DontLog().Run(); err == nil {
existingBranches[i] = ref
}
})
}
wg.Wait()
return ""
})
existingBranches = lo.Filter(existingBranches, func(branch string, _ int) bool {
return branch != ""

View file

@ -1,6 +1,10 @@
package utils
import "golang.org/x/exp/slices"
import (
"sync"
"golang.org/x/exp/slices"
)
// NextIndex returns the index of the element that comes after the given number
func NextIndex(numbers []int, currentNumber int) int {
@ -179,3 +183,24 @@ func Shift[T any](slice []T) (T, []T) {
slice = slice[1:]
return value, slice
}
// Map function which handles each element in its own goroutine
func ConcurrentMap[T any, V any](items []T, fn func(T) V) []V {
results := make([]V, len(items))
var wg sync.WaitGroup
for i, item := range items {
i := i
item := item
wg.Add(1)
go func() {
defer wg.Done()
results[i] = fn(item)
}()
}
wg.Wait()
return results
}

View file

@ -315,3 +315,13 @@ func TestMoveElement(t *testing.T) {
})
})
}
func TestConcurrentMap(t *testing.T) {
in := []int{1, 2, 3}
out := ConcurrentMap(in, func(i int) int {
return i * 2
})
assert.EqualValues(t, []int{2, 4, 6}, out)
}