structkit 3.2.0__tar.gz → 3.3.0__tar.gz

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 (127) hide show
  1. {structkit-3.2.0/structkit.egg-info → structkit-3.3.0}/PKG-INFO +22 -7
  2. {structkit-3.2.0 → structkit-3.3.0}/README.md +21 -6
  3. {structkit-3.2.0 → structkit-3.3.0}/pyproject.toml +1 -1
  4. {structkit-3.2.0 → structkit-3.3.0}/structkit/commands/completion.py +1 -3
  5. structkit-3.3.0/structkit/commands/config.py +82 -0
  6. {structkit-3.2.0 → structkit-3.3.0}/structkit/commands/generate.py +137 -4
  7. structkit-3.3.0/structkit/commands/init.py +66 -0
  8. structkit-3.3.0/structkit/config.py +202 -0
  9. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/README.md +2 -2
  10. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/github/prompts/struct.yaml +3 -3
  11. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/github/workflows/run-struct.yaml +3 -3
  12. {structkit-3.2.0 → structkit-3.3.0}/structkit/file_item.py +2 -0
  13. structkit-3.3.0/structkit/filters.py +181 -0
  14. structkit-3.3.0/structkit/main.py +205 -0
  15. {structkit-3.2.0 → structkit-3.3.0}/structkit/mcp_server.py +7 -1
  16. structkit-3.3.0/structkit/project_file.py +113 -0
  17. {structkit-3.2.0 → structkit-3.3.0/structkit.egg-info}/PKG-INFO +22 -7
  18. {structkit-3.2.0 → structkit-3.3.0}/structkit.egg-info/SOURCES.txt +6 -0
  19. {structkit-3.2.0 → structkit-3.3.0}/tests/test_commands.py +4 -1
  20. {structkit-3.2.0 → structkit-3.3.0}/tests/test_commands_more.py +1 -1
  21. {structkit-3.2.0 → structkit-3.3.0}/tests/test_completion_command.py +18 -0
  22. structkit-3.3.0/tests/test_config_command.py +213 -0
  23. structkit-3.3.0/tests/test_config_layering.py +297 -0
  24. {structkit-3.2.0 → structkit-3.3.0}/tests/test_file_item.py +29 -0
  25. {structkit-3.2.0 → structkit-3.3.0}/tests/test_filters.py +1 -0
  26. structkit-3.3.0/tests/test_filters_more.py +358 -0
  27. structkit-3.3.0/tests/test_hooks.py +287 -0
  28. {structkit-3.2.0 → structkit-3.3.0}/tests/test_init_command.py +5 -6
  29. structkit-3.3.0/tests/test_project_file.py +166 -0
  30. {structkit-3.2.0 → structkit-3.3.0}/tests/test_sources_command.py +2 -2
  31. structkit-3.2.0/structkit/commands/init.py +0 -53
  32. structkit-3.2.0/structkit/filters.py +0 -117
  33. structkit-3.2.0/structkit/main.py +0 -100
  34. structkit-3.2.0/tests/test_filters_more.py +0 -93
  35. structkit-3.2.0/tests/test_hooks.py +0 -69
  36. {structkit-3.2.0 → structkit-3.3.0}/LICENSE +0 -0
  37. {structkit-3.2.0 → structkit-3.3.0}/MANIFEST.in +0 -0
  38. {structkit-3.2.0 → structkit-3.3.0}/setup.cfg +0 -0
  39. {structkit-3.2.0 → structkit-3.3.0}/setup.py +0 -0
  40. {structkit-3.2.0 → structkit-3.3.0}/structkit/__init__.py +0 -0
  41. {structkit-3.2.0 → structkit-3.3.0}/structkit/commands/__init__.py +0 -0
  42. {structkit-3.2.0 → structkit-3.3.0}/structkit/commands/explain.py +0 -0
  43. {structkit-3.2.0 → structkit-3.3.0}/structkit/commands/generate_schema.py +0 -0
  44. {structkit-3.2.0 → structkit-3.3.0}/structkit/commands/graph.py +0 -0
  45. {structkit-3.2.0 → structkit-3.3.0}/structkit/commands/import.py +0 -0
  46. {structkit-3.2.0 → structkit-3.3.0}/structkit/commands/info.py +0 -0
  47. {structkit-3.2.0 → structkit-3.3.0}/structkit/commands/lint.py +0 -0
  48. {structkit-3.2.0 → structkit-3.3.0}/structkit/commands/list.py +0 -0
  49. {structkit-3.2.0 → structkit-3.3.0}/structkit/commands/mcp.py +0 -0
  50. {structkit-3.2.0 → structkit-3.3.0}/structkit/commands/search.py +0 -0
  51. {structkit-3.2.0 → structkit-3.3.0}/structkit/commands/sources.py +0 -0
  52. {structkit-3.2.0 → structkit-3.3.0}/structkit/commands/validate.py +0 -0
  53. {structkit-3.2.0 → structkit-3.3.0}/structkit/commands/vars.py +0 -0
  54. {structkit-3.2.0 → structkit-3.3.0}/structkit/completers.py +0 -0
  55. {structkit-3.2.0 → structkit-3.3.0}/structkit/content_fetcher.py +0 -0
  56. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/ansible-playbook.yaml +0 -0
  57. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/chef-cookbook.yaml +0 -0
  58. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/ci-cd-pipelines.yaml +0 -0
  59. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/cloudformation-files.yaml +0 -0
  60. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/configs/chglog.yaml +0 -0
  61. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/configs/codeowners.yaml +0 -0
  62. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/configs/devcontainer.yaml +0 -0
  63. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/configs/editor-config.yaml +0 -0
  64. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/configs/eslint.yaml +0 -0
  65. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/configs/jshint.yaml +0 -0
  66. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/configs/kubectl.yaml +0 -0
  67. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/configs/prettier.yaml +0 -0
  68. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/docker-files.yaml +0 -0
  69. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/documentation-template.yaml +0 -0
  70. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/git-hooks.yaml +0 -0
  71. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/github/chatmodes/plan.yaml +0 -0
  72. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/github/instructions/generic.yaml +0 -0
  73. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/github/prompts/generic.yaml +0 -0
  74. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/github/prompts/react-form.yaml +0 -0
  75. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/github/prompts/security-api.yaml +0 -0
  76. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/github/templates.yaml +0 -0
  77. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/github/workflows/codeql.yaml +0 -0
  78. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/github/workflows/execute-tf-workflow.yaml +0 -0
  79. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/github/workflows/labeler.yaml +0 -0
  80. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/github/workflows/pre-commit.yaml +0 -0
  81. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/github/workflows/release-drafter.yaml +0 -0
  82. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/github/workflows/stale.yaml +0 -0
  83. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/helm-chart.yaml +0 -0
  84. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/kubernetes-manifests.yaml +0 -0
  85. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/project/custom-structures.yaml +0 -0
  86. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/project/generic.yaml +0 -0
  87. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/project/go.yaml +0 -0
  88. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/project/java.yaml +0 -0
  89. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/project/n8n.yaml +0 -0
  90. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/project/nodejs.yaml +0 -0
  91. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/project/python.yaml +0 -0
  92. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/project/ruby.yaml +0 -0
  93. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/project/rust.yaml +0 -0
  94. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/prompts/run-struct-trigger.yaml +0 -0
  95. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/terraform/apps/aws-accounts.yaml +0 -0
  96. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/terraform/apps/environments.yaml +0 -0
  97. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/terraform/apps/generic.yaml +0 -0
  98. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/terraform/apps/github-organization.yaml +0 -0
  99. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/terraform/apps/init.yaml +0 -0
  100. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/terraform/modules/generic.yaml +0 -0
  101. {structkit-3.2.0 → structkit-3.3.0}/structkit/contribs/vagrant-files.yaml +0 -0
  102. {structkit-3.2.0 → structkit-3.3.0}/structkit/input_store.py +0 -0
  103. {structkit-3.2.0 → structkit-3.3.0}/structkit/logging_config.py +0 -0
  104. {structkit-3.2.0 → structkit-3.3.0}/structkit/model_wrapper.py +0 -0
  105. {structkit-3.2.0 → structkit-3.3.0}/structkit/sources.py +0 -0
  106. {structkit-3.2.0 → structkit-3.3.0}/structkit/struct_refs.py +0 -0
  107. {structkit-3.2.0 → structkit-3.3.0}/structkit/template_renderer.py +0 -0
  108. {structkit-3.2.0 → structkit-3.3.0}/structkit/utils.py +0 -0
  109. {structkit-3.2.0 → structkit-3.3.0}/structkit.egg-info/dependency_links.txt +0 -0
  110. {structkit-3.2.0 → structkit-3.3.0}/structkit.egg-info/entry_points.txt +0 -0
  111. {structkit-3.2.0 → structkit-3.3.0}/structkit.egg-info/requires.txt +0 -0
  112. {structkit-3.2.0 → structkit-3.3.0}/structkit.egg-info/top_level.txt +0 -0
  113. {structkit-3.2.0 → structkit-3.3.0}/tests/test_completers.py +0 -0
  114. {structkit-3.2.0 → structkit-3.3.0}/tests/test_content_fetcher_more.py +0 -0
  115. {structkit-3.2.0 → structkit-3.3.0}/tests/test_env_var_cli_args.py +0 -0
  116. {structkit-3.2.0 → structkit-3.3.0}/tests/test_env_var_structures_path.py +0 -0
  117. {structkit-3.2.0 → structkit-3.3.0}/tests/test_explain_command.py +0 -0
  118. {structkit-3.2.0 → structkit-3.3.0}/tests/test_file_item_strategies.py +0 -0
  119. {structkit-3.2.0 → structkit-3.3.0}/tests/test_graph_command.py +0 -0
  120. {structkit-3.2.0 → structkit-3.3.0}/tests/test_input_store.py +0 -0
  121. {structkit-3.2.0 → structkit-3.3.0}/tests/test_mcp_integration.py +0 -0
  122. {structkit-3.2.0 → structkit-3.3.0}/tests/test_messages_and_summary.py +0 -0
  123. {structkit-3.2.0 → structkit-3.3.0}/tests/test_model_wrapper.py +0 -0
  124. {structkit-3.2.0 → structkit-3.3.0}/tests/test_search_command.py +0 -0
  125. {structkit-3.2.0 → structkit-3.3.0}/tests/test_template_helpers.py +0 -0
  126. {structkit-3.2.0 → structkit-3.3.0}/tests/test_template_renderer.py +0 -0
  127. {structkit-3.2.0 → structkit-3.3.0}/tests/test_utils_more.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: structkit
