summaryrefslogtreecommitdiff
path: root/internal/resource/pkg
diff options
context:
space:
mode:
Diffstat (limited to 'internal/resource/pkg')
-rw-r--r--internal/resource/pkg/dnf.go34
-rw-r--r--internal/resource/pkg/pkg.go47
2 files changed, 81 insertions, 0 deletions
diff --git a/internal/resource/pkg/dnf.go b/internal/resource/pkg/dnf.go
new file mode 100644
index 0000000..ad03da2
--- /dev/null
+++ b/internal/resource/pkg/dnf.go
@@ -0,0 +1,34 @@
+package pkg
+
+import (
+ "fmt"
+ "log"
+
+ "codeberg.org/snonux/gonf/internal/exec"
+)
+
+func applyDNF(name string, ensure Ensure) error {
+ var args []string
+
+ switch ensure {
+ case PkgPresent:
+ args = []string{"install", "-y", name}
+ case PkgAbsent:
+ args = []string{"remove", "-y", name}
+ case PkgLatest:
+ args = []string{"install", "-y", name}
+ default:
+ log.Fatalf("unsupported ensure state: %v", ensure)
+ }
+
+ stdout, stderr, exitCode, err := exec.Run("dnf", args...)
+ if err != nil {
+ return fmt.Errorf("failed to execute dnf: %w", err)
+ }
+
+ if exitCode != 0 {
+ return fmt.Errorf("dnf failed with exit code %d: %s\n%s", exitCode, stdout, stderr)
+ }
+
+ return nil
+}
diff --git a/internal/resource/pkg/pkg.go b/internal/resource/pkg/pkg.go
new file mode 100644
index 0000000..72f098c
--- /dev/null
+++ b/internal/resource/pkg/pkg.go
@@ -0,0 +1,47 @@
+package pkg
+
+import (
+ "errors"
+ "os"
+)
+
+type Ensure int
+
+const (
+ PkgPresent Ensure = iota
+ PkgAbsent
+ PkgLatest
+)
+
+type applyFunc func(name string, ensure Ensure) error
+
+func Present(name string, ensure Ensure) error {
+ bin, err := detect()
+ if err != nil {
+ return err
+ }
+
+ var applyFunc applyFunc
+
+ switch bin {
+ case "dnf":
+ applyFunc = applyDNF
+ }
+
+ return applyFunc(name, ensure)
+}
+
+func detect() (string, error) {
+ switch {
+ case exists("/etc/fedora-release"):
+ fallthrough
+ case exists("/etc/rocky-release"):
+ return "dnf", nil
+ }
+ return "", errors.New("unable to detect package manager!")
+}
+
+func exists(path string) bool {
+ _, err := os.Stat(path)
+ return err == nil
+}