bun_install 0.1.0

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
use core::fmt;
use std::io::Write as _;

use bun_core::fmt::PathSep;
use bun_core::{Global, Output, fmt as bun_fmt};
use bun_core::{ZStr, strings};
use bun_paths::platform;
use bun_paths::resolve_path;
use bun_paths::{PathBuffer, Platform, SEP};
use bun_sys::{self as sys, Dir, Fd, FdDirExt as _, FdExt as _};

use crate::bun_fs::FileSystem;
use crate::bun_json as JSON;
use crate::dependency::{Dependency, DependencyExt as _};
use crate::isolated_install::FileCopier;
use crate::lockfile_real::package::{Package, PackageColumns as _};
use crate::lockfile_real::tree;
use crate::lockfile_real::{self as lockfile, Lockfile, PackageIndexEntry};
use crate::package_manager_real::PackageManager;
use crate::package_manager_real::options::{LogLevel, PatchFeatures};
use crate::package_manager_real::package_manager_directories::{
    compute_cache_dir_and_subpath, get_temporary_directory,
};
use crate::{
    BuntagHashBuf, DependencyID, Features, PackageID, buntaghashbuf_make, initialize_store,
    invalid_package_id,
};

#[inline]
fn string_hash(s: &[u8]) -> u64 {
    bun_semver::semver_string::Builder::string_hash(s)
}

#[derive(Default)]
pub struct PatchCommitResult {
    pub patch_key: Box<[u8]>,
    pub patchfile_path: Box<[u8]>,
    pub not_in_workspace_root: bool,
}

