unlab-gpu 0.1.0

Micro scripting language for neural networks that uses unmtx-gpu.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
//
// Copyright (c) 2025-2026 Łukasz Szpakowski
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
//! A package module.
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt;
use std::fs;
use std::fs::File;
use std::fs::copy;
use std::fs::create_dir_all;
use std::fs::remove_dir;
use std::fs::rename;
use std::io;
use std::io::BufReader;
use std::io::ErrorKind;
use std::io::Read;
use std::io::Write;
use std::io::stdout;
use std::path;
use std::path::Path;
use std::path::PathBuf;
use std::result;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::RwLock;
use bzip2::read::BzDecoder;
use flate2::read::GzDecoder;
use jammdb::Bucket;
use jammdb::DB;
use jammdb::KVPair;
use jammdb::ToBytes;
use jammdb::Tx;
use liblzma::read::XzDecoder;
use zip::read::ZipArchive;
use crate::curl;
use crate::curl::easy::List;
use crate::serde::de;
use crate::serde::de::Visitor;
use crate::serde::Deserialize;
use crate::serde::Deserializer;
use crate::serde::Serialize;
use crate::serde::Serializer;
use crate::builtin_doc::*;
use crate::dfs::*;
use crate::doc::*;
use crate::error::*;
use crate::fs::*;
use crate::mod_node::*;
use crate::utils::*;
use crate::version::*;

pub mod bitbucket;
pub mod github;
pub mod gitlab;

/// An User-Agent HTTP header for Curl.
pub const USER_AGENT_HTTP_HEADER: &'static str = concat!("User-Agent: Unlab-pkg/", env!("CARGO_PKG_VERSION"));

/// A printer trait.
///
/// The printer prints messages for a package manager. Some methods of printer has the done flag.
/// the flag should be set if an operation is completed, othersise the flag should be unset.
pub trait Print
{
    /// Prints the "Updating:" message.
    fn print_updating(&self);

    /// Prints the "Pre-installing:" message.
    fn print_pre_installing(&self);
    
    /// Prints the "Installing:" message.
    fn print_installing(&self);

    /// Prints the "Pre-removing:" message.
    fn print_pre_removing(&self);

    /// Prints the "Removing:" message.
    fn print_removing(&self);

    /// Prints the "Documenting:" message.
    fn print_documenting(&self);

    /// Prints the "Updating package ..." message.
    fn print_updating_pkg_versions(&self, name: &PkgName, is_done: bool);
    
    /// Prints the "Downloading package ..." message.
    fn print_downloading_pkg_file(&self, name: &PkgName, is_done: bool) -> Result<()>;

    /// Prints the "Downloading package ..." message with progress.
    fn print_downloading_pkg_file_with_progress(&self, name: &PkgName, byte_count: f64, total_byte_count: f64) -> Result<()>;
 
    /// Prints the "Extracting package ..." message. 
    fn print_extracting_pkg_file(&self, name: &PkgName, is_done: bool);
    
    /// Prints the "Checking dependent version requirements ..." message.
    fn print_checking_dependent_version_reqs(&self, is_done: bool);

    /// Prints the "Searching path conflicts ..." message.
    fn print_searching_path_conflicts(&self, is_done: bool);

    /// Prints the "Documenting package ..." message.
    fn print_documenting_pkg(&self, name: &PkgName, is_done: bool);
    
    /// Prints the "Installing package ..." message.
    fn print_installing_pkg(&self, name: &PkgName, is_done: bool);

    /// Prints the "Removing package ..." message.
    fn print_removing_pkg(&self, name: &PkgName, is_done: bool);

    /// Prints the "Removing package documentation ..." message.
    fn print_removing_pkg_doc(&self, name: &PkgName, is_done: bool);
    
    /// Prints the "Cleaning after installation ..." message.
    fn print_cleaning_after_install(&self, is_done: bool);

    /// Prints the "Cleaning before removal ..." messgage.
    fn print_cleaning_before_removal(&self, is_done: bool);

    /// Prints the "Cleaning after error ..." message.
    fn print_cleaning_after_error(&self, is_done: bool);

    /// Prints the "Cleaning ..." message.
    fn print_cleaning(&self, is_done: bool);
    
    /// Prints the newline character for an occurred error.
    fn print_lf_for_error(&self);
    
    /// Prints the error.
    fn eprint_error(&self, err: &Error);
}

/// A structure of empty printer.
///
/// The empty printer is dummy that doesn't print any messages.
#[derive(Copy, Clone, Debug)]
pub struct EmptyPrinter;

impl EmptyPrinter
{
    /// Creates an empty printer.
    pub fn new() -> Self
    { EmptyPrinter }
}

impl Print for EmptyPrinter
{
    fn print_updating(&self)
    {}

    fn print_pre_installing(&self)
    {}
    
    fn print_installing(&self)
    {}

    fn print_pre_removing(&self)
    {}

    fn print_removing(&self)
    {}

    fn print_documenting(&self)
    {}

    fn print_updating_pkg_versions(&self, _name: &PkgName, _is_done: bool)
    {}

    fn print_downloading_pkg_file(&self, _name: &PkgName, _is_done: bool) -> Result<()>
    { Ok(()) }

    fn print_downloading_pkg_file_with_progress(&self, _name: &PkgName, _byte_count: f64, _total_byte_count: f64) -> Result<()>
    { Ok(()) }
    
    fn print_extracting_pkg_file(&self, _name: &PkgName, _is_done: bool)
    {}
    
    fn print_checking_dependent_version_reqs(&self, _is_done: bool)
    {}

    fn print_searching_path_conflicts(&self, _is_done: bool)
    {}

    fn print_documenting_pkg(&self, _name: &PkgName, _is_done: bool)
    {}
    
    fn print_installing_pkg(&self, _name: &PkgName, _is_done: bool)
    {}

    fn print_removing_pkg(&self, _name: &PkgName, _is_done: bool)
    {}

    fn print_removing_pkg_doc(&self, _name: &PkgName, _is_done: bool)
    {}

    fn print_cleaning_after_install(&self, _is_done: bool)
    {}

    fn print_cleaning_before_removal(&self, _is_done: bool)
    {}

    fn print_cleaning_after_error(&self, _is_done: bool)
    {}

    fn print_cleaning(&self, _is_done: bool)
    {}
    
    fn print_lf_for_error(&self)
    {}
    
    fn eprint_error(&self, _err: &Error)
    {}
}

/// A structure of standard printer.
///
/// The standard printer prints messages to the standard output and error messages to the
/// standard error.
#[derive(Debug)]
pub struct StdPrinter
{
    byte_count: Mutex<f64>,
    has_lf_for_error: AtomicBool,
}

impl StdPrinter
{
    /// Creates a standard printer.
    pub fn new() -> Self
    { StdPrinter { byte_count: Mutex::new(0.0), has_lf_for_error: AtomicBool::new(false), } }
}

impl Print for StdPrinter
{
    fn print_updating(&self)
    { println!("Updating:"); }

    fn print_pre_installing(&self)
    { println!("Pre-installing:"); }
    
    fn print_installing(&self)
    { println!("Installing:"); }

    fn print_pre_removing(&self)
    { println!("Pre-removing:"); }

    fn print_removing(&self)
    { println!("Removing:"); }

    fn print_documenting(&self)
    { println!("Documenting:"); }

    fn print_updating_pkg_versions(&self, name: &PkgName, is_done: bool)
    {
        if is_done {
            println!(" done");
            self.has_lf_for_error.store(false, Ordering::SeqCst);
        } else {
            print!("Updating {} ...", name);
            let _res = stdout().flush();
            self.has_lf_for_error.store(true, Ordering::SeqCst);
        }
    }
    
    fn print_downloading_pkg_file(&self, name: &PkgName, is_done: bool) -> Result<()>
    {
        if is_done {
            let byte_count = {
                let byte_count_g = mutex_lock(&self.byte_count)?;
                *byte_count_g
            };
            println!("  progress: {}KiB (100%)", (byte_count / 1024.0).ceil());
        } else {
            {
                let mut byte_count_g = mutex_lock(&self.byte_count)?;
                *byte_count_g = 0.0;
            }
            println!("Downloading {} ...", name);
        }
        self.has_lf_for_error.store(false, Ordering::SeqCst);
        Ok(())
    }

    fn print_downloading_pkg_file_with_progress(&self, _name: &PkgName, byte_count: f64, total_byte_count: f64) -> Result<()>
    {
        if total_byte_count != 0.0 {
            print!("  progress: {}KiB ({}%)\r", (byte_count / 1024.0).ceil(), ((byte_count * 100.0) / total_byte_count).floor());
        } else {
            print!("  progress: {}KiB (?%)\r", (byte_count / 1024.0).ceil());
        }
        let _res = stdout().flush();
        self.has_lf_for_error.store(true, Ordering::SeqCst);
        {
            let mut byte_count_g = mutex_lock(&self.byte_count)?;
            *byte_count_g = byte_count;
        }
        Ok(())
    }
    
    fn print_extracting_pkg_file(&self, name: &PkgName, is_done: bool)
    {
        if is_done {
            println!(" done");
            self.has_lf_for_error.store(false, Ordering::SeqCst);
        } else {
            print!("Extracting {} ...", name);
            let _res = stdout().flush();
            self.has_lf_for_error.store(true, Ordering::SeqCst);
        }
    }
    
    fn print_checking_dependent_version_reqs(&self, is_done: bool)
    {
        if is_done {
            println!(" done");
            self.has_lf_for_error.store(false, Ordering::SeqCst);
        } else {
            print!("Checking dependent version requirements ...");
            let _res = stdout().flush();
            self.has_lf_for_error.store(true, Ordering::SeqCst);
        }
    }

    fn print_searching_path_conflicts(&self, is_done: bool)
    {
        if is_done {
            println!(" done");
            self.has_lf_for_error.store(false, Ordering::SeqCst);
        } else {
            print!("Searching path conflicts ...");
            let _res = stdout().flush();
            self.has_lf_for_error.store(true, Ordering::SeqCst);
        }
    }

    fn print_documenting_pkg(&self, name: &PkgName, is_done: bool)
    {
        if is_done {
            println!(" done");
            self.has_lf_for_error.store(false, Ordering::SeqCst);
        } else {
            print!("Documenting {} ...", name);
            let _res = stdout().flush();
            self.has_lf_for_error.store(true, Ordering::SeqCst);
        }
    }
    
    fn print_installing_pkg(&self, name: &PkgName, is_done: bool)
    {
        if is_done {
            println!(" done");
            self.has_lf_for_error.store(false, Ordering::SeqCst);
        } else {
            print!("Installing {} ...", name);
            let _res = stdout().flush();
            self.has_lf_for_error.store(true, Ordering::SeqCst);
        }
    }

    fn print_removing_pkg(&self, name: &PkgName, is_done: bool)
    {
        if is_done {
            println!(" done");
            self.has_lf_for_error.store(false, Ordering::SeqCst);
        } else {
            print!("Removing {} ...", name);
            let _res = stdout().flush();
            self.has_lf_for_error.store(true, Ordering::SeqCst);
        }
    }

    fn print_removing_pkg_doc(&self, name: &PkgName, is_done: bool)
    {
        if is_done {
            println!(" done");
            self.has_lf_for_error.store(false, Ordering::SeqCst);
        } else {
            print!("Removing {} documentation ...", name);
            let _res = stdout().flush();
            self.has_lf_for_error.store(true, Ordering::SeqCst);
        }
    }

    fn print_cleaning_after_install(&self, is_done: bool)
    {
        if is_done {
            println!(" done");
            self.has_lf_for_error.store(false, Ordering::SeqCst);
        } else {
            print!("Cleaning after installation ...");
            let _res = stdout().flush();
            self.has_lf_for_error.store(true, Ordering::SeqCst);
        }
    }

    fn print_cleaning_before_removal(&self, is_done: bool)
    {
        if is_done {
            println!(" done");
            self.has_lf_for_error.store(false, Ordering::SeqCst);
        } else {
            print!("Cleaning before removal ...");
            let _res = stdout().flush();
            self.has_lf_for_error.store(true, Ordering::SeqCst);
        }
    }
    
    fn print_cleaning_after_error(&self, is_done: bool)
    {
        if is_done {
            println!(" done");
            self.has_lf_for_error.store(false, Ordering::SeqCst);
        } else {
            self.print_lf_for_error();
            print!("Cleaning after error ...");
            let _res = stdout().flush();
            self.has_lf_for_error.store(true, Ordering::SeqCst);
        }
    }

    fn print_cleaning(&self, is_done: bool)
    {
        if is_done {
            println!(" done");
            self.has_lf_for_error.store(false, Ordering::SeqCst);
        } else {
            print!("Cleaning ...");
            let _res = stdout().flush();
            self.has_lf_for_error.store(true, Ordering::SeqCst);
        }
    }
    
    fn print_lf_for_error(&self)
    {
        if self.has_lf_for_error.swap(false, Ordering::SeqCst) {
            println!("");
        }
    }
    
    fn eprint_error(&self, err: &Error)
    {
        self.print_lf_for_error();
        eprintln!("{}", err);
    }
}

/// A source trait.
///
/// The source allows to access a package diractory. The package is automatically updated,
/// downaloded, and extracted by the source if it is necessery. Also, the packege source allows
/// to manually update the package versions. The package updating is called the updating of
/// package versions.
pub trait Source
{
    /// Updating the package versions.
    fn update(&mut self) -> Result<()>;
    
    /// Returns the package versions.
    fn versions(&mut self) -> Result<&BTreeSet<Version>>;
    
    /// Sets the current package version.
    fn set_current_version(&mut self, version: Version);

    /// Returns the package directory.
    fn dir(&mut self) -> Result<&Path>;
}

/// A trait of source factory.
///
/// The source factory creates source for the specified package.
pub trait SourceCreate
{
    /// Creates a source.
    fn create(&self, name: PkgName, old_name: Option<PkgName>, home_dir: PathBuf, work_dir: PathBuf, printer: Arc<dyn Print + Send + Sync>) -> Option<Box<dyn Source + Send + Sync>>;
}

/// A structure of package name.
///
/// The package name often consists an account and a repository name. The account often contains
/// the git hosting service and a login. The package name should contain one slash character.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct PkgName
{
    name: String,
}

impl PkgName
{
    /// Creates a package name.
    pub fn new(name: String) -> Self
    { PkgName { name, } }

    /// Parses the string slice to a package name.
    ///
    /// This method indeed checks whether the package name is correct.
    pub fn parse(s: &str) -> Result<Self>
    {
        if s.split('/').count() < 2 {
            return Err(Error::InvalidPkgName);
        }
        let ss = s.split('/');
        for t in ss {
            if t.is_empty() || t.contains('\\') || t == "." || t == ".." {
                return Err(Error::InvalidPkgName);
            }
        }
        Ok(Self::new(String::from(s)))
    }
    
    /// Returns the name as the string slice.
    pub fn name(&self) -> &str
    { self.name.as_str() }
    
    /// Converts the package name to a path buffer.
    pub fn to_path_buf(&self) -> PathBuf
    { PathBuf::from(self.name.replace('/', path::MAIN_SEPARATOR_STR)) }
}

impl fmt::Display for PkgName
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
    { write!(f, "{}", self.name) }
}

impl Serialize for PkgName
{
    fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
        where S: Serializer
    { serializer.serialize_str(format!("{}", self).as_str()) }
}

struct PkgNameVisitor;

impl<'de> Visitor<'de> for PkgNameVisitor
{
    type Value = PkgName;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result
    { write!(formatter, "a package name") }

    fn visit_str<E>(self, v: &str) -> result::Result<Self::Value, E>
        where E: de::Error
    {
        match PkgName::parse(v) {
            Ok(pkg_name) => Ok(pkg_name),
            Err(err) => Err(E::custom(format!("{}", err))),
        }
    }
}

