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
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
//! Patch file parser and applier.
//!
//! Port of `src/patch/patch.zig`.

use core::mem;

use bun_collections::bit_set::ArrayBitSet;
use bun_core::{PathString, strings};
use bun_core::{ZBox, ZStr};
use bun_paths::{self as paths, PathBuffer};
use bun_sys::{self as sys, Fd, FdExt};

bun_core::declare_scope!(Patch, visible);

/// 256-bit set keyed by byte value. `IntegerBitSet<256>` overflows the single-
/// `usize` mask; `ArrayBitSet<256, 4>` is the >64-bit form per bit_set.rs note.
type ByteBitSet = ArrayBitSet<256, 4>;

const WHITESPACE: &[u8] = b" \t\n\r";

// TODO: calculate this for different systems
const PAGE_SIZE: usize = 16384;

// ──────────────────────────────────────────────────────────────────────────
// PatchFilePart / PatchFile
// ──────────────────────────────────────────────────────────────────────────

/// All strings point to the original patch file text
// PORT NOTE: lifetime — every `&'a [u8]` in this module borrows from the
// original patch file text. The port generally avoids struct lifetimes, but
// this parser's whole output is borrowed; raw `*const [u8]` everywhere would
// be worse.
pub enum PatchFilePart<'a> {
    FilePatch(Box<FilePatch<'a>>),
    FileDeletion(Box<FileDeletion<'a>>),
    FileCreation(Box<FileCreation<'a>>),
    FileRename(Box<FileRename<'a>>),
    FileModeChange(Box<FileModeChange<'a>>),
}

// Zig `deinit` only freed owned fields → Drop is automatic.

#[derive(Default)]
pub struct PatchFile<'a> {
    pub parts: Vec<PatchFilePart<'a>>,
}

// Zig `deinit` only freed owned fields → Drop is automatic.

#[cfg_attr(unix, allow(dead_code))]
struct ApplyState {
    pathbuf: PathBuffer,
    // TODO(port): lifetime — `patch_dir_abs_path` is a self-referential slice
    // into `self.pathbuf`. Model as (len) and reconstruct on demand to avoid
    // a self-ref borrow.
    patch_dir_abs_path: Option<usize>,
}

impl ApplyState {
    fn new() -> Self {
        Self {
            pathbuf: PathBuffer::uninit(),
            patch_dir_abs_path: None,
        }
    }

    #[cfg_attr(unix, allow(dead_code))]
    fn patch_dir_abs_path(&mut self, fd: Fd) -> sys::Result<&ZStr> {
        if let Some(len) = self.patch_dir_abs_path {
            // pathbuf[len] == 0 was written below on a previous call.
            return sys::Result::Ok(ZStr::from_buf(&self.pathbuf.0, len));
        }
        match sys::get_fd_path(fd, &mut self.pathbuf) {
            sys::Result::Ok(p) => {
                // PORT NOTE: reshaped for borrowck — capture len, drop `p`,
                // then re-borrow `self.pathbuf` to write the sentinel.
                let len = p.len();
                // Zig `state.pathbuf[0..p.len :0]` asserts a NUL sentinel; on
                // Linux `readlink(2)` does not NUL-terminate, so write it
                // explicitly (the buffer is zero-initialized but be defensive).
                self.pathbuf.0[len] = 0;
                self.patch_dir_abs_path = Some(len);
                sys::Result::Ok(ZStr::from_buf(&self.pathbuf.0, len))
            }
            sys::Result::Err(e) => sys::Result::Err(e.with_fd(fd)),
        }
    }
}

impl<'a> PatchFile<'a> {
    pub fn apply(&self, patch_dir: Fd) -> Option<sys::Error> {
        let mut state = ApplyState::new();
        // PERF(port): was stack-fallback + arena bulk-free per iteration — profile if hot.

        for part in &self.parts {
            match part {
                PatchFilePart::FileDeletion(file_deletion) => {
                    if !is_safe_patch_path(file_deletion.path) {
                        return Some(sys::Error::from_code(sys::E::EINVAL, sys::Tag::unlink));
                    }
                    let pathz = ZBox::from_vec_with_nul(file_deletion.path.to_vec());

                    if let sys::Result::Err(e) = sys::unlinkat(patch_dir, &pathz) {
                        return Some(e.without_path());
                    }
                }
                PatchFilePart::FileRename(file_rename) => {
                    if !is_safe_patch_path(file_rename.from_path)
                        || !is_safe_patch_path(file_rename.to_path)
                    {
                        return Some(sys::Error::from_code(sys::E::EINVAL, sys::Tag::rename));
                    }
                    let from_path = ZBox::from_vec_with_nul(file_rename.from_path.to_vec());
                    let to_path = ZBox::from_vec_with_nul(file_rename.to_path.to_vec());

                    let todir = paths::dirname_simple(to_path.as_bytes());
                    if !todir.is_empty() {
                        if let sys::Result::Err(e) =
                            sys::mkdir_recursive_at_mode(patch_dir, todir, 0o755)
                        {
                            return Some(e.without_path());
                        }
                    }

                    if let sys::Result::Err(e) =
                        sys::renameat(patch_dir, &from_path, patch_dir, &to_path)
                    {
                        return Some(e.without_path());
                    }
                }
                PatchFilePart::FileCreation(file_creation) => {
                    if !is_safe_patch_path(file_creation.path) {
                        return Some(sys::Error::from_code(sys::E::EINVAL, sys::Tag::open));
                    }
                    let filepath_z = ZBox::from_vec_with_nul(file_creation.path.to_vec());
                    let filepath = PathString::init(filepath_z.as_bytes());
                    let filedir = paths::dirname_simple(filepath.slice());
                    let mode = file_creation.mode;

                    if !filedir.is_empty() {
                        // PORT NOTE: Zig calls `NodeFS.mkdirRecursive` with the bare relative
                        // `filedir` (resolved against process CWD), then immediately `openat`s
                        // the same path against `patch_dir`. That is internally inconsistent
                        // when `patch_dir != cwd`. We intentionally diverge and create the
                        // directory under `patch_dir` so the subsequent `openat` succeeds.
                        // Consider back-porting this fix to patch.zig.
                        if let sys::Result::Err(e) =
                            sys::mkdir_recursive_at_mode(patch_dir, filedir, mode.to_bun_mode())
                        {
                            return Some(e.without_path());
                        }
                    }

                    let newfile_fd = match sys::openat(
                        patch_dir,
                        &filepath_z,
                        sys::O::CREAT | sys::O::WRONLY | sys::O::TRUNC,
                        mode.to_bun_mode(),
                    ) {
                        sys::Result::Ok(fd) => fd,
                        sys::Result::Err(e) => return Some(e.without_path()),
                    };
                    let _close_newfile = scopeguard::guard(newfile_fd, |fd| fd.close());

                    let Some(hunk) = &file_creation.hunk else {
                        continue;
                    };

                    let last_line = hunk.parts[0].lines.len().saturating_sub(1);
                    let no_newline_at_end_of_file = hunk.parts[0].no_newline_at_end_of_file;

                    let count = {
                        let mut total: usize = 0;
                        for (i, line) in hunk.parts[0].lines.iter().enumerate() {
                            total += line.len();
                            total += (i < last_line) as usize;
                        }
                        total += (!no_newline_at_end_of_file) as usize;
                        total
                    };

                    // PERF(port): Zig used arena for small (<= PAGE_SIZE) allocations.
                    let _ = PAGE_SIZE;

                    // TODO: this additional allocation is probably not necessary in all cases and should be avoided or use stack buffer
                    let file_contents: Vec<u8> = {
                        let mut contents = vec![0u8; count];
                        let mut i: usize = 0;
                        for (idx, line) in hunk.parts[0].lines.iter().enumerate() {
                            contents[i..i + line.len()].copy_from_slice(line);
                            i += line.len();
                            if idx < last_line || !no_newline_at_end_of_file {
                                contents[i] = b'\n';
                                i += 1;
                            }
                        }
                        contents
                    };

                    let mut written: usize = 0;
                    while written < file_contents.len() {
                        match sys::write(newfile_fd, &file_contents[written..]) {
                            sys::Result::Ok(bytes) => written += bytes,
                            sys::Result::Err(e) => return Some(e.without_path()),
                        }
                    }
                }
                PatchFilePart::FilePatch(file_patch) => {
                    if !is_safe_patch_path(file_patch.path) {
                        return Some(sys::Error::from_code(sys::E::EINVAL, sys::Tag::open));
                    }
                    // TODO: should we compute the hash of the original file and check it against the on in the patch?
                    if let sys::Result::Err(e) = apply_patch(file_patch, patch_dir, &mut state) {
                        return Some(e.without_path());
                    }
                }
                PatchFilePart::FileModeChange(file_mode_change) => {
                    if !is_safe_patch_path(file_mode_change.path) {
                        return Some(sys::Error::from_code(sys::E::EINVAL, sys::Tag::fchmodat));
                    }
                    let newmode = file_mode_change.new_mode;
                    let filepath = ZBox::from_vec_with_nul(file_mode_change.path.to_vec());
                    #[cfg(unix)]
                    {
                        if let sys::Result::Err(e) =
                            sys::fchmodat(patch_dir, &filepath, newmode.to_bun_mode(), 0)
                        {
                            return Some(e.without_path());
                        }
                    }

                    #[cfg(windows)]
                    {
                        let absfilepath = match state.patch_dir_abs_path(patch_dir) {
                            sys::Result::Ok(p) => p,
                            sys::Result::Err(e) => return Some(e.without_path()),
                        };
                        let mut buf = PathBuffer::uninit();
                        let joined_absfilepath =
                            paths::resolve_path::join_z_buf::<paths::platform::Auto>(
                                &mut buf[..],
                                &[absfilepath.as_bytes(), filepath.as_bytes()],
                            );
                        let fd = match sys::open(&joined_absfilepath, sys::O::RDWR, 0) {
                            sys::Result::Err(e) => return Some(e.without_path()),
                            sys::Result::Ok(f) => f,
                        };
                        let _close = scopeguard::guard(fd, |fd| fd.close());
                        if let sys::Result::Err(e) = sys::fchmod(fd, newmode.to_bun_mode()) {
                            return Some(e.without_path());
                        }
                    }
                }
            }
        }

        None
    }
}

/// Invariants:
/// - Hunk parts are ordered by first to last in file
/// - The original starting line and the patched starting line are equal in the first hunk part
///
/// TODO: this is a very naive and slow implementation which works by creating a list of lines
/// we can speed it up by:
/// - If file size <= PAGE_SIZE, read the whole file into memory. memcpy/memmove the file contents around will be fast
/// - If file size > PAGE_SIZE, rather than making a list of lines, make a list of chunks
fn apply_patch(patch: &FilePatch<'_>, patch_dir: Fd, state: &mut ApplyState) -> sys::Result<()> {
    // PERF(port): was arena.arena().dupeZ — profile if hot.
    let file_path = ZBox::from_vec_with_nul(patch.path.to_vec());

    // Need to get the mode of the original file
    // And also get the size to read file into memory
    let stat = {
        #[cfg(unix)]
        let r = sys::fstatat(patch_dir, &file_path);
        #[cfg(not(unix))]
        let r = {
            let p = match state.patch_dir_abs_path(patch_dir) {
                sys::Result::Ok(p) => paths::resolve_path::join_z::<paths::platform::Auto>(&[
                    p.as_bytes(),
                    file_path.as_bytes(),
                ]),
                sys::Result::Err(e) => return sys::Result::Err(e),
            };
            sys::stat(p)
        };
        match r {
            sys::Result::Err(e) => return sys::Result::Err(e.with_path(file_path.as_bytes())),
            sys::Result::Ok(stat) => stat,
        }
    };
    #[cfg(unix)]
    let _ = state; // suppress unused on posix

    // Purposefully use `bun.default_allocator` here because if the file size is big like
    // 1gb we don't want to have 1gb hanging around in memory until arena is cleared
    //
    // But if the file size is small, like less than a single page, it's probably ok
    // to use the arena
    // PERF(port): was arena vs default_allocator selection — profile if hot.
    let _use_arena: bool = stat.st_size as usize <= PAGE_SIZE;
    // TODO(port): Zig used `patch_dir.stdDir().readFileAlloc(...)` (std.fs). Replace with bun_sys::File::read_from.
    let filebuf: Vec<u8> = match read_file_alloc(patch_dir, &file_path, 1024 * 1024 * 1024 * 4) {
        Ok(b) => b,
        Err(_) => {
            return sys::Result::Err(
                sys::Error::from_code(sys::E::EINVAL, sys::Tag::read)
                    .with_path(file_path.as_bytes()),
            );
        }
    };

    let file_line_count: usize;
    let lines_count: usize = {
        let mut count: usize = 0;
        for _ in filebuf.split(|b| *b == b'\n') {
            count += 1;
        }
        file_line_count = count;

        // Adjust to account for the changes
        for hunk in &patch.hunks {
            count = usize::try_from(
                i64::try_from(count).expect("int cast") + i64::from(hunk.header.patched.len)
                    - i64::from(hunk.header.original.len),
            )
            .unwrap();
            for part in &hunk.parts {
                let part: &PatchMutationPart = part;
                match part.ty {
                    PartType::Deletion => {
                        // deleting the no newline pragma so we are actually adding a line
                        count += if part.no_newline_at_end_of_file { 1 } else { 0 };
                    }
                    PartType::Insertion => {
                        count -= if part.no_newline_at_end_of_file { 1 } else { 0 };
                    }
                    PartType::Context => {}
                }
            }
        }

        count
    };

    // TODO: i hate this
    let mut lines: Vec<&[u8]> = Vec::with_capacity(lines_count);
    {
        let mut i: usize = 0;
        for line in filebuf.split(|b| *b == b'\n') {
            lines.push(line);
            i += 1;
        }
        debug_assert!(i == file_line_count);
    }

    for hunk in &patch.hunks {
        let mut line_cursor = (hunk.header.patched.start - 1) as usize;

        // Validate hunk start position is within bounds
        if line_cursor > lines.len() {
            return sys::Result::Err(
                sys::Error::from_code(sys::E::EINVAL, sys::Tag::fstatat)
                    .with_path(file_path.as_bytes()),
            );
        }

        for part in &hunk.parts {
            let part: &PatchMutationPart = part;
            match part.ty {
                PartType::Context => {
                    // TODO: check if the lines match in the original file?

                    // Validate context lines exist
                    if line_cursor + part.lines.len() > lines.len() {
                        return sys::Result::Err(
                            sys::Error::from_code(sys::E::EINVAL, sys::Tag::fstatat)
                                .with_path(file_path.as_bytes()),
                        );
                    }

                    line_cursor += part.lines.len();
                }
                PartType::Insertion => {
                    // Validate insertion position is within bounds
                    if line_cursor > lines.len() {
                        return sys::Result::Err(
                            sys::Error::from_code(sys::E::EINVAL, sys::Tag::fstatat)
                                .with_path(file_path.as_bytes()),
                        );
                    }

                    // Zig: addManyAt + @memcpy
                    lines.splice(line_cursor..line_cursor, part.lines.iter().copied());
                    line_cursor += part.lines.len();
                    if part.no_newline_at_end_of_file {
                        let _ = lines.pop();
                    }
                }
                PartType::Deletion => {
                    // TODO: check if the lines match in the original file?

                    // Validate deletion range is within bounds
                    if line_cursor + part.lines.len() > lines.len() {
                        return sys::Result::Err(
                            sys::Error::from_code(sys::E::EINVAL, sys::Tag::fstatat)
                                .with_path(file_path.as_bytes()),
                        );
                    }

                    lines.drain(line_cursor..line_cursor + part.lines.len());
                    if part.no_newline_at_end_of_file {
                        lines.push(b"");
                    }
                    // line_cursor -= part.lines.len();
                }
            }
        }
    }

    let file_fd = match sys::openat(
        patch_dir,
        &file_path,
        sys::O::CREAT | sys::O::WRONLY | sys::O::TRUNC,
        stat.st_mode as sys::Mode,
    ) {
        sys::Result::Err(e) => return sys::Result::Err(e.with_path(file_path.as_bytes())),
        sys::Result::Ok(fd) => fd,
    };
    let _close_file = scopeguard::guard(file_fd, |fd| fd.close());

    let contents = join_bytes(b"\n", &lines);

    let mut written: usize = 0;
    while written < contents.len() {
        match sys::write(file_fd, &contents[written..]) {
            sys::Result::Ok(w) => written += w,
            sys::Result::Err(e) => return sys::Result::Err(e.with_path(file_path.as_bytes())),
        }
    }

    sys::Result::Ok(())
}

fn read_file_alloc(dir: Fd, path: &ZStr, max: usize) -> sys::Result<Vec<u8>> {
    // PORT NOTE: Zig's `std.fs.Dir.readFileAlloc` opens, fstats, allocates
    // `min(size, max)` and errors `error.FileTooBig` past `max`. Enforce the
    // same cap so a pathological multi-GiB target file errors instead of
    // allocating unboundedly. (`error.FileTooBig` would surface as `.INVAL` at
    // the only call site anyway, so we map it to EINVAL here.)
    let stat = sys::fstatat(dir, path)?;
    if stat.st_size as u64 > max as u64 {
        return sys::Result::Err(
            sys::Error::from_code(sys::E::EINVAL, sys::Tag::read).with_path(path.as_bytes()),
        );
    }
    sys::File::read_from(dir, path)
}

/// Port of `std.mem.join` for byte slices.
fn join_bytes(sep: &[u8], slices: &[&[u8]]) -> Vec<u8> {
    if slices.is_empty() {
        return Vec::new();
    }
    let total: usize =
        slices.iter().map(|s| s.len()).sum::<usize>() + sep.len() * (slices.len() - 1);
    let mut out = Vec::with_capacity(total);
    for (i, s) in slices.iter().enumerate() {
        if i != 0 {
            out.extend_from_slice(sep);
        }
        out.extend_from_slice(s);
    }
    out
}

// ──────────────────────────────────────────────────────────────────────────
// FileDeets
// ──────────────────────────────────────────────────────────────────────────

#[derive(Default)]
struct FileDeets<'a> {
    diff_line_from_path: Option<&'a [u8]>,
    diff_line_to_path: Option<&'a [u8]>,
    old_mode: Option<&'a [u8]>,
    new_mode: Option<&'a [u8]>,
    deleted_file_mode: Option<&'a [u8]>,
    new_file_mode: Option<&'a [u8]>,
    rename_from: Option<&'a [u8]>,
    rename_to: Option<&'a [u8]>,
    before_hash: Option<&'a [u8]>,
    after_hash: Option<&'a [u8]>,
    from_path: Option<&'a [u8]>,
    to_path: Option<&'a [u8]>,
    hunks: Vec<Hunk<'a>>,
}

impl<'a> FileDeets<'a> {
    fn take_hunks(&mut self) -> Vec<Hunk<'a>> {
        mem::take(&mut self.hunks)
    }

    // Zig `deinit` only freed owned fields → Drop is automatic.

    fn nullify_empty_strings(&mut self) {
        // Zig used @typeInfo reflection over all `?[]const u8` fields. No Rust
        // equivalent — written out by hand.
        macro_rules! nullify {
            ($($f:ident),*) => {$(
                if matches!(self.$f, Some(v) if v.is_empty()) {
                    self.$f = None;
                }
            )*};
        }
        nullify!(
            diff_line_from_path,
            diff_line_to_path,
            old_mode,
            new_mode,
            deleted_file_mode,
            new_file_mode,
            rename_from,
            rename_to,
            before_hash,
            after_hash,
            from_path,
            to_path
        );
    }
}

// ──────────────────────────────────────────────────────────────────────────
// PatchMutationPart / Hunk
// ──────────────────────────────────────────────────────────────────────────

#[derive(Default)]
pub struct PatchMutationPart<'a> {
    pub ty: PartType,
    pub lines: Vec<&'a [u8]>,
    /// This technically can only be on the last part of a hunk
    pub no_newline_at_end_of_file: bool,
}

