wcl 0.6.1-alpha

WCL (Wil's Configuration Language) — a typed, block-structured configuration language
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
use clap::{Parser, Subcommand};
use std::path::{Path, PathBuf};
use std::process;

use crate::lang::diagnostic::{Diagnostic, Severity};
use crate::lang::span::SourceMap;

/// Shared library search path options
#[derive(clap::Args, Clone, Debug, Default)]
pub struct LibraryArgs {
    /// Extra library search path (may be repeated; searched before defaults)
    #[arg(long = "lib-path", value_name = "DIR")]
    pub lib_paths: Vec<PathBuf>,
    /// Disable default XDG/system library search paths
    #[arg(long)]
    pub no_default_lib_paths: bool,
}

impl LibraryArgs {
    pub fn apply(&self, opts: &mut crate::ParseOptions) {
        opts.lib_paths.clone_from(&self.lib_paths);
        opts.no_default_lib_paths = self.no_default_lib_paths;
    }
}

/// Format a diagnostic with file location (line:col) when available.
pub(crate) fn format_diagnostic(
    diag: &Diagnostic,
    source_map: &SourceMap,
    fallback_path: &Path,
) -> String {
    let prefix = match diag.severity {
        Severity::Error => "error",
        Severity::Warning => "warning",
        Severity::Info => "info",
        Severity::Hint => "hint",
    };

    let code_part = match diag.code.as_deref() {
        Some(c) => format!("[{}]", c),
        None => String::new(),
    };

    let span = diag.span;
    let is_dummy = span == crate::lang::span::Span::dummy();

    if is_dummy {
        format!("{}{}: {}", prefix, code_part, diag.message)
    } else {
        let (line, col) = source_map.line_col(span.file, span.start);
        let file_path = source_map.get_file(span.file).path.as_str();
        let display_path = if file_path.is_empty() || file_path == "<input>" {
            fallback_path.display().to_string()
        } else {
            file_path.to_string()
        };
        format!(
            "{}:{}:{}: {}{}: {}",
            display_path, line, col, prefix, code_part, diag.message
        )
    }
}

mod add;
mod convert;
mod docs;
mod eval;
mod fmt;
mod inspect;
mod path;
mod query;
mod remove;
mod set;
mod table;
mod transform;
mod validate;
mod vars;
#[cfg(feature = "wdoc")]
mod wdoc;

#[derive(Parser)]
#[command(
    name = "wcl",
    version,
    about = "WCL \u{2014} Wil's Configuration Language CLI"
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Validate a WCL document
    Validate {
        /// Input file
        file: PathBuf,
        /// Treat warnings as errors
        #[arg(long)]
        strict: bool,
        /// External schema file
        #[arg(long)]
        schema: Option<PathBuf>,
        /// Set a variable (KEY=VALUE, may repeat)
        #[arg(long = "var", value_name = "KEY=VALUE")]
        vars: Vec<String>,
        #[command(flatten)]
        lib_args: LibraryArgs,
    },
    /// Format a WCL document
    Fmt {
        /// Input file
        file: PathBuf,
        /// Write formatted output back to file
        #[arg(long)]
        write: bool,
        /// Check if file is already formatted (exit code only)
        #[arg(long)]
        check: bool,
    },
    /// Query a WCL document
    Query {
        /// Input file
        file: PathBuf,
        /// Query expression
        query: String,
        /// Output format
        #[arg(long, default_value = "text")]
        format: String,
        /// Count results only
        #[arg(long)]
        count: bool,
        /// Search recursively in directory
        #[arg(long)]
        recursive: bool,
        #[command(flatten)]
        lib_args: LibraryArgs,
    },
    /// Inspect the AST or HIR of a WCL document
    Inspect {
        /// Input file
        file: PathBuf,
        /// Show raw AST
        #[arg(long)]
        ast: bool,
        /// Show resolved HIR
        #[arg(long)]
        hir: bool,
        /// Show scope tree
        #[arg(long)]
        scopes: bool,
        /// Show dependency graph
        #[arg(long)]
        deps: bool,
    },
    /// Evaluate a WCL document and print resolved output
    Eval {
        /// Input file
        file: PathBuf,
        /// Output format (json, yaml, toml)
        #[arg(long, default_value = "json")]
        format: String,
        /// Set a variable (KEY=VALUE, may repeat)
        #[arg(long = "var", value_name = "KEY=VALUE")]
        vars: Vec<String>,
        #[command(flatten)]
        lib_args: LibraryArgs,
    },
    /// Start the WCL language server
    Lsp {
        /// Listen on a TCP address instead of stdio (e.g. 127.0.0.1:9257)
        #[arg(long)]
        tcp: Option<String>,
    },
    /// Convert between WCL and other formats
    Convert {
        /// Input file
        file: PathBuf,
        /// Output format (json, yaml, toml)
        #[arg(long)]
        to: Option<String>,
        /// Input format for conversion to WCL
        #[arg(long)]
        from: Option<String>,
        #[command(flatten)]
        lib_args: LibraryArgs,
    },
    /// Set a value by path
    Set {
        /// Input file
        file: PathBuf,
        /// Path to the value (e.g. service#svc-api.port)
        path: String,
        /// New value
        value: String,
    },
    /// Add a new block
    Add {
        /// Input file
        file: PathBuf,
        /// Block specification (e.g. "service svc-new")
        block_spec: String,
        /// Auto-determine file placement
        #[arg(long)]
        file_auto: bool,
    },
    /// Remove a block or attribute by path
    Remove {
        /// Input file
        file: PathBuf,
        /// Path to remove (e.g. service#svc-old, service#svc-api.debug)
        path: String,
    },
    /// Table row operations (insert, remove, update)
    Table {
        #[command(subcommand)]
        action: TableAction,
    },
    /// Generate schema documentation as an mdBook
    Docs {
        /// Input WCL files
        #[arg(required = true)]
        files: Vec<PathBuf>,
        /// Output directory
        #[arg(long, default_value = "docs-out")]
        output: PathBuf,
        /// Book title
        #[arg(long, default_value = "WCL Schema Reference")]
        title: String,
        #[command(flatten)]
        lib_args: LibraryArgs,
    },
    /// Run data transformations
    Transform {
        #[command(subcommand)]
        action: TransformAction,
    },
    /// Build, validate, or serve wdoc documentation
    #[cfg(feature = "wdoc")]
    Wdoc {
        #[command(subcommand)]
        action: WdocAction,
    },
}

