Просмотр исходного кода

style: apply ruff formatting to entire codebase

xcad 4 месяцев назад
Родитель
Сommit
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,
             "title": data.get("title", key.replace("_", " ").title()),
         }
-        
+
         # Only add optional fields if explicitly provided in the source data
         if "description" in data:
             section_init_data["description"] = data["description"]
@@ -84,7 +84,7 @@ class VariableCollection:
             section_init_data["required"] = True
         if "needs" in data:
             section_init_data["needs"] = data["needs"]
-            
+
         return VariableSection(section_init_data)
 
     def _initialize_variables(
@@ -164,7 +164,7 @@ class VariableCollection:
         if toggle_var.type != "bool":
             raise VariableValidationError(
                 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
@@ -403,35 +403,35 @@ class VariableCollection:
 
     def reset_disabled_bool_variables(self) -> list[str]:
         """Reset bool variables with unsatisfied dependencies to False.
-        
+
         This ensures that disabled bool variables don't accidentally remain True
         and cause confusion in templates or configuration.
-        
+
         Note: CLI-provided variables are NOT reset here - they are validated
         later in validate_all() to provide better error messages.
-        
+
         Returns:
             List of variable names that were reset
         """
         reset_vars = []
-        
+
         # Pre-compute satisfaction states to avoid repeated lookups
         section_states = {
             key: (self.is_section_satisfied(key), section.is_enabled())
             for key, section in self._sections.items()
         }
-        
+
         for section_key, section in self._sections.items():
             section_satisfied, is_enabled = section_states[section_key]
-            
+
             for var_name, variable in section.variables.items():
                 # Only process bool variables
                 if variable.type != "bool":
                     continue
-                    
+
                 # Check if variable's own dependencies are satisfied
                 var_satisfied = self.is_variable_satisfied(var_name)
-                
+
                 # 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:
                     # 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
                         if variable.origin == "cli":
                             continue
-                        
+
                         # Store original value if not already stored (for display purposes)
                         if not hasattr(variable, "_original_disabled"):
                             variable._original_disabled = variable.value
-                        
+
                         variable.value = False
                         reset_vars.append(var_name)
                         logger.debug(
@@ -451,7 +451,7 @@ class VariableCollection:
                             f"(section satisfied: {section_satisfied}, enabled: {is_enabled}, "
                             f"var satisfied: {var_satisfied})"
                         )
-        
+
         return reset_vars
 
     def sort_sections(self) -> None:
@@ -737,12 +737,16 @@ class VariableCollection:
         for section_key, section in self._sections.items():
             section_satisfied = self.is_section_satisfied(section_key)
             is_enabled = section.is_enabled()
-            
+
             for var_name, variable in section.variables.items():
                 # 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)
-                    
+
                     if not section_satisfied or not is_enabled or not var_satisfied:
                         # Build error message with unmet needs (use set to avoid duplicates)
                         unmet_needs = set()
@@ -754,8 +758,12 @@ class VariableCollection:
                             for need in variable.needs:
                                 if not self._is_need_satisfied(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(
                             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)
                 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)
                 if "value" in other_var._explicit_fields:

+ 12 - 13
cli/core/module.py

@@ -149,7 +149,7 @@ class Module(ABC):
     ) -> list[Template]:
         """List all templates."""
         logger.debug(f"Listing templates for module '{self.name}'")
-        
+
         # Load all templates using centralized helper
         filtered_templates = self._load_all_templates()
 
@@ -185,7 +185,7 @@ class Module(ABC):
         logger.debug(
             f"Searching templates for module '{self.name}' with query='{query}'"
         )
-        
+
         # Load templates with search filter using centralized helper
         filtered_templates = self._load_all_templates(
             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)
             template.variables.sort_sections()
-            
+
             # Reset disabled bool variables to False to prevent confusion
             reset_vars = template.variables.reset_disabled_bool_variables()
             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)
 
@@ -308,16 +310,12 @@ class Module(ABC):
                 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())}")
 
         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.
 
         Args:
@@ -745,11 +743,13 @@ class Module(ABC):
         # Re-sort sections after all overrides (toggle values may have changed)
         if template.variables:
             template.variables.sort_sections()
-            
+
             # Reset disabled bool variables to False to prevent confusion
             reset_vars = template.variables.reset_disabled_bool_variables()
             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:
             self.display.display_template(template, id)
@@ -1378,4 +1378,3 @@ class Module(ABC):
             raise FileNotFoundError(
                 f"Template '{id}' could not be loaded: {exc}"
             ) from exc
-

+ 6 - 2
cli/core/prompt.py

@@ -38,7 +38,9 @@ class PromptHandler:
         )  # Track which variables we've already prompted for
 
         # 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:
                 continue
 
@@ -60,7 +62,9 @@ class PromptHandler:
                     # Prompt for toggle variable using standard variable prompting logic
                     # This ensures consistent handling of description, extra text, validation hints, etc.
                     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:
                         collected[toggle_var.name] = new_value

+ 6 - 5
cli/core/template.py

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

+ 4 - 2
cli/core/variable.py

@@ -92,7 +92,9 @@ class Variable:
             try:
                 self.value = self.convert(self.value)
             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:
         """Validate and convert a raw value based on the variable type.
@@ -413,7 +415,7 @@ class Variable:
 
     def get_parent(self) -> Optional["VariableSection"]:
         """Get the parent VariableSection that contains this variable.
-        
+
         Returns:
             The parent VariableSection if set, None otherwise
         """

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

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