|
| 1 | +import json |
| 2 | +import os |
| 3 | +import yaml |
| 4 | + |
| 5 | +from structkit.commands import Command |
| 6 | +from structkit.completers import structures_completer |
| 7 | + |
| 8 | + |
| 9 | +class VarsCommand(Command): |
| 10 | + """Inspect variables declared by a structure definition.""" |
| 11 | + |
| 12 | + def __init__(self, parser): |
| 13 | + super().__init__(parser) |
| 14 | + parser.description = "Inspect variables declared by a structure definition" |
| 15 | + structure_arg = parser.add_argument('structure_definition', type=str, help='Structure definition name or path to a YAML file') |
| 16 | + structure_arg.completer = structures_completer |
| 17 | + parser.add_argument( |
| 18 | + '-s', |
| 19 | + '--structures-path', |
| 20 | + type=str, |
| 21 | + help='Path to structure definitions (env: STRUCTKIT_STRUCTURES_PATH)', |
| 22 | + default=os.getenv('STRUCTKIT_STRUCTURES_PATH', None) |
| 23 | + ) |
| 24 | + parser.add_argument('--json', action='store_true', help='Output variables as JSON') |
| 25 | + parser.set_defaults(func=self.execute) |
| 26 | + |
| 27 | + def execute(self, args): |
| 28 | + config = self._load_yaml_config(args.structure_definition, args.structures_path) |
| 29 | + if config is None: |
| 30 | + raise SystemExit(1) |
| 31 | + if not isinstance(config, dict): |
| 32 | + self.logger.error("❗ Invalid structure config: top-level YAML content must be a mapping") |
| 33 | + raise SystemExit(1) |
| 34 | + |
| 35 | + try: |
| 36 | + variables = self._normalize_variables(config.get('variables', [])) |
| 37 | + except ValueError as exc: |
| 38 | + self.logger.error(f"❗ Invalid variables config: {exc}") |
| 39 | + raise SystemExit(1) from exc |
| 40 | + |
| 41 | + if args.json: |
| 42 | + print(json.dumps(variables, indent=2)) |
| 43 | + else: |
| 44 | + self._print_text(args.structure_definition, variables) |
| 45 | + |
| 46 | + def _load_yaml_config(self, structure_definition, structures_path): |
| 47 | + if structure_definition.endswith(('.yaml', '.yml')) and not structure_definition.startswith("file://"): |
| 48 | + structure_definition = f"file://{structure_definition}" |
| 49 | + |
| 50 | + if structure_definition.startswith("file://") and structure_definition.endswith((".yaml", ".yml")): |
| 51 | + file_path = structure_definition[7:] |
| 52 | + else: |
| 53 | + this_file = os.path.dirname(os.path.realpath(__file__)) |
| 54 | + contribs_path = os.path.join(this_file, "..", "contribs") |
| 55 | + file_path = os.path.join(contribs_path, f"{structure_definition}.yaml") |
| 56 | + if structures_path: |
| 57 | + file_path = os.path.join(structures_path, f"{structure_definition}.yaml") |
| 58 | + if not os.path.exists(file_path): |
| 59 | + file_path = os.path.join(contribs_path, f"{structure_definition}.yaml") |
| 60 | + |
| 61 | + if not os.path.exists(file_path): |
| 62 | + self.logger.error(f"❗ File not found: {file_path}") |
| 63 | + return None |
| 64 | + |
| 65 | + try: |
| 66 | + with open(file_path, 'r') as f: |
| 67 | + return yaml.safe_load(f) or {} |
| 68 | + except yaml.YAMLError as exc: |
| 69 | + self.logger.error(f"❗ Invalid YAML in {file_path}: {exc}") |
| 70 | + return None |
| 71 | + except OSError as exc: |
| 72 | + self.logger.error(f"❗ Failed to read {file_path}: {exc}") |
| 73 | + return None |
| 74 | + |
| 75 | + def _normalize_variables(self, variables): |
| 76 | + if variables is None: |
| 77 | + return [] |
| 78 | + if not isinstance(variables, list): |
| 79 | + raise ValueError("the 'variables' key must be a list") |
| 80 | + |
| 81 | + normalized = [] |
| 82 | + for item in variables: |
| 83 | + if not isinstance(item, dict): |
| 84 | + raise ValueError("each variable entry must be a mapping") |
| 85 | + for name, content in item.items(): |
| 86 | + if not isinstance(name, str): |
| 87 | + raise ValueError("each variable name must be a string") |
| 88 | + if content is None: |
| 89 | + content = {} |
| 90 | + if not isinstance(content, dict): |
| 91 | + raise ValueError(f"the content of '{name}' must be a mapping") |
| 92 | + |
| 93 | + has_default = 'default' in content |
| 94 | + description = content.get('description', content.get('help', '')) |
| 95 | + normalized.append({ |
| 96 | + 'name': name, |
| 97 | + 'type': content.get('type', ''), |
| 98 | + 'default': content.get('default') if has_default else None, |
| 99 | + 'description': description if description is not None else '', |
| 100 | + 'required': bool(content.get('required', False)), |
| 101 | + }) |
| 102 | + return normalized |
| 103 | + |
| 104 | + def _print_text(self, structure_definition, variables): |
| 105 | + print(f"Variables for {structure_definition}") |
| 106 | + if not variables: |
| 107 | + print("No variables defined.") |
| 108 | + return |
| 109 | + |
| 110 | + rows = [[ |
| 111 | + variable['name'], |
| 112 | + variable['type'] or '-', |
| 113 | + self._format_default(variable['default']), |
| 114 | + 'required' if variable['required'] else 'optional', |
| 115 | + variable['description'] or '-', |
| 116 | + ] for variable in variables] |
| 117 | + headers = ['Name', 'Type', 'Default', 'Required', 'Description'] |
| 118 | + widths = [len(header) for header in headers] |
| 119 | + for row in rows: |
| 120 | + for index, value in enumerate(row): |
| 121 | + widths[index] = max(widths[index], len(value)) |
| 122 | + |
| 123 | + print(" " + " ".join(header.ljust(widths[index]) for index, header in enumerate(headers))) |
| 124 | + print(" " + " ".join("-" * width for width in widths)) |
| 125 | + for row in rows: |
| 126 | + print(" " + " ".join(value.ljust(widths[index]) for index, value in enumerate(row))) |
| 127 | + |
| 128 | + def _format_default(self, value): |
| 129 | + if value is None: |
| 130 | + return '-' |
| 131 | + if isinstance(value, bool): |
| 132 | + return str(value).lower() |
| 133 | + return str(value) |
0 commit comments