pijul_org / pijul

Support for recursive patches (including replacements for #[repr(packed)] on some structs)

By blabla on June 19, 2018
This patch is not signed.
8ALK2JBD4FAU4qpaRhdH5YiCKHY43PCKtk6yshL8mcFPYyEVb4r2W4a17qFA65kKXaLdhMFV2naJ7Qmghh4PVzeS
This patch is in the following branches:
latest
master
testing
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
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
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773

1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566

2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
version = "0.11.27"
 "want 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "hyper 0.11.27 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_json 1.0.17 (registry+https://github.com/rust-lang/crates.io-index)",
 "hyper 0.11.27 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_urlencoded 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)",
version = "0.5.2"
 "itoa 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)",
version = "0.1.0"
version = "0.0.4"
 "futures 0.1.21 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "try-lock 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"checksum hyper 0.11.27 (registry+https://github.com/rust-lang/crates.io-index)" = "34a590ca09d341e94cddf8e5af0bbccde205d5fbc2fa3c09dd67c7f85cea59d7"
"checksum serde_urlencoded 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e703cef904312097cfceab9ce131ff6bbe09e8c964a0703345a5f49238757bc1"
"checksum try-lock 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ee2aa4715743892880f70885373966c83d73ef1b0838a664ef0c76fffd35e7c2"
"checksum want 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "a05d9d966753fa4b5c8db73fcab5eed4549cfe0e1e4e66911e5564a0085c35d1"
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "MacTypes-sys"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

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

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

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

[[package]]
name = "ascii-canvas"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "term 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

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

[[package]]
name = "base64"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "safemem 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "base64"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "bincode"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "autocfg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "bindgen"
version = "0.43.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "cexpr 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "clang-sys 0.26.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "env_logger 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "peeking_take_while 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "proc-macro2 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "quote 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "which 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

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

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

[[package]]
name = "block-buffer"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "block-padding 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "byte-tools 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "generic-array 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "block-padding"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "byte-tools 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "buffered-reader"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bzip2 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "flate2 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

[[package]]
name = "bytes"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

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

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

[[package]]
name = "chrono"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "num-integer 0.1.39 (registry+https://github.com/rust-lang/crates.io-index)",
 "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
 "time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "clang-sys"
version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "glob 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "libloading 0.5.0 (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 = "cloudabi"
version = "0.0.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)",
]

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

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

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

[[package]]
name = "crc"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "build_const 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "crossbeam-channel"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "crossbeam-utils 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "smallvec 0.6.9 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "crossbeam-deque"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "crossbeam-epoch 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "crossbeam-utils 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "crossbeam-epoch"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "arrayvec 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)",
 "cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "crossbeam-utils 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "memoffset 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "scopeguard 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "crossbeam-queue"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "crossbeam-utils 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "crossbeam-utils"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "cryptovec"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "diffs"
version = "0.3.0"

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

[[package]]
name = "digest"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "generic-array 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "dirs"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "redox_users 0.3.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 = "docopt"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
 "strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

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

[[package]]
name = "env_logger"
version = "0.6.1"
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.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "termcolor 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "failure_derive"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)",
 "quote 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "syn 0.15.29 (registry+https://github.com/rust-lang/crates.io-index)",
 "synstructure 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "filetime"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "redox_syscall 0.1.51 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "flate2"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "crc32fast 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "miniz-sys 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "miniz_oxide_c_api 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "foreign-types"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

[[package]]
name = "fuchsia-cprng"
version = "0.1.1"
source = "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 = "futures"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"

[[package]]
name = "futures-cpupool"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "num_cpus 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "generic-array"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "getch"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "termios 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "globset"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "aho-corasick 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)",
 "fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "memchr 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "h2"
version = "0.1.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "http 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)",
 "indexmap 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "string 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "http"
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "humantime"
version = "1.2.0"
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 = "hyper"
version = "0.11.26"
version = "0.12.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures-cpupool 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)",
 "h2 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)",
 "http 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)",
 "httparse 1.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)",
 "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-executor 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-reactor 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-tcp 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-threadpool 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-timer 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)",
 "want 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "hyper-tls"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "hyper 0.12.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "native-tls 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.12 (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.8 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "ignore"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "crossbeam-channel 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)",
 "globset 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "memchr 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "same-file 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "walkdir 2.2.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "iovec"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "itoa"
version = "0.3.4"
source = "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 = "kernel32-sys"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "lalrpop"
version = "0.16.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "ascii-canvas 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "bit-set 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "diff 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "docopt 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "ena 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "itertools 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "lalrpop-util 0.16.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "petgraph 0.4.13 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex-syntax 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
 "sha2 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "string_cache 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "term 0.4.6 (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 = "lalrpop-util"
version = "0.16.3"
source = "registry+https://github.com/rust-lang/crates.io-index"

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

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

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

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

