File: distro.go

package info (click to toggle)
golang-github-tredoe-osutil 1.5.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 476 kB
  • sloc: makefile: 4
file content (75 lines) | stat: -rw-r--r-- 1,609 bytes parent folder | download
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright 2013 Jonas mg
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

// Package distro detects the Linux distribution.
package distro

import (
	"os"

	"github.com/tredoe/osutil/config/shconf"
)

// Distro represents a distribution of Linux system.
type Distro int

// Most used Linux distributions.
const (
	DistroUnknown Distro = iota
	Arch
	CentOS
	Debian
	Fedora
	Manjaro
	OpenSUSE
	Ubuntu
)

var distroNames = [...]string{
	DistroUnknown: "unknown distribution",
	Arch:          "Arch",
	CentOS:        "CentOS",
	Debian:        "Debian",
	Fedora:        "Fedora",
	Manjaro:       "Manjaro",
	OpenSUSE:      "openSUSE",
	Ubuntu:        "Ubuntu",
}

func (s Distro) String() string { return distroNames[s] }

var idToDistro = map[string]Distro{
	"arch":                Arch,
	"manjaro":             Manjaro, // based on Arch
	"centos":              CentOS,
	"debian":              Debian,
	"fedora":              Fedora,
	"opensuse-leap":       OpenSUSE,
	"opensuse-tumbleweed": OpenSUSE,
	"ubuntu":              Ubuntu,
}

// Detect returns the Linux distribution.
func Detect() (Distro, error) {
	var id string
	var err error

	if _, err = os.Stat("/etc/os-release"); !os.IsNotExist(err) {
		cfg, err := shconf.ParseFile("/etc/os-release")
		if err != nil {
			return 0, err
		}
		if id, err = cfg.Get("ID"); err != nil {
			return 0, err
		}

		if v, found := idToDistro[id]; found {
			return v, nil
		}
	}

	return DistroUnknown, nil
}