unistructgen 0.2.2

A powerful Rust code generator
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
# 🚀 Quick Start Guide

Get up and running with UniStructGen in **5 minutes**.

## 📋 Table of Contents

1. [Installation]#-installation
2. [Your First Struct]#-your-first-struct
3. [External API Integration]#-external-api-integration
4. [Advanced Features]#-advanced-features
5. [CLI Usage]#-cli-usage
6. [Common Patterns]#-common-patterns
7. [Troubleshooting]#-troubleshooting
8. [Next Steps]#-next-steps

---

## 📦 Installation

### Option 1: Proc-Macro (Recommended)

Add to your `Cargo.toml`:

```toml
[dependencies]
unistructgen-macro = "0.1"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

# Optional but recommended
chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1.0", features = ["serde", "v4"] }
```

### Option 2: CLI Tool

```bash
cargo install unistructgen
```

### Option 3: Both

```bash
# Install CLI
cargo install unistructgen

# Add macro to Cargo.toml
# [dependencies]
# unistructgen-macro = "0.1"
```

---

## ⚡ Killer Example (60 Seconds)

```bash
cargo run -p killer-example
```

This single example shows:
- Compile-time type generation from JSON
- LLM tool schemas from Rust functions
- Safe, structured tool execution

See `examples/killer-example/README.md` for details.

---

## 🎯 Your First Struct

Let's start with the simplest example and build from there.

### Step 1: Basic JSON to Struct

Create a new file `src/main.rs`:

```rust
use unistructgen_macro::generate_struct_from_json;

// Define your struct from JSON
generate_struct_from_json! {
    name = "User",
    json = r#"{
        "id": 1,
        "name": "Alice",
        "email": "alice@example.com"
    }"#
}

fn main() {
    // Use the generated struct
    let user = User {
        id: 42,
        name: "Bob".to_string(),
        email: "bob@example.com".to_string(),
    };

    println!("User: {} <{}>", user.name, user.email);

    // Serialize to JSON
    let json = serde_json::to_string_pretty(&user).unwrap();
    println!("{}", json);
}
```

**Run it:**
```bash
cargo run
```

**Output:**
```
User: Bob <bob@example.com>
{
  "id": 42,
  "name": "Bob",
  "email": "bob@example.com"
}
```

### Step 2: Nested Objects

Let's add complexity with nested structures:

```rust
use unistructgen_macro::generate_struct_from_json;

generate_struct_from_json! {
    name = "Company",
    json = r#"{
        "name": "Acme Corp",
        "founded": 2020,
        "address": {
            "street": "123 Main St",
            "city": "New York",
            "zipCode": "10001"
        },
        "employees": [
            {
                "name": "John Doe",
                "position": "Engineer",
                "salary": 100000
            }
        ]
    }"#
}

fn main() {
    let company = Company {
        name: "TechCorp".to_string(),
        founded: 2024,
        address: Address {
            street: "456 Tech Ave".to_string(),
            city: "San Francisco".to_string(),
            zip_code: "94102".to_string(),
        },
        employees: vec![
            Employees {
                name: "Jane Smith".to_string(),
                position: "CTO".to_string(),
                salary: 200000,
            }
        ],
    };

    println!("Company: {}", company.name);
    println!("Location: {}, {}", company.address.city, company.address.zip_code);
    println!("Employees: {}", company.employees.len());
}
```

**What happened?**
- UniStructGen automatically created **three structs**: `Company`, `Address`, and `Employees`
- Field names converted: `zipCode``zip_code`
- Arrays inferred as `Vec<T>`
- All with serde derives by default

### Step 3: Smart Type Detection

UniStructGen detects special types automatically:

```rust
use unistructgen_macro::generate_struct_from_json;

generate_struct_from_json! {
    name = "Event",
    json = r#"{
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "title": "Conference",
        "startTime": "2024-06-15T09:00:00Z",
        "endTime": "2024-06-15T17:00:00Z",
        "attendees": 150
    }"#
}

fn main() {
    let event = Event {
        id: uuid::Uuid::new_v4(),  // ✨ Auto-detected as UUID
        title: "Rust Meetup".to_string(),
        start_time: chrono::Utc::now(),  // ✨ Auto-detected as DateTime
        end_time: chrono::Utc::now() + chrono::Duration::hours(2),
        attendees: 50,
    };

    println!("Event: {} (ID: {})", event.title, event.id);
    println!("Start: {}", event.start_time.format("%Y-%m-%d %H:%M"));
}
```

