pmeunier / carnix

Description

By blabla on February 25, 2019
This patch is not signed.
9kMu5Dcv8gUugMSSjsFWCYkvC2Ab62voMpgE2L4sv4bFa6jtqdjsb2VDgJrnxRSEQ4LQJvWoXQjvrZWgqjLZEcgb
This patch is in the following branches:
master
In file Cargo.lock

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
version = "0.9.9"
[[package]]
name = "aho-corasick"
version = "0.6.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "memchr 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "ansi_term"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "argon2rs"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "blake2-rfc 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)",
 "scoped_threadpool 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "arrayvec"
version = "0.4.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "nodrop 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "atty"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "autocfg"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"

[[package]]
name = "backtrace"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "autocfg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "backtrace-sys 0.1.28 (registry+https://github.com/rust-lang/crates.io-index)",
 "cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "rustc-demangle 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "backtrace-sys"
version = "0.1.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cc 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "bitflags"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"

[[package]]
name = "blake2-rfc"
version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "arrayvec 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)",
 "constant_time_eq 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "carnix"
version = "0.9.8"
version = "0.10.0"
dependencies = [
In file Cargo.toml

1
2

3
4
version = "0.9.9"
[package]
name = "carnix"
version = "0.9.8"
version = "0.10.0"
authors = ["pe@pijul.org <pe@pijul.org>"]
In file src/krate.rs
39
40
41
    pub authors: Vec<String>,
    pub description: Option<String>,
    pub edition: Option<String>,

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
            writeln!(w, "{}  description = \"{}\";", indent, descr)?;
use std::path::Path;
use toml;
use std;
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Write};
use regex::Regex;
use std::path::PathBuf;
use itertools::Itertools;
use dirs;
use failure::Error;
use cfg;
use krate::*;
use cache::*;

struct FeatName<'a>(&'a str);
impl<'a> std::fmt::Display for FeatName<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        if self.0.chars().all(|x| {
            (x >= '0' && x <= '9') || (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z') || x == '_'
                || x == '-'
        }) {
            write!(f, "{}", self.0)
        } else {
            write!(f, "\"{}\"", self.0)
        }
    }
}

#[derive(Debug)]
enum CrateType {
    Workspace {
        members: BTreeMap<String, (Crate, PathBuf)>,
        package: Option<(String, (Crate, PathBuf))>,
    },
    Single(String, (Crate, PathBuf))
}

enum Either<A, B> {
    A(A),
    B(B)
}

impl<Item, A:Iterator<Item = Item>, B:Iterator<Item = Item>> Iterator for Either<A, B> {
    type Item = Item;
    fn next(&mut self) -> Option<Self::Item> {
        match *self {
            Either::A(ref mut a) => a.next(),
            Either::B(ref mut b) => b.next(),
        }
    }
}

impl CrateType {
    fn is_workspace(&self) -> bool {
        if let CrateType::Workspace { .. } = *self {
            true
        } else {
            false
        }
    }
    fn get(&self, key: &str) -> Option<&(Crate, PathBuf)> {
        match *self {
            CrateType::Workspace { members: ref x, ref package } => {
                if let Some(x) = x.get(key) {
                    Some(x)
                } else if let Some(ref p) = *package {
                    if p.0 == key {
                        Some(&p.1)
                    } else {
                        None
                    }
                } else {
                    None
                }
            },
            CrateType::Single(ref name, ref cr) if name == key => Some(cr),
            CrateType::Single(_, _) => None,
        }
    }
    fn source_type<P: AsRef<Path>>(&self, src: Option<P>, name: &str) -> SourceType {
        if let Some(&(_, ref path)) = self.get(name) {
            if let Some(ref src) = src {
                if self.is_workspace() {
                    SourceType::Path {
                        path: src.as_ref().to_path_buf(),
                        workspace_member: Some(path.to_path_buf()),
                    }
                } else {
                    SourceType::Path {
                        path: src.as_ref().to_path_buf(),
                        workspace_member: None,
                    }
                }
            } else {
                SourceType::CratesIO
            }
        } else {
            SourceType::None
        }
    }
    fn iter<'a>(&'a self) -> impl Iterator<Item = (&'a String, &'a (Crate, PathBuf))> {
        match *self {
            CrateType::Workspace { ref members, ref package } =>
                Either::A(
                    members.iter().chain(package.iter().map(|&(ref a, ref b)| (a, b)))
                ),
            CrateType::Single(ref name, ref cr) => {
                Either::B(
                    std::iter::once((name, cr))
                )
            }
        }
    }
}