/// - Arg is the dir containing the package with changes OR name and version
/// - Get the patch file contents by running git diff on the temp dir and the original package dir
/// - Write the patch file to $PATCHES_DIR/$PKG_NAME_AND_VERSION.patch
/// - Update "patchedDependencies" in package.json
/// - Run install to install newly patched pkg
pub fn do_patch_commit(
    manager: &mut PackageManager,
    pathbuf: &mut PathBuffer,
    log_level: LogLevel,
) -> Result<Option<PatchCommitResult>, bun_core::Error> {
    let mut folder_path_buf = PathBuffer::uninit();
    let mut lockfile: Box<Lockfile> = Box::default();
    let log = manager.log_mut();
    // TODO(port): narrow error set
    match lockfile.load_from_cwd::<true>(Some(manager), log) {
        lockfile::LoadResult::NotFound => {
            Output::err_generic(
                "Cannot find lockfile. Install packages with `<cyan>bun install<r>` before patching them.",
                (),
            );
            Global::crash();
        }
        lockfile::LoadResult::Err(cause) => {
            if log_level != LogLevel::Silent {
                match cause.step {
                    lockfile::LoadStep::OpenFile => Output::pretty_error(format_args!(
                        "<r><red>error<r> opening lockfile:<r> {}\n<r>",
                        cause.value.name(),
                    )),
                    lockfile::LoadStep::ParseFile => Output::pretty_error(format_args!(
                        "<r><red>error<r> parsing lockfile:<r> {}\n<r>",
                        cause.value.name(),
                    )),
                    lockfile::LoadStep::ReadFile => Output::pretty_error(format_args!(
                        "<r><red>error<r> reading lockfile:<r> {}\n<r>",
                        cause.value.name(),
                    )),
                    lockfile::LoadStep::Migrating => Output::pretty_error(format_args!(
                        "<r><red>error<r> migrating lockfile:<r> {}\n<r>",
                        cause.value.name(),
                    )),
                }

                if manager.options.enable.fail_early() {
                    Output::pretty_error("<b><red>failed to load lockfile<r>\n");
                } else {
                    Output::pretty_error("<b><red>ignoring lockfile<r>\n");
                }

                Output::flush();
            }
            Global::crash();
        }
        lockfile::LoadResult::Ok(_) => {}
    }

    let argument: &'static [u8] = manager.options.positionals[1];
    let arg_kind: PatchArgKind = PatchArgKind::from_arg(argument);

    let workspace_package_id = manager
        .root_package_id
        .get(&lockfile, manager.workspace_name_hash);
    let not_in_workspace_root = workspace_package_id != 0;
    // PORT NOTE: reshaped for borrowck — owned buffer kept separately so `argument` can borrow it
    let argument_owned: Option<Box<[u8]>>;
    let argument: &[u8] = if arg_kind == PatchArgKind::Path
        && not_in_workspace_root
        && (!Platform::Posix.is_absolute(argument)
            || (cfg!(windows) && !Platform::Windows.is_absolute(argument)))
    {
        if let Some(rel_path) = path_argument_relative_to_root_workspace_package(
            &lockfile,
            workspace_package_id,
            argument,
        ) {
            argument_owned = Some(rel_path);
            argument_owned.as_deref().unwrap()
        } else {
            argument
        }
    } else {
        argument
    };

    // Attempt to open the existing node_modules folder
    let root_node_modules: Dir = match sys::openat_os_path(
        Fd::cwd(),
        bun_paths::os_path_literal!("node_modules"),
        sys::O::DIRECTORY | sys::O::RDONLY,
        0o755,
    ) {
        Ok(fd) => Dir::from_fd(fd),
        Err(e) => {
            Output::pretty_error(format_args!(
                "<r><red>error<r>: failed to open root <b>node_modules<r> folder: {}<r>\n",
                e
            ));
            Global::crash();
        }
    };

    let mut iterator = tree::Iterator::<{ tree::IteratorPathStyle::NodeModules }>::init(&lockfile);
    let mut resolution_buf = [0u8; 1024];
    let (changes_dir, pkg): (Vec<u8>, Package) = match arg_kind {
            PatchArgKind::Path => 'result: {
                let package_json_path =
                    resolve_path::join_z::<platform::Auto>(&[argument, b"package.json"]);
                let package_json_source: bun_ast::Source =
                    match bun_ast::to_source(package_json_path, Default::default()) {
                        Ok(s) => s,
                        Err(e) => {
                            Output::err(
                                e,
                                "failed to read {f}",
                                (bun_fmt::quote(package_json_path.as_bytes()),),
                            );
                            Global::crash();
                        }
                    };

                initialize_store();
                let log = manager.log_mut();
                let bump = bun_alloc::Arena::new();
                let json = match JSON::parse_package_json_utf8(&package_json_source, log, &bump) {
                    Ok(j) => j,
                    Err(err) => {
                        let _ = log.print(std::ptr::from_mut(Output::error_writer()));
                        Output::pretty_errorln(format_args!(
                            "<r><red>{}<r> parsing package.json in <b>\"{}\"<r>",
                            err.name(),
                            bstr::BStr::new(package_json_source.path.pretty_dir()),
                        ));
                        Global::crash();
                    }
                };

                let version: &[u8] = 'version: {
                    if let Some(v) = json.get(b"version") {
                        if let bun_ast::ExprData::EString(s) = &v.data {
                            let s = s.data.slice();
                            break 'version s;
                        }
                    }
                    Output::pretty_error(format_args!(
                        "<r><red>error<r>: invalid package.json, missing or invalid property \"version\": {}<r>\n",
                        bstr::BStr::new(package_json_source.path.text()),
                    ));
                    Global::crash();
                };

                let mut resolver: () = ();
                let mut package = Package::default();
                let log = manager.log_mut();
                package.parse_with_json::<()>(
                    &mut lockfile,
                    manager,
                    log,
                    &package_json_source,
                    json,
                    &mut resolver,
                    Features::FOLDER,
                )?;

                let actual_package = match lockfile.package_index.get(&package.name_hash) {
                    None => {
                        Output::pretty_error(
                            "<r><red>error<r>: failed to find package in lockfile package index, this is a bug in Bun. Please file a GitHub issue.<r>\n",
                        );
                        Global::crash();
                    }
                    Some(PackageIndexEntry::Id(id)) => *lockfile.packages.get(*id as usize),
                    Some(PackageIndexEntry::Ids(ids)) => 'brk: {
                        for &id in ids.as_slice() {
                            let pkg = *lockfile.packages.get(id as usize);
                            let total = resolution_buf.len();
                            let mut cursor: &mut [u8] = &mut resolution_buf[..];
                            write!(
                                &mut cursor,
                                "{}",
                                pkg.resolution
                                    .fmt(lockfile.buffers.string_bytes.as_slice(), PathSep::Posix)
                            )
                            .expect("unreachable");
                            let written = total - cursor.len();
                            let resolution_label = &resolution_buf[..written];
                            if resolution_label == version {
                                break 'brk pkg;
                            }
                        }
                        Output::pretty_error(format_args!(
                            "<r><red>error<r>: could not find package with name:<r> {}\n<r>",
                            bstr::BStr::new(
                                package.name.slice(lockfile.buffers.string_bytes.as_slice())
                            ),
                        ));
                        Global::crash();
                    }
                };

                let changes_dir = argument.to_vec();

                break 'result (changes_dir, actual_package);
            }
            PatchArgKind::NameAndVersion => 'brk: {
                let (name, version) = Dependency::split_name_and_maybe_version(argument);
                let (pkg_id, node_modules_relative_path) = pkg_info_for_name_and_version(
                    &lockfile,
                    &mut iterator,
                    argument,
                    name,
                    version,
                );

                let changes_dir = resolve_path::join_z_buf::<platform::Auto>(
                    &mut pathbuf[..],
                    &[&node_modules_relative_path, name],
                )
                .as_bytes()
                .to_vec();
                break 'brk (changes_dir, *lockfile.packages.get(pkg_id as usize));
            }
        };

    // `compute_cache_dir_and_subpath` resolves `pkg.resolution`'s strings against `manager.lockfile`.
    manager.lockfile = lockfile;
    let name = manager.lockfile.str(&pkg.name).to_vec();
    let cache_result =
        compute_cache_dir_and_subpath(manager, &name, &pkg.resolution, &mut folder_path_buf, None);
    let cache_dir: Fd = cache_result.cache_dir;
    let cache_dir_subpath: &ZStr = cache_result.cache_dir_subpath;
    let changes_dir: &[u8] = &changes_dir;
    let lockfile: &Lockfile = &manager.lockfile;

    let name = name.as_slice();
    let resolution_label_len = {
        let total = resolution_buf.len();
        let mut cursor: &mut [u8] = &mut resolution_buf[..];
        write!(
            &mut cursor,
            "{}@{}",
            bstr::BStr::new(name),
            pkg.resolution
                .fmt(lockfile.buffers.string_bytes.as_slice(), PathSep::Posix)
        )
        .expect("unreachable");
        total - cursor.len()
    };
    let resolution_label = &resolution_buf[..resolution_label_len];

    let patchfile_contents: Vec<u8> = 'brk: {
        let new_folder = changes_dir;
        let mut buf2 = PathBuffer::uninit();
        let mut buf3 = PathBuffer::uninit();
        let old_folder: &[u8] = 'old_folder: {
            let cache_dir_path = match sys::get_fd_path(cache_dir, &mut buf2) {
                Ok(s) => s,
                Err(e) => {
                    Output::err(e, "failed to read from cache", ());
                    Global::crash();
                }
            };
            break 'old_folder resolve_path::join::<platform::Posix>(&[
                cache_dir_path,
                cache_dir_subpath.as_bytes(),
            ]);
        };

        let random_tempdir = match bun_paths::fs::FileSystem::tmpname(
            b"node_modules_tmp",
            &mut buf2[..],
            bun_core::fast_random(),
        ) {
            Ok(s) => s,
            Err(e) => {
                Output::err(e, "failed to make tempdir", ());
                Global::crash();
            }
        };

        // If the package has nested a node_modules folder, we don't want this to
        // appear in the patch file when we run git diff.
        //
        // There isn't an option to exclude it with `git diff --no-index`, so we
        // will `rename()` it out and back again.
        let has_nested_node_modules: bool = 'has_nested_node_modules: {
            let new_folder_handle =
                match Dir::cwd().open_dir(new_folder, sys::OpenDirOptions::default()) {
                    Ok(h) => h,
                    Err(e) => {
                        Output::err(
                            e,
                            "failed to open directory <b>{s}<r>",
                            (bstr::BStr::new(new_folder),),
                        );
                        Global::crash();
                    }
                };

            if sys::renameat_concurrently_a(
                new_folder_handle.fd,
                b"node_modules",
                root_node_modules.fd,
                random_tempdir.as_bytes(),
                sys::RenameOptions {
                    move_fallback: true,
                },
            )
            .is_err()
            {
                break 'has_nested_node_modules false;
            }

            break 'has_nested_node_modules true;
        };

        let patch_tag_tmpname = match bun_paths::fs::FileSystem::tmpname(
            b"patch_tmp",
            &mut buf3[..],
            bun_core::fast_random(),
        ) {
            Ok(s) => s,
            Err(e) => {
                Output::err(e, "failed to make tempdir", ());
                Global::crash();
            }
        };

        let mut bunpatchtagbuf: BuntagHashBuf = BuntagHashBuf::default();
        // If the package was already patched then it might have a ".bun-tag-XXXXXXXX"
        // we need to rename this out and back too.
        let bun_patch_tag: Option<&[u8]> = 'has_bun_patch_tag: {
            let name_and_version_hash = string_hash(resolution_label);
            let patch_tag: &[u8] = 'patch_tag: {
                if let Some(patchdep) = lockfile.patched_dependencies.get(&name_and_version_hash) {
                    if let Some(hash) = patchdep.patchfile_hash() {
                        break 'patch_tag &*buntaghashbuf_make(&mut bunpatchtagbuf, hash);
                    }
                }
                break 'has_bun_patch_tag None;
            };
            let new_folder_handle =
                match Dir::cwd().open_dir(new_folder, sys::OpenDirOptions::default()) {
                    Ok(h) => h,
                    Err(e) => {
                        Output::err(
                            e,
                            "failed to open directory <b>{s}<r>",
                            (bstr::BStr::new(new_folder),),
                        );
                        Global::crash();
                    }
                };

            if let Err(e) = sys::renameat_concurrently_a(
                new_folder_handle.fd,
                patch_tag,
                root_node_modules.fd,
                patch_tag_tmpname.as_bytes(),
                sys::RenameOptions {
                    move_fallback: true,
                },
            ) {
                Output::warn(format_args!(
                    "failed renaming the bun patch tag, this may cause issues: {}",
                    e
                ));
                break 'has_bun_patch_tag None;
            }
            break 'has_bun_patch_tag Some(patch_tag);
        };
        // PORT NOTE: deferred restore — one-off rename-back logic on every exit
        // path of `'brk`. Captures borrow into stack buffers.
        scopeguard::defer! {
            if has_nested_node_modules || bun_patch_tag.is_some() {
                let new_folder_handle = match Dir::cwd().open_dir(new_folder, sys::OpenDirOptions::default()) {
                    Ok(h) => h,
                    Err(e) => {
                        Output::pretty_error(format_args!(
                            "<r><red>error<r>: failed to open directory <b>{}<r> {}<r>\n",
                            bstr::BStr::new(new_folder),
                            e,
                        ));
                        Global::crash();
                    }
                };

                if has_nested_node_modules {
                    if let Err(e) = sys::renameat_concurrently_a(
                        root_node_modules.fd,
                        random_tempdir.as_bytes(),
                        new_folder_handle.fd,
                        b"node_modules",
                        sys::RenameOptions { move_fallback: true },
                    ) {
                        Output::warn(format_args!("failed renaming nested node_modules folder, this may cause issues: {}", e));
                    }
                }

                if let Some(patch_tag) = bun_patch_tag {
                    if let Err(e) = sys::renameat_concurrently_a(
                        root_node_modules.fd,
                        patch_tag_tmpname.as_bytes(),
                        new_folder_handle.fd,
                        patch_tag,
                        sys::RenameOptions { move_fallback: true },
                    ) {
                        Output::warn(format_args!("failed renaming the bun patch tag, this may cause issues: {}", e));
                    }
                }
            }
        }

        let mut cwdbuf = PathBuffer::uninit();
        let cwd = match sys::getcwd_z(&mut cwdbuf) {
            Ok(fd) => fd,
            Err(e) => {
                Output::pretty_error(format_args!(
                    "<r><red>error<r>: failed to get cwd path {}<r>\n",
                    e
                ));
                Global::crash();
            }
        };
        let mut gitbuf = PathBuffer::uninit();
        let git = match bun_which::which(
            &mut gitbuf,
            bun_core::env_var::PATH.get().unwrap_or(b""),
            cwd.as_bytes(),
            b"git",
        ) {
            Some(g) => g,
            None => {
                Output::pretty_error(
                    "<r><red>error<r>: git must be installed to use `bun patch --commit` <r>\n",
                );
                Global::crash();
            }
        };
        let paths = crate::patch_parser::git_diff_preprocess_paths::<false>(old_folder, new_folder);
        let (opts, _envp_guard) =
            crate::patch_parser::spawn_opts(&paths[0], &paths[1], cwd, git, &mut manager.event_loop);

        let mut spawn_result = match bun_spawn::sync::spawn(&opts) {
            Err(e) => {
                Output::pretty_error(format_args!(
                    "<r><red>error<r>: failed to make diff {}<r>\n",
                    e.name(),
                ));
                Global::crash();
            }
            Ok(Ok(r)) => r,
            Ok(Err(e)) => {
                Output::pretty_error(format_args!(
                    "<r><red>error<r>: failed to make diff {}<r>\n",
                    e
                ));
                Global::crash();
            }
        };

        let contents: Vec<u8> =
            match crate::patch_parser::diff_post_process(&mut spawn_result, &paths[0], &paths[1]) {
                Err(e) => {
                    Output::pretty_error(format_args!(
                        "<r><red>error<r>: failed to make diff {}<r>\n",
                        e.name(),
                    ));
                    Global::crash();
                }
                Ok(Ok(stdout)) => stdout,
                Ok(Err(stderr)) => {
                    struct Truncate<'a> {
                        stderr: &'a Vec<u8>,
                    }

                    impl fmt::Display for Truncate<'_> {
                        fn fmt(&self, writer: &mut fmt::Formatter<'_>) -> fmt::Result {
                            let truncate_stderr = self.stderr.len() > 256;
                            if truncate_stderr {
                                write!(
                                    writer,
                                    "{}... ({} more bytes)",
                                    bstr::BStr::new(&self.stderr[0..256]),
                                    self.stderr.len() - 256
                                )
                            } else {
                                write!(writer, "{}", bstr::BStr::new(&self.stderr[..]))
                            }
                        }
                    }
                    Output::pretty_error(format_args!(
                        "<r><red>error<r>: failed to make diff {}<r>\n",
                        Truncate { stderr: &stderr }
                    ));
                    drop(stderr);
                    Global::crash();
                }
            };

        if contents.is_empty() {
            Output::pretty(format_args!(
                "\n<r>No changes detected, comparing <red>{}<r> to <green>{}<r>\n",
                bstr::BStr::new(old_folder),
                bstr::BStr::new(new_folder)
            ));
            Output::flush();
            drop(contents);
            return Ok(None);
        }

        break 'brk contents;
    };

    // write the patch contents to temp file then rename
    let mut tmpname_buf = [0u8; 1024];
    let tempfile_name =
        bun_paths::fs::FileSystem::tmpname(b"tmp", &mut tmpname_buf, bun_core::fast_random())?;
    let tmpdir = get_temporary_directory(manager).handle.fd();
    if let Err(e) = sys::File::write_file(tmpdir, tempfile_name, &patchfile_contents) {
        Output::err(e, "failed to write patch to temp file", ());
        Global::crash();
    }

    resolution_buf[resolution_label_len..resolution_label_len + b".patch".len()]
        .copy_from_slice(b".patch");
    let mut patch_filename: &[u8] = &resolution_buf[0..resolution_label_len + b".patch".len()];
    let escaped_owned: Option<Box<[u8]>>;
    if let Some(escaped) = escape_patch_filename(patch_filename) {
        escaped_owned = Some(escaped);
        patch_filename = escaped_owned.as_deref().unwrap();
    } else {
        escaped_owned = None;
    }
    let _ = &escaped_owned;

    let patches_dir: &[u8] = match &manager.options.patch_features {
        PatchFeatures::Commit { patches_dir } => patches_dir,
        // Reaching `doPatchCommit` implies `Subcommand::PatchCommit`, which always
        // sets `patch_features = .commit` in `Options::load`.
        _ => unreachable!("patch_features must be Commit in doPatchCommit"),
    };

    let path_in_patches_dir =
        resolve_path::join_z::<platform::Posix>(&[patches_dir, patch_filename]);

    // mkdir-p syscall is used here, no JS surface; route directly through
    // `bun_sys::mkdir_recursive` to avoid the `bun_runtime` dep cycle.
    if let Err(e) = sys::mkdir_recursive(patches_dir) {
        Output::err(
            e,
            "failed to make patches dir {f}",
            (bun_fmt::quote(patches_dir),),
        );
        Global::crash();
    }

    // rename to patches dir
    if let Err(e) = sys::renameat_concurrently(
        tmpdir,
        tempfile_name,
        Fd::cwd(),
        path_in_patches_dir,
        sys::RenameOptions {
            move_fallback: true,
        },
    ) {
        Output::err(e, "failed renaming patch file to patches dir", ());
        Global::crash();
    }

    let mut patch_key = Vec::new();
    // PORT NOTE: re-slice instead of reusing `resolution_label` so its borrow ends
    // before the `.patch` suffix write above; the prefix bytes are unchanged.
    write!(
        &mut patch_key,
        "{}",
        bstr::BStr::new(&resolution_buf[..resolution_label_len])
    )
    .expect("infallible: in-memory write");
    let patch_key: Box<[u8]> = patch_key.into_boxed_slice();
    let patchfile_path: Box<[u8]> = Box::<[u8]>::from(path_in_patches_dir.as_bytes());
    let _ = sys::unlink(resolve_path::join_z::<platform::Auto>(&[
        changes_dir,
        b".bun-patch-tag",
    ]));

    Ok(Some(PatchCommitResult {
        patch_key,
        patchfile_path,
        not_in_workspace_root,
    }))
}