impl<'de> Deserialize<'de> for PkgName
{
    fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
        where D: Deserializer<'de>
    { deserializer.deserialize_str(PkgNameVisitor) }
}

/// A structure of package information.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PkgInfo
{
    /// A package name.
    pub name: PkgName,
    /// A package description.
    pub description: Option<String>,
    /// A package authors.
    pub authors: Option<Vec<String>>,
    /// A package license.
    pub license: Option<String>,
    /// A required Unlab-gpu version.
    #[serde(rename = "unlab-gpu-version")]
    pub unlab_gpu_version: Option<VersionReq>,
}

/// An enumeration of source information of version.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum VersionSrcInfo
{
    /// A path to package directory.
    #[serde(rename = "dir")]
    Dir(String),
    /// A path to package archive.
    #[serde(rename = "file")]
    File(String),
    /// An URL to package archive.
    #[serde(rename = "url")]
    Url(String),
}

/// An enumeration of source information.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum SrcInfo
{
    /// A new package name. 
    #[serde(rename = "renamed")]
    Renamed(PkgName),
    /// Version with version source informations.
    #[serde(rename = "versions")]
    Versions(Arc<BTreeMap<Version, VersionSrcInfo>>),
}

/// A structure of package manifest.
///
/// The package manifest contains basic informations about package for example a package name,
/// package description, and package dependencies. These informations can be used to package
/// installation.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Manifest
{
    /// A package information.
    pub package: PkgInfo,
    /// Package dependencies.
    pub dependencies: Option<HashMap<PkgName, VersionReq>>,
    /// Package constraints.
    pub constraints: Option<Arc<HashMap<PkgName, VersionReq>>>,
    /// Custrom sources.
    pub sources: Option<Arc<HashMap<PkgName, SrcInfo>>>,
}

impl Manifest
{
    /// Creates a package manifest.
    pub fn new(name: PkgName) -> Self
    {
        Manifest {
            package: PkgInfo {
                name,
                description: None,
                authors: None,
                license: None,
                unlab_gpu_version: None,
            },
            dependencies: Some(HashMap::new()),
            constraints: None,
            sources: None,
        }
    }
    
    /// Reads a package manifest from the reader.
    pub fn read(r: &mut dyn Read) -> Result<Self>
    {
        let mut s = String::new();
        match r.read_to_string(&mut s) {
            Ok(_) => {
                match toml::from_str(s.as_str()) {
                    Ok(manifest) => Ok(manifest),
                    Err(err) => Err(Error::TomlDe(err)),
                }
            },
            Err(err) => Err(Error::Io(err)),
        }
    }

    /// Writes the package manifest to the writer.
    pub fn write(&self, w: &mut dyn Write) -> Result<()>
    {
        match toml::to_string(self) {
            Ok(s) => {
                match write!(w, "{}", s) {
                    Ok(()) => Ok(()),
                    Err(err) => Err(Error::Io(err)),
                }
            },
            Err(err) => Err(Error::TomlSer(err)),
        }
    }

    /// Loads a package manifest from the file.
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self>
    {
        match File::open(path) {
            Ok(mut file) => Self::read(&mut file),
            Err(err) => Err(Error::Io(err)),
        }
    }

    /// Loads a package manifest from the file if the file exists, otherwise this method returns
    /// `None`.
    pub fn load_opt<P: AsRef<Path>>(path: P) -> Result<Option<Self>>
    {
        match File::open(path) {
            Ok(mut file) => Ok(Some(Self::read(&mut file)?)),
            Err(err) if err.kind() == ErrorKind::NotFound => Ok(None), 
            Err(err) => Err(Error::Io(err)),
        }
    }

    /// Saves the package manifest to a file.
    pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<()>
    {
        match File::create(path) {
            Ok(mut file) => self.write(&mut file),
            Err(err) => Err(Error::Io(err)),
        }
    }
}

/// A structure of paths.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Paths
{
    /// Paths to binaries.
    pub bin: Vec<String>,
    /// Paths to libraries.
    pub lib: Vec<String>,
}

impl Paths
{
    /// Creates paths.
    pub fn new(bin: Vec<String>, lib: Vec<String>) -> Self
    { Paths { bin, lib, } }
    
    /// Reads paths from the reader.
    pub fn read(r: &mut dyn Read) -> Result<Self>
    {
        let mut s = String::new();
        match r.read_to_string(&mut s) {
            Ok(_) => {
                match toml::from_str(s.as_str()) {
                    Ok(paths) => Ok(paths),
                    Err(err) => Err(Error::TomlDe(err)),
                }
            },
            Err(err) => Err(Error::Io(err)),
        }
    }

    /// Writes the paths to the writer.
    pub fn write(&self, w: &mut dyn Write) -> Result<()>
    {
        match toml::to_string(self) {
            Ok(s) => {
                match write!(w, "{}", s) {
                    Ok(()) => Ok(()),
                    Err(err) => Err(Error::Io(err)),
                }
            },
            Err(err) => Err(Error::TomlSer(err)),
        }
    }
    
    /// Loads paths from the file.
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self>
    {
        match File::open(path) {
            Ok(mut file) => Self::read(&mut file),
            Err(err) => Err(Error::Io(err)),
        }
    }

    /// Loads paths from the file if the file exists, otherwise this method returns `None`.
    pub fn load_opt<P: AsRef<Path>>(path: P) -> Result<Option<Self>>
    {
        match File::open(path) {
            Ok(mut file) => Ok(Some(Self::read(&mut file)?)),
            Err(err) if err.kind() == ErrorKind::NotFound => Ok(None), 
            Err(err) => Err(Error::Io(err)),
        }
    }

    /// Saves the paths to a file.
    pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<()>
    {
        match File::create(path) {
            Ok(mut file) => self.write(&mut file),
            Err(err) => Err(Error::Io(err)),
        }
    }
}

/// A structure of documentation paths.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DocPaths
{
    /// Paths to documentation.
    pub doc: Vec<String>,
}

impl DocPaths
{
    /// Creates documentation paths.
    pub fn new(doc: Vec<String>) -> Self
    { DocPaths { doc, } }
    
    /// Reads documentation paths from the reader.
    pub fn read(r: &mut dyn Read) -> Result<Self>
    {
        let mut s = String::new();
        match r.read_to_string(&mut s) {
            Ok(_) => {
                match toml::from_str(s.as_str()) {
                    Ok(doc_paths) => Ok(doc_paths),
                    Err(err) => Err(Error::TomlDe(err)),
                }
            },
            Err(err) => Err(Error::Io(err)),
        }
    }

    /// Writes the documentation paths to the writer.
    pub fn write(&self, w: &mut dyn Write) -> Result<()>
    {
        match toml::to_string(self) {
            Ok(s) => {
                match write!(w, "{}", s) {
                    Ok(()) => Ok(()),
                    Err(err) => Err(Error::Io(err)),
                }
            },
            Err(err) => Err(Error::TomlSer(err)),
        }
    }
    
    /// Loads documentation paths from the file.
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self>
    {
        match File::open(path) {
            Ok(mut file) => Self::read(&mut file),
            Err(err) => Err(Error::Io(err)),
        }
    }

    /// Loads documentation paths from the file if the file exists, otherwise this method returns
    /// `None`.
    pub fn load_opt<P: AsRef<Path>>(path: P) -> Result<Option<Self>>
    {
        match File::open(path) {
            Ok(mut file) => Ok(Some(Self::read(&mut file)?)),
            Err(err) if err.kind() == ErrorKind::NotFound => Ok(None), 
            Err(err) => Err(Error::Io(err)),
        }
    }

    /// Saves the documentation paths to a file.
    pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<()>
    {
        match File::create(path) {
            Ok(mut file) => self.write(&mut file),
            Err(err) => Err(Error::Io(err)),
        }
    }
}

/// A structure of package versions.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Versions
{
    /// Package versions.
    pub versions: BTreeSet<Version>,
}

impl Versions
{
    /// Creates package versions.
    pub fn new(versions: BTreeSet<Version>) -> Self
    { Versions { versions, } }
    
    /// Reads package versions from the reader.
    pub fn read(r: &mut dyn Read) -> Result<Self>
    {
        let mut s = String::new();
        match r.read_to_string(&mut s) {
            Ok(_) => {
                match toml::from_str(s.as_str()) {
                    Ok(versions) => Ok(versions),
                    Err(err) => Err(Error::TomlDe(err)),
                }
            },
            Err(err) => Err(Error::Io(err)),
        }
    }

    /// Writes the package versions to the writer.
    pub fn write(&self, w: &mut dyn Write) -> Result<()>
    {
        match toml::to_string(self) {
            Ok(s) => {
                match write!(w, "{}", s) {
                    Ok(()) => Ok(()),
                    Err(err) => Err(Error::Io(err)),
                }
            },
            Err(err) => Err(Error::TomlSer(err)),
        }
    }
    
    /// Loads package versions from the file.
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self>
    {
        match File::open(path) {
            Ok(mut file) => Self::read(&mut file),
            Err(err) => Err(Error::Io(err)),
        }
    }

    /// Loads package versions from the file if the file exists, otherwise this method returns
    /// `None`.
    pub fn load_opt<P: AsRef<Path>>(path: P) -> Result<Option<Self>>
    {
        match File::open(path) {
            Ok(mut file) => Ok(Some(Self::read(&mut file)?)),
            Err(err) if err.kind() == ErrorKind::NotFound => Ok(None), 
            Err(err) => Err(Error::Io(err)),
        }
    }

    /// Saves the package versions to a file.
    pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<()>
    {
        match File::create(path) {
            Ok(mut file) => self.write(&mut file),
            Err(err) => Err(Error::Io(err)),
        }
    }
}

/// A strcuture of package configuration.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PkgConfig
{
    /// An account.
    pub account: Option<String>,
    /// A domain.
    pub domain: Option<String>,
}

impl PkgConfig
{
    /// Creates a package configuration.
    pub fn new(account: Option<String>, domain: Option<String>) -> Self
    { PkgConfig { account, domain, } }
    
    /// Reads a package configuration from the reader.
    pub fn read(r: &mut dyn Read) -> Result<Self>
    {
        let mut s = String::new();
        match r.read_to_string(&mut s) {
            Ok(_) => {
                match toml::from_str(s.as_str()) {
                    Ok(config) => Ok(config),
                    Err(err) => Err(Error::TomlDe(err)),
                }
            },
            Err(err) => Err(Error::Io(err)),
        }
    }

    /// Writes the package configuration to the writer.
    pub fn write(&self, w: &mut dyn Write) -> Result<()>
    {
        match toml::to_string(self) {
            Ok(s) => {
                match write!(w, "{}", s) {
                    Ok(()) => Ok(()),
                    Err(err) => Err(Error::Io(err)),
                }
            },
            Err(err) => Err(Error::TomlSer(err)),
        }
    }
    
    /// Loads a package configuration from the file.
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self>
    {
        match File::open(path) {
            Ok(mut file) => Self::read(&mut file),
            Err(err) => Err(Error::Io(err)),
        }
    }

    /// Loads a package configuration from the file if the file exists, otherwise this method
    /// returns `None`.
    pub fn load_opt<P: AsRef<Path>>(path: P) -> Result<Option<Self>>
    {
        match File::open(path) {
            Ok(mut file) => Ok(Some(Self::read(&mut file)?)),
            Err(err) if err.kind() == ErrorKind::NotFound => Ok(None), 
            Err(err) => Err(Error::Io(err)),
        }
    }

    /// Saves the package configurataion to a file.
    pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<()>
    {
        match File::create(path) {
            Ok(mut file) => self.write(&mut file),
            Err(err) => Err(Error::Io(err)),
        }
    }
}

/// Reads versions from the reader.
pub fn read_versions(r: &mut dyn Read) -> Result<HashMap<PkgName, Version>>
{
    let mut s = String::new();
    match r.read_to_string(&mut s) {
        Ok(_) => {
            match toml::from_str::<HashMap<PkgName, Version>>(s.as_str()) {
                Ok(src_infos) => Ok(src_infos),
                Err(err) => Err(Error::TomlDe(err)),
            }
        },
        Err(err) => Err(Error::Io(err)),
    }
}

/// Writes the versions to the writer.
pub fn write_versions(w: &mut dyn Write, versions: &HashMap<PkgName, Version>) -> Result<()>
{
    match toml::to_string(versions) {
        Ok(s) => {
            match write!(w, "{}", s) {
                Ok(()) => Ok(()),
                Err(err) => Err(Error::Io(err)),
            }
        },
        Err(err) => Err(Error::TomlSer(err)),
    }
}

/// Loads versions from the file.
pub fn load_versions<P: AsRef<Path>>(path: P) -> Result<HashMap<PkgName, Version>>
{
    match File::open(path) {
        Ok(mut file) => read_versions(&mut file),
        Err(err) => Err(Error::Io(err)),
    }
}

/// Loads versions from the file if the file exists, otherwise this function returns `None`.
pub fn load_opt_versions<P: AsRef<Path>>(path: P) -> Result<Option<HashMap<PkgName, Version>>>
{
    match File::open(path) {
        Ok(mut file) => Ok(Some(read_versions(&mut file)?)),
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),
        Err(err) => Err(Error::Io(err)),
    }
}

/// Loads versions from the file if the file exists, otherwise this function returns an empty
/// hash map.
pub fn load_versions_or_empty<P: AsRef<Path>>(path: P) -> Result<HashMap<PkgName, Version>>
{
    match File::open(path) {
        Ok(mut file) => read_versions(&mut file),
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(HashMap::new()),
        Err(err) => Err(Error::Io(err)),
    }
}

/// Saves the versions to a file.
pub fn save_versions<P: AsRef<Path>>(path: P, versions: &HashMap<PkgName, Version>) -> Result<()>
{
    match File::create(path) {
        Ok(mut file) => write_versions(&mut file, versions),
        Err(err) => Err(Error::Io(err)),
    }
}

/// Reads version requirements from the reader.
pub fn read_version_reqs(r: &mut dyn Read) -> Result<HashMap<PkgName, VersionReq>>
{
    let mut s = String::new();
    match r.read_to_string(&mut s) {
        Ok(_) => {
            match toml::from_str::<HashMap<PkgName, VersionReq>>(s.as_str()) {
                Ok(version_reqs) => Ok(version_reqs),
                Err(err) => Err(Error::TomlDe(err)),
            }
        },
        Err(err) => Err(Error::Io(err)),
    }
}

/// Writes the version requirements to the writer.
pub fn write_version_reqs(w: &mut dyn Write, version_reqs: &HashMap<PkgName, VersionReq>) -> Result<()>
{
    match toml::to_string(version_reqs) {
        Ok(s) => {
            match write!(w, "{}", s) {
                Ok(()) => Ok(()),
                Err(err) => Err(Error::Io(err)),
            }
        },
        Err(err) => Err(Error::TomlSer(err)),
    }
}

/// Loads version requirements from the file.
pub fn load_version_reqs<P: AsRef<Path>>(path: P) -> Result<HashMap<PkgName, VersionReq>>
{
    match File::open(path) {
        Ok(mut file) => read_version_reqs(&mut file),
        Err(err) => Err(Error::Io(err)),
    }
}

/// Loads version requirements from the file if the file exists, otherwise this function returns
/// `None`.
pub fn load_opt_version_reqs<P: AsRef<Path>>(path: P) -> Result<Option<HashMap<PkgName, VersionReq>>>
{
    match File::open(path) {
        Ok(mut file) => Ok(Some(read_version_reqs(&mut file)?)),
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),
        Err(err) => Err(Error::Io(err)),
    }
}

