Преглед изворни кода

style: apply ruff formatting to entire codebase

xcad пре 4 месеци
родитељ
комит
0e07ee0ea7
6 измењених фајлова са 57 додато и 46 уклоњено
  1. 28 22
      cli/core/collection.py
  2. 12 13
      cli/core/module.py
  3. 6 2
      cli/core/prompt.py
  4. 6 5
      cli/core/template.py
  5. 4 2
      cli/core/variable.py
  6. 1 2
      cli/modules/compose/spec_v1_1.py

+ 28 - 22
cli/core/collection.py

@@ -72,7 +72,7 @@ class VariableCollection:
             "key": key,
             "key": key,
             "title": data.get("title", key.replace("_", " ").title()),
             "title": data.get("title", key.replace("_", " ").title()),
         }
         }
-        
+
         # Only add optional fields if explicitly provided in the source data
         # Only add optional fields if explicitly provided in the source data
         if "description" in data:
         if "description" in data:
             section_init_data["description"] = data["description"]
             section_init_data["description"] = data["description"]
@@ -84,7 +84,7 @@ class VariableCollection:
             section_init_data["required"] = True
             section_init_data["required"] = True
         if "needs" in data:
         if "needs" in data:
             section_init_data["needs"] = data["needs"]
             section_init_data["needs"] = data["needs"]