fn workspace_members(base_path: &Path, cargo_toml: &toml::Value) -> Option<CrateType> {
    let package = if let Some(package) = cargo_toml.get("package") {
        let name = package.get("name").unwrap();
        let cra = get_package_version(&package);
        Some((
            name.as_str().unwrap().to_owned(),
            (cra, base_path.to_path_buf()),
        ))
    } else {
        None
    };

    if let Some(ws) = cargo_toml.get("workspace") {
        let mut workspace_members = BTreeMap::new();
        let empty_vec = Vec::new();
        let members = match ws.as_table().unwrap().get("members") {
            Some(m) => m.as_array().unwrap(),
            None => &empty_vec,
        };
        for mem in members {
            let mem = mem.as_str().unwrap();
            let mut path = base_path.join(mem);
            path.push("Cargo.toml");
            let mut toml: toml::Value = {
                let mut cargofile = std::fs::File::open(&path).unwrap();
                let mut toml = String::new();
                cargofile.read_to_string(&mut toml).unwrap();
                toml::de::from_str(&toml).unwrap()
            };
            if let Some(package) = toml.as_table_mut().unwrap().remove("package") {
                {
                    let name = package.get("name").unwrap();
                    let cra = get_package_version(&package);
                    debug!("mem path {:?}", path);
                    path.pop();
                    workspace_members.insert(
                        name.as_str().unwrap().to_owned(),
                        (cra, path)
                    );
                }
            }
        }
        return Some(CrateType::Workspace { members: workspace_members, package })
    }

    package.map(|(a, b)| CrateType::Single(a, b))
}

pub fn generate_nix<W: Write, P: AsRef<Path>, Q: AsRef<Path>>(
    lockfile: P,
    standalone: bool,
    src: Option<Q>,
    nix_file: W,
) -> Result<BTreeMap<Crate, Meta>, Error> {
    let mut cr = lockfile.as_ref().to_path_buf();
    let mut lock: toml::Value = {
        let mut lockfile = std::fs::File::open(&cr).unwrap();
        let mut toml = String::new();
        lockfile.read_to_string(&mut toml).unwrap();
        toml::de::from_str(&toml).unwrap()
    };

    let mut packages = if let Some(package) = lock.as_table_mut().unwrap().remove("package") {
        if let toml::Value::Array(package) = package {
            package
        } else {
            Vec::new()
        }
    } else {
        Vec::new()
    };

    cr.set_extension("toml");

    let cargo_toml: toml::Value = {
        let mut cargofile = std::fs::File::open(&cr).unwrap();
        let mut toml = String::new();
        cargofile.read_to_string(&mut toml).unwrap();
        toml::de::from_str(&toml).unwrap()
    };

    let (mut deps, _) = {
        make_dependencies(
            cr.parent().unwrap(),
            cargo_toml.get("dependencies"),
            cargo_toml.get("features"),
        )
    };

    let base_path = cr.parent().unwrap();

    let workspace_members =
        workspace_members(base_path, &cargo_toml).expect("neither workspace nor regular crate");
    debug!("ws members {:?}", workspace_members);

    debug!("main deps: {:?} {:?}", cr, deps);

    // Loading the cache (a map between package versions and Nix store paths).
    let mut cache_path = dirs::home_dir().unwrap();
    cache_path.push(".cargo");
    std::fs::create_dir_all(&cache_path).unwrap();
    cache_path.push("nix-cache");
    let mut cache = Cache::new(&cache_path)?;


    // Compute the meta-information for all packages in the lock file.
    debug!("base_path: {:?}", base_path);

    let main_meta = {
        let root = if let Some(root) = lock.as_table().unwrap().get("root") {
            Some(root)
        } else if let Some(name) = cargo_toml.get("package").and_then(|package| package.as_table().and_then(|package| package.get("name"))) {
            packages.iter().find(|x| x.get("name").unwrap() == name)
        } else {
            None
        };

        if let Some(root) = root {
            let main_cra = get_package_version(&root);

            debug!("name = {:?}", main_cra.name);
            if let Some(dep) = deps.get(&main_cra.name) {
                debug!("dep = {:?}", dep);
            }

            let path = workspace_members.source_type(src.as_ref(), &main_cra.name);
            let mut meta = match main_cra.prefetch(&mut cache, &path) {
                Ok(meta) => meta,
                Err(e) => {
                    std::mem::drop(cache);
                    return Err(e)
                }
            };
            if let Some(inc) = cargo_toml
                .get("package")
                .unwrap()
                .as_table()
                .unwrap()
                .get("include")
            {
                meta.include = Some(
                    inc.as_array()
                        .unwrap()
                        .into_iter()
                        .map(|x| x.as_str().unwrap().to_string())
                        .collect(),
                )
            }
            if let Some(ref src) = src {
                meta.src = Src::Path {
                    path: src.as_ref().to_path_buf(),
                    workspace_member: None,
                }
            }
            Some(meta)
        } else {
            None
        }
    };

    let mut all_packages = match fixpoint(
        &mut cache,
        src,
        &mut packages,
        &mut deps,
        &workspace_members,
        main_meta.as_ref(),
    ) {
        Ok(pack) => pack,
        Err(e) => {
            std::mem::drop(cache);
            return Err(e)
        }
    };

    // Make sure we save the cache.
    std::mem::drop(cache);

    // Adding the root crate, the one we're compiling.
    if let Some(mut main_meta) = main_meta {
        if let Some(root) = lock.as_table_mut().unwrap().get("root") {
            debug!("root = {:?}", root);
            let main_cra = get_package_version(&root);
            // Add the crates' dependencies.
            if let Some(deps) = root.get("dependencies") {
                update_deps(&main_cra, deps, &mut main_meta);
            }
            if let Some(deps) = root.get("build-dependencies") {
                update_deps(&main_cra, deps, &mut main_meta);
            }
            all_packages.insert(main_cra.clone(), main_meta);
        }
    }

    output(standalone, workspace_members, &all_packages, base_path, nix_file)?;
    Ok(all_packages)
}