fn escape_patch_filename(name: &[u8]) -> Option<Box<[u8]>> {
    #[derive(Copy, Clone, PartialEq, Eq)]
    #[repr(u8)]
    enum EscapeVal {
        Slash,
        Backslash,
        Space,
        Newline,
        CarriageReturn,
        Tab,
        // NTFS-reserved; escaped on every OS so a committed patches/ dir checks out on Windows.
        Colon,
        Question,
        Asterisk,
        Quote,
        LessThan,
        GreaterThan,
        Pipe,
        // Dot,
        Other,
    }

    impl EscapeVal {
        pub(crate) fn escaped(self) -> Option<&'static [u8]> {
            match self {
                EscapeVal::Slash => Some(b"%2F"),
                EscapeVal::Backslash => Some(b"%5c"),
                EscapeVal::Space => Some(b"%20"),
                EscapeVal::Newline => Some(b"%0A"),
                EscapeVal::CarriageReturn => Some(b"%0D"),
                EscapeVal::Tab => Some(b"%09"),
                EscapeVal::Colon => Some(b"%3A"),
                EscapeVal::Question => Some(b"%3F"),
                EscapeVal::Asterisk => Some(b"%2A"),
                EscapeVal::Quote => Some(b"%22"),
                EscapeVal::LessThan => Some(b"%3C"),
                EscapeVal::GreaterThan => Some(b"%3E"),
                EscapeVal::Pipe => Some(b"%7C"),
                // EscapeVal::Dot => Some(b"%2E"),
                EscapeVal::Other => None,
            }
        }
    }

    // PORT NOTE: Zig built this table via @typeInfo reflection over single-char enum field names.
    // Rust has no equivalent; the table is filled by hand with the same entries.
    const ESCAPE_TABLE: [EscapeVal; 256] = {
        let mut table = [EscapeVal::Other; 256];
        table[b'/' as usize] = EscapeVal::Slash;
        table[b'\\' as usize] = EscapeVal::Backslash;
        table[b' ' as usize] = EscapeVal::Space;
        table[b'\n' as usize] = EscapeVal::Newline;
        table[b'\r' as usize] = EscapeVal::CarriageReturn;
        table[b'\t' as usize] = EscapeVal::Tab;
        table[b':' as usize] = EscapeVal::Colon;
        table[b'?' as usize] = EscapeVal::Question;
        table[b'*' as usize] = EscapeVal::Asterisk;
        table[b'"' as usize] = EscapeVal::Quote;
        table[b'<' as usize] = EscapeVal::LessThan;
        table[b'>' as usize] = EscapeVal::GreaterThan;
        table[b'|' as usize] = EscapeVal::Pipe;
        table
    };
    let mut count: usize = 0;
    for &c in name {
        count += if let Some(e) = ESCAPE_TABLE[c as usize].escaped() {
            e.len()
        } else {
            1
        };
    }
    if count == name.len() {
        return None;
    }
    let mut buf = vec![0u8; count].into_boxed_slice();
    let mut i: usize = 0;
    for &c in name {
        let single = [c];
        let e: &[u8] = ESCAPE_TABLE[c as usize].escaped().unwrap_or(&single[..]);
        buf[i..i + e.len()].copy_from_slice(e);
        i += e.len();
    }
    Some(buf)
}

