ucg 0.6.4

A configuration generation grammar.
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
// Copyright 2017 Jeremy Wall <jeremy@marzhillstudios.com>
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
#[macro_use]
extern crate clap;
extern crate dirs;
extern crate rustyline;
extern crate ucglib;

use std::cell::RefCell;
use std::collections::BTreeMap;
use std::error::Error;
use std::fs::File;
use std::io;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process;
use std::rc::Rc;

use ucglib::build;
use ucglib::build::assets::{Cache, MemoryCache};
use ucglib::build::Val;
use ucglib::convert::traits;
use ucglib::convert::{ConverterRegistry, ImporterRegistry};
use ucglib::iter::OffsetStrIter;
use ucglib::parse::parse;

fn do_flags<'a, 'b>() -> clap::App<'a, 'b> {
    clap_app!(
        ucg =>
            (version: crate_version!())
            (author: crate_authors!())
            (about: "Universal Configuration Grammar compiler.")
            (@arg nostrict: --("no-strict") "Turn off strict checking.")
            (@subcommand eval =>
             (about: "Evaluate an expression with an optional ucg file as context.")
             (@arg expr: --expr -e +takes_value +required "Expression to evaluate.")
             (@arg target: --format +takes_value "Output type. (flags, json, env, exec) defaults to json.")
             (@arg INPUT: "ucg file to use as context for the expression.")
            )
            (@subcommand repl =>
                (about: "Start the ucg repl for interactive evaluation.")
            )
            (@subcommand build =>
             (about: "Build a list of ucg files.")
             (@arg recurse: -r "Whether we should recurse in directories or not.")
             (@arg INPUT: ... "Input ucg files or directories to build. If not provided then build the contents of the current directory.")
            )
            (@subcommand test =>
             (about: "Check a list of ucg files for errors and run test assertions.")
             (@arg recurse: -r "Whether we should recurse or not.")
             (@arg INPUT: ... "Input ucg files or directories to run test assertions for. If not provided it will scan the current directory for files with _test.ucg")
            )
            (@subcommand fmt =>
             (about: "Format ucg files automatically.")
             (@arg recurse: -r "Whether we should recurse or not.")
             (@arg indent: -i --indent "How many spaces to indent by. Defaults to 4")
             (@arg INPUT: ... "Input ucg files or directories to format")
            )
            (@subcommand converters =>
             (about: "list the available converters")
             (@arg converter: "Converter name to get help for.")
            )
            (@subcommand importers =>
             (about: "list the available importers for includes")
            )
            (@subcommand env =>
             (about: "Describe the environment variables ucg uses.")
            )
    )
}

fn run_converter(c: &traits::Converter, v: Rc<Val>, f: Option<&str>) -> traits::ConvertResult {
    let mut file: Box<std::io::Write> = match f {
        Some(f) => {
            let mut path_buf = PathBuf::from(f);
            path_buf.set_extension(c.file_ext());
            let new_path = path_buf.to_str().unwrap();
            Box::new(File::create(&new_path)?)
        }
        None => Box::new(io::stdout()),
    };
    let result = c.convert(v, file.as_mut());
    file.flush()?;
    result
}

fn build_file<'a, C: Cache>(
    file: &'a str,
    validate: bool,
    strict: bool,
    import_paths: &'a Vec<PathBuf>,
    cache: Rc<RefCell<C>>,
    registry: &'a ConverterRegistry,
) -> Result<build::FileBuilder<'a, C>, Box<dyn Error>> {
    let mut file_path_buf = PathBuf::from(file);
    if file_path_buf.is_relative() {
        file_path_buf = std::env::current_dir()?.join(file_path_buf);
    }
    let mut builder =
        build::FileBuilder::new(std::env::current_dir()?, import_paths, cache, registry);
    builder.set_strict(strict);
    if validate {
        builder.enable_validate_mode();
    }
    builder.build(file_path_buf)?;
    if validate {
        println!("{}", builder.assert_collector.summary);
    }
    Ok(builder)
}

