Add .migrated directory for migrated json files

This commit is contained in:
2025-12-08 18:06:15 +01:00
parent 00cd8c8877
commit d5b68a900f

View File

@@ -13,6 +13,7 @@ import (
// migrateFromJSON migrates instances from JSON files to SQLite database // migrateFromJSON migrates instances from JSON files to SQLite database
// This is a one-time migration that runs on first startup with existing JSON files. // This is a one-time migration that runs on first startup with existing JSON files.
// Migrated files are moved to a .migrated subdirectory to avoid re-importing.
func migrateFromJSON(cfg *config.AppConfig, db database.InstanceStore) error { func migrateFromJSON(cfg *config.AppConfig, db database.InstanceStore) error {
instancesDir := cfg.Instances.InstancesDir instancesDir := cfg.Instances.InstancesDir
if instancesDir == "" { if instancesDir == "" {
@@ -24,16 +25,6 @@ func migrateFromJSON(cfg *config.AppConfig, db database.InstanceStore) error {
return nil // No instances directory, nothing to migrate return nil // No instances directory, nothing to migrate
} }
// Check if database is empty (no instances)
existing, err := db.LoadAll()
if err != nil {
return fmt.Errorf("failed to check existing instances: %w", err)
}
if len(existing) > 0 {
return nil // Database already has instances, skip migration
}
// Find all JSON files // Find all JSON files
files, err := filepath.Glob(filepath.Join(instancesDir, "*.json")) files, err := filepath.Glob(filepath.Join(instancesDir, "*.json"))
if err != nil { if err != nil {
@@ -46,6 +37,12 @@ func migrateFromJSON(cfg *config.AppConfig, db database.InstanceStore) error {
log.Printf("Migrating %d instances from JSON to SQLite...", len(files)) log.Printf("Migrating %d instances from JSON to SQLite...", len(files))
// Create migrated directory
migratedDir := filepath.Join(instancesDir, ".migrated")
if err := os.MkdirAll(migratedDir, 0755); err != nil {
return fmt.Errorf("failed to create migrated directory: %w", err)
}
// Migrate each JSON file // Migrate each JSON file
var migrated int var migrated int
for _, file := range files { for _, file := range files {
@@ -53,6 +50,14 @@ func migrateFromJSON(cfg *config.AppConfig, db database.InstanceStore) error {
log.Printf("Failed to migrate %s: %v", file, err) log.Printf("Failed to migrate %s: %v", file, err)
continue continue
} }
// Move the file to the migrated directory
destPath := filepath.Join(migratedDir, filepath.Base(file))
if err := os.Rename(file, destPath); err != nil {
log.Printf("Warning: Failed to move %s to migrated directory: %v", file, err)
// Don't fail the migration if we can't move the file
}
migrated++ migrated++
} }