structkit 3.0.0__py3-none-any.whl → 3.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. structkit/commands/__init__.py +1 -0
  2. structkit/commands/completion.py +1 -0
  3. structkit/commands/explain.py +362 -0
  4. structkit/commands/generate.py +98 -36
  5. structkit/commands/generate_schema.py +1 -1
  6. structkit/commands/graph.py +302 -0
  7. structkit/commands/import.py +1 -3
  8. structkit/commands/info.py +8 -3
  9. structkit/commands/init.py +1 -0
  10. structkit/commands/lint.py +352 -0
  11. structkit/commands/list.py +13 -5
  12. structkit/commands/mcp.py +13 -13
  13. structkit/commands/search.py +86 -0
  14. structkit/commands/sources.py +88 -0
  15. structkit/commands/validate.py +54 -32
  16. structkit/commands/vars.py +133 -0
  17. structkit/completers.py +1 -0
  18. structkit/content_fetcher.py +1 -0
  19. structkit/contribs/ansible-playbook.yaml +4 -0
  20. structkit/contribs/chef-cookbook.yaml +4 -0
  21. structkit/contribs/ci-cd-pipelines.yaml +4 -0
  22. structkit/contribs/cloudformation-files.yaml +4 -0
  23. structkit/contribs/configs/chglog.yaml +4 -0
  24. structkit/contribs/configs/codeowners.yaml +3 -0
  25. structkit/contribs/configs/devcontainer.yaml +4 -0
  26. structkit/contribs/configs/editor-config.yaml +4 -0
  27. structkit/contribs/configs/eslint.yaml +4 -0
  28. structkit/contribs/configs/jshint.yaml +4 -0
  29. structkit/contribs/configs/kubectl.yaml +4 -0
  30. structkit/contribs/configs/prettier.yaml +4 -0
  31. structkit/contribs/docker-files.yaml +4 -0
  32. structkit/contribs/documentation-template.yaml +4 -0
  33. structkit/contribs/git-hooks.yaml +4 -0
  34. structkit/contribs/github/chatmodes/plan.yaml +4 -0
  35. structkit/contribs/github/instructions/generic.yaml +4 -0
  36. structkit/contribs/github/prompts/generic.yaml +4 -0
  37. structkit/contribs/github/prompts/react-form.yaml +4 -0
  38. structkit/contribs/github/prompts/security-api.yaml +4 -0
  39. structkit/contribs/github/prompts/struct.yaml +4 -0
  40. structkit/contribs/github/templates.yaml +4 -0
  41. structkit/contribs/github/workflows/codeql.yaml +4 -0
  42. structkit/contribs/github/workflows/execute-tf-workflow.yaml +5 -0
  43. structkit/contribs/github/workflows/labeler.yaml +5 -0
  44. structkit/contribs/github/workflows/pre-commit.yaml +4 -0
  45. structkit/contribs/github/workflows/release-drafter.yaml +9 -4
  46. structkit/contribs/github/workflows/run-struct.yaml +4 -0
  47. structkit/contribs/github/workflows/stale.yaml +4 -0
  48. structkit/contribs/helm-chart.yaml +4 -0
  49. structkit/contribs/kubernetes-manifests.yaml +5 -0
  50. structkit/contribs/project/custom-structures.yaml +5 -0
  51. structkit/contribs/project/generic.yaml +6 -0
  52. structkit/contribs/project/go.yaml +4 -0
  53. structkit/contribs/project/java.yaml +5 -0
  54. structkit/contribs/project/n8n.yaml +5 -0
  55. structkit/contribs/project/nodejs.yaml +4 -0
  56. structkit/contribs/project/python.yaml +5 -0
  57. structkit/contribs/project/ruby.yaml +5 -0
  58. structkit/contribs/project/rust.yaml +5 -0
  59. structkit/contribs/prompts/run-struct-trigger.yaml +5 -0
  60. structkit/contribs/terraform/apps/aws-accounts.yaml +5 -0
  61. structkit/contribs/terraform/apps/environments.yaml +5 -0
  62. structkit/contribs/terraform/apps/generic.yaml +5 -0
  63. structkit/contribs/terraform/apps/github-organization.yaml +4 -0
  64. structkit/contribs/terraform/apps/init.yaml +4 -0
  65. structkit/contribs/terraform/modules/generic.yaml +5 -0
  66. structkit/contribs/vagrant-files.yaml +4 -0
  67. structkit/file_item.py +14 -3
  68. structkit/filters.py +5 -0
  69. structkit/input_store.py +38 -9
  70. structkit/logging_config.py +1 -0
  71. structkit/main.py +15 -0
  72. structkit/mcp_server.py +404 -2
  73. structkit/model_wrapper.py +1 -0
  74. structkit/sources.py +371 -0
  75. structkit/struct_refs.py +140 -0
  76. structkit/template_renderer.py +36 -9
  77. structkit/utils.py +3 -0
  78. {structkit-3.0.0.dist-info → structkit-3.2.0.dist-info}/METADATA +81 -31
  79. structkit-3.2.0.dist-info/RECORD +85 -0
  80. {structkit-3.0.0.dist-info → structkit-3.2.0.dist-info}/WHEEL +1 -1
  81. structkit-3.0.0.dist-info/RECORD +0 -77
  82. {structkit-3.0.0.dist-info → structkit-3.2.0.dist-info}/entry_points.txt +0 -0
  83. {structkit-3.0.0.dist-info → structkit-3.2.0.dist-info}/licenses/LICENSE +0 -0
  84. {structkit-3.0.0.dist-info → structkit-3.2.0.dist-info}/top_level.txt +0 -0
