Files
HostKeeper/cmd/hostkeeper/export.go
T
swanadiva 30b57f6084 feat: implement export and import commands
- Add export command with JSON file output and size summary
- Add import command with replace/merge strategies and dry-run preview
- Add integration test for export/import round-trip via storage layer
- Update project state documentation
2026-06-23 13:58:51 +07:00

90 lines
2.0 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/spf13/cobra"
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
)
var (
exportFormat string
exportIncludeKeys bool
)
// exportCmd represents the export command
var exportCmd = &cobra.Command{
Use: "export [filename]",
Short: "Export hosts and credentials to file",
Long: `Export all saved hosts, SSH keys, snippets to a file for backup or transfer.
Examples:
# Export to default file
hostkeeper export my-backup
# Export with .json extension
hostkeeper export my-backup.json`,
Args: cobra.ExactArgs(1),
RunE: runExport,
}
func init() {
exportCmd.Flags().StringVar(&exportFormat, "format", "json", "Export format (json)")
exportCmd.Flags().BoolVar(&exportIncludeKeys, "include-keys", true, "Include SSH keys in export")
rootCmd.AddCommand(exportCmd)
}
func runExport(cmd *cobra.Command, args []string) error {
filename := args[0]
if filepath.Ext(filename) != ".json" {
filename = filename + ".json"
}
cfg := appCfg
if cfg == nil {
var err error
cfg, err = config.New()
if err != nil {
return fmt.Errorf("failed to initialize config: %w", err)
}
}
store, err := storage.NewJSONStorage(cfg.GetDataDir())
if err != nil {
return fmt.Errorf("failed to initialize storage: %w", err)
}
ctx := context.Background()
data, err := store.ExportData(ctx)
if err != nil {
return fmt.Errorf("failed to export data: %w", err)
}
jsonBytes, err := json.MarshalIndent(data, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal export data: %w", err)
}
if err := os.WriteFile(filename, jsonBytes, 0600); err != nil {
return fmt.Errorf("failed to write export file: %w", err)
}
fmt.Printf("Export successful!\n")
fmt.Printf(" File: %s\n", filename)
fmt.Printf(" Hosts: %d\n", len(data.Hosts))
fmt.Printf(" Keys: %d\n", len(data.KeyPairs))
fmt.Printf(" Snippets: %d\n", len(data.Snippets))
fmt.Printf(" Size: %.2f KB\n", float64(len(jsonBytes))/1024)
return nil
}