style: Apply code formatting with go fmt

- Run 'make format' to ensure all Go code follows standard formatting
- Maintains consistent code style across the entire codebase
- No functional changes, only whitespace and formatting improvements
This commit is contained in:
Ole-Morten Duesund 2025-09-01 10:05:29 +02:00
commit 2bffa2c418
19 changed files with 543 additions and 527 deletions

View file

@ -19,28 +19,28 @@ import (
// Shared configuration structures (should match main skyview)
type Config struct {
Server ServerConfig `json:"server"`
Sources []SourceConfig `json:"sources"`
Settings Settings `json:"settings"`
Database *database.Config `json:"database,omitempty"`
Callsign *CallsignConfig `json:"callsign,omitempty"`
Origin OriginConfig `json:"origin"`
Server ServerConfig `json:"server"`
Sources []SourceConfig `json:"sources"`
Settings Settings `json:"settings"`
Database *database.Config `json:"database,omitempty"`
Callsign *CallsignConfig `json:"callsign,omitempty"`
Origin OriginConfig `json:"origin"`
}
type CallsignConfig struct {
Enabled bool `json:"enabled"`
CacheHours int `json:"cache_hours"`
PrivacyMode bool `json:"privacy_mode"`
Sources map[string]CallsignSourceConfig `json:"sources"`
ExternalAPIs map[string]ExternalAPIConfig `json:"external_apis,omitempty"`
Enabled bool `json:"enabled"`
CacheHours int `json:"cache_hours"`
PrivacyMode bool `json:"privacy_mode"`
Sources map[string]CallsignSourceConfig `json:"sources"`
ExternalAPIs map[string]ExternalAPIConfig `json:"external_apis,omitempty"`
}
type CallsignSourceConfig struct {
Enabled bool `json:"enabled"`
Priority int `json:"priority"`
License string `json:"license"`
RequiresConsent bool `json:"requires_consent,omitempty"`
UserAcceptsTerms bool `json:"user_accepts_terms,omitempty"`
Enabled bool `json:"enabled"`
Priority int `json:"priority"`
License string `json:"license"`
RequiresConsent bool `json:"requires_consent,omitempty"`
UserAcceptsTerms bool `json:"user_accepts_terms,omitempty"`
}
type ExternalAPIConfig struct {
@ -51,14 +51,14 @@ type ExternalAPIConfig struct {
}
type OriginConfig struct {
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
Name string `json:"name,omitempty"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
Name string `json:"name,omitempty"`
}
type ServerConfig struct {
Host string `json:"host"`
Port int `json:"port"`
Host string `json:"host"`
Port int `json:"port"`
}
type SourceConfig struct {
@ -152,7 +152,7 @@ OPTIONS:
if err != nil {
log.Fatalf("Configuration loading failed: %v", err)
}
// Initialize database connection using shared config
db, err := initDatabaseFromConfig(config, *dbPath)
if err != nil {
@ -215,7 +215,7 @@ func initDatabase(dbPath string) (*database.Database, error) {
// cmdInit initializes an empty database
func cmdInit(db *database.Database, force bool) error {
dbPath := db.GetConfig().Path
// Check if database already exists and has data
if !force {
if stats, err := db.GetHistoryManager().GetStatistics(); err == nil {
@ -271,19 +271,19 @@ func cmdList(db *database.Database) error {
func cmdStatus(db *database.Database) error {
fmt.Println("SkyView Database Status")
fmt.Println("======================")
dbPath := db.GetConfig().Path
fmt.Printf("Database: %s\n", dbPath)
// Check if file exists and get size
if stat, err := os.Stat(dbPath); err == nil {
fmt.Printf("Size: %.2f MB\n", float64(stat.Size())/(1024*1024))
fmt.Printf("Modified: %s\n", stat.ModTime().Format(time.RFC3339))
// Add database optimization stats
optimizer := database.NewOptimizationManager(db, db.GetConfig())
if stats, err := optimizer.GetOptimizationStats(); err == nil {
fmt.Printf("Efficiency: %.1f%% (%d used pages, %d free pages)\n",
fmt.Printf("Efficiency: %.1f%% (%d used pages, %d free pages)\n",
stats.Efficiency, stats.UsedPages, stats.FreePages)
if stats.AutoVacuumEnabled {
fmt.Printf("Auto-VACUUM: Enabled\n")
@ -320,7 +320,7 @@ func cmdStatus(db *database.Database) error {
var airportCount, airlineCount int
db.GetConnection().QueryRow(`SELECT COUNT(*) FROM airports`).Scan(&airportCount)
db.GetConnection().QueryRow(`SELECT COUNT(*) FROM airlines`).Scan(&airlineCount)
// Get data source update information
var lastUpdate time.Time
var updateCount int
@ -329,7 +329,7 @@ func cmdStatus(db *database.Database) error {
FROM data_sources
WHERE imported_at IS NOT NULL
`).Scan(&updateCount, &lastUpdate)
fmt.Printf("📊 Database Statistics:\n")
fmt.Printf(" Reference Data:\n")
if airportCount > 0 {
@ -344,7 +344,7 @@ func cmdStatus(db *database.Database) error {
fmt.Printf(" • Last Updated: %s\n", lastUpdate.Format("2006-01-02 15:04:05"))
}
}
fmt.Printf(" Flight History:\n")
if totalRecords, ok := stats["total_records"].(int); ok {
fmt.Printf(" • Aircraft Records: %d\n", totalRecords)
@ -361,13 +361,13 @@ func cmdStatus(db *database.Database) error {
if hasOldest && hasNewest && oldestRecord != nil && newestRecord != nil {
if oldest, ok := oldestRecord.(time.Time); ok {
if newest, ok := newestRecord.(time.Time); ok {
fmt.Printf(" • Flight Data Range: %s to %s\n",
fmt.Printf(" • Flight Data Range: %s to %s\n",
oldest.Format("2006-01-02"),
newest.Format("2006-01-02"))
}
}
}
// Show airport data sample if available
if airportCount > 0 {
var sampleAirports []string
@ -398,7 +398,7 @@ func cmdStatus(db *database.Database) error {
// cmdUpdate updates data from specified sources (or safe sources by default)
func cmdUpdate(db *database.Database, sources []string, force bool) error {
availableSources := database.GetAvailableDataSources()
// If no sources specified, use safe (non-consent-required) sources
if len(sources) == 0 {
log.Println("Updating from safe data sources...")
@ -407,7 +407,7 @@ func cmdUpdate(db *database.Database, sources []string, force bool) error {
sources = append(sources, strings.ToLower(strings.ReplaceAll(source.Name, " ", "")))
}
}
if len(sources) == 0 {
log.Println("No safe data sources available for automatic update")
return nil
@ -416,7 +416,7 @@ func cmdUpdate(db *database.Database, sources []string, force bool) error {
}
loader := database.NewDataLoader(db.GetConnection())
for _, sourceName := range sources {
// Find matching source
var matchedSource *database.DataSource
@ -426,13 +426,13 @@ func cmdUpdate(db *database.Database, sources []string, force bool) error {
break
}
}
if matchedSource == nil {
log.Printf("⚠️ Unknown source: %s", sourceName)
continue
}
// Check for consent requirement
// Check for consent requirement
if matchedSource.RequiresConsent && !force {
log.Printf("Skipping %s: requires license acceptance (%s)", matchedSource.Name, matchedSource.License)
log.Printf("Use --force to accept license terms, or 'skyview-data import %s' for interactive acceptance", sourceName)
@ -446,7 +446,7 @@ func cmdUpdate(db *database.Database, sources []string, force bool) error {
}
log.Printf("Loading %s...", matchedSource.Name)
result, err := loader.LoadDataSource(*matchedSource)
if err != nil {
log.Printf("Failed to load %s: %v", matchedSource.Name, err)
@ -454,11 +454,13 @@ func cmdUpdate(db *database.Database, sources []string, force bool) error {
}
log.Printf("Loaded %s: %d records in %v", matchedSource.Name, result.RecordsNew, result.Duration)
if len(result.Errors) > 0 {
log.Printf(" %d errors occurred during import (first few):", len(result.Errors))
for i, errMsg := range result.Errors {
if i >= 3 { break }
if i >= 3 {
break
}
log.Printf(" %s", errMsg)
}
}
@ -471,7 +473,7 @@ func cmdUpdate(db *database.Database, sources []string, force bool) error {
// cmdImport imports data from a specific source with interactive license acceptance
func cmdImport(db *database.Database, sourceName string, force bool) error {
availableSources := database.GetAvailableDataSources()
var matchedSource *database.DataSource
for _, available := range availableSources {
if strings.EqualFold(strings.ReplaceAll(available.Name, " ", ""), sourceName) {
@ -479,7 +481,7 @@ func cmdImport(db *database.Database, sourceName string, force bool) error {
break
}
}
if matchedSource == nil {
return fmt.Errorf("unknown data source: %s", sourceName)
}
@ -491,17 +493,17 @@ func cmdImport(db *database.Database, sourceName string, force bool) error {
fmt.Printf(" URL: %s\n", matchedSource.URL)
fmt.Println()
fmt.Printf("By importing this data, you agree to comply with the %s license terms.\n", matchedSource.License)
if !askForConfirmation("Do you accept the license terms?") {
fmt.Println("Import cancelled.")
return nil
}
matchedSource.UserAcceptedLicense = true
}
fmt.Printf("📥 Importing %s...\n", matchedSource.Name)
loader := database.NewDataLoader(db.GetConnection())
result, err := loader.LoadDataSource(*matchedSource)
if err != nil {
@ -550,10 +552,10 @@ func cmdReset(db *database.Database, force bool) error {
// askForConfirmation asks the user for yes/no confirmation
func askForConfirmation(question string) bool {
fmt.Printf("%s (y/N): ", question)
var response string
fmt.Scanln(&response)
response = strings.ToLower(strings.TrimSpace(response))
return response == "y" || response == "yes"
}
@ -564,30 +566,30 @@ func loadConfig(configPath string) (*Config, error) {
if err != nil {
return nil, fmt.Errorf("failed to read config file %s: %w", configPath, err)
}
var config Config
if err := json.Unmarshal(data, &config); err != nil {
return nil, fmt.Errorf("failed to parse config file %s: %w", configPath, err)
}
return &config, nil
}
// initDatabaseFromConfig initializes database using shared configuration
func initDatabaseFromConfig(config *Config, dbPathOverride string) (*database.Database, error) {
var dbConfig *database.Config
if config.Database != nil {
dbConfig = config.Database
} else {
dbConfig = database.DefaultConfig()
}
// Allow command-line override of database path
if dbPathOverride != "" {
dbConfig.Path = dbPathOverride
}
// Resolve database path if empty
if dbConfig.Path == "" {
resolvedPath, err := database.ResolveDatabasePath(dbConfig.Path)
@ -596,18 +598,18 @@ func initDatabaseFromConfig(config *Config, dbPathOverride string) (*database.Da
}
dbConfig.Path = resolvedPath
}
// Create and initialize database
db, err := database.NewDatabase(dbConfig)
if err != nil {
return nil, fmt.Errorf("failed to create database: %w", err)
}
if err := db.Initialize(); err != nil {
db.Close()
return nil, fmt.Errorf("failed to initialize database: %w", err)
}
return db, nil
}
@ -615,23 +617,23 @@ func initDatabaseFromConfig(config *Config, dbPathOverride string) (*database.Da
func cmdOptimize(db *database.Database, force bool) error {
fmt.Println("Database Storage Optimization")
fmt.Println("============================")
// We need to get the database path from the config
// For now, let's create a simple optimization manager
config := &database.Config{
Path: "./dev-skyview.db", // Default path - this should be configurable
}
// Create optimization manager
optimizer := database.NewOptimizationManager(db, config)
// Get current stats
fmt.Println("📊 Current Database Statistics:")
stats, err := optimizer.GetOptimizationStats()
if err != nil {
return fmt.Errorf("failed to get database stats: %w", err)
}
fmt.Printf(" • Size: %.1f MB\n", float64(stats.DatabaseSize)/(1024*1024))
fmt.Printf(" • Page Size: %d bytes\n", stats.PageSize)
fmt.Printf(" • Total Pages: %d\n", stats.PageCount)
@ -639,48 +641,47 @@ func cmdOptimize(db *database.Database, force bool) error {
fmt.Printf(" • Free Pages: %d\n", stats.FreePages)
fmt.Printf(" • Efficiency: %.1f%%\n", stats.Efficiency)
fmt.Printf(" • Auto VACUUM: %v\n", stats.AutoVacuumEnabled)
// Check if optimization is needed
needsOptimization := stats.FreePages > 0 || stats.Efficiency < 95.0
if !needsOptimization && !force {
fmt.Println("✅ Database is already well optimized!")
fmt.Println(" Use --force to run optimization anyway")
return nil
}
// Perform optimizations
if force && !needsOptimization {
fmt.Println("\n🔧 Force optimization requested:")
} else {
fmt.Println("\n🔧 Applying Optimizations:")
}
if err := optimizer.VacuumDatabase(); err != nil {
return fmt.Errorf("VACUUM failed: %w", err)
}
if err := optimizer.OptimizeDatabase(); err != nil {
return fmt.Errorf("optimization failed: %w", err)
}
// Show final stats
fmt.Println("\n📈 Final Statistics:")
finalStats, err := optimizer.GetOptimizationStats()
if err != nil {
return fmt.Errorf("failed to get final stats: %w", err)
}
fmt.Printf(" • Size: %.1f MB\n", float64(finalStats.DatabaseSize)/(1024*1024))
fmt.Printf(" • Efficiency: %.1f%%\n", finalStats.Efficiency)
fmt.Printf(" • Free Pages: %d\n", finalStats.FreePages)
if stats.DatabaseSize > finalStats.DatabaseSize {
saved := stats.DatabaseSize - finalStats.DatabaseSize
fmt.Printf(" • Space Saved: %.1f MB\n", float64(saved)/(1024*1024))
}
fmt.Println("\n✅ Database optimization completed!")
return nil
}