pmeunier / carnix

Removing the dependency on sqlite, parsing URLs properly, and the merge command for crates-io.nix

By blabla on November 30, 2018
This patch is not signed.
7VKLn3y6QFsszbNPbaSNvk65rGRZskwLCyEh1tBSHWeMhVEHexCKvpW6aiRGUGDMhBa936UwvLvi7QLKHz1BirrJ
This patch is in the following branches:
master
In file Cargo.lock

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

81
82
83
84
85
86
87
88
89
90

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

version = "0.9.3"
[[package]]
name = "aho-corasick"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "memchr 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

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

[[package]]
name = "backtrace"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "backtrace-sys 0.1.24 (registry+https://github.com/rust-lang/crates.io-index)",
 "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "rustc-demangle 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

[[package]]
name = "carnix"
version = "0.8.11"
version = "0.9.6"
dependencies = [
 "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "dirs 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "env_logger 0.5.13 (registry+https://github.com/rust-lang/crates.io-index)",
 "error-chain 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "itertools 0.7.8 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "nom 3.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "rusqlite 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)",
 "tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "toml 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
 "url 1.7.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

[[package]]
name = "clap"
version = "2.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "textwrap 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "dirs"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "redox_users 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "env_logger"
version = "0.5.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "humantime 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "termcolor 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "error-chain"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "failure"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "failure_derive 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "failure_derive"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)",
 "quote 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)",
 "syn 0.15.13 (registry+https://github.com/rust-lang/crates.io-index)",
 "synstructure 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "fuchsia-zircon"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "fuchsia-zircon-sys"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"

[[package]]
name = "humantime"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "idna"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)",
 "unicode-bidi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "unicode-normalization 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "itertools"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "either 1.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "lazy_static"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "libsqlite3-sys"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)",
 "vcpkg 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
]

[[package]]
name = "linked-hash-map"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"

[[package]]
name = "log"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "lru-cache"
version = "0.1.1"
name = "matches"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "linked-hash-map 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "memchr"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "memchr"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "nom"
version = "3.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "memchr 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "proc-macro2"
version = "0.4.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "quote"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "rand"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "redox_termios"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "redox_users"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "argon2rs 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "failure 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "regex"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "aho-corasick 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)",
 "memchr 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex-syntax 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "utf8-ranges 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "regex-syntax"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "ucd-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "rusqlite"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "libsqlite3-sys 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "lru-cache 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "lru-cache 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
]
]

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

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

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

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

[[package]]
name = "serde_derive"
version = "1.0.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)",
 "quote 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)",
 "syn 0.15.13 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "serde_json"
version = "1.0.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "ryu 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "syn"
version = "0.15.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)",
 "quote 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)",
 "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "synstructure"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)",
 "quote 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)",
 "syn 0.15.13 (registry+https://github.com/rust-lang/crates.io-index)",
 "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tempdir"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "rand 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "termcolor"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "wincolor 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "termion"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
 "redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "textwrap"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

[[package]]
name = "toml"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "unicode-bidi"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

[[package]]
name = "url"
version = "1.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "idna 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)",
 "percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "vcpkg"
version = "0.2.6"
name = "utf8-ranges"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"

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

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

[[package]]
name = "winapi"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"

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