/// Ensure context, insertion, deletion values are in sync with HunkLineType enum
#[repr(u8)]
#[derive(Copy, Clone, PartialEq, Eq, Default, strum::IntoStaticStr)]
pub enum PartType {
    #[default]
    Context = 0,
    Insertion,
    Deletion,
}

// Zig `PatchMutationPart.deinit` only freed `lines` → Drop is automatic.

#[derive(Default)]
pub struct Hunk<'a> {
    pub header: Header,
    pub parts: Vec<PatchMutationPart<'a>>,
}

#[derive(Copy, Clone)]
pub struct HeaderRange {
    pub start: u32,
    pub len: u32,
}

impl Default for HeaderRange {
    fn default() -> Self {
        Self { start: 1, len: 0 }
    }
}

#[derive(Copy, Clone, Default)]
pub struct Header {
    pub original: HeaderRange,
    pub patched: HeaderRange,
}

impl Header {
    pub const EMPTY: Header = Header {
        original: HeaderRange { start: 1, len: 0 },
        patched: HeaderRange { start: 1, len: 0 },
    };
}

// Zig `Hunk.deinit` only freed owned fields → Drop is automatic.

impl<'a> Hunk<'a> {
    pub(crate) fn verify_integrity(&self) -> bool {
        let mut original_length: usize = 0;
        let mut patched_length: usize = 0;

        for part in &self.parts {
            match part.ty {
                PartType::Context => {
                    patched_length += part.lines.len();
                    original_length += part.lines.len();
                }
                PartType::Insertion => patched_length += part.lines.len(),
                PartType::Deletion => original_length += part.lines.len(),
            }
        }

        if original_length != self.header.original.len as usize
            || patched_length != self.header.patched.len as usize
        {
            return false;
        }
        true
    }
}

