pmeunier / carnix

Formatting + patch.* in cargo.toml

By blabla on April 9, 2019
signed by pmeunier.
B1Twot1nC9Hv51nFvpFiRrZjcms2RGh8YzLaiMPykFTSURzh9TUxRnCXKi91bVapgvEY9Mm5HYSQciBQ3dnmKTif
This patch is in the following branches:
master
In file src/cache.rs
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
use failure::Error;
use krate::Src;
use std;
use std::collections::BTreeMap;
use std::io::{Read, Write};
use failure::Error;
use std::path::Path;
use std::path::PathBuf;

#[derive(Debug, Clone)]
pub struct Prefetch {
    pub prefetch: Src,
    pub path: PathBuf,
}

#[derive(Debug)]
pub struct Cache {
    path: PathBuf,
    cache: String,
    lines: Vec<(usize, usize)>,
    new: BTreeMap<String, Prefetch>,
}

impl Drop for Cache {
    fn drop(&mut self) {
        std::fs::create_dir_all(self.path.parent().unwrap()).unwrap();
        let mut path2 = self.path.clone();
        path2.set_extension("tmp");
        let mut f = std::fs::File::create(&path2).unwrap();
        let mut new_it = self.new.iter().peekable();
        let mut ex_it = self.lines.iter().peekable();
        loop {
            let advance_new = if let Some((a, b)) = new_it.peek() {
                if let Some((c, d)) = ex_it.peek() {
                    let (u, v, w) = self.get_index(*c, *d).unwrap();
                    if u < a {
                        writeln!(f, "{} {} {}", u, v, w).unwrap();
                        false
                    } else {
                        if let Src::Crate { ref sha256 } = b.prefetch {
                            writeln!(f, "{} {} {}", a, sha256, b.path.to_string_lossy()).unwrap();
                        }
                        true
                    }
                } else {
                    if let Src::Crate { ref sha256 } = b.prefetch {
                        writeln!(f, "{} {} {}", a, sha256, b.path.to_string_lossy()).unwrap();
                    }
                    true
                }
            } else {
                for &(l0, l1) in ex_it {
                    let (u, v, w) = self.get_index(l0, l1).unwrap();
                    writeln!(f, "{} {} {}", u, v, w).unwrap();
                }
                break
                break;
            };
            if advance_new {
                new_it.next();
            } else {
                ex_it.next();
            }
        }
        std::fs::rename(&path2, &self.path).unwrap();
    }
}

impl Cache {
    pub fn new<P:AsRef<Path>>(path: P) -> Result<Self, Error> {
    pub fn new<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
        let path = path.as_ref();
        let mut cache = String::new();
        if let Ok(mut f) = std::fs::File::open(path) {
            f.read_to_string(&mut cache)?;
        }
        let mut lines = Vec::new();
        for l in cache.lines() {
            if lines.is_empty() {
                lines.reserve(2 * cache.len() / l.len());
            }
            let l0 = l.as_ptr() as usize - cache.as_ptr() as usize;
            lines.push((l0, l0 + l.len()))
        }
        Ok(Cache {
            path: path.to_path_buf(),
            cache,
            lines,
            new: BTreeMap::new(),
        })
    }

    fn get_index(&self, l0: usize, l1: usize) -> Option<(&str, &str, &str)> {
        let a = self.cache.get(l0..l1).unwrap();
        let mut it = a.split(' ');
        if let (Some(u), Some(v), Some(w)) = (it.next(), it.next(), it.next()) {
            Some((u, v, w))
        } else {
            None
        }
    }