/// 1. Arg is either:
///   - name and possibly version (e.g. "is-even" or "is-even@1.0.0")
///   - path to package in node_modules
/// 2. Calculate cache dir for package
/// 3. Overwrite the input package with the one from the cache (cuz it could be hardlinked)
/// 4. Print to user
pub fn prepare_patch(manager: &mut PackageManager) -> Result<(), bun_core::Error> {
    let argument: &'static [u8] = manager.options.positionals[1];

    let arg_kind: PatchArgKind = PatchArgKind::from_arg(argument);

    let mut folder_path_buf = PathBuffer::uninit();
    let mut resolution_buf = [0u8; 1024];

    #[cfg(windows)]
    let mut win_normalizer = PathBuffer::uninit();

    let workspace_name_hash = manager.workspace_name_hash;
    let workspace_package_id = manager
        .root_package_id
        .get(&manager.lockfile, workspace_name_hash);
    let not_in_workspace_root = workspace_package_id != 0;
    // PORT NOTE: reshaped for borrowck — owned buffer kept so `argument` can borrow it.
    let argument_owned: Option<Box<[u8]>>;
    let argument: &[u8] = if arg_kind == PatchArgKind::Path
        && not_in_workspace_root
        && (!Platform::Posix.is_absolute(argument)
            || (cfg!(windows) && !Platform::Windows.is_absolute(argument)))
    {
        if let Some(rel_path) = path_argument_relative_to_root_workspace_package(
            &manager.lockfile,
            workspace_package_id,
            argument,
        ) {
            argument_owned = Some(rel_path);
            argument_owned.as_deref().unwrap()
        } else {
            argument
        }
    } else {
        argument
    };

    let (cache_dir, cache_dir_subpath, module_folder, pkg_name): (Fd, &[u8], Vec<u8>, Vec<u8>) =
        match arg_kind {
            PatchArgKind::Path => 'brk: {
                let package_json_path =
                    resolve_path::join_z::<platform::Auto>(&[argument, b"package.json"]);
                let package_json_source: bun_ast::Source =
                    match bun_ast::to_source(package_json_path, Default::default()) {
                        Ok(s) => s,
                        Err(e) => {
                            Output::err(
                                e,
                                "failed to read {f}",
                                (bun_fmt::quote(package_json_path.as_bytes()),),
                            );
                            Global::crash();
                        }
                    };

                initialize_store();
                let log = manager.log_mut();
                let bump = bun_alloc::Arena::new();
                let json = match JSON::parse_package_json_utf8(&package_json_source, log, &bump) {
                    Ok(j) => j,
                    Err(err) => {
                        let _ = log.print(std::ptr::from_mut(Output::error_writer()));
                        Output::pretty_errorln(format_args!(
                            "<r><red>{}<r> parsing package.json in <b>\"{}\"<r>",
                            err.name(),
                            bstr::BStr::new(package_json_source.path.pretty_dir()),
                        ));
                        Global::crash();
                    }
                };

                let version: &[u8] = 'version: {
                    if let Some(v) = json.get(b"version") {
                        if let bun_ast::ExprData::EString(s) = &v.data {
                            let s = s.data.slice();
                            break 'version s;
                        }
                    }
                    Output::pretty_error(format_args!(
                        "<r><red>error<r>: invalid package.json, missing or invalid property \"version\": {}<r>\n",
                        bstr::BStr::new(package_json_source.path.text()),
                    ));
                    Global::crash();
                };

                let mut resolver: () = ();
                let mut package = Package::default();
                let log = manager.log_mut();
                // PORT NOTE: borrowck — `parse_with_json` needs `&mut Lockfile` and
                // `&mut PackageManager` simultaneously, but the lockfile here is
                // `manager.lockfile`. Temporarily move the Box out so the two
                // borrows are disjoint; `parse_with_json` never reads `pm.lockfile`
                // (it takes the lockfile as its own parameter). Restore before
                // propagating any error so `manager` is never left half-torn.
                let mut lockfile: Box<Lockfile> = core::mem::take(&mut manager.lockfile);
                let parse_result = package.parse_with_json::<()>(
                    &mut lockfile,
                    manager,
                    log,
                    &package_json_source,
                    json,
                    &mut resolver,
                    Features::FOLDER,
                );
                manager.lockfile = lockfile;
                parse_result?;
                let lockfile: &Lockfile = &manager.lockfile;
                let strbuf = lockfile.buffers.string_bytes.as_slice();

                let actual_package = match lockfile.package_index.get(&package.name_hash) {
                    None => {
                        Output::pretty_error(
                            "<r><red>error<r>: failed to find package in lockfile package index, this is a bug in Bun. Please file a GitHub issue.<r>\n",
                        );
                        Global::crash();
                    }
                    Some(PackageIndexEntry::Id(id)) => *lockfile.packages.get(*id as usize),
                    Some(PackageIndexEntry::Ids(ids)) => 'id: {
                        for &id in ids.as_slice() {
                            let pkg = *lockfile.packages.get(id as usize);
                            let total = resolution_buf.len();
                            let mut cursor: &mut [u8] = &mut resolution_buf[..];
                            write!(
                                &mut cursor,
                                "{}",
                                pkg.resolution.fmt(strbuf, PathSep::Posix)
                            )
                            .expect("unreachable");
                            let written = total - cursor.len();
                            let resolution_label = &resolution_buf[..written];
                            if resolution_label == version {
                                break 'id pkg;
                            }
                        }
                        Output::pretty_error(format_args!(
                            "<r><red>error<r>: could not find package with name:<r> {}\n<r>",
                            bstr::BStr::new(package.name.slice(strbuf)),
                        ));
                        Global::crash();
                    }
                };

                let name = lockfile.str(&package.name).to_vec();
                let existing_patchfile_hash: Option<u64> = 'existing_patchfile_hash: {
                    // PERF(port): was stack-fallback alloc — profile if it shows up on a hot path.
                    let mut name_and_version = Vec::new();
                    write!(
                        &mut name_and_version,
                        "{}@{}",
                        bstr::BStr::new(&name),
                        actual_package.resolution.fmt(strbuf, PathSep::Posix)
                    )
                    .expect("unreachable");
                    let name_and_version_hash = string_hash(&name_and_version);
                    if let Some(patched_dep) =
                        lockfile.patched_dependencies.get(&name_and_version_hash)
                    {
                        if let Some(hash) = patched_dep.patchfile_hash() {
                            break 'existing_patchfile_hash Some(hash);
                        }
                    }
                    break 'existing_patchfile_hash None;
                };

                let cache_result = compute_cache_dir_and_subpath(
                    manager,
                    &name,
                    &actual_package.resolution,
                    &mut folder_path_buf,
                    existing_patchfile_hash,
                );
                let cache_dir = cache_result.cache_dir;
                let cache_dir_subpath = cache_result.cache_dir_subpath;

                #[cfg(windows)]
                let buf = resolve_path::path_to_posix_buf::<u8>(argument, &mut win_normalizer[..])
                    .to_vec();
                #[cfg(not(windows))]
                let buf = argument.to_vec();

                break 'brk (cache_dir, cache_dir_subpath.as_bytes(), buf, name);
            }
            PatchArgKind::NameAndVersion => 'brk: {
                let pkg_maybe_version_to_patch = argument;
                let (name, version) =
                    Dependency::split_name_and_maybe_version(pkg_maybe_version_to_patch);
                let mut iterator = tree::Iterator::<{ tree::IteratorPathStyle::NodeModules }>::init(
                    &manager.lockfile,
                );
                let (pkg_id, folder_relative_path) = pkg_info_for_name_and_version(
                    &manager.lockfile,
                    &mut iterator,
                    pkg_maybe_version_to_patch,
                    name,
                    version,
                );

                let strbuf = manager.lockfile.buffers.string_bytes.as_slice();
                let pkg = *manager.lockfile.packages.get(pkg_id as usize);
                let pkg_name = pkg.name.slice(strbuf).to_vec();

                let existing_patchfile_hash: Option<u64> = 'existing_patchfile_hash: {
                    // PERF(port): was stack-fallback alloc — profile if it shows up on a hot path.
                    let mut name_and_version = Vec::new();
                    write!(
                        &mut name_and_version,
                        "{}@{}",
                        bstr::BStr::new(name),
                        pkg.resolution.fmt(strbuf, PathSep::Posix)
                    )
                    .expect("unreachable");
                    let name_and_version_hash = string_hash(&name_and_version);
                    if let Some(patched_dep) = manager
                        .lockfile
                        .patched_dependencies
                        .get(&name_and_version_hash)
                    {
                        if let Some(hash) = patched_dep.patchfile_hash() {
                            break 'existing_patchfile_hash Some(hash);
                        }
                    }
                    break 'existing_patchfile_hash None;
                };

                let pkg_resolution = pkg.resolution;
                let cache_result = compute_cache_dir_and_subpath(
                    manager,
                    &pkg_name,
                    &pkg_resolution,
                    &mut folder_path_buf,
                    existing_patchfile_hash,
                );

                let cache_dir = cache_result.cache_dir;
                let cache_dir_subpath = cache_result.cache_dir_subpath;

                let module_folder_ =
                    resolve_path::join::<platform::Auto>(&[&folder_relative_path, name]);
                #[cfg(windows)]
                let buf =
                    resolve_path::path_to_posix_buf::<u8>(module_folder_, &mut win_normalizer[..])
                        .to_vec();
                #[cfg(not(windows))]
                let buf = module_folder_.to_vec();

                break 'brk (cache_dir, cache_dir_subpath.as_bytes(), buf, pkg_name);
            }
        };

    let module_folder: &[u8] = &module_folder;
    let pkg_name: &[u8] = &pkg_name;

    // The package may be installed using the hard link method,
    // meaning that changes to the folder will also change the package in the cache.
    //
    // So we will overwrite the folder by directly copying the package in cache into it
    //
    // With the isolated linker's global virtual store, `module_folder` is
    // reached *through* a `node_modules/.bun/<storepath>` symlink that points
    // into `<cache>/links/`. `deleteTree(module_folder)` would follow that
    // symlink and wipe the shared global entry (and its dep symlinks)
    // underneath every other project, then FileCopier would write the user's
    // edits into the shared cache. Detach first: walk up `module_folder` to
    // find the first symlink ancestor, replace it with a real directory, and
    // recreate the path below it so the copy lands in a project-local tree.
    detach_module_folder_from_shared_store(module_folder);

    if let Err(e) =
        overwrite_package_in_node_modules_folder(cache_dir, cache_dir_subpath, module_folder)
    {
        Output::pretty_error(format_args!(
            "<r><red>error<r>: error overwriting folder in node_modules: {}\n<r>",
            e.name(),
        ));
        Global::crash();
    }

    if not_in_workspace_root {
        let mut bufn = PathBuffer::uninit();
        Output::pretty(format_args!(
            "\nTo patch <b>{}<r>, edit the following folder:\n\n  <cyan>{}<r>\n",
            bstr::BStr::new(pkg_name),
            bstr::BStr::new(resolve_path::join_string_buf::<platform::Posix>(
                &mut bufn[..],
                &[
                    FileSystem::instance().top_level_dir_without_trailing_slash(),
                    module_folder
                ]
            )),
        ));
        Output::pretty(format_args!(
            "\nOnce you're done with your changes, run:\n\n  <cyan>bun patch --commit '{}'<r>\n",
            bstr::BStr::new(resolve_path::join_string_buf::<platform::Posix>(
                &mut bufn[..],
                &[
                    FileSystem::instance().top_level_dir_without_trailing_slash(),
                    module_folder
                ]
            )),
        ));
    } else {
        Output::pretty(format_args!(
            "\nTo patch <b>{}<r>, edit the following folder:\n\n  <cyan>{}<r>\n",
            bstr::BStr::new(pkg_name),
            bstr::BStr::new(module_folder)
        ));
        Output::pretty(format_args!(
            "\nOnce you're done with your changes, run:\n\n  <cyan>bun patch --commit '{}'<r>\n",
            bstr::BStr::new(module_folder)
        ));
    }

    Ok(())
}

