Welcome to mirror list, hosted at ThFree Co, Russian Federation.

reify.js « arborist « test « arborist « workspaces - github.com/npm/cli.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0c68bdd4dd7480be568f566ff06fd3cb040594e6 (plain)
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
const { join, resolve, basename } = require('path')
const t = require('tap')
const runScript = require('@npmcli/run-script')
const localeCompare = require('@isaacs/string-locale-compare')('en')
const tnock = require('../fixtures/tnock')

const fs = require('fs')

let failRm = false
let failRename = null
let failRenameOnce = null
let failMkdir = null
const { rename: realRename, rm: realRm, mkdir: realMkdir } = fs
const fsMock = {
  ...fs,
  mkdir (...args) {
    if (failMkdir) {
      process.nextTick(() => args.pop()(failMkdir))
      return
    }

    return realMkdir(...args)
  },
  rename (...args) {
    if (failRename) {
      process.nextTick(() => args.pop()(failRename))
    } else if (failRenameOnce) {
      const er = failRenameOnce
      failRenameOnce = null
      process.nextTick(() => args.pop()(er))
    } else {
      return realRename(...args)
    }
  },
  rm (...args) {
    if (failRm) {
      process.nextTick(() => args.pop()(new Error('rm fail')))
      return
    }

    realRm(...args)
  },
}
const mocks = {
  fs: fsMock,
  'fs/promises': {
    ...fs.promises,
    mkdir: async (...args) => {
      if (failMkdir) {
        throw failMkdir
      }

      return fs.promises.mkdir(...args)
    },
    rm: async (...args) => {
      if (failRm) {
        throw new Error('rm fail')
      }

      return fs.promises.rm(...args)
    },
  },
}

const oldLockfileWarning = [
  'warn',
  'old lockfile',
  `
The package-lock.json file was created with an old version of npm,
so supplemental metadata must be fetched from the registry.

This is a one-time fix-up, please be patient...
`,
]

// need this to be injected so that it doesn't pull from main cache
const moveFile = t.mock('@npmcli/move-file', { fs: fsMock })
mocks['@npmcli/move-file'] = moveFile

// track the warnings that are emitted.  returns a function that removes
// the listener and provides the list of what it saw.
const warningTracker = () => {
  const list = []
  const onlog = (...msg) => msg[0] === 'warn' && list.push(msg)
  process.on('log', onlog)
  return () => {
    process.removeListener('log', onlog)
    return list
  }
}

const debugLogTracker = () => {
  const list = []
  mockDebug.log = (...msg) => list.push(msg)
  return () => {
    mockDebug.log = () => {}
    return list
  }
}
const mockDebug = Object.assign(fn => fn(), { log: () => {} })

const Arborist = t.mock('../../lib/index.js', {
  ...mocks,
  // need to not mock this one, so we still can swap the process object
  '../../lib/signal-handling.js': require('../../lib/signal-handling.js'),

  // mock the debug so we can test these even when not enabled
  '../../lib/debug.js': mockDebug,
})

const { Node, Link, Shrinkwrap } = Arborist

const {
  start,
  stop,
  registry,
  advisoryBulkResponse,
} = require('../fixtures/registry-mocks/server.js')

t.before(start)
t.teardown(stop)

const cache = t.testdir()

const {
  normalizePath,
  normalizePaths,
  printTree,
} = require('../fixtures/utils.js')

const cwd = normalizePath(process.cwd())
t.cleanSnapshot = s => s.split(cwd).join('{CWD}')
  .split(registry).join('https://registry.npmjs.org/')

const fixture = (t, p) => require('../fixtures/reify-cases/' + p)(t)

const printReified = (path, opt) => reify(path, opt).then(printTree)

const newArb = (opt) => new Arborist({
  audit: false,
  cache,
  registry,
  // give it a very long timeout so CI doesn't crash as easily
  timeout: 30 * 60 * 1000,
  ...opt,
})

const reify = (path, opt) => newArb({ path, ...(opt || {}) }).reify(opt)

t.test('tarball deps with transitive tarball deps', t =>
  t.resolveMatchSnapshot(printReified(fixture(t, 'tarball-dependencies'))))

t.test('update a yarn.lock file', async t => {
  const path = fixture(t, 'yarn-lock-mkdirp')
  const tree = await reify(path, { add: ['abbrev'] })
  t.matchSnapshot(printTree(tree), 'add abbrev')
  t.matchSnapshot(fs.readFileSync(path + '/yarn.lock', 'utf8'), 'updated yarn lock')
})

t.test('weirdly broken lockfile without resolved value', t =>
  t.resolveMatchSnapshot(printReified(fixture(t, 'dep-missing-resolved'))))

t.test('testing-peer-deps package', t =>
  t.resolveMatchSnapshot(printReified(fixture(t, 'testing-peer-deps'))))

t.test('just the shrinkwrap', t => {
  const paths = [
    'cli-750-fresh',
    'yarn-lock-mkdirp',
  ]
  t.plan(paths.length)
  for (const p of paths) {
    t.test(p, async t => {
      const path = fixture(t, p)
      const arb = newArb({ path, audit: true, packageLockOnly: true })
      await arb.reify()
      t.ok(arb.auditReport, 'got an audit report')
      t.throws(() => fs.statSync(path + '/node_modules'), { code: 'ENOENT' })
      t.matchSnapshot(fs.readFileSync(path + '/package-lock.json', 'utf8'))
    })
  }
})

t.test('packageLockOnly can add deps', async t => {
  const path = t.testdir({ 'package.json': '{}' })
  await reify(path, { add: ['abbrev'], packageLockOnly: true })
  t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8'))
  t.matchSnapshot(fs.readFileSync(path + '/package-lock.json', 'utf8'))
  t.throws(() => fs.statSync(path + '/node_modules'), { code: 'ENOENT' })
})

t.test('malformed package.json should not be overwitten', async t => {
  t.plan(2)

  const path = fixture(t, 'malformed-json')
  const originalContent = fs.readFileSync(path + '/package.json', 'utf8')

  try {
    await reify(path)
  } catch (err) {
    t.match(err, { code: 'EJSONPARSE' }, 'should throw EJSONPARSE error')
  }

  const resultContent = fs.readFileSync(path + '/package.json', 'utf8')
  t.equal(
    resultContent,
    originalContent,
    'should not touch file contents on malformed json'
  )
})

t.test('packageLockOnly does not work on globals', t => {
  const path = t.testdir({ 'package.json': '{}' })
  return t.rejects(() => reify(path, { global: true, packageLockOnly: true }))
})

t.test('omit peer deps', t => {
  const path = fixture(t, 'testing-peer-deps')
  // in this one we also snapshot the timers, mostly just as a smoke test
  const timers = {}
  const finishedTimers = []
  const onTime = name => {
    t.notOk(timers[name], 'should not have duplicated timers started')
    timers[name] = true
  }
  const onTimeEnd = name => {
    t.ok(timers[name], 'should not end unstarted timer')
    delete timers[name]
    finishedTimers.push(name)
  }
  process.on('time', onTime)
  process.on('timeEnd', onTimeEnd)

  return reify(path, { omit: ['peer'] })
    .then(tree => {
      for (const node of tree.inventory.values()) {
        t.equal(node.peer, false, 'did not reify any peer nodes')
      }

      const lock = require(tree.path + '/package-lock.json')
      // eslint-disable-next-line promise/always-return
      for (const [loc, meta] of Object.entries(lock.packages)) {
        if (meta.peer) {
          t.throws(() => fs.statSync(resolve(path, loc)), 'peer not reified')
        } else {
          t.equal(fs.statSync(resolve(path, loc)).isDirectory(), true)
        }
      }
    })
  // eslint-disable-next-line promise/always-return
    .then(() => {
      process.removeListener('time', onTime)
      process.removeListener('timeEnd', onTimeEnd)
      finishedTimers.sort(localeCompare)
      t.matchSnapshot(finishedTimers, 'finished timers')
      t.strictSame(timers, {}, 'should have no timers in progress now')
    })
})

t.test('testing-peer-deps nested', t =>
  t.resolveMatchSnapshot(printReified(fixture(t, 'testing-peer-deps-nested'))))

t.test('a workspace with a duplicated nested conflicted dep', t =>
  t.resolveMatchSnapshot(printReified(fixture(t, 'workspace4'))))

t.test('testing-peer-deps nested with update', t =>
  t.resolveMatchSnapshot(printReified(fixture(t, 'testing-peer-deps-nested'), {
    update: { names: ['@isaacs/testing-peer-deps'] },
    save: false,
  })))

t.test('update a bundling node without updating all of its deps', t => {
  const path = fixture(t, 'tap-react15-collision-legacy-sw')

  // check that it links the bin
  const bin = resolve(path, 'node_modules/.bin/tap')
  const checkBin = process.platform === 'win32'
    ? () => t.ok(fs.statSync(bin + '.cmd').isFile(), 'created shim')
    : () => t.ok(fs.lstatSync(bin).isSymbolicLink(), 'created symlink')

  const checkPackageLock = () => {
    t.match(require(path + '/package-lock.json').packages['node_modules/fsevents'],
      {
        dev: true,
        optional: true,
      },
      'contains fsevents in lockfile')
  }

  return t.resolveMatchSnapshot(printReified(path, {
    saveType: 'dev',
    add: ['tap@14.10.5'],
    omit: ['optional'],
  }))
    .then(checkBin)
    .then(checkPackageLock)
})

t.test('Bundles rebuilt as long as rebuildBundle not false', async t => {
  t.test('rebuild the bundle', async t => {
    const path = fixture(t, 'testing-rebuild-bundle')
    const a = resolve(path, 'node_modules/@isaacs/testing-rebuild-bundle-a')
    const dir = resolve(a, 'node_modules/@isaacs/testing-rebuild-bundle-b')
    const file = resolve(dir, 'cwd')
    await reify(path)
    t.equal(fs.readFileSync(file, 'utf8'), dir)
  })
  t.test('do not rebuild the bundle', async t => {
    const path = fixture(t, 'testing-rebuild-bundle')
    const a = resolve(path, 'node_modules/@isaacs/testing-rebuild-bundle-a')
    const dir = resolve(a, 'node_modules/@isaacs/testing-rebuild-bundle-b')
    const file = resolve(dir, 'cwd')
    await reify(path, { rebuildBundle: false })
    t.throws(() => fs.statSync(file))
  })
})

t.test('transitive deps containing asymmetrical bin no lockfile', t => {
  const path = fixture(t, 'testing-asymmetrical-bin-no-lock')

  // check that it links the bin
  const bin = resolve(path, 'node_modules/.bin/b')
  const checkBin = process.platform === 'win32'
    ? () => t.ok(fs.statSync(bin + '.cmd').isFile(), 'created shim')
    : () => t.ok(fs.lstatSync(bin).isSymbolicLink(), 'created symlink')

  return t.resolveMatchSnapshot(printReified(path, { packageLock: false }))
    .then(checkBin)
    .then(() => t.throws(() => fs.statSync(path + '/package-lock.json')))
})

t.test('transitive deps containing asymmetrical bin with lockfile', t => {
  const path = fixture(t, 'testing-asymmetrical-bin-with-lock')

  // check that it links the bin
  const bin = resolve(path, 'node_modules/.bin/b')
  const checkBin = process.platform === 'win32'
    ? () => t.ok(fs.statSync(bin + '.cmd').isFile(), 'created shim')
    : () => t.ok(fs.lstatSync(bin).isSymbolicLink(), 'created symlink')

  return t.resolveMatchSnapshot(printReified(path, {}))
    .then(checkBin)
})

t.test('omit optional dep', t => {
  const path = fixture(t, 'tap-react15-collision-legacy-sw')
  const ignoreScripts = true

  const arb = newArb({ path, ignoreScripts })
  // eslint-disable-next-line promise/always-return
  return arb.reify({ omit: ['optional'] }).then(tree => {
    t.equal(tree.children.get('fsevents'), undefined, 'no fsevents in tree')
    t.throws(() => fs.statSync(path + '/node_modules/fsevents'), 'no fsevents unpacked')
    t.match(require(path + '/package-lock.json').packages['node_modules/fsevents'], {
      dev: true,
      optional: true,
    }, 'fsevents present in lockfile')
  })
    .then(() => t.ok(arb.diff, 'has a diff tree'))
})

t.test('dev, optional, devOptional flags and omissions', t => {
  const path = 'testing-dev-optional-flags'
  const omits = [['dev'], ['dev', 'optional'], ['optional']]
  t.plan(omits.length)
  omits.forEach(omit => t.test(omit.join(','), t =>
    t.resolveMatchSnapshot(printReified(fixture(t, path), {
      omit,
    }))))
})