// ──────────────────────────────────────────────────────────────────────────
// FileMode
// ──────────────────────────────────────────────────────────────────────────

#[repr(u32)]
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum FileMode {
    NonExecutable = 0o644,
    Executable = 0o755,
}

impl FileMode {
    pub(crate) fn to_bun_mode(self) -> sys::Mode {
        sys::Mode::try_from(self as u32).expect("int cast")
    }

    pub(crate) fn from_u32(mode: u32) -> Option<FileMode> {
        match mode {
            0o644 => Some(FileMode::NonExecutable),
            0o755 => Some(FileMode::Executable),
            _ => None,
        }
    }
}

// ──────────────────────────────────────────────────────────────────────────
// FileRename / FileModeChange / FilePatch / FileDeletion / FileCreation
// ──────────────────────────────────────────────────────────────────────────

pub struct FileRename<'a> {
    pub from_path: &'a [u8],
    pub to_path: &'a [u8],
}
// Does not allocate — no Drop needed.

pub struct FileModeChange<'a> {
    pub path: &'a [u8],
    pub old_mode: FileMode,
    pub new_mode: FileMode,
}
// Does not allocate — no Drop needed.

pub struct FilePatch<'a> {
    pub path: &'a [u8],
    pub hunks: Vec<Hunk<'a>>,
    pub before_hash: Option<&'a [u8]>,
    pub after_hash: Option<&'a [u8]>,
}
// Zig `deinit` freed hunks + bun.destroy(this) → Drop on Box<FilePatch> handles both.

pub struct FileDeletion<'a> {
    pub path: &'a [u8],
    pub mode: FileMode,
    pub hunk: Option<Box<Hunk<'a>>>,
    pub hash: Option<&'a [u8]>,
}
// Zig `deinit` freed hunk + bun.destroy(this) → Drop on Box<FileDeletion> handles both.

pub struct FileCreation<'a> {
    pub path: &'a [u8],
    pub mode: FileMode,
    pub hunk: Option<Box<Hunk<'a>>>,
    pub hash: Option<&'a [u8]>,
}
// Zig `deinit` freed hunk + bun.destroy(this) → Drop on Box<FileCreation> handles both.

#[derive(Copy, Clone, PartialEq, Eq)]
pub(crate) enum PatchFilePartKind {
    FilePatch,
    FileDeletion,
    FileCreation,
    FileRename,
    FileModeChange,
}

// ──────────────────────────────────────────────────────────────────────────
// json_fmt — JSON `Display` adapter for `PatchFile`
//
// Port of Zig's `std.json.fmt(patchfile, .{})` (used only by the testing
// bindings in `src/patch_jsc/testing.zig`). The output shape is dictated by
// Zig's default `std.json.stringify` rules, so it must match exactly for the
// snapshot tests in `test/js/bun/patch/patch.test.ts` to pass:
//   - struct           → `{"field":...}` in field-declaration order
//   - `ArrayListUnmanaged` (our `Vec<T>`) → `{"items":[...],"capacity":N}`
//   - `[]const u8`     → JSON string
//   - `enum`           → `"tag_name"`
//   - `union(enum)`    → `{"tag_name":payload}`
//   - `?T`             → `null` or value
//   - `*T`             → serialized as the pointee
// ──────────────────────────────────────────────────────────────────────────

/// Returns a `Display` adapter that serializes `patchfile` as JSON, matching
/// the output of Zig's `std.json.fmt(patchfile, .{})`.
pub fn json_fmt<'a, 'b>(patchfile: &'b PatchFile<'a>) -> impl core::fmt::Display + 'b {
    PatchFileJsonFmt(patchfile)
}

struct PatchFileJsonFmt<'a, 'b>(&'b PatchFile<'a>);

impl core::fmt::Display for PatchFileJsonFmt<'_, '_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        json::write_patch_file(f, self.0)
    }
}

mod json {
    use super::*;
    use core::fmt::{Result, Write};

    use bun_core::fmt::encode_json_string as write_str;

    fn write_opt_str(w: &mut impl Write, s: Option<&[u8]>) -> Result {
        match s {
            None => w.write_str("null"),
            Some(s) => write_str(w, s),
        }
    }

    /// Zig `std.ArrayListUnmanaged(T)` is a plain struct `{ items: []T, capacity: usize }`,
    /// which `std.json` serializes field-wise. Reproduce that wrapper around a `Vec<T>`.
    fn write_list<W: Write, T>(
        w: &mut W,
        v: &Vec<T>,
        mut elem: impl FnMut(&mut W, &T) -> Result,
    ) -> Result {
        w.write_str("{\"items\":[")?;
        for (i, e) in v.iter().enumerate() {
            if i != 0 {
                w.write_char(',')?;
            }
            elem(w, e)?;
        }
        write!(w, "],\"capacity\":{}}}", v.capacity())
    }

