From 6b98c27419220d3f576a32fabdc701308f7f4137 Mon Sep 17 00:00:00 2001 From: thelovekesh Date: Sun, 24 May 2026 02:34:52 +0530 Subject: [PATCH] Remove svn migration cmd --- cmd/svn-download/svn-download.go | 935 ----------------------- cmd/svn-migrate/svn-migrate.go | 1211 ------------------------------ 2 files changed, 2146 deletions(-) delete mode 100644 cmd/svn-download/svn-download.go delete mode 100644 cmd/svn-migrate/svn-migrate.go diff --git a/cmd/svn-download/svn-download.go b/cmd/svn-download/svn-download.go deleted file mode 100644 index c58f4cd3..00000000 --- a/cmd/svn-download/svn-download.go +++ /dev/null @@ -1,935 +0,0 @@ -package main - -import ( - "bufio" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "os" - "os/exec" - "os/signal" - "path/filepath" - "regexp" - "strings" - "sync" - "syscall" - "time" - - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "github.com/spf13/cobra" -) - -const ( - defaultDownloaderWorkers = 5 - downloaderRequestTimeout = 30 * time.Second - defaultDownloaderManifestFile = "svn-download-manifest.json" - globalLogFileName = "svn-download-activity.log" -) - -var ( - nameReg = regexp.MustCompile(`^[\w-]{3,164}$`) - downloaderHttpClient = &http.Client{Timeout: downloaderRequestTimeout} - log = logrus.New() -) - -type DownloaderConfig struct { - PackageType string - OutputDir string - NumWorkers int - ManifestPath string - SvnRepoURL string - Limit int - Verbose bool - LogPath string -} - -type APIResponse struct { - Version string `json:"version"` -} - -type PackageDownloadState struct { - Status string `json:"status"` - LatestVersion string `json:"latest_version,omitempty"` - SVNCheckedOutAt time.Time `json:"svn_checked_out_at,omitempty"` - LocalPath string `json:"local_path,omitempty"` - Error string `json:"error,omitempty"` - Retryable bool `json:"retryable,omitempty"` - Retries int `json:"retries,omitempty"` - LastExitCode int `json:"last_exit_code,omitempty"` -} - -type DownloaderManifest struct { - LastUpdated time.Time `json:"last_updated"` - RepoType string `json:"repo_type"` - SvnBaseURL string `json:"svn_base_url"` - LastAPIVersionsSync time.Time `json:"last_api_versions_sync,omitempty"` - Packages map[string]*PackageDownloadState `json:"packages"` - manifestPath string - mu sync.Mutex -} - -// FileHook enables dual logging: structured JSON to file, readable text to stdout -type FileHook struct { - file *os.File - formatter logrus.Formatter - levels []logrus.Level -} - -func NewFileHook(filePath string, formatter logrus.Formatter, levels []logrus.Level) (*FileHook, error) { - logDir := filepath.Dir(filePath) - if err := os.MkdirAll(logDir, 0755); err != nil { - return nil, errors.Wrapf(err, "failed to create log directory: %s", logDir) - } - - file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) - if err != nil { - return nil, errors.Wrapf(err, "failed to open log file: %s", filePath) - } - - return &FileHook{file: file, formatter: formatter, levels: levels}, nil -} - -func (hook *FileHook) Fire(entry *logrus.Entry) error { - lineBytes, err := hook.formatter.Format(entry) - if err != nil { - return err - } - _, err = hook.file.Write(lineBytes) - return err -} - -func (hook *FileHook) Levels() []logrus.Level { - if len(hook.levels) == 0 { - return logrus.AllLevels - } - return hook.levels -} - -func setupLogger(logLevel logrus.Level, jsonLogFilePath string, verbose bool) error { - log.SetOutput(os.Stdout) - log.SetLevel(logLevel) - - if verbose { - log.SetFormatter(&logrus.TextFormatter{ - FullTimestamp: true, - TimestampFormat: "2006-01-02 15:04:05.000", - ForceColors: true, - }) - } else { - log.SetFormatter(&logrus.TextFormatter{ - TimestampFormat: "15:04:05", - ForceColors: true, - }) - } - - if jsonLogFilePath != "" { - fileHook, err := NewFileHook(jsonLogFilePath, &logrus.JSONFormatter{ - TimestampFormat: time.RFC3339Nano, - }, logrus.AllLevels) - - if err != nil { - log.WithError(err).Errorf("āŒ failed to initialize file logging: %s", jsonLogFilePath) - } else { - log.AddHook(fileHook) - log.Infof("šŸ“ logging: text to stdout, json to %s", jsonLogFilePath) - } - } else { - log.Info("šŸ“ logging: text to stdout only") - } - - return nil -} - -func loadDownloaderManifest(path string) (*DownloaderManifest, error) { - data, err := os.ReadFile(path) - if err != nil { - if os.IsNotExist(err) { - log.Infof("šŸ“„ downloader manifest %s not found, creating new one", path) - return &DownloaderManifest{ - Packages: make(map[string]*PackageDownloadState), - manifestPath: path, - }, nil - } - return nil, errors.Wrapf(err, "failed to read downloader manifest %s", path) - } - - var manifest DownloaderManifest - if err := json.Unmarshal(data, &manifest); err != nil { - return nil, errors.Wrapf(err, "failed to unmarshal downloader manifest %s", path) - } - - if manifest.Packages == nil { - manifest.Packages = make(map[string]*PackageDownloadState) - } - manifest.manifestPath = path - log.Infof("āœ… loaded downloader manifest from %s", path) - return &manifest, nil -} - -func (m *DownloaderManifest) Save() error { - m.mu.Lock() - defer m.mu.Unlock() - - m.LastUpdated = time.Now() - data, err := json.MarshalIndent(m, "", " ") - if err != nil { - return errors.Wrap(err, "failed to marshal downloader manifest") - } - - if err := os.MkdirAll(filepath.Dir(m.manifestPath), 0755); err != nil { - return errors.Wrapf(err, "failed to create directory for manifest %s", m.manifestPath) - } - - return os.WriteFile(m.manifestPath, data, 0644) -} - -func (m *DownloaderManifest) GetPackageState(slug string) (*PackageDownloadState, bool) { - m.mu.Lock() - defer m.mu.Unlock() - - state, exists := m.Packages[slug] - if exists { - sCopy := *state - return &sCopy, true - } - return nil, false -} - -func (m *DownloaderManifest) UpdatePackageState(slug string, state *PackageDownloadState) { - m.mu.Lock() - defer m.mu.Unlock() - m.Packages[slug] = state -} - -func checkSVNInstalled() error { - _, err := exec.LookPath("svn") - if err != nil { - return errors.New("svn command-line tool is not installed or not in PATH") - } - return nil -} - -func listSVNPackages(ctx context.Context, svnRepoURL string, limit int) ([]string, error) { - l := log.WithFields(logrus.Fields{ - "svn_repo_url": svnRepoURL, - "action": "list_packages", - }) - - l.Info("šŸ“‹ listing packages from svn repository...") - - cmd := exec.CommandContext(ctx, "svn", "list", svnRepoURL) - stdout, err := cmd.StdoutPipe() - if err != nil { - return nil, errors.Wrap(err, "failed to get stdout pipe for svn list") - } - - stderr, err := cmd.StderrPipe() - if err != nil { - return nil, errors.Wrap(err, "failed to get stderr pipe for svn list") - } - - if err := cmd.Start(); err != nil { - return nil, errors.Wrap(err, "failed to start svn list command") - } - - var packageNames []string - scanner := bufio.NewScanner(stdout) - count := 0 - limitReached := false - - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) - if line != "" { - name := strings.TrimRight(line, "/") - if name != "" { - packageNames = append(packageNames, name) - count++ - if limit > 0 && count >= limit { - l.Infof("šŸ“Š reached limit of %d packages from svn list", limit) - limitReached = true - break - } - } - } - } - - // If we reached the limit, kill the command to prevent hanging - if limitReached { - l.Debug("terminating svn command after reaching limit") - if err := cmd.Process.Kill(); err != nil { - l.WithError(err).Debug("failed to kill svn process, will wait normally") - } - - // Drain remaining output to prevent blocking - go func() { - _, _ = io.Copy(io.Discard, stdout) - }() - go func() { - _, _ = io.Copy(io.Discard, stderr) - }() - } - - var svnErrOutput strings.Builder - if !limitReached { - if _, err := io.Copy(&svnErrOutput, stderr); err != nil { - l.WithError(err).Warn("could not read from svn list stderr pipe") - } - } - - if err := cmd.Wait(); err != nil { - // If we killed the process due to limit, don't treat it as an error - if limitReached { - l.Debug("svn command terminated after reaching limit (expected)") - } else { - l.Errorf("āŒ svn list command failed. stderr: %s", svnErrOutput.String()) - return nil, errors.Wrapf(err, "svn list command failed for %s. stderr: %s", svnRepoURL, svnErrOutput.String()) - } - } - - if err := scanner.Err(); err != nil { - return nil, errors.Wrap(err, "error reading svn list output") - } - - l.Infof("āœ… found %d package names from svn", len(packageNames)) - return packageNames, nil -} - -func fetchLatestVersion(ctx context.Context, packageName, packageType string) (version string, statusCode int, err error) { - l := log.WithFields(logrus.Fields{ - "package": packageName, - "action": "api_lookup", - }) - - var apiURL string - if packageType == "theme" { - apiURL = fmt.Sprintf("https://api.wordpress.org/themes/info/1.2/?action=theme_information&slug=%s", packageName) - } else { - apiURL = fmt.Sprintf("https://api.wordpress.org/plugins/info/1.2/?action=plugin_information&slug=%s", packageName) - } - - l.Debugf("fetching from: %s", apiURL) - - req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil) - if err != nil { - return "", 0, errors.Wrap(err, "failed to create api request") - } - - resp, err := downloaderHttpClient.Do(req) - if err != nil { - return "", 0, errors.Wrap(err, "api request failed") - } - defer resp.Body.Close() - - bodyBytes, readErr := io.ReadAll(resp.Body) - if readErr != nil { - l.WithError(readErr).Warn("could not read api response body") - } - - if resp.StatusCode != http.StatusOK { - return "", resp.StatusCode, fmt.Errorf("api returned status %d. body: %s", resp.StatusCode, string(bodyBytes)) - } - - var apiResp APIResponse - if err := json.Unmarshal(bodyBytes, &apiResp); err != nil { - return "", resp.StatusCode, errors.Wrapf(err, "failed to decode api response. body: %s", string(bodyBytes)) - } - - if apiResp.Version == "" { - return "", resp.StatusCode, fmt.Errorf("api response has no version. body: %s", string(bodyBytes)) - } - - l.Debugf("āœ… fetched version: %s", apiResp.Version) - return apiResp.Version, resp.StatusCode, nil -} - -func min(a, b int) int { - if a < b { - return a - } - return b -} - -// isRetryableExitCode determines if an SVN exit code indicates a retryable error -func isRetryableExitCode(exitCode int) bool { - switch exitCode { - case 0: - return false // Success, no retry needed - case 1: - return true // General error, could be temporary - case 2: - return false // System error, usually not retryable - case 3: - return false // Authentication error, not retryable without config change - case 4: - return false // Authorization error, not retryable - case 5: - return true // Network error, retryable - case 6: - return false // File/path error, usually not retryable - case 125: - return true // Temporary failure, retryable - default: - // For unknown exit codes, default to non-retryable to be safe - return false - } -} - -func checkoutSVNPackage(ctx context.Context, svnBaseRepoURL, packageName, packageType, outputDir string) (string, int, error) { - l := log.WithFields(logrus.Fields{ - "package": packageName, - "type": packageType, - "action": "svn_checkout", - }) - - var packageSvnURL string - - if packageType == "theme" { - packageSvnURL = fmt.Sprintf("%s/%s", strings.TrimRight(svnBaseRepoURL, "/"), packageName) - } else { - packageSvnURL = fmt.Sprintf("%s/%s/tags", strings.TrimRight(svnBaseRepoURL, "/"), packageName) - } - - localCheckoutPath := filepath.Join(outputDir, packageName) - - parentDirForCheckout := filepath.Dir(localCheckoutPath) - if err := os.MkdirAll(parentDirForCheckout, 0755); err != nil { - l.WithError(err).Errorf("āŒ failed to create parent directory: %s", parentDirForCheckout) - return "", -1, errors.Wrapf(err, "failed to create parent dir for %s", localCheckoutPath) - } - - // Remove existing directory for clean checkout - if _, err := os.Stat(localCheckoutPath); err == nil { - l.Infof("šŸ—‘ļø removing existing directory %s for clean checkout", localCheckoutPath) - if err := os.RemoveAll(localCheckoutPath); err != nil { - l.WithError(err).Errorf("āš ļø failed to remove existing directory %s", localCheckoutPath) - } else { - l.Debug("āœ… successfully removed existing directory") - } - } - - l.Infof("šŸ“„ checking out %s to %s", packageSvnURL, localCheckoutPath) - - cmdArgs := []string{ - "co", - "--non-interactive", - "--trust-server-cert-failures=unknown-ca,cn-mismatch,expired,not-yet-valid,other", - packageSvnURL, - localCheckoutPath, - } - - cmd := exec.CommandContext(ctx, "svn", cmdArgs...) - outputBytes, err := cmd.CombinedOutput() - outputStr := string(outputBytes) - - l.WithField("output", outputStr).Debug("svn command output") - - exitCode := 0 - if err != nil { - if exitError, ok := err.(*exec.ExitError); ok { - exitCode = exitError.ExitCode() - } else { - exitCode = -1 - } - } - - l.WithFields(logrus.Fields{ - "exit_code": exitCode, - "output": outputStr[:min(200, len(outputStr))], - }).Debug("svn checkout command completed") - - if err != nil { - l.WithError(err).WithFields(logrus.Fields{ - "exit_code": exitCode, - "full_output": outputStr, - }).Error("āŒ svn checkout command failed") - - return localCheckoutPath, exitCode, errors.Wrapf(err, "svn checkout failed for %s (exit code %d). output: %s", packageSvnURL, exitCode, outputStr) - } - - l.Info("āœ… svn checkout successful") - return localCheckoutPath, exitCode, nil -} - -func downloaderWorker(ctx context.Context, cfg *DownloaderConfig, manifest *DownloaderManifest, packageNames <-chan string, wg *sync.WaitGroup) { - defer wg.Done() - - for packageName := range packageNames { - select { - case <-ctx.Done(): - log.WithField("package", packageName).Info("āš ļø worker context cancelled, stopping") - return - default: - } - - l := log.WithField("package", packageName) - l.Info("šŸ‘· worker processing package") - - currentState, exists := manifest.GetPackageState(packageName) - - if exists { - if currentState.Status == "downloaded" || currentState.Status == "api_not_found" || currentState.Status == "skipped_invalid_name" { - l.Infof("ā­ļø package status is '%s', skipping", currentState.Status) - continue - } - if currentState.Status == "download_failed" && !currentState.Retryable { - l.Infof("ā­ļø package download failed previously (non-retryable: %s), skipping", currentState.Error) - continue - } - } - - if !exists { - currentState = &PackageDownloadState{Status: "pending_api_check"} - } else if currentState.Status == "download_failed" && currentState.Retryable { - l.Info("šŸ”„ retrying previously failed (but retryable) download") - currentState.Status = "api_qualified_pending_download" - } else { - currentState.Status = "pending_api_check" - } - - currentState.Retryable = false - manifest.UpdatePackageState(packageName, currentState) - - if !nameReg.MatchString(packageName) { - l.Warnf("āš ļø package name '%s' is not a valid slug", packageName) - currentState.Status = "skipped_invalid_name" - currentState.Error = "invalid slug format" - manifest.UpdatePackageState(packageName, currentState) - continue - } - - if currentState.Status == "pending_api_check" { - l.Info("šŸ” checking package against wordpress api...") - - select { - case <-ctx.Done(): - l.Info("āš ļø context cancelled during api check") - return - default: - } - - currentAPIVersion, statusCode, err := fetchLatestVersion(ctx, packageName, cfg.PackageType) - - if err != nil { - currentState.Error = err.Error() - if statusCode == http.StatusNotFound || strings.Contains(err.Error(), "no version") { - l.Info("āŒ package not found on wordpress api (404 or no version)") - currentState.Status = "api_not_found" - currentState.LatestVersion = "" - } else { - l.WithError(err).Warn("āš ļø error checking package with wordpress api") - currentState.Status = "api_error" - } - } else { - l.Infof("āœ… package found on wordpress api, version: %s", currentAPIVersion) - if currentState.LatestVersion != "" && currentState.LatestVersion != currentAPIVersion { - l.Infof("šŸ”„ api version changed: old '%s', new '%s', will re-sync", currentState.LatestVersion, currentAPIVersion) - } - currentState.Status = "api_qualified_pending_download" - currentState.LatestVersion = currentAPIVersion - currentState.Error = "" - } - - manifest.UpdatePackageState(packageName, currentState) - } - - if currentState.Status == "api_qualified_pending_download" { - select { - case <-ctx.Done(): - l.Info("āš ļø context cancelled during download") - return - default: - } - - l.Info("šŸ“„ attempting svn checkout...") - localPath, exitCode, err := checkoutSVNPackage(ctx, cfg.SvnRepoURL, packageName, cfg.PackageType, cfg.OutputDir) - - currentState.LocalPath = localPath - currentState.LastExitCode = exitCode - - if err != nil { - l.WithError(err).WithField("exit_code", exitCode).Error("āŒ failed to checkout package from svn") - currentState.Status = "download_failed" - currentState.Error = err.Error() - - if isRetryableExitCode(exitCode) { - currentState.Retryable = true - l.Infof("šŸ”„ marking download as retryable based on exit code %d", exitCode) - } else { - currentState.Retryable = false - l.Infof("āŒ marking download as non-retryable based on exit code %d", exitCode) - } - } else { - l.Info("šŸŽ‰ package downloaded/updated successfully") - currentState.Status = "downloaded" - currentState.SVNCheckedOutAt = time.Now() - currentState.Error = "" - currentState.Retryable = false - } - - manifest.UpdatePackageState(packageName, currentState) - } - - // Save manifest after each package - select { - case <-ctx.Done(): - l.Info("āš ļø context cancelled before saving manifest") - return - default: - } - - if err := manifest.Save(); err != nil { - l.WithError(err).Error("āŒ failed to save manifest after processing package") - } - } -} - -var rootCmd = &cobra.Command{ - Use: "svn-download", - Short: "wordpress theme/plugin svn downloader", - SilenceUsage: true, - SilenceErrors: true, - RunE: runDownload, -} - -func runDownload(cmd *cobra.Command, args []string) error { - log.SetOutput(os.Stdout) - log.SetFormatter(&logrus.TextFormatter{ForceColors: true, FullTimestamp: true}) - - cfg := DownloaderConfig{} - cfg.PackageType, _ = cmd.Flags().GetString("type") - cfg.OutputDir, _ = cmd.Flags().GetString("output-dir") - cfg.NumWorkers, _ = cmd.Flags().GetInt("workers") - cfg.ManifestPath, _ = cmd.Flags().GetString("manifest-path") - cfg.Limit, _ = cmd.Flags().GetInt("limit") - cfg.Verbose, _ = cmd.Flags().GetBool("verbose") - cfg.LogPath, _ = cmd.Flags().GetString("log-path") - - if err := validateConfig(&cfg); err != nil { - _, _ = fmt.Fprintf(os.Stderr, "validation error: %v\n", err) - return err - } - - logLevel := logrus.InfoLevel - if cfg.Verbose { - logLevel = logrus.DebugLevel - } - - if err := setupLogger(logLevel, cfg.LogPath, cfg.Verbose); err != nil { - fmt.Fprintf(os.Stderr, "critical: failed to setup logger: %v\n", err) - return err - } - - mainLogger := log.WithField("component", "main") - mainLogger.Info("šŸš€ wordpress svn downloader started") - - mainLogger.WithFields(logrus.Fields{ - "package_type": cfg.PackageType, - "output_dir": cfg.OutputDir, - "workers": cfg.NumWorkers, - "limit": cfg.Limit, - "verbose": cfg.Verbose, - "log_path": cfg.LogPath, - }).Debug("configuration loaded") - - mainLogger.Infof("šŸ“„ using manifest file: %s", cfg.ManifestPath) - manifest, err := loadDownloaderManifest(cfg.ManifestPath) - if err != nil { - mainLogger.WithError(err).Error("āŒ failed to load or initialize downloader manifest") - return err - } - - if manifest.RepoType != "" && manifest.RepoType != cfg.PackageType { - mainLogger.Warnf("āš ļø manifest was for '%s', current run is for '%s', package states might be irrelevant", manifest.RepoType, cfg.PackageType) - } - manifest.RepoType = cfg.PackageType - manifest.SvnBaseURL = cfg.SvnRepoURL - - // Setup signal handling with immediate cancellation - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - sigCh := make(chan os.Signal, 1) - signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) - - go func() { - sig := <-sigCh - mainLogger.Warnf("šŸ›‘ received signal %s, cancelling all operations immediately", sig) - cancel() - - time.Sleep(2 * time.Second) - mainLogger.Warn("šŸ›‘ force exiting after cleanup timeout") - os.Exit(1) - }() - - mainLogger.Info("šŸ“‹ listing packages from svn, this might take a while...") - allPackageNames, err := listSVNPackages(ctx, cfg.SvnRepoURL, cfg.Limit) - if err != nil { - if ctx.Err() == context.Canceled { - mainLogger.Info("āš ļø svn listing cancelled by user") - return nil - } - mainLogger.WithError(err).Error("āŒ failed to list packages from svn") - if saveErr := manifest.Save(); saveErr != nil { - mainLogger.WithError(saveErr).Error("āŒ failed to save manifest after svn list failure") - } - return err - } - - if len(allPackageNames) == 0 { - mainLogger.Info("ā„¹ļø no packages found in svn repository list") - if saveErr := manifest.Save(); saveErr != nil { - mainLogger.WithError(saveErr).Error("āŒ failed to save manifest (no packages listed)") - } - return nil - } - - if cfg.Limit > 0 && len(allPackageNames) > cfg.Limit { - allPackageNames = allPackageNames[:cfg.Limit] - } - mainLogger.Infof("šŸ“Š total packages to consider: %d", len(allPackageNames)) - - jobs := make(chan string, len(allPackageNames)) - var wg sync.WaitGroup - - numEffectiveWorkers := cfg.NumWorkers - if len(allPackageNames) < numEffectiveWorkers { - numEffectiveWorkers = len(allPackageNames) - } - if numEffectiveWorkers == 0 && len(allPackageNames) > 0 { - numEffectiveWorkers = 1 - } - - mainLogger.Infof("šŸ‘· starting download process: %d packages with %d workers", len(allPackageNames), numEffectiveWorkers) - - // Start workers - for i := 0; i < numEffectiveWorkers; i++ { - wg.Add(1) - go downloaderWorker(ctx, &cfg, manifest, jobs, &wg) - } - - // Job feeder - go func() { - defer close(jobs) - for _, pkgName := range allPackageNames { - select { - case jobs <- pkgName: - case <-ctx.Done(): - mainLogger.Info("āš ļø context cancelled, stopping job feeding") - return - } - } - }() - - // Wait for completion or cancellation - done := make(chan struct{}) - go func() { - wg.Wait() - close(done) - }() - - select { - case <-done: - mainLogger.Info("āœ… all workers finished") - case <-ctx.Done(): - mainLogger.Warn("āš ļø operation cancelled, waiting for workers to finish current tasks...") - <-done - mainLogger.Info("āœ… workers finished after cancellation") - } - - mainLogger.Info("šŸ’¾ saving final manifest...") - if err := manifest.Save(); err != nil { - mainLogger.WithError(err).Error("āŒ failed to save final manifest") - return err - } - - fmt.Println("\n" + strings.Repeat("=", 80)) - fmt.Println("šŸ“„ detailed logs: stdout (text) + log file (json)") - fmt.Println("šŸ“‹ manifest files: svn-download-manifest.json") - fmt.Println(strings.Repeat("=", 80)) - - mainLogger.Info("šŸŽ‰ download process completed") - return nil -} - -func validateConfig(config *DownloaderConfig) error { - // Validate package type - if config.PackageType != "theme" && config.PackageType != "plugin" { - return errors.New("package type must be 'theme' or 'plugin'") - } - - // Set SVN repository URL based on package type - if config.PackageType == "theme" { - config.SvnRepoURL = "https://themes.svn.wordpress.org" - } else { - config.SvnRepoURL = "https://plugins.svn.wordpress.org" - } - - // Validate and setup output directory - if config.OutputDir == "" { - config.OutputDir = filepath.Join(".", "wp-content", config.PackageType+"s") - } - - absOutputDir, err := filepath.Abs(config.OutputDir) - if err != nil { - return errors.Wrapf(err, "invalid output directory path: %s", config.OutputDir) - } - config.OutputDir = absOutputDir - - // Create output directory and test write permissions - if err := os.MkdirAll(config.OutputDir, 0755); err != nil { - return errors.Wrapf(err, "failed to create output directory: %s", config.OutputDir) - } - - // Test write permissions by creating a temporary file - testFile := filepath.Join(config.OutputDir, ".write_test") - if err := os.WriteFile(testFile, []byte("test"), 0644); err != nil { - return errors.Wrapf(err, "no write permission for output directory: %s", config.OutputDir) - } - os.Remove(testFile) // Clean up test file - - log.Infof("šŸ“ output directory: %s", config.OutputDir) - - // Check SVN installation - if err := checkSVNInstalled(); err != nil { - return errors.Wrap(err, "svn installation check failed") - } - log.Info("āœ… svn command-line tool found") - - // Test SVN repository connectivity - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - - log.Infof("šŸ”— testing connectivity to svn repository: %s", config.SvnRepoURL) - cmd := exec.CommandContext(ctx, "svn", "info", config.SvnRepoURL, "--non-interactive") - if err := cmd.Run(); err != nil { - return errors.Wrapf(err, "failed to connect to svn repository: %s", config.SvnRepoURL) - } - log.Info("āœ… svn repository connectivity confirmed") - - // Test WordPress API connectivity - log.Info("🌐 testing connectivity to wordpress api...") - ctx2, cancel2 := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel2() - - var testAPIURL string - if config.PackageType == "theme" { - testAPIURL = "https://api.wordpress.org/themes/info/1.2/?action=theme_information&slug=twentytwentyfour" - } else { - testAPIURL = "https://api.wordpress.org/plugins/info/1.2/?action=plugin_information&slug=hello-dolly" - } - - req, err := http.NewRequestWithContext(ctx2, "GET", testAPIURL, nil) - if err != nil { - return errors.Wrap(err, "failed to create test api request") - } - - resp, err := downloaderHttpClient.Do(req) - if err != nil { - return errors.Wrapf(err, "failed to connect to wordpress api: %s", testAPIURL) - } - resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("wordpress api returned status %d, expected 200", resp.StatusCode) - } - log.Info("āœ… wordpress api connectivity confirmed") - - // Validate workers count - if config.NumWorkers <= 0 { - config.NumWorkers = defaultDownloaderWorkers - log.Infof("āš ļø invalid workers count, using default: %d", defaultDownloaderWorkers) - } - if config.NumWorkers > 50 { - return errors.New("workers count cannot exceed 50 (to prevent overwhelming the svn server)") - } - - // Validate limit - if config.Limit < 0 { - config.Limit = 0 - log.Warn("āš ļø negative limit not allowed, using 0 (no limit)") - } - - // Validate and setup manifest path - if config.ManifestPath == "" { - config.ManifestPath = defaultDownloaderManifestFile - } - - absManifestPath, err := filepath.Abs(config.ManifestPath) - if err != nil { - return errors.Wrapf(err, "invalid manifest path: %s", config.ManifestPath) - } - config.ManifestPath = absManifestPath - - // Ensure manifest directory exists and is writable - manifestDir := filepath.Dir(config.ManifestPath) - if err := os.MkdirAll(manifestDir, 0755); err != nil { - return errors.Wrapf(err, "failed to create manifest directory: %s", manifestDir) - } - - // Test manifest file write permissions - testManifest := config.ManifestPath + ".write_test" - if err := os.WriteFile(testManifest, []byte("{}"), 0644); err != nil { - return errors.Wrapf(err, "no write permission for manifest path: %s", config.ManifestPath) - } - os.Remove(testManifest) - - if config.LogPath == "" { - config.LogPath = globalLogFileName - log.Infof("šŸ“ no log path specified, using default: %s", config.LogPath) - } - - // Validate and setup log path - if config.LogPath != "" { - absLogPath, err := filepath.Abs(config.LogPath) - if err != nil { - return fmt.Errorf("invalid log path: %w", err) - } - config.LogPath = absLogPath - - info, err := os.Stat(config.LogPath) - if err == nil && info.IsDir() { - config.LogPath = filepath.Join(config.LogPath, globalLogFileName) - } else if os.IsNotExist(err) { - parentDir := filepath.Dir(config.LogPath) - if _, err := os.Stat(parentDir); os.IsNotExist(err) { - if mkErr := os.MkdirAll(parentDir, 0755); mkErr != nil { - return fmt.Errorf("cannot create log directory %s: %w", parentDir, mkErr) - } - } - } - - // Test log file write permissions - testLog := config.LogPath + ".write_test" - if err := os.WriteFile(testLog, []byte("test"), 0644); err != nil { - return errors.Wrapf(err, "no write permission for log path: %s", config.LogPath) - } - os.Remove(testLog) // Clean up test file - } - - return nil -} - -func init() { - rootCmd.Flags().StringP("type", "t", "", "repository type: 'plugin' or 'theme' (required)") - rootCmd.Flags().StringP("output-dir", "o", "", "directory to download packages into (default: ./wp-content/{type}s)") - rootCmd.Flags().IntP("workers", "w", defaultDownloaderWorkers, "number of parallel download workers") - rootCmd.Flags().StringP("manifest-path", "m", defaultDownloaderManifestFile, "path to the downloader manifest json file") - rootCmd.Flags().IntP("limit", "l", 0, "limit the number of packages to process (0 for no limit)") - rootCmd.Flags().BoolP("verbose", "v", false, "enable verbose (debug) logging") - rootCmd.Flags().String("log-path", "", fmt.Sprintf("path to json log file (default: ./%s)", globalLogFileName)) - - if err := rootCmd.MarkFlagRequired("type"); err != nil { - fmt.Fprintf(os.Stderr, "error marking 'type' flag as required: %v\n", err) - os.Exit(1) - } -} - -func main() { - if err := rootCmd.Execute(); err != nil { - fmt.Fprintf(os.Stderr, "āŒ failed to run command: %v\n", err) - os.Exit(1) - } -} diff --git a/cmd/svn-migrate/svn-migrate.go b/cmd/svn-migrate/svn-migrate.go deleted file mode 100644 index c1af85af..00000000 --- a/cmd/svn-migrate/svn-migrate.go +++ /dev/null @@ -1,1211 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "os" - "os/exec" - "path/filepath" - "regexp" - "strings" - "sync" - "time" - - "github.com/Masterminds/semver/v3" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "github.com/spf13/cobra" -) - -const ( - defaultMaxWorkers = 5 - defaultTagTimeout = 5 * time.Minute - requestTimeout = 30 * time.Second - statusSuccess = "success" - statusFailed = "failed" - statusPending = "pending" - manifestFileName = "manifest.json" - globalLogFileName = "wpm-migration-activity.log" - defaultDownloadManifestFile = "svn-download-manifest.json" - - wpmOutputAlreadyExists = "already exists" - wpmErrorInitNoPluginMainFile = "no main plugin file with valid plugin headers" - wpmErrorInitVersionMismatch = "does not match specified version" -) - -var ( - nameReg = regexp.MustCompile(`^[\w-]{3,164}$`) - httpClient = &http.Client{Timeout: requestTimeout} - log = logrus.New() -) - -type Config struct { - RepoPath string - RepoType string - MaxWorkers int - TagTimeout time.Duration - DryRun bool - Verbose bool - WpmPath string - LogPath string - DownloadManifestPath string -} - -type PackageInfo struct { - Name string - Type string - Path string - TagsPath string - SvnTags []string - LatestVersion string -} - -type TagManifest struct { - Status string `json:"status"` - PublishedAt time.Time `json:"published_at,omitempty"` - PublishTag string `json:"publish_tag,omitempty"` - Error string `json:"error,omitempty"` - Retryable bool `json:"retryable"` - LastAttempt time.Time `json:"last_attempt,omitempty"` - WpmInitLog string `json:"wpm_init_log,omitempty"` - WpmPublishLog string `json:"wpm_publish_log,omitempty"` -} - -type PackageManifest struct { - PackageName string `json:"package_name"` - Type string `json:"type"` - Qualified bool `json:"qualified"` - ApiLookupDone bool `json:"api_lookup_done"` - ApiError string `json:"api_error,omitempty"` - LatestWpVersion string `json:"latest_wp_version"` - TotalSvnTags int `json:"total_svn_tags"` - LastSvnSync time.Time `json:"last_svn_sync"` - LastUpdated time.Time `json:"last_updated"` - Tags map[string]TagManifest `json:"tags"` - path string `json:"-"` -} - -type MigrationResult struct { - PackageName string - IsQualified bool - QualificationReason string - SvnTagsCount int - TagsProcessedThisRun int - TagsSucceededThisRun int - TagsFailedThisRun int - TagsSkippedSuccess int - TagsSkippedNonRetryable int - Error error - Duration time.Duration -} - -type APIResponse struct { - Version string `json:"version"` -} - -// DownloadManifest structures for reading from svn-download-manifest.json -type DownloadPackageState struct { - Status string `json:"status"` - LatestVersion string `json:"latest_version,omitempty"` -} - -type DownloadManifest struct { - RepoType string `json:"repo_type"` - Packages map[string]*DownloadPackageState `json:"packages"` -} - -// FileHook enables dual logging: structured JSON to file, readable text to stdout -type FileHook struct { - file *os.File - formatter logrus.Formatter - levels []logrus.Level -} - -func NewFileHook(filePath string, formatter logrus.Formatter, levels []logrus.Level) (*FileHook, error) { - logDir := filepath.Dir(filePath) - if err := os.MkdirAll(logDir, 0755); err != nil { - return nil, errors.Wrapf(err, "failed to create log directory: %s", logDir) - } - - file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) - if err != nil { - return nil, errors.Wrapf(err, "failed to open log file: %s", filePath) - } - - return &FileHook{file: file, formatter: formatter, levels: levels}, nil -} - -func (hook *FileHook) Fire(entry *logrus.Entry) error { - lineBytes, err := hook.formatter.Format(entry) - if err != nil { - return err - } - _, err = hook.file.Write(lineBytes) - return err -} - -func (hook *FileHook) Levels() []logrus.Level { - if len(hook.levels) == 0 { - return logrus.AllLevels - } - return hook.levels -} - -func setupLogger(logLevel logrus.Level, jsonLogFilePath string, verbose bool) error { - log.SetOutput(os.Stdout) - log.SetLevel(logLevel) - - if verbose { - log.SetFormatter(&logrus.TextFormatter{ - FullTimestamp: true, - TimestampFormat: "2006-01-02 15:04:05.000", - ForceColors: true, - }) - } else { - log.SetFormatter(&logrus.TextFormatter{ - TimestampFormat: "15:04:05", - ForceColors: true, - }) - } - - if jsonLogFilePath != "" { - fileHook, err := NewFileHook(jsonLogFilePath, &logrus.JSONFormatter{ - TimestampFormat: time.RFC3339Nano, - }, logrus.AllLevels) - - if err != nil { - log.WithError(err).Errorf("āŒ failed to initialize file logging: %s", jsonLogFilePath) - } else { - log.AddHook(fileHook) - log.Infof("šŸ“ logging: text to stdout, json to %s", jsonLogFilePath) - } - } else { - log.Info("šŸ“ logging: text to stdout only") - } - - return nil -} - -func loadDownloadManifest(path string) (*DownloadManifest, error) { - if path == "" { - return nil, nil // No download manifest configured - } - - data, err := os.ReadFile(path) - if err != nil { - if os.IsNotExist(err) { - log.Debugf("download manifest not found at %s", path) - return nil, nil // File doesn't exist, that's ok - } - return nil, errors.Wrapf(err, "failed to read download manifest %s", path) - } - - var manifest DownloadManifest - if err := json.Unmarshal(data, &manifest); err != nil { - return nil, errors.Wrapf(err, "failed to unmarshal download manifest %s", path) - } - - if manifest.Packages == nil { - manifest.Packages = make(map[string]*DownloadPackageState) - } - - log.Debugf("loaded download manifest from %s with %d packages", path, len(manifest.Packages)) - return &manifest, nil -} - -func getVersionFromDownloadManifest(downloadManifest *DownloadManifest, packageName, repoType string) (string, bool) { - if downloadManifest == nil { - return "", false - } - - // Check if manifest is for the same repo type - if downloadManifest.RepoType != repoType { - log.Debugf("download manifest repo type mismatch: expected %s, got %s", repoType, downloadManifest.RepoType) - return "", false - } - - pkgState, exists := downloadManifest.Packages[packageName] - if !exists { - return "", false - } - - // Only use version if package was successfully processed and has a version - if pkgState.Status == "downloaded" && pkgState.LatestVersion != "" { - return pkgState.LatestVersion, true - } - - return "", false -} - -// normalizeVersion handles version strings with more than 3 dot-separated parts -func normalizeVersion(version string) (string, error) { - if version == "" { - return "", errors.New("version cannot be empty") - } - - parts := strings.Split(version, ".") - if len(parts) > 3 { - major := parts[0] - minor := parts[1] - patch := parts[2] - prerelease := strings.Join(parts[3:], ".") - version = fmt.Sprintf("%s.%s.%s-%s", major, minor, patch, prerelease) - } - - v, err := semver.NewVersion(version) - if err != nil { - return "", errors.Wrapf(err, "invalid version format: %s", version) - } - - return v.String(), nil -} - -func getManifestPath(packageRootPath string) string { - return filepath.Join(packageRootPath, manifestFileName) -} - -func loadManifest(manifestPath string) (*PackageManifest, error) { - data, err := os.ReadFile(manifestPath) - if err != nil { - if os.IsNotExist(err) { - return nil, os.ErrNotExist - } - return nil, errors.Wrapf(err, "failed to read manifest: %s", manifestPath) - } - - var manifest PackageManifest - if err := json.Unmarshal(data, &manifest); err != nil { - return nil, errors.Wrapf(err, "failed to unmarshal manifest: %s", manifestPath) - } - - manifest.path = manifestPath - if manifest.Tags == nil { - manifest.Tags = make(map[string]TagManifest) - } - - return &manifest, nil -} - -func saveManifest(manifest *PackageManifest) error { - manifest.LastUpdated = time.Now() - data, err := json.MarshalIndent(manifest, "", " ") - if err != nil { - return errors.Wrap(err, "failed to marshal manifest") - } - - if manifest.path == "" { - return errors.New("manifest path is not set") - } - - if err := os.MkdirAll(filepath.Dir(manifest.path), 0755); err != nil { - return errors.Wrapf(err, "failed to create directory for manifest: %s", manifest.path) - } - - return os.WriteFile(manifest.path, data, 0644) -} - -func fetchLatestVersion(ctx context.Context, packageName, repoType string, downloadManifest *DownloadManifest) (version string, statusCode int, err error) { - l := log.WithFields(logrus.Fields{"package": packageName, "action": "api_lookup"}) - - // First, try to get version from download manifest - if downloadManifest != nil { - if manifestVersion, found := getVersionFromDownloadManifest(downloadManifest, packageName, repoType); found { - l.Debugf("āœ… found version in download manifest: %s", manifestVersion) - return manifestVersion, 200, nil // Return 200 to indicate success - } - l.Debug("version not found in download manifest, falling back to api call") - } else { - l.Debug("no download manifest available, using api call") - } - - var apiURL string - if repoType == "theme" { - apiURL = fmt.Sprintf("https://api.wordpress.org/themes/info/1.2/?action=theme_information&slug=%s", packageName) - } else { - apiURL = fmt.Sprintf("https://api.wordpress.org/plugins/info/1.2/?action=plugin_information&slug=%s", packageName) - } - - l.Debugf("fetching from: %s", apiURL) - - req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil) - if err != nil { - return "", 0, errors.Wrap(err, "failed to create API request") - } - - resp, err := httpClient.Do(req) - if err != nil { - return "", 0, errors.Wrap(err, "API request failed") - } - defer resp.Body.Close() - - bodyBytes, readErr := io.ReadAll(resp.Body) - if readErr != nil { - l.WithError(readErr).Warn("could not read api response body") - } - - if resp.StatusCode != http.StatusOK { - return "", resp.StatusCode, fmt.Errorf("api returned status %d. body: %s", resp.StatusCode, string(bodyBytes)) - } - - var apiResp APIResponse - if err := json.Unmarshal(bodyBytes, &apiResp); err != nil { - return "", resp.StatusCode, errors.Wrapf(err, "failed to decode api response. body: %s", string(bodyBytes)) - } - - if apiResp.Version == "" { - return "", resp.StatusCode, fmt.Errorf("api response has no version. body: %s", string(bodyBytes)) - } - - l.Debugf("āœ… fetched version from api: %s", apiResp.Version) - return apiResp.Version, resp.StatusCode, nil -} - -func getPackageSvnTags(tagsPath string) ([]string, error) { - l := log.WithField("tags_path", tagsPath) - entries, err := os.ReadDir(tagsPath) - if err != nil { - return nil, errors.Wrapf(err, "failed to read tags directory: %s", tagsPath) - } - - var validRawTags []string - for _, entry := range entries { - if entry.IsDir() { - dirName := entry.Name() - if strings.HasPrefix(dirName, ".") { - l.Debugf("skipping dot-directory: %s", dirName) - continue - } - - if _, normErr := normalizeVersion(dirName); normErr == nil { - validRawTags = append(validRawTags, dirName) - } else { - l.Debugf("skipping invalid version '%s': %v", dirName, normErr) - } - } - } - - l.Debugf("found %d valid tag directories", len(validRawTags)) - return validRawTags, nil -} - -func runWpmCommand(ctx context.Context, l *logrus.Entry, wpmPath string, args []string, workDir string) (string, error) { - cmd := exec.CommandContext(ctx, wpmPath, args...) - cmd.Dir = workDir - - commandStr := fmt.Sprintf("%s %s", wpmPath, strings.Join(args, " ")) - l.WithFields(logrus.Fields{ - "command": commandStr, - "workdir": workDir, - }).Info("šŸ”§ executing wpm command") - - outputBytes, err := cmd.CombinedOutput() - outputStr := string(outputBytes) - - l.WithField("output", outputStr).Debug("wpm command output") - - if err != nil { - exitCode := -1 - if cmd.ProcessState != nil { - exitCode = cmd.ProcessState.ExitCode() - } - - l.WithFields(logrus.Fields{ - "exit_code": exitCode, - "output": outputStr, - }).WithError(err).Error("āŒ wpm command failed") - - if ctx.Err() == context.DeadlineExceeded { - return outputStr, errors.New("wpm command timed out") - } - return outputStr, errors.Wrapf(err, "wpm command failed. output: %s", outputStr) - } - - l.Info("āœ… wpm command completed") - return outputStr, nil -} - -func migratePackage(ctx context.Context, pkgInfo *PackageInfo, manifest *PackageManifest, config *Config) *MigrationResult { - start := time.Now() - l := log.WithFields(logrus.Fields{ - "package": pkgInfo.Name, - "type": pkgInfo.Type, - "action": "migrate", - }) - - result := &MigrationResult{ - PackageName: pkgInfo.Name, - IsQualified: manifest.Qualified, - QualificationReason: manifest.ApiError, - SvnTagsCount: len(pkgInfo.SvnTags), - } - - if manifest.Qualified { - result.QualificationReason = "OK" - } - - l.WithFields(logrus.Fields{ - "tags_path": pkgInfo.TagsPath, - "tags_count": len(pkgInfo.SvnTags), - "qualified": manifest.Qualified, - "api_done": manifest.ApiLookupDone, - "api_error": manifest.ApiError, - "latest_version": manifest.LatestWpVersion, - "tag_timeout": config.TagTimeout.Seconds(), - "dry_run": config.DryRun, - }).Info("šŸš€ starting package migration") - - if !manifest.Qualified && manifest.ApiLookupDone { - l.Infof("ā­ļø package not qualified (%s). skipping tags.", manifest.ApiError) - if err := saveManifest(manifest); err != nil { - l.WithError(err).Error("failed to save manifest for non-qualified package") - result.Error = errors.Wrapf(err, "failed to save manifest for %s", pkgInfo.Name) - } - result.Duration = time.Since(start) - return result - } - - for i, rawVersionName := range pkgInfo.SvnTags { - tagLogger := l.WithFields(logrus.Fields{ - "tag": rawVersionName, - "index": fmt.Sprintf("%d/%d", i+1, len(pkgInfo.SvnTags)), - }) - - tagLogger.Info("šŸ·ļø processing tag") - - tagManifestEntry, entryExists := manifest.Tags[rawVersionName] - - if entryExists { - if tagManifestEntry.Status == statusSuccess { - tagLogger.Info("āœ… already migrated successfully") - result.TagsSkippedSuccess++ - continue - } - if tagManifestEntry.Status == statusFailed && !tagManifestEntry.Retryable { - tagLogger.WithField("error", tagManifestEntry.Error).Info("ā­ļø failed previously (non-retryable)") - result.TagsSkippedNonRetryable++ - continue - } - } else { - tagManifestEntry = TagManifest{Status: statusPending} - } - - result.TagsProcessedThisRun++ - tagManifestEntry.LastAttempt = time.Now() - tagPath := filepath.Join(pkgInfo.TagsPath, rawVersionName) - - if _, statErr := os.Stat(tagPath); os.IsNotExist(statErr) { - errMsg := fmt.Sprintf("tag directory not found: %s", tagPath) - tagLogger.WithField("tag_path", tagPath).Error("āŒ " + errMsg) - tagManifestEntry.Status = statusFailed - tagManifestEntry.Error = errMsg - tagManifestEntry.Retryable = false - manifest.Tags[rawVersionName] = tagManifestEntry - result.TagsFailedThisRun++ - - if !config.DryRun { - if err := saveManifest(manifest); err != nil { - tagLogger.WithError(err).Error("failed to save manifest") - } - } - continue - } - - versionForWpmCommand := rawVersionName - - if config.DryRun { - tagLogger.WithField("wpm_version", versionForWpmCommand).Info("šŸ” dry run: would migrate") - continue - } - - tagCtx, cancelTag := context.WithTimeout(ctx, config.TagTimeout) - - // wpm init - initArgs := []string{"--cwd", tagPath, "init", "--migrate", "--name", pkgInfo.Name, "--version", versionForWpmCommand} - initOutput, initErr := runWpmCommand(tagCtx, tagLogger.WithField("cmd", "init"), config.WpmPath, initArgs, tagPath) - tagManifestEntry.WpmInitLog = initOutput - - if initErr != nil { - errStr := initErr.Error() - if strings.Contains(initOutput, wpmOutputAlreadyExists) || strings.Contains(errStr, wpmOutputAlreadyExists) { - tagLogger.Info("āœ… wpm init: already exists, continuing") - tagManifestEntry.Error = "" - } else { - tagManifestEntry.Error = fmt.Sprintf("init failed: %s", errStr) - if strings.Contains(errStr, wpmErrorInitNoPluginMainFile) || strings.Contains(errStr, wpmErrorInitVersionMismatch) { - tagLogger.WithError(initErr).Error("āŒ wpm init failed (non-retryable)") - tagManifestEntry.Status = statusFailed - tagManifestEntry.Retryable = false - } else { - tagLogger.WithError(initErr).Error("āŒ wpm init failed (retryable)") - tagManifestEntry.Status = statusFailed - tagManifestEntry.Retryable = true - } - cancelTag() - manifest.Tags[rawVersionName] = tagManifestEntry - result.TagsFailedThisRun++ - if err := saveManifest(manifest); err != nil { - tagLogger.WithError(err).Error("failed to save manifest after init fail") - } - continue - } - } else { - tagLogger.Info("āœ… wpm init successful") - tagManifestEntry.Error = "" - } - - // wpm publish - publishCmdTag := "untagged" - if rawVersionName == manifest.LatestWpVersion { - publishCmdTag = "latest" - } - tagManifestEntry.PublishTag = publishCmdTag - - publishArgs := []string{"--cwd", tagPath, "publish", "--access", "public", "--tag", publishCmdTag} - publishOutput, publishErr := runWpmCommand(tagCtx, tagLogger.WithField("cmd", "publish"), config.WpmPath, publishArgs, tagPath) - tagManifestEntry.WpmPublishLog = publishOutput - - if publishErr != nil { - errStr := publishErr.Error() - tagManifestEntry.Error = fmt.Sprintf("publish failed: %s", errStr) - if strings.Contains(publishOutput, wpmOutputAlreadyExists) || strings.Contains(errStr, wpmOutputAlreadyExists) { - tagLogger.Info("āœ… wpm publish: already published") - tagManifestEntry.Status = statusSuccess - tagManifestEntry.PublishedAt = time.Now() - tagManifestEntry.Error = "" - tagManifestEntry.Retryable = false - } else { - tagLogger.WithError(publishErr).Error("āŒ wpm publish failed (retryable)") - tagManifestEntry.Status = statusFailed - tagManifestEntry.Retryable = true - } - } else { - tagLogger.WithField("publish_tag", publishCmdTag).Info("šŸŽ‰ successfully migrated") - tagManifestEntry.Status = statusSuccess - tagManifestEntry.PublishedAt = time.Now() - tagManifestEntry.Error = "" - tagManifestEntry.Retryable = false - } - - cancelTag() - - manifest.Tags[rawVersionName] = tagManifestEntry - - switch tagManifestEntry.Status { - case statusSuccess: - result.TagsSucceededThisRun++ - case statusFailed: - result.TagsFailedThisRun++ - } - - if err := saveManifest(manifest); err != nil { - errMsg := fmt.Sprintf("critical: failed to save manifest after processing %s", rawVersionName) - tagLogger.WithError(err).Error(errMsg) - result.Error = errors.New(errMsg) - result.Duration = time.Since(start) - return result - } - - tagLogger.Info("āœ… finished processing tag") - } - - l.WithFields(logrus.Fields{ - "total_tags": result.SvnTagsCount, - "attempted": result.TagsProcessedThisRun, - "succeeded": result.TagsSucceededThisRun, - "failed": result.TagsFailedThisRun, - "skipped_ok": result.TagsSkippedSuccess, - "skipped_nonret": result.TagsSkippedNonRetryable, - "duration": time.Since(start).Seconds(), - }).Info("šŸ“Š package migration summary") - - if err := saveManifest(manifest); err != nil { - l.WithError(err).Error("failed to save manifest at end") - if result.Error == nil { - result.Error = errors.Wrap(err, "final manifest save failed") - } - } - - result.Duration = time.Since(start) - return result -} - -func processPackage(ctx context.Context, svnRepoPath, repoType, packageName string, config *Config, downloadManifest *DownloadManifest) (*PackageInfo, *PackageManifest, error) { - l := log.WithFields(logrus.Fields{ - "package": packageName, - "type": repoType, - "action": "process", - }) - - l.Info("šŸ“¦ starting package processing") - - packageRootPath := filepath.Join(svnRepoPath, packageName) - - if _, err := os.Stat(packageRootPath); os.IsNotExist(err) { - l.WithError(err).Error("āŒ package directory not found") - return nil, nil, fmt.Errorf("package directory not found: %s", packageRootPath) - } - - if _, err := os.Stat(packageRootPath); os.IsNotExist(err) { - if repoType == "plugin" { - l.WithField("tags_dir", packageRootPath).Error("āŒ plugin tags directory missing") - manifestPath := getManifestPath(packageRootPath) - manifest := &PackageManifest{ - PackageName: packageName, - Type: repoType, - Qualified: false, - ApiLookupDone: true, - ApiError: fmt.Sprintf("plugin tags directory missing: %s", packageRootPath), - Tags: make(map[string]TagManifest), - path: manifestPath, - } - if errSave := saveManifest(manifest); errSave != nil { - l.WithError(errSave).Error("failed to save manifest") - return nil, nil, errors.Wrapf(errSave, "failed to save manifest for %s", packageName) - } - pkgInfo := &PackageInfo{Name: packageName, Type: repoType, Path: packageRootPath, TagsPath: packageRootPath, SvnTags: []string{}} - return pkgInfo, manifest, nil - } - } - - manifestPath := getManifestPath(packageRootPath) - manifest, err := loadManifest(manifestPath) - previousSvnTagCount := 0 - - if err != nil { - if !os.IsNotExist(err) { - l.WithError(err).Error("āŒ error loading manifest") - return nil, nil, errors.Wrapf(err, "error loading manifest for %s", packageName) - } - - l.Info("šŸ“ creating new manifest") - manifest = &PackageManifest{ - PackageName: packageName, - Type: repoType, - Tags: make(map[string]TagManifest), - path: manifestPath, - } - } else { - l.Debug("āœ… manifest loaded") - previousSvnTagCount = manifest.TotalSvnTags - manifest.Type = repoType - } - - currentSvnTags, err := getPackageSvnTags(packageRootPath) - if err != nil { - l.WithError(err).WithField("tags_dir", packageRootPath).Error("āŒ failed to get svn tags") - return nil, nil, errors.Wrapf(err, "failed to get svn tags for %s from %s", packageName, packageRootPath) - } - - manifest.TotalSvnTags = len(currentSvnTags) - manifest.LastSvnSync = time.Now() - l.Debugf("found %d valid svn tags (previous: %d)", manifest.TotalSvnTags, previousSvnTagCount) - - shouldFetchApi := false - if !manifest.ApiLookupDone { - shouldFetchApi = true - l.Debug("api lookup needed") - } else if manifest.Qualified && previousSvnTagCount != manifest.TotalSvnTags { - shouldFetchApi = true - l.Debug("refreshing api due to tag count change") - } else if !manifest.Qualified && manifest.ApiLookupDone && - !strings.Contains(manifest.ApiError, "(404)") && - !strings.Contains(manifest.ApiError, "plugin tags directory missing") { - l.Debugf("retrying api lookup: %s", manifest.ApiError) - shouldFetchApi = true - } - - if shouldFetchApi && !config.DryRun { - l.Info("šŸ” fetching latest version from wordpress api") - latestVersion, statusCode, apiErr := fetchLatestVersion(ctx, packageName, repoType, downloadManifest) - manifest.ApiLookupDone = true - - if apiErr != nil { - errMsg := apiErr.Error() - manifest.ApiError = errMsg - manifest.Qualified = false - manifest.LatestWpVersion = "" - - if statusCode == http.StatusNotFound { - manifest.ApiError = fmt.Sprintf("package not found on wordpress.org (%d)", statusCode) - l.Info("āŒ package not found on wordpress.org (404)") - } else { - l.WithField("status", statusCode).WithError(apiErr).Warn("āš ļø api error - marking as not qualified") - } - } else { - manifest.LatestWpVersion = latestVersion - manifest.Qualified = true - manifest.ApiError = "" - l.Infof("āœ… wordpress api latest version: %s", latestVersion) - } - - if errSave := saveManifest(manifest); errSave != nil { - l.WithError(errSave).Error("failed to save manifest after api call") - return nil, nil, errors.Wrapf(errSave, "failed to save manifest for %s after api call", packageName) - } - } else if config.DryRun && shouldFetchApi { - l.Info("šŸ” dry run: would fetch from wordpress api") - } - - pkgInfo := &PackageInfo{ - Name: packageName, - Type: repoType, - Path: packageRootPath, - TagsPath: packageRootPath, - SvnTags: currentSvnTags, - LatestVersion: manifest.LatestWpVersion, - } - - if !shouldFetchApi || config.DryRun { - if errSave := saveManifest(manifest); errSave != nil { - l.WithError(errSave).Error("failed to save manifest") - return nil, nil, errors.Wrapf(errSave, "failed to save manifest for %s", packageName) - } - } - - l.Info("āœ… finished package processing") - return pkgInfo, manifest, nil -} - -func worker(ctx context.Context, jobs <-chan string, results chan<- *MigrationResult, svnRepoPath string, config *Config, downloadManifest *DownloadManifest, wg *sync.WaitGroup) { - defer wg.Done() - - for packageName := range jobs { - workerLogger := log.WithField("worker_package", packageName) - - select { - case <-ctx.Done(): - workerLogger.WithError(ctx.Err()).Info("āš ļø worker context cancelled") - results <- &MigrationResult{PackageName: packageName, Error: ctx.Err()} - return - default: - workerLogger.Info("šŸ‘· worker processing package") - - pkgInfo, manifest, err := processPackage(ctx, svnRepoPath, config.RepoType, packageName, config, downloadManifest) - if err != nil { - workerLogger.WithError(err).Error("āŒ critical error during package processing") - results <- &MigrationResult{PackageName: packageName, Error: err} - continue - } - - if config.DryRun { - workerLogger.WithFields(logrus.Fields{ - "qualified": manifest.Qualified, - "api_done": manifest.ApiLookupDone, - "api_error": manifest.ApiError, - "valid_tags": len(pkgInfo.SvnTags), - "latest_version": manifest.LatestWpVersion, - }).Info("šŸ” dry run: package processed") - - results <- &MigrationResult{ - PackageName: packageName, - IsQualified: manifest.Qualified, - QualificationReason: manifest.ApiError, - SvnTagsCount: len(pkgInfo.SvnTags), - } - continue - } - - migrationResult := migratePackage(ctx, pkgInfo, manifest, config) - results <- migrationResult - workerLogger.Info("āœ… worker finished processing package") - } - } -} - -var rootCmd = &cobra.Command{ - Use: "svn-migrate", - Short: "svn to wpm migration tool", - Args: cobra.ExactArgs(1), - SilenceUsage: true, - SilenceErrors: true, - RunE: runMigrate, -} - -func runMigrate(cmd *cobra.Command, args []string) error { - log.SetOutput(os.Stdout) - log.SetFormatter(&logrus.TextFormatter{ForceColors: true, FullTimestamp: true}) - - config := &Config{} - config.RepoPath = args[0] - config.RepoType, _ = cmd.Flags().GetString("type") - config.MaxWorkers, _ = cmd.Flags().GetInt("workers") - config.TagTimeout, _ = cmd.Flags().GetDuration("tag-timeout") - config.DryRun, _ = cmd.Flags().GetBool("dry-run") - config.Verbose, _ = cmd.Flags().GetBool("verbose") - config.WpmPath, _ = cmd.Flags().GetString("wpm-path") - config.LogPath, _ = cmd.Flags().GetString("log-path") - config.DownloadManifestPath, _ = cmd.Flags().GetString("download-manifest-path") - - if err := validateConfig(config); err != nil { - _, _ = fmt.Fprintf(os.Stderr, "validation error: %v\n", err) - return err - } - - logLevel := logrus.InfoLevel - if config.Verbose { - logLevel = logrus.DebugLevel - } - - if err := setupLogger(logLevel, config.LogPath, config.Verbose); err != nil { - fmt.Fprintf(os.Stderr, "critical: failed to setup logger: %v\n", err) - return err - } - - mainLogger := log.WithField("component", "main") - mainLogger.Info("šŸš€ wordpress migration tool started") - - mainLogger.WithFields(logrus.Fields{ - "repo_path": config.RepoPath, - "repo_type": config.RepoType, - "workers": config.MaxWorkers, - "timeout": config.TagTimeout, - "dry_run": config.DryRun, - "verbose": config.Verbose, - "wpm_path": config.WpmPath, - "log_path": config.LogPath, - "download_manifest_path": config.DownloadManifestPath, - }).Debug("configuration loaded") - - // Load download manifest if available - var downloadManifest *DownloadManifest - if config.DownloadManifestPath != "" { - var err error - downloadManifest, err = loadDownloadManifest(config.DownloadManifestPath) - if err != nil { - mainLogger.WithError(err).Warn("āš ļø failed to load download manifest, will use api calls only") - downloadManifest = nil - } else if downloadManifest != nil { - mainLogger.Infof("āœ… loaded download manifest with %d packages", len(downloadManifest.Packages)) - if downloadManifest.RepoType != config.RepoType { - mainLogger.Warnf("āš ļø download manifest repo type mismatch: expected %s, got %s", config.RepoType, downloadManifest.RepoType) - } - } else { - mainLogger.Info("šŸ“„ download manifest not found, will use api calls only") - } - } else { - mainLogger.Debug("no download manifest path specified, will use api calls only") - } - - repoDirEntries, err := os.ReadDir(config.RepoPath) - if err != nil { - mainLogger.WithError(err).Errorf("āŒ failed to read repository directory: %s", config.RepoPath) - return fmt.Errorf("failed to read repository directory %s: %w", config.RepoPath, err) - } - - var validPackageNames []string - var skippedNames []string - - for _, entry := range repoDirEntries { - if entry.IsDir() { - name := entry.Name() - if !nameReg.MatchString(name) { - skippedNames = append(skippedNames, name) - continue - } - validPackageNames = append(validPackageNames, name) - } - } - - if len(skippedNames) > 0 { - mainLogger.WithFields(logrus.Fields{ - "count": len(skippedNames), - "skipped_dirs": strings.Join(skippedNames, ", "), - "name_regex": nameReg.String(), - }).Warn("āš ļø skipped directories with invalid package names") - } - - if len(validPackageNames) == 0 { - mainLogger.Warn("āš ļø no valid package directories found") - return nil - } - - mainLogger.Infof("šŸ“ found %d valid %s package(s)", len(validPackageNames), config.RepoType) - - if config.DryRun { - mainLogger.Info("šŸ” dry run mode enabled - no changes will be made") - } - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - jobs := make(chan string, len(validPackageNames)) - resultsChan := make(chan *MigrationResult, len(validPackageNames)) - var wg sync.WaitGroup - - numWorkers := config.MaxWorkers - if len(validPackageNames) < numWorkers { - numWorkers = len(validPackageNames) - } - - mainLogger.Infof("šŸ‘· starting migration: %d packages, %d workers, %v timeout per tag", - len(validPackageNames), numWorkers, config.TagTimeout) - - // Start workers - for i := 0; i < numWorkers; i++ { - wg.Add(1) - go worker(ctx, jobs, resultsChan, config.RepoPath, config, downloadManifest, &wg) - } - - // Feed jobs - go func() { - defer close(jobs) - for _, name := range validPackageNames { - select { - case jobs <- name: - case <-ctx.Done(): - mainLogger.Info("āš ļø job feeding cancelled") - return - } - } - }() - - // Close results when all workers done - go func() { - wg.Wait() - close(resultsChan) - }() - - // Collect results - var ( - totalPackagesProcessed, pkgsFullSuccess, pkgsPartialSuccess, - pkgsWithTagFails, pkgsNotQualified, pkgsCriticalError int - totalSvnTagsScanned, totalTagsAttemptedRun, - totalTagsSucceededRun, totalTagsFailedRun int - problematicPackages []string - ) - - overallStart := time.Now() - - for res := range resultsChan { - totalPackagesProcessed++ - resLogger := mainLogger.WithField("result_package", res.PackageName) - - if res.Error != nil { - resLogger.WithError(res.Error).Errorf("šŸ’„ critical error (%.2fs)", res.Duration.Seconds()) - pkgsCriticalError++ - problematicPackages = append(problematicPackages, - fmt.Sprintf("%s (critical error: %v)", res.PackageName, res.Error)) - continue - } - - if config.DryRun { - if !res.IsQualified && res.QualificationReason != "OK" && res.QualificationReason != "" { - pkgsNotQualified++ - } - continue - } - - totalSvnTagsScanned += res.SvnTagsCount - totalTagsAttemptedRun += res.TagsProcessedThisRun - totalTagsSucceededRun += res.TagsSucceededThisRun - totalTagsFailedRun += res.TagsFailedThisRun - - baseFields := logrus.Fields{ - "duration": fmt.Sprintf("%.2fs", res.Duration.Seconds()), - "tags_total": res.SvnTagsCount, - "tags_tried": res.TagsProcessedThisRun, - "tags_success": res.TagsSucceededThisRun, - "tags_failed": res.TagsFailedThisRun, - "tags_skip_ok": res.TagsSkippedSuccess, - "tags_skip_nr": res.TagsSkippedNonRetryable, - } - - if !res.IsQualified { - resLogger.WithFields(baseFields).WithField("reason", res.QualificationReason). - Warn("āš ļø package not qualified") - pkgsNotQualified++ - } else if res.SvnTagsCount == 0 { - resLogger.WithFields(baseFields).Info("āœ… package qualified, no svn tags") - pkgsFullSuccess++ - } else if res.TagsProcessedThisRun == 0 { - resLogger.WithFields(baseFields).Info("āœ… all tags already processed") - pkgsFullSuccess++ - } else if res.TagsSucceededThisRun > 0 && res.TagsFailedThisRun == 0 { - resLogger.WithFields(baseFields).Info("šŸŽ‰ all attempted tags migrated successfully") - pkgsFullSuccess++ - } else if res.TagsSucceededThisRun > 0 && res.TagsFailedThisRun > 0 { - resLogger.WithFields(baseFields).Warn("āš ļø partial success") - pkgsPartialSuccess++ - problematicPackages = append(problematicPackages, - fmt.Sprintf("%s (partial: %dāœ… %dāŒ)", res.PackageName, res.TagsSucceededThisRun, res.TagsFailedThisRun)) - } else if res.TagsFailedThisRun > 0 && res.TagsSucceededThisRun == 0 { - resLogger.WithFields(baseFields).Error("āŒ all attempted tags failed") - pkgsWithTagFails++ - problematicPackages = append(problematicPackages, - fmt.Sprintf("%s (all %d tags failed)", res.PackageName, res.TagsProcessedThisRun)) - } else { - resLogger.WithFields(baseFields).Error("ā“ unhandled status") - pkgsWithTagFails++ - problematicPackages = append(problematicPackages, - fmt.Sprintf("%s (unhandled status)", res.PackageName)) - } - } - - // Final Summary - summaryFields := logrus.Fields{ - "total_duration": fmt.Sprintf("%.2fs", time.Since(overallStart).Seconds()), - "packages_found": len(validPackageNames), - "packages_processed": totalPackagesProcessed, - "packages_success": pkgsFullSuccess, - "packages_partial": pkgsPartialSuccess, - "packages_tag_fails": pkgsWithTagFails, - "packages_not_qualified": pkgsNotQualified, - "packages_critical_error": pkgsCriticalError, - "tags_scanned": totalSvnTagsScanned, - "tags_attempted": totalTagsAttemptedRun, - "tags_succeeded": totalTagsSucceededRun, - "tags_failed": totalTagsFailedRun, - } - - if config.DryRun { - mainLogger.WithFields(logrus.Fields{ - "duration": fmt.Sprintf("%.2fs", time.Since(overallStart).Seconds()), - "packages_found": len(validPackageNames), - "packages_processed": totalPackagesProcessed, - "packages_not_qualified": pkgsNotQualified, - }).Info("šŸ” dry run summary") - } else { - mainLogger.WithFields(summaryFields).Info("šŸ“Š migration summary") - } - - fmt.Println("\n" + strings.Repeat("=", 80)) - fmt.Println("šŸ“„ detailed logs: stdout (text) + log file (json)") - fmt.Println("šŸ“‹ manifest files: [package-dir]/manifest.json") - fmt.Println(strings.Repeat("=", 80)) - - errorCount := pkgsPartialSuccess + pkgsWithTagFails + pkgsCriticalError - if errorCount > 0 { - mainLogger.WithField("error_count", errorCount).Error("āŒ migration completed with issues") - - if len(problematicPackages) > 0 { - fmt.Println("\n🚨 packages requiring attention:") - for _, detail := range problematicPackages { - fmt.Printf(" • %s\n", detail) - } - } - - return fmt.Errorf("%d package(s) had issues requiring attention", errorCount) - } - - if config.DryRun { - mainLogger.Info("šŸ” dry run completed - no changes made") - } else { - mainLogger.Info("šŸŽ‰ migration completed successfully") - } - - return nil -} - -func validateConfig(config *Config) error { - absPath, err := filepath.Abs(config.RepoPath) - if err != nil { - return fmt.Errorf("invalid repository path: %w", err) - } - config.RepoPath = absPath - - if info, err := os.Stat(config.RepoPath); err != nil || !info.IsDir() { - return fmt.Errorf("repository path is not a valid directory: %s", config.RepoPath) - } - - if config.RepoType != "plugin" && config.RepoType != "theme" { - return fmt.Errorf("repository type must be 'plugin' or 'theme'") - } - - if config.WpmPath == "" { - foundPath, err := exec.LookPath("wpm") - if err != nil { - return errors.New("wpm command not found in PATH and --wpm-path not specified") - } - config.WpmPath = foundPath - } else { - absWpmPath, err := filepath.Abs(config.WpmPath) - if err != nil { - return fmt.Errorf("could not get absolute path for wpm binary %s: %w", config.WpmPath, err) - } - if _, err := os.Stat(absWpmPath); err != nil { - return fmt.Errorf("wpm binary not found: %s", absWpmPath) - } - config.WpmPath = absWpmPath - } - - if config.MaxWorkers <= 0 { - config.MaxWorkers = defaultMaxWorkers - } - - if config.TagTimeout <= 0 { - config.TagTimeout = defaultTagTimeout - } - - if config.LogPath == "" { - config.LogPath = globalLogFileName - log.Infof("šŸ“ no log path specified, using default: %s", config.LogPath) - } - - if config.LogPath != "" { - absLogPath, err := filepath.Abs(config.LogPath) - if err != nil { - return fmt.Errorf("invalid log path: %w", err) - } - config.LogPath = absLogPath - - info, err := os.Stat(config.LogPath) - if err == nil && info.IsDir() { - config.LogPath = filepath.Join(config.LogPath, globalLogFileName) - } else if os.IsNotExist(err) { - parentDir := filepath.Dir(config.LogPath) - if _, err := os.Stat(parentDir); os.IsNotExist(err) { - if mkErr := os.MkdirAll(parentDir, 0755); mkErr != nil { - return fmt.Errorf("cannot create log directory %s: %w", parentDir, mkErr) - } - } - } - } - - if config.DownloadManifestPath == "" { - config.DownloadManifestPath = defaultDownloadManifestFile - log.Infof("šŸ“„ no download manifest path specified, using default: %s", config.DownloadManifestPath) - } - - if config.DownloadManifestPath != "" { - absDownloadManifestPath, err := filepath.Abs(config.DownloadManifestPath) - if err != nil { - return fmt.Errorf("invalid download manifest path: %w", err) - } - config.DownloadManifestPath = absDownloadManifestPath - - // Check if file exists and is readable (optional, so don't error if not found) - if _, err := os.Stat(config.DownloadManifestPath); err != nil && !os.IsNotExist(err) { - return fmt.Errorf("cannot access download manifest path %s: %w", config.DownloadManifestPath, err) - } - } - - return nil -} - -func init() { - rootCmd.Flags().StringP("type", "t", "", "repository type: 'plugin' or 'theme' (required)") - rootCmd.Flags().IntP("workers", "w", defaultMaxWorkers, "number of parallel workers") - rootCmd.Flags().Duration("tag-timeout", defaultTagTimeout, "timeout per tag migration") - rootCmd.Flags().Bool("dry-run", false, "simulate migration without making changes") - rootCmd.Flags().BoolP("verbose", "v", false, "enable verbose (debug) logging") - rootCmd.Flags().String("wpm-path", "", "path to wpm binary (if not in PATH)") - rootCmd.Flags().String("log-path", "", fmt.Sprintf("path to json log file (default: ./%s)", globalLogFileName)) - rootCmd.Flags().String("download-manifest-path", "", fmt.Sprintf("path to download manifest file to read versions from (default: ./%s)", defaultDownloadManifestFile)) - - if err := rootCmd.MarkFlagRequired("type"); err != nil { - _, _ = fmt.Fprintf(os.Stderr, "failed to mark 'type' flag as required: %v\n", err) - } -} - -func main() { - logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true, FullTimestamp: true}) - logrus.SetOutput(os.Stderr) - - if err := rootCmd.Execute(); err != nil { - _, _ = fmt.Fprintf(os.Stderr, "failed to run command: %v\n", err) - os.Exit(1) - } -}