    pub fn get(&mut self, url: &str) -> Option<Prefetch> {
        debug!("cache get {:?}", url);
        if let Some(pre) = self.new.get(url) {
            Some(pre.clone())
        } else {
            let n = match self.lines.binary_search_by(|&(a, b)| {
                let url0 = self.cache.get(a..b).unwrap();
                debug!("{:?} {:?}", url, url0);
                if url0.starts_with(url) {
                    std::cmp::Ordering::Equal
                } else {
                    url0.cmp(url)
                }
            }) {
                Ok(n) => n,
                _ => return None
                _ => return None,
            };
            debug!("n = {:?}", n);
            let (l0, l1) = self.lines[n];
            self.get_index(l0, l1).map(|(_, b, c)| {
                Prefetch {
                    prefetch: Src::Crate { sha256: b.to_string() },
                    path: Path::new(c).to_path_buf(),
                }
            self.get_index(l0, l1).map(|(_, b, c)| Prefetch {
                prefetch: Src::Crate {
                    sha256: b.to_string(),
                },
                path: Path::new(c).to_path_buf(),
            })
12
13
14
15
16
17



18


19
20
21
22
23
24
25
26
27
28


29
30
31
32
33
extern crate serde_derive;
extern crate dirs;
extern crate failure;
extern crate serde_json;
extern crate tempdir;
extern crate toml;
extern crate dirs;
use std::io::BufWriter;
use std::io::BufWriter;
extern crate url;
extern crate failure;
#[macro_use] extern crate failure_derive;
#[macro_use]
extern crate failure_derive;

use clap::{App, Arg, SubCommand};
use std::io::BufWriter;
use std::process::Command;

mod error;
pub use error::*;
mod cache;
mod prefetch;
mod krate;
mod cfg;
mod krate;
mod output;
mod prefetch;

In file src/cfg.rs
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
use failure::Error;
use CarnixError;
use std::str::from_utf8;
use std::str::from_utf8;
use nom::IResult;
use std::io::Write;
use std::str::from_utf8;
use CarnixError;

#[derive(Debug, Clone, Copy)]
pub enum CfgOp {
    All,
    Any,
}

#[derive(Debug)]
pub enum Cfg {
    Op {
        op: CfgOp,
        operands: Vec<Cfg>
    },
    Op { op: CfgOp, operands: Vec<Cfg> },
    Not(Vec<Cfg>),
    Cfg(String),
    Equal(String, String)
    Equal(String, String),
}

pub fn parse_target(target: &str) -> Result<Vec<Cfg>, Error> {
    debug!("{:?}", target);
    match cfg(target.as_bytes()) {
        IResult::Done(i, o) => {
            debug!("i = {:?}", i);
            Ok(o)
        }
        IResult::Error(e) => panic!("error {:?}", e),
        IResult::Incomplete(n) => panic!("incomplete {:?}", n)
        IResult::Incomplete(n) => panic!("incomplete {:?}", n),
    }
}

pub fn to_nix(w: &mut Write, target: &[Cfg]) -> Result<(), Error> {
    to_nix_op(w, CfgOp::Any, target)
}


fn to_nix_op(w: &mut Write, op: CfgOp, target: &[Cfg]) -> Result<(), Error> {
    let mut is_first = true;
    for cfg in target {
        if !is_first {
            match op {
                CfgOp::All => write!(w, " && ")?,
                CfgOp::Any => write!(w, " || ")?,
            }
        }
        is_first = false;
        match *cfg {
            Cfg::Op { op, ref operands } => to_nix_op(w, op, operands)?,
            Cfg::Not(ref cfg) => {
                write!(w, "!(")?;
                to_nix_op(w, CfgOp::All, cfg)?;
                write!(w, ")")?;
            }
            Cfg::Equal(ref key, ref value) => {
                match key.as_str() {
                    "target_os" => cfg_value(w, "kernel", value)?,
                    "target_env" => cfg_value(w, "abi", value)?,
                    "target_arch" => cfg_value(w, "cpu", value)?,
                    _ => return Err(CarnixError::CouldNotTranslateTarget.into())
                }
                }
            Cfg::Equal(ref key, ref value) => match key.as_str() {
                "target_os" => cfg_value(w, "kernel", value)?,
                "target_env" => cfg_value(w, "abi", value)?,
                "target_arch" => cfg_value(w, "cpu", value)?,
                _ => return Err(CarnixError::CouldNotTranslateTarget.into()),
            },
            Cfg::Cfg(ref value) => cfg_value(w, "kernel", value)?,
        }
    }
    Ok(())
}

fn cfg_value(w: &mut Write, key: &str, value: &str) -> Result<(), Error> {
    match value {
        "macos" => write!(w, "{} == \"darwin\"", key)?,
        "unix" => write!(w, "({} == \"linux\" || {} == \"darwin\")", key, key)?,
        other => write!(w, "{} == \"{}\"", key, other)?,
    }
    Ok(())
}

named!(parens<Cfg>, ws!(delimited!(tag!("("), expr, tag!(")"))));
named!(
    parens_many<Vec<Cfg>>,
    ws!(delimited!(tag!("("), exprs, tag!(")")))
);
named!(
    not<Cfg>,
    ws!(do_parse!(
        op: tag!("not") >> operands: parens >> (Cfg::Not(vec![operands]))
    ))
);

named!(
    all<Cfg>,
    ws!(do_parse!(
        op: tag!("all")
            >> operands: parens_many
            >> (Cfg::Op {
                op: CfgOp::All,
                operands
            })
    ))
);

named!(parens<Cfg>, ws!(delimited!( tag!("("), expr, tag!(")"))));
named!(parens_many<Vec<Cfg>>, ws!(delimited!(tag!("("), exprs, tag!(")"))));
named!(not<Cfg>, ws!(do_parse!(
    op: tag!("not") >> operands: parens >> (Cfg::Not(vec![operands]))
)));
named!(
    any<Cfg>,
    ws!(do_parse!(
        op: tag!("any")
            >> operands: parens_many
            >> (Cfg::Op {
                op: CfgOp::Any,
                operands
            })
    ))
);

named!(all<Cfg>, ws!(do_parse!(
    op: tag!("all") >> operands: parens_many >> (Cfg::Op { op: CfgOp::All, operands })
)));
named!(expr<Cfg>, alt!(not | all | any | equal | simple));

named!(any<Cfg>, ws!(do_parse!(
    op: tag!("any") >> operands: parens_many >> (Cfg::Op { op: CfgOp::Any, operands })
)));
named!(
    simple<Cfg>,
    map!(ident, |a| Cfg::Cfg(from_utf8(a).unwrap().to_string()))
);
named!(
    equal<Cfg>,
    ws!(do_parse!(
        k: ident
            >> eq: tag!("=")
            >> v: delimited!(tag!("\""), take_till!(|c| c == b'"'), tag!("\""))
            >> (Cfg::Equal(
                from_utf8(k).unwrap().to_string(),
                from_utf8(v).unwrap().to_string()
            ))
    ))
);

named!(expr<Cfg>, alt!(
    not | all | any | equal | simple
));
named!(
    ident<&[u8]>,
    take_while1_s!(|c| (c >= b'a' && c <= b'z')
        || (c >= b'A' && c <= b'Z')
        || (c >= b'0' && c <= b'9')
        || c == b'_'
        || c == b'-')
);

named!(simple<Cfg>, map!(ident, |a| Cfg::Cfg(from_utf8(a).unwrap().to_string())));
named!(equal<Cfg>, ws!(do_parse!(
    k: ident >>
        eq: tag!("=") >>
        v: delimited!(tag!("\""), take_till!(|c| c == b'"'), tag!("\"")) >>
        (Cfg::Equal(from_utf8(k).unwrap().to_string(),
                    from_utf8(v).unwrap().to_string()))
)));

named!(ident<&[u8]>, take_while1_s!(|c| (c >= b'a' && c <= b'z') || (c >= b'A' && c <= b'Z') || (c >= b'0' && c <= b'9') || c == b'_' || c == b'-'));

named!(exprs<Vec<Cfg>>, ws!(separated_list!(tag!(","), expr)));

named!(cfg<Vec<Cfg>>, ws!(alt!(
    do_parse!(op: tag!("cfg") >> operands: parens_many >> (operands)) | map!(simple, |x| vec![x])
)));
named!(
    cfg<Vec<Cfg>>,
    ws!(alt!(
        do_parse!(op: tag!("cfg") >> operands: parens_many >> (operands))
            | map!(simple, |x| vec![x])
    ))
);

In file src/error.rs
7
8

9
10
11
12
13
14
15
16
17
18

19
20
    #[fail(display = "Prefetch returned nothing")]
    PrefetchReturnedNothing,
    #[fail(display = "Prefetching {} returned HTTP error 404. Did you forget to specify `--src`?", _0)]
    #[fail(
        display = "Prefetching {} returned HTTP error 404. Did you forget to specify `--src`?",
        _0
    )]
    Prefetch404(krate::Crate),
    #[fail(display = "Prefetching {} failed", _0)]
    PrefetchFailed(krate::Crate),
    #[fail(display = "Cargo.lock could not be found")]
    NoCargoLock,
    #[fail(display = "nix-prefetch-git failed")]
    NixPrefetchGitFailed
    NixPrefetchGitFailed,
}
In file src/krate.rs
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
use failure::Error;
use regex::Regex;
use std;
use std::collections::{BTreeMap, BTreeSet};
use toml;
use std::path::{Path, PathBuf};
use regex::Regex;
use std;
use failure::Error;
use toml;
use CarnixError;

#[derive(Debug, Clone, PartialEq, Eq, Default, PartialOrd, Ord)]
pub struct Crate {
    pub name: String,
    pub major: usize,
    pub minor: usize,
    pub patch: usize,
    pub subpatch: String,
    pub found_in_lock: bool,
}

#[derive(Debug, PartialEq, Eq)]
pub struct Meta {
    pub src: Src,
    pub include: Option<Vec<String>>,
    pub dependencies: BTreeMap<String, Dep>,
    pub declared_dependencies: BTreeSet<String>,
    pub target_dependencies: Vec<(String, BTreeMap<String, Dep>)>,
    pub build_dependencies: BTreeMap<String, Dep>,
    pub crate_file: String,
    pub lib_name: String,
    pub proc_macro: bool,
    pub plugin: bool,
    pub crate_type: Vec<String>,
    pub default_features: Vec<String>,
    pub declared_features: BTreeSet<String>,
    pub use_default_features: Option<bool>,
    pub build: String,
    pub features: BTreeSet<String>,
    pub implied_features: Vec<ConditionalFeature>,
    pub bins: Vec<Bin>,
    pub authors: Vec<String>,
    pub description: Option<String>,
    pub homepage: Option<String>,
    pub edition: Option<String>,
}

#[derive(Debug, PartialEq, Eq, Default, Clone)]
pub struct Dep {
    pub cr: Crate,
    pub from_crates_io: bool,
    pub is_optional: bool,
    pub path: Option<PathBuf>,
    pub features: Vec<String>,
    pub default_features: bool,
    pub conditional_features: Vec<ConditionalFeature>,
}

#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub enum Src {
    Crate { sha256: String },
    Path { path: PathBuf, workspace_member: Option<PathBuf> },
    Crate {
        sha256: String,
    },
    Path {
        path: PathBuf,
        workspace_member: Option<PathBuf>,
    },
    Git(GitFetch),
}

#[derive(Debug, PartialEq, Eq)]
pub enum SourceType {
    CratesIO,
    None,
    Git { url: String, rev: String },
    Path { path: PathBuf, workspace_member: Option<PathBuf> }
    Git {
        url: String,
        rev: String,
    },
    Path {
        path: PathBuf,
        workspace_member: Option<PathBuf>,
    },
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct ConditionalFeature {
    pub feature: String,
    pub dep_feature: String,
}

#[derive(Debug, PartialEq, Eq)]
pub struct Bin {
    pub path: Option<String>,
    pub name: Option<String>,
    pub required_features: Vec<String>,
}

use std::str::FromStr;
impl FromStr for Crate {
    type Err = ();
    fn from_str(s: &str) -> Result<Crate, Self::Err> {
        debug!("parsing {:?}", s);
        let re = Regex::new(r"(\S*)-(\d*)\.(\d*)\.(\d*)([\+\-]\S*)?").unwrap();
        let cap = re.captures(s).unwrap();
        debug!("cap = {:?}", cap);
        Ok(Crate {
            name: cap.get(1).unwrap().as_str().to_string(),
            major: cap.get(2).unwrap().as_str().parse().unwrap(),
            minor: cap.get(3).unwrap().as_str().parse().unwrap(),
            patch: cap.get(4).unwrap().as_str().parse().unwrap(),
            subpatch: cap.get(5).map(|x| x.as_str().to_string()).unwrap_or(String::new()),
            subpatch: cap
                .get(5)
                .map(|x| x.as_str().to_string())
                .unwrap_or(String::new()),
            found_in_lock: true,
        })
    }
}

impl std::fmt::Display for Crate {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        write!(fmt, "{}-{}.{}.{}{}", self.name, self.major, self.minor, self.patch, self.subpatch)?;
        write!(
            fmt,
            "{}-{}.{}.{}{}",
            self.name, self.major, self.minor, self.patch, self.subpatch
        )?;
        Ok(())
    }
}

pub fn nix_name(name: &str) -> String {
    name.chars().map(|c| match c {
        '-' => '_',
        '.' => '_',
        c => c
    }).collect()
    name.chars()
        .map(|c| match c {
            '-' => '_',
            '.' => '_',
            c => c,
        })
        .collect()
}


#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GitFetch {
    pub url: String,
    pub rev: String,
    pub date: String,
    pub sha256: String,
    #[serde(rename = "fetchSubmodules")]
    pub fetch_submodules: bool
    pub fetch_submodules: bool,
}