/// Loads version requirements from the file if the file exists, otherwise this function returns
/// an empty hash map.
pub fn load_version_reqs_or_empty<P: AsRef<Path>>(path: P) -> Result<HashMap<PkgName, VersionReq>>
{
    match File::open(path) {
        Ok(mut file) => read_version_reqs(&mut file),
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(HashMap::new()),
        Err(err) => Err(Error::Io(err)),
    }
}

/// Saves the version requirements to a file.
pub fn save_version_reqs<P: AsRef<Path>>(path: P, version_reqs: &HashMap<PkgName, VersionReq>) -> Result<()>
{
    match File::create(path) {
        Ok(mut file) => write_version_reqs(&mut file, version_reqs),
        Err(err) => Err(Error::Io(err)),
    }
}

/// Reads source informations from the reader.
pub fn read_src_infos(r: &mut dyn Read) -> Result<HashMap<PkgName, SrcInfo>>
{
    let mut s = String::new();
    match r.read_to_string(&mut s) {
        Ok(_) => {
            match toml::from_str::<HashMap<PkgName, SrcInfo>>(s.as_str()) {
                Ok(src_infos) => Ok(src_infos),
                Err(err) => Err(Error::TomlDe(err)),
            }
        },
        Err(err) => Err(Error::Io(err)),
    }
}

/// Writes the source informations to the writer.
pub fn write_src_infos(w: &mut dyn Write, src_infos: &HashMap<PkgName, SrcInfo>) -> Result<()>
{
    match toml::to_string(src_infos) {
        Ok(s) => {
            match write!(w, "{}", s) {
                Ok(()) => Ok(()),
                Err(err) => Err(Error::Io(err)),
            }
        },
        Err(err) => Err(Error::TomlSer(err)),
    }
}

/// Loads source informations from the file.
pub fn load_src_infos<P: AsRef<Path>>(path: P) -> Result<HashMap<PkgName, SrcInfo>>
{
    match File::open(path) {
        Ok(mut file) => read_src_infos(&mut file),
        Err(err) => Err(Error::Io(err)),
    }
}

/// Loads source informations from the file if the file exists, otherwise this function returns
/// `None`.
pub fn load_opt_src_infos<P: AsRef<Path>>(path: P) -> Result<Option<HashMap<PkgName, SrcInfo>>>
{
    match File::open(path) {
        Ok(mut file) => Ok(Some(read_src_infos(&mut file)?)),
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),
        Err(err) => Err(Error::Io(err)),
    }
}

/// Loads source informations from the file if the file exists, otherwise this function returns
/// an empty hash map.
pub fn load_src_infos_or_empty<P: AsRef<Path>>(path: P) -> Result<HashMap<PkgName, SrcInfo>>
{
    match File::open(path) {
        Ok(mut file) => read_src_infos(&mut file),
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(HashMap::new()),
        Err(err) => Err(Error::Io(err)),
    }
}

/// Saves the source informations to a file.
pub fn save_src_infos<P: AsRef<Path>>(path: P, src_infos: &HashMap<PkgName, SrcInfo>) -> Result<()>
{
    match File::create(path) {
        Ok(mut file) => write_src_infos(&mut file, src_infos),
        Err(err) => Err(Error::Io(err)),
    }
}

/// Converts the tag name to a version.
pub fn tag_name_to_version(tag_name: &str) -> Option<Version>
{
    if tag_name.starts_with("v") {
        match Version::parse(&tag_name[1..]) {
            Ok(version) => Some(version),
            Err(_) => None,
        }
    } else {
        None
    }
}

/// Converts the version to a tag name.
pub fn version_to_tag_name(version: &Version) -> String
{ format!("v{}", version) }

/// Returns a path to the variable directory.
pub fn var_dir<P: AsRef<Path>>(home_dir: P) -> PathBuf
{
    let mut dir = PathBuf::from(home_dir.as_ref());
    dir.push("var");
    dir
}

/// Returns a path to the temporary director.
pub fn tmp_dir<P: AsRef<Path>>(work_dir: P) -> PathBuf
{
    let mut dir = PathBuf::from(work_dir.as_ref());
    dir.push("tmp");
    dir
}

/// Returns a path to the index directory.
pub fn index_dir<P: AsRef<Path>>(home_dir: P) -> PathBuf
{
    let mut dir = var_dir(home_dir);
    dir.push("index");
    dir
}

/// Returns a path to the cache directory.
pub fn cache_dir<P: AsRef<Path>>(home_dir: P) -> PathBuf
{
    let mut dir = var_dir(home_dir);
    dir.push("cache");
    dir
}

/// Returns a path to the index directory for the specified package.
pub fn pkg_index_dir<P: AsRef<Path>>(home_dir: P, name: &PkgName) -> PathBuf
{
    let mut dir = index_dir(home_dir);
    dir.push(name.to_path_buf());
    dir
}

/// Returns a path to the variable directory for the specified package.
pub fn pkg_cache_dir<P: AsRef<Path>>(home_dir: P, name: &PkgName, version: &Version) -> PathBuf
{
    let mut dir = cache_dir(home_dir);
    dir.push(name.to_path_buf());
    dir.push(format!("{}", version).as_str());
    dir
}

/// Returns a path to the temporary directory for the specified package.
pub fn pkg_tmp_dir<P: AsRef<Path>>(work_dir: P, name: &PkgName, version: &Version) -> PathBuf
{
    let mut dir = tmp_dir(work_dir);
    dir.push(name.to_path_buf());
    dir.push(format!("{}", version).as_str());
    dir
}

/// Returns a path to the package directory while extracting.
pub fn pkg_part_dir<P: AsRef<Path>>(work_dir: P, name: &PkgName, version: &Version) -> PathBuf
{
    let mut dir = pkg_tmp_dir(work_dir, name, version);
    dir.push("dir.part");
    dir
}

/// Returns a path to the package directory after extracting.
pub fn pkg_dir<P: AsRef<Path>>(work_dir: P, name: &PkgName, version: &Version) -> PathBuf
{
    let mut dir = pkg_tmp_dir(work_dir, name, version);
    dir.push("dir");
    dir
}

fn io_res_remove_and_rename_for_updated_pkg_versions(new_part_path: &Path, new_path: &Path, path: &Path) -> io::Result<()>
{
    recursively_remove(new_path, true)?;
    rename(new_part_path, new_path)?;
    recursively_remove(path, true)?;
    rename(new_path, path)?;
    Ok(())
}

fn io_res_remove_and_rename_for_unupdated_pkg_versions(new_part_path: &Path, new_path: &Path, path: &Path) -> io::Result<()>
{
    recursively_remove(new_part_path, true)?;
    match fs::metadata(new_path) {
        Ok(_) => {
            recursively_remove(path, true)?;
            rename(new_path, path)?;
            Ok(())
        },
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(()), 
        Err(err) => Err(err),
    }
}

/// Updates the package versions for the specified package.
///
/// This method overwrites the package versions if the package versions exist and the update flag
/// is set, otherwise the package versios isn't overwritten.
pub fn update_pkg_versions<P: AsRef<Path>, F, G>(name: &PkgName, old_name: &Option<PkgName>, home_dir: P, is_update: bool, printer: &Arc<dyn Print + Send + Sync>, f: F, g: G) -> Result<BTreeSet<Version>>
    where F: FnOnce() -> result::Result<curl::easy::Easy, curl::Error>,
        G: FnOnce(&[u8]) -> Result<BTreeSet<Version>>
{
    let path_buf = pkg_index_dir(home_dir.as_ref(), old_name.as_ref().unwrap_or(name));
    let mut new_part_versions_path_buf = path_buf.clone();
    new_part_versions_path_buf.push("versions.toml.new.part");
    let mut new_versions_path_buf = path_buf.clone();
    new_versions_path_buf.push("versions.toml.new");
    let mut versions_path_buf = path_buf.clone();
    versions_path_buf.push("versions.toml");
    let is_to_update = match fs::metadata(versions_path_buf.as_path()) {
        Ok(_) => is_update,
        Err(err) if err.kind() == ErrorKind::NotFound => {
            match fs::metadata(new_versions_path_buf.as_path()) {
                Ok(_) => is_update,
                Err(err) if err.kind() == ErrorKind::NotFound => true,
                Err(err) => return Err(Error::Io(err)),
            }
        },
        Err(err) => return Err(Error::Io(err)),
    };
    if is_to_update {
        printer.print_updating_pkg_versions(name, false);
        match recursively_remove(new_part_versions_path_buf.as_path(), true) {
            Ok(()) => (),
            Err(err) => return Err(Error::Io(err)),
        }
        let data: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));
        let data2 = data.clone();
        let mut easy = match f() {
            Ok(tmp_easy) => tmp_easy,
            Err(err) => return Err(Error::Curl(err)),
        };
        match easy.fail_on_error(true) {
            Ok(()) => (),
            Err(err) => return Err(Error::Curl(err)),
        }
        match easy.write_function(move |buf| {
                let mut data2_g = data2.lock().unwrap();
                data2_g.extend_from_slice(buf);
                Ok(buf.len())
        }) {
            Ok(()) => (),
            Err(err) => return Err(Error::Curl(err)),
        }
        match easy.perform() {
            Ok(()) => (),
            Err(err) => return Err(Error::Curl(err)),
        }
        let versions = {
            let mut data_g = mutex_lock(&data)?;
            let res = g(data_g.as_slice());
            data_g.clear();
            Versions::new(res?)
        };
        match create_dir_all(path_buf.as_path()) {
            Ok(()) => (),
            Err(err) => return Err(Error::Io(err)),
        }
        versions.save(new_part_versions_path_buf.as_path())?;
        match io_res_remove_and_rename_for_updated_pkg_versions(new_part_versions_path_buf.as_path(), new_versions_path_buf.as_path(), versions_path_buf.as_path()) {
            Ok(()) => (),
            Err(err) => return Err(Error::Io(err)),
        }
        printer.print_updating_pkg_versions(name, true);
    } else {
        match io_res_remove_and_rename_for_unupdated_pkg_versions(new_part_versions_path_buf.as_path(), new_versions_path_buf.as_path(), versions_path_buf.as_path()) {
            Ok(()) => (),
            Err(err) => return Err(Error::Io(err)),
        }
    }
    Ok(Versions::load(versions_path_buf)?.versions)
}

fn curl_res_download_pkg_file(name: &PkgName, url: &str, part_file_path: &Path, printer: &Arc<dyn Print + Send + Sync>) -> result::Result<(), curl::Error>
{
    let mut easy = curl::easy::Easy::new();
    easy.url(url)?;
    let mut http_headers = List::new();
    http_headers.append(USER_AGENT_HTTP_HEADER)?;
    easy.http_headers(http_headers)?;
    easy.follow_location(true)?;
    easy.fail_on_error(true)?;
    easy.progress(true)?;
    let name2 = name.clone();
    let printer2 = printer.clone();
    easy.progress_function(move |total_byte_count, byte_count, _, _| {
            match printer2.print_downloading_pkg_file_with_progress(&name2, byte_count, total_byte_count) {
                Ok(()) => (),
                Err(err) => printer2.eprint_error(&err),
            }
            true
    })?;
    let part_file_path_buf = PathBuf::from(part_file_path);
    let printer2 = printer.clone();
    easy.write_function(move |buf| {
            match File::options().create(true).append(true).open(part_file_path_buf.as_path()) {
                Ok(mut file) => {
                    match file.write_all(buf) {
                        Ok(()) => (),
                        Err(err) => printer2.eprint_error(&Error::Io(err)),
                    }
                },
                Err(err) => printer2.eprint_error(&Error::Io(err)),
            }
            Ok(buf.len())
    })?;
    easy.perform()
}

/// Downloads the package archive for the specified package.
///
/// If the old package name is passed, this function writes the package archive in the directory
/// for the old package name.
pub fn download_pkg_file<P: AsRef<Path>>(name: &PkgName, old_name: &Option<PkgName>, version: &Version, url: &str, home_dir: P, printer: &Arc<dyn Print + Send + Sync>) -> Result<PathBuf>
{
    let path_buf = pkg_cache_dir(home_dir.as_ref(), old_name.as_ref().unwrap_or(name), version);
    let first_url_part = match url.split_once('?') {
        Some((tmp_first_url_part, _)) => tmp_first_url_part,
        None => url,
    };
    let (part_file_name, file_name) = if first_url_part.ends_with(".zip") {
        ("file.zip.part", "file.zip")
    } else if first_url_part.ends_with(".tar.gz") {
        ("file.tar.gz.part", "file.tar.gz")
    } else if first_url_part.ends_with(".tar.bz2") {
        ("file.tar.bz2.part", "file.tar.bz2")
    } else if first_url_part.ends_with(".tar.xz") {
        ("file.tar.xz.part", "file.tar.xz")
    } else if first_url_part.ends_with(".tar") {
        ("file.tar.part", "file.tar")
    } else {
        ("file.part", "file")
    };
    let mut part_file_path_buf = path_buf.clone();
    part_file_path_buf.push(part_file_name);
    let mut file_path_buf = path_buf.clone();
    file_path_buf.push(file_name);
    match fs::metadata(file_path_buf.as_path()) {
        Ok(_) => (),
        Err(err) if err.kind() == ErrorKind::NotFound => {
            printer.print_downloading_pkg_file(name, false)?;
            match create_dir_all(path_buf.as_path()) {
                Ok(()) => (),
                Err(err) => return Err(Error::Io(err)),
            }
            match recursively_remove(part_file_path_buf.as_path(), true) {
                Ok(()) => (),
                Err(err) => return Err(Error::Io(err)),
            }
            match curl_res_download_pkg_file(name, url, part_file_path_buf.as_path(), printer) {
                Ok(()) => (),
                Err(err) => return Err(Error::Curl(err)),
            }
            match rename(part_file_path_buf.as_path(), file_path_buf.as_path()) {
                Ok(()) => (),
                Err(err) => return Err(Error::Io(err)),
            }
            printer.print_downloading_pkg_file(name, true)?;
        },
        Err(err) => return Err(Error::Io(err)),
    }
    Ok(file_path_buf)
}