-            
+
         return VariableSection(section_init_data)
         return VariableSection(section_init_data)
 
 
     def _initialize_variables(
     def _initialize_variables(
@@ -164,7 +164,7 @@ class VariableCollection:
         if toggle_var.type != "bool":
         if toggle_var.type != "bool":
             raise VariableValidationError(
             raise VariableValidationError(
                 section.toggle,
                 section.toggle,
-                f"Section '{section.key}' toggle variable must be type 'bool', but is type '{toggle_var.type}'"
+                f"Section '{section.key}' toggle variable must be type 'bool', but is type '{toggle_var.type}'",
             )
             )
 
 
     @staticmethod
     @staticmethod
@@ -403,35 +403,35 @@ class VariableCollection:
 
 
     def reset_disabled_bool_variables(self) -> list[str]:
     def reset_disabled_bool_variables(self) -> list[str]:
         """Reset bool variables with unsatisfied dependencies to False.
         """Reset bool variables with unsatisfied dependencies to False.
-        
+
         This ensures that disabled bool variables don't accidentally remain True
         This ensures that disabled bool variables don't accidentally remain True
         and cause confusion in templates or configuration.
         and cause confusion in templates or configuration.
-        
+
         Note: CLI-provided variables are NOT reset here - they are validated
         Note: CLI-provided variables are NOT reset here - they are validated
         later in validate_all() to provide better error messages.
         later in validate_all() to provide better error messages.
-        
+
         Returns:
         Returns:
             List of variable names that were reset
             List of variable names that were reset
         """
         """
         reset_vars = []
         reset_vars = []
-        
+
         # Pre-compute satisfaction states to avoid repeated lookups
         # Pre-compute satisfaction states to avoid repeated lookups
         section_states = {
         section_states = {
             key: (self.is_section_satisfied(key), section.is_enabled())
             key: (self.is_section_satisfied(key), section.is_enabled())
             for key, section in self._sections.items()
             for key, section in self._sections.items()
         }
         }
-        
+
         for section_key, section in self._sections.items():
         for section_key, section in self._sections.items():
             section_satisfied, is_enabled = section_states[section_key]
             section_satisfied, is_enabled = section_states[section_key]
-            
+
             for var_name, variable in section.variables.items():
             for var_name, variable in section.variables.items():
                 # Only process bool variables
                 # Only process bool variables
                 if variable.type != "bool":
                 if variable.type != "bool":
                     continue
                     continue
-                    
+
                 # Check if variable's own dependencies are satisfied
                 # Check if variable's own dependencies are satisfied
                 var_satisfied = self.is_variable_satisfied(var_name)
                 var_satisfied = self.is_variable_satisfied(var_name)
-                
+
                 # If section is disabled OR variable dependencies aren't met, reset to False
                 # If section is disabled OR variable dependencies aren't met, reset to False
                 if not section_satisfied or not is_enabled or not var_satisfied:
                 if not section_satisfied or not is_enabled or not var_satisfied:
                     # Only reset if current value is not already False
                     # Only reset if current value is not already False
@@ -439,11 +439,11 @@ class VariableCollection:
                         # Don't reset CLI-provided variables - they'll be validated later
                         # Don't reset CLI-provided variables - they'll be validated later
                         if variable.origin == "cli":
                         if variable.origin == "cli":
                             continue
                             continue
-                        
+
                         # Store original value if not already stored (for display purposes)
                         # Store original value if not already stored (for display purposes)
                         if not hasattr(variable, "_original_disabled"):
                         if not hasattr(variable, "_original_disabled"):
                             variable._original_disabled = variable.value
                             variable._original_disabled = variable.value
-                        
+
                         variable.value = False
                         variable.value = False
                         reset_vars.append(var_name)
                         reset_vars.append(var_name)
                         logger.debug(
                         logger.debug(
@@ -451,7 +451,7 @@ class VariableCollection:
                             f"(section satisfied: {section_satisfied}, enabled: {is_enabled}, "
                             f"(section satisfied: {section_satisfied}, enabled: {is_enabled}, "
                             f"var satisfied: {var_satisfied})"
                             f"var satisfied: {var_satisfied})"
                         )
                         )
-        
+
         return reset_vars
         return reset_vars
 
 
     def sort_sections(self) -> None:
     def sort_sections(self) -> None:
@@ -737,12 +737,16 @@ class VariableCollection:
         for section_key, section in self._sections.items():
         for section_key, section in self._sections.items():
             section_satisfied = self.is_section_satisfied(section_key)
             section_satisfied = self.is_section_satisfied(section_key)
             is_enabled = section.is_enabled()
             is_enabled = section.is_enabled()
-            
+
             for var_name, variable in section.variables.items():
             for var_name, variable in section.variables.items():
                 # Check CLI-provided bool variables with unsatisfied dependencies
                 # Check CLI-provided bool variables with unsatisfied dependencies
-                if variable.type == "bool" and variable.origin == "cli" and variable.value is not False:
+                if (
+                    variable.type == "bool"
+                    and variable.origin == "cli"
+                    and variable.value is not False
+                ):
                     var_satisfied = self.is_variable_satisfied(var_name)
                     var_satisfied = self.is_variable_satisfied(var_name)
-                    
+
                     if not section_satisfied or not is_enabled or not var_satisfied:
                     if not section_satisfied or not is_enabled or not var_satisfied:
                         # Build error message with unmet needs (use set to avoid duplicates)
                         # Build error message with unmet needs (use set to avoid duplicates)
                         unmet_needs = set()
                         unmet_needs = set()
@@ -754,8 +758,12 @@ class VariableCollection:
                             for need in variable.needs:
                             for need in variable.needs:
                                 if not self._is_need_satisfied(need):
                                 if not self._is_need_satisfied(need):
                                     unmet_needs.add(need)
                                     unmet_needs.add(need)
-                        
-                        needs_str = ", ".join(sorted(unmet_needs)) if unmet_needs else "dependencies not satisfied"
+
+                        needs_str = (
+                            ", ".join(sorted(unmet_needs))
+                            if unmet_needs
+                            else "dependencies not satisfied"
+                        )
                         errors.append(
                         errors.append(
                             f"{section.key}.{var_name} (set via CLI to {variable.value} but requires: {needs_str})"
                             f"{section.key}.{var_name} (set via CLI to {variable.value} but requires: {needs_str})"
                         )
                         )
@@ -939,9 +947,7 @@ class VariableCollection:
 
 
                 # Special handling for needs (allow explicit null/empty to clear)
                 # Special handling for needs (allow explicit null/empty to clear)
                 if "needs" in other_var._explicit_fields:
                 if "needs" in other_var._explicit_fields:
-                    update["needs"] = (
-                        other_var.needs.copy() if other_var.needs else []
-                    )
+                    update["needs"] = other_var.needs.copy() if other_var.needs else []
 
 
                 # Special handling for value/default (allow explicit null to clear)
                 # Special handling for value/default (allow explicit null to clear)
                 if "value" in other_var._explicit_fields:
                 if "value" in other_var._explicit_fields:

+ 12 - 13
cli/core/module.py

@@ -149,7 +149,7 @@ class Module(ABC):
     ) -> list[Template]:
     ) -> list[Template]:
         """List all templates."""
         """List all templates."""
         logger.debug(f"Listing templates for module '{self.name}'")
         logger.debug(f"Listing templates for module '{self.name}'")