fn make_deps(base_path: &Path, deps: &toml::Value) -> BTreeMap<String, Dep> {
pub fn make_deps(base_path: &Path, deps: &toml::Value) -> BTreeMap<String, Dep> {
    let mut dependencies = BTreeMap::new();
    for (name, dep) in deps.as_table().unwrap() {
        debug!("name={:?}, dep={:?}", name, dep);
        if let Some(dep) = dep.as_table() {
            let name = name.to_string();
            let enabled_features = if let Some(features) = dep.get("features") {
                features
                    .as_array().unwrap()
                    .as_array()
                    .unwrap()
                    .into_iter()
                    .map(|x| x.as_str().unwrap().to_string())
                    .collect()
            } else {
                Vec::new()
            };
            let path = if let Some(path) = dep.get("path") {
                Some(path.as_str().unwrap().to_string())
            } else {
                None
            };
            let mut dep = Dep {
                cr: Crate::default(),
                from_crates_io: false,
                path: if let Some(path) = path {
                    Some(base_path.join(path))
                } else {
                    None
                },
                is_optional: dep.get("optional").map(|x| x.as_bool().unwrap()).unwrap_or(false),
                is_optional: dep
                    .get("optional")
                    .map(|x| x.as_bool().unwrap())
                    .unwrap_or(false),
                features: enabled_features,
                default_features: dep.get("default-features").map(|x| x.as_bool().unwrap()).unwrap_or(true),
                default_features: dep
                    .get("default-features")
                    .map(|x| x.as_bool().unwrap())
                    .unwrap_or(true),
                conditional_features: Vec::new(),
            };
            dep.cr.name.push_str(&name);
            dependencies.insert(name, dep);
        } else if dep.as_str().is_some() {
            let name = name.to_string();
            let mut dep = Dep {
                cr: Crate::default(),
                from_crates_io: false,
                path: None,
                features: Vec::new(),
                is_optional: false,
                default_features: true,
                conditional_features: Vec::new(),
            };
            dep.cr.name.push_str(&name);
            dependencies.insert(name, dep);
        }
    }
    dependencies
}

pub fn make_dependencies(base_path: &Path, deps: Option<&toml::Value>, features: Option<&toml::Value>) -> (BTreeMap<String, Dep>, Vec<ConditionalFeature>) {
pub fn make_dependencies(
    base_path: &Path,
    deps: Option<&toml::Value>,
    features: Option<&toml::Value>,
) -> (BTreeMap<String, Dep>, Vec<ConditionalFeature>) {
    let mut dependencies = BTreeMap::new();
    let mut cond = Vec::new();
    if let Some(deps) = deps {
        dependencies = make_deps(base_path, deps)
    }

    if let Some(features) = features {
        for (a, b) in features.as_table().unwrap().iter() {
            // println!("a {:?}, b {:?}", a, b);
            for b in b.as_array().unwrap() {
                if let Some(b) = b.as_str() {
                    let mut b = b.split('/');
                    match (b.next(), b.next()) {
                        (Some(c), Some(d)) => {
                            if let Some(dep) = dependencies.get_mut(c) {
                                debug!("conditional: {:?} {:?} {:?}", c, a, d);
                                dep.conditional_features.push(ConditionalFeature {
                                    feature: a.to_string(),
                                    dep_feature: d.to_string()
                                    dep_feature: d.to_string(),
                                })
                            }
                        }
                        (Some(c), None) => {
                            // println!("conditional: {:?} {:?} {:?}", c, a, d);
                            cond.push(ConditionalFeature {
                                feature: a.to_string(),
                                dep_feature: c.to_string()
                                dep_feature: c.to_string(),
                            })
                        }
                        _ => {}
                    }
                }
            }
        }
    }

    (dependencies, cond)
}


pub fn find_cargo_lock() -> Result<PathBuf, Error> {
    let mut current = std::env::current_dir()?;
    loop {
        current.push("Cargo.lock");
        debug!("current = {:?}", current);
        if std::fs::metadata(&current).is_ok() {
            return Ok(current)
            return Ok(current);
        }
        current.pop();
        if !current.pop() {
            return Err(CarnixError::NoCargoLock.into())
            return Err(CarnixError::NoCargoLock.into());
        }
    }
}


pub fn parse_git(source: &str) -> SourceType {
    if let Ok(mut url) = url::Url::parse(source.split_at(4).1) {
        let rev = if let Some((_, rev)) = url.query_pairs().find(|(k, _)| k == "rev") {
            rev.to_string()
        } else {
            if let Some(rev) = url.fragment() {
                rev.to_string()
            } else {
                return SourceType::None
                return SourceType::None;
            }
        };
        url.set_query(None);
        url.set_fragment(None);
        return SourceType::Git {
            url: url.to_string(),
            rev,
        }
        };
    }
In file src/main.rs
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
extern crate serde_derive;
extern crate dirs;
extern crate failure;
extern crate serde_json;
extern crate tempdir;
extern crate toml;
extern crate dirs;
extern crate url;
extern crate failure;
#[macro_use] extern crate failure_derive;
#[macro_use]
extern crate failure_derive;

use std::io::{BufWriter, Read, BufRead};
use clap::{App, Arg, ArgMatches, SubCommand, AppSettings};
use clap::{App, Arg, ArgMatches, SubCommand, AppSettings};
use std::process::{Command, Stdio};
use std::path::{Path, PathBuf};
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
use failure::Error;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use failure::Error;
use std::io::{BufRead, BufWriter, Read};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

mod cache;
mod prefetch;
mod cfg;
mod error;
mod krate;
mod cfg;
mod output;
mod error;
mod prefetch;
use error::*;

fn main() {
    env_logger::init();
    let version = crate_version!();
    let matches =
        App::new("carnix")
            .version(version)
            .author("pmeunier <pe@pijul.org>")
            .about("Generate a nix derivation set from a cargo registry")
            .subcommand(
                SubCommand::with_name("generate-crates-io")
                    .arg(Arg::with_name("file")
                         .help("Generate a crates-io.nix file from a list of packages")
                         .takes_value(true))
            )
            )
            .subcommand(
                SubCommand::with_name("merge")
                    .arg(Arg::with_name("file")
                         .help("Merge two crates-io.nix files")
                         .multiple(true)
                         .takes_value(true))
                         .takes_value(true))
            )
            .subcommand(
                SubCommand::with_name("build")
                    .arg(Arg::with_name("include")
                         .short("-I")
                         .help("Forwarded to nix-build")
                         .takes_value(true)
                         .multiple(true))
                    .arg(Arg::with_name("release")
                         .help("Compile in release mode"))
                    .arg(Arg::with_name("member")
                         .long("--member")
                         .takes_value(true)
                         .help("Select which derivation to compile")),
            )
            .subcommand(
                SubCommand::with_name("run")
                SubCommand::with_name("run")
                    .setting(AppSettings::TrailingVarArg)
                    .arg(Arg::with_name("include")
                         .short("-I")
                         .help("Forwarded to nix-build")
                         .takes_value(true)
                         .multiple(true))
                    .arg(Arg::with_name("rest")
                         .help("Pass the remaining arguments to the program")
                         .multiple(true)
                         .last(true))
                    .arg(Arg::with_name("release")
                         .help("Compile in release mode"))
                    .arg(Arg::with_name("member")
                         .long("--member")
                         .takes_value(true)
                         .help("Select which derivation to compile")),
            )
            )
            .subcommand(
                SubCommand::with_name("generate-nix")
                    .arg(
                    .arg(
                        Arg::with_name("src")
                            .long("--src")
                            .help("Source of the main project")
                            .takes_value(true)
                    )
                    )
                    .arg(Arg::with_name("standalone").long("--standalone").help(
                        "Produce a standalone file, which can be built directly with nix-build.",
                    ))
            )
            .get_matches();
    let matches = App::new("carnix")
        .version(version)
        .author("pmeunier <pe@pijul.org>")
        .about("Generate a nix derivation set from a cargo registry")
        .subcommand(
            SubCommand::with_name("generate-crates-io").arg(
                Arg::with_name("file")
                    .help("Generate a crates-io.nix file from a list of packages")
                    .takes_value(true),
            ),
        )
        .subcommand(
            SubCommand::with_name("merge").arg(
                Arg::with_name("file")
                    .help("Merge two crates-io.nix files")
                    .multiple(true)
                    .takes_value(true),
            ),
        )
        .subcommand(
            SubCommand::with_name("build")
                .arg(
                    Arg::with_name("include")
                        .short("-I")
                        .help("Forwarded to nix-build")
                        .takes_value(true)
                        .multiple(true),
                )
                .arg(Arg::with_name("release").help("Compile in release mode"))
                .arg(
                    Arg::with_name("member")
                        .long("--member")
                        .takes_value(true)
                        .help("Select which derivation to compile"),
                ),
        )
        .subcommand(
            SubCommand::with_name("run")
                .setting(AppSettings::TrailingVarArg)
                .arg(
                    Arg::with_name("include")
                        .short("-I")
                        .help("Forwarded to nix-build")
                        .takes_value(true)
                        .multiple(true),
                )
                .arg(
                    Arg::with_name("rest")
                        .help("Pass the remaining arguments to the program")
                        .multiple(true)
                        .last(true),
                )
                .arg(Arg::with_name("release").help("Compile in release mode"))
                .arg(
                    Arg::with_name("member")
                        .long("--member")
                        .takes_value(true)
                        .help("Select which derivation to compile"),
                ),
        )
        .subcommand(
            SubCommand::with_name("generate-nix")
                .arg(
                    Arg::with_name("src")
                        .long("--src")
                        .help("Source of the main project")
                        .takes_value(true),
                )
                .arg(Arg::with_name("standalone").long("--standalone").help(
                    "Produce a standalone file, which can be built directly with nix-build.",
                )),
        )
        .get_matches();

    if let Some(matches) = matches.subcommand_matches("generate-nix") {
        let cargo_lock = krate::find_cargo_lock().unwrap();
        let mut cargo_nix = cargo_lock.clone();
        cargo_nix.set_extension("nix");
        let mut nix_file = BufWriter::new(std::fs::File::create(&cargo_nix).unwrap());
        if let Err(e) = output::generate_nix(
            &cargo_lock,
            matches.is_present("standalone"),
            matches.value_of("src"),
            &mut nix_file,
        ) {
            eprintln!("{}", e);
            std::process::exit(1)
        }
    } else if let Some(matches) = matches.subcommand_matches("build") {
        build(matches).unwrap();
    } else if let Some(matches) = matches.subcommand_matches("run") {
        let path = build(matches).unwrap();
        let mut bindir = Path::new(path.trim()).join("bin");
        let mut dir = std::fs::read_dir(&bindir).unwrap()
            .filter(|x| if let Ok(ref x) = *x {
        let mut dir = std::fs::read_dir(&bindir).unwrap().filter(|x| {
            if let Ok(ref x) = *x {
                match x.path().extension() {
                    None => true,
                    Some(x) => x == "exe"
                    Some(x) => x == "exe",
                }
            } else {
                false
            });
            }
        });
        if let (Some(bin), None) = (dir.next(), dir.next()) {
            let bin = bin.unwrap();
            let args = if let Some(rest) = matches.values_of("rest") {
                rest.collect()
            } else {
                Vec::new()
            };
            let status = Command::new(&bin.path())
                .args(args)
                .status()
                .unwrap();
            let status = Command::new(&bin.path()).args(args).status().unwrap();
            std::process::exit(status.code().unwrap())
        }
    } else if let Some(matches) = matches.subcommand_matches("generate-crates-io") {
        let file: Box<std::io::Read> = if let Some(f) = matches.value_of("file") {
            Box::new(std::fs::File::open(f).unwrap())
        } else {
            Box::new(std::io::stdin())
        };
        let mut file = std::io::BufReader::new(file);
        let mut s = String::new();
        let mut crates = BTreeMap::new();

        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::Cache::new(&cache_path).unwrap();

        loop {
            s.clear();
            match file.read_line(&mut s) {
                Ok(n) if n > 0 => {
                    let mut krate: krate::Crate = s.parse().unwrap();
                    krate.found_in_lock = true;
                    let mut meta = krate.prefetch(&mut cache, &krate::SourceType::CratesIO).unwrap();
                    for (_, dep) in meta.dependencies.iter_mut().chain(meta.build_dependencies.iter_mut()) {
                    let mut meta = krate
                        .prefetch(&mut cache, &krate::SourceType::CratesIO)
                        .unwrap();
                    for (_, dep) in meta
                        .dependencies
                        .iter_mut()
                        .chain(meta.build_dependencies.iter_mut())
                    {
                        dep.cr.found_in_lock = true
                    }
                    for (_, dep) in meta.target_dependencies.iter_mut() {
                        for (_, dep) in dep.iter_mut() {
                            dep.cr.found_in_lock = true
                        }
                    }
                    crates.insert(krate, meta);
                }
                _ => break
                _ => break,
            }
        }
        std::mem::drop(cache);
        let names: BTreeSet<_> = crates.iter().map(|(ref x, _)| x.name.clone()).collect();
        output::write_crates_io(&crates, &names).unwrap();
    } else if let Some(matches) = matches.subcommand_matches("merge") {
        let file: Box<std::io::Read> = if let Some(v) = matches.values_of("file") {
            let mut file: Box<std::io::Read> = Box::new(std::io::empty());
            for f in v {
                file = Box::new(file.chain(std::fs::File::open(f).unwrap()))
            }
            file
        } else {
            Box::new(std::io::stdin())
        };
        let mut file = std::io::BufReader::new(file);
        let mut title = String::new();
        let mut contents = String::new();
        let mut s = String::new();
        let mut crates = BTreeMap::new();
        loop {
            let n = file.read_line(&mut s).unwrap();
            if n == 0 {
                break
                break;
            }
            debug!("s {:?}", s);
            if s == "# end\n" {
                contents.push_str(&s);
                crates.insert(std::mem::replace(&mut title, String::new()),
                              std::mem::replace(&mut contents, String::new()));
            } else if s.starts_with ("# ") {
                crates.insert(
                    std::mem::replace(&mut title, String::new()),
                    std::mem::replace(&mut contents, String::new()),
                );
            } else if s.starts_with("# ") {
                title.push_str(&s);
                contents.push_str(&s);
            } else if !title.is_empty() {
                contents.push_str(&s);
            }
            s.clear();
        }
        println!("{{ lib, buildRustCrate, buildRustCrateHelpers }}:
        println!(
            "{{ lib, buildRustCrate, buildRustCrateHelpers }}:
with buildRustCrateHelpers;
let inherit (lib.lists) fold;
    inherit (lib.attrsets) recursiveUpdate;
in
rec {{");
rec {{"
        );
        for (_, b) in crates.iter() {
            print!("{}", b)
        }
        println!("}}");
    }
}

fn needs_nix_file(current: &mut PathBuf) -> bool {
    current.push("Cargo.nix");
    if let Ok(meta) = std::fs::metadata(&current) {
        current.pop();
        current.push("Cargo.lock");
        if let Ok(lock_meta) = std::fs::metadata(&current) {
            current.pop();
            return meta.modified().unwrap() < lock_meta.modified().unwrap()
            return meta.modified().unwrap() < lock_meta.modified().unwrap();
        }
        current.pop();
        current.push("Cargo.toml");
        if let Ok(toml_meta) = std::fs::metadata(&current) {
            current.pop();
            return meta.modified().unwrap() < toml_meta.modified().unwrap()
            return meta.modified().unwrap() < toml_meta.modified().unwrap();
        }
    }
    current.pop();
    true
}

fn build(matches: &ArgMatches) -> Result<String, Error> {
    Command::new("cargo")
        .args(&["generate-lockfile"])
        .status()?;

    let current = krate::find_cargo_lock()?;
    // current contains the root of the Cargo.lock.
    let mut nix = current.clone();
    nix.pop();
    let needs_nix = needs_nix_file(&mut nix);
    nix.push("Cargo.nix");
    if needs_nix {
        let mut nix_file = BufWriter::new(std::fs::File::create(&nix)?);
        if let Err(e) = output::generate_nix(&current, true, current.parent(), &mut nix_file) {
            eprintln!("{}", e);
            std::process::exit(1)
        }
    }

    let import = if let Some(member) = matches.value_of("member") {
        format!("((import {}{}).{} {{}}).override {{ release = {}; }}",
                if nix.is_relative() { "./" } else { "" },
                &nix.to_string_lossy(),
                member,
                matches.is_present("release"),
        format!(
            "((import {}{}).{} {{}}).override {{ release = {}; }}",
            if nix.is_relative() { "./" } else { "" },
            &nix.to_string_lossy(),
            member,
            matches.is_present("release"),
        )
    } else {
        format!("map (x: x.override {{ release = {}; }}) (import {}{})._all",
                matches.is_present("release"),
                if nix.is_relative() { "./" } else { "" },
                &nix.to_string_lossy(),
        format!(
            "map (x: x.override {{ release = {}; }}) (import {}{})._all",
            matches.is_present("release"),
            if nix.is_relative() { "./" } else { "" },
            &nix.to_string_lossy(),
        )




























































1
2
3
4
5
6
7
8
9
10

11
12








13
14
15
16
17
18

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

38
39
40
41
42

43
44
45

46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108









109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156




157
158
159
160

161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229

230
231
232
233
234
235

236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257

258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299

300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322

323
324
325
326
327
328
329
330
331
332
333
334
335
336

337
338
339
340

341
342
343
344
345
346

347
348
349
350
351
352
353
354
355
356
357
358
359

360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449

450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466

467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482

483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538

539
540
541
542
543

544
545
546
547
548
549
550

551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581

582
583
584
585
586
587
588

589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632



633
634
635

636










637
638
639
640





641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753




754
755
756
757
758
759
760
761

762

763
764
765
766
767
768
769





770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797

798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820

821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909

910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986







987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036








1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153


1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168

1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195

1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220

1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232




1233
1234
1235
1236
1237

use std::path::Path;
use toml;
                    let mut e = output_features
                        .entry(format!("{}.\"{}\"", dep_name, feat))
                        .or_insert(Vec::new());
                            let dep_name =
                                format!("{}.\"{}\"", dep_name, FeatName(&feat.dep_feature),);
                            writeln!(
                                w,
                                "{}  {}.{}",
                                indent,
                                current_prefix.trim_end_matches('.'),
                                current_attrs.pop().unwrap()
                            )?;
                            writeln!(
                                w,
                                "{}  {} = fold recursiveUpdate {{}} [",
                                indent,
                                current_prefix.trim_end_matches('.')
                            )?;
                        current_prefix = a.split_at(i + 1).0;
                    current_attrs.push(format!(
                        "{} = {};",
                        a.trim_start_matches(current_prefix),
                        b[0]
                    ))
                    current_attrs.push(format!(
                        "{} = (f.{} or false) || {};",
                        a.trim_start_matches(current_prefix),
                        a,
                        b[0]
                    ))
                    current_attrs.push(format!(
                        "{} = (f.{} or false);",
                        a.trim_start_matches(current_prefix),
                        a
                    ))
                let mut x = format!(
                    "{} =\n{}      (f.{} or false)",
                    a.trim_start_matches(current_prefix),
                    indent,
                    a
                );
                writeln!(
                    w,
                    "{}  {}.{}",
                    indent,
                    current_prefix.trim_end_matches('.'),
                    current_attrs.pop().unwrap()
                )?;
                writeln!(
                    w,
                    "{}  {} = fold recursiveUpdate {{}} [",
                    indent,
                    current_prefix.trim_end_matches('.')
                )?;
            for (_, dep) in deps
                .iter()
                .filter(|&(_, c)| c.cr.found_in_lock && c.cr.name.len() > 0)
            {
use cache::*;
use cfg;
use dirs;
use failure::Error;
use itertools::Itertools;
use krate::*;
use regex::Regex;
use std;
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Write};
use regex::Regex;
use std::path::Path;
use std::path::PathBuf;
use itertools::Itertools;
use dirs;
use failure::Error;
use cfg;
use cfg;
use cfg;
use krate::*;
use cache::*;
use toml;

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 >= '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))
    Single(String, (Crate, PathBuf)),
}

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

impl<Item, A:Iterator<Item = Item>, B:Iterator<Item = Item>> Iterator for Either<A, 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 } => {
            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))
                )
            }
            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)
                    );
                    workspace_members.insert(name.as_str().unwrap().to_owned(), (cra, path));
                }
            }
        }
        return Some(CrateType::Workspace { members: workspace_members, package })
        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 patches = cargo_toml.get("patch").and_then(|x| {
        x.get("crates-io")
            .map(|x| make_deps(cr.parent().unwrap(), x))
    });

    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"))) {
        } 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)
                    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,
        patches.as_ref(),
        &workspace_members,
        main_meta.as_ref(),
    ) {
        Ok(pack) => pack,
        Err(e) => {
            std::mem::drop(cache);
            return Err(e)
            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)?;
    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
            return SourceType::CratesIO;
        }

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

