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
#![deny(
    missing_debug_implementations,
    trivial_numeric_casts,
    unstable_features,
    unused_import_braces,
    unused_qualifications
)]

extern crate cargo_metadata;
#[macro_use]
extern crate failure;
#[macro_use]
extern crate log;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate ansi_term;

use std::collections::{HashSet, HashMap};
use std::process::{Command, Stdio};
use std::path::{Path, PathBuf};
use std::io::{self, BufRead, BufReader};
use std::ffi::OsString;
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::cell::Cell;
use std::env;
use std::thread;
use std::str;
use std::error;
use std::fmt;

mod cargo;
mod cargo_output;
mod rustc_diagnostic;
mod diagnostic_formatter;

use self::cargo::cfg::{Cfg, CfgExpr};
use self::cargo_output::{CargoOutput, PackageId};

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum BuildType {
    Debug,
    Release
}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Profile {
    Main,
    Test,
    Bench
}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum TargetKind {
    Lib,
    CDyLib,
    Bin,
    Example,
    Test,
    Bench
}

#[derive(Clone, Debug)]
pub struct CargoProject {
    pub packages: Vec< CargoPackage >,
    pub target_directory: String
}

#[derive(Clone, Debug)]
pub struct CargoPackageId( PackageId );

// TODO: Fix this upstream.
impl PartialEq for CargoPackageId {
    fn eq( &self, rhs: &CargoPackageId ) -> bool {
        self.0.name() == rhs.0.name() &&
        self.0.version() == rhs.0.version() &&
        self.0.url() == rhs.0.url()
    }
}

impl Eq for CargoPackageId {}

impl Hash for CargoPackageId {
    fn hash< H: Hasher >( &self, state: &mut H ) {
        self.0.name().hash( state );
        self.0.version().hash( state );
        self.0.url().hash( state );
    }
}

impl CargoPackageId {
    fn new( id: &str ) -> Option< Self > {
        let value = serde_json::Value::String( id.to_owned() );
        match serde_json::from_value( value ).ok() {
            Some( package_id ) => Some( CargoPackageId( package_id ) ),
            None => None
        }
    }
}

impl Deref for CargoPackageId {
    type Target = PackageId;
    fn deref( &self ) -> &Self::Target {
        &self.0
    }
}

#[derive(Clone, PartialEq, Debug)]
pub struct CargoPackage {
    pub id: CargoPackageId,
    pub name: String,
    pub manifest_path: PathBuf,
    pub crate_root: PathBuf,
    pub targets: Vec< CargoTarget >,
    pub dependencies: Vec< CargoDependency >,
    pub is_workspace_member: bool,
    pub is_default: bool
}

#[derive(Clone, PartialEq, Debug)]
pub struct CargoTarget {
    pub name: String,
    pub kind: TargetKind,
    pub source_directory: PathBuf
}

#[derive(Clone, PartialEq, Debug)]
pub enum CargoDependencyKind {
    Normal,
    Development,
    Build
}

#[derive(Clone, PartialEq, Debug)]
pub enum CargoDependencyTarget {
    Expr( CfgExpr ),
    Target( String )
}

struct TargetCfg {
    triplet: String,
    map: HashMap< String, String >,
    set: HashSet< String >
}

impl TargetCfg {
    fn new( triplet: &str ) -> Self {
        let rustc =
            if cfg!( windows ) {
                "rustc.exe"
            } else {
                "rustc"
            };

        // NOTE: Currently this will always emit the "debug_assertion" config
        // even if we're compiling in release mode, and it won't contain "test"
        // even if we're building tests.
        //
        // Cargo works the same way:
        //    https://github.com/rust-lang/cargo/issues/5777

        debug!( "Querying the target config..." );
        let mut command = Command::new( rustc );
        command.arg( "--target" );
        command.arg( triplet );
        command.arg( "--print" );
        command.arg( "cfg" );

        let mut map = HashMap::new();
        let mut set = HashSet::new();

        command.stdout( Stdio::piped() );
        command.stderr( Stdio::inherit() );
        command.stdin( Stdio::null() );
        let result = command.output().expect( "could not launch rustc" );
        if !result.status.success() {
            panic!( "Failed to grab the target configuration from rustc!" );
        }

        for line in BufReader::new( result.stdout.as_slice() ).lines() {
            let line = line.unwrap();
            let line = line.trim();
            if line.is_empty() {
                continue;
            }

            if let Some( index ) = line.chars().position( |byte| byte == '=' ) {
                let key: String = line.chars().take( index ).collect();
                let mut value: String = line.chars().skip( index + 2 ).collect();
                value.pop().unwrap();
                debug!( "Target config: '{}' = '{}'", key, value );
                map.insert( key, value );
            } else {
                debug!( "Target config: '{}'", line );
                set.insert( line.to_owned() );
            }
        }

        TargetCfg {
            triplet: triplet.to_owned(),
            map,
            set
        }
    }

