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
// Copyright (C) 2017 Christopher R. Field.
//
// 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.

use chrono::{Datelike, Utc};
use mustache::{self, MapBuilder};
use regex::Regex;
use std::env;
use std::fs::{self, File};
use std::io::{self, Read, Write, ErrorKind};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::str::FromStr;
use super::{Error, Platform, Result, Template, TimestampServer};
use toml::Value;
use uuid::Uuid;

pub const CARGO_MANIFEST_FILE: &str = "Cargo.toml";
pub const CARGO: &str = "cargo";
pub const DEFAULT_LICENSE_FILE_NAME: &str = "LICENSE";
pub const EXE_FILE_EXTENSION: &str = "exe";
pub const RTF_FILE_EXTENSION: &str = "rtf";
pub const SIGNTOOL: &str = "signtool";
pub const SIGNTOOL_PATH_KEY: &str = "SIGNTOOL_PATH";
pub const WIX: &str = "wix";
pub const WIX_COMPILER: &str = "candle";
pub const WIX_LINKER: &str = "light";
pub const WIX_PATH_KEY: &str = "WIX_PATH";
pub const WIX_SOURCE_FILE_EXTENSION: &str = "wxs";
pub const WIX_SOURCE_FILE_NAME: &str = "main";

/// A builder for running the subcommand.
#[derive(Debug, Clone)]
pub struct Wix<'a> {
    bin_path: Option<&'a str>,
    binary_name: Option<&'a str>,
    capture_output: bool,
    copyright_year: Option<&'a str>,
    copyright_holder: Option<&'a str>,
    description: Option<&'a str>,
    input: Option<&'a str>,
    license_path: Option<&'a str>,
    manufacturer: Option<&'a str>,
    no_build: bool,
    output: Option<&'a str>,
    product_name: Option<&'a str>,
    sign: bool,
    sign_path: Option<&'a str>,
    timestamp: Option<&'a str>,
}

impl<'a> Wix<'a> {
    /// Creates a new `Wix` instance.
    pub fn new() -> Self {
        Wix {
            bin_path: None,
            binary_name: None,
            capture_output: true,
            copyright_year: None,
            copyright_holder: None,
            description: None,
            input: None,
            license_path: None,
            manufacturer: None,
            no_build: false,
            output: None,
            product_name: None,
            sign: false,
            sign_path: None,
            timestamp: None,
        }
    }

    /// Sets the path to the WiX Toolset's `bin` folder.
    ///
    /// The WiX Toolset's `bin` folder should contain the needed `candle.exe` and `light.exe`
    /// applications. The default is to use the PATH system environment variable. This will
    /// override any value obtained from the environment.
    pub fn bin_path(mut self, b: Option<&'a str>) -> Self {
        self.bin_path = b;
        self
    }

    /// Sets the binary name.
    ///
    /// This overrides the binary name determined from the package's manifest (Cargo.toml).
    pub fn binary_name(mut self, b: Option<&'a str>) -> Self {
        self.binary_name = b;
        self
    }

    /// Enables or disables capturing of the output from the builder (`cargo`), compiler
    /// (`candle`), linker (`light`), and signer (`signtool`).
    ///
    /// The default is to capture all output, i.e. display nothing in the console but the log
    /// statements.
    pub fn capture_output(mut self, c: bool) -> Self {
        self.capture_output = c;
        self
    }

    /// Sets the copyright holder in the license dialog of the Windows installer (msi).
    pub fn copyright_holder(mut self, h: Option<&'a str>) -> Self {
        self.copyright_holder = h;
        self
    }

    /// Sets the copyright year in the license dialog of the Windows installer (msi).
    pub fn copyright_year(mut self, y: Option<&'a str>) -> Self {
        self.copyright_year = y;
        self
    }

    /// Sets the description.
    ///
    /// This override the description determined from the `description` field in the package's
    /// manifest (Cargo.toml).
    pub fn description(mut self, d: Option<&'a str>) -> Self {
        self.description = d;
        self
    }

    /// Sets the path to a file to be used as the WiX Source (wxs) file instead of `wix\main.rs`.
    pub fn input(mut self, i: Option<&'a str>) -> Self {
        self.input = i;
        self
    }
    
    /// Sets the path to a file to used as the `License.txt` file within the installer.
    ///
    /// The `License.txt` file is installed into the installation location along side the `bin`
    /// folder. Note, the file can be in any format with any name, but it is automatically renamed
    /// to `License.txt` during creation of the installer.
    pub fn license_file(mut self, l: Option<&'a str>) -> Self {
        self.license_path = l;
        self
    }

    /// Overrides the first author in the `authors` field of the package's manifest (Cargo.toml) as
    /// the manufacturer within the installer.
    pub fn manufacturer(mut self, m: Option<&'a str>) -> Self {
        self.manufacturer = m;
        self
    }

    /// Skips the building of the project with the release profile.
    ///
    /// If `true`, the project will _not_ be built using the release profile, i.e. the `cargo build
    /// --release` command will not be executed. The default is to build the project before each
    /// creation. This is useful if building the project is more involved or is handled in
    /// a separate process.
    pub fn no_build(mut self, n: bool) -> Self {
        self.no_build = n;
        self
    }

    /// Sets the output file.
    ///
    /// The default is to create a MSI file with the `<product-name>-<version>-<arch>.msi` file
    /// name and extension in the `target\wix` folder. Use this method to override the destination
    /// and file name of the Windows installer.
    pub fn output(mut self, o: Option<&'a str>) -> Self {
        self.output = o;
        self
    }

    /// Renders the template for the license and writes it to stdout.
    fn print_license(&self, license: Template) -> Result<()> {
        let manifest = get_manifest()?;
        self.write_license(&mut io::stdout(), &license, &manifest)?;
        Ok(())
    }

    /// Prints a template to stdout.
    ///
    /// In the case of a license template, the copyright year and holder are filled by the current
    /// year and the manufacturer. The output for a license template is also in the Rich Text
    /// Format (RTF). In the case of a WiX Source (WXS) template, the output is in XML. The
    /// UpgradeCode's and Path Component's GUIDs are generated each time the WXS template is printed. 
    pub fn print_template(self, template: Template) -> Result<()> {
        match template {
            t @ Template::Apache2 => self.print_license(t),
            t @ Template::Gpl3 => self.print_license(t),
            t @ Template::Mit => self.print_license(t),
            Template::Wxs => self.print_wix_source(),
        }
    }

    /// Generates unique GUIDs for appropriate values and writes the rendered template to stdout.
    fn print_wix_source(&self) -> Result<()> {
        self.write_wix_source(&mut io::stdout())
    }

    /// Sets the product name.
    ///
    /// This override the product name determined from the `name` field in the package's
    /// manifest (Cargo.toml).
    pub fn product_name(mut self, p: Option<&'a str>) -> Self {
        self.product_name = p;
        self
    }