fn local_source_type<P:AsRef<Path>>(
fn local_source_type<P: AsRef<Path>>(
    crate_type: &CrateType,
    src: Option<P>,
    main_meta: Option<&Meta>,
    deps: &BTreeMap<String, Dep>,
    patches: Option<&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) {
        let mut dep = patches.and_then(|patches| patches.get(name));
        if dep.is_none() {
            dep = deps.get(name)
        };
        if let Some(ref dep) = dep {
            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>,
    patches: Option<&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)
                source_type = local_source_type(
                    crate_type,
                    src.as_ref(),
                    main_meta,
                    &deps,
                    patches,
                    &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)
                        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
                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> {
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 }:
    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(),
        )
        .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"{ 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!(
        let version = format!(
            "{}.{}.{}{}",
            cra.major,
            cra.major,
            cra.minor,
            cra.patch,
            cra.subpatch
        );
        );
        let version = format!("{}.{}.{}{}", cra.major, cra.minor, cra.patch, cra.subpatch);
        writeln!(
            nix_file,
            "  {} = crates.crates.{}.\"{}\" deps;",
            name,
            name,
            name,
            version,
            version,
            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)?;
        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
                    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
                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 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 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 (_, 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)
        {
            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),
                    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());
            }

            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, (optional_dep_name("default", false), false));
                }
            } else {
                let mut x = format!("{} =\n{}      (f.{} or false)", a.trim_start_matches(current_prefix), indent, a);
                default.insert(dep_name, (optional_dep_name("default", true), true));
            }
        }
        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 (_, (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{}  (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!(
            format!(
                "{}.{}.{}{}",
                self.major, self.minor, self.patch, self.subpatch
                self.major, self.minor, self.patch, self.subpatch
            );
        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.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 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
                        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
                            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
                        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,
                indent,
                nix_name_,
                version
                indent, nix_name_, version
            )?;
        }
        writeln!(w, "{}}};", indent)?;



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
            .and_then(|p| p.get("description").map(|s| s.to_string()));
use cache::*;
use failure::Error;
use krate::*;
use regex::Regex;
use serde_json;
use std;
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::io::Read;
use toml::Value;
use std::path::Path;
use std::path::PathBuf;
use std;
use std::process::Command;
use std::str::from_utf8;
use toml;
use std::str::from_utf8;
use std::process::Command;
use std::path::Path;
use serde_json;
use regex::Regex;
use std::borrow::Cow;
use failure::Error;
use cache::*;
use cache::*;
use krate::*;
use toml::Value;
use CarnixError;

impl Crate {

    pub fn prefetch(&self, cache: &mut Cache, source_type: &SourceType) -> Result<Meta, Error> {
        let mut cargo_toml_path = PathBuf::new();
        let prefetch = match *source_type {
            SourceType::Path { ref path, ref workspace_member } => {
            SourceType::Path {
                ref path,
                ref workspace_member,
            } => {
                debug!("path: {:?}", path);
                cargo_toml_path.push(path);
                if let Some(ref mem) = *workspace_member {
                    cargo_toml_path.push(mem);
                }
                Prefetch {
                    path: path.to_path_buf(),
                    prefetch: Src::Path {
                        path: path.to_path_buf(),
                        workspace_member: workspace_member.as_ref().map(|x| x.to_path_buf()),
                    }
                    },
                }
            }
            SourceType::CratesIO => {
                let prefetch = self.prefetch_path(cache)?;
                cargo_toml_path.push(&prefetch.path);
                prefetch
            },
            }
            SourceType::Git { ref url, ref rev } => {
                let prefetch = self.prefetch_git(url, rev, cache)?;
                cargo_toml_path.push(&prefetch.path);
                prefetch
            },
            _ => panic!("unsupported source {:?}", source_type)
            }
            _ => panic!("unsupported source {:?}", source_type),
        };

        debug!("src = {:?}", prefetch.prefetch);
        cargo_toml_path.push("Cargo.toml");
        debug!("cargo_toml: {:?}", cargo_toml_path);

        let mut f = std::fs::File::open(&cargo_toml_path)?;
        let mut toml = String::new();
        f.read_to_string(&mut toml).unwrap();
        let mut v:toml::Value = match toml::de::from_str(&toml) {
        let mut v: toml::Value = match toml::de::from_str(&toml) {
            Ok(v) => v,
            Err(e) => {
                error!("{:?}: {:?}", cargo_toml_path, e);
                return Err(e.into())
                return Err(e.into());
            }
        };
        let v = v.as_table_mut().expect("v not a table");

        let (dependencies, implied, build_dependencies, target_dependencies) = {
            let prefetch_path = match &prefetch.prefetch {
                &Src::Path { ref path, ref workspace_member } => {
                &Src::Path {
                    ref path,
                    ref workspace_member,
                } => {
                    if let Some(ref ws) = *workspace_member {
                        let mut p = path.to_path_buf();
                        p.push(ws);
                        Cow::Owned(p)
                    } else {
                        Cow::Borrowed(path)
                    }
                },
                _ => Cow::Borrowed(&prefetch.path)
                }
                _ => Cow::Borrowed(&prefetch.path),
            };
            let (dependencies, implied) = make_dependencies(&prefetch_path, v.get("dependencies"), v.get("features"));
            let (build_dependencies, _) = make_dependencies(&prefetch_path, v.get("build-dependencies"), None);
            let (dependencies, implied) =
                make_dependencies(&prefetch_path, v.get("dependencies"), v.get("features"));
            let (build_dependencies, _) =
                make_dependencies(&prefetch_path, v.get("build-dependencies"), None);
            debug!("dependencies of {:?} = {:?}", self.name, dependencies);

            let mut target_dependencies = Vec::new();
            if let Some(target) = v.remove("target") {
                let target = if let Value::Table(target) = target {
                    target
                } else {
                    panic!("target not a table")
                };
                debug!("target = {:?}", target);
                for (a, b) in target {
                    debug!("a = {:?}", a);
                    let (dependencies, _) = make_dependencies(&prefetch_path, b.get("dependencies"), None);
                    let (dependencies, _) =
                        make_dependencies(&prefetch_path, b.get("dependencies"), None);
                    target_dependencies.push((a, dependencies))
                }
                debug!("target_deps {:?}", target_dependencies);
            }
            (dependencies, implied, build_dependencies, target_dependencies)
            (
                dependencies,
                implied,
                build_dependencies,
                target_dependencies,
            )
        };
        // Grab the authors from Cargo.toml, so we can create the
        // CARGO_PKG_AUTHORS environment variable at build time.
        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")
        let authors = v.get("package")
        let authors = v.get("package")
        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").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,
            edition
            edition
            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)
            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 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())
                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) ][..])
            .args(
                &[
                    &url,
                    "--unpack",
                    "--name",
                    &(self.name.clone() + "-" + &version),
                ][..],
            )
            .output()?;

        let sha256:String = from_utf8(&prefetch.stdout).unwrap().trim().to_string();
        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())
                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()
            }
            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 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()
                        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(""));
                    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())
                    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()]
                    return vec![s.to_string()];
                } else if let Some(s) = crate_type.as_array() {
                    return s.into_iter().map(|x| x.to_string()).collect()
                    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)
        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()
                        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 {
            false
        }
    } else {
        false
    }
}