    fn matches( &self, expr: &CfgExpr ) -> bool {
        match *expr {
            CfgExpr::Not( ref inner ) => !self.matches( &inner ),
            CfgExpr::All( ref inner ) => inner.iter().all( |inner| self.matches( &inner ) ),
            CfgExpr::Any( ref inner ) => inner.iter().any( |inner| self.matches( &inner ) ),
            CfgExpr::Value( ref inner ) => self.matches_value( &inner )
        }
    }

    fn matches_value( &self, value: &Cfg ) -> bool {
        match *value {
            Cfg::Name( ref name ) => {
                self.set.contains( name )
            },
            Cfg::KeyPair( ref key, ref expected_value ) => {
                self.map.get( key ).map( |value| value == expected_value ).unwrap_or( false )
            }
        }
    }
}

impl CargoDependencyTarget {
    fn matches( &self, target_cfg: &TargetCfg ) -> bool {
        match *self {
            CargoDependencyTarget::Target( ref target ) => *target == target_cfg.triplet,
            CargoDependencyTarget::Expr( ref expr ) => target_cfg.matches( expr )
        }
    }
}

#[derive(Clone, PartialEq, Debug)]
pub struct CargoDependency {
    pub name: String,
    pub kind: CargoDependencyKind,
    pub target: Option< CargoDependencyTarget >,
    pub resolved_to: Option< CargoPackageId >
}

#[derive(Debug)]
pub enum Error {
    CannotLaunchCargo( io::Error ),
    CargoFailed( String ),
    CannotParseCargoOutput( serde_json::Error )
}


impl error::Error for Error {
    fn description( &self ) -> &str {
        match *self {
            Error::CannotLaunchCargo( _ ) => "cannot launch cargo",
            Error::CargoFailed( _ ) => "cargo failed",
            Error::CannotParseCargoOutput( _ ) => "cannot parse cargo output"
        }
    }
}

impl fmt::Display for Error {
    fn fmt( &self, formatter: &mut fmt::Formatter ) -> fmt::Result {
        use std::error::Error as StdError;
        match *self {
            Error::CannotLaunchCargo( ref err ) => write!( formatter, "{}: {}", self.description(), err ),
            Error::CargoFailed( ref err ) => write!( formatter, "{}: {}", self.description(), err ),
            Error::CannotParseCargoOutput( ref err ) => write!( formatter, "{}: {}", self.description(), err )
        }
    }
}

