tusktsk 2.1.3

🦀 TuskTsk Enhanced - Ultra-fast Rust configuration parser with maximum syntax flexibility
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
use tusktsk::{parse_tsk_content, serialize, TuskResult, Config, TuskError};
use clap::{Parser as ClapParser, Subcommand};
use serde_json;
use serde_yaml;
use std::fs;
use std::path::Path;
use std::process;

use crate::commands;

#[derive(ClapParser)]
#[command(name = "tsk")]
#[command(about = "Ultra-fast Rust TuskLang parser and CLI tool")]
#[command(version = "0.1.0")]
pub struct Cli {
    /// Enable verbose output
    #[arg(short, long)]
    verbose: bool,

    /// Suppress non-error output
    #[arg(short, long)]
    quiet: bool,

    /// Use alternate config file
    #[arg(long)]
    config: Option<String>,

    /// Output in JSON format
    #[arg(long)]
    json: bool,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    // Core commands (existing)
    Parse { file: String, format: String, pretty: bool },
    Validate { file: String, verbose: bool },
    Gen { file: String, language: String, output: Option<String> },
    Convert { input: String, from: String, to: String, output: Option<String> },
    Bench { file: String, iterations: usize },

    // Universal CLI Command Spec stubs
    Db(commands::db::DbCommand),
    Dev(commands::dev::DevCommand),
    Test(commands::test::TestCommand),
    Services(commands::services::ServicesCommand),
    Cache(commands::cache::CacheCommand),
    Config(commands::config::ConfigCommand),
    Binary(commands::binary::BinaryCommand),
    Ai(commands::ai::AiCommand),
    Utility(commands::utility::UtilityCommand),
    Css(commands::css::CssCommand),
    License(commands::license::LicenseCommand),
    Peanuts(commands::peanuts::PeanutsCommand),
    Web(commands::web::WebCommand),
    Security(commands::security::SecurityCommand),
    Dependency(commands::dependency::DependencyCommand),
}

/// Run the CLI application
pub async fn run() -> TuskResult<()> {
    let cli = Cli::parse();

    // Handle global options
    if cli.verbose {
        println!("🔍 Verbose mode enabled");
    }

    // Load configuration hierarchy
    let config = load_configuration(&cli.config)?;

    match cli.command {
        Some(cmd) => {
            let result = match cmd {
                Commands::Parse { file, format, pretty } => parse_command(&file, &format, pretty),
                Commands::Validate { file, verbose } => validate_command(&file, verbose),
                Commands::Gen { file, language, output } => gen_command(&file, &language, output.as_deref()),
                Commands::Convert { input, from, to, output } => convert_command(&input, &from, &to, output.as_deref()),
                Commands::Bench { file, iterations } => bench_command(&file, iterations),
                Commands::Db(cmd) => commands::db::run(cmd),
                Commands::Dev(cmd) => commands::dev::run(cmd),
                Commands::Test(cmd) => commands::test::run(cmd).await,
                Commands::Services(cmd) => commands::services::run(cmd),
                Commands::Cache(cmd) => commands::cache::run(cmd),
                Commands::Config(cmd) => commands::config::run(cmd),
                Commands::Binary(cmd) => commands::binary::run(cmd),
                Commands::Ai(cmd) => {
                    commands::ai::run(cmd).await.map_err(|e| TuskError::parse_error(0, e.to_string()))
                },
                Commands::Utility(cmd) => commands::utility::run(cmd),
                Commands::Css(cmd) => commands::css::run(cmd),
                Commands::License(cmd) => commands::license::run(cmd),
                Commands::Peanuts(cmd) => commands::peanuts::run(cmd),
                Commands::Web(cmd) => {
                    commands::web::run(cmd).await.map_err(|e| TuskError::parse_error(0, e.to_string()))
                },
                Commands::Security(cmd) => commands::security::run(cmd).await.map_err(|e| TuskError::parse_error(0, e.to_string())),
                Commands::Dependency(cmd) => commands::dependency::run(cmd).await.map_err(|e| TuskError::parse_error(0, e.to_string())),
            };

            match result {
                Ok(_) => {
                    process::exit(0); // Success
                }
                Err(e) => {
                    if !cli.quiet {
                        eprintln!("❌ Error: {}", e);
                    }
                    process::exit(1); // General error
                }
            }
        }
        None => {
            // Interactive REPL mode
            interactive_mode()?;
        }
    }

    Ok(())
}