[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"

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

[metadata]
"checksum aho-corasick 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)" = "68f56c7353e5a9547cbd76ed90f7bb5ffc3ba09d4ea9bd1d8c06c8b1142eeb5a"
"checksum ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b"
"checksum argon2rs 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "3f67b0b6a86dae6e67ff4ca2b6201396074996379fba2b92ff649126f37cb392"
"checksum arrayvec 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)" = "a1e964f9e24d588183fcb43503abda40d288c8657dfc27311516ce2f05675aef"
"checksum atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "9a7d5b8723950951411ee34d271d99dddcc2035a16ab25310ea2c8cfd4369652"
"checksum backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)" = "89a47830402e9981c5c41223151efcced65a0510c13097c769cede7efb34782a"
"checksum backtrace-sys 0.1.24 (registry+https://github.com/rust-lang/crates.io-index)" = "c66d56ac8dabd07f6aacdaf633f4b8262f5b3601a810a0dcddffd5c22c69daa0"
"checksum bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "228047a76f468627ca71776ecdebd732a3423081fcf5125585bcd7c49886ce12"
"checksum blake2-rfc 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)" = "5d6d530bdd2d52966a6d03b7a964add7ae1a288d25214066fd4b600f0f796400"
"checksum cc 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)" = "f159dfd43363c4d08055a07703eb7a3406b0dac4d0584d96965a3262db3c9d16"
"checksum cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "082bb9b28e00d3c9d39cc03e64ce4cea0f1bb9b3fde493f0cbc008472d22bdf4"
"checksum clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b957d88f4b6a63b9d70d5f454ac8011819c6efa7727858f458ab71c756ce2d3e"
"checksum constant_time_eq 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "8ff012e225ce166d4422e0e78419d901719760f62ae2b7969ca6b564d1b54a9e"
"checksum dirs 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "88972de891f6118092b643d85a0b28e0678e0f948d7f879aa32f2d5aafe97d2a"
"checksum either 1.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3be565ca5c557d7f59e7cfcf1844f9e3033650c929c6566f511e8005f205c1d0"
"checksum env_logger 0.5.13 (registry+https://github.com/rust-lang/crates.io-index)" = "15b0a4d2e39f8420210be8b27eeda28029729e2fd4291019455016c348240c38"
"checksum error-chain 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "07e791d3be96241c77c43846b665ef1384606da2cd2a48730abe606a12906e02"
"checksum failure 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "6dd377bcc1b1b7ce911967e3ec24fa19c3224394ec05b54aa7b083d498341ac7"
"checksum failure_derive 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "64c2d913fe8ed3b6c6518eedf4538255b989945c14c2a7d5cbff62a5e2120596"
"checksum fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82"
"checksum fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7"
"checksum humantime 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0484fda3e7007f2a4a0d9c3a703ca38c71c54c55602ce4660c419fd32e188c9e"
"checksum idna 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "38f09e0f0b1fb55fdee1f17470ad800da77af5186a1a76c026b679358b7e844e"
"checksum itertools 0.7.8 (registry+https://github.com/rust-lang/crates.io-index)" = "f58856976b776fedd95533137617a02fb25719f40e7d9b01c7043cd65474f450"
"checksum itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "1306f3464951f30e30d12373d31c79fbd52d236e5e896fd92f96ec7babbbe60b"
"checksum lazy_static 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ca488b89a5657b0a2ecd45b95609b3e848cf1755da332a0da46e2b2b1cb371a7"
"checksum libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)" = "76e3a3ef172f1a0b9a9ff0dd1491ae5e6c948b94479a3021819ba7d860c8645d"
"checksum libsqlite3-sys 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d3711dfd91a1081d2458ad2d06ea30a8755256e74038be2ad927d94e1c955ca8"
"checksum linked-hash-map 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7860ec297f7008ff7a1e3382d7f7e1dcd69efc94751a2284bafc3d013c2aa939"
"checksum linked-hash-map 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7860ec297f7008ff7a1e3382d7f7e1dcd69efc94751a2284bafc3d013c2aa939"
"checksum log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "d4fcce5fa49cc693c312001daf1d13411c4a5283796bac1084299ea3e567113f"
"checksum matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08"
"checksum memchr 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "148fab2e51b4f1cfc66da2a7c32981d1d3c083a803978268bb11fe4b86925e7a"
"checksum memchr 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4b3629fe9fdbff6daa6c33b90f7c08355c1aca05a3d01fa8063b822fcf185f3b"
"checksum nodrop 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)" = "9a2228dca57108069a5262f2ed8bd2e82496d2e074a06d1ccc7ce1687b6ae0a2"
"checksum nom 3.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05aec50c70fd288702bcd93284a8444607f3292dbdf2a30de5ea5dcdbe72287b"
"checksum pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)" = "676e8eb2b1b4c9043511a9b7bea0915320d7e502b0a079fb03f9635a5252b18c"
"checksum percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831"
"checksum proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)" = "3d7b7eaaa90b4a90a932a9ea6666c95a389e424eff347f0f793979289429feee"
"checksum quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9274b940887ce9addde99c4eee6b5c44cc494b182b97e73dc8ffdcb3397fd3f0"
"checksum quote 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)" = "dd636425967c33af890042c483632d33fa7a18f19ad1d7ea72e8998c6ef8dea5"
"checksum rand 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "8356f47b32624fef5b3301c1be97e5944ecdd595409cc5da11d05f211db6cfbd"
"checksum redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)" = "c214e91d3ecf43e9a4e41e578973adeb14b474f2bee858742d127af75a0112b1"
"checksum redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7e891cfe48e9100a70a3b6eb652fef28920c117d366339687bd5576160db0f76"
"checksum redox_users 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "214a97e49be64fd2c86f568dd0cb2c757d2cc53de95b273b6ad0a1c908482f26"
"checksum regex 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "2069749032ea3ec200ca51e4a31df41759190a88edca0d2d86ee8bedf7073341"
"checksum regex-syntax 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "747ba3b235651f6e2f67dfa8bcdcd073ddb7c243cb21c442fc12395dfcac212d"
"checksum remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3488ba1b9a2084d38645c4c08276a1752dcbf2c7130d74f1569681ad5d2799c5"
"checksum rusqlite 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c9d9118f1ce84d8d0b67f9779936432fb42bb620cef2122409d786892cce9a3c"
"checksum rustc-demangle 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "bcfe5b13211b4d78e5c2cadfebd7769197d95c639c35a50057eb4c05de811395"
"checksum ryu 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "7153dd96dade874ab973e098cb62fcdbb89a03682e46b144fd09550998d4a4a7"
"checksum scoped_threadpool 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "1d51f5df5af43ab3f1360b429fa5e0152ac5ce8c0bd6485cae490332e96846a8"
"checksum serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)" = "15c141fc7027dd265a47c090bf864cf62b42c4d228bbcf4e51a0c9e2b0d3f7ef"
"checksum serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)" = "225de307c6302bec3898c51ca302fc94a7a1697ef0845fcee6448f33c032249c"
"checksum serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)" = "43344e7ce05d0d8280c5940cabb4964bea626aa58b1ec0e8c73fa2a8512a38ce"
"checksum strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bb4f380125926a99e52bc279241539c018323fab05ad6368b56f93d9369ff550"
"checksum syn 0.15.13 (registry+https://github.com/rust-lang/crates.io-index)" = "7b4439ee8325b4e4b57e59309c3724c9a4478eaeb4eb094b6f3fac180a3b2876"
"checksum synstructure 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ec37f4fab4bafaf6b5621c1d54e6aa5d4d059a8f84929e87abfdd7f9f04c6db2"
"checksum tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8"
"checksum termcolor 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "4096add70612622289f2fdcdbd5086dc81c1e2675e6ae58d6c4f62a16c6d7f2f"
"checksum termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "689a3bdfaab439fd92bc87df5c4c78417d3cbe537487274e9b0b2dce76e92096"
"checksum textwrap 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "307686869c93e71f94da64286f9a9524c0f308a9e1c87a583de8e9c9039ad3f6"
"checksum thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b"
"checksum toml 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "4a2ecc31b0351ea18b3fe11274b8db6e4d82bce861bbb22e6dbed40417902c65"
"checksum ucd-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "fd2be2d6639d0f8fe6cdda291ad456e23629558d466e2789d2c3e9892bda285d"
"checksum unicode-bidi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "49f2bd0c6468a8230e1db229cff8029217cf623c767ea5d60bfbd42729ea54d5"
"checksum unicode-normalization 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "6a0180bc61fc5a987082bfa111f4cc95c4caff7f9799f3e46df09163a937aa25"
"checksum unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "882386231c45df4700b275c7ff55b6f3698780a650026380e72dabe76fa46526"
"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc"
"checksum url 1.7.2 (registry+https://github.com/rust-lang/crates.io-index)" = "dd4e7c0d531266369519a4aa4f399d748bd37043b00bde1e4ff1f60a120b355a"
"checksum utf8-ranges 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "fd70f467df6810094968e2fce0ee1bd0e87157aceb026a8c083bcf5e25b9efe4"
"checksum vcpkg 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "def296d3eb3b12371b2c7d0e83bfe1403e4db2d7a0bba324a12b21c4ee13143d"
In file Cargo.toml

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
version = "0.9.3"
[package]
name = "carnix"
version = "0.8.11"
version = "0.9.7"
authors = ["pe@pijul.org <pe@pijul.org>"]
include = ["Cargo.toml", "src/main.rs", "src/cargo-generate-nixfile.rs", "src/cache.rs", "src/cfg.rs", "src/krate.rs", "src/prefetch.rs", "src/preamble.nix", "src/output.rs", "src/error.rs" ]
description = "Generate Nix expressions from Cargo.lock files (in order to use Nix as a build system for crates)."
homepage = "https://nest.pijul.com/pmeunier/carnix"
license = "MIT/Apache-2.0"
repository = "https://nest.pijul.com/pmeunier/carnix"

[[bin]]
name = "cargo-generate-nixfile"
path = "src/cargo-generate-nixfile.rs"

[[bin]]
name = "carnix"
path = "src/main.rs"

[dependencies]
clap = "2.32"
serde = "1.0"
toml = "0.4"
serde_json = "1.0"
env_logger = "0.5"
error-chain = "0.12"
nom = "3.0"
log = "0.4"
regex = "1.0"
serde_derive = "1.0"
rusqlite = "0.14"
tempdir = "0.3"
itertools = "0.7"
dirs = "1.0"
url = "1.7"
In file default.nix
2
3

4
5

6
7
   overlays = [ (import /home/pe/nixpkgs-mozilla/rust-overlay.nix) ];
};
let rust = rustChannels.stable.rust; in
stdenv.mkDerivation {
  name = "carnix";
  buildInputs = [ pkgs.sqlite rust ];
  buildInputs = [ rustChannels.stable.rust ];
}
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
125
126
127
128







