pmeunier / carnix

Fixing a bug with optional dependencies, and typos in proc_macro

By blabla on May 8, 2019
signed by pmeunier.
6gv8hsejXs2L1iKJysZ2Anz4MLReLkm4C4mxbkxHNPmitSWSn8uEkzuDEL7yosY3yCiKMSx3D8ofokM9rTL1ZKam
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

89
90
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[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.10.0"
version = "0.10.1"
dependencies = [
In file Cargo.toml
1
2

3
4
[package]
name = "carnix"
version = "0.10.0"
version = "0.10.2"
authors = ["pe@pijul.org <pe@pijul.org>"]
In file src/cfg.rs
158
159
160
161
162
163
164
165
166
167
168
169
170
    }
}

#[test]
fn test_any() {
    let s = "cfg(any(unix, windows))";
    let x = cfg(s.as_bytes());
    if let IResult::Done(ref i, ref o) = x {
        println!("{:?}", o);
    } else {
        panic!("{:?}", x)
    }
}
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
    ) -> Result<(), Error> {
        let indent = std::iter::repeat(' ').take(n_indent).collect::<String>();
        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) {
            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 meta.dependencies.iter()
            .chain(meta.build_dependencies.iter())
            .chain(meta.target_dependencies.iter().flat_map(|&(_, ref y)| y.iter()))
            .filter(|&(_, dep)| dep.cr.found_in_lock)
        {
            for (_, dep) in deps.iter().filter(|&(_, dep)| dep.cr.found_in_lock) {
                debug!("outputting dep = {:?}", dep);
                let dep_name = format!(
                    "{}.\"${{deps.{}.\"{}\".{}}}\"",
            debug!("outputting dep = {:?}", dep);
            let dep_name = format!(
                "{}.\"${{deps.{}.\"{}\".{}}}\"",
                nix_name(&dep.cr.name),
                nix_name_,
                version,
                nix_name(&dep.cr.name),
            );
            let optional_dep_name = |feat, val| if dep.is_optional {
                Some(format!(
                    "(f: if deps.\"{}\".\"{}\" ? \"{}\" then recursiveUpdate f {{ {}.\"${{deps.\"{}\".\"{}\".\"{}\"}}\".\"{}\" = {}; }} else f)",
                    // if
                    nix_name_,
                    version,
                    nix_name(&dep.cr.name),
                    // then
                    nix_name(&dep.cr.name),
                    nix_name_,
                    version,
                    nix_name(&dep.cr.name),
                );
                for feat in dep.features.iter() {
                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());
                    e.push("true".to_string());
                    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());
                            let mut e = output_features.entry(dep_name).or_insert(Vec::new());
                            e.push(format!(
                                "({}.\"{}\".\"{}\" or false)",
                                nix_name_,
                                nix_name_,
                                version,
                                FeatName(&feat.feature)
                                FeatName(&feat.feature)
                                FeatName(&feat.feature)
                            ));
                            e.push(format!(
                                "(f.\"{}\".\"{}\".\"{}\" or false)",
                                nix_name_,
                                nix_name_,
                                version,
                                FeatName(&feat.feature)
                                FeatName(&feat.feature)
                                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);
                }
                    feat,
                    val,
                ))
            } else {
                None
            };
            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());
            }
        }
        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() {
        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 {
                        } else if current_attrs.len() > 1 {
                        } else if current_attrs.len() > 1 {
                        } else if current_attrs.len() > 1 {
                            writeln!(
                                w,
                                "{}  {} = fold recursiveUpdate {{}} [",
                                indent,
                                current_prefix.trim_end_matches('.')
                            )?;
                            for x in current_attrs.drain(..) {
                            for x in current_attrs.drain(..) {
                            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 !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 b.len() == 0 {
            if b.len() == 0 {
            } else if b.len() == 1 {
                if b[0] == "true" || a == &full_name_default {
                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" {
                } else if b[0] != "false" {
                } else if b[0] != "false" {
                } else if b[0] != "false" {
                } 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") {
                } else if a.ends_with(".default") {
                } else if a.ends_with(".default") {
                } else if a.ends_with(".default") {
                } else if a.ends_with(".default") {
                    // b[0] == false here
                    current_attrs.push(format!(
                        "{} = (f.{} or false);",
                        a.trim_start_matches(current_prefix),
                        a
                    ))
            if !dep.default_features {
                if default.get(&dep_name).is_none() {
                    default.insert(dep_name, (optional_dep_name("default", false), false));
                }
            } else {
                let mut x = format!(
                    "{} =\n{}      (f.{} or false)",
                    a.trim_start_matches(current_prefix),
                    indent,
                    a
                );
                for bb in b.iter() {
                for bb in b.iter() {
                for bb in b.iter() {
                for bb in b.iter() {
                for bb in b.iter() {
                    x.push_str(&format!(" ||\n{}      {}", indent, bb));
                }
                }
                x.push_str(&format!(";"));
                current_attrs.push(x)
                current_attrs.push(x)
                default.insert(dep_name, (optional_dep_name("default", true), true));
            }
        }
        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 {
            } else if current_attrs.len() > 1 {
            } else if current_attrs.len() > 1 {
            } else if current_attrs.len() > 1 {
                writeln!(
                    w,
                    "{}  {} = fold recursiveUpdate {{}} [",
                    indent,
                    current_prefix.trim_end_matches('.')
                )?;
                for x in current_attrs.drain(..) {
                for x in current_attrs.drain(..) {
                for x in current_attrs.drain(..) {
                    writeln!(w, "{}    {{ {} }}", indent, x)?;
                }
                }
                writeln!(w, "{}  ];", indent)?;
        for (dep_name, (optional, default)) in default.iter() {
            if optional.is_none() {
                // We'll take care of optional dependencies later.
                let dep = format!("{}.default", dep_name);
                let mut e = output_features.entry(dep).or_insert(Vec::new());
                e.push(format!("{}", *default));
            }
        }

        output_self_features(
            &mut w,
            &indent,
            &output_features,
            &full_name_default
        )?;

        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)
            {

        for (_, (optional, _)) in default.iter() {
            if let Some(ref opt) = optional {
                // We'll take care of optional dependencies later.
                write!(w, "\n{}  {}", indent, opt)?;
            }
        }

        for (_, dep) in meta.dependencies.iter()
            .chain(meta.build_dependencies.iter())
            .chain(meta.target_dependencies.iter().flat_map(|&(_, ref y)| y.iter()))
            .filter(|&(_, c)| c.cr.found_in_lock && !c.cr.name.is_empty()) {

                at_least_one = true;
                write!(
                    w,
                    "\n{}  ({}features_.{}.\"${{deps.\"{}\".\"{}\".\"{}\"}}\" deps)",
                    "\n{}  (if deps.\"{}\".\"{}\" ? \"{}\" then {}features_.{}.\"${{deps.\"{}\".\"{}\".\"{}\" or \"\"}}\" deps else {{}})",
                    indent,

                    nix_name_,
                    version,
                    nix_name(&dep.cr.name),

                    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!(w, "{}  description = \"{}\";", indent, descr.replace("\"", "\\\\\\\""))?;
        }
        if let Some(ref home) = meta.homepage {
            writeln!(w, "{}  homepage = {};", indent, home)?;
        }
        writeln!(
            w,
            "{}  authors = [ {} ];",
            indent,
            meta.authors.iter().map(|s| format!("\"{}\"", s)).join(" ")
        )?;

        if let Some(ref edition) = meta.edition {
            writeln!(w, "{}  edition = {};", indent, edition)?;
        }

        match meta.src {
            Src::Crate { ref sha256 } => {
                writeln!(w, "{}  sha256 = \"{}\";", indent, sha256)?;
            }
            Src::Path {
                ref path,
                ref workspace_member,
            } => {
                debug!("path = {:?}", path);
                let path_canon = path.canonicalize()?;
                let path = if let Ok(path) = path_canon.strip_prefix(root_prefix) {
                    path
                } else {
                    &path
                };
                let workspace_member = workspace_member.as_ref().map(|x| {
                    if let Ok(ws) = x.strip_prefix(root_prefix) {
                        ws
                    } else {
                        &x
                    }
                });
                let s = path.to_string_lossy();

                let mut filter_source = String::new();
                debug!("fsmeta {:?}", path);
                if let Ok(fsmeta) = std::fs::metadata(&path_canon) {
                    debug!("fsmeta = {:?}", fsmeta);
                    if fsmeta.is_dir() {
                        if let Some(ref include) = meta.include {
                            filter_source.push_str("include [ ");
                            for file in include.iter() {
                                filter_source.push_str("\"");
                                filter_source.push_str(file);
                                filter_source.push_str("\"");
                                filter_source.push_str(" ");
                            }
                            filter_source.push_str("] ");
                        } else if let Some(ref ws) = workspace_member {
                            filter_source.push_str("include [ \"Cargo.toml\" \" ");
                            filter_source.push_str(&ws.to_string_lossy());
                            filter_source.push_str("\" ] ");
                        } else {
                            filter_source.push_str("exclude [ \".git\" \"target\" ] ");
                        }
                    }
                }
                if s.is_empty() {
                    filter_source.push_str("./.");
                } else {
                    if !s.contains("/") {
                        filter_source.push_str("./");
                    }
                    filter_source.push_str(&path.to_string_lossy());
                }

                writeln!(w, "{}  src = {};", indent, filter_source)?;

                if let Some(ref ws) = workspace_member {
                    writeln!(
                        w,
                        "{}  workspace_member = \"{}\";",
                        indent,
                        ws.to_string_lossy()
                    )?;
                }
            }
            Src::Git(ref git) => {
                writeln!(w, "{}  src = fetchgit {{", indent)?;
                writeln!(w, "{}     url = {:?};", indent, git.url)?;
                writeln!(w, "{}     rev = {:?};", indent, git.rev)?;
                writeln!(w, "{}     sha256 = {:?};", indent, git.sha256)?;
                if !git.fetch_submodules {
                    writeln!(w, "{}     fetchSubmodules = false;", indent)?;
                }
                writeln!(w, "{}  }};", indent)?;
            }
        }
        if meta.crate_file.len() > 0 {
            writeln!(w, "{}  libPath = \"{}\";", indent, meta.crate_file)?;
        }
        if meta.lib_name.len() > 0 && meta.lib_name != self.name {
            writeln!(w, "{}  libName = \"{}\";", indent, meta.lib_name)?;
        }
        if meta.proc_macro {
            writeln!(w, "{}  procMacro = {};", indent, meta.proc_macro)?;
        }
        if meta.plugin {
            writeln!(w, "{}  plugin = {};", indent, meta.plugin)?;
        }
        if !meta.crate_type.is_empty() {
            write!(w, "{}  type = [ ", indent)?;
            for t in &meta.crate_type {
                write!(w, "{} ", t)?;
            }
            writeln!(w, "];")?;
        }
        if meta.bins.len() > 0 {
            writeln!(w, "{}  crateBin =", indent)?;
            for (i, bin) in meta.bins.iter().enumerate() {
                if i != 0 {
                    write!(w, " ++\n")?;
                }
                if bin.required_features.is_empty() {
                    write!(w, "{}    [{{ ", indent)?;
                } else {
                    write!(w, "{}    (if ", indent)?;
                    for (i, r) in bin.required_features.iter().enumerate() {
                        if i != 0 {
                            write!(w, "&& ")?;
                        }
                        write!(w, "features.\"{}\".\"{}\".\"{}\" ", nix_name_, version, r)?;
                    }
                    write!(w, "then [{{ ")?;
                }
                if let Some(ref name) = bin.name {
                    write!(w, " name = \"{}\"; ", name)?;
                }
                if let Some(ref path) = bin.path {
                    write!(w, " path = \"{}\"; ", path)?;
                }
                if bin.required_features.is_empty() {
                    write!(w, "}}]")?;
                } else {
                    write!(w, "}} ] else [])")?;
                }
            }
            writeln!(w, ";")?;
        }
        if meta.build.len() > 0 {
            writeln!(w, "{}  build = \"{}\";", indent, meta.build)?;
        }

        let mut is_first = true;
        let mut has_feature_deps = false;
        if !meta.dependencies.is_empty() {
            is_first = false;
            write!(w, "{}  dependencies =", indent)?;
            has_feature_deps |= print_deps(
                &mut w,
                &indent,
                &nix_name_,
                &version,
                prefix,
                meta.dependencies
                    .iter()
                    .filter(|&(_, c)| {
                        c.cr.found_in_lock
                            && c.cr.name.len() > 0
                            && all_packages.contains(&c.cr.name)
                    })
                    .map(|x| x.1),
            )?;
        }
        if !meta.target_dependencies.is_empty() {
            for &(ref target, ref dep) in meta.target_dependencies.iter() {
                if is_first {
                    write!(w, "{}  dependencies = (", indent)?;
                } else {
                    write!(w, "\n{}    ++ (", indent)?;
                }
                debug!("target = {:?}", target);
                let parsed = cfg::parse_target(target)?;
                write!(w, "if ")?;
                cfg::to_nix(&mut w, &parsed)?;
                write!(w, " then")?;
                has_feature_deps |= print_deps(
                    &mut w,
                    &indent,
                    &nix_name_,
                    &version,
                    prefix,
                    dep.iter()
                        .filter(|&(_, c)| {
                            c.cr.found_in_lock
                                && c.cr.name.len() > 0
                                && all_packages.contains(&c.cr.name)
                        })
                        .map(|x| x.1),
                )?;
                write!(w, " else [])")?;
                is_first = false;
            }
        }
        if !meta.dependencies.is_empty() || !meta.target_dependencies.is_empty() {
            writeln!(w, ";")?;
        }

        if !meta.build_dependencies.is_empty() {
            write!(w, "\n{}  buildDependencies =", indent)?;
            print_deps(
                &mut w,
                &indent,
                &nix_name_,
                &version,
                prefix,
                meta.build_dependencies
                    .iter()
                    .filter(|&(_, c)| {
                        c.cr.found_in_lock
                            && c.cr.name.len() > 0
                            && all_packages.contains(&c.cr.name)
                    })
                    .map(|x| x.1),
            )?;
            writeln!(w, ";")?;
        }
        if !meta.declared_features.is_empty() || has_feature_deps {
            write!(
                w,
                "{}  features = mkFeatures (features.\"{}\".\"{}\" or {{}});\n",
                indent, nix_name_, version
            )?;
        }
        writeln!(w, "{}}};", indent)?;

        self.output_package_features(&mut w, n_indent, meta, prefix)?;
        writeln!(w, "# end")?;
        writeln!(w, "")?;
        Ok(())
    }
}

fn output_current_prefix<W:Write>(w: &mut W, indent: &str, current_prefix: &mut &str, current_attrs: &mut Vec<String>) -> Result<(), Error> {
    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)?;
        }
    }
    Ok(())
}

fn output_self_features<W:Write>(w: &mut W, indent: &str, output_features: &BTreeMap<String, Vec<String>>, full_name_default: &str) -> Result<(), Error> {

    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
                output_current_prefix(w, &indent, &mut current_prefix, &mut current_attrs)?;
                // 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)
        }
    }
    output_current_prefix(w, &indent, &mut current_prefix, &mut current_attrs)?;
    Ok(())
}



fn print_deps<'a, W: Write, I: Iterator<Item = &'a Dep>>(
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
        let description = v
            .get("package")
            .and_then(|p| p.get("description").map(|s| s.to_string()));
            .and_then(|p| p.get("description").and_then(|s| s.as_str().map(|s| s.to_string())));
        let homepage = v
            .get("package")
            .and_then(|p| p.get("homepage").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,
            homepage,
            edition,
        })
    }

    fn prefetch_path(&self, cache: &mut Cache) -> Result<Prefetch, Error> {
        debug!("prefetch {:?}", self);
        let version = if self.subpatch.len() > 0 {
            format!(
                "{}.{}.{}{}",
                self.major, self.minor, self.patch, self.subpatch
            )
        } else {
            format!("{}.{}.{}", self.major, self.minor, self.patch)
        };
        let url = format!(
            "https://crates.io/api/v1/crates/{}/{}/download",
            self.name, version
        );

        let from_cache = cache.get(&url);
        if let Some(ref prefetch) = from_cache {
            if std::fs::metadata(&prefetch.path).is_ok() {
                return Ok(prefetch.clone());
            }
        }

        println!("Prefetching {}-{}", self.name, version);
        debug!("url = {:?}", url);
        let prefetch = Command::new("nix-prefetch-url")
            .args(
                &[
                    &url,
                    "--unpack",
                    "--name",
                    &(self.name.clone() + "-" + &version),
                ][..],
            )
            .output()?;

        let sha256: String = from_utf8(&prefetch.stdout).unwrap().trim().to_string();
        if let Ok(path) = get_path(&prefetch.stderr) {
            let pre = Prefetch {
                prefetch: Src::Crate { sha256 },
                path: Path::new(path).to_path_buf(),
            };
            if from_cache.is_none() {
                cache.insert(&url, pre.clone());
            }
            Ok(pre)
        } else {
            if prefetch.stderr.ends_with(b"HTTP error 404\n") {
                Err(CarnixError::Prefetch404(self.clone()).into())
            } else {
                Err(CarnixError::PrefetchFailed(self.clone()).into())
            }
        }
    }

    fn prefetch_git(&self, url: &str, rev: &str, cache: &mut Cache) -> Result<Prefetch, Error> {
        let cached_url = format!("git+{}#{}", url, rev);
        let from_cache = cache.get(&cached_url);
        if let Some(ref prefetch) = from_cache {
            if std::fs::metadata(&prefetch.path).is_ok() {
                return Ok(prefetch.clone());
            }
        }

        println!("Prefetching {} ({})", self.name, cached_url);
        debug!("cached_url = {:?}", cached_url);
        let prefetch = Command::new("nix-prefetch-git")
            .args(&["--url", url, "--rev", rev])
            .output();
        let prefetch = match prefetch {
            Ok(p) => Ok(p),
            Err(_) => Command::new("nix-shell")
                .args(&[
                    "-p",
                    "nix-prefetch-git",
                    "--run",
                    &format!("nix-prefetch-git --url {} --rev {}", url, rev),
                ])
                .output(),
        };

        match prefetch {
            Err(e) => {
                error!("error with nix-prefetch-git: {}", e);
                Err(e.into())
            }
            Ok(prefetch) => {
                if prefetch.status.success() {
                    let prefetch_json: GitFetch =
                        serde_json::from_str(from_utf8(&prefetch.stdout).unwrap()).unwrap();
                    let path = get_path(&prefetch.stderr)?;

                    let pre = Prefetch {
                        prefetch: Src::Git(prefetch_json),
                        path: Path::new(path).to_path_buf(),
                    };
                    if from_cache.is_none() {
                        cache.insert(&cached_url, pre.clone());
                    }
                    Ok(pre)
                } else {
                    error!(
                        "nix-prefetch-git exited with error code {:?}:\n{}",
                        prefetch.status,
                        std::str::from_utf8(&prefetch.stderr).unwrap_or("")
                    );
                    Err(CarnixError::NixPrefetchGitFailed.into())
                }
            }
        }
    }
}

fn include(v: &toml::map::Map<String, toml::Value>) -> Option<Vec<String>> {
    if let Some(inc) = v.get("package") {
        if let Some(inc) = inc.as_table() {
            if let Some(inc) = inc.get("include") {
                if let Some(inc) = inc.as_array() {
                    return Some(
                        inc.into_iter()
                            .filter_map(|x| x.as_str().map(|x| x.to_string()))
                            .collect(),
                    );
                }
            }
        }
    }
    None
}

fn crate_file(v: &toml::map::Map<String, toml::Value>) -> String {
    if let Some(crate_file) = v.get("lib") {
        let crate_file = crate_file.as_table().unwrap();
        if let Some(lib_path) = crate_file.get("path") {
            lib_path.as_str().unwrap().to_string()
        } else {
            String::new()
        }
    } else {
        String::new()
    }
}

fn crate_type(v: &toml::map::Map<String, toml::Value>) -> Vec<String> {
    if let Some(crate_file) = v.get("lib") {
        if let Some(crate_file) = crate_file.as_table() {
            if let Some(crate_type) = crate_file.get("crate-type") {
                debug!("crate_type = {:?}", crate_type);
                if let Some(s) = crate_type.as_str() {
                    return vec![s.to_string()];
                } else if let Some(s) = crate_type.as_array() {
                    return s.into_iter().map(|x| x.to_string()).collect();
                }
            }
        }
    }
    Vec::new()
}

fn lib_name(v: &toml::map::Map<String, toml::Value>) -> String {
    if let Some(crate_file) = v.get("lib") {
        if let Some(name) = crate_file.get("name") {
            name.as_str().unwrap().to_string()
        } else {
            String::new()
        }
    } else {
        String::new()
    }
}

fn bins(v: &mut toml::map::Map<String, toml::Value>) -> Vec<Bin> {
    if let Some(toml::Value::Array(bins)) = v.remove("bin") {
        bins.into_iter()
            .map(|mut x| {
                let bin = x.as_table_mut().unwrap();
                Bin {
                    name: if let Some(toml::Value::String(s)) = bin.remove("name") {
                        Some(s)
                    } else {
                        None
                    },
                    path: if let Some(toml::Value::String(s)) = bin.remove("path") {
                        Some(s)
                    } else {
                        None
                    },
                    required_features: if let Some(toml::Value::Array(s)) =
                        bin.remove("required-features")
                    {
                        let mut v = Vec::new();
                        for s in s {
                            if let toml::Value::String(s) = s {
                                v.push(s)
                            }
                        }
                        v
                    } else {
                        Vec::new()
                    },
                }
            })
            .collect()
    } else {
        Vec::new()
    }
}

fn is_proc_macro(v: &toml::map::Map<String, toml::Value>) -> bool {
    debug!("is_proc_macro: {:?}", v);
    if let Some(crate_file) = v.get("lib") {
        debug!("is_proc_macro: {:?}", crate_file);
        if let Some(&toml::Value::Boolean(proc_macro)) = crate_file.get("proc-macro") {
            proc_macro
        } else if let Some(&toml::Value::Boolean(proc_macro)) = crate_file.get("proc_macro") {
            proc_macro
        } else {