    /// Enables or disables signing of the installer after creation with the `signtool`
    /// application.
    pub fn sign(mut self, s: bool) -> Self {
        self.sign = s;
        self
    }

    /// Sets the path to the folder containing the `signtool.exe` file.
    ///
    /// Normally the `signtool.exe` is installed in the `bin` folder of the Windows SDK
    /// installation. THe default is to use the PATH system environment variable. This will
    /// override any value obtained from the environment.
    pub fn sign_path(mut self, s: Option<&'a str>) -> Self {
        self.sign_path = s;
        self
    }

    /// Sets the URL for the timestamp server used when signing an installer.
    ///
    /// The default is to _not_ use a timestamp server, even though it is highly recommended. Use
    /// this method to enable signing with the timestamp.
    pub fn timestamp(mut self, t: Option<&'a str>) -> Self {
        self.timestamp = t;
        self
    }

    /// Creates the necessary sub-folders and files to immediately use the `cargo wix` subcommand to
    /// create an installer for the package.
    pub fn init(self, force: bool) -> Result<()> {
        let mut main_wxs_path = PathBuf::from(WIX);
        if !main_wxs_path.exists() {
            info!("Creating the '{}' directory", main_wxs_path.display());
            fs::create_dir(&main_wxs_path)?;
        }
        main_wxs_path.push(WIX_SOURCE_FILE_NAME);
        main_wxs_path.set_extension(WIX_SOURCE_FILE_EXTENSION);
        if main_wxs_path.exists() && !force {
            return Err(Error::Generic(
                format!("The '{}' file already exists. Use the '--force' flag to overwrite the contents.", 
                    main_wxs_path.display())
            ));
        } else {
            info!("Creating the 'wix\\main.wxs' file");
            let mut main_wxs = File::create(main_wxs_path)?;
            self.write_wix_source(&mut main_wxs)?;
        }
        let manifest = get_manifest()?;
        if self.get_description(&manifest).is_err() {
            warn!("The 'description' field is missing from the package's manifest (Cargo.toml). Please consider adding the field with a non-empty value to avoid errors during installer creation.");
        }
        let license_name = self.get_manifest_license_name(&manifest);
        debug!("license_name = {:?}", license_name);
        if let Some(l) = license_name {
            info!("Creating the 'wix\\License.{}' file", RTF_FILE_EXTENSION);
            let license = Template::from_str(&l)?;
            let mut license_path = PathBuf::from(WIX);
            license_path.push("License");
            license_path.set_extension(RTF_FILE_EXTENSION);
            let mut rtf = File::create(license_path)?;
            self.write_license(&mut rtf, &license, &manifest)?;
        } else {
            warn!("Could not generate an appropriate license file in the Rich Text Format (RTF). Please manually create one to avoid errors during installer creation.");
        }
        if manifest.get("package").and_then(|p| p.as_table())
            .and_then(|t| t.get("license-file")).is_none() {
            let license_file = Path::new(DEFAULT_LICENSE_FILE_NAME);
            if !license_file.exists() {
                warn!("A '{}' file does not exist in the project root. Please consider adding such a file to avoid errors during installer creation.", DEFAULT_LICENSE_FILE_NAME);
            }
        }
        Ok(())
    }
   