fn detach_module_folder_from_shared_store(module_folder: &[u8]) {
    // `module_folder` reaches here normalised to forward slashes on every
    // platform (see `pathToPosixBuf` in `preparePatch`). Re-normalise to the
    // platform separator so `undo()`/`basename()` walk the path correctly on
    // Windows and the lstat/getFileAttributes calls below see a native path.
    #[cfg(windows)]
    let mut native_buf = PathBuffer::uninit();
    #[cfg(windows)]
    let native: &[u8] = {
        native_buf[0..module_folder.len()].copy_from_slice(module_folder);
        let slice = &mut native_buf[0..module_folder.len()];
        resolve_path::posix_to_platform_in_place::<u8>(slice);
        &*slice
    };
    #[cfg(not(windows))]
    let native: &[u8] = module_folder;

    let mut p = bun_paths::Path::<u8>::from(native).unwrap();
    let mut components: usize = 1;
    for &c in native {
        if c == SEP {
            components += 1;
        }
    }
    let mut depth: usize = 0;
    while depth < components {
        let is_symlink: bool = {
            #[cfg(windows)]
            {
                match sys::get_file_attributes(p.slice_z()) {
                    Some(attrs) => attrs.is_reparse_point,
                    None => return,
                }
            }
            #[cfg(not(windows))]
            {
                if let Ok(st) = sys::lstat(p.slice_z()) {
                    // `mode_t` is `u16` on darwin/freebsd, `u32` on linux.
                    sys::posix::s_islnk(st.st_mode as u32)
                } else {
                    return;
                }
            }
        };
        if is_symlink {
            // Windows directory symlinks/junctions are removed with rmdir,
            // file symlinks with unlink; on POSIX unlink covers both. If
            // removal fails the symlink is still live, and the caller's
            // `deleteTree` + `FileCopier` would follow it into the shared
            // global-store entry — so fail loudly here rather than silently
            // corrupting the cache.
            let remove_err: Option<sys::Error> = {
                #[cfg(windows)]
                'remove: {
                    if sys::rmdir(p.slice_z()).is_err() {
                        if let Err(e) = sys::unlink(p.slice_z()) {
                            break 'remove if e.get_errno() == sys::E::ENOENT {
                                None
                            } else {
                                Some(e)
                            };
                        }
                    }
                    break 'remove None;
                }
                #[cfg(not(windows))]
                {
                    if let Err(e) = sys::unlink(p.slice_z()) {
                        if e.get_errno() == sys::E::ENOENT {
                            None
                        } else {
                            Some(e)
                        }
                    } else {
                        None
                    }
                }
            };
            if let Some(e) = remove_err {
                Output::err(
                    e,
                    "failed to detach <b>{s}<r> from the shared package store; refusing to patch through it",
                    (bstr::BStr::new(p.slice()),),
                );
                Global::crash();
            }
            // Re-create the now-missing path segments below the removed
            // symlink so `module_folder`'s parent exists for the copy.
            let parent = resolve_path::dirname::<platform::Auto>(native);
            if !parent.is_empty() {
                let _ = Fd::cwd().make_path(parent);
            }
            return;
        }
        p.undo(1);
        depth += 1;
    }
}

