Files
LazyPM/internal/service/app.go
2026-02-28 16:39:50 +01:00

88 lines
1.8 KiB
Go

package service
import (
"context"
"fmt"
"log/slog"
"os"
"time"
"github.com/LazyBachelor/LazyPM/internal/models"
"github.com/LazyBachelor/LazyPM/internal/storage"
"github.com/charmbracelet/huh"
"github.com/steveyegge/beads"
)
type App = models.App
type Config = models.Config
func NewApp(ctx context.Context, config Config) (*App, func(), error) {
var cleanupFuncs []func()
if !config.AutoInit {
if !initialized(config.BeadsDBPath) {
fmt.Println("PM is not initialized")
os.Exit(0)
}
}
store, err := beads.NewSQLiteStorage(ctx, config.BeadsDBPath)
if err != nil {
return nil, nil, err
}
cleanupFuncs = append(cleanupFuncs, func() { store.Close() })
beadsSvc, err := storage.NewBeadsIssueStorage(ctx, store, config.IssuePrefix)
if err != nil {
return nil, nil, err
}
cleanupFuncs = append(cleanupFuncs, func() { beadsSvc.Close() })
statStore := storage.NewJsonStorage(config.StatisticsStoragePath, &models.Statistics{
ID: 0,
StartTime: time.Now(),
})
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
statSvc, err := NewStatisticsService(statStore)
if err != nil {
return nil, nil, err
}
return &App{
Issues: beadsSvc,
Stats: statSvc,
Config: config,
Logger: logger,
}, func() { runCleanup(cleanupFuncs) }, nil
}
func runCleanup(funcs []func()) {
for _, fn := range funcs {
fn()
}
}
func initialized(beadsPath string) bool {
_, err := os.Stat(beadsPath)
if os.IsNotExist(err) {
var initialize bool
huh.NewForm(
huh.NewGroup(
huh.NewConfirm().Title("PM is not initialized in this directory!").
Description("Do you want to initialize it here?").
Value(&initialize),
),
).WithTheme(huh.ThemeBase16()).WithAccessible(true).Run()
if !initialize {
return false
}
}
return true
}