impl CargoProject {
    pub fn new(
        manifest_path: Option< &str >,
        no_default_features: bool,
        enable_all_features: bool,
        features: &[String]
    ) -> Result< CargoProject, Error >
    {
        let cwd = env::current_dir().expect( "cannot get current working directory" );
        let cargo = env::var( "CARGO" ).unwrap_or_else( |_|
            if cfg!( windows ) {
                "cargo.exe"
            } else {
                "cargo"
            }.to_owned()
        );

        let mut command = Command::new( cargo );
        command.arg( "metadata" );

        if no_default_features {
            command.arg( "--no-default-features" );
        }

        if enable_all_features {
            command.arg( "--all-features" );
        }

        if !features.is_empty() {
            command.arg( "--features" );
            command.arg( &features.join( " " ) );
        }

        command.arg( "--format-version" );
        command.arg( "1" );

        if let Some( manifest_path ) = manifest_path {
            command.arg( "--manifest-path" );
            command.arg( manifest_path );
        }

        if cfg!( unix ) {
            command.arg( "--color" );
            command.arg( "always" );
        }

        debug!( "Launching: {:?}", command );

        let output = command.output().map_err( |err| Error::CannotLaunchCargo( err ) )?;
        if !output.status.success() {
            return Err( Error::CargoFailed( String::from_utf8_lossy( &output.stderr ).into_owned() ) );
        }
        let metadata = str::from_utf8( &output.stdout ).expect( "cargo output is not valid UTF-8" );
        let metadata: cargo_metadata::Metadata =
            serde_json::from_str( metadata ).map_err( |err| Error::CannotParseCargoOutput( err ) )?;

        let mut workspace_members = HashSet::new();
        for member in metadata.workspace_members {
            workspace_members.insert( member.name().to_owned() );
        }

        let mut project = CargoProject {
            target_directory: metadata.target_directory,
            packages: metadata.packages.into_iter().map( |package| {
                let manifest_path: PathBuf = package.manifest_path.into();
                let is_workspace_member = workspace_members.contains( &*package.name );
                CargoPackage {
                    id: CargoPackageId::new( &package.id ).expect( "unparsable package id" ),
                    name: package.name,
                    crate_root: manifest_path.parent().unwrap().into(),
                    manifest_path: manifest_path,
                    is_workspace_member,
                    is_default: false,
                    targets: package.targets.into_iter().filter_map( |target| {
                        Some( CargoTarget {
                            name: target.name,
                            kind: match target.kind[ 0 ].as_str() {
                                "lib" => TargetKind::Lib,
                                "rlib" => TargetKind::Lib,
                                "cdylib" => TargetKind::CDyLib,
                                "dylib" => TargetKind::Lib,
                                "staticlib" => TargetKind::Lib,
                                "bin" => TargetKind::Bin,
                                "example" => TargetKind::Example,
                                "test" => TargetKind::Test,
                                "bench" => TargetKind::Bench,
                                "custom-build" => return None,
                                "proc-macro" => return None,
                                _ => panic!( "Unknown target kind: '{}'", target.kind[ 0 ] )
                            },
                            source_directory: Into::< PathBuf >::into( target.src_path ).parent().unwrap().into()
                        })
                    }).collect(),
                    dependencies: package.dependencies.into_iter().map( |dependency| {
                        // TODO: Make the `target` field public in `cargo_metadata`.
                        let json: serde_json::Value = serde_json::from_str( &serde_json::to_string( &dependency ).unwrap() ).unwrap();
                        let target = match json.get( "target" ).unwrap() {
                            &serde_json::Value::Null => None,
                            &serde_json::Value::String( ref target ) => {
                                let target = if target.starts_with( "cfg(" ) && target.ends_with( ")" ) {
                                    let cfg = target[ 4..target.len() - 1 ].trim().parse().expect( "cannot parse target specification in a Cargo.toml" );
                                    CargoDependencyTarget::Expr( cfg )
                                } else {
                                    CargoDependencyTarget::Target( target.clone() )
                                };

                                Some( target )
                            },
                            _ => unreachable!()
                        };

                        CargoDependency {
                            name: dependency.name,
                            kind: match dependency.kind {
                                cargo_metadata::DependencyKind::Normal => CargoDependencyKind::Normal,
                                cargo_metadata::DependencyKind::Development => CargoDependencyKind::Development,
                                cargo_metadata::DependencyKind::Build => CargoDependencyKind::Build,
                                other => panic!( "Unknown dependency kind: {:?}", other )
                            },
                            target,
                            resolved_to: None
                        }
                    }).collect()
                }
            }).collect()
        };

        let mut package_map = HashMap::new();
        for (index, package) in project.packages.iter().enumerate() {
            package_map.insert( package.id.clone(), index );
        }

        for node in metadata.resolve.expect( "missing `resolve` metadata section" ).nodes {
            let id = CargoPackageId::new( &node.id ).expect( "unparsable package id in the `resolve` metadata section" );
            let package_index = *package_map.get( &id ).expect( "extra entry in the `resolve` metadata section" );
            let package = &mut project.packages[ package_index ];
            for dependency_id in node.dependencies {
                let dependency_id = CargoPackageId::new( &dependency_id ).expect( "unparsable dependency package id" );

                let mut dependency_found = false;
                for dependency in package.dependencies.iter_mut().filter( |dep| dep.name == dependency_id.name() ) {
                    assert!( dependency.resolved_to.is_none(), "duplicate dependency" );
                    dependency.resolved_to = Some( dependency_id.clone() );
                    dependency_found = true;
                }

                assert!( dependency_found, "dependency missing from packages" );
            }
        }

        let mut default_package: Option< (usize, usize) > = None;
        for (package_index, package) in project.packages.iter().enumerate() {
            if !package.is_workspace_member {
                continue;
            }

            let package_directory = package.manifest_path.parent().unwrap();
            if !cwd.starts_with( package_directory ) {
                continue;
            }

            let common_length = cwd.components().zip( package_directory.components() ).take_while( |&(a, b)| a == b ).count();
            if default_package == None || default_package.unwrap().1 < common_length {
                default_package = Some( (package_index, common_length) );
            }
        }

        if let Some( (default_package_index, _) ) = default_package {
            project.packages[ default_package_index ].is_default = true;
        }

        Ok( project )
    }