**Detected types:**
- ✅ UUID strings → `uuid::Uuid`
- ✅ ISO 8601 dates → `chrono::DateTime<Utc>`
- ✅ Integers → `i64` or `u64`
- ✅ Floats → `f64`
- ✅ Booleans → `bool`

---

## 🌐 External API Integration

The real power: generate structs from **live APIs** at compile time.

### Step 1: Basic API Call

```rust
use unistructgen_macro::struct_from_external_api;

// Fetch and generate at compile time
struct_from_external_api! {
    struct_name = "User",
    url_api = "https://jsonplaceholder.typicode.com/users/1"
}

fn main() {
    // Struct is ready to use!
    println!("User struct generated from live API");
}
```

**What happens:**
1. During compilation, UniStructGen makes an HTTP request
2. Receives the JSON response
3. Generates a fully-typed struct
4. No runtime overhead!

### Step 2: Array Responses

APIs often return arrays. We handle it automatically:

```rust
struct_from_external_api! {
    struct_name = "Todo",
    url_api = "https://jsonplaceholder.typicode.com/todos"
    // Returns: [{"userId": 1, "id": 1, "title": "...", "completed": false}, ...]
    // We automatically extract the first element!
}

fn main() {
    let todo = Todo {
        user_id: 1,
        id: 1,
        title: "Learn UniStructGen".to_string(),
        completed: true,
    };

    println!("Todo: {} ({})", todo.title,
             if todo.completed { "✓" } else { "○" });
}
```

### Step 3: Multiple APIs

Generate multiple structs from different endpoints:

```rust
use unistructgen_macro::struct_from_external_api;

// GitHub API
struct_from_external_api! {
    struct_name = "Repository",
    url_api = "https://api.github.com/repos/rust-lang/rust"
}

// JSONPlaceholder API
struct_from_external_api! {
    struct_name = "Post",
    url_api = "https://jsonplaceholder.typicode.com/posts/1"
}

// Another endpoint
struct_from_external_api! {
    struct_name = "Comment",
    url_api = "https://jsonplaceholder.typicode.com/comments/1"
}

fn main() {
    println!("Generated 3 structs from 3 different APIs!");
}
```

---

## ⚙️ Advanced Features

### Optional Fields

Make all fields `Option<T>`:

```rust
use unistructgen_macro::generate_struct_from_json;

generate_struct_from_json! {
    name = "User",
    json = r#"{"id": 1, "name": "Alice"}"#,
    optional = true  // All fields become Option<T>
}

fn main() {
    let user = User {
        id: Some(42),
        name: Some("Bob".to_string()),
    };

    // Or partial data
    let partial = User {
        id: Some(1),
        name: None,
    };

    println!("Full: {:?}", user);
    println!("Partial: {:?}", partial);
}
```

**Generated:**
```rust
pub struct User {
    pub id: Option<i64>,
    pub name: Option<String>,
}
```

### Default Derive

Add `Default` trait:

```rust
generate_struct_from_json! {
    name = "Config",
    json = r#"{"debug": false, "port": 8080}"#,
    default = true  // Adds #[derive(Default)]
}

fn main() {
    // Use default values
    let config = Config::default();
    println!("Default port: {}", config.port);
}
```

### Disable Serde

If you don't need serialization:

```rust
generate_struct_from_json! {
    name = "Data",
    json = r#"{"value": 42}"#,
    serde = false  // No serde derives
}
```

### Limit Nesting Depth

For deeply nested APIs:

```rust
struct_from_external_api! {
    struct_name = "DeepData",
    url_api = "https://api.example.com/deep",
    max_depth = 3  // Stop at 3 levels deep
}
```

### Request Timeout

Control API request timeout:

```rust
struct_from_external_api! {
    struct_name = "SlowApi",
    url_api = "https://slow-api.example.com/data",
    timeout = 10000  // 10 seconds (default: 30000ms)
}
```

### Combine Options

```rust
struct_from_external_api! {
    struct_name = "FullFeatured",
    url_api = "https://api.example.com/data",

    // All options
    timeout = 10000,
    max_depth = 5,
    optional = true,
    default = true,
    serde = true,
}
```

---

## 💻 CLI Usage

For build scripts, CI/CD, and pre-generation.

### Basic Usage

```bash
# Generate from file
unistructgen generate \
    --input examples/user.json \
    --name User \
    --output src/models/user.rs

# Generate to stdout
unistructgen generate -i schema.json -n Schema

# With options
unistructgen generate \
    -i data.json \
    -n Data \
    --serde true \
    --optional \
    --default
```