-        
+
         # Load all templates using centralized helper
         # Load all templates using centralized helper
         filtered_templates = self._load_all_templates()
         filtered_templates = self._load_all_templates()
 
 
@@ -185,7 +185,7 @@ class Module(ABC):
         logger.debug(
         logger.debug(
             f"Searching templates for module '{self.name}' with query='{query}'"
             f"Searching templates for module '{self.name}' with query='{query}'"
         )
         )
-        
+
         # Load templates with search filter using centralized helper
         # Load templates with search filter using centralized helper
         filtered_templates = self._load_all_templates(
         filtered_templates = self._load_all_templates(
             lambda t: query.lower() in t.id.lower()
             lambda t: query.lower() in t.id.lower()
@@ -246,11 +246,13 @@ class Module(ABC):
 
 
             # Re-sort sections after applying config (toggle values may have changed)
             # Re-sort sections after applying config (toggle values may have changed)
             template.variables.sort_sections()
             template.variables.sort_sections()
-            
+
             # Reset disabled bool variables to False to prevent confusion
             # Reset disabled bool variables to False to prevent confusion
             reset_vars = template.variables.reset_disabled_bool_variables()
             reset_vars = template.variables.reset_disabled_bool_variables()
             if reset_vars:
             if reset_vars:
-                logger.debug(f"Reset {len(reset_vars)} disabled bool variables to False")
+                logger.debug(
+                    f"Reset {len(reset_vars)} disabled bool variables to False"
+                )
 
 
         self.display.display_template(template, id)
         self.display.display_template(template, id)
 
 
@@ -308,16 +310,12 @@ class Module(ABC):
                 f"Variable file must contain a YAML dictionary, got {type(content).__name__}"
                 f"Variable file must contain a YAML dictionary, got {type(content).__name__}"
             )
             )
 
 
-        logger.info(
-            f"Loaded {len(content)} variables from file: {var_path.name}"
-        )
+        logger.info(f"Loaded {len(content)} variables from file: {var_path.name}")
         logger.debug(f"Variables from file: {', '.join(content.keys())}")
         logger.debug(f"Variables from file: {', '.join(content.keys())}")
 
 
         return content
         return content
 
 
-    def _apply_var_file(
-        self, template: Template, var_file_path: Optional[str]
-    ) -> None:
+    def _apply_var_file(self, template: Template, var_file_path: Optional[str]) -> None:
         """Apply variables from a YAML file to template.
         """Apply variables from a YAML file to template.
 
 
         Args:
         Args:
@@ -745,11 +743,13 @@ class Module(ABC):
         # Re-sort sections after all overrides (toggle values may have changed)
         # Re-sort sections after all overrides (toggle values may have changed)
         if template.variables:
         if template.variables:
             template.variables.sort_sections()
             template.variables.sort_sections()
-            
+
             # Reset disabled bool variables to False to prevent confusion
             # Reset disabled bool variables to False to prevent confusion
             reset_vars = template.variables.reset_disabled_bool_variables()
             reset_vars = template.variables.reset_disabled_bool_variables()
             if reset_vars:
             if reset_vars:
-                logger.debug(f"Reset {len(reset_vars)} disabled bool variables to False")
+                logger.debug(
+                    f"Reset {len(reset_vars)} disabled bool variables to False"
+                )
 
 
         if not quiet:
         if not quiet:
             self.display.display_template(template, id)
             self.display.display_template(template, id)
@@ -1378,4 +1378,3 @@ class Module(ABC):
             raise FileNotFoundError(
             raise FileNotFoundError(
                 f"Template '{id}' could not be loaded: {exc}"
                 f"Template '{id}' could not be loaded: {exc}"
             ) from exc
             ) from exc
-

+ 6 - 2
cli/core/prompt.py

@@ -38,7 +38,9 @@ class PromptHandler:
         )  # Track which variables we've already prompted for
         )  # Track which variables we've already prompted for
 
 
         # Process each section (only satisfied dependencies, include disabled for toggle handling)
         # Process each section (only satisfied dependencies, include disabled for toggle handling)
-        for section_key, section in variables.iter_active_sections(include_disabled=True):
+        for section_key, section in variables.iter_active_sections(
+            include_disabled=True
+        ):
             if not section.variables:
             if not section.variables:
                 continue
                 continue
 
 