t.test('omits when both dev and optional flags are set', t => {
  const path = 'testing-dev-optional-flags-2'
  const omits = [['dev'], ['optional']]
  t.plan(omits.length)
  omits.forEach(omit => t.test(omit.join(','), t =>
    t.resolveMatchSnapshot(printReified(fixture(t, path), {
      omit,
    }))))
})

t.test('bad shrinkwrap file', t =>
  t.resolveMatchSnapshot(printReified(fixture(t, 'testing-peer-deps-bad-sw'))))

t.test('multiple bundles at the same level', t => {
  const path = fixture(t, 'two-bundled-deps')
  const a = newArb({ path })
  return a.reify().then(tree => {
    const root = tree.root
    const p = printTree(tree)
    // just fail on the failures, we don't need a zillion tap lines here
    for (const n of tree.inventory.values()) {
      if (n.root !== root) {
        t.equal(n.root, root, 'in same tree')
      } else {
        for (const e of n.edgesIn) {
          if (e.from.root !== root) {
            t.equal(e.from.root, root,
              `edge in same tree ${e.from.location} -> ${n.location}`)
          }
        }
      }
    }
    return t.matchSnapshot(p)
  })
})

t.test('update a node without updating its children', t =>
  t.resolveMatchSnapshot(printReified(fixture(t, 'once-outdated'),
    { update: { names: ['once'] }, save: false })))

t.test('do not add shrinkwrapped deps', t =>
  t.resolveMatchSnapshot(printReified(
    fixture(t, 'shrinkwrapped-dep-no-lock'), { update: true })))

t.test('do not update shrinkwrapped deps', t =>
  t.resolveMatchSnapshot(printReified(
    fixture(t, 'shrinkwrapped-dep-with-lock'),
    { update: { names: ['abbrev'] } })))

t.test('tracks changes of shrinkwrapped dep correctly', async t => {
  const path = t.testdir({
    'package.json': '{}',
  })

  const install1 = await printReified(path, { add: ['@nlf/shrinkwrapped-dep-updates-a@1.0.0'] })
  t.matchSnapshot(install1, 'install added the correct tree')

  const update1 = await printReified(path, { update: true })
  t.match(install1, update1, 'update maintains the same correct tree')

  const install2 = await printReified(path, { add: ['@nlf/shrinkwrapped-dep-updates-a@2.0.0'] })
  t.matchSnapshot(install2, 'installing new version brings in the correct children')

  const update2 = await printReified(path, { update: true })
  t.match(install2, update2, 'update maintains the same correct tree')

  // delete a dependency that was installed as part of the shrinkwrap
  fs.rmSync(resolve(path, 'node_modules/@nlf/shrinkwrapped-dep-updates-a/node_modules/@nlf/shrinkwrapped-dep-updates-b'), { recursive: true, force: true })
  const repair = await printReified(path)
  t.match(repair, install2, 'tree got repaired')
})

t.test('do not install optional deps with mismatched platform specifications', t =>
  t.resolveMatchSnapshot(printReified(
    fixture(t, 'optional-platform-specification'))))

t.test('still do not install optional deps with mismatched platform specifications even when forced', t =>
  t.resolveMatchSnapshot(printReified(
    fixture(t, 'optional-platform-specification'), { force: true })))

t.test('fail to install deps with mismatched platform specifications', t =>
  t.rejects(printReified(fixture(t, 'platform-specification')), { code: 'EBADPLATFORM' }))

t.test('dry run, do not get anything wet', async t => {
  const cases = [
    'shrinkwrapped-dep-with-lock-empty',
    'shrinkwrapped-dep-no-lock-empty',
    'link-dep-empty',
    'link-meta-deps-empty',
    'testing-bundledeps-empty',
  ]
  t.plan(cases.length)
  cases.forEach(c => t.test(c, async t => {
    const path = fixture(t, c)
    const arb = newArb({ path, dryRun: true })
    t.matchSnapshot(printTree(await arb.reify()))
    t.throws(() => fs.statSync(resolve(path, 'node_modules')))
    t.ok(arb.diff)
  }))
})

t.test('reifying with shronk warp dep', t => {
  const cases = [
    'shrinkwrapped-dep-with-lock',
    'shrinkwrapped-dep-with-lock-empty',
    'shrinkwrapped-dep-no-lock',
    'shrinkwrapped-dep-no-lock-empty',
  ]
  t.plan(cases.length)
  for (const c of cases) {
    t.test(c, async t => {
      const path = fixture(t, c)
      const tree = await printReified(path, {
        // set update so that we don't start the idealTree
        // with the actualTree, and can see that the deps
        // are indeed getting set up from the shrink wrap
        update: /no-lock/.test(c),
      })
      t.matchSnapshot(tree)
      const dep = `${path}/node_modules/@isaacs/shrinkwrapped-dependency`
      t.equal(fs.statSync(`${dep}/package.json`).isFile(), true, 'has package.json')
    })
  }
})

t.test('link deps already in place', t =>
  t.resolveMatchSnapshot(printReified(fixture(t, 'link-dep'))))
t.test('create link deps', t =>
  t.resolveMatchSnapshot(printReified(fixture(t, 'link-dep-empty'))))

t.test('link meta deps, fresh install', t =>
  t.resolveMatchSnapshot(printReified(fixture(t, 'link-meta-deps-empty'))))
t.test('link meta deps, update', t =>
  t.resolveMatchSnapshot(printReified(fixture(t, 'link-meta-deps'), {
    // use legacy nesting so we leave the link nested
    legacyNesting: true,
    add: [
      '@isaacs/testing-link-dep@2',
      '@isaacs/testing-link-dev-dep@2',
    ],
  })))

t.test('update a child of a node with bundled deps', t => {
  const path = fixture(t, 'testing-bundledeps-legacy-bundling')
  return t.resolveMatchSnapshot(printReified(path, {
    update: ['@isaacs/testing-bundledeps-c'],
    installStrategy: 'nested',
  }))
})

t.test('update a node without updating a child that has bundle deps', t => {
  const path = fixture(t, 'testing-bundledeps-3')
  return t.resolveMatchSnapshot(printReified(path, {
    update: ['@isaacs/testing-bundledeps-parent'],
    save: false,
  }))
})

t.test('optional dependency failures', t => {
  const cases = [
    'optional-dep-tgz-missing',
    'optional-metadep-tgz-missing',
    'optional-dep-preinstall-fail',
    'optional-dep-install-fail',
    'optional-dep-postinstall-fail',
    'optional-dep-allinstall-fail',
    'optional-metadep-preinstall-fail',
    'optional-metadep-install-fail',
    'optional-metadep-postinstall-fail',
    'optional-metadep-allinstall-fail',
  ]
  t.plan(cases.length * 2)
  let p = [...cases.map(c => t.test(`${c} save=false`, t =>
    t.resolveMatchSnapshot(printReified(fixture(t, c),
      { update: true, save: false }))))]

  // npm update --save
  p = [...cases.map(c => t.test(`${c} save=true`, t =>
    t.resolveMatchSnapshot(printReified(fixture(t, c),
      { update: true, save: true }))))]
  return p
})

t.test('failure to fetch prod dep is failure', t =>
  t.rejects(printReified(fixture(t, 'prod-dep-tgz-missing'))))

t.test('failing script means install failure, unless ignoreScripts', t => {
  const cases = [
    'prod-dep-preinstall-fail',
    'prod-dep-install-fail',
    'prod-dep-postinstall-fail',
    'prod-dep-allinstall-fail',
  ]

  t.plan(cases.length * 2)

  cases.forEach(c => {
    t.test(c, t =>
      t.rejects(printReified(fixture(t, c))))
    t.test(c + ' --ignore-scripts', t =>
      t.resolveMatchSnapshot(printReified(
        fixture(t, c), { ignoreScripts: true })))
  })
})

t.test('link metadep', t => {
  const cases = [
    'cli-750',
    'cli-750-fresh',
  ]
  t.plan(cases.length)
  cases.forEach(c => t.test(c, t =>
    t.resolveMatchSnapshot(printReified(fixture(t, c)))))
})

t.test('warn on reifying deprecated dependency', t => {
  const a = newArb({
    path: fixture(t, 'deprecated-dep'),
    lockfileVersion: 1,
  })
  const check = warningTracker()
  return a.reify({ update: true }).then(() => t.match(check(), [
    [
      'warn',
      'deprecated',
      'mkdirp@0.5.3: Legacy versions of mkdirp are no longer supported. ' +
      'Please update to mkdirp 1.x. (Note that the API surface has changed ' +
      'to use Promises in 1.x.)',
    ],
  ]))
})