fn cargo_lock_source_type(package: &toml::Value) -> SourceType {
    if let Some(source) = package.get("source") {
        let source = source.as_str().unwrap();
        if source == "registry+https://github.com/rust-lang/crates.io-index" {
            return SourceType::CratesIO
        }

        if source.starts_with("git+") {
            return parse_git(source)
        }
    }
    SourceType::None
}

fn local_source_type<P:AsRef<Path>>(
    crate_type: &CrateType,
    src: Option<P>,
    main_meta: Option<&Meta>,
    deps: &BTreeMap<String, Dep>,
    name: &str,
) -> SourceType {
    debug!("src = {:?}", src.as_ref().map(|x| x.as_ref()));
    debug!("crate_type: {:?}", crate_type);
    let loc = crate_type.source_type(src.as_ref(), name);
    debug!("loc: {:?}", loc);
    if let SourceType::None = loc {
        if let Some(ref dep) = deps.get(name) {
            if let Some(ref p) = dep.path {
                debug!("path {:?}", p);
                return SourceType::Path {
                    path: p.to_path_buf(),
                    workspace_member: None,
                };
            }
        } else if let Some(ref main_meta) = main_meta {
            for &(_, ref deps) in main_meta.target_dependencies.iter() {
                if let Some(ref dep) = deps.get(name) {
                    if let Some(ref p) = dep.path {
                        debug!("path {:?}", p);
                        return SourceType::Path {
                            path: p.to_path_buf(),
                            workspace_member: None,
                        };
                    }
                }
            }
        }
    }
    loc
}

fn resolve_replaces(packages: &mut Vec<toml::Value>) -> Vec<toml::Value> {
    // resolve all "replace = "
    let mut replace = BTreeMap::new();
    for pack in packages.iter() {
        if let (Some(repl), Some(source)) = (pack.get("replace"), pack.get("source")) {
            replace.insert(
                repl.as_str().unwrap().to_string(),
                source.as_str().unwrap().to_string(),
            );
        }
    }
    let mut fix = Vec::new();
    for mut pack in packages.drain(..) {
        if pack.get("replace").is_none() {
            let s = format!(
                "{} {}",
                pack.get("name").unwrap().as_str().unwrap(),
                pack.get("version").unwrap().as_str().unwrap()
            );
            if let Some(repl) = replace.get(&s) {
                let mut pack = pack.as_table_mut().unwrap();
                pack.insert("source".to_string(), toml::Value::String(repl.clone()));
                debug!("replaced {:?}", pack);
            }
            fix.push(pack)
        }
    }
    fix
}

