pijul_org/pijul

Myers and Patience Diff integrated into libpijul

By pmeunier on December 6, 2018
signed.
signed.
signed.
signed.
signed.
signed.
signed.
signed.
signed.
signed.
signed.
signed.
signed.
signed.
signed.
signed.
6XXUrxdH22pNQa6y3wtcv3rBmP1aWujW9k9znkhyiyiGrZtGzb1fduwH3nbHSFNvvLwkiSS3ixoNb7XhauUCYMxt

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

version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
 "diffs 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "sanakirja 0.8.20",
version = "0.8.20"
"checksum diffs 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "636c85e9f913aaf101163b6155d262723ae5cc1e98aca74f2efb33e21f7795ac"
[[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.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "memchr 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

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

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

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

[[package]]
name = "base64"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "byteorder 1.2.6 (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.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "byteorder 1.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "bit-vec"
version = "0.4.4"
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.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "constant_time_eq 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "bs58"
version = "0.2.2"
source = "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 = "byteorder"
version = "1.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"

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

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

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

[[package]]
name = "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.80 (registry+https://github.com/rust-lang/crates.io-index)",
 "time 0.1.40 (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.43 (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.43 (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 = "crossbeam-channel"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "crossbeam-epoch 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "crossbeam-utils 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "parking_lot 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "smallvec 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "crossbeam-epoch"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "arrayvec 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "crossbeam-utils 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "lazy_static 1.1.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-epoch"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "arrayvec 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "crossbeam-utils 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "lazy_static 1.1.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-utils"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"

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

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

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

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

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

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

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

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

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

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

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

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

[[package]]
name = "filetime"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "flate2"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "miniz-sys 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "miniz_oxide_c_api 0.2.0 (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.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

[[package]]
name = "getch"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "termios 0.2.2 (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.8 (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.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "memchr 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "h2"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "byteorder 1.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "bytes 0.4.10 (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.13 (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.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "slab 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "string 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.9 (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.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.10 (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.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "hyper"
version = "0.12.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.10 (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.13 (registry+https://github.com/rust-lang/crates.io-index)",
 "http 0.1.13 (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.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)",
 "time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-executor 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-reactor 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-tcp 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-timer 0.2.7 (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.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.10 (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.12 (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.9 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "ignore"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "crossbeam-channel 0.2.6 (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.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "memchr 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "same-file 1.0.3 (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.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi-util 0.1.1 (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.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

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

[[package]]
name = "libflate"
version = "0.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "adler32 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "byteorder 1.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "crc 1.8.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "libpijul"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
version = "0.11.1"
dependencies = [
 "base64 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "base64 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "bincode 1.0.1 (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.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "diffs 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "flate2 1.0.4 (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.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "openssl 0.10.15 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "sanakirja 0.8.19 (registry+https://github.com/rust-lang/crates.io-index)",
 "sanakirja 0.8.21 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)",
 "tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "thrussh-keys 0.11.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "toml 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "libpijul"
version = "0.11.1"
dependencies = [
 "base64 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "bincode 1.0.1 (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.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "flate2 1.0.4 (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.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "openssl 0.10.15 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "sanakirja 0.8.19 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)",
 "tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "thrussh-keys 0.11.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "toml 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
]
source = "registry+https://github.com/rust-lang/crates.io-index"
replace = "libpijul 0.11.1"

[[package]]
name = "line"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
version = "0.1.11"
dependencies = [
 "libc 0.2.43 (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.11"
dependencies = [
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "utf8parse 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
source = "registry+https://github.com/rust-lang/crates.io-index"
replace = "line 0.1.11"

[[package]]
name = "lock_api"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "owning_ref 0.3.3 (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.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

[[package]]
name = "memmap"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "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 = "mime"
version = "0.3.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "unicase 2.2.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.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "phf 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)",
 "phf_codegen 0.7.23 (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.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "miniz_oxide"
version = "0.2.0"
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.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cc 1.0.25 (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.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "miniz_oxide 0.2.0 (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.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.5 (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.1 (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.43 (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.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "openssl 0.10.15 (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.39 (registry+https://github.com/rust-lang/crates.io-index)",
 "schannel 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)",
 "security-framework 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "security-framework-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "tempfile 3.0.4 (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.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "nodrop"
version = "0.1.12"
source = "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.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.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.3 (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.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.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "openssl"
version = "0.10.15"
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.6 (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.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "openssl-sys 0.9.39 (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.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cc 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)",
 "vcpkg 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "owning_ref"
version = "0.3.3"
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 = "pager"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "errno 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "parking_lot_core"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.5.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.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.3.6 (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 = "phf"
version = "0.7.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "phf_shared 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

[[package]]
name = "phf_shared"
version = "0.7.23"
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.11.0"
dependencies = [
 "base64 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "bincode 1.0.1 (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.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "dirs 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "env_logger 0.5.13 (registry+https://github.com/rust-lang/crates.io-index)",
 "flate2 1.0.4 (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.0 (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.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "isatty 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "libpijul 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "line 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "line 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "libpijul 0.11.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "line 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "pager 0.14.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.5.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "reqwest 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "rpassword 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)",
 "shell-escape 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "tar 0.4.17 (registry+https://github.com/rust-lang/crates.io-index)",
 "tempdir 0.3.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.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "thrussh-config 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "thrussh-keys 0.11.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-uds 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "toml 0.4.8 (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.5 (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 = "proc-macro2"
version = "0.4.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

[[package]]
name = "rand"
version = "0.5.5"
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-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand_core 0.2.2 (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_core"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

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

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

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

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

[[package]]
name = "reqwest"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "base64 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "bytes 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)",
 "encoding_rs 0.8.10 (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.13 (registry+https://github.com/rust-lang/crates.io-index)",
 "hyper 0.12.12 (registry+https://github.com/rust-lang/crates.io-index)",
 "hyper-tls 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "libflate 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "mime 0.3.12 (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.80 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_urlencoded 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "uuid 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "rpassword"
version = "2.0.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.43 (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.9"
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.6"
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.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "winapi-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "sanakirja"
version = "0.8.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
source = "registry+https://github.com/rust-lang/crates.io-index"
source = "registry+https://github.com/rust-lang/crates.io-index"
version = "0.8.21"
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.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "memmap 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "schannel"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "lazy_static 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "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.1"
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.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "security-framework-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "security-framework-sys"
version = "0.2.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.43 (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 = "serde"
version = "1.0.80"
source = "registry+https://github.com/rust-lang/crates.io-index"

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

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

[[package]]
name = "serde_urlencoded"
version = "0.5.3"
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.80 (registry+https://github.com/rust-lang/crates.io-index)",
 "url 1.7.1 (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.1"
source = "registry+https://github.com/rust-lang/crates.io-index"

[[package]]
name = "smallvec"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "unreachable 1.0.0 (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.1"
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.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)",
 "quote 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)",
 "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

[[package]]
name = "tar"
version = "0.4.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "filetime 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
 "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.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tempfile"
version = "3.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "redox_syscall 0.1.40 (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.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "byteorder 1.2.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 = "termcolor"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "wincolor 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

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

[[package]]
name = "thrussh"
version = "0.20.5"
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.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "cryptovec 0.4.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.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "openssl 0.10.15 (registry+https://github.com/rust-lang/crates.io-index)",
 "thrussh-keys 0.11.3 (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.11 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "thrussh-config"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "dirs 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "error-chain 0.12.0 (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.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "regex 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "thrussh 0.20.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "thrussh-keys"
version = "0.11.3"
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.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "cryptovec 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "dirs 1.0.4 (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.5 (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.15 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)",
 "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)",
 "thrussh-libsodium 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio 0.1.11 (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.43 (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.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
 "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.10 (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)",
 "tokio-codec 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-current-thread 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-executor 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-fs 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-reactor 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-tcp 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-threadpool 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-timer 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-udp 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-uds 0.2.2 (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.10 (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.9 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

[[package]]
name = "tokio-fs"
version = "0.1.3"
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.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-threadpool 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-io"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.10 (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.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-reactor"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "crossbeam-utils 0.5.0 (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.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.5 (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.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "parking_lot 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)",
 "slab 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-executor 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-io 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-tcp"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.10 (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.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-reactor 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-threadpool"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "crossbeam-deque 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "crossbeam-utils 0.5.0 (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.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "num_cpus 1.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
 "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-executor 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-timer"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "crossbeam-utils 0.5.0 (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.1 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-executor 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-udp"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.10 (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.5 (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.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-reactor 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

[[package]]
name = "tokio-uds"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "bytes 0.4.10 (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.43 (registry+https://github.com/rust-lang/crates.io-index)",
 "log 0.4.5 (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-io 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
 "tokio-reactor 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

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

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

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

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

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

[[package]]
name = "url"
version = "1.7.1"
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.1"
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.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "rand 0.5.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 = "void"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"

[[package]]
name = "walkdir"
version = "2.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "same-file 1.0.3 (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.1 (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.5 (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 = "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.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]

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

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

[[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.43 (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 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.8 (registry+https://github.com/rust-lang/crates.io-index)" = "68f56c7353e5a9547cbd76ed90f7bb5ffc3ba09d4ea9bd1d8c06c8b1142eeb5a"
"checksum ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b"
"checksum argon2rs 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "3f67b0b6a86dae6e67ff4ca2b6201396074996379fba2b92ff649126f37cb392"
"checksum arrayvec 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)" = "a1e964f9e24d588183fcb43503abda40d288c8657dfc27311516ce2f05675aef"
"checksum atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "9a7d5b8723950951411ee34d271d99dddcc2035a16ab25310ea2c8cfd4369652"
"checksum backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)" = "89a47830402e9981c5c41223151efcced65a0510c13097c769cede7efb34782a"
"checksum backtrace-sys 0.1.24 (registry+https://github.com/rust-lang/crates.io-index)" = "c66d56ac8dabd07f6aacdaf633f4b8262f5b3601a810a0dcddffd5c22c69daa0"
"checksum base64 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "621fc7ecb8008f86d7fb9b95356cd692ce9514b80a86d85b397f32a22da7b9e2"
"checksum base64 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)" = "489d6c0ed21b11d038c31b6ceccca973e65d73ba3bd8ecb9a2babf5546164643"
"checksum bincode 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9f2fb9e29e72fd6bc12071533d5dc7664cb01480c59406f656d7ac25c7bd8ff7"
"checksum bit-vec 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "02b4ff8b16e6076c3e14220b39fbc1fabb6737522281a388998046859400895f"
"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 bs58 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "0de79cfb98e7aa9988188784d8664b4b5dad6eaaa0863b91d9a4ed871d4f7a42"
"checksum build_const 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "39092a32794787acd8525ee150305ff051b0aa6cc2abaf193924f5ab05425f39"
"checksum byteorder 1.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "90492c5858dd7d2e78691cfb89f90d273a2800fc11d98f60786e5d87e2f83781"
"checksum bytes 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)" = "0ce55bd354b095246fc34caf4e9e242f5297a7fd938b090cadfea6eee614aa62"
"checksum cc 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)" = "f159dfd43363c4d08055a07703eb7a3406b0dac4d0584d96965a3262db3c9d16"
"checksum cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "082bb9b28e00d3c9d39cc03e64ce4cea0f1bb9b3fde493f0cbc008472d22bdf4"
"checksum chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "45912881121cb26fad7c38c17ba7daa18764771836b34fab7d3fbd93ed633878"
"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 crossbeam-channel 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "7b85741761b7f160bc5e7e0c14986ef685b7f8bf9b7ad081c60c604bb4649827"
"checksum crossbeam-deque 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3486aefc4c0487b9cb52372c97df0a48b8c249514af1ee99703bf70d2f2ceda1"
"checksum crossbeam-epoch 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "30fecfcac6abfef8771151f8be4abc9e4edc112c2bcb233314cafde2680536e9"
"checksum crossbeam-epoch 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9c90f1474584f38e270b5b613e898c8c328aa4f3dea85e0a27ac2e642f009416"
"checksum crossbeam-utils 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "677d453a17e8bd2b913fa38e8b9cf04bcdbb5be790aa294f2389661d72036015"
"checksum cryptovec 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "7d303d98da2c4bfa140116dec731f2a5d19269f7f1be21921ab189c5495d9ff1"
"checksum diffs 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f986674bb2b4ef21915be8625ebddeffe67bcf78153351ca52d626a5f6b29e6e"
"checksum dirs 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "88972de891f6118092b643d85a0b28e0678e0f948d7f879aa32f2d5aafe97d2a"
"checksum dtoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "6d301140eb411af13d3115f9a562c85cc6b541ade9dfa314132244aaee7489dd"
"checksum encoding_rs 0.8.10 (registry+https://github.com/rust-lang/crates.io-index)" = "065f4d0c826fdaef059ac45487169d918558e3cf86c9d89f6e81cf52369126e5"
"checksum env_logger 0.5.13 (registry+https://github.com/rust-lang/crates.io-index)" = "15b0a4d2e39f8420210be8b27eeda28029729e2fd4291019455016c348240c38"
"checksum errno 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "c2a071601ed01b988f896ab14b95e67335d1eeb50190932a1320f7fe3cadc84e"
"checksum errno-dragonfly 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "14ca354e36190500e1e1fb267c647932382b54053c50b14970856c0b00a35067"
"checksum error-chain 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "07e791d3be96241c77c43846b665ef1384606da2cd2a48730abe606a12906e02"
"checksum failure 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "6dd377bcc1b1b7ce911967e3ec24fa19c3224394ec05b54aa7b083d498341ac7"
"checksum failure_derive 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "64c2d913fe8ed3b6c6518eedf4538255b989945c14c2a7d5cbff62a5e2120596"
"checksum filetime 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "da4b9849e77b13195302c174324b5ba73eec9b236b24c221a61000daefb95c5f"
"checksum flate2 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "3b0c7353385f92079524de3b7116cf99d73947c08a7472774e9b3b04bff3b901"
"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-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 gcc 0.3.55 (registry+https://github.com/rust-lang/crates.io-index)" = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2"
"checksum getch 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a5d74884542f30bafa33aa6615b63d6f430f57546e60e3bd59895d5459d776ab"
"checksum globset 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "4743617a7464bbda3c8aec8558ff2f9429047e025771037df561d383337ff865"
"checksum h2 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "7dd33bafe2e6370e6c8eb0cf1b8c5f93390b90acde7e9b03723f166b28b648ed"
"checksum hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "805026a5d0141ffc30abb3be3173848ad46a1b1664fe632428479619a3644d77"
"checksum http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "24f58e8c2d8e886055c3ead7b28793e1455270b5fb39650984c224bc538ba581"
"checksum httparse 1.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e8734b0cfd3bc3e101ec59100e101c2eecd19282202e87808b3037b442777a83"
"checksum humantime 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0484fda3e7007f2a4a0d9c3a703ca38c71c54c55602ce4660c419fd32e188c9e"
"checksum hyper 0.12.12 (registry+https://github.com/rust-lang/crates.io-index)" = "4aca412c241a2dd53af261efc7adf7736fdebd67dc0d1cc1ffdbcb9407e0e810"
"checksum hyper-tls 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "32cd73f14ad370d3b4d4b7dce08f69b81536c82e39fcc89731930fe5788cd661"
"checksum idna 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "38f09e0f0b1fb55fdee1f17470ad800da77af5186a1a76c026b679358b7e844e"
"checksum ignore 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "36ecfc5ad80f0b1226df948c562e2cddd446096be3f644c95106400eae8a5e01"
"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 isatty 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "e31a8281fc93ec9693494da65fbf28c0c2aa60a2eaec25dc58e2f31952e95edc"
"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 lazy_static 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ca488b89a5657b0a2ecd45b95609b3e848cf1755da332a0da46e2b2b1cb371a7"
"checksum lazycell 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ddba4c30a78328befecec92fc94970e53b3ae385827d28620f0f5bb2493081e0"
"checksum libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)" = "76e3a3ef172f1a0b9a9ff0dd1491ae5e6c948b94479a3021819ba7d860c8645d"
"checksum libflate 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)" = "21138fc6669f438ed7ae3559d5789a5f0ba32f28c1f0608d1e452b0bb06ee936"
"checksum libpijul 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d8da466b1fe644509484ccc3a6ed98cf9d3026badc845d2bb2ccc8da33d1124e"
"checksum line 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "7522c8beb5401ce2cbd5d9fb92c043f5d1107e9fbf7a9a7e84fca4295e429da8"
"checksum line 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "7522c8beb5401ce2cbd5d9fb92c043f5d1107e9fbf7a9a7e84fca4295e429da8"
"checksum libpijul 0.11.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f88c6300c97303bd90f2220c351d584a5cc414fcb8f80e7d60cc5b7844566c44"
"checksum line 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)" = "8454cb2e191637548d5734a9eb617344dea73994434b9c197f53d9ac536ed4b1"
"checksum lock_api 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "775751a3e69bde4df9b38dd00a1b5d6ac13791e4223d4a0506577f0dd27cfb7a"
"checksum log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "d4fcce5fa49cc693c312001daf1d13411c4a5283796bac1084299ea3e567113f"
"checksum matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08"
"checksum memchr 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4b3629fe9fdbff6daa6c33b90f7c08355c1aca05a3d01fa8063b822fcf185f3b"
"checksum memmap 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e2ffa2c986de11a9df78620c01eeaaf27d94d3ff02bf81bfcca953102dd0c6ff"
"checksum memoffset 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0f9dc261e2b62d7a622bf416ea3c5245cdd5d9a7fcc428c0d06804dfce1775b3"
"checksum mime 0.3.12 (registry+https://github.com/rust-lang/crates.io-index)" = "0a907b83e7b9e987032439a387e187119cddafc92d5c2aaeb1d92580a793f630"
"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.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5ad30a47319c16cde58d0314f5d98202a80c9083b5f61178457403dfb14e509c"
"checksum miniz_oxide_c_api 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "28edaef377517fd9fe3e085c37d892ce7acd1fbeab9239c5a36eec352d8a8b7e"
"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 nodrop 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)" = "9a2228dca57108069a5262f2ed8bd2e82496d2e074a06d1ccc7ce1687b6ae0a2"
"checksum num 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "4703ad64153382334aa8db57c637364c322d3372e097840c72000dabdcf6156e"
"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.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c51a3322e4bca9d212ad9a158a02abc6934d005490c054a2778df73a70aa0a30"
"checksum openssl 0.10.15 (registry+https://github.com/rust-lang/crates.io-index)" = "5e1309181cdcbdb51bc3b6bedb33dfac2a83b3d585033d3f6d9e22e8c1928613"
"checksum openssl-probe 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "77af24da69f9d9341038eba93a073b1fdaaa1b788221b00a69bce9e762cb32de"
"checksum openssl-sys 0.9.39 (registry+https://github.com/rust-lang/crates.io-index)" = "278c1ad40a89aa1e741a1eed089a2f60b18fab8089c3139b542140fc7d674106"
"checksum owning_ref 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "cdf84f41639e037b484f93433aa3897863b561ed65c6e59c7073d7c561710f37"
"checksum pager 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)" = "175e6ec8b6c51fcbb3a6db4ef68cd94e577d5b5ed7ecadbf24dfd76114ade175"
"checksum parking_lot 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)" = "f0802bff09003b291ba756dc7e79313e51cc31667e94afbe847def490424cde5"
"checksum parking_lot_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ad7f7e6ebdc79edff6fdcb87a55b620174f7a989e3eb31b65231f4af57f00b8c"
"checksum percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831"
"checksum phf 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)" = "cec29da322b242f4c3098852c77a0ca261c9c01b806cae85a5572a1eb94db9a6"
"checksum phf_codegen 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)" = "7d187f00cd98d5afbcd8898f6cf181743a449162aeb329dcd2f3849009e605ad"
"checksum phf_generator 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)" = "03dc191feb9b08b0dc1330d6549b795b9d81aec19efe6b4a45aec8d4caee0c4b"
"checksum phf_shared 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)" = "b539898d22d4273ded07f64a05737649dc69095d92cb87c7097ec68e3f150b93"
"checksum pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)" = "676e8eb2b1b4c9043511a9b7bea0915320d7e502b0a079fb03f9635a5252b18c"
"checksum proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)" = "3d7b7eaaa90b4a90a932a9ea6666c95a389e424eff347f0f793979289429feee"
"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 quote 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)" = "dd636425967c33af890042c483632d33fa7a18f19ad1d7ea72e8998c6ef8dea5"
"checksum rand 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "8356f47b32624fef5b3301c1be97e5944ecdd595409cc5da11d05f211db6cfbd"
"checksum rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)" = "e464cd887e869cddcae8792a4ee31d23c7edd516700695608f5b98c67ee0131c"
"checksum rand_core 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1961a422c4d189dfb50ffa9320bf1f2a9bd54ecb92792fb9477f99a1045f3372"
"checksum rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0905b6b7079ec73b314d4c748701f6931eb79fd97c668caa3f1899b22b32c6db"
"checksum redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)" = "c214e91d3ecf43e9a4e41e578973adeb14b474f2bee858742d127af75a0112b1"
"checksum redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7e891cfe48e9100a70a3b6eb652fef28920c117d366339687bd5576160db0f76"
"checksum redox_users 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "214a97e49be64fd2c86f568dd0cb2c757d2cc53de95b273b6ad0a1c908482f26"
"checksum regex 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "2069749032ea3ec200ca51e4a31df41759190a88edca0d2d86ee8bedf7073341"
"checksum regex-syntax 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "747ba3b235651f6e2f67dfa8bcdcd073ddb7c243cb21c442fc12395dfcac212d"
"checksum remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3488ba1b9a2084d38645c4c08276a1752dcbf2c7130d74f1569681ad5d2799c5"
"checksum reqwest 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)" = "aa238ac676ec77e62be3e70656828ca4f596fccd33c6fab92942701bc8c8b4fe"
"checksum rpassword 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d127299b02abda51634f14025aec43ae87a7aa7a95202b6a868ec852607d1451"
"checksum rustc-demangle 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "bcfe5b13211b4d78e5c2cadfebd7769197d95c639c35a50057eb4c05de811395"
"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.6 (registry+https://github.com/rust-lang/crates.io-index)" = "7153dd96dade874ab973e098cb62fcdbb89a03682e46b144fd09550998d4a4a7"
"checksum safemem 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8dca453248a96cb0749e36ccdfe2b0b4e54a61bfef89fb97ec621eb8e0a93dd9"
"checksum same-file 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "10f7794e2fda7f594866840e95f5c5962e886e228e68b6505885811a94dd728c"
"checksum sanakirja 0.8.19 (registry+https://github.com/rust-lang/crates.io-index)" = "3315ca740ad9558707a67bf8f7eb4a1cc4803c2476916316ba23c8380b782a09"
In file Cargo.toml
1
2

3
4
5
6

7
8
[workspace]

members = [ "libpijul", "pijul", "line" ]
members = [ "libpijul", "pijul", "line", "diffs" ]

[replace]
"libpijul:0.11.1" = { path = "libpijul" }
"line:0.1.10" = { path = "line" }
"line:0.1.11" = { path = "line" }
"diffs:0.2.1" = { path = "diffs" }
4
5

6
7
documentation = "https://docs.rs/diffs"
homepage = "https://nest.pijul.com/pijul_org/pijul"
version = "0.1.0"
version = "0.2.1"
license = "MIT/Apache-2.0"
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
pub trait Diff: Sized {
    type Error;
    /// Called when lines with indices `old` (in the old version) and
    /// `new` (in the new version) start an section equal in both
    /// versions, of length `len`.
    fn equal(&mut self, old: usize, new: usize, len: usize) {}
    fn equal(&mut self, old: usize, new: usize, len: usize) -> Result<(), Self::Error> { Ok(()) }
    /// Called when a section of length `len`, starting at `old`,
    /// needs to be deleted from the old version.
    fn delete(&mut self, old: usize, len: usize) {}
    fn delete(&mut self, old: usize, len: usize) -> Result<(), Self::Error> { Ok(()) }
    /// Called when a section of the new version, of length `new_len`
    /// and starting at `new`, needs to be inserted at position `old'.
    fn insert(&mut self, old: usize, new: usize, new_len: usize) {}
    fn insert(&mut self, old: usize, new: usize, new_len: usize) -> Result<(), Self::Error> { Ok(()) }
    /// Called when a section of the old version, starting at index
    /// `old` and of length `old_len`, needs to be replaced with a
    /// section of length `new_len`, starting at `new`, of the new
    /// version.
    fn replace(&mut self, old: usize, old_len: usize, new: usize, new_len: usize) {
        self.delete(old, old_len);
        self.insert(old + old_len, new, new_len);
    fn replace(&mut self, old: usize, old_len: usize, new: usize, new_len: usize) -> Result<(), Self::Error> {
        self.delete(old, old_len)?;
        self.insert(old, new, new_len)
    }
    /// Always called at the end of the algorithm.
    fn finish(&mut self) {}
    fn finish(&mut self) -> Result<(), Self::Error> { Ok(()) }
}

impl<'a, D: Diff + 'a> Diff for &'a mut D {
    fn equal(&mut self, old: usize, new: usize, len: usize) {
    type Error = D::Error;
    fn equal(&mut self, old: usize, new: usize, len: usize) -> Result<(), Self::Error> {
        (*self).equal(old, new, len)
    }
    fn delete(&mut self, old: usize, len: usize) {
    fn delete(&mut self, old: usize, len: usize) -> Result<(), Self::Error>  {
        (*self).delete(old, len)
    }

    fn insert(&mut self, old: usize, new: usize, new_len: usize) {
    fn insert(&mut self, old: usize, new: usize, new_len: usize) -> Result<(), Self::Error>  {
        (*self).insert(old, new, new_len)
    }

    fn replace(&mut self, old: usize, old_len: usize, new: usize, new_len: usize) {
    fn replace(&mut self, old: usize, old_len: usize, new: usize, new_len: usize) -> Result<(), Self::Error>  {
        (*self).replace(old, old_len, new, new_len)
    }

    fn finish(&mut self) {
    fn finish(&mut self) -> Result<(), Self::Error> {
        (*self).finish()
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

fn modulo(a: isize, b: usize) -> usize {
    if a >= 0 {
        (a as usize) % b
    } else {
        let q = a / (b as isize);
        (a - (b as isize) * (q - 1)) as usize
    }
    let b = b as isize;
    (((a % b) + b) % b) as usize
}

#[test]
fn test_modulo() {
    assert_eq!(modulo(-11, 10), 9);
    assert_eq!(modulo(23, 7), 2);
    assert_eq!(modulo(-12, 6), 0);
}

/// Myers' diff algorithm.
pub fn diff<A, B: PartialEq<A>, D: Diff>(d: &mut D, e: &[A], f: &[B]) {
    diff_offsets(d, e, f, 0, 0);
pub fn diff<A, B: PartialEq<A>, D: Diff>(d: &mut D, e: &[A], f: &[B]) -> Result<(), D::Error> {
    diff_offsets(d, e, f, 0, 0)?;
    d.finish()
}

pub(crate) fn diff_offsets<D: Diff + ?Sized, A, B: PartialEq<A>>(
    diff: &mut D,
    e: &[A],
    f: &[B],
    i: usize,
    j: usize,
) {
) -> Result<(), D::Error> {
    let n = e.len();
    let m = f.len();
    let l = (n + m) as isize;
    let z = (2 * min(n, m) + 2) as usize;
    if n > 0 && m > 0 {
        let w = n as isize - m as isize;
        let mut g = vec![0; z as usize];
        let mut p = vec![0; z as usize];
        for h in 0..=(l / 2 + l % 2) {
            macro_rules! search {
                ($e: expr, $c: expr, $d: expr) => {
                    let (k0, k1) = {
                        let (m, n) = (m as isize, n as isize);
                        (-(h - 2*max(0, h - m)), h-2*max(0, h-n)+1)
                    };
                    for k in (k0..k1).step_by(2) {
                        let mut a: usize = if k == -h || k != h && $c[modulo(k-1, z)] < $c[modulo(k+1, z)] {
                            $c[modulo(k+1, z)]
                        } else {
                            $c[modulo(k-1, z)] + 1
                        };
                        let mut b = (a as isize - k) as usize;
                        let (s, t) = (a, b);
                        while a < n && b < m && {
                            let (e_i, f_i) = if $e { (a, b) } else { (n - a - 1, m - b - 1) };
                            f[f_i] == e[e_i]
                        } {
                            a += 1;
                            b += 1;
                        }
                        $c[modulo(k, z)] = a;
                        let bound = if $e { h-1 } else { h };
                        if (l%2 == 1) == $e
                            && w-k >= -bound && w-k <= bound
                            && $c[modulo(k, z)]+$d[modulo(w-k, z)] >= n
                        {
                            let (x, y, u, v) = if $e {
                                (s, t, a, b)
                            } else {
                                (n-a, m-b, n-s, m-t)
                            };
                            if h + bound > 1 || (x != u && y != v) {
                                diff_offsets(diff, &e[0..x], &f[0..y], i, j);
                                diff_offsets(diff, &e[0..x], &f[0..y], i, j)?;
                                if x != u {
                                    diff.equal(i + x, j + y, u-x);
                                    diff.equal(i + x, j + y, u-x)?;
                                }
                                diff_offsets(diff, &e[u..n], &f[v..m], i+u, j+v);
                                return
                                diff_offsets(diff, &e[u..n], &f[v..m], i+u, j+v)?;
                                return Ok(())
                            } else if m > n {
                                diff.equal(i, j, n);
                                diff.insert(i+n, j+n, m-n);
                                return
                                diff.equal(i, j, n)?;
                                diff.insert(i+n, j+n, m-n)?;
                                return Ok(())
                            } else if m < n {
                                diff.equal(i, j, m);
                                diff.delete(i+m, n-m);
                                return
                                diff.equal(i, j, m)?;
                                diff.delete(i+m, n-m)?;
                                return Ok(())
                            } else {
                                return
                                return Ok(())
                            }
                        }
                    }
                }
            }
            search!(true, g, p);
            search!(false, p, g);
        }
    } else if n > 0 {
        diff.delete(i, n)
        diff.delete(i, n)?
    } else if m > 0 {
        diff.insert(i, j, m)
        diff.insert(i, j, m)?
    }
    Ok(())
}
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

#[derive(Debug)]
struct I<'a, A: 'a> {
    p: &'a [A],
    i: usize,
}

#[cfg(test)]
impl<'a, A: std::fmt::Debug + 'a> std::fmt::Debug for I<'a, A> {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "{:?}", self.p[self.i])
    }
}

impl<'a, 'b, A: 'a, B: PartialEq<A> + 'b> PartialEq<I<'a, A>> for I<'b, B> {
    fn eq(&self, b: &I<'a, A>) -> bool {
        self.p[self.i] == b.p[b.i]
    }
}

fn unique<A: Hash + Eq>(p: &[A]) -> Vec<I<A>> {
    let mut aa = HashMap::new();
    for (i, a) in p.iter().enumerate() {
        match aa.entry(a) {
            Entry::Vacant(e) => {
                e.insert(Some(i));
            }
            Entry::Occupied(mut e) => {
                let e = e.get_mut();
                if e.is_some() {
                    *e = None
                }
            }
        }
    }
    let mut v: Vec<_> = aa
        .into_iter()
        .filter_map(|(_, x)| x)
        .map(|i| I { p, i })
        .collect();
    v.sort_by(|a, b| a.i.cmp(&b.i));
    v
}

/// Patience diff algorithm.
pub fn diff<
    A: Hash + Eq, // + std::fmt::Debug,
    B: Hash + Eq + PartialEq<A>, // + std::fmt::Debug,
    D: Diff,
>(
    d: &mut D,
    a: &[A],
    b: &[B],
) {
) -> Result<(), D::Error> {
    let au = unique(a);
    let bu = unique(b);

    struct Patience<'a, 'b, 'd, A: 'a, B: 'b, D: Diff + 'd> {
        current_a: usize,
        current_b: usize,
        a: &'a [A],
        b: &'b [B],
        d: &'d mut D,
        au: &'a [I<'a, A>],
        bu: &'b [I<'b, B>],
    }
    impl<
            'a,
            'b,
            'd,
            A: 'a, // + std::fmt::Debug,
            B: 'b + PartialEq<A>, // + std::fmt::Debug,
            D: Diff + 'd,
        > Diff for Patience<'a, 'b, 'd, A, B, D>
    {
        fn equal(&mut self, old: usize, new: usize, len: usize) {
        type Error = D::Error;
        fn equal(&mut self, old: usize, new: usize, len: usize) -> Result<(), D::Error> {
            // eprintln!("equal {:?} {:?} {:?}", old, new, len);
            for (old, new) in (old..old + len).zip(new..new + len) {
                let a0 = self.current_a;
                let b0 = self.current_b;
                while self.current_a < self.au[old].i
                    && self.current_b < self.bu[new].i
                    && self.b[self.current_b] == self.a[self.current_a]
                {
                    self.current_a += 1;
                    self.current_b += 1;
                }
                if self.current_a > a0 {
                    self.d.equal(a0, b0, self.current_a - a0)?
                }
                let a = &self.a[self.current_a..self.au[old].i];
                let b = &self.b[self.current_b..self.bu[new].i];
                myers::diff_offsets(self.d, a, b, self.current_a, self.current_b);
                // eprintln!("matching a: {:?} {:?}", self.current_a, self.au[old].i);
                // eprintln!("matching b: {:?} {:?}", self.current_b, self.bu[new].i);
                myers::diff_offsets(self.d, a, b, self.current_a, self.current_b)?;
                self.current_a = self.au[old].i;
                self.current_b = self.bu[new].i;
            }
            Ok(())
        }
        fn finish(&mut self) {
        /*
        fn insert(&mut self, old: usize, new: usize, len: usize) -> Result<(), D::Error> {
            eprintln!("insert {:?} {:?} {:?}", old, new, len);
            Ok(())
        }
        fn delete(&mut self, old: usize, len: usize) -> Result<(), D::Error> {
            eprintln!("delete {:?} {:?}", old, len);
            Ok(())
        }
        fn replace(
            &mut self,
            old: usize,
            len: usize,
            new: usize,
            new_len: usize,
        ) -> Result<(), D::Error> {
            eprintln!("replace {:?} {:?} {:?} {:?}", old, len, new, new_len);
            Ok(())
        }
        */
        fn finish(&mut self) -> Result<(), D::Error> {
            let a = &self.a[self.current_a..];
            let b = &self.b[self.current_b..];
            myers::diff_offsets(self.d, a, b, self.current_a, self.current_b);
            myers::diff_offsets(self.d, a, b, self.current_a, self.current_b)?;
            self.d.finish()
        }
    }
    let mut d = Replace::new(Patience {
        current_a: 0,
        current_b: 0,
        a,
        b,
        d,
        au: &au,
        bu: &bu,
    });
    myers::diff(&mut d, &au, &bu);
    myers::diff(&mut d, &au, &bu)?;
    Ok(())
}

#[test]
fn patience() {
    let a: &[usize] = &[11, 1, 2, 2, 3, 4, 4, 4, 5, 47, 19];
    let b: &[usize] = &[10, 1, 2, 2, 8, 9, 4, 4, 7, 47, 18];
    struct D {}
    impl Diff for D {
        fn equal(&mut self, o: usize, n: usize, len: usize) {
        type Error = ();
        fn equal(&mut self, o: usize, n: usize, len: usize) -> Result<(), ()> {
            println!("equal {:?} {:?} {:?}", o, n, len);
            Ok(())
        }
        fn delete(&mut self, o: usize, len: usize) {
        fn delete(&mut self, o: usize, len: usize) -> Result<(), ()> {
            println!("delete {:?} {:?}", o, len);
            Ok(())
        }
        fn insert(&mut self, o: usize, n: usize, len: usize) {
        fn insert(&mut self, o: usize, n: usize, len: usize) -> Result<(), ()> {
            println!("insert {:?} {:?} {:?}", o, n, len);
            Ok(())
        }
        fn replace(&mut self, o: usize, l: usize, n: usize, nl: usize) {
        fn replace(&mut self, o: usize, l: usize, n: usize, nl: usize) -> Result<(), ()> {
            println!("replace {:?} {:?} {:?} {:?}", o, l, n, nl);
            Ok(())
        }
    }
    let mut d = Replace::new(D {});
    diff(&mut d, a, b);
    diff(&mut d, a, b).unwrap();
}
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
    }
    pub fn into_inner(self) -> D {
        self.d
    }
}


impl<D:Diff> Diff for Replace<D> {
    fn equal(&mut self, old: usize, new: usize, len: usize) {
    type Error = D::Error;
    fn equal(&mut self, old: usize, new: usize, len: usize) -> Result<(), D::Error> {
        if let Some((old0, len0)) = self.del.take() {
            if let Some((_, new1, new_len1)) = self.ins.take() {
                self.d.replace(old0, len0, new1, new_len1)
                self.d.replace(old0, len0, new1, new_len1)?
            } else {
                self.d.delete(old0, len0);
                self.d.delete(old0, len0)?
            }
        } else if let Some((old0, new0, new_len0)) = self.ins.take() {
            self.d.insert(old0, new0, new_len0);
            self.d.insert(old0, new0, new_len0)?
        }

        if let Some((a, b, c)) = self.eq.take() {
            self.eq = Some((a, b, c + len))
        } else {
            self.eq = Some((old, new, len))
        }
        Ok(())
    }
    fn delete(&mut self, old: usize, len: usize) {
    fn delete(&mut self, old: usize, len: usize) -> Result<(), D::Error> {
        if let Some((a, b, c)) = self.eq.take() {
            self.d.equal(a, b, c)
            self.d.equal(a, b, c)?
        }
        if let Some((old0, len0)) = self.del.take() {
            assert_eq!(old, old0 + len0);
            self.del = Some((old0, len0+len))
        } else {
            self.del = Some((old, len))
        }
        Ok(())
    }

    fn insert(&mut self, old: usize, new: usize, new_len: usize) {
    fn insert(&mut self, old: usize, new: usize, new_len: usize) -> Result<(), D::Error> {
        if let Some((a, b, c)) = self.eq.take() {
            self.d.equal(a, b, c)
            self.d.equal(a, b, c)?
        }
        if let Some((old1, new1, new_len1)) = self.ins.take() {
            assert_eq!(new1+new_len1, new);
            self.ins = Some((old1, new1, new_len + new_len1))
        } else {
            self.ins = Some((old, new, new_len))
        }
        Ok(())
    }

    fn replace(&mut self, old: usize, old_len: usize, new: usize, new_len: usize) {
    fn replace(&mut self, old: usize, old_len: usize, new: usize, new_len: usize) -> Result<(), D::Error> {
        if let Some((a, b, c)) = self.eq.take() {
            self.d.equal(a, b, c)
            self.d.equal(a, b, c)?
        }
        self.d.replace(old, old_len, new, new_len)
    }

    fn finish(&mut self) {
    fn finish(&mut self) -> Result<(), D::Error> {
        if let Some((a, b, c)) = self.eq.take() {
            self.d.equal(a, b, c)?
        }
        if let Some((old0, len0)) = self.del.take() {
            if let Some((_, new1, new_len1)) = self.ins.take() {
                self.d.replace(old0, len0, new1, new_len1)
                self.d.replace(old0, len0, new1, new_len1)?
            } else {
                self.d.delete(old0, len0);
                self.d.delete(old0, len0)?
            }
        } else if let Some((old0, new0, new_len0)) = self.ins.take() {
            self.d.insert(old0, new0, new_len0);
            self.d.insert(old0, new0, new_len0)?
        }
        self.d.finish();
        self.d.finish()
    }
}

#[test]
fn myers() {
    use myers;
    let a: &[&str] = &[">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", "a\n", "b\n", "c\n",
                       "================================\n", "d\n", "e\n", "f\n",
                       "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n"];
    let b: &[&str] = &[">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", "x\n", "b\n", "c\n",
                       "================================\n", "y\n", "e\n", "f\n",
                       "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n"];

    struct D {}
    impl Diff for D {
        type Error = ();
        fn equal(&mut self, o: usize, n: usize, len: usize) -> Result<(), ()> {
            println!("equal {:?} {:?} {:?}", o, n, len);
            Ok(())
        }
        fn delete(&mut self, o: usize, len: usize) -> Result<(), ()> {
            println!("delete {:?} {:?}", o, len);
            Ok(())
        }
        fn insert(&mut self, o: usize, n: usize, len: usize) -> Result<(), ()> {
            println!("insert {:?} {:?} {:?}", o, n, len);
            Ok(())
        }
        fn replace(&mut self, o: usize, l: usize, n: usize, nl: usize) -> Result<(), ()> {
            println!("replace {:?} {:?} {:?} {:?}", o, l, n, nl);
            Ok(())
        }
    }
    let mut d = Replace::new(D {});
    myers::diff(&mut d, a, b).unwrap();
}
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
    struct D {}
    impl Diff for D {
        fn delete(&mut self, o: usize, len: usize) {
        type Error = ();
        fn delete(&mut self, o: usize, len: usize) -> Result<(), ()> {
            assert_eq!(o, 3);
            assert_eq!(len, 1);
            println!("delete");
            Ok(())
        }
        fn insert(&mut self, o: usize, n: usize, len: usize) {
            assert_eq!(o, 4);
        fn insert(&mut self, o: usize, n: usize, len: usize) -> Result<(), ()> {
            assert_eq!(o, 3);
            assert_eq!(n, 3);
            assert_eq!(len, 1);
            println!("insert");
            Ok(())
        }
    }
    let mut diff = Replace::new(D {});
    myers::diff(&mut diff, a, b)
    myers::diff(&mut diff, a, b).unwrap()
}

#[test]
fn test_contiguous() {
    let a: &[usize] = &[0,1,2,3,4,4,4,5];
    let b: &[usize] = &[0,1,2,8,9,4,4,7];
    struct D {}
    impl Diff for D {
        fn delete(&mut self, _o: usize, _len: usize) {
            panic!("Should not delete");
        type Error = ();
        fn delete(&mut self, _o: usize, _len: usize) -> Result<(), ()> {
            panic!("Should not delete")
        }
        fn insert(&mut self, _o: usize, _n: usize, _len: usize) {
            panic!("Should not insert");
        fn insert(&mut self, _o: usize, _n: usize, _len: usize) -> Result<(), ()> {
            panic!("Should not insert")
        }
        fn replace(&mut self, o: usize, l: usize, n: usize, nl: usize) {
        fn replace(&mut self, o: usize, l: usize, n: usize, nl: usize) -> Result<(), ()> {
            assert!(o != 3 || (l == 2 && nl == 2));
            assert!(o != 7 || (l == 1 && nl == 1));
            println!("replace {:?} {:?} {:?} {:?}", o, l, n, nl);
            Ok(())
        }
    }
    let mut diff = Replace::new(D{});
    myers::diff(&mut diff, a, b);
    myers::diff(&mut diff, a, b).unwrap();
}

#[test]
fn test_replace() {
    let a: &[usize] = &[0,1,2,3,4];
    let b: &[usize] = &[0,1,2,7,8,9];
    struct D {}
    impl Diff for D {
        fn delete(&mut self, _o: usize, _len: usize) {
        type Error = ();
        fn delete(&mut self, _o: usize, _len: usize) -> Result<(), ()> {
            panic!("should not delete")
        }
        fn insert(&mut self, _o: usize, _n: usize, _len: usize) {
        fn insert(&mut self, _o: usize, _n: usize, _len: usize) -> Result<(), ()> {
            panic!("should not insert")
        }
        fn replace(&mut self, _o: usize, _l: usize, _n: usize, _nl: usize) {
        fn replace(&mut self, _o: usize, _l: usize, _n: usize, _nl: usize) -> Result<(), ()> {
            Ok(())
        }
    }
    let mut diff = Replace::new(D{});
    myers::diff(&mut diff, a, b).unwrap();
}

#[test]
fn test_pat() {
    let a: &[usize] = &[0, 1, 3, 4, 5];
    let b: &[usize] = &[0, 1, 4, 5, 8, 9];
    struct D {}
    impl Diff for D {
        type Error = ();
        fn delete(&mut self, _o: usize, _len: usize) -> Result<(), ()> {
            println!("delete {:?} {:?}", _o, _len);
            Ok(())
        }
        fn insert(&mut self, _o: usize, _n: usize, _len: usize) -> Result<(), ()> {
            println!("insert {:?} {:?} {:?}", _o, _n, _len);
            Ok(())
        }
        fn replace(&mut self, _o: usize, _l: usize, _n: usize, _nl: usize) -> Result<(), ()> {
            println!("replace {:?} {:?} {:?} {:?}", _o, _l, _n, _nl);
            Ok(())
        }
    }
    let mut diff = Replace::new(D{});
    myers::diff(&mut diff, a, b);
    myers::diff(&mut diff, a, b).unwrap();
}


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
sanakirja = { path = "../../sanakirja" }
diffs = "0.2"[package]
name = "libpijul"
description = "A patch-based distributed version control system, easy to use and fast."
version = "0.11.1"
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/optimal_diff/add.rs",
  "src/optimal_diff/delete.rs",
  "src/optimal_diff/mod.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/output.rs",
  "src/conflict.rs",
  "src/file_operations.rs",
  "src/fs_representation.rs"
]

[dependencies]
bitflags = "1.0"
byteorder = "1.2"
flate2 = "1.0"
log = "0.4"
rand = "0.5"
sanakirja = "0.8.19"
sanakirja = "0.8.21"
chrono = { version = "0.4", features = [ "serde" ] }
serde = "1.0"
serde_derive = "1.0"
bincode = "1.0"
hex = "0.3"
tempdir = "0.3"
bs58 = "0.2"
base64 = "0.10"
ignore = "0.4"
serde_json = "1.0"
openssl = "0.10"
thrussh-keys = "0.11"
toml = "0.4"
diffs = "0.2.1"
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
use output;
use diff;

impl<U: Transaction, R> GenericTxn<U, R> {
    /// Return the patch id corresponding to `e`, or `internal` if `e==None`.
    pub fn internal_hash(&self, e: &Option<Hash>, internal: PatchId) -> PatchId {
        match *e {
            Some(Hash::None) => ROOT_PATCH_ID.clone(),
            Some(ref h) => self.get_internal(h.as_ref()).unwrap().to_owned(),
            None => internal.clone(),
        }
    }

    /// Fetch the internal key for this external key (or `internal` if
    /// `key.patch` is `None`).
    pub fn internal_key(&self, key: &Key<Option<Hash>>, internal: PatchId) -> Key<PatchId> {
        // debug!("internal_key: {:?} {:?}", key, internal);
        Key {
            patch: self.internal_hash(&key.patch, internal),
            line: key.line.clone(),
        }
    }

    pub fn internal_key_unwrap(&self, key: &Key<Option<Hash>>) -> Key<PatchId> {
        Key {
            patch: self.get_internal(key.patch.as_ref().unwrap().as_ref())
                .unwrap()
                .to_owned(),
            line: key.line.clone(),
        }
    }
}

impl<'env, T: rand::Rng> MutTxn<'env, T> {
    /// Assumes all patches have been downloaded. The third argument
    /// `remote_patches` needs to contain at least all the patches we
    /// want to apply, and the fourth one `local_patches` at least all
    /// the patches the other repository doesn't have.
    pub fn apply_patches<F, P: output::ToPrefixes>(
        &mut self,
        diff_algorithm: diff::Algorithm,
        branch: &mut Branch,
        r: &Path,
        remote_patches: &[(Hash, Patch)],
        partial_paths: P,
        mut f: F,
    ) -> Result<()>
    where
        F: FnMut(usize, &Hash),
    {
        let (pending, local_pending) = {
            let mut record = RecordState::new();
            self.record(&mut record, branch, &r, None)?;
            self.record(diff_algorithm, &mut record, branch, &r, None)?;
            let (changes, local) = record.finish();
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

impl<'env, T: rand::Rng> MutTxn<'env, T> {
    #[doc(hidden)]
    /// Deleted contexts are conflicts. Reconnect the graph by
    /// inserting pseudo-edges alongside deleted edges.
    pub fn repair_deleted_contexts(
    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
                    || v.flag | EdgeFlags::FOLDER_EDGE
                        != EdgeFlags::PARENT_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_parents.push(v.introduced_by)
                }
                debug!(
                    "parent is_unknown({}): {:?} {:?}",
                    line!(),
                    v,
                    unknown_parents
                );
            }

            if !unknown_parents.is_empty() {
                self.repair_missing_down_context(find_alive, branch, dest, alive, &unknown_parents)?
            }
        }
        Ok(())
    }

    /// Was `context` deleted by patches other than `patch_id`, and
    /// additionally not deleted by `patch_id`?
    fn was_context_deleted(
        &self,
        branch: &Branch,
        patch_id: PatchId,
        context: Key<PatchId>,
    ) -> bool {
        let mut context_deleted = false;
        for v in self.iter_adjacent(branch, context,
                                    EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE,
                                    EdgeFlags::all())
            .take_while(|v| {
                v.flag.contains(EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE)
            }) {
            debug!("was_context_deleted {:?}", v);
            if v.introduced_by == patch_id {
                return false;
            } else {
                context_deleted = true;
                context_deleted = true
            }
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
use backend::*;
use graph;
use graph::Graph;
use patch;
use patch::{Change, ChangeContext, Record};
use {GenericTxn, Result};

use conflict;
use diffs;
use rand;
use record::is_text;
use sanakirja::value::Value;
use std;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::rc::Rc;

#[derive(Debug, PartialEq, Eq, Hash)]
struct Line<'a>(&'a [u8]);

struct Contents<'a, T: Transaction + 'a> {
    key: Key<PatchId>,
    contents: Value<'a, T>,
}

impl<'a, T:Transaction+'a> std::fmt::Debug for Contents<'a, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{:?}", self.contents.into_cow())
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum Status {
    Begin,
    Next,
    End,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Algorithm {
    Myers,
    Patience,
}

impl Default for Algorithm {
    fn default() -> Self {
        Algorithm::Myers
    }
}

struct Diff<'a, 'b, T: Transaction + 'a> {
    conflicts_a: Vec<(usize, usize, bool)>,
    lines_a: Vec<Key<PatchId>>,
    contents_a: Vec<Contents<'a, T>>,
    lines_b: &'b [Line<'b>],
    conflict_starts: HashMap<usize, usize>,
    conflict_ends: HashMap<usize, usize>,
    conflict_down_contexts: HashMap<usize, Vec<LineId>>,
    status: HashMap<usize, Status>,
    conflict_stack: Vec<(usize, usize, bool)>,
    conflict_counter: usize,
    solved_conflicts: HashSet<usize>,
}

impl<'a, 'b, T: Transaction + 'a> graph::LineBuffer<'a, T> for Diff<'a, 'b, T> {
    fn output_line(&mut self, k: &Key<PatchId>, c: Value<'a, T>) -> Result<()> {
        if c.len() != 0 {
            self.conflicts_a.push(*self.conflict_stack.last().unwrap());
            self.lines_a.push(*k);
            self.contents_a.push(Contents {
                key: *k,
                contents: c,
            });
        }
        Ok(())
    }

    fn begin_conflict(&mut self) -> Result<()> {
        let len = self.contents_a.len();
        self.conflict_counter += 1;
        self.conflict_stack.push((self.conflict_counter, 0, false));
        self.conflict_starts.insert(self.conflict_counter, len);
        self.status.insert(len, Status::Begin);
        self.output_conflict_marker(conflict::START_MARKER)
    }

    fn begin_zombie_conflict(&mut self) -> Result<()> {
        let len = self.contents_a.len();
        self.conflict_counter += 1;
        self.conflict_stack.push((self.conflict_counter, 0, true));
        self.conflict_starts.insert(self.conflict_counter, len);
        self.status.insert(len, Status::Begin);
        self.output_conflict_marker(conflict::START_MARKER)
    }

    fn end_conflict(&mut self) -> Result<()> {
        let len = self.contents_a.len();
        self.output_conflict_marker(conflict::END_MARKER)?;
        self.status.insert(len, Status::End);
        let (conflict, _, _) = self.conflict_stack.pop().unwrap();
        self.conflict_ends.insert(conflict, len);
        Ok(())
    }

    fn conflict_next(&mut self) -> Result<()> {
        self.status.insert(self.contents_a.len(), Status::Next);
        if let Some((_, ref mut side, _)) = self.conflict_stack.last_mut() {
            *side += 1
        }
        self.output_conflict_marker(conflict::SEPARATOR)
    }

    fn output_conflict_marker(&mut self, marker: &'a str) -> Result<()> {
        let mut ends_with_newline = true;
        if self.contents_a.len() > 1 {
            for chunk in self.contents_a[self.contents_a.len() - 1].contents.clone() {
                debug!(
                    "chunk {:?} {:?}",
                    std::str::from_utf8(chunk),
                    chunk.ends_with(b"\n")
                );
                ends_with_newline = chunk.ends_with(b"\n")
            }
        };
        debug!("ends_with_newline {:?}", ends_with_newline);
        let (conflict, _, is_zombie) = *self.conflict_stack.last().unwrap();
        self.conflicts_a.push((conflict, 0, is_zombie));
        if ends_with_newline {
            self.lines_a.push(ROOT_KEY);
            self.contents_a.push(Contents {
                key: ROOT_KEY,
                contents: Value::from_slice(&marker.as_bytes()[1..]),
            })
        } else {
            self.lines_a.push(ROOT_KEY);
            self.contents_a.push(Contents {
                key: ROOT_KEY,
                contents: Value::from_slice(marker.as_bytes()),
            });
        }
        Ok(())
    }
}

impl<'a, 'b, T: Transaction + 'b> PartialEq<Contents<'b, T>> for Line<'a> {
    fn eq(&self, b: &Contents<T>) -> bool {
        // debug!("EQ {:?} {:?}", self, b.contents);
        let result = if b.contents.len() as usize == self.0.len() {
            self.0.eq(&b.contents)
        } else if self.0.last() == Some(&0xa) {
            if b.key.is_root() {
                let b = b.contents.into_cow();
                if b[0] == 0xa {
                    (&self.0[..]).eq(&b[1..])
                } else {
                    (&self.0[..]).eq(&b[..])
                }
            } else {
                (&self.0[..self.0.len() - 1]).eq(&b.contents)
            }
        } else {
            false
        };
        // debug!("result = {:?}", result);
        result
    }
}

impl<'b, T: Transaction + 'b> PartialEq<Contents<'b, T>> for Contents<'b, T> {
    fn eq(&self, b: &Contents<T>) -> bool {
        self.contents == b.contents
    }
}
impl<'b, T: Transaction + 'b> Eq for Contents<'b, T> {}
impl<'b, T: Transaction + 'b> std::hash::Hash for Contents<'b, T> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.contents.hash(state)
    }
}

struct Replace {
    old: usize,
    old_len: usize,
    new: usize,
    new_len: usize,
}
struct D {
    r: Vec<Replace>,
    deleted: HashMap<usize, bool>,
}
impl diffs::Diff for D {
    type Error = ();
    fn delete(&mut self, old: usize, old_len: usize) -> std::result::Result<(), ()>{
        for i in old..old + old_len {
            self.deleted.insert(i, false);
        }
        self.r.push(Replace {
            old,
            old_len,
            new: 0,
            new_len: 0,
        });
        Ok(())
    }
    fn insert(&mut self, old: usize, new: usize, new_len: usize) -> std::result::Result<(), ()>{
        self.r.push(Replace {
            old,
            old_len: 0,
            new,
            new_len,
        });
        Ok(())
    }
    fn replace(&mut self, old: usize, old_len: usize, new: usize, new_len: usize) -> std::result::Result<(), ()>{
        for i in old..old + old_len {
            self.deleted.insert(i, true);
        }
        self.r.push(Replace {
            old,
            old_len,
            new,
            new_len,
        });
        Ok(())
    }
}

struct DiffProducer<'a> {
    line_num: &'a mut LineId,
    inode: Key<Option<Hash>>,
    inode_internal: Key<Option<PatchId>>,
    file: Rc<PathBuf>,
    conflict_insertions: HashMap<usize, LineId>,
}

impl<A: Transaction, R: rand::Rng> GenericTxn<A, R> {
    pub fn diff<'a>(
        &'a self,
        algorithm: Algorithm,
        inode: Key<Option<Hash>>,
        branch: &'a Branch,
        file: Rc<PathBuf>,
        line_num: &mut LineId,
        actions: &mut Vec<Record<ChangeContext<PatchId>>>,
        redundant: &mut Vec<(Key<PatchId>, Edge)>,
        a: &mut Graph,
        lines_b: &[u8],
    ) -> Result<()> {
        // First outputting A
        let inode_internal = Key {
            patch: Some(
                self.get_internal(inode.patch.as_ref().unwrap().as_ref())
                    .unwrap(),
            ),
            line: inode.line,
        };
        let mut lines_b_ = Vec::new();
        let mut d = Diff {
            lines_a: Vec::with_capacity(2 * lines_b.len()),
            contents_a: Vec::with_capacity(2 * lines_b.len()),
            conflicts_a: Vec::with_capacity(2 * lines_b.len()),
            lines_b: &[],
            conflict_starts: HashMap::new(),
            conflict_ends: HashMap::new(),
            conflict_down_contexts: HashMap::new(),
            status: HashMap::new(),
            conflict_counter: 0,
            conflict_stack: vec![(0, 0, false)],
            solved_conflicts: HashSet::new(),
        };
        self.output_file(branch, &mut d, a, redundant)?;

        // Now cutting B
        if is_text(&lines_b) {
            let mut i = 0;
            let mut j = 0;

            while j < lines_b.len() {
                if lines_b[j] == 0xa {
                    lines_b_.push(Line(&lines_b[i..j + 1]));
                    i = j + 1
                }
                j += 1;
            }
            if i < j {
                lines_b_.push(Line(&lines_b[i..]))
            }
        } else {
            lines_b_.push(Line(&lines_b[..]))
        };
        d.lines_b = &lines_b_;

        // And finally diffing
        let contents_a = std::mem::replace(&mut d.contents_a, Vec::new());
        debug!(
            "contents_a {:?}",
            contents_a.iter().map(|x| &x.contents).collect::<Vec<_>>()
        );
        debug!("contents_b {:?}", lines_b_);
        let mut dd = diffs::Replace::new(D {
            r: Vec::with_capacity(d.lines_a.len() + lines_b_.len()),
            deleted: HashMap::new(),
        });
        match algorithm {
            Algorithm::Patience => diffs::patience::diff(&mut dd, contents_a.as_slice(), &lines_b_).unwrap(),
            Algorithm::Myers => diffs::myers::diff(&mut dd, contents_a.as_slice(), &lines_b_).unwrap(),
        }
        let dd = dd.into_inner();
        let mut diffprod = DiffProducer {
            line_num,
            inode,
            inode_internal,
            file,
            conflict_insertions: HashMap::new(),
        };
        for r in 0..dd.r.len() {
            if dd.r[r].new_len == 0 {
                let old = dd.r[r].old;
                let len = dd.r[r].old_len;
                self.diff_delete(branch, &mut diffprod, actions, &mut d, old, len)
            } else {
                self.diff_replace(branch, &mut diffprod, actions, &mut d, &dd, r)
            }
        }
        debug!("Diff ended");
        Ok(())
    }

    /// Insert epsilon-edges if we're deleting conflict markers.
    fn order_conflict_sides(
        &self,
        branch: &Branch,
        dp: &mut DiffProducer,
        actions: &mut Vec<Record<ChangeContext<PatchId>>>,
        diff: &mut Diff<A>,
        old: usize,
        len: usize,
    ) {
        if diff.lines_a[old..old + len].iter().any(|x| x.is_root())
            && !diff.lines_a[old - 1].is_root()
            && !diff.lines_a[old + len].is_root()
            && !self.is_connected(branch, diff.lines_a[old - 1], diff.lines_a[old + len])
        {
            let from_patch = diff.lines_a[old - 1];
            let to_patch = diff.lines_a[old + len];
            debug!("Conflict reordering");
            actions.push(Record::Change {
                change: Change::NewNodes {
                    up_context: vec![Key {
                        patch: Some(from_patch.patch),
                        line: from_patch.line,
                    }],
                    down_context: vec![Key {
                        patch: Some(to_patch.patch),
                        line: to_patch.line,
                    }],
                    line_num: *dp.line_num,
                    flag: EdgeFlags::EPSILON_EDGE,
                    nodes: vec![Vec::new()],
                    inode: dp.inode.clone(),
                },
                file: dp.file.clone(),
            });
            *dp.line_num += 1
        }
    }

    /// Actually delete the lines that need to be deleted.
    fn delete_lines(
        &self,
        branch: &Branch,
        dp: &mut DiffProducer,
        actions: &mut Vec<Record<ChangeContext<PatchId>>>,
        diff: &mut Diff<A>,
        old: usize,
        len: usize,
    ) {
        let mut edges = Vec::new();
        let flag0 = EdgeFlags::PARENT_EDGE;
        let flag1 = EdgeFlags::PARENT_EDGE | EdgeFlags::PSEUDO_EDGE | EdgeFlags::EPSILON_EDGE;

        for (i, &key) in diff.lines_a[old..(old + len)].iter().enumerate() {
            match diff.status.get(&(old + i)) {
                Some(&Status::Begin) => {
                    diff.solved_conflicts.insert(diff.conflicts_a[old + i].0);
                    continue;
                }
                None => {}
                _ => continue,
            }
            let ext_hash = self.external_hash(key.patch);
            for v in self
                .iter_adjacent(&branch, key, flag0, flag1)
                .filter(|v| !v.flag.contains(EdgeFlags::EPSILON_EDGE))
            {
                if v.flag.contains(EdgeFlags::PSEUDO_EDGE) {
                    let mut edge = v.clone();
                    edge.flag = EdgeFlags::DELETED_EDGE | EdgeFlags::PARENT_EDGE;
                    edge.introduced_by = ROOT_PATCH_ID;
                    let mut edges = self.iter_nodes(&branch, Some((key, Some(edge))));
                    match edges.next() {
                        Some((k_, v_)) if k_ == key && v_.flag == edge.flag => {
                            // `key` has at least one deleted edge
                            // pointing to it, so key is a zombie. We
                            // need to confirm that it is actually
                            // deleted by deleting edge `v`.
                            debug!("zombie edge: {:?} {:?}", key, v);
                        }
                        x => {
                            // The target of this edge is not deleted,
                            // and not a zombie vertex.  We can ignore
                            // this pseudo-edge, as deleting all alive
                            // edges to the target will have the same
                            // effect.
                            debug!("not a zombie: {:?}", x);
                            continue;
                        }
                    }
                };
                debug!("delete: {:?} {:?}", key, v);
                debug!("actually deleting");
                edges.push(patch::NewEdge {
                    from: Key {
                        patch: Some(ext_hash.to_owned()),
                        line: key.line.clone(),
                    },
                    to: Key {
                        patch: Some(self.external_hash(v.dest.patch).to_owned()),
                        line: v.dest.line.clone(),
                    },
                    introduced_by: Some(self.external_hash(v.introduced_by).to_owned()),
                });
            }
        }

        if !edges.is_empty() {
            actions.push(Record::Change {
                change: Change::NewEdges {
                    edges,
                    previous: EdgeFlags::PARENT_EDGE,
                    flag: EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE,
                    inode: dp.inode.clone(),
                },
                file: dp.file.clone(),
            })
        }

    }

    fn resurrect_zombies(
        &self,
        branch: &Branch,
        dp: &mut DiffProducer,
        actions: &mut Vec<Record<ChangeContext<PatchId>>>,
        diff: &mut Diff<A>,
        old: usize,
        len: usize,
    ) {
        // If the conflict markers of zombie lines have been deleted,
        // resurect the zombies.
        let mut i = old + len;
        let mut resurrections = Vec::new();
        let mut dead_parents = Vec::new();
        while i < diff.lines_a.len() {
            let key = diff.lines_a[i];
            let (conflict, _, is_zombie) = diff.conflicts_a[i];
            debug!("resurrecting {:?} {:?}", key, is_zombie);
            debug!("solved ? {:?} {:?}", conflict, diff.solved_conflicts);
            if is_zombie && !key.is_root() && diff.solved_conflicts.contains(&conflict) {
                // Resurect the zombie, i.e. remove its deleted edges.
                let flag0 = EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE;
                let ext_hash = self.external_hash(key.patch);
                for v in self.iter_adjacent(&branch, key, flag0, flag0) {
                    debug!("resurrecting {:?}: {:?}", key, v);
                    let v_hash = self.external_hash(v.dest.patch).to_owned();
                    resurrections.push(patch::NewEdge {
                        from: Key {
                            patch: Some(ext_hash.to_owned()),
                            line: key.line.clone(),
                        },
                        to: Key {
                            patch: Some(v_hash.clone()),
                            line: v.dest.line.clone(),
                        },
                        introduced_by: Some(self.external_hash(v.introduced_by).to_owned()),
                    });
                    // We must re-kill the parents to make sure they
                    // don't get context-fixed when we apply this
                    // patch.
                    for w in self.iter_adjacent(&branch, v.dest, flag0, flag0) {
                        dead_parents.push(patch::NewEdge {
                            from: Key {
                                patch: Some(v_hash.clone()),
                                line: v.dest.line.clone(),
                            },
                            to: Key {
                                patch: Some(self.external_hash(w.dest.patch).to_owned()),
                                line: w.dest.line.clone(),
                            },
                            introduced_by: Some(self.external_hash(w.introduced_by).to_owned()),
                        })
                    }
                }
                i += 1
            } else {
                break;
            }
        }
        if !resurrections.is_empty() {
            actions.push(Record::Change {
                change: Change::NewEdges {
                    edges: resurrections,
                    previous: EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE,
                    flag: EdgeFlags::PARENT_EDGE,
                    inode: dp.inode.clone(),
                },
                file: dp.file.clone(),
            });
            actions.push(Record::Change {
                change: Change::NewEdges {
                    edges: dead_parents,
                    previous: EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE,
                    flag: EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE,
                    inode: dp.inode.clone(),
                },
                file: dp.file.clone(),
            });
        }
    }

    fn diff_delete(
        &self,
        branch: &Branch,
        dp: &mut DiffProducer,
        actions: &mut Vec<Record<ChangeContext<PatchId>>>,
        diff: &mut Diff<A>,
        old: usize,
        len: usize,
    ) {
        debug!("delete {:?} {:?}", old, len);
        if old > 0 && old + len < diff.lines_a.len() {
            self.order_conflict_sides(branch, dp, actions, diff, old, len)
        }

        self.delete_lines(branch, dp, actions, diff, old, len);
        self.resurrect_zombies(branch, dp, actions, diff, old, len);
    }

    fn get_up_context(
        &self,
        dp: &mut DiffProducer,
        diff: &mut Diff<A>,
        old: usize,
    ) -> Vec<Key<Option<PatchId>>> {
        if old == 0 {
            vec![dp.inode_internal]
        } else {
            let mut up_context_idx = old - 1;
            loop {
                debug!("up_context_idx = {:?}", up_context_idx);
                match diff.status.get(&up_context_idx) {
                    None => {
                        break vec![Key {
                            patch: Some(diff.lines_a[up_context_idx].patch),
                            line: diff.lines_a[up_context_idx].line,
                        }]
                    }
                    Some(&Status::Begin) => {
                        let conflict = diff.conflicts_a[up_context_idx].0;
                        if let Some(&line) = dp.conflict_insertions.get(&conflict) {
                            break vec![Key { patch: None, line }];
                        } else if up_context_idx == 0 {
                            break vec![dp.inode_internal];
                        } else {
                            up_context_idx -= 1
                        }
                    }
                    Some(&Status::Next) => {
                        let conflict = diff.conflicts_a[up_context_idx].0;
                        if let Some(&line) = dp.conflict_insertions.get(&conflict) {
                            break vec![Key { patch: None, line }];
                        } else {
                            let conflict = diff.conflicts_a[up_context_idx].0;
                            up_context_idx = *diff.conflict_starts.get(&conflict).unwrap();
                        }
                    }
                    Some(&Status::End) => {
                        // The up context is all the sides above this end marker
                        let conflict = diff.conflicts_a[up_context_idx].0;
                        let conflict_start = *diff.conflict_starts.get(&conflict).unwrap();
                        let mut up_context = Vec::new();

                        if let Some(ref up) = diff.conflict_down_contexts.get(&up_context_idx) {
                            up_context.extend(up.iter().map(|&x| Key {
                                patch: None,
                                line: x,
                            }));
                        }

                        let mut on = true;
                        while up_context_idx > conflict_start {
                            on |= diff.status.get(&up_context_idx).is_some()
                                && diff.conflicts_a[up_context_idx].0 == conflict;
                            if on && diff.status.get(&up_context_idx).is_none() {
                                // This is a real line, add it
                                up_context.push(Key {
                                    patch: Some(diff.lines_a[up_context_idx].patch),
                                    line: diff.lines_a[up_context_idx].line,
                                });
                                on = false
                            }
                            up_context_idx -= 1
                        }
                        assert!(!up_context.is_empty());
                        break up_context;
                    }
                }
            }
        }
    }

    fn get_down_context(
        &self,
        dp: &mut DiffProducer,
        diff: &mut Diff<A>,
        dd: &D,
        old: usize,
        old_len: usize,
        len: usize,
    ) -> Vec<Key<Option<PatchId>>> {
        let mut down_context_idx = old + old_len;
        loop {
            debug!("down_context_idx = {:?}", down_context_idx);
            if down_context_idx >= diff.lines_a.len() {
                break Vec::new();
            }
            match diff.status.get(&down_context_idx) {
                None => {
                    break vec![Key {
                        patch: Some(diff.lines_a[down_context_idx].patch),
                        line: diff.lines_a[down_context_idx].line,
                    }]
                }
                Some(&Status::End) => {
                    let mut e = diff
                        .conflict_down_contexts
                        .entry(down_context_idx)
                        .or_insert(Vec::new());
                    e.push(*dp.line_num + (len - 1));
                    down_context_idx += 1
                }
                Some(&Status::Next) => {
                    let conflict = diff.conflicts_a[down_context_idx].0;
                    down_context_idx = *diff.conflict_ends.get(&conflict).unwrap();
                }
                Some(&Status::Begin) => {
                    // The down context is all the sides below this beginning marker
                    let conflict = diff.conflicts_a[down_context_idx].0;
                    dp.conflict_insertions
                        .insert(conflict, *dp.line_num + (len - 1));
                    let conflict_end = *diff.conflict_ends.get(&conflict).unwrap();
                    let mut down_context = Vec::new();
                    let mut on = true;
                    while down_context_idx < conflict_end {
                        on |= diff.status.get(&down_context_idx).is_some()
                            && diff.conflicts_a[down_context_idx].0 == conflict;
                        if on && diff.status.get(&down_context_idx).is_none() {
                            match dd.deleted.get(&down_context_idx) {
                                Some(true) => {
                                    // If the down context line has
                                    // been replaced, we'll insert the
                                    // edge later (when dealing with
                                    // the replacement).
                                    on = false
                                }
                                Some(false) => {
                                    // If the line has been
                                    // deleted, wait for the next
                                    // appropriate down context
                                    // line.
                                }
                                None => {
                                    // If the down context has not
                                    // been deleted, just add it
                                    // as a down context.
                                    down_context.push(Key {
                                        patch: Some(diff.lines_a[down_context_idx].patch),
                                        line: diff.lines_a[down_context_idx].line,
                                    });
                                    on = false
                                }
                            }
                        }
                        down_context_idx += 1
                    }
                    assert!(!down_context.is_empty());
                    break down_context;
                }
            }
        }
    }

    fn diff_replace(
        &self,
        branch: &Branch,
        dp: &mut DiffProducer,
        actions: &mut Vec<Record<ChangeContext<PatchId>>>,
        diff: &mut Diff<A>,
        dd: &D,
        r: usize,
    ) {
        let old = dd.r[r].old;
        let old_len = dd.r[r].old_len;
        let from_new = dd.r[r].new;
        let len = dd.r[r].new_len;
        debug!("replace {:?} {:?} {:?} {:?}", old, old_len, from_new, len);
        if old_len > 0 {
            self.diff_delete(branch, dp, actions, diff, old, old_len)
        }
        // Inserting between old and old+1. Both might be conflict
        // markers.
        let up_context = self.get_up_context(dp, diff, old);
        let down_context = self.get_down_context(dp, diff, dd, old, old_len, len);
        let change = Change::NewNodes {
            up_context,
            down_context,
            line_num: *dp.line_num,
            flag: EdgeFlags::empty(),
            nodes: (&diff.lines_b[from_new..(from_new + len)])
                .iter()
                .map(|x| x.0.to_vec())
                .collect(),
            inode: dp.inode.clone(),
        };
        *dp.line_num += len;
        debug!("insert done");
        actions.push(Record::Change {
            file: dp.file.clone(),
            change,
        });
    }
}


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
        self.begin_conflict()
            buf.end_conflict()?;
//! 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 Result;
use backend::*;
use conflict;
use std::cmp::min;
use std::collections::{HashMap, HashSet};

use rand;
use std;

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.output_conflict_marker(conflict::START_MARKER_ZOMB)
    }
    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)
    }
    fn end_zombie_conflict(&mut self) -> Result<()> {
        self.output_conflict_marker(conflict::END_MARKER_ZOMB)
    }
}

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.write(s.as_bytes())?;
        } else {
            self.write(&s.as_bytes()[1..])?;
        }
        Ok(())
    }
}

#[derive(Clone, Debug)]
pub struct Visits {
    pub first: usize,
    pub last: usize,
    /// Does this vertex have incomparable children?
    pub begins_conflict: Option<usize>,
    /// Does this vertex have incoming cross-edges?
    pub ends_conflict: bool,
    /// Has the line been output? (for the second DFS, in
    /// conflict_tree)
    pub output: bool,
}

impl Default for Visits {
    fn default() -> Self {
        Visits {
            first: 0,
            last: 0,
            begins_conflict: None,
            ends_conflict: false,
            output: false,
        }
    }
}

pub struct DFS {
    visits: Vec<Visits>,
    counter: usize,
    has_conflicts: bool,
}

impl DFS {
    pub fn new(n: usize) -> Self {
        DFS {
            visits: vec![Visits::default(); n],
            counter: 1,
            has_conflicts: false,
        }
    }
}

impl DFS {
    fn mark_discovered(&mut self, scc: usize) {
        if self.visits[scc].first == 0 {
            self.visits[scc].first = self.counter;
            self.counter += 1;
        }
    }

    fn mark_last_visit(&mut self, scc: usize) {
        self.mark_discovered(scc);
        self.visits[scc].last = self.counter;
        self.counter += 1;
    }

    fn first_visit(&self, scc: usize) -> usize {
        self.visits[scc].first
    }

    fn last_visit(&self, scc: usize) -> usize {
        self.visits[scc].last
    }
}

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];
                debug!("tarjan: {:?}", l.key);
                (*l).index = index;
                (*l).lowlink = index;
                (*l).flags = (*l).flags | Flags::LINE_ONSTACK | Flags::LINE_VISITED;
                debug!("{:?} {:?} 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
    }

    /// Run a depth-first search on this graph, assigning the
    /// `first_visit` and `last_visit` numbers to each node.
    fn dfs<A: Transaction, R>(
        &mut self,
        txn: &GenericTxn<A, R>,
        branch: &Branch,
        scc: &[Vec<VertexId>],
        dfs: &mut DFS,
        forward: &mut Vec<(Key<PatchId>, Edge)>,
    ) {
        let mut call_stack: Vec<(_, HashSet<usize>, _)> = Vec::with_capacity(scc.len());
        call_stack.push((scc.len() - 1, HashSet::new(), None));

        let mut conflict_stack: Vec<(usize, usize)> = Vec::new();
        debug!("dfs starting");
        while let Some((n_scc, mut forward_scc, descendants)) = call_stack.pop() {
            debug!("dfs, n_scc = {:?}", n_scc);
            for &VertexId(id) in scc[n_scc].iter() {
                debug!("dfs, n_scc: {:?}", self.lines[id].key);
            }
            dfs.mark_discovered(n_scc);
            debug!(
                "scc: {:?}, first {} last {}",
                n_scc,
                dfs.first_visit(n_scc),
                dfs.last_visit(n_scc)
            );
            let is_first_visit = descendants.is_none();
            let mut descendants = if let Some(descendants) = descendants {
                descendants
            } else {
                // First visit / discovery of SCC n_scc.

                // After Tarjan's algorithm, the SCC numbers are in reverse
                // topological order.
                //
                // Here, we want to visit the first child in topological
                // order, hence the one with the largest SCC number first.
                //

                // Collect all descendants of this SCC, in order of increasing
                // SCC.
                let mut descendants = Vec::new();
                for cousin in scc[n_scc].iter() {
                    for &(e, n_child) in self.children(*cousin) {
                        let is_ok = match e {
                            Some(e) if e.flag.contains(EdgeFlags::FOLDER_EDGE) => false,
                            _ => true
                        };
                        if is_ok {
                            let child_component = self[n_child].scc;
                            if child_component < n_scc {
                                // If this is a child and not a sibling.
                                descendants.push(child_component)
                            }
                        }
                    }
                }
                descendants.sort();
                debug!("sorted descendants: {:?}", descendants);
                descendants
            };

            // SCCs to which we have forward edges.
            let mut recursive_call = None;
            while let Some(child) = descendants.pop() {
                debug!(
                    "child {:?}, first {} last {}",
                    child,
                    dfs.first_visit(child),
                    dfs.last_visit(child)
                );

                if dfs.first_visit(child) == 0 {
                    // SCC `child` has not yet been visited, visit it.

                    // If this is not our first visit to SCC `n_scc`,
                    // mark it as the beginning of a conflict.
                    if !is_first_visit {
                        debug!("{:?}: begins conflict", n_scc);
                        dfs.has_conflicts = true;
                        dfs.visits[n_scc].begins_conflict = Some(n_scc);
                        if let Some((scc, end)) = conflict_stack.pop() {
                            conflict_stack.push((scc, end));
                            if scc != n_scc {
                                conflict_stack.push((n_scc, n_scc));
                            }
                        } else {
                            conflict_stack.push((n_scc, n_scc));
                        }
                    }
                    recursive_call = Some(child);
                    break;
                } else if dfs.first_visit(n_scc) < dfs.first_visit(child) {
                    // This is a forward edge.
                    debug!("last_visit to {:?}: {:?}", child, dfs.last_visit(child));
                    forward_scc.insert(child);
                } else {
                    // cross edge
                    debug!(
                        "cross edge, stack: {:?}, updating with {:?}",
                        conflict_stack, child
                    );
                    for c in conflict_stack.iter_mut() {
                        c.1 = std::cmp::min(c.1, child);
                    }
                    dfs.visits[child].ends_conflict = true
                }
            }
            if let Some(child) = recursive_call {
                call_stack.push((n_scc, forward_scc, Some(descendants)));
                call_stack.push((child, HashSet::new(), None));
            } else {
                dfs.mark_last_visit(n_scc);
                if dfs.visits[n_scc].begins_conflict.is_some() {
                    let (begin, end) = conflict_stack.pop().unwrap();
                    assert_eq!(begin, n_scc);
                    debug!("begins_conflict {:?}: {:?}", n_scc, end);
                    dfs.visits[n_scc].begins_conflict = Some(end);
                }

                // After this, collect forward edges. Look at all
                // children of this SCC.
                for cousin in scc[n_scc].iter() {
                    for &(edge, n_child) in self.children(*cousin) {
                        if let Some(mut edge) = edge {
                            // Is this edge a forward edge of the DAG?
                            if forward_scc.contains(&self[n_child].scc)
                                && edge.flag.contains(EdgeFlags::PSEUDO_EDGE)
                                && !txn.test_edge(
                                    branch,
                                    self[*cousin].key,
                                    edge.dest,
                                    EdgeFlags::DELETED_EDGE,
                                    EdgeFlags::DELETED_EDGE,
                                ) {
                                debug!("forward: {:?} {:?}", self[*cousin].key, edge);
                                forward.push((self[*cousin].key, edge))
                            } else {
                                // Does this edge have parallel PSEUDO edges? If so, they may not be "forward", but they are redundant.
                                edge.flag = EdgeFlags::PSEUDO_EDGE;
                                edge.introduced_by = ROOT_PATCH_ID;
                                let mut edges = txn
                                    .iter_nodes(branch, Some((self[*cousin].key, Some(edge))))
                                    .take_while(|&(k, v)| {
                                        k == self[*cousin].key
                                            && v.dest == edge.dest
                                            && v.flag
                                                <= EdgeFlags::FOLDER_EDGE | EdgeFlags::PSEUDO_EDGE
                                    });
                                edges.next(); // ignore the first pseudo-edge.
                                forward.extend(edges.map(|(k, v)| (k, v))); // add all parallel edges.
                            }
                        }
                    }
                }
            }
        }
    }
}

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))));
            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))));
                        if let Some((_, v)) = nodes.next() {
                            // We know the key is `key`.
                            is_zombie = v.flag | EdgeFlags::FOLDER_EDGE
                                == first_edge.flag | EdgeFlags::FOLDER_EDGE
                        }
                    } else {
                        is_zombie = true
                    }
                }
            }
            debug!("is_zombie: {:?}", is_zombie);
            let mut l = Line {
                key: key.clone(),
                flags: if is_zombie {
                    Flags::LINE_HALF_DELETED
                } else {
                    Flags::empty()
                },
                children: graph.children.len(),
                n_children: 0,
                index: 0,
                lowlink: 0,
                scc: 0,
            };

            let mut last_flag = EdgeFlags::empty();
            let mut last_dest = ROOT_KEY;

            for (_, v) in self
                .iter_nodes(&branch, Some((key, None)))
                .take_while(|&(k, v)| {
                    k == key
                        && v.flag
                            <= EdgeFlags::PSEUDO_EDGE
                                | EdgeFlags::FOLDER_EDGE
                                | EdgeFlags::EPSILON_EDGE
                }) {
                debug!("-> v = {:?}", v);
                if last_flag == EdgeFlags::PSEUDO_EDGE && last_dest == v.dest {
                    // This is a doubled edge, it should be removed.
                } else {
                    graph.children.push((Some(v.clone()), DUMMY_VERTEX));
                    l.n_children += 1;
                    if !cache.contains_key(&v.dest) {
                        stack.push(v.dest.clone())
                    } else {
                        debug!("v already visited");
                    }
                    last_flag = v.flag;
                    last_dest = v.dest;
                }
            }
            // If this key has no children, give it the dummy child.
            if l.n_children == 0 {
                debug!("no children for {:?}", l);
                graph.children.push((None, DUMMY_VERTEX));
                l.n_children = 1;
            }
            graph.lines.push(l)
        }
        for &mut (ref child_key, ref mut child_idx) in graph.children.iter_mut() {
            if let Some(ref child_key) = *child_key {
                if let Some(idx) = cache.get(&child_key.dest) {
                    *child_idx = *idx
                }
            }
        }
        graph
    }
}

/// The conflict markers keep track of the number of conflicts, and is
/// used for outputting conflicts to a given LineBuffer.
///
/// "Zombie" conflicts are those conflicts introduced by zombie
/// vertices in the contained Graph.
struct ConflictMarkers<'b> {
    current_is_zombie: bool,
struct ConflictMarkers {
    current_conflicts: usize,
    graph: &'b Graph,
}

impl<'b> ConflictMarkers<'b> {
impl ConflictMarkers {
    /*
    fn output_zombie_markers_if_needed<'a, A: Transaction + 'a, B: LineBuffer<'a, A>>(
        &mut self,
        buf: &mut B,
        vertex: VertexId,
    ) -> Result<()> {
        if self.graph[vertex].is_zombie() {
            if !self.current_is_zombie {
                debug!("begin zombie conflict: vertex = {:?}", self.graph[vertex]);
                self.current_is_zombie = true;
                buf.begin_conflict()?;
                buf.begin_zombie_conflict()?;
            }
        } else if self.current_is_zombie {
            // Zombie segment has ended
            if !self.current_is_zombie {
                debug!("end zombie conflict: vertex = {:?}", self.graph[vertex]);
            }
            buf.end_zombie_conflict()?;
            self.current_is_zombie = false;
        }
        Ok(())
    }

    */
    fn begin_conflict<'a, A: Transaction + 'a, B: LineBuffer<'a, A>>(
        &mut self,
        buf: &mut B,
    ) -> Result<()> {
        self.current_conflicts += 1;
        buf.begin_conflict()?;
        Ok(())
    }
    fn end_conflict<'a, A: Transaction + 'a, B: LineBuffer<'a, A>>(
        &mut self,
        buf: &mut B,
    ) -> Result<()> {
        if self.current_conflicts > 0 {
            buf.end_conflict()?;
            self.current_conflicts -= 1;
        }
        Ok(())
    }
}

/// In the case of nested conflicts, a single conflict sometimes needs
/// to be treated like a line.
#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum ConflictLine {
    Conflict(Vec<Vec<ConflictLine>>),
    Line(usize),
}

#[derive(Debug)]
struct Side {
    next: usize,
    side: Vec<ConflictLine>,
}

#[derive(Debug)]
enum State {
    Init {
        resume_conflict: bool,
    },
    EvalConflict {
        start: usize,
        end: usize,
        cur: usize,
        last_visit: usize,
        sides: Vec<Side>,
    },
}

impl<'a, A: Transaction + 'a, R> GenericTxn<A, R> {
    fn output_conflict<B: LineBuffer<'a, A>>(
        &'a self,
        conflicts: &mut ConflictMarkers,
        buf: &mut B,
        graph: &Graph,
        scc: &[Vec<VertexId>],
        conflict: &mut [Vec<ConflictLine>],
    ) -> Result<()> {
        let mut is_first = true;
        let n_sides = conflict.len();
        debug!(target:"libpijul::graph::output_conflict", "n_sides = {:?}", n_sides);
        if n_sides > 1 {
            conflicts.begin_conflict(buf)?;
        }
        conflict.sort();
        for side in conflict {
            if !is_first {
                buf.conflict_next()?;
            }
            is_first = false;
            debug!(target:"libpijul::graph::output_conflict", "side = {:?}", side);
            for i in side {
                match *i {
                    ConflictLine::Line(i) => self.output_scc(conflicts, graph, &scc[i], buf)?,
                    ConflictLine::Line(i) => self.output_scc(graph, &scc[i], buf)?,
                    ConflictLine::Conflict(ref mut c) => {
                        debug!(target:"libpijul::graph::output_conflict", "begin conflict {:?}", c);
                        self.output_conflict(conflicts, buf, graph, scc, c)?;
                        debug!(target:"libpijul::graph::output_conflict", "end conflict");
                    }
                }
            }
        }
        if n_sides > 1 {
            conflicts.end_conflict(buf)?;
        }
        Ok(())
    }

    /// Output the database contents of the file into the buffer
    /// `buf`. The return value indicates whether there are any
    /// conflicts in the file that was output. If forward edges are
    /// encountered, they are collected into `forward`.
    ///
    pub fn output_file<B: LineBuffer<'a, A>>(
        &'a self,
        branch: &Branch,
        buf: &mut B,
        graph: &mut Graph,
        forward: &mut Vec<(Key<PatchId>, Edge)>,
    ) -> Result<bool> {
        debug!("output_file");
        if graph.lines.len() <= 1 {
            return Ok(false);
        }
        let scc = graph.tarjan(); // SCCs are given here in reverse order.
        debug!("There are {} SCC", scc.len());
        debug!("SCCs = {:?}", scc);

        let mut dfs = DFS::new(scc.len());
        graph.dfs(self, branch, &scc, &mut dfs, forward);

        debug!("dfs done");
        buf.output_line(&graph.lines[1].key, Value::from_slice(b""))?;
        let conflict_tree = conflict_tree(graph, &scc, &mut dfs);
        debug!("conflict_tree = {:?}", conflict_tree);
        let mut conflicts = ConflictMarkers {
            current_is_zombie: false,
            current_conflicts: 0,
            graph: &graph,
        };
        self.output_conflict(&mut conflicts, buf, graph, &scc, &mut [conflict_tree])?;
        // Close any remaining zombie part (if needed).
        conflicts.output_zombie_markers_if_needed(buf, DUMMY_VERTEX)?;
        // conflicts.output_zombie_markers_if_needed(buf, DUMMY_VERTEX)?;
        debug!("/output_file");
        Ok(dfs.has_conflicts)
    }

    fn output_scc<B: LineBuffer<'a, A>>(
        &'a self,
        conflicts: &mut ConflictMarkers,
        // conflicts: &mut ConflictMarkers,
        graph: &Graph,
        scc: &[VertexId],
        buf: &mut B,
    ) -> Result<()> {
        assert_eq!(scc.len(), 1);
        conflicts.output_zombie_markers_if_needed(buf, scc[0])?;
        // conflicts.output_zombie_markers_if_needed(buf, scc[0])?;
        if graph[scc[0]].is_zombie() {
            buf.begin_zombie_conflict()?;
        }
        let key = graph[scc[0]].key;
        if let Some(cont) = self.get_contents(key) {
            debug!(target:"libpijul::graph::output_conflict", "outputting {:?}", cont);
            buf.output_line(&key, cont)?;
        }
        if graph[scc[0]].is_zombie() {
            buf.end_zombie_conflict()?;
        }
        Ok(())
    }
}

fn conflict_tree(graph: &Graph, scc: &[Vec<VertexId>], dfs: &mut DFS) -> Vec<ConflictLine> {
    debug!(target: "tree", "scc = {:?}", scc);
    let mut call_stack = Vec::with_capacity(scc.len());
    call_stack.push((
        scc.len() - 1,
        State::EvalConflict {
            start: scc.len() - 1,
            end: 0,
            cur: 1,
            last_visit: 0,
            sides: vec![Side {
                next: scc.len() - 1,
                side: vec![],
            }],
        },
    ));
    debug!(target: "tree", "conflict tree starting");

    while let Some((i, state)) = call_stack.pop() {
        debug!(target: "tree", "{:?} ({:?}): {:?}, {:?}", i, scc[i], graph[scc[i][0]].key, dfs.visits[i]);
        debug!(target: "tree", "{:?} {:?}", call_stack, state);
        debug!(target: "tree", "stack: {:?}", call_stack);
        debug!(target: "tree", "state: {:?}", state);
        match state {
            State::Init { resume_conflict } => {
                debug!(target:"tree", "new visit to {:?}", graph[scc[i][0]].key);
                dfs.visits[i].output = true;
                if dfs.visits[i].ends_conflict && !resume_conflict {
                    debug!(target: "tree", "ends conflict");
                    if let Some((
                        _,
                        State::EvalConflict {
                            ref mut sides,
                            ref mut cur,
                            ..
                        },
                    )) = call_stack.last_mut()
                    {
                        sides[*cur].next = i
                    }
                } else {
                    if let Some((
                        _,
                        State::EvalConflict {
                            ref cur,
                            ref mut sides,
                            ..
                        },
                    )) = call_stack.last_mut()
                    {
                        sides[*cur].side.push(ConflictLine::Line(i))
                    }
                    }
                    if let Some(c) = dfs.visits[i].begins_conflict {
                        if let Some((
                            _,
                            State::EvalConflict {
                                ref cur,
                                ref mut sides,
                                ..
                            },
                        )) = call_stack.last_mut()
                        {
                            sides[*cur].next = c;
                            sides[*cur].side.push(ConflictLine::Line(i))
                        }
                        debug!(target: "tree", "BEGINS CONFLICT {:?}", c);
                        let mut sides = Vec::new();
                        for cousin in scc[i].iter() {
                            for &(e, n_child) in graph.children(*cousin) {
                                debug!("cousin: {:?}", graph[n_child].scc);
                                let is_ok = match e {
                                    Some(e) if e.flag.contains(EdgeFlags::FOLDER_EDGE) => false,
                                    _ => true
                                };
                                if is_ok {
                                    let next = graph[n_child].scc;
                                    sides.push(Side {
                                        next,
                                        side: Vec::new(),
                                    })
                                }
                            }
                        }
                        sides.sort_by(|a, b| a.next.cmp(&b.next));
                        debug!(target: "tree", "sides: {:?}", sides);
                        let cur = sides.len();
                        call_stack.push((
                            i,
                            State::EvalConflict {
                                sides,
                                start: i,
                                end: c,
                                last_visit: 0,
                                cur,
                            },
                        ));
                    } else {
                        if let Some((
                            _,
                            State::EvalConflict {
                                ref cur,
                                ref mut sides,
                                ..
                            },
                        )) = call_stack.last_mut()
                        {
                            sides[*cur].side.push(ConflictLine::Line(i))
                        }
                        let mut max_scc = None;
                        for cousin in scc[i].iter() {
                            for &(e, n_child) in graph.children(*cousin) {
                                let is_ok = match e {
                                    Some(e) if e.flag.contains(EdgeFlags::FOLDER_EDGE) => false,
                                    _ => true
                                };
                                if is_ok {
                                    let next = graph[n_child].scc;
                                    max_scc = std::cmp::max(max_scc, Some(next))
                                }
                            }
                        }
                        debug!(target: "tree", "max_scc = {:?}", max_scc);
                        if let Some(max_scc) = max_scc {
                            call_stack.push((
                                max_scc,
                                State::Init {
                                    resume_conflict: false,
                                },
                            ))
                        }
                    }
                }
            }
            State::EvalConflict {
                start,
                end,
                mut cur,
                last_visit,
                mut sides,
            } => {
                debug!("EvalConflict");
                if cur > 0 {
                    // Recurse
                    // Recurse, i.e. visit the next unvisited
                    // component of this conflict.
                    let next = sides[cur - 1].next;
                    let visit_next = dfs.visits[next].first > last_visit;
                    call_stack.push((
                        i,
                        State::EvalConflict {
                            start,
                            end,
                            cur: cur - 1,
                            last_visit: if visit_next {
                                dfs.visits[next].last
                            } else {
                                last_visit
                            },
                            sides,
                        },
                    ));
                    if visit_next {
                        call_stack.push((
                            next,
                            State::Init {
                                resume_conflict: dfs.visits[next].ends_conflict,
                            },
                        ));
                    }
                } else if call_stack.is_empty() {
                    // We're done, return.
                    assert_eq!(sides.len(), 1);
                    let side = sides.pop().unwrap();
                    assert!(sides.is_empty());
                    return side.side;
                } else {
                    sides.sort_by(|a, b| a.next.cmp(&b.next));
                    // This conflict is over if all its sides have the same `next`.
                    let conflict_is_over = {
                        let next = sides.iter().filter(|x| !x.side.is_empty()).next().unwrap().next;
                        sides.iter().all(|x| x.side.is_empty() || x.next == next)
                    };
                    debug!("Conflict_is_over: {:?}", conflict_is_over);
                    if conflict_is_over {
                        // The conflict is over.
                        let current = sides
                        let mut current: Vec<_> = sides
                            .into_iter()
                            .filter_map(|x| {
                                if x.side.is_empty() {
                                    None
                                } else {
                                    Some(x.side)
                                }
                            }).collect();
                        if let Some((
                            _,
                            State::EvalConflict {
                                ref cur,
                                ref mut sides,
                                ..
                            },
                        )) = call_stack.last_mut()
                        {
                            sides[*cur].side.push(ConflictLine::Conflict(current));
                            if current.len() >= 2 {
                                sides[*cur].side.push(ConflictLine::Conflict(current));
                            } else if let Some(current) = current.pop() {
                                sides[*cur].side.extend(current.into_iter())
                            }
                        }
                        call_stack.push((
                            end,
                            State::Init {
                                resume_conflict: true,
                            },
                        ));
                    } else {
                        let mut sides_ = Vec::new();
                        let mut next = sides[0].next;
                        let mut current = Vec::new();
                        debug!(target:"tree", "sides {:?}", sides);
                        for side in sides.into_iter().filter(|x| !x.side.is_empty()) {
                            debug!(target:"tree", "side {:?}", side);
                            if side.next != next {
                                let cur = std::mem::replace(&mut current, Vec::new());
                                if !cur.is_empty() {
                                let mut cur = std::mem::replace(&mut current, Vec::new());
                                if cur.len() >= 2 {
                                    sides_.push(Side {
                                        next,
                                        side: vec![ConflictLine::Conflict(cur)],
                                    });
                                } else if let Some(side) = cur.pop() {
                                    sides_.push(Side {
                                        next,
                                        side,
                                    })
                                }
                                next = side.next;
                            }
                            current.push(side.side);
                        }
                        if !current.is_empty() {
                        if current.len() >= 2 {
                            sides_.push(Side {
                                next,
                                side: vec![ConflictLine::Conflict(current)],
                            });
                        } else if let Some(side) = current.pop() {
                            sides_.push(Side {
                                next,
                                side,
                            })
                        }
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
extern crate toml;
extern crate diffs;

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),
    Keys(thrussh_keys::Error),
    Base58Decode(bs58::decode::DecodeError),
    AlreadyAdded,
    FileNotInRepo(PathBuf),
    NoDb(backend::Root),
    WrongHash,
    EOF,
    WrongPatchSignature,
    BranchNameAlreadyExists(String),
    WrongFileHeader(Key<PatchId>),
    FileNameCount(Key<PatchId>),
}

impl std::convert::From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Error::IO(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<thrussh_keys::Error> for Error {
    fn from(e: thrussh_keys::Error) -> Self {
        Error::Keys(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::Keys(ref e) => e.fmt(fmt),
            Error::Base58Decode(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),
        }
    }
}

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::Keys(ref e) => e.description(),
            Error::Base58Decode(ref e) => e.description(),
            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",
        }
    }
}

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 apply;
mod conflict;
pub mod graph;
mod optimal_diff;
mod diff;
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::ID_LENGTH;
pub use output::{Prefixes, ToPrefixes};
pub use patch::{Patch, PatchHeader};
use rand::Rng;
use rand::distributions::Alphanumeric;
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, path: P) -> Result<()> {
        let changes_file =
            fs_representation::branch_changes_file(path.as_ref(), 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: P, is_dir: bool) -> Result<()> {
        self.add_inode(None, path.as_ref(), 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.is_root();
        let e = Edge::zero(EdgeFlags::PARENT_EDGE);
        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)))) {
            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() {
            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_adjacent(branch, key, EdgeFlags::PARENT_EDGE, EdgeFlags::all())
                    {
                        debug!("get_file {:?}", v);
                        if v.flag | EdgeFlags::PSEUDO_EDGE
                            == EdgeFlags::PARENT_EDGE | EdgeFlags::PSEUDO_EDGE
                        {
                            debug!("push!");
                            stack.push(v.dest.clone())
                        } else if v.flag
                            .contains(EdgeFlags::PARENT_EDGE | EdgeFlags::FOLDER_EDGE)
                        {
                            names.push(key);
                        }
                    }
                }
                _ => {}
            }
        }
        debug!("get_file returning {:?}", names);
        names
    }

    pub fn get_file_names<'a>(
        &'a self,
        branch: &Branch,
        key: Key<PatchId>,
    ) -> Vec<(Key<PatchId>, Vec<&'a str>)> {
        let mut names = vec![(key, Vec::new())];
        debug!("inode: {:?}", names);
        // Go back to the root.
        let mut next_names = Vec::new();
        let mut only_roots = false;
        let mut inodes = HashSet::new();
        while !only_roots {
            next_names.clear();
            only_roots = true;
            for (inode, names) in names.drain(..) {
                if !inodes.contains(&inode) {
                    inodes.insert(inode.clone());

                    if inode != ROOT_KEY {
                        only_roots = false;
                    }
                    let names_ = self.file_names(branch, inode);
                    if names_.is_empty() {
                        next_names.push((inode, names));
                        break;
                    } else {
                        debug!("names_ = {:?}", names_);
                        for (inode_, _, base) in names_ {
                            let mut names = names.clone();
                            names.push(base);
                            next_names.push((inode_, names))
                        }
                    }
                }
            }
            std::mem::swap(&mut names, &mut next_names)
        }
        debug!("end: {:?}", names);
        for &mut (_, ref mut name) in names.iter_mut() {
            name.reverse()
        }
        names
    }
}

fn make_remote<'a, I: Iterator<Item = &'a Hash>>(
    target: &Path,
    remote: I,
) -> Result<(Vec<(Hash, Patch)>, usize)> {
    use fs_representation::*;
    use std::fs::File;
    use std::io::BufReader;
    let mut patches = Vec::new();
    let mut patches_dir = patches_dir(target).to_path_buf();
    let mut size_increase = 0;

    for h in remote {
        patches_dir.push(&patch_file_name(h.as_ref()));

        debug!("opening {:?}", patches_dir);
        let file = try!(File::open(&patches_dir));
        let mut file = BufReader::new(file);
        let (h, _, patch) = Patch::from_reader_compressed(&mut file)?;

        size_increase += patch.size_upper_bound();
        patches.push((h.clone(), patch));

        patches_dir.pop();
    }
    Ok((patches, size_increase))
}

/// Apply a number of patches, guessing the new repository size.  If
/// this fails, the repository size is guaranteed to have been
/// increased by at least some pages, and it is safe to call this
/// function again.
///
/// Also, this function takes a file lock on the repository.
pub fn apply_resize<'a, I, F, P: output::ToPrefixes>(
    diff_algorithm: diff::Algorithm,
    target: &Path,
    branch_name: &str,
    remote: I,
    partial_paths: P,
    apply_cb: F,
) -> Result<()>
where
    I: Iterator<Item = &'a Hash>,
    F: FnMut(usize, &Hash),
{
    let (patches, size_increase) = make_remote(target, remote)?;
    apply_resize_patches(
        diff_algorithm,
        target,
        branch_name,
        &patches,
        size_increase,
        partial_paths,
        apply_cb,
    )
}

/// A version of `apply_resize` with the patches list already loaded.
pub fn apply_resize_patches<'a, F, P: output::ToPrefixes>(
    diff_algorithm: diff::Algorithm,
    target: &Path,
    branch_name: &str,
    patches: &[(Hash, Patch)],
    size_increase: usize,
    partial_paths: P,
    apply_cb: F,
) -> Result<()>
where
    F: FnMut(usize, &Hash),
{
    use fs_representation::*;
    info!("applying patches with size_increase {:?}", size_increase);
    let pristine_dir = pristine_dir(target).to_path_buf();
    let repo = Repository::open(pristine_dir, Some(size_increase as u64))?;
    let mut txn = repo.mut_txn_begin(rand::thread_rng())?;
    let mut branch = txn.open_branch(branch_name)?;
    txn.apply_patches(&mut branch, target, &patches, partial_paths, apply_cb)?;
    txn.apply_patches(diff_algorithm, &mut branch, target, &patches, partial_paths, apply_cb)?;
    txn.commit_branch(branch)?;
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
        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> {
    rec: Option<R>,
    extra: Option<C>,
    reord: 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),
            reord: None,
            extra: None,
        }
    }
}

impl<Context> Record<Context> {
    pub fn iter(&self) -> RecordIter<&Record<Context>, &Change<Context>> {
        RecordIter {
            rec: Some(self),
            reord: None,
            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() {
        if let Some(extra) = self.reord.take() {
            Some(extra)
        } else 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, .. } => {
                    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);
                    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)
                }
            }
        } 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 {
                                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 {
                        }).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();
                        })).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(),
                        }).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<&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,
                    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)?;
        }
        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, Clone, 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()?;
        let hash = bs58::decode(&signatures.hash).into_vec()?;
        if !k.verify_detached(&hash, &sig) {
            return Err(Error::WrongPatchSignature);
        }
    }
    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>(Option<
    serde_json::StreamDeserializer<'a, serde_json::de::IoRead<R>, SignatureFile>,
    serde_json::StreamDeserializer<'a, serde_json::de::IoRead<R>, SignatureFile>,
>);
pub struct Signatures<'a, R: Read>(
    Option<serde_json::StreamDeserializer<'a, serde_json::de::IoRead<R>, SignatureFile>>,
);

pub fn read_signatures<'a, R: Read>(r: R) -> Signatures<'a, R> {
    Signatures(Some(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> {
        if let Some(mut s) = self.0.take() {
            match s.next() {
                Some(Ok(result)) => {
                    self.0 = Some(s);
                    Some(Ok(result))
                }
                Some(Err(e)) => Some(Err(e.into())),
                None => None
                None => None,
            }
        } else {
            None
        }
    }
}

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

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()
                });
                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)))
                    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()
            }).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())
        for edge in self
            .iter_adjacent(branch, k, EdgeFlags::empty(), EdgeFlags::all())
            .filter(|e_| !e_.flag.contains(EdgeFlags::PARENT_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
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
use backend::*;
use graph;
use optimal_diff;
use patch::*;
use {Error, Result};

use diff;
use rand;
use std;
use std::cell::RefCell;
use std::collections::HashSet;
use std::fs::metadata;
use std::io::BufRead;
use std::io::Read;
#[cfg(not(windows))]
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::rc::Rc;

#[cfg(not(windows))]
fn permissions(attr: &std::fs::Metadata) -> Option<usize> {
    Some(attr.permissions().mode() as usize)
}
#[cfg(windows)]
fn permissions(_: &std::fs::Metadata) -> Option<usize> {
    None
}

fn file_metadata(path: &Path) -> Result<FileMetadata> {
    let attr = metadata(&path)?;
    let permissions = permissions(&attr).unwrap_or(0o755);
    debug!("permissions = {:?}", permissions);
    Ok(FileMetadata::new(permissions & 0o777, attr.is_dir()))
}

impl<U: Transaction, R> GenericTxn<U, R> {
    pub fn globalize_change(
        &self,
        change: Change<Rc<RefCell<ChangeContext<PatchId>>>>,
        change: Change<ChangeContext<PatchId>>,
    ) -> Change<ChangeContext<Hash>> {
        match change {
            Change::NewNodes {
                up_context,
                down_context,
                flag,
                line_num,
                nodes,
                inode,
            } => Change::NewNodes {
                up_context: Rc::try_unwrap(up_context)
                    .unwrap()
                    .into_inner()
                up_context: up_context
                    .iter()
                    .map(|&k| self.external_key_opt(k))
                    .collect(),
                down_context: Rc::try_unwrap(down_context)
                    .unwrap()
                    .into_inner()
                down_context: down_context
                    .iter()
                    .map(|&k| self.external_key_opt(k))
                    .collect(),
                flag,
                line_num,
                nodes,
                inode,
            },
            Change::NewEdges {
                previous,
                flag,
                edges,
                inode,
            } => Change::NewEdges {
                previous,
                flag,
                edges,
                inode,
            },
        }
    }
    pub fn globalize_record(
        &self,
        change: Record<Rc<RefCell<ChangeContext<PatchId>>>>,
        change: Record<ChangeContext<PatchId>>,
    ) -> Record<ChangeContext<Hash>> {
        match change {
            Record::FileMove { new_name, del, add } => Record::FileMove {
                new_name,
                del: self.globalize_change(del),
                add: self.globalize_change(add),
            },
            Record::FileDel { name, del } => Record::FileDel {
                name,
                del: self.globalize_change(del),
            },
            Record::FileAdd { name, add } => Record::FileAdd {
                name,
                add: self.globalize_change(add),
            },
            Record::Change {
            Record::Change { file, change } => Record::Change {
                file,
                change,
                conflict_reordering,
            } => Record::Change {
                file,
                change: self.globalize_change(change),
                conflict_reordering: conflict_reordering
                    .into_iter()
                    .map(|x| self.globalize_change(x))
                    .collect(),
            },
            Record::Replace {
            Record::Replace { file, adds, dels } => Record::Replace {
                file,
                adds,
                dels,
                conflict_reordering,
            } => Record::Replace {
                file,
                adds: self.globalize_change(adds),
                dels: self.globalize_change(dels),
                conflict_reordering: conflict_reordering
                    .into_iter()
                    .map(|x| self.globalize_change(x))
                    .collect(),
            },
        }
    }
}

pub struct RecordState {
    line_num: LineId,
    updatables: HashSet<InodeUpdate>,
    actions: Vec<Record<ChangeContext<PatchId>>>,
    redundant: Vec<(Key<PatchId>, Edge)>,
}

/// An account of the files that have been added, moved or deleted, as
/// returned by record, and used by apply (when applying a patch
/// created locally) to update the trees and inodes databases.
#[derive(Debug, Hash, PartialEq, Eq)]
pub enum InodeUpdate {
    Add {
        /// `LineId` in the new patch.
        line: LineId,
        /// `FileMetadata` in the updated file.
        meta: FileMetadata,
        /// `Inode` added by this file addition.
        inode: Inode,
    },
    Moved {
        /// `Inode` of the moved file.
        inode: Inode,
    },
    Deleted {
        /// `Inode` of the deleted file.
        inode: Inode,
    },
}

#[derive(Debug)]
pub enum WorkingFileStatus {
    Moved {
        from: FileMetadata,
        to: FileMetadata,
    },
    Deleted,
    Ok,
    Zombie,
}

fn is_text(x: &[u8]) -> bool {
pub(crate) fn is_text(x: &[u8]) -> bool {
    x.iter().take(8000).all(|&c| c != 0)
}

impl<'env, R: rand::Rng> MutTxn<'env, R> {
    /// Create appropriate NewNodes for adding a file.
    fn record_file_addition(
        &self,
        st: &mut RecordState,
        current_inode: Inode,
        parent_node: Key<Option<PatchId>>,
        realpath: &mut std::path::PathBuf,
        basename: &str,
    ) -> Result<Option<LineId>> {
        let name_line_num = st.line_num.clone();
        let blank_line_num = st.line_num + 1;
        st.line_num += 2;

        debug!("metadata for {:?}", realpath);
        let meta = match file_metadata(&realpath) {
            Ok(metadata) => metadata,
            Err(e) => return Err(e),
        };

        let mut name = Vec::with_capacity(basename.len() + 2);
        name.write_metadata(meta).unwrap(); // 2 bytes.
        name.extend(basename.as_bytes());

        let mut nodes = Vec::new();

        st.updatables.insert(InodeUpdate::Add {
            line: blank_line_num.clone(),
            meta: meta,
            inode: current_inode.clone(),
        });
        let up_context_ext = Key {
            patch: if parent_node.line.is_root() {
                Some(Hash::None)
            } else if let Some(patch_id) = parent_node.patch {
                Some(self.external_hash(patch_id).to_owned())
            } else {
                None
            },
            line: parent_node.line.clone(),
        };
        let up_context = Key {
            patch: if parent_node.line.is_root() {
                Some(ROOT_PATCH_ID)
            } else if let Some(patch_id) = parent_node.patch {
                Some(patch_id)
            } else {
                None
            },
            line: parent_node.line.clone(),
        };
        st.actions.push(Record::FileAdd {
            name: realpath.to_string_lossy().to_string(),
            add: Change::NewNodes {
                up_context: Rc::new(RefCell::new(vec![up_context])),
                up_context: vec![up_context],
                line_num: name_line_num,
                down_context: Rc::new(RefCell::new(vec![])),
                down_context: vec![],
                nodes: vec![name, vec![]],
                flag: EdgeFlags::FOLDER_EDGE,
                inode: up_context_ext.clone(),
            },
        });
        // Reading the file
        if !meta.is_dir() {
            nodes.clear();

            let mut node = Vec::new();
            {
                let mut f = std::fs::File::open(realpath.as_path())?;
                f.read_to_end(&mut node)?;
            }

            let up_context = Key {
                patch: None,
                line: blank_line_num.clone(),
            };
            let up_context_ext = Key {
                patch: None,
                line: blank_line_num.clone(),
            };
            if is_text(&node) {
                let mut line = Vec::new();
                let mut f = &node[..];
                loop {
                    match f.read_until('\n' as u8, &mut line) {
                        Ok(l) => {
                            if l > 0 {
                                nodes.push(line.clone());
                                line.clear()
                            } else {
                                break;
                            }
                        }
                        Err(_) => break,
                    }
                }
                let len = nodes.len();
                if !nodes.is_empty() {
                    st.actions.push(Record::Change {
                        change: Change::NewNodes {
                            up_context: Rc::new(RefCell::new(vec![up_context])),
                            up_context: vec![up_context],
                            line_num: st.line_num,
                            down_context: Rc::new(RefCell::new(vec![])),
                            down_context: vec![],
                            nodes: nodes,
                            flag: EdgeFlags::empty(),
                            inode: up_context_ext,
                        },
                        file: Rc::new(realpath.clone()),
                        conflict_reordering: Vec::new(),
                    });
                }
                st.line_num += len;
            } else {
                st.actions.push(Record::Change {
                    change: Change::NewNodes {
                        up_context: Rc::new(RefCell::new(vec![up_context])),
                        up_context: vec![up_context],
                        line_num: st.line_num,
                        down_context: Rc::new(RefCell::new(vec![])),
                        down_context: vec![],
                        nodes: vec![node],
                        flag: EdgeFlags::empty(),
                        inode: up_context_ext,
                    },
                    file: Rc::new(realpath.clone()),
                    conflict_reordering: Vec::new(),
                });
                st.line_num += 1;
            }
            Ok(None)
        } else {
            Ok(Some(blank_line_num))
        }
    }

    /// Diff for binary files, doesn't both splitting the file in
    /// lines. This is wasteful, but doesn't break the format, and
    /// doesn't create conflicts inside binary files.
    fn diff_with_binary(
        &self,
        algorithm: diff::Algorithm,
        inode: Key<Option<Hash>>,
        branch: &Branch,
        st: &mut RecordState,
        ret: &mut graph::Graph,
        path: Rc<PathBuf>,
    ) -> Result<()> {
        let mut lines_b = Vec::new();
        {
            debug!("opening file for diff: {:?}", path);
            let mut f = std::fs::File::open(path.as_ref())?;
            f.read_to_end(&mut lines_b)?;
        }
        let lines = if is_text(&lines_b) {
            optimal_diff::read_lines(&lines_b)
        } else {
            vec![&lines_b[..]]
        };

        self.diff(
            algorithm,
            inode,
            branch,
            path,
            &mut st.line_num,
            &mut st.actions,
            &mut st.redundant,
            ret,
            &lines,
            &lines_b,
        )
    }

    fn record_moved_file(
        &self,
        diff_algorithm: diff::Algorithm,
        branch: &Branch,
        realpath: &mut std::path::PathBuf,
        st: &mut RecordState,
        parent_node: Key<Option<PatchId>>,
        current_node: Key<PatchId>,
        basename: &str,
        new_meta: FileMetadata,
        old_meta: FileMetadata,
    ) -> Result<()> {
        debug!("record_moved_file: parent_node={:?}", parent_node);
        // Delete all former names.
        let mut edges = Vec::new();
        // Now take all grandparents of l2, delete them.

        let mut name = Vec::with_capacity(basename.len() + 2);
        name.write_metadata(new_meta).unwrap();
        name.extend(basename.as_bytes());
        for parent in self.iter_parents(branch, current_node, EdgeFlags::FOLDER_EDGE) {
            debug!("iter_parents: {:?}", parent);
            let previous_name: &[u8] = match self.get_contents(parent.dest) {
                None => &[],
                Some(n) => n.as_slice(),
            };
            let name_changed =
                (&previous_name[2..] != &name[2..]) || (new_meta != old_meta && cfg!(not(windows)));

            for grandparent in self.iter_parents(branch, parent.dest, EdgeFlags::FOLDER_EDGE) {
                debug!("iter_parents: grandparent = {:?}", grandparent);
                let grandparent_changed = if let Some(ref parent_node_patch) = parent_node.patch {
                    *parent_node_patch != grandparent.dest.patch
                        || parent_node.line != grandparent.dest.line
                } else {
                    true
                };
                if grandparent_changed || name_changed {
                    edges.push(NewEdge {
                        from: Key {
                            line: parent.dest.line.clone(),
                            patch: Some(self.external_hash(parent.dest.patch).to_owned()),
                        },
                        to: Key {
                            line: grandparent.dest.line.clone(),
                            patch: Some(self.external_hash(grandparent.dest.patch).to_owned()),
                        },
                        introduced_by: Some(
                            self.external_hash(grandparent.introduced_by).to_owned(),
                        ),
                    })
                }
            }
        }
        debug!("edges:{:?}", edges);
        let up_context_ext = Key {
            patch: if parent_node.line.is_root() {
                Some(Hash::None)
            } else if let Some(parent_patch) = parent_node.patch {
                Some(self.external_hash(parent_patch).to_owned())
            } else {
                None
            },
            line: parent_node.line.clone(),
        };
        let up_context = Key {
            patch: if parent_node.line.is_root() {
                Some(ROOT_PATCH_ID)
            } else if let Some(parent_patch) = parent_node.patch {
                Some(parent_patch)
            } else {
                None
            },
            line: parent_node.line.clone(),
        };
        if !edges.is_empty() {
            // If this file's name or meta info has changed.
            st.actions.push(Record::FileMove {
                new_name: realpath.to_string_lossy().to_string(),
                del: Change::NewEdges {
                    edges: edges,
                    previous: EdgeFlags::FOLDER_EDGE | EdgeFlags::PARENT_EDGE,
                    flag: EdgeFlags::DELETED_EDGE | EdgeFlags::FOLDER_EDGE | EdgeFlags::PARENT_EDGE,
                    inode: up_context_ext.clone(),
                },
                add: Change::NewNodes {
                    up_context: Rc::new(RefCell::new(vec![up_context])),
                    up_context: vec![up_context],
                    line_num: st.line_num,
                    down_context: Rc::new(RefCell::new(vec![
                        Key {
                            patch: Some(current_node.patch),
                            line: current_node.line.clone(),
                        },
                    ])),
                    down_context: vec![Key {
                        patch: Some(current_node.patch),
                        line: current_node.line.clone(),
                    }],
                    nodes: vec![name],
                    flag: EdgeFlags::FOLDER_EDGE,
                    inode: up_context_ext.clone(),
                },
            });
            st.line_num += 1;
        }
        if !old_meta.is_dir() {
            info!("retrieving");
            let mut ret = self.retrieve(branch, current_node);
            debug!("diff");
            let patch_ext = self.get_external(current_node.patch).unwrap();
            self.diff_with_binary(
                diff_algorithm,
                Key {
                    patch: Some(patch_ext.to_owned()),
                    line: current_node.line,
                },
                branch,
                st,
                &mut ret,
                Rc::new(realpath.clone()),
            )?;
        };
        Ok(())
    }

    fn record_deleted_file(
        &self,
        st: &mut RecordState,
        branch: &Branch,
        realpath: &Path,
        current_node: Key<PatchId>,
    ) -> Result<()> {
        debug!("record_deleted_file");
        let mut edges = Vec::new();
        let mut previous = EdgeFlags::FOLDER_EDGE | EdgeFlags::PARENT_EDGE;
        // Now take all grandparents of the current node, delete them.
        for parent in self.iter_parents(branch, current_node, EdgeFlags::FOLDER_EDGE) {
            for grandparent in self.iter_parents(branch, parent.dest, EdgeFlags::FOLDER_EDGE) {
                edges.push(NewEdge {
                    from: self.external_key(&parent.dest).unwrap(),
                    to: self.external_key(&grandparent.dest).unwrap(),
                    introduced_by: Some(self.external_hash(grandparent.introduced_by).to_owned()),
                });
                previous = grandparent.flag;
            }
        }
        // Delete the file recursively
        let mut file_edges = vec![];
        {
            debug!("del={:?}", current_node);
            let ret = self.retrieve(branch, current_node);
            debug!("ret {:?}", ret);
            for l in ret.lines.iter() {
                if l.key != ROOT_KEY {
                    let ext_key = self.external_key(&l.key).unwrap();
                    debug!("ext_key={:?}", ext_key);
                    for v in self.iter_parents(branch, l.key, EdgeFlags::empty()) {
                        debug!("v={:?}", v);
                        file_edges.push(NewEdge {
                            from: ext_key.clone(),
                            to: self.external_key(&v.dest).unwrap(),
                            introduced_by: Some(self.external_hash(v.introduced_by).to_owned()),
                        });
                        if let Some(inode) = self.get_revinodes(v.dest) {
                            st.updatables.insert(InodeUpdate::Deleted {
                                inode: inode.to_owned(),
                            });
                        }
                    }
                    for v in self.iter_parents(branch, l.key, EdgeFlags::FOLDER_EDGE) {
                        debug!("v={:?}", v);
                        edges.push(NewEdge {
                            from: ext_key.clone(),
                            to: self.external_key(&v.dest).unwrap(),
                            introduced_by: Some(self.external_hash(v.introduced_by).to_owned()),
                        });
                    }
                }
            }
        }

        if !edges.is_empty() {
            st.actions.push(Record::FileDel {
                name: realpath.to_string_lossy().to_string(),
                del: Change::NewEdges {
                    edges: edges,
                    previous,
                    flag: EdgeFlags::FOLDER_EDGE | EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE,
                    inode: self.external_key(&current_node).unwrap(),
                },
            });
        }
        if !file_edges.is_empty() {
            st.actions.push(Record::Change {
                change: Change::NewEdges {
                    edges: file_edges,
                    previous: EdgeFlags::PARENT_EDGE,
                    flag: EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE,
                    inode: self.external_key(&current_node).unwrap(),
                },
                file: Rc::new(realpath.to_path_buf()),
                conflict_reordering: Vec::new(),
            });
        }
        Ok(())
    }

    fn record_children(
        &self,
        diff_algorithm: diff::Algorithm,
        branch: &Branch,
        st: &mut RecordState,
        path: &mut std::path::PathBuf,
        current_node: Key<Option<PatchId>>,
        current_inode: Inode,
        obsolete_inodes: &mut Vec<Inode>,
    ) -> Result<()> {
        debug!("children of current_inode {}", current_inode.to_hex());
        let file_id = OwnedFileId {
            parent_inode: current_inode.clone(),
            basename: SmallString::from_str(""),
        };
        debug!("iterating tree, starting from {:?}", file_id.as_file_id());
        for (k, v) in self.iter_tree(Some((&file_id.as_file_id(), None)))
        for (k, v) in self
            .iter_tree(Some((&file_id.as_file_id(), None)))
            .take_while(|&(ref k, _)| k.parent_inode == current_inode)
        {
            debug!("calling record_all recursively, {}", line!());

            if k.basename.len() > 0 {
                // If this is an actual file and not just the "."
                self.record_inode(
                    diff_algorithm,
                    branch,
                    st,
                    current_node.clone(), // parent
                    v,                    // current_inode
                    path,
                    obsolete_inodes,
                    k.basename.as_str(),
                )?
            }
        }
        Ok(())
    }

    /// If `inode` is a file known to the current branch, return
    /// whether it's been moved, deleted, or its "status" (including
    /// permissions) has been changed.
    ///
    /// Returns `None` if `inode` is not known to the current branch.
    fn inode_status(&self, inode: Inode, path: &Path) -> (Option<(WorkingFileStatus, FileHeader)>) {
        match self.get_inodes(inode) {
            Some(file_header) => {
                let old_meta = file_header.metadata;
                let new_meta = file_metadata(path).ok();

                debug!("current_node={:?}", file_header);
                debug!("old_attr={:?},int_attr={:?}", old_meta, new_meta);

                let status = match (new_meta, file_header.status) {
                    (Some(new_meta), FileStatus::Moved) => WorkingFileStatus::Moved {
                        from: old_meta,
                        to: new_meta,
                    },
                    (Some(new_meta), _) if old_meta != new_meta => WorkingFileStatus::Moved {
                        from: old_meta,
                        to: new_meta,
                    },
                    (None, _) | (_, FileStatus::Deleted) => WorkingFileStatus::Deleted,
                    (Some(_), FileStatus::Ok) => WorkingFileStatus::Ok,
                    (Some(_), FileStatus::Zombie) => WorkingFileStatus::Zombie,
                };
                Some((status, file_header.clone()))
            }
            None => None,
        }
    }

    fn record_inode(
        &self,
        diff_algorithm: diff::Algorithm,
        branch: &Branch,
        st: &mut RecordState,
        parent_node: Key<Option<PatchId>>,
        current_inode: Inode,
        realpath: &mut std::path::PathBuf,
        obsolete_inodes: &mut Vec<Inode>,
        basename: &str,
    ) -> Result<()> {
        realpath.push(basename);
        debug!("realpath: {:?}", realpath);
        debug!("inode: {:?}", current_inode);
        debug!("header: {:?}", self.get_inodes(current_inode));
        let status_header = self.inode_status(current_inode, realpath);
        debug!("status_header: {:?}", status_header);
        let mut current_key = match &status_header {
            &Some((_, ref file_header)) => Some(Key {
                patch: Some(file_header.key.patch.clone()),
                line: file_header.key.line.clone(),
            }),
            &None => None,
        };

        match status_header {
            Some((
                WorkingFileStatus::Moved {
                    from: old_meta,
                    to: new_meta,
                },
                file_header,
            )) => {
                st.updatables.insert(InodeUpdate::Moved {
                    inode: current_inode.clone(),
                });
                self.record_moved_file(
                    diff_algorithm,
                    branch,
                    realpath,
                    st,
                    parent_node,
                    file_header.key,
                    basename,
                    new_meta,
                    old_meta,
                )?
            }
            Some((WorkingFileStatus::Deleted, file_header)) => {
                st.updatables.insert(InodeUpdate::Deleted {
                    inode: current_inode.clone(),
                });
                self.record_deleted_file(st, branch, realpath, file_header.key)?
            }
            Some((WorkingFileStatus::Ok, file_header)) => {
                if !file_header.metadata.is_dir() {
                    let mut ret = self.retrieve(branch, file_header.key);
                    debug!("now calling diff {:?}", file_header.key);
                    let inode = Key {
                        patch: Some(self.external_hash(file_header.key.patch).to_owned()),
                        line: file_header.key.line,
                    };
                    self.confirm_path(st, branch, &realpath, file_header.key)?;
                    self.diff_with_binary(inode, branch, st, &mut ret, Rc::new(realpath.clone()))?;
                    self.diff_with_binary(
                        diff_algorithm,
                        inode,
                        branch,
                        st,
                        &mut ret,
                        Rc::new(realpath.clone()),
                    )?;
                } else {
                    // Confirm
                    self.confirm_path(st, branch, &realpath, file_header.key)?;
                }
            }
            Some((WorkingFileStatus::Zombie, _)) => {
                // This file is a zombie, but the user has not
                // specified anything to do with this file, so leave
                // it alone.
            }
            None => {
                if let Ok(new_key) =
                    self.record_file_addition(st, current_inode, parent_node, realpath, basename)
                {
                    current_key = new_key.map(|next| Key {
                        patch: None,
                        line: next,
                    })
                } else {
                    obsolete_inodes.push(current_inode)
                }
            }
        }

        let current_key = current_key;
        debug!("current_node={:?}", current_key);
        if let Some(current_node) = current_key {
            self.record_children(
                diff_algorithm,
                branch,
                st,
                realpath,
                current_node,
                current_inode,
                obsolete_inodes,
            )?;
        };
        realpath.pop();
        Ok(())
    }

    fn external_newedge(
        &self,
        from: Key<PatchId>,
        to: Key<PatchId>,
        introduced_by: PatchId,
    ) -> NewEdge {
        NewEdge {
            from: Key {
                patch: Some(self.external_hash(from.patch).to_owned()),
                line: from.line,
            },
            to: Key {
                patch: Some(self.external_hash(to.patch).to_owned()),
                line: to.line,
            },
            introduced_by: Some(self.external_hash(introduced_by).to_owned()),
        }
    }

    /// `key` must be a non-root inode key.
    fn confirm_path(
        &self,
        st: &mut RecordState,
        branch: &Branch,
        realpath: &Path,
        key: Key<PatchId>,
    ) -> Result<()> {
        debug!("confirm_path");
        let f = EdgeFlags::PARENT_EDGE | EdgeFlags::FOLDER_EDGE | EdgeFlags::DELETED_EDGE;
        // Are there deleted parent edges?
        let mut edges = Vec::new();
        for v in self.iter_adjacent(branch, key, f, f)
        {
        {
        for v in self.iter_adjacent(branch, key, f, f) {
            debug!("confirm {:?}", v.dest);
            edges.push(self.external_newedge(key, v.dest, v.introduced_by));
            for v_ in self.iter_adjacent(branch, v.dest, f, f)
            {
            {
            for v_ in self.iter_adjacent(branch, v.dest, f, f) {
                debug!("confirm 2 {:?}", v_.dest);
                edges.push(self.external_newedge(v.dest, v_.dest, v_.introduced_by));
            }
        }

        if !edges.is_empty() {
            let inode = Key {
                patch: Some(self.external_hash(key.patch).to_owned()),
                line: key.line.clone(),
            };
            st.actions.push(Record::FileAdd {
                name: realpath.to_string_lossy().to_string(),
                add: Change::NewEdges {
                    edges,
                    previous: EdgeFlags::FOLDER_EDGE | EdgeFlags::PARENT_EDGE
                    previous: EdgeFlags::FOLDER_EDGE
                        | EdgeFlags::PARENT_EDGE
                        | EdgeFlags::DELETED_EDGE,
                    flag: EdgeFlags::FOLDER_EDGE | EdgeFlags::PARENT_EDGE,
                    inode,
                },
            });
        }
        debug!("/confirm_path");

        Ok(())
    }
}

impl RecordState {
    pub fn new() -> Self {
        RecordState {
            line_num: LineId::new() + 1,
            actions: Vec::new(),
            updatables: HashSet::new(),
            redundant: Vec::new(),
        }
    }

    pub fn finish(
        self,
    ) -> (
        Vec<Record<Rc<RefCell<ChangeContext<PatchId>>>>>,
        HashSet<InodeUpdate>,
    ) {
    pub fn finish(self) -> (Vec<Record<ChangeContext<PatchId>>>, HashSet<InodeUpdate>) {
        (self.actions, self.updatables)
    }
}

impl<'env, T: rand::Rng> MutTxn<'env, T> {
    pub fn record(
        &mut self,
        diff_algorithm: diff::Algorithm,
        state: &mut RecordState,
        branch: &Branch,
        working_copy: &std::path::Path,
        prefix: Option<&std::path::Path>,
    ) -> Result<()> {
        let mut obsolete_inodes = Vec::new();
        {
            let mut realpath = PathBuf::from(working_copy);

            if let Some(prefix) = prefix {
                realpath.extend(prefix);
                let basename = realpath.file_name().unwrap().to_str().unwrap().to_string();
                realpath.pop();
                let inode = self.find_inode(prefix)?;
                // Key needs to be the parent's node.
                let key: Key<PatchId> = {
                    // find this inode's parent.
                    if let Some(parent) = self.get_revtree(inode) {
                        if parent.parent_inode.is_root() {
                            ROOT_KEY
                        } else if let Some(key) = self.get_inodes(parent.parent_inode) {
                            key.key
                        } else {
                            return Err(Error::FileNotInRepo(prefix.to_path_buf()));
                        }
                    } else {
                        return Err(Error::FileNotInRepo(prefix.to_path_buf()));
                    }
                };
                let key = Key {
                    patch: Some(key.patch),
                    line: key.line,
                };
                self.record_inode(
                    diff_algorithm,
                    &branch,
                    state,
                    key,
                    inode,
                    &mut realpath,
                    &mut obsolete_inodes,
                    &basename,
                )?
            } else {
                let key = Key {
                    patch: None,
                    line: LineId::new(),
                };
                self.record_children(
                    diff_algorithm,
                    &branch,
84
85

86
87
88
89
90
91
92
93
94
95
96
97
98

99
100
username = "0.2"
shell-escape = "0.1"
libpijul = "0.11.0"
libpijul = "0.11.1"

tar = "0.4"
flate2 = "1.0"
ignore = "0.4"
bincode = "1.0"
tempdir = "0.3"
isatty = "0.1"
progrs = "0.1"

base64 = "0.9"
cryptovec = "0.4"

line = "0.1"
line = "0.1.11"
rpassword = "2.0"
109
110
111
            apply_resize(
                libpijul::DiffAlgorithm::default(),
                &opts.repo_root,
350
351

352
353
354
355
356

                change: dels.clone(),
                file: file.clone(),
                conflict_reordering: Vec::new(),
            };
            print_change(term, cwd, repo, current_file, &r)?;
            let r = Record::Change {
                change: adds.clone(),
                file: file.clone(),
                conflict_reordering: Vec::new(),
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
use super::{default_explain, BasicOptions, StaticSubcommand};
use error::Error;
use libpijul::fs_representation::{get_current_branch, set_current_branch};
use libpijul::patch::UnsignedPatch;
use libpijul::{FileStatus, RecordState, ToPrefixes};
use rand;
use error::Error;
use std::collections::HashSet;

pub fn invocation() -> StaticSubcommand {
    return SubCommand::with_name("checkout")
        .about("Change the current branch")
        .arg(
            Arg::with_name("repository")
                .long("repository")
                .help("Local repository.")
                .takes_value(true),
        )
        )
        .arg(
        ).arg(
            Arg::with_name("branch")
                .help("Branch to switch to.")
                .takes_value(true),
        )
        )
        .arg(
        ).arg(
            Arg::with_name("path")
                .long("path")
                .help("Partial path to check out.")
                .takes_value(true),
        )
        )
        .arg(
        ).arg(
            Arg::with_name("force")
                .short("f")
                .long("force")
                .takes_value(false)
                .help("Only check files moves, deletions and additions (much faster)."),
        );
}

pub fn run(args: &ArgMatches) -> Result<(), Error> {
    let opts = BasicOptions::from_args(args)?;
    if let Some(branch) = args.value_of("branch") {
        checkout(
            &opts,
            branch,
            args.is_present("force"),
            args.value_of("path"),
        )
    } else {
        Err(Error::NoSuchBranch)
    }
}

pub fn checkout(
    opts: &BasicOptions,
    branch: &str,
    force: bool,
    partial_path: Option<&str>,
) -> Result<(), Error> {
    let mut force = force;
    let mut provision = 409600;

    loop {
        match try_checkout(opts, branch, force, provision, partial_path) {
            Err(ref e) if e.lacks_space() => {
                provision = provision * 2;
                force = true;
            }
            x => return x,
        }
    }
}

pub fn try_checkout(
    opts: &BasicOptions,
    branch_name: &str,
    force: bool,
    provision: u64,
    partial_path: Option<&str>,
) -> Result<(), Error> {
    let repo = opts.open_and_grow_repo(provision)?;
    let mut txn = repo.mut_txn_begin(rand::thread_rng())?;
    let current_branch = get_current_branch(&opts.repo_root)?;
    // We need to check at least that there are no file
    // moves/additions/deletions, because these would be
    // overwritten by the checkout, sometimes causing Pijul to
    // panic.
    if force {
        // Check whether there are file moves.
        if txn.iter_inodes(None)
        if txn
            .iter_inodes(None)
            .any(|(_, ch)| ch.status != FileStatus::Ok)
        {
            return Err(Error::PendingChanges);
        }
    } else {
        // Check whether there are more general changes.
        let mut record = RecordState::new();
        let current_branch = txn.open_branch(&current_branch)?;
        txn.record(&mut record, &current_branch, &opts.repo_root, None)?;
        txn.record(&mut record, &current_branch, &opts.repo_root, None)?;
        txn.record(
            libpijul::DiffAlgorithm::default(),
            &mut record,
            &current_branch,
            &opts.repo_root,
            None,
        )?;
        txn.commit_branch(current_branch)?;
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
                .takes_value(true)
                .required(false),
        )
        .arg(
        ).arg(
            Arg::with_name("branch")
                .long("branch")
                .help("The branch to show, defaults to the current branch.")
                .takes_value(true)
                .required(false),
        )
        .arg(
        ).arg(
            Arg::with_name("prefix")
                .help("Prefix to start from")
                .takes_value(true)
                .multiple(true),
        );
        )
        .arg(Arg::with_name("patience")
             .long("patience")
             .help("Use patience diff instead of the default (Myers diff)")
             .conflicts_with("myers")
             .takes_value(false))
        .arg(Arg::with_name("myers")
             .long("myers")
             .help("Use Myers diff")
             .conflicts_with("patience")
             .takes_value(false))
}

pub fn run(args: &ArgMatches) -> Result<(), Error> {
    super::setup_pager();

    let opts = BasicOptions::from_args(args)?;
    let repo = opts.open_repo()?;
    let mut txn = repo.mut_txn_begin(rand::thread_rng())?;
    let prefix = if let Some(prefix) = args.value_of("prefix") {
        let p = canonicalize(opts.cwd.join(prefix))?;
        if let Ok(file) = p.strip_prefix(&opts.repo_root) {
            Some(file.to_path_buf())
        } else {
            None
        }
    } else {
        None
    };
    let prefix = if let Some(ref prefix) = prefix {
        Some(prefix.as_path())
    } else {
        None
    };
    let mut record = RecordState::new();
    let branch = txn.open_branch(&opts.branch())?;
    txn.record(&mut record, &branch, &opts.repo_root, prefix)?;
    txn.record(
        if args.is_present("patience") {
            libpijul::DiffAlgorithm::Patience
        } else {
            libpijul::DiffAlgorithm::Myers
        },
        &mut record,
        &branch,
        &opts.repo_root,
        prefix,
    )?;
    txn.commit_branch(branch)?;
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
use commands::{ask, BasicOptions, StaticSubcommand};
use error::Error;
use libpijul;
use libpijul::fs_representation::{ignore_file, patches_dir, untracked_files};
use libpijul::patch::{PatchFlags, Record};
use libpijul::{Hash, InodeUpdate, Key, MutTxn, Patch, PatchId, RecordState, Repository};
use meta::{load_global_or_local_signing_key, Global, Meta};
use rand;
use std::collections::HashSet;
use std::fs::canonicalize;
use std::fs::{metadata, OpenOptions};
use std::io::Write;
use std::mem::drop;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::str::FromStr;
use error::Error;

pub fn record_args(sub: StaticSubcommand) -> StaticSubcommand {
    sub.arg(Arg::with_name("repository")
            .long("repository")
            .help("The repository where to record, defaults to the current directory.")
            .takes_value(true)
            .required(false))
        .arg(Arg::with_name("branch")
             .long("branch")
             .help("The branch where to record, defaults to the current branch.")
             .takes_value(true)
             .required(false))
        .arg(Arg::with_name("date")
             .long("date")
             .help("The date to use to record the patch, default is now.")
             .takes_value(true)
             .required(false))
        .arg(Arg::with_name("message")
             .short("m")
             .long("message")
             .help("The name of the patch to record")
             .takes_value(true))
        .arg(Arg::with_name("description")
             .short("d")
             .long("description")
             .help("The description of the patch to record")
             .takes_value(true))
        .arg(Arg::with_name("no-editor")
             .long("no-editor")
             .help("Do not use an editor to write the patch name and description, even if the variable is set in the configuration file")
             .takes_value(false))
        .arg(Arg::with_name("author")
             .short("A")
             .long("author")
             .help("Author of this patch (multiple occurrences allowed)")
             .takes_value(true))
        .arg(Arg::with_name("patience")
             .long("patience")
             .help("Use patience diff instead of the default (Myers diff)")
             .conflicts_with("myers")
             .takes_value(false))
        .arg(Arg::with_name("myers")
             .long("myers")
             .help("Use Myers diff")
             .conflicts_with("patience")
             .takes_value(false))
}

pub fn invocation() -> StaticSubcommand {
    return record_args(
        SubCommand::with_name("record")
            .about("Record changes in the repository")
            .arg(
                Arg::with_name("all")
                    .short("a")
                    .long("all")
                    .help("Answer 'y' to all questions")
                    .takes_value(false),
            )
            .arg(
            ).arg(
                Arg::with_name("add-new-files")
                    .short("n")
                    .long("add-new-files")
                    .help("Offer to add files that have been created since the last record")
                    .takes_value(false),
            )
            .arg(
            ).arg(
                Arg::with_name("depends-on")
                    .help("Add a dependency to this patch (internal id or hash accepted)")
                    .long("depends-on")
                    .takes_value(true)
                    .multiple(true),
            )
            .arg(
            ).arg(
                Arg::with_name("prefix")
                    .help("Prefix to start from")
                    .takes_value(true)
                    .multiple(true),
            ),
    );
}

fn add_untracked_files<T: rand::Rng>(
    txn: &mut MutTxn<T>,
    repo_root: &Path,
) -> Result<HashSet<PathBuf>, Error> {
    let untracked = untracked_files(txn, repo_root);
    debug!("adding untracked_files at record time: {:?}", &untracked);
    for file in untracked.iter() {
        let m = metadata(&file)?;
        let file = file.strip_prefix(&repo_root)?;
        if let Err(e) = txn.add_file(&file, m.is_dir()) {
            if let libpijul::Error::AlreadyAdded = e {
            } else {
                return Err(e.into());
            }
        }
    }
    Ok(untracked)
}

fn append_to_ignore_file(repo_root: &Path, lines: &Vec<String>) -> Result<(), Error> {
    let ignore_file = ignore_file(repo_root);
    let mut file = OpenOptions::new()
        .append(true)
        .create(true)
        .open(ignore_file)?;
    for line in lines {
        file.write_all(line.as_ref())?;
        file.write_all(b"\n")?
    }
    Ok(())
}

fn select_changes(
    algo: libpijul::DiffAlgorithm,
    opts: &BasicOptions,
    add_new_files: bool,
    branch_name: &str,
    yes_to_all: bool,
    prefix: Option<Vec<PathBuf>>,
) -> Result<(Vec<Record<Vec<Key<Option<Hash>>>>>, HashSet<InodeUpdate>), Error> {
    // Increase by 100 pages. The most things record can write is one
    // write in the branches table, affecting at most O(log n) blocks.
    let repo = opts.open_and_grow_repo(409600)?;
    let mut txn = repo.mut_txn_begin(rand::thread_rng())?;
    let mut to_unadd = if add_new_files {
        add_untracked_files(&mut txn, &opts.repo_root)?
    } else {
        HashSet::<PathBuf>::new()
    };
    let (changes, syncs) =
        changes_from_prefixes(&opts.repo_root, &mut txn, &branch_name, prefix.as_ref())?;
    let (changes, syncs) = changes_from_prefixes(
        algo,
        &opts.repo_root,
        &mut txn,
        &branch_name,
        prefix.as_ref(),
    )?;
    let changes: Vec<_> = changes
        .into_iter()
        .map(|x| txn.globalize_record(x))
        .collect();
    if !yes_to_all {
        let (c, i) = ask_changes(
            &txn,
            &opts.repo_root,
            &opts.cwd,
            &changes,
            ChangesDirection::Record,
            &mut to_unadd,
        )?;
        let selected = changes
            .into_iter()
            .enumerate()
            .filter(|&(i, _)| *(c.get(&i).unwrap_or(&false)))
            .map(|(_, x)| x)
            .collect();
        for file in to_unadd {
            txn.remove_file(&file)?
        }
        txn.commit()?;
        append_to_ignore_file(&opts.repo_root, &i)?;
        Ok((selected, syncs))
    } else {
        txn.commit()?;
        Ok((changes, syncs))
    }
}

pub fn run(args: &ArgMatches) -> Result<Option<Hash>, Error> {
    let opts = BasicOptions::from_args(args)?;
    let yes_to_all = args.is_present("all");
    let patch_name_arg = args.value_of("message");
    let patch_descr_arg = args.value_of("description");
    let authors_arg = args.values_of("author").map(|x| x.collect::<Vec<_>>());
    let branch_name = opts.branch();
    let add_new_files = args.is_present("add-new-files");

    let patch_date = args.value_of("date").map_or(Ok(chrono::Utc::now()), |x| {
        chrono::DateTime::from_str(x).map_err(|_| Error::InvalidDate { date: String::from(x) })
        chrono::DateTime::from_str(x).map_err(|_| Error::InvalidDate {
            date: String::from(x),
        })
    })?;

    let mut save_meta = false;
    let mut save_global = false;

    let mut global = Global::load().unwrap_or_else(|e| {
        info!("loading global key, error {:?}", e);
        save_global = true;
        Global::new()
    });

    let mut meta = match Meta::load(&opts.repo_root) {
        Ok(m) => m,
        Err(_) => {
            save_meta = true;
            Meta::new()
        }
    };

    run_hook(&opts.repo_root, "pre-record", None)?;

    debug!("prefix {:?}", args.value_of("prefix"));
    let prefix = prefix(args, &opts)?;

    let (changes, syncs) = select_changes(&opts, add_new_files, &branch_name, yes_to_all, prefix)?;
    let (changes, syncs) = select_changes(
        if args.is_present("patience") {
            libpijul::DiffAlgorithm::Patience
        } else {
            libpijul::DiffAlgorithm::Myers
        },
        &opts,
        add_new_files,
        &branch_name,
        yes_to_all,
        prefix,
    )?;

    if changes.is_empty() {
        println!("Nothing to record");
        Ok(None)
    } else {
        let template = prepare_changes_template(&opts.repo_root, patch_name_arg.unwrap_or(""), &changes);
        let template =
            prepare_changes_template(&opts.repo_root, patch_name_arg.unwrap_or(""), &changes);

        let repo = opts.open_repo()?;
        let patch = {
            let txn = repo.txn_begin()?;
            debug!("meta:{:?}", meta);

            let authors = decide_authors(authors_arg, &meta, &global)?;

            if authors.is_empty() {
                return Err(Error::NoAuthor)
                return Err(Error::NoAuthor);
            }

            if meta.authors.is_empty() {
                meta.authors = authors.clone();
                save_meta = true;
            }

            if global.author.len() == 0 {
                global.author = authors[0].clone();
                save_global = true;
            }

            debug!("authors:{:?}", authors);

            let (patch_name, description) = decide_patch_message(
                patch_name_arg,
                patch_descr_arg,
                template,
                !args.is_present("no-editor"),
                &opts.repo_root,
                &meta,
                &global,
            )?;

            run_hook(&opts.repo_root, "patch-name", Some(&patch_name))?;

            debug!("patch_name:{:?}", patch_name);
            if save_meta {
                meta.save(&opts.repo_root)?
            }
            if save_global {
                global.save().unwrap_or(())
            }
            debug!("new");
            let changes = changes.into_iter().flat_map(|x| x.into_iter()).collect();
            let branch = txn.get_branch(&branch_name).unwrap();

            let mut extra_deps = Vec::new();
            if let Some(deps) = args.values_of("depends-on") {
                for dep in deps {
                    if let Some(hash) = Hash::from_base58(dep) {
                        if let Some(internal) = txn.get_internal(hash.as_ref()) {
                            if txn.get_patch(&branch.patches, internal).is_some() {
                                extra_deps.push(hash)
                            } else {
                                return Err(Error::ExtraDepNotOnBranch { hash });
                            }
                        } else {
                            return Err(Error::PatchNotFound {
                                repo_root: opts.repo_root().to_string_lossy().into_owned(),
                                patch_hash: hash,
                            });
                        }
                    } else if let Some(internal) = PatchId::from_base58(dep) {
                        if let Some(hash) = txn.get_external(internal) {
                            if txn.get_patch(&branch.patches, internal).is_some() {
                                extra_deps.push(hash.to_owned())
                            } else {
                                return Err(Error::ExtraDepNotOnBranch { hash: hash.to_owned() });
                                return Err(Error::ExtraDepNotOnBranch {
                                    hash: hash.to_owned(),
                                });
                            }
                        }
                    } else {
                        return Err(Error::WrongHash);
                    }
                }
            }
            txn.new_patch(
                &branch,
                authors,
                patch_name,
                description,
                patch_date,
                changes,
                extra_deps.into_iter(),
                PatchFlags::empty(),
            )
        };
        drop(repo);

        let dot_pijul = opts.repo_dir();
        let key = if let Ok(Some(key)) = meta.signing_key() {
            Some(key)
        } else {
            load_global_or_local_signing_key(Some(&dot_pijul)).ok()
        };
        debug!("key.is_some(): {:?}", key.is_some());
        let patches_dir = patches_dir(&opts.repo_root);
        let hash = patch.save(&patches_dir, key.as_ref())?;

        let pristine_dir = opts.pristine_dir();
        let mut increase = 409600;
        let res = loop {
            match record_no_resize(
                &pristine_dir,
                &opts.repo_root,
                &branch_name,
                &hash,
                &patch,
                &syncs,
                increase,
            ) {
                Err(ref e) if e.lacks_space() => increase *= 2,
                e => break e,
            }
        };

        run_hook(&opts.repo_root, "post-record", None)?;

        res
    }
}

pub fn record_no_resize(
    pristine_dir: &Path,
    r: &Path,
    branch_name: &str,
    hash: &Hash,
    patch: &Patch,
    syncs: &HashSet<InodeUpdate>,
    increase: u64,
) -> Result<Option<Hash>, Error> {
    let size_increase = increase + patch.size_upper_bound() as u64;
    let repo = match Repository::open(&pristine_dir, Some(size_increase)) {
        Ok(repo) => repo,
        Err(x) => return Err(Error::Repository(x)),
    };
    let mut txn = repo.mut_txn_begin(rand::thread_rng())?;
    // save patch
    debug!("syncs: {:?}", syncs);
    let mut branch = txn.open_branch(branch_name)?;
    txn.apply_local_patch(&mut branch, r, &hash, &patch, &syncs, false)?;
    txn.commit_branch(branch)?;
    txn.commit()?;
    println!("Recorded patch {}", hash.to_base58());
    Ok(Some(hash.clone()))
}

pub fn explain(res: Result<Option<Hash>, Error>) {
    default_explain(res)
}

pub fn changes_from_prefixes<T: rand::Rng, P: AsRef<Path>>(
    algo: libpijul::DiffAlgorithm,
    repo_root: &Path,
    txn: &mut MutTxn<T>,
    branch_name: &str,
    prefix: Option<&Vec<P>>,
) -> Result<(
    Vec<libpijul::patch::Record<Rc<RefCell<libpijul::patch::ChangeContext<PatchId>>>>>,
    HashSet<libpijul::InodeUpdate>,
), Error> {
) -> Result<
    (
        Vec<libpijul::patch::Record<libpijul::patch::ChangeContext<PatchId>>>,
        HashSet<libpijul::InodeUpdate>,
    ),
    Error,
> {
    let mut record = RecordState::new();
    let branch = txn.open_branch(branch_name)?;
    if let Some(prefixes) = prefix {
        for prefix in prefixes {
            txn.record(&mut record, &branch, repo_root, Some(prefix.as_ref()))?;
            txn.record(algo, &mut record, &branch, repo_root, Some(prefix.as_ref()))?;
        }
    } else {
        txn.record(&mut record, &branch, repo_root, None)?;
        txn.record(algo, &mut record, &branch, repo_root, None)?;
    }
    txn.commit_branch(branch)?;
    let (changes, updates) = record.finish();
    // let changes = changes.into_iter().map(|x| txn.globalize_change(x)).collect();
    Ok((changes, updates))
}

pub fn prefix(args: &ArgMatches, opts: &BasicOptions) -> Result<Option<Vec<PathBuf>>, Error> {
    if let Some(prefixes) = args.values_of("prefix") {
        let prefixes: Result<Vec<_>, Error> = prefixes
            .map(|prefix| {
                let p = opts.cwd.join(prefix);
                let p = if let Ok(p) = canonicalize(&p) { p } else { p };
                let file = p.strip_prefix(&opts.repo_root)?;
                debug!("prefix: {:?}", file);
                Ok(file.to_path_buf())
            })
            .collect();
            }).collect();
        Ok(Some(prefixes?))
    } else {
        Ok(None)
    }
}

pub fn decide_authors(
    authors_args: Option<Vec<&str>>,
    meta: &Meta,
    global: &Global,
) -> Result<Vec<String>, Error> {
    Ok(match authors_args {
        Some(authors) => authors.iter().map(|x| x.to_string()).collect(),
        _ => {
            if meta.authors.len() > 0 {
                meta.authors.clone()
            } else if global.author.len() > 0 {
                vec![global.author.clone()]
            } else {
                ask::ask_authors()?
            }
        }
    })
}

pub fn decide_patch_message(
    name_arg: Option<&str>,
    descr_arg: Option<&str>,
    template: String,
    use_editor: bool,
    repo_root: &PathBuf,
    meta: &Meta,
    global: &Global,
) -> Result<(String, Option<String>), Error> {
    Ok(match name_arg {
        Some(m) => (m.to_string(), descr_arg.map(|x| String::from(x.trim()))),
        _ => {
            let maybe_editor = if use_editor {
                if meta.editor.is_some() {
                    meta.editor.as_ref()
                } else {
                    global.editor.as_ref()
                }
            } else {
                None
            };

            ask::ask_patch_name(repo_root, maybe_editor, template)?
        }
    })
}

fn prepare_changes_template(
    repo_root: &Path,
    descr: &str,
    changes: &[Record<Vec<Key<Option<Hash>>>>],
) -> String {
    let mut res = format!(r#"
    let mut res = format!(
        r#"
{}
# Please enter a patch title, and consider writing a description too. Lines
# starting with '#' will be ignored. Besides, an empty patch title aborts the
# patch recording.
#
# Here is a summary of the changes you are about to record:
#"#, descr);
#"#,
        descr
    );
    let mut known_files = Vec::new();

    for change in changes.iter() {
        match *change {
            Record::Change { ref file, .. }
            | Record::Replace { ref file, .. } => {
            Record::Change { ref file, .. } | Record::Replace { ref file, .. } => {
                let filename = file
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
                apply_resize(
                    libpijul::DiffAlgorithm::default(),
                    &self.path,
                    &remote_branch,
                    patch_hashes.iter(),
                    &[] as &[&str],
                    |_, _| {},
                )
            };
            match app {
                Err(ref e) if e.lacks_space() => debug!("lacks space"),
                Ok(()) => return Ok(()),
                Err(e) => return Err(From::from(e)),
            }
        }
    }
}

impl<'a> Session<'a> {
    pub fn changes(
        &mut self,
        branch: &str,
        remote_path: &[&str],
    ) -> Result<HashMap<Hash, ApplyTimestamp>, Error> {
        match *self {
            Session::Ssh(ref mut ssh_session) => ssh_session.changes(branch, remote_path),
            Session::Local(ref mut local_session) => local_session.changes(branch, remote_path),
            Session::Uri(ref mut uri_session) => uri_session.changes(branch, remote_path),
        }
    }
    pub fn download_patch(&mut self, repo_root: &Path, patch_hash: &Hash) -> Result<PathBuf, Error> {
        let patches_dir_ = patches_dir(repo_root);
        let local_file = patches_dir_.join(&patch_file_name(patch_hash.as_ref()));

        if !metadata(&local_file).is_ok() {
            match *self {
                Session::Local(ref mut local_session) => {
                    local_session.fetch_patch(patch_hash, local_file)
                }
                Session::Ssh(ref mut ssh_session) => {
                    let tmp_dir = TempDir::new_in(&patches_dir_, "pijul_patch")?;
                    let local_tmp_file = tmp_dir.path().join("patch");
                    ssh_session.fetch_patch(patch_hash, local_file, local_tmp_file)
                }
                Session::Uri(ref mut uri_session) => {
                    let tmp_dir = TempDir::new_in(&patches_dir_, "pijul_patch")?;
                    let local_tmp_file = tmp_dir.path().join("patch");
                    uri_session.fetch_patch(patch_hash, local_file, local_tmp_file)
                }
            }
        } else {
            Ok(local_file)
        }
    }

    fn remote_apply(
        &mut self,
        repo_root: &Path,
        remote_branch: &str,
        patch_hashes: HashSet<Hash>,
    ) -> Result<(), Error> {
        match *self {
            Session::Ssh(ref mut ssh_session) => {
                ssh_session.remote_apply(repo_root, remote_branch, patch_hashes)
            }

            Session::Local(ref mut local_session) => {
                local_session.remote_apply(repo_root, remote_branch, &patch_hashes)
            }

            _ => panic!("upload to URI impossible"),
        }
    }

    pub fn remote_init(&mut self) -> Result<(), Error> {
        match *self {
            Session::Ssh(ref mut ssh_session) => ssh_session.remote_init(),
            Session::Local(ref mut local_session) => {
                assert_no_containing_repo(local_session.path)?;
                create_repo(local_session.path)
            }
            _ => panic!("remote init not possible"),
        }
    }

    pub fn pullable_patches(
        &mut self,
        remote_branch: &str,
        local_branch: &str,
        target: &Path,
        remote_path: &[&str],
    ) -> Result<Pullable, Error> {
        let mut remote_patches: Vec<(Hash, ApplyTimestamp)> = self
            .changes(remote_branch, remote_path)?
            .into_iter()
            .map(|(h, s)| (h.to_owned(), s))
            .collect();
        remote_patches.sort_by(|&(_, ref a), &(_, ref b)| a.cmp(&b));
        let local_patches: HashMap<Hash, ApplyTimestamp> = {
            let repo_dir = pristine_dir(&target);
            let repo = Repository::open(&repo_dir, None)?;
            let txn = repo.txn_begin()?;
            if let Some(branch) = txn.get_branch(&local_branch) {
                txn.iter_patches(&branch, None)
                    .map(|(hash, s)| (txn.get_external(hash).unwrap().to_owned(), s))
                    .collect()
            } else {
                HashMap::new()
            }
        };
        debug!("pullable done: {:?}", remote_patches);
        Ok(Pullable {
            local: local_patches.iter().map(|(h, _)| h.to_owned()).collect(),
            remote: remote_patches.into_iter().collect(),
        })
    }

    pub fn pull(
        &mut self,
        target: &Path,
        to_branch: &str,
        pullable: &mut Vec<(Hash, ApplyTimestamp)>,
        partial_paths: &[&str],
        display_progress: bool,
    ) -> Result<(), Error> {
        let mut p = if display_progress && !pullable.is_empty() {
            Some((progrs::start("Pulling patches", pullable.len() as u64), 0))
        } else {
            None
        };
        let mut pullable_plus_deps = Vec::new();
        let mut pulled = HashSet::new();

        while let Some((hash, _)) = pullable.pop() {
            if pulled.contains(&hash) {
                continue;
            }
            debug!("hash = {:?}", hash);
            let path = self.download_patch(&target, &hash)?;

            let patch = {
                let file = File::open(&path)?;
                let mut file = BufReader::new(file);
                Patch::from_reader_compressed(&mut file)?.2
            };
            pulled.insert(hash.clone());

            // If the apply is partial, we might not have all the
            // dependencies. Add them to this list.
            if !partial_paths.is_empty() {
                for dep in patch.dependencies() {
                    if !pulled.contains(dep) {
                        pullable.push((dep.to_owned(), 0));
                    }
                }
            }

            pullable_plus_deps.push((hash.to_owned(), patch));

            p.as_mut().map(|&mut (ref mut p, ref mut n)| {
                p.display({
                    *n = *n + 1;
                    *n
                })
            });
        }
        p.map(|(p, _)| p.stop("done"));
        debug!("patches downloaded");

        let p = std::cell::RefCell::new(progrs::start(
            "Applying patches",
            pullable_plus_deps.len() as u64,
        ));
        let mut size_increase = 4096;
        let current_branch = get_current_branch(target)?;
        loop {
            let app = if current_branch != to_branch {
                apply_resize_patches_no_output(
                    target,
                    &to_branch,
                    &pullable_plus_deps,
                    size_increase,
                    |c, _| p.borrow_mut().display(c as u64),
                )
            } else {
                apply_resize_patches(
                    libpijul::DiffAlgorithm::default(),
                    target,
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
                .takes_value(true)
                .multiple(true),
        );
        )
        .arg(Arg::with_name("patience")
             .long("patience")
             .help("Use patience diff instead of the default (Myers diff)")
             .conflicts_with("myers")
             .takes_value(false))
        .arg(Arg::with_name("myers")
             .long("myers")
             .help("Use Myers diff")
             .conflicts_with("patience")
             .takes_value(false))
}

pub fn run(args: &ArgMatches) -> Result<(), Error> {
    let opts = BasicOptions::from_args(args)?;
    let yes_to_all = args.is_present("all");
    let branch_name = opts.branch();
    let prefix = record::prefix(args, &opts)?;
    // Generate the pending patch.
    let (pending, pending_syncs): (_, HashSet<_>) = if !yes_to_all || prefix.is_some() {
        let repo = opts.open_and_grow_repo(409600)?;
        let mut txn = repo.mut_txn_begin(rand::thread_rng())?;
        let (changes, syncs) = {
            let (changes, syncs) = record::changes_from_prefixes(
                if args.is_present("patience") {
                    libpijul::DiffAlgorithm::Patience
                } else {
                    libpijul::DiffAlgorithm::Myers
                },
                &opts.repo_root,
182
183
184
            apply_resize(
                libpijul::DiffAlgorithm::default(),
                &opts.repo_root,
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
                .takes_value(true)
                .help("Local repository."),
        )
        .arg(
        ).arg(
            Arg::with_name("short")
                .long("short")
                .short("s")
                .help("Output in short format"),
        )
}

pub fn explain(r: Result<(), Error>) {
    default_explain(r)
}

pub fn run(args: &ArgMatches) -> Result<(), Error> {
    let opts = BasicOptions::from_args(args)?;
    let current_branch = opts.branch();
    let repo = opts.open_and_grow_repo(409600)?;
    let short = args.is_present("short");

    let (unrecorded, untracked, conflicts) = {
        let mut txn = repo.mut_txn_begin(rand::thread_rng())?;
        let unrecorded = unrecorded_changes(&mut txn, &opts.repo_root, &current_branch)?;

        let untracked = untracked_files(&txn, &opts.repo_root);
        let conflicts = txn.list_conflict_files(&current_branch, &[])?;
        (unrecorded, untracked, conflicts)
    };

    if short {
        print_shortstatus(&opts.cwd, &opts.repo_root, unrecorded, untracked, conflicts);
    } else {
        print_longstatus(
            &current_branch,
            &opts.repo_root,
            &opts.cwd,
            unrecorded,
            untracked,
            conflicts,
        );
    }
    Ok(())
}

fn print_longstatus(
    branch: &str,
    repo_root: &PathBuf,
    cwd: &Path,
    changed: Vec<(Rc<PathBuf>, ChangeType)>,
    untracked: HashSet<PathBuf>,
    conflicts: Vec<PathBuf>,
) {
    println!("On branch {}", branch);
    if changed.is_empty() && untracked.is_empty() && conflicts.is_empty() {
        println!("Nothing to record, working tree clean");
    }

    if !conflicts.is_empty() {
        println!("{}", CONFLICTED_FILES);
        for f in conflicts {
            println!(
                "        {}",
                relativize(&cwd, &repo_root.as_path().join(f.as_path())).display()
            );
        }
    }

    if !changed.is_empty() {
        println!("{}", UNRECORDED_FILES);
        for (f, t) in changed {
            println!(
                "        {:10} {}",
                t.long(),
                relativize(&cwd, f.as_path()).display()
            );
        }
    }

    if !untracked.is_empty() {
        println!("{}", UNTRACKED_FILES);
        for f in untracked {
            println!("        {}", relativize(&cwd, f.as_path()).display());
        }
    }
}

fn print_shortstatus(
    cwd: &Path,
    repo_root: &PathBuf,
    changed: Vec<(Rc<PathBuf>, ChangeType)>,
    untracked: HashSet<PathBuf>,
    conflicts: Vec<PathBuf>,
) {
    for f in conflicts {
        println!(
            "C {}",
            relativize(&cwd, &repo_root.as_path().join(f.as_path())).display()
        );
    }
    for (f, t) in changed {
        println!("{} {}", t.short(), relativize(&cwd, f.as_path()).display());
    }
    for f in untracked {
        println!("? {}", relativize(&cwd, f.as_path()).display());
    }
}

#[derive(Debug)]
enum ChangeType {
    Modified,
    New,
    Del,
    Move(Rc<PathBuf>),
}

impl ChangeType {
    fn short(&self) -> &str {
        match *self {
            ChangeType::Modified => "M",
            ChangeType::New => "A",
            ChangeType::Del => "D",
            ChangeType::Move(_) => "→",
        }
    }

    fn long(&self) -> &str {
        match *self {
            ChangeType::Modified => "modified:",
            ChangeType::New => "new file:",
            ChangeType::Del => "deleted:",
            ChangeType::Move(_) => "moved:",
        }
    }
}

fn unrecorded_changes<T: rand::Rng>(
    txn: &mut MutTxn<T>,
    repo_root: &PathBuf,
    branch: &String,
) -> Result<Vec<(Rc<PathBuf>, ChangeType)>, Error> {
    let mut record = RecordState::new();
    let branch = txn.open_branch(branch)?;
    txn.record(&mut record, &branch, repo_root, None)?;
    txn.record(
        libpijul::DiffAlgorithm::default(),
        &mut record,
        &branch,
        repo_root,
        None,
    )?;
    txn.commit_branch(branch)?;
24
25

26
27
    cat a/file >> file
    mv file a/file
    pijul record -a --repository a -m "resolution" -A resolver --date "$DATE"
    RUST_LOG="libpijul=debug" pijul record -a --repository a -m "resolution" -A resolver --date "$DATE" 2> /tmp/log

14
15

16
17
18
19
20
21
22
23
24

25
26
27
28
29
30
31
    pijul clone a b
    echo -n a > a/file
    pijul record -a --repository a -m "a" -A Alice --date "$DATE"
    RUST_LOG="libpijul=debug" RUST_BACKTRACE=1 pijul record -a --repository a -m "a" -A Alice --date "$DATE" 2> /tmp/log

    echo -n b > b/file
    pijul record -a --repository b -m "b" -A Bob --date "$DATE"

    pijul pull -a --repository a b

    run tail -n 1 a/file
    assert_output "^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<$"

    cd a
    pijul info --debug
    cp debug_master /tmp
    cp file /tmp
    pijul revert -a
    cd ..
    run pijul diff --repository a
16
17

18
19
20
21
22
23
24
25
26
27
28

29
30
31

    cd b
    echo b >> file
    pijul record -a -m "b" -A "me"
    RUST_LOG="libpijul::diff=debug" pijul record -a -m "b" -A "me" 2> /tmp/loga
    pijul info --debug
    cp debug_master /tmp/deba

    cd ../a
    echo c >> file
    pijul record -a -m "a" -A "me"
    pijul pull ../b -a

    grep -v ">>>" file | grep -v "<<<" | grep -v "===" > file2
    mv file2 file
    pijul record -a -m "conflict resolution" -A "me"
    cp file /tmp
    RUST_BACKTRACE=1 RUST_LOG="libpijul::diff=debug,libpijul::apply=debug" pijul record -a -m "conflict resolution" -A "me" 2> /tmp/log
    pijul info --debug

23
24

25

26
27
28

    pijul pull ../b -a

    cp file /tmp
    echo b > file
    pijul record -a -m "conflict resolution" -A "me"
    RUST_LOG="libpijul::diff=debug" pijul record -a -m "conflict resolution" -A "me" 2> /tmp/log
    pijul revert -a
    echo b > file2
    cp file file2 /tmp
33
34

35
36
37
38
    sed -i -e "s/a/x/" file
    sed -i -e "s/d/u/" file
    pijul record -a -m "s/a/x" -A "Me"
    RUST_LOG="libpijul::diff=debug" pijul record -a -m "s/a/x" -A "Me" 2> /tmp/log
    pijul info --debug
    cp debug_master /tmp
    pijul revert -a
23
24
25
26

27
28
29
30
31
32
33
34


35
36
37
38
39
40
41

42
43
    pijul_uncovered record -a -m "def" -A "Me"

    RUST_LOG="libpijul::graph=debug,tree" pijul_uncovered pull -a ../a 2> /tmp/log0

    pijul_uncovered pull -a ../a
    echo w > file2
    cat file >> file2
    mv file2 file
    sed -i -e "s/e/x/" file
    sed -i -e "s/a/a1/" file
    sed -i -e "s/f/f2/" file
    echo z >> file
    cp file /tmp
    RUST_LOG="libpijul::optimal_diff=debug" RUST_BACKTRACE=1 pijul record -a -m "s/e/x, s/b/y" -A "Me" 2> /tmp/log

    RUST_LOG="libpijul::diff=debug" RUST_BACKTRACE=1 pijul record -a -m "s/e/x, s/b/y" -A "Me" 2> /tmp/log
    pijul revert -a
    pijul_uncovered info --debug --exclude-parents
    cp debug_master /tmp


    cd ../a
    pijul_uncovered pull -a ../b
    RUST_LOG="libpijul::graph=debug,tree" pijul_uncovered pull -a ../b 2> /tmp/log2
    cp file /tmp
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    pijul_uncovered pull -a ../a


    echo w > file2
    cat file >> file2
    mv file2 file
    sed -i -e "s/f/f2/" file
    sed -i -e "s/c/c2/" file

    cp file /tmp/file
    RUST_LOG="libpijul::optimal_diff=debug" RUST_BACKTRACE=1 pijul record -a -m "s/e/x, s/b/y" -A "Me" 2> /tmp/log
    pijul_uncovered info --debug --exclude-parents
    cp debug_master /tmp/debug0


    pijul_uncovered revert -a
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
    append_random b/toto_append
    cat b/toto_append >> b/toto
    cp b/toto_append b_toto_append
    cp b/toto b_toto_append
    cp b_toto_append /tmp/b_toto_append0

    pijul_uncovered record --repository a -a -m msg -A me
    pijul_uncovered record --repository b -a -m msg -A me
    pijul pull -a --repository b a
    yes | pijul_uncovered record --repository b -m msg -A me

    pijul pull -a --repository b a 2> /tmp/log
    pijul pull -a --repository a b

    cp b/toto_append /tmp/b_toto_append
    assert_files_equal a/toto b/toto

    pijul_uncovered clone a c
    pijul_uncovered clone a d
    rm -Rf /tmp/a /tmp/b
    pijul_uncovered clone a /tmp/a
    pijul_uncovered clone b /tmp/b
    grep ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" b/toto

    # fixing the conflict by keeping the lines
    cp b_toto_append b/toto
    grep -v ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" b/toto | grep -v "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" > b/toto_
    mv b/toto_ b/toto
    cp b/toto /tmp/b_toto

    pijul record --repository b -a -m "fix: keep" -A me
    pijul record --repository b -a -m "fix: keep" -A me
    RUST_LOG="libpijul::diff=debug,libpijul::apply=debug" pijul record --repository b -m "fix: keep" -A me -a 2> /tmp/log
    pijul pull -a --repository a b
    cd a
    pijul info --debug
    cp debug_master /tmp
    cd ..
    ! grep ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" a/toto
9
10

11
12
13
14
15
16
17

18
19
20
21
22
23

24
25
26
27
28

29
30
    pijul init

    echo "a\nb\nc" > file
    echo -e "a\nb\nc" > file
    pijul add file
    pijul record -a -m "Add file" -A "Me"

    cd ..
    pijul clone a left
    cd left
    echo "a\nb\nleft\nleft\nc" > file
    echo -e "a\nb\nleft\nleft\nc" > file
    pijul record -a -m "Edit file left" -A left

    cd ..
    pijul clone a right
    cd right
    echo "a\nb\nright\nright\nc" > file
    echo -e "a\nb\nright\nright\nc" > file
    pijul record -a -m "Edit file right	" -A right
    pijul pull ../left -a
    run pijul status -s
    assert_output "C file"
    echo "a\nb\nleft\nright\nright\nleft\nc" > file
    echo -e "a\nb\nleft\nright\nright\nleft\nc" > file
    pijul record -a -m "Resolve conflict right" -A right
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
    echo -e "a\nb\nc\nd\ne\nf" > x/y/z/file
    pijul_uncovered add x/y/z/file
    pijul_uncovered record -a -m msg -A me
    pijul_uncovered record -a -m "A" -A me
    cd ..

    pijul_uncovered clone a b

    pijul remove --repository a x
    pijul record --repository a -a -m msg -A me
    pijul record --repository a -a -m "B" -A me

    echo "blabla" >> b/x/y/z/file
    pijul record --repository b -a -m msg -A me
    pijul record --repository b -a -m "C" -A me

    pijul pull -a --repository b a
    pijul pull -a --repository a b

    ls a/x/y/z/file
    grep -v ">>>>" a/x/y/z/file | grep -v "<<<<" > file
    cp file /tmp/file_solved
    mv file a/x/y/z


    cd a
    pijul_uncovered ls | grep file

    # Confirming the presence of the conflicting file
    pijul add x/y/z/file
    pijul record -a -m msg -A me
    pijul record -a -m msg -A me
    pijul_uncovered info --debug
    cp debug_master /tmp
    pijul record -a -m "D" -A me
    cp x/y/z/file /tmp/file0
    pijul_uncovered info --debug --exclude-parents
    cp debug_master /tmp/debug0

    cd ..

    pijul_uncovered clone a c
    RUST_LOG="libpijul::apply=debug" pijul_uncovered clone a c 2> /tmp/log
    cd c
    pijul log > /tmp/plog
    pijul_uncovered info --debug --exclude-parents
    cp debug_master /tmp/debug1
    cp x/y/z/file /tmp