    /// Builds the project using the release profile, creates the installer (msi), and optionally
    /// signs the output. 
    pub fn create(self) -> Result<()> {
        debug!("binary_name = {:?}", self.binary_name);
        debug!("capture_output = {:?}", self.capture_output);
        debug!("description = {:?}", self.description);
        debug!("input = {:?}", self.input);
        debug!("manufacturer = {:?}", self.manufacturer);
        debug!("product_name = {:?}", self.product_name);
        debug!("sign = {:?}", self.sign);
        debug!("timestamp = {:?}", self.timestamp);
        let manifest = get_manifest()?;
        let version = self.get_version(&manifest)?;
        debug!("version = {:?}", version);
        let product_name = self.get_product_name(&manifest)?;
        debug!("product_name = {:?}", product_name);
        let description = self.get_description(&manifest)?;
        debug!("description = {:?}", description);
        let homepage = self.get_homepage(&manifest);
        debug!("homepage = {:?}", homepage);
        let license_name = self.get_license_name(&manifest)?;
        debug!("license_name = {:?}", license_name);
        let license_source = self.get_license_source(&manifest);
        debug!("license_source = {:?}", license_source);
        let manufacturer = self.get_manufacturer(&manifest)?;
        debug!("manufacturer = {}", manufacturer);
        let help_url = self.get_help_url(&manifest);
        debug!("help_url = {:?}", help_url);
        let binary_name = self.get_binary_name(&manifest)?;
        debug!("binary_name = {:?}", binary_name);
        let platform = self.get_platform();
        debug!("platform = {:?}", platform);
        let source_wxs = self.get_wxs_source()?;
        debug!("source_wxs = {:?}", source_wxs);
        let source_wixobj = self.get_source_wixobj(); 
        debug!("source_wixobj = {:?}", source_wixobj);
        let destination_msi = self.get_destination_msi(&product_name, &version, &platform);
        debug!("destination_msi = {:?}", destination_msi);
        if self.no_build {
            warn!("Skipped building the release binary");
        } else {
            // Build the binary with the release profile. If a release binary has already been built, then
            // this will essentially do nothing.
            info!("Building the release binary");
            let mut builder = Command::new(CARGO);
            debug!("builder = {:?}", builder);
            if self.capture_output {
                trace!("Capturing the '{}' output", CARGO);
                builder.stdout(Stdio::null());
                builder.stderr(Stdio::null());
            }
            let status = builder.arg("build").arg("--release").status()?;
            if !status.success() {
                return Err(Error::Command(CARGO, status.code().unwrap_or(100)));
            }
        }
        // Compile the installer
        info!("Compiling the installer");
        let mut compiler = self.get_compiler()?;
        debug!("compiler = {:?}", compiler);
        if self.capture_output {
            trace!("Capturing the '{}' output", WIX_COMPILER);
            compiler.stdout(Stdio::null());
            compiler.stderr(Stdio::null());
        } 
        compiler.arg(format!("-dVersion={}", version))
            .arg(format!("-dPlatform={}", platform))
            .arg(format!("-dProductName={}", product_name))
            .arg(format!("-dBinaryName={}", binary_name))
            .arg(format!("-dDescription={}", description))
            .arg(format!("-dManufacturer={}", manufacturer))
            .arg(format!("-dLicenseName={}", license_name))
            .arg(format!("-dLicenseSource={}", license_source.display()));
        if let Some(h) = help_url {
            trace!("Using '{}' for the help URL", h);
            compiler.arg(format!("-dHelp={}", h));
        } else {
            warn!("A help URL could not be found. Considering adding the 'documentation', \
                  'homepage', or 'repository' fields to the package's manifest.");
        }
        let status = compiler.arg("-o")
            .arg(&source_wixobj)
            .arg(&source_wxs)
            .status().map_err(|err| {
                if err.kind() == ErrorKind::NotFound {
                    Error::Generic(format!(
                        "The compiler application ({}) could not be found in the PATH environment \
                        variable. Please check the WiX Toolset (http://wixtoolset.org/) is \
                        installed and the WiX Toolset's 'bin' folder has been added to the PATH \
                        environment variable, or use the '-B,--bin-path' command line argument or \
                        the {} environment variable.", 
                        WIX_COMPILER,
                        WIX_PATH_KEY
                    ))
                } else {
                    err.into()
                }
            })?;
        if !status.success() {
            return Err(Error::Command(WIX_COMPILER, status.code().unwrap_or(100)));
        }
        // Link the installer
        info!("Linking the installer");
        let mut linker = self.get_linker()?; 
        debug!("linker = {:?}", linker);
        if self.capture_output {
            trace!("Capturing the '{}' output", WIX_LINKER);
            linker.stdout(Stdio::null());
            linker.stderr(Stdio::null());
        }
        let status = linker
            .arg("-ext")
            .arg("WixUIExtension")
            .arg("-cultures:en-us")
            .arg(&source_wixobj)
            .arg("-out")
            .arg(&destination_msi)
            .status().map_err(|err| {
                if err.kind() == ErrorKind::NotFound {
                    Error::Generic(format!(
                        "The linker application ({}) could not be found in the PATH environment \
                        variable. Please check the WiX Toolset (http://wixtoolset.org/) is \
                        installed and the WiX Toolset's 'bin' folder has been added to the PATH \
                        environment variable, or use the '-B,--bin-path' command line argument or \
                        the {} environment variable.", 
                        WIX_LINKER,
                        WIX_PATH_KEY
                    ))
                } else {
                    err.into()
                }
            })?;
        if !status.success() {
            return Err(Error::Command(WIX_LINKER, status.code().unwrap_or(100)));
        }
        // Sign the installer
        if self.sign {
            info!("Signing the installer");
            let mut signer = self.get_signer()?;
            debug!("signer = {:?}", signer);
            if self.capture_output {
                trace!("Capturing the {} output", SIGNTOOL);
                signer.stdout(Stdio::null());
                signer.stderr(Stdio::null());
            }
            signer.arg("sign")
                .arg("/a")
                .arg("/d")
                .arg(format!("{} - {}", product_name, description));
            if let Some(h) = homepage {
                trace!("Using the '{}' URL for the expanded description", h);
                signer.arg("/du").arg(h);
            }
            if let Some(t) = self.timestamp {
                let server = TimestampServer::from_str(&t)?;
                trace!("Using the '{}' timestamp server to sign the installer", server); 
                signer.arg("/t");
                signer.arg(server.url());
            }
            let status = signer.arg(&destination_msi).status().map_err(|err| {
                if err.kind() == ErrorKind::NotFound {
                    Error::Generic(format!(
                        "The {0} application could not be found. Please check the Windows 10 SDK \
                        (https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk) is \
                        installed and you are using the x64 or x86 Native Build Tools prompt so the \
                        {0} application is available.",
                        SIGNTOOL
                    ))
                } else {
                    err.into()
                }
            })?;
            if !status.success() {
                return Err(Error::Command(SIGNTOOL, status.code().unwrap_or(100)));
            }
        }
        Ok(())
    }

    /// Gets the binary name.
    ///
    /// This is the name of the executable (exe) file.
    fn get_binary_name(&self, manifest: &Value) -> Result<String> {
        if let Some(b) = self.binary_name {
            Ok(b.to_owned())
        } else {
            manifest.get("bin")
                .and_then(|b| b.as_table())
                .and_then(|t| t.get("name")) 
                .and_then(|n| n.as_str())
                .map_or(self.get_product_name(manifest), |s| Ok(String::from(s)))
        }
    }

    /// Gets the command for the compiler application (`candle.exe`).
    fn get_compiler(&self) -> Result<Command> {
        if let Some(mut path) = self.bin_path.map(|s| {
            let mut p = PathBuf::from(s);
            trace!("Using the '{}' path to the WiX Toolset's 'bin' folder for the compiler", p.display());
            p.push(WIX_COMPILER);
            p.set_extension(EXE_FILE_EXTENSION);
            p
        }) {
            if !path.exists() {
                path.pop(); // Remove the `candle` application from the path
                Err(Error::Generic(format!(
                    "The compiler application ('{}') does not exist at the '{}' path specified via \
                    the '-B, --bin-path' command line argument. Please check the path is correct and \
                    the compiler application exists at the path.",
                    WIX_COMPILER, 
                    path.display()
                )))
            } else {
                Ok(Command::new(path))
            }
        } else {
            if let Some(mut path) = env::var_os(WIX_PATH_KEY).map(|s| {
                let mut p = PathBuf::from(s);
                trace!("Using the '{}' path to the WiX Toolset's 'bin' folder for the compiler", p.display());
                p.push(WIX_COMPILER);
                p.set_extension(EXE_FILE_EXTENSION);
                p
            }) {
                if !path.exists() {
                    path.pop(); // Remove the `candle` application from the path
                    Err(Error::Generic(format!(
                        "The compiler application ('{}') does not exist at the '{}' path specified \
                        via the {} environment variable. Please check the path is correct and the \
                        compiler application exists at the path.",
                        WIX_COMPILER,
                        path.display(),
                        WIX_PATH_KEY
                    )))
                } else {
                    Ok(Command::new(path))
                }
            } else {
                Ok(Command::new(WIX_COMPILER))
            }
        }
    }

    /// Gets the copyright holder.
    ///
    /// The default is use the manufacturer.
    fn get_copyright_holder(&self, manifest: &Value) -> Result<String> {
        if let Some(h) = self.copyright_holder {
            Ok(h.to_owned())
        } else {
            self.get_manufacturer(manifest)
        }
    }

    /// Gets the copyright year.
    ///
    /// The default is to use the current year.
    fn get_copyright_year(&self) -> String {
        self.copyright_year
            .map(|y| String::from(y))
            .unwrap_or(Utc::now().year().to_string())
    }

    /// Gets the description.
    ///
    /// If no description is explicitly set using the builder pattern, then the description from
    /// the package's manifest (Cargo.toml) is used.
    fn get_description(&self, manifest: &Value) -> Result<String> {
        self.description.or_else(|| manifest.get("package")
            .and_then(|p| p.as_table())
            .and_then(|t| t.get("description"))
            .and_then(|d| d.as_str()))
            .map(|s| String::from(s))
            .ok_or(Error::Manifest("description"))
    }

