Implement watching crontab file

This commit is contained in:
2025-06-27 18:05:22 +02:00
parent fbbee71052
commit 83820f05e9
3 changed files with 68 additions and 4 deletions

View File

@@ -2,4 +2,9 @@ module crontabd
go 1.23.6
require git.site.quack-lab.dev/dave/cylogger v1.2.3
require (
git.site.quack-lab.dev/dave/cylogger v1.2.3
github.com/fsnotify/fsnotify v1.9.0
)
require golang.org/x/sys v0.13.0 // indirect

View File

@@ -1,2 +1,6 @@
git.site.quack-lab.dev/dave/cylogger v1.2.3 h1:g6fwgrd3HvGsxljvKbjcFaMynTO2AZFWjC2ZvCi1raQ=
git.site.quack-lab.dev/dave/cylogger v1.2.3/go.mod h1:sf16Zs5ZRncn0ySgwxRJShkge1M10CM2RAUkKn8Bel8=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=

View File

@@ -2,9 +2,12 @@ package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"github.com/fsnotify/fsnotify"
logger "git.site.quack-lab.dev/dave/cylogger"
)
@@ -14,13 +17,65 @@ func main() {
flag.Parse()
logger.InitFlag()
homeDir, err := os.UserHomeDir()
var err error
crontabFile, err = resolveCrontabPath()
if err != nil {
logger.Error("Failed to get user home directory: %v", err)
logger.Error("Failed to resolve crontab file path: %v", err)
return
}
err = ensureExists(crontabFile)
if err != nil {
logger.Error("Failed to ensure crontab file exists: %v", err)
return
}
logger.Info("Crontab file resolved as: %s", crontabFile)
watcher, err := fsnotify.NewWatcher()
if err != nil {
logger.Error("Failed to create watcher: %v", err)
return
}
err = watcher.Add(crontabFile)
if err != nil {
logger.Error("Failed to add crontab file to watcher: %v", err)
return
}
logger.Info("Watching crontab file: %s", crontabFile)
}
func resolveCrontabPath() (string, error) {
// Resolve crontab file location
homeDir, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("failed to get user home directory: %v", err)
}
userName := os.Getenv("USERNAME")
crontabFile = filepath.Join(homeDir, "crontab", userName+".cron")
logger.Info("Crontab file: %s", crontabFile)
crontabFile, err = filepath.Abs(crontabFile)
if err != nil {
return "", fmt.Errorf("failed to get absolute path: %v", err)
}
crontabFile = filepath.Clean(crontabFile)
return crontabFile, nil
}
func ensureExists(path string) error {
// Make sure it exists
err := os.MkdirAll(filepath.Dir(path), 0755)
if err != nil {
return fmt.Errorf("failed to create directory: %v", err)
}
file, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
os.WriteFile(path, []byte(""), 0644)
} else {
return fmt.Errorf("failed to open crontab file: %v", err)
}
}
defer file.Close()
return nil
}