src.elv.sh@v0.21.0-dev.0.20240515223629-06979efb9a2a/pkg/mods/platform/platform.go (about)

     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  
     5  import (
     6  	"os"
     7  	"runtime"
     8  	"strings"
     9  
    10  	"src.elv.sh/pkg/eval"
    11  	"src.elv.sh/pkg/eval/vars"
    12  )
    13  
    14  var osHostname = os.Hostname // to allow mocking in unit tests
    15  
    16  type hostnameOpt struct{ StripDomain bool }
    17  
    18  func (o *hostnameOpt) SetDefaultOptions() {}
    19  
    20  func hostname(opts hostnameOpt) (string, error) {
    21  	hostname, err := osHostname()
    22  	if err != nil {
    23  		return "", err
    24  	}
    25  	if !opts.StripDomain {
    26  		return hostname, nil
    27  	}
    28  	parts := strings.SplitN(hostname, ".", 2)
    29  	return parts[0], nil
    30  }
    31  
    32  var Ns = eval.BuildNsNamed("platform").
    33  	AddVars(map[string]vars.Var{
    34  		"arch":       vars.NewReadOnly(runtime.GOARCH),
    35  		"os":         vars.NewReadOnly(runtime.GOOS),
    36  		"is-unix":    vars.NewReadOnly(isUnix),
    37  		"is-windows": vars.NewReadOnly(isWindows),
    38  	}).
    39  	AddGoFns(map[string]any{
    40  		"hostname": hostname,
    41  	}).Ns()