modbot/lib/readers/os.go

75 lines
1.9 KiB
Go
Raw Permalink Normal View History

// modbot is a system information agregator
2024-07-30 04:02:05 -04:00
// Copyright (C) 2024 frosty <inthishouseofcards@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
2024-08-25 02:27:55 -04:00
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
2024-07-30 04:02:05 -04:00
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2024-08-25 02:27:55 -04:00
// GNU General Public License for more details.
2024-07-30 04:02:05 -04:00
//
2024-08-25 02:27:55 -04:00
// You should have received a copy of the GNU General Public License
2024-07-30 04:02:05 -04:00
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package readers
import (
"bufio"
"fmt"
2024-07-30 04:02:05 -04:00
"os"
"strings"
)
type OsInfo struct {
Name string
PrettyName string
Version string
}
func ReadOs() func() (interface{}, error) {
return func() (interface{}, error) {
const osPath = "/lib/os-release"
file, err := os.Open(osPath)
if err != nil {
return OsInfo{}, fmt.Errorf("failed to open %s: %w", osPath, err)
}
defer file.Close()
2024-07-30 04:02:05 -04:00
var osName, osPrettyName, osVersion string
scanner := bufio.NewScanner(file)
2024-07-30 04:02:05 -04:00
for scanner.Scan() {
line := scanner.Text()
line = strings.ReplaceAll(line, "\"", "")
fields := strings.SplitN(line, "=", 2)
if len(fields) < 2 {
return OsInfo{}, fmt.Errorf("unexpected format in %s: %s", osPath, line)
}
2024-07-30 04:02:05 -04:00
switch {
case strings.HasPrefix(line, "NAME"):
osName = fields[1]
case strings.HasPrefix(line, "PRETTY_NAME"):
osPrettyName = fields[1]
case strings.HasPrefix(line, "VERSION_ID"):
osVersion = fields[1]
}
2024-07-30 04:02:05 -04:00
}
if err := scanner.Err(); err != nil {
return OsInfo{}, fmt.Errorf("failed to read from %s: %w", osPath, err)
}
return OsInfo{
Name: osName,
PrettyName: osPrettyName,
Version: osVersion,
}, nil
}
}