/// Extracts the package archive for the specified package.
pub fn extract_pkg_file<P: AsRef<Path>, F>(name: &PkgName, version: &Version, work_dir: P, printer: &Arc<dyn Print + Send + Sync>, f: F) -> Result<PathBuf>
    where F: FnOnce() -> Result<PathBuf>
{
    let part_path_buf = pkg_part_dir(work_dir.as_ref(), name, version);
    let path_buf = pkg_dir(work_dir.as_ref(), name, version);
    match fs::metadata(path_buf.as_path()) {
        Ok(_) => (),
        Err(err) if err.kind() == ErrorKind::NotFound => {
            let archive_path_buf = f()?;
            printer.print_extracting_pkg_file(name, false);
            match recursively_remove(part_path_buf.as_path(), true) {
                Ok(()) => (),
                Err(err) => return Err(Error::Io(err)),
            }
            match create_dir_all(part_path_buf.as_path()) {
                Ok(()) => (),
                Err(err) => return Err(Error::Io(err)),
            }
            if archive_path_buf.to_string_lossy().into_owned().ends_with(".zip") {
                match File::open(archive_path_buf) {
                    Ok(file) => {
                        let mut r = BufReader::new(file); 
                        let mut archive = match ZipArchive::new(&mut r) {
                            Ok(tmp_archive) => tmp_archive,
                            Err(err) => return Err(Error::Zip(Box::new(err))),
                        };
                        match archive.extract(part_path_buf.as_path()) {
                            Ok(()) => (),
                            Err(err) => return Err(Error::Zip(Box::new(err))),
                        }
                    },
                    Err(err) => return Err(Error::Io(err)),
                }
            } else if archive_path_buf.to_string_lossy().into_owned().ends_with(".tar.gz") {
                match File::open(archive_path_buf) {
                    Ok(file) => {
                        let mut r = BufReader::new(file); 
                        let mut decoder = GzDecoder::new(&mut r);
                        let mut archive = tar::Archive::new(&mut decoder);
                        match archive.unpack(part_path_buf.as_path()) {
                            Ok(()) => (),
                            Err(err) => return Err(Error::Io(err)),
                        }
                    },
                    Err(err) => return Err(Error::Io(err)),
                }
            } else if archive_path_buf.to_string_lossy().into_owned().ends_with(".tar.bz2") {
                match File::open(archive_path_buf) {
                    Ok(file) => {
                        let mut r = BufReader::new(file); 
                        let mut decoder = BzDecoder::new(&mut r);
                        let mut archive = tar::Archive::new(&mut decoder);
                        match archive.unpack(part_path_buf.as_path()) {
                            Ok(()) => (),
                            Err(err) => return Err(Error::Io(err)),
                        }
                    },
                    Err(err) => return Err(Error::Io(err)),
                }
            } else if archive_path_buf.to_string_lossy().into_owned().ends_with(".tar.xz") {
                match File::open(archive_path_buf) {
                    Ok(file) => {
                        let mut r = BufReader::new(file); 
                        let mut decoder = XzDecoder::new(&mut r);
                        let mut archive = tar::Archive::new(&mut decoder);
                        match archive.unpack(part_path_buf.as_path()) {
                            Ok(()) => (),
                            Err(err) => return Err(Error::Io(err)),
                        }
                    },
                    Err(err) => return Err(Error::Io(err)),
                }
            } else {
                match File::open(archive_path_buf) {
                    Ok(file) => {
                        let mut r = BufReader::new(file); 
                        let mut archive = tar::Archive::new(&mut r);
                        match archive.unpack(part_path_buf.as_path()) {
                            Ok(()) => (),
                            Err(err) => return Err(Error::Io(err)),
                        }
                    },
                    Err(err) => return Err(Error::Io(err)),
                }
            }
            match rename(part_path_buf.as_path(), path_buf.as_path()) {
                Ok(()) => (),
                Err(err) => return Err(Error::Io(err)),
            }
            printer.print_extracting_pkg_file(name, true);
        },
        Err(err) => return Err(Error::Io(err)),
    }
    match only_one_dir_in_dir(path_buf.as_path()) {
        Ok(Some(only_one_dir)) => Ok(only_one_dir),
        Ok(None) => Ok(path_buf),
        Err(err) => Err(Error::Io(err)),
    }
}

/// A structure of custom source.
///
/// The custom source is defined by an user. The user can specify the package versions and how to
/// get a package.
#[derive(Clone)]
pub struct CustomSrc
{
    name: PkgName,
    home_dir: PathBuf,
    work_dir: PathBuf,
    version_src_infos: Arc<BTreeMap<Version, VersionSrcInfo>>,
    printer: Arc<dyn Print + Send + Sync>,
    versions: Arc<BTreeSet<Version>>,
    current_version: Option<Version>,
    dir: Option<PathBuf>,
}

impl CustomSrc
{
    /// Creates a custom source.
    pub fn new(name: PkgName, home_dir: PathBuf, work_dir: PathBuf, version_src_infos: Arc<BTreeMap<Version, VersionSrcInfo>>, printer: Arc<dyn Print + Send + Sync>) -> Self
    {
        let versions: Arc<BTreeSet<Version>> = Arc::new(version_src_infos.keys().map(|v| v.clone()).collect()); 
        CustomSrc {
            name,
            home_dir,
            work_dir,
            version_src_infos,
            printer,
            versions,
            current_version: None,
            dir: None,
        }
    }
    
    /// Returns the package name.
    pub fn name(&self) -> &PkgName
    { &self.name }

    /// Returns the path to the Unlab-gpu home directory.
    pub fn home_dir(&self) -> &Path
    { self.home_dir.as_path() }

    /// Returns the path to the work directory of current package.
    pub fn work_dir(&self) -> &Path
    { self.work_dir.as_path() }

    /// Returns the source informations of versions.
    pub fn version_src_infos(&self) -> &Arc<BTreeMap<Version, VersionSrcInfo>>
    { &self.version_src_infos }

    /// Returns the printer.
    pub fn printer(&self) -> &Arc<dyn Print + Send + Sync>
    { &self.printer }

    /// Returns the current package version.
    pub fn current_version(&self) -> Option<&Version>
    { 
        match &self.current_version {
            Some(current_version) => Some(current_version),
            None => None,
        }
    }
}

impl Source for CustomSrc
{
    fn update(&mut self) -> Result<()>
    { Ok(()) }
    
    fn versions(&mut self) -> Result<&BTreeSet<Version>>
    { Ok(&self.versions) }
    
    fn set_current_version(&mut self, version: Version)
    { self.current_version = Some(version); }
    
    fn dir(&mut self) -> Result<&Path>
    {
        if self.dir.is_none() {
            match &self.current_version {
                Some(current_version) => {
                    match self.version_src_infos.get(current_version) {
                        Some(version_src_info) => {
                            self.dir = match version_src_info {
                                VersionSrcInfo::Dir(tmp_dir) => Some(PathBuf::from(tmp_dir.replace('/', path::MAIN_SEPARATOR_STR))),
                                VersionSrcInfo::File(file) => Some(extract_pkg_file(&self.name, current_version, &self.work_dir, &self.printer, || Ok(PathBuf::from(file.replace('/', path::MAIN_SEPARATOR_STR))))?),
                                VersionSrcInfo::Url(url) => {
                                    Some(extract_pkg_file(&self.name, current_version, &self.work_dir, &self.printer, || {
                                            download_pkg_file(&self.name, &None, current_version, url, &self.home_dir, &self.printer)
                                    })?)
                                },
                            };
                        },
                        None => return Err(Error::PkgName(self.name.clone(), String::from("not found version"))),
                    }
                },
                None => return Err(Error::PkgName(self.name.clone(), String::from("no current version"))),
            }
        }
        Ok(self.dir.as_ref().unwrap().as_path())
    }
}

#[derive(Clone, Debug)]
struct Pkg
{
    dir: Option<PathBuf>,
    info_dir: Option<PathBuf>,
    new_part_info_dir: Option<PathBuf>,
    is_added_by_dependent: bool,
    has_new_version_from_bucket: bool,
}

impl Pkg
{
    fn new() -> Self
    {
        Pkg {
            dir: Some(PathBuf::from(".")),
            info_dir: None,
            new_part_info_dir: None,
            is_added_by_dependent: false,
            has_new_version_from_bucket: true,
        }
    }

    fn io_res_copy_info_files(dir: &Option<PathBuf>, info_dir: &PathBuf, new_part_info_dir: &PathBuf) -> io::Result<()>
    {
        create_dir_all(new_part_info_dir)?;
        match dir {
            Some(dir) => {
                let mut src_manifest_file = dir.clone();
                src_manifest_file.push("Unlab.toml");
                let mut dst_manifest_file = new_part_info_dir.clone();
                dst_manifest_file.push("manifest.toml");
                copy(src_manifest_file, dst_manifest_file)?;
            },
            None => (),
        }
        let mut src_dependents_file = info_dir.clone();
        src_dependents_file.push("dependents.toml");
        let mut dst_dependents_file = new_part_info_dir.clone();
        dst_dependents_file.push("dependents.toml");
        match fs::metadata(dst_dependents_file.as_path()) {
            Ok(_) => (),
            Err(err) if err.kind() == ErrorKind::NotFound => {
                match copy(src_dependents_file.as_path(), dst_dependents_file.as_path()) {
                    Ok(_) => (),
                    Err(err) if err.kind() == ErrorKind::NotFound => {
                        let _res = File::create(dst_dependents_file)?;
                    },
                    Err(err) => return Err(err),
                }
            },
            Err(err) => return Err(err),
        }
        Ok(())
    }

    fn copy_info_files(dir: &Option<PathBuf>, info_dir: &PathBuf, new_part_info_dir: &PathBuf) -> Result<()>
    {
        match Self::io_res_copy_info_files(dir, info_dir, new_part_info_dir) {
            Ok(()) => Ok(()),
            Err(err) => Err(Error::Io(err)),
        }
    }
    
    fn new_with_copying_and_flags(dir: Option<PathBuf>, info_dir: PathBuf, new_part_info_dir: PathBuf, is_added_by_dependent: bool, is_new_version_from_bucket: bool) -> Result<Self>
    {
        Self::copy_info_files(&dir, &info_dir, &new_part_info_dir)?;
        Ok(Pkg {
                dir,
                info_dir: Some(info_dir),
                new_part_info_dir: Some(new_part_info_dir),
                is_added_by_dependent,
                has_new_version_from_bucket: is_new_version_from_bucket,
        })
    }

    fn new_with_copying(dir: Option<PathBuf>, info_dir: PathBuf, new_part_info_dir: PathBuf) -> Result<Self>
    { Self::new_with_copying_and_flags(dir, info_dir, new_part_info_dir, false, true) }

    fn new_without_copying_with_flags(info_dir: PathBuf, is_added_by_dependent: bool, is_new_version_from_bucket: bool) -> Self
    {
        Pkg {
            dir: None,
            info_dir: Some(info_dir),
            new_part_info_dir: None,
            is_added_by_dependent,
            has_new_version_from_bucket: is_new_version_from_bucket,
        }
    }

    fn new_without_copying(info_dir: PathBuf) -> Self
    { Self::new_without_copying_with_flags(info_dir, false, true) }
    
    fn old_manifest(&self) -> Result<Option<Manifest>>
    {
        match &self.new_part_info_dir {
            Some(new_part_info_dir) => {
                match &self.info_dir {
                    Some(info_dir) => {
                        let mut new_manifest_file = new_part_info_dir.clone();
                        new_manifest_file.push("manifest.toml");
                        let is_new_manifest = match fs::metadata(new_manifest_file) {
                            Ok(_) => true,
                            Err(err) if err.kind() == ErrorKind::NotFound => false,
                            Err(err) => return Err(Error::Io(err)),
                        };
                        if is_new_manifest {
                            let mut old_manifest_file = info_dir.clone();
                            old_manifest_file.push("manifest.toml");
                            match Manifest::load(old_manifest_file) {
                                Ok(tmp_old_manifest) => Ok(Some(tmp_old_manifest)),
                                Err(Error::Io(io_err)) if io_err.kind() == ErrorKind::NotFound => Ok(None),
                                Err(err) => Err(err),
                            }
                        } else {
                            Ok(None)
                        }
                    },
                    None => Ok(None),
                }
            },
            None => Ok(None),
        }
    }

    fn manifest(&self) -> Result<Manifest>
    {
        let mut manifest = match &self.new_part_info_dir {
            Some(new_part_info_dir) => {
                let mut manifest_file = new_part_info_dir.clone();
                manifest_file.push("manifest.toml");
                Manifest::load_opt(manifest_file)?
            },
            None => None
        };
        if manifest.is_none() {
            manifest = match &self.info_dir {
                Some(info_dir) => {
                    let mut manifest_file = info_dir.clone();
                    manifest_file.push("manifest.toml");
                    Manifest::load_opt(manifest_file)?
                },
                None => None,
            };
        }
        if manifest.is_none() {
            match &self.dir {
                Some(dir) => {
                    let mut manifest_file = dir.clone();
                    manifest_file.push("Unlab.toml");
                    match Manifest::load_opt(manifest_file)? {
                        Some(manifest) => Ok(manifest),
                        None => Err(Error::Pkg(String::from("no manifest file"))),
                    }
                },
                None => Err(Error::Pkg(String::from("no manifest file"))),
            }
        } else {
            match manifest {
                Some(manifest) => Ok(manifest),
                None => Err(Error::Pkg(String::from("no manifest file"))),
            }
        }
    }

    fn dependents(&self) -> Result<HashMap<PkgName, VersionReq>>
    {
        match &self.new_part_info_dir {
            Some(new_part_info_dir) => {
                let mut dependents_file = new_part_info_dir.clone();
                dependents_file.push("dependents.toml");
                load_version_reqs_or_empty(dependents_file)
            },
            None => Ok(HashMap::new()),
        }
    }

    fn save_dependents(&self, dependents: &HashMap<PkgName, VersionReq>) -> Result<()>
    {
        match &self.new_part_info_dir {
            Some(new_part_info_dir) => {
                let mut dependents_file = new_part_info_dir.clone();
                dependents_file.push("dependents.toml");
                save_version_reqs(dependents_file, dependents)
            },
            None => Ok(()),
        }
    }

    fn is_to_install(&self) -> Result<bool>
    {
        match &self.new_part_info_dir {
            Some(new_part_info_dir) => {
                let mut manifest_file = new_part_info_dir.clone();
                manifest_file.push("manifest.toml");
                match fs::metadata(manifest_file) {
                    Ok(_) => Ok(true),
                    Err(err) if err.kind() == ErrorKind::NotFound => Ok(false),
                    Err(err) => Err(Error::Io(err)),
                }
            },
            None => Ok(false),
        }
    }
}

fn db_tx(db: &DB, writable: bool) -> Result<Tx<'_>>
{
    match db.tx(writable) {
        Ok(tx) => Ok(tx),
        Err(err) => Err(Error::Jammdb(Box::new(err))),
    }
}

fn tx_get_or_create_bucket<'b, 'tx, T: ToBytes<'tx>>(tx: &'b Tx<'tx>, name: T) -> Result<Bucket<'b, 'tx>>
{
    match tx.get_or_create_bucket(name) {
        Ok(bucket) => Ok(bucket),
        Err(err) => Err(Error::Jammdb(Box::new(err))),
    }
}

/// Returns the factories of default sources.
pub fn default_src_factories() -> Vec<Arc<dyn SourceCreate + Send + Sync>>
{
    vec![
        Arc::new(github::GitHubSrcFactory::new()),
        Arc::new(gitlab::GitLabSrcFactory::new()),
        Arc::new(bitbucket::BitbucketSrcFactory::new())
    ]
}

fn tx_delete_bucket<'tx, T: ToBytes<'tx>>(tx: &Tx<'tx>, name: T) -> Result<()>
{
    match tx.delete_bucket(name) {
        Ok(()) => Ok(()),
        Err(err) => Err(Error::Jammdb(Box::new(err))),
    }
}

fn tx_commit<'tx>(tx: Tx<'tx>) -> Result<()>
{
    match tx.commit() {
        Ok(()) => Ok(()),
        Err(err) => Err(Error::Jammdb(Box::new(err))),
    }
}

fn bucket_put<'a, 'b, 'tx, T: ToBytes<'tx>, S: ToBytes<'tx>>(bucket: &'a Bucket<'b, 'tx>, key: T, value: S) -> Result<Option<KVPair<'b, 'tx>>>
{
    match bucket.put(key, value) {
        Ok(kv_pair) => Ok(kv_pair),
        Err(err) => Err(Error::Jammdb(Box::new(err))),
    }
}

fn max_pkg_version(versions: &BTreeSet<Version>, version_req: Option<&VersionReq>, constraint: Option<&VersionReq>, locked_version: Option<&Version>) -> Option<Version>
{
    let mut version_reqs: Vec<&VersionReq> = Vec::new();
    match version_req {
        Some(version_req) => version_reqs.push(version_req),
        None => (),
    }
    match constraint {
        Some(constraint) => version_reqs.push(constraint),
        None => (),
    }
    match locked_version {
        Some(locked_version) => {
            match versions.get(locked_version) {
                Some(version) if version_reqs.iter().all(|r| r.matches(version)) => return Some(version.clone()),
                _ => (),
            }
        },
        None => (),
    }
    let mut max_version: Option<Version> = None;
    for version in versions {
        if version_reqs.iter().all(|r| r.matches(version)) {
            max_version = Some(version.clone());
        }
    }
    max_version
}

