platform.go 968 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Package platform exposes variables and functions that deal with the
  2. // specific platform being run on, such as the OS name and CPU architecture.
  3. package platform
  4. import (
  5. "os"
  6. "runtime"
  7. "strings"
  8. "src.elv.sh/pkg/eval"
  9. "src.elv.sh/pkg/eval/vars"
  10. )
  11. var osHostname = os.Hostname // to allow mocking in unit tests
  12. type hostnameOpt struct{ StripDomain bool }
  13. func (o *hostnameOpt) SetDefaultOptions() {}
  14. func hostname(opts hostnameOpt) (string, error) {
  15. hostname, err := osHostname()
  16. if err != nil {
  17. return "", err
  18. }
  19. if !opts.StripDomain {
  20. return hostname, nil
  21. }
  22. parts := strings.SplitN(hostname, ".", 2)
  23. return parts[0], nil
  24. }
  25. var Ns = eval.BuildNsNamed("platform").
  26. AddVars(map[string]vars.Var{
  27. "arch": vars.NewReadOnly(runtime.GOARCH),
  28. "os": vars.NewReadOnly(runtime.GOOS),
  29. "is-unix": vars.NewReadOnly(isUnix),
  30. "is-windows": vars.NewReadOnly(isWindows),
  31. }).
  32. AddGoFns(map[string]any{
  33. "hostname": hostname,
  34. }).Ns()