|
| 1 | +package commands |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + |
| 7 | + "github.com/malamtime/cli/model" |
| 8 | + "github.com/sirupsen/logrus" |
| 9 | + "github.com/urfave/cli/v2" |
| 10 | + "go.opentelemetry.io/otel/attribute" |
| 11 | + "go.opentelemetry.io/otel/trace" |
| 12 | +) |
| 13 | + |
| 14 | +func pullDotfiles(c *cli.Context) error { |
| 15 | + ctx, span := commandTracer.Start(c.Context, "dotfiles-pull", trace.WithSpanKind(trace.SpanKindClient)) |
| 16 | + defer span.End() |
| 17 | + SetupLogger(os.ExpandEnv("$HOME/" + model.COMMAND_BASE_STORAGE_FOLDER)) |
| 18 | + |
| 19 | + apps := c.StringSlice("apps") |
| 20 | + span.SetAttributes(attribute.StringSlice("apps", apps)) |
| 21 | + |
| 22 | + config, err := configService.ReadConfigFile(ctx) |
| 23 | + if err != nil { |
| 24 | + logrus.Errorln(err) |
| 25 | + return err |
| 26 | + } |
| 27 | + |
| 28 | + if config.Token == "" { |
| 29 | + return fmt.Errorf("no token found, please run 'shelltime auth login' first") |
| 30 | + } |
| 31 | + |
| 32 | + mainEndpoint := model.Endpoint{ |
| 33 | + APIEndpoint: config.APIEndpoint, |
| 34 | + Token: config.Token, |
| 35 | + } |
| 36 | + |
| 37 | + // Prepare filter if apps are specified |
| 38 | + var filter *model.DotfileFilter |
| 39 | + if len(apps) > 0 { |
| 40 | + filter = &model.DotfileFilter{ |
| 41 | + Apps: apps, |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + // Fetch dotfiles from server |
| 46 | + logrus.Infof("Fetching dotfiles from server...") |
| 47 | + resp, err := model.FetchDotfilesFromServer(ctx, mainEndpoint, filter) |
| 48 | + if err != nil { |
| 49 | + logrus.Errorln("Failed to fetch dotfiles from server:", err) |
| 50 | + return err |
| 51 | + } |
| 52 | + |
| 53 | + if resp == nil || len(resp.Data.FetchUser.Dotfiles.Apps) == 0 { |
| 54 | + logrus.Infoln("No dotfiles found on server") |
| 55 | + fmt.Println("\n📭 No dotfiles found on server") |
| 56 | + return nil |
| 57 | + } |
| 58 | + |
| 59 | + // Initialize all available app handlers |
| 60 | + allApps := map[string]model.DotfileApp{ |
| 61 | + "nvim": model.NewNvimApp(), |
| 62 | + "fish": model.NewFishApp(), |
| 63 | + "git": model.NewGitApp(), |
| 64 | + "zsh": model.NewZshApp(), |
| 65 | + "bash": model.NewBashApp(), |
| 66 | + "ghostty": model.NewGhosttyApp(), |
| 67 | + } |
| 68 | + |
| 69 | + // Process fetched dotfiles |
| 70 | + totalProcessed := 0 |
| 71 | + totalSkipped := 0 |
| 72 | + totalFailed := 0 |
| 73 | + |
| 74 | + for _, appData := range resp.Data.FetchUser.Dotfiles.Apps { |
| 75 | + app, exists := allApps[appData.App] |
| 76 | + if !exists { |
| 77 | + logrus.Warnf("Unknown app type: %s", appData.App) |
| 78 | + continue |
| 79 | + } |
| 80 | + |
| 81 | + logrus.Infof("Processing %s dotfiles...", appData.App) |
| 82 | + |
| 83 | + // Collect files to process for this app |
| 84 | + filesToProcess := make(map[string]string) |
| 85 | + var pathsToBackup []string |
| 86 | + |
| 87 | + for _, file := range appData.Files { |
| 88 | + if len(file.Records) == 0 { |
| 89 | + logrus.Debugf("No records found for %s", file.Path) |
| 90 | + continue |
| 91 | + } |
| 92 | + |
| 93 | + // Get the best record: prioritize records without host, fallback to latest |
| 94 | + var selectedRecord *model.DotfileRecord |
| 95 | + var latestRecord *model.DotfileRecord |
| 96 | + |
| 97 | + for i := range file.Records { |
| 98 | + record := &file.Records[i] |
| 99 | + |
| 100 | + // Track the latest record overall |
| 101 | + if latestRecord == nil || record.UpdatedAt.After(latestRecord.UpdatedAt) { |
| 102 | + latestRecord = record |
| 103 | + } |
| 104 | + |
| 105 | + // If we find a record without a host (general config), use it |
| 106 | + if record.Host.ID == 0 || record.Host.Hostname == "" { |
| 107 | + if selectedRecord == nil || record.UpdatedAt.After(selectedRecord.UpdatedAt) { |
| 108 | + selectedRecord = record |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + // If no host-less record found, use the latest record |
| 114 | + if selectedRecord == nil { |
| 115 | + selectedRecord = latestRecord |
| 116 | + } |
| 117 | + |
| 118 | + if selectedRecord == nil { |
| 119 | + continue |
| 120 | + } |
| 121 | + |
| 122 | + // Adjust path for current user |
| 123 | + adjustedPath := AdjustPathForCurrentUser(file.Path) |
| 124 | + filesToProcess[adjustedPath] = selectedRecord.Content |
| 125 | + pathsToBackup = append(pathsToBackup, adjustedPath) |
| 126 | + } |
| 127 | + |
| 128 | + if len(filesToProcess) == 0 { |
| 129 | + continue |
| 130 | + } |
| 131 | + |
| 132 | + // Check which files are different |
| 133 | + equalityMap, err := app.IsEqual(ctx, filesToProcess) |
| 134 | + if err != nil { |
| 135 | + logrus.Warnf("Failed to check file equality for %s: %v", appData.App, err) |
| 136 | + } |
| 137 | + |
| 138 | + // Filter out files that are already equal |
| 139 | + filesToUpdate := make(map[string]string) |
| 140 | + var pathsToActuallyBackup []string |
| 141 | + |
| 142 | + for path, content := range filesToProcess { |
| 143 | + if isEqual, exists := equalityMap[path]; exists && isEqual { |
| 144 | + logrus.Debugf("Skipping %s - content is identical", path) |
| 145 | + totalSkipped++ |
| 146 | + } else { |
| 147 | + filesToUpdate[path] = content |
| 148 | + pathsToActuallyBackup = append(pathsToActuallyBackup, path) |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + if len(filesToUpdate) == 0 { |
| 153 | + logrus.Infof("All %s files are up to date", appData.App) |
| 154 | + continue |
| 155 | + } |
| 156 | + |
| 157 | + // Backup files that will be modified |
| 158 | + if err := app.Backup(ctx, pathsToActuallyBackup); err != nil { |
| 159 | + logrus.Warnf("Failed to backup files for %s: %v", appData.App, err) |
| 160 | + } |
| 161 | + |
| 162 | + // Save the updated files |
| 163 | + if err := app.Save(ctx, filesToUpdate); err != nil { |
| 164 | + logrus.Errorf("Failed to save files for %s: %v", appData.App, err) |
| 165 | + totalFailed += len(filesToUpdate) |
| 166 | + } else { |
| 167 | + totalProcessed += len(filesToUpdate) |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + if totalProcessed == 0 && totalFailed == 0 && totalSkipped == 0 { |
| 172 | + logrus.Infoln("No dotfiles found to process") |
| 173 | + fmt.Println("\n📭 No dotfiles to process") |
| 174 | + } else if totalProcessed == 0 && totalFailed == 0 { |
| 175 | + logrus.Infof("All dotfiles are up to date - Skipped: %d", totalSkipped) |
| 176 | + fmt.Println("\n✅ All dotfiles are up to date") |
| 177 | + fmt.Printf("🔄 Skipped: %d files (already identical)\n", totalSkipped) |
| 178 | + } else { |
| 179 | + logrus.Infof("Pull complete - Processed: %d, Skipped: %d, Failed: %d", totalProcessed, totalSkipped, totalFailed) |
| 180 | + fmt.Printf("\n✅ Pull complete\n") |
| 181 | + fmt.Printf("📥 Updated: %d files\n", totalProcessed) |
| 182 | + if totalSkipped > 0 { |
| 183 | + fmt.Printf("🔄 Skipped: %d files (already identical)\n", totalSkipped) |
| 184 | + } |
| 185 | + if totalFailed > 0 { |
| 186 | + fmt.Printf("⚠️ Failed: %d files\n", totalFailed) |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + return nil |
| 191 | +} |
0 commit comments