fn is_plugin(v: &toml::map::Map<String, toml::Value>) -> bool {
    if let Some(crate_file) = v.get("lib") {
        if let Some(&toml::Value::Boolean(plugin)) = crate_file.get("plugin") {
            plugin
        } else {
            false
        }
    } else {
        false
    }
}

fn build(v: &toml::map::Map<String, toml::Value>) -> String {
    if let Some(package) = v.get("package") {
        if let Some(build) = package.as_table().unwrap().get("build") {
            return build.as_str().unwrap().to_string()
            return build.as_str().unwrap().to_string();
        }
    }
    String::new()
}

fn features(v: &toml::map::Map<String, toml::Value>) -> (Vec<String>, BTreeSet<String>) {
    let mut default_features = Vec::new();
    let mut declared_features = BTreeSet::new();

    if let Some(features) = v.get("features") {
        let features = features.as_table().unwrap();
        if let Some(default) = features.get("default") {
            default_features.extend(
                default.as_array().unwrap().into_iter().map(|x| x.as_str().unwrap().to_string())
                default
                    .as_array()
                    .unwrap()
                    .into_iter()
                    .map(|x| x.as_str().unwrap().to_string()),
            )
        }
        for (f, _) in features.iter() {
            if f != "default" {
                declared_features.insert(f.to_string());
            }
        }
    }
    (default_features, declared_features)
}

