Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion README.es.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ struct structure.yaml .
Ejecuta el script con el siguiente comando usando uno de los siguientes subcomandos:

- `generate`: Genera la estructura del proyecto basada en la configuración YAML.
- `generate-schema`: Genera esquema JSON para las plantillas de estructura disponibles.
- `validate`: Valida la configuración YAML para asegurarte de que sea válida.
- `info`: Muestra información sobre el script y sus dependencias.
- `list`: Lista las estructuras disponibles.
Expand Down Expand Up @@ -133,6 +134,37 @@ struct generate \

```

### Comando Generate Schema

El comando `generate-schema` crea definiciones de esquema JSON para las plantillas de estructura disponibles, facilitando que las herramientas e IDEs proporcionen autocompletado y validación.

#### Uso Básico

```sh
# Generar esquema a stdout
struct generate-schema

# Generar esquema con ruta de estructuras personalizada
struct generate-schema -s /ruta/a/estructuras/personalizadas

# Guardar esquema en archivo
struct generate-schema -o schema.json

# Combinar ruta personalizada y archivo de salida
struct generate-schema -s /ruta/a/estructuras/personalizadas -o schema.json
```

#### Opciones del Comando

- `-s, --structures-path`: Ruta a definiciones de estructura adicionales (opcional)
- `-o, --output`: Ruta del archivo de salida para el esquema (predeterminado: stdout)

El esquema generado incluye todas las estructuras disponibles tanto del directorio contribs integrado como de cualquier ruta de estructuras personalizada que especifiques. Esto es útil para:

- Autocompletado IDE al escribir archivos `.struct.yaml`
- Validación de referencias de estructura en tus configuraciones
- Descubrimiento programático de plantillas disponibles

## 📄 Configuración YAML

Aquí tienes un ejemplo de un archivo de configuración YAML:
Expand Down Expand Up @@ -402,7 +434,7 @@ Puedes referenciar valores del mapping en tus plantillas usando la variable `map

Esto se renderizará como:

```
```text
987654321
```

Expand Down
34 changes: 33 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ struct generate structure.yaml .
Run the script with the following command using one of the following subcommands:

- `generate`: Generate the project structure based on the YAML configuration.
- `generate-schema`: Generate JSON schema for available structure templates.
- `validate`: Validate the YAML configuration file.
- `info`: Display information about the script and its dependencies.
- `list`: List the available structs
Expand Down Expand Up @@ -128,6 +129,37 @@ struct generate \
./my-terraform-module
```

### Generate Schema Command

The `generate-schema` command creates JSON schema definitions for available structure templates, making it easier for tools and IDEs to provide autocompletion and validation.

#### Basic Usage

```sh
# Generate schema to stdout
struct generate-schema

# Generate schema with custom structures path
struct generate-schema -s /path/to/custom/structures

# Save schema to file
struct generate-schema -o schema.json

# Combine custom path and output file
struct generate-schema -s /path/to/custom/structures -o schema.json
```

#### Command Options

- `-s, --structures-path`: Path to additional structure definitions (optional)
- `-o, --output`: Output file path for the schema (default: stdout)

The generated schema includes all available structures from both the built-in contribs directory and any custom structures path you specify. This is useful for:

- IDE autocompletion when writing `.struct.yaml` files
- Validation of structure references in your configurations
- Programmatic discovery of available templates

## 📝 YAML Configuration

### Configuration Properties
Expand Down Expand Up @@ -471,7 +503,7 @@ You can reference mapping values in your templates using the `mappings` variable

This will render as:

```
```text
987654321
```

Expand Down
66 changes: 66 additions & 0 deletions struct_module/commands/generate_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from struct_module.commands import Command
import os
import json

# Generate Schema command class
class GenerateSchemaCommand(Command):
def __init__(self, parser):
super().__init__(parser)
parser.add_argument('-s', '--structures-path', type=str, help='Path to structure definitions')
parser.add_argument('-o', '--output', type=str, help='Output file path for the schema (default: stdout)')
parser.set_defaults(func=self.execute)

def execute(self, args):
self.logger.info("Generating JSON schema for available structures")
self._generate_schema(args)

def _generate_schema(self, args):
# Get the path to contribs directory (built-in structures)
this_file = os.path.dirname(os.path.realpath(__file__))
contribs_path = os.path.join(this_file, "..", "contribs")

# Determine paths to scan
if args.structures_path:
final_path = args.structures_path
paths_to_list = [final_path, contribs_path]
else:
paths_to_list = [contribs_path]

# Collect all available structures
all_structures = set()
for path in paths_to_list:
if os.path.exists(path):
for root, _, files in os.walk(path):
for file in files:
if file.endswith(".yaml"):
file_path = os.path.join(root, file)
rel_path = os.path.relpath(file_path, path)
# Remove .yaml extension
rel_path = rel_path[:-5]
all_structures.add(rel_path)

# Create JSON schema
schema = {
"definitions": {
"PluginList": {
"enum": sorted(list(all_structures))
}
}
}

# Convert to JSON string
json_output = json.dumps(schema, indent=2)

# Output to file or stdout
if args.output:
# Create output directory if it doesn't exist
output_dir = os.path.dirname(args.output)
if output_dir and not os.path.exists(output_dir):
os.makedirs(output_dir)

with open(args.output, 'w') as f:
f.write(json_output)
self.logger.info(f"Schema written to {args.output}")
print(f"✅ Schema successfully generated at: {args.output}")
else:
print(json_output)
2 changes: 2 additions & 0 deletions struct_module/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from struct_module.commands.info import InfoCommand
from struct_module.commands.validate import ValidateCommand
from struct_module.commands.list import ListCommand
from struct_module.commands.generate_schema import GenerateSchemaCommand
from struct_module.logging_config import configure_logging


Expand All @@ -26,6 +27,7 @@ def main():
ValidateCommand(subparsers.add_parser('validate', help='Validate the YAML configuration file'))
GenerateCommand(subparsers.add_parser('generate', help='Generate the project structure'))
ListCommand(subparsers.add_parser('list', help='List available structures'))
GenerateSchemaCommand(subparsers.add_parser('generate-schema', help='Generate JSON schema for available structures'))

argcomplete.autocomplete(parser)

Expand Down
Loading
Loading