    pub fn default_package( &self ) -> Option< &CargoPackage > {
        self.packages.iter().find( |package| package.is_default )
    }

    pub fn used_packages( &self, triplet: &str, main_package: &CargoPackage, profile: Profile ) -> Vec< &CargoPackage > {
        let mut package_map = HashMap::new();
        for (index, package) in self.packages.iter().enumerate() {
            package_map.insert( package.id.clone(), index );
        }

        struct Entry< 'a > {
            package: &'a CargoPackage,
            is_used: Cell< bool >
        }

        let mut queue = Vec::new();
        let entries: Vec< Entry > = self.packages.iter().enumerate().map( |(index, package)| {
            let is_main_package = package == main_package;
            if is_main_package {
                queue.push( index );
            }

            Entry {
                package,
                is_used: Cell::new( is_main_package )
            }
        }).collect();

        let target_cfg = TargetCfg::new( triplet );
        while let Some( index ) = queue.pop() {
            for dependency in &entries[ index ].package.dependencies {
                if let Some( ref target ) = dependency.target {
                    if !target.matches( &target_cfg ) {
                        continue;
                    }
                }

                match profile {
                    Profile::Main => {
                        match dependency.kind {
                            CargoDependencyKind::Normal => {},
                            CargoDependencyKind::Development |
                            CargoDependencyKind::Build => continue
                        }
                    },
                    Profile::Test |
                    Profile::Bench => {
                        match dependency.kind {
                            CargoDependencyKind::Normal |
                            CargoDependencyKind::Development => {},
                            CargoDependencyKind::Build => continue
                        }
                    }
                }

                let dependency_id = match dependency.resolved_to {
                    Some( ref dependency_id ) => dependency_id,
                    None => continue
                };

                let dependency_index = *package_map.get( dependency_id ).unwrap();
                if entries[ dependency_index ].is_used.get() {
                    continue;
                }

                entries[ dependency_index ].is_used.set( true );
                queue.push( dependency_index );
            }
        }

        entries.into_iter().filter( |entry| entry.is_used.get() ).map( |entry| entry.package ).collect()
    }
}

#[derive(Clone, Debug)]
pub enum BuildTarget {
    Lib( String, Profile ),
    Bin( String, Profile ),
    ExampleBin( String ),
    IntegrationTest( String ),
    IntegrationBench( String )
}

impl BuildTarget {
    fn is_executable( &self ) -> bool {
        match *self {
            BuildTarget::Lib( _, Profile::Main ) => false,
            _ => true
        }
    }
}

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum MessageFormat {
    Human,
    Json
}

