rgen-tool 0.1.0

rgen is a deterministic, language-agnostic code generation framework that treats software artifacts as projections of knowledge graphs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
# Rpack Development Guide

This guide covers creating, testing, and publishing rpacks to the rgen marketplace.

## Overview

Rpacks are versioned template collections that can be shared across the rgen community. They include:

- **Templates**: `.tmpl` files with YAML frontmatter
- **Macros**: Reusable template fragments (`.tera` files)
- **RDF Graphs**: Semantic models and SPARQL queries
- **Tests**: Golden tests for validation
- **Dependencies**: Other rpacks this rpack depends on

## Getting Started

### Initialize New Rpack

```bash
# Create new rpack
rgen pack init

# This creates:
# ├── rgen.toml          # Rpack manifest
# ├── templates/          # Template directory
# ├── macros/            # Macro directory
# ├── graphs/            # RDF graphs
# ├── tests/             # Test directory
# └── README.md          # Documentation
```

### Rpack Structure

```
my-rpack/
├── rgen.toml              # Rpack manifest
├── templates/             # Template files
│   └── cli/
│       └── subcommand/
│           ├── rust.tmpl
│           ├── graphs/         # Local RDF data
│           │   ├── cli.ttl
│           │   └── shapes/
│           │       └── cli.shacl.ttl
│           └── queries/        # Local SPARQL queries
│               └── commands.rq
├── macros/                # Reusable fragments
│   └── common.tera
├── tests/                 # Golden tests
│   └── test_hello.rs
├── README.md              # Documentation
└── .gitignore             # Git ignore file
```

## Rpack Manifest (`rgen.toml`)

### Basic Manifest

```toml
[rpack]
id = "io.rgen.rust.cli-subcommand"
name = "Rust CLI subcommand"
version = "0.1.0"
description = "Generate clap subcommands"
license = "MIT"
authors = ["Your Name <your.email@example.com>"]
repository = "https://github.com/your-org/your-rpack"
homepage = "https://github.com/your-org/your-rpack"
keywords = ["rust", "cli", "clap"]
rgen_compat = ">=0.2 <0.4"

[dependencies]
"io.rgen.macros.std" = "^0.2"

[templates]
entrypoints = ["cli/subcommand/rust.tmpl"]
includes   = ["macros/**/*.tera"]

[rdf]
base = "http://example.org/"
prefixes.ex = "http://example.org/"
files  = ["templates/**/graphs/*.ttl"]
inline = ["@prefix ex: <http://example.org/> . ex:Foo a ex:Type ."]
```

### Manifest Fields

#### Required Fields
- `id`: Unique identifier (reverse domain notation)
- `name`: Human-readable name
- `version`: Semantic version
- `description`: Brief description
- `license`: License identifier
- `rgen_compat`: Required rgen version range

#### Optional Fields
- `authors`: List of authors
- `repository`: Source repository URL
- `homepage`: Project homepage
- `keywords`: Search keywords
- `readme`: Path to README file
- `changelog`: Path to changelog file

## Template Development

### Template Structure

```yaml
---
to: "src/cmds/{{ name | snake_case }}.rs"
vars:
  name: "example"
  description: "Example command"
rdf:
  inline:
    - mediaType: text/turtle
      text: |
        @prefix cli: <urn:rgen:cli#> .
        [] a cli:Command ;
           cli:name "{{ name }}" ;
           cli:description "{{ description }}" .
sparql:
  vars:
    - name: slug
      query: |
        PREFIX cli: <urn:rgen:cli#>
        SELECT ?slug WHERE { ?c a cli:Command ; cli:name ?slug } LIMIT 1
determinism:
  seed: "{{ name }}"
---
// Generated by rpack: {{ rpack.id }}
// Template: {{ template.path }}

use clap::Parser;

#[derive(Parser)]
pub struct {{ name | pascal }}Args {
    /// {{ description }}
    #[arg(short, long)]
    pub verbose: bool,
}

pub fn {{ name | snake_case }}(args: {{ name | pascal }}Args) -> Result<(), Box<dyn std::error::Error>> {
    println!("{{ name | pascal }} command executed");
    if args.verbose {
        println!("Verbose mode enabled");
    }
    Ok(())
}
```

### Template Best Practices