fn do_validate<C: Cache>(
    file: &str,
    strict: bool,
    import_paths: &Vec<PathBuf>,
    cache: Rc<RefCell<C>>,
    registry: &ConverterRegistry,
) -> bool {
    println!("Validating {}", file);
    match build_file(file, true, strict, import_paths, cache, registry) {
        Ok(b) => {
            if b.assert_collector.success {
                println!("File {} Pass\n", file);
            } else {
                println!("File {} Fail\n", file);
                return false;
            }
        }
        Err(msg) => {
            eprintln!("Err: {}", msg);
            return false;
        }
    }
    return true;
}

fn process_output(
    output: &Option<(String, Rc<Val>)>,
    file: Option<&str>,
    registry: &ConverterRegistry,
) -> bool {
    let (typ, val) = match output {
        Some((ref typ, ref val)) => (typ, val.clone()),
        None => {
            return false;
        }
    };
    match registry.get_converter(typ) {
        Some(converter) => {
            run_converter(converter, val, file).unwrap();
            eprintln!("\nConversion successful");
            return true;
        }
        None => {
            eprintln!("No such converter {}", typ);
            return false;
        }
    }
}

fn do_compile<C: Cache>(
    file: &str,
    strict: bool,
    import_paths: &Vec<PathBuf>,
    cache: Rc<RefCell<C>>,
    registry: &ConverterRegistry,
) -> bool {
    println!("Building {}", file);
    let builder = match build_file(file, false, strict, import_paths, cache.clone(), registry) {
        Ok(builder) => builder,
        Err(err) => {
            eprintln!("{}", err);
            return false;
        }
    };
    if builder.out_lock.is_none() {
        eprintln!("Build results in no artifacts.");
    }
    process_output(&builder.out_lock, Some(file), registry)
}

fn visit_ucg_files<C: Cache>(
    path: &Path,
    recurse: bool,
    validate: bool,
    strict: bool,
    import_paths: &Vec<PathBuf>,
    cache: Rc<RefCell<C>>,
    registry: &ConverterRegistry,
) -> Result<bool, Box<dyn Error>> {
    let our_path = String::from(path.to_string_lossy());
    let mut result = true;
    let mut summary = String::new();
    if path.is_dir() {
        let mut dir_iter = std::fs::read_dir(path)?.peekable();
        loop {
            let entry = match dir_iter.next() {
                Some(e) => e,
                None => {
                    break;
                }
            };
            let next_item = entry?;
            let next_path = next_item.path();
            let path_as_string = String::from(next_path.to_string_lossy());
            if next_path.is_dir() && recurse {
                if let Err(e) = visit_ucg_files(
                    &next_path,
                    recurse,
                    validate,
                    strict,
                    import_paths,
                    cache.clone(),
                    registry,
                ) {
                    eprintln!("{}", e);
                    result = false;
                }
            } else {
                if validate && path_as_string.ends_with("_test.ucg") {
                    if !do_validate(
                        &path_as_string,
                        strict,
                        import_paths,
                        cache.clone(),
                        registry,
                    ) {
                        result = false;
                        summary.push_str(format!("{} - FAIL\n", path_as_string).as_str())
                    } else {
                        summary.push_str(format!("{} - PASS\n", path_as_string).as_str())
                    }
                } else if !validate && path_as_string.ends_with(".ucg") {
                    if !do_compile(
                        &path_as_string,
                        strict,
                        import_paths,
                        cache.clone(),
                        registry,
                    ) {
                        result = false;
                    }
                }
            }
        }
    } else if validate && our_path.ends_with("_test.ucg") {
        if !do_validate(&our_path, strict, import_paths, cache, registry) {
            result = false;
            summary.push_str(format!("{} - FAIL\n", our_path).as_str());
        } else {
            summary.push_str(format!("{} - PASS\n", &our_path).as_str());
        }
    } else if !validate {
        if !do_compile(&our_path, strict, import_paths, cache, registry) {
            result = false;
        }
    }
    if validate && !summary.is_empty() {
        println!("RESULTS:");
        println!("{}", summary);
    }
    Ok(result)
}