@@ -1,6 +1,7 @@
1
1
  import logging
2
2
  from structkit.completers import log_level_completer
3
3
 
4
+
4
5
  # Base command class
5
6
  class Command:
6
7
  def __init__(self, parser):
@@ -3,6 +3,7 @@ import os
3
3
 
4
4
  SUPPORTED_SHELLS = ["bash", "zsh", "fish"]
5
5
 
6
+
6
7
  class CompletionCommand(Command):
7
8
  def __init__(self, parser):
8
9
  super().__init__(parser)
@@ -0,0 +1,362 @@
1
+ import json
2
+ import os
3
+ from typing import Any, Dict, List, Optional, Set, Tuple
4
+
5
+ import yaml
6
+
7
+ from structkit.commands import Command
8
+ from structkit.completers import file_strategy_completer, structures_completer
9
+ from structkit.template_renderer import TemplateRenderer
10
+
11
+
12
+ class ExplainCommand(Command):
13
+ """Explain how a structure definition resolves without creating anything."""
14
+
15
+ def __init__(self, parser):
16
+ super().__init__(parser)
17
+ parser.description = "Preview how a structure definition resolves without generating files"
18
+ structure_arg = parser.add_argument('structure_definition', type=str, help='Structure definition name or path to a YAML file')
19
+ structure_arg.completer = structures_completer
20
+ parser.add_argument('base_path', nargs='?', default='.', type=str, help='Base path used to resolve generated paths and conflicts (default: current directory)')
21
+ parser.add_argument(
22
+ '-s',
23
+ '--structures-path',
24
+ type=str,
25
+ help='Path to structure definitions (env: STRUCTKIT_STRUCTURES_PATH)',
26
+ default=os.getenv('STRUCTKIT_STRUCTURES_PATH', None)
27
+ )
28
+ parser.add_argument('-v', '--vars', type=str, help='Template variables in the format KEY1=value1,KEY2=value2')
29
+ parser.add_argument(
30
+ '-f',
31
+ '--file-strategy',
32
+ type=str,
33
+ choices=['overwrite', 'skip', 'append', 'rename', 'backup'],
34
+ default=os.getenv('STRUCTKIT_FILE_STRATEGY', 'overwrite'),
35
+ help='Strategy to report when generated files already exist (env: STRUCTKIT_FILE_STRATEGY)').completer = file_strategy_completer
36
+ parser.add_argument('--json', action='store_true', help='Output the explanation as JSON')
37
+ parser.set_defaults(func=self.execute)
38
+
39
+ def execute(self, args):
40
+ explanation = self.explain(
41
+ args.structure_definition,
42
+ args.base_path,
43
+ structures_path=args.structures_path,
44
+ vars_str=args.vars,
45
+ file_strategy=args.file_strategy,
46
+ )
47
+ if args.json:
48
+ print(json.dumps(explanation, indent=2))
49
+ else:
50
+ print(self.format_text(explanation))
51
+
52
+ def explain(
53
+ self,
54
+ structure_definition: str,
55
+ base_path: str = '.',
56
+ structures_path: Optional[str] = None,
57
+ vars_str: Optional[str] = None,
58
+ file_strategy: str = 'overwrite',
59
+ ) -> Dict[str, Any]:
60
+ provided_vars = self._parse_template_vars(vars_str)
61
+ context = {
62
+ 'structures_path': structures_path,
63
+ 'provided_vars': provided_vars,
64
+ 'input_store': '/tmp/structkit/input.json',
65
+ 'non_interactive': True,
66
+ 'file_strategy': file_strategy,
67
+ }
68
+ explanation = {
69
+ 'structure': structure_definition,
70
+ 'base_path': base_path,
71
+ 'file_strategy': file_strategy,
72
+ 'creates_files': False,
73
+ 'executes_hooks': False,
74
+ 'variables': [],
75
+ 'hooks': {'pre': [], 'post': []},
76
+ 'files': [],
77
+ 'folders': [],
78
+ 'nested_structures': [],
79
+ 'remote_files': [],
80
+ 'warnings': [],
81
+ }
82
+ self._collect(structure_definition, base_path, context, explanation, set(), path=[structure_definition])
83
+ return explanation
84
+
85
+ def format_text(self, explanation: Dict[str, Any]) -> str:
86
+ lines = [
87
+ f"Structure explanation: {explanation['structure']}",
88
+ f"Base path: {explanation['base_path']}",
89
+ f"File strategy: {explanation['file_strategy']}",
90
+ "Safety: no files or folders will be created, and hooks will not be executed.",
91
+ "",
92
+ ]
93
+
94
+ lines.append("Variables:")
95
+ if explanation['variables']:
96
+ for variable in explanation['variables']:
97
+ value = variable.get('resolved_value')
98
+ value_text = '<unresolved>' if value is None else str(value)
99
+ default = variable.get('default')
100
+ default_text = '' if default is None else f" default={default}"
101
+ lines.append(f" - {variable['name']}: value={value_text}{default_text} source={variable.get('source', 'unknown')}")
102
+ else:
103
+ lines.append(" - none")
104
+
105
+ lines.append("")
106
+ lines.append("Hooks (not executed):")
107
+ hooks = explanation['hooks']
108
+ if hooks['pre'] or hooks['post']:
109
+ for hook in hooks['pre']:
110
+ lines.append(f" - pre: {hook['command']} ({hook['structure']})")
111
+ for hook in hooks['post']:
112
+ lines.append(f" - post: {hook['command']} ({hook['structure']})")
113
+ else:
114
+ lines.append(" - none")
115
+
116
+ lines.append("")
117
+ lines.append("Folders:")
118
+ if explanation['folders']:
119
+ for folder in explanation['folders']:
120
+ lines.append(f" - {folder['path']}")
121
+ else:
122
+ lines.append(" - none")
123
+
124
+ lines.append("")
125
+ lines.append("Files:")
126
+ if explanation['files']:
127
+ for file_info in explanation['files']:
128
+ remote = f" remote={file_info['remote']}" if file_info.get('remote') else ''
129
+ lines.append(f" - {file_info['path']} action={file_info['conflict_action']}{remote}")
130
+ else:
131
+ lines.append(" - none")
132
+
133
+ lines.append("")
134
+ lines.append("Nested structures:")
135
+ if explanation['nested_structures']:
136
+ for nested in explanation['nested_structures']:
137
+ vars_text = ''
138
+ if nested.get('vars'):
139
+ vars_text = " with " + ",".join(f"{k}={v}" for k, v in nested['vars'].items())
140
+ lines.append(f" - {nested['structure']} -> {nested['base_path']}{vars_text}")
141
+ else:
142
+ lines.append(" - none")
143
+
144
+ lines.append("")
145
+ lines.append("Remote files:")
146
+ if explanation['remote_files']:
147
+ for remote in explanation['remote_files']:
148
+ lines.append(f" - {remote['file']} -> {remote['path']}")
149
+ else:
150
+ lines.append(" - none")
151
+
152
+ if explanation['warnings']:
153
+ lines.append("")
154
+ lines.append("Warnings:")
155
+ for warning in explanation['warnings']:
156
+ lines.append(f" - {warning}")
157
+
158
+ return "\n".join(lines)
159
+
160
+ def _collect(
161
+ self,
162
+ structure_definition: str,
163
+ base_path: str,
164
+ context: Dict[str, Any],
165
+ explanation: Dict[str, Any],
166
+ seen: Set[Tuple[str, str]],
167
+ path: List[str],
168
+ ):
169
+ config, source = self._load_yaml_config(structure_definition, context['structures_path'])
170
+ if config is None:
171
+ explanation['warnings'].append(f"Structure not found or could not be loaded: {structure_definition}")
172
+ return
173
+ if not isinstance(config, dict):
174
+ explanation['warnings'].append(f"Structure is not a mapping: {structure_definition}")
175
+ return
176
+
177
+ key = (source or structure_definition, os.path.abspath(base_path))
178
+ if key in seen:
179
+ explanation['warnings'].append(f"Skipped recursive structure reference: {' -> '.join(path)}")
180
+ return
181
+ seen.add(key)
182
+
183
+ variables = config.get('variables', []) or []
184
+ resolved_vars = self._resolve_variables(variables, context['provided_vars'])
185
+ self._append_variables(explanation, structure_definition, variables, resolved_vars, context['provided_vars'])
186
+
187
+ for command in config.get('pre_hooks', []) or []:
188
+ explanation['hooks']['pre'].append({'structure': structure_definition, 'command': command})
189
+ for command in config.get('post_hooks', []) or []:
190
+ explanation['hooks']['post'].append({'structure': structure_definition, 'command': command})
191
+
192
+ files = config.get('files', config.get('structure', [])) or []
193
+ for item in files:
194
+ if not isinstance(item, dict):
195
+ explanation['warnings'].append(f"Unsupported file entry in {structure_definition}: {item}")
196
+ continue
197
+ for name, content in item.items():
198
+ rendered_name = self._render_value(str(name), variables, resolved_vars)
199
+ file_path = os.path.normpath(os.path.join(base_path, rendered_name))
200
+ remote = content.get('file') if isinstance(content, dict) else None
201
+ skip = bool(isinstance(content, dict) and content.get('skip', False))
202
+ skip_if_exists = bool(isinstance(content, dict) and content.get('skip_if_exists', False))
203
+ conflict_action = self._conflict_action(file_path, context['file_strategy'], skip, skip_if_exists)
204
+ file_info = {
205
+ 'structure': structure_definition,
206
+ 'name': rendered_name,
207
+ 'path': file_path,
208
+ 'exists': os.path.exists(file_path),
209
+ 'conflict_action': conflict_action,
210
+ 'remote': remote,
211
+ 'has_prompt': bool(isinstance(content, dict) and content.get('user_prompt')),
212
+ 'skip': skip,
213
+ 'skip_if_exists': skip_if_exists,
214
+ }
215
+ explanation['files'].append(file_info)
216
+ if remote:
217
+ explanation['remote_files'].append({'structure': structure_definition, 'file': remote, 'path': file_path})
218
+
219
+ folders = config.get('folders', []) or []
220
+ for item in folders:
221
+ if not isinstance(item, dict):
222
+ folder_path = os.path.normpath(os.path.join(base_path, str(item)))
223
+ explanation['folders'].append({'structure': structure_definition, 'name': str(item), 'path': folder_path})
224
+ continue
225
+ for folder, content in item.items():
226
+ rendered_folder = self._render_value(str(folder), variables, resolved_vars)
227
+ folder_path = os.path.normpath(os.path.join(base_path, rendered_folder))
228
+ explanation['folders'].append({'structure': structure_definition, 'name': rendered_folder, 'path': folder_path})
229
+ if not isinstance(content, dict):
230
+ continue
231
+
232
+ with_vars = self._render_with_vars(content.get('with', {}), variables, resolved_vars)
233
+ nested_vars = context['provided_vars'].copy()
234
+ nested_vars.update(with_vars)
235
+ structs = content.get('struct') or content.get('structkit')
236
+ if isinstance(structs, str):
237
+ structs = [structs]
238
+ if isinstance(structs, list):
239
+ for nested_struct in structs:
240
+ explanation['nested_structures'].append({
241
+ 'structure': nested_struct,
242
+ 'base_path': folder_path,
243
+ 'parent': structure_definition,
244
+ 'vars': with_vars,
245
+ })
246
+ nested_context = context.copy()
247
+ nested_context['provided_vars'] = nested_vars
248
+ self._collect(nested_struct, folder_path, nested_context, explanation, seen, path + [nested_struct])
249
+
250
+ seen.remove(key)
251
+
252
+ def _load_yaml_config(self, structure_definition, structures_path):
253
+ if structure_definition.endswith((".yaml", ".yml")) and not structure_definition.startswith("file://"):
254
+ structure_definition = f"file://{structure_definition}"
255
+
256
+ if structure_definition.startswith("file://") and structure_definition.endswith((".yaml", ".yml")):
257
+ file_path = structure_definition[7:]
258
+ else:
259
+ this_file = os.path.dirname(os.path.realpath(__file__))
260
+ contribs_path = os.path.join(this_file, "..", "contribs")
261
+ file_path = os.path.join(contribs_path, f"{structure_definition}.yaml")
262
+ if structures_path:
263
+ file_path = os.path.join(structures_path, f"{structure_definition}.yaml")
264
+ if not os.path.exists(file_path):
265
+ file_path = os.path.join(contribs_path, f"{structure_definition}.yaml")
266
+
267
+ if not os.path.exists(file_path):
268
+ self.logger.error(f"❗ File not found: {file_path}")
269
+ return None, file_path
270
+
271
+ try:
272
+ with open(file_path, 'r') as f:
273
+ return yaml.safe_load(f) or {}, file_path
274
+ except (yaml.YAMLError, OSError) as exc:
275
+ self.logger.error(f"❗ Failed to load {file_path}: {exc}")
276
+ return None, file_path
277
+
278
+ def _parse_template_vars(self, vars_str):
279
+ result = {}
280
+ if not vars_str:
281
+ return result
282
+ for token in [t.strip() for t in vars_str.strip(', ').split(',')]:
283
+ if not token or '=' not in token:
284
+ continue
285
+ key, value = token.split('=', 1)
286
+ key = key.strip()
287
+ if key:
288
+ result[key] = value
289
+ return result
290
+
291
+ def _resolve_variables(self, variables, provided_vars):
292
+ resolved = {}
293
+ for item in variables:
294
+ if not isinstance(item, dict):
295
+ continue
296
+ for name, content in item.items():
297
+ content = content or {}
298
+ if name in provided_vars:
299
+ resolved[name] = provided_vars[name]
300
+ elif isinstance(content, dict) and 'default' in content:
301
+ resolved[name] = content.get('default')
302
+ elif isinstance(content, dict) and (content.get('env') or content.get('default_from_env')):
303
+ env_key = content.get('env') or content.get('default_from_env')
304
+ if os.getenv(env_key) is not None:
305
+ resolved[name] = os.getenv(env_key)
306
+ for name, value in provided_vars.items():
307
+ resolved.setdefault(name, value)
308
+ return resolved
309
+
310
+ def _append_variables(self, explanation, structure_definition, variables, resolved_vars, provided_vars):
311
+ existing = {(item['structure'], item['name']) for item in explanation['variables']}
312
+ for item in variables:
313
+ if not isinstance(item, dict):
314
+ continue
315
+ for name, content in item.items():
316
+ if (structure_definition, name) in existing:
317
+ continue
318
+ content = content or {}
319
+ source = 'provided' if name in provided_vars else ('default' if isinstance(content, dict) and 'default' in content else 'unresolved')
320
+ if isinstance(content, dict) and source == 'unresolved' and (content.get('env') or content.get('default_from_env')):
321
+ env_key = content.get('env') or content.get('default_from_env')
322
+ source = f"env:{env_key}" if os.getenv(env_key) is not None else source
323
+ explanation['variables'].append({
324
+ 'structure': structure_definition,
325
+ 'name': name,
326
+ 'type': content.get('type', '') if isinstance(content, dict) else '',
327
+ 'default': content.get('default') if isinstance(content, dict) and 'default' in content else None,
328
+ 'required': bool(content.get('required', False)) if isinstance(content, dict) else False,
329
+ 'resolved_value': resolved_vars.get(name),
330
+ 'source': source,
331
+ })
332
+
333
+ def _render_value(self, value, variables, resolved_vars):
334
+ try:
335
+ renderer = TemplateRenderer(variables, '/tmp/structkit/explain-input.json', True, {})
336
+ return renderer.render_template(value, resolved_vars)
337
+ except Exception as exc:
338
+ return f"{value} [unresolved: {exc}]"
339
+
340
+ def _render_with_vars(self, with_config, variables, resolved_vars):
341
+ if not isinstance(with_config, dict):
342
+ return {}
343
+ rendered = {}
344
+ for key, value in with_config.items():
345
+ rendered[key] = self._render_value(str(value), variables, resolved_vars)
346
+ return rendered
347
+
348
+ def _conflict_action(self, path, file_strategy, skip=False, skip_if_exists=False):
349
+ exists = os.path.exists(path)
350
+ if skip:
351
+ return 'skip (skip=true)'
352
+ if skip_if_exists and exists:
353
+ return 'skip existing file (skip_if_exists=true)'
354
+ if not exists:
355
+ return 'create'
356
+ return {
357
+ 'overwrite': 'overwrite existing file',
358
+ 'skip': 'skip existing file',
359
+ 'append': 'append to existing file',
360
+ 'rename': 'rename new file',
361
+ 'backup': 'backup and overwrite existing file',
362
+ }.get(file_strategy, file_strategy)
@@ -2,12 +2,20 @@ from structkit.commands import Command
2
2
  import os
