hnakra/cli/cli.go
2023-05-31 15:52:33 -04:00

38 lines
1.1 KiB
Go

// Package cli provides utilities for writing command line utilities that
// interact with services.
package cli
import "os"
import "fmt"
import "flag"
import "strings"
// Sayf is like Printf, but prints the program name before the message. This is
// used for printing messages and errors.
func Sayf (format string, values ...any) {
Printf(os.Args[0] + ": " + format, values...)
}
// Printf prints to stderr.
func Printf (format string, values ...any) {
fmt.Fprintf(flag.CommandLine.Output(), format, values...)
}
// ServiceUser returns the system user that corresponds to the given service
// name. This is not necissarily equivalent Hnakra user, although it is good
// practice to have a 1:1 correspondance between them.
func ServiceUser (service string) string {
return "hn-" + strings.ToLower(service)
}
// NeedRoot halts the program and displays an error if it is not being run as
// root. This should be called whenever an operation takes place that requires
// root privelages.
func NeedRoot() {
uid := os.Getuid()
if uid != 0 {
Sayf("this utility must be run as root")
os.Exit(1)
}
}