fn inspect_command<C: Cache>(
    matches: &clap::ArgMatches,
    import_paths: &Vec<PathBuf>,
    cache: Rc<RefCell<C>>,
    registry: &ConverterRegistry,
    strict: bool,
) {
    let file = matches.value_of("INPUT");
    let sym = matches.value_of("expr");
    let target = matches.value_of("target").unwrap_or("json");
    let mut builder = build::FileBuilder::new(
        std::env::current_dir().unwrap(),
        import_paths,
        cache,
        registry,
    );
    builder.set_strict(strict);
    match registry.get_converter(target) {
        Some(converter) => {
            if let Some(file) = file {
                if let Err(e) = builder.build(file) {
                    eprintln!("{:?}", e);
                    process::exit(1);
                }
            }
            let val = match sym {
                Some(sym_name) => {
                    let normalized = if !sym_name.ends_with(";") {
                        let mut temp = sym_name.to_owned();
                        temp.push_str(";");
                        temp
                    } else {
                        sym_name.to_owned()
                    };
                    let mut builder = builder.clone_builder();
                    match builder.eval_string(&normalized) {
                        Ok(v) => Some(v.clone()),
                        Err(e) => {
                            eprintln!("{}", e);
                            process::exit(1);
                        }
                    }
                }
                None => builder.last,
            };
            match val {
                Some(value) => {
                    // We use None here because we always output to stdout for an inspect.
                    run_converter(converter, value, None).unwrap();
                    println!("");
                    process::exit(0);
                }
                None => {
                    eprintln!("No value.");
                    process::exit(1);
                }
            }
        }
        None => {
            eprintln!(
                "No such format {}\nrun `ucg converters` to see available formats.",
                target
            );
            process::exit(1);
        }
    }
}

fn build_command<C: Cache>(
    matches: &clap::ArgMatches,
    import_paths: &Vec<PathBuf>,
    cache: Rc<RefCell<C>>,
    registry: &ConverterRegistry,
    strict: bool,
) {
    let files = matches.values_of("INPUT");
    let recurse = matches.is_present("recurse");
    let mut ok = true;
    if files.is_none() {
        let curr_dir = std::env::current_dir().unwrap();
        let ok = visit_ucg_files(
            curr_dir.as_path(),
            recurse,
            false,
            strict,
            import_paths,
            cache.clone(),
            &registry,
        );
        if let Ok(false) = ok {
            process::exit(1)
        }
        process::exit(0);
    }
    for file in files.unwrap() {
        let pb = PathBuf::from(file);
        if let Ok(false) = visit_ucg_files(
            &pb,
            recurse,
            false,
            strict,
            import_paths,
            cache.clone(),
            &registry,
        ) {
            ok = false;
        }
    }
    if !ok {
        process::exit(1)
    }
}

fn fmt_file(p: &Path, indent: usize) -> std::result::Result<(), Box<dyn Error>> {
    let mut f = File::open(p)?;
    let mut contents = String::new();
    f.read_to_string(&mut contents)?;
    let mut comment_map = BTreeMap::new();
    let stmts = parse(OffsetStrIter::new(&contents), Some(&mut comment_map))?;
    let mut printer = ucglib::ast::printer::AstPrinter::new(indent, std::io::stdout())
        .with_comment_map(&comment_map);
    printer.render(&stmts)?;
    Ok(())
}

fn fmt_dir(p: &Path, recurse: bool, indent: usize) -> std::result::Result<(), Box<dyn Error>> {
    // TODO(jwall): We should handle this error more gracefully
    // for the user here.
    let dir_iter = std::fs::read_dir(p)?.peekable();
    for entry in dir_iter {
        let next_item = entry.unwrap();
        let path = next_item.path();
        if path.is_dir() && recurse {
            fmt_dir(&path, recurse, indent)?;
        } else {
            fmt_file(&path, indent)?;
        }
    }
    Ok(())
}

fn fmt_command(matches: &clap::ArgMatches) -> std::result::Result<(), Box<dyn Error>> {
    let files = matches.values_of("INPUT");
    let recurse = matches.is_present("recurse");
    let indent = match matches.value_of("indent") {
        Some(s) => s.parse::<usize>()?,
        None => 4,
    };

    let mut paths = Vec::new();
    if files.is_none() {
        paths.push(std::env::current_dir()?);
    } else {
        for f in files.unwrap() {
            paths.push(PathBuf::from(f));
        }
    }
    for p in paths {
        if p.is_dir() {
            fmt_dir(&p, recurse, indent)?;
        } else {
            fmt_file(&p, indent)?;
        }
    }
    Ok(())
}