### Real-World Example

```bash
# Create a schema file
cat > product.json << EOF
{
  "id": "123e4567-e89b-12d3-a456-426614174000",
  "name": "Laptop",
  "price": 999.99,
  "inStock": true,
  "createdAt": "2024-01-15T10:30:00Z"
}
EOF

# Generate Rust code
unistructgen generate \
    --input product.json \
    --name Product \
    --output src/product.rs \
    --serde true

# Use in your code
cat > src/main.rs << 'EOF'
mod product;
use product::Product;

fn main() {
    let p = Product {
        id: uuid::Uuid::new_v4(),
        name: "Mouse".to_string(),
        price: 29.99,
        in_stock: true,
        created_at: chrono::Utc::now(),
    };
    println!("{:?}", p);
}
EOF

cargo run
```

### Pipeline Integration

```bash
# Fetch from API and generate
curl -o schema.json https://api.example.com/schema.json
unistructgen generate --input schema.json --name ApiSchema --output src/api_schema.rs

# In CI/CD (GitHub Actions example)
- name: Generate structs
  run: |
    cargo install unistructgen
    unistructgen generate -i schema.json -n Schema -o src/schema.rs

- name: Commit generated code
  run: |
    git add src/schema.rs
    git commit -m "Update generated schemas"
```

---

## 📚 Common Patterns

### Compile-Time Fetch Controls

For macros that fetch remote content at compile time (`struct_from_external_api!`, `openapi_to_rust!` with `url`, `env_file` over HTTP), you can control networking behavior:

- `UNISTRUCTGEN_FETCH_OFFLINE=1` — disable network access (cache only)
- `UNISTRUCTGEN_FETCH_CACHE=0` — disable caching
- `UNISTRUCTGEN_FETCH_CACHE_DIR=/path` — custom cache directory
- `UNISTRUCTGEN_FETCH_TIMEOUT_MS=60000` — override timeout (ms)

### Pattern 1: Configuration Files

```rust
use unistructgen_macro::json_struct;
use std::fs;

#[json_struct(name = "AppConfig")]
const CONFIG_SCHEMA: &str = r#"{
    "server": {
        "host": "localhost",
        "port": 8080,
        "tls": false
    },
    "database": {
        "url": "postgres://localhost/mydb",
        "poolSize": 10
    },
    "logging": {
        "level": "info",
        "format": "json"
    }
}"#;

fn main() {
    // Read config file
    let config_str = fs::read_to_string("config.json").unwrap();
    let config: AppConfig = serde_json::from_str(&config_str).unwrap();

    println!("Server: {}:{}", config.server.host, config.server.port);
    println!("Database pool: {}", config.database.pool_size);
    println!("Log level: {}", config.logging.level);
}
```

### Pattern 2: API Response Handler

```rust
use unistructgen_macro::struct_from_external_api;

struct_from_external_api! {
    struct_name = "GithubRepo",
    url_api = "https://api.github.com/repos/rust-lang/rust"
}

async fn fetch_repo(owner: &str, repo: &str) -> Result<GithubRepo, Box<dyn std::error::Error>> {
    let url = format!("https://api.github.com/repos/{}/{}", owner, repo);
    let response = reqwest::get(&url).await?;
    let repo: GithubRepo = response.json().await?;
    Ok(repo)
}

#[tokio::main]
async fn main() {
    let repo = fetch_repo("rust-lang", "rust").await.unwrap();
    println!("⭐ Stars: {}", repo.stargazers_count);
    println!("🍴 Forks: {}", repo.forks_count);
}
```

### Pattern 3: Multi-File Organization

```rust
// src/models/mod.rs
pub mod user;
pub mod post;
pub mod comment;

// src/models/user.rs
use unistructgen_macro::struct_from_external_api;

struct_from_external_api! {
    struct_name = "User",
    url_api = "https://jsonplaceholder.typicode.com/users/1"
}

// src/models/post.rs
use unistructgen_macro::struct_from_external_api;

struct_from_external_api! {
    struct_name = "Post",
    url_api = "https://jsonplaceholder.typicode.com/posts/1"
}

// src/main.rs
mod models;
use models::{user::User, post::Post};

fn main() {
    // Use both types
}
```

### Pattern 4: Test Fixtures