#[derive(Subcommand)]
enum TransformAction {
    /// Execute a transform
    Run {
        /// Transform name (block ID in the WCL file)
        name: String,
        /// WCL file containing the transform definition
        #[arg(short, long)]
        file: PathBuf,
        /// Input data file (stdin if omitted)
        #[arg(long)]
        input: Option<PathBuf>,
        /// Output data file (stdout if omitted)
        #[arg(long)]
        output: Option<PathBuf>,
        /// Parameters (KEY=VALUE, may repeat)
        #[arg(long = "param", value_name = "KEY=VALUE")]
        params: Vec<String>,
        #[command(flatten)]
        lib_args: LibraryArgs,
    },
}

#[cfg(feature = "wdoc")]
#[derive(Subcommand)]
enum WdocAction {
    /// Build wdoc to HTML
    Build {
        /// Input WCL file(s)
        #[arg(required = true)]
        files: Vec<PathBuf>,
        /// Output directory
        #[arg(long, default_value = "wdoc-out")]
        output: PathBuf,
        /// Set a variable (KEY=VALUE, may repeat)
        #[arg(long = "var", value_name = "KEY=VALUE")]
        vars: Vec<String>,
        #[command(flatten)]
        lib_args: LibraryArgs,
    },
    /// Validate wdoc structure without building
    Validate {
        /// Input WCL file(s)
        #[arg(required = true)]
        files: Vec<PathBuf>,
        /// Set a variable (KEY=VALUE, may repeat)
        #[arg(long = "var", value_name = "KEY=VALUE")]
        vars: Vec<String>,
        #[command(flatten)]
        lib_args: LibraryArgs,
    },
    /// Start a dev server with live reload
    Serve {
        /// Input WCL file(s)
        #[arg(required = true)]
        files: Vec<PathBuf>,
        /// Port to listen on
        #[arg(long, default_value = "3000")]
        port: u16,
        /// Open browser automatically
        #[arg(long)]
        open: bool,
        /// Set a variable (KEY=VALUE, may repeat)
        #[arg(long = "var", value_name = "KEY=VALUE")]
        vars: Vec<String>,
        #[command(flatten)]
        lib_args: LibraryArgs,
    },
}