#[derive(Clone, Debug)]
pub struct BuildConfig {
    pub build_target: BuildTarget,
    pub build_type: BuildType,
    pub triplet: Option< String >,
    pub package: Option< String >,
    pub features: Vec< String >,
    pub no_default_features: bool,
    pub enable_all_features: bool,
    pub extra_paths: Vec< PathBuf >,
    pub extra_rustflags: Vec< String >,
    pub extra_environment: Vec< (String, String) >,
    pub message_format: MessageFormat,
    pub is_verbose: bool,
    pub use_color: bool
}

fn profile_to_arg( profile: Profile ) -> &'static str {
    match profile {
        Profile::Main => "dev",
        Profile::Test => "test",
        Profile::Bench => "bench"
    }
}

pub fn target_to_build_target( target: &CargoTarget, profile: Profile ) -> BuildTarget {
    match target.kind {
        TargetKind::Lib => BuildTarget::Lib( target.name.clone(), profile ),
        TargetKind::CDyLib => BuildTarget::Lib( target.name.clone(), profile ),
        TargetKind::Bin => BuildTarget::Bin( target.name.clone(), profile ),
        TargetKind::Example => BuildTarget::ExampleBin( target.name.clone() ),
        TargetKind::Test => BuildTarget::IntegrationTest( target.name.clone() ),
        TargetKind::Bench => BuildTarget::IntegrationBench( target.name.clone() )
    }
}

impl BuildConfig {
    fn as_command( &self, should_build: bool ) -> Command {
        let mut command = Command::new( "cargo" );
        if should_build {
            command.arg( "rustc" );
        } else {
            command.arg( "check" );
        }

        command.arg( "--message-format" );
        command.arg( "json" );

        if cfg!( unix ) && self.use_color {
            command.arg( "--color" );
            command.arg( "always" );
        }

        if let Some( ref triplet ) = self.triplet {
            command.arg( "--target" ).arg( triplet.as_str() );
        }

        if let Some( ref package ) = self.package {
            command.arg( "--package" ).arg( package.as_str() );
        }

        match self.build_type {
            BuildType::Debug => {},
            BuildType::Release => {
                command.arg( "--release" );
            }
        }

        match self.build_target {
            BuildTarget::Lib( _, _ ) if !should_build => {
                command.arg( "--lib" );
            },
            BuildTarget::Bin( ref name, _ ) if !should_build => {
                command.arg( "--bin" ).arg( name.as_str() );
            },
            BuildTarget::Lib( _, profile ) => {
                command
                    .arg( "--profile" ).arg( profile_to_arg( profile ) )
                    .arg( "--lib" );
            },
            BuildTarget::Bin( ref name, profile ) => {
                command
                    .arg( "--profile" ).arg( profile_to_arg( profile ) )
                    .arg( "--bin" ).arg( name.as_str() );
            },
            BuildTarget::ExampleBin( ref name ) => {
                command.arg( "--example" ).arg( name.as_str() );
            },
            BuildTarget::IntegrationTest( ref name ) => {
                command.arg( "--test" ).arg( name.as_str() );
            },
            BuildTarget::IntegrationBench( ref name ) => {
                command.arg( "--bench" ).arg( name.as_str() );
            }
        }

        if self.no_default_features {
            command.arg( "--no-default-features" );
        }

        if self.enable_all_features {
            command.arg( "--all-features" );
        }

        if !self.features.is_empty() {
            command.arg( "--features" );
            command.arg( &self.features.join( " " ) );
        }

        if self.is_verbose {
            command.arg( "--verbose" );
        }

        command
    }

    pub fn check( &self ) -> CargoResult {
        let status = self.launch_cargo( false ).map( |(status, _)| status );
        CargoResult {
            status,
            artifacts: Vec::new()
        }
    }