t.test('rollbacks', { buffered: false }, t => {
  t.test('fail retiring shallow nodes', t => {
    const path = fixture(t, 'testing-bundledeps-3')
    const a = newArb({ path, installStrategy: 'nested' })
    const expect = new Error('rename fail')
    const kRenamePath = Symbol.for('renamePath')
    const renamePath = a[kRenamePath]
    a[kRenamePath] = (from, to) => {
      a[kRenamePath] = renamePath
      failRename = expect
      return a[kRenamePath](from, to)
    }
    const kRollback = Symbol.for('rollbackRetireShallowNodes')
    const rollbackRetireShallowNodes = a[kRollback]
    let rolledBack = false
    a[kRollback] = er => {
      rolledBack = true
      failRename = null
      t.equal(er, expect)
      a[kRollback] = rollbackRetireShallowNodes
      return a[kRollback](er)
    }

    return t.rejects(a.reify({
      update: ['@isaacs/testing-bundledeps-parent'],
    }), expect).then(() => t.equal(rolledBack, true, 'rolled back'))
  })

  t.test('fail retiring nodes because rm fails after eexist', t => {
    const path = fixture(t, 'testing-bundledeps-3')
    const a = newArb({ path, installStrategy: 'nested' })
    const eexist = new Error('rename fail')
    eexist.code = 'EEXIST'
    const kRenamePath = Symbol.for('renamePath')
    const renamePath = a[kRenamePath]
    a[kRenamePath] = (from, to) => {
      a[kRenamePath] = renamePath
      failRename = eexist
      failRm = true
      return a[kRenamePath](from, to)
    }
    const kRollback = Symbol.for('rollbackRetireShallowNodes')
    const rollbackRetireShallowNodes = a[kRollback]
    let rolledBack = false
    a[kRollback] = er => {
      rolledBack = true
      failRename = new Error('some other error')
      failRm = false
      t.match(er, new Error('rm fail'))
      a[kRollback] = rollbackRetireShallowNodes
      return a[kRollback](er).then(er => {
        failRename = null
        return er
      }, er => {
        failRename = null
        throw er
      })
    }

    return t.rejects(a.reify({
      update: ['@isaacs/testing-bundledeps-parent'],
    }), new Error('rm fail'))
      .then(() => t.equal(rolledBack, true, 'rolled back'))
  })

  t.test('fail retiring node, but then rm fixes it', async t => {
    const path = fixture(t, 'testing-bundledeps-3')
    const a = newArb({ path, installStrategy: 'nested' })
    const eexist = new Error('rename fail')
    eexist.code = 'EEXIST'
    const kRenamePath = Symbol.for('renamePath')
    const renamePath = a[kRenamePath]
    a[kRenamePath] = (from, to) => {
      a[kRenamePath] = renamePath
      failRenameOnce = eexist
      return a[kRenamePath](from, to)
    }
    const kRollback = Symbol.for('rollbackRetireShallowNodes')
    const rollbackRetireShallowNodes = a[kRollback]
    a[kRollback] = er => {
      t.fail('should not roll back!')
      a[kRollback] = rollbackRetireShallowNodes
      return a[kRollback](er)
    }

    const tree = await a.reify({
      update: ['@isaacs/testing-bundledeps-parent'],
      save: false,
    })
    return printTree(tree)
  })

  t.test('fail creating sparse tree', t => {
    t.teardown(() => failMkdir = null)
    const path = fixture(t, 'testing-bundledeps-3')
    const a = newArb({ path, installStrategy: 'nested' })
    const kCreateST = Symbol.for('createSparseTree')
    const createSparseTree = a[kCreateST]
    a[kCreateST] = () => {
      a[kCreateST] = createSparseTree
      failMkdir = new Error('poop')
      return a[kCreateST]()
    }
    const kRollback = Symbol.for('rollbackCreateSparseTree')
    const rollbackCreateSparseTree = a[kRollback]
    a[kRollback] = er => {
      t.match(er, new Error('poop'))
      a[kRollback] = rollbackCreateSparseTree
      return a[kRollback](er)
    }

    return t.rejects(a.reify({
      update: ['@isaacs/testing-bundledeps-parent'],
    }).then(() => 'it worked'), new Error('poop'))
  })

  t.test('fail rolling back from creating sparse tree', t => {
    failMkdir = null
    failRm = null
    const path = fixture(t, 'testing-bundledeps-3')
    const a = newArb({ path, installStrategy: 'nested' })

    const kCreateST = Symbol.for('createSparseTree')
    const kRetireShallowNodes = Symbol.for('retireShallowNodes')
    const retireShallowNodes = a[kRetireShallowNodes]
    a[kRetireShallowNodes] = async () => {
      a[kRetireShallowNodes] = retireShallowNodes
      await a[kRetireShallowNodes]()
      failRm = true
    }
    const createSparseTree = a[kCreateST]
    t.teardown(() => failMkdir = null)
    a[kCreateST] = () => {
      a[kCreateST] = createSparseTree
      failMkdir = new Error('poop')
      return a[kCreateST]()
    }
    const kRollback = Symbol.for('rollbackCreateSparseTree')
    const rollbackCreateSparseTree = a[kRollback]
    a[kRollback] = er => {
      t.match(er, new Error('poop'))
      a[kRollback] = rollbackCreateSparseTree
      return a[kRollback](er)
    }

    const check = warningTracker()
    return t.rejects(a.reify({
      update: ['@isaacs/testing-bundledeps-parent'],
    }).then(tree => 'it worked'), new Error('poop'))
    // eslint-disable-next-line promise/always-return
      .then(() => {
        const warnings = check()
        t.equal(warnings.length, 2)
        t.match(warnings, [
          oldLockfileWarning,
          [
            'warn',
            'cleanup',
            'Failed to remove some directories',
            [[String, new Error('rm fail')]],
          ],
        ])
      })
      .then(() => failRm = false)
  })

  t.test('fail loading shrinkwraps and updating trees', t => {
    const path = fixture(t, 'shrinkwrapped-dep-no-lock-empty')
    const a = newArb({ path, installStrategy: 'nested' })
    const kLoadSW = Symbol.for('loadShrinkwrapsAndUpdateTrees')
    const loadShrinkwrapsAndUpdateTrees = a[kLoadSW]
    a[kLoadSW] = seen => {
      a[kLoadSW] = loadShrinkwrapsAndUpdateTrees
      const kDiff = Symbol.for('diffTrees')
      const diffTrees = a[kDiff]
      a[kDiff] = () => {
        a[kDiff] = diffTrees
        return Promise.reject(new Error('poop'))
      }
      return a[kLoadSW](seen)
    }
    const kRollback = Symbol.for('rollbackCreateSparseTree')
    const rollbackCreateSparseTree = a[kRollback]
    a[kRollback] = er => {
      t.match(er, new Error('poop'))
      a[kRollback] = rollbackCreateSparseTree
      return a[kRollback](er)
    }

    return t.rejects(a.reify(), new Error('poop'))
  })

  t.test('fail loading bundles and updating trees', t => {
    const path = fixture(t, 'two-bundled-deps')
    const a = newArb({ path, installStrategy: 'nested' })
    const kLoadBundles = Symbol.for('loadBundlesAndUpdateTrees')
    const loadBundlesAndUpdateTrees = a[kLoadBundles]
    a[kLoadBundles] = (depth, bundlesByDepth) => {
      const kRN = Symbol.for('reifyNode')
      const reifyNode = a[kRN]
      a[kRN] = node => {
        a[kRN] = reifyNode
        return Promise.reject(new Error('poop'))
      }
      a[kLoadBundles] = loadBundlesAndUpdateTrees
      return a[kLoadBundles](depth, bundlesByDepth)
    }
    return t.rejects(a.reify(), new Error('poop'))
  })

  t.test('fail unpacking new modules', t => {
    const path = fixture(t, 'two-bundled-deps')
    const a = newArb({ path, installStrategy: 'nested' })
    const kUnpack = Symbol.for('unpackNewModules')
    const unpackNewModules = a[kUnpack]
    a[kUnpack] = () => {
      const kReify = Symbol.for('reifyNode')
      const reifyNode = a[kReify]
      a[kReify] = node => {
        a[kReify] = reifyNode
        return Promise.reject(new Error('poop'))
      }
      a[kUnpack] = unpackNewModules
      return a[kUnpack]()
    }
    return t.rejects(a.reify(), new Error('poop'))
  })

  t.test('fail moving back retired unchanged', t => {
    const path = fixture(t, 'testing-bundledeps-3')
    const a = newArb({ path, installStrategy: 'nested' })
    const kMoveback = Symbol.for('moveBackRetiredUnchanged')

    const moveBackRetiredUnchanged = a[kMoveback]
    a[kMoveback] = () => {
      a[kMoveback] = moveBackRetiredUnchanged
      const kMoveContents = Symbol.for('moveContents')
      const moveContents = a[kMoveContents]
      a[kMoveContents] = () => {
        a[kMoveContents] = moveContents
        return Promise.reject(new Error('poop'))
      }
      return a[kMoveback]()
    }
    const kRollback = Symbol.for('rollbackMoveBackRetiredUnchanged')
    const rollbackMoveBackRetiredUnchanged = a[kRollback]
    a[kRollback] = er => {
      t.match(er, new Error('poop'))
      a[kRollback] = rollbackMoveBackRetiredUnchanged
      return a[kRollback](er)
    }
    return t.rejects(a.reify({
      update: ['@isaacs/testing-bundledeps-parent'],
    }), new Error('poop'))
  })

  t.test('fail removing retired and deleted nodes', t => {
    const path = fixture(t, 'testing-bundledeps-3')
    const a = newArb({ path, installStrategy: 'nested' })
    const kRemove = Symbol.for('removeTrash')
    const removeRetiredAndDeletedNodes = a[kRemove]
    a[kRemove] = () => {
      failRm = true
      a[kRemove] = removeRetiredAndDeletedNodes
      return a[kRemove]()
    }
    const check = warningTracker()

    return t.resolveMatchSnapshot(a.reify({
      update: ['@isaacs/testing-bundledeps-parent'],
      save: false,
      // eslint-disable-next-line promise/always-return
    }).then(tree => printTree(tree))).then(() => {
      const warnings = check()
      t.equal(warnings.length, 2)
      t.match(warnings, [
        oldLockfileWarning,
        [
          'warn',
          'cleanup',
          'Failed to remove some directories',
          [[String, new Error('rm fail')]],
        ],
      ])
    })
      .then(() => failRm = false)
  })

  t.end()
})

t.test('saving the ideal tree', t => {
  const kSaveIdealTree = Symbol.for('saveIdealTree')
  t.test('save=false', async t => {
    // doesn't actually do anything, just for coverage.
    // if it wasn't an early exit, it'd blow up and throw
    // an error though.
    const path = t.testdir()
    const a = newArb({ path })
    t.notOk(await a[kSaveIdealTree]({ save: false }))
  })

  t.test('save some stuff', t => {
    const pkg = {
      bundleDependencies: ['a', 'b', 'c'],
      dependencies: {
        a: 'git+ssh://git@github.com:foo/bar#baz',
        b: '',
        d: 'npm:c@1.x <1.9.9',
        e: '*',
        f: 'git+https://user:pass@github.com/baz/quux#asdf',
        g: '',
        h: '~1.2.3',
      },
      devDependencies: {
        c: `git+ssh://git@githost.com:a/b/c.git#master`,
      },
      workspaces: [
        'e',
      ],
    }

    const npa = require('npm-package-arg')
    const kResolvedAdd = Symbol.for('resolvedAdd')
    const path = t.testdir({
      'package.json': JSON.stringify(pkg),
      e: {
        'package.json': JSON.stringify({ name: 'e' }),
      },
      node_modules: {
        e: t.fixture('symlink', '../e'),
      },
    })
    const a = newArb({ path })
    const hash = '71f3ccfefba85d2048484569dba8c1829f6f41d7'
    return a.loadActual().then(tree => Shrinkwrap.load({ path }).then(meta => {
      tree.meta = meta
      meta.add(tree)
      return tree
    })).then(async tree => {
      // saving swaps the ideal tree onto the actual tree
      a.idealTree = tree

      // simulated child nodes
      // Note: these all show up as "extraneous" in the lockfile,
      // because we don't do the calcDepFlags step in this simulation,
      // but since we're only testing the saving step, that's fine.
      new Node({
        name: 'a',
        resolved: `git+ssh://git@github.com:foo/bar#${hash}`,
        parent: tree,
        pkg: {},
      })
      new Node({
        name: 'b',
        resolved: 'https://registry.npmjs.org/b/-/b-1.2.3.tgz',
        pkg: { version: '1.2.3', name: 'b' },
        parent: tree,
      })
      new Node({
        name: 'c',
        resolved: `git+ssh://git@githost.com:a/b/c.git#${hash}`,
        parent: tree,
        pkg: {},
      })
      new Node({
        name: 'd',
        resolved: 'https://registry.npmjs.org/c/-/c-1.2.3.tgz',
        pkg: {
          name: 'c',
          version: '1.2.3',
        },
        parent: tree,
      })
      new Node({
        name: 'f',
        resolved: `git+https://user:pass@github.com/baz/quux#${hash}`,
        pkg: {
          name: 'f',
          version: '1.2.3',
        },
        parent: tree,
      })
      new Node({
        name: 'g',
        resolved: 'https://registry.npmjs.org/g/-/g-1.2.3.tgz',
        pkg: {
          name: 'g', // no version, somehow
        },
        parent: tree,
      })
      new Node({
        name: 'h',
        resolved: 'https://registry.npmjs.org/h/-/h-1.2.3.tgz',
        pkg: {
          name: 'h',
          version: '1.2.3',
        },
        parent: tree,
      })

      const target = new Node({
        name: 'e',
        pkg: {
          name: 'e',
        },
        path: resolve(tree.path, 'e'),
        fsParent: tree,
      })
      new Link({
        name: 'e',
        realpath: target.path,
        path: resolve(tree.path, 'node_modules/e'),
        resolved: 'file:../e',
        pkg: {
          name: 'e',
        },
      })

      a[kResolvedAdd] = [
        npa('a@git+ssh://git@github.com:foo/bar#baz'),
        npa('b'),
        npa('d@npm:c@1.x <1.9.9'),
        npa('c@git+ssh://git@githost.com:a/b/c.git#master'),
        npa('e'),
        npa('f@git+https://user:pass@github.com/baz/quux#asdf'),
        npa('g'),
        npa('h@~1.2.3'),
      ].map(spec => Object.assign(spec, { tree }))

      // NB: these are all going to be marked as extraneous, because we're
      // skipping the actual buildIdealTree step that flags them properly
      return a[kSaveIdealTree]({})
      // eslint-disable-next-line promise/always-return
    }).then(saved => {
      t.ok(saved, 'true, because it was saved')
      t.matchSnapshot(require(path + '/package-lock.json'), 'lock after save')
      t.strictSame(require(path + '/package.json'), {
        bundleDependencies: ['a', 'b', 'c'],
        dependencies: {
          a: 'github:foo/bar#baz',
          b: '^1.2.3',
          d: 'npm:c@1.x <1.9.9',
          e: '*',
          f: 'git+https://user:pass@github.com/baz/quux.git#asdf',
          g: '*',
          h: '~1.2.3',
        },
        workspaces: [
          'e',
        ],
        devDependencies: {
          c: 'git+ssh://git@githost.com:a/b/c.git#master',
        },
      })
    })
  })

  t.end()
})

t.test('scoped registries', async t => {
  const path = t.testdir()

  // this is a very artifical test that is setting a lot of internal things
  // up so that we assert that the intended behavior of sending right
  // resolved data for pacote.extract is working as intended, alternatively
  // we might prefer to replace this with a proper parallel alternative
  // registry server so that we can have more of an integration test instead
  let sawPacoteExtract = false
  const pacote = {
    extract: res => {
      sawPacoteExtract = true
      t.matchSnapshot(
        res,
        'should preserve original resolved value'
      )
      return true
    },
  }
  const ArboristMock = t.mock('../../lib/arborist', {
    ...mocks,
    pacote,
  })
  const a = new ArboristMock({
    audit: false,
    path,
    cache,
    registry,
  })
  const kReify = Symbol.for('reifyNode')
  a.addTracker('reify')
  a.idealTree = new Node({ path })

  const node = new Node({
    name: '@ruyadorno/theoretically-private-pkg',
    resolved: 'https://npm.pkg.github.com/@ruyadorno/' +
      'theoretically-private-pkg/-/theoretically-private-pkg-1.2.3.tgz',
    pkg: { version: '1.2.3', name: '@ruyadorno/theoretically-private-pkg' },
    parent: a.idealTree,
  })
  await a[kReify](node)
  t.equal(sawPacoteExtract, true, 'saw pacote extraction')
})

