jkconfig 0.2.2

A Ratatui-based TUI component library for JSON Schema configuration
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
# JKConfig

[![Crates.io](https://img.shields.io/crates/v/jkconfig.svg)](https://crates.io/crates/jkconfig)
[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)](https://github.com/ZR233/ostool)

A beautiful Terminal User Interface (TUI) configuration editor powered by JSON Schema. JKConfig automatically generates interactive forms from JSON Schema definitions, making configuration management intuitive and error-free.

![JKConfig Main Interface](docs/image.png)

> **Define your config in Rust → Generate JSON Schema → Edit with beautiful TUI**

```
┌─────────────────┐      ┌──────────────────┐      ┌─────────────────┐
│  Rust Structs   │      │  JSON Schema     │      │   Beautiful     │
│  + schemars     │ ──▶  │  (Auto-gen)      │ ──▶  │   TUI Editor    │
│  (#[derive])    │      │  config.schema   │      │   (jkconfig)    │
└─────────────────┘      └──────────────────┘      └─────────────────┘
         │                                                    │
         │                                                    ▼
         │                                          ┌─────────────────┐
         └──────────────────────────────────────▶  │  Config File    │
                     Load & Use                     │  .toml / .json  │
                                                    └─────────────────┘
```

## ✨ Features

- 🎨 **Beautiful TUI Interface** - Modern, responsive terminal UI built with [Ratatui]https://github.com/ratatui/ratatui
- 📋 **JSON Schema Driven** - Automatically generates UI from JSON Schema (Draft 2020-12)
- 🔧 **Multiple Data Types** - Support for String, Integer, Number, Boolean, Enum, Array, Object, and OneOf
- 💾 **Multi-Format Support** - Read/write TOML and JSON configuration files
- ⌨️ **Keyboard Shortcuts** - Efficient navigation with Vim-like keybindings
- 🎯 **Type Validation** - Real-time validation based on schema constraints
- 🔄 **Auto Backup** - Automatic backup before saving changes
- 📚 **Nested Structures** - Handle complex nested objects and arrays
- 🌈 **Color-Coded UI** - Visual indicators for different data types and states

## 🤔 Why JKConfig?

### Traditional Approach
```rust
// ❌ Manual config editing - error prone
// Edit raw TOML/JSON → Easy to make mistakes → Runtime errors
```

### JKConfig Approach
```rust
// ✅ Type-safe from Rust to UI
// Define in Rust → Generate Schema → Edit with TUI → Load with confidence
```

**Benefits:**
- 🛡️ **Type Safety**: Your Rust types define the schema, ensuring consistency
- 🎨 **User Friendly**: Non-developers can edit configs with a beautiful interface
-**Fast**: No more hunting through docs to understand config structure
- 🔍 **Discoverable**: Built-in help and descriptions for every field
- 🚀 **Productive**: Keyboard shortcuts for power users

Perfect for:
- 🔧 CLI tools that need user configuration
- 🏗️ Build systems (like ostool!)
- 🎮 Game server configurations
- 🔌 Plugin systems
- 📦 Any Rust project with complex configuration needs

## 📦 Installation

### From Crates.io

```bash
cargo install jkconfig
```

### From Source

```bash
git clone https://github.com/ZR233/ostool.git
cd ostool/jkconfig
cargo build --release
```

## 🚀 Quick Start

The recommended workflow is to define your configuration structure in Rust and generate the JSON Schema automatically.

### 1. Define Your Config Structure in Rust

Add dependencies to your `Cargo.toml`:

```toml
[dependencies]
serde = { version = "1.0", features = ["derive"] }
schemars = { version = "1.0", features = ["derive"] }
```

Create your configuration structure:

```rust
use schemars::{JsonSchema, schema_for};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct AppConfig {
    /// Server configuration
    server: ServerConfig,
    /// List of enabled features
    features: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct ServerConfig {
    /// Server hostname or IP address
    host: String,
    /// Server port number
    port: u16,
    /// Enable or disable the server
    #[serde(default)]
    enabled: bool,
}

fn main() {
    // Generate JSON Schema
    let schema = schema_for!(AppConfig);
    let schema_json = serde_json::to_string_pretty(&schema).unwrap();
    
    // Save to file
    std::fs::write("config-schema.json", schema_json).unwrap();
    println!("Schema generated successfully!");
}
```

Run to generate the schema:

```bash
cargo run
# Output: config-schema.json created
```

### 2. (Optional) Create Initial Configuration

Create `config.toml`:

```toml
[server]
host = "localhost"
port = 8080
enabled = true

features = ["logging", "metrics", "auth"]
```

### 3. Launch JKConfig TUI

```bash
# Edit config.toml with the generated schema
jkconfig -c config.toml -s config-schema.json

# Or let it auto-detect (looks for config-schema.json)
jkconfig -c config.toml
```

Now you have a beautiful TUI to edit your configuration! 🎉

### Alternative: Direct JSON Schema

If you prefer writing JSON Schema directly:

<details>
<summary>Click to see JSON Schema example</summary>

Create `config-schema.json`:

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "AppConfig",
  "type": "object",
  "properties": {
    "server": {
      "type": "object",
      "description": "Server configuration",
      "properties": {
        "host": {
          "type": "string",
          "description": "Server hostname or IP address"
        },
        "port": {
          "type": "integer",
          "description": "Server port number"
        },
        "enabled": {
          "type": "boolean",
          "description": "Enable or disable the server"
        }
      },
      "required": ["host", "port"]
    },
    "features": {
      "type": "array",
      "description": "List of enabled features",
      "items": {
        "type": "string"
      }
    }
  },
  "required": ["server", "features"]
}
```

</details>

## 🎮 Usage

### Command Line Options

```bash
jkconfig [OPTIONS]

Options:
  -c, --config <FILE>  Configuration file path [default: .project.toml]
  -s, --schema <FILE>  JSON Schema file path (auto-detected if not specified)
  -h, --help          Print help information
```

### Keyboard Shortcuts

#### Navigation
- ``/`` or `j`/`k` - Move cursor up/down
- `Enter` - Select/Edit item
- `Esc` - Go back to previous menu

#### Actions
- `C` - Clear current value
- `M` - Toggle menu state (for optional menus)
- `Tab` - Switch OneOf variants

#### Global
- `S` - Save and exit
- `Q` - Quit without saving
- `~` - Toggle debug console

#### Array Editor
- `Enter` - Add new item or edit selected item
- `Del` - Delete selected item
- `Esc` - Close array editor

## 📖 Supported JSON Schema Features

### Data Types

| Type | Description | Example |
|------|-------------|---------|
| `string` | Text input | `"hostname"` |
| `integer` | Whole numbers | `8080` |
| `number` | Decimal numbers | `3.14` |
| `boolean` | True/false toggle | `true` |
| `enum` | Selection list | `["option1", "option2"]` |
| `array` | List of items | `["item1", "item2"]` |
| `object` | Nested structure | `{"key": "value"}` |

### Advanced Features

- **OneOf** - Select one variant from multiple schemas
- **AnyOf** - Flexible variant selection
- **$ref** - Schema references and reuse
- **$defs** - Schema definitions
- **required** - Mark fields as mandatory
- **description** - Display help text
- **default** - Default values

## 🎨 UI Components

### Type Icons

- 📂 Menu/Object
- 🔀 OneOf variant
- 🔡 String
- 🔢 Integer/Number
- ✅/❎ Boolean
- 📚 Enum
- 📋 Array

## 🔧 Configuration File Formats

JKConfig supports both TOML and JSON formats:

### TOML (Recommended)
```toml
[server]
host = "localhost"
port = 8080

features = ["feature1", "feature2"]
```

### JSON
```json
{
  "server": {
    "host": "localhost",
    "port": 8080
  },
  "features": ["feature1", "feature2"]
}
```

## 🛠️ Advanced Usage

### Schema Auto-Detection

If you don't specify a schema file, JKConfig will automatically look for:
- `<config-name>-schema.json`

Example:
- Config: `app.toml` → Schema: `app-schema.json`
- Config: `config.json` → Schema: `config-schema.json`

### Backup System

JKConfig automatically creates backups before saving:
- Format: `bk-<timestamp>.<ext>`
- Example: `bk-1698765432.toml`

### Complex Schemas

JKConfig handles complex nested structures:

```json
{
  "type": "object",
  "properties": {
    "database": {
      "oneOf": [
        {
          "type": "object",
          "properties": {
            "PostgreSQL": {
              "type": "object",
              "properties": {
                "host": { "type": "string" },
                "port": { "type": "integer" }
              }
            }
          }
        },
        {
          "type": "object",
          "properties": {
            "MySQL": {
              "type": "object",
              "properties": {
                "host": { "type": "string" },
                "port": { "type": "integer" }
              }
            }
          }
        }
      ]
    }
  }
}
```

## 🤝 Integration

### Complete Workflow Example

Here's a complete example showing the recommended workflow from Rust structs to TUI editing:

```rust
// config_types.rs
use schemars::{JsonSchema, schema_for};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct MyAppConfig {
    /// Application name
    pub app_name: String,
    
    /// Server settings
    pub server: ServerConfig,
    
    /// Database configuration
    pub database: DatabaseConfig,
    
    /// Optional features
    #[serde(default)]
    pub features: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct ServerConfig {
    pub host: String,
    pub port: u16,
    #[serde(default = "default_true")]
    pub enabled: bool,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct DatabaseConfig {
    pub url: String,
    pub max_connections: u32,
}

fn default_true() -> bool { true }

fn main() -> anyhow::Result<()> {
    // 1. Generate schema
    let schema = schema_for!(MyAppConfig);
    std::fs::write(
        "myapp-schema.json",
        serde_json::to_string_pretty(&schema)?
    )?;
    
    // 2. Create default config
    let default_config = MyAppConfig {
        app_name: "My Application".to_string(),
        server: ServerConfig {
            host: "0.0.0.0".to_string(),
            port: 8080,
            enabled: true,
        },
        database: DatabaseConfig {
            url: "postgres://localhost/mydb".to_string(),
            max_connections: 10,
        },
        features: vec!["auth".to_string(), "logging".to_string()],
    };
    
    // Save as TOML
    let toml_str = toml::to_string_pretty(&default_config)?;
    std::fs::write("myapp.toml", toml_str)?;
    
    println!("✓ Schema generated: myapp-schema.json");
    println!("✓ Default config created: myapp.toml");
    println!("\nNow run: jkconfig -c myapp.toml");
    
    Ok(())
}
```

### Load Configuration in Your App

```rust
use serde::Deserialize;

#[derive(Deserialize)]
struct MyAppConfig {
    app_name: String,
    server: ServerConfig,
    // ... other fields
}

fn main() -> anyhow::Result<()> {
    // Load the config file (edited with jkconfig)
    let config_str = std::fs::read_to_string("myapp.toml")?;
    let config: MyAppConfig = toml::from_str(&config_str)?;
    
    println!("Starting {} on {}:{}", 
        config.app_name,
        config.server.host,
        config.server.port
    );
    
    // Use your config...
    Ok(())
}
```

### Use JKConfig as a Library

You can also use JKConfig programmatically in your Rust code:

```rust
use jkconfig::data::AppData;

// Load configuration programmatically
let app_data = AppData::new(
    Some("config.toml"),
    Some("config-schema.json")
)?;

// Access the configuration tree
println!("{:#?}", app_data.root);

// Get as JSON for further processing
let json_value = app_data.root.as_json();
```

### Advanced: Complex Enum Types

JKConfig supports complex enum types (OneOf in JSON Schema):

```rust
use schemars::{JsonSchema, schema_for};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub enum DatabaseType {
    PostgreSQL {
        host: String,
        port: u16,
        database: String,
    },
    MySQL {
        host: String,
        port: u16,
        database: String,
    },
    SQLite {
        path: String,
    },
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct Config {
    pub database: DatabaseType,
}

fn main() {
    let schema = schema_for!(Config);
    std::fs::write(
        "config-schema.json",
        serde_json::to_string_pretty(&schema).unwrap()
    ).unwrap();
}
```

In the TUI, you can use `Tab` to switch between different database types!

## 📝 Examples

See the `tests/` directory for complete examples:
- Basic object structures
- Enum and OneOf variants
- Nested configurations
- Array handling

## 💡 Best Practices

### 1. Document Your Schema

Use doc comments in your Rust structs - they become descriptions in the UI:

```rust
#[derive(JsonSchema, Serialize, Deserialize)]
struct Config {
    /// The server hostname or IP address.
    /// 
    /// Examples: "localhost", "0.0.0.0", "example.com"
    /// Default: "127.0.0.1"
    host: String,
}
```

### 2. Provide Sensible Defaults

```rust
#[derive(JsonSchema, Serialize, Deserialize)]
struct Config {
    #[serde(default = "default_port")]
    port: u16,
}

fn default_port() -> u16 { 8080 }
```

### 3. Use Enums for Fixed Choices

```rust
#[derive(JsonSchema, Serialize, Deserialize)]
enum LogLevel {
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}
```

### 4. Organize Complex Configs

```rust
// ✅ Good: Organized in modules
#[derive(JsonSchema, Serialize, Deserialize)]
struct AppConfig {
    server: ServerConfig,
    database: DatabaseConfig,
    logging: LoggingConfig,
}

// ❌ Avoid: Flat structure with many fields
struct AppConfig {
    server_host: String,
    server_port: u16,
    db_host: String,
    db_port: u16,
    // ... 50 more fields
}
```

### 5. Version Your Schemas

```rust
#[derive(JsonSchema, Serialize, Deserialize)]
struct Config {
    #[serde(default = "config_version")]
    version: String,
    // ... rest of config
}

fn config_version() -> String { "1.0.0".to_string() }
```

### 6. Integrate into Your Build Process

Add a `build.rs`:

```rust
// build.rs
use schemars::schema_for;

fn main() {
    let schema = schema_for!(MyConfig);
    std::fs::write(
        "config-schema.json",
        serde_json::to_string_pretty(&schema).unwrap()
    ).unwrap();
}
```

### 7. Provide a Config Command

```rust
use clap::Parser;

#[derive(Parser)]
enum Cli {
    /// Run the application
    Run,
    /// Edit configuration with TUI
    Config {
        #[arg(short, long, default_value = "config.toml")]
        file: String,
    },
}

fn main() {
    match Cli::parse() {
        Cli::Run => run_app(),
        Cli::Config { file } => {
            // Launch jkconfig
            std::process::Command::new("jkconfig")
                .arg("-c")
                .arg(&file)
                .status()
                .expect("Failed to launch jkconfig");
        }
    }
}
```

## 🐛 Troubleshooting

### Schema not found
```
Error: Schema file does not exist: config-schema.json
```
**Solution**: Ensure your schema file exists and the path is correct.

### Unsupported file format
```
Error: Unsupported config file extension: "yaml"
```
**Solution**: Use `.toml` or `.json` extensions.

### Invalid schema
```
Error: Schema conversion error at path...
```
**Solution**: Validate your JSON Schema using [JSON Schema Validator](https://www.jsonschemavalidator.net/)

## 🔄 Comparison with Similar Tools

| Feature | JKConfig | Other Config Editors |
|---------|----------|---------------------|
| JSON Schema Support | ✅ Full | ⚠️ Limited |
| Terminal UI | ✅ Modern | ⚠️ Basic |
| Multiple Formats | ✅ TOML/JSON | ⚠️ Varies |
| Type Safety | ✅ Full | ❌ Manual |
| Auto Backup | ✅ Yes | ❌ No |
| Nested Structures | ✅ Full | ⚠️ Limited |

## 📚 Documentation

- [JSON Schema Specification]https://json-schema.org/
- [Ratatui Documentation]https://docs.rs/ratatui/
- [TOML Specification]https://toml.io/

## 🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## 📄 License

This project is licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE)
- MIT License ([LICENSE-MIT]LICENSE-MIT)

at your option.

## 👏 Acknowledgments

- Built with [Ratatui]https://github.com/ratatui/ratatui TUI framework
- Inspired by Linux kernel's `menuconfig`
- JSON Schema validation and parsing

## 📧 Contact

- Author: 周睿 (Zhou Rui)
- Email: zrufo747@outlook.com
- Repository: https://github.com/ZR233/ostool

---

Made with ❤️ by the ostool team