    fn file_mode_tag(m: FileMode) -> &'static str {
        match m {
            FileMode::NonExecutable => "non_executable",
            FileMode::Executable => "executable",
        }
    }

    fn part_type_tag(t: PartType) -> &'static str {
        match t {
            PartType::Context => "context",
            PartType::Insertion => "insertion",
            PartType::Deletion => "deletion",
        }
    }

    fn write_header(w: &mut impl Write, h: &Header) -> Result {
        write!(
            w,
            "{{\"original\":{{\"start\":{},\"len\":{}}},\"patched\":{{\"start\":{},\"len\":{}}}}}",
            h.original.start, h.original.len, h.patched.start, h.patched.len,
        )
    }

    fn write_mutation_part(w: &mut impl Write, p: &PatchMutationPart<'_>) -> Result {
        // Zig field name is `type`; Rust field is `ty`.
        write!(w, "{{\"type\":\"{}\",\"lines\":", part_type_tag(p.ty))?;
        write_list(w, &p.lines, |w, line| write_str(w, line))?;
        write!(
            w,
            ",\"no_newline_at_end_of_file\":{}}}",
            p.no_newline_at_end_of_file
        )
    }

    fn write_hunk(w: &mut impl Write, h: &Hunk<'_>) -> Result {
        w.write_str("{\"header\":")?;
        write_header(w, &h.header)?;
        w.write_str(",\"parts\":")?;
        write_list(w, &h.parts, |w, p| write_mutation_part(w, p))?;
        w.write_char('}')
    }

    fn write_opt_hunk(w: &mut impl Write, h: &Option<Box<Hunk<'_>>>) -> Result {
        match h {
            None => w.write_str("null"),
            Some(h) => write_hunk(w, h),
        }
    }

    fn write_file_patch(w: &mut impl Write, fp: &FilePatch<'_>) -> Result {
        w.write_str("{\"path\":")?;
        write_str(w, fp.path)?;
        w.write_str(",\"hunks\":")?;
        write_list(w, &fp.hunks, |w, h| write_hunk(w, h))?;
        w.write_str(",\"before_hash\":")?;
        write_opt_str(w, fp.before_hash)?;
        w.write_str(",\"after_hash\":")?;
        write_opt_str(w, fp.after_hash)?;
        w.write_char('}')
    }

    fn write_file_deletion(w: &mut impl Write, fd: &FileDeletion<'_>) -> Result {
        w.write_str("{\"path\":")?;
        write_str(w, fd.path)?;
        write!(w, ",\"mode\":\"{}\",\"hunk\":", file_mode_tag(fd.mode))?;
        write_opt_hunk(w, &fd.hunk)?;
        w.write_str(",\"hash\":")?;
        write_opt_str(w, fd.hash)?;
        w.write_char('}')
    }

    fn write_file_creation(w: &mut impl Write, fc: &FileCreation<'_>) -> Result {
        w.write_str("{\"path\":")?;
        write_str(w, fc.path)?;
        write!(w, ",\"mode\":\"{}\",\"hunk\":", file_mode_tag(fc.mode))?;
        write_opt_hunk(w, &fc.hunk)?;
        w.write_str(",\"hash\":")?;
        write_opt_str(w, fc.hash)?;
        w.write_char('}')
    }

    fn write_file_rename(w: &mut impl Write, fr: &FileRename<'_>) -> Result {
        w.write_str("{\"from_path\":")?;
        write_str(w, fr.from_path)?;
        w.write_str(",\"to_path\":")?;
        write_str(w, fr.to_path)?;
        w.write_char('}')
    }

    fn write_file_mode_change(w: &mut impl Write, fm: &FileModeChange<'_>) -> Result {
        w.write_str("{\"path\":")?;
        write_str(w, fm.path)?;
        write!(
            w,
            ",\"old_mode\":\"{}\",\"new_mode\":\"{}\"}}",
            file_mode_tag(fm.old_mode),
            file_mode_tag(fm.new_mode),
        )
    }

    fn write_part(w: &mut impl Write, part: &PatchFilePart<'_>) -> Result {
        match part {
            PatchFilePart::FilePatch(p) => {
                w.write_str("{\"file_patch\":")?;
                write_file_patch(w, p)?;
            }
            PatchFilePart::FileDeletion(p) => {
                w.write_str("{\"file_deletion\":")?;
                write_file_deletion(w, p)?;
            }
            PatchFilePart::FileCreation(p) => {
                w.write_str("{\"file_creation\":")?;
                write_file_creation(w, p)?;
            }
            PatchFilePart::FileRename(p) => {
                w.write_str("{\"file_rename\":")?;
                write_file_rename(w, p)?;
            }
            PatchFilePart::FileModeChange(p) => {
                w.write_str("{\"file_mode_change\":")?;
                write_file_mode_change(w, p)?;
            }
        }
        w.write_char('}')
    }

    pub(super) fn write_patch_file(w: &mut impl Write, pf: &PatchFile<'_>) -> Result {
        w.write_str("{\"parts\":")?;
        write_list(w, &pf.parts, |w, p| write_part(w, p))?;
        w.write_char('}')
    }
}

// ──────────────────────────────────────────────────────────────────────────
// ParseErr
// ──────────────────────────────────────────────────────────────────────────

#[derive(thiserror::Error, strum::IntoStaticStr, Debug, Copy, Clone, PartialEq, Eq)]
pub enum ParseErr {
    #[error("unrecognized_pragma")]
    unrecognized_pragma,
    #[error("no_newline_at_eof_pragma_encountered_without_context")]
    no_newline_at_eof_pragma_encountered_without_context,
    #[error("hunk_lines_encountered_before_hunk_header")]
    hunk_lines_encountered_before_hunk_header,
    #[error("hunk_header_integrity_check_failed")]
    hunk_header_integrity_check_failed,
    #[error("bad_diff_line")]
    bad_diff_line,
    #[error("bad_header_line")]
    bad_header_line,
    #[error("rename_from_and_to_not_give")]
    rename_from_and_to_not_give,
    #[error("no_path_given_for_file_deletion")]
    no_path_given_for_file_deletion,
    #[error("no_path_given_for_file_creation")]
    no_path_given_for_file_creation,
    #[error("bad_file_mode")]
    bad_file_mode,
}

impl From<ParseErr> for bun_core::Error {
    fn from(e: ParseErr) -> Self {
        bun_core::err!(from e)
    }
}

// ──────────────────────────────────────────────────────────────────────────
// parsePatchFile / patchFileSecondPass
// ──────────────────────────────────────────────────────────────────────────

/// NOTE: the returned `PatchFile` struct will contain pointers to original file text so make sure to not deallocate `file`
pub fn parse_patch_file(file: &[u8]) -> Result<PatchFile<'_>, ParseErr> {
    let mut lines_parser = PatchLinesParser::default();

    'brk: {
        match lines_parser.parse(file, ParseOpts::default()) {
            Ok(()) => break 'brk,
            Err(err) => {
                // TODO: the parser can be refactored to remove this as it is a hacky workaround, like detecting while parsing if legacy diffs are used
                if err == ParseErr::hunk_header_integrity_check_failed {
                    lines_parser.reset();
                    lines_parser.parse(
                        file,
                        ParseOpts {
                            support_legacy_diffs: true,
                        },
                    )?;
                    break 'brk;
                }
                return Err(err);
            }
        }
    }

    // PORT NOTE: reshaped for borrowck — take ownership of result vec instead of slicing.
    let mut files = mem::take(&mut lines_parser.result);
    patch_file_second_pass(&mut files)
}

fn patch_file_second_pass<'a>(files: &mut [FileDeets<'a>]) -> Result<PatchFile<'a>, ParseErr> {
    let mut result = PatchFile::default();

    for file in files.iter_mut() {
        let ty: PatchFilePartKind = if file.rename_from.is_some_and(|s| !s.is_empty()) {
            PatchFilePartKind::FileRename
        } else if file.deleted_file_mode.is_some_and(|s| !s.is_empty()) {
            PatchFilePartKind::FileDeletion
        } else if file.new_file_mode.is_some_and(|s| !s.is_empty()) {
            PatchFilePartKind::FileCreation
        } else if !file.hunks.is_empty() {
            PatchFilePartKind::FilePatch
        } else {
            PatchFilePartKind::FileModeChange
        };

        let mut destination_file_path: Option<&'a [u8]> = None;

        match ty {
            PatchFilePartKind::FileRename => {
                if file.rename_from.is_none() || file.rename_to.is_none() {
                    return Err(ParseErr::rename_from_and_to_not_give);
                }

                result
                    .parts
                    .push(PatchFilePart::FileRename(Box::new(FileRename {
                        from_path: file.rename_from.unwrap(),
                        to_path: file.rename_to.unwrap(),
                    })));

                destination_file_path = file.rename_to;
            }
            PatchFilePartKind::FileDeletion => {
                let path = file
                    .diff_line_from_path
                    .or(file.from_path)
                    .ok_or(ParseErr::no_path_given_for_file_deletion)?;
                result
                    .parts
                    .push(PatchFilePart::FileDeletion(Box::new(FileDeletion {
                        hunk: if !file.hunks.is_empty() {
                            let value = mem::replace(
                                &mut file.hunks[0],
                                Hunk {
                                    header: Header::EMPTY,
                                    ..Default::default()
                                },
                            );
                            Some(Box::new(value))
                        } else {
                            None
                        },
                        path,
                        mode: parse_file_mode(file.deleted_file_mode.unwrap())
                            .ok_or(ParseErr::bad_file_mode)?,
                        hash: file.before_hash,
                    })));
            }
            PatchFilePartKind::FileCreation => {
                let path = file
                    .diff_line_to_path
                    .or(file.to_path)
                    .ok_or(ParseErr::no_path_given_for_file_creation)?;
                result
                    .parts
                    .push(PatchFilePart::FileCreation(Box::new(FileCreation {
                        hunk: if !file.hunks.is_empty() {
                            let value = mem::replace(
                                &mut file.hunks[0],
                                Hunk {
                                    header: Header::EMPTY,
                                    ..Default::default()
                                },
                            );
                            Some(Box::new(value))
                        } else {
                            None
                        },
                        path,
                        mode: parse_file_mode(file.new_file_mode.unwrap())
                            .ok_or(ParseErr::bad_file_mode)?,
                        hash: file.after_hash,
                    })));
            }
            PatchFilePartKind::FilePatch | PatchFilePartKind::FileModeChange => {
                destination_file_path = file.to_path.or(file.diff_line_to_path);
            }
        }

        if let (Some(path), Some(old_mode), Some(new_mode)) =
            (destination_file_path, file.old_mode, file.new_mode)
            && old_mode != new_mode
        {
            result
                .parts
                .push(PatchFilePart::FileModeChange(Box::new(FileModeChange {
                    path,
                    old_mode: parse_file_mode(old_mode).ok_or(ParseErr::bad_file_mode)?,
                    new_mode: parse_file_mode(new_mode).ok_or(ParseErr::bad_file_mode)?,
                })));
        }

        if let Some(path) = destination_file_path
            && !file.hunks.is_empty()
        {
            result
                .parts
                .push(PatchFilePart::FilePatch(Box::new(FilePatch {
                    path,
                    hunks: file.take_hunks(),
                    before_hash: file.before_hash,
                    after_hash: file.after_hash,
                })));
        }
    }

    Ok(result)
}

fn parse_file_mode(mode: &[u8]) -> Option<FileMode> {
    let parsed_mode = bun_core::parse_int::<u32>(mode, 8).ok()? & 0o777;
    FileMode::from_u32(parsed_mode)
}