fn check_dir(path: &Path, err_msg: &str) -> Result<()>
{
    match fs::metadata(path) {
        Ok(metadata) if metadata.is_dir() => Ok(()),
        Ok(_) => Err(Error::Pkg(String::from(err_msg))),
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
        Err(err) => Err(Error::Io(err)),
    }
}

fn check_dir_for_pkg(path: &Path, name: &PkgName, err_msg: &str) -> Result<()>
{
    match fs::metadata(path) {
        Ok(metadata) if metadata.is_dir() => Ok(()),
        Ok(_) => Err(Error::PkgName(name.clone(), String::from(err_msg))),
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
        Err(err) => Err(Error::Io(err)),
    }
}

/// A structure of package manager.
///
/// The package manager is used to install packages and remove package. Default sources can be
/// used to download and extract the packages by the package manager. The package manager
/// installs the packages to the Unlab-gpu home directory by default where they are available
/// for a user. Also, the packages can be installed as dependencies of current package by
/// default.
#[derive(Clone)]
pub struct PkgManager
{
    pkg_db: DB,
    home_dir: PathBuf,
    work_dir: PathBuf,
    bin_dir: PathBuf,
    lib_dir: PathBuf,
    doc_dir: PathBuf,
    pkgs: HashMap<PkgName, Pkg>,
    locks: HashMap<PkgName, Version>,
    constraints: Arc<HashMap<PkgName, VersionReq>>,
    sources: Arc<HashMap<PkgName, SrcInfo>>,
    src_factories: Vec<Arc<dyn SourceCreate + Send + Sync>>,
    printer: Arc<dyn Print + Send + Sync>,
}

impl PkgManager
{
    /// Creates a package manager.
    ///
    /// This method takes paths to the Unlab-gpu home directory, the work directory, the binary
    /// dirtectory, the library directory, and the documentation directory. The factories of
    /// default soruces which allows to access to the package. Also, this method takes the
    /// printer that prints messages. If the packages isn't installed as the dependencies for
    /// the current package, the path of work directory should be the path to the the Unlab-gpu
    /// home directory.
    pub fn new(home_dir: PathBuf, work_dir: PathBuf, bin_dir: PathBuf, lib_dir: PathBuf, doc_dir: PathBuf, src_factories: Vec<Arc<dyn SourceCreate + Send + Sync>>, printer: Arc<dyn Print + Send + Sync>) -> Result<Self>
    {
        let mut work_var_dir = work_dir.clone();
        work_var_dir.push("var");
        match create_dir_all(work_var_dir.as_path()) {
            Ok(()) => (),
            Err(err) => return Err(Error::Io(err)),
        }
        let mut pkg_db_file = work_var_dir.clone();
        pkg_db_file.push("pkg.db");
        let pkg_db = match DB::open(pkg_db_file) {
            Ok(tmp_pkg_db) => tmp_pkg_db,
            Err(err) => return Err(Error::Jammdb(Box::new(err))),
        };
        Ok(PkgManager {
                pkg_db,
                home_dir,
                work_dir,
                bin_dir,
                lib_dir,
                doc_dir,
                pkgs: HashMap::new(),
                locks: HashMap::new(),
                constraints: Arc::new(HashMap::new()),
                sources: Arc::new(HashMap::new()),
                src_factories,
                printer,
        })
    }
    
    /// Returns the path to the Unlab-gpu home directory.
    pub fn home_dir(&self) -> &Path
    { self.home_dir.as_path() }

    /// Returns the path to the work directory of current package.
    pub fn work_dir(&self) -> &Path
    { self.work_dir.as_path() }

    /// Returns the path to the binary directory.
    pub fn bin_dir(&self) -> &Path
    { self.bin_dir.as_path() }

    /// Returns the path to the library directory.
    pub fn lib_dir(&self) -> &Path
    { self.lib_dir.as_path() }
    
    /// Returns the path to the documentation directory.
    pub fn doc_dir(&self) -> &Path
    { self.doc_dir.as_path() }

    /// Returns the locked versions of packages
    pub fn locks(&self) -> &HashMap<PkgName, Version>
    { &self.locks }

    /// Sets the locked versions of packages.
    pub fn set_locks(&mut self, locks: HashMap<PkgName, Version>)
    { self.locks = locks; }

    /// Loads the locked versions of packages.
    pub fn load_locks(&mut self) -> Result<()>
    {
        self.locks = load_versions_or_empty("Unlab.lock")?;
        Ok(())
    }

    /// Saves the locked versions of packages.
    pub fn save_locks(&self) -> Result<()>
    { save_versions("Unlab.lock", &self.locks) }
    
    /// Saves the locked version packages from the database.
    pub fn save_locks_from_pkg_versions(&self) -> Result<()>
    {
        let mut locks: HashMap<PkgName, Version> = HashMap::new();
        self.pkg_versions_for_bucket_in("versions", |name, version| {
                locks.insert(name.clone(), version.clone());
                Ok(())
        })?;
        save_versions("Unlab.lock", &locks)
    }
    
    /// Returns the constraints.
    pub fn constraints(&self) -> &Arc<HashMap<PkgName, VersionReq>>
    { &self.constraints }

    /// Sets the constraints.
    pub fn set_constraints(&mut self, constraints: Arc<HashMap<PkgName, VersionReq>>)
    { self.constraints = constraints; }

    /// Loads the constraints.
    pub fn load_constraints(&mut self) -> Result<()>
    {
        self.constraints = Arc::new(load_version_reqs_or_empty(self.constraints_file())?);
        Ok(())
    }
    
    /// Returns the custom sources.
    pub fn sources(&self) -> &Arc<HashMap<PkgName, SrcInfo>>
    { &self.sources }

    /// Sets the custom sources.
    pub fn set_sources(&mut self, sources: Arc<HashMap<PkgName, SrcInfo>>)
    { self.sources = sources; }

    /// Loads the custom sources.
    pub fn load_sources(&mut self) -> Result<()>
    {
        self.sources = Arc::new(load_src_infos_or_empty(self.sources_file())?);
        Ok(())
    }

    /// Returns the factories of sources.
    pub fn src_factories(&self) -> &[Arc<dyn SourceCreate + Send + Sync>]
    { self.src_factories.as_slice() }

    /// Returns the printer.
    pub fn printer(&self) -> &Arc<dyn Print + Send + Sync>
    { &self.printer }
    
    /// Loads the manifest of current package.
    pub fn manifest() -> Result<Manifest>
    { Manifest::load("Unlab.toml") }

    /// Saves the manifest of current package.
    pub fn save_manifest(manifest: &Manifest) -> Result<()>
    { manifest.save("Unlab.toml") }
    
    /// Resets the package manager.
    pub fn reset(&mut self)
    { self.pkgs.clear(); }
    
    /// Returns the path to the constraints.
    pub fn constraints_file(&self) -> PathBuf
    {
        let mut file = self.home_dir.clone();
        file.push("constraints.toml");
        file
    }

    /// Returns the path to the custom sources.
    pub fn sources_file(&self) -> PathBuf
    {
        let mut file = self.home_dir.clone();
        file.push("sources.toml");
        file
    }
    
    /// Returns the path to the variable directory in the work directory.
    pub fn work_var_dir(&self) -> PathBuf
    {
        let mut dir = self.work_dir.clone();
        dir.push("var");
        dir
    }    

    /// Returns the path to the temporary directory in the work directory.
    pub fn work_tmp_dir(&self) -> PathBuf
    {
        let mut dir = self.work_dir.clone();
        dir.push("tmp");
        dir
    }    
    
    /// Returns the path to the information directory.
    pub fn info_dir(&self) -> PathBuf
    {
        let mut dir = self.work_var_dir();
        dir.push("info");
        dir
    }

    /// Returns the path to the information directory while pre-installing.
    pub fn new_part_info_dir(&self) -> PathBuf
    {
        let mut dir = self.work_var_dir();
        dir.push("info.new.part");
        dir
    }
    
    /// Returns the path to the information directory while installing.
    pub fn new_info_dir(&self) -> PathBuf
    {
        let mut dir = self.work_var_dir();
        dir.push("info.new");
        dir
    }

    /// Returns the path to the information directory for the specified package.
    pub fn pkg_info_dir(&self, name: &PkgName) -> PathBuf
    {
        let mut dir = self.info_dir();
        dir.push(name.to_path_buf());
        dir
    }

    /// Returns the path to the information directory while pre-installing for the specified
    /// package.
    pub fn pkg_new_part_info_dir(&self, name: &PkgName) -> PathBuf
    {
        let mut dir = self.new_part_info_dir();
        dir.push(name.to_path_buf());
        dir
    }
    
    /// Returns the path to the information directory while installing for the specified package.
    pub fn pkg_new_info_dir(&self, name: &PkgName) -> PathBuf
    {
        let mut dir = self.new_info_dir();
        dir.push(name.to_path_buf());
        dir
    }
    
    /// Returns the path to the documentation directory in the temporary directory for the
    /// specified package.
    pub fn pkg_tmp_doc_dir(&self, name: &PkgName, version: &Version) -> PathBuf
    {
        let mut dir = self.work_tmp_dir();
        dir.push(name.to_path_buf());
        dir.push(format!("{}", version));
        dir.push("doc");
        dir
    }
    
    /// Creates a source for the specified package.
    pub fn create_source(&self, name: &PkgName) -> Result<Box<dyn Source + Send + Sync>>
    {
        match self.sources.get(name) {
            Some(src_info) => {
                match src_info {
                    SrcInfo::Renamed(old_name) => {
                        for src_factory in &self.src_factories {
                            match src_factory.create(name.clone(), Some(old_name.clone()), self.home_dir.clone(), self.work_dir.clone(), self.printer.clone()) {
                                Some(src) => return Ok(src),
                                None => (),
                            }
                        }
                        Err(Error::PkgName(name.clone(), String::from("unrecognized source for renamed package")))
                    },
                    SrcInfo::Versions(version_src_infos) => Ok(Box::new(CustomSrc::new(name.clone(), self.home_dir.clone(), self.work_dir.clone(), version_src_infos.clone(), self.printer.clone()))),
                }
            },
            None => {
                for src_factory in &self.src_factories {
                    match src_factory.create(name.clone(), None, self.home_dir.clone(), self.work_dir.clone(), self.printer.clone()) {
                        Some(src) => return Ok(src),
                        None => (),
                    }
                }
                Err(Error::PkgName(name.clone(), String::from("unrecognized source for package")))
            },
        }
    }
    
    fn has_bucket(&self, bucket_name: &str) -> Result<bool>
    {
        let tx = db_tx(&self.pkg_db, false)?;
        match tx.get_bucket(bucket_name) {
            Ok(_) => Ok(true),
            Err(jammdb::Error::BucketMissing) => Ok(false),
            Err(err) => Err(Error::Jammdb(Box::new(err))),
        }
    }

    fn remove_bucket(&self, bucket_name: &str) -> Result<()>
    {
        let tx = db_tx(&self.pkg_db, true)?;
        match tx.delete_bucket(bucket_name) {
            Ok(()) => (),
            Err(jammdb::Error::BucketMissing) => (),
            Err(err) => return Err(Error::Jammdb(Box::new(err))),
        }
        tx_commit(tx)?;
        Ok(())
    }
    
    fn pkg_versions_for_bucket(&self, bucket_name: &str) -> Result<Vec<(PkgName, Version)>>
    {
        let tx = db_tx(&self.pkg_db, false)?;
        match tx.get_bucket(bucket_name) {
            Ok(version_bucket) => {
                let mut pairs: Vec<(PkgName, Version)> = Vec::new();
                for data in version_bucket.cursor() {
                    let name = match String::from_utf8(data.kv().key().to_vec()) {
                        Ok(s) => PkgName::parse(s.as_str())?,
                        Err(_) => return Err(Error::Pkg(format!("invalid package name data"))),
                    };
                    let version = match String::from_utf8(data.kv().value().to_vec()) {
                        Ok(s) => Version::parse(s.as_str())?,
                        Err(_) => return Err(Error::Pkg(format!("invalid version data"))),
                    };
                    pairs.push((name, version));
                }
                Ok(pairs)
            },
            Err(jammdb::Error::BucketMissing) => Ok(Vec::new()),
            Err(err) => Err(Error::Jammdb(Box::new(err))),
        }
    }

    fn pkg_versions_for_bucket_in<F>(&self, bucket_name: &str, mut f: F) -> Result<()>
        where F: FnMut(&PkgName, &Version) -> Result<()>
    {
        let tx = db_tx(&self.pkg_db, false)?;
        match tx.get_bucket(bucket_name) {
            Ok(version_bucket) => {
                for data in version_bucket.cursor() {
                    let name = match String::from_utf8(data.kv().key().to_vec()) {
                        Ok(s) => PkgName::parse(s.as_str())?,
                        Err(_) => return Err(Error::Pkg(format!("invalid package name data"))),
                    };
                    let version = match String::from_utf8(data.kv().value().to_vec()) {
                        Ok(s) => Version::parse(s.as_str())?,
                        Err(_) => return Err(Error::Pkg(format!("invalid version data"))),
                    };
                    f(&name, &version)?;
                }
                Ok(())
            },
            Err(jammdb::Error::BucketMissing) => Ok(()),
            Err(err) => Err(Error::Jammdb(Box::new(err))),
        }
    }
    
    fn pkg_version_for_bucket(&self, bucket_name: &str, name: &PkgName) -> Result<Option<Version>>
    {
        let tx = db_tx(&self.pkg_db, false)?;
        match tx.get_bucket(bucket_name) {
            Ok(version_bucket) => {
                match version_bucket.get(name.name()) {
                    Some(data) => {
                        match String::from_utf8(data.kv().value().to_vec()) {
                            Ok(s) => Ok(Some(Version::parse(s.as_str())?)),
                            Err(_) => Err(Error::Pkg(format!("invalid version data"))),
                        }
                    },
                    None => Ok(None),
                }
            },
            Err(jammdb::Error::BucketMissing) => Ok(None),
            Err(err) => Err(Error::Jammdb(Box::new(err))),
        }
    }

    fn add_pkg_version_for_bucket(&self, bucket_name: &str, name: &PkgName, version: &Version) -> Result<()>
    {
        let tx = db_tx(&self.pkg_db, true)?;
        let version_bucket = tx_get_or_create_bucket(&tx, bucket_name)?;
        bucket_put(&version_bucket, name.name(), format!("{}", version))?;
        tx_commit(tx)?;
        Ok(())
    }
    
    fn move_pkg_versions_for_buckets(&self, src_bucket_name: &str, dst_bucket_name: &str) -> Result<()>
    { 
        let tx = db_tx(&self.pkg_db, true)?;
        {
            let src_version_bucket = match tx.get_bucket(src_bucket_name) {
                Ok(tmp_src_version_bucket) => tmp_src_version_bucket,
                Err(jammdb::Error::BucketMissing) => return Ok(()),
                Err(err) => return Err(Error::Jammdb(Box::new(err))),
            };
            let dst_version_bucket = tx_get_or_create_bucket(&tx, dst_bucket_name)?;
            for data in src_version_bucket.cursor() {
                bucket_put(&dst_version_bucket, data.kv().key().to_vec(), data.kv().value().to_vec())?;
            }
        }
        tx_delete_bucket(&tx, src_bucket_name)?;
        tx_commit(tx)?;
        Ok(())
    }