t.test('bin links adding and removing', t => {
  const path = t.testdir({
    'package.json': JSON.stringify({}),
  })
  const rbin = resolve(path, 'node_modules/.bin/rimraf')
  return reify(path, { add: ['rimraf@2.7.1'] })
    .then(() => fs.statSync(rbin)) // should be there
    .then(() => reify(path, { rm: ['rimraf'] }))
    .then(() => t.throws(() => fs.statSync(rbin))) // should be gone
})

t.test('global style', t => {
  const path = t.testdir()
  const nm = resolve(path, 'node_modules')
  const rbinPart = '.bin/rimraf' +
    (process.platform === 'win32' ? '.cmd' : '')
  const rbin = resolve(nm, rbinPart)
  return reify(path, { add: ['rimraf@2'], installStrategy: 'shallow' })
    .then(() => fs.statSync(rbin))
    .then(() => t.strictSame(fs.readdirSync(nm).sort(), ['.bin', '.package-lock.json', 'rimraf']))
})

t.test('global', t => {
  const isWindows = process.platform === 'win32'

  const path = t.testdir({ lib: {} })
  const lib = resolve(path, 'lib')
  const nm = resolve(lib, 'node_modules')

  const binTarget = isWindows ? lib : resolve(path, 'bin')
  const rimrafBin = resolve(binTarget, isWindows ? 'rimraf.cmd' : 'rimraf')
  const semverBin = resolve(binTarget, isWindows ? 'semver.cmd' : 'semver')

  t.test('add rimraf', t =>
    reify(lib, { add: ['rimraf@2'], global: true })
      .then(() => fs.statSync(rimrafBin))
      .then(() => t.strictSame(fs.readdirSync(nm), ['rimraf'])))

  t.test('add semver', t =>
    reify(lib, { add: ['semver@6.3.0'], global: true })
      .then(() => fs.statSync(rimrafBin))
      .then(() => fs.statSync(semverBin))
      .then(() => t.strictSame(fs.readdirSync(nm).sort(), ['rimraf', 'semver'])))

  t.test('remove semver', t =>
    reify(lib, { rm: ['semver'], global: true })
      .then(() => fs.statSync(rimrafBin))
      .then(() => t.throws(() => fs.statSync(semverBin)))
      .then(() => t.strictSame(fs.readdirSync(nm), ['rimraf'])))

  t.test('remove rimraf', t =>
    reify(lib, { rm: ['rimraf'], global: true })
      .then(() => t.throws(() => fs.statSync(rimrafBin)))
      .then(() => t.throws(() => fs.statSync(semverBin)))
      .then(() => t.strictSame(fs.readdirSync(nm), [])))

  t.test('add without bin links', t =>
    reify(lib, { add: ['rimraf@2'], global: true, binLinks: false })
      .then(() => t.throws(() => fs.statSync(rimrafBin)))
      .then(() => t.throws(() => fs.statSync(semverBin)))
      .then(() => t.strictSame(fs.readdirSync(nm), ['rimraf'])))

  t.end()
})

t.test('workspaces', t => {
  t.test('reify simple-workspaces', t =>
    t.resolveMatchSnapshot(printReified(fixture(t, 'workspaces-simple')), 'should reify simple workspaces'))

  t.test('reify workspaces lockfile', async t => {
    const path = fixture(t, 'workspaces-simple')
    await reify(path)
    t.matchSnapshot(require(path + '/package-lock.json'), 'should lock workspaces config')
  })

  t.test('reify workspaces bin files', t => {
    const path = fixture(t, 'workspaces-link-bin')

    const bins = [
      resolve(path, 'node_modules/.bin/a'),
      resolve(path, 'node_modules/.bin/b'),
    ]

    const checkBin = () => {
      for (const bin of bins) {
        if (process.platform === 'win32') {
          t.ok(fs.statSync(bin + '.cmd').isFile(), 'created shim')
        } else {
          t.ok(fs.lstatSync(bin).isSymbolicLink(), 'created symlink')
        }
      }
    }

    return t.resolveMatchSnapshot(printReified(path, {}))
      .then(checkBin)
  })

  t.test('reify from an actual loaded workspace env', t =>
    t.resolveMatchSnapshot(
      printReified(fixture(t, 'workspaces-non-simplistic')),
      'should not clean up entire nm folder for no reason'
    ))

  t.test('add new workspaces dep', async t => {
    const path = fixture(t, 'workspaces-add-new-dep')
    await reify(path)
    t.matchSnapshot(require(path + '/package-lock.json'), 'should update package-lock with new added dep')
  })

  t.test('root as-a-workspace', async t => {
    const path = fixture(t, 'workspaces-root-linked')
    await reify(path)
    t.matchSnapshot(require(path + '/package-lock.json'), 'should produce expected package-lock file')
  })

  t.end()
})

t.test('reify from old package-lock with bins', async t => {
  const path = fixture(t, 'old-package-lock-with-bins')
  await reify(path, {})

  t.matchSnapshot(
    require(resolve(path, 'package-lock.json')),
    'should add bins entry to package-lock packages entry'
  )

  const bin = resolve(path, 'node_modules/.bin/ruy')
  if (process.platform === 'win32') {
    t.ok(fs.statSync(`${bin}.cmd`).isFile(), 'created shim')
  } else {
    t.ok(fs.lstatSync(bin).isSymbolicLink(), 'created symlink')
  }
})

t.test('fail early if bins will conflict', async t => {
  const path = t.testdir({
    lib: {
      'semver.cmd': 'this is not the linked bin',
    },
    bin: {
      semver: 'this is not the linked bin',
    },
  })
  const arb = newArb({
    global: true,
    path: `${path}/lib`,
  })
  arb.rebuild = async () => {
    throw Object.assign(new Error('nope'), { code: 'NOPE' })
  }
  await t.rejects(arb.reify({ add: ['semver'] }), { code: 'EEXIST' })
})

t.test('add a dep present in the tree, with v1 shrinkwrap', async t => {
  // https://github.com/npm/arborist/issues/70
  const path = fixture(t, 'old-package-lock')
  await reify(path, { add: ['wrappy'] })
  t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8'))
})

t.test('store files with a custom indenting', async t => {
  const tabIndentedPackageJson =
    fs.readFileSync(
      resolve(__dirname, '../fixtures/tab-indented-package-json/package.json'),
      'utf8'
    ).replace(/\r\n/g, '\n')
  const path = t.testdir({
    'package.json': tabIndentedPackageJson,
  })
  await reify(path)
  t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8'))
  t.matchSnapshot(fs.readFileSync(path + '/package-lock.json', 'utf8'))
})

t.test('do not rewrite valid package.json shorthands', async t => {
  const path = fixture(t, 'package-json-shorthands')
  await reify(path)
  const res = require(path + '/package.json')
  t.equal(res.bin, './index.js', 'should not rewrite bin property')
  t.equal(res.funding, 'https://example.com', 'should not rewrite funding')
})

t.test('modules bundled by the root should be installed', async t => {
  const path = fixture(t, 'root-bundler')
  await reify(path)
  t.matchSnapshot(fs.readFileSync(path + '/node_modules/child/package.json', 'utf8'))
})

t.test('add a new pkg to a prefix that needs to be mkdirpd', async t => {
  const path = resolve(t.testdir(), 'missing/path/to/root')
  const tree = await reify(path, { add: ['abbrev'] })
  t.matchSnapshot(
    printTree(tree),
    'should output a successful tree in mkdirp folder'
  )
  t.matchSnapshot(
    fs.readFileSync(path + '/package.json', 'utf8'),
    'should place expected package.json file into place'
  )
  t.matchSnapshot(
    fs.readFileSync(path + '/package-lock.json', 'utf8'),
    'should place expected lockfile file into place'
  )

  t.test('dry run scenarios', async t => {
    const path = resolve(t.testdir(), 'missing/path/to/root')

    try {
      await reify(path, { add: ['abbrev'], dryRun: true })
    } catch (e) {
      // TODO: should this be throwing?
    }

    t.throws(() =>
      fs.statSync(resolve(path, 'node_modules')), { code: 'ENOENT' })

    t.throws(() =>
      fs.statSync(resolve(path, 'package.json')), { code: 'ENOENT' })
  })
})

t.test('do not delete root-bundled deps in global update', async t => {
  const path = t.testdir()
  const file = resolve(__dirname, '../fixtures/bundle.tgz')
  await reify(path, { global: true, add: [`file:${file}`] })
  const depPJ = resolve(path, 'node_modules/bundle/node_modules/dep/package.json')
  t.matchSnapshot(fs.readFileSync(depPJ, 'utf8'), 'after first install')
  await reify(path, { global: true, add: [`file:${file}`] })
  t.matchSnapshot(fs.readFileSync(depPJ, 'utf8'), 'after second install')
})

t.test('do not excessively duplicate bundled metadeps', async t => {
  const path = fixture(t, 'bundle-metadep-duplication')
  const tree = await reify(path)
  const hidden = path + '/node_modules/.package-lock.json'
  t.matchSnapshot(fs.readFileSync(hidden, 'utf8'), 'hidden lockfile')
  const plock = path + '/package-lock.json'
  t.matchSnapshot(fs.readFileSync(plock, 'utf8'), 'normal lockfile')
  t.matchSnapshot(printTree(tree), 'tree')
})

t.test('do not reify root when root matches duplicated metadep', async t => {
  const path = fixture(t, 'test-root-matches-metadep')
  await reify(path)
  fs.statSync(path + '/do-not-delete-this-file')
})

t.test('reify properly with all deps when lockfile is ancient', async t => {
  const path = fixture(t, 'sax')
  const tree = await reify(path)
  t.matchSnapshot(printTree(tree))
  fs.statSync(path + '/node_modules/tap/node_modules/.bin/nyc')
})

t.test('add multiple pkgs in a specific order', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      name: 'multiple-pkgs',
    }),
  })
  await reify(path, { add: ['wrappy', 'abbrev'] })
  t.matchSnapshot(
    fs.readFileSync(path + '/package.json', 'utf8'),
    'should alphabetically sort dependencies'
  )
  await reify(path, { add: ['once'] })
  t.matchSnapshot(
    fs.readFileSync(path + '/package.json', 'utf8'),
    'should alphabetically sort new added dep'
  )
})

t.test('save complete lockfile on update-all', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      name: 'save-package-lock-after-update-test',
      version: '1.0.0',
    }),
  })
  // install the older version first
  const lock = () => fs.readFileSync(`${path}/package-lock.json`, 'utf8')
  await reify(path, { add: ['abbrev@1.0.4'] })
  t.matchSnapshot(lock(), 'should have abbrev 1.0.4')
  await reify(path, { update: true, save: false })
  t.matchSnapshot(lock(), 'should update, but not drop root metadata')
})

t.test('save proper lockfile with bins when upgrading lockfile', t => {
  const completeOpts = [true, false]
  completeOpts.forEach(complete => {
    t.test(`complete=${complete}`, async t => {
      const path = fixture(t, 'semver-installed-with-old-package-lock')
      const lock = () => fs.readFileSync(`${path}/package-lock.json`, 'utf8')
      await reify(path, { complete })
      t.matchSnapshot(lock(), 'should upgrade, with bins in place')
    })
  })

  t.end()
})