[[package]]
name = "libpijul"
version = "0.12.0"
dependencies = [
 "base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "bincode 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "bs58 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "diffs 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "flate2 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "ignore 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "openssl 0.10.20 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "sanakirja 0.10.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "sequoia-openpgp 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_json 1.0.39 (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.10 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "line"
version = "0.1.15"
dependencies = [
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "utf8parse 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "lock_api"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "owning_ref 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "scopeguard 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

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

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

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

[[package]]
name = "memsec"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "mach_o_sys 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "mime"
version = "0.3.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "unicase 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "mime_guess"
version = "2.0.0-alpha.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "mime 0.3.13 (registry+https://github.com/rust-lang/crates.io-index)",
 "phf 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)",
 "phf_codegen 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)",
 "unicase 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "miniz_oxide"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "adler32 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "miniz_oxide_c_api"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cc 1.0.31 (registry+https://github.com/rust-lang/crates.io-index)",
 "crc 1.8.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "miniz_oxide 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "mio"
version = "0.6.16"
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)",
 "fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "lazycell 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)",
 "slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "mio-uds"
version = "0.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "miow"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
 "ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "native-tls"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "openssl 0.10.20 (registry+https://github.com/rust-lang/crates.io-index)",
 "openssl-probe 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "openssl-sys 0.9.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "schannel 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)",
 "security-framework 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "security-framework-sys 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "tempfile 3.0.7 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "net2"
version = "0.2.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "nettle"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "nettle-sys 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "nettle-sys"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bindgen 0.43.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

[[package]]
name = "nom"
version = "4.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "memchr 2.2.0 (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 = "num"
version = "0.1.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "num-bigint 0.1.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "num-bigint 0.1.44 (registry+https://github.com/rust-lang/crates.io-index)",
 "num-complex 0.1.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "num-integer 0.1.39 (registry+https://github.com/rust-lang/crates.io-index)",
 "num-iter 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)",
 "num-rational 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)",
 "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "num-bigint"
version = "0.1.43"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "num-integer 0.1.39 (registry+https://github.com/rust-lang/crates.io-index)",
 "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "num-complex"
version = "0.1.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "num-integer"
version = "0.1.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "num-iter"
version = "0.1.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "num-integer 0.1.39 (registry+https://github.com/rust-lang/crates.io-index)",
 "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "num-rational"
version = "0.1.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "num-bigint 0.1.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "num-bigint 0.1.44 (registry+https://github.com/rust-lang/crates.io-index)",
 "num-integer 0.1.39 (registry+https://github.com/rust-lang/crates.io-index)",
 "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

[[package]]
name = "openssl"
version = "0.10.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "openssl-sys 0.9.43 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "openssl-sys"
version = "0.9.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cc 1.0.31 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)",
 "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "vcpkg 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "owning_ref"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "parking_lot"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "lock_api 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "parking_lot_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "parking_lot_core"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "smallvec 0.6.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 = "pathdiff"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"

[[package]]
name = "peeking_take_while"
version = "0.1.2"
source = "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 = "petgraph"
version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "fixedbitset 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "ordermap 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "phf"
version = "0.7.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "phf_shared 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "phf_codegen"
version = "0.7.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "phf_generator 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)",
 "phf_shared 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "phf_generator"
version = "0.7.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "phf_shared 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "phf_shared"
version = "0.7.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "siphasher 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "unicase 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "pijul"
version = "0.12.0"
dependencies = [
 "atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "bincode 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "bs58 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "cryptovec 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "dirs 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "env_logger 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "flate2 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "getch 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "ignore 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "libpijul 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "line 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "pathdiff 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "progrs 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "reqwest 0.9.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "rpassword 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "sequoia-openpgp 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
 "shell-escape 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "tar 0.4.22 (registry+https://github.com/rust-lang/crates.io-index)",
 "tempfile 3.0.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "term 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "thrussh 0.20.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "thrussh-config 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "thrussh-keys 0.11.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-uds 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "toml 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)",
 "username 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "walkdir 2.2.7 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

[[package]]
name = "proc-macro2"
version = "0.3.5"
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 = "proc-macro2"
version = "0.4.27"
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 = "progrs"
version = "0.1.1"
source = "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 = "quickcheck"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "env_logger 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

[[package]]
name = "rand"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "rdrand 0.4.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 = "rand"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_core 0.3.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 = "rand"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "autocfg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_chacha 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_hc 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_isaac 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_jitter 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_os 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_pcg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_xorshift 0.1.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 = "rand_chacha"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "autocfg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "rand_core"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "rand_hc"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "rand_jitter"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_core 0.4.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 = "rand_os"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "rdrand 0.4.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 = "rand_pcg"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "autocfg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "rdrand"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "redox_syscall"
version = "0.1.51"
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.51 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "redox_users"
version = "0.3.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.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_os 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "redox_syscall 0.1.51 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "regex-syntax"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "ucd-util 0.1.3 (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 = "reqwest"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "encoding_rs 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)",
 "flate2 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "http 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)",
 "hyper 0.12.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "hyper-tls 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "mime 0.3.13 (registry+https://github.com/rust-lang/crates.io-index)",
 "mime_guess 2.0.0-alpha.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "native-tls 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_urlencoded 0.5.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-executor 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-threadpool 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-timer 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)",
 "url 1.7.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "uuid 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "rpassword"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

[[package]]
name = "rustc_version"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

[[package]]
name = "sanakirja"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "fs2 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "memmap 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "schannel"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "lazy_static 1.3.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 = "scoped_threadpool"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"

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

[[package]]
name = "security-framework"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "core-foundation 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "core-foundation-sys 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "security-framework-sys 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "security-framework-sys"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "MacTypes-sys 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "core-foundation-sys 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "semver"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "sequoia-openpgp"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "base64 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "buffered-reader 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "bzip2 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "flate2 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "lalrpop 0.16.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "lalrpop-util 0.16.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "memsec 0.5.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "nettle 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "quickcheck 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "serde_derive"
version = "1.0.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)",
 "quote 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "syn 0.15.29 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "serde_json"
version = "1.0.39"
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.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "serde_urlencoded"
version = "0.5.1"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "dtoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
 "url 1.7.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "sha2"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "block-buffer 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "digest 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "fake-simd 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "opaque-debug 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

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

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

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

[[package]]
name = "string_cache"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "new_debug_unreachable 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "phf_shared 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)",
 "precomputed-hash 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
 "string_cache_codegen 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "string_cache_shared 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "string_cache_codegen"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "phf_generator 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)",
 "phf_shared 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)",
 "proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)",
 "quote 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "string_cache_shared 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "string_cache_shared"
version = "0.3.0"
source = "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.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)",
 "quote 0.6.11 (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.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)",
 "quote 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "syn 0.15.29 (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 = "tar"
version = "0.4.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "filetime 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "redox_syscall 0.1.51 (registry+https://github.com/rust-lang/crates.io-index)",
 "xattr 0.2.2 (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.6 (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 = "tempfile"
version = "3.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "redox_syscall 0.1.51 (registry+https://github.com/rust-lang/crates.io-index)",
 "remove_dir_all 0.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 = "term"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "term"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "byteorder 1.3.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 = "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.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "redox_syscall 0.1.51 (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 = "termios"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.50 (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.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "thrussh"
version = "0.20.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "cryptovec 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "openssl 0.10.20 (registry+https://github.com/rust-lang/crates.io-index)",
 "thrussh-keys 0.11.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "thrussh-libsodium 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "thrussh-config"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "dirs 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "thrussh 0.20.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "thrussh-keys"
version = "0.11.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "base64 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "bit-vec 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "cryptovec 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "dirs 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "num-bigint 0.1.44 (registry+https://github.com/rust-lang/crates.io-index)",
 "num-integer 0.1.39 (registry+https://github.com/rust-lang/crates.io-index)",
 "openssl 0.10.20 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
 "thrussh-libsodium 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
 "yasna 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "thrussh-libsodium"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "tokio"
version = "0.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)",
 "num_cpus 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-codec 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-current-thread 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-executor 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-fs 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-reactor 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-sync 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-tcp 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-threadpool 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-timer 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-trace-core 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-udp 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-uds 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-codec"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-current-thread"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-executor 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-executor"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "crossbeam-utils 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-fs"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-threadpool 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-io"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-reactor"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "crossbeam-utils 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)",
 "num_cpus 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-executor 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-sync 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-sync"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-tcp"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-reactor 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-threadpool"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "crossbeam-deque 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "crossbeam-queue 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "crossbeam-utils 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "num_cpus 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-executor 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-timer"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "crossbeam-utils 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-executor 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-trace-core"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-udp"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-codec 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-reactor 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-uds"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)",
 "mio-uds 0.6.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-codec 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-reactor 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

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

[[package]]
name = "unicase"
version = "1.4.2"
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 = "unicase"
version = "2.3.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 = "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.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "smallvec 0.6.9 (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 = "username"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "advapi32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

[[package]]
name = "uuid"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "vcpkg"
version = "0.2.6"
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 = "walkdir"
version = "2.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "same-file 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "want"
version = "0.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "try-lock 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "winapi"
version = "0.2.8"
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-build"
version = "0.1.1"
source = "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.2"
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.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

[[package]]
name = "yasna"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bit-vec 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "num 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)",
]

[metadata]
"checksum MacTypes-sys 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "eaf9f0d0b1cc33a4d2aee14fb4b2eac03462ef4db29c8ac4057327d8a71ad86f"
"checksum adler32 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "7e522997b529f05601e05166c07ed17789691f562762c7f3b987263d2dedee5c"
"checksum advapi32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e06588080cb19d0acb6739808aafa5f26bfb2ca015b2b6370028b44cf7cb8a9a"
"checksum aho-corasick 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)" = "81ce3d38065e618af2d7b77e10c5ad9a069859b4be3c2250f674af3840d9c8a5"
"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.10 (registry+https://github.com/rust-lang/crates.io-index)" = "92c7fb76bc8826a8b33b4ee5bb07a247a81e76764ab4d55e8f73e3a4d8808c71"
"checksum ascii-canvas 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b385d69402821a1c254533a011a312531cbcc0e3e24f19bbb4747a5a2daf37e2"
"checksum atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "9a7d5b8723950951411ee34d271d99dddcc2035a16ab25310ea2c8cfd4369652"
"checksum autocfg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a6d640bee2da49f60a4068a7fae53acde8982514ab7bae8b8cea9e88cbcfd799"
"checksum backtrace 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)" = "cd5a90e2b463010cd0e0ce9a11d4a9d5d58d9f41d4a6ba3dcaf9e68b466e88b4"
"checksum backtrace-sys 0.1.28 (registry+https://github.com/rust-lang/crates.io-index)" = "797c830ac25ccc92a7f8a7b9862bde440715531514594a6154e3d4a54dd769b6"
"checksum base64 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0b25d992356d2eb0ed82172f5248873db5560c4721f564b13cb5193bda5e668e"
"checksum base64 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)" = "489d6c0ed21b11d038c31b6ceccca973e65d73ba3bd8ecb9a2babf5546164643"
"checksum bincode 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "3efe0b4c8eaeed8600549c29f538a6a11bf422858d0ed435b1d70ec4ab101190"
"checksum bindgen 0.43.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6d52d263eacd15d26cbcf215d254b410bd58212aaa2d3c453a04b2d3b3adcf41"
"checksum bit-set 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "e84c238982c4b1e1ee668d136c510c67a13465279c0cb367ea6baf6310620a80"
"checksum bit-vec 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "02b4ff8b16e6076c3e14220b39fbc1fabb6737522281a388998046859400895f"
"checksum bit-vec 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f59bbe95d4e52a6398ec21238d31577f2b28a9d86807f06ca59d191d8440d0bb"
"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 block-buffer 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "49665c62e0e700857531fa5d3763e91b539ff1abeebd56808d378b495870d60d"
"checksum block-padding 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d75255892aeb580d3c566f213a2b6fdc1c66667839f45719ee1d30ebf2aea591"
"checksum bs58 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "0de79cfb98e7aa9988188784d8664b4b5dad6eaaa0863b91d9a4ed871d4f7a42"
"checksum buffered-reader 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8df3a7107eaef76e1e904f306c3f3f4c3bb142ba90e80d390e8d40e680b09b8d"
"checksum build_const 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "39092a32794787acd8525ee150305ff051b0aa6cc2abaf193924f5ab05425f39"
"checksum byte-tools 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7"
"checksum byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a019b10a2a7cdeb292db131fc8113e57ea2a908f6e7894b0c3c671893b65dbeb"
"checksum bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)" = "206fdffcfa2df7cbe15601ef46c813fce0965eb3286db6b56c583b814b51c81c"
"checksum bzip2 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "42b7c3cbf0fa9c1b82308d57191728ca0256cb821220f4e2fd410a72ade26e3b"
"checksum bzip2-sys 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "6584aa36f5ad4c9247f5323b0a42f37802b37a836f0ad87084d7a33961abe25f"
"checksum cc 1.0.31 (registry+https://github.com/rust-lang/crates.io-index)" = "c9ce8bb087aacff865633f0bd5aeaed910fe2fe55b55f4739527f2e023a2e53d"
"checksum cexpr 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "a7fa24eb00d5ffab90eaeaf1092ac85c04c64aaf358ea6f84505b8116d24c6af"
"checksum cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "11d43355396e872eefb45ce6342e4374ed7bc2b3a502d1b28e36d6e23c05d1f4"
"checksum chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "45912881121cb26fad7c38c17ba7daa18764771836b34fab7d3fbd93ed633878"
"checksum clang-sys 0.26.4 (registry+https://github.com/rust-lang/crates.io-index)" = "6ef0c1bcf2e99c649104bd7a7012d8f8802684400e03db0ec0af48583c6fa0e4"
"checksum clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b957d88f4b6a63b9d70d5f454ac8011819c6efa7727858f458ab71c756ce2d3e"
"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f"
"checksum constant_time_eq 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "8ff012e225ce166d4422e0e78419d901719760f62ae2b7969ca6b564d1b54a9e"
"checksum core-foundation 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "286e0b41c3a20da26536c6000a280585d519fd07b3956b43aed8a79e9edce980"
"checksum core-foundation-sys 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "716c271e8613ace48344f723b60b900a93150271e5be206212d052bbc0883efa"
"checksum crc 1.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d663548de7f5cca343f1e0a48d14dcfb0e9eb4e079ec58883b7251539fa10aeb"
"checksum crc32fast 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ba125de2af0df55319f41944744ad91c71113bf74a4646efff39afe1f6842db1"
"checksum crossbeam-channel 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "0f0ed1a4de2235cabda8558ff5840bffb97fcb64c97827f354a451307df5f72b"
"checksum crossbeam-deque 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b18cd2e169ad86297e6bc0ad9aa679aee9daa4f19e8163860faf7c164e4f5a71"
"checksum crossbeam-epoch 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "04c9e3102cc2d69cd681412141b390abd55a362afc1540965dad0ad4d34280b4"
"checksum crossbeam-queue 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7c979cd6cfe72335896575c6b5688da489e420d36a27a0b9eb0c73db574b4a4b"
"checksum crossbeam-utils 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)" = "f8306fcef4a7b563b76b7dd949ca48f52bc1141aa067d2ea09565f3e2652aa5c"
"checksum cryptovec 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "e412d5c27b9048893c168870a91ce9df1ce55b780153fa11d1bd89e5606d08d9"
"checksum diff 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)" = "3c2b69f912779fbb121ceb775d74d51e915af17aaebc38d28a592843a2dd0a3a"
"checksum diffs 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a195326f620ab1da14f60d991c066311122cbdce579a00085d8be45899c7da0c"
"checksum digest 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "05f47366984d3ad862010e22c7ce81a7dbcaebbdfb37241a620f8b6596ee135c"
"checksum dirs 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "3fd78930633bd1c6e35c4b42b1df7b0cbc6bc191146e512bb3bedf243fcc3901"
"checksum docopt 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "db2906c2579b5b7207fc1e328796a9a8835dc44e22dbe8e460b1d636f9a7b225"
"checksum dtoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "6d301140eb411af13d3115f9a562c85cc6b541ade9dfa314132244aaee7489dd"
"checksum either 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c67353c641dc847124ea1902d69bd753dee9bb3beff9aa3662ecf86c971d1fac"
"checksum ena 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f56c93cc076508c549d9bb747f79aa9b4eb098be7b8cad8830c3137ef52d1e00"
"checksum encoding_rs 0.8.17 (registry+https://github.com/rust-lang/crates.io-index)" = "4155785c79f2f6701f185eb2e6b4caf0555ec03477cb4c70db67b465311620ed"
"checksum env_logger 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b61fa891024a945da30a9581546e8cfaf5602c7b3f4c137a2805cf388f92075a"
"checksum failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "795bd83d3abeb9220f257e597aa0080a508b27533824adf336529648f6abf7e2"
"checksum failure_derive 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "ea1063915fd7ef4309e222a5a07cf9c319fb9c7836b1f89b85458672dbb127e1"
"checksum fake-simd 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed"
"checksum filetime 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "a2df5c1a8c4be27e7707789dc42ae65976e60b394afd293d1419ab915833e646"
"checksum fixedbitset 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "86d4de0081402f5e88cdac65c8dcdcc73118c1a7a465e2a05f0da05843a8ea33"
"checksum flate2 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f87e68aa82b2de08a6e037f1385455759df6e445a8df5e005b4297191dbf18aa"
"checksum fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "2fad85553e09a6f881f739c29f0b00b0f01357c743266d478b68951ce23285f3"
"checksum foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
"checksum foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
"checksum fs2 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"
"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba"
"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 futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)" = "49e7653e374fe0d0c12de4250f0bdb60680b8c80eed558c5c7538eec9c89e21b"
"checksum futures-cpupool 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "ab90cde24b3319636588d0c35fe03b1333857621051837ed769faefb4c2162e4"
"checksum generic-array 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3c0f28c2f5bfb5960175af447a2da7c18900693738343dc896ffbcabd9839592"
"checksum getch 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "bbb0b59927a20adfdc274a345f8b4b476e552e56ec0bfb072e0a455c12463602"
"checksum glob 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "8be18de09a56b60ed0edf84bc9df007e30040691af7acd1c41874faac5895bfb"
"checksum globset 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "4743617a7464bbda3c8aec8558ff2f9429047e025771037df561d383337ff865"
"checksum h2 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)" = "910a5e7be6283a9c91b3982fa5188368c8719cce2a3cf3b86048673bf9d9c36b"
"checksum hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "805026a5d0141ffc30abb3be3173848ad46a1b1664fe632428479619a3644d77"
"checksum http 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)" = "fe67e3678f2827030e89cc4b9e7ecd16d52f132c0b940ab5005f88e821500f6a"
"checksum httparse 1.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e8734b0cfd3bc3e101ec59100e101c2eecd19282202e87808b3037b442777a83"
"checksum humantime 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3ca7e5f2e110db35f93b837c81797f3714500b81d517bf20c431b16d3ca4f114"
"checksum hyper 0.12.25 (registry+https://github.com/rust-lang/crates.io-index)" = "7d5b6658b016965ae301fa995306db965c93677880ea70765a84235a96eae896"
"checksum hyper-tls 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "3a800d6aa50af4b5850b2b0f659625ce9504df908e9733b635720483be26174f"
"checksum idna 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "38f09e0f0b1fb55fdee1f17470ad800da77af5186a1a76c026b679358b7e844e"
"checksum ignore 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "ad03ca67dc12474ecd91fdb94d758cbd20cb4e7a78ebe831df26a9b7511e1162"
"checksum indexmap 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7e81a7c05f79578dbc15793d8b619db9ba32b4577003ef3af1a91c416798c58d"
"checksum iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "dbe6e417e7d0975db6512b90796e8ce223145ac4e33c377e4a42882a0e88bb08"
"checksum itertools 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5b8467d9c1cebe26feb08c640139247fac215782d35371ade9a2136ed6085358"
"checksum itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "1306f3464951f30e30d12373d31c79fbd52d236e5e896fd92f96ec7babbbe60b"
"checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d"
"checksum lalrpop 0.16.3 (registry+https://github.com/rust-lang/crates.io-index)" = "4e2e80bee40b22bca46665b4ef1f3cd88ed0fb043c971407eac17a0712c02572"
"checksum lalrpop-util 0.16.3 (registry+https://github.com/rust-lang/crates.io-index)" = "33b27d8490dbe1f9704b0088d61e8d46edc10d5673a8829836c6ded26a9912c7"
"checksum lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bc5729f27f159ddd61f4df6228e827e86643d4d3e7c32183cb30a1c08f604a14"
"checksum lazycell 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f"
"checksum libc 0.2.50 (registry+https://github.com/rust-lang/crates.io-index)" = "aab692d7759f5cd8c859e169db98ae5b52c924add2af5fbbca11d12fefb567c1"
"checksum libloading 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9c3ad660d7cb8c5822cd83d10897b0f1f1526792737a179e73896152f85b88c2"
"checksum libpijul 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0aa2597c58ba745d3a9d5a03663d31a62ffa0c3804b4b6734593847055e96efe"
"checksum line 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)" = "04a85c38c9108ca150a17aed8138dc6228160a17a239fa0338288d42f3d63a5e"
"checksum lock_api 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "62ebf1391f6acad60e5c8b43706dde4582df75c06698ab44511d15016bc2442c"
"checksum log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c84ec4b527950aa83a329754b01dbe3f58361d1c5efacd1f6d68c494d08a17c6"
"checksum mach_o_sys 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3e854583a83f20cf329bb9283366335387f7db59d640d1412167e05fedb98826"
"checksum matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08"
"checksum memchr 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2efc7bc57c883d4a4d6e3246905283d8dae951bb3bd32f49d6ef297f546e1c39"
"checksum memmap 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6585fd95e7bb50d6cc31e20d4cf9afb4e2ba16c5846fc76793f11218da9c475b"
"checksum memoffset 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0f9dc261e2b62d7a622bf416ea3c5245cdd5d9a7fcc428c0d06804dfce1775b3"
"checksum memsec 0.5.4 (registry+https://github.com/rust-lang/crates.io-index)" = "99ea6115ff21342fa519c02047c6e87e932ac51aa214e344f2c1fd85ec6ed50c"
"checksum mime 0.3.13 (registry+https://github.com/rust-lang/crates.io-index)" = "3e27ca21f40a310bd06d9031785f4801710d566c184a6e15bad4f1d9b65f9425"
"checksum mime_guess 2.0.0-alpha.6 (registry+https://github.com/rust-lang/crates.io-index)" = "30de2e4613efcba1ec63d8133f344076952090c122992a903359be5a4f99c3ed"
"checksum miniz-sys 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)" = "0300eafb20369952951699b68243ab4334f4b10a88f411c221d444b36c40e649"
"checksum miniz_oxide 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c468f2369f07d651a5d0bb2c9079f8488a66d5466efe42d0c5c6466edcb7f71e"
"checksum miniz_oxide_c_api 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b7fe927a42e3807ef71defb191dc87d4e24479b221e67015fe38ae2b7b447bab"
"checksum mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)" = "71646331f2619b1026cc302f87a2b8b648d5c6dd6937846a16cc8ce0f347f432"
"checksum mio-uds 0.6.7 (registry+https://github.com/rust-lang/crates.io-index)" = "966257a94e196b11bb43aca423754d87429960a768de9414f3691d6957abf125"
"checksum miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919"
"checksum native-tls 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "ff8e08de0070bbf4c31f452ea2a70db092f36f6f2e4d897adf5674477d488fb2"
"checksum net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)" = "42550d9fb7b6684a6d404d9fa7250c2eb2646df731d1c06afc06dcee9e1bcf88"
"checksum nettle 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "16f1959280669371d12190f792f44ac3166fd0fc089766f1a64e92bacb76e2ef"
"checksum nettle-sys 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "bc3118c8e6ffc6b26857b59427293771bd418216cb0c9fcf540282397f8460d9"
"checksum new_debug_unreachable 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "f40f005c60db6e03bae699e414c58bf9aa7ea02a2d0b9bfbcf19286cc4c82b30"
"checksum nodrop 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "2f9667ddcc6cc8a43afc9b7917599d7216aa09c463919ea32c59ed6cac8bc945"
"checksum nom 4.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2ad2a91a8e869eeb30b9cb3119ae87773a8f4ae617f41b1eb9c154b2905f7bd6"
"checksum num 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "4703ad64153382334aa8db57c637364c322d3372e097840c72000dabdcf6156e"
"checksum num-bigint 0.1.43 (registry+https://github.com/rust-lang/crates.io-index)" = "81b483ea42927c463e191802e7334556b48e7875297564c0e9951bd3a0ae53e3"
"checksum num-bigint 0.1.44 (registry+https://github.com/rust-lang/crates.io-index)" = "e63899ad0da84ce718c14936262a41cee2c79c981fc0a0e7c7beb47d5a07e8c1"
"checksum num-complex 0.1.43 (registry+https://github.com/rust-lang/crates.io-index)" = "b288631d7878aaf59442cffd36910ea604ecd7745c36054328595114001c9656"
"checksum num-integer 0.1.39 (registry+https://github.com/rust-lang/crates.io-index)" = "e83d528d2677f0518c570baf2b7abdcf0cd2d248860b68507bdcb3e91d4c0cea"
"checksum num-iter 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)" = "af3fdbbc3291a5464dc57b03860ec37ca6bf915ed6ee385e7c6c052c422b2124"
"checksum num-rational 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "ee314c74bd753fc86b4780aa9475da469155f3848473a261d2d18e35245a784e"
"checksum num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "0b3a5d7cc97d6d30d8b9bc8fa19bf45349ffe46241e8816f50f62f6d6aaabee1"
"checksum num_cpus 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1a23f0ed30a54abaa0c7e83b1d2d87ada7c3c23078d1d87815af3e3b6385fbba"
"checksum opaque-debug 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "93f5bb2e8e8dec81642920ccff6b61f1eb94fa3020c5a325c9851ff604152409"
"checksum openssl 0.10.20 (registry+https://github.com/rust-lang/crates.io-index)" = "5a0d6b781aac4ac1bd6cafe2a2f0ad8c16ae8e1dd5184822a16c50139f8838d9"
"checksum openssl-probe 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "77af24da69f9d9341038eba93a073b1fdaaa1b788221b00a69bce9e762cb32de"
"checksum openssl-sys 0.9.43 (registry+https://github.com/rust-lang/crates.io-index)" = "33c86834957dd5b915623e94f2f4ab2c70dd8f6b70679824155d5ae21dbd495d"
"checksum ordermap 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "a86ed3f5f244b372d6b1a00b72ef7f8876d0bc6a78a4c9985c53614041512063"
"checksum owning_ref 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "49a4b8ea2179e6a2e27411d3bca09ca6dd630821cf6894c6c7c8467a8ee7ef13"
"checksum parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ab41b4aed082705d1056416ae4468b6ea99d52599ecf3169b00088d43113e337"
"checksum parking_lot_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "94c8c7923936b28d546dfd14d4472eaf34c99b14e1c973a32b3e6d4eb04298c9"
"checksum pathdiff 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a3bf70094d203e07844da868b634207e71bfab254fe713171fae9a6e751ccf31"
"checksum peeking_take_while 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099"
"checksum percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831"
"checksum petgraph 0.4.13 (registry+https://github.com/rust-lang/crates.io-index)" = "9c3659d1ee90221741f65dd128d9998311b0e40c5d3c23a62445938214abce4f"
"checksum phf 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)" = "b3da44b85f8e8dfaec21adae67f95d93244b2ecf6ad2a692320598dcc8e6dd18"
"checksum phf_codegen 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)" = "b03e85129e324ad4166b06b2c7491ae27fe3ec353af72e72cd1654c7225d517e"
"checksum phf_generator 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)" = "09364cc93c159b8b06b1f4dd8a4398984503483891b0c26b867cf431fb132662"
"checksum phf_shared 0.7.24 (registry+https://github.com/rust-lang/crates.io-index)" = "234f71a15de2288bcb7e3b6515828d22af7ec8598ee6d24c3b526fa0a80b67a0"
"checksum pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)" = "676e8eb2b1b4c9043511a9b7bea0915320d7e502b0a079fb03f9635a5252b18c"
"checksum precomputed-hash 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
"checksum proc-macro2 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "77997c53ae6edd6d187fec07ec41b207063b5ee6f33680e9fa86d405cdd313d4"
"checksum proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)" = "4d317f9caece796be1980837fd5cb3dfec5613ebdb04ad0956deea83ce168915"
"checksum progrs 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "df45e02a175d824d8f9d86d4c1ad2b1325d1b933dce1b5615e218b9d25ea1281"
"checksum quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9274b940887ce9addde99c4eee6b5c44cc494b182b97e73dc8ffdcb3397fd3f0"
"checksum quickcheck 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)" = "3568ae5409428feef71bf062778bf5acfadc3d496b7696afa829f9eef70e17dc"
"checksum quote 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9949cfe66888ffe1d53e6ec9d9f3b70714083854be20fd5e271b232a017401e8"
"checksum quote 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)" = "cdd8e04bd9c52e0342b406469d494fcb033be4bdbe5c606016defbb1681411e1"
"checksum rand 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293"
"checksum rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9"
"checksum rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)" = "6d71dacdc3c88c1fde3885a3be3fbab9f35724e6ce99467f7d9c5026132184ca"
"checksum rand_chacha 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "556d3a1ca6600bfcbab7c7c91ccb085ac7fbbcd70e008a98742e7847f4f7bcef"
"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b"
"checksum rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0"
"checksum rand_hc 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7b40677c7be09ae76218dc623efbf7b18e34bced3f38883af07bb75630a21bc4"
"checksum rand_isaac 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08"
"checksum rand_jitter 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "7b9ea758282efe12823e0d952ddb269d2e1897227e464919a554f2a03ef1b832"
"checksum rand_os 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071"
"checksum rand_pcg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "abf9b09b01790cfe0364f52bf32995ea3c39f4d2dd011eac241d2914146d0b44"
"checksum rand_xorshift 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cbf7e9e623549b0e21f6e97cf8ecf247c1a8fd2e8a992ae265314300b2455d5c"
"checksum rdrand 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2"
"checksum redox_syscall 0.1.51 (registry+https://github.com/rust-lang/crates.io-index)" = "423e376fffca3dfa06c9e9790a9ccd282fafb3cc6e6397d01dbf64f9bacc6b85"
"checksum redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7e891cfe48e9100a70a3b6eb652fef28920c117d366339687bd5576160db0f76"
"checksum redox_users 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3fe5204c3a17e97dde73f285d49be585df59ed84b50a872baf416e73b62c3828"
"checksum regex 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "53ee8cfdddb2e0291adfb9f13d31d3bbe0a03c9a402c01b1e24188d86c35b24f"
"checksum regex-syntax 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)" = "8c2f35eedad5295fdf00a63d7d4b238135723f92b434ec06774dad15c7ab0861"
"checksum remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3488ba1b9a2084d38645c4c08276a1752dcbf2c7130d74f1569681ad5d2799c5"
"checksum reqwest 0.9.12 (registry+https://github.com/rust-lang/crates.io-index)" = "962fa64e670e70b9d3a81c3688832eb59293ef490e0af5ad169763f62016ac5e"
"checksum rpassword 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d37473170aedbe66ffa3ad3726939ba677d83c646ad4fd99e5b4bc38712f45ec"
"checksum rustc-demangle 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "adacaae16d02b6ec37fdc7acfcddf365978de76d1983d3ee22afc260e1ca9619"
"checksum rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)" = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda"
"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"
"checksum ryu 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "eb9e9b8cde282a9fe6a42dd4681319bfb63f121b8a8ee9439c6f4107e58a46f7"
"checksum safemem 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8dca453248a96cb0749e36ccdfe2b0b4e54a61bfef89fb97ec621eb8e0a93dd9"
"checksum same-file 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "8f20c4be53a8a1ff4c1f1b2bd14570d2f634628709752f0702ecdd2b3f9a5267"
"checksum sanakirja 0.10.2 (registry+https://github.com/rust-lang/crates.io-index)" = "85771b7cbe2941ad20fa0f52bbaa2f2417a451f72c24c5afd5f5142e11a96522"
"checksum schannel 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)" = "f2f6abf258d99c3c1c5c2131d99d064e94b7b3dd5f416483057f308fea253339"
"checksum scoped_threadpool 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "1d51f5df5af43ab3f1360b429fa5e0152ac5ce8c0bd6485cae490332e96846a8"
"checksum scopeguard 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "94258f53601af11e6a49f722422f6e3425c52b06245a5cf9bc09908b174f5e27"
"checksum security-framework 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "bfab8dda0e7a327c696d893df9ffa19cadc4bd195797997f5223cf5831beaf05"
"checksum security-framework-sys 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3d6696852716b589dff9e886ff83778bb635150168e83afa8ac6b8a78cb82abc"
"checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403"
"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"
"checksum sequoia-openpgp 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3565c5533b5060b1b99cac0f01b49b6de5d4c92f75342f5ff4ab04dbec62fc4b"
"checksum serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)" = "92514fb95f900c9b5126e32d020f5c6d40564c27a5ea6d1d7d9f157a96623560"
"checksum serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)" = "bb6eabf4b5914e88e24eea240bb7c9f9a2cbc1bbbe8d961d381975ec3c6b806c"
"checksum serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)" = "5a23aa71d4a4d43fdbfaac00eff68ba8a06a51759a89ac3304323e800c4dd40d"
"checksum serde_urlencoded 0.5.4 (registry+https://github.com/rust-lang/crates.io-index)" = "d48f9f99cd749a2de71d29da5f948de7f2764cc5a9d7f3c97e3514d4ee6eabf2"
"checksum sha2 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7b4d8bfd0e469f417657573d8451fb33d16cfe0989359b93baf3a1ffc639543d"
"checksum shell-escape 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "170a13e64f2a51b77a45702ba77287f5c6829375b04a69cf2222acd17d0cfab9"
"checksum siphasher 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "0b8de496cf83d4ed58b6be86c3a275b8602f6ffe98d3024a869e124147a9a3ac"
"checksum slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8"
"checksum smallvec 0.6.9 (registry+https://github.com/rust-lang/crates.io-index)" = "c4488ae950c49d403731982257768f48fada354a5203fe81f9bb6f43ca9002be"
"checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8"
"checksum string 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "b639411d0b9c738748b5397d5ceba08e648f4f1992231aa859af1a017f31f60b"
"checksum string_cache 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)" = "25d70109977172b127fe834e5449e5ab1740b9ba49fa18a2020f509174f25423"
"checksum string_cache_codegen 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1eea1eee654ef80933142157fdad9dd8bc43cf7c74e999e369263496f04ff4da"
"checksum string_cache_shared 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b1884d1bc09741d466d9b14e6d37ac89d6909cbcac41dd9ae982d4d063bbedfc"
"checksum strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bb4f380125926a99e52bc279241539c018323fab05ad6368b56f93d9369ff550"
"checksum syn 0.15.29 (registry+https://github.com/rust-lang/crates.io-index)" = "1825685f977249735d510a242a6727b46efe914bb67e38d30c071b1b72b1d5c2"
"checksum synstructure 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "73687139bf99285483c96ac0add482c3776528beac1d97d444f6e91f203a2015"
"checksum tar 0.4.22 (registry+https://github.com/rust-lang/crates.io-index)" = "c2167ff53da2a661702b3299f71a91b61b1dffef36b4b2884b1f9c67254c0133"
"checksum tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8"
"checksum tempfile 3.0.7 (registry+https://github.com/rust-lang/crates.io-index)" = "b86c784c88d98c801132806dadd3819ed29d8600836c4088e855cdf3e178ed8a"
"checksum term 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "fa63644f74ce96fbeb9b794f66aff2a52d601cbd5e80f4b97123e3899f4570f1"
"checksum term 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5e6b677dd1e8214ea1ef4297f85dbcbed8e8cdddb561040cc998ca2551c37561"
"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 termios 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "d5d9cf598a6d7ce700a4e6a9199da127e6819a61e64b68609683cc9a01b5683a"
"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 thrussh 0.20.7 (registry+https://github.com/rust-lang/crates.io-index)" = "d9b59c9d297b6558822dc1cf588dc4e5745072e451f85ced02a46229de2ae53f"
"checksum thrussh-config 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "304c60927dc25047c61cbcf08dc8cb2cd319f0a32b7ed9a8cf0d7058ff7a7631"
"checksum thrussh-keys 0.11.9 (registry+https://github.com/rust-lang/crates.io-index)" = "5e72f93d9f96aa5ce3f38c1e105c668ce06867b6cdbffe68c261cfb4d59c7066"
"checksum thrussh-libsodium 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "b30fe73a9e5064d27b5ae97da9616ca8f3701499c2dd61a11f2d1e53bd207883"
"checksum time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "db8dcfca086c1143c9270ac42a2bbd8a7ee477b78ac8e45b19abfb0cbede4b6f"
"checksum tokio 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)" = "65641e515a437b308ab131a82ce3042ff9795bef5d6c5a9be4eb24195c417fd9"
"checksum tokio-codec 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5c501eceaf96f0e1793cf26beb63da3d11c738c4a943fdf3746d81d64684c39f"
"checksum tokio-current-thread 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "d16217cad7f1b840c5a97dfb3c43b0c871fef423a6e8d2118c604e843662a443"
"checksum tokio-executor 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "83ea44c6c0773cc034771693711c35c677b4b5a4b21b9e7071704c54de7d555e"
"checksum tokio-fs 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "3fe6dc22b08d6993916647d108a1a7d15b9cd29c4f4496c62b92c45b5041b7af"
"checksum tokio-io 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)" = "5090db468dad16e1a7a54c8c67280c5e4b544f3d3e018f0b913b400261f85926"
"checksum tokio-reactor 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "6af16bfac7e112bea8b0442542161bfc41cbfa4466b580bdda7d18cb88b911ce"
"checksum tokio-sync 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "fda385df506bf7546e70872767f71e81640f1f251bdf2fd8eb81a0eaec5fe022"
"checksum tokio-tcp 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "1d14b10654be682ac43efee27401d792507e30fd8d26389e1da3b185de2e4119"
"checksum tokio-threadpool 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "ec5759cf26cf9659555f36c431b515e3d05f66831741c85b4b5d5dfb9cf1323c"
"checksum tokio-timer 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)" = "2910970404ba6fa78c5539126a9ae2045d62e3713041e447f695f41405a120c6"
"checksum tokio-trace-core 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "350c9edade9830dc185ae48ba45667a445ab59f6167ef6d0254ec9d2430d9dd3"
"checksum tokio-udp 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "66268575b80f4a4a710ef83d087fdfeeabdce9b74c797535fbac18a2cb906e92"
"checksum tokio-uds 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "037ffc3ba0e12a0ab4aca92e5234e0dedeb48fddf6ccd260f1f150a36a9f2445"
"checksum toml 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)" = "758664fc71a3a69038656bee8b6be6477d2a6c315a6b81f7081f591bffa4111f"
"checksum try-lock 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e604eb7b43c06650e854be16a2a03155743d3752dd1c943f6829e26b7a36e382"
"checksum typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "612d636f949607bdf9b123b4a6f6d966dedf3ff669f7f045890d3a4a73948169"
"checksum ucd-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "535c204ee4d8434478593480b8f86ab45ec9aae0e83c568ca81abf0fd0e88f86"
"checksum unicase 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7f4765f83163b74f957c797ad9253caf97f103fb064d3999aea9568d09fc8a33"
"checksum unicase 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "41d17211f887da8e4a70a45b9536f26fc5de166b81e2d5d80de4a17fd22553bd"
"checksum unicode-bidi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "49f2bd0c6468a8230e1db229cff8029217cf623c767ea5d60bfbd42729ea54d5"
"checksum unicode-normalization 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "141339a08b982d942be2ca06ff8b076563cbe223d1befd5450716790d44e2426"
"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 username 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "92e425df6527f7bc1adc7eb3b829ecaec746fbbc0b05e42133ff84afef3b1a09"
"checksum utf8-ranges 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "796f7e48bef87609f7ade7e06495a87d5cd06c7866e6a5cbfceffc558a243737"
"checksum utf8parse 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8772a4ccbb4e89959023bc5b7cb8623a795caa7092d99f3aa9501b9484d4557d"
"checksum uuid 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)" = "600ef8213e9f8a0ac1f876e470e90780ae0478eabce7f76aff41b0f4ef0fd5c0"
"checksum vcpkg 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "def296d3eb3b12371b2c7d0e83bfe1403e4db2d7a0bba324a12b21c4ee13143d"
"checksum vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05c78687fb1a80548ae3250346c3db86a80a7cdd77bda190189f2d0a0987c81a"
"checksum version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd"
"checksum walkdir 2.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "9d9d7ed3431229a144296213105a390676cc49c9b6a72bd19f3176c98e129fa1"
"checksum want 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "797464475f30ddb8830cc529aaaae648d581f99e2036a928877dfde027ddf6b3"
"checksum which 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "e84a603e7e0b1ce1aa1ee2b109c7be00155ce52df5081590d1ffb93f4f515cb2"
"checksum winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a"


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
sanakirja = { path = "../../sanakirja" } # "0.8.16"
toml = "*"
[package]
name = "libpijul"
description = "A patch-based distributed version control system, easy to use and fast."
version = "0.12.0"
authors = ["Pierre-Étienne Meunier","Florent Becker"]
license = "GPL-2.0+"
homepage = "https://pijul.org/"
documentation = "https://docs.rs/libpijul"
repository = "https://nest.pijul.com/pijul_org/pijul"

include = [
  "Cargo.toml", "COPYING",
  "src/copyright",
  "src/record.rs",
  "src/diff.rs",
  "src/unrecord/mod.rs",
  "src/unrecord/context_repair.rs",
  "src/unrecord/edges.rs",
  "src/unrecord/nodes.rs",
  "src/apply/mod.rs",
  "src/apply/apply.rs",
  "src/apply/find_alive.rs",
  "src/apply/repair_deleted_context.rs",
  "src/backend/mod.rs",
  "src/backend/edge.rs",
  "src/backend/file_header.rs",
  "src/backend/file_id.rs",
  "src/backend/hash.rs",
  "src/backend/inode.rs",
  "src/backend/key.rs",
  "src/backend/patch_id.rs",
  "src/backend/small_string.rs",
  "src/patch/mod.rs",
  "src/patch/pretty.rs",
  "src/lib.rs",
  "src/error.rs",
  "src/log",
  "src/graph.rs",
  "src/graph/dfs.rs",
  "src/output.rs",
  "src/conflict.rs",
  "src/file_operations.rs",
  "src/fs_representation.rs",
  "src/status.rs"
]

[dependencies]
bitflags = "1.0"
byteorder = "1.3"
flate2 = "1.0"
log = "0.4"
rand = "0.6"
sanakirja = "0.10"
chrono = { version = "0.4", features = [ "serde" ] }
serde = "1.0"
serde_derive = "1.0"
bincode = "1.1"
hex = "0.3"
tempdir = "0.3"
bs58 = "0.2"
base64 = "0.10"
ignore = "0.4"
serde_json = "1.0"
openssl = "0.10"
toml = "0.4"
sequoia-openpgp = "0.4"
failure = "0.1"
diffs = "0.3.0"



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
            self.iter_nodes(&branch, Some((to, Some(edge))))
            self.iter_nodes(&branch, Some((to, Some(edge))))
                .map(|(_, x)| x)
use backend::*;
use patch::*;
use rand;
use std::collections::HashSet;
use Result;

impl<'env, T: rand::Rng> MutTxn<'env, T> {
    /// Applies a patch to a repository. "new_patches" are patches that
    /// just this repository has, and the remote repository doesn't have.
    pub fn apply(
        &mut self,
        branch: &mut Branch,
        patch: &Patch,
        patch_id: PatchId,
        timestamp: ApplyTimestamp,
    ) -> Result<()> {
        assert!(self.put_patches(&mut branch.patches, patch_id, timestamp)?);
        assert!(self.put_revpatches(&mut branch.revpatches, timestamp, patch_id)?);
        debug!("apply_raw");
        // Here we need to first apply *all* the NewNodes, and then
        // the Edges, because some of the NewNodes might be the
        // children of newly deleted edges, and we need to add the
        // corresponding pseudo-edges.
        for ch in patch.changes().iter() {
            if let Change::NewNodes {
                ref up_context,
                ref down_context,
                ref line_num,
                flag,
                ref nodes,
                ..
            } = *ch
            {
                assert!(!nodes.is_empty());
                debug!("apply: newnodes");
                self.add_new_nodes(
                    branch,
                    patch_id,
                    up_context,
                    down_context,
                    line_num,
                    flag,
                    nodes,
                )?;
            }
        }
        let mut parents: HashSet<Key<PatchId>> = HashSet::new();
        let mut children: HashSet<Edge> = HashSet::new();
        for ch in patch.changes().iter() {
            if let Change::NewEdges {
                previous,
                flag,
                ref edges,
                ..
            } = *ch
            {
                self.add_new_edges(
                    branch,
                    patch_id,
                    Some(previous),
                    flag,
                    edges,
                    &mut parents,
                    &mut children,
                )?;
                debug!("apply_raw:edges.done");
            }
        }

        // If there is a missing context, add pseudo-edges along the
        // edges that deleted the conflict, until finding (in both
        // directions) an alive context.
        self.repair_deleted_contexts(branch, patch, patch_id)?;

        Ok(())
    }

    /// Delete old versions of `edges`.
    fn delete_old_edge(
        &mut self,
        branch: &mut Branch,
        patch_id: PatchId,
        previous: EdgeFlags,
        from: Key<PatchId>,
        to: Key<PatchId>,
        introduced_by: PatchId,
    ) -> Result<()> {
        debug!(
            "delete {:?} -> {:?} ({:?}) {:?}",
            from, to, previous, introduced_by
        );
        // debug!("delete_old_edges: introduced_by = {:?}", e.introduced_by);
        let mut deleted_e = Edge {
            flag: previous,
            dest: to,
            introduced_by,
        };
        self.put_cemetery(from, &deleted_e, patch_id)?;
        self.put_cemetery(from, deleted_e, patch_id)?;
        if !self.del_edge_both_dirs(branch, from, deleted_e)? {
            debug!("killing pseudo instead {:?} {:?}", from, deleted_e);
            deleted_e.flag |= EdgeFlags::PSEUDO_EDGE;
            let result = self.del_edge_both_dirs(branch, from, deleted_e)?;
            debug!("killed ? {:?}", result);
        }
        Ok(())
    }

    fn add_new_edges(
        &mut self,
        branch: &mut Branch,
        patch_id: PatchId,
        previous: Option<EdgeFlags>,
        flag: EdgeFlags,
        edges: &[NewEdge],
        parents: &mut HashSet<Key<PatchId>>,
        children: &mut HashSet<Edge>,
    ) -> Result<()> {
        for e in edges {
            debug!("add_new_edges {:?}", e);
            // If the edge has not been forgotten about,
            // insert the new version.
            let e_from = self.internal_key(&e.from, patch_id);
            let e_to = self.internal_key(&e.to, patch_id);
            assert!(e_from != e_to);
            let to = if flag.contains(EdgeFlags::PARENT_EDGE) {
                e_from
            } else {
                e_to
            };

            // If this is a deletion edge and not a folder edge, reconnect parents and children.
            if flag.contains(EdgeFlags::DELETED_EDGE) && !flag.contains(EdgeFlags::FOLDER_EDGE) {
                self.reconnect_parents_children(branch, patch_id, to, parents, children)?;
            }

            let introduced_by = self.internal_hash(&e.introduced_by, patch_id);

            if let Some(previous) = previous {
                self.delete_old_edge(branch, patch_id, previous, e_from, e_to, introduced_by)?
            }

            if flag.contains(EdgeFlags::DELETED_EDGE) && !flag.contains(EdgeFlags::FOLDER_EDGE) {
                self.delete_old_pseudo_edges(branch, patch_id, to, children)?
            }

            // Let's build the edge we're about to insert.
            let e = Edge {
                flag,
                dest: e_to,
                introduced_by: patch_id.clone(),
            };

            // Finally, add the new version of the edge.
            self.put_edge_both_dirs(branch, e_from, e)?;
        }
        Ok(())
    }

    /// Add pseudo edges from all keys of `parents` to all `dest` of
    /// the edges in `children`, with the same edge flags as in
    /// `children`, plus `PSEUDO_EDGE`.
    pub fn reconnect_parents_children(
        &mut self,
        branch: &mut Branch,
        patch_id: PatchId,
        to: Key<PatchId>,
        parents: &mut HashSet<Key<PatchId>>,
        children: &mut HashSet<Edge>,
    ) -> Result<()> {
        // Collect all the alive parents of the source of this edge.
        parents.clear();
        parents.extend(
            self.iter_nodes(&branch, Some((to, Some(&edge))))
            self.iter_adjacent(
                &branch,
                to,
                EdgeFlags::PARENT_EDGE,
                EdgeFlags::PARENT_EDGE | EdgeFlags::PSEUDO_EDGE,
            )
            .filter_map(|v| {
                if !v.flag.contains(EdgeFlags::EPSILON_EDGE)
                    && self.is_alive_or_zombie(branch, v.dest)
                {
                    Some(v.dest)
                } else {
                    None
                }
            }),
        );

        // Now collect all the alive children of the target of this edge.
        children.clear();
        children.extend(self.iter_adjacent(
            &branch,
            to,
            EdgeFlags::empty(),
            EdgeFlags::PSEUDO_EDGE | EdgeFlags::FOLDER_EDGE,
        ));

        debug!("reconnecting {:?} {:?}", parents, children);

        for &parent in parents.iter() {
            for e in children.iter() {
                // If these are not already connected
                // or pseudo-connected, add a
                // pseudo-edge.
                if parent != e.dest && !self.is_connected(branch, parent, e.dest) {
                    let pseudo_edge = Edge {
                        flag: e.flag | EdgeFlags::PSEUDO_EDGE,
                        dest: e.dest,
                        introduced_by: patch_id.clone(),
                    };
                    debug!("reconnect_parents_children: {:?} {:?}", parent, pseudo_edge);
                    self.put_edge_both_dirs(branch, parent, pseudo_edge)?;
                }
            }
        }
        Ok(())
    }

    fn delete_old_pseudo_edges(
        &mut self,
        branch: &mut Branch,
        patch_id: PatchId,
        to: Key<PatchId>,
        pseudo_edges: &mut HashSet<Edge>,
    ) -> Result<()> {
        // Now collect pseudo edges, and delete them.
        pseudo_edges.clear();
        for to_edge in self
            .iter_adjacent(branch, to, EdgeFlags::empty(), EdgeFlags::DELETED_EDGE)
            .filter(|v| v.flag.contains(EdgeFlags::PSEUDO_EDGE))
        {
            // Is this pseudo-edge a zombie marker? I.e. is there a
            // deleted edge in parallel of it? Since we haven't yet
            // introduced the new deleted edge, there is no possible
            // risk of confusion here.
            let mut e = Edge::zero(
                EdgeFlags::DELETED_EDGE
                    | (to_edge.flag & (EdgeFlags::PARENT_EDGE | EdgeFlags::FOLDER_EDGE)),
            );
            e.dest = to_edge.dest;
            let mut is_zombie_marker = to_edge.introduced_by != patch_id
                && (match self.iter_nodes(branch, Some((to, Some(&e)))).next() {
                && (match self.iter_nodes(branch, Some((to, Some(e)))).next() {
                    Some((k, v)) if k == to && v.dest == e.dest && v.flag == e.flag => {
                        v.introduced_by != patch_id
                    }
                    _ => false,
                });
            debug!(
                "is_zombie_marker {:?}: {:?}",
                to_edge.dest, is_zombie_marker
            );
            if !is_zombie_marker {
                // This edge is not a zombie marker, we can delete it.
                pseudo_edges.insert(*to_edge);
                pseudo_edges.insert(to_edge);
            }




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
                for (_, v) in self.iter_nodes(&branch, Some((a, Some(e))))
                    for (_, v) in self.iter_nodes(&branch, Some((a, Some(e))))
                for (_, v) in self.iter_nodes(&branch, Some((a, Some(e))))
                for (_, e) in self.iter_nodes(branch, Some((current, Some(e))))
use backend::*;
use std::collections::HashSet;

#[derive(Debug)]
pub struct FindAlive {
    stack: Vec<Key<PatchId>>,
    visited: HashSet<Key<PatchId>>,
}

impl FindAlive {
    pub fn new() -> Self {
        FindAlive {
            stack: Vec::new(),
            visited: HashSet::new(),
        }
    }
    pub fn clear(&mut self) {
        self.stack.clear();
        self.visited.clear();
    }
    pub fn push(&mut self, k: Key<PatchId>) {
        self.stack.push(k)
    }
    pub fn pop(&mut self) -> Option<Key<PatchId>> {
        while let Some(p) = self.stack.pop() {
            if !self.visited.contains(&p) {
                self.visited.insert(p.clone());
                return Some(p);
            }
        }
        None
    }
}

impl<U: Transaction, R> GenericTxn<U, R> {
    /// Recursively find all ancestors by doing a DFS, and collect all
    /// edges until finding an alive ancestor.
    ///
    /// Returns whether or not at least one traversed vertex was dead
    /// (or otherwise said, returns `false` if and only if there all
    /// vertices in `find_alive` are alive).
    pub fn find_alive_ancestors(
        &self,
        find_alive: &mut FindAlive,
        branch: &Branch,
        alive: &mut Vec<Key<PatchId>>,
        file_ancestor: &mut Option<Key<PatchId>>,
        files: &mut Vec<(Key<PatchId>, Edge)>,
    ) -> bool {
        let mut first_is_alive = false;
        let mut file = None;
        while let Some(a) = find_alive.pop() {
            if self.is_alive(branch, a) {
                // This node is alive.
                alive.push(a);
            } else {
                first_is_alive = true;
                for v in self.iter_adjacent(
                    &branch,
                    a,
                    EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE,
                    EdgeFlags::all(),
                ) {
                    debug!("find_alive_ancestors: {:?}", v);
                    if v.flag.contains(EdgeFlags::FOLDER_EDGE) {
                        // deleted file.
                        file = Some(a);
                        *file_ancestor = Some(a)
                    } else {
                        find_alive.push(v.dest)
                    }
                }
            }
        }
        debug!("file {:?}", file);
        if let Some(file) = file {
            find_alive.clear();
            find_alive.push(file);
            while let Some(a) = find_alive.pop() {
                debug!("file {:?}", a);
                if !self.is_alive(branch, a) {
                    debug!("not alive");
                    first_is_alive = true;
                    let flag =
                        EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE | EdgeFlags::FOLDER_EDGE;
                    for v in self.iter_adjacent(&branch, a, flag, EdgeFlags::all()) {
                        debug!("file find_alive_ancestors: {:?}", v);
                        // deleted file, collect.
                        files.push((a, *v));
                        files.push((a, v));
                        find_alive.push(v.dest)


                if self.iter_nodes(&branch, Some((header.key, Some(edge))))
                if self.iter_nodes(&branch, Some((header.key, Some(edge))))


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
        for (_, v) in self.iter_nodes(branch, Some((context, Some(e))))
        for (_, v) in self.iter_nodes(branch, Some((context, Some(e))))
use apply::find_alive::*;
use backend::*;
use patch::*;
use rand;
use std::collections::HashSet;
use Result;

impl<'env, T: rand::Rng> MutTxn<'env, T> {
    /// Deleted contexts are conflicts. Reconnect the graph by
    /// inserting pseudo-edges alongside deleted edges.
    pub(in apply) fn repair_deleted_contexts(
        &mut self,
        branch: &mut Branch,
        patch: &Patch,
        patch_id: PatchId,
    ) -> Result<()> {
        let mut alive = Vec::new();
        let mut files = Vec::new();
        let mut find_alive = FindAlive::new();
        // repair_missing_context adds all zombie edges needed.
        for ch in patch.changes().iter() {
            match *ch {
                Change::NewEdges {
                    flag, ref edges, ..
                } => {
                    if !flag.contains(EdgeFlags::DELETED_EDGE) {
                        self.repair_context_nondeleted(
                            branch,
                            patch_id,
                            edges,
                            flag,
                            &mut find_alive,
                            &mut alive,
                            &mut files,
                        )?
                    } else {
                        self.repair_context_deleted(
                            branch,
                            patch_id,
                            edges,
                            flag,
                            &mut find_alive,
                            &mut alive,
                            &mut files,
                            patch.dependencies(),
                        )?
                    }
                }
                Change::NewNodes {
                    ref up_context,
                    ref down_context,
                    flag,
                    ..
                } => {
                    debug!("repairing missing contexts for newnodes");
                    // If not all lines in `up_context` are alive, this
                    // is a conflict, repair.
                    for c in up_context {
                        let c = self.internal_key(c, patch_id);

                        // Is the up context deleted by another patch, and the
                        // deletion was not also confirmed by this patch?

                        let up_context_deleted = self.was_context_deleted(branch, patch_id, c);
                        debug!(
                            "up_context_deleted: patch_id = {:?} context = {:?} up_context_deleted = {:?}",
                            patch_id, c, up_context_deleted
                        );
                        if up_context_deleted {
                            self.repair_missing_up_context(
                                &mut find_alive,
                                branch,
                                c,
                                flag,
                                &mut alive,
                                &mut files,
                                &[patch_id],
                            )?
                        }
                    }
                    // If not all lines in `down_context` are alive,
                    // this is a conflict, repair.
                    for c in down_context {
                        let c = self.internal_key(c, patch_id);
                        let down_context_deleted = self.was_context_deleted(branch, patch_id, c);
                        debug!("down_context_deleted: {:?}", down_context_deleted);
                        if down_context_deleted {
                            self.repair_missing_down_context(
                                &mut find_alive,
                                branch,
                                c,
                                &mut alive,
                                &[patch_id],
                            )?
                        }
                    }
                    debug!("apply: newnodes, done");
                }
            }
        }
        Ok(())
    }

    /// This function handles the case where we're adding an alive
    /// edge, and the origin or destination (or both) of this edge is
    /// dead in the graph.
    fn repair_context_nondeleted(
        &mut self,
        branch: &mut Branch,
        patch_id: PatchId,
        edges: &[NewEdge],
        flag: EdgeFlags,
        find_alive: &mut FindAlive,
        alive: &mut Vec<Key<PatchId>>,
        files: &mut Vec<(Key<PatchId>, Edge)>,
    ) -> Result<()> {
        debug!("repairing missing contexts for non-deleted edges");
        for e in edges {
            let (up_context, down_context) = if flag.contains(EdgeFlags::PARENT_EDGE) {
                (
                    self.internal_key(&e.to, patch_id),
                    self.internal_key(&e.from, patch_id),
                )
            } else {
                (
                    self.internal_key(&e.from, patch_id),
                    self.internal_key(&e.to, patch_id),
                )
            };

            if self.was_context_deleted(branch, patch_id, up_context) {
                self.repair_missing_up_context(
                    find_alive,
                    branch,
                    up_context,
                    flag,
                    alive,
                    files,
                    &[patch_id],
                )?
            }
            if self.was_context_deleted(branch, patch_id, down_context) {
                self.repair_missing_down_context(
                    find_alive,
                    branch,
                    down_context,
                    alive,
                    &[patch_id],
                )?
            }
        }
        Ok(())
    }

    /// Handle the case where we're inserting a deleted edge, but the
    /// source or target (or both) does not know about (at least one
    /// of) its adjacent edges.
    fn repair_context_deleted(
        &mut self,
        branch: &mut Branch,
        patch_id: PatchId,
        edges: &[NewEdge],
        flag: EdgeFlags,
        find_alive: &mut FindAlive,
        alive: &mut Vec<Key<PatchId>>,
        files: &mut Vec<(Key<PatchId>, Edge)>,
        dependencies: &HashSet<Hash>,
    ) -> Result<()> {
        debug!("repairing missing contexts for deleted edges");
        debug_assert!(flag.contains(EdgeFlags::DELETED_EDGE));

        for e in edges {
            let dest = if flag.contains(EdgeFlags::PARENT_EDGE) {
                self.internal_key(&e.from, patch_id)
            } else {
                self.internal_key(&e.to, patch_id)
            };

            debug!("dest = {:?}", dest);

            // If there is at least one unknown child, repair the
            // context.
            let mut unknown_children = Vec::new();
            for (k, v) in self.iter_nodes(branch, Some((dest, None))) {
                if k != dest
                    || v.flag | EdgeFlags::FOLDER_EDGE
                        > EdgeFlags::PSEUDO_EDGE | EdgeFlags::EPSILON_EDGE | EdgeFlags::FOLDER_EDGE
                {
                    break;
                }
                if v.introduced_by != patch_id && {
                    let ext = self.external_hash(v.introduced_by).to_owned();
                    !dependencies.contains(&ext)
                } {
                    unknown_children.push(v.introduced_by)
                }

                debug!(
                    "child is_unknown({}): {:?} {:?}",
                    line!(),
                    v,
                    unknown_children
                );
            }

            if !unknown_children.is_empty() {
                self.repair_missing_up_context(
                    find_alive,
                    branch,
                    dest,
                    flag,
                    alive,
                    files,
                    &unknown_children,
                )?;
            }

            // If there is at least one alive parent we don't know
            // about, repair.
            let e = Edge::zero(EdgeFlags::PARENT_EDGE);
            unknown_children.clear();
            let mut unknown_parents = unknown_children;
            for (k, v) in self.iter_nodes(branch, Some((dest, Some(e)))) {
                if k != dest


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
use byteorder::{LittleEndian, ByteOrder};
            introduced_by: PatchId(LittleEndian::read_u64(&s[17..]))
use super::key::*;
use super::patch_id::*;
use byteorder::{ByteOrder, LittleEndian};
use sanakirja::*;
use std;

bitflags! {
    /// Possible flags of edges.
    ///
    /// Possible values are `PSEUDO_EDGE`, `FOLDER_EDGE`,
    /// `PARENT_EDGE` and `DELETED_EDGE`.
    #[derive(Serialize, Deserialize)]
    pub struct EdgeFlags: u8 {
        /// A pseudo-edge, computed when applying the patch to
        /// restore connectivity, and/or mark conflicts.
        const PSEUDO_EDGE = 1;
        /// An edge encoding file system hierarchy.
        const FOLDER_EDGE = 2;
        /// An epsilon-edge, i.e. a "non-transitive" edge used to
        /// solve conflicts.
        const EPSILON_EDGE = 4;
        /// A "reverse" edge (all edges in the graph have a reverse edge).
        const PARENT_EDGE = 8;
        /// An edge whose target (if not also `PARENT_EDGE`) or
        /// source (if also `PARENT_EDGE`) is marked as deleted.
        const DELETED_EDGE = 16;
    }
}

/// The target half of an edge in the repository graph.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(packed)]
pub struct Edge {
    /// Flags of this edge.
    pub flag: EdgeFlags,
    /// Target of this edge.
    pub dest: Key<PatchId>,
    /// Patch that introduced this edge (possibly as a
    /// pseudo-edge, i.e. not explicitly in the patch, but
    /// computed from it).
    pub introduced_by: PatchId,
}
impl Edge {
    /// Create an edge with the flags set to `flags`, and other
    /// parameters to 0.
    pub fn zero(flag: EdgeFlags) -> Edge {
        Edge {
            flag: flag,
            dest: ROOT_KEY.clone(),
            introduced_by: ROOT_PATCH_ID.clone(),
        }
    }
    #[doc(hidden)]
    pub fn to_unsafe(&self) -> UnsafeEdge {
        UnsafeEdge(self)
    }
    #[doc(hidden)]
    pub unsafe fn from_unsafe<'a>(p: UnsafeEdge) -> &'a Edge {
        &*p.0
    }
}

#[derive(Clone, Copy)]
pub struct UnsafeEdge(*const Edge);

impl std::fmt::Debug for UnsafeEdge {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        unsafe { Edge::from_unsafe(*self).fmt(fmt) }
    }
    }
}

impl Representable for UnsafeEdge {
impl Representable for Edge {
    fn alignment() -> Alignment {
        Alignment::B1
    }
    fn onpage_size(&self) -> u16 {
        std::mem::size_of::<Edge>() as u16
    }
    unsafe fn write_value(&self, p: *mut u8) {
        trace!("write_value {:?}", p);
        std::ptr::copy(self.0, p as *mut Edge, 1)
        let s = std::slice::from_raw_parts_mut(p, 25);
        s[0] = (*self).flag.bits();
        LittleEndian::write_u64(&mut s[1..], (*self).dest.patch.0);
        LittleEndian::write_u64(&mut s[9..], (*self).dest.line.0);
        LittleEndian::write_u64(&mut s[17..], (*self).introduced_by.0);
    }
    unsafe fn read_value(p: *const u8) -> Self {
        trace!("read_value {:?}", p);
        UnsafeEdge(p as *const Edge)
        let s = std::slice::from_raw_parts(p, 25);
        Edge {
            flag: EdgeFlags::from_bits(s[0]).unwrap(),
            dest: Key {
                patch: PatchId(LittleEndian::read_u64(&s[1..])),
                line: LineId(LittleEndian::read_u64(&s[9..])),
            },
            introduced_by: PatchId(LittleEndian::read_u64(&s[17..])),
        }
    }
    unsafe fn cmp_value<T>(&self, _: &T, x: Self) -> std::cmp::Ordering {
        let a: &Edge = &*self.0;
        let b: &Edge = &*x.0;
        let a: &Edge = self;
        let b: &Edge = &x;
        a.cmp(b)


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
use Error;
            UnsafeHash::Recursive { len, .. } => len as u16,
use bs58;
use byteorder::{ByteOrder, LittleEndian};
use sanakirja::{Alignment, Representable};
use serde;
use serde::de::{Deserialize, Deserializer, Visitor};
use serde::ser::{Serialize, Serializer};
use std;
use {Error, LineId};

const SHA512_BYTES: usize = 512 / 8;

/// The external hash of patches.
#[derive(Serialize, Deserialize, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub enum Hash {
    /// None is the hash of the "null patch", which introduced a
    /// single root vertex at the beginning of the repository.
    None,
    /// Patch hashed using the SHA2-512 algorithm.
    Sha512(Sha512),
    /// Recursive patch hashes (patches written as text in the repository).
    Recursive(Recursive),
}

#[derive(Serialize, Deserialize, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub struct Recursive(Vec<u8>);

impl Recursive {
    pub fn patch(&self) -> HashRef {
        match unsafe { std::mem::transmute(self.0[0]) } {
            Algorithm::None => HashRef::None,
            Algorithm::Sha512 => HashRef::Sha512(&self.0[1..self.0.len() - 8]),
            Algorithm::Recursive => HashRef::Recursive(&self.0[1..self.0.len() - 8]),
        }
    }
    pub fn line(&self) -> LineId {
        match unsafe { std::mem::transmute(self.0[0]) } {
            Algorithm::None => LineId(0),
            Algorithm::Sha512 => LineId(LittleEndian::read_u64(&self.0[self.0.len() - 8..])),
            Algorithm::Recursive => LineId(LittleEndian::read_u64(&self.0[self.0.len() - 8..])),
        }
    }
}

impl Hash {
    pub fn recursive(&self, line: LineId) -> Self {
        match *self {
            Hash::None => Hash::Recursive(Recursive(vec![Algorithm::None as u8])),
            Hash::Sha512(ref p) => {
                let mut v = Vec::new();
                v.push(Algorithm::Sha512 as u8);
                v.extend(&p.0[..]);
                v.extend(b"\0\0\0\0\0\0\0\0");
                LittleEndian::write_u64(&mut v[SHA512_BYTES..], line.0);
                Hash::Recursive(Recursive(v))
            }
            Hash::Recursive(Recursive(ref p)) => {
                let mut v = Vec::new();
                v.push(Algorithm::Recursive as u8);
                v.extend(p);
                v.extend(b"\0\0\0\0\0\0\0\0");
                LittleEndian::write_u64(&mut v[p.len()..], line.0);
                Hash::Recursive(Recursive(v))
            }
        }
    }
}

pub struct Sha512(pub [u8; SHA512_BYTES]);

impl PartialEq for Sha512 {
    fn eq(&self, h: &Sha512) -> bool {
        (&self.0[..]).eq(&h.0[..])
    }
}
impl Eq for Sha512 {}
impl PartialOrd for Sha512 {
    fn partial_cmp(&self, h: &Sha512) -> Option<std::cmp::Ordering> {
        (&self.0[..]).partial_cmp(&h.0[..])
    }
}
impl Ord for Sha512 {
    fn cmp(&self, h: &Sha512) -> std::cmp::Ordering {
        (&self.0[..]).cmp(&h.0[..])
    }
}

impl std::hash::Hash for Sha512 {
    fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
        (&self.0[..]).hash(h)
    }
}

struct Sha512Visitor;
impl<'a> Visitor<'a> for Sha512Visitor {
    type Value = Sha512;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(formatter, "A byte slice of length {}", SHA512_BYTES)
    }

    fn visit_bytes<E: serde::de::Error>(self, v: &[u8]) -> Result<Self::Value, E> {
        let mut x: [u8; SHA512_BYTES] = [0; SHA512_BYTES];
        x.copy_from_slice(v);
        Ok(Sha512(x))
    }
}

impl<'a> Deserialize<'a> for Sha512 {
    fn deserialize<D: Deserializer<'a>>(d: D) -> Result<Sha512, D::Error> {
        d.deserialize_bytes(Sha512Visitor)
    }
}

impl Serialize for Sha512 {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_bytes(&self.0[..])
    }
}

impl std::fmt::Debug for Sha512 {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        (&self.0[..]).fmt(fmt)
    }
}
impl<'a> std::fmt::Debug for HashRef<'a> {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "{}", self.to_base58())
    }
}
impl std::fmt::Debug for Hash {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.as_ref().fmt(fmt)
    }
}

/// A borrowed version of `Hash`.
#[derive(Copy, Clone, Hash, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum HashRef<'a> {
    None,
    Sha512(&'a [u8]),
    Recursive(&'a [u8]),
}

impl Hash {
    /// Get a `Hash` from a binary slice. This function does not
    /// compute the digest of anything, it just converts types.
    pub fn from_binary(v: &[u8]) -> Option<Self> {
        if v.len() == 0 {
            None
        } else {
            if v[0] == Algorithm::Sha512 as u8 && v.len() == 1 + SHA512_BYTES {
                let mut hash = [0; SHA512_BYTES];
                hash.clone_from_slice(&v[1..]);
                Some(Hash::Sha512(Sha512(hash)))
            } else if v[0] == Algorithm::None as u8 && v.len() == 1 {
                Some(Hash::None)
            } else {
                None
            }
        }
    }

    /// Decode a hash from a base58-encoded `str`.
    pub fn from_base58(base58: &str) -> Option<Self> {
        if let Ok(v) = bs58::decode(base58).into_vec() {
            Self::from_binary(&v)
        } else {
            None
        }
    }

    /// This hash as a slice (nonempty iff SHA512). This method
    /// might disappear when new hashes are introduced.
    pub fn as_slice(&self) -> &[u8] {
        match *self {
            Hash::None => &[],
            Hash::Sha512(ref e) => &e.0,
        }
        }
    }

    /// A borrowed version of this `Hash`, used for instance to
    /// query the databases.
    pub fn as_ref(&self) -> HashRef {
    pub fn as_hash_ref(&self) -> HashRef {
        match *self {
            Hash::None => HashRef::None,
            Hash::Sha512(ref e) => HashRef::Sha512(unsafe {
                std::slice::from_raw_parts(e.0.as_ptr() as *const u8, SHA512_BYTES)
            }),
            Hash::Recursive(Recursive(ref p)) => HashRef::Recursive(p.as_slice()),
        }
    }

    pub fn as_ref(&self) -> HashRef {
        self.as_hash_ref()
    }

    /// Create a `Hash` from the binary slice of the patch contents.
    pub fn of_slice(buf: &[u8]) -> Result<Hash, Error> {
        use openssl::hash::*;
        let hash = {
            let mut hasher = Hasher::new(MessageDigest::sha512())?;
            hasher.update(buf)?;
            hasher.finish()?
        };
        let mut digest: [u8; SHA512_BYTES] = [0; SHA512_BYTES];
        digest.clone_from_slice(hash.as_ref());
        Ok(Hash::Sha512(Sha512(digest)))
    }
}

impl<'a> HashRef<'a> {
    /// Encode this `HashRef` in binary.
    pub fn to_binary(&self) -> Vec<u8> {
        let u = self.to_unsafe();
        let mut v = vec![0; u.onpage_size() as usize];
        unsafe { u.write_value(v.as_mut_ptr()) }
        v
    }

    /// Encode this `HashRef` in base58.
    pub fn to_base58(&self) -> String {
        bs58::encode(&self.to_binary()).into_string()
    }
}
impl Hash {
    /// Encode this `Hash` in base64.
    pub fn to_base58(&self) -> String {
        self.as_ref().to_base58()
    }
}

impl<'a> HashRef<'a> {
    /// Build an owned version of a `HashRef`.
    pub fn to_owned(&self) -> Hash {
        match *self {
            HashRef::None => Hash::None,
            HashRef::Sha512(e) => {
                let mut hash = [0; SHA512_BYTES];
                unsafe {
                    std::ptr::copy_nonoverlapping(
                        e.as_ptr() as *const u8,
                        hash.as_mut_ptr() as *mut u8,
                        SHA512_BYTES,
                    )
                }
                Hash::Sha512(Sha512(hash))
            }
            HashRef::Recursive(p) => Hash::Recursive(Recursive(p.to_vec())),
        }
    }
}

impl Clone for Hash {
    fn clone(&self) -> Self {
        self.as_ref().to_owned()
    }
}

pub const ROOT_HASH: &'static Hash = &Hash::None;

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
#[repr(u8)]
pub enum Algorithm {
    None = 0,
    Sha512 = 1,
    Recursive = 2,
}

#[derive(Clone, Copy, Debug)]
pub enum UnsafeHash {
    None,
    Sha512(*const u8),
    Recursive { ptr: *const u8, len: usize },
}

impl<'a> HashRef<'a> {
    pub fn to_unsafe(&self) -> UnsafeHash {
        match *self {
            HashRef::None => UnsafeHash::None,
            HashRef::Sha512(e) => UnsafeHash::Sha512(e.as_ptr()),
            HashRef::Recursive(p) => UnsafeHash::Recursive {
                ptr: p.as_ptr(),
                len: p.len(),
            },
        }
    }
    pub unsafe fn from_unsafe(p: UnsafeHash) -> HashRef<'a> {
        match p {
            UnsafeHash::None => HashRef::None,
            UnsafeHash::Sha512(p) => HashRef::Sha512(std::slice::from_raw_parts(p, SHA512_BYTES)),
            UnsafeHash::Recursive { ptr, len } => {
                HashRef::Recursive(std::slice::from_raw_parts(ptr, len))
            }
        }
    }
}

impl Representable for UnsafeHash {
    fn alignment() -> Alignment {
        Alignment::B1
    }

    fn onpage_size(&self) -> u16 {
        1 + (match *self {
            UnsafeHash::Sha512(_) => 64,
            UnsafeHash::None => 0,
            UnsafeHash::Recursive { len, .. } => len as u16,
        })
    }
    unsafe fn write_value(&self, p: *mut u8) {
        trace!("write_value {:?} {:?}", self, p);
        match *self {
            UnsafeHash::Sha512(q) => {
                *p = Algorithm::Sha512 as u8;
                std::ptr::copy(q, p.offset(1), 64)
            }
            UnsafeHash::None => *p = Algorithm::None as u8,
            UnsafeHash::Recursive { ptr, len } => {
                *p = Algorithm::Recursive as u8;
                std::ptr::copy(ptr, p.offset(1), len)
            }
        }
    }
    unsafe fn read_value(p: *const u8) -> Self {
        trace!("read_value {:?} {:?}", p, *p);
        match std::mem::transmute(*p) {
            Algorithm::Sha512 => UnsafeHash::Sha512(p.offset(1)),
            Algorithm::None => UnsafeHash::None,
            Algorithm::Recursive => {
                let rec = Self::read_value(p.offset(1));
                UnsafeHash::Recursive {
                    ptr: p.offset(1),
                    len: rec.onpage_size() as usize,
                }
            }
        }
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
use super::patch_id::*;
use Hash;
use bs58;
use sanakirja::{Alignment, Representable};
use std;
use Hash;

const LINE_ID_SIZE: usize = 8;
pub const KEY_SIZE: usize = PATCH_ID_SIZE + LINE_ID_SIZE;

/// The node at the root of the repository graph.
pub const ROOT_KEY: Key<PatchId> = Key {
    patch: ROOT_PATCH_ID,
    line: LineId([0; LINE_ID_SIZE]),
    line: LineId(0),
};

use hex::ToHex;
use std::fmt::Write;
impl ToHex for Key<PatchId> {
    fn write_hex<W: Write>(&self, w: &mut W) -> std::fmt::Result {
        self.patch.write_hex(w)?;
        self.line.write_hex(w)
    }
    fn write_hex_upper<W: Write>(&self, w: &mut W) -> std::fmt::Result {
        self.patch.write_hex(w)?;
        self.line.write_hex(w)
    }
}

impl Key<PatchId> {
    pub fn to_base58(&self) -> String {
        self.patch.to_base58() + &bs58::encode(&self.line.0).into_string()
        let mut b = self.patch.to_base58();
        let mut x = [0; 8];
        LittleEndian::write_u64(&mut x, self.line.0);
        bs58::encode(&x).into(&mut b);
        b
    }
    pub fn to_hex(&self) -> String {
        let mut s = String::new();
        self.write_hex(&mut s).unwrap();
        s
    }
}

impl Key<Hash> {
    pub fn to_base58(&self) -> String {
        self.patch.to_base58() + &bs58::encode(&self.line.0).into_string()
        let mut b = self.patch.to_base58();
        let mut x = [0; 8];
        LittleEndian::write_u64(&mut x, self.line.0);
        bs58::encode(&x).into(&mut b);
        b
    }
}

impl Key<PatchId> {
    /// Is this the root key? (the root key is all 0s).
    pub fn is_root(&self) -> bool {
        self == &ROOT_KEY
    }

    /// Decode this key from its hexadecimal representation.
    pub fn from_hex(hex: &str) -> Option<Self> {
        let mut s = [0; KEY_SIZE];
        if super::from_hex(hex, &mut s) {
            Some(Key {
                patch: PatchId(LittleEndian::read_u64(&s[..8])),
                line: LineId(LittleEndian::read_u64(&s[8..])),
            })
        } else {
            None
        }
    }
}

// A LineId contains a counter encoded little-endian, so that it
// can both be deterministically put into a Sanakirja database,
// and passed to standard serializers.

/// An index for file chunks within a patch.
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Serialize, Deserialize)]
pub struct LineId([u8; LINE_ID_SIZE]);
pub struct LineId(pub u64);

impl ToHex for LineId {
    fn write_hex<W: Write>(&self, w: &mut W) -> std::fmt::Result {
        PatchId(self.0).write_hex(w)
    }
    fn write_hex_upper<W: Write>(&self, w: &mut W) -> std::fmt::Result {
        PatchId(self.0).write_hex_upper(w)
    }
}

impl std::fmt::Debug for LineId {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "LineId(0x{})", self.to_hex())
    }
}

impl LineId {
    /// Creates a new `LineId`, initialized to 0.
    pub fn new() -> LineId {
        LineId([0; LINE_ID_SIZE])
        LineId(0)
    }
    /// Is this line identifier all 0?
    pub fn is_root(&self) -> bool {
        self.0.iter().all(|x| *x == 0)
        self.0 == 0
    }
    pub fn to_hex(&self) -> String {
        let mut s = String::new();
        self.write_hex(&mut s).unwrap();
        s
    }
    pub fn to_base58(&self) -> String {
        let mut x = [0; 8];
        LittleEndian::write_u64(&mut x, self.0);
        let mut b = String::new();
        bs58::encode(&x).into(&mut b);
        b
    }
    pub fn from_base58(s: &str) -> Option<Self> {
        let mut p = [0; 8];
        if bs58::decode(s).into(&mut p).is_ok() {
            Some(LineId(LittleEndian::read_u64(&p)))
        } else {
            None
        }
    }
}
use byteorder::{ByteOrder, LittleEndian};
impl std::ops::Add<usize> for LineId {
    type Output = LineId;
    fn add(self, x: usize) -> Self::Output {
        let a = LittleEndian::read_u64(&self.0);
        let mut b = LineId::new();
        LittleEndian::write_u64(&mut b.0, a + x as u64);
        b
        LineId(self.0 + x as u64)
    }
}
impl std::ops::AddAssign<usize> for LineId {
    fn add_assign(&mut self, x: usize) {
        *self = self.clone() + x
    }
}

/// A node in the repository graph, made of a patch internal
/// identifier, and a line identifier in that patch.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Serialize, Deserialize)]
pub struct Key<H> {
    /// The patch that introduced this node.
    pub patch: H,
    /// The line identifier of the node in that patch. Here,
    /// "line" does not imply anything on the contents of the
    /// chunk.
    pub line: LineId,
}

#[test]
fn test_key_alignment() {
    assert_eq!(std::mem::size_of::<Key<PatchId>>(), 16)
}

impl<T> AsRef<LineId> for Key<T> {
    fn as_ref(&self) -> &LineId {
        &self.line
    }
}

impl<T: Clone> Key<Option<T>> {
    pub fn unwrap_patch(&self) -> Key<T> {
        Key {
            patch: self.patch.as_ref().unwrap().clone(),
            line: self.line.clone(),
        }
    }
}

impl Representable for Key<PatchId> {
    fn alignment() -> Alignment {
        Alignment::B1
    }
    fn onpage_size(&self) -> u16 {
        (PATCH_ID_SIZE + LINE_ID_SIZE) as u16
    }
    unsafe fn write_value(&self, p: *mut u8) {
        trace!("write_value {:?}", p);
        std::ptr::copy(self as *const Key<PatchId> as *const u8, p, KEY_SIZE)
        let p = std::slice::from_raw_parts_mut(p, KEY_SIZE);
        LittleEndian::write_u64(p, self.patch.0);
        LittleEndian::write_u64(&mut p[PATCH_ID_SIZE..], self.line.0);
    }
    unsafe fn read_value(p: *const u8) -> Self {
        trace!("read_value {:?}", p);
        let mut k = std::mem::uninitialized();
        std::ptr::copy(p, (&mut k) as *mut Key<PatchId> as *mut u8, 16);
        k
        let p = std::slice::from_raw_parts(p, KEY_SIZE);
        let patch = LittleEndian::read_u64(p);
        let line = LittleEndian::read_u64(&p[PATCH_ID_SIZE..]);
        Key {
            patch: PatchId(patch),
            line: LineId(line),
        }
    }












1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466

467
468


469
470
471
472

473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599

600
601
602


603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689

690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872






873
874
875
876
877
878
879
880
881
882
883
884
885
886

887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342

1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369

1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385

1386
1387
1388
1389
1390
1391
1392
1393

1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410

1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641


1642
1643
1644
1645
1646
1647
1648


1649
1650
1651
1652

1653
1654
        sanakirja::Db<(self::key::Key<PatchId>, self::edge::Edge), self::patch_id::PatchId>,
    Cursor<'a, T, (Key<PatchId>, Edge), PatchId>,
            self.txn.iter(&branch.db, key.map(|(k, v)| (k, v))),
                .iter(&self.dbs.cemetery, Some(((key, edge), None))),
           .put(&mut self.rng, &mut branch.db, key, edge)?)
        self.put_nodes(branch, key, edge)?;
        self.put_nodes(branch, key, edge)
        edge: Option<Edge>,
            edge,
        self.del_nodes(branch, key, Some(edge))?;
        self.del_nodes(branch, key, Some(edge))
            (key, edge),
use hex;
use rand;
use sanakirja;
use sanakirja::Representable;
pub use sanakirja::Transaction;
use std;
use std::path::Path;
use {Error, Result};

pub use self::patch_id::*;

fn from_hex(hex: &str, s: &mut [u8]) -> bool {
    let hex = hex.as_bytes();
    if hex.len() <= 2 * s.len() {
        let mut i = 0;
        while i < hex.len() {
            let h = hex[i].to_ascii_lowercase();
            if h >= b'0' && h <= b'9' {
                s[i / 2] = s[i / 2] << 4 | (h - b'0')
            } else if h >= b'a' && h <= b'f' {
                s[i / 2] = s[i / 2] << 4 | (h - b'a' + 10)
            } else {
                return false;
            }
            i += 1
        }
        if i & 1 == 1 {
            s[i / 2] = s[i / 2] << 4
        }
        true
    } else {
        false
    }
}
mod edge;
mod file_header;
mod file_id;
mod hash;
mod inode;
mod key;
mod patch_id;
mod small_string;

pub use self::edge::*;
pub use self::file_header::*;
pub use self::file_id::*;
pub use self::hash::*;
pub use self::inode::*;
pub use self::key::*;
pub use self::small_string::*;

pub type NodesDb = sanakirja::Db<self::key::Key<PatchId>, self::edge::UnsafeEdge>;
pub type NodesDb = sanakirja::Db<self::key::Key<PatchId>, self::edge::Edge>;

/// The type of patch application numbers.
pub type ApplyTimestamp = u64;

/// The u64 is the epoch time in seconds when this patch was applied
/// to the repository.
type PatchSet = sanakirja::Db<self::patch_id::PatchId, ApplyTimestamp>;

type RevPatchSet = sanakirja::Db<ApplyTimestamp, self::patch_id::PatchId>;

pub struct Dbs {
    /// A map of the files in the working copy.
    tree: sanakirja::Db<self::file_id::UnsafeFileId, self::inode::Inode>,
    /// The reverse of tree.
    revtree: sanakirja::Db<self::inode::Inode, self::file_id::UnsafeFileId>,
    /// A map from inodes (in tree) to keys in branches.
    inodes: sanakirja::Db<self::inode::Inode, self::file_header::FileHeader>,
    /// The reverse of inodes, minus the header.
    revinodes: sanakirja::Db<self::key::Key<PatchId>, self::inode::Inode>,
    /// Text contents of keys.
    contents: sanakirja::Db<self::key::Key<PatchId>, sanakirja::value::UnsafeValue>,
    /// A map from external patch hashes to internal ids.
    internal: sanakirja::Db<self::hash::UnsafeHash, self::patch_id::PatchId>,
    /// The reverse of internal.
    external: sanakirja::Db<self::patch_id::PatchId, self::hash::UnsafeHash>,
    /// A reverse map of patch dependencies, i.e. (k,v) is in this map
    /// means that v depends on k.
    revdep: sanakirja::Db<self::patch_id::PatchId, self::patch_id::PatchId>,
    /// A map from branch names to graphs.
    branches:
        sanakirja::Db<self::small_string::UnsafeSmallStr, (NodesDb, PatchSet, RevPatchSet, u64)>,
    /// A map of edges to patches that remove them.
    cemetery: sanakirja::Db<(self::key::Key<PatchId>, self::edge::Edge), self::patch_id::PatchId>,
    /// Dependencies
    dep: sanakirja::Db<self::patch_id::PatchId, self::patch_id::PatchId>,
    /// Files touched by patches.
    touched_files: sanakirja::Db<self::key::Key<PatchId>, self::patch_id::PatchId>,
    /// Partial checkouts: branch -> partial
    partials: sanakirja::Db<self::small_string::UnsafeSmallStr, self::key::Key<PatchId>>,
}

/// Common type for both mutable transactions (`MutTxn`) and immutable
/// transaction (`Txn`). All of `Txn`'s methods are also `MutTxn`'s
/// methods.
pub struct GenericTxn<T, R> {
    #[doc(hidden)]
    pub txn: T,
    #[doc(hidden)]
    pub rng: R,
    #[doc(hidden)]
    pub dbs: Dbs,
}

/// A mutable transaction on a repository.
pub type MutTxn<'env, R> = GenericTxn<sanakirja::MutTxn<'env, ()>, R>;
/// An immutable transaction on a repository.
pub type Txn<'env> = GenericTxn<sanakirja::Txn<'env>, ()>;

/// The default name of a branch, for users who start working before
/// choosing branch names (or like the default name, "master").
pub const DEFAULT_BRANCH: &'static str = "master";

/// A repository. All operations on repositories must be done via transactions.
pub struct Repository {
    pub env: sanakirja::Env,
}

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Root {
    Tree,
    RevTree,
    Inodes,
    RevInodes,
    Contents,
    Internal,
    External,
    RevDep,
    Branches,
    Cemetery,
    TouchedFiles,
    Dep,
    RevTouchedFiles,
    Partials,
}

trait OpenDb: Transaction {
    fn open_db<K: Representable, V: Representable>(
        &mut self,
        num: Root,
    ) -> Result<sanakirja::Db<K, V>> {
        if let Some(db) = self.root(num as usize) {
            Ok(db)
        } else {
            Err(Error::NoDb(num))
        }
    }
}

impl<'a, T> OpenDb for sanakirja::MutTxn<'a, T> {
    fn open_db<K: Representable, V: Representable>(
        &mut self,
        num: Root,
    ) -> Result<sanakirja::Db<K, V>> {
        if let Some(db) = self.root(num as usize) {
            Ok(db)
        } else {
            Ok(self.create_db()?)
        }
    }
}
impl<'a> OpenDb for sanakirja::Txn<'a> {}

// Repositories need at least 2^5 = 32 pages, each of size 2^12.
const MIN_REPO_SIZE: u64 = 1 << 17;

impl Repository {
    #[doc(hidden)]
    pub fn size(&self) -> u64 {
        self.env.size()
    }

    #[doc(hidden)]
    pub fn repository_size<P: AsRef<Path>>(path: P) -> Result<u64> {
        let size = sanakirja::Env::file_size(path.as_ref())?;
        debug!("repository_size = {:?}", size);
        Ok(size)
    }

    /// Open a repository, possibly increasing the size of the
    /// underlying file if `size_increase` is `Some(…)`.
    pub fn open<P: AsRef<Path>>(path: P, size_increase: Option<u64>) -> Result<Self> {
        let size = if let Some(size) = size_increase {
            Repository::repository_size(path.as_ref()).unwrap_or(MIN_REPO_SIZE)
                + std::cmp::max(size, MIN_REPO_SIZE)
        } else {
            if let Ok(len) = Repository::repository_size(path.as_ref()) {
                std::cmp::max(len, MIN_REPO_SIZE)
            } else {
                MIN_REPO_SIZE
            }
        };
        Ok(Repository {
            env: sanakirja::Env::new(path, size)?,
        })
    }

    /// Open a repository, possibly increasing the size of the
    /// underlying file if `size_increase` is `Some(…)`.
    pub unsafe fn open_nolock<P: AsRef<Path>>(path: P, size_increase: Option<u64>) -> Result<Self> {
        let size = if let Some(size) = size_increase {
            Repository::repository_size(path.as_ref()).unwrap_or(MIN_REPO_SIZE)
                + std::cmp::max(size, MIN_REPO_SIZE)
        } else {
            if let Ok(len) = Repository::repository_size(path.as_ref()) {
                std::cmp::max(len, MIN_REPO_SIZE)
            } else {
                MIN_REPO_SIZE
            }
        };
        debug!("sanakirja::Env::new_nolock");
        Ok(Repository {
            env: sanakirja::Env::new_nolock(path, size)?,
        })
    }

    /// Close a repository. It is undefined behaviour to use it afterwards.
    pub unsafe fn close(&mut self) {
        self.env.close()
    }

    /// Start an immutable transaction. Immutable transactions can run
    /// concurrently.
    pub fn txn_begin(&self) -> Result<Txn> {
        let mut txn = self.env.txn_begin()?;
        let dbs = Dbs::new(&mut txn)?;
        let repo = GenericTxn {
            txn: txn,
            rng: (),
            dbs: dbs,
        };
        Ok(repo)
    }

    /// Start a mutable transaction. Mutable transactions exclude each
    /// other, but can in principle be run concurrently with immutable
    /// transactions. In that case, the immutable transaction only
    /// have access to the state of the repository immediately before
    /// the mutable transaction started.
    pub fn mut_txn_begin<R: rand::Rng>(&self, r: R) -> Result<MutTxn<R>> {
        let mut txn = self.env.mut_txn_begin()?;
        let dbs = Dbs::new(&mut txn)?;
        let repo = GenericTxn {
            txn: txn,
            rng: r,
            dbs: dbs,
        };
        Ok(repo)
    }
}

impl Dbs {
    fn new<T: OpenDb>(txn: &mut T) -> Result<Self> {
        let external = txn.open_db(Root::External)?;
        let branches = txn.open_db(Root::Branches)?;
        let tree = txn.open_db(Root::Tree)?;
        let revtree = txn.open_db(Root::RevTree)?;
        let inodes = txn.open_db(Root::Inodes)?;
        let revinodes = txn.open_db(Root::RevInodes)?;
        let internal = txn.open_db(Root::Internal)?;
        let contents = txn.open_db(Root::Contents)?;
        let revdep = txn.open_db(Root::RevDep)?;
        let cemetery = txn.open_db(Root::Cemetery)?;
        let dep = txn.open_db(Root::Dep)?;
        let touched_files = txn.open_db(Root::TouchedFiles)?;
        let partials = txn.open_db(Root::Partials)?;

        Ok(Dbs {
            external,
            branches,
            inodes,
            tree,
            revtree,
            revinodes,
            internal,
            revdep,
            contents,
            cemetery,
            dep,
            touched_files,
            partials,
        })
    }
}

/// The representation of a branch. The "application number" of a
/// patch on a branch is the state of the application counter at the
/// time the patch has been applied to that branch.
#[derive(Debug)]
pub struct Branch {
    /// The table containing the branch graph.
    pub db: NodesDb,
    /// The map of all patches applied to that branch, ordered by patch hash.
    pub patches: PatchSet,
    /// The map of all patches applied to that branch, ordered by application number.
    pub revpatches: RevPatchSet,
    /// The number of patches that have been applied on that branch,
    /// including patches that are no longer on the branch (i.e. that
    /// have been unrecorded).
    pub apply_counter: u64,
    /// Branch name.
    pub name: small_string::SmallString,
}

use sanakirja::Commit;
/// Branches and commits.
impl<'env, R: rand::Rng> MutTxn<'env, R> {
    /// Open a branch by name, creating an empty branch with that name
    /// if the name doesn't exist.
    pub fn open_branch<'name>(&mut self, name: &str) -> Result<Branch> {
        let name = small_string::SmallString::from_str(name);
        let (branch, patches, revpatches, counter) = if let Some(x) =
            self.txn
                .get(&self.dbs.branches, name.as_small_str().to_unsafe(), None)
        {
            x
        } else {
            (
                self.txn.create_db()?,
                self.txn.create_db()?,
                self.txn.create_db()?,
                0,
            )
        };
        Ok(Branch {
            db: branch,
            patches: patches,
            revpatches: revpatches,
            name: name,
            apply_counter: counter,
        })
    }

    /// Commit a branch. This is a extremely important thing to do on
    /// branches, and it is not done automatically when committing
    /// transactions.
    ///
    /// **I repeat: not calling this method before committing a
    /// transaction might cause database corruption.**
    pub fn commit_branch(&mut self, branch: Branch) -> Result<()> {
        debug!("Commit_branch. This is not too safe.");
        // Since we are replacing the value, we don't want to
        // decrement its reference counter (which del would do), hence
        // the transmute.
        //
        // This would normally be wrong. The only reason it works is
        // because we know that dbs_branches has never been forked
        // from another database, hence all the reference counts to
        // its elements are 1 (and therefore represented as "not
        // referenced" in Sanakirja.
        let mut dbs_branches: sanakirja::Db<UnsafeSmallStr, (u64, u64, u64, u64)> =
            unsafe { std::mem::transmute(self.dbs.branches) };

        debug!("Commit_branch, dbs_branches = {:?}", dbs_branches);
        self.txn.del(
            &mut self.rng,
            &mut dbs_branches,
            branch.name.as_small_str().to_unsafe(),
            None,
        )?;
        debug!("Commit_branch, dbs_branches = {:?}", dbs_branches);
        self.dbs.branches = unsafe { std::mem::transmute(dbs_branches) };
        self.txn.put(
            &mut self.rng,
            &mut self.dbs.branches,
            branch.name.as_small_str().to_unsafe(),
            (
                branch.db,
                branch.patches,
                branch.revpatches,
                branch.apply_counter,
            ),
        )?;
        debug!("Commit_branch, self.dbs.branches = {:?}", self.dbs.branches);
        Ok(())
    }

    /// Rename a branch. The branch still needs to be committed after
    /// this operation.
    pub fn rename_branch(&mut self, branch: &mut Branch, new_name: &str) -> Result<()> {
        debug!("Commit_branch. This is not too safe.");
        // Since we are replacing the value, we don't want to
        // decrement its reference counter (which del would do), hence
        // the transmute.
        //
        // Read the note in `commit_branch` to understand why this
        // works.
        let name_exists = self.get_branch(new_name).is_some();
        if name_exists {
            Err(Error::BranchNameAlreadyExists(new_name.to_string()))
        } else {
            let mut dbs_branches: sanakirja::Db<UnsafeSmallStr, (u64, u64, u64, u64)> =
                unsafe { std::mem::transmute(self.dbs.branches) };
            self.txn.del(
                &mut self.rng,
                &mut dbs_branches,
                branch.name.as_small_str().to_unsafe(),
                None,
            )?;
            self.dbs.branches = unsafe { std::mem::transmute(dbs_branches) };
            branch.name.clone_from_str(new_name);
            Ok(())
        }
    }

    /// Commit a transaction. **Be careful to commit all open branches
    /// before**.
    pub fn commit(mut self) -> Result<()> {
        self.txn.set_root(Root::Tree as usize, self.dbs.tree);
        self.txn.set_root(Root::RevTree as usize, self.dbs.revtree);
        self.txn.set_root(Root::Inodes as usize, self.dbs.inodes);
        self.txn
            .set_root(Root::RevInodes as usize, self.dbs.revinodes);
        self.txn
            .set_root(Root::Contents as usize, self.dbs.contents);
        self.txn
            .set_root(Root::Internal as usize, self.dbs.internal);
        self.txn
            .set_root(Root::External as usize, self.dbs.external);
        self.txn
            .set_root(Root::Branches as usize, self.dbs.branches);
        self.txn.set_root(Root::RevDep as usize, self.dbs.revdep);
        self.txn
            .set_root(Root::Cemetery as usize, self.dbs.cemetery);
        self.txn.set_root(Root::Dep as usize, self.dbs.dep);
        self.txn
            .set_root(Root::TouchedFiles as usize, self.dbs.touched_files);
        self.txn
            .set_root(Root::Partials as usize, self.dbs.partials);

        self.txn.commit()?;
        Ok(())
    }
}

use sanakirja::value::*;
use sanakirja::{Cursor, RevCursor};
pub struct TreeIterator<'a, T: Transaction + 'a>(Cursor<'a, T, UnsafeFileId, Inode>);

impl<'a, T: Transaction + 'a> Iterator for TreeIterator<'a, T> {
    type Item = (FileId<'a>, Inode);
    fn next(&mut self) -> Option<Self::Item> {
        debug!("tree iter");
        if let Some((k, v)) = self.0.next() {
            debug!("tree iter: {:?} {:?}", k, v);
            unsafe { Some((FileId::from_unsafe(k), v)) }
        } else {
            None
        }
    }
}

pub struct RevtreeIterator<'a, T: Transaction + 'a>(Cursor<'a, T, Inode, UnsafeFileId>);

impl<'a, T: Transaction + 'a> Iterator for RevtreeIterator<'a, T> {
    type Item = (Inode, FileId<'a>);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((k, v)) = self.0.next() {
            unsafe { Some((k, FileId::from_unsafe(v))) }
        } else {
            None
        }
    }
}

pub struct NodesIterator<'a, T: Transaction + 'a>(Cursor<'a, T, Key<PatchId>, UnsafeEdge>);
pub struct NodesIterator<'a, T: Transaction + 'a>(Cursor<'a, T, Key<PatchId>, Edge>);

impl<'a, T: Transaction + 'a> Iterator for NodesIterator<'a, T> {
    type Item = (Key<PatchId>, &'a Edge);
impl<'a, T: Transaction> Iterator for NodesIterator<'a, T> {
    type Item = (Key<PatchId>, Edge);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((k, v)) = self.0.next() {
            unsafe { Some((k, Edge::from_unsafe(v))) }
            Some((k, v))
        } else {
            None
        }
    }
}
pub struct BranchIterator<'a, T: Transaction + 'a>(
    Cursor<'a, T, UnsafeSmallStr, (NodesDb, PatchSet, RevPatchSet, u64)>,
);

impl<'a, T: Transaction + 'a> Iterator for BranchIterator<'a, T> {
    type Item = Branch;
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((k, v)) = self.0.next() {
            unsafe {
                Some(Branch {
                    name: SmallStr::from_unsafe(k).to_owned(),
                    db: v.0,
                    patches: v.1,
                    revpatches: v.2,
                    apply_counter: v.3,
                })
            }
        } else {
            None
        }
    }
}

pub struct PatchesIterator<'a, T: Transaction + 'a>(Cursor<'a, T, PatchId, ApplyTimestamp>);

impl<'a, T: Transaction + 'a> Iterator for PatchesIterator<'a, T> {
    type Item = (PatchId, ApplyTimestamp);
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

pub struct RevAppliedIterator<'a, T: Transaction + 'a>(RevCursor<'a, T, ApplyTimestamp, PatchId>);

impl<'a, T: Transaction + 'a> Iterator for RevAppliedIterator<'a, T> {
    type Item = (ApplyTimestamp, PatchId);
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

pub struct AppliedIterator<'a, T: Transaction + 'a>(Cursor<'a, T, ApplyTimestamp, PatchId>);

impl<'a, T: Transaction + 'a> Iterator for AppliedIterator<'a, T> {
    type Item = (ApplyTimestamp, PatchId);
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

pub struct InodesIterator<'a, T: Transaction + 'a>(Cursor<'a, T, Inode, FileHeader>);

impl<'a, T: Transaction + 'a> Iterator for InodesIterator<'a, T> {
    type Item = (Inode, FileHeader);
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

pub struct InternalIterator<'a, T: Transaction + 'a>(Cursor<'a, T, UnsafeHash, PatchId>);

impl<'a, T: Transaction + 'a> Iterator for InternalIterator<'a, T> {
    type Item = (HashRef<'a>, PatchId);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((k, v)) = self.0.next() {
            unsafe { Some((HashRef::from_unsafe(k), v)) }
        } else {
            None
        }
    }
}
pub struct ExternalIterator<'a, T: Transaction + 'a>(Cursor<'a, T, PatchId, UnsafeHash>);

impl<'a, T: Transaction + 'a> Iterator for ExternalIterator<'a, T> {
    type Item = (PatchId, HashRef<'a>);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((k, v)) = self.0.next() {
            unsafe { Some((k, HashRef::from_unsafe(v))) }
        } else {
            None
        }
    }
}

pub struct RevdepIterator<'a, T: Transaction + 'a>(Cursor<'a, T, PatchId, PatchId>);

impl<'a, T: Transaction + 'a> Iterator for RevdepIterator<'a, T> {
    type Item = (PatchId, PatchId);
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

pub struct DepIterator<'a, T: Transaction + 'a>(Cursor<'a, T, PatchId, PatchId>);

impl<'a, T: Transaction + 'a> Iterator for DepIterator<'a, T> {
    type Item = (PatchId, PatchId);
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

pub struct ContentsIterator<'a, T: Transaction + 'a>(
    &'a T,
    Cursor<'a, T, Key<PatchId>, UnsafeValue>,
);

impl<'a, T: Transaction + 'a> Iterator for ContentsIterator<'a, T> {
    type Item = (Key<PatchId>, Value<'a, T>);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((k, v)) = self.1.next() {
            unsafe { Some((k, Value::from_unsafe(&v, self.0))) }
        } else {
            None
        }
    }
}

pub struct CemeteryIterator<'a, T: Transaction + 'a>(Cursor<'a, T, (Key<PatchId>, Edge), PatchId>);

impl<'a, T: Transaction + 'a> Iterator for CemeteryIterator<'a, T> {
    type Item = ((Key<PatchId>, &'a Edge), PatchId);
    type Item = ((Key<PatchId>, Edge), PatchId);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(((k, v), w)) = self.0.next() {
            unsafe { Some(((k, Edge::from_unsafe(v)), w)) }
            unsafe { Some(((k, Edge::from_unsafe(v)), w)) }
            Some(((k, v), w))
        } else {
            None
        }
    }
}

pub struct TouchedIterator<'a, T: Transaction + 'a>(Cursor<'a, T, Key<PatchId>, PatchId>);

impl<'a, T: Transaction + 'a> Iterator for TouchedIterator<'a, T> {
    type Item = (Key<PatchId>, PatchId);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((k, v)) = self.0.next() {
            Some((k, v))
        } else {
            None
        }
    }
}

pub struct PartialsIterator<'a, T: Transaction + 'a>(Cursor<'a, T, UnsafeSmallStr, Key<PatchId>>);

impl<'a, T: Transaction + 'a> Iterator for PartialsIterator<'a, T> {
    type Item = (SmallStr<'a>, Key<PatchId>);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((k, v)) = self.0.next() {
            unsafe { Some((SmallStr::from_unsafe(k), v)) }
        } else {
            None
        }
    }
}

mod dump {
    use super::*;
    use sanakirja;

    impl<U: Transaction, R> GenericTxn<U, R> {
        pub fn dump(&self) {
            debug!("============= dumping Tree");
            for (k, v) in self.iter_tree(None) {
                debug!("> {:?} {:?}", k, v)
            }
            debug!("============= dumping Inodes");
            for (k, v) in self.iter_inodes(None) {
                debug!("> {:?} {:?}", k, v)
            }
            debug!("============= dumping RevDep");
            for (k, v) in self.iter_revdep(None) {
                debug!("> {:?} {:?}", k, v)
            }
            debug!("============= dumping Internal");
            for (k, v) in self.iter_internal(None) {
                debug!("> {:?} {:?}", k, v)
            }
            debug!("============= dumping External");
            for (k, v) in self.iter_external(None) {
                debug!("> {:?} {:?} {:?}", k, v, v.to_base58());
            }
            debug!("============= dumping Contents");
            {
                sanakirja::debug(&self.txn, &[&self.dbs.contents], "dump_contents", true);
            }
            debug!("============= dumping Partials");
            for (k, v) in self.iter_partials("") {
                debug!("> {:?} {:?}", k, v);
            }
            debug!("============= dumping Branches");
            for (br, (db, patches, revpatches, counter)) in self.txn.iter(&self.dbs.branches, None)
            {
                debug!("patches: {:?} {:?}", patches, revpatches);
                debug!(
                    "============= dumping Patches in branch {:?}, counter = {:?}",
                    br, counter
                );
                for (k, v) in self.txn.iter(&patches, None) {
                    debug!("> {:?} {:?}", k, v)
                }
                debug!("============= dumping RevPatches in branch {:?}", br);
                for (k, v) in self.txn.iter(&revpatches, None) {
                    debug!("> {:?} {:?}", k, v)
                }
                debug!("============= dumping Nodes in branch {:?}", br);
                unsafe {
                    // sanakirja::debug(&self.txn, &[&db], path);
                    debug!("> {:?}", SmallStr::from_unsafe(br));
                    for (k, v) in self.txn.iter(&db, None) {
                        debug!(">> {:?} {:?}", k, Edge::from_unsafe(v))
                        debug!(">> {:?} {:?}", k, v)
                    }
                }
            }
        }
    }
}

/// An iterator for nodes adjacent to `key` through an edge with flags smaller than `max_flag`.
pub struct AdjIterator<'a, U: Transaction + 'a> {
    it: NodesIterator<'a, U>,
    key: Key<PatchId>,
    /// iter as long as the flag is smaller than this
    max_flag: EdgeFlags,
}

impl<'a, U: Transaction + 'a> Iterator for AdjIterator<'a, U> {
    type Item = Edge;
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((v, e)) = self.it.next() {
            if v == self.key && e.flag <= self.max_flag {
                Some(e)
            } else {
                None
            }
        } else {
            None
        }
    }
}

/*
macro_rules! iterate_parents {
    ($txn:expr, $branch:expr, $key:expr, $flag: expr) => { {
        let edge = Edge::zero($flag|PARENT_EDGE);
        $txn.iter_nodes(& $branch, Some(($key, Some(&edge))))
            .take_while(|&(k, parent)| {
                *k == *$key && parent.flag <= $flag|PARENT_EDGE|PSEUDO_EDGE
            })
            .map(|(_,b)| b)
    } }
}
*/
use std::collections::{BTreeMap, HashSet};
#[derive(Debug)]
pub struct PageCounts {
    pub tree: usize,
    pub revtree: usize,
    pub inodes: usize,
    pub revinodes: usize,
    pub contents: usize,
    pub internal: usize,
    pub external: usize,
    pub revdep: usize,
    pub branch_table: usize,
    pub cemetery: usize,
    pub dep: usize,
    pub touched_files: usize,
    pub partials: usize,
    pub branches: BTreeMap<String, usize>,
}

impl PageCounts {
    pub fn sum(&self) -> usize {
        self.tree
            + self.revtree
            + self.inodes
            + self.revinodes
            + self.contents
            + self.internal
            + self.external
            + self.revdep
            + self.branch_table
            + self.cemetery
            + self.dep
            + self.touched_files
            + self.partials
            + self.branches.iter().map(|x| x.1).sum::<usize>()
    }
}

impl<'a> Txn<'a> {
    pub fn page_counts(&self) -> PageCounts {
        let mut references = HashSet::new();
        self.txn.references(&mut references, self.dbs.tree);
        let tree = references.len();
        references.clear();
        self.txn.references(&mut references, self.dbs.revtree);
        let revtree = references.len();
        references.clear();
        self.txn.references(&mut references, self.dbs.inodes);
        let inodes = references.len();
        references.clear();
        self.txn.references(&mut references, self.dbs.revinodes);
        let revinodes = references.len();
        references.clear();
        self.txn.references(&mut references, self.dbs.contents);
        let contents = references.len();
        references.clear();
        self.txn.references(&mut references, self.dbs.internal);
        let internal = references.len();
        references.clear();
        self.txn.references(&mut references, self.dbs.external);
        let external = references.len();
        references.clear();
        self.txn.references(&mut references, self.dbs.revdep);
        let revdep = references.len();
        references.clear();
        self.txn.references(&mut references, self.dbs.branches);
        let branch_table = references.len();
        references.clear();
        self.txn.references(&mut references, self.dbs.cemetery);
        let cemetery = references.len();
        references.clear();
        self.txn.references(&mut references, self.dbs.dep);
        let dep = references.len();
        references.clear();
        self.txn.references(&mut references, self.dbs.touched_files);
        let touched_files = references.len();
        references.clear();
        self.txn.references(&mut references, self.dbs.partials);
        let partials = references.len();

        let mut branches = BTreeMap::new();
        for br in self.iter_branches(None) {
            references.clear();
            self.txn.references(&mut references, br.db);
            branches.insert(br.name.as_str().to_string(), references.len());
        }

        PageCounts {
            tree,
            revtree,
            inodes,
            revinodes,
            contents,
            internal,
            external,
            revdep,
            branch_table,
            cemetery,
            dep,
            touched_files,
            partials,
            branches,
        }
    }
}

impl<U: Transaction, R> GenericTxn<U, R> {
    /// Does this repository has a branch called `name`?
    pub fn has_branch(&self, name: &str) -> bool {
        let name = small_string::SmallString::from_str(name);
        self.txn
            .get(&self.dbs.branches, name.as_small_str().to_unsafe(), None)
            .is_some()
    }

    /// Get the branch with the given name, if it exists.
    pub fn get_branch<'name>(&self, name: &str) -> Option<Branch> {
        let name = small_string::SmallString::from_str(name);
        if let Some((branch, patches, revpatches, counter)) =
            self.txn
                .get(&self.dbs.branches, name.as_small_str().to_unsafe(), None)
        {
            Some(Branch {
                db: branch,
                patches: patches,
                revpatches: revpatches,
                apply_counter: counter,
                name: name,
            })
        } else {
            None
        }
    }

    /// Return the first edge of this `key` if `edge` is `None`, and
    /// a pointer to the edge in the database if `edge` is `Some`.
    pub fn get_nodes<'a>(
        &'a self,
        branch: &Branch,
        key: Key<PatchId>,
        edge: Option<&Edge>,
    ) -> Option<&'a Edge> {
        self.txn
        self.txn
            .get(&branch.db, key, edge.map(|e| e.to_unsafe()))
            .map(|e| unsafe { Edge::from_unsafe(e) })
        edge: Option<Edge>,
    ) -> Option<Edge> {
        self.txn.get(&branch.db, key, edge)
    }

    /// An iterator over keys and edges, in branch `branch`, starting
    /// from key and edge specified by `key`. If `key` is `None`, the
    /// iterations start from the first key and first edge. If `key`
    /// is of the form `Some(a, None)`, they start from the first edge
    /// of key `a`. If `key` is of the from `Some(a, Some(b))`, they
    /// start from the first key and edge that is at least `(a, b)`.
    pub fn iter_nodes<'a>(
        &'a self,
        branch: &'a Branch,
        key: Option<(Key<PatchId>, Option<&Edge>)>,
        key: Option<(Key<PatchId>, Option<Edge>)>,
    ) -> NodesIterator<'a, U> {
        NodesIterator(self.txn.iter(&branch.db, key.map(|(k, v)| (k, v))))
    }

    pub fn iter_adjacent<'a>(
        &'a self,
        branch: &'a Branch,
        key: Key<PatchId>,
        min_flag: EdgeFlags,
        max_flag: EdgeFlags,
    ) -> AdjIterator<'a, U> {
        let edge = Edge::zero(min_flag);
        AdjIterator {
            it: self.iter_nodes(branch, Some((key, Some(edge)))),
            key,
            max_flag: max_flag,
        }
    }

    pub fn iter_parents<'a>(
        &'a self,
        branch: &'a Branch,
        key: Key<PatchId>,
        flag: EdgeFlags,
    ) -> AdjIterator<'a, U> {
        let edge = Edge::zero(flag | EdgeFlags::PARENT_EDGE);
        AdjIterator {
            it: self.iter_nodes(branch, Some((key, Some(edge)))),
            key,
            max_flag: flag | EdgeFlags::PARENT_EDGE | EdgeFlags::PSEUDO_EDGE,
        }
    }

    pub fn iter_folder_children<'a>(
        &'a self,
        branch: &'a Branch,
        key: Key<PatchId>,
        flag: EdgeFlags,
    ) -> AdjIterator<'a, U> {
        let edge = Edge::zero(flag | EdgeFlags::FOLDER_EDGE);
        AdjIterator {
            it: self.iter_nodes(branch, Some((key, Some(edge)))),
            key,
            max_flag: flag
                | EdgeFlags::FOLDER_EDGE
                | EdgeFlags::PSEUDO_EDGE
                | EdgeFlags::EPSILON_EDGE,
        }
    }

    /// An iterator over branches in the database, starting from the
    /// given branch name.
    pub fn iter_branches<'a>(&'a self, key: Option<&SmallStr>) -> BranchIterator<'a, U> {
        BranchIterator(
            self.txn
                .iter(&self.dbs.branches, key.map(|k| (k.to_unsafe(), None))),
        )
    }

    /// An iterator over branches in the database, starting from the
    /// given branch name.
    pub fn iter_partials<'a>(&'a self, branch: &str) -> PartialsIterator<'a, U> {
        let key = SmallString::from_str(branch);
        PartialsIterator(self.txn.iter(
            &self.dbs.partials,
            Some((key.as_small_str().to_unsafe(), None)),
        ))
    }

    /// An iterator over patches in a branch, in the alphabetical
    /// order of their hash.
    pub fn iter_patches<'a>(
        &'a self,
        branch: &'a Branch,
        key: Option<PatchId>,
    ) -> PatchesIterator<'a, U> {
        PatchesIterator(self.txn.iter(&branch.patches, key.map(|k| (k, None))))
    }

    /// An iterator over patches in a branch, in the reverse order in
    /// which they were applied.
    pub fn rev_iter_applied<'a>(
        &'a self,
        branch: &'a Branch,
        key: Option<ApplyTimestamp>,
    ) -> RevAppliedIterator<'a, U> {
        RevAppliedIterator(
            self.txn
                .rev_iter(&branch.revpatches, key.map(|k| (k, None))),
        )
    }

    /// An iterator over patches in a branch in the order in which
    /// they were applied.
    pub fn iter_applied<'a>(
        &'a self,
        branch: &'a Branch,
        key: Option<ApplyTimestamp>,
    ) -> AppliedIterator<'a, U> {
        AppliedIterator(self.txn.iter(&branch.revpatches, key.map(|k| (k, None))))
    }

    /// An iterator over files and directories currently tracked by
    /// Pijul, starting from the given `FileId`. The `Inode`s returned
    /// by the iterator can be used to form new `FileId`s and traverse
    /// the tree from top to bottom.
    ///
    /// The set of tracked files is changed by the following
    /// operations: outputting the repository, adding, deleting and
    /// moving files. It is not related to branches, but only to the
    /// files actually present on the file system.
    pub fn iter_tree<'a>(&'a self, key: Option<(&FileId, Option<Inode>)>) -> TreeIterator<'a, U> {
        debug!("iter_tree: {:?}", key);
        TreeIterator(
            self.txn
                .iter(&self.dbs.tree, key.map(|(k, v)| (k.to_unsafe(), v))),
        )
    }

    /// An iterator over files and directories, following directories
    /// in the opposite direction.
    pub fn iter_revtree<'a>(
        &'a self,
        key: Option<(Inode, Option<&FileId>)>,
    ) -> RevtreeIterator<'a, U> {
        RevtreeIterator(self.txn.iter(
            &self.dbs.revtree,
            key.map(|(k, v)| (k, v.map(|v| v.to_unsafe()))),
        ))
    }

    /// An iterator over the "inodes" database, which contains
    /// correspondences between files on the filesystem and the files
    /// in the graph.
    pub fn iter_inodes<'a>(
        &'a self,
        key: Option<(Inode, Option<FileHeader>)>,
    ) -> InodesIterator<'a, U> {
        InodesIterator(self.txn.iter(&self.dbs.inodes, key))
    }

    /// Iterator over the `PatchId` to `Hash` correspondence.
    pub fn iter_external<'a>(
        &'a self,
        key: Option<(PatchId, Option<HashRef>)>,
    ) -> ExternalIterator<'a, U> {
        ExternalIterator(self.txn.iter(
            &self.dbs.external,
            key.map(|(k, v)| (k, v.map(|v| v.to_unsafe()))),
        ))
    }

    /// Iterator over the `Hash` to `PatchId` correspondence.
    pub fn iter_internal<'a>(
        &'a self,
        key: Option<(HashRef, Option<PatchId>)>,
    ) -> InternalIterator<'a, U> {
        InternalIterator(
            self.txn
                .iter(&self.dbs.internal, key.map(|(k, v)| (k.to_unsafe(), v))),
        )
    }

    /// Iterator over reverse dependencies (`(k, v)` is in the reverse
    /// dependency table if `v` depends on `k`, and both are in at
    /// least one branch).
    pub fn iter_revdep<'a>(
        &'a self,
        key: Option<(PatchId, Option<PatchId>)>,
    ) -> RevdepIterator<'a, U> {
        RevdepIterator(self.txn.iter(&self.dbs.revdep, key))
    }

    /// Iterator over dependencies.
    pub fn iter_dep<'a>(&'a self, key: Option<(PatchId, Option<PatchId>)>) -> DepIterator<'a, U> {
        DepIterator(self.txn.iter(&self.dbs.dep, key))
    }

    /// An iterator over line contents (common to all branches).
    pub fn iter_contents<'a>(&'a self, key: Option<Key<PatchId>>) -> ContentsIterator<'a, U> {
        ContentsIterator(
            &self.txn,
            self.txn.iter(&self.dbs.contents, key.map(|k| (k, None))),
        )
    }

    /// An iterator over edges in the cemetery.
    pub fn iter_cemetery<'a>(&'a self, key: Key<PatchId>, edge: Edge) -> CemeteryIterator<'a, U> {
        CemeteryIterator(self.txn.iter(&self.dbs.cemetery, Some(((key, edge), None))))
    }

    /// An iterator over patches that touch a certain file.
    pub fn iter_touched<'a>(&'a self, key: Key<PatchId>) -> TouchedIterator<'a, U> {
        TouchedIterator(self.txn.iter(&self.dbs.touched_files, Some((key, None))))
    }

    /// Tell whether a patch touches a file
    pub fn get_touched<'a>(&'a self, key: Key<PatchId>, patch: PatchId) -> bool {
        self.txn
            .get(&self.dbs.touched_files, key, Some(patch))
            .is_some()
    }

    /// Get the `Inode` of a give `FileId`. A `FileId` is itself
    /// composed of an inode and a name, hence this can be used to
    /// traverse the tree of tracked files from top to bottom.
    pub fn get_tree<'a>(&'a self, key: &FileId) -> Option<Inode> {
        self.txn.get(&self.dbs.tree, key.to_unsafe(), None)
    }

    /// Get the parent `FileId` of a given `Inode`. A `FileId` is
    /// itself composed of an `Inode` and a name, so this can be used
    /// to traverse the tree of tracked files from bottom to top
    /// (starting from a leaf).
    pub fn get_revtree<'a>(&'a self, key: Inode) -> Option<FileId<'a>> {
        self.txn
            .get(&self.dbs.revtree, key, None)
            .map(|e| unsafe { FileId::from_unsafe(e) })
    }

    /// Get the key in branches for the given `Inode`, as well as
    /// meta-information on the file (permissions, and whether it has
    /// been moved or deleted compared to the branch).
    ///
    /// This table is updated every time the repository is output, and
    /// when files are moved or deleted. It is meant to be
    /// synchronised with the current branch (if any).
    pub fn get_inodes<'a>(&'a self, key: Inode) -> Option<FileHeader> {
        self.txn.get(&self.dbs.inodes, key, None)
    }

    /// Get the `Inode` corresponding to `key` in branches (see the
    /// documentation for `get_inodes`).
    pub fn get_revinodes(&self, key: Key<PatchId>) -> Option<Inode> {
        self.txn.get(&self.dbs.revinodes, key, None)
    }

    /// Get the contents of a line.
    pub fn get_contents<'a>(&'a self, key: Key<PatchId>) -> Option<Value<'a, U>> {
        if let Some(e) = self.txn.get(&self.dbs.contents, key, None) {
            unsafe { Some(Value::from_unsafe(&e, &self.txn)) }
        } else {
            None
        }
    }

    /// Get the `PatchId` (or internal patch identifier) of the
    /// provided patch hash.
    pub fn get_internal(&self, key: HashRef) -> Option<PatchId> {
        match key {
            HashRef::None => Some(ROOT_PATCH_ID),
            h => self.txn.get(&self.dbs.internal, h.to_unsafe(), None),
        }
    }

    /// Get the `HashRef` (external patch identifier) of the provided
    /// internal patch identifier.
    pub fn get_external<'a>(&'a self, key: PatchId) -> Option<HashRef<'a>> {
        self.txn
            .get(&self.dbs.external, key, None)
            .map(|e| unsafe { HashRef::from_unsafe(e) })
    }

    /// Get the patch number in the branch. Patch numbers are
    /// guaranteed to always increase when a new patch is applied, but
    /// are not necessarily consecutive.
    pub fn get_patch(&self, patch_set: &PatchSet, patchid: PatchId) -> Option<ApplyTimestamp> {
        self.txn.get(patch_set, patchid, None)
    }

    /// Get the smallest patch id that depends on `patch` (and is at
    /// least `dep` in alphabetical order if `dep`, is `Some`).
    pub fn get_revdep(&self, patch: PatchId, dep: Option<PatchId>) -> Option<PatchId> {
        self.txn.get(&self.dbs.revdep, patch, dep)
    }

    /// Get the smallest patch id that `patch` depends on (and is at
    /// least `dep` in alphabetical order if `dep`, is `Some`).
    pub fn get_dep(&self, patch: PatchId, dep: Option<PatchId>) -> Option<PatchId> {
        self.txn.get(&self.dbs.dep, patch, dep)
    }

    /// Dump the graph of a branch into a writer, in dot format.
    pub fn debug<W>(&self, branch_name: &str, w: &mut W, exclude_parents: bool)
    where
        W: std::io::Write,
    {
        debug!("debugging branch {:?}", branch_name);
        let mut styles = Vec::with_capacity(16);
        for i in 0..32 {
            let flag = EdgeFlags::from_bits(i as u8).unwrap();
            styles.push(
                ("color=").to_string()
                    + ["red", "blue", "orange", "green", "black"][(i >> 1) & 3]
                    + if flag.contains(EdgeFlags::DELETED_EDGE) {
                        ", style=dashed"
                    } else {
                        ""
                    }
                    + if flag.contains(EdgeFlags::PSEUDO_EDGE) {
                        ", style=dotted"
                    } else {
                        ""
                    },
            )
        }
        w.write(b"digraph{\n").unwrap();
        let branch = self.get_branch(branch_name).unwrap();

        let mut cur: Key<PatchId> = ROOT_KEY.clone();
        for (k, v) in self.iter_nodes(&branch, None) {
            if k != cur {
                let cont = if let Some(cont) = self.get_contents(k) {
                    let cont = cont.into_cow();
                    let cont = &cont[..std::cmp::min(50, cont.len())];
                    format!(
                        "{:?}",
                        match std::str::from_utf8(cont) {
                            Ok(x) => x.to_string(),
                            Err(_) => hex::encode(cont),
                        }
                    )
                } else {
                    "\"\"".to_string()
                };
                // remove the leading and trailing '"'.
                let cont = &cont[1..(cont.len() - 1)];
                write!(
                    w,
                    "n_{}[label=\"{}.{}: {}\"];\n",
                    k.to_hex(),
                    k.patch.to_base58(),
                    k.line.to_hex(),
                    cont.replace("\n", "")
                )
                .unwrap();
                cur = k.clone();
            }
            debug!("debug: {:?}", v);
            let flag = v.flag.bits();
            if !(exclude_parents && v.flag.contains(EdgeFlags::PARENT_EDGE)) {
                write!(
                    w,
                    "n_{}->n_{}[{},label=\"{} {}\"];\n",
                    k.to_hex(),
                    &v.dest.to_hex(),
                    styles[(flag & 0xff) as usize],
                    flag,
                    v.introduced_by.to_base58()
                )
                .unwrap();
            }
        }
        w.write(b"}\n").unwrap();
    }

    /// Dump the graph of a branch into a writer, in dot format.
    pub fn debug_folders<W>(&self, branch_name: &str, w: &mut W)
    where
        W: std::io::Write,
    {
        debug!("debugging branch {:?}", branch_name);
        let mut styles = Vec::with_capacity(16);
        for i in 0..32 {
            let flag = EdgeFlags::from_bits(i as u8).unwrap();
            styles.push(
                ("color=").to_string()
                    + ["red", "blue", "orange", "green", "black"][(i >> 1) & 3]
                    + if flag.contains(EdgeFlags::DELETED_EDGE) {
                        ", style=dashed"
                    } else {
                        ""
                    }
                    + if flag.contains(EdgeFlags::PSEUDO_EDGE) {
                        ", style=dotted"
                    } else {
                        ""
                    },
            )
        }
        w.write(b"digraph{\n").unwrap();
        let branch = self.get_branch(branch_name).unwrap();

        let mut nodes = vec![ROOT_KEY];
        while let Some(k) = nodes.pop() {
            let cont = if let Some(cont) = self.get_contents(k) {
                let cont = cont.into_cow();
                let cont = &cont[..std::cmp::min(50, cont.len())];
                if cont.len() > 2 {
                    let (a, b) = cont.split_at(2);
                    let cont = format!("{:?}", std::str::from_utf8(b).unwrap());
                    let cont = &cont[1..(cont.len() - 1)];
                    format!("{} {}", hex::encode(a), cont)
                } else {
                    format!("{}", hex::encode(cont))
                }
            } else {
                "".to_string()
            };
            // remove the leading and trailing '"'.
            write!(
                w,
                "n_{}[label=\"{}.{}: {}\"];\n",
                k.to_hex(),
                k.patch.to_base58(),
                k.line.to_hex(),
                cont.replace("\n", "")
            )
            .unwrap();

            for child in self.iter_adjacent(&branch, k, EdgeFlags::empty(), EdgeFlags::all()) {
                let flag = child.flag.bits();
                write!(
                    w,
                    "n_{}->n_{}[{},label=\"{} {}\"];\n",
                    k.to_hex(),
                    &child.dest.to_hex(),
                    styles[(flag & 0xff) as usize],
                    flag,
                    child.introduced_by.to_base58()
                )
                .unwrap();
                if child.flag.contains(EdgeFlags::FOLDER_EDGE)
                    && !child.flag.contains(EdgeFlags::PARENT_EDGE)
                {
                    nodes.push(child.dest)
                }
            }
        }
        w.write(b"}\n").unwrap();
    }

    /// Is there an alive/pseudo edge from `a` to `b`.
    pub fn is_connected(&self, branch: &Branch, a: Key<PatchId>, b: Key<PatchId>) -> bool {
        self.test_edge(
            branch,
            a,
            b,
            EdgeFlags::empty(),
            EdgeFlags::PSEUDO_EDGE | EdgeFlags::FOLDER_EDGE,
        )
    }

    /// Is there an alive/pseudo edge from `a` to `b`.
    pub fn test_edge(
        &self,
        branch: &Branch,
        a: Key<PatchId>,
        b: Key<PatchId>,
        min: EdgeFlags,
        max: EdgeFlags,
    ) -> bool {
        debug!("is_connected {:?} {:?}", a, b);
        let mut edge = Edge::zero(min);
        edge.dest = b;
        self.iter_nodes(&branch, Some((a, Some(&edge))))
        self.iter_nodes(&branch, Some((a, Some(edge))))
            .take_while(|&(k, v)| k == a && v.dest == b && v.flag <= max)
            .next()
            .is_some()
    }
}

