Skip to content

Commit

Permalink
Fix wg implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
matbme committed Dec 1, 2023
1 parent 4e2e9a3 commit b89936f
Showing 1 changed file with 29 additions and 11 deletions.
40 changes: 29 additions & 11 deletions diff/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"cmp"
"regexp"
"strconv"
"sync"
)

type Package map[string]string
Expand Down Expand Up @@ -82,29 +83,53 @@ func CompareVersions(a, b string) int {
return compResult
}

func processPackage(pkg, oldVersion, newVersion string, c chan<- struct{ PackageDiff; int }, wg *sync.WaitGroup) {
func processPackage(pkg, oldVersion, newVersion string, c chan<- struct {
PackageDiff
int
}, wg *sync.WaitGroup) {
defer wg.Done()

result := CompareVersions(oldVersion, newVersion)
c <- struct{ PackageDiff; int }{PackageDiff{pkg, newVersion, oldVersion}, result}
c <- struct {
PackageDiff
int
}{PackageDiff{pkg, newVersion, oldVersion}, result}
}

// PackageDiff returns the difference in packages between two images, organized into
// four slices: Added, Upgraded, Downgraded, and Removed packages, respectively.
func DiffPackages(oldPackages, newPackages Package) ([]PackageDiff, []PackageDiff, []PackageDiff, []PackageDiff) {
var wg sync.WaitGroup
c := make(chan struct{ PackageDiff; int }, len(oldPackages))
c := make(chan struct {
PackageDiff
int
}, len(oldPackages))

for pkg, oldVersion := range oldPackages {
wg.Add(1)

if newVersion, ok := newPackages[pkg]; ok {
go processPackage(pkg, oldVersion, newVersion, c, &wg)
} else {
go processPackage(pkg, oldVersion, "", c, &wg)
c <- struct {
PackageDiff
int
}{PackageDiff{pkg, oldVersion, ""}, 2}
wg.Done()
}
}

removed := []PackageDiff{}
wg.Add(1)
go func() {
for pkg, version := range newPackages {
if _, ok := oldPackages[pkg]; !ok {
removed = append(removed, PackageDiff{pkg, "", version})
}
}
wg.Done()
}()

go func() {
wg.Wait()
close(c)
Expand All @@ -113,8 +138,6 @@ func DiffPackages(oldPackages, newPackages Package) ([]PackageDiff, []PackageDif
added := []PackageDiff{}
upgraded := []PackageDiff{}
downgraded := []PackageDiff{}
removed := []PackageDiff{}

for pkgResult := range c {
switch pkgResult.int {
case -1:
Expand All @@ -126,10 +149,5 @@ func DiffPackages(oldPackages, newPackages Package) ([]PackageDiff, []PackageDif
}
}

// Collect removed packages
for pkg, version := range newPackages {
removed = append(removed, PackageDiff{pkg, "", version})
}

return added, upgraded, downgraded, removed
}

0 comments on commit b89936f

Please sign in to comment.