    /// Gets the URL of the project's homepage from the manifest (Cargo.toml).
    fn get_homepage(&self, manifest: &Value) -> Option<String> {
        manifest.get("package")
            .and_then(|p| p.as_table())
            .and_then(|t| t.get("homepage"))
            .and_then(|d| d.as_str())
            .map(|s| String::from(s))
    }

    /// Gets the license name.
    ///
    /// If a path to a license file is specified, then the file name will be used. If no license
    /// path is specified, then the file name from the `license-file` field in the package's
    /// manifest is used.
    fn get_license_name(&self, manifest: &Value) -> Result<String> {
        if let Some(l) = self.license_path.map(|s| PathBuf::from(s)) {
            l.file_name()
                .and_then(|f| f.to_str())
                .map(|s| String::from(s))
                .ok_or(Error::Generic(
                    format!("The '{}' license path does not contain a file name.", l.display())
                ))
        } else {
            manifest.get("package")
                .and_then(|p| p.as_table())
                .and_then(|t| t.get("license-file"))
                .and_then(|l| l.as_str())
                .map_or(Ok(String::from("License.txt")), |l| {
                    Path::new(l).file_name()
                        .and_then(|f| f.to_str())
                        .map(|s| String::from(s))
                        .ok_or(Error::Generic(
                            format!("The 'license-file' field value does not contain a file name.")))
                })
        }
    }

    /// Gets the name of the license from the `license` field in the package's manifest
    /// (Cargo.toml).
    fn get_manifest_license_name(&self, manifest: &Value) -> Option<String> {
        manifest.get("package")
            .and_then(|p| p.as_table())
            .and_then(|t| t.get("license"))
            .and_then(|l| l.as_str())
            .and_then(|s| s.split("/").next())
            .map(|s| String::from(s))
    }

    /// Gets the license source file.
    ///
    /// This is the license file that is placed in the installation location alongside the `bin`
    /// folder for the executable (exe) file.
    fn get_license_source(&self, manifest: &Value) -> PathBuf {
        // Order of precedence:
        //
        // 1. CLI (-l,--license)
        // 2. Manifest `license-file`
        // 3. LICENSE file in root
        self.license_path.map(|l| PathBuf::from(l)).unwrap_or(
            manifest.get("package")
                .and_then(|p| p.as_table())
                .and_then(|t| t.get("license-file"))
                .and_then(|l| l.as_str())
                .map(|s| PathBuf::from(s))
                // TODO: Add check that the default license exists
                .unwrap_or(PathBuf::from(DEFAULT_LICENSE_FILE_NAME))
        )
    }

    /// Gets the command for the linker application (`light.exe`).
    fn get_linker(&self) -> Result<Command> {
        if let Some(mut path) = self.bin_path.map(|s| {
            let mut p = PathBuf::from(s);
            trace!("Using the '{}' path to the WiX Toolset 'bin' folder for the linker", p.display());
            p.push(WIX_LINKER);
            p.set_extension(EXE_FILE_EXTENSION);
            p
        }) {
            if !path.exists() {
                path.pop(); // Remove the 'light' application from the path
                Err(Error::Generic(format!(
                    "The linker application ('{}') does not exist at the '{}' path specified via \
                    the '-B, --bin-path' command line argument. Please check the path is correct \
                    and the linker application exists at the path.",
                    WIX_LINKER,
                    path.display()
                )))
            } else {
                Ok(Command::new(path))
            }
        } else {
            if let Some(mut path) = env::var_os(WIX_PATH_KEY).map(|s| {
                let mut p = PathBuf::from(s);
                trace!("Using the '{}' path to the WiX Toolset's 'bin' folder for the linker", p.display());
                p.push(WIX_LINKER);
                p.set_extension(EXE_FILE_EXTENSION);
                p
            }) {
                if !path.exists() {
                    path.pop(); // Remove the `candle` application from the path
                    Err(Error::Generic(format!(
                        "The linker application ('{}') does not exist at the '{}' path specified \
                        via the {} environment variable. Please check the path is correct and the \
                        linker application exists at the path.",
                        WIX_LINKER,
                        path.display(),
                        WIX_PATH_KEY
                    )))
                } else {
                    Ok(Command::new(path))
                }
            } else {
                Ok(Command::new(WIX_LINKER))
            }
        }
    }

    /// Gets the manufacturer.
    ///
    /// The manufacturer is displayed in the Add/Remove Programs (ARP) control panel under the
    /// "Publisher" column. If no manufacturer is explicitly set using the builder pattern, then
    /// the first author from the `authors` field in the package's manifest (Cargo.toml) is used.
    fn get_manufacturer(&self, manifest: &Value) -> Result<String> {
        if let Some(m) = self.manufacturer {
            Ok(m.to_owned())
        } else {
            manifest.get("package")
                .and_then(|p| p.as_table())
                .and_then(|t| t.get("authors"))
                .and_then(|a| a.as_array())
                .and_then(|a| a.get(0)) 
                .and_then(|f| f.as_str())
                .and_then(|s| {
                    // Strip email if it exists.
                    let re = Regex::new(r"<(.*?)>").unwrap();
                    Some(re.replace_all(s, ""))
                })
                .map(|s| String::from(s.trim()))
                .ok_or(Error::Manifest("authors"))
        }
    }

    /// Gets the platform.
    fn get_platform(&self) -> Platform {
        if cfg!(target_arch = "x86_64") {
            Platform::X64
        } else {
            Platform::X86
        }
    }

    /// Gets the product name.
    fn get_product_name(&self, manifest: &Value) -> Result<String> {
        if let Some(p) = self.product_name {
            Ok(p.to_owned())
        } else {
            manifest.get("package")
                .and_then(|p| p.as_table())
                .and_then(|t| t.get("name"))
                .and_then(|n| n.as_str())
                .map(|s| String::from(s))
                .ok_or(Error::Manifest("name"))
        }
    }