/// Low-level operations on mutable transactions.
impl<'env, R: rand::Rng> MutTxn<'env, R> {
    /// Delete a branch, destroying its associated graph and patch set.
    pub fn drop_branch(&mut self, branch: &str) -> Result<bool> {
        let name = SmallString::from_str(branch);
        Ok(self.txn.del(
            &mut self.rng,
            &mut self.dbs.branches,
            name.as_small_str().to_unsafe(),
            None,
        )?)
    }

    /// Add a binding to the graph of a branch. All edges must be
    /// inserted twice, once in each direction, and this method only
    /// inserts one direction.
    pub fn put_edge_one_dir(
        &mut self,
        branch: &mut Branch,
        key: Key<PatchId>,
        edge: &Edge,
        edge: Edge,
    ) -> Result<bool> {
        debug!("put_nodes: {:?} {:?}", key, edge);
        Ok(self.txn.put(&mut self.rng, &mut branch.db, key, edge)?)
    }

    /// Same as `put_nodes`, but also adds the reverse edge.
    pub fn put_edge_both_dirs(
        &mut self,
        branch: &mut Branch,
        mut key: Key<PatchId>,
        mut edge: Edge,
    ) -> Result<bool> {
        self.put_edge_one_dir(branch, key, edge)?;
        std::mem::swap(&mut key, &mut edge.dest);
        edge.flag.toggle(EdgeFlags::PARENT_EDGE);
        self.put_nodes(branch, key, &edge)
        self.put_edge_one_dir(branch, key, edge)
    }