t.test('rollback if process is terminated during reify process', async t => {
  const onExit = require('../../lib/signal-handling.js')
  // mock the process so we don't have to kill this test
  // copy-pasta from signal-handling test
  const EE = require('events')
  const proc = onExit.process = new class MockProcess extends EE {
    constructor () {
      super()
      this.pid = process.pid
    }

    // ignore the beforeExit handler, since we won't actually let that happen
    once (ev, ...args) {
      if (ev !== 'beforeExit') {
        return super.once(ev, ...args)
      }
    }

    kill (pid, signal) {
      if (pid !== this.pid) {
        throw Object.assign(new Error('wrong pid sent to kill() method'), {
          expect: this.pid,
          actual: pid,
        })
      }
      return new Promise(res => process.nextTick(() => {
        this.emit(signal)
        res()
      }))
    }
  }()

  t.teardown(() => onExit.process = process)

  const methods = [
    Symbol.for('retireShallowNodes'),
    Symbol.for('createSparseTree'),
    Symbol.for('loadShrinkwrapsAndUpdateTrees'),
    Symbol.for('loadBundlesAndUpdateTrees'),
    Symbol.for('unpackNewModules'),
    Symbol.for('moveBackRetiredUnchanged'),
    Symbol.for('build'),
    Symbol.for('removeTrash'),
  ]

  t.plan(methods.length)
  for (const method of methods) {
    t.test(Symbol.keyFor(method), t => {
      const orig = Arborist.prototype[method]
      t.teardown(() => Arborist.prototype[method] = orig)
      Arborist.prototype[method] = async function (...args) {
        return Promise.resolve(orig.call(this, ...args)).then(() =>
          proc.kill(process.pid, 'SIGINT'))
      }
      const path = t.testdir({
        'package.json': JSON.stringify({ dependencies: { abbrev: '' } }),
      })

      t.test('clean install', async t => {
        const arb = newArb({ path })
        // starting from an empty folder, ends up empty
        await t.rejects(arb.reify(), {
          message: 'process terminated',
          signal: 'SIGINT',
        })
        // if it fails while removing trash well... it's already over.
        // we can't actually roll back at that point, because "trash" is gone
        if (method !== Symbol.for('removeTrash')) {
          t.throws(() => fs.statSync(path + '/node_modules'), { code: 'ENOENT' })
        }
      })

      t.test('upgrade install', async t => {
        // ensure that we end up with the same thing we started with,
        // if it was something other than we're installing
        const a = resolve(path, 'node_modules/abbrev')
        fs.mkdirSync(a, { recursive: true })
        const pj = resolve(a, 'package.json')
        fs.writeFileSync(pj, JSON.stringify({
          name: 'abbrev',
          version: '0.0.0',
        }))
        const arb = newArb({ path })
        await t.rejects(arb.reify({ add: ['abbrev@1.1.1'] }), {
          message: 'process terminated',
          signal: 'SIGINT',
        })

        // if it fails while removing trash well... it's already over.
        // we can't actually roll back at that point, because "trash" is gone
        if (method !== Symbol.for('removeTrash')) {
          t.same(JSON.parse(fs.readFileSync(pj, 'utf8')), {
            name: 'abbrev',
            version: '0.0.0',
          })
        }
      })

      t.end()
    })
  }
})

t.test('warn and correct if damaged data in lockfile', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      dependencies: {
        abbrev: '',
      },
    }),
    'package-lock.json': JSON.stringify({
      name: 'garbage-in-reify-tree',
      lockfileVersion: 2,
      requires: true,
      packages: {
        '': {
          dependencies: {
            abbrev: '',
          },
        },
        'node_modules/abbrev': {
          integrity: 'sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==',
        },
      },
      dependencies: {
        abbrev: {
          integrity: 'sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==',
        },
      },
    }),
  })

  t.test('first pass logs', async t => {
    const getLogs = warningTracker()
    await reify(path)
    t.strictSame(getLogs(), [
      [
        'warn',
        'reify',
        'invalid or damaged lockfile detected\n' +
        'please re-try this operation once it completes\n' +
        'so that the damage can be corrected, or perform\n' +
        'a fresh install with no lockfile if the problem persists.',
      ],
    ], 'got warnings')
    t.matchSnapshot(fs.readFileSync(path + '/package-lock.json', 'utf8'), '"fixed" lockfile')
  })

  t.test('second pass just does the right thing', async t => {
    const getLogs = warningTracker()
    await reify(path)
    t.strictSame(getLogs(), [], 'no warnings this time')
    t.matchSnapshot(fs.readFileSync(path + '/package-lock.json', 'utf8'), 'actually fixed lockfile')
  })
})

t.test('properly update one module when multiple are present', async t => {
  const path = t.testdir({})
  const abbrevpj = resolve(path, 'node_modules/abbrev/package.json')
  const oncepj = resolve(path, 'node_modules/once/package.json')

  await newArb({ path, global: true }).reify({ add: ['abbrev@1.0.4'] })
  t.equal(JSON.parse(fs.readFileSync(abbrevpj, 'utf8')).version, '1.0.4')
  t.throws(() => fs.readFileSync(oncepj, 'utf8'), 'once should not be yet')

  await newArb({ path, global: true }).reify({ add: ['once'] })
  t.equal(JSON.parse(fs.readFileSync(abbrevpj, 'utf8')).version, '1.0.4')
  t.equal(JSON.parse(fs.readFileSync(oncepj, 'utf8')).version, '1.4.0')

  await newArb({ path, global: true }).reify({ update: ['abbrev'] })
  t.equal(JSON.parse(fs.readFileSync(abbrevpj, 'utf8')).version, '1.1.1')
  t.equal(JSON.parse(fs.readFileSync(oncepj, 'utf8')).version, '1.4.0')
})

t.test('saving should not replace file: dep with version', async t => {
  // need to run in the path, as if the user typed `npm i file:abbrev`
  const cwd = process.cwd()
  t.teardown(() => process.chdir(cwd))
  const path = t.testdir({
    abbrev: {
      'package.json': JSON.stringify({
        name: 'abbrev',
        version: '1.1.1',
      }),
    },
    'package.json': JSON.stringify({}),
  })
  process.chdir(path)

  const pj = resolve(path, 'package.json')
  await newArb({ path, save: true }).reify({ add: ['file:abbrev'] })
  const pj1 = fs.readFileSync(pj, 'utf8')
  t.equal(JSON.parse(pj1).dependencies.abbrev, 'file:abbrev',
    'saved as file: spec after file: install')
  await newArb({ path, save: true }).reify({ add: ['abbrev'] })
  const pj2 = fs.readFileSync(pj, 'utf8')
  t.equal(JSON.parse(pj2).dependencies.abbrev, 'file:abbrev',
    'still a file: spec after a bare name install')
})

t.test('filtered reification in workspaces', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      workspaces: [
        'apps/*',
        'packages/*',
      ],
    }),
    // 'apps' comes ahead of 'node_modules' alphabetically,
    // included in the test so that we ensure that the copy
    // over works properly in both directions.
    apps: {
      x: {
        'package.json': JSON.stringify({
          name: 'x',
          version: '1.2.3',
        }),
      },
    },
    // this is going to be a workspace that we switch to in the ideal
    // tree, but the actual tree will still be lagging behind.
    foo: {
      x: {
        'package.json': JSON.stringify({
          name: 'x',
          version: '1.2.3',
        }),
      },
    },
    packages: {
      a: {
        'package.json': JSON.stringify({
          name: 'a',
          version: '1.2.3',
          dependencies: {
            once: '',
            wrappy: '1.0.2',
          },
        }),
      },
      b: {
        'package.json': JSON.stringify({
          name: 'b',
          version: '1.2.3',
          dependencies: {
            abbrev: '',
          },
        }),
      },
      c: {
        'package.json': JSON.stringify({
          name: 'c',
          version: '1.2.3',
          dependencies: {
            wrappy: '1.0.0',
          },
        }),
      },
    },
  })

  const hiddenLock = resolve(path, 'node_modules/.package-lock.json')

  t.matchSnapshot(await printReified(path, { workspaces: ['c'] }),
    'reify the c workspace only')

  t.matchSnapshot(fs.readFileSync(hiddenLock, 'utf8'),
    'hidden lockfile - c')

  t.matchSnapshot(await printReified(path, { workspaces: ['x'] }),
    'reify the x workspace after reifying c')

  t.matchSnapshot(fs.readFileSync(hiddenLock, 'utf8'),
    'hidden lockfile - c, x')

  t.matchSnapshot(await printReified(path, { workspaces: ['a'] }),
    'reify the a workspace after reifying c')

  t.matchSnapshot(fs.readFileSync(hiddenLock, 'utf8'),
    'hidden lockfile - c, x, a')

  // now remove the a workspace, and move x to a new target location,
  // but we will not reify the apps->foo change.
  fs.writeFileSync(`${path}/package.json`, JSON.stringify({
    workspaces: [
      'foo/*',
      'packages/b',
      'packages/c',
    ],
  }))

  t.matchSnapshot(await printReified(path, { workspaces: ['a', 'c'] }),
    'reify the workspaces, removing a and leaving c and old x in place')

  t.matchSnapshot(fs.readFileSync(hiddenLock, 'utf8'),
    'hidden lockfile - c, old x, removed a')

  // Same thing, BUT, we now have a reason to already have the foo/x
  // in fsChildren.  fully reify with this package.json, then change
  // the root package.json back to the test above.  This exercises an
  // edge case where the actual and ideal trees are somewhat out of sync,
  // by virtue of the actualTree being generated with a package.json
  // which has changed, but where only PART of the idealTree is reified
  // over it.
  fs.writeFileSync(`${path}/package.json`, JSON.stringify({
    dependencies: {
      foox: 'file:foo/x',
    },
    workspaces: [
      'apps/x',
      'packages/a',
      'packages/c',
    ],
  }))
  await reify(path)
  fs.writeFileSync(`${path}/package.json`, JSON.stringify({
    workspaces: [
      'foo/*',
      'packages/b',
      'packages/c',
    ],
  }))
  t.matchSnapshot(await printReified(path, { workspaces: ['a', 'c'] }),
    'reify the workspaces, foo/x linked, c, old x, removed a')

  t.matchSnapshot(fs.readFileSync(hiddenLock, 'utf8'),
    'hidden lockfile - foo/x linked, c, old x, removed a')
})

t.test('project with bundled deps and a link dep on itself', async t => {
  const pkg = {
    name: '@isaacs/testing-bundle-self-link',
    version: '1.0.0',
    bin: {
      'testing-bundle-self-link': 'bin.js',
    },
    scripts: {
      test: 'testing-bundle-self-link',
      postinstall: 'testing-bundle-self-link',
    },
    bundleDependencies: [
      'abbrev',
    ],
    dependencies: {
      '@isaacs/testing-bundle-self-link': 'file:.',
      abbrev: '',
    },
  }
  const path = t.testdir({
    'package.json': JSON.stringify(pkg),
    'bin.js': `#!/usr/bin/env node
console.log('TAP version 13')
console.log('1..1')
console.log('ok 1 - this is fine')
`,
  })

  t.matchSnapshot(await printReified(path), 'result')
  t.resolves(runScript({
    event: 'test',
    path,
    pkg,
    stdioString: true,
    stdio: 'pipe',
  }), 'test result')
})

t.test('running lifecycle scripts of unchanged link nodes on reify', async t => {
  const path = fixture(t, 'link-dep-lifecycle-scripts')
  t.matchSnapshot(await printReified(path), 'result')

  t.ok(fs.lstatSync(resolve(path, 'a/a-prepare')).isFile(),
    'should run prepare lifecycle scripts for links directly linked to the tree')
  t.ok(fs.lstatSync(resolve(path, 'a/a-post-install')).isFile(),
    'should run postinstall lifecycle scripts for links directly linked to the tree')
})

t.test('save-prod, with optional', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      devDependencies: { abbrev: '*' },
      optionalDependencies: { abbrev: '*' },
    }),
  })
  const arb = newArb({ path })
  await arb.reify({ add: ['abbrev'], saveType: 'prod' })
  t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8'))
})

t.test('saveBundle', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      dependencies: { abbrev: '*' },
    }),
  })
  const arb = newArb({ path })
  await arb.reify({ add: ['abbrev'], saveType: 'prod', saveBundle: true })
  t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8'))
})

t.test('no saveType: dev w/ compatible peer', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      peerDependencies: { abbrev: '*' },
      devDependencies: { abbrev: '*' },
    }),
  })
  const arb = newArb({ path })
  await arb.reify({ add: ['abbrev'] })
  t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8'))
})

t.test('no saveType: dev w/ incompatible peer', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      peerDependencies: { abbrev: '0.0.0' },
      devDependencies: { abbrev: '*' },
    }),
  })
  const arb = newArb({ path })
  await arb.reify({ add: ['abbrev'] })
  t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8'))
})

t.test('no saveType: dev w/ compatible optional', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      optionalDependencies: { abbrev: '*' },
      devDependencies: { abbrev: '*' },
    }),
  })
  const arb = newArb({ path })
  await arb.reify({ add: ['abbrev'] })
  t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8'))
})

t.test('no saveType: dev w/ incompatible optional', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      optionalDependencies: { abbrev: '0.0.0' },
      devDependencies: { abbrev: '*' },
    }),
  })
  const arb = newArb({ path })
  await arb.reify({ add: ['abbrev'] })
  t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8'))
})