fn fixpoint<P: AsRef<Path>>(
    cache: &mut Cache,
    src: Option<P>,
    packages: &mut Vec<toml::Value>,
    deps: &mut BTreeMap<String, Dep>,
    crate_type: &CrateType,
    main_meta: Option<&Meta>,
) -> Result<BTreeMap<Crate, Meta>, Error> {
    let mut all_packages = BTreeMap::new();

    // Here we need to compute a fixpoint of dependencies to resolve
    // all sources. This is because local sources are sometimes
    // referenced not only from this package's Cargo.toml, but from
    // this package's (transitive) dependencies, in which case the
    // only way to know where they are is to go down the dependency
    // tree (because they are not in the Cargo.lock).
    let mut packages_fixpoint = resolve_replaces(packages);
    let mut unknown_packages = packages; // empty at this point.

    while !packages_fixpoint.is_empty() {
        let mut at_least_one_resolved = false;
        for package in packages_fixpoint.drain(..) {
            let cra = get_package_version(&package);

            // We first try to resolve the source type using the Cargo.lock.
            let mut source_type = cargo_lock_source_type(&package);
            debug!("name = {:?} {:?}", cra, source_type);

            // Then try from local paths.
            if let SourceType::None = source_type {
                source_type = local_source_type(crate_type, src.as_ref(), main_meta, &deps, &cra.name)
            }

            // Finally, we prefetch the package (if available), and
            // set its source field, if the package is local.
            let meta = {
                debug!("path = {:?}", source_type);
                if source_type != SourceType::None {
                    match cra.prefetch(cache, &source_type) {
                        Ok(mut prefetch) => Some(prefetch),
                        Err(e) => return Err(e)
                    }
                } else {
                    None
                }
            };

            debug!("meta = {:?}", meta);
            if let Some(mut meta) = meta {
                // If we've successfully retrieved the package's
                // meta-information (i.e. parsed the part of our
                // Cargo.lock related to that package, and the
                // package's own Cargo.toml), we might have learned
                // exact versions of the package's dependencies from
                // the Cargo.lock, and we need to update them.
                at_least_one_resolved = true;
                for (a, b) in meta.dependencies
                    .iter()
                    .chain(meta.build_dependencies.iter())
                {
                    debug!("inserting dep for {:?}: {:?}", a, b);
                    deps.insert(a.to_string(), b.clone());
                }

                if let Some(deps) = package.get("dependencies") {
                    update_deps(&cra, deps, &mut meta)
                }
                if let Some(deps) = package.get("build-dependencies") {
                    update_deps(&cra, deps, &mut meta)
                }
                if let Some(target) = package.get("target") {
                    for package in target.as_array().unwrap().iter() {
                        if let Some(deps) = package.get("dependencies") {
                            update_deps(&cra, deps, &mut meta)
                        }
                    }
                }

                all_packages.insert(cra, meta);
            } else {
                // Else, add the package back to the fixpoint. If we
                // have learned about other dependencies during this
                // pass of the fixpoint, we might have updated `deps`,
                // so we might be able to resolve this package later.
                if all_packages.get(&cra).is_none() {
                    unknown_packages.push(package)
                } else {
                    error!(
                        "Several packages with the same name and version number {:?}",
                        cra
                    )
                }
            }
        }
        if !at_least_one_resolved {
            error!("Could not resolve some sources, unknown packages:");
            for package in unknown_packages.iter() {
                if let Some(name) = package.get("name") {
                    error!("  - {}", name.as_str().unwrap());
                } else {
                    error!("  - {:?}", package)
                }
            }
            std::process::exit(1)
        }
        std::mem::swap(&mut packages_fixpoint, &mut unknown_packages)
    }

    Ok(all_packages)
}