    /// Gets the command for the `signtool` application.
    fn get_signer(&self) -> Result<Command> {
        if let Some(mut path) = self.sign_path.map(|s| {
            let mut p = PathBuf::from(s);
            trace!("Using the '{}' path to the Windows SDK 'bin' folder for the signer", p.display());
            p.push(SIGNTOOL);
            p.set_extension(EXE_FILE_EXTENSION);
            p
        }) {
            if !path.exists() {
                path.pop(); // Remove the 'signtool' application from the path
                Err(Error::Generic(format!(
                    "The signer application ('{}') does not exist at the '{}' path specified via \
                    the '-S, --sign-path' command line argument. Please check the path is correct and \
                    the signer application exists at the path.",
                    SIGNTOOL, 
                    path.display()
                )))
            } else {
                Ok(Command::new(path))
            }
        } else {
            if let Some(mut path) = env::var_os(SIGNTOOL_PATH_KEY).map(|s| {
                let mut p = PathBuf::from(s);
                trace!("Using the '{}' path to the Windows SDK 'bin' folder for the signer", p.display());
                p.push(SIGNTOOL);
                p.set_extension(EXE_FILE_EXTENSION);
                p
            }) {
                if !path.exists() {
                    path.pop(); // Remove the `signtool` application from the path
                    Err(Error::Generic(format!(
                        "The signer application ('{}') does not exist at the '{}' path specified \
                        via the {} environment variable. Please check the path is correct and the \
                        signer application exists at the path.",
                        SIGNTOOL,
                        path.display(),
                        SIGNTOOL_PATH_KEY
                    )))
                } else {
                    Ok(Command::new(path))
                }
            } else {
                Ok(Command::new(SIGNTOOL))
            }
        }
    }

    /// Gets the destination for the linker.
    fn get_destination_msi(&self, product_name: &str, version: &str, platform: &Platform) -> PathBuf {
        if let Some(o) = self.output {
            PathBuf::from(o)
        } else {
            let mut destination_msi = PathBuf::from("target");
            destination_msi.push(WIX);
            // Do NOT use the `set_extension` method for the MSI path. Since the pkg_version is in X.X.X
            // format, the `set_extension` method will replace the Patch version number and
            // architecture/platform with `msi`.  Instead, just include the extension in the formatted
            // name.
            destination_msi.push(&format!("{}-{}-{}.msi", product_name, version, platform.arch()));
            destination_msi
        }
    }

    /// Gets the destination for the compiler output/linker input.
    fn get_source_wixobj(&self) -> PathBuf {
        let mut source_wixobj = PathBuf::from("target");
        source_wixobj.push(WIX);
        source_wixobj.push(WIX_SOURCE_FILE_NAME);
        source_wixobj.set_extension("wixobj");
        source_wixobj
    }

    /// Gets the URL that appears in the installer's extended details.
    fn get_help_url(&self, manifest: &Value) -> Option<String> {
        manifest.get("package")
            .and_then(|p| p.as_table())
            .and_then(|t| t.get("documentation").or(t.get("homepage")).or(t.get("repository")))
            .and_then(|h| h.as_str())
            .map(|s| String::from(s))
    }

    /// Gets the WiX Source (wxs) file.
    fn get_wxs_source(&self) -> Result<PathBuf> {
        if let Some(p) = self.input.map(|s| PathBuf::from(s)) {
            if p.exists() {
                if p.is_dir() {
                    Err(Error::Generic(format!("The '{}' path is not a file. Please check the path and ensure it is to a WiX Source (wxs) file.", p.display())))
                } else {
                    trace!("Using the '{}' WiX source file", p.display());
                    Ok(p)
                }
            } else {
                Err(Error::Generic(format!("The '{0}' file does not exist. Consider using the 'cargo wix --print-template WXS > {0}' command to create it.", p.display())))
            }
        } else {
            trace!("Using the default WiX source file");
            let mut main_wxs = PathBuf::from(WIX);
            main_wxs.push(WIX_SOURCE_FILE_NAME);
            main_wxs.set_extension(WIX_SOURCE_FILE_EXTENSION);
            if main_wxs.exists() {
                Ok(main_wxs)
            } else {
               Err(Error::Generic(format!("The '{0}' file does not exist. Consider using the 'cargo wix --init' command to create it.", main_wxs.display())))
            }
        }
    }

    /// Gets the package version.
    fn get_version(&self, cargo_toml: &Value) -> Result<String> {
        cargo_toml.get("package")
            .and_then(|p| p.as_table())
            .and_then(|t| t.get("version"))
            .and_then(|v| v.as_str())
            .map(|s| String::from(s))
            .ok_or(Error::Manifest("version"))
    }

    /// Renders the license in the Rich Text Format (RTF) as an End User's License Agreement (EULA).
    ///
    /// The EULA is automatically included in the Windows installer (msi) and displayed in the license
    /// dialog.
    fn write_license<W: Write>(&self, writer: &mut W, template: &Template, manifest: &Value) -> Result<()> {
        let template = mustache::compile_str(template.to_str())?;
        let data = MapBuilder::new()
            .insert_str("copyright-year", self.get_copyright_year())
            .insert_str("copyright-holder", self.get_copyright_holder(manifest)?)
            .build();
        template.render_data(writer, &data)?;
        Ok(())
    }

    /// Generates unique GUIDs for appropriate values and renders the template.
    fn write_wix_source<W: Write>(&self, writer: &mut W) -> Result<()> {
        let template = mustache::compile_str(Template::Wxs.to_str())?;
        let data = MapBuilder::new()
            .insert_str("upgrade-code-guid", Uuid::new_v4().hyphenated().to_string().to_uppercase())
            .insert_str("path-component-guid", Uuid::new_v4().hyphenated().to_string().to_uppercase())
            .build();
        template.render_data(writer, &data)?;
        Ok(())
    }
}

impl<'a> Default for Wix<'a> {
    fn default() -> Self {
        Wix::new()
    }
}

/// Gets the parsed package's manifest (Cargo.toml).
fn get_manifest() -> Result<Value> {
    let cargo_file_path = Path::new(CARGO_MANIFEST_FILE);
    debug!("cargo_file_path = {:?}", cargo_file_path);
    let mut cargo_file = File::open(cargo_file_path)?;
    let mut cargo_file_content = String::new();
    cargo_file.read_to_string(&mut cargo_file_content)?;
    let manifest = cargo_file_content.parse::<Value>()?;
    Ok(manifest)
}

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

    static COMPLETE_MANIFEST: &str = r#"[package]
name = "cargo-wix"
description = "Build Windows installers using the Wix Toolset"
version = "0.0.2"
authors = ["Christopher Field <cfield2@gmail.com>"]
license = "Apache-2.0/MIT"
repository = "https://github.com/volks73/cargo-wix"
documentation = "https://volks73.github.io/cargo-wix"
homepage = "https://github.com/volks73/cargo-wix"
readme = "README.md"

[[bin]]
name = "cargo-wix"
doc = false

[lib]
name = "cargo_wix""#;

    static MINIMAL_MANIFEST: &str = r#"[package]
name = "minimal-project"
version = "0.0.1"
authors = ["Christopher Field"]"#;

    static LICENSE_FILE_MANIFEST: &str = r#"[package]