/// Load configuration following hierarchical order
fn load_configuration(cli_config: &Option<String>) -> TuskResult<Option<Config>> {
    // 1. Command-line specified config
    if let Some(config_path) = cli_config {
        if let Ok(content) = fs::read_to_string(config_path) {
            let parsed = parse_tsk_content(&content)?;
            return Ok(Some(Config { data: parsed }));
        }
    }

    // 2. Current directory peanu.pnt or peanu.tsk
    for filename in &["peanu.pnt", "peanu.tsk"] {
        if let Ok(content) = fs::read_to_string(filename) {
            let parsed = parse_tsk_content(&content)?;
            return Ok(Some(Config { data: parsed }));
        }
    }

    // 3. Parent directories (walking up)
    let mut current_dir = std::env::current_dir()?;
    for _ in 0..10 { // Limit depth to prevent infinite loops
        for filename in &["peanu.pnt", "peanu.tsk"] {
            let config_path = current_dir.join(filename);
            if let Ok(content) = fs::read_to_string(config_path) {
                let parsed = parse_tsk_content(&content)?;
                return Ok(Some(Config { data: parsed }));
            }
        }
        
        if !current_dir.pop() {
            break;
        }
    }

    // 4. User home directory ~/.tusklang/config.tsk
    if let Some(home) = dirs::home_dir() {
        let config_path = home.join(".tusklang").join("config.tsk");
        if let Ok(content) = fs::read_to_string(config_path) {
            return Ok(Some(parse_tsk_content(&content)?));
        }
    }

    // 5. System-wide /etc/tusklang/config.tsk
    let system_config = Path::new("/etc/tusklang/config.tsk");
    if let Ok(content) = fs::read_to_string(system_config) {
        return Ok(Some(parse_tsk_content(&content)?));
    }

    Ok(None)
}

/// Interactive REPL mode
fn interactive_mode() -> TuskResult<()> {
    println!("TuskLang v0.1.0 - Interactive Mode");
    println!("Type 'help' for commands, 'exit' to quit");
    
    use std::io::{self, Write};
    
    loop {
        print!("tsk> ");
        io::stdout().flush()?;
        
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        
        let input = input.trim();
        
        match input {
            "exit" | "quit" => break,
            "help" => {
                println!("Available commands:");
                println!("  db status|migrate|console|backup|restore|init");
                println!("  dev serve|compile|optimize");
                println!("  test all|parser|fujsen|sdk|performance");
                println!("  services start|stop|restart|status");
                println!("  cache clear|status|warm|memcached|distributed");
                println!("  config get|check|validate|compile|docs|clear-cache|stats");
                println!("  binary compile|execute|benchmark|optimize");
                println!("  ai claude|chatgpt|analyze|optimize|security");
                println!("  utility parse|validate|convert|get|set");
                println!("  css compile|watch|optimize|validate|lint|format|stats");
                println!("  license generate|validate|check|add|remove|list|info");
                println!("  peanuts compile|execute|validate|decompile|info|list|sign|verify");
                println!("  exit - Exit interactive mode");
            }
            "" => continue,
            _ => {
                // Parse and execute command
                let args: Vec<&str> = input.split_whitespace().collect();
                if !args.is_empty() {
                    println!("🔄 Executing: {}", input);
                    // TODO: Implement command parsing and execution
                    println!("⚠️  Command execution not yet implemented in interactive mode");
                }
            }
        }
    }
    
    println!("👋 Goodbye!");
    Ok(())
}

/// Parse command implementation
fn parse_command(file: &str, format: &str, pretty: bool) -> TuskResult<()> {
    let content = fs::read_to_string(file)
        .map_err(|e| TuskError::parse_error(0, e.to_string()))?;

    let config = parse_tsk_content(&content)?;

    let output = match format.to_lowercase().as_str() {
        "json" => {
            if pretty {
                serde_json::to_string_pretty(&config)?
            } else {
                serde_json::to_string(&config)?
            }
        }
        "yaml" => serde_yaml::to_string(&config)?,
        "tsk" => serialize(&config)?,
        _ => return Err(TuskError::validation_error(
            "format".to_string(),
            format.to_string(),
            "supported_formats".to_string(),
            format!("Unsupported output format: {}", format)
        )),
    };

    println!("{}", output);
    Ok(())
}

/// Validate command implementation
fn validate_command(file: &str, verbose: bool) -> TuskResult<()> {
    let content = fs::read_to_string(file)
        .map_err(|e| TuskError::parse_error(0, e.to_string()))?;

    match parse_tsk_content(&content) {
        Ok(_) => {
            if verbose {
                println!("✅ File '{}' is valid TuskLang syntax", file);
            } else {
                println!("✅ Valid");
            }
            Ok(())
        }
        Err(e) => {
            if verbose {
                eprintln!("❌ Validation failed: {}", e);
                if let Some(line) = e.line_number() {
                    eprintln!("   Error occurred at line {}", line);
                }
            } else {
                eprintln!("❌ Invalid");
            }
            Err(e)
        }
    }
}

/// Generate command implementation
fn gen_command(file: &str, language: &str, output_file: Option<&str>) -> TuskResult<()> {
    let content = fs::read_to_string(file)
        .map_err(|e| TuskError::parse_error(0, e.to_string()))?;

    let config = parse_tsk_content(&content)?;
    let file_name = Path::new(file).file_stem().unwrap_or_default().to_string_lossy();

    let generated_code = match language.to_lowercase().as_str() {
        "rust" => generate_rust_struct(&file_name, &config)?,
        "json" => serde_json::to_string_pretty(&config)?,
        "yaml" => serde_yaml::to_string(&config)?,
        _ => return Err(TuskError::validation_error(
            "language".to_string(),
            language.to_string(),
            "supported_languages".to_string(),
            format!("Unsupported language: {}", language)
        )),
    };

    if let Some(output_path) = output_file {
        fs::write(output_path, generated_code)
            .map_err(|e| TuskError::parse_error(0, e.to_string()))?;
        println!("Generated code written to: {}", output_path);
    } else {
        println!("{}", generated_code);
    }

    Ok(())
}