    /// Delete an edge from a graph.
    pub fn del_edge_one_dir(
        &mut self,
        branch: &mut Branch,
        key: Key<PatchId>,
        edge: Option<&Edge>,
        edge: Edge,
    ) -> Result<bool> {
        Ok(self
            .txn
            .del(&mut self.rng, &mut branch.db, key, Some(edge))?)
    }

    /// Same as `del_nodes`, but also deletes the reverse edge.
    pub fn del_edge_both_dirs(
        &mut self,
        branch: &mut Branch,
        mut key: Key<PatchId>,
        mut edge: Edge,
    ) -> Result<bool> {
        self.del_edge_one_dir(branch, key, edge)?;
        std::mem::swap(&mut key, &mut edge.dest);
        edge.flag.toggle(EdgeFlags::PARENT_EDGE);
        self.del_nodes(branch, key, Some(&edge))
        self.del_edge_one_dir(branch, key, edge)
    }

    /// Add a file or directory into the tree database, with parent
    /// `key.parent_inode`, name `key.basename` and inode `Inode`
    /// (usually randomly generated, as `Inode`s have no relation
    /// with patches or branches).
    ///
    /// All bindings inserted here must have the reverse inserted into
    /// the revtree database. If `(key, edge)` is inserted here, then
    /// `(edge, key)` must be inserted into revtree.
    pub fn put_tree(&mut self, key: &FileId, edge: Inode) -> Result<bool> {
        Ok(self
            .txn
            .put(&mut self.rng, &mut self.dbs.tree, key.to_unsafe(), edge)?)
    }