license-file = "LICENSE-CUSTOM""#;

    fn complete_manifest() -> Value {
        COMPLETE_MANIFEST.parse::<Value>().unwrap()
    }

    fn minimal_manifest() -> Value {
        MINIMAL_MANIFEST.parse::<Value>().unwrap()
    }

    fn license_file_manifest() -> Value {
        LICENSE_FILE_MANIFEST.parse::<Value>().unwrap()
    }

    #[test]
    fn defaults_are_correct() {
        let wix = Wix::new();
        assert!(wix.bin_path.is_none());
        assert!(wix.binary_name.is_none());
        assert!(wix.capture_output);
        assert!(wix.copyright_holder.is_none());
        assert!(wix.copyright_year.is_none());
        assert!(wix.description.is_none());
        assert!(wix.input.is_none());
        assert!(wix.license_path.is_none());
        assert!(wix.manufacturer.is_none());
        assert!(!wix.no_build);
        assert!(wix.product_name.is_none());
        assert!(!wix.sign);
        assert!(wix.timestamp.is_none());
    }

    #[test]
    fn bin_path_works() {
        let mut expected = PathBuf::from("C:");
        expected.push("WiX Toolset");
        expected.push("bin");
        let wix = Wix::new().bin_path(expected.to_str());
        assert_eq!(wix.bin_path, expected.to_str());
    }

    #[test]
    fn binary_name_works() {
        const EXPECTED: Option<&str> = Some("test");
        let wix = Wix::new().binary_name(EXPECTED);
        assert_eq!(wix.binary_name, EXPECTED);
    }

    #[test]
    fn capture_output_works() {
        let wix = Wix::new().capture_output(false);
        assert!(!wix.capture_output);
    }

    #[test]
    fn copyright_holder_works() {
        const EXPECTED: Option<&str> = Some("Test");
        let wix = Wix::new().copyright_holder(EXPECTED);
        assert_eq!(wix.copyright_holder, EXPECTED);
    }

    #[test]
    fn copyright_year_works() {
        const EXPECTED: Option<&str> = Some("2013");
        let wix = Wix::new().copyright_year(EXPECTED);
        assert_eq!(wix.copyright_year, EXPECTED);
    }

    #[test]
    fn description_works() {
        const EXPECTED: Option<&str> = Some("test description");
        let wix = Wix::new().description(EXPECTED);
        assert_eq!(wix.description, EXPECTED);
    }

    #[test]
    fn input_works() {
        const EXPECTED: Option<&str> = Some("test.wxs");
        let wix = Wix::new().input(EXPECTED);
        assert_eq!(wix.input, EXPECTED);
    }

    #[test]
    fn license_file_works() {
        const EXPECTED: Option<&str> = Some("MIT-LICENSE");
        let wix = Wix::new().license_file(EXPECTED);
        assert_eq!(wix.license_path, EXPECTED);
    }

    #[test]
    fn manufacturer_works() {
        const EXPECTED: Option<&str> = Some("Tester");
        let wix = Wix::new().manufacturer(EXPECTED);
        assert_eq!(wix.manufacturer, EXPECTED);
    }

    #[test]
    fn no_build_works() {
        let wix = Wix::new().no_build(true);
        assert!(wix.no_build);
    }

    #[test]
    fn product_name_works() {
        const EXPECTED: Option<&str> = Some("Test Product Name");
        let wix = Wix::new().product_name(EXPECTED);
        assert_eq!(wix.product_name, EXPECTED);
    }

    #[test]
    fn sign_works() {
        let wix = Wix::new().sign(true);
        assert!(wix.sign);
    }

    #[test]
    fn sign_path_works() {
        let mut expected = PathBuf::from("C:");
        expected.push("Program Files");
        expected.push("Windows Kit");
        expected.push("bin");
        let wix = Wix::new().sign_path(expected.to_str());
        assert_eq!(wix.sign_path, expected.to_str());
    }

    #[test]
    fn timestamp_works() {
        const EXPECTED: Option<&str> = Some("http://timestamp.comodoca.com/");
        let wix = Wix::new().timestamp(EXPECTED);
        assert_eq!(wix.timestamp, EXPECTED);
    }

    #[test]
    fn strip_email_works() {
        const EXPECTED: &str = "Christopher R. Field";
        let re = Regex::new(r"<(.*?)>").unwrap();
        let actual = re.replace_all("Christopher R. Field <user2@example.com>", "");
        assert_eq!(actual.trim(), EXPECTED);
    }

    #[test]
    fn strip_email_works_without_email() {
        const EXPECTED: &str = "Christopher R. Field";
        let re = Regex::new(r"<(.*?)>").unwrap();
        let actual = re.replace_all("Christopher R. Field", "");
        assert_eq!(actual.trim(), EXPECTED);
    }

    #[test]
    fn strip_email_works_with_only_email() {
        const EXPECTED: &str = "user1@example.com";
        let re = Regex::new(r"<(.*?)>").unwrap();
        let actual = re.replace_all("user1@example.com", "");
        assert_eq!(actual.trim(), EXPECTED);
    }

    #[test]
    fn get_binary_name_is_correct_with_default() {
        const EXPECTED: &str = "cargo-wix";
        let wix = Wix::new();
        let actual = wix.get_binary_name(&complete_manifest()).unwrap();
        assert_eq!(&actual, EXPECTED); 
    }

    #[test]
    fn get_binary_name_is_correct_with_some_value() {
        const EXPECTED: &str = "test";
        let wix = Wix::new().binary_name(Some(EXPECTED));
        let actual = wix.get_binary_name(&complete_manifest()).unwrap();
        assert_eq!(&actual, EXPECTED);
    }

    #[test]
    fn get_compiler_is_correct_with_default() {
        let compiler = Wix::new().get_compiler().unwrap();
        assert_eq!(format!("{:?}", compiler), format!("{:?}", Command::new(WIX_COMPILER)));
    }

    fn wix_toolset_bin_folder() -> PathBuf {
        let mut wix_toolset_bin = PathBuf::from("C:\\");
        wix_toolset_bin.push("Program Files (x86)");
        // TODO: Change this to be version independent
        wix_toolset_bin.push("WiX Toolset v3.11");
        wix_toolset_bin.push("bin");
        wix_toolset_bin
    }

    #[test]
    fn get_compiler_is_correct_with_some_value() {
        let test_path = wix_toolset_bin_folder();
        let mut expected = PathBuf::from(&test_path);
        expected.push(WIX_COMPILER);
        expected.set_extension(EXE_FILE_EXTENSION);
        let compiler = Wix::new().bin_path(test_path.to_str()).get_compiler().unwrap();
        assert_eq!(format!("{:?}", compiler), format!("{:?}", Command::new(expected)));
    }

    #[test]
    #[should_panic]
    fn get_compiler_fails_with_nonexistent_path_from_some_value() {
        let test_path = PathBuf::from("C:\\");
        let mut expected = PathBuf::from(&test_path);
        expected.push(WIX_COMPILER);
        expected.set_extension(EXE_FILE_EXTENSION);
        Wix::new().bin_path(test_path.to_str()).get_compiler().unwrap();
    }

    #[test]
    fn get_compiler_is_correct_with_environment_variable() {
        let test_path = wix_toolset_bin_folder();
        env::set_var(WIX_PATH_KEY, &test_path);
        let mut expected = PathBuf::from(&test_path);
        expected.push(WIX_COMPILER);
        expected.set_extension(EXE_FILE_EXTENSION);
        let compiler = Wix::new().get_compiler().unwrap();
        env::remove_var(WIX_PATH_KEY);
        assert_eq!(format!("{:?}", compiler), format!("{:?}", Command::new(expected)));
    }

    #[test]
    #[should_panic]
    fn get_compiler_fails_with_nonexistent_path_from_environment_variable() {
        let test_path = PathBuf::from("C:\\");
        env::set_var(WIX_PATH_KEY, &test_path);
        let mut expected = PathBuf::from(&test_path);
        expected.push(WIX_COMPILER);
        expected.set_extension(EXE_FILE_EXTENSION);
        let result = Wix::new().get_compiler();
        env::remove_var(WIX_PATH_KEY);
        result.unwrap();
    }

    #[test]
    fn get_copyright_holder_is_correct_with_default() {
        let wix = Wix::new();
        let actual = wix.get_copyright_holder(&complete_manifest()).unwrap();
        assert_eq!(&actual, "Christopher Field");
    }

    #[test]
    fn get_copyright_holder_is_correct_with_some_value() {
        const EXPECTED: &str = "Test";
        let wix = Wix::new().copyright_holder(Some(EXPECTED));
        let actual = wix.get_copyright_holder(&complete_manifest()).unwrap();
        assert_eq!(&actual, EXPECTED);
    }

    #[test]
    fn get_copyright_year_is_correct_with_default() {
        let wix = Wix::new();
        let actual = wix.get_copyright_year();
        assert_eq!(actual, Utc::now().year().to_string());
    }

    #[test]
    fn get_copyright_year_is_correct_with_some_value() {
        const EXPECTED: &str = "1980";
        let wix = Wix::new().copyright_year(Some(EXPECTED));
        let actual = wix.get_copyright_year();
        assert_eq!(&actual, EXPECTED);
    }

    #[test]
    fn get_description_is_correct_with_default() {
        const EXPECTED: &str = "Build Windows installers using the Wix Toolset";
        let wix = Wix::new();
        let actual = wix.get_description(&complete_manifest()).unwrap();
        assert_eq!(&actual, EXPECTED);
    }

    #[test]
    fn get_description_is_correct_with_some_value() {
        const EXPECTED: &str = "description";
        let wix = Wix::new().description(Some(EXPECTED));
        let actual = wix.get_description(&complete_manifest()).unwrap();
        assert_eq!(&actual, EXPECTED);
    }

    #[test]
    #[should_panic]
    fn get_description_fails_with_minimal_manifest() {
        Wix::new().get_description(&minimal_manifest()).unwrap();
    }

    #[test]
    fn get_homepage_is_correct_with_default() {
        assert!(Wix::new().get_homepage(&minimal_manifest()).is_none());
    }

    #[test]
    fn get_homepage_is_correct_with_complete_manifest() {
        let actual = Wix::new().get_homepage(&complete_manifest());
        assert_eq!(actual, Some(String::from("https://github.com/volks73/cargo-wix")));
    }

    #[test]
    fn get_license_name_is_correct_with_complete_manifest() {
        let actual = Wix::new().get_license_name(&complete_manifest()).unwrap();
        assert_eq!(&actual, "License.txt");
    }

    #[test]
    fn get_license_name_is_correct_with_minimal_manifest() {
        let actual = Wix::new().get_license_name(&minimal_manifest()).unwrap();
        assert_eq!(&actual, "License.txt");
    }

    #[test]
    fn get_license_name_is_correct_with_license_file_manifest() {
        let actual = Wix::new().get_license_name(&license_file_manifest()).unwrap();
        assert_eq!(&actual, "LICENSE-CUSTOM");
    }

    #[test]
    fn get_license_name_is_correct_with_license_file() {
        const EXPECTED: &str = "License.doc";
        let test_path = env::home_dir().map(|h| {
            h.join(EXPECTED)
        }).unwrap();
        let actual = Wix::new().license_file(test_path.to_str())
            .get_license_name(&license_file_manifest())
            .unwrap();
        assert_eq!(&actual, EXPECTED);
    }

    #[test]
    fn get_manifest_license_name_is_correct_with_complete_manifest() {
        const EXPECTED: &str = "Apache-2.0";
        let actual = Wix::new().get_manifest_license_name(&complete_manifest()).unwrap();
        assert_eq!(&actual, EXPECTED);
    }

    #[test]
    fn get_manifest_license_name_is_none_with_minimal_manifest() {
        let actual = Wix::new().get_manifest_license_name(&minimal_manifest());
        assert!(actual.is_none());
    }

    #[test]
    fn get_license_source_is_correct_with_complete_manifest() {
        let actual = Wix::new().get_license_source(&complete_manifest());
        assert_eq!(actual.to_str().unwrap(), DEFAULT_LICENSE_FILE_NAME);
    }

    #[test]
    fn get_license_source_is_correct_with_minimal_manifest() {
        let actual = Wix::new().get_license_source(&minimal_manifest());
        assert_eq!(actual.to_str().unwrap(), DEFAULT_LICENSE_FILE_NAME);
    }

    #[test]
    fn get_license_source_is_correct_with_some_value() {
        let expected = env::home_dir().map(|h| {
            h.join(DEFAULT_LICENSE_FILE_NAME)
        }).unwrap();
        let actual = Wix::new().license_file(expected.to_str())
            .get_license_source(&minimal_manifest());
        assert_eq!(actual, expected);
    }

    #[test]
    fn get_linker_is_correct_with_default() {
        let linker = Wix::new().get_linker().unwrap();
        assert_eq!(format!("{:?}", linker), format!("{:?}", Command::new(WIX_LINKER)));
    }

    #[test]
    fn get_linker_is_correct_with_some_value() {
        let test_path = wix_toolset_bin_folder();
        let mut expected = PathBuf::from(&test_path);
        expected.push(WIX_LINKER);
        expected.set_extension(EXE_FILE_EXTENSION);
        let linker = Wix::new().bin_path(test_path.to_str()).get_linker().unwrap();
        assert_eq!(format!("{:?}", linker), format!("{:?}", Command::new(expected)));
    }

    #[test]
    #[should_panic]
    fn get_linker_fails_with_nonexistent_path_from_some_value() {
        let test_path = PathBuf::from("C:\\");
        let mut expected = PathBuf::from(&test_path);
        expected.push(WIX_LINKER);
        expected.set_extension(EXE_FILE_EXTENSION);
        Wix::new().bin_path(test_path.to_str()).get_linker().unwrap();
    }

    #[test]
    fn get_linker_is_correct_with_environment_variable() {
        let test_path = wix_toolset_bin_folder();
        env::set_var(WIX_PATH_KEY, &test_path);
        let mut expected = PathBuf::from(&test_path);
        expected.push(WIX_LINKER);
        expected.set_extension(EXE_FILE_EXTENSION);
        let linker = Wix::new().get_linker().unwrap();
        env::remove_var(WIX_PATH_KEY);
        assert_eq!(format!("{:?}", linker), format!("{:?}", Command::new(expected)));
    }

    #[test]
    #[should_panic]
    fn get_linker_fails_with_nonexistent_path_from_environment_variable() {
        let test_path = PathBuf::from("C:\\");
        env::set_var(WIX_PATH_KEY, &test_path);
        let mut expected = PathBuf::from(&test_path);
        expected.push(WIX_LINKER);
        expected.set_extension(EXE_FILE_EXTENSION);
        let result = Wix::new().get_linker();
        env::remove_var(WIX_PATH_KEY);
        result.unwrap();
    }

    #[test]
    fn get_manufacturer_is_correct_with_complete_manifest() {
        let actual = Wix::new().get_manufacturer(&complete_manifest()).unwrap();
        assert_eq!(&actual, "Christopher Field");
    }

    #[test]
    fn get_manufacturer_is_correct_with_minimal_manifest() {
        let actual = Wix::new().get_manufacturer(&minimal_manifest()).unwrap();
        assert_eq!(&actual, "Christopher Field");
    }

    #[test]
    fn get_manufacturer_is_correct_with_some_value() {
        const EXPECTED: &str = "Test Manufacturer";
        let actual = Wix::new().manufacturer(Some(EXPECTED))
            .get_manufacturer(&complete_manifest()).unwrap();
        assert_eq!(&actual, EXPECTED);
    }

    #[test]
    fn get_product_name_is_correct_with_complete_manifest() {
        let actual = Wix::new().get_product_name(&complete_manifest()).unwrap();
        assert_eq!(&actual, "cargo-wix");
    }

    #[test]
    fn get_product_name_is_correct_with_minimal_manifest() {
        let actual = Wix::new().get_product_name(&minimal_manifest()).unwrap();
        assert_eq!(&actual, "minimal-project");
    }

    #[test]
    fn get_product_name_is_correct_with_some_value() {
        const EXPECTED: &str = "Test Product Name";
        let actual = Wix::new().product_name(Some(EXPECTED))
            .get_product_name(&complete_manifest()).unwrap();
        assert_eq!(&actual, EXPECTED);
    }

    #[test]
    fn get_signer_is_correct_with_default() {
        let signer = Wix::new().get_signer().unwrap();
        assert_eq!(format!("{:?}", signer), format!("{:?}", Command::new(SIGNTOOL)));
    }

    fn windows_10_bin_folder() -> PathBuf {
        let mut windows_10_bin = PathBuf::from("C:\\");
        windows_10_bin.push("Program Files (x86)");
        windows_10_bin.push("Windows Kits");
        windows_10_bin.push("10");
        windows_10_bin.push("bin");
        let version_folder = fs::read_dir(&windows_10_bin).unwrap().filter_map(|entry| {
            let path = entry.unwrap().path();
            if path.is_dir() {
                Some(path)
            } else {
                None
            }
        }).find(|path| {
            let name = path.file_name().unwrap();
            name != "arm" && name != "arm64" && name != "x64" && name != "x86" 
        }).unwrap();
        windows_10_bin.push(version_folder);
        windows_10_bin.push("x64");
        windows_10_bin
    }

    #[test]
    fn get_signer_is_correct_with_some_value() {
        let test_path = windows_10_bin_folder();
        let mut expected = PathBuf::from(&test_path);
        expected.push(SIGNTOOL);
        expected.set_extension(EXE_FILE_EXTENSION);
        let signer = Wix::new().sign_path(test_path.to_str()).get_signer().unwrap();
        assert_eq!(format!("{:?}", signer), format!("{:?}", Command::new(expected)));
    }

    #[test]
    #[should_panic]
    fn get_signer_fails_with_nonexistent_path_from_some_value() {
        let test_path = PathBuf::from("C:\\");
        let mut expected = PathBuf::from(&test_path);
        expected.push(SIGNTOOL);
        expected.set_extension(EXE_FILE_EXTENSION);
        Wix::new().sign_path(test_path.to_str()).get_signer().unwrap();
    }

    #[test]
    fn get_signer_is_correct_with_environment_variable() {
        let test_path = windows_10_bin_folder();
        env::set_var(SIGNTOOL_PATH_KEY, &test_path);
        let mut expected = PathBuf::from(&test_path);
        expected.push(SIGNTOOL);
        expected.set_extension(EXE_FILE_EXTENSION);
        let signer = Wix::new().get_signer().unwrap();
        env::remove_var(SIGNTOOL_PATH_KEY);
        assert_eq!(format!("{:?}", signer), format!("{:?}", Command::new(expected)));
    }

    #[test]
    #[should_panic]
    fn get_signer_fails_with_nonexistent_path_from_environment_variable() {
        let test_path = PathBuf::from("C:\\");
        env::set_var(SIGNTOOL_PATH_KEY, &test_path);
        let mut expected = PathBuf::from(&test_path);
        expected.push(SIGNTOOL);
        expected.set_extension(EXE_FILE_EXTENSION);
        let result = Wix::new().get_signer();
        env::remove_var(SIGNTOOL_PATH_KEY);
        result.unwrap();
    }

    #[test]
    fn get_destination_msi_is_correct_with_defaults() {
        const PRODUCT_NAME: &str = "test";
        const VERSION: &str = "1.2.3";
        const PLATFORM: Platform = Platform::X64;
        let mut expected = PathBuf::from("target");
        expected.push(WIX);
        expected.push(format!("{}-{}-{}.msi", PRODUCT_NAME, VERSION, PLATFORM.arch()));
        let actual = Wix::new().get_destination_msi(PRODUCT_NAME, VERSION, &PLATFORM);
        assert_eq!(actual, expected);
    }

    #[test]
    fn get_destination_msi_is_correct_with_some_value() {
        const PRODUCT_NAME: &str = "test";
        const VERSION: &str = "1.2.3";
        const PLATFORM: Platform = Platform::X64;
        let mut expected = PathBuf::from("C:");
        expected.push("output");
        expected.push("installer.msi");
        let actual = Wix::new().output(expected.to_str())
            .get_destination_msi(PRODUCT_NAME, VERSION, &PLATFORM);
        assert_eq!(actual, expected);
    }
}