github.com/markusbkk/elvish@v0.0.0-20231204143114-91dc52438621/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 "github.com/markusbkk/elvish/pkg/eval" 11 "github.com/markusbkk/elvish/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 41 // 42 // ```elvish 43 // platform:hostname &strip-domain=$false 44 // ``` 45 // 46 // Outputs the hostname of the system. If the option `&strip-domain` is `$true`, 47 // strips the part after the first dot. 48 // 49 // This function throws an exception if it cannot determine the hostname. It is 50 // implemented using Go's [`os.Hostname`](https://golang.org/pkg/os/#Hostname). 51 // 52 // Examples: 53 // 54 // ```elvish-transcript 55 // ~> platform:hostname 56 // ▶ lothlorien.elv.sh 57 // ~> platform:hostname &strip-domain=$true 58 // ▶ lothlorien 59 // ``` 60 61 var osHostname = os.Hostname // to allow mocking in unit tests 62 63 type hostnameOpt struct{ StripDomain bool } 64 65 func (o *hostnameOpt) SetDefaultOptions() {} 66 67 func hostname(opts hostnameOpt) (string, error) { 68 hostname, err := osHostname() 69 if err != nil { 70 return "", err 71 } 72 if !opts.StripDomain { 73 return hostname, nil 74 } 75 parts := strings.SplitN(hostname, ".", 2) 76 return parts[0], nil 77 } 78 79 var Ns = eval.BuildNsNamed("platform"). 80 AddVars(map[string]vars.Var{ 81 "arch": vars.NewReadOnly(runtime.GOARCH), 82 "os": vars.NewReadOnly(runtime.GOOS), 83 "is-unix": vars.NewReadOnly(isUnix), 84 "is-windows": vars.NewReadOnly(isWindows), 85 }). 86 AddGoFns(map[string]interface{}{ 87 "hostname": hostname, 88 }).Ns()