Compare commits

...
7 Commits
Author SHA1 Message Date
AI BotandRiyyi 1159be59d0 Add safety check before package pruning
Verifies all state packages are installed locally before running
markAllAsDeps and orphan cleanup.
2026-05-04 23:28:58 +02:00
Riyyi 0fc0684801 Improve tarball selection when installing AUR packages 2026-05-04 22:47:07 +02:00
AI BotandRiyyi bcddfd13e7 Also install repo dependencies when installing AUR packages 2026-05-04 21:13:25 +02:00
Riyyi 4472bbc2e9 Add grill-me skill 2026-05-04 20:25:43 +02:00
Riyyi b371c74e9a Make tool request elevated privileges on-demand 2026-05-03 23:04:34 +02:00
Riyyi 76b83437ac Add safety check before rm -rf call 2026-05-03 22:17:51 +02:00
AI BotandRiyyi b04869f0e1 Move log to user owned directory 2026-05-03 21:29:49 +02:00
10 changed files with 253 additions and 65 deletions
+10
View File
@@ -0,0 +1,10 @@
---
name: grill-me
description: Interview the user relentlessly about a plan or design until reaching shared understanding, resolving each branch of the decision tree. Use when user wants to stress-test a plan, get grilled on their design, or mentions "grill me".
---
Interview me relentlessly about every aspect of this plan until we reach a shared understanding. Walk down each branch of the design tree, resolving dependencies between decisions one-by-one. For each question, provide your recommended answer.
Ask the questions one at a time.
If a question can be answered by exploring the codebase, explore the codebase instead.
+7 -13
View File
@@ -27,22 +27,22 @@ sudo mv declpac /usr/local/bin/
- pacman - pacman
- makepkg (for AUR support) - makepkg (for AUR support)
- git (for AUR support) - git (for AUR support)
- Root privileges - sudo/doas (root privileges)
## Usage ## Usage
```bash ```bash
# Single state file # Single state file
sudo declpac --state packages.txt declpac --state packages.txt
# Multiple state files # Multiple state files
sudo declpac --state base.txt --state apps.txt declpac --state base.txt --state apps.txt
# From stdin # From stdin
cat packages.txt | sudo declpac cat packages.txt | declpac
# Preview changes without applying # Preview changes without applying
sudo declpac --dry-run --state packages.txt declpac --dry-run --state packages.txt
``` ```
### State File Format ### State File Format
@@ -89,17 +89,11 @@ If the pacman database is older than 24 hours, it is automatically refreshed.
### Logging ### Logging
Operations are logged to `/var/log/declpac.log`. Operation are logged to `$XDG_STATE_HOME/declpac.log`
(or `~/.local/state/declpac.log` on fallback)
## Troubleshooting ## Troubleshooting
### Permission denied
Use sudo:
```bash
sudo declpac --state packages.txt
```
### Package not found ### Package not found
Check if the package exists: Check if the package exists:
+3
View File
@@ -8,6 +8,7 @@ import (
"github.com/urfave/cli/v3" "github.com/urfave/cli/v3"
"github.com/Riyyi/declpac/pkg/auth"
"github.com/Riyyi/declpac/pkg/input" "github.com/Riyyi/declpac/pkg/input"
"github.com/Riyyi/declpac/pkg/log" "github.com/Riyyi/declpac/pkg/log"
"github.com/Riyyi/declpac/pkg/output" "github.com/Riyyi/declpac/pkg/output"
@@ -97,6 +98,8 @@ func run(cfg *Config) error {
return nil return nil
} }
auth.Start()
if err := log.OpenLog(); err != nil { if err := log.OpenLog(); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err) fmt.Fprintf(os.Stderr, "error: %v\n", err)
return err return err
+104
View File
@@ -0,0 +1,104 @@
package auth
import (
"fmt"
"os/exec"
"regexp"
"strconv"
"time"
"github.com/Riyyi/declpac/pkg/log"
)
var tool string
var timeout time.Duration = 5 * time.Minute
var refreshCommand []string = []string{"-n", "true"}
// -----------------------------------------
// public
func Command(name string, args ...string) *exec.Cmd {
if tool == "" {
return log.Command(name, args...)
}
args = append([]string{name}, args...)
return log.Command(tool, args...)
}
func Run() {
exec.Command(tool, refreshCommand...).Run()
}
func Start() error {
err := detect()
if err != nil {
return err
}
// Automatically refresh privilege elevation to prevent user prompts
go func() {
for {
Run()
time.Sleep(timeout)
}
}()
return nil
}
// -----------------------------------------
// private
func detect() error {
tool = getTool()
if tool == "" {
return fmt.Errorf("no privilege elevation tool detected in PATH")
}
parseTimeout()
// We have to be a little faster than the actual timeout
timeout -= 30 * time.Second
return nil
}
func execLookPath(name string) string {
path, err := exec.LookPath(name)
if err != nil {
return ""
}
return path
}
func getTool() string {
sudo := execLookPath("sudo")
doas := execLookPath("doas")
if sudo != "" {
return "sudo"
}
if doas != "" {
return "doas"
}
return ""
}
func parseTimeout() {
switch tool {
case "sudo":
out, err := exec.Command("sudo", "sudo", "-V").CombinedOutput()
if err != nil {
return
}
re := regexp.MustCompile(`Authentication timestamp timeout: (\d+)\..*`)
matches := re.FindStringSubmatch(string(out))
if len(matches) == 2 {
if minutes, err := strconv.Atoi(matches[1]); err == nil {
timeout = time.Duration(minutes) * time.Minute
}
}
case "doas":
exec.Command("doas", "true").Run()
}
}
+5 -13
View File
@@ -6,6 +6,8 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/Riyyi/declpac/pkg/lib"
) )
var ErrEmptyList = errors.New("package list is empty") var ErrEmptyList = errors.New("package list is empty")
@@ -28,7 +30,7 @@ func ReadPackages(stateFiles []string) (map[string]bool, error) {
packages := make(map[string]bool) packages := make(map[string]bool)
for _, file := range stateFiles { for _, file := range stateFiles {
expanded := expandPath(file) expanded := lib.ExpandPath(file)
if err := readStateFile(expanded, packages); err != nil { if err := readStateFile(expanded, packages); err != nil {
return nil, err return nil, err
} }
@@ -51,27 +53,17 @@ func ReadPackages(stateFiles []string) (map[string]bool, error) {
// ----------------------------------------- // -----------------------------------------
// private // private
func expandPath(path string) string {
if strings.HasPrefix(path, "~/") {
home, err := os.UserHomeDir()
if err != nil {
return path
}
return filepath.Join(home, path[2:])
}
return path
}
func fileExists(path string) bool { func fileExists(path string) bool {
_, err := os.Stat(path) _, err := os.Stat(path)
return err == nil return err == nil
} }
func getImplicitStateFile() string { func getImplicitStateFile() string {
cfgDir, _ := os.UserConfigDir() cfgDir := os.Getenv("XDG_CONFIG_HOME")
if cfgDir == "" { if cfgDir == "" {
cfgDir = "~/.config" cfgDir = "~/.config"
} }
cfgDir = lib.ExpandPath(cfgDir)
return filepath.Join(cfgDir, "declpac") return filepath.Join(cfgDir, "declpac")
} }
+21
View File
@@ -0,0 +1,21 @@
package lib
import (
"os"
"path/filepath"
"strings"
)
// -----------------------------------------
// public
func ExpandPath(path string) string {
if strings.HasPrefix(path, "~/") {
home, err := os.UserHomeDir()
if err != nil {
return path
}
return filepath.Join(home, path[2:])
}
return path
}
+11 -2
View File
@@ -8,6 +8,8 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"time" "time"
"github.com/Riyyi/declpac/pkg/lib"
) )
var logFile *os.File var logFile *os.File
@@ -29,7 +31,7 @@ func Command(name string, args ...string) *exec.Cmd {
return exec.Command(name, args...) return exec.Command(name, args...)
} }
func Debug(format string, args ...interface{}) { func Debug(format string, args ...any) {
if !Verbose { if !Verbose {
return return
} }
@@ -41,11 +43,18 @@ func GetLogWriter() io.Writer {
} }
func OpenLog() error { func OpenLog() error {
logPath := filepath.Join("/var/log", "declpac.log") stateDir := os.Getenv("XDG_STATE_HOME")
if stateDir == "" {
stateDir = "~/.local/state"
}
stateDir = lib.ExpandPath(stateDir)
logPath := filepath.Join(stateDir, "declpac.log")
f, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) f, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil { if err != nil {
return err return err
} }
logFile = f logFile = f
writeTimestamp() writeTimestamp()
return nil return nil
+32
View File
@@ -84,6 +84,12 @@ func Sync(packages []string, noCheck bool, prune bool) (*output.Result, error) {
var removed int var removed int
if prune { if prune {
log.Debug("Sync: running prune sanity check...")
if err := pruneSanityCheck(packages); err != nil {
return nil, err
}
log.Debug("Sync: prune sanity check passed (%.2fs)", time.Since(start).Seconds())
log.Debug("Sync: marking all as deps...") log.Debug("Sync: marking all as deps...")
if err := markAllAsDeps(); err != nil { if err := markAllAsDeps(); err != nil {
return nil, err return nil, err
@@ -183,3 +189,29 @@ func markAllAsDeps() error {
log.Debug("markAllAsDeps: done (%.2fs)", time.Since(start).Seconds()) log.Debug("markAllAsDeps: done (%.2fs)", time.Since(start).Seconds())
return nil return nil
} }
// pruneSanityCheck checks if the installation of all state packages succeeded,
// before attempting to do package marking and orphan cleanup.
func pruneSanityCheck(statePackages []string) error {
start := time.Now()
log.Debug("pruneSanityCheck: starting...")
localPackages, err := read.List()
if err != nil {
return fmt.Errorf("failed to list local packages: %w", err)
}
var missing []string
for _, pkg := range statePackages {
if !slices.Contains(localPackages, pkg) {
missing = append(missing, pkg)
}
}
if len(missing) > 0 {
return fmt.Errorf("safety check: missing state packages: %v", missing)
}
log.Debug("pruneSanityCheck: done (%.2fs)", time.Since(start).Seconds())
return nil
}
+53 -36
View File
@@ -4,18 +4,16 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"os/user"
"strings" "strings"
"sync"
"time" "time"
"github.com/Riyyi/declpac/pkg/auth"
"github.com/Riyyi/declpac/pkg/fetch" "github.com/Riyyi/declpac/pkg/fetch"
"github.com/Riyyi/declpac/pkg/fetch/aur" "github.com/Riyyi/declpac/pkg/fetch/aur"
"github.com/Riyyi/declpac/pkg/log" "github.com/Riyyi/declpac/pkg/log"
) )
var sudoUser string
var sudoUserOnce sync.Once
type Result struct { type Result struct {
Installed int Installed int
Removed int Removed int
@@ -37,19 +35,18 @@ func InstallAUR(f *fetch.Fetcher, pkgName string, packageBase string, asDeps boo
return err return err
} }
sudoUser := getSudoUser() tmpDir := getTempDirName() + "/" + pkgName
tmpDir := "/tmp/declpac/" + pkgName if err := createTempDir(tmpDir); err != nil {
if err := createTempDir(sudoUser, tmpDir); err != nil {
return err return err
} }
defer os.RemoveAll(tmpDir) defer os.RemoveAll(tmpDir)
if err := cloneRepo(sudoUser, packageBase, tmpDir, logWriter); err != nil { if err := cloneRepo(packageBase, tmpDir, logWriter); err != nil {
return err return err
} }
log.Debug("InstallAUR: cloned (%.2fs)", time.Since(start).Seconds()) log.Debug("InstallAUR: cloned (%.2fs)", time.Since(start).Seconds())
if err := buildPackage(sudoUser, tmpDir, asDeps, logWriter); err != nil { if err := buildPackage(tmpDir, asDeps, logWriter); err != nil {
return err return err
} }
log.Debug("InstallAUR: built (%.2fs)", time.Since(start).Seconds()) log.Debug("InstallAUR: built (%.2fs)", time.Since(start).Seconds())
@@ -80,7 +77,7 @@ func MarkAs(packages []string, flag string, logWriter io.Writer) error {
} }
args := append([]string{"-D", "--" + flagName}, packages...) args := append([]string{"-D", "--" + flagName}, packages...)
cmd := log.Command("pacman", args...) cmd := auth.Command("pacman", args...)
cmd.Stdout = logWriter cmd.Stdout = logWriter
cmd.Stderr = logWriter cmd.Stderr = logWriter
err := cmd.Run() err := cmd.Run()
@@ -100,7 +97,7 @@ func RefreshDB(logWriter io.Writer) error {
logWriter = os.Stderr logWriter = os.Stderr
} }
cmd := log.Command("pacman", "-Syy") cmd := auth.Command("pacman", "-Syy")
cmd.Stdout = logWriter cmd.Stdout = logWriter
cmd.Stderr = logWriter cmd.Stderr = logWriter
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
@@ -127,7 +124,7 @@ func RemoveOrphans(orphans []string, logWriter io.Writer) (int, error) {
args := make([]string, 0, 3+len(orphans)) args := make([]string, 0, 3+len(orphans))
args = append(args, "pacman", "-Rns", "--noconfirm") args = append(args, "pacman", "-Rns", "--noconfirm")
args = append(args, orphans...) args = append(args, orphans...)
removeCmd := log.Command(args[0], args[1:]...) removeCmd := auth.Command(args[0], args[1:]...)
removeCmd.Stdout = logWriter removeCmd.Stdout = logWriter
removeCmd.Stderr = logWriter removeCmd.Stderr = logWriter
err := removeCmd.Run() err := removeCmd.Run()
@@ -150,7 +147,7 @@ func SyncPackages(packages []string, logWriter io.Writer) error {
} }
args := append([]string{"-S", "--needed", "--noconfirm"}, packages...) args := append([]string{"-S", "--needed", "--noconfirm"}, packages...)
cmd := log.Command("pacman", args...) cmd := auth.Command("pacman", args...)
cmd.Stdout = logWriter cmd.Stdout = logWriter
cmd.Stderr = logWriter cmd.Stderr = logWriter
err := cmd.Run() err := cmd.Run()
@@ -165,12 +162,12 @@ func SyncPackages(packages []string, logWriter io.Writer) error {
// ----------------------------------------- // -----------------------------------------
// private // private
func buildPackage(sudoUser string, tmpDir string, asDeps bool, logWriter io.Writer) error { func buildPackage(tmpDir string, asDeps bool, logWriter io.Writer) error {
makepkgArgs := []string{"makepkg", "-s", "--noconfirm"} makepkgArgs := []string{"-D", tmpDir, "-s", "--noconfirm"}
if asDeps { if asDeps {
makepkgArgs = append(makepkgArgs, "--asdeps") makepkgArgs = append(makepkgArgs, "--asdeps")
} }
makepkgCmd := log.Command("su", "-", sudoUser, "-c", "cd "+tmpDir+" && "+strings.Join(makepkgArgs, " ")) makepkgCmd := log.Command("makepkg", makepkgArgs...)
makepkgCmd.Stdout = logWriter makepkgCmd.Stdout = logWriter
makepkgCmd.Stderr = logWriter makepkgCmd.Stderr = logWriter
if err := makepkgCmd.Run(); err != nil { if err := makepkgCmd.Run(); err != nil {
@@ -179,9 +176,9 @@ func buildPackage(sudoUser string, tmpDir string, asDeps bool, logWriter io.Writ
return nil return nil
} }
func cloneRepo(sudoUser string, packageBase string, tmpDir string, logWriter io.Writer) error { func cloneRepo(packageBase string, tmpDir string, logWriter io.Writer) error {
cloneURL := "https://aur.archlinux.org/" + packageBase + ".git" cloneURL := "https://aur.archlinux.org/" + packageBase + ".git"
cloneCmd := log.Command("su", "-", sudoUser, "-c", "git clone "+cloneURL+" "+tmpDir) cloneCmd := log.Command("git", "clone", cloneURL, tmpDir)
cloneCmd.Stdout = logWriter cloneCmd.Stdout = logWriter
cloneCmd.Stderr = logWriter cloneCmd.Stderr = logWriter
if err := cloneCmd.Run(); err != nil { if err := cloneCmd.Run(); err != nil {
@@ -190,11 +187,21 @@ func cloneRepo(sudoUser string, packageBase string, tmpDir string, logWriter io.
return nil return nil
} }
func createTempDir(sudoUser string, tmpDir string) error { func createTempDir(tmpDir string) error {
mkdirCmd := log.Command("su", "-", sudoUser, "-c", "rm -rf "+tmpDir+" && mkdir -p "+tmpDir) if tmpDir == "" || tmpDir == "/" || !strings.HasPrefix(tmpDir, "/tmp") {
return fmt.Errorf("safety check: prevented malformed rm -rf call")
}
rmdirCmd := log.Command("rm", "-rf", tmpDir)
if err := rmdirCmd.Run(); err != nil {
return fmt.Errorf("failed to remove temp directory: %w", err)
}
mkdirCmd := log.Command("mkdir", "-p", tmpDir)
if err := mkdirCmd.Run(); err != nil { if err := mkdirCmd.Run(); err != nil {
return fmt.Errorf("failed to create temp directory: %w", err) return fmt.Errorf("failed to create temp directory: %w", err)
} }
return nil return nil
} }
@@ -208,6 +215,11 @@ func findPKGFile(pkgName string, dir string) (string, error) {
if !strings.HasSuffix(name, ".pkg.tar.zst") && !strings.HasSuffix(name, ".pkg.tar.gz") { if !strings.HasSuffix(name, ".pkg.tar.zst") && !strings.HasSuffix(name, ".pkg.tar.gz") {
continue continue
} }
// Skip packages that do not start with the exact package name, ex: sunshine-bin -> sunshine
if !strings.HasPrefix(name, pkgName) {
continue
}
// Skip packages that provide a debug package, ex: sunshine-bin -> sunshine-debug
if strings.HasPrefix(name, pkgName+"-debug") { if strings.HasPrefix(name, pkgName+"-debug") {
continue continue
} }
@@ -227,21 +239,17 @@ func getAURInfo(f *fetch.Fetcher, pkgName string, packageBase string) *aur.Packa
return &info return &info
} }
func getSudoUser() string { func getTempDirName() string {
sudoUserOnce.Do(func() { user, err := user.Current()
sudoUser = os.Getenv("SUDO_USER") if err != nil {
if sudoUser == "" { return "/tmp/declpac"
sudoUser = os.Getenv("USER")
if sudoUser == "" {
sudoUser = "root"
} }
}
}) return "/tmp/declpac-" + user.Username
return sudoUser
} }
func installBuiltPackage(pkgFile string, logWriter io.Writer) error { func installBuiltPackage(pkgFile string, logWriter io.Writer) error {
installCmd := log.Command("pacman", "-U", "--noconfirm", pkgFile) installCmd := auth.Command("pacman", "-U", "--noconfirm", pkgFile)
installCmd.Stdout = logWriter installCmd.Stdout = logWriter
installCmd.Stderr = logWriter installCmd.Stderr = logWriter
if err := installCmd.Run(); err != nil { if err := installCmd.Run(); err != nil {
@@ -265,17 +273,26 @@ func resolveAndInstallDeps(f *fetch.Fetcher, aurInfo *aur.Package, logWriter io.
return fmt.Errorf("failed to resolve dependencies: %w", err) return fmt.Errorf("failed to resolve dependencies: %w", err)
} }
var aurDeps []string var repoDeps, aurDeps []string
for _, dep := range depends { for _, dep := range depends {
info := resolved[dep] info := resolved[dep]
if info.Installed { if info.Installed {
continue continue
} }
if info.Exists { pkg := dep
continue if info.Provided != "" {
pkg = info.Provided
} }
if info.InAUR { if info.Exists {
aurDeps = append(aurDeps, dep) repoDeps = append(repoDeps, pkg)
} else if info.InAUR {
aurDeps = append(aurDeps, pkg)
}
}
if len(repoDeps) > 0 {
if err := SyncPackages(repoDeps, logWriter); err != nil {
return fmt.Errorf("failed to install repo dependencies: %w", err)
} }
} }
+6
View File
@@ -5,6 +5,12 @@
"source": "JuliusBrussee/caveman", "source": "JuliusBrussee/caveman",
"sourceType": "github", "sourceType": "github",
"computedHash": "a818cdc41dcfaa50dd891c5cb5e5705968338de02e7e37949ca56e8c30ad4176" "computedHash": "a818cdc41dcfaa50dd891c5cb5e5705968338de02e7e37949ca56e8c30ad4176"
},
"grill-me": {
"source": "mattpocock/skills",
"sourceType": "github",
"skillPath": "skills/productivity/grill-me/SKILL.md",
"computedHash": "784f0dbb7403b0f00324bce9a112f715342777a0daee7bbb7385f9c6f0a170ea"
} }
} }
} }