fn overwrite_package_in_node_modules_folder(
    cache_dir: Fd,
    cache_dir_subpath: &[u8],
    node_modules_folder_path: &[u8],
) -> Result<(), bun_core::Error> {
    let _ = Fd::cwd().delete_tree(node_modules_folder_path);

    // FileCopier's path fields are `.unit = .os` (u16 on Windows). `Path::from`
    // is generic over the *input* width and converts internally, so accepting
    // `&[u8]` and producing `Path<OSPathChar>` is intentional. `.sep = .auto`
    // (Zig spec) is required so `/` is normalized to `\` on Windows — the inputs
    // here arrive posix-normalized and are later passed to Win32 APIs.
    let dest_subpath = bun_paths::Path::<
        bun_paths::OSPathChar,
        { bun_paths::path_options::Kind::ANY },
        { bun_paths::path_options::PathSeparators::AUTO },
    >::from(node_modules_folder_path)
    .unwrap();

    let src_path: bun_paths::AbsPath<
        bun_paths::OSPathChar,
        { bun_paths::path_options::PathSeparators::AUTO },
    > = 'src_path: {
        #[cfg(windows)]
        {
            let mut path_buf = bun_paths::WPathBuffer::uninit();
            let abs_path = sys::get_fd_path_w(cache_dir, &mut path_buf)?;

            let mut sp = bun_paths::AbsPath::<
                bun_paths::OSPathChar,
                { bun_paths::path_options::PathSeparators::AUTO },
            >::from(&*abs_path)
            .unwrap();
            sp.append(cache_dir_subpath)?;

            break 'src_path sp;
        }

        // unused if not windows
        #[cfg(not(windows))]
        {
            break 'src_path bun_paths::AbsPath::init();
        }
    };

    let cached_package_folder = Dir::borrow(&cache_dir).open_dir(
        cache_dir_subpath,
        sys::OpenDirOptions {
            iterate: true,
            ..Default::default()
        },
    )?;

    let ignore_directories: &[&bun_paths::OSPathSlice] = &[
        bun_paths::os_path_literal!("node_modules"),
        bun_paths::os_path_literal!(".git"),
        bun_paths::os_path_literal!("CMakeFiles"),
    ];

    let mut copier: FileCopier = FileCopier::init(
        cached_package_folder.fd,
        src_path,
        dest_subpath,
        ignore_directories,
    )?;

    copier.copy()?;
    Ok(())
}