    pub fn build< F >( &self, mut postprocess: Option< F > ) -> CargoResult
        where F: for <'a> FnMut( Vec< PathBuf > ) -> Vec< PathBuf >
    {
        let mut result = self.build_internal( &mut postprocess );
        if result.is_ok() == false {
            return result;
        }

        // HACK: For some reason when you install emscripten for the first time
        // the first build is always a dud (it produces no artifacts), so we retry once.
        let is_emscripten = self.triplet.as_ref().map( |triplet| {
            triplet == "wasm32-unknown-emscripten" || triplet == "asmjs-unknown-emscripten"
        }).unwrap_or( false );

        if is_emscripten && self.build_target.is_executable() {
            let no_js_generated = result
                .artifacts()
                .iter()
                .find( |artifact| artifact.extension().map( |ext| ext == "js" ).unwrap_or( false ) )
                .is_none();

            if no_js_generated {
                debug!( "No artifacts were generated yet build succeeded; retrying..." );
                result = self.build_internal( &mut postprocess );
            }
        }

        return result;
    }

    fn launch_cargo( &self, should_build: bool ) -> Option< (i32, Vec< cargo_output::Artifact >) > {
        let mut command = self.as_command( should_build );

        let env_paths = env::var_os( "PATH" )
            .map( |paths| env::split_paths( &paths ).collect() )
            .unwrap_or( Vec::new() );

        let mut paths = Vec::new();
        paths.extend( self.extra_paths.clone().into_iter() );
        paths.extend( env_paths.into_iter() );

        let new_paths = env::join_paths( paths ).unwrap();
        debug!( "Will launch cargo with PATH: {:?}", new_paths );
        command.env( "PATH", new_paths );

        let mut rustflags = OsString::new();
        for flag in &self.extra_rustflags {
            if !rustflags.is_empty() {
                rustflags.push( " " );
            }
            rustflags.push( flag );
        }

        if let Some( env_rustflags ) = env::var_os( "RUSTFLAGS" ) {
            if !rustflags.is_empty() {
                rustflags.push( " " );
            }
            rustflags.push( env_rustflags );
        }

        debug!( "Will launch cargo with RUSTFLAGS: {:?}", rustflags );
        command.env( "RUSTFLAGS", rustflags );

        for &(ref key, ref value) in &self.extra_environment {
            debug!( "Will launch cargo with variable \"{}\" set to \"{}\"", key, value );
            command.env( key, value );
        }

        command.stdout( Stdio::piped() );
        command.stderr( Stdio::piped() );

        debug!( "Launching cargo: {:?}", command );
        let mut child = match command.spawn() {
            Ok( child ) => child,
            Err( _ ) => return None
        };

        let stderr = BufReader::new( child.stderr.take().unwrap() );
        let stdout = BufReader::new( child.stdout.take().unwrap() );

        let is_verbose = self.is_verbose;
        thread::spawn( move || {
            let mut skip = 0;
            for line in stderr.lines() {
                let line = match line {
                    Ok( line ) => line,
                    Err( _ ) => break
                };

                if skip > 0 {
                    skip -= 1;
                    continue;
                }

                // This is really ugly, so let's skip it.
                if line.trim() == "Caused by:" && !is_verbose {
                    skip += 1;
                    continue;
                }

                eprintln!( "{}", line );
            }
        });

        let mut artifacts = Vec::new();
        for line in stdout.lines() {
            let line = match line {
                Ok( line ) => line,
                Err( _ ) => break
            };

            let line = line.trim();
            if line.is_empty() {
                continue;
            }

            let json: serde_json::Value = serde_json::from_str( &line ).expect( "failed to parse cargo output" );
            let line = serde_json::to_string_pretty( &json ).unwrap();
            if let Some( output ) = CargoOutput::parse( &line ) {
                match output {
                    CargoOutput::Message( message ) => {
                        match self.message_format {
                            MessageFormat::Human => diagnostic_formatter::print( self.use_color, &message ),
                            MessageFormat::Json => {
                                println!( "{}", serde_json::to_string( &message.to_json_value() ).unwrap() );
                            }
                        }
                    },
                    CargoOutput::Artifact( artifact ) => {
                        for filename in &artifact.filenames {
                            debug!( "Built artifact: {}", filename );
                        }

                        artifacts.push( artifact );
                    },
                    CargoOutput::BuildScriptExecuted( executed ) => {
                        match self.message_format {
                            MessageFormat::Human => {},
                            MessageFormat::Json => {
                                println!( "{}", serde_json::to_string( &executed.to_json_value() ).unwrap() );
                            }
                        }
                    }
                }
            }
        }

        let result = child.wait();
        let status = result.unwrap().code().expect( "failed to grab cargo status code" );
        debug!( "Cargo finished with status: {}", status );

        Some( (status, artifacts) )
    }