/// Convert command implementation
fn convert_command(input: &str, from: &str, to: &str, output_file: Option<&str>) -> TuskResult<()> {
    let content = fs::read_to_string(input)
        .map_err(|e| TuskError::parse_error(0, e.to_string()))?;

    // Parse input format
    let config = match from.to_lowercase().as_str() {
        "tsk" => parse_tsk_content(&content)?,
        "json" => serde_json::from_str::<()>(&content)?,
        "yaml" => serde_yaml::from_str::<()>(&content)?,
        _ => return Err(TuskError::validation_error(
            "from".to_string(),
            from.to_string(),
            "supported_formats".to_string(),
            format!("Unsupported input format: {}", from)
        )),
    };

    // Convert to output format
    let output = match to.to_lowercase().as_str() {
        "tsk" => serialize(&config)?,
        "json" => serde_json::to_string_pretty(&config)?,
        "yaml" => serde_yaml::to_string(&config)?,
        _ => return Err(TuskError::validation_error(
            "to".to_string(),
            to.to_string(),
            "supported_formats".to_string(),
            format!("Unsupported output format: {}", to)
        )),
    };

    if let Some(output_path) = output_file {
        fs::write(output_path, output)
            .map_err(|e| TuskError::parse_error(0, e.to_string()))?;
        println!("Converted file written to: {}", output_path);
    } else {
        println!("{}", output);
    }

    Ok(())
}

/// Benchmark command implementation
fn bench_command(file: &str, iterations: usize) -> TuskResult<()> {
    let content = fs::read_to_string(file)
        .map_err(|e| TuskError::parse_error(0, e.to_string()))?;

    println!("Running benchmark with {} iterations...", iterations);
    
    let start = std::time::Instant::now();
    
    for _ in 0..iterations {
        parse_tsk_content(&content)?;
    }
    
    let duration = start.elapsed();
    let avg_time = duration.as_nanos() as f64 / iterations as f64;
    
    println!("Results:");
    println!("  Total time: {:?}", duration);
    println!("  Average time per parse: {:.2} ns", avg_time);
    println!("  Parses per second: {:.0}", 1_000_000_000.0 / avg_time);
    
    Ok(())
}

/// Generate Rust struct from TuskLang config
fn generate_rust_struct(struct_name: &str, config: &Config) -> TuskResult<String> {
    let mut code = String::new();
    
    // Convert to PascalCase
    let struct_name = to_pascal_case(struct_name);
    
    code.push_str(&format!("#[derive(Debug, Clone, Serialize, Deserialize)]\n"));
    code.push_str(&format!("pub struct {} {{\n", struct_name));
    
    // Add standard fields
    code.push_str(&format!("    pub app: String,\n"));
    code.push_str(&format!("    pub version: String,\n"));
    code.push_str(&format!("    pub features: Vec<String>,\n"));
    
    code.push_str("}\n");
    
    Ok(code)
}

/// Convert string to PascalCase
fn to_pascal_case(s: &str) -> String {
    s.split(|c| c == '_' || c == '-')
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().chain(chars).collect(),
            }
        })
        .collect()
}

/// Convert string to snake_case
fn to_snake_case(s: &str) -> String {
    s.replace('-', "_").to_lowercase()
}

/// Get Rust type for a TuskLang value
fn get_rust_type(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(_) => "String".to_string(),
        serde_json::Value::Number(n) => {
            if n.as_f64().map(|f| f.fract() == 0.0).unwrap_or(false) {
                "i64".to_string()
            } else {
                "f64".to_string()
            }
        }
        serde_json::Value::Bool(_) => "bool".to_string(),
        serde_json::Value::Array(arr) => {
            if arr.is_empty() {
                "Vec<serde_json::Value>".to_string()
            } else {
                format!("Vec<{}>", get_rust_type(&arr[0]))
            }
        }
        serde_json::Value::Object(_) => "serde_json::Value".to_string(),
        serde_json::Value::Null => "Option<serde_json::Value>".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_to_pascal_case() {
        assert_eq!(to_pascal_case("app_name"), "AppName");
        assert_eq!(to_pascal_case("database_config"), "DatabaseConfig");
        assert_eq!(to_pascal_case("api-v1"), "ApiV1");
    }

    #[test]
    fn test_to_snake_case() {
        assert_eq!(to_snake_case("appName"), "appname");
        assert_eq!(to_snake_case("database-config"), "database_config");
        assert_eq!(to_snake_case("API_V1"), "api_v1");
    }
}