type NodeModulesIterator<'a> = tree::Iterator<'a, { tree::IteratorPathStyle::NodeModules }>;

// PORT NOTE: reshaped for borrowck — `tree::Iterator::next` returns an
// `IteratorNext<'_>` borrowing the iterator's internal `path_buf`, so we
// cannot return it from inside a `while let` (borrowck rejects the next
// iteration's reborrow even though it's unreachable). Callers only need
// `relative_path`, so copy it out into an owned `Vec<u8>`.

fn node_modules_folder_for_dependency_ids(
    iterator: &mut NodeModulesIterator<'_>,
    ids: &[IdPair],
) -> Option<Vec<u8>> {
    loop {
        let node_modules = iterator.next(None)?;
        let mut found = false;
        for id in ids {
            if node_modules.dependencies.contains(&id.0) {
                found = true;
                break;
            }
        }
        if found {
            return Some(node_modules.relative_path.as_bytes().to_vec());
        }
    }
}

fn node_modules_folder_for_dependency_id(
    iterator: &mut NodeModulesIterator<'_>,
    dependency_id: DependencyID,
) -> Option<Vec<u8>> {
    loop {
        let node_modules = iterator.next(None)?;
        if !node_modules.dependencies.contains(&dependency_id) {
            continue;
        }
        return Some(node_modules.relative_path.as_bytes().to_vec());
    }
}

type IdPair = (DependencyID, PackageID);