t.test('no saveType: prod w/ peer', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      peerDependencies: { abbrev: '*' },
      dependencies: { abbrev: '*' },
    }),
  })
  const arb = newArb({ path })
  await arb.reify({ add: ['abbrev'] })
  t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8'))
})

t.test('no saveType: peer only', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      peerDependencies: { abbrev: '*' },
    }),
  })
  const arb = newArb({ path })
  await arb.reify({ add: ['abbrev'] })
  t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8'))
})

t.test('no saveType: optional only', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      optionalDependencies: { abbrev: '*' },
    }),
  })
  const arb = newArb({ path })
  await arb.reify({ add: ['abbrev'] })
  t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8'))
})

t.test('do not delete linked targets when link omitted', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      devDependencies: {
        foo: 'file:foo',
      },
      dependencies: {
        abbrev: '',
      },
    }),
    node_modules: {
      foo: t.fixture('symlink', '../foo'),
      abbrev: {
        'package.json': JSON.stringify({
          name: 'abbrev',
          version: '1.2.3',
        }),
      },
    },
    foo: {
      'package.json': JSON.stringify({
        name: 'foo',
        version: '1.2.3',
        dependencies: {
          bar: '1.2.3',
        },
      }),
      'index.js': 'console.log("hello from foo")',
      node_modules: {
        bar: {
          'package.json': JSON.stringify({
            name: 'bar',
            version: '1.2.3',
          }),
        },
      },
    },
  })
  const barpj = resolve(path, 'foo/node_modules/bar/package.json')
  const fooindex = resolve(path, 'foo/index.js')
  t.equal(fs.existsSync(barpj), true, 'bar package.json present')
  t.equal(fs.existsSync(fooindex), true, 'foo index.js present')
  const tree = await reify(path, { omit: ['dev'] })
  t.equal(fs.existsSync(barpj), true, 'bar package.json still present')
  t.equal(fs.existsSync(fooindex), true, 'foo index.js still present')
  t.notOk(tree.children.get('foo'), 'does not have foo child any more')
  t.equal(tree.fsChildren.size, 1, 'still has foo fschild')
})

t.test('add spec * with semver prefix range gets updated', async t => {
  const path = t.testdir({ 'package.json': '{}' })
  const arb = newArb({ path })
  await arb.reify({ add: ['latest-is-prerelease'] })
  t.matchSnapshot(fs.readFileSync(path + '/package.json', 'utf8'))
})

t.test('add deps to workspaces', async t => {
  const fixture = {
    'package.json': JSON.stringify({
      workspaces: [
        'packages/*',
      ],
      dependencies: {
        mkdirp: '^1.0.4',
      },
    }),
    packages: {
      a: {
        'package.json': JSON.stringify({
          name: 'a',
          version: '1.2.3',
          dependencies: {
            mkdirp: '^0.5.0',
          },
        }),
      },
      b: {
        'package.json': JSON.stringify({
          name: 'b',
          version: '1.2.3',
        }),
      },
    },
  }

  t.test('no args', async t => {
    const path = t.testdir(fixture)
    const tree = await reify(path)
    t.equal(tree.children.get('mkdirp').version, '1.0.4')
    t.equal(tree.children.get('a').target.children.get('mkdirp').version, '0.5.5')
    t.equal(tree.children.get('b').target.children.get('mkdirp'), undefined)
    t.matchSnapshot(printTree(tree), 'returned tree')
    t.matchSnapshot(require(path + '/package-lock.json'), 'lockfile')
  })

  t.test('add mkdirp 0.5.0 to b', async t => {
    const path = t.testdir(fixture)
    await reify(path)
    const tree = await reify(path, { workspaces: ['b'], add: ['mkdirp@0.5.0'] })
    t.equal(tree.children.get('mkdirp').version, '1.0.4')
    t.equal(tree.children.get('a').target.children.get('mkdirp').version, '0.5.5')
    t.equal(tree.children.get('b').target.children.get('mkdirp').version, '0.5.0')
    t.matchSnapshot(printTree(tree), 'returned tree')
    t.matchSnapshot(require(path + '/packages/b/package.json'), 'package.json b')
    t.matchSnapshot(require(path + '/package-lock.json'), 'lockfile')
  })

  t.test('remove mkdirp from a', async t => {
    const path = t.testdir(fixture)
    await reify(path)
    const tree = await reify(path, { workspaces: ['a'], rm: ['mkdirp'] })
    t.equal(tree.children.get('mkdirp').version, '1.0.4')
    t.equal(tree.children.get('a').target.children.get('mkdirp'), undefined)
    t.equal(tree.children.get('a').target.edgesOut.get('mkdirp'), undefined)
    t.equal(tree.children.get('b').target.children.get('mkdirp'), undefined)
    t.matchSnapshot(printTree(tree), 'returned tree')
    t.matchSnapshot(require(path + '/packages/a/package.json'), 'package.json a')
    t.matchSnapshot(require(path + '/package-lock.json'), 'lockfile')
  })

  t.test('upgrade mkdirp in a, dedupe on root', async t => {
    const path = t.testdir(fixture)
    await reify(path)
    const tree = await reify(path, { workspaces: ['a'], add: ['mkdirp@1'] })
    t.equal(tree.children.get('mkdirp').version, '1.0.4')
    t.equal(tree.children.get('a').target.children.get('mkdirp'), undefined)
    t.equal(tree.children.get('a').target.edgesOut.get('mkdirp').spec, '^1.0.4')
    t.equal(tree.children.get('b').target.children.get('mkdirp'), undefined)
    t.matchSnapshot(printTree(tree), 'returned tree')
    t.matchSnapshot(require(path + '/packages/a/package.json'), 'package.json a')
    t.matchSnapshot(require(path + '/package-lock.json'), 'lockfile')
  })

  t.test('add mkdirp 0.5.0 to b, empty start', async t => {
    const path = t.testdir(fixture)
    const tree = await reify(path, { workspaces: ['b'], add: ['mkdirp@0.5.0'] })
    t.equal(tree.children.get('mkdirp'), undefined)
    t.equal(tree.children.get('a'), undefined, 'did not even link workspace "a"')
    t.equal(tree.children.get('b').target.children.get('mkdirp').version, '0.5.0')
    t.matchSnapshot(printTree(tree), 'returned tree')
    t.matchSnapshot(require(path + '/packages/b/package.json'), 'package.json b')
    t.matchSnapshot(require(path + '/package-lock.json'), 'lockfile')
  })

  t.test('remove mkdirp from a, empty start', async t => {
    const path = t.testdir(fixture)
    const tree = await reify(path, { workspaces: ['a'], rm: ['mkdirp'] })
    t.equal(tree.children.get('mkdirp'), undefined)
    t.equal(tree.children.get('a').target.children.get('mkdirp'), undefined)
    t.equal(tree.children.get('a').target.edgesOut.get('mkdirp'), undefined)
    t.equal(tree.children.get('b'), undefined, 'did not link workspace "b"')
    t.matchSnapshot(printTree(tree), 'returned tree')
    t.matchSnapshot(require(path + '/packages/a/package.json'), 'package.json a')
    t.matchSnapshot(require(path + '/package-lock.json'), 'lockfile')
  })

  t.test('upgrade mkdirp in a, dedupe on root, empty start', async t => {
    const path = t.testdir(fixture)
    const tree = await reify(path, { workspaces: ['a'], add: ['mkdirp@1'] })
    t.equal(tree.children.get('mkdirp').version, '1.0.4')
    t.equal(tree.children.get('a').target.children.get('mkdirp'), undefined)
    t.equal(tree.children.get('a').target.edgesOut.get('mkdirp').spec, '^1.0.4')
    t.equal(tree.children.get('b'), undefined, 'did not link "b" workspace')
    t.matchSnapshot(printTree(tree), 'returned tree')
    t.matchSnapshot(require(path + '/packages/a/package.json'), 'package.json a')
    t.matchSnapshot(require(path + '/package-lock.json'), 'lockfile')
  })

  t.test('add a to root', async t => {
    const path = t.testdir(fixture)
    await reify(path)
    const tree = await reify(path, { add: ['a'], lockfileVersion: 3 })
    t.matchSnapshot(printTree(tree), 'returned tree')
    t.matchSnapshot(require(path + '/package.json'), 'package.json added workspace as dep')
    t.matchSnapshot(require(path + '/package-lock.json'), 'lockfile added workspace as dep')
  })
})

t.test('reify audit only workspace deps when reifying workspace', async t => {
  const auditFile = resolve(__dirname, '../fixtures/audit-nyc-mkdirp/advisory-bulk.json')
  t.teardown(advisoryBulkResponse(auditFile))
  const path = t.testdir({
    'package.json': JSON.stringify({
      workspaces: ['packages/*'],
    }),
    packages: {
      a: {
        'package.json': JSON.stringify({
          name: 'a',
          version: '1.2.3',
          dependencies: {
            'kind-of': '6.0.0',
          },
        }),
      },
      b: {
        'package.json': JSON.stringify({
          name: 'b',
          version: '1.2.3',
          dependencies: {
            minimist: '0.0.8',
          },
        }),
      },
    },
  })
  const arb = newArb({ path, audit: true, workspaces: ['a'] })
  const tree = await arb.reify()
  const report = arb.auditReport.toJSON()
  t.equal(report.vulnerabilities.minimist, undefined, 'minimist not audited')
  t.match(report.vulnerabilities['kind-of'], {
    name: 'kind-of',
    severity: 'low',
    range: '6.0.0 - 6.0.2',
    nodes: ['node_modules/kind-of'],
    fixAvailable: {
      name: 'kind-of',
      version: '6.0.3',
      isSemVerMajor: false,
    },
    via: [{
      source: 1490,
      name: 'kind-of',
      dependency: 'kind-of',
      title: 'Validation Bypass',
      url: 'https://npmjs.com/advisories/1490',
      severity: 'low',
      range: '>=6.0.0 <6.0.3',
    }],
  }, 'kind-of audited')
  t.matchSnapshot(printTree(tree), 'resulting tree')
})

t.test('update a dep when the lockfile is lying about it', async t => {
  // lockfile and pj have new version, but old version is in nm
  // no hidden lockfile to provide metadata
  const path = t.testdir({
    'package.json': JSON.stringify({
      dependencies: {
        abbrev: '1.1.1',
      },
    }),
    'package-lock.json': JSON.stringify({
      lockfileVersion: 2,
      requires: true,
      packages: {
        '': {
          devDependencies: {
            abbrev: '1.1.1',
          },
        },
        'node_modules/abbrev': {
          version: '1.1.1',
          resolved: 'https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz',
          integrity: 'sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==',
          dev: true,
        },
      },
      dependencies: {
        abbrev: {
          version: '1.1.1',
          resolved: 'https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz',
          integrity: 'sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==',
          dev: true,
        },
      },
    }),
    node_modules: {
      abbrev: {
        'package.json': JSON.stringify({
          name: 'abbrev',
          version: '1.1.0',
        }),
      },
    },
  })

  const tree = await reify(path)
  const abbrev = tree.children.get('abbrev')
  t.equal(abbrev.version, '1.1.1')
  t.equal(require(abbrev.path + '/package.json').version, '1.1.1')
})

t.test('shrinkwrap which lacks metadata updates deps', async t => {
  const path = t.testdir({
    'package.json': '{}',
  })

  const first = await reify(path, {
    add: ['@isaacs/testing-shrinkwrap-abbrev@1.2.0'],
  })
  const firstAbbrev = first.children.get('@isaacs/testing-shrinkwrap-abbrev')
    .children.get('abbrev')
  t.equal(firstAbbrev.version, '1.1.0')

  const abbrevPath = firstAbbrev.path
  const abbrevpj = () =>
    JSON.parse(fs.readFileSync(abbrevPath + '/package.json', 'utf8'))

  t.equal(abbrevpj().version, firstAbbrev.version)

  const second = await reify(path, {
    add: ['@isaacs/testing-shrinkwrap-abbrev@1.2.1'],
  })
  const secondAbbrev = second.children.get('@isaacs/testing-shrinkwrap-abbrev')
    .children.get('abbrev')
  t.equal(secondAbbrev.version, '1.1.1')
  t.equal(abbrevpj().version, secondAbbrev.version)
})