3
3
  import yaml
4
4
  import argparse
5
- from structkit.file_item import FileItem
5
+ from structkit.file_item import FileItem, ContentFetchError
6
6
  from structkit.completers import file_strategy_completer, structures_completer
7
- from structkit.template_renderer import TemplateRenderer
7
+ from structkit.template_renderer import TemplateRenderer, TemplateVariableError
8
+ from structkit.sources import SourceError, resolve_structures_path
9
+ from structkit.struct_refs import SourceContext, resolve_struct_reference
10
+ from structkit.input_store import InputStoreError
8
11
 
9
12
  import subprocess
10
13
 
14
+
15
+ class GenerateConfigError(ValueError):
16
+ """Expected generate config load/shape error shown without traceback."""
17
+
18
+
11
19
  # Generate command class
12
20
  class GenerateCommand(Command):
13
21
  def __init__(self, parser):
@@ -16,19 +24,32 @@ class GenerateCommand(Command):
16
24
  structure_arg = parser.add_argument('structure_definition', nargs='?', default='.struct.yaml', type=str, help='Path to the YAML configuration file (default: .struct.yaml)')
17
25
  structure_arg.completer = structures_completer
18
26
  parser.add_argument('base_path', nargs='?', default='.', type=str, help='Base path where the structure will be created (default: current directory)')