@@ -60,7 +62,9 @@ class PromptHandler:
                     # Prompt for toggle variable using standard variable prompting logic
                     # Prompt for toggle variable using standard variable prompting logic
                     # This ensures consistent handling of description, extra text, validation hints, etc.
                     # This ensures consistent handling of description, extra text, validation hints, etc.
                     current_value = toggle_var.convert(toggle_var.value)
                     current_value = toggle_var.convert(toggle_var.value)
-                    new_value = self._prompt_variable(toggle_var, required=section.required)
+                    new_value = self._prompt_variable(
+                        toggle_var, required=section.required
+                    )
 
 
                     if new_value != current_value:
                     if new_value != current_value:
                         collected[toggle_var.name] = new_value
                         collected[toggle_var.name] = new_value

+ 6 - 5
cli/core/template.py

@@ -31,7 +31,7 @@ logger = logging.getLogger(__name__)
 
 
 class TemplateErrorHandler:
 class TemplateErrorHandler:
     """Handles parsing and formatting of template rendering errors.
     """Handles parsing and formatting of template rendering errors.
-    
+
     This class provides utilities for:
     This class provides utilities for:
     - Extracting error context from template files
     - Extracting error context from template files
     - Generating helpful suggestions based on Jinja2 errors
     - Generating helpful suggestions based on Jinja2 errors
@@ -447,10 +447,12 @@ class Template:
             import importlib
             import importlib
 
 
             module = importlib.import_module(f"cli.modules.{kind}")
             module = importlib.import_module(f"cli.modules.{kind}")
-            
+
             # Check if module has schema-specific specs (multi-schema support)
             # Check if module has schema-specific specs (multi-schema support)
             # Try SCHEMAS constant first (uppercase), then schemas attribute
             # Try SCHEMAS constant first (uppercase), then schemas attribute
-            schemas = getattr(module, "SCHEMAS", None) or getattr(module, "schemas", None)
+            schemas = getattr(module, "SCHEMAS", None) or getattr(
+                module, "schemas", None
+            )
             if schemas and schema_version in schemas:
             if schemas and schema_version in schemas:
                 spec = schemas[schema_version]
                 spec = schemas[schema_version]
                 logger.debug(
                 logger.debug(
@@ -462,7 +464,7 @@ class Template:
                 logger.debug(
                 logger.debug(
                     f"Loaded and cached module spec for kind '{kind}' (default/no schema mapping)"
                     f"Loaded and cached module spec for kind '{kind}' (default/no schema mapping)"
                 )
                 )
-            
+
             return spec
             return spec
         except Exception as e:
         except Exception as e:
             raise ValueError(
             raise ValueError(
@@ -563,7 +565,6 @@ class Template:
 
 
         return used_variables
         return used_variables
 
 
-
     def _filter_specs_to_used(
     def _filter_specs_to_used(
         self,
         self,
         used_variables: set,
         used_variables: set,

+ 4 - 2
cli/core/variable.py

@@ -92,7 +92,9 @@ class Variable:
             try:
             try:
                 self.value = self.convert(self.value)
                 self.value = self.convert(self.value)
             except ValueError as exc:
             except ValueError as exc:
-                raise VariableValidationError(self.name, f"Invalid default value: {exc}")
+                raise VariableValidationError(
+                    self.name, f"Invalid default value: {exc}"
+                )
 
 
     def convert(self, value: Any) -> Any:
     def convert(self, value: Any) -> Any:
         """Validate and convert a raw value based on the variable type.
         """Validate and convert a raw value based on the variable type.
@@ -413,7 +415,7 @@ class Variable:
 
 
     def get_parent(self) -> Optional["VariableSection"]:
     def get_parent(self) -> Optional["VariableSection"]:
         """Get the parent VariableSection that contains this variable.
         """Get the parent VariableSection that contains this variable.
-        
+
         Returns:
         Returns:
             The parent VariableSection if set, None otherwise
             The parent VariableSection if set, None otherwise
         """
         """

+ 1 - 2
cli/modules/compose/spec_v1_1.py

@@ -105,8 +105,7 @@ spec = OrderedDict(
             "title": "Ports",
             "title": "Ports",
             "toggle": "ports_enabled",
             "toggle": "ports_enabled",
             "needs": "network_mode=bridge",
             "needs": "network_mode=bridge",
-            "vars": {
-            },
+            "vars": {},
         },
         },
         "traefik": {
         "traefik": {
             "title": "Traefik",
             "title": "Traefik",