| 1 | |
| 2 | |
| 3 | package hostimage |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "runtime" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | ) |
| 14 | |
| 15 | func Host(ctx context.Context) (Identity, error) { |
| 16 | if runtime.GOOS == "darwin" { |
| 17 | output, err := exec.CommandContext(ctx, "/usr/bin/sw_vers").Output() |
| 18 | if err != nil { |
| 19 | return Identity{}, err |
| 20 | } |
| 21 | identity := Identity{System: "macos", Arch: runtime.GOARCH} |
| 22 | for _, line := range strings.Split(string(output), "\n") { |
| 23 | key, value, _ := strings.Cut(line, ":") |
| 24 | switch key { |
| 25 | case "ProductVersion": |
| 26 | identity.Version = strings.TrimSpace(value) |
| 27 | case "BuildVersion": |
| 28 | identity.Build = strings.TrimSpace(value) |
| 29 | } |
| 30 | } |
| 31 | return identity, nil |
| 32 | } |
| 33 | data, err := os.ReadFile("/etc/os-release") |
| 34 | if err != nil { |
| 35 | return Identity{}, err |
| 36 | } |
| 37 | return linuxIdentity(string(data)) |
| 38 | } |
| 39 | |
| 40 | func linuxIdentity(data string) (Identity, error) { |
| 41 | values := make(map[string]string) |
| 42 | for _, line := range strings.Split(data, "\n") { |
| 43 | key, value, ok := strings.Cut(line, "=") |
| 44 | if !ok { |
| 45 | continue |
| 46 | } |
| 47 | if strings.HasPrefix(value, `"`) { |
| 48 | unquoted, err := strconv.Unquote(value) |
| 49 | if err != nil { |
| 50 | return Identity{}, err |
| 51 | } |
| 52 | value = unquoted |
| 53 | } else { |
| 54 | value = strings.Trim(value, "'") |
| 55 | } |
| 56 | values[key] = value |
| 57 | } |
| 58 | version := values["VERSION_ID"] |
| 59 | if values["ID"] == "debian" { |
| 60 | version = strings.SplitN(version, ".", 2)[0] |
| 61 | } |
| 62 | identity := Identity{System: values["ID"] + "-" + version, Version: version, Arch: runtime.GOARCH} |
| 63 | switch identity.System { |
| 64 | case "debian-12", "debian-13", "ubuntu-22.04", "ubuntu-24.04": |
| 65 | return identity, nil |
| 66 | default: |
| 67 | return Identity{}, fmt.Errorf("当前尚未适配 %s 的本机系统创建,仍可选择 Debian 13", values["PRETTY_NAME"]) |
| 68 | } |
| 69 | } |