    /// Delete a file or directory from the tree database. Similarly
    /// to the comments in the documentation of the `put_tree` method,
    /// the reverse binding must be delete from the revtree database.
    pub fn del_tree(&mut self, key: &FileId, edge: Option<Inode>) -> Result<bool> {
        Ok(self
            .txn
            .del(&mut self.rng, &mut self.dbs.tree, key.to_unsafe(), edge)?)
    }

    /// Add a file into the revtree database (see the documentation of
    /// the `put_tree` method).
    pub fn put_revtree(&mut self, key: Inode, value: &FileId) -> Result<bool> {
        Ok(self
            .txn
            .put(&mut self.rng, &mut self.dbs.revtree, key, value.to_unsafe())?)
    }

    /// Delete a file from the revtree database (see the documentation
    /// of the `put_tree` method).
    pub fn del_revtree(&mut self, key: Inode, value: Option<&FileId>) -> Result<bool> {
        Ok(self.txn.del(
            &mut self.rng,
            &mut self.dbs.revtree,
            key,
            value.map(|e| e.to_unsafe()),
        )?)
    }

    /// Delete a binding from the `inodes` database, i.e. the
    /// correspondence between branch graphs and the file tree.
    ///
    /// All bindings in inodes must have their reverse in revinodes
    /// (without the `FileMetadata`). `del_revinodes` must be called
    /// immediately before or immediately after calling this method.
    pub fn del_inodes(&mut self, key: Inode, value: Option<FileHeader>) -> Result<bool> {
        Ok(self
            .txn
            .del(&mut self.rng, &mut self.dbs.inodes, key, value)?)
    }

    /// Replace a binding in the inodes database, or insert a new
    /// one if `key` doesn't exist yet in that database.
    ///
    /// All bindings in inodes must have their reverse inserted in
    /// revinodes (without the `FileMetadata`).
    pub fn replace_inodes(&mut self, key: Inode, value: FileHeader) -> Result<bool> {
        self.txn
            .del(&mut self.rng, &mut self.dbs.inodes, key, None)?;
        Ok(self
            .txn
            .put(&mut self.rng, &mut self.dbs.inodes, key, value)?)
    }

    /// Replace a binding in the revinodes database, or insert a new
    /// one if `key` doesnt exist yet in that database.
    ///
    /// All bindings in revinodes must have their reverse inserted
    /// inodes (with an extra `FileMetadata`).
    pub fn replace_revinodes(&mut self, key: Key<PatchId>, value: Inode) -> Result<bool> {
        self.txn
            .del(&mut self.rng, &mut self.dbs.revinodes, key, None)?;
        Ok(self
            .txn
            .put(&mut self.rng, &mut self.dbs.revinodes, key, value)?)
    }

    /// Delete a binding from the `revinodes` database, i.e. the
    /// correspondence between the file tree and branch graphs.
    ///
    /// All bindings in revinodes must have their reverse in inodes
    /// (with an extra `FileMetadata`). `del_inodes` must be called
    /// immediately before or immediately after calling this method.
    pub fn del_revinodes(&mut self, key: Key<PatchId>, value: Option<Inode>) -> Result<bool> {
        Ok(self
            .txn
            .del(&mut self.rng, &mut self.dbs.revinodes, key, value)?)
    }

    /// Add the contents of a line. Note that this table is common to
    /// all branches.
    pub fn put_contents(&mut self, key: Key<PatchId>, value: UnsafeValue) -> Result<bool> {
        Ok(self
            .txn
            .put(&mut self.rng, &mut self.dbs.contents, key, value)?)
    }

    /// Remove the contents of a line.
    pub fn del_contents(&mut self, key: Key<PatchId>, value: Option<UnsafeValue>) -> Result<bool> {
        Ok(self
            .txn
            .del(&mut self.rng, &mut self.dbs.contents, key, value)?)
    }

    /// Register the internal identifier of a patch. The
    /// `put_external` method must be called immediately after, or
    /// immediately before this method.
    pub fn put_internal(&mut self, key: HashRef, value: PatchId) -> Result<bool> {
        Ok(self.txn.put(
            &mut self.rng,
            &mut self.dbs.internal,
            key.to_unsafe(),
            value,
        )?)
    }

    /// Unregister the internal identifier of a patch. Remember to
    /// also unregister its external id.
    pub fn del_internal(&mut self, key: HashRef) -> Result<bool> {
        Ok(self
            .txn
            .del(&mut self.rng, &mut self.dbs.internal, key.to_unsafe(), None)?)
    }

    /// Register the extern identifier of a patch. The `put_internal`
    /// method must be called immediately after, or immediately before
    /// this method.
    pub fn put_external(&mut self, key: PatchId, value: HashRef) -> Result<bool> {
        Ok(self.txn.put(
            &mut self.rng,
            &mut self.dbs.external,
            key,
            value.to_unsafe(),
        )?)
    }

    /// Unregister the extern identifier of a patch. Remember to also
    /// unregister its internal id.
    pub fn del_external(&mut self, key: PatchId) -> Result<bool> {
        Ok(self
            .txn
            .del(&mut self.rng, &mut self.dbs.external, key, None)?)
    }

    /// Add a patch id to a branch. This doesn't apply the patch, it
    /// only registers it as applied. The `put_revpatches` method must be
    /// called on the same branch immediately before, or immediately
    /// after.
    pub fn put_patches(
        &mut self,
        branch: &mut PatchSet,
        value: PatchId,
        time: ApplyTimestamp,
    ) -> Result<bool> {
        Ok(self.txn.put(&mut self.rng, branch, value, time)?)
    }

    /// Delete a patch id from a branch. This doesn't unrecord the
    /// patch, it only removes it from the patch set. The
    /// `del_revpatches` method must be called on the same branch
    /// immediately before, or immediately after.
    pub fn del_patches(&mut self, branch: &mut PatchSet, value: PatchId) -> Result<bool> {
        Ok(self.txn.del(&mut self.rng, branch, value, None)?)
    }

    /// Add a patch id to a branch. This doesn't apply the patch, it
    /// only registers it as applied. The `put_patches` method must be
    /// called on the same branch immediately before, or immediately
    /// after.
    pub fn put_revpatches(
        &mut self,
        branch: &mut RevPatchSet,
        time: ApplyTimestamp,
        value: PatchId,
    ) -> Result<bool> {
        Ok(self.txn.put(&mut self.rng, branch, time, value)?)
    }

    /// Delete a patch id from a branch. This doesn't unrecord the
    /// patch, it only removes it from the patch set. The
    /// `del_patches` method must be called on the same branch
    /// immediately before, or immediately after.
    pub fn del_revpatches(
        &mut self,
        revbranch: &mut RevPatchSet,
        timestamp: ApplyTimestamp,
        value: PatchId,
    ) -> Result<bool> {
        Ok(self
            .txn
            .del(&mut self.rng, revbranch, timestamp, Some(value))?)
    }

    /// Register a reverse dependency. All dependencies of all patches
    /// applied on at least one branch must be registered in this
    /// database, i.e. if a depends on b, then `(b, a)` must be
    /// inserted here.
    pub fn put_revdep(&mut self, patch: PatchId, revdep: PatchId) -> Result<bool> {
        Ok(self
            .txn
            .put(&mut self.rng, &mut self.dbs.revdep, patch, revdep)?)
    }

    /// Register a dependency. All dependencies of all patches applied
    /// on at least one branch must be registered in this database,
    /// i.e. if a depends on b, then `(b, a)` must be inserted here.
    pub fn put_dep(&mut self, patch: PatchId, dep: PatchId) -> Result<bool> {
        Ok(self.txn.put(&mut self.rng, &mut self.dbs.dep, patch, dep)?)
    }

    /// Remove a reverse dependency. Only call this method when the
    /// patch with identifier `patch` is not applied to any branch.
    pub fn del_revdep(&mut self, patch: PatchId, revdep: Option<PatchId>) -> Result<bool> {
        Ok(self
            .txn
            .del(&mut self.rng, &mut self.dbs.revdep, patch, revdep)?)
    }

    /// Remove a dependency. Only call this method when the patch with
    /// identifier `patch` is not applied to any branch.
    pub fn del_dep(&mut self, patch: PatchId, dep: Option<PatchId>) -> Result<bool> {
        Ok(self.txn.del(&mut self.rng, &mut self.dbs.dep, patch, dep)?)
    }

    /// Add an edge to the cemetery.
    pub fn put_cemetery(&mut self, key: Key<PatchId>, edge: &Edge, patch: PatchId) -> Result<bool> {
        let unsafe_edge = edge.to_unsafe();
    pub fn put_cemetery(&mut self, key: Key<PatchId>, edge: Edge, patch: PatchId) -> Result<bool> {
        Ok(self
            .txn
            .put(&mut self.rng, &mut self.dbs.cemetery, (key, edge), patch)?)
    }

    /// Delete an edge from the cemetery.
    pub fn del_cemetery(&mut self, key: Key<PatchId>, edge: &Edge, patch: PatchId) -> Result<bool> {
        let unsafe_edge = edge.to_unsafe();
    pub fn del_cemetery(&mut self, key: Key<PatchId>, edge: Edge, patch: PatchId) -> Result<bool> {
        Ok(self.txn.del(
            &mut self.rng,
            &mut self.dbs.cemetery,
            (key, unsafe_edge),
            (key, edge),
            Some(patch),





















































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
use byteorder::{ByteOrder, BigEndian};
const HEXDIGITS: [char; 16] = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
];
const UHEXDIGITS: [char; 16] = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
];

        write!(
            w,
            "{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}",
            HEXDIGITS[((self.0 >> 60) & 0xf) as usize],
            HEXDIGITS[((self.0 >> 56) & 0xf) as usize],
            HEXDIGITS[((self.0 >> 52) & 0xf) as usize],
            HEXDIGITS[((self.0 >> 48) & 0xf) as usize],
            HEXDIGITS[((self.0 >> 44) & 0xf) as usize],
            HEXDIGITS[((self.0 >> 40) & 0xf) as usize],
            HEXDIGITS[((self.0 >> 36) & 0xf) as usize],
            HEXDIGITS[((self.0 >> 32) & 0xf) as usize],
            HEXDIGITS[((self.0 >> 28) & 0xf) as usize],
            HEXDIGITS[((self.0 >> 24) & 0xf) as usize],
            HEXDIGITS[((self.0 >> 20) & 0xf) as usize],
            HEXDIGITS[((self.0 >> 16) & 0xf) as usize],
            HEXDIGITS[((self.0 >> 12) & 0xf) as usize],
            HEXDIGITS[((self.0 >> 8) & 0xf) as usize],
            HEXDIGITS[((self.0 >> 4) & 0xf) as usize],
            HEXDIGITS[(self.0 & 0xf) as usize]
        )
        write!(
            w,
            "{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}",
            UHEXDIGITS[((self.0 >> 60) & 0xf) as usize],
            UHEXDIGITS[((self.0 >> 56) & 0xf) as usize],
            UHEXDIGITS[((self.0 >> 52) & 0xf) as usize],
            UHEXDIGITS[((self.0 >> 48) & 0xf) as usize],
            UHEXDIGITS[((self.0 >> 44) & 0xf) as usize],
            UHEXDIGITS[((self.0 >> 40) & 0xf) as usize],
            UHEXDIGITS[((self.0 >> 36) & 0xf) as usize],
            UHEXDIGITS[((self.0 >> 32) & 0xf) as usize],
            UHEXDIGITS[((self.0 >> 28) & 0xf) as usize],
            UHEXDIGITS[((self.0 >> 24) & 0xf) as usize],
            UHEXDIGITS[((self.0 >> 20) & 0xf) as usize],
            UHEXDIGITS[((self.0 >> 16) & 0xf) as usize],
            UHEXDIGITS[((self.0 >> 12) & 0xf) as usize],
            UHEXDIGITS[((self.0 >> 8) & 0xf) as usize],
            UHEXDIGITS[((self.0 >> 4) & 0xf) as usize],
            UHEXDIGITS[(self.0 & 0xf) as usize]
        )
        PatchId(BigEndian::read_u64(s))
        BigEndian::write_u64(&mut x, self.0);
            Some(PatchId(BigEndian::read_u64(&p)))
        BigEndian::write_u64(std::slice::from_raw_parts_mut(p, 8), self.0)
        let x = PatchId(BigEndian::read_u64(std::slice::from_raw_parts(p, 8)));
use bs58;
use byteorder::{ByteOrder, LittleEndian};
use sanakirja::{Alignment, Representable};
use std;

// Patch Identifiers.
pub const PATCH_ID_SIZE: usize = 8;
pub const ROOT_PATCH_ID: PatchId = PatchId([0; PATCH_ID_SIZE]);
pub const ROOT_PATCH_ID: PatchId = PatchId(0);

/// An internal patch identifier, less random than external patch
/// identifiers, but more stable in time, and much smaller.
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Serialize, Deserialize)]
pub struct PatchId([u8; PATCH_ID_SIZE]);
pub struct PatchId(pub(crate) u64);

impl std::fmt::Debug for PatchId {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "PatchId({})", self.to_base58())
    }
}

use hex::ToHex;
use std::fmt::Write;

impl ToHex for PatchId {
    fn write_hex<W: Write>(&self, w: &mut W) -> std::fmt::Result {
        let mut x = [0; 8];
        LittleEndian::write_u64(&mut x, self.0);
        x.write_hex(w)
    }

    fn write_hex_upper<W: Write>(&self, w: &mut W) -> std::fmt::Result {
        let mut x = [0; 8];
        LittleEndian::write_u64(&mut x, self.0);
        x.write_hex_upper(w)
    }
}

impl PatchId {
    /// New patch id (initialised to 0).
    pub fn new() -> Self {
        PatchId([0; PATCH_ID_SIZE])
        PatchId(0)
    }

    pub fn from_slice(s: &[u8]) -> Self {
        PatchId(LittleEndian::read_u64(s))
    }