1. **Use semantic variable names**: `name`, `description`, `version`
2. **Include RDF models**: Define semantic structure
3. **Add SPARQL queries**: Extract variables from graphs
4. **Include determinism**: Use seeds for reproducibility
5. **Add comments**: Document generated code
6. **Use filters**: Apply transformations (`| snake_case`, `| pascal`)

## Macro Development

### Creating Macros

```tera
{#- Common CLI argument structure #}
{% macro cli_args(name, description) %}
#[derive(Parser)]
pub struct {{ name | pascal }}Args {
    /// {{ description }}
    #[arg(short, long)]
    pub verbose: bool,
}
{% endmacro %}

{#- Common error handling #}
{% macro error_handling() %}
-> Result<(), Box<dyn std::error::Error>> {
    // Error handling logic
    Ok(())
}
{% endmacro %}
```

### Using Macros

```yaml
---
to: "src/cmds/{{ name }}.rs"
---
{% import "macros/common.tera" as common %}

{{ common::cli_args(name, description) }}

pub fn {{ name }}(args: {{ name | pascal }}Args) {{ common::error_handling() }}
```

## RDF Graph Development

### Graph Structure

```turtle
@prefix cli: <urn:rgen:cli#> .
@prefix ex: <http://example.org/> .
@base <http://example.org/> .

ex:Command a cli:Command ;
    cli:name "example" ;
    cli:description "Example command" ;
    cli:subcommands (
        ex:StatusCommand
        ex:ConfigCommand
    ) .

ex:StatusCommand a cli:Command ;
    cli:name "status" ;
    cli:description "Show status" .

ex:ConfigCommand a cli:Command ;
    cli:name "config" ;
    cli:description "Manage configuration" .
```

### SPARQL Queries

```sparql
PREFIX cli: <urn:rgen:cli#>
PREFIX ex: <http://example.org/>

# Extract command names
SELECT ?name WHERE {
    ?cmd a cli:Command ;
         cli:name ?name .
}

# Extract subcommands
SELECT ?parent ?child WHERE {
    ?parent a cli:Command ;
            cli:subcommands ?child .
    ?child a cli:Command .
}
```

## Testing

### Golden Tests

```rust
// tests/test_hello.rs
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_hello_command() {
        // Test generated code compiles
        let args = HelloArgs { verbose: false };
        let result = hello(args);
        assert!(result.is_ok());
    }
}
```

### Test Configuration

```toml
# rgen.toml
[tests]
golden = ["tests/*.rs"]
variables = [
    { name = "test1", description = "Test command 1" },
    { name = "test2", description = "Test command 2" }
]
```

### Running Tests

```bash
# Run all tests
rgen pack test

# Run specific test
rgen pack test --test test_hello

# Run with verbose output
rgen pack test --verbose
```

## Linting and Validation

### Lint Rpack

```bash
# Lint rpack for publishing
rgen pack lint

# Lint specific template
rgen pack lint --template templates/cli/subcommand/rust.tmpl

# Lint with fixes
rgen pack lint --fix
```

### Validation Checks

The linter checks for:

- **Manifest validity**: Correct `rgen.toml` structure
- **Template syntax**: Valid YAML frontmatter
- **RDF validity**: Well-formed RDF graphs
- **SPARQL syntax**: Valid SPARQL queries
- **Dependencies**: Resolvable dependencies
- **Versioning**: Semantic versioning compliance

## Publishing

### Prepare for Publishing

```bash
# Update version
# Edit rgen.toml:
# version = "0.2.0"

# Run tests
rgen pack test

# Lint rpack
rgen pack lint

# Generate changelog
rgen pack changelog
```

### Publish to Registry

```bash
# Publish rpack
rgen pack publish

# Publish with specific version
rgen pack publish --version 0.2.0

# Publish with dry run
rgen pack publish --dry-run
```

### Publishing Process

1. **Validation**: Rpack is validated against schema
2. **Testing**: Golden tests are run
3. **Linting**: Code quality checks
4. **Registry Upload**: Rpack is uploaded to registry
5. **Index Update**: Registry index is updated
6. **Notification**: Community is notified

## Versioning

### Semantic Versioning

Follow semantic versioning (semver):