fn is_safe_patch_path(path: &[u8]) -> bool {
    !path.is_empty()
        && !paths::is_absolute_loose(path)
        && !path
            .split(|&c| c == b'/' || c == b'\\')
            .any(|part| part == b"..")
}

// ──────────────────────────────────────────────────────────────────────────
// ScalarSplitIter / LookbackIterator
// ──────────────────────────────────────────────────────────────────────────

/// Port of `std.mem.SplitIterator(u8, .scalar)` exposing `.index` so callers
/// can rewind / inspect cursor (Rust's `slice::Split` does not expose this).
struct ScalarSplitIter<'a> {
    buffer: &'a [u8],
    /// `None` once iteration is exhausted.
    index: Option<usize>,
    delimiter: u8,
}

impl<'a> ScalarSplitIter<'a> {
    fn new(buffer: &'a [u8], delimiter: u8) -> Self {
        Self {
            buffer,
            index: Some(0),
            delimiter,
        }
    }

    fn next(&mut self) -> Option<&'a [u8]> {
        let start = self.index?;
        let end = match strings::index_of_char(&self.buffer[start..], self.delimiter) {
            Some(pos) => {
                let pos = pos as usize;
                self.index = Some(start + pos + 1);
                start + pos
            }
            None => {
                self.index = None;
                self.buffer.len()
            }
        };
        Some(&self.buffer[start..end])
    }
}

struct LookbackIterator<'a> {
    inner: ScalarSplitIter<'a>,
    prev_index: usize,
}

impl<'a> LookbackIterator<'a> {
    pub(crate) fn from_inner(inner: ScalarSplitIter<'a>) -> Self {
        Self {
            inner,
            prev_index: 0,
        }
    }

    pub(crate) fn next(&mut self) -> Option<&'a [u8]> {
        self.prev_index = self.inner.index.unwrap_or(self.prev_index);
        self.inner.next()
    }

    pub(crate) fn back(&mut self) {
        self.inner.index = Some(self.prev_index);
    }
}

// ──────────────────────────────────────────────────────────────────────────
// PatchLinesParser
// ──────────────────────────────────────────────────────────────────────────

#[derive(Default)]
struct PatchLinesParser<'a> {
    result: Vec<FileDeets<'a>>,
    current_file_patch: FileDeets<'a>,
    state: ParserState,
    current_hunk: Option<Hunk<'a>>,
    current_hunk_mutation_part: Option<PatchMutationPart<'a>>,
}

#[derive(Copy, Clone, PartialEq, Eq, Default)]
enum ParserState {
    #[default]
    ParsingHeader,
    ParsingHunks,
}

#[repr(u8)]
#[derive(Copy, Clone, PartialEq, Eq)]
enum HunkLineType {
    /// Additional context
    Context = 0,
    /// Example:
    /// + sjfskdjfsdf
    Insertion,
    /// Example:
    /// - sjfskdjfsdf
    Deletion,
    /// Example:
    /// @@ -1,3 +1,3 @@
    Header,
    /// Example:
    /// \ No newline at end of file
    Pragma,
}

#[derive(Default, Clone, Copy)]
struct ParseOpts {
    support_legacy_diffs: bool,
}

impl<'a> PatchLinesParser<'a> {
    // Zig `deinit` had a `comptime clear_result_retaining_capacity: bool` param.
    // In Rust, Drop handles freeing; `reset()` handles the retain-capacity case.

    fn reset(&mut self) {
        // PORT NOTE: reshaped for borrowck — take result vec, clear it, reinit self.
        let mut result = mem::take(&mut self.result);
        result.clear();
        *self = Self {
            result,
            ..Default::default()
        };
    }

    pub(crate) fn parse(&mut self, file_: &'a [u8], opts: ParseOpts) -> Result<(), ParseErr> {
        if file_.is_empty() {
            return Ok(());
        }
        let end = 'brk: {
            // std.mem.splitBackwardsScalar — peek at last segment after final '\n'
            let mut prev: usize = file_.len();
            let last_nl = file_.iter().rposition(|b| *b == b'\n');
            let last_line = match last_nl {
                Some(i) => &file_[i + 1..],
                None => file_,
            };
            if last_line.is_empty() {
                if let Some(i) = last_nl {
                    // Zig: iter.index.? — index points to the byte BEFORE the delimiter.
                    prev = i;
                }
            }
            break 'brk prev;
        };
        if end == 0 || end > file_.len() {
            return Ok(());
        }
        let file = &file_[..end];
        let mut lines = LookbackIterator::from_inner(ScalarSplitIter::new(file, b'\n'));

        while let Some(line) = lines.next() {
            match self.state {
                ParserState::ParsingHeader => {
                    if line.starts_with(b"@@") {
                        self.state = ParserState::ParsingHunks;
                        self.current_file_patch.hunks = Vec::new();
                        lines.back();
                    } else if line.starts_with(b"diff --git ") {
                        if self.current_file_patch.diff_line_from_path.is_some() {
                            self.commit_file_patch();
                        }
                        // Equivalent to:
                        // const match = line.match(/^diff --git a\/(.*?) b\/(.*?)\s*$/)
                        // currentFilePatch.diffLineFromPath = match[1]
                        // currentFilePatch.diffLineToPath = match[2]
                        let m = parse_diff_line_paths(line).ok_or(
                            // TODO: store line somewhere
                            ParseErr::bad_diff_line,
                        )?;
                        self.current_file_patch.diff_line_from_path = Some(m.0);
                        self.current_file_patch.diff_line_to_path = Some(m.1);
                    } else if line.starts_with(b"old mode ") {
                        self.current_file_patch.old_mode =
                            Some(strings::trim(&line[b"old mode ".len()..], WHITESPACE));
                    } else if line.starts_with(b"new mode ") {
                        self.current_file_patch.new_mode =
                            Some(strings::trim(&line[b"new mode ".len()..], WHITESPACE));
                    } else if line.starts_with(b"deleted file mode ") {
                        self.current_file_patch.deleted_file_mode = Some(strings::trim(
                            &line[b"deleted file mode ".len()..],
                            WHITESPACE,
                        ));
                    } else if line.starts_with(b"new file mode ") {
                        self.current_file_patch.new_file_mode =
                            Some(strings::trim(&line[b"new file mode ".len()..], WHITESPACE));
                    } else if line.starts_with(b"rename from ") {
                        self.current_file_patch.rename_from =
                            Some(strings::trim(&line[b"rename from ".len()..], WHITESPACE));
                    } else if line.starts_with(b"rename to ") {
                        self.current_file_patch.rename_to =
                            Some(strings::trim(&line[b"rename to ".len()..], WHITESPACE));
                    } else if line.starts_with(b"index ") {
                        let Some(hashes) = parse_diff_hashes(&line[b"index ".len()..]) else {
                            continue;
                        };
                        self.current_file_patch.before_hash = Some(hashes.0);
                        self.current_file_patch.after_hash = Some(hashes.1);
                    } else if line.starts_with(b"--- ") {
                        // The line may be shorter than "--- a/" (e.g. a bare "--- ");
                        // treat the missing path as empty like the JS implementation's
                        // `line.slice("--- a/".length)`.
                        self.current_file_patch.from_path = Some(strings::trim(
                            line.get(b"--- a/".len()..).unwrap_or_default(),
                            WHITESPACE,
                        ));
                    } else if line.starts_with(b"+++ ") {
                        self.current_file_patch.to_path = Some(strings::trim(
                            line.get(b"+++ b/".len()..).unwrap_or_default(),
                            WHITESPACE,
                        ));
                    }
                }
                ParserState::ParsingHunks => {
                    if opts.support_legacy_diffs && line.starts_with(b"--- a/") {
                        self.state = ParserState::ParsingHeader;
                        self.commit_file_patch();
                        lines.back();
                        continue;
                    }
                    // parsing hunks
                    let hunk_line_type: HunkLineType = if line.is_empty() {
                        // treat blank lines as context
                        HunkLineType::Context
                    } else {
                        let maybe = match line[0] {
                            b'@' => Some(HunkLineType::Header),
                            b'-' => Some(HunkLineType::Deletion),
                            b'+' => Some(HunkLineType::Insertion),
                            b' ' => Some(HunkLineType::Context),
                            b'\\' => Some(HunkLineType::Pragma),
                            b'\r' => Some(HunkLineType::Context),
                            _ => None,
                        };
                        match maybe {
                            Some(t) => t,
                            None => {
                                // unrecognized, bail out
                                self.state = ParserState::ParsingHeader;
                                self.commit_file_patch();
                                lines.back();
                                continue;
                            }
                        }
                    };

                    match hunk_line_type {
                        HunkLineType::Header => {
                            self.commit_hunk();
                            self.current_hunk = Some(parse_hunk_header_line(line)?);
                        }
                        HunkLineType::Pragma => {
                            if !line.starts_with(b"\\ No newline at end of file") {
                                // TODO: store line
                                return Err(ParseErr::unrecognized_pragma);
                            }
                            if self.current_hunk_mutation_part.is_none() {
                                return Err(
                                    ParseErr::no_newline_at_eof_pragma_encountered_without_context,
                                );
                            }
                            self.current_hunk_mutation_part
                                .as_mut()
                                .unwrap()
                                .no_newline_at_end_of_file = true;
                        }
                        HunkLineType::Insertion
                        | HunkLineType::Deletion
                        | HunkLineType::Context => {
                            if self.current_hunk.is_none() {
                                return Err(ParseErr::hunk_lines_encountered_before_hunk_header);
                            }
                            if self.current_hunk_mutation_part.is_some()
                                && (self.current_hunk_mutation_part.as_ref().unwrap().ty as u8)
                                    != (hunk_line_type as u8)
                            {
                                let part = self.current_hunk_mutation_part.take().unwrap();
                                self.current_hunk.as_mut().unwrap().parts.push(part);
                            }

                            if self.current_hunk_mutation_part.is_none() {
                                self.current_hunk_mutation_part = Some(PatchMutationPart {
                                    ty: match hunk_line_type {
                                        HunkLineType::Context => PartType::Context,
                                        HunkLineType::Insertion => PartType::Insertion,
                                        HunkLineType::Deletion => PartType::Deletion,
                                        _ => unreachable!(),
                                    },
                                    ..Default::default()
                                });
                            }

                            self.current_hunk_mutation_part
                                .as_mut()
                                .unwrap()
                                .lines
                                .push(&line[1.min(line.len())..]);
                        }
                    }
                }
            }
        }

