diff --git a/cmd/devenv/root.go b/cmd/devenv/root.go index 75f55da..71f342f 100644 --- a/cmd/devenv/root.go +++ b/cmd/devenv/root.go @@ -26,5 +26,4 @@ func init() { // Add subcommands to root rootCmd.AddCommand(generateCmd) rootCmd.AddCommand(versionCmd) - rootCmd.AddCommand(validateCmd) } diff --git a/cmd/devenv/validate.go b/cmd/devenv/validate.go deleted file mode 100644 index a821867..0000000 --- a/cmd/devenv/validate.go +++ /dev/null @@ -1,163 +0,0 @@ -package main - -import ( - "fmt" - "os" - - "github.com/nauticalab/devenv-engine/internal/validation" - "github.com/spf13/cobra" -) - -var ( - // Validate command flags - validateConfigDir string -) - -// validateCmd represents the validate command -var validateCmd = &cobra.Command{ - Use: "validate [developer-name]", - Short: "Validate developer environment configurations", - Long: `Validate developer environment configurations for common issues. - -This command checks for: -- SSH port conflicts between developers -- SSH ports outside valid NodePort range (30000-32767) -- Missing or invalid configuration files - -Examples: - devenv validate # Validate all configurations - devenv validate eywalker # Validate specific developer (includes conflict checking) - devenv validate --config-dir ./configs`, - Args: cobra.MaximumNArgs(1), // At most 1 argument (developer name) - Run: func(cmd *cobra.Command, args []string) { - validator := validation.NewPortValidator(validateConfigDir) - - if len(args) == 0 { - // Validate all developers - validateAll(validator) - } else { - // Validate single developer (with conflict checking) - developerName := args[0] - validateSingle(validator, developerName) - } - }, -} - -func init() { - // Validate command specific flags - validateCmd.Flags().StringVar(&validateConfigDir, "config-dir", "./developers", "Directory containing developer configuration files") -} - -// validateAll validates all developer configurations -func validateAll(validator *validation.PortValidator) { - fmt.Println("šŸ” Validating all developer configurations...") - - result, err := validator.ValidateAll() - if err != nil { - fmt.Fprintf(os.Stderr, "āŒ Validation failed: %v\n", err) - os.Exit(1) - } - - printValidationResult(result, "") - - if !result.IsValid { - os.Exit(1) - } -} - -// validateSingle validates a single developer configuration (including conflicts) -func validateSingle(validator *validation.PortValidator, developerName string) { - fmt.Printf("šŸ” Validating configuration for developer: %s\n", developerName) - - result, err := validator.ValidateSingle(developerName) - if err != nil { - fmt.Fprintf(os.Stderr, "āŒ Validation failed: %v\n", err) - os.Exit(1) - } - - printValidationResult(result, developerName) - - if !result.IsValid { - os.Exit(1) - } -} - -// printValidationResult prints the validation results in a user-friendly format -func printValidationResult(result *validation.ValidationResult, targetUser string) { - // Print warnings first - for _, warning := range result.Warnings { - fmt.Printf("āš ļø Warning: %s\n", warning.Message) - if warning.FilePath != "" && verbose { - fmt.Printf(" File: %s\n", warning.FilePath) - } - } - - // Print errors with context-specific messaging - for _, err := range result.Errors { - switch err.Type { - case "conflict": - if targetUser != "" { - // Single user validation - show from their perspective - fmt.Printf("āŒ Port Conflict: %s\n", err.Message) - } else { - // All users validation - show general conflict - fmt.Printf("āŒ Port Conflict: Port %d is assigned to multiple developers: %v\n", err.Port, err.Users) - } - if verbose { - fmt.Printf(" Affected users: %v\n", err.Users) - } - case "out_of_range": - fmt.Printf("āŒ Invalid Port Range: %s\n", err.Message) - if verbose && err.FilePath != "" { - fmt.Printf(" File: %s\n", err.FilePath) - } - case "invalid": - fmt.Printf("āŒ Configuration Error: %s\n", err.Message) - if verbose && err.FilePath != "" { - fmt.Printf(" File: %s\n", err.FilePath) - } - default: - fmt.Printf("āŒ Error: %s\n", err.Message) - } - } - - // Print summary - if len(result.Errors) == 0 && len(result.Warnings) == 0 { - if targetUser != "" { - fmt.Printf("āœ… Configuration for %s is valid!\n", targetUser) - } else { - fmt.Println("āœ… All configurations are valid!") - } - } else if result.IsValid { - if targetUser != "" { - fmt.Printf("āœ… Configuration for %s is valid (%d warnings)\n", targetUser, len(result.Warnings)) - } else { - fmt.Printf("āœ… All configurations are valid (%d warnings)\n", len(result.Warnings)) - } - } else { - fmt.Printf("āŒ Validation failed with %d errors and %d warnings\n", len(result.Errors), len(result.Warnings)) - - // Provide helpful suggestions - if len(result.Errors) > 0 { - fmt.Println("\nšŸ’” Suggestions:") - hasConflicts := false - hasRangeErrors := false - - for _, err := range result.Errors { - if err.Type == "conflict" && !hasConflicts { - if targetUser != "" { - fmt.Printf(" • Assign a unique SSH port to %s\n", targetUser) - } else { - fmt.Println(" • Assign unique SSH ports to each developer") - } - fmt.Printf(" • Valid port range: %d-%d\n", validation.NodePortMin, validation.NodePortMax) - hasConflicts = true - } - if err.Type == "out_of_range" && !hasRangeErrors { - fmt.Printf(" • Use ports between %d and %d (Kubernetes NodePort range)\n", validation.NodePortMin, validation.NodePortMax) - hasRangeErrors = true - } - } - } - } -} diff --git a/internal/validation/ports.go b/internal/validation/ports.go deleted file mode 100644 index 786d8c5..0000000 --- a/internal/validation/ports.go +++ /dev/null @@ -1,204 +0,0 @@ -package validation - -import ( - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/nauticalab/devenv-engine/internal/config" -) - -const ( - // Kubernetes NodePort valid range - NodePortMin = 30000 - NodePortMax = 32767 -) - -// PortValidator handles SSH port validation across developer configurations -type PortValidator struct { - configDir string -} - -// ValidationResult contains all validation results -type ValidationResult struct { - Errors []ValidationError - Warnings []ValidationWarning - IsValid bool -} - -// ValidationError represents a validation failure -type ValidationError struct { - Type string // "conflict", "out_of_range", "invalid" - Port int - Users []string - Message string - FilePath string -} - -// ValidationWarning represents a non-fatal validation issue -type ValidationWarning struct { - Type string - User string - Message string - FilePath string -} - -// NewPortValidator creates a new port validator -func NewPortValidator(configDir string) *PortValidator { - return &PortValidator{configDir: configDir} -} - -// ValidateAll scans all developer configs and validates SSH ports -func (pv *PortValidator) ValidateAll() (*ValidationResult, error) { - result := &ValidationResult{ - Errors: []ValidationError{}, - Warnings: []ValidationWarning{}, - IsValid: true, - } - - // Find all developer configuration directories - developers, err := pv.findDeveloperDirs() - if err != nil { - return nil, fmt.Errorf("failed to scan developer directories in %s: %w", pv.configDir, err) - } - if len(developers) == 0 { - result.Warnings = append(result.Warnings, ValidationWarning{ - Type: "no_configs", - Message: fmt.Sprintf("No developer configurations found in %s", pv.configDir), - }) - return result, nil - } - - // Load all configurations and collect port assignments - portAssignments := make(map[int][]string) // port -> []users - for _, developerName := range developers { - port, validationError, validationWarning := pv.validateSingleDeveloper(developerName) - if validationError != nil { - result.Errors = append(result.Errors, *validationError) - result.IsValid = false - continue - } - if validationWarning != nil { - result.Warnings = append(result.Warnings, *validationWarning) - continue - } - - // Track port assignments for conflict detection - portAssignments[port] = append(portAssignments[port], developerName) - } - - // Check for port conflicts - for port, users := range portAssignments { - if len(users) > 1 { - result.Errors = append(result.Errors, ValidationError{ - Type: "conflict", - Port: port, - Users: users, - Message: fmt.Sprintf("Port %d is assigned to multiple developers: %s", port, strings.Join(users, ", ")), - }) - result.IsValid = false - } - } - - return result, nil -} - -func (pv *PortValidator) validateSingleDeveloper(developerName string) (int, *ValidationError, *ValidationWarning) { - cfg, err := config.LoadDeveloperConfig(pv.configDir, developerName) - if err != nil { - return 0, &ValidationError{ - Type: "invalid", - Users: []string{developerName}, - Message: fmt.Sprintf("Failed to load config: %v", err), - FilePath: filepath.Join(pv.configDir, developerName, "devenv-config.yaml"), - }, nil - } - - // Check if SSH port is configured - if cfg.SSHPort == 0 { - return 0, nil, &ValidationWarning{ - Type: "no_ssh_port", - User: developerName, - Message: fmt.Sprintf("No SSH port configured for developer %s", developerName), - FilePath: filepath.Join(pv.configDir, developerName, "devenv-config.yaml"), - } - } - - // Validate port range - if cfg.SSHPort < NodePortMin || cfg.SSHPort > NodePortMax { - return cfg.SSHPort, &ValidationError{ - Type: "out_of_range", - Port: cfg.SSHPort, - Users: []string{developerName}, - Message: fmt.Sprintf("SSH port %d for developer %s is out of valid range (%d-%d)", cfg.SSHPort, developerName, NodePortMin, NodePortMax), - FilePath: filepath.Join(pv.configDir, developerName, "devenv-config.yaml"), - }, nil - } - - return cfg.SSHPort, nil, nil -} - -// ValidateSingle validates a single developer by running full validation and filtering results -func (pv *PortValidator) ValidateSingle(developerName string) (*ValidationResult, error) { - // Run full validation to catch all conflicts - fullResult, err := pv.ValidateAll() - if err != nil { - return nil, err - } - - // Filter results to only those relevant to the target developer - result := &ValidationResult{ - Errors: []ValidationError{}, - Warnings: []ValidationWarning{}, - IsValid: true, - } - - // Filter errors - include if target user is involved - for _, err := range fullResult.Errors { - if pv.errorInvolvesUser(err, developerName) { - result.Errors = append(result.Errors, err) - result.IsValid = false - } - } - - // Filter warnings - include if it's about the target user - for _, warning := range fullResult.Warnings { - if warning.User == developerName { - result.Warnings = append(result.Warnings, warning) - } - } - - return result, nil -} - -// errorInvolvesUser checks if a validation error involves the specified user -func (pv *PortValidator) errorInvolvesUser(err ValidationError, targetUser string) bool { - for _, user := range err.Users { - if user == targetUser { - return true - } - } - return false -} - -func (pv *PortValidator) findDeveloperDirs() ([]string, error) { - var developers []string - - entries, err := os.ReadDir(pv.configDir) - if err != nil { - return nil, fmt.Errorf("failed to read config directory %s: %w", pv.configDir, err) - } - - for _, entry := range entries { - if entry.IsDir() { - // Check if devenv-config.yaml exists in the directory - configPath := filepath.Join(pv.configDir, entry.Name(), "devenv-config.yaml") - if _, err := os.Stat(configPath); err == nil { - developers = append(developers, entry.Name()) - } - } - } - - return developers, nil -}