    fn pkg_names_for_bucket(&self, bucket_name: &str) -> Result<Vec<PkgName>>
    {
        let tx = db_tx(&self.pkg_db, false)?;
        match tx.get_bucket(bucket_name) {
            Ok(version_bucket) => {
                let mut names: Vec<PkgName> = Vec::new();
                for data in version_bucket.cursor() {
                    let name = match String::from_utf8(data.kv().key().to_vec()) {
                        Ok(s) => PkgName::parse(s.as_str())?,
                        Err(_) => return Err(Error::Pkg(format!("invalid package name data"))),
                    };
                    names.push(name);
                }
                Ok(names)
            },
            Err(jammdb::Error::BucketMissing) => Ok(Vec::new()),
            Err(err) => Err(Error::Jammdb(Box::new(err))),
        }
    }

    fn has_pkg_names_for_bucket(&self, bucket_name: &str, name: &PkgName) -> Result<bool>
    {
        let tx = db_tx(&self.pkg_db, false)?;
        match tx.get_bucket(bucket_name) {
            Ok(name_bucket) => {
                match name_bucket.get(name.name()) {
                    Some(_) => Ok(true),
                    None => Ok(false),
                }
            },
            Err(jammdb::Error::BucketMissing) => Ok(false),
            Err(err) => Err(Error::Jammdb(Box::new(err))),
        }
    }
    
    fn add_pkg_names_for_bucket(&self, bucket_name: &str, name: &PkgName) -> Result<()>
    {
        let tx = db_tx(&self.pkg_db, true)?;
        let name_bucket = tx_get_or_create_bucket(&tx, bucket_name)?;
        bucket_put(&name_bucket, name.name(), "t")?;
        tx_commit(tx)?;
        Ok(())
    }

    fn add_pkg_names_for_bucket_and_removing(&self, bucket_name: &str, names: &[PkgName]) -> Result<()>
    {
        let tx = db_tx(&self.pkg_db, true)?;
        let name_bucket = tx_get_or_create_bucket(&tx, bucket_name)?;
        for name in names {
            let mut dependents_file = self.pkg_info_dir(&name);
            dependents_file.push("dependents.toml");
            let dependents = load_opt_version_reqs(dependents_file)?;
            match dependents {
                Some(dependents) => {
                    if dependents.is_empty() {
                        bucket_put(&name_bucket, name.name(), "t")?;
                    } else {
                        return Err(Error::PkgName(name.clone(), String::from("can't remove package")));
                    }
                },
                None => return Err(Error::PkgName(name.clone(), String::from("package isn't installed"))),
            }
        }
        tx_commit(tx)?;
        Ok(())
    }    

    fn add_pkg_names_for_buckets_and_autoremoving(&self, bucket_name: &str, version_bucket_name: &str, visiteds: &HashSet<PkgName>) -> Result<()>
    {
        let tx = db_tx(&self.pkg_db, true)?;
        {
            let version_bucket = match tx.get_bucket(version_bucket_name) {
                Ok(tmp_version_bucket) => tmp_version_bucket,
                Err(jammdb::Error::BucketMissing) => return Ok(()),
                Err(err) => return Err(Error::Jammdb(Box::new(err))),
            };
            let name_bucket = tx_get_or_create_bucket(&tx, bucket_name)?;
            for data in version_bucket.cursor() {
                let name = match String::from_utf8(data.kv().key().to_vec()) {
                    Ok(s) => PkgName::parse(s.as_str())?,
                    Err(_) => return Err(Error::Pkg(format!("invalid package name data"))),
                };
                if !visiteds.contains(&name) {
                    bucket_put(&name_bucket, data.kv().key().to_vec(), "t")?;
                }
            }
        }
        tx_commit(tx)?;
        Ok(())
    }    
    
    fn remove_pkg_versions_for_buckets(&self, removal_bucket_name: &str, bucket_name: &str) -> Result<()>
    { 
        let tx = db_tx(&self.pkg_db, true)?;
        {
            let removal_bucket = match tx.get_bucket(removal_bucket_name) {
                Ok(tmp_removal_bucket) => tmp_removal_bucket,
                Err(jammdb::Error::BucketMissing) => return Ok(()),
                Err(err) => return Err(Error::Jammdb(Box::new(err))),
            };
            let version_bucket = tx_get_or_create_bucket(&tx, bucket_name)?;
            for data in removal_bucket.cursor() {
                match version_bucket.delete(data.kv().key()) {
                    Ok(_) => (),
                    Err(err) => return Err(Error::Jammdb(Box::new(err))),
                }
            }
        }
        tx_delete_bucket(&tx, removal_bucket_name)?;
        tx_commit(tx)?;
        Ok(())
    }
    
    /// Returns the package versions.
    pub fn pkg_versions(&self) -> Result<Vec<(PkgName, Version)>>
    { self.pkg_versions_for_bucket("versions") }

    /// Calls the function for each package version.
    pub fn pkg_versions_in<F>(&self, f: F) -> Result<()>
        where F: FnMut(&PkgName, &Version) -> Result<()>
    { self.pkg_versions_for_bucket_in("versions", f) }

    /// Returns the package version if the package is installed, otherwise `None`.
    pub fn pkg_version(&self, name: &PkgName) -> Result<Option<Version>>
    { self.pkg_version_for_bucket("versions", name) }
    
    /// Returns the package manifest if the package is installed, otherwise `None`.
    pub fn pkg_manifest(&self, name: &PkgName) -> Result<Option<Manifest>>
    {
        let mut manifest_file = self.pkg_info_dir(name);
        manifest_file.push("manifest.toml");
        Manifest::load_opt(manifest_file)
    }

    /// Returns the package dependents if the package is installed, otherwise `None`.
    pub fn pkg_dependents(&self, name: &PkgName) -> Result<Option<HashMap<PkgName, VersionReq>>>
    {
        let mut dependents_file = self.pkg_info_dir(name);
        dependents_file.push("dependents.toml");
        load_opt_version_reqs(dependents_file)
    }

    /// Returns the package paths if the package is installed, otherwise `None`.
    pub fn pkg_paths(&self, name: &PkgName) -> Result<Option<Paths>>
    {
        let mut paths_file = self.pkg_info_dir(name);
        paths_file.push("paths.toml");
        Paths::load_opt(paths_file)
    }    
        
    fn io_res_remove_dirs_for_cleaning(&self) -> io::Result<()>
    {
        recursively_remove(self.work_tmp_dir(), true)?;
        recursively_remove(self.new_part_info_dir(), true)?;
        Ok(())
    }
    
    fn clean_after_error(&self) -> Result<()>
    {
        self.printer.print_cleaning_after_error(false);
        self.remove_bucket("new_versions")?;
        self.remove_bucket("pkgs_to_remove")?;
        self.remove_bucket("pkgs_to_change")?;
        match self.io_res_remove_dirs_for_cleaning() {
            Ok(()) => (),
            Err(err) => return Err(Error::Io(err)),
        }
        self.printer.print_cleaning_after_error(true);
        Ok(())
    }

    fn new_pkg_version_for_pre_installing(&mut self, name: &PkgName) -> Result<Option<Version>>
    {
        let is_new_version_from_bucket = match self.pkgs.get_mut(name) {
            Some(pkg) => {
                let tmp_is_new_version_from_bucket = pkg.has_new_version_from_bucket;
                pkg.has_new_version_from_bucket = true;
                tmp_is_new_version_from_bucket
            },
            None => true,
        };
        if is_new_version_from_bucket {
            self.pkg_version_for_bucket("new_versions", name)
        } else {
            Ok(None)
        }
    }
    
    fn prepare_new_infos_for_pre_installing_without_reset(&mut self, name: &PkgName, visiteds: &mut HashSet<PkgName>, is_update: bool, is_force: bool) -> Result<()>
    {
        if visiteds.contains(name) {
            return Ok(());
        }
        let res = dfs(name, visiteds, self, |name, data| {
                let pkg = match data.pkgs.get(name) {
                    Some(tmp_pkg) if !tmp_pkg.is_added_by_dependent => tmp_pkg.clone(),
                    _ => {
                        let mut src = data.create_source(name)?;
                        let old_version = data.pkg_version_for_bucket("versions", name)?;
                        let new_version_from_bucket = data.new_pkg_version_for_pre_installing(name)?;
                        let new_version = match &new_version_from_bucket {
                            Some(tmp_new_version) => Some(tmp_new_version.clone()),
                            None => {
                                if is_update {
                                    src.update()?;
                                }
                                let versions = src.versions()?;
                                let old_dependants = if old_version.is_some() {
                                    let mut old_dependents_file = data.pkg_info_dir(name);
                                    old_dependents_file.push("dependents.toml");
                                    load_version_reqs(old_dependents_file)?
                                } else {
                                    HashMap::new()
                                };
                                let mut tmp_new_version: Option<Version> = None; 
                                for old_version_req in old_dependants.values() {
                                    let max_version = max_pkg_version(&versions, Some(old_version_req), data.constraints.get(name), data.locks.get(name));
                                    match &max_version {
                                        Some(max_version) => {
                                            match &tmp_new_version {
                                                Some(tmp_new_version) => {
                                                    if tmp_new_version != max_version {
                                                        return Err(Error::PkgName(name.clone(), format!("version requirements indicate two different package versions: {}, {}", tmp_new_version, max_version)));
                                                    }
                                                },
                                                None => tmp_new_version = Some(max_version.clone()),
                                            }
                                        },
                                        None => return Err(Error::PkgName(name.clone(), String::from("each package version isn't matched to version requirement"))),
                                    }
                                }
                                match tmp_new_version {
                                    Some(tmp_new_version) => Some(tmp_new_version),
                                    None => max_pkg_version(&versions, None, data.constraints.get(name), data.locks.get(name)),
                                }
                            },
                        };
                        match &new_version {
                            Some(new_version) => {
                                src.set_current_version(new_version.clone());
                                if new_version_from_bucket.is_none() {
                                    data.add_pkg_version_for_bucket("new_versions", name, &new_version)?;
                                }
                                let dir = if is_force || old_version.as_ref().map(|ov| ov != new_version).unwrap_or(true) {
                                    Some(PathBuf::from(src.dir()?))
                                } else {
                                    None
                                };
                                data.pkgs.insert(name.clone(), Pkg::new_with_copying(dir, data.pkg_info_dir(name), data.pkg_new_part_info_dir(name))?);
                                data.pkgs.get(name).unwrap().clone()
                            },
                            None => return Err(Error::PkgName(name.clone(), String::from("each package version isn't matched to version requirement"))),
                        }
                    },
                };
                let manifest = pkg.manifest()?;
                match manifest.package.unlab_gpu_version {
                    Some(version_req) => {
                        let version = Version::parse(env!("CARGO_PKG_VERSION"))?;
                        if !version_req.matches(&version) {
                            return Err(Error::PkgName(name.clone(), format!("unlab-gpu version {} isn't matched to version requirement {}", version, version_req)));
                        }
                    },
                    None => (),
                }
                match &manifest.dependencies {
                    Some(deps) => {
                        for (dep_name, dep_version_req) in deps {
                            let mut dep_src = data.create_source(dep_name)?;
                            if is_update {
                                dep_src.update()?;
                            }
                            let versions = dep_src.versions()?;
                            let max_version = max_pkg_version(&versions, Some(dep_version_req), data.constraints.get(dep_name), data.locks.get(dep_name));
                            match &max_version {
                                Some(max_version) => {
                                    let dep_new_version_from_bucket = data.new_pkg_version_for_pre_installing(dep_name)?;
                                    match &dep_new_version_from_bucket {
                                        Some(dep_new_version_from_bucket) => {
                                            if dep_new_version_from_bucket != max_version {
                                                return Err(Error::PkgName(dep_name.clone(), format!("version requirements indicate two different package versions: {}, {}", dep_new_version_from_bucket, max_version)));
                                            }
                                        },
                                        None => data.add_pkg_version_for_bucket("new_versions", dep_name, max_version)?,
                                    }
                                },
                                None => return Err(Error::PkgName(dep_name.clone(), String::from("each package version isn't matched to version requirement"))),
                            }
                        }
                        Ok(deps.keys().map(|dn| dn.clone()).collect())
                    },
                    None => Ok(Vec::new()),
                }
        }, |name, data| {
                let pkg = match data.pkgs.get(name) {
                    Some(tmp_pkg) => tmp_pkg.clone(),
                    None => return Err(Error::PkgName(name.clone(), String::from("no package"))),
                };
                if pkg.is_to_install()? {
                    let old_manifest = pkg.old_manifest()?;
                    match old_manifest {
                        Some(old_manifest) => {
                            match &old_manifest.dependencies {
                                Some(old_deps) => {
                                    for old_dep_name in old_deps.keys() {
                                        if data.pkg_version_for_bucket("new_versions", old_dep_name)?.is_none() {
                                            match data.pkg_version_for_bucket("versions", old_dep_name)? {
                                                Some(version) => {
                                                    data.add_pkg_version_for_bucket("new_versions", old_dep_name, &version)?;
                                                    data.pkgs.insert(old_dep_name.clone(), Pkg::new_with_copying_and_flags(None, data.pkg_info_dir(old_dep_name), data.pkg_new_part_info_dir(old_dep_name), true, false)?);
                                                },
                                                None => return Err(Error::PkgName(old_dep_name.clone(), String::from("no package version"))),
                                            }
                                        }
                                        match data.pkgs.get(old_dep_name) {
                                            Some(old_dep_pkg) => {
                                                let mut depentents = old_dep_pkg.dependents()?;
                                                depentents.remove(name);
                                                old_dep_pkg.save_dependents(&depentents)?;
                                            },
                                            None => return Err(Error::PkgName(old_dep_name.clone(), String::from("no package"))),
                                        }
                                    }
                                },
                                None => (),
                            }
                        },
                        None => (),
                    }
                    let manifest = pkg.manifest()?;
                    match &manifest.dependencies {
                        Some(deps) => {
                            for (dep_name, dep_version_req) in deps {
                                match data.pkgs.get(dep_name) {
                                    Some(dep_pkg) => {
                                        let mut depentents = dep_pkg.dependents()?;
                                        depentents.insert(name.clone(), dep_version_req.clone());
                                        dep_pkg.save_dependents(&depentents)?;
                                    },
                                    None => return Err(Error::PkgName(dep_name.clone(), String::from("no package"))),
                                }
                            }
                        },
                        None => (),
                    }
                }
                Ok(())
        })?;
        match res {
            DfsResult::Success => Ok(()),
            DfsResult::Cycle(names) => Err(Error::PkgDepCycle(names)),
        }
    }

    fn prepare_new_infos_for_pre_installing(&mut self, name: &PkgName, visiteds: &mut HashSet<PkgName>, is_update: bool, is_force: bool) -> Result<()>
    {
        let res = self.prepare_new_infos_for_pre_installing_without_reset(name, visiteds, is_update, is_force);
        match res {
            Ok(()) => Ok(()),
            Err(err) => {
                self.pkgs.clear();
                self.clean_after_error()?;
                Err(err)
            },
        }
    }
    
    fn check_dependent_version_reqs(&self) -> Result<()>
    {
        self.printer.print_checking_dependent_version_reqs(false);
        let new_versions = self.pkg_versions_for_bucket("new_versions")?;
        for (name, new_version) in &new_versions {
            match self.pkgs.get(name) {
                Some(pkg) => {
                    let mut src = self.create_source(name)?;
                    let versions = src.versions()?;
                    let dependents = pkg.dependents()?;
                    for version_req in dependents.values() {
                        let max_version = max_pkg_version(&versions, Some(version_req), self.constraints.get(name), self.locks.get(name));
                        match &max_version {
                            Some(max_version) => {
                                if new_version != max_version {
                                    return Err(Error::PkgName(name.clone(), format!("version requirements indicate two different package versions: {}, {}", new_version, max_version)));
                                }
                            },
                            None => return Err(Error::PkgName(name.clone(), String::from("each package version isn't matched to version requirement"))),
                        }
                    }
                },
                None => return Err(Error::PkgName(name.clone(), String::from("no package"))),
            }
        }
        self.printer.print_checking_dependent_version_reqs(true);
        Ok(())
    }