t.test('move aside symlink clutter', async t => {
  // have to make the clutter manually, because we collide packages based
  // on case-insensitive names, so the ABBREV folder would be removed.
  // not sure how this would ever happen, but defense in depth.
  const path = t.testdir({
    'package.json': JSON.stringify({
      dependencies: {
        abbrev: 'latest',
      },
    }),
    target: {
      file: 'do not delete me please',
      'package.json': JSON.stringify({ name: 'ABBREV', version: '1.0.0' }),
    },
    'sensitivity-test': t.fixture('symlink', './target'),
  })

  // check to see if we're on a case-insensitive fs
  try {
    const st = fs.lstatSync(path + '/SENSITIVITY-TEST')
    t.equal(st.isSymbolicLink(), true, 'fs is case insensitive')
  } catch (er) {
    t.plan(0, 'case sensitive file system, test not relevant')
    return
  }

  const kReifyPackages = Symbol.for('reifyPackages')
  const reifyPackages = Arborist.prototype[kReifyPackages]
  t.teardown(() => Arborist.prototype[kReifyPackages] = reifyPackages)
  Arborist.prototype[kReifyPackages] = async function () {
    fs.mkdirSync(path + '/node_modules')
    fs.symlinkSync('../target', path + '/node_modules/ABBREV')
    Arborist.prototype[kReifyPackages] = reifyPackages
    return this[kReifyPackages]()
  }

  const tree = await printReified(path)
  const st = fs.lstatSync(path + '/node_modules/abbrev')
  t.equal(st.isSymbolicLink(), false)
  t.equal(st.isDirectory(), true)
  const realName = basename(fs.realpathSync.native(path + '/node_modules/abbrev'))
  t.equal(realName, 'abbrev', 'lowercase form is the winner')
  t.equal(fs.readFileSync(path + '/target/file', 'utf8'),
    'do not delete me please')
  const linkPJ = fs.readFileSync(path + '/target/package.json', 'utf8')
  t.strictSame(JSON.parse(linkPJ), {
    name: 'ABBREV',
    version: '1.0.0',
  })
  const abbrevPJ = fs.readFileSync(path + '/node_modules/abbrev/package.json', 'utf8')
  t.match(JSON.parse(abbrevPJ), {
    name: 'abbrev',
    version: '1.1.1',
  })

  t.matchSnapshot(tree)
})

t.test('collide case-variant dep names', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      dependencies: {
        ABBREV: 'file:target',
        abbrev: '1',
      },
    }),
    target: {
      file: 'do not delete me please',
      'package.json': JSON.stringify({ name: 'ABBREV', version: '1.0.0' }),
    },
    node_modules: {
      ABBREV: t.fixture('symlink', '../target'),
    },
  })

  const tree = await printReified(path)
  const st = fs.lstatSync(path + '/node_modules/abbrev')
  t.equal(st.isSymbolicLink(), false)
  const realName = basename(fs.realpathSync.native(path + '/node_modules/abbrev'))
  t.equal(realName, 'abbrev', 'lowercase form is the winner')
  t.equal(fs.readFileSync(path + '/target/file', 'utf8'),
    'do not delete me please')
  const linkPJ = fs.readFileSync(path + '/target/package.json', 'utf8')
  t.strictSame(JSON.parse(linkPJ), {
    name: 'ABBREV',
    version: '1.0.0',
  })

  t.matchSnapshot(tree, 'tree 1')
  const tree2 = await printReified(path, { add: ['abbrev@latest'] })
  t.matchSnapshot(tree2, 'tree 2')
  const linkPJ2 = fs.readFileSync(path + '/target/package.json', 'utf8')
  t.strictSame(JSON.parse(linkPJ2), {
    name: 'ABBREV',
    version: '1.0.0',
  }, 'target was not overwritten')
  t.equal(fs.readFileSync(path + '/target/file', 'utf8'),
    'do not delete me please')
  const abbrevPJ = fs.readFileSync(path + '/node_modules/abbrev/package.json', 'utf8')
  t.match(JSON.parse(abbrevPJ), {
    name: 'abbrev',
    version: '1.1.1',
  })
})

t.test('node_modules may not be a symlink', async t => {
  const path = t.testdir({
    target: {},
    node_modules: t.fixture('symlink', 'target'),
    'package.json': JSON.stringify({
      dependencies: {
        abbrev: '',
      },
    }),
  })
  const warnings = warningTracker()
  const tree = await printReified(path)
  t.matchSnapshot(tree)
  t.matchSnapshot(normalizePaths(warnings()))
})

t.test('never unpack into anything other than a real directory', async t => {
  const kUnpack = Symbol.for('unpackNewModules')
  const unpackNewModules = Arborist.prototype[kUnpack]
  const path = t.testdir({
    'package.json': JSON.stringify({
      dependencies: {
        once: '',
        wrappy: 'file:target',
      },
    }),
    target: {
      donotdeleteme: 'please do not delete this',
      'package.json': JSON.stringify({
        name: 'donotclobberme',
        version: '1.2.3-please-do-not-clobber',
      }),
    },
  })
  const arb = newArb({ path })
  const logs = debugLogTracker()
  const wrappy = resolve(path, 'node_modules/once/node_modules/wrappy')
  arb[kUnpack] = () => {
    // will have already created it
    fs.rmSync(wrappy, { recursive: true, force: true })
    const target = resolve(path, 'target')
    fs.symlinkSync(target, wrappy, 'junction')
    arb[kUnpack] = unpackNewModules
    return arb[kUnpack]()
  }
  await t.rejects(arb.reify({ path }), {
    message: 'ENOTDIR: not a directory',
    code: 'ENOTDIR',
    path: wrappy,
  })
  t.match(logs(), [['unpacking into a non-directory', { path: wrappy }]])
})

t.test('adding an unresolvable optional dep is OK', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      optionalDependencies: {
        abbrev: '999999',
      },
    }),
  })
  const tree = await reify(path, { add: ['abbrev'] })
  t.strictSame([...tree.children.values()], [], 'nothing actually added')
  t.matchSnapshot(printTree(tree))
})

t.test('includeWorkspaceRoot in addition to workspace', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      dependencies: {
        once: '',
      },
      workspaces: ['packages/*'],
    }),
    packages: {
      a: {
        'package.json': JSON.stringify({
          name: 'a',
          version: '1.0.1',
          dependencies: {
            abbrev: '',
          },
        }),
      },
      b: {
        'package.json': JSON.stringify({
          name: 'b',
          version: '9.8.1',
          dependencies: {
            semver: '',
          },
        }),
      },
    },
  })
  const tree = await reify(path, { includeWorkspaceRoot: true, workspaces: ['a'] })
  t.matchSnapshot(printTree(tree))
  t.equal(tree.inventory.query('name', 'semver').size, 0)
  t.equal(tree.inventory.query('name', 'abbrev').size, 1)
  t.equal(tree.inventory.query('name', 'once').size, 1)
})

t.test('no workspace', async t => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      dependencies: {
        once: '',
      },
      workspaces: ['packages/*'],
    }),
    packages: {
      a: {
        'package.json': JSON.stringify({
          name: 'a',
          version: '1.0.1',
          dependencies: {
            abbrev: '',
          },
        }),
      },
      b: {
        'package.json': JSON.stringify({
          name: 'b',
          version: '9.8.1',
          dependencies: {
            semver: '',
          },
        }),
      },
    },
  })
  const tree = await reify(path, { workspacesEnabled: false, workspaces: ['a', 'b'] })
  t.matchSnapshot(printTree(tree))
  t.equal(tree.inventory.query('name', 'semver').size, 0)
  t.equal(tree.inventory.query('name', 'abbrev').size, 0)
  t.equal(tree.inventory.query('name', 'once').size, 1)
})

t.test('add local dep with existing dev + peer/optional', async t => {
  const path = t.testdir({
    project: {
      'package.json': JSON.stringify({
        devDependencies: {
          abbrev: '^1.0.0',
        },
        peerDependencies: {
          abbrev: '^1.0.0',
        },
        optionalDependencies: {
          abbrev: '^1.0.0',
        },
      }),
    },
    dep: {
      'package.json': JSON.stringify({
        name: 'abbrev',
        version: '1.0.0',
      }),
    },
  })

  const project = resolve(path, 'project')
  const cwd = process.cwd()
  t.teardown(() => process.chdir(cwd))
  process.chdir(project)

  const tree = await reify(project, { add: ['../dep'] })

  t.matchSnapshot(printTree(tree), 'tree')
  t.equal(tree.children.get('abbrev').resolved, 'file:../../dep', 'resolved')
  t.equal(tree.children.size, 1, 'children')
})

t.test('runs dependencies script if tree changes', async (t) => {
  const path = t.testdir({
    'package.json': JSON.stringify({
      name: 'root',
      version: '1.0.0',
      dependencies: {
        abbrev: '^1.1.1',
      },
      scripts: {
        predependencies: `node -e "require('fs').writeFileSync('ran-predependencies', '')"`,
        dependencies: `node -e "require('fs').writeFileSync('ran-dependencies', '')"`,
        postdependencies: `node -e "require('fs').writeFileSync('ran-postdependencies', '')"`,
      },
    }),
  })

  await reify(path)

  for (const script of ['predependencies', 'dependencies', 'postdependencies']) {
    const expectedPath = join(path, `ran-${script}`)
    t.ok(fs.existsSync(expectedPath), `ran ${script}`)
    // delete the files after we assert they exist
    fs.unlinkSync(expectedPath)
  }

  // reify again without changing dependencies
  await reify(path)

  for (const script of ['predependencies', 'dependencies', 'postdependencies']) {
    const expectedPath = join(path, `ran-${script}`)
    // and this time we assert that they do _not_ exist
    t.not(fs.existsSync(expectedPath), `did not run ${script}`)
  }

  // take over console.log as run-script is going to print a banner for these because
  // they're running in the foreground
  const _log = console.log
  t.teardown(() => {
    console.log = _log
  })
  const logs = []
  console.log = (msg) => logs.push(msg)
  // reify again, this time adding a new dependency
  await reify(path, { foregroundScripts: true, add: ['once@^1.4.0'] })
  console.log = _log

  t.match(logs, [/predependencies/, /dependencies/, /postdependencies/], 'logged banners')

  // files should exist again
  for (const script of ['predependencies', 'dependencies', 'postdependencies']) {
    const expectedPath = join(path, `ran-${script}`)
    t.ok(fs.existsSync(expectedPath), `ran ${script}`)
    fs.unlinkSync(expectedPath)
  }
})

