Change counter store to xdg data dir

This commit is contained in:
2025-07-21 10:28:39 +03:00
parent 6d9e14c262
commit 87188deda5
3 changed files with 27 additions and 10 deletions

18
main.go
View File

@@ -12,6 +12,7 @@ import (
"syscall"
"time"
"github.com/adrg/xdg"
"github.com/fsnotify/fsnotify"
)
@@ -22,6 +23,11 @@ func main() {
destDir := "/home/av/temp/dest"
os.MkdirAll(destDir, 0755)
counterFile, err := xdg.DataFile("filemover/counter")
if err != nil {
log.Fatalf("Application data dir not accessible, %v", err)
}
// Контекст для graceful shutdown
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -36,20 +42,20 @@ func main() {
// Запуск единственного обработчика
go func() {
defer wg.Done()
counter := loadCounter(destDir)
counter := loadCounter(counterFile)
for {
select {
case file, ok := <-tasks:
if !ok {
// Канал закрыт, завершаем работу
saveCounter(destDir, counter)
saveCounter(counterFile, counter)
log.Println("Worker stopped")
return
}
processFile(file, destDir, &counter)
case <-ctx.Done():
// Получен сигнал завершения
saveCounter(destDir, counter)
saveCounter(counterFile, counter)
log.Println("Worker stopped by context")
return
}
@@ -145,8 +151,7 @@ func processFile(filePath, destDir string, counter *int) {
log.Printf("Moved: %s -> %s", filePath, destPath)
}
func loadCounter(dir string) int {
counterPath := filepath.Join(dir, "counter.txt")
func loadCounter(counterPath string) int {
data, err := os.ReadFile(counterPath)
if err != nil {
if !os.IsNotExist(err) {
@@ -162,8 +167,7 @@ func loadCounter(dir string) int {
return count
}
func saveCounter(dir string, count int) {
counterPath := filepath.Join(dir, "counter.txt")
func saveCounter(counterPath string, count int) {
if err := os.WriteFile(counterPath, []byte(strconv.Itoa(count)), 0644); err != nil {
log.Printf("Failed to save counter: %v", err)
}