    fn pkg_is_to_install_for_pre_install(&self, name: &PkgName) -> Result<bool>
    {
        let mut manifest_file = self.pkg_new_part_info_dir(name);
        manifest_file.push("manifest.toml");
        match fs::metadata(manifest_file) {
            Ok(_) => Ok(true),
            Err(err) if err.kind() == ErrorKind::NotFound => Ok(false),
            Err(err) => Err(Error::Io(err)),
        }
    }
        
    fn search_path_conflicts(&self) -> Result<()>
    {
        self.printer.print_searching_path_conflicts(false);
        check_dir(self.bin_dir.as_path(), "bin isn't directory")?;
        check_dir(self.lib_dir.as_path(), "lib isn't directory")?;
        check_dir(self.doc_dir.as_path(), "doc isn't directory")?;
        let new_versions = self.pkg_versions_for_bucket("new_versions")?;
        let mut ignored_bin_paths: HashSet<PathBuf> = HashSet::new();
        let mut ignored_lib_paths: HashSet<PathBuf> = HashSet::new();
        for (name, _) in &new_versions {
            if self.pkg_is_to_install_for_pre_install(name)? {
                let mut old_paths_file = self.pkg_info_dir(name);
                old_paths_file.push("paths.toml");
                match Paths::load_opt(old_paths_file)? {
                    Some(paths) => {
                        for bin_path in &paths.bin {
                            ignored_bin_paths.insert(PathBuf::from(bin_path));
                        }
                        for lib_path in &paths.lib {
                            ignored_lib_paths.insert(PathBuf::from(lib_path));
                        }
                    },
                    None => (),
                }
            }
        }
        for (name, new_version) in &new_versions {
            if self.pkg_is_to_install_for_pre_install(name)? {
                let mut src = self.create_source(name)?;
                src.set_current_version(new_version.clone());
                let mut pkg_bin_dir = PathBuf::from(src.dir()?);
                pkg_bin_dir.push("bin");
                check_dir_for_pkg(pkg_bin_dir.as_path(), name, "bin in package isn't directory")?;
                let bin_paths = match conflicts(pkg_bin_dir, self.bin_dir.as_path(), &ignored_bin_paths, Some(1)) {
                    Ok((conflict_paths, paths)) => {
                        if conflict_paths.is_empty() {
                            paths
                        } else {
                            return Err(Error::PkgPathConflicts(name.clone(), None, conflict_paths, PkgPathConflict::Bin));
                        }
                    },
                    Err(err) => return Err(Error::Io(err)),
                };
                let mut pkg_lib_dir = PathBuf::from(src.dir()?);
                pkg_lib_dir.push("lib");
                check_dir_for_pkg(pkg_lib_dir.as_path(), name, "lib in package isn't directory")?;
                let lib_paths = match conflicts(pkg_lib_dir, self.lib_dir.as_path(), &ignored_lib_paths, Some(2)) {
                    Ok((conflict_paths, paths)) => {
                        if conflict_paths.is_empty() {
                            paths
                        } else {
                            return Err(Error::PkgPathConflicts(name.clone(), None, conflict_paths, PkgPathConflict::Lib));
                        }
                    },
                    Err(err) => return Err(Error::Io(err)),
                };
                let mut bin: Vec<String> = Vec::new();
                for bin_path in &bin_paths {
                    match bin_path.to_str() {
                        Some(s) => bin.push(String::from(s)),
                        None => return Err(Error::PkgName(name.clone(), String::from("bin path contains invalid UTF-8 character"))),
                    }
                }
                let mut lib: Vec<String> = Vec::new();
                for lib_path in &lib_paths {
                    match lib_path.to_str() {
                        Some(s) => lib.push(String::from(s)),
                        None => return Err(Error::PkgName(name.clone(), String::from("lib path contains invalid UTF-8 character"))),
                    }
                }
                let paths = Paths::new(bin, lib);
                let mut paths_file = self.pkg_new_part_info_dir(name);
                paths_file.push("paths.toml");
                paths.save(paths_file)?;
            }
        }
        for (i, (name, new_version)) in new_versions.iter().enumerate() {
            for (name2, new_version2) in &new_versions[(i + 1)..] {
                if self.pkg_is_to_install_for_pre_install(name)? && self.pkg_is_to_install_for_pre_install(name2)? {
                    let mut src = self.create_source(name)?;
                    src.set_current_version(new_version.clone());
                    let mut src2 = self.create_source(name2)?;
                    src2.set_current_version(new_version2.clone());
                    let mut pkg_bin_dir = PathBuf::from(src.dir()?);
                    pkg_bin_dir.push("bin");
                    let mut pkg_bin_dir2 = PathBuf::from(src2.dir()?);
                    pkg_bin_dir2.push("bin");
                    match conflicts(pkg_bin_dir, pkg_bin_dir2, &HashSet::new(), Some(1)) {
                        Ok((conflict_paths, _)) => {
                            if !conflict_paths.is_empty() {
                                return Err(Error::PkgPathConflicts(name.clone(), Some(name2.clone()), conflict_paths, PkgPathConflict::Bin));
                            }
                        },
                        Err(err) => return Err(Error::Io(err)),
                    }
                    let mut pkg_lib_dir = PathBuf::from(src.dir()?);
                    pkg_lib_dir.push("lib");
                    let mut pkg_lib_dir2 = PathBuf::from(src2.dir()?);
                    pkg_lib_dir2.push("lib");
                    match conflicts(pkg_lib_dir, pkg_lib_dir2, &HashSet::new(), Some(2)) {
                        Ok((conflict_paths, _)) => {
                            if !conflict_paths.is_empty() {
                                return Err(Error::PkgPathConflicts(name.clone(), Some(name2.clone()), conflict_paths, PkgPathConflict::Lib));
                            }
                        },
                        Err(err) => return Err(Error::Io(err)),
                    }
                }
            }
        }
        self.printer.print_searching_path_conflicts(true);
        Ok(())
    }

    fn generate_pkg_doc(&self, name: &PkgName, new_version: &Version) -> Result<()>
    {
        if self.pkg_is_to_install_for_pre_install(name)? {
            self.printer.print_documenting_pkg(name, false);
            let mut src = self.create_source(name)?;
            src.set_current_version(new_version.clone());
            let doc_dir = self.pkg_tmp_doc_dir(name, &new_version);
            let mut paths_file = self.pkg_new_part_info_dir(name);
            paths_file.push("paths.toml");
            let paths = Paths::load(paths_file)?;
            let mut pkg_lib_dir = PathBuf::from(src.dir()?);
            pkg_lib_dir.push("lib");
            for path in &paths.lib {
                let mut lib_doc_dir = doc_dir.clone();
                lib_doc_dir.push(path);
                match create_dir_all(lib_doc_dir.as_path()) {
                    Ok(()) => (),
                    Err(err) => return Err(Error::Io(err)),
                }
                generate_doc(pkg_lib_dir.as_path(), doc_dir.as_path(), path)?;
            }
            self.printer.print_documenting_pkg(name, true);
        }
        Ok(())
    }
    
    fn generate_docs(&self) -> Result<()>
    {
        let new_versions = self.pkg_versions_for_bucket("new_versions")?;
        for (name, new_version) in &new_versions {
            self.generate_pkg_doc(name, new_version)?;
        }
        Ok(())
    }
    
    fn check_new_infos_and_generate_docs_for_pre_installing_without_reset(&self, is_doc: bool) -> Result<()>
    {
        self.check_dependent_version_reqs()?;
        self.search_path_conflicts()?;
        if is_doc {
            self.generate_docs()?;
        }
        match rename(self.new_part_info_dir(), self.new_info_dir()) {
           Ok(()) => Ok(()),
           Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
           Err(err) => Err(Error::Io(err)),
        }
    }

    fn check_new_infos_and_generate_docs_for_pre_installing(&mut self, is_doc: bool) -> Result<()>
    {
        let res = self.check_new_infos_and_generate_docs_for_pre_installing_without_reset(is_doc);
        self.pkgs.clear();
        match res {
            Ok(()) => Ok(()),
            Err(err) => {
                self.clean_after_error()?;
                Err(err)
            },
        }
    }
    
    fn prepare_new_infos_for_pre_removing_without_reset(&mut self) -> Result<()>
    {
        let names = self.pkg_names_for_bucket("pkgs_to_remove")?;
        for name in &names {
            let pkg = Pkg::new_without_copying(self.pkg_info_dir(name));
            let manifest = pkg.manifest()?;
            match &manifest.dependencies {
                Some(deps) => {
                    for dep_name in deps.keys() {
                        if !self.has_pkg_names_for_bucket("pkgs_to_change", dep_name)? {
                            if self.pkg_version_for_bucket("versions", dep_name)?.is_some() {
                                self.add_pkg_names_for_bucket("pkgs_to_change", dep_name)?;
                                self.pkgs.insert(dep_name.clone(), Pkg::new_with_copying_and_flags(None, self.pkg_info_dir(dep_name), self.pkg_new_part_info_dir(dep_name), true, false)?);
                            } else {
                                return Err(Error::PkgName(dep_name.clone(), String::from("no package version")));
                            }
                        }
                        match self.pkgs.get(dep_name) {
                            Some(dep_pkg) => {
                                let mut depentents = dep_pkg.dependents()?;
                                depentents.remove(name);
                                dep_pkg.save_dependents(&depentents)?;
                            },
                            None => return Err(Error::PkgName(dep_name.clone(), String::from("no package"))),
                        }
                    }
                },
                None => (),
            }
        }
        Ok(())
    }

    fn prepare_new_infos_for_pre_removing(&mut self) -> Result<()>
    {
        let res = self.prepare_new_infos_for_pre_removing_without_reset();
        self.pkgs.clear();
        match res {
            Ok(()) => {
                match rename(self.new_part_info_dir(), self.new_info_dir()) {
                    Ok(()) => Ok(()),
                    Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
                    Err(err) => Err(Error::Io(err)),
                }
            },
            Err(err) => {
                self.clean_after_error()?;
                Err(err)
            },
        }
    }
    
    fn io_res_install_pkg(&self, name: &PkgName, new_version: &Version, dir: &Path, paths: &Paths, is_doc: bool) -> io::Result<()>
    {
        let mut src_bin_dir = PathBuf::from(dir);
        src_bin_dir.push("bin");
        let dst_bin_dir = self.bin_dir.clone();
        let bin_paths: Vec<PathBuf> = paths.bin.iter().map(|s| PathBuf::from(s)).collect();
        recursively_copy_paths_in_dir(src_bin_dir, dst_bin_dir, bin_paths.as_slice())?;
        let mut src_lib_dir = PathBuf::from(dir);
        src_lib_dir.push("lib");
        let dst_lib_dir = self.lib_dir.clone();
        let lib_paths: Vec<PathBuf> = paths.lib.iter().map(|s| PathBuf::from(s)).collect();
        recursively_copy_paths_in_dir(src_lib_dir, dst_lib_dir, lib_paths.as_slice())?;
        if is_doc {
            let src_doc_dir = self.pkg_tmp_doc_dir(name, new_version);
            let dst_doc_dir = self.doc_dir.clone();
            recursively_copy_paths_in_dir(src_doc_dir, dst_doc_dir, lib_paths.as_slice())?;
        }
        create_dir_all(self.pkg_info_dir(name))?;
        let mut src_manifest_file = self.pkg_new_info_dir(name);
        src_manifest_file.push("manifest.toml");
        let mut dst_manifest_file = self.pkg_info_dir(name);
        dst_manifest_file.push("manifest.toml");
        copy(src_manifest_file, dst_manifest_file)?;
        let mut src_dependents_file = self.pkg_new_info_dir(name);
        src_dependents_file.push("dependents.toml");
        let mut dst_dependents_file = self.pkg_info_dir(name);
        dst_dependents_file.push("dependents.toml");
        copy(src_dependents_file, dst_dependents_file)?;
        let mut src_paths_file = self.pkg_new_info_dir(name);
        src_paths_file.push("paths.toml");
        let mut dst_paths_file = self.pkg_info_dir(name);
        dst_paths_file.push("paths.toml");
        rename(src_paths_file, dst_paths_file)?;
        Ok(())
    }

    fn io_res_copy_dependents_file(&self, name: &PkgName) -> io::Result<()>
    {
        create_dir_all(self.pkg_info_dir(name))?;
        let mut src_dependents_file = self.pkg_new_info_dir(name);
        src_dependents_file.push("dependents.toml");
        let mut dst_dependents_file = self.pkg_info_dir(name);
        dst_dependents_file.push("dependents.toml");
        match copy(src_dependents_file, dst_dependents_file) {
            Ok(_) => Ok(()),
            Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
            Err(err) => Err(err),
        }
    }
    
    fn install_pkg(&self, name: &PkgName, new_version: &Version, is_doc: bool) -> Result<()>
    {
        let mut paths_file = self.pkg_new_info_dir(name);
        paths_file.push("paths.toml");
        match Paths::load(paths_file) {
            Ok(paths) => {
                self.printer.print_installing_pkg(name, false);
                let mut src = self.create_source(name)?;
                src.set_current_version(new_version.clone());
                match self.io_res_install_pkg(name, new_version, src.dir()?, &paths, is_doc) {
                    Ok(()) => (),
                    Err(err) => return Err(Error::Io(err)),
                }
                self.printer.print_installing_pkg(name, true);
                Ok(())
            },
            Err(Error::Io(io_err)) if io_err.kind() == ErrorKind::NotFound => {
                match self.io_res_copy_dependents_file(name) {
                    Ok(()) => Ok(()),
                    Err(err) => Err(Error::Io(err)),
                }
            },
            Err(err) => Err(err),
        }
    }
    
    fn change_pkg(&self, name: &PkgName) -> Result<()>
    {
        match self.io_res_copy_dependents_file(name) {
            Ok(()) => Ok(()),
            Err(err) => Err(Error::Io(err)),
        }
    }
    
    fn io_res_remove_pkg(&self, name: &PkgName, paths: &Paths) -> io::Result<()>
    {
        let bin_dir = self.bin_dir.clone();
        let bin_paths: Vec<PathBuf> = paths.bin.iter().map(|s| PathBuf::from(s)).collect();
        recursively_remove_paths_in_dir(bin_dir, bin_paths.as_slice(), true)?;
        let lib_dir = self.lib_dir.clone();
        let lib_paths: Vec<PathBuf> = paths.lib.iter().map(|s| PathBuf::from(s)).collect();
        recursively_remove_paths_in_dir(lib_dir, lib_paths.as_slice(), true)?;
        let doc_dir = self.doc_dir.clone();
        recursively_remove_paths_in_dir(doc_dir, lib_paths.as_slice(), true)?;
        let mut manifest_file = self.pkg_info_dir(name);
        manifest_file.push("manifest.toml");
        recursively_remove(manifest_file, true)?;
        let mut dependents_file = self.pkg_info_dir(name);
        dependents_file.push("dependents.toml");
        recursively_remove(dependents_file, true)?;
        let mut paths_file = self.pkg_info_dir(name);
        paths_file.push("paths.toml");
        recursively_remove(paths_file, true)?;
        let mut tmp_suffix_path_buf = name.to_path_buf();
        tmp_suffix_path_buf.pop();
        while tmp_suffix_path_buf != PathBuf::from("") {
            let mut dir_path_buf = self.info_dir();
            dir_path_buf.push(tmp_suffix_path_buf.as_path());
            match remove_dir(dir_path_buf.as_path()) {
                Ok(()) => (),
                Err(_) => break,
            }
            tmp_suffix_path_buf.pop();
        }
        Ok(())
    }