    /// Encode this patch id in base58.
    pub fn to_base58(&self) -> String {
        bs58::encode(&self.0).into_string()
        let mut x = [0; 8];
        LittleEndian::write_u64(&mut x, self.0);
        bs58::encode(&x).into_string()
    }
    /// Decode this patch id from its base58 encoding.
    pub fn from_base58(s: &str) -> Option<Self> {
        let mut p = PatchId::new();
        if bs58::decode(s).into(&mut p.0).is_ok() {
            Some(p)
        let mut p = [0; 8];
        if bs58::decode(s).into(&mut p).is_ok() {
            Some(PatchId(LittleEndian::read_u64(&p)))
        } else {
            None
        }
    }
    pub fn is_root(&self) -> bool {
        *self == ROOT_PATCH_ID
    }
}

impl std::ops::Deref for PatchId {
    type Target = [u8];
    type Target = u64;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl std::ops::DerefMut for PatchId {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl Representable for PatchId {
    fn alignment() -> Alignment {
        Alignment::B1
        Alignment::B8
    }
    fn onpage_size(&self) -> u16 {
        8
    }
    unsafe fn write_value(&self, p: *mut u8) {
        trace!("write_value {:?}", p);
        std::ptr::copy(self.0.as_ptr(), p, PATCH_ID_SIZE)
        LittleEndian::write_u64(std::slice::from_raw_parts_mut(p, 8), self.0)
    }
    unsafe fn read_value(p: *const u8) -> Self {
        trace!("read_value {:?}", p);
        let mut patch_id: PatchId = std::mem::uninitialized();
        std::ptr::copy(p, patch_id.0.as_mut_ptr(), 8);
        patch_id
        let x = PatchId(LittleEndian::read_u64(std::slice::from_raw_parts(p, 8)));
        trace!("read_value {:?} {:?}", p, x.to_base58());
        x
    }






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
        for (_, child) in self.iter_nodes(branch, Some((key, Some(e)))).take_while(
            for (_, grandchild) in self.iter_nodes(branch, Some((child.dest, Some(e))))
        for (_, parent) in self.iter_nodes(branch, Some((key, Some(e))))
                    for (_, grandparent) in self.iter_nodes(branch, Some((parent.dest, Some(e))))
            for (_, child) in self.iter_nodes(branch, Some((current_key, Some(e))))
                    for (_, grandchild) in self.iter_nodes(branch, Some((child.dest, Some(e))))
//! Manipulating the internal representation of files and directories
//! tracked by Pijul (i.e. adding files, removing files, getting file
//! names…).

use backend;
use backend::*;
use {Error, Result};
use fs_representation::{RepoPath, in_repo_root};

use rand;
use std;
use std::collections::BTreeMap;
use std::iter::Iterator;
use std::path::{Path, PathBuf};

impl<'env, R: rand::Rng> MutTxn<'env, R> {
    pub fn mark_inode_moved(&mut self, inode: Inode) {
        let mut header = None;
        if let Some(h) = self.get_inodes(inode) {
            header = Some(h.clone())
        }
        if let Some(mut h) = header {
            h.status = FileStatus::Moved;
            self.replace_inodes(inode, h).unwrap();
        }
    }

    /// Create an inode that doesn't exist in the repository, but
    /// doesn't put it into the repository.
    pub fn create_new_inode(&self) -> Inode {
        let mut already_taken = true;
        let mut inode: Inode = ROOT_INODE.clone();
        while already_taken {
            for i in inode.iter_mut() {
                *i = rand::random()
            }
            already_taken = self.get_revtree(inode).is_some();
        }
        inode
    }

    /// Record the information that `parent_inode` is now a parent of
    /// file `filename`, and `filename` has inode `child_inode`.
    fn make_new_child(
        &mut self,
        parent_inode: Inode,
        filename: &str,
        is_dir: bool,
        child_inode: Option<Inode>,
    ) -> Result<Inode> {
        let parent_id = OwnedFileId {
            parent_inode: parent_inode.clone(),
            basename: SmallString::from_str(filename),
        };
        if filename == ".pijul" {
            return Err(Error::CannotAddDotPijul);
        }
        if let Some(inode) = self.get_tree(&parent_id.as_file_id()) {
            // If we already have the file, make sure the file status
            // is Ok (i.e. not zombie, not deleted).
            let mut header = if let Some(header) = self.get_inodes(inode) {
                header.to_owned()
            } else {
                return Err(Error::AlreadyAdded);
            };
            if let FileStatus::Ok = header.status {
            } else {
                header.status = FileStatus::Ok;
                self.replace_inodes(inode, header)?;
            }
            Ok(inode)
        } else {
            // Else, add a new file.

            let child_inode = match child_inode {
                None => self.create_new_inode(),
                Some(i) => i.clone(),
            };
            self.put_tree(&parent_id.as_file_id(), child_inode)?;
            self.put_revtree(child_inode, &parent_id.as_file_id())?;

            if is_dir {
                // If this new file is a directory, add a name-less
                // file id without a reverse in revtree.
                let dir_id = OwnedFileId {
                    parent_inode: child_inode.clone(),
                    basename: SmallString::from_str(""),
                };
                self.put_tree(&dir_id.as_file_id(), child_inode)?;
            };
            Ok(child_inode)
        }
    }

    pub fn add_inode<P: AsRef<Path>>(
        &mut self,
        inode: Option<Inode>,
        path: &RepoPath<P>,
        is_dir: bool,
    ) -> Result<()> {
        if let Some(parent) = path.parent() {
            let (mut current_inode, unrecorded_path) =
                self.closest_in_repo_ancestor(&parent).unwrap();

            for c in unrecorded_path {
                current_inode =
                    self.make_new_child(current_inode, c.as_os_str().to_str().unwrap(), true, None)?
            }

            self.make_new_child(
                current_inode,
                path.file_name().unwrap().to_str().unwrap(),
                is_dir,
                inode,
            )?;
        }
        Ok(())
    }

    pub fn inode_is_ancestor_of(&self, a: Inode, mut b: Inode) -> bool {
        loop {
            if a == b {
                return true;
            }
            if let Some(b_parent) = self.get_revtree(b) {
                b = b_parent.parent_inode
            } else {
                return false;
            }
        }
    }

    pub fn move_file(
        &mut self,
        origin: &RepoPath<impl AsRef<Path>>,
        destination: &RepoPath<impl AsRef<Path>>,
        is_dir: bool,
    ) -> Result<()> {
        debug!("move_file: {},{}", origin.display(), destination.display());
        if let Some(parent) = origin.parent() {
            let fileref = OwnedFileId {
                parent_inode: self.find_inode(&parent)?,
                basename: SmallString::from_str(origin.file_name().unwrap().to_str().unwrap()),
            };

            if let Some(inode) = self.get_tree(&fileref.as_file_id()).map(|i| i.clone()) {
                // Now the last inode is in "*inode"
                debug!("txn.del fileref={:?}", fileref);
                self.del_tree(&fileref.as_file_id(), None)?;
                self.del_revtree(inode, None)?;

                debug!("inode={} destination={}", inode.to_hex(), destination.display());
                self.add_inode(Some(inode), destination, is_dir)?;
                self.mark_inode_moved(inode);

                return Ok(());
            }
        }
        Err(Error::FileNotInRepo(origin.to_path_buf()))
    }

    // Deletes a directory, given by its inode, recursively.
    pub fn rec_delete(&mut self, key: Inode) -> Result<bool> {
        debug!("rec_delete, key={:?}", key.to_hex());
        let file_id = OwnedFileId {
            parent_inode: key.clone(),
            basename: SmallString::from_str(""),
        };

        let children: Vec<(_, Inode)> = self
            .iter_tree(Some((&file_id.as_file_id(), None)))
            .take_while(|&(ref k, _)| key == k.parent_inode)
            .filter(|&(ref k, _)| !k.basename.is_empty())
            .map(|(k, v)| (k.to_owned(), v.to_owned()))
            .collect();

        let mut has_recorded_descendants = false;
        for (_, b) in children {
            debug!("deleting from tree {:?}", b);
            has_recorded_descendants |= self.rec_delete(b)?;
        }

        // Now that the directory is empty, mark the corresponding node as deleted (flag '2').
        if let Some(mut header) = self.get_inodes(key).map(|h| h.clone()) {
            // If this is was recorded, mark deleted.
            debug!("key {:?}, header = {:?}", key, header);
            header.status = FileStatus::Deleted;
            self.replace_inodes(key, header)?;
            debug!("after = {:?}", self.get_inodes(key).map(|h| h.clone()));
        } else if !has_recorded_descendants {
            // Else, simply delete from the tree.
            let parent = self.get_revtree(key).unwrap().to_owned();
            debug!("key = {:?}, parent = {:?}", key, parent);
            self.del_tree(&parent.as_file_id(), None)?;
            self.del_revtree(key, None)?;
        }
        Ok(has_recorded_descendants)
    }

    /// Removes a file from the repository.
    pub fn remove_file(&mut self, path: &RepoPath<impl AsRef<Path>>)
                       -> Result<()> {
        debug!("remove_file");
        let inode = self.find_inode(path)?;
        debug!("rec_delete");
        self.rec_delete(inode)?;
        debug!("/rec_delete");
        Ok(())
    }
}

impl<A: Transaction, R> backend::GenericTxn<A, R> {
    /// Traverses the `tree` base recursively, collecting all descendants of `key`.
    fn collect(
        &self,
        key: Inode,
        current_path: &RepoPath<impl AsRef<Path>>,
        basename: &str,
        files: &mut Vec<RepoPath<PathBuf>>,
    ) -> Result<()> {
        debug!("collecting {:?},{:?}", key, basename);
        let add = match self.get_inodes(key) {
            Some(inode) => {
                debug!("node = {:?}", inode);
                inode.status != FileStatus::Deleted
            }
            None => true,
        };
        if add {
            debug!("basename = {:?}", basename);
            
            let next_pb = current_path.join(Path::new(basename));
            if basename.len() > 0 {
                files.push(next_pb.clone())
            }

            debug!("starting iterator, key={:?}", key);
            let fileid = OwnedFileId {
                parent_inode: key.clone(),
                basename: SmallString::from_str(""),
            };
            for (k, v) in self
                .iter_tree(Some((&fileid.as_file_id(), None)))
                .take_while(|&(ref k, _)| k.parent_inode == key)
            {
                debug!("iter: {:?} {:?}", k, v);
                if k.basename.len() > 0 {
                    self.collect(v.to_owned(), &next_pb, k.basename.as_str(), files)?;
                }
            }
            debug!("ending iterator {:?}", {
                let v: Vec<_> = self.iter_tree(Some((&fileid.as_file_id(), None))).collect();
                v
            });
        }
        Ok(())
    }

    /// Returns a vector containing all files in the repository.
    pub fn list_files(&self, inode: Inode) -> Result<Vec<RepoPath<PathBuf>>> {
        debug!("list_files {:?}", inode);
        let mut files = Vec::new();
        self.collect(inode, &in_repo_root(), "", &mut files)?;
        Ok(files)
    }

    /// Returns a list of files under the given inode.
    pub fn list_files_under_inode(
        &self,
        inode: Inode,
    ) -> Vec<(SmallString, Option<Key<PatchId>>, Inode)> {
        let mut result = Vec::new();

        let file_id = OwnedFileId {
            parent_inode: inode,
            basename: SmallString::from_str(""),
        };
        for (k, v) in self
            .iter_tree(Some((&file_id.as_file_id(), None)))
            .take_while(|&(ref k, _)| k.parent_inode == inode)
        {
            let header = self.get_inodes(k.parent_inode).map(|x| x.clone());
            // add: checking that this file has neither been moved nor deleted.
            println!("============= {:?} {:?}", k, v);
            let add = match header {
                Some(ref h) => h.status == FileStatus::Ok,
                None => true,
            };
            if add && k.basename.len() > 0 {
                result.push((
                    k.basename.to_owned(),
                    header.map(|h| h.key.clone()),
                    v.clone(),
                ))
            }
        }

        result
    }

    /// Returns a list of files under the given inode.
    pub fn list_files_under_node(
        &self,
        branch: &Branch,
        key: Key<PatchId>,
    ) -> BTreeMap<Key<PatchId>, Vec<(FileMetadata, &str)>> {
        let mut result = BTreeMap::new();

        let e = Edge::zero(EdgeFlags::FOLDER_EDGE);
        for (_, child) in self.iter_nodes(branch, Some((key, Some(&e)))).take_while(
        for (_, child) in self
            .iter_nodes(branch, Some((key, Some(e))))
            .take_while(|&(k, ref v)| {
                k == key && v.flag <= EdgeFlags::FOLDER_EDGE | EdgeFlags::PSEUDO_EDGE
            })
        {
            let name = self.get_contents(child.dest).unwrap();
            // This is supposed to be a small string anyway.
            let (perms, basename) = name.as_slice().split_at(2);
            let perms = FileMetadata::from_contents(perms);
            let basename = std::str::from_utf8(basename).unwrap();

            for (_, grandchild) in self.iter_nodes(branch, Some((child.dest, Some(&e))))
            for (_, grandchild) in self
                .iter_nodes(branch, Some((child.dest, Some(e))))
                .take_while(|&(k, ref v)| {
                    k == child.dest && v.flag <= EdgeFlags::FOLDER_EDGE | EdgeFlags::PSEUDO_EDGE
                })
            {
                let names = result.entry(grandchild.dest.to_owned()).or_insert(vec![]);
                names.push((perms, basename))
            }
        }
        result
    }

    pub fn is_directory(&self, inode: &Inode) -> bool {
        let file_id = OwnedFileId {
            parent_inode: inode.clone(),
            basename: SmallString::from_str(""),
        };
        inode == &ROOT_INODE || self.get_tree(&file_id.as_file_id()).is_some()
    }

    /// Splits a path into (1) the deepest inode from the root that is
    /// an ancestor of the path or the path itself and (2) the
    /// remainder of this path
    fn closest_in_repo_ancestor<'a>(
        &self,
        path: &'a RepoPath<impl AsRef<Path>>
    ) -> Result<(Inode, std::iter::Peekable<std::path::Components<'a>>)> {
        let mut components = path.components().peekable();
        let mut fileid = OwnedFileId {
            parent_inode: ROOT_INODE,
            basename: SmallString::from_str(""),
        };

        loop {
            if let Some(c) = components.peek() {
                fileid.basename = SmallString::from_str(c.as_os_str().to_str().unwrap());
                if let Some(v) = self.get_tree(&fileid.as_file_id()) {
                    fileid.parent_inode = v.clone()
                } else {
                    break;
                }
            } else {
                break;
            }
            components.next();
        }
        Ok((fileid.parent_inode.clone(), components))
    }

    /// Find the inode corresponding to that path, or return an error if there's no such inode.
    pub fn find_inode(&self, path: &RepoPath<impl AsRef<Path>>)
                      -> Result<Inode> {
        let (inode, mut remaining_path_components) = self.closest_in_repo_ancestor(path)?;
        if remaining_path_components.next().is_none() {
            Ok(inode)
        } else {
            Err(Error::FileNotInRepo(path.to_path_buf()))
        }
    }

    pub fn file_names(
        &self,
        branch: &Branch,
        key: Key<PatchId>,
    ) -> Vec<(Key<PatchId>, FileMetadata, &str)> {
        let mut result = Vec::new();
        let e = Edge::zero(EdgeFlags::FOLDER_EDGE | EdgeFlags::PARENT_EDGE);

        debug!("file_names, key {:?}", key);
        for (_, parent) in self.iter_nodes(branch, Some((key, Some(&e))))
        for (_, parent) in self
            .iter_nodes(branch, Some((key, Some(e))))
            .take_while(|&(k, _)| k == key)
            .filter(|&(_, ref v)| {
                v.flag
                    .contains(EdgeFlags::FOLDER_EDGE | EdgeFlags::PARENT_EDGE)
            })
        {
            debug!("file_names, parent {:?}", parent);
            match self.get_contents(parent.dest) {
                Some(ref name) if name.len() >= 2 => {
                    // This is supposed to be a small string anyway.
                    let (perms, basename) = name.as_slice().split_at(2);
                    let perms = FileMetadata::from_contents(perms);
                    let basename = std::str::from_utf8(basename).unwrap();

                    for (_, grandparent) in self.iter_nodes(branch, Some((parent.dest, Some(&e))))
                    for (_, grandparent) in self
                        .iter_nodes(branch, Some((parent.dest, Some(e))))
                        .take_while(|&(k, _)| k == parent.dest)
                        .filter(|&(_, ref v)| {
                            v.flag
                                .contains(EdgeFlags::FOLDER_EDGE | EdgeFlags::PARENT_EDGE)
                        })
                    {
                        result.push((grandparent.dest.to_owned(), perms, basename));
                        break;
                    }
                }
                _ => error!("Key: {:?}, file {}, line {}", key, file!(), line!()),
            }
        }
        result
    }

    pub fn prefix_keys(&self, branch: &Branch, path: &RepoPath<impl AsRef<Path>>)
                       -> Result<Vec<Key<PatchId>>> {
        let mut result = Vec::new();
        let e = Edge::zero(EdgeFlags::FOLDER_EDGE);

        let mut current_key = ROOT_KEY;

        for comp in path.components() {
            let mut is_first = true;
            let cur = current_key;
            for (_, child) in self.iter_nodes(branch, Some((current_key, Some(&e))))
            for (_, child) in self
                .iter_nodes(branch, Some((current_key, Some(e))))
                .take_while(|&(k, _)| k == cur)
                .filter(|&(_, ref v)| v.flag.contains(EdgeFlags::FOLDER_EDGE))
            {
                let contents = self.get_contents(child.dest).unwrap();
                if contents.into_cow().split_at(2).1
                    == comp.as_os_str().to_str().expect("file encoding problem").as_bytes() {
                    if !is_first {
                        return Err(Error::FileNameCount(current_key));
                    }

                    for (_, grandchild) in self.iter_nodes(branch, Some((child.dest, Some(&e))))
                    for (_, grandchild) in self
                        .iter_nodes(branch, Some((child.dest, Some(e))))
                        .take_while(|&(k, _)| k == child.dest)


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
                                Some((self[*cousin].key, Some(edge))),
                            forward.extend(edges.map(|(k, v)| (k, v))); // add all parallel edges.
//! The data structure of the in-memory version of Pijul's main
//! datastructure, used to edit and organise it (for instance before a
//! record or before outputting a file).
use backend::*;
use conflict;
use std::cmp::min;
use std::collections::{HashMap, HashSet};
use Result;

use rand;
use std;

mod dfs;
use self::dfs::{DFS, Path, PathElement};

bitflags! {
    struct Flags: u8 {
        const LINE_HALF_DELETED = 4;
        const LINE_VISITED = 2;
        const LINE_ONSTACK = 1;
    }
}

/// The elementary datum in the representation of the repository state
/// at any given point in time. We need this structure (as opposed to
/// working directly on a branch) in order to add more data, such as
/// strongly connected component identifier, to each node.
#[derive(Debug)]
pub struct Line {
    /// The internal identifier of the line.
    pub key: Key<PatchId>,

    // The status of the line with respect to a dfs of
    // a graph it appears in. This is 0 or
    // `LINE_HALF_DELETED`.
    flags: Flags,
    children: usize,
    n_children: usize,
    index: usize,
    lowlink: usize,
    scc: usize,
}

impl Line {
    pub fn is_zombie(&self) -> bool {
        self.flags.contains(Flags::LINE_HALF_DELETED)
    }
}

/// A graph, representing the whole content of the repository state at
/// a point in time. The encoding is a "flat adjacency list", where
/// each vertex contains a index `children` and a number of children
/// `n_children`. The children of that vertex are then
/// `&g.children[children .. children + n_children]`.
#[derive(Debug)]
pub struct Graph {
    /// Array of all alive lines in the graph. Line 0 is a dummy line
    /// at the end, so that all nodes have a common successor
    pub lines: Vec<Line>,
    /// Edge + index of the line in the "lines" array above. "None"
    /// means "dummy line at the end", and corresponds to line number
    /// 0.
    children: Vec<(Option<Edge>, VertexId)>,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
struct VertexId(usize);

const DUMMY_VERTEX: VertexId = VertexId(0);

impl std::ops::Index<VertexId> for Graph {
    type Output = Line;
    fn index(&self, idx: VertexId) -> &Self::Output {
        self.lines.index(idx.0)
    }
}
impl std::ops::IndexMut<VertexId> for Graph {
    fn index_mut(&mut self, idx: VertexId) -> &mut Self::Output {
        self.lines.index_mut(idx.0)
    }
}

use std::io::Write;

impl Graph {
    fn children(&self, i: VertexId) -> &[(Option<Edge>, VertexId)] {
        let ref line = self[i];
        &self.children[line.children..line.children + line.n_children]
    }

    fn child(&self, i: VertexId, j: usize) -> &(Option<Edge>, VertexId) {
        &self.children[self[i].children + j]
    }

    pub fn debug<W: Write, R, A: Transaction>(
        &self,
        txn: &GenericTxn<A, R>,
        branch: &Branch,
        add_others: bool,
        introduced_by: bool,
        mut w: W,
    ) -> std::io::Result<()> {
        writeln!(w, "digraph {{")?;
        let mut cache = HashMap::new();
        if add_others {
            for (line, i) in self.lines.iter().zip(0..) {
                cache.insert(line.key, i);
            }
        }
        let mut others = HashSet::new();
        for (line, i) in self.lines.iter().zip(0..) {
            let contents = {
                if let Some(c) = txn.get_contents(line.key) {
                    let c = c.into_cow();
                    if let Ok(c) = std::str::from_utf8(&c) {
                        c.split_at(std::cmp::min(50, c.len())).0.to_string()
                    } else {
                        "<INVALID>".to_string()
                    }
                } else {
                    "".to_string()
                }
            };
            let contents = format!("{:?}", contents);
            let contents = contents.split_at(contents.len() - 1).0.split_at(1).1;
            writeln!(
                w,
                "n_{}[label=\"{}: {}.{}: {}\"];",
                i,
                i,
                line.key.patch.to_base58(),
                line.key.line.to_hex(),
                contents
            )?;

            if add_others && !line.key.is_root() {
                for v in txn.iter_adjacent(branch, line.key, EdgeFlags::empty(), EdgeFlags::all()) {
                    if let Some(dest) = cache.get(&v.dest) {
                        writeln!(
                            w,
                            "n_{} -> n_{}[color=red,label=\"{:?}{}{}\"];",
                            i,
                            dest,
                            v.flag.bits(),
                            if introduced_by { " " } else { "" },
                            if introduced_by {
                                v.introduced_by.to_base58()
                            } else {
                                String::new()
                            }
                        )?;
                    } else {
                        if !others.contains(&v.dest) {
                            others.insert(v.dest);
                            writeln!(
                                w,
                                "n_{}[label=\"{}.{}\",color=red];",
                                v.dest.to_base58(),
                                v.dest.patch.to_base58(),
                                v.dest.line.to_hex()
                            )?;
                        }
                        writeln!(
                            w,
                            "n_{} -> n_{}[color=red,label=\"{:?}{}{}\"];",
                            i,
                            v.dest.to_base58(),
                            v.flag.bits(),
                            if introduced_by { " " } else { "" },
                            if introduced_by {
                                v.introduced_by.to_base58()
                            } else {
                                String::new()
                            }
                        )?;
                    }
                }
            }
            for &(ref edge, VertexId(j)) in
                &self.children[line.children..line.children + line.n_children]
            {
                if let Some(ref edge) = *edge {
                    writeln!(
                        w,
                        "n_{}->n_{}[label=\"{:?}{}{}\"];",
                        i,
                        j,
                        edge.flag.bits(),
                        if introduced_by { " " } else { "" },
                        if introduced_by {
                            edge.introduced_by.to_base58()
                        } else {
                            String::new()
                        }
                    )?
                } else {
                    writeln!(w, "n_{}->n_{}[label=\"none\"];", i, j)?
                }
            }
        }
        writeln!(w, "}}")?;
        Ok(())
    }
}

use sanakirja::value::Value;
/// A "line outputter" trait.
pub trait LineBuffer<'a, T: 'a + Transaction> {
    fn output_line(&mut self, key: &Key<PatchId>, contents: Value<'a, T>) -> Result<()>;

    fn output_conflict_marker(&mut self, s: &'a str) -> Result<()>;
    fn begin_conflict(&mut self) -> Result<()> {
        self.output_conflict_marker(conflict::START_MARKER)
    }
    fn begin_zombie_conflict(&mut self) -> Result<()> {
        self.begin_conflict()
    }
    fn conflict_next(&mut self) -> Result<()> {
        self.output_conflict_marker(conflict::SEPARATOR)
    }
    fn end_conflict(&mut self) -> Result<()> {
        self.output_conflict_marker(conflict::END_MARKER)
    }
}

pub struct Writer<W: std::io::Write> {
    pub w: W,
    new_line: bool,
}

impl<W: std::io::Write> Writer<W> {
    pub fn new(w: W) -> Self {
        Writer { w, new_line: true }
    }
}

impl<W: std::io::Write> std::ops::Deref for Writer<W> {
    type Target = W;
    fn deref(&self) -> &Self::Target {
        &self.w
    }
}

impl<W: std::io::Write> std::ops::DerefMut for Writer<W> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.w
    }
}

impl<'a, T: 'a + Transaction, W: std::io::Write> LineBuffer<'a, T> for Writer<W> {
    fn output_line(&mut self, k: &Key<PatchId>, c: Value<T>) -> Result<()> {
        let mut ends_with_newline = false;
        let mut is_empty = true;
        for chunk in c {
            debug!("output line {:?} {:?}", k, std::str::from_utf8(chunk));
            is_empty = is_empty && chunk.is_empty();
            ends_with_newline = chunk.ends_with(b"\n");
            self.w.write_all(chunk)?
        }
        if !is_empty {
            // empty "lines" (such as in the beginning of a file)
            // don't change the status of self.new_line.
            self.new_line = ends_with_newline;
        }
        Ok(())
    }

    fn output_conflict_marker(&mut self, s: &'a str) -> Result<()> {
        debug!("output_conflict_marker {:?}", self.new_line);
        if !self.new_line {
            self.w.write(s.as_bytes())?;
        } else {
            debug!("{:?}", &s.as_bytes()[1..]);
            self.w.write(&s.as_bytes()[1..])?;
        }
        Ok(())
    }
}

impl Graph {
    /// Tarjan's strongly connected component algorithm, returning a
    /// vector of strongly connected components, where each SCC is a
    /// vector of vertex indices.
    fn tarjan(&mut self) -> Vec<Vec<VertexId>> {
        if self.lines.len() <= 1 {
            return vec![vec![VertexId(0)]];
        }

        let mut call_stack = vec![(VertexId(1), 0, true)];

        let mut index = 0;
        let mut stack = Vec::new();
        let mut scc = Vec::new();
        while let Some((n_l, i, first_visit)) = call_stack.pop() {
            if first_visit {
                // First time we visit this node.
                let ref mut l = self[n_l];
                l.index = index;
                l.lowlink = index;
                l.flags = l.flags | Flags::LINE_ONSTACK | Flags::LINE_VISITED;
                debug!("tarjan {:?} {:?} chi", l.key, l.n_children);
                stack.push(n_l);
                index = index + 1;
            } else {
                let &(_, n_child) = self.child(n_l, i);
                self[n_l].lowlink = std::cmp::min(self[n_l].lowlink, self[n_child].lowlink);
            }

            let call_stack_length = call_stack.len();
            for j in i..self[n_l].n_children {
                let &(_, n_child) = self.child(n_l, j);
                if !self[n_child].flags.contains(Flags::LINE_VISITED) {
                    call_stack.push((n_l, j, false));
                    call_stack.push((n_child, 0, true));
                    break;
                // self.tarjan_dfs(scc, stack, index, n_child);
                } else {
                    if self[n_child].flags.contains(Flags::LINE_ONSTACK) {
                        self[n_l].lowlink = min(self[n_l].lowlink, self[n_child].index)
                    }
                }
            }
            if call_stack_length < call_stack.len() {
                // recursive call
                continue;
            }
            // Here, all children of n_l have been visited.

            if self[n_l].index == self[n_l].lowlink {
                let mut v = Vec::new();
                loop {
                    match stack.pop() {
                        None => break,
                        Some(n_p) => {
                            self[n_p].scc = scc.len();
                            self[n_p].flags = self[n_p].flags ^ Flags::LINE_ONSTACK;
                            v.push(n_p);
                            if n_p == n_l {
                                break;
                            }
                        }
                    }
                }
                scc.push(v);
            }
        }
        scc
    }
}

impl<A: Transaction, R> GenericTxn<A, R> {
    /// This function constructs a graph by reading the branch from the
    /// input key. It guarantees that all nodes but the first one (index
    /// 0) have a common descendant, which is index 0.
    pub fn retrieve<'a>(&'a self, branch: &Branch, key0: Key<PatchId>) -> Graph {
        let mut graph = Graph {
            lines: Vec::new(),
            children: Vec::new(),
        };
        // Insert last "dummy" line (so that all lines have a common descendant).
        graph.lines.push(Line {
            key: ROOT_KEY,
            flags: Flags::empty(),
            children: 0,
            n_children: 0,
            index: 0,
            lowlink: 0,
            scc: 0,
        });

        // Avoid the root key.
        let mut cache: HashMap<Key<PatchId>, VertexId> = HashMap::new();
        cache.insert(ROOT_KEY.clone(), DUMMY_VERTEX);
        let mut stack = Vec::new();
        if self.get_nodes(&branch, key0, None).is_some() {
            stack.push(key0)
        }
        while let Some(key) = stack.pop() {
            if cache.contains_key(&key) {
                // We're doing a DFS here, this can definitely happen.
                continue;
            }

            let idx = VertexId(graph.lines.len());
            cache.insert(key.clone(), idx);

            debug!("{:?}", key);
            let mut is_zombie = false;
            // Does this vertex have a DELETED/DELETED+FOLDER edge
            // pointing to it?
            let mut first_edge = Edge::zero(EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE);
            let mut nodes = self.iter_nodes(&branch, Some((key, Some(&first_edge))));
            let mut nodes = self.iter_nodes(&branch, Some((key, Some(first_edge))));
            if let Some((k, v)) = nodes.next() {
                debug!("zombie? {:?} {:?}", k, v);
                if k == key
                    && (v.flag | EdgeFlags::FOLDER_EDGE == first_edge.flag | EdgeFlags::FOLDER_EDGE)
                {
                    // Does this vertex also have an alive edge
                    // pointing to it? (might not be the case for the
                    // first vertex)
                    if key == key0 {
                        first_edge.flag = EdgeFlags::PARENT_EDGE;
                        nodes = self.iter_nodes(&branch, Some((key, Some(&first_edge))));
                        nodes = self.iter_nodes(&branch, Some((key, Some(first_edge))));
                        if let Some((_, v)) = nodes.next() {

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


238


241
242

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


                    for (_, v) in self.iter_nodes(branch, Some((key, Some(e))))
//! This crate contains the core API to access Pijul repositories.
//!
//! The key object is a `Repository`, on which `Txn` (immutable
//! transactions) and `MutTxn` (mutable transactions) can be started,
//! to perform a variety of operations.
//!
//! Another important object is a `Patch`, which encodes two different pieces of information:
//!
//! - Information about deleted and inserted lines between two versions of a file.
//!
//! - Information about file moves, additions and deletions.
//!
//! The standard layout of a repository is defined in module
//! `fs_representation`, and mainly consists of a directory called
//! `.pijul` at the root of the repository, containing:
//!
//! - a directory called `pristine`, containing a Sanakirja database
//! storing most of the repository information.
//!
//! - a directory called `patches`, actually containing the patches,
//! where each patch is a gzipped compression of the bincode encoding
//! of the `patch::Patch` type.
//!
//! At the moment, users of this library, such as the Pijul
//! command-line tool, may use other files in the `.pijul` directory,
//! such as user preferences, or information about remote branches and
//! repositories.
#![recursion_limit = "128"]
#[macro_use]
extern crate bitflags;
extern crate chrono;
#[macro_use]
extern crate log;

extern crate base64;
extern crate bincode;
extern crate bs58;
extern crate byteorder;
extern crate flate2;
extern crate hex;
extern crate ignore;
extern crate openssl;
extern crate rand;
extern crate sanakirja;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate diffs;
extern crate failure;
extern crate sequoia_openpgp;
extern crate serde_json;
extern crate tempdir;
extern crate toml;

pub use sanakirja::Transaction;
use std::collections::HashSet;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;

#[derive(Debug)]
pub enum Error {
    IO(std::io::Error),
    Sanakirja(sanakirja::Error),
    Bincode(bincode::Error),
    Utf8(std::str::Utf8Error),
    Serde(serde_json::Error),
    OpenSSL(openssl::error::Error),
    OpenSSLStack(openssl::error::ErrorStack),
    Base58Decode(bs58::decode::DecodeError),
    Failure(failure::Error),
    AlreadyAdded,
    FileNotInRepo(PathBuf),
    NoDb(backend::Root),
    WrongHash,
    EOF,
    WrongPatchSignature,
    BranchNameAlreadyExists(String),
    WrongFileHeader(Key<PatchId>),
    FileNameCount(Key<PatchId>),
    MissingDependency(Hash),
    PatchNotOnBranch(PatchId),
    CannotAddDotPijul,
    KeyIsEncrypted,
}

impl std::convert::From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Error::IO(e)
    }
}

impl std::convert::From<failure::Error> for Error {
    fn from(e: failure::Error) -> Self {
        Error::Failure(e)
    }
}

impl std::convert::From<sanakirja::Error> for Error {
    fn from(e: sanakirja::Error) -> Self {
        Error::Sanakirja(e)
    }
}

impl std::convert::From<bincode::Error> for Error {
    fn from(e: bincode::Error) -> Self {
        Error::Bincode(e)
    }
}

impl std::convert::From<serde_json::Error> for Error {
    fn from(e: serde_json::Error) -> Self {
        Error::Serde(e)
    }
}

impl std::convert::From<std::str::Utf8Error> for Error {
    fn from(e: std::str::Utf8Error) -> Self {
        Error::Utf8(e)
    }
}

impl std::convert::From<openssl::error::ErrorStack> for Error {
    fn from(e: openssl::error::ErrorStack) -> Self {
        Error::OpenSSLStack(e)
    }
}

impl std::convert::From<bs58::decode::DecodeError> for Error {
    fn from(e: bs58::decode::DecodeError) -> Self {
        Error::Base58Decode(e)
    }
}

pub type Result<A> = std::result::Result<A, Error>;

impl std::fmt::Display for Error {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        match *self {
            Error::IO(ref e) => e.fmt(fmt),
            Error::Sanakirja(ref e) => e.fmt(fmt),
            Error::Bincode(ref e) => e.fmt(fmt),
            Error::Utf8(ref e) => e.fmt(fmt),
            Error::Serde(ref e) => e.fmt(fmt),
            Error::OpenSSL(ref e) => e.fmt(fmt),
            Error::OpenSSLStack(ref e) => e.fmt(fmt),
            Error::Base58Decode(ref e) => e.fmt(fmt),
            Error::Failure(ref e) => e.fmt(fmt),
            Error::AlreadyAdded => write!(fmt, "Already added"),
            Error::FileNotInRepo(ref file) => write!(fmt, "File {:?} not tracked", file),
            Error::NoDb(ref e) => write!(fmt, "Table missing: {:?}", e),
            Error::WrongHash => write!(fmt, "Wrong hash"),
            Error::EOF => write!(fmt, "EOF"),
            Error::WrongPatchSignature => write!(fmt, "Wrong patch signature"),
            Error::BranchNameAlreadyExists(ref name) => {
                write!(fmt, "Branch {:?} already exists", name)
            }
            Error::WrongFileHeader(ref h) => write!(
                fmt,
                "Wrong file header (possible branch corruption): {:?}",
                h
            ),
            Error::FileNameCount(ref f) => {
                write!(fmt, "Name {:?} doesn't have exactly one child", f)
            }
            Error::MissingDependency(ref f) => write!(fmt, "Missing dependency: {:?}", f),
            Error::PatchNotOnBranch(ref f) => {
                write!(fmt, "The patch is not on this branch {:?}", f)
            }
            Error::CannotAddDotPijul => write!(fmt, "Cannot add a file or directory name .pijul"),
            Error::KeyIsEncrypted => write!(fmt, "Key is encrypted"),
        }
    }
}

impl std::error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::IO(ref e) => e.description(),
            Error::Sanakirja(ref e) => e.description(),
            Error::Bincode(ref e) => e.description(),
            Error::Utf8(ref e) => e.description(),
            Error::Serde(ref e) => e.description(),
            Error::OpenSSL(ref e) => e.description(),
            Error::OpenSSLStack(ref e) => e.description(),
            Error::Base58Decode(ref e) => e.description(),
            Error::Failure(ref e) => e.name().unwrap_or("Unknown Failure"),
            Error::AlreadyAdded => "Already added",
            Error::FileNotInRepo(_) => "File not tracked",
            Error::NoDb(_) => "One of the tables is missing",
            Error::WrongHash => "Wrong hash",
            Error::EOF => "EOF",
            Error::WrongPatchSignature => "Wrong patch signature",
            Error::BranchNameAlreadyExists(_) => "Branch name already exists",
            Error::WrongFileHeader(_) => "Wrong file header (possible branch corruption)",
            Error::FileNameCount(_) => "A file name doesn't have exactly one child",
            Error::MissingDependency(_) => "Missing dependency",
            Error::PatchNotOnBranch(_) => "The patch is not on this branch",
            Error::CannotAddDotPijul => "Cannot add a file or directory name .pijul",
            Error::KeyIsEncrypted => "Key is encrypted",
        }
    }
}

impl Error {
    pub fn lacks_space(&self) -> bool {
        match *self {
            Error::Sanakirja(sanakirja::Error::NotEnoughSpace) => true,
            _ => false,
        }
    }
}

#[macro_use]
mod backend;
mod file_operations;
pub mod fs_representation;

pub mod patch;
pub mod status;

pub mod apply;
mod conflict;
mod diff;
pub mod graph;
mod output;
mod record;
mod unrecord;

pub use backend::{
    ApplyTimestamp, Branch, Edge, EdgeFlags, FileId, FileMetadata, FileStatus, GenericTxn, Hash,
    HashRef, Inode, Key, LineId, MutTxn, OwnedFileId, PatchId, Repository, SmallStr, SmallString,
    Txn, DEFAULT_BRANCH, ROOT_INODE, ROOT_KEY,
};


>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
use fs_representation::{RepoRoot, ID_LENGTH};

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

================================
pub use fs_representation::{RepoRoot, RepoPath};
use fs_representation::{ID_LENGTH};

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
pub use output::{ConflictingFile, Prefixes, ToPrefixes};
pub use patch::{Patch, PatchHeader};
use rand::distributions::Alphanumeric;
use rand::Rng;
pub use record::{InodeUpdate, RecordState};
pub use sanakirja::value::Value;
use std::io::Read;

pub use diff::Algorithm as DiffAlgorithm;

impl<'env, T: rand::Rng> backend::MutTxn<'env, T> {
    pub fn output_changes_file<P: AsRef<Path>>(
        &mut self,
        branch: &Branch,
        fs_repo: &RepoRoot<P>,
    ) -> Result<()> {
        let changes_file = fs_repo.branch_changes_file(branch.name.as_str());
        let mut branch_id: Vec<u8> = vec![b'\n'; ID_LENGTH + 1];
        {
            if let Ok(mut file) = std::fs::File::open(&changes_file) {
                file.read_exact(&mut branch_id)?;
            }
        }
        let mut branch_id = if let Ok(s) = String::from_utf8(branch_id) {
            s
        } else {
            "\n".to_string()
        };
        if branch_id.as_bytes()[0] == b'\n' {
            branch_id.truncate(0);
            let mut rng = rand::thread_rng();
            branch_id.extend(rng.sample_iter(&Alphanumeric).take(ID_LENGTH));
            branch_id.push('\n');
        }

        let mut file = std::fs::File::create(&changes_file)?;
        file.write_all(&branch_id.as_bytes())?;
        for (s, hash) in self.iter_applied(&branch, None) {
            let hash_ext = self.get_external(hash).unwrap();
            writeln!(file, "{}:{}", hash_ext.to_base58(), s)?
        }
        Ok(())
    }

    pub fn branch_patches(&mut self, branch: &Branch) -> HashSet<(backend::Hash, ApplyTimestamp)> {
        self.iter_patches(branch, None)
            .map(|(patch, time)| (self.external_hash(patch).to_owned(), time))
            .collect()
    }

    pub fn fork(&mut self, branch: &Branch, new_name: &str) -> Result<Branch> {
        if branch.name.as_str() == new_name {
            Err(Error::BranchNameAlreadyExists(new_name.to_string()))
        } else {
            Ok(Branch {
                db: self.txn.fork(&mut self.rng, &branch.db)?,
                patches: self.txn.fork(&mut self.rng, &branch.patches)?,
                revpatches: self.txn.fork(&mut self.rng, &branch.revpatches)?,
                name: SmallString::from_str(new_name),
                apply_counter: branch.apply_counter,
            })
        }
    }
    
    pub fn add_file<P: AsRef<Path>>(&mut self, path: &RepoPath<P>, is_dir: bool) -> Result<()> {
        self.add_inode(None, path, is_dir)
    }

    fn file_nodes_fold_<A, F: FnMut(A, Key<PatchId>) -> A>(
        &self,
        branch: &Branch,
        root: Key<PatchId>,
        level: usize,
        mut init: A,
        f: &mut F,
    ) -> Result<A> {
        for v in self
            .iter_adjacent(&branch, root, EdgeFlags::empty(), EdgeFlags::all())
            .take_while(|v| {
                v.flag.contains(EdgeFlags::FOLDER_EDGE) && !v.flag.contains(EdgeFlags::PARENT_EDGE)
            })
        {
            debug!("file_nodes_fold_: {:?} {:?}", root, v);
            if level & 1 == 0 && level > 0 {
                init = f(init, root)
            }
            init = self.file_nodes_fold_(branch, v.dest, level + 1, init, f)?
        }
        Ok(init)
    }

    pub fn file_nodes_fold<A, F: FnMut(A, Key<PatchId>) -> A>(
        &self,
        branch: &Branch,
        init: A,
        mut f: F,
    ) -> Result<A> {
        self.file_nodes_fold_(branch, ROOT_KEY, 0, init, &mut f)
    }
}

impl<T: Transaction, R> backend::GenericTxn<T, R> {
    /// Tells whether a `key` is alive in `branch`, i.e. is either the
    /// root, or all its ingoing edges are alive.
    pub fn is_alive(&self, branch: &Branch, key: Key<PatchId>) -> bool {
        debug!("is_alive {:?}?", key);
        let mut alive = key == ROOT_KEY;
        let mut alive = key.is_root();
        let e = Edge::zero(EdgeFlags::PARENT_EDGE);
        for (k, v) in self.iter_nodes(&branch, Some((key, Some(&e)))) {
        for (k, v) in self.iter_nodes(&branch, Some((key, Some(e)))) {
            if k != key {
                break;
            }
            alive = alive
                || (!v.flag.contains(EdgeFlags::DELETED_EDGE)
                    && !v.flag.contains(EdgeFlags::PSEUDO_EDGE))
        }
        alive
    }

    /// Tells whether a `key` is alive or zombie in `branch`, i.e. is
    /// either the root, or has at least one of its incoming alive
    /// edge is alive.
    pub fn is_alive_or_zombie(&self, branch: &Branch, key: Key<PatchId>) -> bool {
        debug!("is_alive_or_zombie {:?}?", key);
        if key == ROOT_KEY {
            return true;
        }
        let e = Edge::zero(EdgeFlags::PARENT_EDGE);
        for (k, v) in self.iter_nodes(&branch, Some((key, Some(&e)))) {
        for (k, v) in self.iter_nodes(&branch, Some((key, Some(e)))) {
            if k != key {
                break;
            }
            debug!("{:?}", v);
            if v.flag.contains(EdgeFlags::PARENT_EDGE) && !v.flag.contains(EdgeFlags::DELETED_EDGE)
            {
                return true;
            }
        }
        false
    }

    /// Test whether `key` has a neighbor with flag `flag0`. If
    /// `include_pseudo`, this includes pseudo-neighbors.
    pub fn has_edge(
        &self,
        branch: &Branch,
        key: Key<PatchId>,
        min: EdgeFlags,
        max: EdgeFlags,
    ) -> bool {
        let e = Edge::zero(min);
        if let Some((k, v)) = self.iter_nodes(&branch, Some((key, Some(&e)))).next() {
        if let Some((k, v)) = self.iter_nodes(&branch, Some((key, Some(e)))).next() {
            debug!("has_edge {:?}", v.flag);
            k == key && (v.flag <= max)
        } else {
            false
        }
    }

    /// Tells which paths (of folder nodes) a key is in.
    pub fn get_file<'a>(&'a self, branch: &Branch, key: Key<PatchId>) -> Vec<Key<PatchId>> {
        let mut stack = vec![key.to_owned()];
        let mut seen = HashSet::new();
        let mut names = Vec::new();
        loop {
            match stack.pop() {
                None => break,
                Some(key) if !seen.contains(&key) => {
                    debug!("key {:?}, None", key);
                    seen.insert(key.clone());

                    for v in self.iter_adjacent(branch, key, EdgeFlags::empty(), EdgeFlags::all()) {
                        debug!("all_edges: {:?}", v);
                    }
                    for (_, v) in self.iter_nodes(branch, Some((key, Some(&e))))
                    for (_, v) in self.iter_nodes(branch, Some((key, Some(&e))))


                for (k, v) in self.iter_nodes(&branch, Some((key, Some(edge))))
                        let mut edges = self.iter_nodes(&branch, Some((key, Some(edge))));



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
        for (_, b) in self.iter_nodes(&branch, Some((key, Some(e))))
            let (_, b_key) = self.iter_nodes(&branch, Some((b.dest, Some(e))))
                        self.iter_nodes(&branch, Some((b_key.dest, Some(e))))
use backend::*;
use graph;
use patch::*;
use rand;
use record::InodeUpdate;
use std;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use tempdir;
use {Error, Result};

use super::fs_representation::{RepoRoot, RepoPath, in_repo_root};

#[cfg(not(windows))]
use std::os::unix::fs::PermissionsExt;

#[cfg(not(windows))]
fn set_permissions(name: &Path, permissions: u16) -> Result<()> {
    let metadata = std::fs::metadata(&name)?;
    let mut current = metadata.permissions();
    debug!(
        "setting mode for {:?} to {:?} (currently {:?})",
        name, permissions, current
    );
    current.set_mode(permissions as u32);
    std::fs::set_permissions(name, current)?;
    Ok(())
}

#[cfg(windows)]
fn set_permissions(_name: &Path, _permissions: u16) -> Result<()> {
    Ok(())
}

#[derive(Debug)]
struct OutputItem {
    parent: Inode,
    meta: FileMetadata,
    key: Key<PatchId>,
    inode: Option<Inode>,
    is_zombie: bool,
    related: Related,
}

#[derive(Debug, PartialEq, Eq)]
pub enum Related {
    No,
    Ancestor,
    Exact,
}

pub struct ConflictingFile {
    pub inode: Inode,
    pub n_conflicts: usize,
    pub path: RepoPath<PathBuf>,
}

fn is_related(prefixes: &Prefixes, key: Key<PatchId>) -> Related {
    if prefixes.0.is_empty() {
        return Related::Exact;
    }
    for pref in prefixes.0.iter() {
        let mut is_first = true;
        for &p in pref {
            if p == key {
                if is_first {
                    return Related::Exact;
                } else {
                    return Related::Ancestor;
                }
            }
            is_first = false
        }
    }
    Related::No
}

impl<'env, T: rand::Rng> MutTxn<'env, T> {
    // Climb up the tree (using revtree).
    fn filename_of_inode(&self, inode: Inode, working_copy: &Path) -> Option<PathBuf> {
        let mut components = Vec::new();
        let mut current = inode;
        loop {
            match self.get_revtree(current) {
                Some(v) => {
                    components.push(v.basename.to_owned());
                    current = v.parent_inode.clone();
                    if current == ROOT_INODE {
                        break;
                    }
                }
                None => {
                    debug!("filename_of_inode: not in tree");
                    return None;
                }
            }
        }
        let mut working_copy = working_copy.to_path_buf();
        for c in components.iter().rev() {
            working_copy.push(c.as_small_str().as_str());
        }
        Some(working_copy)
    }

    /// Collect all the children of key `key` into `files`.
    fn collect_children(
        &mut self,
        branch: &Branch,
        path: RepoPath<&Path>,
        key: Key<PatchId>,
        inode: Inode,
        base_path: &RepoPath<impl AsRef<Path> + std::fmt::Debug>,
        prefixes: &Prefixes,
        files: &mut HashMap<RepoPath<PathBuf>, HashMap<Key<PatchId>, OutputItem>>,
    ) -> Result<()> {
        debug!("collect_children {:?}", base_path);
        let f = EdgeFlags::FOLDER_EDGE | EdgeFlags::PSEUDO_EDGE | EdgeFlags::EPSILON_EDGE;
        for b in self.iter_adjacent(&branch, key, EdgeFlags::empty(), f) {
            debug!("b={:?}", b);
            let cont_b = self.get_contents(b.dest).unwrap();
            let (_, b_key) = self.iter_nodes(&branch, Some((b.dest, Some(&e))))
            let (_, b_key) = self
                .iter_nodes(
                    &branch,
                    Some((b.dest, Some(Edge::zero(EdgeFlags::FOLDER_EDGE)))),
                )
                .next()












































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
use std::collections::{HashMap, HashSet};
use std::fs::{metadata, File, OpenOptions};
use thrussh_keys;
use thrussh_keys::key::KeyPair;
use thrussh_keys::PublicKeyBase64;
use bs58;
use serde_json;
use {ErrorKind, Result};
/// Semantic groups of changes, for interface purposes.
        new_name: String,
        name: String,
        name: String,
        file: Rc<PathBuf>,
        conflict_reordering: Vec<Change<Context>>,
    },
    Replace {
        file: Rc<PathBuf>,
        adds: Change<Context>,
        dels: Change<Context>,
        conflict_reordering: Vec<Change<Context>>,
        if let Some(extra) = self.extra.take() {
            Some(extra)
                    Some(del)
                Record::FileDel { del: c, .. }
                | Record::FileAdd { add: c, .. }
                | Record::Change { change: c, .. } => Some(c),
                Record::Replace { adds, dels, .. } => {
                    self.extra = Some(adds);
                    Some(dels)
                }
            None
            Some(extra)
                    Some(del)
                Record::FileDel { del: ref c, .. }
                | Record::FileAdd { add: ref c, .. }
                | Record::Change { change: ref c, .. } => Some(c),
                Record::Replace {
                    ref adds, ref dels, ..
                } => {
                    self.extra = Some(adds);
                    Some(dels)
                }
            None
                        })
                        .chain((1..nodes.len()).map(|i| NewEdge {
                        }))
                        .collect();
                        })
                        .collect(),
                    return Err(ErrorKind::EOF.into());
                return Err(ErrorKind::EOF.into());
                return Err(ErrorKind::WrongHash.into());
            _ => Err(ErrorKind::WrongHash.into()),
    pub fn save<P: AsRef<Path>>(&self, dir: P, key: Option<&KeyPair>) -> Result<Hash> {
        if metadata(&path).is_err() {
            debug!("save, path {:?}", path);
            let f = File::create(&path)?;
            debug!("created");
            let mut w = flate2::GzBuilder::new()
                .filename(h.as_bytes())
                .write(f, flate2::Compression::best());
            w.write_all(&buf)?;
            w.finish()?;
            debug!("saved");
        }
            let mut file = OpenOptions::new()

            let mut signatures: SignatureFile =
                serde_json::from_reader(&mut file).unwrap_or(SignatureFile {
                    hash: h,
                    signatures: HashMap::new(),
                });
            let signature = key.sign_detached(&hash.as_ref().to_binary())?;
            let public_key = key.public_key_base64();
            signatures
                .signatures
                .insert(public_key, bs58::encode(&signature.as_ref()).into_string());
            serde_json::to_writer(&mut file, &signatures)?;
#[derive(Debug, Serialize, Deserialize)]
pub struct SignatureFile {
    pub hash: String,
    pub signatures: HashMap<String, String>,
}

pub fn read_signature_file(r: &mut Read) -> Result<SignatureFile> {
    let signatures: SignatureFile = serde_json::from_reader(r)?;
    // verify signatures
    for (key, sig) in signatures.signatures.iter() {
        let k = thrussh_keys::parse_public_key_base64(&key)?;
        let sig = bs58::decode(sig).into_vec()?;
        if !k.verify_detached(signatures.hash.as_bytes(), &sig) {
            return Err(ErrorKind::WrongPatchSignature.into());
        }
    }
    Ok(signatures)
}

impl SignatureFile {
    pub fn write_signature_file(&self, w: &mut Write) -> Result<()> {
        serde_json::to_writer(w, self)?;
        Ok(())
    }
}

pub struct Signatures<'a, R: Read>(
    serde_json::StreamDeserializer<'a, serde_json::de::IoRead<R>, SignatureFile>,
);

pub fn read_signatures<'a, R: Read>(r: R) -> Signatures<'a, R> {
    Signatures(serde_json::Deserializer::from_reader(r).into_iter())
}

impl<'a, R: Read> Iterator for Signatures<'a, R> {
    type Item = Result<SignatureFile>;
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|n| n.map_err(super::Error::from))
    }
}

pub fn read_changes(r: &mut Read) -> Result<HashMap<Hash, ApplyTimestamp>> {
    let mut result = HashMap::new();
                result.insert(h, s);
) -> Result<HashMap<Hash, ApplyTimestamp>> {
                } => for c in up_context.iter().chain(down_context.iter()) {
                    match c.patch {
                        None | Some(Hash::None) => {}
                        Some(ref dep) => {
                            debug!("dependencies (line {}) += {:?}", line!(), dep);
                            deps.insert(dep.clone());
                },
                let already_covered = covered.get(&current).is_some() || (current != dep && {
                    let current_ext = self.get_external(current).unwrap();
                    deps.get(&current_ext.to_owned()).is_some()
                });
                    for (_, parent) in self.iter_revdep(Some((current, None)))
            })
            .collect()
        for (_, edge) in self.iter_nodes(branch, Some((k, None)))
            .take_while(|&(k_, _)| k_ == k)
            .filter(|&(_, e_)| !e_.flag.contains(EdgeFlags::PARENT_EDGE))
//! Definition of patches, and a number of methods.
use chrono;
use chrono::{DateTime, Utc};
use flate2;
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::io::{BufRead, Read, Write};
use std::path::Path;
use std::path::PathBuf;
use std::rc::Rc;
use std::str::from_utf8;
pub type Flag = u8;
use bincode::{deserialize, deserialize_from, serialize};
use sequoia_openpgp::constants::DataFormat;
use sequoia_openpgp::crypto;
use sequoia_openpgp::serialize::stream::{LiteralWriter, Message, Signer};

use {Error, Result};
use super::fs_representation::RepoPath;

mod pretty;

bitflags! {
    #[derive(Serialize, Deserialize)]
    pub struct PatchFlags: u32 {
        const TAG = 1;
    }
}

/// A patch without its signature suffix.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UnsignedPatch {
    /// Header part, containing the metadata.
    pub header: PatchHeader,
    /// The dependencies of this patch.
    pub dependencies: HashSet<Hash>,
    /// The actual contents of the patch.
    pub changes: Vec<Change<ChangeContext<Hash>>>,
}

/// The definition of a patch.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum Patch {
    Unsigned0,
    Signed0,
    Unsigned(UnsignedPatch),
}

impl Patch {
    /// The contents of this patch.
    pub fn changes(&self) -> &[Change<ChangeContext<Hash>>] {
        match *self {
            Patch::Signed0 | Patch::Unsigned0 => {
                panic!("refusing to interact with old patch version")
            }
            Patch::Unsigned(ref patch) => &patch.changes,
        }
    }

    pub fn changes_mut(&mut self) -> &mut Vec<Change<ChangeContext<Hash>>> {
        match *self {
            Patch::Signed0 | Patch::Unsigned0 => {
                panic!("refusing to interact with old patch version")
            }
            Patch::Unsigned(ref mut patch) => &mut patch.changes,
        }
    }
    /// The dependencies of this patch.
    pub fn dependencies(&self) -> &HashSet<Hash> {
        match *self {
            Patch::Signed0 | Patch::Unsigned0 => {
                panic!("refusing to interact with old patch version")
            }
            Patch::Unsigned(ref patch) => &patch.dependencies,
        }
    }
    pub fn dependencies_mut(&mut self) -> &mut HashSet<Hash> {
        match *self {
            Patch::Signed0 | Patch::Unsigned0 => {
                panic!("refusing to interact with old patch version")
            }
            Patch::Unsigned(ref mut patch) => &mut patch.dependencies,
        }
    }
    /// The header of this patch.
    pub fn header(&self) -> &PatchHeader {
        match *self {
            Patch::Signed0 | Patch::Unsigned0 => {
                panic!("refusing to interact with old patch version")
            }
            Patch::Unsigned(ref patch) => &patch.header,
        }
    }
    pub fn header_mut(&mut self) -> &mut PatchHeader {
        match *self {
            Patch::Signed0 | Patch::Unsigned0 => {
                panic!("refusing to interact with old patch version")
            }
            Patch::Unsigned(ref mut patch) => &mut patch.header,
        }
    }

    /// Reads everything in this patch, but the actual contents.
    pub fn read_dependencies<R: Read>(mut r: R) -> Result<Vec<Hash>> {
        let version: u32 = deserialize_from(&mut r)?;
        assert_eq!(version, 2);
        let _header: PatchHeader = deserialize_from(&mut r)?;
        debug!("version: {:?}", version);
        Ok(deserialize_from(&mut r)?)
    }
}

/// The header of a patch contains all the metadata about a patch
/// (but not the actual contents of a patch).
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PatchHeader {
    pub authors: Vec<String>,
    pub name: String,
    pub description: Option<String>,
    pub timestamp: DateTime<Utc>,
    pub flag: PatchFlags,
}

use std::ops::{Deref, DerefMut};
impl Deref for Patch {
    type Target = PatchHeader;
    fn deref(&self) -> &Self::Target {
        self.header()
    }
}
impl DerefMut for Patch {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.header_mut()
    }
}

/// Options are for when this edge is between vertices introduced by
/// the current patch.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewEdge {
    pub from: Key<Option<Hash>>,
    pub to: Key<Option<Hash>>,
    pub introduced_by: Option<Hash>,
}

pub type ChangeContext<H> = Vec<Key<Option<H>>>;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Change<Context> {
    NewNodes {
        up_context: Context,
        down_context: Context,
        flag: EdgeFlags,
        line_num: LineId,
        nodes: Vec<Vec<u8>>,
        inode: Key<Option<Hash>>,
    },
    NewEdges {
        previous: EdgeFlags,
        flag: EdgeFlags,
        edges: Vec<NewEdge>,
        inode: Key<Option<Hash>>,
    },
}

impl PatchHeader {
    /// Reads everything in this patch, but the actual contents.
    pub fn from_reader_nochanges<R: Read>(mut r: R) -> Result<PatchHeader> {
        let version: u32 = deserialize_from(&mut r)?;
        debug!("version: {:?}", version);
        Ok(deserialize_from(&mut r)?)
    }
}

/// A record is a group of changes pertaining to a file or region of a
/// file.  They are going to be offered together, since displaying one
/// of the changes may be affected by the other (eg, if a file is
/// being moved, we need to display the correct name when asking about
/// modifications within that file).
#[derive(Debug)]
pub enum Record<Context> {
    FileMove {
        new_name: RepoPath<PathBuf>,
        del: Change<Context>,
        add: Change<Context>,
    },
    FileDel {
        name: RepoPath<PathBuf>,
        del: Change<Context>,
        contents: Option<Change<Context>>,
    },
    FileAdd {
        name: RepoPath<PathBuf>,
        add: Change<Context>,
        contents: Option<Change<Context>>,
    },
    Change {
        file: Rc<RepoPath<PathBuf>>,
        change: Change<Context>,
        replacement: Option<Change<Context>>,
        old_line: usize,
        new_line: usize,
    },
}

pub struct RecordIter<R, C> {
    rec: Option<R>,
    extra: Option<C>,
}

impl<Context> IntoIterator for Record<Context> {
    type IntoIter = RecordIter<Record<Context>, Change<Context>>;
    type Item = Change<Context>;
    fn into_iter(self) -> Self::IntoIter {
        RecordIter {
            rec: Some(self),
            extra: None,
        }
    }
}

impl<Context> Record<Context> {
    pub fn iter(&self) -> RecordIter<&Record<Context>, &Change<Context>> {
        RecordIter {
            rec: Some(self),
            extra: None,
        }
    }
}

impl<Context> Iterator for RecordIter<Record<Context>, Change<Context>> {
    type Item = Change<Context>;
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(extra) = self.extra.take() {
            return Some(extra);
        } else if let Some(rec) = self.rec.take() {
            match rec {
                Record::FileMove { del, add, .. } => {
                    self.extra = Some(add);
                    return Some(del);
                }
                Record::FileDel { del, contents, .. } => {
                    self.extra = contents;
                    return Some(del);
                }
                Record::FileAdd { add, contents, .. } => {
                    self.extra = contents;
                    return Some(add);
                }
                Record::Change {
                    change,
                    replacement,
                    ..
                } => {
                    if let Some(r) = replacement {
                        self.extra = Some(r)
                    }
                    return Some(change);
                }
            }
        } else {
            return None;
        }
    }
}

impl<'a, Context> Iterator for RecordIter<&'a Record<Context>, &'a Change<Context>> {
    type Item = &'a Change<Context>;
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(extra) = self.extra.take() {
            return Some(extra);
        } else if let Some(rec) = self.rec.take() {
            match *rec {
                Record::FileMove {
                    ref del, ref add, ..
                } => {
                    self.extra = Some(add);
                    return Some(del);
                }
                Record::FileDel {
                    ref del,
                    ref contents,
                    ..
                } => {
                    self.extra = contents.as_ref();
                    return Some(del);
                }
                Record::FileAdd {
                    ref add,
                    ref contents,
                    ..
                } => {
                    self.extra = contents.as_ref();
                    return Some(add);
                }
                Record::Change {
                    replacement: ref r,
                    change: ref c,
                    ..
                } => {
                    if let Some(ref r) = r {
                        self.extra = Some(r)
                    }
                    return Some(c);
                }
            }
        } else {
            return None;
        }
    }
}

impl UnsignedPatch {
    pub fn empty() -> Self {
        UnsignedPatch {
            header: PatchHeader {
                authors: vec![],
                name: "".to_string(),
                description: None,
                timestamp: chrono::Utc::now(),
                flag: PatchFlags::empty(),
            },
            dependencies: HashSet::new(),
            changes: vec![],
        }
    }
    pub fn leave_unsigned(self) -> Patch {
        Patch::Unsigned(self)
    }

    fn is_tag(&self) -> bool {
        self.header.flag.contains(PatchFlags::TAG)
    }

    pub fn inverse(&self, hash: &Hash, changes: &mut Vec<Change<ChangeContext<Hash>>>) {
        for ch in self.changes.iter() {
            debug!("inverse {:?}", ch);
            match *ch {
                Change::NewNodes {
                    ref up_context,
                    flag,
                    line_num,
                    ref nodes,
                    ref inode,
                    ..
                } => {
                    let edges = up_context
                        .iter()
                        .map(|up| NewEdge {
                            from: Key {
                                patch: match up.patch {
                                    Some(ref h) => Some(h.clone()),
                                    None => Some(hash.clone()),
                                },
                                line: up.line,
                            },
                            to: Key {
                                patch: Some(hash.clone()),
                                line: line_num,
                            },
                            introduced_by: Some(hash.clone()),
                        })
                        .chain((1..nodes.len()).map(|i| NewEdge {
                            from: Key {
                                patch: Some(hash.clone()),
                                line: line_num + (i - 1),
                            },
                            to: Key {
                                patch: Some(hash.clone()),
                                line: line_num + i,
                            },
                            introduced_by: Some(hash.clone()),
                        }))
                        .collect();
                    changes.push(Change::NewEdges {
                        edges,
                        inode: inode.clone(),
                        previous: flag,
                        flag: flag ^ EdgeFlags::DELETED_EDGE,
                    })
                }
                Change::NewEdges {
                    previous,
                    flag,
                    ref edges,
                    ref inode,
                } => changes.push(Change::NewEdges {
                    previous: flag,
                    flag: previous,
                    inode: inode.clone(),
                    edges: edges
                        .iter()
                        .map(|e| NewEdge {
                            from: e.from.clone(),
                            to: e.to.clone(),
                            introduced_by: Some(hash.clone()),
                        })
                        .collect(),
                }),
            }
        }
    }
}

impl Patch {
    /// An approximate upper bound of the number of extra bytes in the
    /// database this patch might require. This depends a lot on the
    /// patch and the database, so it might be wrong.
    pub fn size_upper_bound(&self) -> usize {
        // General overhead for applying a patch; 8 pages.
        let mut size: usize = 1 << 15;
        for c in self.changes().iter() {
            match *c {
                Change::NewNodes { ref nodes, .. } => {
                    size += nodes.iter().map(|x| x.len()).sum::<usize>();
                    size += nodes.len() * 2048 // + half a page
                }
                Change::NewEdges { ref edges, .. } => size += edges.len() * 2048,
            }
        }
        size
    }

    pub fn is_tag(&self) -> bool {
        match *self {
            Patch::Unsigned(ref patch) => patch.is_tag(),
            _ => false,
        }
    }

    /// Read one patch from a gzip-compressed `BufRead`. If several
    /// patches are available in the same `BufRead`, this method can
    /// be called again.
    pub fn from_reader_compressed<R: BufRead>(r: &mut R) -> Result<(Hash, Vec<u8>, Patch)> {
        let mut rr = flate2::bufread::GzDecoder::new(r);
        let filename = {
            let filename = if let Some(header) = rr.header() {
                if let Some(filename) = header.filename() {
                    from_utf8(filename)?
                } else {
                    return Err(Error::EOF);
                }
            } else {
                return Err(Error::EOF);
            };
            if let Some(h) = Hash::from_base58(filename) {
                h
            } else {
                return Err(Error::WrongHash);
            }
        };

        let mut buf = Vec::new();
        rr.read_to_end(&mut buf)?;

        // Checking the hash.
        let patch: Patch = deserialize(&buf[..])?;
        patch.check_hash(&buf, &filename)?;

        Ok((filename, buf, patch))
    }

    fn check_hash(&self, buf: &[u8], filename: &Hash) -> Result<()> {
        let buf = match *self {
            Patch::Signed0 | Patch::Unsigned0 => {
                panic!("refusing to interact with old patch version")
            }
            Patch::Unsigned(_) => buf,
        };
        let hash = Hash::of_slice(buf)?;
        match (filename, &hash) {
            (&Hash::Sha512(ref filename), &Hash::Sha512(ref hash))
                if &filename.0[..] == &hash.0[..] =>
            {
                Ok(())
            }
            _ => Err(Error::WrongHash),
        }
    }

    pub fn to_buf(&self) -> Result<(Vec<u8>, Hash)> {
        // Encoding to a buffer.
        let buf = serialize(&self)?;
        // Hashing the buffer.
        let hash = Hash::of_slice(&buf)?;
        Ok((buf, hash))
    }

    /// Save the patch, computing the hash.
    pub fn save<P: AsRef<Path>>(&self, dir: P, key: Option<&mut crypto::KeyPair>) -> Result<Hash> {
        let (buf, hash) = self.to_buf()?;
        // Writing to the file.
        let h = hash.to_base58();
        let mut path = dir.as_ref().join(&h);
        path.set_extension("gz");
        debug!("save, path {:?}", path);
        let f = File::create(&path)?;
        debug!("created");
        let mut w = flate2::GzBuilder::new()
            .filename(h.as_bytes())
            .write(f, flate2::Compression::best());
        w.write_all(&buf)?;
        w.finish()?;
        debug!("saved");

        if let Some(key) = key {
            path.set_extension("sig");
            let file = OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .open(&path)?;
            let message = Message::new(file);
            let mut signer = Signer::detached(message, vec![key as &mut crypto::Signer])?;
            let mut w = LiteralWriter::new(signer, DataFormat::Binary, Some(h.as_bytes()), None)?;
            w.write_all(&buf)?;
            w.finalize()?
        }
        Ok(hash)
    }

    pub fn inverse(&self, hash: &Hash, changes: &mut Vec<Change<ChangeContext<Hash>>>) {
        match *self {
            Patch::Unsigned0 => panic!("Can't reverse old patches"),
            Patch::Signed0 => panic!("Can't reverse old patches"),
            Patch::Unsigned(ref u) => u.inverse(hash, changes),
        }
    }
}

pub fn read_changes(r: &mut Read) -> Result<Vec<(Hash, ApplyTimestamp)>> {
    let mut s = String::new();
    r.read_to_string(&mut s)?;
    let mut result = Vec::new();
    for l in s.lines() {
        let mut sp = l.split(':');
        match (
            sp.next().and_then(Hash::from_base58),
            sp.next().and_then(|s| s.parse().ok()),
        ) {
            (Some(h), Some(s)) => {
                result.push((h, s));
            }
            _ => {}
        }
    }
    Ok(result)
}

pub fn read_changes_from_file<P: AsRef<Path>>(
    changes_file: P,
) -> Result<Vec<(Hash, ApplyTimestamp)>> {
    let mut file = File::open(changes_file)?;
    read_changes(&mut file)
}

impl<U: Transaction, R> GenericTxn<U, R> {
    pub fn new_patch<I: Iterator<Item = Hash>>(
        &self,
        branch: &Branch,
        authors: Vec<String>,
        name: String,
        description: Option<String>,
        timestamp: DateTime<Utc>,
        changes: Vec<Change<ChangeContext<Hash>>>,
        extra_dependencies: I,
        flag: PatchFlags,
    ) -> Patch {
        let mut dependencies = self.dependencies(branch, changes.iter());
        dependencies.extend(extra_dependencies);
        Patch::Unsigned(UnsignedPatch {
            header: PatchHeader {
                authors,
                name,
                description,
                timestamp,
                flag,
            },
            dependencies,
            changes,
        })
    }

    pub fn dependencies<'a, I: Iterator<Item = &'a Change<ChangeContext<Hash>>>>(
        &self,
        branch: &Branch,
        changes: I,
    ) -> HashSet<Hash> {
        let mut deps = HashSet::new();
        let mut zombie_deps = HashSet::new();
        for ch in changes {
            match *ch {
                Change::NewNodes {
                    ref up_context,
                    ref down_context,
                    ..
                } => {
                    for c in up_context.iter().chain(down_context.iter()) {
                        match c.patch {
                            None | Some(Hash::None) => {}
                            Some(ref dep) => {
                                debug!("dependencies (line {}) += {:?}", line!(), dep);
                                deps.insert(dep.clone());
                            }
                        }
                    }
                }
                Change::NewEdges {
                    flag, ref edges, ..
                } => {
                    for e in edges {
                        let (from, to) = if flag.contains(EdgeFlags::PARENT_EDGE) {
                            (&e.to, &e.from)
                        } else {
                            (&e.from, &e.to)
                        };

                        match from.patch {
                            None | Some(Hash::None) => {}
                            Some(ref h) => {
                                debug!("dependencies (line {}) += {:?}", line!(), h);
                                deps.insert(h.clone());
                                if flag.contains(EdgeFlags::DELETED_EDGE) {
                                    // Add "known patches" to
                                    // allow identifying missing
                                    // contexts.
                                    let k = Key {
                                        patch: self.get_internal(h.as_ref()).unwrap().to_owned(),
                                        line: from.line.clone(),
                                    };
                                    self.edge_context_deps(branch, k, &mut zombie_deps)
                                }
                            }
                        }
                        match to.patch {
                            None | Some(Hash::None) => {}
                            Some(ref h) => {
                                debug!("dependencies (line {}) += {:?}", line!(), h);
                                deps.insert(h.clone());
                                if flag.contains(EdgeFlags::DELETED_EDGE) {
                                    // Add "known patches" to
                                    // allow identifying
                                    // missing contexts.
                                    let k = Key {
                                        patch: self.get_internal(h.as_ref()).unwrap().to_owned(),
                                        line: to.line.clone(),
                                    };
                                    self.edge_context_deps(branch, k, &mut zombie_deps)
                                }
                            }
                        }
                        match e.introduced_by {
                            None | Some(Hash::None) => {}
                            Some(ref h) => {
                                debug!("dependencies (line {}) += {:?}", line!(), h);
                                zombie_deps.insert(h.clone());
                            }
                        }
                    }
                }
            }
        }
        let mut h = self.minimize_deps(&deps);
        for z in zombie_deps.drain() {
            h.insert(z);
        }
        h
    }

    pub fn minimize_deps(&self, deps: &HashSet<Hash>) -> HashSet<Hash> {
        debug!("minimize_deps {:?}", deps);
        let mut covered = HashSet::new();
        let mut stack = Vec::new();
        let mut seen = HashSet::new();
        for dep_ext in deps.iter() {
            // For each dependency, do a DFS.
            let dep = self.get_internal(dep_ext.as_ref()).unwrap();
            debug!("dep = {:?}", dep);
            stack.clear();
            stack.push((dep, false));
            while let Some((current, on_path)) = stack.pop() {
                // Is current already covered? (either transitively in
                // covered, or directly in deps).
                let already_covered = covered.get(&current).is_some()
                    || (current != dep && {
                        let current_ext = self.get_external(current).unwrap();
                        deps.get(&current_ext.to_owned()).is_some()
                    });
                if already_covered {
                    // We look at all patches on the current path, and
                    // mark them as covered.
                    for &(h, h_on_path) in stack.iter() {
                        if h_on_path {
                            debug!("covered: h {:?}", h);
                            covered.insert(h);
                        }
                    }
                    break;
                }
                // If we've already seen `current`, and dep is not
                // covered, we don't need to explore `current`'s
                // children.  Or, if we're coming here for the second
                // time (i.e. after exploring all children), no need to
                // explore the children again either.
                if seen.insert(current) && !on_path {
                    stack.push((current, true));

                    for (_, parent) in self
                        .iter_revdep(Some((current, None)))
                        .take_while(|k| k.0 == current)
                    {
                        stack.push((parent, false))
                    }
                }
            }
        }

        deps.iter()
            .filter_map(|dep_ext| {
                let dep = self.get_internal(dep_ext.as_ref()).unwrap();
                if covered.get(&dep).is_none() {
                    Some(dep_ext.to_owned())
                } else {
                    None
                }
            })
            .collect()
    }

    fn edge_context_deps(&self, branch: &Branch, k: Key<PatchId>, deps: &mut HashSet<Hash>) {
        for edge in self
            .iter_adjacent(branch, k, EdgeFlags::empty(), EdgeFlags::all())
            .filter(|e_| !e_.flag.contains(EdgeFlags::PARENT_EDGE))
        {
            if let Some(ext) = self.get_external(edge.introduced_by) {
                deps.insert(ext.to_owned());
            }
        }
    }
}

use backend::*;
use sanakirja;

impl<A: sanakirja::Transaction, R> GenericTxn<A, R> {
    /// Gets the external key corresponding to the given key, returning an
    /// owned vector. If the key is just a patch internal hash, it returns the
    /// corresponding external hash.
    pub fn external_key(&self, key: &Key<PatchId>) -> Option<Key<Option<Hash>>> {
        Some(Key {
            patch: Some(self.external_hash(key.patch).to_owned()),
            line: key.line,
        })
    }

    pub fn external_hash(&self, key: PatchId) -> HashRef {
        if key == ROOT_PATCH_ID {
            ROOT_HASH.as_ref()
        } else {
            self.get_external(key).unwrap()
        }
    }

    pub(crate) fn external_hash_opt(&self, h: Option<PatchId>) -> Option<Hash> {
        h.map(|x| self.external_hash(x).to_owned())
    }

    pub(crate) fn external_key_opt(&self, h: Key<Option<PatchId>>) -> Key<Option<Hash>> {
        Key {
            line: h.line,
            patch: self.external_hash_opt(h.patch),
        }
    }

    /// Create a new internal patch id, register it in the "external" and
    /// "internal" bases, and write the result in its second argument
    /// ("result").
    pub fn new_internal(&self, ext: HashRef) -> PatchId {
        let mut result = match ext {
            HashRef::None => return ROOT_PATCH_ID,
            HashRef::Sha512(h) => PatchId::from_slice(h),
            HashRef::Recursive(p) => PatchId::from_slice(p),
        };
        while self.get_external(result).is_some() {
            result.0 += 1
        }
        result
    }
}















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
use std::str::from_utf8;
        let deps = self.dependencies.iter().map(|x| x.clone()).zip(1..).collect();
        let deps_vec:Vec<_> = self.dependencies
            dependencies: self.dependencies
            changes: self.changes.iter().map(|x| x.to_change(&deps_vec)).collect(),
            format!("{}.{}", deps.get(&k).unwrap(), key.line.to_base58())
        (Some(a), Some(b)) =>
            Key {
                patch: Some(deps[a.parse::<usize>().unwrap()].clone()),
                line: LineId::from_base58(b).unwrap(),
            },
            line: LineId(0)
        }
                                }).unwrap()
                                }).unwrap()
use super::{Change, ChangeContext, NewEdge, Patch, PatchHeader, UnsignedPatch};
use base64;
use serde_json;
use std::collections::HashMap;
use std::str::from_utf8;
use {EdgeFlags, Hash, Key, LineId};

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PrettyPatch {
    pub header: PatchHeader,
    pub dependencies: Vec<String>,
    pub changes: Vec<PrettyChange>,
}

impl Patch {
    pub fn to_pretty(&self) -> PrettyPatch {
        match *self {
            Patch::Signed0 | Patch::Unsigned0 => {
                panic!("refusing to interact with old patch version")
            }
            Patch::Unsigned(ref patch) => patch.to_pretty(),
        }
    }
}

impl UnsignedPatch {
    pub fn to_pretty(&self) -> PrettyPatch {
        let deps = self
            .dependencies
            .iter()
            .map(|x| x.clone())
            .zip(1..)
            .collect();
        PrettyPatch {
            header: self.header.clone(),
            dependencies: self.dependencies.iter().map(|x| x.to_base58()).collect(),
            changes: self.changes.iter().map(|x| x.to_pretty(&deps)).collect(),
        }
    }
}

impl PrettyPatch {
    pub fn to_patch(&self) -> UnsignedPatch {
        let deps_vec: Vec<_> = self
            .dependencies
            .iter()
            .map(|x| Hash::from_base58(x).unwrap())
            .collect();

        UnsignedPatch {
            header: self.header.clone(),
            dependencies: self
                .dependencies
                .iter()
                .map(|x| Hash::from_base58(x).unwrap())
                .collect(),
            changes: self
                .changes
                .iter()
                .map(|x| x.to_change(&deps_vec))
                .collect(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PrettyChange {
    NewNodes {
        up_context: Vec<String>,
        down_context: Vec<String>,
        flag: u8,
        line_num: u64,
        nodes: Vec<serde_json::Value>,
        inode: String,
    },
    NewEdges {
        previous: u8,
        flag: u8,
        edges: Vec<PrettyNewEdge>,
        inode: String,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrettyNewEdge {
    pub from: String,
    pub to: String,
    pub introduced_by: usize,
}

impl PrettyNewEdge {
    fn to_new_edge(&self, deps: &[Hash]) -> NewEdge {
        NewEdge {
            from: read_key(deps, &self.from),
            to: read_key(deps, &self.to),
            introduced_by: Some(deps[self.introduced_by].clone()),
        }
    }
}

impl NewEdge {
    fn to_pretty(&self, deps: &HashMap<Hash, usize>) -> PrettyNewEdge {
        PrettyNewEdge {
            from: print_key(deps, &self.from),
            to: print_key(deps, &self.to),
            introduced_by: if let Some(ref i) = self.introduced_by {
                *deps.get(i).unwrap()
            } else {
                0
            },
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Filename {
    name: String,
    flag: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Binary {
    binary: String,
}

fn print_key(deps: &HashMap<Hash, usize>, key: &Key<Option<Hash>>) -> String {
    if let Some(ref k) = key.patch {
        if *k == Hash::None {
            String::new()
        } else {
            debug!("print key: {:?} {:?}", k, deps);
            if let Some(dep) = deps.get(&k) {
                format!("{}.{}", dep, key.line.to_base58())
            } else {
                format!("{}", key.line.to_base58())
            }
        }
    } else {
        format!("{}", key.line.to_base58())
    }
}

fn read_key(deps: &[Hash], key: &str) -> Key<Option<Hash>> {
    let mut it = key.split('.');
    match (it.next(), it.next()) {
        (Some(a), Some(b)) => Key {
            patch: Some(deps[a.parse::<usize>().unwrap()].clone()),
            line: LineId::from_base58(b).unwrap(),
        },
        (Some(a), None) => Key {
            patch: None,
            line: LineId::from_base58(a).unwrap(),
        },
        _ => Key {
            patch: Some(Hash::None),
            line: LineId(0),
        },
    }
}

impl Change<ChangeContext<Hash>> {
    fn to_pretty(&self, deps: &HashMap<Hash, usize>) -> PrettyChange {
        match *self {
            Change::NewNodes {
                ref up_context,
                ref down_context,
                flag,
                line_num,
                ref nodes,
                ref inode,
            } => PrettyChange::NewNodes {
                up_context: up_context.iter().map(|x| print_key(&deps, x)).collect(),
                down_context: down_context.iter().map(|x| print_key(&deps, x)).collect(),
                flag: flag.bits(),
                line_num: line_num.0,
                nodes: if flag.contains(EdgeFlags::FOLDER_EDGE) {
                    nodes
                        .iter()
                        .map(|x| {
                            if x.len() >= 2 {
                                serde_json::to_value(Filename {
                                    name: from_utf8(&x[2..]).unwrap().to_string(),
                                    flag: ((x[0] as u16) << 8) | (x[1] as u16),
                                })
                                .unwrap()
                            } else {
                                serde_json::to_value("").unwrap()
                            }
                        })
                        .collect()
                } else {
                    nodes
                        .iter()
                        .map(|x| {
                            if let Ok(x) = from_utf8(x) {
                                serde_json::to_value(x).unwrap()
                            } else {
                                serde_json::to_value(Binary {
                                    binary: base64::encode(x),
                                })
                                .unwrap()
                            }
                        })
                        .collect()
                },
                inode: print_key(deps, inode),
            },
            Change::NewEdges {
                previous,
                flag,
                ref edges,
                ref inode,
            } => PrettyChange::NewEdges {
                previous: previous.bits(),
                flag: flag.bits(),
                inode: print_key(deps, inode),
                edges: edges.iter().map(|x| x.to_pretty(deps)).collect(),
            },
        }
    }
}

impl PrettyChange {
    pub fn to_change(&self, deps: &[Hash]) -> Change<ChangeContext<Hash>> {
        match *self {
            PrettyChange::NewNodes {
                ref up_context,
                ref down_context,
                flag,
                line_num,
                ref nodes,
                ref inode,
            } => Change::NewNodes {
                up_context: up_context.iter().map(|x| read_key(deps, x)).collect(),
                down_context: down_context.iter().map(|x| read_key(deps, x)).collect(),
                flag: EdgeFlags::from_bits_truncate(flag),
                line_num: LineId(line_num),
                nodes: nodes
                    .iter()
                    .map(|x| {
                        let filename: Result<Filename, _> = serde_json::from_value(x.clone());
                        if let Ok(filename) = filename {
                            let mut v = Vec::new();
                            v.push((filename.flag >> 8) as u8);
                            v.push(filename.flag as u8);
                            v.extend(filename.name.as_bytes());
                            return v;
                        }
                        let binary: Result<Binary, _> = serde_json::from_value(x.clone());
                        if let Ok(binary) = binary {
                            return base64::decode(&binary.binary).unwrap();
                        }
                        let string: String = serde_json::from_value(x.clone()).unwrap();
                        string.into()
                    })
                    .collect(),
                inode: read_key(deps, inode),
            },
            PrettyChange::NewEdges {
                previous,
                flag,
                ref edges,
                ref inode,
            } => Change::NewEdges {
                previous: EdgeFlags::from_bits_truncate(previous),
                flag: EdgeFlags::from_bits_truncate(flag),
                inode: read_key(deps, inode),
                edges: edges.iter().map(|x| x.to_new_edge(deps)).collect(),
            },
        }
    }
}



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































//! Definition of patches, and a number of methods.
use chrono;
use chrono;
use chrono::{DateTime, Utc};
use flate2;
use rand;
use std::collections::{HashMap, HashSet};
use std::collections::{HashMap, HashSet};
use std::fs::{metadata, File, OpenOptions};
use std::io::{BufRead, Read, Write};
use std::path::Path;
use std::path::PathBuf;
use std::path::PathBuf;
use std::rc::Rc;
use std::str::from_utf8;
use thrussh_keys;
use thrussh_keys::PublicKeyBase64;
use thrussh_keys::PublicKeyBase64;
pub type Flag = u8;
pub type Flag = u8;
pub type Flag = u8;
use bincode::{deserialize, deserialize_from, serialize};
use bincode::{deserialize, deserialize_from, serialize};
use bs58;
use bs58;
use serde_json;
use {ErrorKind, Result};


bitflags! {
    #[derive(Serialize, Deserialize)]
    pub struct PatchFlags: u32 {
        const TAG = 1;
    }
}

/// A patch without its signature suffix.
/// A patch without its signature suffix.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UnsignedPatch {
    /// Header part, containing the metadata.
    pub header: PatchHeader,
    /// The dependencies of this patch.
    pub dependencies: HashSet<Hash>,
    /// The actual contents of the patch.
    pub changes: Vec<Change<ChangeContext<Hash>>>,
}

/// The definition of a patch.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum Patch {
    Unsigned0,
    Signed0,
    Unsigned(UnsignedPatch),
}

impl Patch {
    /// The contents of this patch.
    pub fn changes(&self) -> &[Change<ChangeContext<Hash>>] {
        match *self {
            Patch::Signed0 | Patch::Unsigned0 => {
                panic!("refusing to interact with old patch version")
            }
            Patch::Unsigned(ref patch) => &patch.changes,
            Patch::Unsigned(ref patch) => &patch.changes,
        }
    }
    pub fn changes_mut(&mut self) -> &mut Vec<Change<ChangeContext<Hash>>> {
        match *self {
            Patch::Signed0 | Patch::Unsigned0 => {
                panic!("refusing to interact with old patch version")
            }
            Patch::Unsigned(ref mut patch) => &mut patch.changes,
            Patch::Unsigned(ref mut patch) => &mut patch.changes,
        }
    }
    /// The dependencies of this patch.
    pub fn dependencies(&self) -> &HashSet<Hash> {
        match *self {
            Patch::Signed0 | Patch::Unsigned0 => {
                panic!("refusing to interact with old patch version")
            }
            Patch::Unsigned(ref patch) => &patch.dependencies,
            Patch::Unsigned(ref patch) => &patch.dependencies,
        }
    }
    pub fn dependencies_mut(&mut self) -> &mut HashSet<Hash> {
        match *self {
            Patch::Signed0 | Patch::Unsigned0 => {
                panic!("refusing to interact with old patch version")
            }
            Patch::Unsigned(ref mut patch) => &mut patch.dependencies,
            Patch::Unsigned(ref mut patch) => &mut patch.dependencies,
        }
    }
    /// The header of this patch.
    pub fn header(&self) -> &PatchHeader {
        match *self {
            Patch::Signed0 | Patch::Unsigned0 => {
                panic!("refusing to interact with old patch version")
            }
            Patch::Unsigned(ref patch) => &patch.header,
            Patch::Unsigned(ref patch) => &patch.header,
        }
    }
    pub fn header_mut(&mut self) -> &mut PatchHeader {
        match *self {
            Patch::Signed0 | Patch::Unsigned0 => {
                panic!("refusing to interact with old patch version")
            }
            Patch::Unsigned(ref mut patch) => &mut patch.header,
            Patch::Unsigned(ref mut patch) => &mut patch.header,
        }
    }

    /// Reads everything in this patch, but the actual contents.
    pub fn read_dependencies<R: Read>(mut r: R) -> Result<Vec<Hash>> {
        let version: u32 = deserialize_from(&mut r)?;
        assert_eq!(version, 2);
        assert_eq!(version, 2);
        assert_eq!(version, 2);
        let _header: PatchHeader = deserialize_from(&mut r)?;
        debug!("version: {:?}", version);
        debug!("version: {:?}", version);
        debug!("version: {:?}", version);
        Ok(deserialize_from(&mut r)?)
    }
    }
}
}

/// The header of a patch contains all the metadata about a patch
/// (but not the actual contents of a patch).
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PatchHeader {
    pub authors: Vec<String>,
    pub name: String,
    pub description: Option<String>,
    pub timestamp: DateTime<Utc>,
    pub flag: PatchFlags,
}

use std::ops::{Deref, DerefMut};
impl Deref for Patch {
    type Target = PatchHeader;
    fn deref(&self) -> &Self::Target {
        self.header()
    }
}
impl DerefMut for Patch {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.header_mut()
    }
}

/// Options are for when this edge is between vertices introduced by
/// Options are for when this edge is between vertices introduced by
/// the current patch.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewEdge {
    pub from: Key<Option<Hash>>,
    pub to: Key<Option<Hash>>,
    pub introduced_by: Option<Hash>,
}

pub type ChangeContext<H> = Vec<Key<Option<H>>>;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Change<Context> {
    NewNodes {
        up_context: Context,
        down_context: Context,
        flag: EdgeFlags,
        line_num: LineId,
        nodes: Vec<Vec<u8>>,
        inode: Key<Option<Hash>>,
    },
    NewEdges {
        previous: EdgeFlags,
        flag: EdgeFlags,
        edges: Vec<NewEdge>,
        inode: Key<Option<Hash>>,
    },
    },
}

impl PatchHeader {
    /// Reads everything in this patch, but the actual contents.
    pub fn from_reader_nochanges<R: Read>(mut r: R) -> Result<PatchHeader> {
        let version: u32 = deserialize_from(&mut r)?;
        debug!("version: {:?}", version);
        debug!("version: {:?}", version);
        debug!("version: {:?}", version);
        Ok(deserialize_from(&mut r)?)
    }
    }
}

/// Semantic groups of changes, for interface purposes.
/// Semantic groups of changes, for interface purposes.
#[derive(Debug)]
pub enum Record<Context> {
    FileMove {
        new_name: String,
        del: Change<Context>,
        add: Change<Context>,
    },
    FileDel {
        name: String,
        del: Change<Context>,
    },
    FileAdd {
        name: String,
        add: Change<Context>,
    },
    Change {
        file: Rc<PathBuf>,
        change: Change<Context>,
        conflict_reordering: Vec<Change<Context>>,
    },
    Replace {
        file: Rc<PathBuf>,
        adds: Change<Context>,
        dels: Change<Context>,
        conflict_reordering: Vec<Change<Context>>,
    },
}
}

pub struct RecordIter<R, C> {
pub struct RecordIter<R, C> {
    rec: Option<R>,
    extra: Option<C>,
}

impl<Context> IntoIterator for Record<Context> {
    type IntoIter = RecordIter<Record<Context>, Change<Context>>;
    type Item = Change<Context>;
    fn into_iter(self) -> Self::IntoIter {
        RecordIter {
            rec: Some(self),
            extra: None,
        }
    }
}

impl<Context> Record<Context> {
    pub fn iter(&self) -> RecordIter<&Record<Context>, &Change<Context>> {
        RecordIter {
            rec: Some(self),
            extra: None,
        }
    }
}

impl<Context> Iterator for RecordIter<Record<Context>, Change<Context>> {
    type Item = Change<Context>;
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(extra) = self.extra.take() {
            Some(extra)
        } else if let Some(rec) = self.rec.take() {
            match rec {
                Record::FileMove { del, add, .. } => {
                    self.extra = Some(add);
                    Some(del)
                }
                Record::FileDel { del: c, .. }
                | Record::FileAdd { add: c, .. }
                | Record::Change { change: c, .. } => Some(c),
                Record::Replace { adds, dels, .. } => {
                Record::Replace { adds, dels, .. } => {
                    self.extra = Some(adds);
                    Some(dels)
                }
            }
            }
        } else {
            None
        }
    }
}

impl<'a, Context> Iterator for RecordIter<&'a Record<Context>, &'a Change<Context>> {
    type Item = &'a Change<Context>;
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(extra) = self.extra.take() {
            Some(extra)
        } else if let Some(rec) = self.rec.take() {
            match *rec {
                Record::FileMove {
                    ref del, ref add, ..
                } => {
                    self.extra = Some(add);
                    self.extra = Some(add);
                    Some(del)
                }
                Record::FileDel { del: ref c, .. }
                | Record::FileAdd { add: ref c, .. }
                | Record::Change { change: ref c, .. } => Some(c),
                Record::Replace {
                    ref adds, ref dels, ..
                } => {
                    self.extra = Some(adds);
                    self.extra = Some(adds);
                    Some(dels)
                }
            }
        } else {
            None
        }
    }
}

impl UnsignedPatch {
    pub fn empty() -> Self {
        UnsignedPatch {
            header: PatchHeader {
                authors: vec![],
                name: "".to_string(),
                description: None,
                timestamp: chrono::Utc::now(),
                flag: PatchFlags::empty(),
            },
            dependencies: HashSet::new(),
            changes: vec![],
        }
    }
    pub fn leave_unsigned(self) -> Patch {
        Patch::Unsigned(self)
    }