        self.commit_file_patch();

        for file_deet in &self.result {
            for hunk in &file_deet.hunks {
                if !hunk.verify_integrity() {
                    return Err(ParseErr::hunk_header_integrity_check_failed);
                }
            }
        }

        Ok(())
    }

    fn commit_hunk(&mut self) {
        if let Some(mut hunk) = self.current_hunk.take() {
            if let Some(mutation_part) = self.current_hunk_mutation_part.take() {
                hunk.parts.push(mutation_part);
            }
            self.current_file_patch.hunks.push(hunk);
        }
    }

    fn commit_file_patch(&mut self) {
        self.commit_hunk();
        self.current_file_patch.nullify_empty_strings();
        let fp = mem::take(&mut self.current_file_patch);
        self.result.push(fp);
    }
}

struct HunkHeaderLineImpl<'a> {
    line_nr: u32,
    line_count: u32,
    rest: &'a [u8],
}

fn parse_hunk_header_line_impl(text_: &[u8]) -> Result<HunkHeaderLineImpl<'_>, ParseErr> {
    let mut text = text_;
    let digits: ByteBitSet = {
        let mut set = ByteBitSet::init_empty();
        let mut c = b'0';
        while c <= b'9' {
            set.set(c as usize);
            c += 1;
        }
        set
    };

    // @@ -100,32 +100,32 @@
    //     ^
    let line_nr_start: usize = 0;
    let mut line_nr_end: usize = 0;
    let mut saw_comma = false;
    let mut saw_whitespace = false;
    while line_nr_end < text.len() {
        if text[line_nr_end] == b',' {
            saw_comma = true;
            break;
        } else if text[line_nr_end] == b' ' {
            saw_whitespace = true;
            break;
        }
        if !digits.is_set(text[line_nr_end] as usize) {
            return Err(ParseErr::bad_header_line);
        }
        line_nr_end += 1;
    }
    if !saw_comma && !saw_whitespace {
        return Err(ParseErr::bad_header_line);
    }
    let line_nr = &text[line_nr_start..line_nr_end];
    let mut line_nr_count: &[u8] = b"1";
    if line_nr_end + 1 >= text.len() {
        return Err(ParseErr::bad_header_line);
    }

    text = &text[line_nr_end..];
    if text.is_empty() {
        return Err(ParseErr::bad_header_line);
    }

    // @@ -100,32 +100,32 @@
    //        ^
    //        but the comma can be optional
    if saw_comma {
        text = &text[1..];
        saw_whitespace = false;
        let first_col_start = 0;
        let mut first_col_end: usize = 0;
        while first_col_end < text.len() {
            if text[first_col_end] == b' ' {
                saw_whitespace = true;
                break;
            }
            if !digits.is_set(text[first_col_end] as usize) {
                return Err(ParseErr::bad_header_line);
            }
            first_col_end += 1;
        }
        if !saw_whitespace {
            return Err(ParseErr::bad_header_line);
        }
        line_nr_count = &text[first_col_start..first_col_end];
        text = &text[first_col_end..];
    }

    Ok(HunkHeaderLineImpl {
        line_nr: 1.max(bun_core::parse_decimal::<u32>(line_nr).ok_or(ParseErr::bad_header_line)?),
        line_count: bun_core::parse_decimal::<u32>(line_nr_count)
            .ok_or(ParseErr::bad_header_line)?,
        rest: text,
    })
}

fn parse_hunk_header_line<'a>(line_: &'a [u8]) -> Result<Hunk<'a>, ParseErr> {
    //  const match = headerLine.trim()
    //    .match(/^@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@.*/)

    let mut line = strings::trim(line_, WHITESPACE);
    // @@ -100,32 +100,32 @@
    // ^^^^
    // this part
    if !(line.len() >= 4
        && line[0] == b'@'
        && line[1] == b'@'
        && line[2] == b' '
        && line[3] == b'-')
    {
        // TODO: store line
        return Err(ParseErr::bad_header_line);
    }

    if line.len() <= 4 {
        return Err(ParseErr::bad_header_line);
    }

    // @@ -100,32 +100,32 @@
    //     ^
    line = &line[4..];

    let first_result = parse_hunk_header_line_impl(line)?;
    // @@ -100,32 +100,32 @@
    //           ^
    line = first_result.rest;
    if line.len() < 2 || line[1] != b'+' {
        return Err(ParseErr::bad_header_line);
    }
    line = &line[2..];

    let second_result = parse_hunk_header_line_impl(line)?;
    // @@ -100,32 +100,32 @@
    //                   ^
    line = second_result.rest;

    if line.len() >= 3 && line[0] == b' ' && line[1] == b'@' && line[2] == b'@' {
        return Ok(Hunk {
            header: Header {
                original: HeaderRange {
                    start: first_result.line_nr,
                    len: first_result.line_count,
                },
                patched: HeaderRange {
                    start: second_result.line_nr,
                    len: second_result.line_count,
                },
            },
            parts: Vec::new(),
        });
    }

    Err(ParseErr::bad_header_line)
}

fn parse_diff_hashes(line: &[u8]) -> Option<(&[u8], &[u8])> {
    // index 2de83dd..842652c 100644
    //       ^
    //       we expect that we are here
    debug_assert!(!line.starts_with(b"index "));

    // From @pnpm/patch-package the regex is this:
    // const match = line.match(/(\w+)\.\.(\w+)/)

    let delimiter_start = strings::index_of(line, b"..")? as usize;

    // PERF(port): was comptime IntegerBitSet — ArrayBitSet::set is non-const,
    // so this builds at runtime. Profile if it shows up on a hot path.
    let valid_chars: ByteBitSet = {
        let mut bitset = ByteBitSet::init_empty();
        // TODO: the regex uses \w which is [a-zA-Z0-9_]
        let mut c = b'0';
        while c <= b'9' {
            bitset.set(c as usize);
            c += 1;
        }
        c = b'a';
        while c <= b'z' {
            bitset.set(c as usize);
            c += 1;
        }
        c = b'A';
        while c <= b'Z' {
            bitset.set(c as usize);
            c += 1;
        }
        bitset.set(b'_' as usize);
        bitset
    };

    let a_part = &line[..delimiter_start];
    for &c in a_part {
        if !valid_chars.is_set(c as usize) {
            return None;
        }
    }

    let b_part_start = delimiter_start + 2;
    if b_part_start >= line.len() {
        return None;
    }
    let lmao_bro = &line[b_part_start..];
    core::hint::black_box(lmao_bro);
    let b_part_end = match strings::index_of_any(&line[b_part_start..], b" \n\r\t") {
        Some(pos) => pos + b_part_start,
        None => line.len(),
    };

    let b_part = &line[b_part_start..b_part_end];
    for &c in a_part {
        if !valid_chars.is_set(c as usize) {
            return None;
        }
    }
    for &c in b_part {
        if !valid_chars.is_set(c as usize) {
            return None;
        }
    }

    Some((a_part, b_part))
}

fn parse_diff_line_paths(line: &[u8]) -> Option<(&[u8], &[u8])> {
    // From @pnpm/patch-package the regex is this:
    // const match = line.match(/^diff --git a\/(.*?) b\/(.*?)\s*$/)

    const PREFIX: &[u8] = b"diff --git a/";
    if !line.starts_with(PREFIX) {
        return None;
    }
    // diff --git a/banana.ts b/banana.ts
    //              ^
    let rest = &line[PREFIX.len()..];
    if rest.is_empty() {
        return None;
    }

    let a_path_start_index: usize = 0;
    let a_path_end_index: usize;
    let b_path_start_index: usize;

    let mut i: usize = 0;
    loop {
        let start_of_b_part = strings::index_of_char(&rest[i..], b'b')? as usize;
        i += start_of_b_part;
        if i > 0 && rest[i - 1] == b' ' && i + 1 < rest.len() && rest[i + 1] == b'/' {
            // diff --git a/banana.ts b/banana.ts
            //                       ^  ^
            //                       |  |
            //    a_path_end_index   +  |
            //    b_path_start_index    +
            a_path_end_index = i - 1;
            b_path_start_index = i + 2;
            break;
        }
        i += 1;
    }

    let a_path = &rest[a_path_start_index..a_path_end_index];
    let b_path = bun_core::strings::trim_right(&rest[b_path_start_index..], b" \n\r\t");
    Some((a_path, b_path))
}

// `pub const TestingAPIs = @import("../patch_jsc/testing.zig").TestingAPIs;`
// — *_jsc alias line; deleted per PORTING.md. Consumers use bun_patch_jsc::TestingAPIs.

