Skip to content

Commit

Permalink
test: Reuse macOSAvailable code from Code-Hex/vz
Browse files Browse the repository at this point in the history
We want to avoid running the macOS13-specific tests on older macOS
versions.
  • Loading branch information
cfergeau committed Oct 10, 2023
1 parent 5c4bad2 commit deeea95
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions test/osversion.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package test

// The code in this file is heavily based on https://github.com/Code-Hex/vz/blob/40946b951fffa07406b272c582eda76de7c24028/osversion.go#L46-L70

import (
"errors"
"strconv"
"strings"
"sync"
"syscall"

"golang.org/x/mod/semver"
)

func macOSAvailable(version float64) error {
if macOSMajorMinorVersion() < version {
return ErrUnsupportedOSVersion
}
return nil
}

var (
// ErrUnsupportedOSVersion is returned when calling a method which is only
// available in newer macOS versions.
ErrUnsupportedOSVersion = errors.New("unsupported macOS version")

majorMinorVersion float64
majorMinorVersionOnce interface{ Do(func()) } = &sync.Once{}
)

func fetchMajorMinorVersion() (float64, error) {
osver, err := syscall.Sysctl("kern.osproductversion")
if err != nil {
return 0, err
}
prefix := "v"
majorMinor := strings.TrimPrefix(semver.MajorMinor(prefix+osver), prefix)
version, err := strconv.ParseFloat(majorMinor, 64)
if err != nil {
return 0, err
}
return version, nil
}

func macOSMajorMinorVersion() float64 {
majorMinorVersionOnce.Do(func() {
version, err := fetchMajorMinorVersion()
if err != nil {
panic(err)
}
majorMinorVersion = version
})
return majorMinorVersion
}

0 comments on commit deeea95

Please sign in to comment.