    fn is_tag(&self) -> bool {
        self.header.flag.contains(PatchFlags::TAG)
    }

    pub fn inverse(&self, hash: &Hash, changes: &mut Vec<Change<ChangeContext<Hash>>>) {
        for ch in self.changes.iter() {
            debug!("inverse {:?}", ch);
            match *ch {
                Change::NewNodes {
                    ref up_context,
                    flag,
                    line_num,
                    ref nodes,
                    ref inode,
                    ..
                } => {
                    let edges = up_context
                        .iter()
                        .map(|up| NewEdge {
                            from: Key {
                            from: Key {
                                patch: match up.patch {
                                    Some(ref h) => Some(h.clone()),
                                    None => Some(hash.clone()),
                                },
                                },
                                line: up.line,
                            },
                            to: Key {
                                patch: Some(hash.clone()),
                                line: line_num,
                            },
                            },
                            introduced_by: Some(hash.clone()),
                        })
                        .chain((1..nodes.len()).map(|i| NewEdge {
                            from: Key {
                            from: Key {
                                patch: Some(hash.clone()),
                                line: line_num + (i - 1),
                            },
                            },
                            to: Key {
                                patch: Some(hash.clone()),
                                line: line_num + i,
                            },
                            introduced_by: Some(hash.clone()),
                        }))
                        .collect();
                    changes.push(Change::NewEdges {
                    changes.push(Change::NewEdges {
                        edges,
                        inode: inode.clone(),
                        previous: flag,
                        flag: flag ^ EdgeFlags::DELETED_EDGE,
                    })
                }
                Change::NewEdges {
                    previous,
                    flag,
                    ref edges,
                    ref inode,
                } => changes.push(Change::NewEdges {
                    previous: flag,
                    flag: previous,
                    inode: inode.clone(),
                    edges: edges
                        .iter()
                        .map(|e| NewEdge {
                            from: e.from.clone(),
                            to: e.to.clone(),
                            introduced_by: Some(hash.clone()),
                        })
                        .collect(),
                }),
            }
            }
        }
    }
}

impl Patch {
    /// An approximate upper bound of the number of extra bytes in the
    /// database this patch might require. This depends a lot on the
    /// patch and the database, so it might be wrong.
    pub fn size_upper_bound(&self) -> usize {
        // General overhead for applying a patch; 8 pages.
        let mut size: usize = 1 << 15;
        for c in self.changes().iter() {
            match *c {
                Change::NewNodes { ref nodes, .. } => {
                    size += nodes.iter().map(|x| x.len()).sum::<usize>();
                    size += nodes.len() * 2048 // + half a page
                }
                }
            }
            }
        }
        size
    }