3
- Version: 3.2.0
3
+ Version: 3.3.0
4
4
  Summary: YAML-first project scaffolding tool with remote content fetching, AI/MCP integration, and DevOps automation
5
5
  Author: httpdss
6
6
  License: MIT
@@ -55,20 +55,20 @@ Requires-Dist: flake8>=4.0.0; extra == "dev"
55
55
  Requires-Dist: mypy>=0.990; extra == "dev"
56
56
  Dynamic: license-file
57
57
 
58
- # 🚀 StructKit: YAML-first scaffolding for teams and AI agents
58
+ # StructKit
59
59
 
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.
60
+ YAML scaffolding your AI assistant can actually run.
61
+
62
+ 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
63
 
62
64
  [![codecov](https://codecov.io/github/httpdss/structkit/graph/badge.svg?token=JL5WIO1C9T)](https://codecov.io/github/httpdss/structkit)
63
65
  ![GitHub issues](https://img.shields.io/github/issues/httpdss/structkit)
64
66
  ![GitHub pull requests](https://img.shields.io/github/issues-pr/httpdss/structkit)
65
67
  ![GitHub stars](https://img.shields.io/github/stars/httpdss/structkit?style=social)
66
68
 
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.
68
-
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)**
69
+ > 🚀 **[Quick Start](docs/quickstart.md)** | 📚 **[Docs](docs/index.md)** | 🤖 **[MCP / AI Agent Guide](docs/mcp-integration.md)** | 💬 **[Discussions](https://github.com/httpdss/structkit/discussions)**
70
70
 
71
- ## ⚡ Try it in 60 seconds
71
+ ## Try it in 60 seconds
72
72
 
73
73
  ```bash
74
74
  # Install the CLI
@@ -79,6 +79,9 @@ structkit list
79
79
 
80
80
  # Generate a ready-made Terraform module scaffold
81
81
  structkit generate --vars module_name=my-terraform-module terraform/modules/generic ./my-terraform-module
82
+
83
+ # Start MCP server for AI integration
84
+ structkit mcp --server
82
85
  ```
83
86
 
84
87
  Prefer Docker?
@@ -88,6 +91,18 @@ docker run --rm -v "$(pwd):/workdir" ghcr.io/httpdss/structkit:main \
88
91
  generate --vars module_name=my-terraform-module terraform/modules/generic ./my-terraform-module
89
92
  ```
90
93
 
94
+ ## Ecosystem
95
+
96
+ These are install paths for [StructKit](https://github.com/httpdss/structkit), not separate products. Star this repo.
97
+
98
+ - [GitHub Action](https://github.com/httpdss/structkit-action) — validate, generate, or drift-check in CI
99
+ - [VS Code / Cursor](https://github.com/httpdss/vscode-structkit) — schema and autocomplete for `.structkit.yaml`
100
+ - [Agent skills](https://github.com/httpdss/structkit-skills) — inspect, preview, generate, validate from an assistant
101
+ - [pre-commit](https://github.com/httpdss/structkit-pre-commit) — validate structures before they land
102
+ - [Homebrew](https://github.com/httpdss/homebrew-structkit) — `brew tap httpdss/structkit && brew install structkit`
103
+ - [Backstage](https://github.com/httpdss/backstage-plugin-structkit) — scaffolder actions for platform teams
104
+ - [Hermes plugin](https://github.com/httpdss/hermes-plugin-structkit) — safe StructKit tools inside Hermes
105
+
91
106
  ## 👤 Who StructKit is for
92
107
 
93
108
  - **Platform / DevEx teams** standardizing service layouts, CI baselines, and engineering conventions across many repos.
@@ -1,17 +1,17 @@
1
- # 🚀 StructKit: YAML-first scaffolding for teams and AI agents
1
+ # StructKit
2
2
 
3
- > 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.
3
+ YAML scaffolding your AI assistant can actually run.
4
+
5
+ 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.
4
6
 
5
7
  [![codecov](https://codecov.io/github/httpdss/structkit/graph/badge.svg?token=JL5WIO1C9T)](https://codecov.io/github/httpdss/structkit)
6
8
  ![GitHub issues](https://img.shields.io/github/issues/httpdss/structkit)
7
9
  ![GitHub pull requests](https://img.shields.io/github/issues-pr/httpdss/structkit)
8
10
  ![GitHub stars](https://img.shields.io/github/stars/httpdss/structkit?style=social)
9
11
 
10
- **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.
11
-
12
- > 🚀 **[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)**
12
+ > 🚀 **[Quick Start](docs/quickstart.md)** | 📚 **[Docs](docs/index.md)** | 🤖 **[MCP / AI Agent Guide](docs/mcp-integration.md)** | 💬 **[Discussions](https://github.com/httpdss/structkit/discussions)**
13
13
 
14
- ## ⚡ Try it in 60 seconds
14
+ ## Try it in 60 seconds
15
15
 
16
16
  ```bash
17
17
  # Install the CLI
@@ -22,6 +22,9 @@ structkit list
22
22
 
23
23
  # Generate a ready-made Terraform module scaffold
24
24
  structkit generate --vars module_name=my-terraform-module terraform/modules/generic ./my-terraform-module
25
+
26
+ # Start MCP server for AI integration
27
+ structkit mcp --server
25
28
  ```
26
29
 
27
30
  Prefer Docker?
@@ -31,6 +34,18 @@ docker run --rm -v "$(pwd):/workdir" ghcr.io/httpdss/structkit:main \
31
34
  generate --vars module_name=my-terraform-module terraform/modules/generic ./my-terraform-module
32
35
  ```
33
36
 
37
+ ## Ecosystem
38
+
39
+ These are install paths for [StructKit](https://github.com/httpdss/structkit), not separate products. Star this repo.
40
+
41
+ - [GitHub Action](https://github.com/httpdss/structkit-action) — validate, generate, or drift-check in CI
42
+ - [VS Code / Cursor](https://github.com/httpdss/vscode-structkit) — schema and autocomplete for `.structkit.yaml`
43
+ - [Agent skills](https://github.com/httpdss/structkit-skills) — inspect, preview, generate, validate from an assistant
44
+ - [pre-commit](https://github.com/httpdss/structkit-pre-commit) — validate structures before they land
45
+ - [Homebrew](https://github.com/httpdss/homebrew-structkit) — `brew tap httpdss/structkit && brew install structkit`
46
+ - [Backstage](https://github.com/httpdss/backstage-plugin-structkit) — scaffolder actions for platform teams
47
+ - [Hermes plugin](https://github.com/httpdss/hermes-plugin-structkit) — safe StructKit tools inside Hermes
48
+
34
49
  ## 👤 Who StructKit is for
35
50
 
36
51
  - **Platform / DevEx teams** standardizing service layouts, CI baselines, and engineering conventions across many repos.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "structkit"
7
- version = "3.2.0"
7
+ version = "3.3.0"
8
8
  description = "YAML-first project scaffolding tool with remote content fetching, AI/MCP integration, and DevOps automation"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -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
 
@@ -0,0 +1,66 @@
1
+ from structkit.commands import Command
2
+ import os
3
+ import textwrap
4
+ from structkit.project_file import (
5
+ CANONICAL_PROJECT_STRUCT_FILE,
6
+ LEGACY_PROJECT_STRUCT_FILE,
7
+ )
8
+
9
+ BASIC_STRUCTKIT_YAML = textwrap.dedent(
10
+ """
11
+ # Generated by `structkit init`
12
+ # Edit as needed to customize your project bootstrap
13
+
14
+ pre_hooks:
15
+ - echo "Starting structkit generation"
16
+
17
+ post_hooks:
18
+ - echo "Structkit generation completed"
19
+
20
+ files:
21
+ - README.md: |
22
+ # Project
23
+
24
+ Initialized with structkit.
25
+
26
+ folders:
27
+ - ./:
28
+ struct:
29
+ - github/workflows/run-struct
30
+ """
31
+ ).lstrip()
32
+
33
+
34
+ class InitCommand(Command):
35
+ def __init__(self, parser):
36
+ super().__init__(parser)
37
+ parser.description = f"Initialize a basic {CANONICAL_PROJECT_STRUCT_FILE} in the target directory"
38
+ parser.add_argument('path', nargs='?', default='.', help='Directory to initialize (default: current directory)')
39
+ parser.set_defaults(func=self.execute)
40
+
41
+ def execute(self, args):
42
+ base_path = os.path.abspath(args.path or '.')
43
+ target = os.path.join(base_path, CANONICAL_PROJECT_STRUCT_FILE)
44
+ legacy = os.path.join(base_path, LEGACY_PROJECT_STRUCT_FILE)
45
+
46
+ os.makedirs(base_path, exist_ok=True)
47
+
48
+ # If either canonical or legacy file exists, do not overwrite.
49
+ if os.path.exists(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}.")
60
+ return
61
+
62
+ with open(target, 'w') as f:
63
+ f.write(BASIC_STRUCTKIT_YAML)
64
+
65
+ print(f"✅ Created {CANONICAL_PROJECT_STRUCT_FILE}")
66
+ print(f" - {target}")
@@ -0,0 +1,202 @@
1
+ """Configuration layering system for structkit.
2
+
3
+ Supports loading and merging configuration from multiple sources:
4
+ 1. Built-in defaults
5
+ 2. User config (~/.config/struct/config.yaml)
6
+ 3. Project config (.structkit.yaml, legacy .struct.yaml, or --config-file)
7
+ 4. CLI arguments
8
+
9
+ Priority order: CLI args > Project config > User config > Built-in defaults
10
+ """
11
+
12
+ import os
13
+ import yaml
14
+ from pathlib import Path
15
+ from typing import Dict, Any, Optional
16
+ import logging
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ def get_user_config_path() -> Path:
22
+ """Get the path to the user config file.
23
+
24
+ Returns ~/.config/struct/config.yaml
25
+ """
26
+ return Path.home() / ".config" / "struct" / "config.yaml"
27
+
28
+
29
+ def get_builtin_defaults() -> Dict[str, Any]:
30
+ """Return built-in default configuration values.
31
+
32
+ These are the lowest priority defaults used when no other config is provided.
33
+ """
34
+ return {
35
+ 'file_strategy': 'overwrite',
36
+ 'input_store': '/tmp/structkit/input.json',
37
+ 'log': 'INFO',
38
+ 'non_interactive': False,
39
+ 'output': 'file',
40
+ }
41
+
42
+
43
+ def load_yaml_config(config_path: str) -> Optional[Dict[str, Any]]:
44
+ """Load a YAML config file and return its contents.
45
+
46
+ Args:
47
+ config_path: Path to the YAML config file
48
+
49
+ Returns:
50
+ Dictionary with config values, or None if file doesn't exist or is empty
51
+ """
52
+ if not config_path or not os.path.exists(config_path):
53
+ return None
54
+
55
+ try:
56
+ with open(config_path, 'r') as f:
57
+ config = yaml.safe_load(f)
58
+ if config is None:
59
+ return {}
60
+ if not isinstance(config, dict):
61
+ logger.warning(f"Config file {config_path} does not contain a mapping, ignoring")
62
+ return {}
63
+ return config
64
+ except yaml.YAMLError as exc:
65
+ logger.warning(f"Failed to parse YAML in {config_path}: {exc}")
66
+ return {}
67
+ except OSError as exc:
68
+ logger.warning(f"Failed to read {config_path}: {exc}")
69
+ return {}
70
+
71
+
72
+ def merge_config_layer(base: Dict[str, Any], override: Optional[Dict[str, Any]]) -> Dict[str, Any]:
73
+ """Merge an override config layer into a base config.
74
+
75
+ Override values take precedence over base values. Only merges top-level keys.
76
+
77
+ Args:
78
+ base: Base configuration dictionary
79
+ override: Override configuration dictionary (can be None)
80
+
81
+ Returns:
82
+ Merged configuration dictionary
83
+ """
84
+ if override is None:
85
+ return base.copy()
86
+
87
+ result = base.copy()
88
+ for key, value in override.items():
89
+ if value is not None:
90
+ result[key] = value
91
+ return result
92
+
93
+
94
+ def load_layered_config(project_config_path: Optional[str] = None) -> Dict[str, Any]:
95
+ """Load configuration from all layers and merge them.
96
+
97
+ Merge order (lowest to highest priority):
98
+ 1. Built-in defaults
99
+ 2. User config (~/.config/struct/config.yaml)
100
+ 3. Project config (if provided)
101
+
102
+ Args:
103
+ project_config_path: Path to project-specific config file
104
+
105
+ Returns:
106
+ Merged configuration dictionary
107
+ """
108
+ # Start with built-in defaults
109
+ config = get_builtin_defaults()
110
+
111
+ # Layer in user config
112
+ user_config_path = get_user_config_path()
113
+ if user_config_path.exists():
114
+ logger.debug(f"Loading user config from {user_config_path}")
115
+ user_config = load_yaml_config(str(user_config_path))
116
+ config = merge_config_layer(config, user_config)
117
+
118
+ # Layer in project config
119
+ if project_config_path:
120
+ logger.debug(f"Loading project config from {project_config_path}")
121
+ project_config = load_yaml_config(project_config_path)
122
+ config = merge_config_layer(config, project_config)
123
+
124
+ return config
125
+
126
+
127
+ def merge_cli_args(config: Dict[str, Any], args) -> Dict[str, Any]:
128
+ """Merge CLI arguments into configuration, giving CLI args highest priority.
129
+
130
+ Args:
131
+ config: Configuration dictionary from layered config files
132
+ args: argparse Namespace with CLI arguments
133
+
134
+ Returns:
135
+ Final merged configuration dictionary
136
+ """
137
+ result = config.copy()
138
+ args_dict = vars(args)
139
+
140
+ # List of config keys that can be set via CLI args
141
+ # We only override config file values if the CLI arg was explicitly provided
142
+ # (i.e., it's not None and differs from the default)
143
+ cli_overridable_keys = [
144
+ 'structures_path',
145
+ 'input_store',
146
+ 'file_strategy',
147
+ 'backup',
148
+ 'global_system_prompt',
149
+ 'non_interactive',
150
+ 'output',
151
+ 'log',
152
+ 'log_file',
153
+ 'source',
154
+ ]
155
+
156
+ for key in cli_overridable_keys:
157
+ if key in args_dict and args_dict[key] is not None:
158
+ result[key] = args_dict[key]
159
+
160
+ return result
161
+
162
+
163
+ def apply_config_to_args(config: Dict[str, Any], args):
164
+ """Apply configuration values to argparse namespace.
165
+
166
+ This modifies the args namespace in place, setting values from the config
167
+ only if the arg was not explicitly set via CLI.
168
+
169
+ Args:
170
+ config: Configuration dictionary
171
+ args: argparse Namespace to update
172
+ """
173
+ args_dict = vars(args)
174
+
175
+ for key, value in config.items():
176
+ # Only set the value if the arg doesn't already have a non-None value
177
+ # This ensures CLI args take precedence
178
+ if key in args_dict and args_dict[key] is None:
179
+ args_dict[key] = value
180
+
181
+
182
+ def get_effective_config(args) -> Dict[str, Any]:
183
+ """Get the effective configuration by merging all layers including CLI args.
184
+
185
+ This is the final configuration that would be used after all merging is complete.
186
+
187
+ Args:
188
+ args: argparse Namespace with CLI arguments
189
+
190
+ Returns:
191
+ Effective configuration dictionary
192
+ """
193
+ # Get the project config file path from args if present
194
+ project_config_path = getattr(args, 'config_file', None)
195
+
196
+ # Load layered config from files
197
+ config = load_layered_config(project_config_path)
198
+
199
+ # Merge in CLI args (highest priority)
200
+ config = merge_cli_args(config, args)
201
+
202
+ return config