129
130
131
use rusqlite;
use std::path::Path;
use krate::Src;
use serde_json;
use std::path::PathBuf;
use Error;
use std;
use std::collections::BTreeMap;
use std::io::{Read, Write};

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

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

impl Cache {
    pub fn new<P:AsRef<Path>>(file: P) -> Self {
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
                    }

        let conn = rusqlite::Connection::open(
            file,
        ).unwrap();
                } 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
            };
            if advance_new {
                new_it.next();
            } else {
                ex_it.next();
            }
        }
        std::fs::rename(&path2, &self.path).unwrap();
    }
}

        conn.execute("CREATE TABLE IF NOT EXISTS fetches (
                  id              INTEGER PRIMARY KEY,
                  name            TEXT UNIQUE NOT NULL,
                  json            TEXT,
                  path            TEXT NOT NULL
                  )", &[]).unwrap();
        Cache {
            cache: conn,
impl Cache {
    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> {
        let mut get_stmt = self.cache.prepare("SELECT json, path FROM fetches WHERE name = ?1").unwrap();
        let pre: Option<Prefetch> = get_stmt.query_map(&[&url], |row| {
            let pref: String = row.get(0);
            let path: String = row.get(1);
            Prefetch {
                prefetch: serde_json::from_str(&pref).unwrap(),
                path: Path::new(&path).to_path_buf()
            }
        }).unwrap().next().and_then(|x| x.ok());
        pre
        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
            };
            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(),
                }
            })
        }
    }

    pub fn insert(&mut self, url: &str, prefetch: &Prefetch) {
        let mut insert_stmt = self.cache.prepare("INSERT INTO fetches(name, json, path) VALUES(?1, ?2, ?3)").unwrap();
        insert_stmt.execute(&[
            &url,
            &serde_json::to_string(&prefetch.prefetch).unwrap(),
            &prefetch.path.to_str()
        ]).unwrap();
    pub fn insert(&mut self, url: &str, prefetch: Prefetch) {
        self.new.insert(url.to_string(), prefetch);
    }
10
11

12
13
14
15
16
17
18
19
20
extern crate nom;
extern crate regex;
extern crate rusqlite;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate tempdir;
extern crate toml;
extern crate dirs;
extern crate url;

In file src/cfg.rs
60
61
62
                    "target_env" => cfg_value(w, "abi", value)?,
                    "target_arch" => cfg_value(w, "cpu", value)?,
                    _ => return Err(ErrorKind::CouldNotTranslateTarget.into())
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
            return SourceType::None
use std::collections::{BTreeMap, BTreeSet};
use toml;
use std::path::{Path, PathBuf};
use regex::Regex;
use std;
use {Error, ErrorKind};

#[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>,
}

