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
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate serde;
#[macro_use]
extern crate origen;

mod app_commands;
mod commands;
mod python;

use app_commands::AppCommands;
use clap::{App, AppSettings, Arg, SubCommand};
use indexmap::map::IndexMap;
use origen::utility::version::to_pep440;
use origen::{LOGGER, STATUS};
use std::path::Path;

#[derive(Clone)]
pub struct CommandHelp {
    name: String,
    help: String,
    shortcut: Option<String>,
}

impl CommandHelp {
    fn render(&self, width: usize) -> String {
        let mut msg = "".to_string();
        msg += &format!("{:width$} {}", self.name, self.help, width = width + 3);
        if let Some(a) = &self.shortcut {
            msg += &format!(" [aliases: {}]", a);
        }
        msg += "\n";
        msg
    }
}

// This is the entry point for the Origen CLI tool
fn main() {
    let verbosity_re = regex::Regex::new(r"-([vV]+)").unwrap();

    // Intercept the 'origen exec' command immediately to prevent further parsing of it, this
    // is so that something like 'origen exec pytest -v' will apply '-v' as an argument to pytest
    // and not to origen
    let mut args: Vec<String> = std::env::args().collect();
    if args.len() > 1 && args[1] == "exec" {
        args = args.drain(2..).collect();
        if args.len() > 0 && (args[0] == "-h" || args[0] == "--help" || args[0] == "help") {
            // Just fall through to display the help in this case
        } else {
            // Apply any leading -vvv to origen, any -v later in the args will be applied to the
            // 3rd party command
            if args.len() > 0 && verbosity_re.is_match(&args[0]) {
                let captures = verbosity_re.captures(&args[0]).unwrap();
                let x = captures.get(1).unwrap().as_str();
                let verbosity = x.chars().count() as u8;
                origen::initialize(Some(verbosity), None);
                args = args.drain(1..).collect();
            }
            // Commmand is not actually available outside an app, so just fall through
            // to generate the appropriate error
            if STATUS.is_app_present {
                if args.len() > 0 {
                    let cmd = args[0].clone();
                    args = args.drain(1..).collect();
                    let cmd_args: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
                    commands::exec::run(&cmd, cmd_args);
                } else {
                    std::process::exit(0);
                }
            }
        }
    }

    // Set the verbosity immediately, this is to allow log statements to work in really
    // low level stuff, e.g. when building the STATUS
    let mut verbosity: u8 = 0;
    for arg in std::env::args() {
        if let Some(captures) = verbosity_re.captures(&arg) {
            let x = captures.get(1).unwrap().as_str();
            verbosity = x.chars().count() as u8;
        }
    }
    let exe = match std::env::current_exe() {
        Ok(p) => Some(format!("{}", p.display())),
        Err(e) => {
            log_error!("{}", e);
            None
        }
    };
    origen::initialize(Some(verbosity), exe);

    let version = match STATUS.is_app_present {
        true => format!(
            "Origen CLI: {}",
            to_pep440(&STATUS.origen_version.to_string()).unwrap_or("Error".to_string())
        ),
        false => format!(
            "Origen: {}",
            to_pep440(&STATUS.origen_version.to_string()).unwrap_or("Error".to_string())
        ),
    };
    if STATUS.app.is_some() {
        origen::core::application::config::Config::check_defaults(
            &STATUS.app.as_ref().unwrap().root,
        );
    }

    let mut app = App::new("")
        .setting(AppSettings::ArgRequiredElseHelp)
        .setting(AppSettings::VersionlessSubcommands)
        .setting(AppSettings::DisableVersion)
        .before_help("Origen, The Semiconductor Developer's Kit")
        .after_help("See 'origen <command> -h' for more information on a specific command.")
        .version(&*version)
        .arg(
            Arg::with_name("verbose")
                .short("v")
                .multiple(true)
                .global(true)
                .help("Terminal verbosity level e.g. -v, -vv, -vvv"),
        );

    // The main help message is going to be automatically generated to allow us to handle and clearly
    // separate commands added by the app and plugins.
    // When a command is added below it must also be added to these vectors.
    let mut origen_commands: Vec<CommandHelp> = vec![];
    let mut app_commands: Vec<CommandHelp> = vec![];

    /************************************************************************************/
    /******************** Global only commands ******************************************/
    /************************************************************************************/
    if !STATUS.is_app_present {
        //************************************************************************************/
        let proj_help = "Manage multi-repository project areas and workspaces";
        origen_commands.push(CommandHelp {
            name: "proj".to_string(),
            help: proj_help.to_string(),
            shortcut: None,
        });

        app = app
            .subcommand(
                SubCommand::with_name("proj")
                    .display_order(1)
                    .about(proj_help)
                    .setting(AppSettings::ArgRequiredElseHelp)
                    .subcommand(SubCommand::with_name("init")
                        .display_order(5)
                        .about("Initialize a new project directory (create an initial project BOM)")
                        .arg(Arg::with_name("dir")
                            .takes_value(true)
                            .help("The path to the project directory to initialize (PWD will be used by default if not given)")
                            .value_name("DIR")
                        )
                    )
                    .subcommand(SubCommand::with_name("packages")
                        .display_order(7)
                        .about("Displays the IDs of all packages and package groups defined by the BOM")
                    )
                    .subcommand(SubCommand::with_name("create")
                        .display_order(10)
                        .about("Create a new project workspace from the project BOM")
                        .arg(Arg::with_name("path")
                            .help("The path to the new workspace directory")
                            .takes_value(true)
                            .value_name("PATH")
                            .required(true)
                        )
                    )
                    .subcommand(SubCommand::with_name("update")
                        .display_order(15)
                        .about("Update an existing project workspace per its current BOM")
                        .arg(Arg::with_name("force")
                            .short("f")
                            .long("force")
                            .required(false)
                            .takes_value(false)
                            .help("Force the update and potentially lose any local modifications")
                        )
                        .arg(Arg::with_name("links")
                            .short("l")
                            .long("links")
                            .required(false)
                            .takes_value(false)
                            .help("Update the workspace links")
                        )
                        .arg(Arg::with_name("packages")
                            .value_name("PACKAGES")
                            .takes_value(true)
                            .multiple(true)
                            .help("Packages and/or groups to be updated, run 'origen proj packages' to see a list of possible package IDs")
                            .required_unless("links")
                            .required(true)
                        )
                    )
                    .subcommand(SubCommand::with_name("mods")
                        .display_order(20)
                        .about("Display a list of modified files within the given package(s)")
                        .arg(Arg::with_name("packages")
                            .help("Package(s) to look for modifications in, use 'all' to see the modification to all packages")
                            .multiple(true)
                            .value_name("PACKAGES")
                            .required(true)
                        )
                    )
                    .subcommand(SubCommand::with_name("clean")
                        .display_order(20)
                        .about("Revert all local modifications within the given package(s)")
                        .arg(Arg::with_name("packages")
                            .help("Package(s) to revert local modifications in, use 'all' to clean all packages")
                            .multiple(true)
                            .value_name("PACKAGES")
                            .required(true)
                        )
                    )
                    .subcommand(SubCommand::with_name("tag")
                        .display_order(20)
                        .about("Apply the given tag to the current view of the given package(s)")
                        .arg(Arg::with_name("name")
                            .help("Name of the tag to be applied")
                            .takes_value(true)
                            .value_name("NAME")
                            .required(true)
                        )
                        .arg(Arg::with_name("packages")
                            .help("Package(s) to be tagged, use 'all' to tag all packages")
                            .multiple(true)
                            .takes_value(true)
                            .value_name("PACKAGES")
                            .required(true)
                        )
                        .arg(Arg::with_name("force")
                            .short("f")
                            .long("force")
                            .required(false)
                            .takes_value(false)
                            .help("Force the application of the tag even if there are local modifications")
                        )
                        .arg(Arg::with_name("message")
                            .short("m")
                            .long("message")
                            .required(false)
                            .takes_value(true)
                            .help("A message to be applied with the tag")
                        )
                    )
                    .subcommand(SubCommand::with_name("bom")
                        .display_order(25)
                        .about("View the active BOM in the current or given directory")
                        .arg(Arg::with_name("dir")
                            .takes_value(true)
                            .help("The path to a directory (PWD will be used by default if not given)")
                            .value_name("DIR")
                        )
                    )
            );

        //************************************************************************************/
        let new_help = "Create a new Origen application";
        origen_commands.push(CommandHelp {
            name: "new".to_string(),
            help: new_help.to_string(),
            shortcut: None,
        });
        app = app.subcommand(
            SubCommand::with_name("new").about(new_help).arg(
                Arg::with_name("name")
                    .help("The lowercased and underscored name of the new application")
                    .takes_value(true)
                    .required(true)
                    .number_of_values(1)
                    .value_name("NAME"),
            )
            .arg(Arg::with_name("setup")
                .help("Don't create the new app's virtual environment after building (need to manually run 'origen env setup' within the new app workspace before using it in that case)")
                .long("no-setup")
                .required(false)
                .takes_value(false)
            ),
        );
    }

    /************************************************************************************/
    /******************** Global and app commands ***************************************/
    /************************************************************************************/

    /************************************************************************************/
    /******************** Origen dev commands *******************************************/
    /************************************************************************************/
    if STATUS.is_origen_present || STATUS.is_app_present {
        let fmt_help = match STATUS.is_origen_present {
            true => "Nicely format all Rust and Python files",
            false => "Nicely format all of your application's Python files",
        };

        origen_commands.push(CommandHelp {
            name: "fmt".to_string(),
            help: fmt_help.to_string(),
            shortcut: None,
        });

        app = app
            //************************************************************************************/
            .subcommand(SubCommand::with_name("fmt").about(fmt_help));
    }

    if STATUS.is_origen_present || STATUS.is_app_in_origen_dev_mode {
        let build_help = match STATUS.is_origen_present {
            true => "Build and publish Origen, builds the pyapi Rust package by default",
            false => "Build Origen",
        };

        origen_commands.push(CommandHelp {
            name: "build".to_string(),
            help: build_help.to_string(),
            shortcut: None,
        });

        //************************************************************************************/
        let mut sub = SubCommand::with_name("build").about(build_help).arg(
            Arg::with_name("cli")
                .long("cli")
                .required(false)
                .takes_value(false)
                .display_order(1)
                .help("Build the CLI (instead of the Python API)"),
        );

        if STATUS.is_origen_present {
            sub = sub
                .arg(
                    Arg::with_name("release")
                        .long("release")
                        .required(false)
                        .takes_value(false)
                        .display_order(1)
                        .help("Build a release version (applied by default with --publish and only applicable to Rust builds)"),
                )
                .arg(
                    Arg::with_name("target")
                        .long("target")
                        .required(false)
                        .takes_value(true)
                        .display_order(1)
                        .help("The Rust h/ware target (passed directly to Cargo build)"),
                )
                .arg(
                    Arg::with_name("python")
                        .long("python")
                        .required(false)
                        .takes_value(false)
                        .display_order(1)
                        .help("Build the pure Python package (instead of the Python API)"),
                )
                .arg(
                    Arg::with_name("publish")
                        .long("publish")
                        .required(false)
                        .takes_value(false)
                        .display_order(1)
                        .help("Publish packages (e.g. to PyPI) after building"),
                )
                .arg(
                    Arg::with_name("dry_run")
                        .long("dry-run")
                        .required(false)
                        .takes_value(false)
                        .display_order(1)
                        .help("Use with --publish to perform a full dry run of the publishable build without actually publishing it"),
                )
                .arg(
                    Arg::with_name("version")
                        .long("version")
                        .required(false)
                        .takes_value(true)
                        .value_name("VERSION")
                        .display_order(1)
                        .help("Set the version (of all components) to the given value"),
                );
        }

        app = app.subcommand(sub);
    }

    /************************************************************************************/
    /******************** In application commands ***************************************/
    /************************************************************************************/
    if STATUS.is_app_present {
        /************************************************************************************/
        let i_help = "Start an Origen console to interact with the DUT";
        origen_commands.push(CommandHelp {
            name: "interactive".to_string(),
            help: i_help.to_string(),
            shortcut: Some("i".to_string()),
        });
        app = app.subcommand(
            SubCommand::with_name("interactive")
                .about(i_help)
                .visible_alias("i")
                .arg(
                    Arg::with_name("target")
                        .short("t")
                        .long("target")
                        .help("Override the default target currently set by the workspace")
                        .takes_value(true)
                        .use_delimiter(true)
                        .multiple(true)
                        .number_of_values(1)
                        .value_name("TARGET"),
                )
                .arg(
                    Arg::with_name("mode")
                        .short("m")
                        .long("mode")
                        .help("Override the default execution mode currently set by the workspace")
                        .takes_value(true)
                        .value_name("MODE"),
                ),
        );

        /************************************************************************************/
        let new_help = "Generate a new block, flow, pattern, etc. for your application";
        origen_commands.push(CommandHelp {
            name: "new".to_string(),
            help: new_help.to_string(),
            shortcut: None,
        });
        app = app.subcommand(
            SubCommand::with_name("new")
            .about(new_help)
            .setting(AppSettings::ArgRequiredElseHelp)
            .subcommand(SubCommand::with_name("dut")
                .display_order(5)
                .about("Create a new top-level (DUT) block, see 'origen new dut -h' for more info")
                .long_about(
"This generator creates a top-level (DUT) block and all of the associated resources for it, e.g. a
reg file, controller, target, timesets, pins, etc.

The NAME of the DUT should be given in lower case, optionally prefixed by parent DUT name(s) separated
by a forward slash.

Any parent DUT(s) will be created if they don't exist, but they will not be modified if they do.

Examples:
  origen new dut                # Creates <app_name>/blocks/dut/...
  origen new dut falcon         # Creates <app_name>/blocks/dut/derivatives/falcon/...
  origen new dut dsp/falcon     # Creates <app_name>/blocks/dut/derivatives/dsp/derivatives/falcon/...")
                .arg(Arg::with_name("name")
                    .takes_value(true)
                    .required(false)
                    .help("The name of the new DUT")
                    .value_name("NAME")
                )
            )
            .subcommand(SubCommand::with_name("block")
                .display_order(5)
                .about("Create a new block, see 'origen new block -h' for more info")
                .long_about(
"This generator creates a block (e.g. to represent RAM, ATD, Flash, DAC, etc.) and all of the associated
resources for it, e.g. a reg file, controller, timesets, etc.

The NAME should be given in lower case (e.g. flash/flash2kb, adc/adc16), optionally with
additional parent sub-block names after the initial type.

Alternatively, a reference to an existing BLOCK can be added, in which case a nested block will be created
within that block's 'blocks/' directory, rather than a primary top-level block.

Any parent block(s) will be created if they don't exist, but they will not be modified if they do.

Examples:
  origen new block dac                  # Creates <app_name>/blocks/dac/...
  origen new block adc/adc8bit          # Creates <app_name>/blocks/adc/derivatives/adc8bit/...
  origen new block adc/adc16bit         # Creates <app_name>/blocks/adc/derivatives/adc16bit/...
  origen new block nvm/flash/flash2kb   # Creates <app_name>/blocks/nvm/derivatives/flash/derivatives/flash2kb/...

  # Example of creating a nested sub-block
  origen new block bist --parent nvm/flash   # Creates <app_name>/blocks/nvm/derivatives/flash/blocks/bist/...")
                .arg(Arg::with_name("name")
                    .takes_value(true)
                    .required(true)
                    .help("The name of the new block, including its parents if applicable")
                    .value_name("NAME")
                )
                .arg(
                    Arg::with_name("parent")
                        .short("p")
                        .long("parent")
                        .help("Create the new block nested within this existing block")
                        .takes_value(true)
                        .required(false)
                        .value_name("PARENT")
                )
            )
        );

        /************************************************************************************/
        let g_help = "Generate patterns or test programs";
        origen_commands.push(CommandHelp {
            name: "generate".to_string(),
            help: g_help.to_string(),
            shortcut: Some("g".to_string()),
        });
        app = app.subcommand(
            SubCommand::with_name("generate")
                .about(g_help)
                .visible_alias("g")
                .arg(
                    Arg::with_name("files")
                        .help("The name of the file(s) to be generated")
                        .takes_value(true)
                        .value_name("FILES")
                        .multiple(true)
                        .required(true),
                )
                .arg(
                    Arg::with_name("target")
                        .short("t")
                        .long("target")
                        .help("Override the default target currently set by the workspace")
                        .takes_value(true)
                        .use_delimiter(true)
                        .multiple(true)
                        .number_of_values(1)
                        .value_name("TARGET"),
                )
                .arg(
                    Arg::with_name("mode")
                        .short("m")
                        .long("mode")
                        .help("Override the default execution mode currently set by the workspace")
                        .takes_value(true)
                        .value_name("MODE"),
                )
                .arg(
                    Arg::with_name("output_dir")
                        .short("o")
                        .long("output-dir")
                        .help("Override the default output directory (<APP ROOT>/output)")
                        .takes_value(true)
                        .value_name("OUTPUT_DIR"),
                )
                .arg(
                    Arg::with_name("reference_dir")
                        .short("r")
                        .long("reference-dir")
                        .help("Override the default reference directory (<APP ROOT>/.ref)")
                        .takes_value(true)
                        .value_name("REFERENCE_DIR"),
                )
                .arg(
                    Arg::with_name("debug")
                        .long("debug")
                        .short("d")
                        .help("Enable Python caller tracking for debug (takes longer to execute)")
                        .takes_value(false),
                ),
        );

        /************************************************************************************/
        let c_help = "Compile templates";
        origen_commands.push(CommandHelp {
            name: "compile".to_string(),
            help: c_help.to_string(),
            shortcut: Some("c".to_string()),
        });
        app = app.subcommand(
            SubCommand::with_name("compile")
                .about(c_help)
                .visible_alias("c")
                .arg(
                    Arg::with_name("files")
                        .help("The name of the file(s) to be generated")
                        .takes_value(true)
                        .value_name("FILES")
                        .multiple(true)
                        .required(true),
                )
                .arg(
                    Arg::with_name("target")
                        .short("t")
                        .long("target")
                        .help("Override the default target currently set by the workspace")
                        .takes_value(true)
                        .use_delimiter(true)
                        .multiple(true)
                        .number_of_values(1)
                        .value_name("TARGET"),
                )
                .arg(
                    Arg::with_name("mode")
                        .short("m")
                        .long("mode")
                        .help("Override the default execution mode currently set by the workspace")
                        .takes_value(true)
                        .value_name("MODE"),
                ),
        );

        /************************************************************************************/
        let t_help = "Set/view the default target";
        origen_commands.push(CommandHelp {
            name: "target".to_string(),
            help: t_help.to_string(),
            shortcut: Some("t".to_string()),
        });
        app = app.subcommand(
            SubCommand::with_name("target")
                .about(t_help)
                .visible_alias("t")
                .arg(
                    Arg::with_name("full-paths")
                        .long("full-paths")
                        .short("f")
                        .help("Display targets' full paths")
                        .takes_value(false),
                )
                .subcommand(
                    SubCommand::with_name("add")
                        .about("Activates the given target(s)")
                        .visible_alias("a")
                        .arg(
                            Arg::with_name("targets")
                                .help("Targets to be activated")
                                .takes_value(true)
                                .value_name("TARGETS")
                                .multiple(true)
                                .required(true),
                        )
                        .arg(
                            Arg::with_name("full-paths")
                                .long("full-paths")
                                .short("f")
                                .help("Display targets' full paths")
                                .takes_value(false),
                        ),
                )
                .subcommand(
                    SubCommand::with_name("remove")
                        .about("Deactivates the given target(s)")
                        .visible_alias("r")
                        .arg(
                            Arg::with_name("targets")
                                .help("Targets to be deactivated")
                                .takes_value(true)
                                .value_name("TARGETS")
                                .multiple(true)
                                .required(true),
                        )
                        .arg(
                            Arg::with_name("full-paths")
                                .long("full-paths")
                                .short("f")
                                .help("Display targets' full paths")
                                .takes_value(false),
                        ),
                )
                .subcommand(
                    SubCommand::with_name("set")
                        .about("Activates the given target(s) while deactivating all others")
                        .visible_alias("s")
                        .arg(
                            Arg::with_name("targets")
                                .help("Targets to be set")
                                .takes_value(true)
                                .value_name("TARGETS")
                                .multiple(true)
                                .required(true),
                        )
                        .arg(
                            Arg::with_name("full-paths")
                                .long("full-paths")
                                .short("f")
                                .help("Display targets' full paths")
                                .takes_value(false),
                        ),
                )
                .subcommand(
                    SubCommand::with_name("default")
                        .about("Activates the default target(s) while deactivating all others")
                        .visible_alias("d")
                        .arg(
                            Arg::with_name("full-paths")
                                .long("full-paths")
                                .short("f")
                                .help("Display targets' full paths")
                                .takes_value(false),
                        ),
                )
                .subcommand(
                    SubCommand::with_name("view")
                        .about("Views the currently activated target(s)")
                        .visible_alias("v")
                        .arg(
                            Arg::with_name("full-paths")
                                .long("full-paths")
                                .short("f")
                                .help("Display targets' full paths")
                                .takes_value(false),
                        ),
                ),
        );

        /************************************************************************************/
        let t_help = "Create, Build, and View Web Documentation";
        origen_commands.push(CommandHelp {
            name: "web".to_string(),
            help: t_help.to_string(),
            shortcut: Some("w".to_string()),
        });
        app = app.subcommand(
            SubCommand::with_name("web")
                .about(t_help)
                .setting(AppSettings::ArgRequiredElseHelp)
                .visible_alias("w")
                .subcommand(
                    SubCommand::with_name("build") // What I think this command should be called
                        .about("Builds the web documentation")
                        .visible_alias("b")
                        .visible_alias("compile") // If coming from O1
                        .visible_alias("html") // If coming from Sphinx and using quickstart's Makefile
                        .arg(
                            Arg::with_name("view")
                                .long("view")
                                .help("Launch your web browser after the build")
                                .takes_value(false),
                        )
                        .arg(
                            Arg::with_name("clean")
                                .long("clean")
                                .help(
                                    "Clean up directories from previous builds and force a rebuild",
                                )
                                .takes_value(false),
                        )
                        .arg(
                            Arg::with_name("release")
                                .long("release")
                                .short("r")
                                .help("Release (deploy) the resulting web pages")
                                .takes_value(false),
                        )
                        .arg(
                            Arg::with_name("archive")
                                .long("archive")
                                .short("a")
                                .help("Archive the resulting web pages after building")
                                .takes_value(true)
                                .multiple(false)
                                .min_values(0),
                        )
                        .arg(
                            Arg::with_name("as-release")
                                .long("as-release")
                                .help("Build webpages with release checks")
                                .takes_value(false),
                        )
                        .arg(
                            Arg::with_name("release-with-warnings")
                                .long("release-with-warnings")
                                .help("Release webpages even if warnings persists")
                                .takes_value(false),
                        )
                        .arg(
                            Arg::with_name("no-api")
                                .long("no-api")
                                .help("Skip building the API")
                                .takes_value(false),
                        )
                        .arg(
                            Arg::with_name("sphinx-args")
                                .long("sphinx-args")
                                .help(
                                    "Additional arguments to pass to the 'sphinx-build' command
  Argument will passed as a single string and appended to the build command
  E.g.: 'origen web build --sphinx-args \"-q -D my_config_define=1\"'
     -> 'sphinx-build <source_dir> <output_dir> -q -D my_config_define=1'",
                                )
                                .takes_value(true)
                                .multiple(false)
                                .allow_hyphen_values(true),
                        ), // .arg(Arg::with_name("pdf")
                           //     .long("pdf")
                           //     .help("Create a PDF of resulting web pages")
                           //     .takes_value(false)
                           // )
                )
                .subcommand(
                    SubCommand::with_name("view")
                        .about("Launches your web browser to view previously built documentation")
                        .visible_alias("v"),
                )
                .subcommand(
                    SubCommand::with_name("clean")
                        .about("Cleans the output directory and all cached files"),
                ),
        );

        /************************************************************************************/
        let mailer_help =
            "Command-line-interface to Origen's mailer for quick emailing or shell-scripting";
        origen_commands.push(CommandHelp {
            name: "mailer".to_string(),
            help: mailer_help.to_string(),
            shortcut: None,
        });
        app = app.subcommand(
            SubCommand::with_name("mailer")
                .about(mailer_help)
                .setting(AppSettings::ArgRequiredElseHelp)
                .subcommand(
                    SubCommand::with_name("send")
                        .about("Quickly send an email")
                        .arg(
                            Arg::with_name("body")
                                .help("Email message body")
                                .long("body")
                                .takes_value(true)
                                .required(true)
                                .value_name("BODY")
                                .index(1),
                        )
                        .arg(
                            Arg::with_name("subject")
                                .help("Email subject line")
                                .long("subject")
                                .short("s")
                                .takes_value(true)
                                .value_name("SUBJECT"),
                        )
                        .arg(
                            Arg::with_name("to")
                                .help("Recipient list")
                                .long("to")
                                .short("t")
                                .takes_value(true)
                                .required(true)
                                .multiple(true)
                                .value_name("TO"),
                        ),
                )
                .subcommand(
                    SubCommand::with_name("test")
                        .about("Send a test email")
                        .arg(
                            Arg::with_name("to")
                                .help(
                                    "Recipient list. If omitted, will be sent to the current user",
                                )
                                .long("to")
                                .short("t")
                                .takes_value(true)
                                .required(false)
                                .multiple(true)
                                .value_name("TO"),
                        ),
                ),
        );

        /************************************************************************************/
        let credentials_help = "Set or clear user credentials";
        origen_commands.push(CommandHelp {
            name: "credentials".to_string(),
            help: credentials_help.to_string(),
            shortcut: None,
        });
        app = app.subcommand(
            SubCommand::with_name("credentials")
                .about(credentials_help)
                .setting(AppSettings::ArgRequiredElseHelp)
                .subcommand(
                    SubCommand::with_name("set")
                        .about("Set the current user's password")
                        .arg(
                            Arg::with_name("all")
                                .help("Set the password for all datasets")
                                .takes_value(false)
                                .required(false)
                                .long("all")
                                .short("a"),
                        )
                        .arg(
                            Arg::with_name("dataset")
                                .help("Specify the dataset to set the password for")
                                .takes_value(true)
                                .required(false)
                                .value_name("DATASET")
                                .multiple(true)
                                .conflicts_with("all")
                                .long("dataset")
                                .short("d"),
                        ),
                )
                .subcommand(
                    SubCommand::with_name("clear")
                        .about("Clear the user's password")
                        .arg(
                            Arg::with_name("all")
                                .help("Clear the password for all datasets")
                                .takes_value(false)
                                .required(false)
                                .conflicts_with("dataset")
                                .long("all")
                                .short("a"),
                        )
                        .arg(
                            Arg::with_name("dataset")
                                .help("Specify the dataset to clear the password for")
                                .takes_value(true)
                                .required(false)
                                .value_name("DATASET")
                                .multiple(true)
                                .long("dataset")
                                .short("d"),
                        ),
                ),
        );

        /************************************************************************************/
        let mode_help = "Set/view the default execution mode";
        origen_commands.push(CommandHelp {
            name: "mode".to_string(),
            help: mode_help.to_string(),
            shortcut: Some("m".to_string()),
        });
        app = app.subcommand(
            SubCommand::with_name("mode")
                .about(mode_help)
                .visible_alias("m")
                .arg(
                    Arg::with_name("mode")
                        .help("The name of the mode to be set as the default mode")
                        .takes_value(true)
                        .value_name("MODE"),
                ),
        );

        /************************************************************************************/
        let app_help = "Commands for packaging and releasing your application";
        origen_commands.push(CommandHelp {
            name: "app".to_string(),
            help: app_help.to_string(),
            shortcut: None,
        });
        app = app.subcommand(
            SubCommand::with_name("app")
                .about(app_help)
                .setting(AppSettings::ArgRequiredElseHelp)
                .subcommand(
                    SubCommand::with_name("package")
                        .about("Build the app into a Python package (a wheel)"),
                ),
        );

        /************************************************************************************/
        let env_help = "Manage your application's Origen/Python environment (dependencies, etc.)";
        origen_commands.push(CommandHelp {
            name: "env".to_string(),
            help: env_help.to_string(),
            shortcut: None,
        });
        app = app.subcommand(SubCommand::with_name("env").about(env_help)
            .setting(AppSettings::ArgRequiredElseHelp)
            .subcommand(
                SubCommand::with_name("setup")
                    .about("Setup your application's Python environment for the first time in a new workspace, this will install dependencies per the poetry.lock file")
                    .arg(Arg::with_name("origen")
                            .long("origen")
                            .help("The path to a local version of Origen to use (to develop Origen)")
                            .takes_value(true),
                    ),
            )
            .subcommand(
                SubCommand::with_name("update")
                    .about("Update your application's Python dependencies according to the latest pyproject.toml file"),
            )
        );

        /************************************************************************************/
        let exec_help = "Execute a command within your application's Origen/Python environment (e.g. origen exec pytest)";
        origen_commands.push(CommandHelp {
            name: "exec".to_string(),
            help: exec_help.to_string(),
            shortcut: None,
        });
        app = app.subcommand(
            SubCommand::with_name("exec")
                .about(exec_help)
                .setting(AppSettings::ArgRequiredElseHelp)
                .setting(AppSettings::DisableVersion)
                .setting(AppSettings::AllowLeadingHyphen)
                .arg(
                    Arg::with_name("cmd")
                        .help("The command to be run")
                        .takes_value(true)
                        .required(true)
                        .value_name("COMMAND"),
                )
                .arg(
                    Arg::with_name("args")
                        .help("Arguments to be passed to the command")
                        .takes_value(true)
                        .allow_hyphen_values(true)
                        .multiple(true)
                        .number_of_values(1)
                        .required(false)
                        //.last(true)
                        .value_name("ARGS"),
                ),
        );

        /************************************************************************************/
        let save_ref_help = "Save a reference version of the given file, this will be automatically checked for differences the next time it is generated";
        origen_commands.push(CommandHelp {
            name: "save_ref".to_string(),
            help: save_ref_help.to_string(),
            shortcut: None,
        });
        app = app.subcommand(
            SubCommand::with_name("save_ref")
                .about(save_ref_help)
                .arg(
                    Arg::with_name("files")
                        .help("The name of the file(s) to be saved")
                        .takes_value(true)
                        .value_name("FILES")
                        .multiple(true)
                        .required_unless_one(&["new", "changed"]),
                )
                .arg(
                    Arg::with_name("new")
                        .long("new")
                        .required(false)
                        .takes_value(false)
                        .help("Update all NEW file references from the last generate run"),
                )
                .arg(
                    Arg::with_name("changed")
                        .long("changed")
                        .required(false)
                        .takes_value(false)
                        .help("Update all CHANGED file references from the last generate run"),
                ),
        );
    }

    // This is used to justify the command names in the help
    let mut name_width = origen_commands
        .iter()
        .map(|c| c.name.chars().count())
        .max()
        .unwrap();

    let mut app_command_defs = AppCommands::new(Path::new("/"));
    let cmds;
    if STATUS.is_app_present {
        app_command_defs = AppCommands::new(&origen::app().unwrap().root);
        app_command_defs.parse_commands();
        // Need to hold this in a long-lived immutable reference for referencing in clap args
        cmds = app_command_defs.commands.clone();

        if let Some(width) = app_command_defs.max_name_width() {
            if width > name_width {
                name_width = width;
            }
        }
        for command in &app_command_defs.command_helps {
            app_commands.push(command.clone());
        }
        // This defines the application commands
        // For each command
        for i in 0..cmds.len() {
            let cmd = build_command(&cmds[i]);
            app = app.subcommand(cmd);
        }
    }

    // Clap is great, but its generated help doesn't give the flexibility needed to handle things
    // like app and plugin command additions, so we make our own

    let mut help_message = format!(
        "Origen, The Semiconductor Developer's Kit

{}

USAGE:
    origen [FLAGS] [COMMAND]
FLAGS:
    -h, --help       Prints help information
    -v               Terminal verbosity level e.g. -v, -vv, -vvv

CORE COMMANDS:
",
        version
    );

    for command in &origen_commands {
        help_message += &command.render(name_width);
    }

    if !app_commands.is_empty() {
        help_message += "\nAPP COMMANDS:\n";
        for command in &app_commands {
            help_message += &command.render(name_width);
        }
    }

    help_message += "\nSee 'origen <command> -h' for more information on a specific command.";

    app = app.help(help_message.as_str());

    let matches = app.get_matches();

    let _ = LOGGER.set_verbosity(matches.occurrences_of("verbose") as u8);

    match matches.subcommand_name() {
        Some("app") => commands::app::run(matches.subcommand_matches("app").unwrap()),
        Some("env") => commands::env::run(matches.subcommand_matches("env").unwrap()),
        Some("fmt") => commands::fmt::run(),
        Some("new") => commands::new::run(matches.subcommand_matches("new").unwrap()),
        Some("build") => commands::build::run(matches.subcommand_matches("build").unwrap()),
        Some("proj") => commands::proj::run(matches.subcommand_matches("proj").unwrap()),
        Some("interactive") => {
            log_trace!("Launching interactive session");
            let m = matches.subcommand_matches("interactive").unwrap();
            commands::interactive::run(
                if let Some(targets) = m.values_of("target") {
                    Some(targets.collect())
                } else {
                    Option::None
                },
                &m.value_of("mode"),
            );
        }
        Some("generate") => {
            let m = matches.subcommand_matches("generate").unwrap();
            commands::launch(
                "generate",
                if let Some(targets) = m.values_of("target") {
                    Some(targets.collect())
                } else {
                    Option::None
                },
                &m.value_of("mode"),
                Some(m.values_of("files").unwrap().collect()),
                m.value_of("output_dir"),
                m.value_of("reference_dir"),
                m.is_present("debug"),
                None,
            );
        }
        Some("compile") => {
            let m = matches.subcommand_matches("compile").unwrap();
            commands::launch(
                "compile",
                if let Some(targets) = m.values_of("target") {
                    Some(targets.collect())
                } else {
                    Option::None
                },
                &m.value_of("mode"),
                Some(m.values_of("files").unwrap().collect()),
                m.value_of("output_dir"),
                m.value_of("reference_dir"),
                false,
                None,
            );
        }
        Some("target") => {
            let m = matches.subcommand_matches("target").unwrap();
            let subm = m.subcommand();
            if let Some(s) = subm.1 {
                commands::target::run(
                    Some(subm.0),
                    match s.values_of("targets") {
                        Some(targets) => Some(targets.collect()),
                        None => None,
                    },
                    s.is_present("full-paths"),
                )
            } else {
                commands::target::run(None, None, m.is_present("full-paths"));
            }
        }
        Some("web") => {
            let cmd = matches.subcommand_matches("web").unwrap();
            let subcmd = cmd.subcommand();
            let sub = subcmd.1.unwrap();
            match subcmd.0 {
                "build" => {
                    let mut args = IndexMap::new();
                    if sub.is_present("view") {
                        args.insert("view", "True".to_string());
                    }
                    if sub.is_present("clean") {
                        args.insert("clean", "True".to_string());
                    }
                    if sub.is_present("no-api") {
                        args.insert("no-api", "True".to_string());
                    }
                    if sub.is_present("as-release") {
                        args.insert("as-release", "True".to_string());
                    }
                    if sub.is_present("release-with-warnings") {
                        args.insert("release-with-warnings", "True".to_string());
                    }
                    if sub.is_present("release") {
                        args.insert("release", "True".to_string());
                    }
                    if sub.is_present("archive") {
                        if let Some(archive) = sub.value_of("archive") {
                            args.insert("archive", format!("'{}'", archive));
                        } else {
                            args.insert("archive", "True".to_string());
                        }
                    }
                    if let Some(s_args) = sub.value_of("sphinx-args") {
                        // Recall that this comes in as a single argument, potentially quoted to mimic multiple,
                        // but a single argument from the perspective here nonetheless
                        args.insert("sphinx-args", format!("'{}'", s_args));
                    }
                    commands::launch(
                        "web:build",
                        if let Some(targets) = cmd.values_of("target") {
                            Some(targets.collect())
                        } else {
                            Option::None
                        },
                        &None,
                        None,
                        None,
                        None,
                        false,
                        Some(args),
                    )
                }
                "view" => commands::launch("web:view", None, &None, None, None, None, false, None),
                "clean" => {
                    commands::launch("web:clean", None, &None, None, None, None, false, None)
                }
                _ => {}
            }
        }
        Some("mailer") => {
            let cmd = matches.subcommand_matches("mailer").unwrap();
            let subcmd = cmd.subcommand();
            let sub = subcmd.1.unwrap();
            match subcmd.0 {
                "send" => {
                    let m = origen::mailer();
                    let e = origen::core::user::get_current_email()
                        .expect("Could not resolve current user's email");
                    let email = m.compose(
                        &e,
                        if let Some(recipients) = sub.values_of("to") {
                            recipients.collect()
                        } else {
                            vec![&e]
                        },
                        sub.value_of("subject"),
                        sub.value_of("body"),
                        true,
                    );
                    match email {
                        Ok(e) => match m.send(e) {
                            Ok(_) => {}
                            Err(e) => {
                                origen::display_redln!("Errors occurred sending email:\n{}", e.msg);
                            }
                        },
                        Err(e) => {
                            origen::display_redln!("Errors occurred composing email:\n{}", e.msg);
                        }
                    }
                }
                "test" => {
                    let m = origen::mailer();
                    if let Some(t) = sub.values_of("to") {
                        match m.test(Some(t.collect())) {
                            Ok(_) => {}
                            Err(e) => {
                                origen::display_redln!(
                                    "Error occurred sending test email:\n{}",
                                    e.msg
                                );
                            }
                        }
                    } else {
                        match m.test(None) {
                            Ok(_) => {}
                            Err(e) => {
                                origen::display_redln!(
                                    "Errors occurred sending test email:\n{}",
                                    e.msg
                                );
                            }
                        }
                    }
                }
                _ => {}
            }
        }
        Some("credentials") => {
            let cmd = matches.subcommand_matches("credentials").unwrap();
            let subcmd = cmd.subcommand();
            let sub = subcmd.1.unwrap();
            match subcmd.0 {
                "set" => {
                    if sub.is_present("all") {
                        match origen::core::user::set_all_passwords() {
                            Ok(_) => {}
                            Err(e) => {
                                origen::display_redln!(
                                    "Could not set all passwords. Errors were encountered:\n{}",
                                    e.msg
                                );
                            }
                        }
                    } else {
                        if let Some(datasets) = sub.values_of("dataset") {
                            match origen::core::user::set_passwords(Some(datasets.collect())) {
                                Ok(_) => {}
                                Err(e) => {
                                    origen::display_redln!("Could not set all requested passwords. Errors were encountered:\n{}", e.msg);
                                }
                            }
                        } else {
                            match origen::core::user::set_passwords(None) {
                                Ok(_) => {}
                                Err(e) => {
                                    origen::display_redln!("Could not clear all passwords. Errors were encountered:\n{}", e.msg);
                                }
                            }
                        }
                    }
                }
                "clear" => {
                    if sub.is_present("all") {
                        match origen::core::user::clear_all_passwords() {
                            Ok(_) => {}
                            Err(e) => {
                                origen::display_redln!(
                                    "Could not clear all passwords. Errors were encountered:\n{}",
                                    e.msg
                                );
                            }
                        }
                    } else {
                        if let Some(datasets) = sub.values_of("dataset") {
                            match origen::core::user::clear_passwords(Some(datasets.collect())) {
                                Ok(_) => {}
                                Err(e) => {
                                    origen::display_redln!("Could not clear all given passwords. Errors were encountered:\n{}", e.msg);
                                }
                            }
                        } else {
                            match origen::core::user::clear_passwords(None) {
                                Ok(_) => {}
                                Err(e) => {
                                    origen::display_redln!(
                                        "Could not clear password. Errors were encountered:\n{}",
                                        e.msg
                                    );
                                }
                            }
                        }
                    }
                }
                _ => {}
            }
        }
        Some("mode") => {
            let matches = matches.subcommand_matches("mode").unwrap();
            commands::mode::run(matches.value_of("mode"));
        }
        Some("save_ref") => {
            let matches = matches.subcommand_matches("save_ref").unwrap();
            commands::save_ref::run(matches);
        }
        // To get here means the user has typed "origen -v", which officially means
        // verbosity level 1 with no command, but this is what they really mean
        None => {
            if STATUS.is_app_present {
                // Run a short command line operation to get the Origen version back from the Python domain
                let cmd = "from origen.boot import run_cmd; run_cmd('_version_');";
                let mut origen_version = "".to_string();

                let res = python::run_with_callbacks(
                    cmd,
                    Some(&mut |line| {
                        origen_version += line;
                    }),
                    None,
                );

                if let Err(e) = res {
                    log_error!("{}", e);
                    log_error!("Couldn't boot app to determine the in-application Origen version");
                    origen_version = "Unknown".to_string();
                }

                let app_version = match origen::app().unwrap().version() {
                    Err(e) => {
                        log_error!("{}", e);
                        "Error".to_string()
                    }
                    Ok(v) => format!("{}", v),
                };

                if STATUS.is_app_in_origen_dev_mode {
                    println!(
                        "App:    {}\nOrigen: {} (from {})\nCLI:    {}",
                        to_pep440(&app_version).unwrap_or("Error".to_string()),
                        to_pep440(&origen_version).unwrap_or("Error".to_string()),
                        STATUS.origen_wksp_root.display(),
                        to_pep440(&STATUS.origen_version.to_string())
                            .unwrap_or("Error".to_string())
                    );
                } else {
                    println!(
                        "App:    {}\nOrigen: {}\nCLI:    {}",
                        to_pep440(&app_version).unwrap_or("Error".to_string()),
                        to_pep440(&origen_version).unwrap_or("Error".to_string()),
                        to_pep440(&STATUS.origen_version.to_string())
                            .unwrap_or("Error".to_string())
                    );
                }
            } else {
                println!(
                    "Origen: {}",
                    to_pep440(&STATUS.origen_version.to_string()).unwrap_or("Error".to_string())
                );
            }
        }
        _ => {
            // To get here we must be dealing with a command added by an app/plugin
            app_command_defs.dispatch(&matches);
        }
    }
}

fn build_command(cmd_def: &app_commands::Command) -> App {
    let mut cmd = SubCommand::with_name(&cmd_def.name).about(cmd_def.help.as_str());
    if cmd_def.alias.is_some() {
        cmd = cmd.visible_alias(cmd_def.alias.as_ref().unwrap().as_str());
    }
    if cmd_def.arg.is_some() {
        // For each arg
        for j in 0..cmd_def.arg.as_ref().unwrap().len() {
            let arg_def = &cmd_def.arg.as_ref().unwrap()[j];
            let mut arg = Arg::with_name(&arg_def.name).help(&arg_def.help);
            // If this is an arg without a switch
            if arg_def.switch.is_some() && !arg_def.switch.unwrap() {
                // Do nothing?
            } else {
                if arg_def.long.is_some() {
                    arg = arg.long(&arg_def.long.as_ref().unwrap());
                } else {
                    arg = arg.long(&arg_def.name);
                }
                if arg_def.short.is_some() {
                    arg = arg.short(arg_def.short.as_ref().unwrap())
                }
            }
            if arg_def.takes_value.is_some() {
                arg = arg.takes_value(arg_def.takes_value.unwrap())
            }
            if arg_def.multiple.is_some() {
                arg = arg.multiple(arg_def.multiple.unwrap())
            }
            if arg_def.required.is_some() {
                arg = arg.required(arg_def.required.unwrap())
            }
            if arg_def.value_name.is_some() {
                arg = arg.value_name(arg_def.value_name.as_ref().unwrap())
            } else {
                arg = arg.value_name(arg_def.upcased_name.as_ref().unwrap())
            }
            if arg_def.use_delimiter.is_some() {
                arg = arg.use_delimiter(arg_def.use_delimiter.unwrap())
            }
            if arg_def.hidden.is_some() {
                arg = arg.hidden(arg_def.hidden.unwrap())
            }

            cmd = cmd.arg(arg);
        }
    }
    if let Some(subcommands) = &cmd_def.subcommand {
        for c in subcommands {
            let subcmd = build_command(&c);
            cmd = cmd.subcommand(subcmd);
        }
    }
    cmd
}