#[derive(Subcommand)]
enum TableAction {
    /// Insert a row into a table
    Insert {
        /// Input file
        file: PathBuf,
        /// Table name (inline ID)
        table: String,
        /// Row values as pipe-delimited: '"alice" | 25'
        values: String,
    },
    /// Remove rows matching a condition
    Remove {
        /// Input file
        file: PathBuf,
        /// Table name (inline ID)
        table: String,
        /// Condition expression: 'name == "alice"'
        #[arg(long = "where")]
        condition: String,
    },
    /// Update cells in rows matching a condition
    Update {
        /// Input file
        file: PathBuf,
        /// Table name (inline ID)
        table: String,
        /// Condition: 'name == "alice"'
        #[arg(long = "where")]
        condition: String,
        /// Assignments: 'age = 26, role = "admin"'
        #[arg(long)]
        set: String,
    },
}

pub fn main() {
    let cli = Cli::parse();

    let result = match cli.command {
        Commands::Validate {
            file,
            strict,
            schema,
            vars,
            lib_args,
        } => validate::run(&file, strict, schema.as_deref(), &vars, &lib_args),
        Commands::Fmt { file, write, check } => fmt::run(&file, write, check),
        Commands::Query {
            file,
            query,
            format,
            count,
            recursive,
            lib_args,
        } => query::run(&file, &query, &format, count, recursive, &lib_args),
        Commands::Inspect {
            file,
            ast,
            hir,
            scopes,
            deps,
        } => inspect::run(&file, ast, hir, scopes, deps),
        Commands::Eval {
            file,
            format,
            vars,
            lib_args,
        } => eval::run(&file, &format, &vars, &lib_args),
        Commands::Lsp { tcp } => {
            let rt = tokio::runtime::Runtime::new()
                .map_err(|e| format!("failed to create tokio runtime: {}", e));
            match rt {
                Ok(rt) => {
                    if let Some(addr) = tcp {
                        rt.block_on(async {
                            wcl_lsp::start_tcp(&addr).await.map_err(|e| e.to_string())
                        })
                    } else {
                        rt.block_on(wcl_lsp::start_stdio());
                        Ok(())
                    }
                }
                Err(e) => Err(e),
            }
        }
        Commands::Convert {
            file,
            to,
            from,
            lib_args,
        } => convert::run(&file, to.as_deref(), from.as_deref(), &lib_args),
        Commands::Set { file, path, value } => set::run(&file, &path, &value),
        Commands::Add {
            file,
            block_spec,
            file_auto,
        } => add::run(&file, &block_spec, file_auto),
        Commands::Remove { file, path } => remove::run(&file, &path),
        Commands::Docs {
            files,
            output,
            title,
            lib_args,
        } => docs::run(&files, &output, &title, &lib_args),
        Commands::Table { action } => match action {
            TableAction::Insert {
                file,
                table: table_name,
                values,
            } => table::run_insert(&file, &table_name, &values),
            TableAction::Remove {
                file,
                table: table_name,
                condition,
            } => table::run_remove(&file, &table_name, &condition),
            TableAction::Update {
                file,
                table: table_name,
                condition,
                set,
            } => table::run_update(&file, &table_name, &condition, &set),
        },
        #[cfg(feature = "wdoc")]
        Commands::Wdoc { action } => match action {
            WdocAction::Build {
                files,
                output,
                vars,
                lib_args,
            } => wdoc::run_build(&files, &output, &vars, &lib_args),
            WdocAction::Validate {
                files,
                vars,
                lib_args,
            } => wdoc::run_validate(&files, &vars, &lib_args),
            WdocAction::Serve {
                files,
                port,
                open,
                vars,
                lib_args,
            } => wdoc::run_serve(&files, port, open, &vars, &lib_args),
        },
        Commands::Transform { action } => match action {
            TransformAction::Run {
                name,
                file,
                input,
                output,
                params,
                lib_args,
            } => transform::run(
                &name,
                &file,
                input.as_deref(),
                output.as_deref(),
                &params,
                &lib_args,
            ),
        },
    };

    if let Err(e) = result {
        eprintln!("error: {}", e);
        process::exit(1);
    }
}