    fn build_internal< F >( &self, postprocess: &mut Option< F > ) -> CargoResult
        where F: for <'a> FnMut( Vec< PathBuf > ) -> Vec< PathBuf >
    {
        let (status, mut artifacts) = match self.launch_cargo( true ) {
            Some( result ) => result,
            None => {
                return CargoResult {
                    status: None,
                    artifacts: Vec::new()
                }
            }
        };

        fn has_extension< P: AsRef< Path > >( path: P, extension: &str ) -> bool {
            path.as_ref().extension().map( |ext| ext == extension ).unwrap_or( false )
        }

        fn find_artifact( artifacts: &[cargo_output::Artifact], extension: &str ) -> Option< (usize, usize) > {
            artifacts.iter().enumerate().filter_map( |(artifact_index, artifact)| {
                if let Some( filename_index ) = artifact.filenames.iter().position( |filename| has_extension( filename, extension ) ) {
                    Some( (artifact_index, filename_index) )
                } else {
                    None
                }
            }).next()
        }

        // For some reason when building tests cargo doesn't treat
        // the `.wasm` file as an artifact.
        if status == 0 && self.triplet.as_ref().map( |triplet| triplet == "wasm32-unknown-emscripten" ).unwrap_or( false ) {
            match self.build_target {
                BuildTarget::Bin( _, Profile::Test ) |
                BuildTarget::Lib( _, Profile::Test ) |
                BuildTarget::IntegrationTest( _ ) => {
                    if find_artifact( &artifacts, "wasm" ).is_none() {
                        if let Some( (artifact_index, filename_index) ) = find_artifact( &artifacts, "js" ) {
                            let wasm_path = {
                                let main_artifact = Path::new( &artifacts[ artifact_index ].filenames[ filename_index ] );
                                let filename = main_artifact.file_name().unwrap();
                                main_artifact.parent().unwrap().join( "deps" ).join( filename ).with_extension( "wasm" )
                            };

                            assert!( wasm_path.exists(), "internal error: wasm doesn't exist where I expected it to be" );
                            artifacts[ artifact_index ].filenames.push( wasm_path.to_str().unwrap().to_owned() );
                            debug!( "Found `.wasm` test artifact: {:?}", wasm_path );
                        }
                    }
                },
                _ => {}
            }
        }

        let mut artifact_paths = Vec::new();
        for mut artifact in &mut artifacts {
            if let Some( ref mut callback ) = postprocess.as_mut() {
                let filenames = artifact.filenames.iter().map( |filename| Path::new( &filename ).to_owned() ).collect();
                let filenames = callback( filenames );
                artifact.filenames = filenames.into_iter().map( |filename| filename.to_str().unwrap().to_owned() ).collect();
            }
        }

        for mut artifact in artifacts {
            if artifact.filenames.is_empty() {
                continue;
            }

            match self.message_format {
                MessageFormat::Human => {},
                MessageFormat::Json => {
                    println!( "{}", serde_json::to_string( &artifact.to_json_value() ).unwrap() );
                }
            }

            for filename in artifact.filenames {
                // NOTE: Since we extract the paths from the JSON
                //       we get a list of artifacts as `String`s instead of `PathBuf`s.
                artifact_paths.push( filename.into() )
            }
        }

        CargoResult {
            status: Some( status ),
            artifacts: artifact_paths
        }
    }
}

#[derive(Debug)]
pub struct CargoResult {
    status: Option< i32 >,
    artifacts: Vec< PathBuf >
}

impl CargoResult {
    pub fn is_ok( &self ) -> bool {
        self.status == Some( 0 )
    }

    pub fn artifacts( &self ) -> &[PathBuf] {
        &self.artifacts
    }
}