github.com/kolbycrouch/elvish@v0.14.1-0.20210614162631-215b9ac1c423/pkg/eval/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  //elvdoc:var arch
    15  //
    16  // The architecture of the platform; e.g. amd64, arm, ppc.
    17  // This corresponds to Go's
    18  // [`GOARCH`](https://pkg.go.dev/runtime?tab=doc#pkg-constants) constant.
    19  // This is read-only.
    20  
    21  //elvdoc:var os
    22  //
    23  // The name of the operating system; e.g. darwin (macOS), linux, etc.
    24  // This corresponds to Go's
    25  // [`GOOS`](https://pkg.go.dev/runtime?tab=doc#pkg-constants) constant.
    26  // This is read-only.
    27  
    28  //elvdoc:var is-unix
    29  //
    30  // Whether or not the platform is UNIX-like. This includes Linux, macOS
    31  // (Darwin), FreeBSD, NetBSD, and OpenBSD. This can be used to decide, for
    32  // example, if the `unix` module is usable.
    33  // This is read-only.
    34  
    35  //elvdoc:var is-windows
    36  //
    37  // Whether or not the platform is Microsoft Windows.
    38  // This is read-only.
    39  
    40  //elvdoc:fn hostname &strip-domain=false
    41  //
    42  // Outputs the hostname of the system. If the option `&strip-domain` is `$true`,
    43  // strips the part after the first dot.
    44  //
    45  // This function throws an exception if it cannot determine the hostname. It is
    46  // implemented using Go's [`os.Hostname`](https://golang.org/pkg/os/#Hostname).
    47  //
    48  // Examples:
    49  //
    50  // ```elvish-transcript
    51  // ~> platform:hostname
    52  // ▶ lothlorien.elv.sh
    53  // ~> platform:hostname &strip-domain=$true
    54  // ▶ lothlorien
    55  // ```
    56  
    57  var osHostname = os.Hostname // to allow mocking in unit tests
    58  
    59  type hostnameOpt struct{ StripDomain bool }
    60  
    61  func (o *hostnameOpt) SetDefaultOptions() {}
    62  
    63  func hostname(opts hostnameOpt) (string, error) {
    64  	hostname, err := osHostname()
    65  	if err != nil {
    66  		return "", err
    67  	}
    68  	if !opts.StripDomain {
    69  		return hostname, nil
    70  	}
    71  	parts := strings.SplitN(hostname, ".", 2)
    72  	return parts[0], nil
    73  }
    74  
    75  var Ns = eval.NsBuilder{
    76  	"arch":       vars.NewReadOnly(runtime.GOARCH),
    77  	"os":         vars.NewReadOnly(runtime.GOOS),
    78  	"is-unix":    vars.NewReadOnly(isUnix),
    79  	"is-windows": vars.NewReadOnly(isWindows),
    80  }.AddGoFns("platform:", map[string]interface{}{
    81  	"hostname": hostname,
    82  }).Ns()