19
- parser.add_argument('-s', '--structures-path', type=str, help='Path to structure definitions')
20
- parser.add_argument('-n', '--input-store', type=str, help='Path to the input store', default='/tmp/structkit/input.json')
27
+ parser.add_argument(
28
+ '-s',
29
+ '--structures-path',
30
+ type=str,
31
+ help='Path to structure definitions (env: STRUCTKIT_STRUCTURES_PATH). Takes precedence over --source.',
32
+ default=os.getenv('STRUCTKIT_STRUCTURES_PATH', None)
33
+ )
34
+ parser.add_argument('--source', type=str, help='Named source to use when resolving structure definitions')
35
+ parser.add_argument('-n', '--input-store', type=str, help='Path to the input store (env: STRUCTKIT_INPUT_STORE)', default=os.getenv('STRUCTKIT_INPUT_STORE', '/tmp/structkit/input.json'))
21
36
  parser.add_argument('-d', '--dry-run', action='store_true', help='Perform a dry run without creating any files or directories')
22
37
  parser.add_argument('--diff', action='store_true', help='Show unified diffs for files that would change during dry-run or console output')
23
38
  parser.add_argument('-v', '--vars', type=str, help='Template variables in the format KEY1=value1,KEY2=value2')
24
- parser.add_argument('-b', '--backup', type=str, help='Path to the backup folder')
25
- parser.add_argument('-f', '--file-strategy', type=str, choices=['overwrite', 'skip', 'append', 'rename', 'backup'], default='overwrite', help='Strategy for handling existing files').completer = file_strategy_completer
26
- parser.add_argument('-p', '--global-system-prompt', type=str, help='Global system prompt for OpenAI')
27
- parser.add_argument('--non-interactive', action='store_true', help='Run the command in non-interactive mode')
39
+ parser.add_argument('-b', '--backup', type=str, help='Path to the backup folder (env: STRUCTKIT_BACKUP_PATH)', default=os.getenv('STRUCTKIT_BACKUP_PATH', None))
40
+ parser.add_argument(
41
+ '-f',
42
+ '--file-strategy',
43
+ type=str,
44
+ choices=['overwrite', 'skip', 'append', 'rename', 'backup'],
45
+ default=os.getenv('STRUCTKIT_FILE_STRATEGY', 'overwrite'),
46
+ help='Strategy for handling existing files (env: STRUCTKIT_FILE_STRATEGY)').completer = file_strategy_completer
47
+ parser.add_argument('-p', '--global-system-prompt', type=str, help='Global system prompt for OpenAI (env: STRUCTKIT_GLOBAL_SYSTEM_PROMPT)', default=os.getenv('STRUCTKIT_GLOBAL_SYSTEM_PROMPT', None))
48
+ parser.add_argument('--non-interactive', action='store_true', help='Run the command in non-interactive mode (env: STRUCTKIT_NON_INTERACTIVE)', default=os.getenv('STRUCTKIT_NON_INTERACTIVE', '').lower() in ('true', '1', 'yes'))
28
49
  parser.add_argument('--mappings-file', type=str, action='append',
29
50
  help='Path to a YAML file containing mappings to be used in templates (can be specified multiple times)')
30
51
  parser.add_argument('-o', '--output', type=str,
31
- choices=['console', 'file'], default='file', help='Output mode')
52
+ choices=['console', 'file'], default=os.getenv('STRUCTKIT_OUTPUT_MODE', 'file'), help='Output mode (env: STRUCTKIT_OUTPUT_MODE)')
32
53
  parser.set_defaults(func=self.execute)
33
54
 
34
55
  def _parse_template_vars(self, vars_str):
@@ -96,8 +117,7 @@ class GenerateCommand(Command):
96
117
  structure_definition = f"file://{structure_definition}"
97
118
 
98
119
  if structure_definition.startswith("file://") and structure_definition.endswith(".yaml"):
99
- with open(structure_definition[7:], 'r') as f:
100
- return yaml.safe_load(f)
120
+ file_path = structure_definition[7:]
101
121
  else:
102
122
  this_file = os.path.dirname(os.path.realpath(__file__))
103
123
  contribs_path = os.path.join(this_file, "..", "contribs")
@@ -106,14 +126,40 @@ class GenerateCommand(Command):
106
126
  file_path = os.path.join(structures_path, f"{structure_definition}.yaml")
107
127
  if not os.path.exists(file_path):
108
128
  file_path = os.path.join(contribs_path, f"{structure_definition}.yaml")
109
- if not os.path.exists(file_path):
110
- self.logger.error(f"❗ File not found: {file_path}")
111
- return None
129
+
130
+ try:
112
131
  with open(file_path, 'r') as f:
113
132
  return yaml.safe_load(f)
133
+ except FileNotFoundError:
134
+ raise GenerateConfigError(f"File not found: {file_path}") from None
135
+ except yaml.YAMLError as exc:
136
+ raise GenerateConfigError(f"Invalid YAML in {file_path}: {exc}") from None
137
+ except OSError as exc:
138
+ raise GenerateConfigError(f"Failed to read {file_path}: {exc}") from None
139
+
140
+ def _validate_loaded_config(self, config):
141
+ if config is None:
142
+ return {}
143
+ if not isinstance(config, dict):
144
+ raise GenerateConfigError("Top-level YAML content must be a mapping.")
145
+ return config
114
146
 
115
147
  def execute(self, args):
116
- self.logger.info(f"Generating structure")
148
+ try:
149
+ args.structures_path, args.structure_definition = resolve_structures_path(
150
+ args.structures_path,
151
+ getattr(args, 'source', None),
152
+ args.structure_definition,
153
+ )
154
+ except SourceError as exc:
155
+ self.logger.error(f"❗ {exc}")
156
+ raise SystemExit(1) from exc
157
+
158
+ # Log when using STRUCTKIT_STRUCTURES_PATH environment variable
159
+ if args.structures_path and args.structures_path == os.getenv('STRUCTKIT_STRUCTURES_PATH'):
160
+ self.logger.info(f"Using STRUCTKIT_STRUCTURES_PATH: {args.structures_path}")
161
+
162
+ self.logger.info("Generating structure")
117
163
  self.logger.info(f" Structure definition: {args.structure_definition}")
118
164
  self.logger.info(f" Base path: {args.base_path}")
119
165
 
@@ -135,6 +181,16 @@ class GenerateCommand(Command):
135
181
  self.logger.error(f"Mappings file not found: {mappings_file_path}")
136
182
  return
137
183
 
184
+ # Load and validate config before creating output/backup paths, so config
185
+ # errors do not leave partial filesystem side effects behind.
186
+ try:
187
+ config = self._validate_loaded_config(
188
+ self._load_yaml_config(args.structure_definition, args.structures_path)
189
+ )
190
+ except GenerateConfigError as exc:
191
+ self.logger.error(f"❗ {exc}")
192
+ raise SystemExit(1) from None
193
+
138
194
  if args.backup and not os.path.exists(args.backup):
139
195
  os.makedirs(args.backup)
140
196
 
@@ -142,12 +198,6 @@ class GenerateCommand(Command):
142
198
  self.logger.info(f"Creating base path: {args.base_path}")
143
199
  os.makedirs(args.base_path)
144
200
 
145
- # Load config to check for hooks
146
- config = None
147
- config = self._load_yaml_config(args.structure_definition, args.structures_path)
148
- if config is None:
149
- return
150
-
151
201
  pre_hooks = config.get('pre_hooks', [])
152
202
  post_hooks = config.get('post_hooks', [])
153
203
 
@@ -157,22 +207,30 @@ class GenerateCommand(Command):
157
207
  return
158
208
 
159
209
  # Actually generate structure
160
- self._create_structure(args, mappings)
210
+ try:
211
+ self._create_structure(args, mappings)
212
+ except (GenerateConfigError, SourceError, TemplateVariableError, ContentFetchError, InputStoreError) as exc:
213
+ self.logger.error(f"❗ {exc}")
214
+ raise SystemExit(1) from None
161
215
 
162
216
  # Run post-hooks
163
217
  if not self._run_hooks(post_hooks, hook_type="post"):
164
218
  self.logger.error("Post-hook failed.")
165
219
  return
166
220
 
167
- def _create_structure(self, args, mappings=None, summary=None, print_summary=True):
221
+ def _create_structure(self, args, mappings=None, summary=None, print_summary=True, source_context=None):
168
222
  if isinstance(args, dict):
169
223
  args = argparse.Namespace(**args)
170
- this_file = os.path.dirname(os.path.realpath(__file__))
171
- contribs_path = os.path.join(this_file, "..", "contribs")
172
224
 
173
- config = self._load_yaml_config(args.structure_definition, args.structures_path)
174
- if config is None:
175
- return summary if summary is not None else None
225
+ config = self._validate_loaded_config(
226
+ self._load_yaml_config(args.structure_definition, args.structures_path)
227
+ )
228
+
229
+ is_top_level_source_context = source_context is None
230
+ source_context = (source_context or SourceContext.from_global()).merge_inline(
231
+ config.get('sources'),
232
+ allow_override=is_top_level_source_context,
233
+ )
176
234
 
177
235
  # Safely parse template variables
178
236
  template_vars = self._parse_template_vars(args.vars) if getattr(args, 'vars', None) else {}
@@ -302,9 +360,9 @@ class GenerateCommand(Command):
302
360
 
303
361
  # check if content has structkit value
304
362
  if 'struct' in content:
305
- self.logger.info(f"Generating structure")
363
+ self.logger.info("Generating structure")
306
364
  self.logger.info(f" Folder: {folder}")
307
- self.logger.info(f" Struct(s):")
365
+ self.logger.info(" Struct(s):")
308
366
  if isinstance(content['struct'], list):
309
367
  # iterate over the list of structures
310
368
  for struct in content['struct']:
@@ -344,10 +402,12 @@ class GenerateCommand(Command):
344
402
  merged_vars = merged_vars if merged_vars else None
345
403
 
346
404
  if isinstance(content['struct'], str):
405
+ child_structures_path, child_structure_definition = resolve_struct_reference(
406
+ content['struct'], args.structures_path, source_context)
347
407
  self._create_structure({
348
- 'structure_definition': content['struct'],
408
+ 'structure_definition': child_structure_definition,
349
409
  'base_path': folder_path,
350
- 'structures_path': args.structures_path,
410
+ 'structures_path': child_structures_path,
351
411
  'dry_run': args.dry_run,
352
412
  'diff': getattr(args, 'diff', False),
353
413
  'output': getattr(args, 'output', 'file'),
@@ -357,13 +417,15 @@ class GenerateCommand(Command):
357
417
  'global_system_prompt': args.global_system_prompt,
358
418
  'input_store': args.input_store,
359
419
  'non_interactive': args.non_interactive,
360
- }, mappings=mappings, summary=summary, print_summary=False)
420
+ }, mappings=mappings, summary=summary, print_summary=False, source_context=source_context)
361
421
  elif isinstance(content['struct'], list):
362
422
  for struct in content['struct']:
423
+ child_structures_path, child_structure_definition = resolve_struct_reference(
424
+ struct, args.structures_path, source_context)
363
425
  self._create_structure({
364
- 'structure_definition': struct,
426
+ 'structure_definition': child_structure_definition,
365
427
  'base_path': folder_path,
366
- 'structures_path': args.structures_path,
428
+ 'structures_path': child_structures_path,
367
429
  'dry_run': args.dry_run,
368
430
  'diff': getattr(args, 'diff', False),
369
431
  'output': getattr(args, 'output', 'file'),
@@ -373,7 +435,7 @@ class GenerateCommand(Command):
373
435
  'global_system_prompt': args.global_system_prompt,
374
436
  'input_store': args.input_store,
375
437
  'non_interactive': args.non_interactive,
376
- }, mappings=mappings, summary=summary, print_summary=False)
438
+ }, mappings=mappings, summary=summary, print_summary=False, source_context=source_context)
377
439
  else:
378
440
  self.logger.warning(f"Unsupported content in folder: {folder}")
379
441
 
@@ -7,7 +7,7 @@ class GenerateSchemaCommand(Command):
7
7
  def __init__(self, parser):
8
8
  super().__init__(parser)
9
9
  parser.description = "Generate JSON schema for available structures"
10
- parser.add_argument('-s', '--structures-path', type=str, help='Path to structure definitions')
10
+ parser.add_argument('-s', '--structures-path', type=str, help='Path to structure definitions (env: STRUCTKIT_STRUCTURES_PATH)', default=os.getenv('STRUCTKIT_STRUCTURES_PATH', None))
11
11
  parser.add_argument('-o', '--output', type=str, help='Output file path for the schema (default: stdout)')
12
12
  parser.set_defaults(func=self.execute)
13
13