fn pkg_info_for_name_and_version(
    lockfile: &Lockfile,
    iterator: &mut NodeModulesIterator<'_>,
    pkg_maybe_version_to_patch: &[u8],
    name: &[u8],
    version: Option<&[u8]>,
) -> (PackageID, Vec<u8>) {
    // PERF(port): was stack-fallback alloc — profile if it shows up on a hot path.
    let mut pairs: Vec<IdPair> = Vec::with_capacity(8);

    let name_hash = string_hash(name);

    let strbuf = lockfile.buffers.string_bytes.as_slice();

    let mut buf = [0u8; 1024];
    let dependencies = lockfile.buffers.dependencies.as_slice();

    for (dep_id, dep) in dependencies.iter().enumerate() {
        if dep.name_hash != name_hash {
            continue;
        }
        let pkg_id = lockfile.buffers.resolutions.as_slice()[dep_id];
        if pkg_id == invalid_package_id {
            continue;
        }
        let pkg = *lockfile.packages.get(pkg_id as usize);
        if let Some(v) = version {
            let written = {
                let total = buf.len();
                let mut cursor: &mut [u8] = &mut buf[..];
                write!(
                    &mut cursor,
                    "{}",
                    pkg.resolution.fmt(strbuf, PathSep::Posix)
                )
                .expect("Resolution name too long");
                total - cursor.len()
            };
            let label = &buf[..written];
            if label == v {
                pairs.push((dep_id as DependencyID, pkg_id));
            }
        } else {
            pairs.push((dep_id as DependencyID, pkg_id));
        }
    }

    if pairs.is_empty() {
        Output::pretty_errorln(format_args!(
            "\n<r><red>error<r>: package <b>{}<r> not found<r>",
            bstr::BStr::new(pkg_maybe_version_to_patch)
        ));
        Global::crash();
    }

    // user supplied a version e.g. `is-even@1.0.0`
    if version.is_some() {
        if pairs.len() == 1 {
            let (dep_id, pkg_id) = pairs[0];
            let folder = match node_modules_folder_for_dependency_id(iterator, dep_id) {
                Some(f) => f,
                None => {
                    Output::pretty_error(format_args!(
                        "<r><red>error<r>: could not find the folder for <b>{}<r> in node_modules<r>\n<r>",
                        bstr::BStr::new(pkg_maybe_version_to_patch),
                    ));
                    Global::crash();
                }
            };
            return (pkg_id, folder);
        }

        // we found multiple dependents of the supplied pkg + version
        // the final package in the node_modules might be hoisted
        // so we are going to try looking for each dep id in node_modules
        let (_, pkg_id) = pairs[0];
        let folder = match node_modules_folder_for_dependency_ids(iterator, &pairs) {
            Some(f) => f,
            None => {
                Output::pretty_error(format_args!(
                    "<r><red>error<r>: could not find the folder for <b>{}<r> in node_modules<r>\n<r>",
                    bstr::BStr::new(pkg_maybe_version_to_patch),
                ));
                Global::crash();
            }
        };

        return (pkg_id, folder);
    }

    // Otherwise the user did not supply a version, just the pkg name

    // Only one match, let's use it
    if pairs.len() == 1 {
        let (dep_id, pkg_id) = pairs[0];
        let folder = match node_modules_folder_for_dependency_id(iterator, dep_id) {
            Some(f) => f,
            None => {
                Output::pretty_error(format_args!(
                    "<r><red>error<r>: could not find the folder for <b>{}<r> in node_modules<r>\n<r>",
                    bstr::BStr::new(pkg_maybe_version_to_patch),
                ));
                Global::crash();
            }
        };
        return (pkg_id, folder);
    }

    // Otherwise we have multiple matches
    //
    // There are two cases:
    // a) the multiple matches are all the same underlying package (this happens because there could be multiple dependents of the same package)
    // b) the matches are actually different packages, we'll prompt the user to select which one

    let (_, pkg_id) = pairs[0];
    let count: u32 = {
        let mut count: u32 = 0;
        for pair in &pairs {
            if pair.1 == pkg_id {
                count += 1;
            }
        }
        count
    };

    // Disambiguate case a) from b)
    if count as usize == pairs.len() {
        // It may be hoisted, so we'll try the first one that matches
        let folder = match node_modules_folder_for_dependency_ids(iterator, &pairs) {
            Some(f) => f,
            None => {
                Output::pretty_error(format_args!(
                    "<r><red>error<r>: could not find the folder for <b>{}<r> in node_modules<r>\n<r>",
                    bstr::BStr::new(pkg_maybe_version_to_patch),
                ));
                Global::crash();
            }
        };
        return (pkg_id, folder);
    }

    Output::pretty_errorln(format_args!(
        "\n<r><red>error<r>: Found multiple versions of <b>{}<r>, please specify a precise version from the following list:<r>",
        bstr::BStr::new(name),
    ));
    let mut i: usize = 0;
    while i < pairs.len() {
        let (_, pkgid) = pairs[i];
        if pkgid == invalid_package_id {
            i += 1;
            continue;
        }

        let pkg = *lockfile.packages.get(pkgid as usize);

        Output::pretty_error(format_args!(
            "  {}@<blue>{}<r>\n",
            bstr::BStr::new(pkg.name.slice(strbuf)),
            pkg.resolution.fmt(strbuf, PathSep::Posix)
        ));

        if i + 1 < pairs.len() {
            for p in &mut pairs[i + 1..] {
                if p.1 == pkgid {
                    p.1 = invalid_package_id;
                }
            }
        }
        i += 1;
    }
    Global::crash();
}

// PORT NOTE: takes `workspace_package_id` directly instead of `&mut PackageManager` —
// both callers already compute it via `root_package_id.get()` immediately before, and
// passing `manager` here would alias `&manager.lockfile` in `prepare_patch`.
fn path_argument_relative_to_root_workspace_package(
    lockfile: &Lockfile,
    workspace_package_id: PackageID,
    argument: &[u8],
) -> Option<Box<[u8]>> {
    if workspace_package_id == 0 {
        return None;
    }
    let workspace_res = &lockfile.packages.items_resolution()[workspace_package_id as usize];
    let workspace_str = *workspace_res.workspace();
    let rel_path: &[u8] = workspace_str.slice(lockfile.buffers.string_bytes.as_slice());
    Some(Box::<[u8]>::from(resolve_path::join::<platform::Posix>(&[
        rel_path, argument,
    ])))
}

#[derive(Copy, Clone, PartialEq, Eq)]
enum PatchArgKind {
    Path,
    NameAndVersion,
}

impl PatchArgKind {
    pub(crate) fn from_arg(argument: &[u8]) -> PatchArgKind {
        if strings::contains(argument, b"node_modules/") {
            return PatchArgKind::Path;
        }
        // PORT NOTE: spec asymmetry — Zig (patchPackage.zig:1028) uses `hasPrefix`
        // for the Windows-backslash arm but `contains` for the posix arm above.
        // Match the spec exactly; if this is a Zig bug, fix both sides separately.
        if cfg!(windows) && strings::has_prefix(argument, b"node_modules\\") {
            return PatchArgKind::Path;
        }
        PatchArgKind::NameAndVersion
    }
}

// ported from: src/install/PackageManager/patchPackage.zig