- **Major** (1.0.0 → 2.0.0): Breaking changes
- **Minor** (1.0.0 → 1.1.0): New features
- **Patch** (1.0.0 → 1.0.1): Bug fixes

### Version Guidelines

- **0.x.x**: Development versions
- **1.x.x**: Stable versions
- **Pre-release**: Use `-alpha`, `-beta`, `-rc` suffixes

### Changelog

```markdown
# Changelog

## [0.2.0] - 2024-01-15

### Added
- New CLI subcommand template
- Support for verbose flag
- Error handling macros

### Changed
- Updated RDF model structure
- Improved SPARQL queries

### Fixed
- Template variable resolution
- Macro import issues

## [0.1.0] - 2024-01-01

### Added
- Initial release
- Basic CLI subcommand template
```

## Dependencies

### Adding Dependencies

```toml
# rgen.toml
[dependencies]
"io.rgen.macros.std" = "^0.2"
"io.rgen.common.rdf" = "~0.1.0"
"io.rgen.rust.cli" = ">=0.1.0 <0.3.0"
```

### Dependency Types

- **Caret (^)**: Compatible versions (^0.2.0 = >=0.2.0 <0.3.0)
- **Tilde (~)**: Patch-level changes (~0.1.0 = >=0.1.0 <0.2.0)
- **Exact**: Specific version (=0.2.1)
- **Range**: Version range (>=0.1.0 <0.3.0)

### Dependency Resolution

```bash
# Check dependencies
rgen pack deps

# Update dependencies
rgen pack update

# Resolve conflicts
rgen pack resolve
```

## Best Practices

### Rpack Design

1. **Single Responsibility**: One rpack, one purpose
2. **Consistent API**: Use standard variable names
3. **Documentation**: Include README and examples
4. **Testing**: Comprehensive golden tests
5. **Versioning**: Follow semver strictly

### Template Quality

1. **Readability**: Clear, well-commented code
2. **Maintainability**: Modular, reusable templates
3. **Performance**: Efficient SPARQL queries
4. **Security**: Validate all inputs
5. **Accessibility**: Follow language best practices

### Community Guidelines

1. **Naming**: Use descriptive, consistent names
2. **Licensing**: Choose appropriate licenses
3. **Contributing**: Welcome community contributions
4. **Support**: Provide issue tracking
5. **Updates**: Regular maintenance and updates

## Troubleshooting

### Common Issues

#### Template Not Found
```bash
# Check template path
rgen pack lint --template templates/cli/subcommand/rust.tmpl

# Verify entrypoints in manifest
cat rgen.toml | grep entrypoints
```

#### Dependency Conflicts
```bash
# Check dependency tree
rgen pack deps --tree

# Resolve conflicts
rgen pack resolve --force
```

#### RDF Validation Errors
```bash
# Validate RDF graphs
rgen pack lint --rdf-only

# Check SPARQL syntax
rgen pack lint --sparql-only
```

#### Test Failures
```bash
# Run tests with verbose output
rgen pack test --verbose

# Check test configuration
cat rgen.toml | grep -A 10 "\[tests\]"
```

### Getting Help

- **Documentation**: Check this guide and other docs
- **Community**: Join rgen community forums
- **Issues**: Report bugs and request features
- **Discussions**: Ask questions and share ideas

## Advanced Topics

### Custom Filters

```rust
// Add custom Tera filters
use tera::{Filter, Value, Result};

pub fn custom_filter(value: &Value, _: &HashMap<String, Value>) -> Result<Value> {
    // Custom filter logic
    Ok(value.clone())
}
```

### Plugin System

```toml
# rgen.toml
[plugins]
"io.rgen.plugin.custom" = "^0.1.0"
```

### CI/CD Integration

```yaml
# .github/workflows/publish.yml
name: Publish Rpack

on:
  push:
    tags:
      - 'v*'

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Install rgen
        run: cargo install rgen
      - name: Test rpack
        run: rgen pack test
      - name: Lint rpack
        run: rgen pack lint
      - name: Publish rpack
        run: rgen pack publish
        env:
          RGEN_REGISTRY_TOKEN: ${{ secrets.RGEN_REGISTRY_TOKEN }}
```

This guide provides comprehensive coverage of rpack development, from initial creation to publishing and maintenance. Follow these practices to create high-quality, maintainable rpacks for the rgen community.