github.com/kubri/kubri@v0.5.1-0.20240317001612-bda2aaef967e/integrations/sparkle/os.go (about) 1 package sparkle 2 3 import ( 4 "errors" 5 "fmt" 6 "path" 7 8 "github.com/dlclark/regexp2" 9 ) 10 11 type OS uint8 12 13 const ( 14 Unknown OS = iota 15 MacOS 16 Windows 17 Windows64 18 Windows32 19 ) 20 21 var ErrUnknownOS = errors.New("unknown os") 22 23 func (os OS) String() string { 24 switch os { 25 default: 26 return "" 27 case MacOS: 28 return "macos" 29 case Windows: 30 return "windows" 31 case Windows64: 32 return "windows-x64" 33 case Windows32: 34 return "windows-x86" 35 } 36 } 37 38 func (os OS) MarshalText() ([]byte, error) { 39 if os > Windows32 { 40 return nil, ErrUnknownOS 41 } 42 return []byte(os.String()), nil 43 } 44 45 func (os *OS) UnmarshalText(text []byte) error { 46 s := string(text) 47 for i := Unknown; i <= Windows32; i++ { 48 if i.String() == s { 49 *os = i 50 return nil 51 } 52 } 53 return fmt.Errorf("%w: %s", ErrUnknownOS, text) 54 } 55 56 func isOS(os, target OS) bool { 57 switch target { 58 case os, Unknown: 59 return true 60 case Windows: 61 return os > Windows 62 } 63 return false 64 } 65 66 //nolint:gochecknoglobals 67 var ( 68 reWin64 = regexp2.MustCompile(`amd64|x64|x86[\W_]?64|64[\W_]?bit`, regexp2.IgnoreCase) 69 reWin32 = regexp2.MustCompile(`386|x86(?![\W_]?64)|ia32|32[\W_]?bit`, regexp2.IgnoreCase) 70 ) 71 72 func detectOS(name string) OS { 73 ext := path.Ext(name) 74 switch ext { 75 case "": 76 case ".dmg", ".pkg", ".mpkg": 77 return MacOS 78 case ".exe", ".msi": 79 is64, _ := reWin64.MatchString(name) 80 is32, _ := reWin32.MatchString(name) 81 switch { 82 case is64 == is32: 83 case is64: 84 return Windows64 85 case is32: 86 return Windows32 87 } 88 return Windows 89 } 90 91 return Unknown 92 }