pub fn write_crates_io(all_packages: &BTreeMap<Crate, Meta>, names: &BTreeSet<String>) -> Result<(), Error> {
    let mut extra_crates_io = std::io::BufWriter::new(std::fs::File::create("crates-io.nix")?);
    extra_crates_io.write_all(b"{ lib, buildRustCrate, buildRustCrateHelpers }:
with buildRustCrateHelpers;
let inherit (lib.lists) fold;
    inherit (lib.attrsets) recursiveUpdate;
in
rec {\n
")?;
    for (cra, meta) in all_packages.iter() {
        if let Src::Crate { .. } = meta.src {
            cra.output_package(Path::new(""), &mut extra_crates_io, 2, &meta, &names, "")?;
        }
    }
    extra_crates_io.write_all(b"}\n")?;
    Ok(())
}

fn output<W: Write>(
    standalone: bool,
    workspace_members: CrateType,
    all_packages: &BTreeMap<Crate, Meta>,
    root_prefix: &Path,
    mut nix_file: W,
) -> Result<(), Error> {
    // And output.
    let mut command_line = String::new();
    for arg in std::env::args() {
        if !command_line.is_empty() {
            command_line.push_str(" ");
        }
        command_line.push_str(&arg);
    }
    nix_file.write_all(
        format!(
            "# Generated by carnix {}: {}\n",
            env!("CARGO_PKG_VERSION"),
            command_line
        ).as_bytes(),
    )?;

    if standalone {
        nix_file.write_all(b"{ pkgs ? import <nixpkgs> {} }: with pkgs;\n\n")?;
    } else {
        nix_file.write_all(b"{ lib, buildPlatform, buildRustCrate, buildRustCrateHelpers, cratesIO, fetchgit }:\n")?;
    }
    nix_file.write_all(b"with buildRustCrateHelpers;\nlet inherit (lib.lists) fold;\n    inherit (lib.attrsets) recursiveUpdate;\n")?;
    if standalone {
        nix_file.write_all(b"  cratesIO = (callPackage ./crates-io.nix { });\n")?;
    }
    nix_file.write_all(b"in\n")?;
    let mut names = BTreeSet::new();
    for (cra, _) in all_packages.iter() {
        names.insert(cra.name.clone());
    }

    write_crates_io(&all_packages, &names)?;
    {
        // Write a list of packages and versions, to be used by
        // `carnix generate-crates-io`.
        let mut f = std::fs::File::create("crates-io.list")?;
        for (cra, meta) in all_packages.iter() {
            if let Src::Crate { .. } = meta.src {
                writeln!(f, "{}", cra)?;
            }
        }
    }
    nix_file.write_all(b"rec {\n")?;
    nix_file.write_all(b"  crates = cratesIO")?;
    let mut is_first = true;
    for (cra, meta) in all_packages.iter() {
        if let Src::Crate { .. } = meta.src {
        } else {
            if is_first {
                nix_file.write_all(b" // rec {\n")?;
                is_first = false;
            }
            cra.output_package(root_prefix, &mut nix_file, 4, &meta, &names, "cratesIO.")?;
        }
    }
    if is_first {
        nix_file.write_all(b";\n")?;
    } else {
        // If we wrote at least one line, close the opened attribute set.
        nix_file.write_all(b"\n  };\n\n")?;
    }


    let mut all = b"[ ".to_vec();
    for (_, &(ref cra, _)) in workspace_members.iter() {

        let name = nix_name(&cra.name);
        let version = format!(
            "{}.{}.{}{}",
            cra.major,
            cra.minor,
            cra.patch,
            cra.subpatch
        );
        writeln!(
            nix_file,
            "  {} = crates.crates.{}.\"{}\" deps;",
            name,
            name,
            version,
        )?;

        write!(&mut all, "({} {{}}) ", name)?;
    }

    write!(&mut all, "]")?;

    nix_file.write_all(b"  __all = ")?;
    nix_file.write_all(&all)?;
    nix_file.write_all(b";\n")?;

    for (cra, meta) in all_packages.iter() {
        cra.output_package_call(&mut nix_file, 2, &meta)?;
    }
    nix_file.write_all(b"}\n")?;
    Ok(())
}

/// Add the dependencies from Cargo.lock.
fn update_deps(cra: &Crate, deps: &toml::Value, meta: &mut Meta) {
    let dep_re = Regex::new(r"^(\S*) (\d*)\.(\d*)\.(\d*)([\+\-]\S*)?(.*)?").unwrap();
    let mut deps_names = BTreeSet::new();
    for dep in deps.as_array().unwrap() {
        let dep = dep.as_str().unwrap();
        let cap = dep_re.captures(&dep).unwrap();
        deps_names.insert(cap.get(1).unwrap().as_str());
        debug!("updating deps for {:?}: {:?}", cra.name, dep);
        let (a, b, c, d) = {
            (
                cap.get(2).unwrap().as_str().parse().unwrap(),
                cap.get(3).unwrap().as_str().parse().unwrap(),
                cap.get(4).unwrap().as_str().parse().unwrap(),
                cap.get(5)
                    .map(|x| x.as_str().to_string())
                    .unwrap_or(String::new()),
            )
        };
        let from_crates_io = if let Some(source) = cap.get(6) {
            source.as_str() == " (registry+https://github.com/rust-lang/crates.io-index)"
        } else {
            false
        };
        let name = cap.get(1).unwrap().as_str().to_string();
        debug!("update name = {:?}", name);
        if let Some(entry) = meta.dependencies.get_mut(&name) {
            debug!("meta.dependencies");
            entry.cr.major = a;
            entry.cr.minor = b;
            entry.cr.patch = c;
            entry.cr.subpatch = d.clone();
            entry.cr.name = name.clone();
            entry.cr.found_in_lock = true;
            entry.from_crates_io = from_crates_io;
        }
        if let Some(entry) = meta.build_dependencies.get_mut(&name) {
            debug!("meta.build_dependencies");
            entry.cr.major = a;
            entry.cr.minor = b;
            entry.cr.patch = c;
            entry.cr.subpatch = d.clone();
            entry.cr.name = name.clone();
            entry.cr.found_in_lock = true;
            entry.from_crates_io = from_crates_io;
        }
        for &mut (_, ref mut deps) in meta.target_dependencies.iter_mut() {
            if let Some(entry) = deps.get_mut(&name) {
                debug!("meta.target_dependencies");
                entry.cr.major = a;
                entry.cr.minor = b;
                entry.cr.patch = c;
                entry.cr.subpatch = d.clone();
                entry.cr.name = name.clone();
                entry.cr.found_in_lock = true;
                entry.from_crates_io = from_crates_io;
            }
        }
    }
}

fn get_package_version(package: &toml::Value) -> Crate {
    let mut name = package
        .as_table()
        .unwrap()
        .get("name")
        .unwrap()
        .as_str()
        .unwrap()
        .to_string();
    let version = package.get("version").unwrap().as_str().unwrap();
    name.push_str("-");
    name.push_str(version);
    name.parse().unwrap()
}

impl Crate {
    pub fn output_package_call<W: Write>(
        &self,
        mut w: W,
        n_indent: usize,
        meta: &Meta,
    ) -> Result<(), Error> {
        let mut indent = String::new();
        for _ in 0..n_indent {
            indent.push(' ');
        }
        let version = format!(
            "{}.{}.{}{}",
            self.major,
            self.minor,
            self.patch,
            self.subpatch
        );
        // debug!("output_package_call {:?}", full_name);
        let nix_name_ = nix_name(&self.name);

        write!(w, "{}deps.{}.\"{}\" = {{",
               indent,
               nix_name_,
               version)?;
        let mut is_first = true;
        let mut h = BTreeSet::new();
        for deps in std::iter::once(&meta.dependencies)
            .chain(std::iter::once(&meta.build_dependencies))
            .chain(meta.target_dependencies.iter().map(|&(_, ref y)| y))
        {
            for (_, dep) in deps.iter().filter(|&(_, dep)| dep.cr.found_in_lock) {

                if h.contains(&dep.cr) {
                    continue
                }
                debug!("outputting dep = {:?}", dep);
                if is_first {
                    writeln!(w, "")?;
                }
                is_first = false;
                writeln!(w,"{}  {} = \"{}.{}.{}{}\";",
                         indent,
                         nix_name(&dep.cr.name),
                         dep.cr.major, dep.cr.minor, dep.cr.patch,
                         dep.cr.subpatch
                )?;
                h.insert(&dep.cr);
            }
        }
        if !is_first {
            writeln!(w, "{}}};", indent)?;
        } else {
            writeln!(w, "}};")?;
        }
        Ok(())
    }

    pub fn output_package_features<W: Write>(
        &self,
        mut w: W,
        n_indent: usize,
        meta: &Meta,
        prefix: &str,
    ) -> Result<(), Error> {

        let mut indent = String::new();
        for _ in 0..n_indent {
            indent.push(' ');
        }

        let version =
            format!(
                "{}.{}.{}{}",
                self.major, self.minor, self.patch, self.subpatch
            );

        writeln!(
            w,
            "{}features_.\"{}\".\"{}\" = deps: f: updateFeatures f (rec {{",
            indent, nix_name(&self.name), version
        )?;
        let mut output_features = BTreeMap::new();
        let nix_name_ = nix_name(&self.name);
        let full_name_default = format!("{}.\"{}\".default", nix_name_, version);
        if meta.use_default_features == Some(false) {
        } else {
            let e = output_features
                .entry(full_name_default.clone())
                .or_insert(Vec::new());
            e.push(format!("(f.{}.\"{}\".default or true)", nix_name_, version))
        }
        if !meta.implied_features.is_empty() {
            for feat in meta.implied_features.iter() {
                let dep = format!("{}.\"{}\".\"{}\"", nix_name_, version, FeatName(&feat.dep_feature));
                let mut e = output_features.entry(dep).or_insert(Vec::new());
                e.push(format!(
                    "(f.{}.\"{}\".\"{}\" or false)",
                    nix_name_,
                    version,
                    FeatName(&feat.feature)
                ));
                e.push(format!(
                    "({}.\"{}\".\"{}\" or false)",
                    nix_name_,
                    version,
                    FeatName(&feat.feature)
                ));
            }
        }

        let mut seen = BTreeSet::new();
        let mut default = BTreeMap::new();
        for deps in std::iter::once(&meta.dependencies)
            .chain(std::iter::once(&meta.build_dependencies))
            .chain(meta.target_dependencies.iter().map(|&(_, ref y)| y))
        {
            for (_, dep) in deps.iter().filter(|&(_, dep)| dep.cr.found_in_lock) {
                debug!("outputting dep = {:?}", dep);
                let dep_name = format!(
                    "{}.\"${{deps.{}.\"{}\".{}}}\"",
                    nix_name(&dep.cr.name),
                    nix_name_,
                    version,
                    nix_name(&dep.cr.name),
                );
                for feat in dep.features.iter() {
                    let mut e = output_features.entry(format!("{}.\"{}\"", dep_name, feat)).or_insert(Vec::new());
                    e.push("true".to_string());
                }

                if !dep.conditional_features.is_empty() {
                    for feat in dep.conditional_features.iter() {
                        if !seen.contains(&(&dep.cr.name, &feat.feature)) {
                            let dep_name = format!(
                                "{}.\"{}\"",
                                dep_name,
                                FeatName(&feat.dep_feature),
                            );
                            let mut e = output_features.entry(dep_name).or_insert(Vec::new());
                            e.push(format!(
                                "({}.\"{}\".\"{}\" or false)",
                                nix_name_,
                                version,
                                FeatName(&feat.feature)
                            ));
                            e.push(format!(
                                "(f.\"{}\".\"{}\".\"{}\" or false)",
                                nix_name_,
                                version,
                                FeatName(&feat.feature)
                            ));
                            seen.insert((&dep.cr.name, &feat.feature));
                        }
                    }
                }
                if !dep.default_features {
                    if default.get(&dep_name).is_none() {
                        default.insert(dep_name, false);
                    }
                } else {
                    default.insert(dep_name, true);
                }
            }
        }
        for (dep_name, default) in default.iter() {
            let dep = format!("{}.default", dep_name);
            let mut e = output_features.entry(dep).or_insert(Vec::new());
            e.push(format!("{}", *default));
        }

        let mut current_prefix = "";
        let mut current_attrs = Vec::new();

        for (a, b) in output_features.iter() {

            if !b.is_empty() {
                if current_prefix.is_empty() || !a.starts_with(current_prefix) {
                    // change current prefix
                    if !current_prefix.is_empty() {
                        // close previous prefix
                        if current_attrs.len() == 1 {
                            writeln!(w, "{}  {}.{}", indent, current_prefix.trim_end_matches('.'), current_attrs.pop().unwrap())?;
                        } else if current_attrs.len() > 1 {
                            writeln!(w, "{}  {} = fold recursiveUpdate {{}} [", indent, current_prefix.trim_end_matches('.'))?;
                            for x in current_attrs.drain(..) {
                                writeln!(w, "{}    {{ {} }}", indent, x)?;
                            }
                            writeln!(w, "{}  ];", indent)?;
                        }
                    }
                    // open new prefix
                    if let Some(i) = a.find('.') {
                        current_prefix = a.split_at(i+1).0;
                    }
                }
            }

            if b.len() == 0 {
            } else if b.len() == 1 {

                if b[0] == "true" || a == &full_name_default {
                    current_attrs.push(format!("{} = {};", a.trim_start_matches(current_prefix), b[0]))
                } else if b[0] != "false" {
                    current_attrs.push(format!("{} = (f.{} or false) || {};", a.trim_start_matches(current_prefix), a, b[0]))
                } else if a.ends_with(".default") {
                    // b[0] == false here
                    current_attrs.push(format!("{} = (f.{} or false);", a.trim_start_matches(current_prefix), a))
                }
            } else {
                let mut x = format!("{} =\n{}      (f.{} or false)", a.trim_start_matches(current_prefix), indent, a);
                for bb in b.iter() {
                    x.push_str(&format!(" ||\n{}      {}", indent, bb));
                }
                x.push_str(&format!(";"));
                current_attrs.push(x)
            }
        }
        if !current_prefix.is_empty() {
            // close previous prefix
            if current_attrs.len() == 1 {
                writeln!(w, "{}  {}.{}", indent, current_prefix.trim_end_matches('.'), current_attrs.pop().unwrap())?;
            } else if current_attrs.len() > 1 {
                writeln!(w, "{}  {} = fold recursiveUpdate {{}} [", indent, current_prefix.trim_end_matches('.'))?;
                for x in current_attrs.drain(..) {
                    writeln!(w, "{}    {{ {} }}", indent, x)?;
                }
                writeln!(w, "{}  ];", indent)?;
            }
        }

        write!(w, "{}}}) [", indent)?;
        let mut at_least_one = false;
        for (_, deps) in std::iter::once(("", &meta.dependencies))
            .chain(std::iter::once(("_build", &meta.build_dependencies)))
            .chain(meta.target_dependencies.iter().map(|&(_, ref y)| ("", y)))
        {
            for (_, dep) in deps.iter().filter(|&(_, c)| {
                c.cr.found_in_lock && c.cr.name.len() > 0
            }) {
                at_least_one = true;
                write!(
                    w,
                    "\n{}  ({}features_.{}.\"${{deps.\"{}\".\"{}\".\"{}\"}}\" deps)",
                    indent,
                    if dep.from_crates_io { prefix } else { "" },
                    nix_name(&dep.cr.name),
                    nix_name_,
                    version,
                    nix_name(&dep.cr.name),
                )?;
            }
        }
        if at_least_one {
            writeln!(w, "\n{}];\n\n", indent)?;
        } else {
            writeln!(w, "];\n\n")?;
        }
        Ok(())
    }

    pub fn output_package<W: Write>(
        &self,
        root_prefix: &Path,
        mut w: W,
        n_indent: usize,
        meta: &Meta,
        all_packages: &BTreeSet<String>,
        prefix: &str,
    ) -> Result<(), Error> {
        let mut indent = String::new();
        for _ in 0..n_indent {
            indent.push(' ');
        }

        let nix_name_ = nix_name(&self.name);
        let version =
            format!(
                "{}.{}.{}{}",
                self.major, self.minor, self.patch, self.subpatch
            );

        writeln!(w, "# {}-{}\n", self.name, version)?;
        write!(w, "{}crates.{}.\"{}\" = deps: {{ features?(features_.\"{}\".\"{}\" deps {{}}) }}: buildRustCrate {{\n",

               indent,
               nix_name(&self.name),
               version,
               nix_name(&self.name),
               version,
        )?;

        writeln!(w, "{}  crateName = \"{}\";", indent, self.name)?;

        writeln!(w, "{}  version = \"{}\";", indent, version)?;

        if let Some(ref descr) = meta.description {
            writeln!(w, "{}  description = {};", indent, descr)?;
        }
        writeln!(
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
        let edition = v.get("package").and_then(|p| p.get("edition").map(|s| s.to_string()));
        let description = v.get("package").and_then(|p| p.get("description").map(|s| s.to_string()));
        let authors = v.get("package")
            .and_then(|x| x.get("authors"))
            .and_then(|x| x.as_array())
            .map(|x| {
                x.iter()
                    .map(|y| y.as_str().unwrap().to_owned())
                    .collect::<Vec<_>>()
            })
            .unwrap_or_else(Vec::new);

        let (default_features, declared_features) = features(v);
        let include = include(v);
        Ok(Meta {
            src: prefetch.prefetch,
            include,
            dependencies,
            declared_dependencies: declared_dependencies(v),
            target_dependencies,
            build_dependencies,
            crate_file: crate_file(v),
            lib_name: lib_name(v),
            proc_macro: is_proc_macro(v),
            plugin: is_plugin(v),
            crate_type: crate_type(v),
            default_features,
            declared_features,
            use_default_features: None,
            features: BTreeSet::new(),
            build: build(v),
            implied_features: implied,
            bins: bins(v),
            authors,
            description,
            edition