#[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> },
    Git(GitFetch),
}

#[derive(Debug, PartialEq, Eq)]
pub enum SourceType {
    CratesIO,
    None,
    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()),
            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)?;
        Ok(())
    }
}

pub fn nix_name(name: &str) -> String {
    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
}

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()
                    .into_iter()
                    .map(|x| x.as_str().unwrap().to_string())
                    .collect()
            } else {
                Vec::new()
            };
            let path = if let (Some(path), None) = (dep.get("path"), dep.get("version")) {
                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),
                features: enabled_features,
                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>) {
    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()
                                })
                            }
                        }
                        (Some(c), None) => {
                            // println!("conditional: {:?} {:?} {:?}", c, a, d);
                            cond.push(ConditionalFeature {
                                feature: a.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)
        }
        current.pop();
        if !current.pop() {
            return Err(ErrorKind::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
            }
        };
        url.set_query(None);
        url.set_fragment(None);
        return SourceType::Git {
            url: url.to_string(),
            rev,
        }
    }
    SourceType::None
}
In file src/main.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
        let file: Box<std::io::Read> = if let Some(f) = matches.value_of("file") {
            Box::new(std::fs::File::open(f).unwrap())
#[macro_use]
extern crate clap;
extern crate env_logger;
#[macro_use]
extern crate error_chain;
extern crate itertools;
#[macro_use]
extern crate log;
#[macro_use]
extern crate nom;
extern crate regex;
extern crate rusqlite;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate tempdir;
extern crate toml;
use std::io::{BufWriter, Read};
use std::io::{BufWriter, Read};
extern crate dirs;
extern crate url;

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

use std::collections::BTreeMap;
use std::collections::BTreeSet;
mod error;
pub use error::*;
mod cache;
mod prefetch;
mod krate;
mod cfg;
mod output;

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("build").arg(
                    Arg::with_name("include")
                        .short("-I")
                        .help("Forwarded to nix-build")
                        .takes_value(true)
                        .multiple(true),
                ),
                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)),
                         .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),
                            .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 {
                match x.path().extension() {
                    None => true,
                    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();
            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()) {
                        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
            }
        }
        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
            }
            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 ("# ") {
                title.push_str(&s);
                contents.push_str(&s);
            } else if !title.is_empty() {
                contents.push_str(&s);
            }
            s.clear();
        }
        println!("{{ lib, buildRustCrate, buildRustCrateHelpers }}:
with buildRustCrateHelpers;
let inherit (lib.lists) fold;
    inherit (lib.attrsets) recursiveUpdate;
in
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()
        }
        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()
        }
    }
    current.pop();
    true
}