    pub fn is_tag(&self) -> bool {
        match *self {
            Patch::Unsigned(ref patch) => patch.is_tag(),
            _ => false,
        }
    }

    /// Read one patch from a gzip-compressed `BufRead`. If several
    /// patches are available in the same `BufRead`, this method can
    /// be called again.
    pub fn from_reader_compressed<R: BufRead>(r: &mut R) -> Result<(Hash, Vec<u8>, Patch)> {
        let mut rr = flate2::bufread::GzDecoder::new(r);
        let filename = {
            let filename = if let Some(header) = rr.header() {
                if let Some(filename) = header.filename() {
                    from_utf8(filename)?
                } else {
                    return Err(ErrorKind::EOF.into());
                }
                }
            } else {
                return Err(ErrorKind::EOF.into());
            };
            };
            if let Some(h) = Hash::from_base58(filename) {
                h
            } else {
                return Err(ErrorKind::WrongHash.into());
            }
            }
            }
        };

        let mut buf = Vec::new();
        rr.read_to_end(&mut buf)?;

        // Checking the hash.
        let patch: Patch = deserialize(&buf[..])?;
        patch.check_hash(&buf, &filename)?;

        Ok((filename, buf, patch))
    }

    fn check_hash(&self, buf: &[u8], filename: &Hash) -> Result<()> {
    fn check_hash(&self, buf: &[u8], filename: &Hash) -> Result<()> {
        let buf = match *self {
            Patch::Signed0 | Patch::Unsigned0 => {
                panic!("refusing to interact with old patch version")
            }
            Patch::Unsigned(_) => buf,
            Patch::Unsigned(_) => buf,
        };
        let hash = Hash::of_slice(buf)?;
        match (filename, &hash) {
            (&Hash::Sha512(ref filename), &Hash::Sha512(ref hash))
                if &filename.0[..] == &hash.0[..] =>
            {
                Ok(())
            }
            _ => Err(ErrorKind::WrongHash.into()),
            _ => Err(ErrorKind::WrongHash.into()),
        }
    }

    pub fn to_buf(&self) -> Result<(Vec<u8>, Hash)> {
        // Encoding to a buffer.
        let buf = serialize(&self)?;
        // Hashing the buffer.
        // Hashing the buffer.
        let hash = Hash::of_slice(&buf)?;
        Ok((buf, hash))
    }

    /// Save the patch, computing the hash.
    pub fn save<P: AsRef<Path>>(&self, dir: P, key: Option<&KeyPair>) -> Result<Hash> {
        let (buf, hash) = self.to_buf()?;
        // Writing to the file.
        let h = hash.to_base58();
        let mut path = dir.as_ref().join(&h);
        path.set_extension("gz");
        if metadata(&path).is_err() {
            debug!("save, path {:?}", path);
            let f = File::create(&path)?;
            debug!("created");
            let mut w = flate2::GzBuilder::new()
                .filename(h.as_bytes())
                .write(f, flate2::Compression::best());
            w.write_all(&buf)?;
            w.finish()?;
            debug!("saved");
        }

        if let Some(key) = key {
            path.set_extension("sig");
            let mut file = OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .open(&path)?;

            let mut signatures: SignatureFile =
                serde_json::from_reader(&mut file).unwrap_or(SignatureFile {
                    hash: h,
                    hash: h,
                    signatures: HashMap::new(),
                });
                });
            let signature = key.sign_detached(&hash.as_ref().to_binary())?;
            let public_key = key.public_key_base64();
            signatures
                .signatures
                .insert(public_key, bs58::encode(&signature.as_ref()).into_string());
            serde_json::to_writer(&mut file, &signatures)?;
            serde_json::to_writer(&mut file, &signatures)?;
        }
        Ok(hash)
    }

    pub fn inverse(&self, hash: &Hash, changes: &mut Vec<Change<ChangeContext<Hash>>>) {
        match *self {
            Patch::Unsigned0 => panic!("Can't reverse old patches"),
            Patch::Signed0 => panic!("Can't reverse old patches"),
            Patch::Unsigned(ref u) => u.inverse(hash, changes),
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SignatureFile {
    pub hash: String,
    pub signatures: HashMap<String, String>,
}

pub fn read_signature_file(r: &mut Read) -> Result<SignatureFile> {
    let signatures: SignatureFile = serde_json::from_reader(r)?;
    // verify signatures
    for (key, sig) in signatures.signatures.iter() {
        let k = thrussh_keys::parse_public_key_base64(&key)?;
        let sig = bs58::decode(sig).into_vec()?;
        if !k.verify_detached(signatures.hash.as_bytes(), &sig) {
            return Err(ErrorKind::WrongPatchSignature.into());
        }
        }
    }
    Ok(signatures)
}

impl SignatureFile {
    pub fn write_signature_file(&self, w: &mut Write) -> Result<()> {
        serde_json::to_writer(w, self)?;
        Ok(())
    }
}

pub struct Signatures<'a, R: Read>(
    serde_json::StreamDeserializer<'a, serde_json::de::IoRead<R>, SignatureFile>,
);


pub fn read_signatures<'a, R: Read>(r: R) -> Signatures<'a, R> {
    Signatures(serde_json::Deserializer::from_reader(r).into_iter())
    Signatures(serde_json::Deserializer::from_reader(r).into_iter())
}

impl<'a, R: Read> Iterator for Signatures<'a, R> {
    type Item = Result<SignatureFile>;
    type Item = Result<SignatureFile>;
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|n| n.map_err(super::Error::from))
    }
}

pub fn read_changes(r: &mut Read) -> Result<HashMap<Hash, ApplyTimestamp>> {
pub fn read_changes(r: &mut Read) -> Result<HashMap<Hash, ApplyTimestamp>> {
    let mut s = String::new();
    r.read_to_string(&mut s)?;
    let mut result = HashMap::new();
    for l in s.lines() {
        let mut sp = l.split(':');
        match (
            sp.next().and_then(Hash::from_base58),
            sp.next().and_then(|s| s.parse().ok()),
        ) {
            (Some(h), Some(s)) => {
                result.insert(h, s);
            }
            _ => {}
            _ => {}
        }
    }
    Ok(result)
}

pub fn read_changes_from_file<P: AsRef<Path>>(
    changes_file: P,
) -> Result<HashMap<Hash, ApplyTimestamp>> {
    let mut file = File::open(changes_file)?;
    read_changes(&mut file)
    read_changes(&mut file)
}

impl<U: Transaction, R> GenericTxn<U, R> {
    pub fn new_patch<I: Iterator<Item = Hash>>(
        &self,
        &self,
        branch: &Branch,
        authors: Vec<String>,
        name: String,
        description: Option<String>,
        timestamp: DateTime<Utc>,
        changes: Vec<Change<ChangeContext<Hash>>>,
        extra_dependencies: I,
        flag: PatchFlags,
    ) -> Patch {
    ) -> Patch {
        let mut dependencies = self.dependencies(branch, changes.iter());
        let mut dependencies = self.dependencies(branch, changes.iter());
        dependencies.extend(extra_dependencies);
        Patch::Unsigned(UnsignedPatch {
            header: PatchHeader {
                authors,
                name,
                description,
                timestamp,
                flag,
            },
            dependencies,
            changes,
        })
    }

    pub fn dependencies<'a, I: Iterator<Item = &'a Change<ChangeContext<Hash>>>>(
        &self,
        branch: &Branch,
        changes: I,
    ) -> HashSet<Hash> {
        let mut deps = HashSet::new();
        let mut deps = HashSet::new();
        let mut zombie_deps = HashSet::new();
        for ch in changes {
            match *ch {
                Change::NewNodes {
                    ref up_context,
                    ref down_context,