forked from denisbrodbeck/machineid
-
Notifications
You must be signed in to change notification settings - Fork 13
/
id_darwin.go
51 lines (46 loc) · 1.28 KB
/
id_darwin.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// +build darwin
package machineid
import (
"bytes"
"fmt"
"os"
"strings"
)
// machineID returns the uuid returned by `ioreg -rd1 -c IOPlatformExpertDevice`.
// If there is an error running the commad an empty string is returned.
func machineID() (string, error) {
buf, err := runIoreg(false)
if err != nil {
// cron jobs run with a very minimal environment, including a very basic PATH.
// ioreg is in /usr/sbin, so it won't be found as a command based on that basic PATH
// let's try to use absolute path
if buf, err = runIoreg(true); err != nil {
return "", err
}
}
id, err := extractID(buf.String())
if err != nil {
return "", err
}
return trim(id), nil
}
func extractID(lines string) (string, error) {
for _, line := range strings.Split(lines, "\n") {
if strings.Contains(line, "IOPlatformUUID") {
parts := strings.SplitAfter(line, `" = "`)
if len(parts) == 2 {
return strings.TrimRight(parts[1], `"`), nil
}
}
}
return "", fmt.Errorf("Failed to extract 'IOPlatformUUID' value from `ioreg` output.\n%s", lines)
}
func runIoreg(tryAbsolutePath bool) (buf *bytes.Buffer, err error) {
buf = &bytes.Buffer{}
cmd := "ioreg"
if tryAbsolutePath {
cmd = "/usr/sbin/ioreg"
}
err = run(buf, os.Stderr, cmd, "-rd1", "-c", "IOPlatformExpertDevice")
return
}