operatingsystem_unix.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2020 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //go:build freebsd || darwin || linux
  15. // +build freebsd darwin linux
  16. package machine
  17. import (
  18. "fmt"
  19. "io/ioutil"
  20. "os"
  21. "os/exec"
  22. "regexp"
  23. "runtime"
  24. "strings"
  25. )
  26. var rex = regexp.MustCompile("(PRETTY_NAME)=(.*)")
  27. // getOperatingSystem gets the name of the current operating system.
  28. func getOperatingSystem() (string, error) {
  29. if runtime.GOOS == "darwin" || runtime.GOOS == "freebsd" {
  30. cmd := exec.Command("uname", "-s")
  31. osName, err := cmd.Output()
  32. if err != nil {
  33. return "", err
  34. }
  35. return string(osName), nil
  36. }
  37. bytes, err := ioutil.ReadFile("/etc/os-release")
  38. if err != nil && os.IsNotExist(err) {
  39. // /usr/lib/os-release in stateless systems like Clear Linux
  40. bytes, err = ioutil.ReadFile("/usr/lib/os-release")
  41. }
  42. if err != nil {
  43. return "", fmt.Errorf("error opening file : %v", err)
  44. }
  45. line := rex.FindAllStringSubmatch(string(bytes), -1)
  46. if len(line) > 0 {
  47. return strings.Trim(line[0][2], "\""), nil
  48. }
  49. return "Linux", nil
  50. }