fn test_command<C: Cache>(
    matches: &clap::ArgMatches,
    import_paths: &Vec<PathBuf>,
    cache: Rc<RefCell<C>>,
    registry: &ConverterRegistry,
    strict: bool,
) {
    let files = matches.values_of("INPUT");
    let recurse = matches.is_present("recurse");
    if files.is_none() {
        let curr_dir = std::env::current_dir().unwrap();
        let ok = visit_ucg_files(
            curr_dir.as_path(),
            recurse,
            true,
            strict,
            import_paths,
            cache.clone(),
            &registry,
        );
        if let Ok(false) = ok {
            process::exit(1)
        }
    } else {
        let mut ok = true;
        for file in files.unwrap() {
            let pb = PathBuf::from(file);
            //if pb.is_dir() {
            if let Ok(false) = visit_ucg_files(
                pb.as_path(),
                recurse,
                true,
                strict,
                import_paths,
                cache.clone(),
                &registry,
            ) {
                ok = false;
            }
        }
        if !ok {
            process::exit(1)
        }
    }
    process::exit(0);
}

fn converters_command(matches: &clap::ArgMatches, registry: &ConverterRegistry) {
    if let Some(ref cname) = matches.value_of("converter") {
        let mut found = false;
        for (name, c) in registry.get_converter_list().iter() {
            if cname == name {
                println!("* {}", name);
                println!("Description: {}", c.description());
                println!("Output Extension: `.{}`", c.file_ext());
                println!("");
                println!("{}", c.help());
                found = true;
            }
        }
        if !found {
            println!("No such converter {}", cname);
            process::exit(1);
        }
    } else {
        println!("Available converters:");
        println!("");
        for (name, c) in registry.get_converter_list().iter() {
            println!("* {}", name);
            println!("Description: {}", c.description());
            println!("Output Extension: `.{}`", c.file_ext());
            println!("");
        }
    }
}

fn importers_command(registry: &ImporterRegistry) {
    println!("Available importers");
    println!("");
    for (name, _importer) in registry.get_importer_list().iter() {
        println!("- {}", name);
    }
}

fn env_help() {
    println!(
        include_str!("help/env.txt"),
        std::env::var("UCG_IMPORT_PATH").unwrap_or(String::new())
    );
}

fn print_repl_help() {
    println!(include_str!("help/repl.txt"));
}

