git » chasquid » commit ad03885

chasquid-util: Fix creating the directory on user-add

author Alberto Bertogli
2025-01-20 23:31:32 UTC
committer Alberto Bertogli
2025-01-20 23:31:32 UTC
parent 2f17f570b31c5913412e91a5a665f1a729dc9be7

chasquid-util: Fix creating the directory on user-add

`chasquid-util user-add` is meant to create the domain directory if it
doesn't exist; however there's a bug that makes this not happen, and
instead the command fails with:

  Error writing database: open <path>: no such file or directory

This patch fixes the issue and adds a test to ensure we don't have any
regressions on this behaviour.

Thanks to raspbeguy (https://github.com/raspbeguy) for reporting this
issue (on IRC).

cmd/chasquid-util/chasquid-util.go +11 -6
cmd/chasquid-util/test.sh +3 -1

diff --git a/cmd/chasquid-util/chasquid-util.go b/cmd/chasquid-util/chasquid-util.go
index 7333951..3158f8d 100644
--- a/cmd/chasquid-util/chasquid-util.go
+++ b/cmd/chasquid-util/chasquid-util.go
@@ -4,7 +4,9 @@ package main
 
 import (
 	"bytes"
+	"errors"
 	"fmt"
+	"io/fs"
 	"os"
 	"path/filepath"
 	"sort"
@@ -126,19 +128,22 @@ func userDBFromArgs(create bool) (string, string, *userdb.DB) {
 		Fatalf("Domain missing, username should be of the form 'user@domain'")
 	}
 
-	db, err := userdb.Load(userDBForDomain(domain))
-	if err != nil {
-		if create && os.IsNotExist(err) {
+	if create {
+		dbDir := filepath.Dir(userDBForDomain(domain))
+		if _, err := os.Stat(dbDir); errors.Is(err, fs.ErrNotExist) {
 			fmt.Println("Creating database")
-			err = os.MkdirAll(filepath.Dir(userDBForDomain(domain)), 0755)
+			err = os.MkdirAll(dbDir, 0755)
 			if err != nil {
 				Fatalf("Error creating database dir: %v", err)
 			}
-		} else {
-			Fatalf("Error loading database: %v", err)
 		}
 	}
 
+	db, err := userdb.Load(userDBForDomain(domain))
+	if err != nil {
+		Fatalf("Error loading database: %v", err)
+	}
+
 	user, err = normalize.User(user)
 	if err != nil {
 		Fatalf("Error normalizing user: %v", err)
diff --git a/cmd/chasquid-util/test.sh b/cmd/chasquid-util/test.sh
index c40c2ca..8f69587 100755
--- a/cmd/chasquid-util/test.sh
+++ b/cmd/chasquid-util/test.sh
@@ -25,13 +25,15 @@ function check_userdb() {
 
 
 rm -rf .config/
-mkdir -p .config/domains/domain/ .data/domaininfo
+mkdir -p .config/ .data/domaininfo
 echo 'data_dir: ".data"' >> .config/chasquid.conf
 
 if ! r print-config > /dev/null; then
 	fail print-config
 fi
 
+# We intentionally run this when the domain directory doesn't exist, as we
+# want to confirm it creates it.
 if ! r user-add interactive@domain --password=passwd > /dev/null; then
 	fail user-add
 fi