// ──────────────────────────────────────────────────────────────────────────
// spawnOpts / diffPostProcess / gitDiff*
// ──────────────────────────────────────────────────────────────────────────

// PORT NOTE: Zig returns `bun.spawn.sync.Options` with `argv`/`envp` allocated on
// `bun.default_allocator` and freed by the caller. `bun_spawn::sync::Options` owns
// `argv` (`Vec<Box<[u8]>>`) but borrows `envp` (`Option<*const *const c_char>`), so
// the null-terminated envp array is returned alongside as the second tuple element —
// caller must keep it alive while `Options` is in use (no `Box::leak`, §Forbidden).
pub fn spawn_opts(
    old_folder: &[u8],
    new_folder: &[u8],
    cwd: &ZStr,
    git: &ZStr,
    loop_: &mut bun_event_loop::AnyEventLoop<'static>,
) -> (bun_spawn::sync::Options, Vec<*const core::ffi::c_char>) {
    let argv: Vec<Box<[u8]>> = {
        const ARGV: &[&[u8]] = &[
            b"git",
            b"-c",
            b"core.safecrlf=false",
            b"diff",
            b"--src-prefix=a/",
            b"--dst-prefix=b/",
            b"--ignore-cr-at-eol",
            b"--irreversible-delete",
            b"--full-index",
            b"--no-index",
        ];
        // PERF(port): Zig stored borrowed slices; `Options.argv` is
        // `Vec<Box<[u8]>>`, so we copy. Profile if it shows up on a hot path.
        let mut argv_buf: Vec<Box<[u8]>> = Vec::with_capacity(ARGV.len() + 2);
        argv_buf.push(Box::from(git.as_bytes()));
        for i in 1..ARGV.len() {
            argv_buf.push(Box::from(ARGV[i]));
        }
        argv_buf.push(Box::from(old_folder));
        argv_buf.push(Box::from(new_folder));
        argv_buf
    };

    // envp is `[:null]?[*:0]const u8` — null-terminated array of C strings. All
    // entries point at `'static` storage (string literals / process env block);
    // only the array itself is heap-backed and returned to the caller.
    let envp_buf: Vec<*const core::ffi::c_char> = {
        const ENV_ARR: [&[u8]; 4] = [
            b"GIT_CONFIG_NOSYSTEM\0",
            b"HOME\0",
            b"XDG_CONFIG_HOME\0",
            b"USERPROFILE\0",
        ];
        let path = bun_core::env_var::PATH.get();
        let mut envp_buf: Vec<*const core::ffi::c_char> =
            Vec::with_capacity(ENV_ARR.len() + usize::from(path.is_some()) + 1);
        for s in &ENV_ARR {
            envp_buf.push(s.as_ptr().cast::<core::ffi::c_char>());
        }
        if let Some(p) = path {
            // PORT NOTE: `env_var::PATH.get()` yields a slice into the C env
            // block (NUL byte immediately follows on POSIX — see
            // `bun_core::getenv_z`), matching Zig's `@ptrCast(p.ptr)`.
            envp_buf.push(p.as_ptr().cast::<core::ffi::c_char>());
        }
        envp_buf.push(core::ptr::null()); // sentinel
        envp_buf
    };

    #[cfg(not(windows))]
    let _ = loop_;

    let opts = bun_spawn::sync::Options {
        stdout: bun_spawn::sync::Stdio::Buffer,
        stderr: bun_spawn::sync::Stdio::Buffer,
        cwd: cwd.as_bytes().into(),
        envp: Some(envp_buf.as_ptr()),
        argv,
        #[cfg(windows)]
        windows: bun_spawn::sync::WindowsOptions {
            // Zig matched on `loop.*` to build the handle by hand; `as_handle`
            // owns that conversion now so variant internals stay encapsulated.
            loop_: bun_event_loop::AnyEventLoop::as_handle(loop_),
            ..Default::default()
        },
        ..Default::default()
    };

    (opts, envp_buf)
}

pub fn diff_post_process(
    result: &mut bun_spawn::sync::Result,
    old_folder: &[u8],
    new_folder: &[u8],
) -> Result<core::result::Result<Vec<u8>, Vec<u8>>, bun_core::Error> {
    let mut stdout: Vec<u8> = Vec::new();
    let mut stderr: Vec<u8> = Vec::new();

    mem::swap(&mut stdout, &mut result.stdout);
    mem::swap(&mut stderr, &mut result.stderr);

    // PORT NOTE: errdefer-style flags replaced by Drop semantics; on early return
    // the unreturned vec is dropped automatically.

    if !stderr.is_empty() {
        return Ok(Err(stderr));
    }

    bun_core::scoped_log!(Patch, "Before postprocess: {}\n", bstr::BStr::new(&stdout));
    git_diff_postprocess(&mut stdout, old_folder, new_folder)?;
    Ok(Ok(stdout))
}

// PORT NOTE: Zig signature returns `[2]if (sentinel) [:0]const u8 else []const u8` —
// return type depends on a comptime bool. Rust cannot express this without GAT-ish
// traits, so we return owned `Vec<u8>` pairs (NUL-appended when SENTINEL).
pub fn git_diff_preprocess_paths<const SENTINEL: bool>(
    old_folder_: &[u8],
    new_folder_: &[u8],
) -> [Vec<u8>; 2] {
    let bump: usize = if SENTINEL { 1 } else { 0 };

    #[cfg(windows)]
    let old_folder: Vec<u8> = {
        // backslash in the path fucks everything up
        let mut cpy = vec![0u8; old_folder_.len() + bump];
        cpy[..old_folder_.len()].copy_from_slice(old_folder_);
        paths::slashes_to_posix_in_place(&mut cpy[..]);
        if SENTINEL {
            cpy[old_folder_.len()] = 0;
            // Zig: `break :brk cpy[0..len :0]` — sentinel slice's `.len` excludes
            // the NUL. Truncate so `Vec::len()` matches; the NUL byte stays in
            // spare capacity for callers that need a C string via `.as_ptr()`.
            cpy.truncate(old_folder_.len());
        }
        cpy
    };
    #[cfg(not(windows))]
    let old_folder: Vec<u8> = old_folder_.to_vec();

    #[cfg(windows)]
    let new_folder: Vec<u8> = {
        let mut cpy = vec![0u8; new_folder_.len() + bump];
        cpy[..new_folder_.len()].copy_from_slice(new_folder_);
        paths::slashes_to_posix_in_place(&mut cpy[..]);
        if SENTINEL {
            cpy[new_folder_.len()] = 0;
            // Zig: `break :brk cpy[0..len :0]` — `.len` excludes the sentinel.
            cpy.truncate(new_folder_.len());
        }
        cpy
    };
    #[cfg(not(windows))]
    let new_folder: Vec<u8> = new_folder_.to_vec();

    #[cfg(unix)]
    if SENTINEL {
        // Zig: allocator.dupeZ — append NUL.
        let mut o = old_folder;
        o.push(0);
        let mut n = new_folder;
        n.push(0);
        return [o, n];
    }

    let _ = bump;
    [old_folder, new_folder]
}

pub fn git_diff_internal(
    old_folder_: &[u8],
    new_folder_: &[u8],
    loop_: &mut bun_event_loop::AnyEventLoop<'static>,
) -> Result<core::result::Result<Vec<u8>, Vec<u8>>, bun_core::Error> {
    let paths = git_diff_preprocess_paths::<false>(old_folder_, new_folder_);
    let old_folder = &paths[0][..];
    let new_folder = &paths[1][..];

    // Zig used `std.process.Child`, which searches `$PATH` for argv[0].
    // `bun_spawn::sync` execs argv[0] verbatim (execve, no PATH search), so
    // resolve `git` here — same as `patchCommit`'s `bun.which` call.
    let mut gitbuf = PathBuffer::uninit();
    let git = bun_which::which(
        &mut gitbuf,
        bun_core::env_var::PATH.get().unwrap_or(b""),
        b"",
        b"git",
    )
    .ok_or_else(|| bun_core::err!(FileNotFound))?;

    const ARGV: &[&[u8]] = &[
        b"-c",
        b"core.safecrlf=false",
        b"diff",
        b"--src-prefix=a/",
        b"--dst-prefix=b/",
        b"--ignore-cr-at-eol",
        b"--irreversible-delete",
        b"--full-index",
        b"--no-index",
    ];
    let mut argv: Vec<Box<[u8]>> = Vec::with_capacity(ARGV.len() + 3);
    argv.push(Box::from(git.as_bytes()));
    for s in ARGV {
        argv.push(Box::from(*s));
    }
    argv.push(Box::from(old_folder));
    argv.push(Box::from(new_folder));

    // env: { PATH (inherited if set), GIT_CONFIG_NOSYSTEM=1, HOME=, XDG_CONFIG_HOME=, USERPROFILE= }
    // Static entries point at 'static literals; PATH=<value>\0 needs an owned buffer.
    let path_var: Option<Vec<u8>> = bun_core::env_var::PATH.get().map(|p| {
        let mut s = Vec::with_capacity(b"PATH=".len() + p.len() + 1);
        s.extend_from_slice(b"PATH=");
        s.extend_from_slice(p);
        s.push(0);
        s
    });
    const ENV_STATIC: &[&[u8]] = &[
        b"GIT_CONFIG_NOSYSTEM=1\0",
        b"HOME=\0",
        b"XDG_CONFIG_HOME=\0",
        b"USERPROFILE=\0",
    ];
    let mut envp_buf: Vec<*const core::ffi::c_char> =
        Vec::with_capacity(ENV_STATIC.len() + usize::from(path_var.is_some()) + 1);
    if let Some(p) = &path_var {
        envp_buf.push(p.as_ptr().cast::<core::ffi::c_char>());
    }
    for s in ENV_STATIC {
        envp_buf.push(s.as_ptr().cast::<core::ffi::c_char>());
    }
    envp_buf.push(core::ptr::null()); // sentinel

    #[cfg(not(windows))]
    let _ = loop_;

    let opts = bun_spawn::sync::Options {
        stdout: bun_spawn::sync::Stdio::Buffer,
        stderr: bun_spawn::sync::Stdio::Buffer,
        envp: Some(envp_buf.as_ptr()),
        argv,
        // PORT NOTE: Zig used `std.process.Child` (no uv loop). The Rust port
        // routes through `bun_spawn::sync::spawn`, whose Windows path
        // unconditionally derefs `windows.loop_` (process.rs spawn_windows_*).
        // `WindowsOptions::default()` is `zeroed_unchecked()`, so leaving this
        // defaulted is a null deref on Windows — supply the caller's loop.
        #[cfg(windows)]
        windows: bun_spawn::sync::WindowsOptions {
            loop_: bun_event_loop::AnyEventLoop::as_handle(loop_),
            ..Default::default()
        },
        ..Default::default()
    };

    // unfortunately, git diff returns non-zero exit codes even when it succeeds.
    // we have to check that stderr was not empty to know if it failed
    let mut result = bun_spawn::sync::spawn(&opts)??;

    // Keep envp storage alive across the spawn call; Options.envp borrows it.
    drop(opts);
    drop(envp_buf);
    drop(path_var);

    let mut stdout = mem::take(&mut result.stdout);
    let stderr = mem::take(&mut result.stderr);

    if !stderr.is_empty() {
        return Ok(Err(stderr));
    }

    bun_core::scoped_log!(Patch, "Before postprocess: {}\n", bstr::BStr::new(&stdout));
    git_diff_postprocess(&mut stdout, old_folder, new_folder)?;
    Ok(Ok(stdout))
}