```rust
#[cfg(test)]
mod tests {
    use unistructgen_macro::generate_struct_from_json;

    generate_struct_from_json! {
        name = "TestUser",
        json = r#"{
            "id": 1,
            "name": "Test User",
            "email": "test@example.com"
        }"#
    }

    #[test]
    fn test_user_creation() {
        let user = TestUser {
            id: 1,
            name: "Alice".to_string(),
            email: "alice@test.com".to_string(),
        };

        assert_eq!(user.id, 1);
        assert_eq!(user.name, "Alice");
    }
}
```

---

## 🔧 Troubleshooting

### Issue: "Failed to fetch from API"

**Problem:** Network error during compilation

**Solution:**
```rust
// Check your internet connection
// Increase timeout
struct_from_external_api! {
    struct_name = "Data",
    url_api = "https://api.example.com/data",
    timeout = 60000  // 60 seconds
}
```

### Issue: "Invalid JSON structure: expected object, found array"

**Problem:** API returns an array but you're treating it as object

**Solution:** This should work automatically now, but if not:
```rust
// Arrays are auto-detected and first element is extracted
struct_from_external_api! {
    struct_name = "Item",
    url_api = "https://api.example.com/items"  // Returns [...]
}
// This works! We extract the first element
```

### Issue: Compilation is slow

**Problem:** Multiple API calls during compilation

**Solution:**
```rust
// Option 1: Use CLI to pre-generate
// unistructgen generate -i schema.json -o models.rs

// Option 2: Cache responses
// Option 3: Use inline JSON in dev, API in release
#[cfg(debug_assertions)]
generate_struct_from_json! {
    name = "User",
    json = r#"{"id": 1, "name": "Dev"}"#
}

#[cfg(not(debug_assertions))]
struct_from_external_api! {
    struct_name = "User",
    url_api = "https://api.example.com/user"
}
```

### Issue: Field names conflict with Rust keywords

**Problem:** JSON has field named `type`, `impl`, etc.

**Solution:** Automatic!
```rust
// JSON: {"type": "user"}
// Generated:
pub struct Data {
    pub type_: String,  // Automatically appends _
}
```

### Issue: Need custom derives

**Problem:** Want `PartialOrd`, `Eq`, etc.

**Solution:**
```rust
use unistructgen_macro::generate_struct_from_json;

generate_struct_from_json! {
    name = "User",
    json = r#"{"id": 1, "name": "Alice"}"#
}

// Add custom derives after generation
#[derive(PartialOrd, Ord, Eq)]
struct UserWrapper(User);
```

---

## 🎯 Next Steps

Congratulations! You now know the essentials of UniStructGen.

### Learn More

1. **[Complete Examples]EXAMPLES.md** - See real-world usage patterns
2. **[External API Guide]docs/EXTERNAL_API_GUIDE.md** - Advanced API integration
3. **[API Documentation]https://docs.rs/unistructgen** - Full reference
4. **[Architecture]docs/ARCHITECTURE.md** - How it works internally

### Build Something

Try these projects:

1. **Weather App**
   ```rust
   struct_from_external_api! {
       struct_name = "Weather",
       url_api = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_KEY"
   }
   ```

2. **GitHub Stats**
   ```rust
   struct_from_external_api! {
       struct_name = "GitHubUser",
       url_api = "https://api.github.com/users/yourusername"
   }
   ```

3. **REST API Client**
   - Use UniStructGen to generate all your API models
   - Build a fully-typed client
   - Never worry about API changes

### Join the Community

- [Star us on GitHub]https://github.com/maxBogovick/unistructgen
- 💬 [Join Discussions]https://github.com/maxBogovick/unistructgen/discussions
- 🐛 [Report Issues]https://github.com/maxBogovick/unistructgen/issues
- 📝 [Contribute]CONTRIBUTING.md

---

## 🤔 FAQ

**Q: Can I use this in production?**
A: Yes! All code generation happens at compile time. Zero runtime cost.

**Q: What if the API changes?**
A: Just recompile. The struct will be regenerated from the latest API response.

**Q: Does it work with private APIs?**
A: Yes, but the API must be accessible during compilation. For private APIs with auth, use the CLI with environment variables.

**Q: Can I modify generated code?**
A: Yes! Either edit the generated output (if using CLI) or create wrapper types.

**Q: What about GraphQL?**
A: Coming soon! For now, you can use the JSON response from a GraphQL query.

**Q: Does it work offline?**
A: `generate_struct_from_json!` works offline. `struct_from_external_api!` needs network during compilation.

---

<div align="center">

**Ready to build?** [Back to README](README.md) • [See Examples](EXAMPLES.md) • [Read Docs](https://docs.rs/unistructgen)

Made with 🦀 and ❤️ for Rust developers.

</div>