t.test('save package.json on update', t => {
  t.test('should save many deps in multiple package.json when using save=true', async t => {
    const path = fixture(t, 'workspaces-need-update')

    await reify(path, { update: true, save: true })

    t.same(
      require(resolve(path, 'package.json')),
      { dependencies: { abbrev: '^1.1.1' }, workspaces: ['a', 'b'] },
      'should save top level dep update to root package.json'
    )
    t.same(
      require(resolve(path, 'a', 'package.json')),
      { dependencies: { abbrev: '^1.1.1', once: '^1.4.0' } },
      'should save workspace dep to its package.json file')

    t.matchSnapshot(
      fs.readFileSync(resolve(path, 'package-lock.json'), 'utf8'),
      'should update lockfile with many deps updated package.json save=true'
    )
  })

  t.test('should not save many deps in multiple package.json when using save=false', async t => {
    const path = fixture(t, 'workspaces-need-update')

    await reify(path, { update: true, save: false })

    t.same(
      require(resolve(path, 'package.json')),
      {
        dependencies: { abbrev: '^1.0.4' },
        workspaces: ['a', 'b'],
      },
      'should not save top level dep update to root package.json'
    )
    t.same(
      require(resolve(path, 'a', 'package.json')),
      { dependencies: { abbrev: '^1.0.4', once: '^1.3.2' } },
      'should not save workspace dep to its package.json file')

    // package-lock entries will still get updated:
    t.matchSnapshot(
      fs.readFileSync(resolve(path, 'package-lock.json'), 'utf8'),
      'should update lockfile with many deps updated package.json save=false'
    )
  })

  t.test('should not save any with save=false and package-lock=false', async t => {
    const path = fixture(t, 'workspaces-need-update')

    await reify(path, { update: true, save: false, packageLock: false })

    t.same(
      require(resolve(path, 'package.json')),
      {
        dependencies: { abbrev: '^1.0.4' },
        workspaces: ['a', 'b'],
      },
      'should not save top level dep update to root package.json'
    )
    t.same(
      require(resolve(path, 'a', 'package.json')),
      { dependencies: { abbrev: '^1.0.4', once: '^1.3.2' } },
      'should not save workspace dep to its package.json file')

    // package-lock entries will still get updated:
    t.matchSnapshot(
      JSON.stringify(JSON.parse(fs.readFileSync(resolve(path, 'package-lock.json'), 'utf8')), null, 2),
      'should update lockfile with many deps updated package.json save=false'
    )
  })

  t.test('should update named dep across multiple package.json using save=true', async t => {
    const path = fixture(t, 'workspaces-need-update')

    await reify(path, { update: ['abbrev'], save: true })

    t.same(
      require(resolve(path, 'package.json')),
      {
        dependencies: { abbrev: '^1.1.1' },
        workspaces: ['a', 'b'],
      },
      'should save top level dep update to root package.json'
    )
    t.same(
      require(resolve(path, 'a', 'package.json')),
      { dependencies: { abbrev: '^1.1.1', once: '^1.3.2' } },
      'should save only workspace a updated dep to its package.json file')
    t.same(
      require(resolve(path, 'b', 'package.json')),
      { dependencies: { abbrev: '^1.1.1' } },
      'should save only workspace b updated dep to its package.json file')

    t.matchSnapshot(
      fs.readFileSync(resolve(path, 'package-lock.json'), 'utf8'),
      'should update lockfile with many deps updated package.json save=true'
    )
  })

  t.test('should update single named dep across multiple package.json using save=true', async t => {
    const path = fixture(t, 'workspaces-need-update')

    await reify(path, { update: ['once'], save: true })

    t.same(
      require(resolve(path, 'package.json')),
      {
        dependencies: { abbrev: '^1.0.4' },
        workspaces: ['a', 'b'],
      },
      'should save no top level dep update to root package.json'
    )
    t.same(
      require(resolve(path, 'a', 'package.json')),
      { dependencies: { abbrev: '^1.0.4', once: '^1.4.0' } },
      'should save only workspace single updated dep to its package.json file')
    t.same(
      require(resolve(path, 'b', 'package.json')),
      { dependencies: { abbrev: '^1.0.4' } },
      'should not change workspace b package.json file')

    t.matchSnapshot(
      fs.readFileSync(resolve(path, 'package-lock.json'), 'utf8'),
      'should update lockfile with single dep updated package.json save=true'
    )
  })

  t.test('should preserve exact ranges', async t => {
    const path = fixture(t, 'update-exact-version')

    await reify(path, { update: true, save: true })

    t.equal(
      require(resolve(path, 'package.json')).dependencies.abbrev,
      '1.0.4',
      'should save no top level dep update to root package.json'
    )
  })

  t.test('should preserve exact ranges, missing actual tree', async t => {
    const path = t.testdir({
      'package.json': JSON.stringify({
        dependencies: {
          abbrev: '1.0.4',
        },
      }),
    })

    await reify(path, { update: true, save: true })

    t.equal(
      require(resolve(path, 'package.json')).dependencies.abbrev,
      '1.0.4',
      'should save no top level dep update to root package.json'
    )
  })

  t.test('should not throw when trying to update a link dep', async t => {
    const path = t.testdir({
      one: {
        'package.json': JSON.stringify({
          name: 'one',
          version: '1.0.0',
          dependencies: {
            two: 'file:../two',
          },
        }),
      },
      two: {
        'package.json': JSON.stringify({
          name: 'two',
          version: '1.0.0',
        }),
      },
    })

    await t.resolves(reify(resolve(path, 'one'), { update: true, save: true, workspaces: [] }))

    t.equal(
      require(resolve(path, 'one', 'package.json')).dependencies.two,
      'file:../two',
      'should have made no changes'
    )
  })
  t.end()
})

t.test('installLinks', (t) => {
  t.test('when true, packs and extracts instead of symlinks', async (t) => {
    const path = t.testdir({
      a: {
        'package.json': JSON.stringify({
          name: 'a',
          version: '1.0.0',
          main: 'index.js',
          dependencies: {
            b: 'file:../b',
          },
        }),
        'index.js': '',
      },
      b: {
        'package.json': JSON.stringify({
          name: 'b',
          version: '1.0.0',
          main: 'index.js',
        }),
        'index.js': '',
      },
    })

    await reify(resolve(path, 'a'), { installLinks: true })

    const installedB = fs.lstatSync(resolve(path, 'a/node_modules/b'))
    t.ok(installedB.isDirectory(), 'a/node_modules/b is a directory')
  })

  t.test('when false, symlinks', async (t) => {
    const path = t.testdir({
      a: {
        'package.json': JSON.stringify({
          name: 'a',
          version: '1.0.0',
          main: 'index.js',
          dependencies: {
            b: 'file:../b',
          },
        }),
        'index.js': '',
      },
      b: {
        'package.json': JSON.stringify({
          name: 'b',
          version: '1.0.0',
          main: 'index.js',
        }),
        'index.js': '',
      },
    })

    await reify(resolve(path, 'a'), { installLinks: false })

    const installedB = fs.lstatSync(resolve(path, 'a/node_modules/b'))
    t.ok(installedB.isSymbolicLink(), 'a/node_modules/b is a symlink')
  })

  t.test('when symlinks exist, installLinks set to true replaces them with dirs', async (t) => {
    const path = t.testdir({
      a: {
        'package.json': JSON.stringify({
          name: 'a',
          version: '1.0.0',
          main: 'index.js',
          dependencies: {
            b: 'file:../b',
          },
        }),
        'index.js': '',
      },
      b: {
        'package.json': JSON.stringify({
          name: 'b',
          version: '1.0.0',
          main: 'index.js',
        }),
        'index.js': '',
      },
    })

    await reify(resolve(path, 'a'), { installLinks: false, save: true })

    const firstB = fs.lstatSync(resolve(path, 'a/node_modules/b'))
    t.ok(firstB.isSymbolicLink(), 'a/node_modules/b is a symlink')

    await reify(resolve(path, 'a'), { installLinks: true, save: true })

    const secondB = fs.lstatSync(resolve(path, 'a/node_modules/b'))
    t.ok(secondB.isDirectory(), 'a/node_modules/b is now a directory')
  })

  t.test('when directories exist, installLinks set to false replaces them with symlinks', async (t) => {
    const path = t.testdir({
      a: {
        'package.json': JSON.stringify({
          name: 'a',
          version: '1.0.0',
          main: 'index.js',
          dependencies: {
            b: 'file:../b',
          },
        }),
        'index.js': '',
      },
      b: {
        'package.json': JSON.stringify({
          name: 'b',
          version: '1.0.0',
          main: 'index.js',
        }),
        'index.js': '',
      },
    })

    await reify(resolve(path, 'a'), { installLinks: true })

    const firstB = fs.lstatSync(resolve(path, 'a/node_modules/b'))
    t.ok(firstB.isDirectory(), 'a/node_modules/b is a directory')

    await reify(resolve(path, 'a'), { installLinks: false })

    const secondB = fs.lstatSync(resolve(path, 'a/node_modules/b'))
    t.ok(secondB.isSymbolicLink(), 'a/node_modules/b is now a symlink')
  })

  t.test('when installLinks is true, dependencies of links are installed', async (t) => {
    const path = t.testdir({
      a: {
        'package.json': JSON.stringify({
          name: 'a',
          version: '1.0.0',
          main: 'index.js',
          dependencies: {
            b: 'file:../b',
          },
        }),
        'index.js': '',
      },
      b: {
        'package.json': JSON.stringify({
          name: 'b',
          version: '1.0.0',
          main: 'index.js',
          dependencies: {
            abbrev: '^1.0.0',
          },
        }),
        'index.js': '',
      },
    })

    await reify(resolve(path, 'a'), { installLinks: true })

    const installedB = fs.lstatSync(resolve(path, 'a/node_modules/b'))
    t.ok(installedB.isDirectory(), 'a/node_modules/b is a directory')

    const abbrev = fs.lstatSync(resolve(path, 'a/node_modules/abbrev'))
    t.ok(abbrev.isDirectory(), 'abbrev got installed')
  })

  t.test('workspaces are always symlinks, even with installLinks set to true', async (t) => {
    const path = t.testdir({
      a: {
        'package.json': JSON.stringify({
          name: 'a',
          version: '1.0.0',
          main: 'index.js',
          dependencies: {
            b: 'file:../b',
            c: '^1.0.0',
          },
          workspaces: ['./c'],
        }),
        'index.js': '',
        c: {
          'package.json': JSON.stringify({
            name: 'c',
            version: '1.0.0',
            main: 'index.js',
          }),
          'index.js': '',
        },
      },
      b: {
        'package.json': JSON.stringify({
          name: 'b',
          version: '1.0.0',
          main: 'index.js',
          dependencies: {
            abbrev: '^1.0.0',
          },
        }),
        'index.js': '',
      },
    })

    await reify(resolve(path, 'a'), { installLinks: true })

    const installedB = fs.lstatSync(resolve(path, 'a/node_modules/b'))
    t.ok(installedB.isDirectory(), 'a/node_modules/b is a directory')

    const installedC = fs.lstatSync(resolve(path, 'a/node_modules/c'))
    t.ok(installedC.isSymbolicLink(), 'a/node_modules/c is a symlink')

    const abbrev = fs.lstatSync(resolve(path, 'a/node_modules/abbrev'))
    t.ok(abbrev.isDirectory(), 'abbrev got installed')
  })

  t.end()
})

t.only('should preserve exact ranges, missing actual tree', async (t) => {
  const Arborist = require('../../lib/index.js')
  const abbrev = resolve(__dirname,
    '../fixtures/registry-mocks/content/abbrev/-/abbrev-1.1.1.tgz')
  const abbrevTGZ = fs.readFileSync(abbrev)

  const abbrevPackument = JSON.stringify({
    _id: 'abbrev',
    _rev: 'lkjadflkjasdf',
    name: 'abbrev',
    'dist-tags': { latest: '1.1.1' },
    versions: {
      '1.1.1': {
        name: 'abbrev',
        version: '1.1.1',
        dist: {
          tarball: 'https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz',
        },
      },
    },
  })

  const abbrevPackument2 = JSON.stringify({
    _id: 'abbrev',
    _rev: 'lkjadflkjasdf',
    name: 'abbrev',
    'dist-tags': { latest: '1.1.1' },
    versions: {
      '1.1.1': {
        name: 'abbrev',
        version: '1.1.1',
        dist: {
          tarball: 'https://registry.garbage.org/abbrev/-/abbrev-1.1.1.tgz',
        },
      },
    },
  })

  t.only('host should not be replaced replaceRegistryHost=never', async (t) => {
    const testdir = t.testdir({
      project: {
        'package.json': JSON.stringify({
          name: 'myproject',
          version: '1.0.0',
          dependencies: {
            abbrev: '1.1.1',
          },
        }),
      },
    })

    tnock(t, 'https://registry.github.com')
      .get('/abbrev')
      .reply(200, abbrevPackument)

    tnock(t, 'https://registry.npmjs.org')
      .get('/abbrev/-/abbrev-1.1.1.tgz')
      .reply(200, abbrevTGZ)

    const arb = new Arborist({
      path: resolve(testdir, 'project'),
      registry: 'https://registry.github.com',
      cache: resolve(testdir, 'cache'),
      replaceRegistryHost: 'never',
    })
    await arb.reify()
  })

  t.only('host should be replaced replaceRegistryHost=npmjs', async (t) => {
    const testdir = t.testdir({
      project: {
        'package.json': JSON.stringify({
          name: 'myproject',
          version: '1.0.0',
          dependencies: {
            abbrev: '1.1.1',
          },
        }),
      },
    })

    tnock(t, 'https://registry.github.com')
      .get('/abbrev')
      .reply(200, abbrevPackument)

    tnock(t, 'https://registry.github.com')
      .get('/abbrev/-/abbrev-1.1.1.tgz')
      .reply(200, abbrevTGZ)

    const arb = new Arborist({
      path: resolve(testdir, 'project'),
      registry: 'https://registry.github.com',
      cache: resolve(testdir, 'cache'),
      replaceRegistryHost: 'npmjs',
    })
    await arb.reify()
  })

  t.only('host should be always replaceRegistryHost=always', async (t) => {
    const testdir = t.testdir({
      project: {
        'package.json': JSON.stringify({
          name: 'myproject',
          version: '1.0.0',
          dependencies: {
            abbrev: '1.1.1',
          },
        }),
      },
    })

    tnock(t, 'https://registry.github.com')
      .get('/abbrev')
      .reply(200, abbrevPackument2)

    tnock(t, 'https://registry.github.com')
      .get('/abbrev/-/abbrev-1.1.1.tgz')
      .reply(200, abbrevTGZ)

    const arb = new Arborist({
      path: resolve(testdir, 'project'),
      registry: 'https://registry.github.com',
      cache: resolve(testdir, 'cache'),
      replaceRegistryHost: 'always',
    })
    await arb.reify()
  })
})