util: port sd_booted function

Manpage provided by systemd states that the sd_booted function internally "checks whether the directory /run/systemd/system/ exists", as well as that "a simple check like this can also be implemented trivially in shell or any other language". This implies the behaviour of this function can be expected to be stable.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
This commit is contained in:
Ophestra Umiker 2024-07-11 01:13:41 +09:00
parent 94c69806ef
commit 65c02b540d
Signed by: cat
SSH Key Fingerprint: SHA256:gQ67O0enBZ7UdZypgtspB2FDM1g3GVw8nX0XSdcFw8Q
1 changed files with 28 additions and 0 deletions

28
util.go Normal file
View File

@ -0,0 +1,28 @@
package main
import (
"errors"
"fmt"
"io/fs"
"os"
)
const (
systemdCheckPath = "/run/systemd/system"
)
// https://www.freedesktop.org/software/systemd/man/sd_booted.html
func sdBooted() bool {
_, err := os.Stat(systemdCheckPath)
if err != nil {
if verbose {
if errors.Is(err, fs.ErrNotExist) {
fmt.Println("System not booted through systemd")
} else {
fmt.Println("Error accessing", systemdCheckPath+":", err.Error())
}
}
return false
}
return true
}