final: refactor for removal of system package and reduction of interactions to state package

State query command has been moved to main where it belongs, "system" information are now fetched in app.New and stored in *App with accessors for relevant values. Exit (cleanup-related) functions are separated into its dedicated "final" package.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
This commit is contained in:
2024-09-16 20:31:15 +09:00
parent d49b97b1d4
commit 8bdae74ebe
20 changed files with 324 additions and 286 deletions

View File

@@ -5,6 +5,7 @@ import (
"fmt"
"os"
"os/user"
"path"
"strconv"
"git.ophivana.moe/cat/fortify/internal/state"
@@ -12,18 +13,25 @@ import (
"git.ophivana.moe/cat/fortify/internal/verbose"
)
const (
xdgRuntimeDir = "XDG_RUNTIME_DIR"
)
type App struct {
launchOptionText string
uid int // assigned
env []string // modified via AppendEnv
command []string // set on initialisation
uid int
env []string
command []string
launchOptionText string // set on initialisation
launchOption uint8 // assigned
launchOption uint8
toolPath string
sharePath string // set on initialisation
runtimePath string // assigned
runDirPath string // assigned
toolPath string // assigned
enablements state.Enablements
*user.User
enablements state.Enablements // set via setEnablement
*user.User // assigned
// absolutely *no* method of this type is thread-safe
// so don't treat it as if it is
@@ -33,6 +41,10 @@ func (a *App) LaunchOption() uint8 {
return a.launchOption
}
func (a *App) RunDir() string {
return a.runDirPath
}
func (a *App) setEnablement(e state.Enablement) {
if a.enablements.Has(e) {
panic("enablement " + e.String() + " set twice")
@@ -42,8 +54,25 @@ func (a *App) setEnablement(e state.Enablement) {
}
func New(userName string, args []string, launchOptionText string) *App {
a := &App{command: args, launchOptionText: launchOptionText}
a := &App{
command: args,
launchOptionText: launchOptionText,
sharePath: path.Join(os.TempDir(), "fortify."+strconv.Itoa(os.Geteuid())),
}
// runtimePath, runDirPath
if r, ok := os.LookupEnv(xdgRuntimeDir); !ok {
fmt.Println("Env variable", xdgRuntimeDir, "unset")
// too early for fatal
os.Exit(1)
} else {
a.runtimePath = r
a.runDirPath = path.Join(a.runtimePath, "fortify")
verbose.Println("Runtime directory at", a.runDirPath)
}
// *user.User
if u, err := user.Lookup(userName); err != nil {
if errors.As(err, new(user.UnknownUserError)) {
fmt.Println("unknown user", userName)
@@ -58,6 +87,7 @@ func New(userName string, args []string, launchOptionText string) *App {
a.User = u
}
// uid
if u, err := strconv.Atoi(a.Uid); err != nil {
// usually unreachable
panic("uid parse")
@@ -70,6 +100,7 @@ func New(userName string, args []string, launchOptionText string) *App {
verbose.Println("System booted with systemd as init system (PID 1).")
}
// launchOption, toolPath
switch a.launchOptionText {
case "sudo":
a.launchOption = LaunchMethodSudo