fn build(matches: &ArgMatches) -> Result<String> {
    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 = format!(
        "(import {}{}).__all",
        if nix.is_relative() { "./" } else { "" },
        &nix.to_string_lossy()
    );
    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"),
        )
    } else {
        format!("map (x: x.override {{ release = {}; }}) (import {}{})._all",
                matches.is_present("release"),
                if nix.is_relative() { "./" } else { "" },
                &nix.to_string_lossy(),
        )
    };
    debug!("{:?}", import);
    let mut args = vec!["-E", &import];
7
8


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169

170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218

219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310


311
312
313
314
315
316
317
318
















319
320


321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527

528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560








561
562
563
564
565

566
567
568

569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845









846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992

993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232

1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274










1275
1276
1277

1278
1279
1280
1281
1282



1283
1284
1285
1286
1287
1288
use std::path::PathBuf;
use itertools::Itertools;


use dirs;
use Error;
use cfg;
use krate::*;
use cache::*;

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

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

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

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

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

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

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

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

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

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

    cr.set_extension("toml");

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

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

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

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

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

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


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

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

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

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

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

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

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

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

    output(standalone, workspace_members, all_packages, base_path, nix_file)?;
    Ok(())
    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" {
            SourceType::CratesIO
        } else if source.starts_with("git+") {
            let url = source.split_at(4).1;
            debug!("url = {:?}", url);
            let mut commit = url.split('#');
            if let (Some(url), Some(rev)) = (commit.next(), commit.next()) {
                SourceType::Git {
                    url: url.to_string(),
                    rev: rev.to_string(),
                }
            } else {
                error!("could not parse Git url");
                SourceType::None
            }
        } else {
            SourceType::None
            return SourceType::CratesIO
        }
    } else {
        SourceType::None

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

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

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

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

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

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

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

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

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

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

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

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

    Ok(all_packages)
}

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

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

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

    write_crates_io(&all_packages, &names)?;
    {
        let mut extra_crates_io = std::io::BufWriter::new(std::fs::File::create("crates-io.nix")?);
        extra_crates_io.write_all(b"{ lib, buildRustCrate, buildRustCrateHelpers }:
with buildRustCrateHelpers;
let inherit (lib.lists) fold;
    inherit (lib.attrsets) recursiveUpdate;
in
rec {\n
")?;
        // 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 {
                cra.output_package(root_prefix, &mut extra_crates_io, 2, &meta, &names, "")?;
                writeln!(f, "{}", cra)?;
            }
        }
        extra_crates_io.write_all(b"}\n")?;
    }
    if standalone {
        nix_file.write_all(b"let cratesIO = callPackage ./crates-io.nix { };
    crates = cratesIO")?;
    } else {
        nix_file.write_all(b"let crates = cratesIO")?;
    }
    let mut is_first = true;
    for (cra, meta) in all_packages.iter() {
        if let Src::Crate { .. } = meta.src {
        } else {
            if is_first {
                writeln!(nix_file, " // rec {{")?;
                is_first = false;
            }
            cra.output_package(root_prefix, &mut nix_file, 2, &meta, &names, "cratesIO.")?;
        }
    }
    if is_first {
        nix_file.write_all(b"; in\n")?;
    } else {
        nix_file.write_all(b"\n}; in\n\n")?;
    }

    nix_file.write_all(b"rec {\n")?;





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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

        writeln!(
            w,
            "{}  authors = [ {} ];",
            indent,
            meta.authors.iter().map(|s| format!("\"{}\"", s)).join(" ")
        )?;

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

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

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

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



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

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


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

fn print_deps<'a, W: Write, I: Iterator<Item = &'a Dep>>(
    mut w: W,
    indent: &str,
    nix_name_: &str,
    version: &str,
    prefix: &str,
    deps: I,
) -> Result<bool, std::io::Error> {
    writeln!(w, " mapFeatures features ([")?;
    let mut at_least_one = false;
    let mut feature_deps = Vec::new();
    for i in deps {
        at_least_one = true;
        debug!("print_deps i {:?}", i);
        if i.is_optional {
            feature_deps.push(i)
        } else {
            writeln!(
                w,
                "{}    ({}crates.\"{}\".\"${{deps.\"{}\".\"{}\".\"{}\"}}\" deps)",
                indent,
                if i.from_crates_io { prefix } else { "" },
                nix_name(&i.cr.name),
                nix_name_,
                version,
                nix_name(&i.cr.name),
            )?;
        }
    }

    if at_least_one {
        write!(w, "{}  ]", indent)?;
    } else {
        write!(w, "]")?;
    }
    for i in feature_deps.iter() {

        let i_version = format!(
            "{}.{}.{}{}{}",
            i.cr.major,
            i.cr.minor,
            i.cr.patch,
            if i.cr.subpatch.is_empty() { "" } else { "-" },
            nix_name(&i.cr.subpatch)
        );

        let i_name = nix_name(&i.cr.name);
        write!(
            w,
            "\n{}    ++ (if features.{}.\"{}\".{} or false then [ ({}crates.{}.\"{}\" deps) ] else [])",
            "\n{}    ++ (if features.{}.\"{}\".{} or false then [ ({}crates.{}.\"${{deps.\"{}\".\"{}\".{}}}\" deps) ] else [])",
            indent,
            nix_name_,
            version,
            FeatName(&i.cr.name),
            nix_name(&i.cr.name),
            nix_name(&i.cr.name),
            i_version
            if i.from_crates_io { prefix } else { "" },
            i_name,
            nix_name_,
            version,
            i_name,
        )?;

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
            cache.insert(&url, pre.clone());
use std::collections::{BTreeMap, BTreeSet};
use std::io::Read;
use toml::Value;
use std::path::PathBuf;
use std;
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 {Error, ErrorKind};
use cache::*;
use krate::*;

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 } => {
                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)
        };

        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) {
            Ok(v) => v,
            Err(e) => {
                error!("{:?}: {:?}", cargo_toml_path, e);
                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 } => {
                    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)
            };
            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);
                    target_dependencies.push((a, dependencies))
                }
                debug!("target_deps {:?}", 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 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,
        })
    }


    fn prefetch_path(&self, cache: &mut Cache) -> Result<Prefetch, Error> {

        debug!("prefetch {:?}", self);
        let version = if self.subpatch.len() > 0 {
            format!("{}.{}.{}{}", self.major, self.minor, self.patch, self.subpatch)
        } else {
            format!("{}.{}.{}", self.major, self.minor, self.patch)
        };
        let url = format!("https://crates.io/api/v1/crates/{}/{}/download", self.name, version);

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

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

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




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

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

        match prefetch {
            Err(e) => {
                error!("error with nix-prefetch-git: {}", e);
                Err(e.into())
            }
            Ok(prefetch) => {

                if prefetch.status.success() {

                    let prefetch_json: GitFetch = serde_json::from_str(from_utf8(&prefetch.stdout).unwrap()).unwrap();
                    let path = get_path(&prefetch.stderr)?;

                    let pre = Prefetch {
                        prefetch: Src::Git(prefetch_json),
                        path: Path::new(path).to_path_buf()
                    };
                    if from_cache.is_none() {
                        cache.insert(&cached_url, &pre);
                        cache.insert(&cached_url, pre.clone());
                    }