fn declared_dependencies(v: &toml::map::Map<String, toml::Value>) -> BTreeSet<String> {
    let mut declared_dependencies = BTreeSet::new();
    if let Some(deps) = v.get("dependencies") {
        if let Some(deps) = deps.as_table() {
            for (f, _) in deps.iter() {
                declared_dependencies.insert(f.clone());
            }
        }
    }
    if let Some(deps) = v.get("dev-dependencies") {
        if let Some(deps) = deps.as_table() {
            for (f, _) in deps.iter() {
                declared_dependencies.insert(f.clone());
            }
        }
    }
    declared_dependencies
}

fn get_path(stderr: &[u8]) -> Result<&str, Error> {
    debug!("{:?}", from_utf8(&stderr));
    let path_re = Regex::new("path is (‘|')?([^’'\n]*)(’|')?").unwrap();
    let prefetch_stderr = from_utf8(&stderr).expect("stderr of nix-prefetch-url not utf8");
    let cap = if let Some(cap) = path_re.captures(prefetch_stderr) {
        cap
    } else {
        eprintln!("nix-prefetch-url returned:\n{}", prefetch_stderr);
        return Err(CarnixError::PrefetchReturnedNothing.into())
        return Err(CarnixError::PrefetchReturnedNothing.into());
    };