    fn remove_pkg(&self, name: &PkgName) -> Result<()>
    {
        let mut paths_file = self.pkg_info_dir(name);
        paths_file.push("paths.toml");
        match Paths::load(paths_file) {
            Ok(paths) => {
                self.printer.print_removing_pkg(name, false);
                match self.io_res_remove_pkg(name, &paths) {
                    Ok(()) => (),
                    Err(err) => return Err(Error::Io(err)),
                }
                self.printer.print_removing_pkg(name, true);
                Ok(())
            },
            Err(Error::Io(io_err)) if io_err.kind() == ErrorKind::NotFound => Ok(()),
            Err(err) => Err(err),
        }
    }

    fn pkg_is_to_install(&self, name: &PkgName) -> Result<bool>
    {
        let mut paths_file = self.pkg_new_info_dir(name);
        paths_file.push("paths.toml");
        match fs::metadata(paths_file) {
            Ok(_) => Ok(true),
            Err(err) if err.kind() == ErrorKind::NotFound => Ok(false),
            Err(err) => Err(Error::Io(err)),
        }
    }

    fn install_pkgs(&self, is_doc: bool) -> Result<()>
    {
        let new_versions = self.pkg_versions_for_bucket("new_versions")?;
        for (name, _) in &new_versions {
            if self.pkg_is_to_install(name)? {
                self.remove_pkg(name)?;
            }
        }
        for (name, new_version) in &new_versions {
            self.install_pkg(name, new_version, is_doc)?;
        }
        self.printer.print_cleaning_after_install(false);
        match recursively_remove(self.work_tmp_dir(), true) {
            Ok(()) => (),
            Err(err) => return Err(Error::Io(err)),
        }
        self.move_pkg_versions_for_buckets("new_versions", "versions")?;
        match recursively_remove(self.new_info_dir(), true) {
            Ok(()) => (),
            Err(err) => return Err(Error::Io(err)),
        }
        self.printer.print_cleaning_after_install(true);
        Ok(())
    }

    fn change_pkgs(&self) -> Result<()>
    {
        let names = self.pkg_names_for_bucket("pkgs_to_change")?;
        for name in &names {
            self.change_pkg(name)?;
        }
        self.remove_bucket("pkgs_to_change")?;
        self.printer.print_cleaning_before_removal(false);
        match recursively_remove(self.new_info_dir(), true) {
            Ok(()) => (),
            Err(err) => return Err(Error::Io(err)),
        }
        self.printer.print_cleaning_before_removal(true);
        Ok(())
    }
    
    fn remove_pkgs(&self) -> Result<()>
    {
        let names = self.pkg_names_for_bucket("pkgs_to_remove")?;
        for name in &names {
            self.remove_pkg(name)?;
        }
        self.remove_pkg_versions_for_buckets("pkgs_to_remove", "versions")
    }
    
    /// Updates the versions of packages.
    pub fn update(&self, names: &[PkgName]) -> Result<()>
    {
        self.printer.print_updating();
        for name in names {
            let mut src = self.create_source(name)?;
            src.update()?;
        }
        Ok(())
    }
    
    /// Installs the specified packages with depedencies.
    ///
    /// This method overwrites the versions of packages if the update flag is set, otherwise
    /// the versions of the packages aren't updated. If the force flag is set, the packages with
    /// the dependencies are reinstalled. The documentations are installed for the packages if
    /// the documentation is set, otherwise the documentation aren't installed.
    pub fn install(&mut self, names: &[PkgName], is_update: bool, is_force: bool, is_doc: bool) -> Result<()>
    {
        self.printer.print_pre_installing();
        let mut visiteds: HashSet<PkgName> = HashSet::new();
        for name in names {
            self.prepare_new_infos_for_pre_installing(name, &mut visiteds, is_update, is_force)?;
        }
        self.check_new_infos_and_generate_docs_for_pre_installing(is_doc)?;
        self.printer.print_installing();
        self.install_pkgs(is_doc)?;
        Ok(())
    }
    
    /// Installs the dependencies for the current package.
    ///
    /// The unused packages are automatically removed from the work directory. See also
    /// [install](Self::install).
    pub fn install_deps(&mut self, is_update: bool, is_force: bool, is_doc: bool) -> Result<()>
    {
        self.printer.print_pre_installing();
        let mut visiteds: HashSet<PkgName> = HashSet::new();
        let current_pkg = Pkg::new();
        let manifest = current_pkg.manifest()?;
        let start_name = manifest.package.name.clone();
        self.constraints = manifest.constraints.map(|cs| cs.clone()).unwrap_or(Arc::new(HashMap::new()));
        self.sources = manifest.sources.map(|ss| ss.clone()).unwrap_or(Arc::new(HashMap::new()));
        self.pkgs.insert(start_name.clone(), current_pkg);
        self.prepare_new_infos_for_pre_installing(&start_name, &mut visiteds, is_update, is_force)?;
        self.add_pkg_names_for_buckets_and_autoremoving("pkgs_to_remove", "versions", &visiteds)?;
        self.check_new_infos_and_generate_docs_for_pre_installing(is_doc)?;
        self.printer.print_installing();
        self.install_pkgs(is_doc)?;
        self.printer.print_removing();
        self.remove_pkgs()?;
        Ok(())
    }
    
    /// Removes the specified packages.
    pub fn remove(&mut self, names: &[PkgName]) -> Result<()>
    {
        self.printer.print_pre_removing();
        self.add_pkg_names_for_bucket_and_removing("pkgs_to_remove", names)?;
        self.prepare_new_infos_for_pre_removing()?;
        self.printer.print_removing();
        self.change_pkgs()?;
        self.remove_pkgs()?;
        Ok(())
    }
    
    /// Checks whether the preparation to the last operation or the last operations was
    /// interrupted.
    ///
    /// If the preparation to the last operation or the last operation was interrupted, this
    /// method returns an error with the appropriate message.
    pub fn check_last_op(&self, are_deps: bool) -> Result<()>
    {
        let is_new_part_info_dir = match fs::metadata(self.new_part_info_dir()) {
            Ok(_) => true,
            Err(err) if err.kind() == ErrorKind::NotFound => false,
            Err(err) => return Err(Error::Io(err)),
        };
        if is_new_part_info_dir {
            if are_deps {
                return Err(Error::Pkg(String::from("Preparation to last operation was interrupted. Please call command 'unlab-pkg clean-deps' to clean after preparation.")));
            } else {
                return Err(Error::Pkg(String::from("Preparation to last operation was interrupted. Please call command 'unlab-pkg clean' to clean after preparation.")));
            }
        }
        let is_new_info_dir = match fs::metadata(self.new_info_dir()) {
            Ok(_) => true,
            Err(err) if err.kind() == ErrorKind::NotFound => false,
            Err(err) => return Err(Error::Io(err)),
        };
        if (is_new_info_dir && self.has_bucket("new_versions")?) || is_new_info_dir || self.has_bucket("pkgs_to_remove")? {
            if are_deps {
                return Err(Error::Pkg(String::from("Last operation was interrupted. Please call command 'unlab-pkg continue-deps' to complete last operation.")));
            } else {
                return Err(Error::Pkg(String::from("Last operation was interrupted. Please call command 'unlab-pkg continue' to complete last operation.")));
            }
        }
        Ok(())
    }

    /// Continues the interrupted last operation.
    pub fn cont(&self, is_doc: bool, are_deps: bool) -> Result<()>
    {
        let is_new_part_info_dir = match fs::metadata(self.new_part_info_dir()) {
            Ok(_) => true,
            Err(err) if err.kind() == ErrorKind::NotFound => false,
            Err(err) => return Err(Error::Io(err)),
        };
        if is_new_part_info_dir {
            return Ok(());
        }
        let is_new_info_dir = match fs::metadata(self.new_info_dir()) {
            Ok(_) => true,
            Err(err) if err.kind() == ErrorKind::NotFound => false,
            Err(err) => return Err(Error::Io(err)),
        };
        if is_new_info_dir && !self.has_bucket("pkgs_to_remove")? {
            self.printer.print_installing();
            self.install_pkgs(is_doc)?;
        } else if is_new_info_dir && (are_deps || !self.has_bucket("pkgs_to_remove")?) {
            self.printer.print_installing();
            self.printer.print_cleaning_after_install(false);
            match recursively_remove(self.new_info_dir(), true) {
                Ok(()) => (),
                Err(err) => return Err(Error::Io(err)),
            }
            self.printer.print_cleaning_after_install(true);
        }
        if self.has_bucket("pkgs_to_remove")? {
            self.printer.print_removing();
            if !are_deps {
                if is_new_info_dir && self.has_bucket("pkgs_to_change")? {
                    self.change_pkgs()?;
                } else if is_new_info_dir {
                    self.printer.print_cleaning_before_removal(false);
                    match recursively_remove(self.new_info_dir(), true) {
                        Ok(()) => (),
                        Err(err) => return Err(Error::Io(err)),
                    }
                    self.printer.print_cleaning_before_removal(true);
                }
            }
            self.remove_pkgs()?;
        }
        Ok(())
    }

    /// Cleans after the interrupted preparation to the last operation.
    pub fn clean(&self) -> Result<()>
    {
        let is_new_part_info_dir = match fs::metadata(self.new_part_info_dir()) {
            Ok(_) => true,
            Err(err) if err.kind() == ErrorKind::NotFound => false,
            Err(err) => return Err(Error::Io(err)),
        };
        if is_new_part_info_dir {
            self.printer.print_cleaning(false);
            self.remove_bucket("new_versions")?;
            self.remove_bucket("pkgs_to_remove")?;
            self.remove_bucket("pkgs_to_change")?;
            match self.io_res_remove_dirs_for_cleaning() {
                Ok(()) => (),
                Err(err) => return Err(Error::Io(err)),
            }
            self.printer.print_cleaning(true);
        }
        Ok(())
    }
    
    /// Updates the versions of all packages.
    pub fn update_all(&self) -> Result<()>
    {
        let mut names: Vec<PkgName> = Vec::new();
        self.pkg_versions_in(|name, _| {
                names.push(name.clone());
                Ok(())
        })?;
        self.update(names.as_slice())
    }

    /// Reinstalls all packages.
    ///
    /// See [install](Self::install).
    pub fn install_all(&mut self, is_update: bool, is_force: bool, is_doc: bool) -> Result<()>
    {
        let mut names: Vec<PkgName> = Vec::new();
        self.pkg_versions_in(|name, _| {
                let dependents = self.pkg_dependents(name)?;
                if dependents.map(|ds| ds.is_empty()).unwrap_or(true) {
                    names.push(name.clone());
                }
                Ok(())
        })?;
        self.install(names.as_slice(), is_update, is_force, is_doc)
    }
    
    fn io_res_remove_pkg_doc(&self, doc_paths: &DocPaths) -> io::Result<()>
    {
        let doc_paths: Vec<PathBuf> = doc_paths.doc.iter().map(|s| PathBuf::from(s)).collect();
        recursively_remove_paths_in_dir(self.doc_dir.as_path(), doc_paths.as_slice(), true)?;
        let mut doc_paths_file = self.work_dir.clone();
        doc_paths_file.push("doc-paths.toml");
        recursively_remove(doc_paths_file, true)?;
        Ok(())
    }

    /// Generates a documentation for the current package.
    pub fn generate_doc(&self) -> Result<()>
    {
        self.printer.print_documenting();
        let name = Self::manifest()?.package.name;
        let mut doc_paths_file = self.work_var_dir();
        doc_paths_file.push("doc-paths.toml");
        match DocPaths::load(doc_paths_file) {
            Ok(doc_paths) => {
                self.printer.print_removing_pkg_doc(&name, false);
                match self.io_res_remove_pkg_doc(&doc_paths) {
                    Ok(()) => (),
                    Err(err) => return Err(Error::Io(err)),
                }
                self.printer.print_removing_pkg_doc(&name, true);
            },
            Err(Error::Io(io_err)) if io_err.kind() == ErrorKind::NotFound => (),
            Err(err) => return Err(err),
        }
        {
            self.printer.print_searching_path_conflicts(false);
            let pkg_lib_dir = PathBuf::from("lib");
            check_dir_for_pkg(pkg_lib_dir.as_path(), &name, "lib in package isn't directory")?;
            let lib_paths = match conflicts(pkg_lib_dir, self.doc_dir.as_path(), &HashSet::new(), Some(2)) {
                Ok((conflict_paths, paths)) => {
                    if conflict_paths.is_empty() {
                        paths
                    } else {
                        return Err(Error::PkgPathConflicts(name.clone(), None, conflict_paths, PkgPathConflict::Doc));
                    }
                },
                Err(err) => return Err(Error::Io(err)),
            };
            let mut doc: Vec<String> = Vec::new();
            for lib_path in &lib_paths {
                match lib_path.to_str() {
                    Some(s) => doc.push(String::from(s)),
                    None => return Err(Error::PkgName(name.clone(), String::from("lib path contains invalid UTF-8 character"))),
                }
            }
            let doc_paths = DocPaths::new(doc);
            let mut doc_paths_file = self.work_var_dir();
            doc_paths_file.push("doc-paths.toml");
            doc_paths.save(doc_paths_file)?;
            self.printer.print_searching_path_conflicts(true);
        }
        {
            self.printer.print_documenting_pkg(&name, false);
            let mut doc_paths_file = self.work_var_dir();
            doc_paths_file.push("doc-paths.toml");
            let doc_paths = DocPaths::load(doc_paths_file)?;
            let pkg_lib_dir = PathBuf::from("lib");
            for path in &doc_paths.doc {
                let mut lib_doc_dir = self.doc_dir.clone();
                lib_doc_dir.push(path);
                match create_dir_all(lib_doc_dir.as_path()) {
                    Ok(()) => (),
                    Err(err) => return Err(Error::Io(err)),
                }
                generate_doc(pkg_lib_dir.as_path(), self.doc_dir.as_path(), path)?;
            }
            self.printer.print_documenting_pkg(&name, true);
        }
        Ok(())
    }
    
    /// Generates a documentation of the standard built-in functions.
    pub fn generate_std_doc(&self) -> Result<()>
    {
        self.printer.print_documenting();
        let name = PkgName::new(String::from("std/root"));
        let mut doc_path = PathBuf::from("std");
        doc_path.push("root");
        let mut lib_doc_dir = self.doc_dir.clone();
        lib_doc_dir.push(doc_path.as_path());
        match fs::metadata(lib_doc_dir.as_path()) {
            Ok(_) => {
                self.printer.print_removing_pkg_doc(&name, false);
                match recursively_remove_paths_in_dir(self.doc_dir.as_path(), &[doc_path.clone()], true) {
                    Ok(()) => (),
                    Err(err) => return Err(Error::Io(err)),
                }
                self.printer.print_removing_pkg_doc(&name, true);
            },
            Err(err) if err.kind() == ErrorKind::NotFound => (),
            Err(err) => return Err(Error::Io(err)),
        }
        {
            self.printer.print_documenting_pkg(&name, false);
            match create_dir_all(lib_doc_dir.as_path()) {
                Ok(()) => (),
                Err(err) => return Err(Error::Io(err)),
            }
            let mut sig_root_mod: ModNode<Sig, ()> = ModNode::new(());
            let mut doc_root_mod: ModNode<String, Option<String>> = ModNode::new(None);
            add_std_builtin_fun_doc(&mut sig_root_mod, &mut doc_root_mod);
            let doc_tree = DocTree::new(Arc::new(RwLock::new(sig_root_mod)), Arc::new(RwLock::new(doc_root_mod)));
            let doc_gen = DocGen::new(self.doc_dir.clone(), doc_path);
            doc_gen.generate(&doc_tree)?;
            self.printer.print_documenting_pkg(&name, true);
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests;