structkit 3.2.1__py3-none-any.whl → 3.3.1__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.
@@ -51,9 +51,7 @@ class CompletionCommand(Command):
51
51
  print("exec zsh")
52
52
 
53
53
  elif shell == "fish":
54
- print("\n# Install shtab (once, in your environment):")
55
- print("python -m pip install shtab")
56
- print("\n# Generate static fish completion for 'struct':")
54
+ print("\n# Generate static fish completion for 'structkit':")
57
55
  print('mkdir -p ~/.config/fish/completions')
58
56
  print('structkit --print-completion fish > ~/.config/fish/completions/structkit.fish')
59
57
  print("\n# Apply now:")
@@ -0,0 +1,82 @@
1
+ """Config command for displaying effective configuration."""
2
+
3
+ from structkit.commands import Command
4
+ import yaml
5
+ import json
6
+ from structkit.config import get_effective_config, get_user_config_path, get_builtin_defaults
7
+
8
+
9
+ class ConfigCommand(Command):
10
+ def __init__(self, parser):
11
+ # Don't call super().__init__() yet - we need to set up subparsers first
12
+ self.parser = parser
13
+ import logging
14
+ self.logger = logging.getLogger(__name__)
15
+
16
+ parser.description = "Display and manage structkit configuration"
17
+
18
+ # Create subparsers for config subcommands
19
+ subparsers = parser.add_subparsers(dest='config_subcommand', help='Config subcommand')
20
+
21
+ # print subcommand
22
+ print_parser = subparsers.add_parser('print', help='Print the effective configuration')
23
+ print_parser.add_argument(
24
+ '--format',
25
+ type=str,
26
+ choices=['yaml', 'json'],
27
+ default='yaml',
28
+ help='Output format (default: yaml)'
29
+ )
30
+ print_parser.set_defaults(config_func=self.print_config)
31
+
32
+ # Add common arguments to the main parser and all subparsers
33
+ for p in [parser, print_parser]:
34
+ self._add_common_args(p)
35
+
36
+ parser.set_defaults(func=self.execute)
37
+
38
+ def _add_common_args(self, parser):
39
+ """Add common arguments to a parser (replicating Command base class)."""
40
+ from structkit.completers import log_level_completer
41
+ parser.add_argument('-l', '--log', type=str, default='INFO', help='Set the logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)').completer = log_level_completer
42
+ parser.add_argument('-c', '--config-file', type=str, help='Path to a configuration file')
43
+ parser.add_argument('-i', '--log-file', type=str, help='Path to a log file')
44
+
45
+ def execute(self, args):
46
+ """Execute the config command."""
47
+ # If no subcommand is provided, show help
48
+ if not hasattr(args, 'config_func'):
49
+ self.parser.print_help()
50
+ return
51
+
52
+ # Execute the subcommand
53
+ args.config_func(args)
54
+
55
+ def print_config(self, args):
56
+ """Print the effective configuration after all layers are merged.
57
+
58
+ This shows the final configuration that structkit would use,
59
+ combining built-in defaults, user config, project config, and CLI args.
60
+ """
61
+ # Get effective config
62
+ effective_config = get_effective_config(args)
63
+
64
+ # Format and print
65
+ if args.format == 'json':
66
+ output = json.dumps(effective_config, indent=2, sort_keys=True)
67
+ else: # yaml
68
+ output = yaml.dump(effective_config, default_flow_style=False, sort_keys=True)
69
+
70
+ print(output.rstrip())
71
+
72
+ # Show config sources
73
+ user_config_path = get_user_config_path()
74
+ self.logger.info("")
75
+ self.logger.info("Configuration sources:")
76
+ self.logger.info(" 1. Built-in defaults: always loaded")
77
+ self.logger.info(f" 2. User config: {user_config_path} {'(exists)' if user_config_path.exists() else '(not found)'}")
78
+ if hasattr(args, 'config_file') and args.config_file:
79
+ self.logger.info(f" 3. Project config: {args.config_file}")
80
+ else:
81
+ self.logger.info(" 3. Project config: none specified")
82
+ self.logger.info(" 4. CLI arguments: highest priority")
@@ -8,6 +8,11 @@ from structkit.template_renderer import TemplateRenderer, TemplateVariableError
8
8
  from structkit.sources import SourceError, resolve_structures_path
9
9
  from structkit.struct_refs import SourceContext, resolve_struct_reference
10
10
  from structkit.input_store import InputStoreError
11
+ from structkit.project_file import (
12
+ CANONICAL_PROJECT_STRUCT_FILE,
13
+ LEGACY_PROJECT_STRUCT_FILE,
14
+ resolve_project_struct_file,
15
+ )
11
16
 
12
17
  import subprocess
13
18
 
@@ -21,7 +26,16 @@ class GenerateCommand(Command):
21
26
  def __init__(self, parser):
22
27
  super().__init__(parser)
23
28
  parser.description = "Generate the project structure from a YAML configuration file"
24
- structure_arg = parser.add_argument('structure_definition', nargs='?', default='.struct.yaml', type=str, help='Path to the YAML configuration file (default: .struct.yaml)')
29
+ structure_arg = parser.add_argument(
30
+ 'structure_definition',
31
+ nargs='?',
32
+ default=CANONICAL_PROJECT_STRUCT_FILE,
33
+ type=str,
34
+ help=(
35
+ f'Path to the YAML configuration file (default: {CANONICAL_PROJECT_STRUCT_FILE}; '
36
+ f'falls back to {LEGACY_PROJECT_STRUCT_FILE} for compatibility)'
37
+ ),
38
+ )
25
39
  structure_arg.completer = structures_completer
26
40
  parser.add_argument('base_path', nargs='?', default='.', type=str, help='Base path where the structure will be created (default: current directory)')
27
41
  parser.add_argument(
@@ -50,6 +64,8 @@ class GenerateCommand(Command):
50
64
  help='Path to a YAML file containing mappings to be used in templates (can be specified multiple times)')
51
65
  parser.add_argument('-o', '--output', type=str,
52
66
  choices=['console', 'file'], default=os.getenv('STRUCTKIT_OUTPUT_MODE', 'file'), help='Output mode (env: STRUCTKIT_OUTPUT_MODE)')
67
+ parser.add_argument('--no-hooks', action='store_true', help='Skip all pre/post hooks (env: STRUCTKIT_NO_HOOKS)', default=os.getenv('STRUCTKIT_NO_HOOKS', '').lower() in ('true', '1', 'yes'))
68
+ parser.add_argument('--hooks-allowlist', type=str, help='Path to hooks allowlist file (env: STRUCTKIT_HOOKS_ALLOWLIST)', default=os.getenv('STRUCTKIT_HOOKS_ALLOWLIST', None))
53
69
  parser.set_defaults(func=self.execute)
54
70
 
55
71
  def _parse_template_vars(self, vars_str):
@@ -91,9 +107,108 @@ class GenerateCommand(Command):
91
107
  result[key] = value
92
108
  return result
93
109
 
94
- def _run_hooks(self, hooks, hook_type="pre"): # helper for running hooks
110
+ def _load_hooks_allowlist(self, allowlist_path):
111
+ """Load the hooks allowlist from a file.
112
+ Returns a set of allowed commands or None if file doesn't exist.
113
+ """
114
+ if not allowlist_path:
115
+ return None
116
+
117
+ allowlist_file = None
118
+ if os.path.isabs(allowlist_path):
119
+ allowlist_file = allowlist_path
120
+ else:
121
+ allowlist_file = os.path.join(os.getcwd(), allowlist_path)
122
+
123
+ if not os.path.exists(allowlist_file):
124
+ # Also check for .struct-hooks-allowlist in current directory if no explicit path given
125
+ default_allowlist = os.path.join(os.getcwd(), '.struct-hooks-allowlist')
126
+ if allowlist_path == default_allowlist and not os.path.exists(default_allowlist):
127
+ return None
128
+ self.logger.warning(f"Hooks allowlist file not found: {allowlist_file}")
129
+ return None
130
+
131
+ try:
132
+ with open(allowlist_file, 'r') as f:
133
+ lines = f.readlines()
134
+ # Parse allowlist: ignore empty lines and comments (lines starting with #)
135
+ allowlist = set()
136
+ for line in lines:
137
+ line = line.strip()
138
+ if line and not line.startswith('#'):
139
+ allowlist.add(line)
140
+ return allowlist
141
+ except Exception as e:
142
+ self.logger.error(f"Failed to read hooks allowlist: {e}")
143
+ return None
144
+
145
+ def _check_hook_allowed(self, cmd, allowlist):
146
+ """Check if a command is allowed by the allowlist.
147
+ If allowlist is None, all commands are allowed.
148
+ If allowlist is a set, only commands in the set are allowed.
149
+ """
150
+ if allowlist is None:
151
+ return True
152
+
153
+ # Check exact match first
154
+ if cmd in allowlist:
155
+ return True
156
+
157
+ # Check if the base command (first word) is allowed
158
+ base_cmd = cmd.split()[0] if cmd.split() else cmd
159
+ if base_cmd in allowlist:
160
+ return True
161
+
162
+ return False
163
+
164
+ def _confirm_hooks(self, hooks, hook_type="pre"):
165
+ """Ask user to confirm hook execution.
166
+ Returns True if user confirms, False otherwise.
167
+ """
95
168
  if not hooks:
96
169
  return True
170
+
171
+ print(f"\n⚠️ The following {hook_type}-hooks will be executed:")
172
+ for cmd in hooks:
173
+ print(f" - {cmd}")
174
+
175
+ response = input(f"\nDo you want to run these {hook_type}-hooks? [y/N]: ").strip().lower()
176
+ return response in ('y', 'yes')
177
+
178
+ def _run_hooks(self, hooks, hook_type="pre", skip_hooks=False, non_interactive=False, allowlist=None):
179
+ """Run pre/post hooks with safety controls.
180
+
181
+ Args:
182
+ hooks: List of shell commands to run
183
+ hook_type: Type of hooks ("pre" or "post")
184
+ skip_hooks: If True, skip all hooks
185
+ non_interactive: If True, skip confirmation prompt
186
+ allowlist: Set of allowed commands or None to allow all
187
+
188
+ Returns:
189
+ True if all hooks succeeded or were skipped, False if any failed
190
+ """
191
+ if not hooks or skip_hooks:
192
+ if skip_hooks and hooks:
193
+ self.logger.info(f"Skipping {hook_type}-hooks (--no-hooks enabled)")
194
+ return True
195
+
196
+ # Check if any hooks are blocked by allowlist
197
+ if allowlist is not None:
198
+ blocked_hooks = [cmd for cmd in hooks if not self._check_hook_allowed(cmd, allowlist)]
199
+ if blocked_hooks:
200
+ self.logger.error(f"The following {hook_type}-hooks are not in the allowlist:")
201
+ for cmd in blocked_hooks:
202
+ self.logger.error(f" - {cmd}")
203
+ self.logger.error("Hook execution blocked. Update allowlist or use --no-hooks to skip.")
204
+ return False
205
+
206
+ # Ask for confirmation in interactive mode
207
+ if not non_interactive:
208
+ if not self._confirm_hooks(hooks, hook_type):
209
+ self.logger.info(f"User declined to run {hook_type}-hooks. Aborting.")
210
+ return False
211
+
97
212
  for cmd in hooks:
98
213
  self.logger.info(f"Running {hook_type}-hook: {cmd}")
99
214
  try:
@@ -145,6 +260,9 @@ class GenerateCommand(Command):
145
260
  return config
146
261
 
147
262
  def execute(self, args):
263
+ args.structure_definition = resolve_project_struct_file(
264
+ explicit_path=getattr(args, 'structure_definition', None),
265
+ )
148
266
  try:
149
267
  args.structures_path, args.structure_definition = resolve_structures_path(
150
268
  args.structures_path,
@@ -201,8 +319,23 @@ class GenerateCommand(Command):
201
319
  pre_hooks = config.get('pre_hooks', [])
202
320
  post_hooks = config.get('post_hooks', [])
203
321
 
322
+ skip_hooks = getattr(args, 'no_hooks', False)
323
+ non_interactive = getattr(args, 'non_interactive', False)
324
+
325
+ # Load hooks allowlist if provided (only if hooks are enabled)
326
+ allowlist = None
327
+ if not skip_hooks:
328
+ allowlist_path = getattr(args, 'hooks_allowlist', None)
329
+ if not allowlist_path:
330
+ # Check for default .struct-hooks-allowlist in current directory
331
+ default_allowlist = os.path.join(os.getcwd(), '.struct-hooks-allowlist')
332
+ if os.path.exists(default_allowlist):
333
+ allowlist_path = default_allowlist
334
+
335
+ allowlist = self._load_hooks_allowlist(allowlist_path) if allowlist_path else None
336
+
204
337
  # Run pre-hooks
205
- if not self._run_hooks(pre_hooks, hook_type="pre"):
338
+ if not self._run_hooks(pre_hooks, hook_type="pre", skip_hooks=skip_hooks, non_interactive=non_interactive, allowlist=allowlist):
206
339
  self.logger.error("Aborting generation due to pre-hook failure.")
207
340
  return
208
341
 
@@ -214,7 +347,7 @@ class GenerateCommand(Command):
214
347
  raise SystemExit(1) from None
215
348
 
216
349
  # Run post-hooks
217
- if not self._run_hooks(post_hooks, hook_type="post"):
350
+ if not self._run_hooks(post_hooks, hook_type="post", skip_hooks=skip_hooks, non_interactive=non_interactive, allowlist=allowlist):
218
351
  self.logger.error("Post-hook failed.")
219
352
  return
220
353
 
@@ -1,6 +1,10 @@
1
1
  from structkit.commands import Command
2
2
  import os
3
3
  import textwrap
4
+ from structkit.project_file import (
5
+ CANONICAL_PROJECT_STRUCT_FILE,
6
+ LEGACY_PROJECT_STRUCT_FILE,
7
+ )
4
8
 
5
9
  BASIC_STRUCTKIT_YAML = textwrap.dedent(
6
10
  """
@@ -17,7 +21,7 @@ BASIC_STRUCTKIT_YAML = textwrap.dedent(
17
21
  - README.md: |
18
22
  # Project
19
23
 
20
- Initialized with struct.
24
+ Initialized with structkit.
21
25
 
22
26
  folders:
23
27
  - ./:
@@ -30,24 +34,33 @@ BASIC_STRUCTKIT_YAML = textwrap.dedent(
30
34
  class InitCommand(Command):
31
35
  def __init__(self, parser):
32
36
  super().__init__(parser)
33
- parser.description = "Initialize a basic .struct.yaml in the target directory"
37
+ parser.description = f"Initialize a basic {CANONICAL_PROJECT_STRUCT_FILE} in the target directory"
34
38
  parser.add_argument('path', nargs='?', default='.', help='Directory to initialize (default: current directory)')
35
39
  parser.set_defaults(func=self.execute)
36
40
 
37
41
  def execute(self, args):
38
42
  base_path = os.path.abspath(args.path or '.')
39
- target = os.path.join(base_path, '.struct.yaml')
43
+ target = os.path.join(base_path, CANONICAL_PROJECT_STRUCT_FILE)
44
+ legacy = os.path.join(base_path, LEGACY_PROJECT_STRUCT_FILE)
40
45
 
41
46
  os.makedirs(base_path, exist_ok=True)
42
47
 
43
- # If file exists, do not overwrite without explicit confirmation behavior (keep simple: skip)
48
+ # If either canonical or legacy file exists, do not overwrite.
44
49
  if os.path.exists(target):
45
- self.logger.info(f".struct.yaml already exists at {target}, skipping creation")
46
- print(f"⚠️ .struct.yaml already exists at: {target}")
50
+ self.logger.info(f"{CANONICAL_PROJECT_STRUCT_FILE} already exists at {target}, skipping creation")
51
+ print(f"⚠️ {CANONICAL_PROJECT_STRUCT_FILE} already exists at: {target}")
52
+ return
53
+
54
+ if os.path.exists(legacy):
55
+ self.logger.info(
56
+ f"{LEGACY_PROJECT_STRUCT_FILE} already exists at {legacy}, skipping creation"
57
+ )
58
+ print(f"⚠️ {LEGACY_PROJECT_STRUCT_FILE} already exists at: {legacy}")
59
+ print(f" Consider renaming it to {CANONICAL_PROJECT_STRUCT_FILE}.")
47
60
  return
48
61
 
49
62
  with open(target, 'w') as f:
50
63
  f.write(BASIC_STRUCTKIT_YAML)
51
64
 
52
- print("✅ Created .struct.yaml")
65
+ print(f"✅ Created {CANONICAL_PROJECT_STRUCT_FILE}")
53
66
  print(f" - {target}")
structkit/config.py ADDED
@@ -0,0 +1,209 @@
1
+ """Configuration layering system for structkit.
2
+
3
+ Supports loading and merging CLI configuration from multiple sources:
4
+ 1. Built-in defaults
5
+ 2. User config (~/.config/struct/config.yaml) — loaded automatically when present
6
+ 3. Project config from --config-file only (not auto-loaded from .structkit.yaml)
7
+ 4. CLI arguments
8
+
9
+ Priority order: CLI args > --config-file > user config > built-in defaults
10
+
11
+ .structkit.yaml (and legacy .struct.yaml) is the structure definition used by
12
+ generate/validate/etc., not a layered CLI config file.
13
+
14
+ Named structure sources live in a separate file
15
+ (~/.config/structkit/sources.yaml, overridable via STRUCTKIT_SOURCES_CONFIG).
16
+ """
17
+
18
+ import os
19
+ import yaml
20
+ from pathlib import Path
21
+ from typing import Dict, Any, Optional
22
+ import logging
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ def get_user_config_path() -> Path:
28
+ """Get the path to the user config file.
29
+
30
+ Returns ~/.config/struct/config.yaml
31
+ """
32
+ return Path.home() / ".config" / "struct" / "config.yaml"
33
+
34
+
35
+ def get_builtin_defaults() -> Dict[str, Any]:
36
+ """Return built-in default configuration values.
37
+
38
+ These are the lowest priority defaults used when no other config is provided.
39
+ """
40
+ return {
41
+ 'file_strategy': 'overwrite',
42
+ 'input_store': '/tmp/structkit/input.json',
43
+ 'log': 'INFO',
44
+ 'non_interactive': False,
45
+ 'output': 'file',
46
+ }
47
+
48
+
49
+ def load_yaml_config(config_path: str) -> Optional[Dict[str, Any]]:
50
+ """Load a YAML config file and return its contents.
51
+
52
+ Args:
53
+ config_path: Path to the YAML config file
54
+
55
+ Returns:
56
+ Dictionary with config values, or None if file doesn't exist or is empty
57
+ """
58
+ if not config_path or not os.path.exists(config_path):
59
+ return None
60
+
61
+ try:
62
+ with open(config_path, 'r') as f:
63
+ config = yaml.safe_load(f)
64
+ if config is None:
65
+ return {}
66
+ if not isinstance(config, dict):
67
+ logger.warning(f"Config file {config_path} does not contain a mapping, ignoring")
68
+ return {}
69
+ return config
70
+ except yaml.YAMLError as exc:
71
+ logger.warning(f"Failed to parse YAML in {config_path}: {exc}")
72
+ return {}
73
+ except OSError as exc:
74
+ logger.warning(f"Failed to read {config_path}: {exc}")
75
+ return {}
76
+
77
+
78
+ def merge_config_layer(base: Dict[str, Any], override: Optional[Dict[str, Any]]) -> Dict[str, Any]:
79
+ """Merge an override config layer into a base config.
80
+
81
+ Override values take precedence over base values. Only merges top-level keys.
82
+
83
+ Args:
84
+ base: Base configuration dictionary
85
+ override: Override configuration dictionary (can be None)
86
+
87
+ Returns:
88
+ Merged configuration dictionary
89
+ """
90
+ if override is None:
91
+ return base.copy()
92
+
93
+ result = base.copy()
94
+ for key, value in override.items():
95
+ if value is not None:
96
+ result[key] = value
97
+ return result
98
+
99
+
100
+ def load_layered_config(project_config_path: Optional[str] = None) -> Dict[str, Any]:
101
+ """Load configuration from all layers and merge them.
102
+
103
+ Merge order (lowest to highest priority):
104
+ 1. Built-in defaults
105
+ 2. User config (~/.config/struct/config.yaml)
106
+ 3. Project config from --config-file, if provided
107
+ (.structkit.yaml is not auto-loaded here)
108
+
109
+ Args:
110
+ project_config_path: Path from --config-file, or None
111
+
112
+ Returns:
113
+ Merged configuration dictionary
114
+ """
115
+ # Start with built-in defaults
116
+ config = get_builtin_defaults()
117
+
118
+ # Layer in user config
119
+ user_config_path = get_user_config_path()
120
+ if user_config_path.exists():
121
+ logger.debug(f"Loading user config from {user_config_path}")
122
+ user_config = load_yaml_config(str(user_config_path))
123
+ config = merge_config_layer(config, user_config)
124
+
125
+ # Layer in project config
126
+ if project_config_path:
127
+ logger.debug(f"Loading project config from {project_config_path}")
128
+ project_config = load_yaml_config(project_config_path)
129
+ config = merge_config_layer(config, project_config)
130
+
131
+ return config
132
+
133
+
134
+ def merge_cli_args(config: Dict[str, Any], args) -> Dict[str, Any]:
135
+ """Merge CLI arguments into configuration, giving CLI args highest priority.
136
+
137
+ Args:
138
+ config: Configuration dictionary from layered config files
139
+ args: argparse Namespace with CLI arguments
140
+
141
+ Returns:
142
+ Final merged configuration dictionary
143
+ """
144
+ result = config.copy()
145
+ args_dict = vars(args)
146
+
147
+ # List of config keys that can be set via CLI args
148
+ # We only override config file values if the CLI arg was explicitly provided
149
+ # (i.e., it's not None and differs from the default)
150
+ cli_overridable_keys = [
151
+ 'structures_path',
152
+ 'input_store',
153
+ 'file_strategy',
154
+ 'backup',
155
+ 'global_system_prompt',
156
+ 'non_interactive',
157
+ 'output',
158
+ 'log',
159
+ 'log_file',
160
+ 'source',
161
+ ]
162
+
163
+ for key in cli_overridable_keys:
164
+ if key in args_dict and args_dict[key] is not None:
165
+ result[key] = args_dict[key]
166
+
167
+ return result
168
+
169
+
170
+ def apply_config_to_args(config: Dict[str, Any], args):
171
+ """Apply configuration values to argparse namespace.
172
+
173
+ This modifies the args namespace in place, setting values from the config
174
+ only if the arg was not explicitly set via CLI.
175
+
176
+ Args:
177
+ config: Configuration dictionary
178
+ args: argparse Namespace to update
179
+ """
180
+ args_dict = vars(args)
181
+
182
+ for key, value in config.items():
183
+ # Only set the value if the arg doesn't already have a non-None value
184
+ # This ensures CLI args take precedence
185
+ if key in args_dict and args_dict[key] is None:
186
+ args_dict[key] = value
187
+
188
+
189
+ def get_effective_config(args) -> Dict[str, Any]:
190
+ """Get the effective configuration by merging all layers including CLI args.
191
+
192
+ This is the final configuration that would be used after all merging is complete.
193
+
194
+ Args:
195
+ args: argparse Namespace with CLI arguments
196
+
197
+ Returns:
198
+ Effective configuration dictionary
199
+ """
200
+ # Get the project config file path from args if present
201
+ project_config_path = getattr(args, 'config_file', None)
202
+
203
+ # Load layered config from files
204
+ config = load_layered_config(project_config_path)
205
+
206
+ # Merge in CLI args (highest priority)
207
+ config = merge_cli_args(config, args)
208
+
209
+ return config
@@ -194,8 +194,8 @@ The `contribs` folder contains various sub-structs that can be used to generate
194
194
 
195
195
  #### `github/prompts/struct`
196
196
 
197
- - **Description**: Provides a prompt for creating a new .struct.yaml file and workflow to run struct.
198
- - **When to Use**: Use this sub-structkit when you need to create a new .struct.yaml file and workflow to run struct.
197
+ - **Description**: Provides a prompt for creating a new .structkit.yaml file and workflow to run struct.
198
+ - **When to Use**: Use this sub-structkit when you need to create a new .structkit.yaml file and workflow to run struct.
199
199
 
200
200
  ### Project
201
201
 
@@ -34,4 +34,4 @@ files:
34
34
  # Code of Conduct
35
35
  Our standards for how to behave within our community.
36
36
  - LICENSE.md:
37
- file: https://raw.githubusercontent.com/git/git-scm.com/main/MIT-LICENSE.txt
37
+ file: https://raw.githubusercontent.com/httpdss/structkit/main/LICENSE
@@ -1,6 +1,6 @@
1
1
  description: >
2
2
  Creates a GitHub Copilot prompt that configures an AI assistant for generating
3
- valid .struct.yaml files for the StructKit tool, with schema references and usage examples.
3
+ valid .structkit.yaml files for the StructKit tool, with schema references and usage examples.
4
4
 
5
5
  files:
6
6
  - .github/prompts/struct.prompt.md:
@@ -9,9 +9,9 @@ files:
9
9
 
10
10
  ## Role
11
11
 
12
- You are an expert assistant that generates valid `.struct.yaml` files for the [StructKit tool](https://github.com/httpdss/struct), which automates project structure generation from YAML configuration.
12
+ You are an expert assistant that generates valid `.structkit.yaml` files for the [StructKit tool](https://github.com/httpdss/structkit), which automates project structure generation from YAML configuration.
13
13
 
14
- ## Defining the `.struct.yaml` file
14
+ ## Defining the `.structkit.yaml` file
15
15
 
16
16
  this file has 3 main keys: `structures`, `folders`, and `variables`.
17
17
 
@@ -1,6 +1,6 @@
1
1
  description: >
2
2
  Creates a GitHub Actions workflow (run-struct.yaml) that can be manually triggered
3
- via workflow_dispatch to run struct file generation, plus a starter .struct.yaml file.
3
+ via workflow_dispatch to run struct file generation, plus a starter .structkit.yaml file.
4
4
 
5
5
  files:
6
6
  - .github/workflows/run-struct.yaml:
@@ -15,11 +15,11 @@ files:
15
15
  generate:
16
16
  uses: httpdss/structkit/.github/workflows/struct-generate.yaml@main
17
17
  with:
18
- struct_file: 'file://.struct.yaml'
18
+ struct_file: 'file://.structkit.yaml'
19
19
  output_dir: '.'
20
20
  secrets:
21
21
  token: {{@ github_token @}}
22
- - .struct.yaml:
22
+ - .structkit.yaml:
23
23
  skip_if_exists: true
24
24
  content: |
25
25
  files:
structkit/filters.py CHANGED
@@ -12,31 +12,95 @@ from cachetools import TTLCache, cached
12
12
  cache = TTLCache(maxsize=100, ttl=600)
13
13
 
14
14
 
15
+ def _is_git_object_id(value):
16
+ return (
17
+ isinstance(value, str)
18
+ and re.fullmatch(r"(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})", value) is not None
19
+ )
20
+
21
+
22
+ def _resolve_commit_sha(repo, git_object, peel_tags=True, max_depth=10):
23
+ """Resolve a GitHub Git object to its commit object ID."""
24
+ seen = set()
25
+
26
+ for _ in range(max_depth):
27
+ object_type = getattr(git_object, "type", None)
28
+ sha = getattr(git_object, "sha", None)
29
+ if not isinstance(object_type, str) or not _is_git_object_id(sha):
30
+ raise ValueError("Malformed Git object")
31
+
32
+ if object_type == "commit":
33
+ return sha
34
+ if object_type != "tag" or not peel_tags or sha in seen:
35
+ raise ValueError("Git object does not resolve to a commit")
36
+
37
+ seen.add(sha)
38
+ git_tag = repo.get_git_tag(sha)
39
+ git_object = getattr(git_tag, "object", None)
40
+
41
+ raise ValueError("Annotated tag nesting limit exceeded")
42
+
43
+
44
+ def _resolve_tag_sha(repo, tag_name):
45
+ if not isinstance(tag_name, str) or not tag_name:
46
+ raise ValueError("Malformed release tag name")
47
+ git_ref = repo.get_git_ref(f"tags/{tag_name}")
48
+ return _resolve_commit_sha(repo, getattr(git_ref, "object", None))
49
+
50
+
51
+ def _resolve_branch_sha(repo, branch_name):
52
+ if not isinstance(branch_name, str) or not branch_name:
53
+ raise ValueError("Malformed default branch name")
54
+ git_ref = repo.get_git_ref(f"heads/{branch_name}")
55
+ return _resolve_commit_sha(repo, getattr(git_ref, "object", None), peel_tags=False)
56
+
57
+
15
58
  @cached(cache)
16
- def get_latest_release(repo_name):
17
- token = os.getenv('GITHUB_TOKEN')
59
+ def get_latest_release(repo_name, strip_v=False, return_sha=False):
60
+ token = os.getenv("GITHUB_TOKEN")
18
61
 
19
62
  # Use the token if available, otherwise proceed without authentication
20
63
  if token:
21
- g = Github(token)
64
+ g = Github(token)
22
65
  else:
23
- g = Github()
66
+ g = Github()
24
67
 
68
+ repo = None
25
69
  try:
26
- # Get the repository object
27
- repo = g.get_repo(repo_name)
28
- # Get the latest release
29
- latest_release = repo.get_latest_release()
30
- return latest_release.tag_name
70
+ # Get the repository object
71
+ repo = g.get_repo(repo_name)
72
+ # Get the latest release
73
+ latest_release = repo.get_latest_release()
31
74
  except Exception:
32
- # If an error occurs, return the default branch name
33
- try:
34
- default_branch = repo.default_branch
35
- return default_branch
36
- except Exception as e:
37
- print(f"Error getting default branch: {e}")
75
+ # If an error occurs, return the default branch name
76
+ try:
77
+ if repo is None:
78
+ raise ValueError("Repository lookup failed")
79
+ default_branch = repo.default_branch
80
+ if return_sha:
81
+ return _resolve_branch_sha(repo, default_branch)
82
+ return default_branch
83
+ except Exception as e:
84
+ print(f"Error getting default branch: {e}")
85
+ return "LATEST_RELEASE_ERROR"
86
+
87
+ try:
88
+ tag_name = getattr(latest_release, "tag_name", None)
89
+ except Exception:
90
+ return "LATEST_RELEASE_ERROR"
91
+ if not isinstance(tag_name, str) or not tag_name:
38
92
  return "LATEST_RELEASE_ERROR"
39
93
 
94
+ if return_sha:
95
+ try:
96
+ return _resolve_tag_sha(repo, tag_name)
97
+ except Exception:
98
+ return "LATEST_RELEASE_ERROR"
99
+
100
+ if strip_v and tag_name.startswith("v"):
101
+ return tag_name[1:]
102
+ return tag_name
103
+
40
104
 
41
105
  @cached(cache)
42
106
  def get_default_branch(repo_name):
structkit/main.py CHANGED
@@ -1,8 +1,10 @@
1
1
  import argparse
2
2
  import logging
3
3
  import os
4
+ import shlex
4
5
  from dotenv import load_dotenv
5
6
  from structkit.utils import read_config_file, merge_configs
7
+ from structkit.config import load_layered_config, apply_config_to_args
6
8
  from structkit.commands.generate import GenerateCommand
7
9
  from structkit.commands.info import InfoCommand
8
10
  from structkit.commands.vars import VarsCommand
@@ -15,6 +17,7 @@ from structkit.commands.graph import GraphCommand
15
17
  from structkit.commands.generate_schema import GenerateSchemaCommand
16
18
  from structkit.commands.mcp import MCPCommand
17
19
  from structkit.commands.sources import SourcesCommand
20
+ from structkit.commands.config import ConfigCommand
18
21
  from structkit.logging_config import configure_logging
19
22
 
20
23
  # Optional dependency: shtab for static shell completion generation
@@ -24,6 +27,94 @@ except Exception: # pragma: no cover - optional at runtime
24
27
  shtab = None
25
28
 
26
29
  load_dotenv()
30
+ SUPPORTED_COMPLETION_SHELLS = ("bash", "zsh", "tcsh", "fish")
31
+
32
+
33
+ def _fish_quote(value):
34
+ return shlex.quote(str(value))
35
+
36
+
37
+ def _fish_condition(command_path):
38
+ if not command_path:
39
+ return "__fish_structkit_using_command"
40
+ return "__fish_structkit_using_command " + " ".join(_fish_quote(command) for command in command_path)
41
+
42
+
43
+ def _fish_completion_script(parser):
44
+ """Generate a static Fish completion script from an argparse parser."""
45
+ lines = [
46
+ "function __fish_structkit_using_command",
47
+ " set -l words (commandline -opc)",
48
+ " set -e words[1]",
49
+ " set -l commands",
50
+ " for word in $words",
51
+ " if not string match -qr '^-' -- $word",
52
+ " set -a commands $word",
53
+ " end",
54
+ " end",
55
+ " test (count $commands) -eq (count $argv)",
56
+ " or return 1",
57
+ " for index in (seq (count $argv))",
58
+ " test \"$commands[$index]\" = \"$argv[$index]\"",
59
+ " or return 1",
60
+ " end",
61
+ "end",
62
+ "",
63
+ f"complete -c {_fish_quote(parser.prog)} -f",
64
+ ]
65
+
66
+ def add_completions(current_parser, command_path=()):
67
+ condition = _fish_condition(command_path)
68
+ for action in current_parser._actions:
69
+ if isinstance(action, argparse._SubParsersAction):
70
+ for name, subparser in action.choices.items():
71
+ if name not in action._name_parser_map:
72
+ continue
73
+ help_text = action._name_parser_map[name].description or ""
74
+ command = (
75
+ f"complete -c {_fish_quote(parser.prog)} -n {_fish_quote(condition)} "
76
+ f"-a {_fish_quote(name)}"
77
+ )
78
+ if help_text:
79
+ command += f" -d {_fish_quote(help_text)}"
80
+ lines.append(command)
81
+ add_completions(subparser, command_path + (name,))
82
+ continue
83
+
84
+ if action.help is argparse.SUPPRESS:
85
+ continue
86
+
87
+ choices = getattr(action, "choices", None)
88
+ arguments = ""
89
+ if choices:
90
+ arguments = " -a " + _fish_quote(" ".join(map(str, choices)))
91
+
92
+ for option in action.option_strings:
93
+ option_type = "-l" if option.startswith("--") else "-s"
94
+ command = (
95
+ f"complete -c {_fish_quote(parser.prog)} -n {_fish_quote(condition)} "
96
+ f"{option_type} {_fish_quote(option.lstrip('-'))}"
97
+ )
98
+ if action.nargs != 0:
99
+ command += " -r"
100
+ command += arguments
101
+ if action.help:
102
+ command += f" -d {_fish_quote(action.help)}"
103
+ lines.append(command)
104
+
105
+ add_completions(parser)
106
+ return "\n".join(lines)
107
+
108
+
109
+ class PrintCompletionAction(argparse.Action):
110
+ """Print a completion script for shtab-supported shells or Fish."""
111
+
112
+ def __call__(self, parser, namespace, values, option_string=None):
113
+ if values == "fish":
114
+ print(_fish_completion_script(parser))
115
+ else:
116
+ print(shtab.complete(parser, values))
117
+ parser.exit(0)
27
118
 
28
119
 
29
120
  def get_parser():
@@ -48,19 +139,24 @@ def get_parser():
48
139
  GenerateSchemaCommand(subparsers.add_parser('generate-schema', help='Generate JSON schema for available structures'))
49
140
  MCPCommand(subparsers.add_parser('mcp', help='MCP (Model Context Protocol) support'))
50
141
  SourcesCommand(subparsers.add_parser('sources', help='Manage named custom structure sources'))
142
+ ConfigCommand(subparsers.add_parser('config', help='Display and manage structkit configuration'))
51
143
 
52
- # init to create a basic .struct.yaml
144
+ # init to create a basic .structkit.yaml
53
145
  from structkit.commands.init import InitCommand
54
- InitCommand(subparsers.add_parser('init', help='Initialize a basic .struct.yaml in the target directory'))
146
+ InitCommand(subparsers.add_parser('init', help='Initialize a basic .structkit.yaml in the target directory'))
55
147
 
56
148
  # completion manager
57
149
  from structkit.commands.completion import CompletionCommand
58
150
  CompletionCommand(subparsers.add_parser('completion', help='Manage shell completions'))
59
151
 
60
- # Add shtab completion printing flags if available
152
+ # shtab supports bash, zsh, and tcsh. Fish is generated locally.
61
153
  if shtab is not None:
62
- # Adds --print-completion and --shell flags
63
- shtab.add_argument_to(parser)
154
+ parser.add_argument(
155
+ "--print-completion",
156
+ choices=SUPPORTED_COMPLETION_SHELLS,
157
+ action=PrintCompletionAction,
158
+ help="print shell completion script",
159
+ )
64
160
 
65
161
  return parser
66
162
 
@@ -75,9 +171,18 @@ def main():
75
171
  parser.print_help()
76
172
  parser.exit()
77
173
 
78
- # Read config file if provided
79
- if getattr(args, 'config_file', None):
80
- file_config = read_config_file(args.config_file)
174
+ # Load layered configuration (built-in defaults, user config, project config)
175
+ # This loads from ~/.config/struct/config.yaml and any --config-file
176
+ project_config_path = getattr(args, 'config_file', None)
177
+ layered_config = load_layered_config(project_config_path)
178
+
179
+ # Apply config to args (only for values not set via CLI)
180
+ apply_config_to_args(layered_config, args)
181
+
182
+ # For backward compatibility, also support the old merge_configs approach
183
+ # if config_file was explicitly provided
184
+ if project_config_path:
185
+ file_config = read_config_file(project_config_path)
81
186
  args = argparse.Namespace(**merge_configs(file_config, args))
82
187
 
83
188
  # Resolve logging level precedence: STRUCTKIT_LOG_LEVEL env > --debug (if present) > --log
structkit/mcp_server.py CHANGED
@@ -136,6 +136,7 @@ class StructMCPServer:
136
136
  mappings: Optional[Dict[str, str]] = None,
137
137
  structures_path: Optional[str] = None,
138
138
  source: Optional[str] = None,
139
+ no_hooks: bool = True,
139
140
  ) -> str:
140
141
  try:
141
142
  structures_path, structure_definition = resolve_structures_path(structures_path, source, structure_definition)
@@ -161,6 +162,8 @@ class StructMCPServer:
161
162
  args.log = "INFO"
162
163
  args.config_file = None
163
164
  args.log_file = None
165
+ args.no_hooks = no_hooks
166
+ args.hooks_allowlist = None
164
167
 
165
168
  # If mappings provided, convert to vars string consumed by GenerateCommand
166
169
  if mappings:
@@ -452,7 +455,7 @@ class StructMCPServer:
452
455
  self.logger.debug(f"MCP response: explain_structure len={len(result)} preview=\n{preview}")
453
456
  return result
454
457
 
455
- @self.app.tool(name="generate_structure", description="Generate a project structure using specified definition and options")
458
+ @self.app.tool(name="generate_structure", description="Generate a project structure using specified definition and options. MCP calls skip hooks by default for safety; set no_hooks=false to enable them.")
456
459
  async def generate_structure(
457
460
  structure_definition: str,
458
461
  base_path: str,
@@ -461,6 +464,7 @@ class StructMCPServer:
461
464
  mappings: Optional[Dict[str, str]] = None,
462
465
  structures_path: Optional[str] = None,
463
466
  source: Optional[str] = None,
467
+ no_hooks: bool = True,
464
468
  ) -> str:
465
469
  self.logger.debug(
466
470
  "MCP request: generate_structure args=%s",
@@ -472,6 +476,7 @@ class StructMCPServer:
472
476
  "mappings": mappings,
473
477
  "structures_path": structures_path,
474
478
  "source": source,
479
+ "no_hooks": no_hooks,
475
480
  },
476
481
  )
477
482
  result = self._generate_structure_logic(
@@ -482,6 +487,7 @@ class StructMCPServer:
482
487
  mappings,
483
488
  structures_path,
484
489
  source,
490
+ no_hooks,
485
491
  )
486
492
  preview = result if len(result) <= 1000 else result[:1000] + f"... [truncated {len(result)-1000} chars]"
487
493
  self.logger.debug(f"MCP response: generate_structure len={len(result)} preview=\n{preview}")
@@ -0,0 +1,113 @@
1
+ """Canonical and legacy project structure filenames.
2
+
3
+ The product was originally named STRUCT, so repositories commonly commit
4
+ ``.struct.yaml``. The canonical name is now ``.structkit.yaml``. Commands that
5
+ default to the project structure file prefer the canonical name and fall back
6
+ to the legacy name when it is the only one present.
7
+ """
8
+
9
+ import logging
10
+ import os
11
+ from typing import Optional, Tuple
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ CANONICAL_PROJECT_STRUCT_FILE = ".structkit.yaml"
16
+ LEGACY_PROJECT_STRUCT_FILE = ".struct.yaml"
17
+ PROJECT_STRUCT_FILES = (
18
+ CANONICAL_PROJECT_STRUCT_FILE,
19
+ LEGACY_PROJECT_STRUCT_FILE,
20
+ )
21
+
22
+
23
+ def strip_file_scheme(path: str) -> Tuple[str, bool]:
24
+ """Return (local_path, had_file_scheme) for a structure path."""
25
+ if path.startswith("file://"):
26
+ return path[7:], True
27
+ return path, False
28
+
29
+
30
+ def is_default_project_struct_path(path: Optional[str]) -> bool:
31
+ """Return True when path is omitted or names a default project file."""
32
+ if not path:
33
+ return True
34
+ local_path, _ = strip_file_scheme(path)
35
+ return os.path.basename(local_path) in PROJECT_STRUCT_FILES
36
+
37
+
38
+ def find_existing_project_struct_file(directory: str = ".") -> Optional[str]:
39
+ """Return the existing default project file in directory, if any.
40
+
41
+ Prefers ``.structkit.yaml`` over the legacy ``.struct.yaml``.
42
+ """
43
+ canonical = os.path.join(directory, CANONICAL_PROJECT_STRUCT_FILE)
44
+ if os.path.isfile(canonical):
45
+ return canonical
46
+
47
+ legacy = os.path.join(directory, LEGACY_PROJECT_STRUCT_FILE)
48
+ if os.path.isfile(legacy):
49
+ return legacy
50
+
51
+ return None
52
+
53
+
54
+ def resolve_project_struct_file(
55
+ explicit_path: Optional[str] = None,
56
+ directory: str = ".",
57
+ ) -> str:
58
+ """Resolve which project structure file a command should use.
59
+
60
+ Non-default paths (named structures, custom YAML files) are returned
61
+ unchanged. Default names prefer ``.structkit.yaml`` and fall back to
62
+ ``.struct.yaml`` when the canonical file is missing.
63
+
64
+ If neither default file exists, the canonical name is returned so error
65
+ messages mention ``.structkit.yaml``.
66
+ """
67
+ if explicit_path and not is_default_project_struct_path(explicit_path):
68
+ return explicit_path
69
+
70
+ file_scheme = False
71
+ search_dir = directory
72
+ if explicit_path:
73
+ local_path, file_scheme = strip_file_scheme(explicit_path)
74
+ parent = os.path.dirname(local_path)
75
+ if parent:
76
+ search_dir = parent
77
+ existing_path = local_path
78
+ else:
79
+ existing_path = os.path.join(directory, os.path.basename(local_path))
80
+ if os.path.isfile(existing_path):
81
+ return explicit_path
82
+
83
+ canonical = os.path.normpath(os.path.join(search_dir, CANONICAL_PROJECT_STRUCT_FILE))
84
+ legacy = os.path.normpath(os.path.join(search_dir, LEGACY_PROJECT_STRUCT_FILE))
85
+
86
+ if os.path.isfile(canonical):
87
+ if os.path.isfile(legacy):
88
+ logger.info(
89
+ "Both %s and %s exist; using %s. Rename or remove %s to avoid ambiguity.",
90
+ CANONICAL_PROJECT_STRUCT_FILE,
91
+ LEGACY_PROJECT_STRUCT_FILE,
92
+ CANONICAL_PROJECT_STRUCT_FILE,
93
+ LEGACY_PROJECT_STRUCT_FILE,
94
+ )
95
+ chosen = canonical
96
+ elif os.path.isfile(legacy):
97
+ logger.info(
98
+ "Using legacy %s; prefer renaming it to %s.",
99
+ LEGACY_PROJECT_STRUCT_FILE,
100
+ CANONICAL_PROJECT_STRUCT_FILE,
101
+ )
102
+ chosen = legacy
103
+ else:
104
+ chosen = canonical
105
+
106
+ if file_scheme:
107
+ return f"file://{chosen}"
108
+ if explicit_path and os.path.dirname(explicit_path) in ("", "."):
109
+ # Keep a bare filename when the caller passed one (argparse default).
110
+ return os.path.basename(chosen)
111
+ if explicit_path is None and search_dir in ("", "."):
112
+ return os.path.basename(chosen)
113
+ return chosen
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: structkit
3
- Version: 3.2.1
3
+ Version: 3.3.1
4
4
  Summary: YAML-first project scaffolding tool with remote content fetching, AI/MCP integration, and DevOps automation
5
5
  Author: httpdss
6
- License: MIT
6
+ License: Apache-2.0
7
7
  Project-URL: Homepage, https://structkit.app/
8
8
  Project-URL: Repository, https://github.com/httpdss/structkit
9
9
  Project-URL: Issues, https://github.com/httpdss/structkit/issues
@@ -14,7 +14,7 @@ Keywords: project-scaffolding,project-template,scaffolding,cookiecutter-alternat
14
14
  Classifier: Development Status :: 4 - Beta
15
15
  Classifier: Intended Audience :: Developers
16
16
  Classifier: Intended Audience :: System Administrators
17
- Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: License :: OSI Approved :: Apache Software License
18
18
  Classifier: Programming Language :: Python :: 3
19
19
  Classifier: Programming Language :: Python :: 3.8
20
20
  Classifier: Programming Language :: Python :: 3.9
@@ -37,6 +37,7 @@ Requires-Dist: jinja2>=3.1.0
37
37
  Requires-Dist: PyGithub>=1.58.0
38
38
  Requires-Dist: shtab>=1.6.0
39
39
  Requires-Dist: colorlog>=6.7.0
40
+ Requires-Dist: cachetools>=5.0
40
41
  Requires-Dist: pydantic-ai-slim[anthropic,google,openai]>=0.1.0
41
42
  Requires-Dist: fastmcp>=2.0.0
42
43
  Provides-Extra: s3
@@ -55,20 +56,22 @@ Requires-Dist: flake8>=4.0.0; extra == "dev"
55
56
  Requires-Dist: mypy>=0.990; extra == "dev"
56
57
  Dynamic: license-file
57
58
 
58
- # 🚀 StructKit: YAML-first scaffolding for teams and AI agents
59
+ # StructKit
59
60
 
60
- > Define project structures once in YAML, then generate consistent repos, CI files, docs, Terraform modules, and app layouts locally, in CI, or through an AI assistant via MCP.
61
+ YAML scaffolding your AI assistant can actually run.
62
+
63
+ Define a repo once (files, CI, Terraform, app layout). Generate it from the CLI, from CI, or through an assistant over MCP. When the org template on GitHub changes, the next generate picks it up. No golden repo. No separate Cookiecutter tree.
61
64
 
62
65
  [![codecov](https://codecov.io/github/httpdss/structkit/graph/badge.svg?token=JL5WIO1C9T)](https://codecov.io/github/httpdss/structkit)
63
66
  ![GitHub issues](https://img.shields.io/github/issues/httpdss/structkit)
64
67
  ![GitHub pull requests](https://img.shields.io/github/issues-pr/httpdss/structkit)
65
68
  ![GitHub stars](https://img.shields.io/github/stars/httpdss/structkit?style=social)
66
69
 
67
- **StructKit** replaces copy-pasted boilerplate and aging "golden repos" with reusable YAML structures. It can render template variables, fetch canonical files from remote sources, preview changes before writing, and expose your scaffolds to AI assistants through the Model Context Protocol.
70
+ > 🚀 **[Quick Start](docs/quickstart.md)** | 📚 **[Docs](docs/index.md)** | 🤖 **[MCP / AI Agent Guide](docs/mcp-integration.md)** | 💬 **[Discussions](https://github.com/httpdss/structkit/discussions)**
68
71
 
69
- > 🚀 **[Quick Start](docs/quickstart.md)** | 📚 **[Docs](docs/index.md)** | 🧩 **[Examples](examples/)** | 🤖 **[MCP / AI Agent Guide](docs/mcp-integration.md)** | 🧠 **[Agent Skills](docs/agent-skills.md)** | 💬 **[Discussions](https://github.com/httpdss/structkit/discussions)**
72
+ ⭐ If StructKit saves you time, please [star the repo](https://github.com/httpdss/structkit) — it helps others find it.
70
73
 
71
- ## ⚡ Try it in 60 seconds
74
+ ## Try it in 60 seconds
72
75
 
73
76
  ```bash
74
77
  # Install the CLI
@@ -79,6 +82,9 @@ structkit list
79
82
 
80
83
  # Generate a ready-made Terraform module scaffold
81
84
  structkit generate --vars module_name=my-terraform-module terraform/modules/generic ./my-terraform-module
85
+
86
+ # Start MCP server for AI integration
87
+ structkit mcp --server
82
88
  ```
83
89
 
84
90
  Prefer Docker?
@@ -88,6 +94,20 @@ docker run --rm -v "$(pwd):/workdir" ghcr.io/httpdss/structkit:main \
88
94
  generate --vars module_name=my-terraform-module terraform/modules/generic ./my-terraform-module
89
95
  ```
90
96
 
97
+ ## Ecosystem
98
+
99
+ These are install paths for [StructKit](https://github.com/httpdss/structkit), not separate products. Star this repo.
100
+
101
+ - [structkit-setup](https://github.com/httpdss/structkit-setup) — install StructKit on `PATH` in GitHub Actions (`httpdss/structkit-setup@v0`), then run any `structkit` command
102
+ - [GitHub Action](https://github.com/httpdss/structkit-action) — validate, generate, or drift-check in CI (`httpdss/structkit-setup@v0`, then `httpdss/structkit-action@v0`)
103
+ - [VS Code / Cursor](https://github.com/httpdss/vscode-structkit) — schema and autocomplete for `.structkit.yaml`
104
+ - [Agent skills](https://github.com/httpdss/structkit-skills) — inspect, preview, generate, validate from an assistant
105
+ - [pre-commit](https://github.com/httpdss/structkit-pre-commit) — validate structures before they land
106
+ - [Homebrew](https://github.com/httpdss/homebrew-structkit) — `brew install httpdss/structkit/structkit`
107
+ - Linux `.deb` / `.rpm` — download from [build-linux-packages](https://github.com/httpdss/structkit/actions/workflows/build-linux-packages.yaml) workflow artifacts (not attached to GitHub Releases), or build locally per [packaging/README.md](packaging/README.md)
108
+ - [Backstage](https://github.com/httpdss/backstage-plugin-structkit) — scaffolder actions for platform teams
109
+ - [Hermes plugin](https://github.com/httpdss/hermes-plugin-structkit) — safe StructKit tools inside Hermes
110
+
91
111
  ## 👤 Who StructKit is for
92
112
 
93
113
  - **Platform / DevEx teams** standardizing service layouts, CI baselines, and engineering conventions across many repos.
@@ -124,6 +144,8 @@ Project scaffolding tools exist in most ecosystems, but StructKit solves problem
124
144
  - **🌐 Remote Content** - Fetch files from GitHub, HTTP/HTTPS, S3, and Google Cloud Storage
125
145
  - **🛡️ Smart File Handling** - Multiple strategies for managing existing files (overwrite, skip, backup, etc.)
126
146
  - **🪝 Automation Hooks** - Pre and post-generation shell commands
147
+ - **🔒 Hook Safety** - Skip hooks (`--no-hooks` / `STRUCTKIT_NO_HOOKS`), confirm interactively, or restrict commands with an allowlist
148
+ - **⚙️ Config Layering** - Merge built-in defaults, `~/.config/struct/config.yaml`, optional `--config-file`, and CLI flags
127
149
  - **🎯 Dry Run Mode** - Preview changes before applying them
128
150
  - **✅ Validation & Schema** - Built-in YAML validation and IDE support
129
151
  - **🤖 MCP Integration** - Model Context Protocol support for AI-assisted development workflows
@@ -185,6 +207,7 @@ Our comprehensive documentation is organized into the following sections:
185
207
  - **[YAML Configuration](docs/configuration.md)** - Complete configuration reference
186
208
  - **[Template Variables](docs/template-variables.md)** - Dynamic content and Jinja2 features
187
209
  - **[File Handling](docs/file-handling.md)** - Managing files, permissions, and remote content
210
+ - **[Environment Variables](docs/environment-variables.md)** - `STRUCTKIT_*` defaults and overrides
188
211
  - **[Schema Reference](docs/schema.md)** - YAML validation and IDE support
189
212
 
190
213
  ### 🔧 Advanced Features
@@ -221,7 +244,7 @@ Our comprehensive documentation is organized into the following sections:
221
244
 
222
245
  ## 📜 License
223
246
 
224
- MIT License - see [LICENSE](LICENSE) for details.
247
+ Apache-2.0 License - see [LICENSE](LICENSE) for details.
225
248
 
226
249
  ## 💰 Support
227
250
 
@@ -1,26 +1,29 @@
1
1
  structkit/__init__.py,sha256=NUdm0byilRA0-t0KCBmbJJvVbeNyC0q-XuQyQX4wFnE,160
2
2
  structkit/completers.py,sha256=3kOzXygY3lno8RdJgM2ri3AH_koxzJOGmXYJsoUuMuk,2018
3
+ structkit/config.py,sha256=mojjd_6RY0gy01l0xAyAvUYZz_XzKjFjO0LTgjNmZtc,6410
3
4
  structkit/content_fetcher.py,sha256=5dgjv2J_9SIBgVvetYb12Vs_BN2MoD_gPdEXUcPTvsI,9609
4
5
  structkit/file_item.py,sha256=j0fogUoGk5PkUPrOadaXMKsyth-PZihx0awNgK0olkw,7336
5
- structkit/filters.py,sha256=FhImindlN-oMrwJI8CwolHkwViOOF--KGK6L3oOFwmg,2560
6
+ structkit/filters.py,sha256=AXbYxEM_pKHhJUeAuQyN1CGfNvfZHThc0j_XQCmLbvI,4796
6
7
  structkit/input_store.py,sha256=gd8_m15MMtyG_neKSRt4BFlpcU_jX7xZnFF5XAj1GR0,1702
7
8
  structkit/logging_config.py,sha256=lYRWf8PGZ1CKMeu0PCFPklXx2FHtgyKl1t6ZnIe46nQ,1071
8
- structkit/main.py,sha256=T9OFCPBn_RsU7Kj9w2kgA6ssQnJAfNYkwN4uPmJLDCU,4085
9
- structkit/mcp_server.py,sha256=qg8TXA2WezMg46kDpkgD0_WNCAHrgVf6rvXU2mXWXb8,30295
9
+ structkit/main.py,sha256=YpL7Ow6zjocrjtKfTHVzZ6YQ9_SQ5ENGoXCA3Gkf4Tg,8165
10
+ structkit/mcp_server.py,sha256=7K-LdJjEBkgV3rpm6PjFU7qe527P80eVSseTUA7_NDc,30578
10
11
  structkit/model_wrapper.py,sha256=3OhaB5bVyHoec7AJS_kLbcV1z2_aGJ7FHY1mdX9SZd8,2054
12
+ structkit/project_file.py,sha256=lZ4lZS9dnBemL7LewkPb6U2giW0TYfsXAhx8DHoFT9c,3890
11
13
  structkit/sources.py,sha256=UvZ2pPyUHIpFOrYJbZHzOi2g0oymWNzvkLPVGuxqsBc,13831
12
14
  structkit/struct_refs.py,sha256=VJixm6sx0ElGogbnwhcRcQhfvNjkdrUv2hMp8T5nAOc,5808
13
15
  structkit/template_renderer.py,sha256=4haUlbAoz_f8GmC8tU8HBYdFiSBDBT7Q_yiadEDOOmU,10441
14
16
  structkit/utils.py,sha256=3xCt3p91r7SRnmJB3ke1D6vszR30sdmH1K6LxxwWGG4,1238
15
17
  structkit/commands/__init__.py,sha256=SZqu6rM7TBOtPnAV6GPbSnt7awJ63DS5pHDmn6eEeYg,746
16
- structkit/commands/completion.py,sha256=VtGDb51px6VGK3NDnsYog_tb3V3SdIKDIR5TFUqZpjc,2750
18
+ structkit/commands/completion.py,sha256=fKB9Nao2sSWCDaA1i_L7m7rSC1JX-iCRZI1KjoLZ0lo,2648
19
+ structkit/commands/config.py,sha256=QR1wZnER5dGCp0YKk-qczpJfc_jsFgJZ_ytjCO-Qp1Y,3379
17
20
  structkit/commands/explain.py,sha256=P8zAZBw7oM3mwhTmH1ZGY3Nhq663fpGzaXXngPpvx0A,15562
18
- structkit/commands/generate.py,sha256=jN5Uj5xK-cbKrJCe479T31M8zoppR1pdLEREjCvfPLU,20875
21
+ structkit/commands/generate.py,sha256=WYd7K6gBDovPn0izw7NfogJhyCsbCNWjGasD1Kiy15k,25993
19
22
  structkit/commands/generate_schema.py,sha256=UIYvp46zb5l5ouQHA1Usxzt20r2QS5fgHOIQ26g8B_E,2657
20
23
  structkit/commands/graph.py,sha256=aA26oh5v3z9tddOURMAgERbmAKY29MB911vWpFuZKZA,11320
21
24
  structkit/commands/import.py,sha256=p4u5NJCwWwp7FKemAz7oQfT3Uu9uKxrCa3Q2wcG2Pqw,2483
22
25
  structkit/commands/info.py,sha256=ZBnOGBp4Y9ppiHJbW0RC9Whpu2A-czdB9kdpHbFuIHY,3528
23
- structkit/commands/init.py,sha256=lGJYjSLpjvBgAh0RYX6mQ_gb7C7_aDm23ARf-ZaqAro,1460
26
+ structkit/commands/init.py,sha256=N1nOAO7bTuaOQxfP3fWlAmE59kojxwgnNtFBkK2PrcM,2016
24
27
  structkit/commands/lint.py,sha256=3o9ovN9Ebnh6r0YTG6G9MIlXCU2hhpxzaDJwZ0lM7e4,14030
25
28
  structkit/commands/list.py,sha256=0KZ9VHPtkqSHLnEGN5-bH9YsIx0NxcbXFaw6MXQrRg4,3548
26
29
  structkit/commands/mcp.py,sha256=UE-yGmblGs0hCBc10qqZhkYEntT1544szyw3PzGyzRU,6072
@@ -28,13 +31,13 @@ structkit/commands/search.py,sha256=GNlvis4uE2X1FAEnOUCeiu3iGTLF6Yolx13lxJ4Wd1M,
28
31
  structkit/commands/sources.py,sha256=xsiwRya8HqsD4fWEN2cbqZLfx9ev3nMZ5DNOqvrJqqw,3422
29
32
  structkit/commands/validate.py,sha256=QGBrvOFOIOWRx01DT69tpQI5lTtlxDsgbmRYCavGDWU,7852
30
33
  structkit/commands/vars.py,sha256=6RasC2Hq1uZ-uyRQmqFow_ML3gqHIElV8jAO5VDkQWU,5249
31
- structkit/contribs/README.md,sha256=v7MYSB2RFufeWrPzvqXxQRTm9i4s_DU0rAU14Mdg9bo,13271
34
+ structkit/contribs/README.md,sha256=0aPaE1VTGZgmXoRJZpMP-qdEgkBMd2L5qwYC1dAWB-0,13277
32
35
  structkit/contribs/ansible-playbook.yaml,sha256=3yFjCExmSBi5t-BPROVnrrKVJEDgmb946Si8Mq78LvI,1088
33
36
  structkit/contribs/chef-cookbook.yaml,sha256=P2OQd63B6PHU6u3kuRi_sU7CVd4Jb_Le9rHzr-InPJw,1596
34
37
  structkit/contribs/ci-cd-pipelines.yaml,sha256=BaE9CjkTEAgadBUsly5Q5cSiJ2ULwQjnV7pvhb_fnWg,1933
35
38
  structkit/contribs/cloudformation-files.yaml,sha256=bGP6-zeMmvSjbr5EsvNXukmTQ840nif89rVeayFeoSk,855
36
39
  structkit/contribs/docker-files.yaml,sha256=EqzAyQ-m9OpvZFyMtrxMjYhZk51kFGYyKdeDSaUPc8o,752
37
- structkit/contribs/documentation-template.yaml,sha256=J5QKXosdEDLlhvIU37hkuNK3KlPIdX5xE1hCKmY7S7g,971
40
+ structkit/contribs/documentation-template.yaml,sha256=LVwOZOlyx7Ewu3He9r9Fgt_Sei15NysOVm0hnivRA0s,965
38
41
  structkit/contribs/git-hooks.yaml,sha256=SekIVw2khlKU4QWWcdfO_9ol1qtb_E1bj7b1dMQjtjw,647
39
42
  structkit/contribs/helm-chart.yaml,sha256=MQ96X_emkmvAuiHoT8MuC72wPBloKqe_NsP-rRVJZyM,5013
40
43
  structkit/contribs/kubernetes-manifests.yaml,sha256=nk3ZBzj1nOhGWGazXByBcFCD3bC8tsiEy7P6wjMfN3w,2896
@@ -53,13 +56,13 @@ structkit/contribs/github/instructions/generic.yaml,sha256=enF0mSUsmv_uSVbiD5c2j
53
56
  structkit/contribs/github/prompts/generic.yaml,sha256=L37Ez5fFdY2xUtnITJTnKJ8jZNMgvkds3kgIYd37s08,251
54
57
  structkit/contribs/github/prompts/react-form.yaml,sha256=xTPpO1pZ4AkTTnxcsOf5rJ3AYoHlWrGChCod5v4zX3U,936
55
58
  structkit/contribs/github/prompts/security-api.yaml,sha256=roJpIFJiwc0uPbDPKgR8clAJSCLAkqFb6oceWSdb2QI,517
56
- structkit/contribs/github/prompts/struct.yaml,sha256=QulKnqzlRm_fCfiXeFUGHTLymofYYr7IvD7A0VaqtUo,4539
59
+ structkit/contribs/github/prompts/struct.yaml,sha256=tW2wiF5cu7w_V8QinCcEDzjGXXdPisqO34j4XL1e73Q,4551
57
60
  structkit/contribs/github/workflows/codeql.yaml,sha256=NzUH2cHjgOwQBc3IDaKVFYPsfhVo151g6AOfTTIi8Ls,4648
58
61
  structkit/contribs/github/workflows/execute-tf-workflow.yaml,sha256=NRieIgePO9enk65kGOzLBZck7I-E974fhUbqY3Zuhxs,1464
59
62
  structkit/contribs/github/workflows/labeler.yaml,sha256=lpszSNFmaoFiXat-eAXEf-QHtg4B-3kpMNvcBaleF_U,2950
60
63
  structkit/contribs/github/workflows/pre-commit.yaml,sha256=feQtHcs8nwB57lJ5fcnDPtwLuQZo_YKNbOEpTZuco8g,1113
61
64
  structkit/contribs/github/workflows/release-drafter.yaml,sha256=hg9DicbqW_JdI3Z0CeC1fmvUWk-C6XN0lA1012QnsxM,2530
62
- structkit/contribs/github/workflows/run-struct.yaml,sha256=3AZRtNFLye5lqoBCMZ60Jis9AhSBF85XIJr_kFBasFU,912
65
+ structkit/contribs/github/workflows/run-struct.yaml,sha256=Kmiv3DaTRRzCyc8uj1W1_eX1kvS-FwM9KU-YxTgX8E0,921
63
66
  structkit/contribs/github/workflows/stale.yaml,sha256=aIsOOai99I3oGXNkPKTIduT87e-NfCLwagh2GQctIGI,747
64
67
  structkit/contribs/project/custom-structures.yaml,sha256=27EO-YFaVKi6I9p5eIqGy4V4n9YJFRwYQ4ETr8_0sNs,884
65
68
  structkit/contribs/project/generic.yaml,sha256=aymgJ1GRfCICtAMJGxQNJQvzjatandou-A4IS7ywDJY,9656
@@ -77,9 +80,9 @@ structkit/contribs/terraform/apps/generic.yaml,sha256=RClgHvjyeiHGkW3MqbMzuxPk4o
77
80
  structkit/contribs/terraform/apps/github-organization.yaml,sha256=-JJf691uoK286KllE6boWkDZhpK4Q_8ry26YXlqtav0,1155
78
81
  structkit/contribs/terraform/apps/init.yaml,sha256=BhZc4LqHfe_T1tmBmC-w_xGn5Ad2hhl0TdNhBJNEapM,489
79
82
  structkit/contribs/terraform/modules/generic.yaml,sha256=tflQFhe9RAUOwP4lGSd6_bKuFOkFswkNAyMVWTjuXBY,1787
80
- structkit-3.2.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
81
- structkit-3.2.1.dist-info/METADATA,sha256=NuwjRgic2U_l0DaoXKReog9s3eJ-yfCGtDwzT3py8Co,10579
82
- structkit-3.2.1.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
83
- structkit-3.2.1.dist-info/entry_points.txt,sha256=xJ-CjU6FUT2--cnTVqYIvHvvjihRQCZfel75L0iLvj8,50
84
- structkit-3.2.1.dist-info/top_level.txt,sha256=hXn8F2XQ9ZStiqI_jAcqJYUI9S362zBTzElR4rhOBbI,10
85
- structkit-3.2.1.dist-info/RECORD,,
83
+ structkit-3.3.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
84
+ structkit-3.3.1.dist-info/METADATA,sha256=rhxZBA1V1vAoGxEKq5H_54ENaSL8yk6XXtx59vZ0byU,12299
85
+ structkit-3.3.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
86
+ structkit-3.3.1.dist-info/entry_points.txt,sha256=xJ-CjU6FUT2--cnTVqYIvHvvjihRQCZfel75L0iLvj8,50
87
+ structkit-3.3.1.dist-info/top_level.txt,sha256=hXn8F2XQ9ZStiqI_jAcqJYUI9S362zBTzElR4rhOBbI,10
88
+ structkit-3.3.1.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (83.0.0)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5