/// Now we need to do the equivalent of these regex subtitutions.
///
/// Assume that:
///   aFolder = old_folder = "the_old_folder"
///   bFolder = new_folder = "the_new_folder"
///
/// We use the --src-prefix=a/ and --dst-prefix=b/ options with git diff,
/// so the paths end up looking like so:
///
/// - a/the_old_folder/package.json
/// - b/the_old_folder/package.json
/// - a/the_older_folder/src/index.js
/// - b/the_older_folder/src/index.js
///
/// We need to strip out all references to "the_old_folder" and "the_new_folder":
/// - a/package.json
/// - b/package.json
/// - a/src/index.js
/// - b/src/index.js
///
/// The operations look roughy like the following sequence of substitutions and regexes:
///   .replace(new RegExp(`(a|b)(${escapeStringRegexp(`/${removeTrailingAndLeadingSlash(aFolder)}/`)})`, "g"), "$1/")
///   .replace(new RegExp(`(a|b)${escapeStringRegexp(`/${removeTrailingAndLeadingSlash(bFolder)}/`)}`, "g"), "$1/")
///   .replace(new RegExp(escapeStringRegexp(`${aFolder}/`), "g"), "")
///   .replace(new RegExp(escapeStringRegexp(`${bFolder}/`), "g"), "");
fn git_diff_postprocess(
    stdout: &mut Vec<u8>,
    old_folder: &[u8],
    new_folder: &[u8],
) -> Result<(), bun_core::Error> {
    // TODO(port): narrow error set
    let old_folder_trimmed = strings::trim(old_folder, b"/");
    let new_folder_trimmed = strings::trim(new_folder, b"/");

    let mut old_buf = PathBuffer::uninit();
    let mut new_buf = PathBuffer::uninit();

    let (a_old_folder_slash, b_new_folder_slash) = {
        let ob = &mut old_buf[..];
        ob[0] = b'a';
        ob[1] = b'/';
        ob[2..2 + old_folder_trimmed.len()].copy_from_slice(old_folder_trimmed);
        ob[2 + old_folder_trimmed.len()] = b'/';

        let nb = &mut new_buf[..];
        nb[0] = b'b';
        nb[1] = b'/';
        nb[2..2 + new_folder_trimmed.len()].copy_from_slice(new_folder_trimmed);
        nb[2 + new_folder_trimmed.len()] = b'/';

        (
            &old_buf[0..2 + old_folder_trimmed.len() + 1],
            &new_buf[0..2 + new_folder_trimmed.len() + 1],
        )
    };

    // const @"$old_folder/" = @"a/$old_folder/"[2..];
    // const @"$new_folder/" = @"b/$new_folder/"[2..];

    // these vars are here to disambguate `a/$OLD_FOLDER` when $OLD_FOLDER itself contains "a/"
    // basically if $OLD_FOLDER contains "a/" then the code will replace it
    // so we need to not run that code path
    let mut saw_a_folder: Option<usize> = None;
    let mut saw_b_folder: Option<usize> = None;
    let mut line_idx: u32 = 0;

    // PORT NOTE: reshaped for borrowck — Zig mutated `stdout` while iterating
    // `std.mem.splitScalar` over it (relying on the iterator's by-value buffer
    // pointer staying valid because replaceRange only shrinks). In Rust we
    // re-implement the cursor manually so we can mutate `stdout` between lines.
    let mut cursor: usize = 0;
    while cursor <= stdout.len() {
        // Compute current line [line_start, line_end) and the index AFTER its delimiter.
        let line_start = cursor;
        let (line_end, next_cursor, exhausted) =
            match strings::index_of_char(&stdout[cursor..], b'\n') {
                Some(pos) => {
                    let pos = pos as usize;
                    (cursor + pos, cursor + pos + 1, false)
                }
                None => (stdout.len(), stdout.len(), true),
            };
        // Mirror Zig SplitIterator: `index` after next() points one past delimiter,
        // so `index - 1 - line.len() == line_start`.
        let line_len = line_end - line_start;

        // Borrow line for read-only checks; drop before mutating stdout.
        let skip = {
            let line = &stdout[line_start..line_end];
            should_skip_line(line)
        };

        if !skip {
            // a/$old_folder/
            if let Some(idx) = strings::index_of(&stdout[line_start..line_end], a_old_folder_slash)
            {
                let old_folder_slash_start = idx + 2;
                stdout.drain(
                    line_start + old_folder_slash_start
                        ..line_start + old_folder_slash_start + old_folder_trimmed.len() + 1,
                );
                // Zig: line_iter.index.? -= 1 + line.len  → re-examine this same line.
                cursor = line_start;
                saw_a_folder = Some(line_idx as usize);
                continue;
            }
            // b/$new_folder/
            if let Some(idx) = strings::index_of(&stdout[line_start..line_end], b_new_folder_slash)
            {
                let new_folder_slash_start = idx + 2;
                stdout.drain(
                    line_start + new_folder_slash_start
                        ..line_start + new_folder_slash_start + new_folder_trimmed.len() + 1,
                );
                // Zig: line_iter.index.? -= new_folder_trimmed.len + 1 → next iteration
                // resumes at the (now-shifted) byte after this line's '\n'.
                cursor = next_cursor - (new_folder_trimmed.len() + 1);
                saw_b_folder = Some(line_idx as usize);
                continue;
            }
            if saw_a_folder.is_none() || saw_a_folder.unwrap() != line_idx as usize {
                if let Some(idx) = strings::index_of(&stdout[line_start..line_end], old_folder) {
                    let line = &stdout[line_start..line_end];
                    if idx + old_folder.len() < line_len && line[idx + old_folder.len()] == b'/' {
                        stdout.drain(line_start + idx..line_start + idx + old_folder.len() + 1);
                        cursor = line_start;
                        saw_a_folder = Some(line_idx as usize);
                        continue;
                    }
                }
            }
            if saw_b_folder.is_none() || saw_b_folder.unwrap() != line_idx as usize {
                if let Some(idx) = strings::index_of(&stdout[line_start..line_end], new_folder) {
                    let line = &stdout[line_start..line_end];
                    if idx + new_folder.len() < line_len && line[idx + new_folder.len()] == b'/' {
                        stdout.drain(line_start + idx..line_start + idx + new_folder.len() + 1);
                        cursor = line_start;
                        saw_b_folder = Some(line_idx as usize);
                        continue;
                    }
                }
            }
        }

        line_idx += 1;
        saw_a_folder = None;
        saw_b_folder = None;
        if exhausted {
            break;
        }
        cursor = next_cursor;
    }

    Ok(())
}

/// We need to remove occurrences of "a/" and "b/" and "$old_folder/" and
/// "$new_folder/" but we don't want to remove them from the actual patch
/// content (maybe someone had a/$old_folder/foo.txt in the changed files).
///
/// To do that we have to skip the lines in the patch file that correspond
/// to changes.
///
/// ```patch
///
/// diff --git a/numbers.txt b/banana.txt
/// old mode 100644
/// new mode 100755
/// similarity index 96%
/// rename from numbers.txt
/// rename to banana.txt
/// index fbf1785..92d2c5f
/// --- a/numbers.txt
/// +++ b/banana.txt
/// @@ -1,4 +1,4 @@
/// -one
/// +ne
///
///  two
/// ```
fn should_skip_line(line: &[u8]) -> bool {
    line.is_empty()
        || (matches!(line[0], b' ' | b'-' | b'+')
            // line like: "--- a/numbers.txt" or "+++ b/numbers.txt" we should not skip
            && !(line.len() >= 4 && (&line[0..4] == b"--- " || &line[0..4] == b"+++ ")))
}

// ported from: src/patch/patch.zig