fn do_repl<C: Cache>(
    import_paths: &Vec<PathBuf>,
    cache: Rc<RefCell<C>>,
    registry: &ConverterRegistry,
) -> std::result::Result<(), Box<dyn Error>> {
    let config = rustyline::Config::builder();
    let mut editor = rustyline::Editor::<()>::with_config(
        config
            .history_ignore_space(true)
            .history_ignore_dups(false)
            .build(),
    );
    let path_home = dirs::home_dir().unwrap_or(std::env::temp_dir());
    let config_home = std::env::var("XDG_CACHE_HOME")
        .unwrap_or_else(|_| format!("{}/.cache", path_home.to_string_lossy()));
    let mut config_home = PathBuf::from(config_home);
    config_home.push("ucg");
    config_home.push("line_hist");
    if editor.load_history(&config_home).is_err() {
        eprintln!(
            "No history file {} Continuing without history.",
            config_home.to_string_lossy()
        );
        // introduce a scope so the file will get automatically closed after
        {
            let base_dir = config_home.parent().unwrap();
            if !base_dir.exists() {
                if let Err(e) = std::fs::create_dir_all(base_dir) {
                    eprintln!("{}", e);
                }
            }
            if let Err(e) = std::fs::File::create(&config_home) {
                eprintln!("{}", e);
            }
        }
    }
    let mut builder =
        build::FileBuilder::new(std::env::current_dir()?, import_paths, cache, registry);
    // loop
    let mut lines = ucglib::io::StatementAccumulator::new();
    println!("Welcome to the UCG repl. Ctrl-D to exit");
    println!("Type '#help' for help.");
    println!("");
    loop {
        // print prompt
        let line = editor.readline(&format!("{}> ", lines.next_line()))?;
        // TODO check for a repl command.
        // repl commands are only valid while not accumulating a statement;
        let trimmed = line.trim();
        if trimmed.starts_with("#") {
            // handle the various commands.
            if trimmed.starts_with("#help") {
                print_repl_help();
            } else if trimmed.starts_with("#del") {
                // remove a named binding from the builder output.
                let args: Vec<&str> = trimmed.split(" ").skip(1).collect();
                if args.len() != 1 {
                    // print usage of the #del command
                    eprintln!("The '#del' command expects a single argument specifying \nthe binding to delete.");
                } else {
                    let key = ucglib::ast::PositionedItem {
                        pos: ucglib::ast::Position::new(0, 0, 0),
                        val: args[0].to_string(),
                    };
                    if let None = builder.scope_mut().build_output.remove(&key) {
                        eprintln!("No such binding {}", key.val);
                    }
                }
            } else {
                eprintln!("Invalid repl command...");
                eprintln!("");
                print_repl_help();
            }
            continue;
        }
        lines.push(line);
        // check to see if that line is a statement
        loop {
            // read a statement
            if let Some(stmt) = lines.get_statement() {
                // if it is then
                // eval statement
                match builder.eval_string(&stmt) {
                    // print the result
                    Err(e) => eprintln!("{}", e),
                    Ok(v) => {
                        if builder.out_lock.is_some() {
                            process_output(&builder.out_lock, None, registry);
                            builder.out_lock = None;
                        } else {
                            println!("{}", v);
                            editor.history_mut().add(stmt);
                            editor.save_history(&config_home)?;
                        }
                    }
                }
                // start loop over at prompt.
                break;
            }
            // if not then keep accumulating lines without a prompt
            lines.push(editor.readline(&format!("{}> ", lines.next_line()))?);
        }
    }
}

fn repl<C: Cache>(
    import_paths: &Vec<PathBuf>,
    cache: Rc<RefCell<C>>,
    registry: &ConverterRegistry,
) {
    if let Err(e) = do_repl(import_paths, cache, registry) {
        eprintln!("{}", e);
        process::exit(1);
    }
}

fn main() {
    let mut app = do_flags();
    let app_matches = app.clone().get_matches();
    let cache = Rc::new(RefCell::new(MemoryCache::new()));
    let registry = ConverterRegistry::make_registry();
    let mut import_paths = Vec::new();
    if let Some(mut p) = dirs::home_dir() {
        p.push(".ucg");
        // Attempt to create directory if it doesn't exist.
        if !p.exists() {
            std::fs::create_dir(&p).unwrap();
        }
        import_paths.push(p);
    }
    if let Ok(path_list_str) = std::env::var("UCG_IMPORT_PATH") {
        for p in std::env::split_paths(&path_list_str) {
            import_paths.push(p);
        }
    }
    let strict = if app_matches.is_present("nostrict") {
        false
    } else {
        true
    };
    if let Some(matches) = app_matches.subcommand_matches("eval") {
        inspect_command(matches, &import_paths, cache, &registry, strict);
    } else if let Some(matches) = app_matches.subcommand_matches("build") {
        build_command(matches, &import_paths, cache, &registry, strict);
    } else if let Some(matches) = app_matches.subcommand_matches("test") {
        test_command(matches, &import_paths, cache, &registry, strict);
    } else if let Some(matches) = app_matches.subcommand_matches("converters") {
        converters_command(matches, &registry)
    } else if let Some(_) = app_matches.subcommand_matches("importers") {
        let registry = ImporterRegistry::make_registry();
        importers_command(&registry)
    } else if let Some(_) = app_matches.subcommand_matches("env") {
        env_help()
    } else if let Some(_) = app_matches.subcommand_matches("repl") {
        repl(&import_paths, cache, &registry)
    } else if let Some(matches) = app_matches.subcommand_matches("fmt") {
        if let Err(e) = fmt_command(matches) {
            eprintln!("{}", e);
        }
    } else {
        app.print_help().unwrap();
        println!("");
    }
}