summaryrefslogtreecommitdiff
path: root/src/buildtool/file_system/git_repo.cpp
blob: 800da4b867f8c64d91e6ec0e1afb3434e6c50d8a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
// Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "src/buildtool/file_system/git_repo.hpp"

#include <algorithm>
#include <cstddef>
#include <map>
#include <sstream>
#include <string_view>
#include <thread>
#include <unordered_set>

#include "src/buildtool/common/artifact_digest_factory.hpp"
#include "src/buildtool/crypto/hash_function.hpp"
#include "src/buildtool/file_system/file_system_manager.hpp"
#include "src/buildtool/logging/log_level.hpp"
#include "src/buildtool/logging/logger.hpp"
#include "src/utils/cpp/gsl.hpp"
#include "src/utils/cpp/hex_string.hpp"
#include "src/utils/cpp/path.hpp"

extern "C" {
#include <git2.h>
#include <git2/sys/odb_backend.h>
}

#ifndef BOOTSTRAP_BUILD_TOOL
namespace {

/// \brief libgit2 file modes corresponding to non-special entries.
std::unordered_set<git_filemode_t> const kNonSpecialGitFileModes{
    GIT_FILEMODE_BLOB,
    GIT_FILEMODE_BLOB_EXECUTABLE,
    GIT_FILEMODE_TREE};

[[nodiscard]] auto ToHexString(git_oid const& oid) noexcept
    -> std::optional<std::string> {
    std::string hex_id(GIT_OID_HEXSZ, '\0');
    if (git_oid_fmt(hex_id.data(), &oid) != 0) {
        return std::nullopt;
    }
    return hex_id;
}

[[nodiscard]] auto ToRawString(git_oid const& oid) noexcept
    -> std::optional<std::string> {
    if (auto hex_id = ToHexString(oid)) {
        return FromHexString(*hex_id);
    }
    return std::nullopt;
}

/// \brief Returns true if mode corresponds to a supported object type.
[[nodiscard]] auto GitFileModeIsNonSpecial(git_filemode_t const& mode) noexcept
    -> bool {
    return kNonSpecialGitFileModes.contains(mode);
}

[[nodiscard]] auto GitFileModeToObjectType(git_filemode_t const& mode) noexcept
    -> std::optional<ObjectType> {
    switch (mode) {
        case GIT_FILEMODE_BLOB:
            return ObjectType::File;
        case GIT_FILEMODE_BLOB_EXECUTABLE:
            return ObjectType::Executable;
        case GIT_FILEMODE_TREE:
            return ObjectType::Tree;
        case GIT_FILEMODE_LINK:
            return ObjectType::Symlink;  // condition not tested here
        default: {
            std::ostringstream str;
            str << std::oct << static_cast<int>(mode);
            Logger::Log(
                LogLevel::Error, "unsupported git filemode {}", str.str());
            return std::nullopt;
        }
    }
}

[[nodiscard]] constexpr auto ObjectTypeToGitFileMode(ObjectType type) noexcept
    -> git_filemode_t {
    switch (type) {
        case ObjectType::File:
            return GIT_FILEMODE_BLOB;
        case ObjectType::Executable:
            return GIT_FILEMODE_BLOB_EXECUTABLE;
        case ObjectType::Tree:
            return GIT_FILEMODE_TREE;
        case ObjectType::Symlink:
            return GIT_FILEMODE_LINK;
    }
    return GIT_FILEMODE_UNREADABLE;  // make gcc happy
}

[[nodiscard]] auto GitTypeToObjectType(git_object_t const& type) noexcept
    -> std::optional<ObjectType> {
    switch (type) {
        case GIT_OBJECT_BLOB:
            return ObjectType::File;
        case GIT_OBJECT_TREE:
            return ObjectType::Tree;
        default:
            Logger::Log(LogLevel::Error,
                        "unsupported git object type {}",
                        git_object_type2string(type));
            return std::nullopt;
    }
}

[[nodiscard]] auto ObjectTypeToPerm(ObjectType type) noexcept -> std::string {
    switch (type) {
        case ObjectType::File:
            return "100644";
        case ObjectType::Executable:
            return "100755";
        case ObjectType::Tree:
            return "40000";
        case ObjectType::Symlink:
            return "120000";
    }
    return "";  // make gcc happy
}

#ifndef NDEBUG
/// \brief Debug-level check that given tree entries are consistent. If needed,
/// also check that the entries are in the underlying object database of the
/// provided CAS instance.
[[nodiscard]] auto ValidateEntries(GitRepo::tree_entries_t const& entries,
                                   GitCASPtr const& cas = nullptr) -> bool {
    return std::all_of(entries.begin(), entries.end(), [cas](auto entry) {
        auto const& [id, nodes] = entry;
        // if CAS given, check that the entry is in the object database
        if (cas != nullptr and not cas->ReadHeader(id)) {
            return false;
        }
        // for a given raw id, either all entries are trees or none of them
        return std::all_of(
                   nodes.begin(),
                   nodes.end(),
                   [](auto entry) { return IsTreeObject(entry.type); }) or
               std::none_of(nodes.begin(), nodes.end(), [](auto entry) {
                   return IsTreeObject(entry.type);
               });
    });
}
#endif

[[nodiscard]] auto flat_tree_walker_ignore_special(const char* /*root*/,
                                                   const git_tree_entry* entry,
                                                   void* payload) noexcept
    -> int {
    auto* entries =
        reinterpret_cast<GitRepo::tree_entries_t*>(payload);  // NOLINT

    std::string name = git_tree_entry_name(entry);
    auto const* oid = git_tree_entry_id(entry);
    if (auto raw_id = ToRawString(*oid)) {
        if (not GitFileModeIsNonSpecial(git_tree_entry_filemode(entry))) {
            return 0;  // allow, but not store
        }
        if (auto type =
                GitFileModeToObjectType(git_tree_entry_filemode(entry))) {
            // no need to test for symlinks, as no symlink entry will reach this
            (*entries)[*raw_id].emplace_back(std::move(name), *type);
            return 1;  // return >=0 on success, 1 == skip subtrees (flat)
        }
    }
    Logger::Log(LogLevel::Error,
                "failed ignore_special walk for git tree entry: {}",
                name);
    return -1;  // fail
}

[[nodiscard]] auto flat_tree_walker(const char* /*root*/,
                                    const git_tree_entry* entry,
                                    void* payload) noexcept -> int {
    auto* entries =
        reinterpret_cast<GitRepo::tree_entries_t*>(payload);  // NOLINT

    std::string name = git_tree_entry_name(entry);
    auto const* oid = git_tree_entry_id(entry);
    if (auto raw_id = ToRawString(*oid)) {
        if (auto type =
                GitFileModeToObjectType(git_tree_entry_filemode(entry))) {
            // symlinks need to be checked in caller for non-upwardness
            (*entries)[*raw_id].emplace_back(std::move(name), *type);
            return 1;  // return >=0 on success, 1 == skip subtrees (flat)
        }
    }
    Logger::Log(LogLevel::Error, "failed walk for git tree entry: {}", name);
    return -1;  // fail
}

struct InMemoryODBBackend {
    git_odb_backend parent;
    GitRepo::tree_entries_t const* entries{nullptr};     // object headers
    std::unordered_map<std::string, std::string> trees;  // solid tree objects
};

[[nodiscard]] auto backend_read_header(size_t* len_p,
                                       git_object_t* type_p,
                                       git_odb_backend* _backend,
                                       const git_oid* oid) -> int {
    if (len_p != nullptr and type_p != nullptr and _backend != nullptr and
        oid != nullptr) {
        auto* b = reinterpret_cast<InMemoryODBBackend*>(_backend);  // NOLINT
        if (auto id = ToRawString(*oid)) {
            if (auto it = b->trees.find(*id); it != b->trees.end()) {
                *type_p = GIT_OBJECT_TREE;
                *len_p = it->second.size();
                return GIT_OK;
            }
            if (b->entries != nullptr) {
                if (auto it = b->entries->find(*id); it != b->entries->end()) {
                    if (not it->second.empty()) {
                        // pretend object is in database, size is ignored.
                        *type_p = IsTreeObject(it->second.front().type)
                                      ? GIT_OBJECT_TREE
                                      : GIT_OBJECT_BLOB;
                        *len_p = 0;
                        return GIT_OK;
                    }
                }
            }
            return GIT_ENOTFOUND;
        }
    }
    return GIT_ERROR;
}

[[nodiscard]] auto backend_read(void** data_p,
                                size_t* len_p,
                                git_object_t* type_p,
                                git_odb_backend* _backend,
                                const git_oid* oid) -> int {
    if (data_p != nullptr and len_p != nullptr and type_p != nullptr and
        _backend != nullptr and oid != nullptr) {
        auto* b = reinterpret_cast<InMemoryODBBackend*>(_backend);  // NOLINT
        if (auto id = ToRawString(*oid)) {
            if (auto it = b->trees.find(*id); it != b->trees.end()) {
                *type_p = GIT_OBJECT_TREE;
                *len_p = it->second.size();
                *data_p = git_odb_backend_data_alloc(_backend, *len_p);
                if (*data_p == nullptr) {
                    return GIT_ERROR;
                }
                std::memcpy(*data_p, it->second.data(), *len_p);
                return GIT_OK;
            }
            return GIT_ENOTFOUND;
        }
    }
    return GIT_ERROR;
}

[[nodiscard]] auto backend_exists(git_odb_backend* _backend,
                                  const git_oid* oid) -> int {
    if (_backend != nullptr and oid != nullptr) {
        auto* b = reinterpret_cast<InMemoryODBBackend*>(_backend);  // NOLINT
        if (auto id = ToRawString(*oid)) {
            return (b->entries != nullptr and b->entries->contains(*id)) or
                           b->trees.contains(*id)
                       ? 1
                       : 0;
        }
    }
    return GIT_ERROR;
}

[[nodiscard]] auto backend_write(git_odb_backend* _backend,
                                 const git_oid* oid,
                                 const void* data,
                                 std::size_t len,
                                 git_object_t type) -> int {
    if (data != nullptr and _backend != nullptr and oid != nullptr) {
        auto* b = reinterpret_cast<InMemoryODBBackend*>(_backend);  // NOLINT
        if (auto id = ToRawString(*oid)) {
            if (auto t = GitTypeToObjectType(type)) {
                std::string s(static_cast<char const*>(data), len);
                if (type == GIT_OBJECT_TREE) {
                    b->trees.emplace(std::move(*id), std::move(s));
                    return GIT_OK;
                }
            }
        }
    }
    return GIT_ERROR;
}

void backend_free(git_odb_backend* /*_backend*/) {}

[[nodiscard]] auto CreateInMemoryODBParent() -> git_odb_backend {
    git_odb_backend b{};
    b.version = GIT_ODB_BACKEND_VERSION;
    b.read_header = &backend_read_header;
    b.read = &backend_read;
    b.exists = &backend_exists;
    b.write = &backend_write;
    b.free = &backend_free;
    return b;
}

// A backend that can be used to read and create tree objects in-memory.
auto const kInMemoryODBParent = CreateInMemoryODBParent();

struct FetchIntoODBBackend {
    git_odb_backend parent;
    git_odb* target_odb;  // the odb where the fetch objects will end up into
};

[[nodiscard]] auto fetch_backend_writepack(git_odb_writepack** _writepack,
                                           git_odb_backend* _backend,
                                           [[maybe_unused]] git_odb* odb,
                                           git_indexer_progress_cb progress_cb,
                                           void* progress_payload) -> int {
    if (_backend != nullptr) {
        auto* b = reinterpret_cast<FetchIntoODBBackend*>(_backend);  // NOLINT
        return git_odb_write_pack(
            _writepack, b->target_odb, progress_cb, progress_payload);
    }
    return GIT_ERROR;
}

[[nodiscard]] auto fetch_backend_exists(git_odb_backend* _backend,
                                        const git_oid* oid) -> int {
    if (_backend != nullptr) {
        auto* b = reinterpret_cast<FetchIntoODBBackend*>(_backend);  // NOLINT
        return git_odb_exists(b->target_odb, oid);
    }
    return GIT_ERROR;
}

void fetch_backend_free(git_odb_backend* /*_backend*/) {}

[[nodiscard]] auto CreateFetchIntoODBParent() -> git_odb_backend {
    git_odb_backend b{};
    b.version = GIT_ODB_BACKEND_VERSION;
    // only populate the functions needed
    b.writepack = &fetch_backend_writepack;  // needed for fetch
    b.exists = &fetch_backend_exists;
    b.free = &fetch_backend_free;
    return b;
}

// A backend that can be used to fetch from the remote of another repository.
auto const kFetchIntoODBParent = CreateFetchIntoODBParent();

// callback to remote fetch without an SSL certificate check
const auto certificate_passthrough_cb = [](git_cert* /*cert*/,
                                           int /*valid*/,
                                           const char* /*host*/,
                                           void* /*payload*/) -> int {
    return 0;
};

}  // namespace
#endif  // BOOTSTRAP_BUILD_TOOL

GitRepo::GuardedRepo::GuardedRepo(std::shared_mutex* mutex) noexcept
    : mutex_{mutex} {}

auto GitRepo::GuardedRepo::Ptr() -> git_repository* {
    return repo_;
}

auto GitRepo::GuardedRepo::PtrRef() -> git_repository** {
    return &repo_;
}

GitRepo::GuardedRepo::~GuardedRepo() noexcept {
#ifndef BOOTSTRAP_BUILD_TOOL
    if (repo_ != nullptr) {
        std::unique_lock lock{*mutex_};
        git_repository_free(repo_);
    }
#endif
}

auto GitRepo::Open(GitCASPtr git_cas) noexcept -> std::optional<GitRepo> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
    auto repo = GitRepo(std::move(git_cas));
    if (not repo.repo_) {
        return std::nullopt;
    }
    return repo;
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::Open(std::filesystem::path const& repo_path) noexcept
    -> std::optional<GitRepo> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
    auto repo = GitRepo(repo_path);
    if (not repo.repo_) {
        return std::nullopt;
    }
    return repo;
#endif  // BOOTSTRAP_BUILD_TOOL
}

GitRepo::GitRepo(GitCASPtr git_cas) noexcept {
#ifndef BOOTSTRAP_BUILD_TOOL
    try {
        if (git_cas != nullptr) {
            auto repo_ptr = std::make_shared<GuardedRepo>(&git_cas->mutex_);
            {
                // acquire the odb lock exclusively
                std::unique_lock lock{git_cas->mutex_};
                if (git_repository_wrap_odb(repo_ptr->PtrRef(),
                                            git_cas->odb_.get()) != 0) {
                    Logger::Log(LogLevel::Error,
                                "could not create wrapper for git repository");
                    return;
                }
            }
            repo_ = std::move(repo_ptr);
            is_repo_fake_ = true;
            git_cas_ = std::move(git_cas);
        }
        else {
            Logger::Log(LogLevel::Error,
                        "git repository creation attempted with null odb!");
        }
    } catch (std::exception const& ex) {
        Logger::Log(LogLevel::Error,
                    "opening git object database failed with:\n{}",
                    ex.what());
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

GitRepo::GitRepo(std::filesystem::path const& repo_path) noexcept {
#ifndef BOOTSTRAP_BUILD_TOOL
    try {
        static std::mutex repo_mutex{};
        std::unique_lock lock{repo_mutex};
        auto cas = std::make_shared<GitCAS>();
        // open repo, but retain it
        auto repo_ptr = std::make_shared<GuardedRepo>(&cas->mutex_);
        if (git_repository_open_ext(repo_ptr->PtrRef(),
                                    repo_path.c_str(),
                                    GIT_REPOSITORY_OPEN_NO_SEARCH,
                                    nullptr) != 0) {
            Logger::Log(LogLevel::Error,
                        "opening git repository {} failed with:\n{}",
                        repo_path.string(),
                        GitLastError());
            return;
        }
        repo_ = repo_ptr;  // retain repo pointer
        // get odb
        git_odb* odb_ptr{nullptr};
        git_repository_odb(&odb_ptr, repo_->Ptr());
        if (odb_ptr == nullptr) {
            Logger::Log(LogLevel::Error,
                        "retrieving odb of git repository {} failed with:\n{}",
                        repo_path.string(),
                        GitLastError());
            // release resources
            git_odb_free(odb_ptr);
            return;
        }
        cas->odb_.reset(odb_ptr);  // retain odb pointer
        is_repo_fake_ = false;
        // save root path; this differs if repository is bare or not
        if (git_repository_is_bare(repo_->Ptr()) != 0) {
            cas->git_path_ = std::filesystem::absolute(
                ToNormalPath(git_repository_path(repo_->Ptr())));
        }
        else {
            cas->git_path_ = std::filesystem::absolute(
                ToNormalPath(git_repository_workdir(repo_->Ptr())));
        }
        // retain the pointer
        git_cas_ = std::static_pointer_cast<GitCAS const>(cas);
    } catch (std::exception const& ex) {
        Logger::Log(LogLevel::Error,
                    "opening git object database failed with:\n{}",
                    ex.what());
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

GitRepo::GitRepo(GitRepo&& other) noexcept
    : git_cas_{std::move(other.git_cas_)},
      repo_{std::move(other.repo_)},
      is_repo_fake_{other.is_repo_fake_} {
    other.git_cas_ = nullptr;
}

auto GitRepo::operator=(GitRepo&& other) noexcept -> GitRepo& {
    git_cas_ = std::move(other.git_cas_);
    repo_ = std::move(other.repo_);
    is_repo_fake_ = other.is_repo_fake_;
    other.git_cas_ = nullptr;
    return *this;
}

auto GitRepo::InitAndOpen(std::filesystem::path const& repo_path,
                          bool is_bare) noexcept -> std::optional<GitRepo> {
#ifndef BOOTSTRAP_BUILD_TOOL
    try {
        static std::mutex repo_mutex{};
        std::unique_lock lock{repo_mutex};

        GitContext::Create();  // initialize libgit2

        // check if init is actually needed
        if (git_repository_open_ext(nullptr,
                                    repo_path.c_str(),
                                    GIT_REPOSITORY_OPEN_NO_SEARCH,
                                    nullptr) == 0) {
            return GitRepo(repo_path);  // success
        }

        git_repository* tmp_repo{nullptr};
        std::size_t max_attempts = kGitLockNumTries;  // number of tries
        int err = 0;
        std::string err_mess{};
        while (max_attempts > 0) {
            --max_attempts;
            err = git_repository_init(&tmp_repo,
                                      repo_path.c_str(),
                                      static_cast<std::size_t>(is_bare));
            if (err == 0) {
                git_repository_free(tmp_repo);
                return GitRepo(repo_path);  // success
            }
            err_mess = GitLastError();  // store last error message
            // only retry if failure is due to locking
            if (err != GIT_ELOCKED) {
                break;
            }
            git_repository_free(tmp_repo);  // cleanup before next attempt
            // check if init hasn't already happened in another process
            if (git_repository_open_ext(nullptr,
                                        repo_path.c_str(),
                                        GIT_REPOSITORY_OPEN_NO_SEARCH,
                                        nullptr) == 0) {
                return GitRepo(repo_path);  // success
            }
            // repo still not created, so sleep and try again
            std::this_thread::sleep_for(
                std::chrono::milliseconds(kGitLockWaitTime));
        }
        Logger::Log(LogLevel::Error,
                    "initializing git repository {} failed with:\n{}",
                    (repo_path / "").string(),
                    err_mess);
    } catch (std::exception const& ex) {
        Logger::Log(LogLevel::Error,
                    "initializing git repository {} failed with:\n{}",
                    (repo_path / "").string(),
                    ex.what());
    }
#endif  // BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
}

auto GitRepo::GetGitCAS() const noexcept -> GitCASPtr {
    return git_cas_;
}

auto GitRepo::GetRepoRef() const noexcept -> GuardedRepoPtr {
    return repo_;
}

auto GitRepo::GetGitPath() const noexcept -> std::filesystem::path const& {
    return git_cas_->git_path_;
}

auto GitRepo::GetGitOdb() const noexcept
    -> std::unique_ptr<git_odb, decltype(&odb_closer)> const& {
    return git_cas_->odb_;
}

auto GitRepo::CommitDirectory(std::filesystem::path const& dir,
                              std::string const& message,
                              anon_logger_ptr const& logger) noexcept
    -> std::optional<std::string> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
    try {
        // only possible for real repository!
        if (IsRepoFake()) {
            (*logger)("cannot commit directory using a fake repository!",
                      true /*fatal*/);
            return std::nullopt;
        }
        // share the odb lock
        std::shared_lock lock{GetGitCAS()->mutex_};

        // Due to limitations of Git in general, and libgit2 in particular, by
        // which updating the index with entries that have Git-specific magic
        // names is cumbersome, if at all possible, we resort to creating
        // manually the tree to be commited from the given subdirectory by
        // recursively creating and writing to the object database all the blobs
        // and subtrees.

        // get tree containing the subdirectory entries
        auto raw_id = CreateTreeFromDirectory(dir, logger);
        if (not raw_id) {
            return std::nullopt;
        }

        // get tree oid
        git_oid tree_oid;
        if (git_oid_fromraw(&tree_oid,
                            reinterpret_cast<unsigned char const*>(  // NOLINT
                                raw_id->data())) != 0) {
            (*logger)(fmt::format("subdir tree object id parsing in git "
                                  "repository {} failed with:\n{}",
                                  GetGitPath().string(),
                                  GitLastError()),
                      true /*fatal*/);
            return std::nullopt;
        }

        // set committer signature
        git_signature* signature_ptr{nullptr};
        if (git_signature_new(
                &signature_ptr, "Nobody", "nobody@example.org", 0, 0) != 0) {
            (*logger)(
                fmt::format("creating signature in git repository {} failed "
                            "with:\n{}",
                            GetGitPath().string(),
                            GitLastError()),
                true /*fatal*/);
            // cleanup resources
            git_signature_free(signature_ptr);
            return std::nullopt;
        }
        auto signature =
            std::unique_ptr<git_signature, decltype(&signature_closer)>(
                signature_ptr, signature_closer);

        // get tree object
        git_tree* tree_ptr = nullptr;
        if (git_tree_lookup(&tree_ptr, repo_->Ptr(), &tree_oid) != 0) {
            (*logger)(
                fmt::format("tree lookup in git repository {} failed with:\n{}",
                            GetGitPath().string(),
                            GitLastError()),
                true /*fatal*/);
            // cleanup resources
            git_tree_free(tree_ptr);
            return std::nullopt;
        }
        auto tree = std::unique_ptr<git_tree, decltype(&tree_closer)>(
            tree_ptr, tree_closer);

        // commit the tree containing the staged files
        git_buf buffer = GIT_BUF_INIT_CONST(NULL, 0);
        git_message_prettify(&buffer, message.c_str(), 0, '#');

        git_oid commit_oid;
        // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)
        if (git_commit_create_v(&commit_oid,
                                repo_->Ptr(),
                                "HEAD",
                                signature.get(),
                                signature.get(),
                                nullptr,
                                buffer.ptr,
                                tree.get(),
                                0) != 0) {
            (*logger)(
                fmt::format("git commit in repository {} failed with:\n{}",
                            GetGitPath().string(),
                            GitLastError()),
                true /*fatal*/);
            git_buf_dispose(&buffer);
            return std::nullopt;
        }
        std::string commit_hash{git_oid_tostr_s(&commit_oid)};
        git_buf_dispose(&buffer);
        return commit_hash;  // success!
    } catch (std::exception const& ex) {
        Logger::Log(
            LogLevel::Error, "commit subdir failed with:\n{}", ex.what());
        return std::nullopt;
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::KeepTag(std::string const& commit,
                      std::string const& message,
                      anon_logger_ptr const& logger) noexcept
    -> std::optional<std::string> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
    try {
        // only possible for real repository!
        if (IsRepoFake()) {
            (*logger)("cannot tag commits using a fake repository!",
                      true /*fatal*/);
            return std::nullopt;
        }
        // share the odb lock
        std::shared_lock lock{GetGitCAS()->mutex_};

        // get commit spec
        git_object* target_ptr{nullptr};
        if (git_revparse_single(&target_ptr, repo_->Ptr(), commit.c_str()) !=
            0) {
            (*logger)(fmt::format("rev-parse commit {} in repository {} failed "
                                  "with:\n{}",
                                  commit,
                                  GetGitPath().string(),
                                  GitLastError()),
                      true /*fatal*/);
            git_object_free(target_ptr);
            return std::nullopt;
        }
        auto target = std::unique_ptr<git_object, decltype(&object_closer)>(
            target_ptr, object_closer);

        // set tagger signature
        git_signature* tagger_ptr{nullptr};
        if (git_signature_new(
                &tagger_ptr, "Nobody", "nobody@example.org", 0, 0) != 0) {
            (*logger)(
                fmt::format("creating signature in git repository {} failed "
                            "with:\n{}",
                            GetGitPath().string(),
                            GitLastError()),
                true /*fatal*/);
            // cleanup resources
            git_signature_free(tagger_ptr);
            return std::nullopt;
        }
        auto tagger =
            std::unique_ptr<git_signature, decltype(&signature_closer)>(
                tagger_ptr, signature_closer);

        // create tag
        git_oid oid;
        auto name = fmt::format("keep-{}", commit);
        git_strarray tag_names{};

        // check if tag hasn't already been added by another process
        if (git_tag_list_match(&tag_names, name.c_str(), repo_->Ptr()) == 0 and
            tag_names.count > 0) {
            git_strarray_dispose(&tag_names);
            return name;  // success!
        }
        git_strarray_dispose(&tag_names);  // free any allocated unused space

        std::size_t max_attempts = kGitLockNumTries;  // number of tries
        int err = 0;
        std::string err_mess{};
        while (max_attempts > 0) {
            --max_attempts;
            err = git_tag_create(&oid,
                                 repo_->Ptr(),
                                 name.c_str(),
                                 target.get(),
                                 tagger.get(),
                                 message.c_str(),
                                 1 /*force*/);
            if (err == 0) {
                return name;  // success!
            }
            err_mess = GitLastError();  // store last error message
            // only retry if failure is due to locking
            if (err != GIT_ELOCKED) {
                break;
            }
            // check if tag hasn't already been added by another process
            if (git_tag_list_match(&tag_names, name.c_str(), repo_->Ptr()) ==
                    0 and
                tag_names.count > 0) {
                git_strarray_dispose(&tag_names);
                return name;  // success!
            }
            git_strarray_dispose(
                &tag_names);  // free any allocated unused space
            // tag still not in, so sleep and try again
            std::this_thread::sleep_for(
                std::chrono::milliseconds(kGitLockWaitTime));
        }
        (*logger)(
            fmt::format("tag creation in git repository {} failed with:\n{}",
                        GetGitPath().string(),
                        err_mess),
            true /*fatal*/);
        return std::nullopt;
    } catch (std::exception const& ex) {
        Logger::Log(LogLevel::Error, "keep tag failed with:\n{}", ex.what());
        return std::nullopt;
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::GetHeadCommit(anon_logger_ptr const& logger) noexcept
    -> std::optional<std::string> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
    try {
        // only possible for real repository!
        if (IsRepoFake()) {
            (*logger)("cannot access HEAD ref using a fake repository!",
                      true /*fatal*/);
            return std::nullopt;
        }
        // share the odb lock
        std::shared_lock lock{GetGitCAS()->mutex_};

        // get root commit id
        git_oid head_oid;
        if (git_reference_name_to_id(&head_oid, repo_->Ptr(), "HEAD") != 0) {
            (*logger)(fmt::format("retrieving head commit in git repository {} "
                                  "failed with:\n{}",
                                  GetGitPath().string(),
                                  GitLastError()),
                      true /*fatal*/);
            return std::nullopt;
        }
        return std::string(git_oid_tostr_s(&head_oid));
    } catch (std::exception const& ex) {
        Logger::Log(
            LogLevel::Error, "get head commit failed with:\n{}", ex.what());
        return std::nullopt;
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::FetchFromPath(std::shared_ptr<git_config> cfg,
                            std::string const& repo_path,
                            std::optional<std::string> const& branch,
                            anon_logger_ptr const& logger) noexcept -> bool {
#ifdef BOOTSTRAP_BUILD_TOOL
    return false;
#else
    try {
        // only possible for real repository!
        if (IsRepoFake()) {
            (*logger)("Cannot fetch commit using a fake repository!",
                      true /*fatal*/);
            return false;
        }
        // create remote from repo
        git_remote* remote_ptr{nullptr};
        if (git_remote_create_anonymous(
                &remote_ptr, GetRepoRef()->Ptr(), repo_path.c_str()) != 0) {
            (*logger)(fmt::format("Creating remote {} for local repository {} "
                                  "failed with:\n{}",
                                  repo_path,
                                  GetGitPath().string(),
                                  GitLastError()),
                      true /*fatal*/);
            // cleanup resources
            git_remote_free(remote_ptr);
            return false;
        }
        // wrap remote object
        auto remote = std::unique_ptr<git_remote, decltype(&remote_closer)>(
            remote_ptr, remote_closer);

        // get a well-defined config file
        if (not cfg) {
            // get config snapshot of current repo
            git_config* cfg_ptr{nullptr};
            if (git_repository_config_snapshot(&cfg_ptr, GetRepoRef()->Ptr()) !=
                0) {
                (*logger)(fmt::format("Retrieving config object in fetch from "
                                      "path failed with:\n{}",
                                      GitLastError()),
                          true /*fatal*/);
                return false;
            }
            // share pointer with caller
            cfg.reset(cfg_ptr, config_closer);
        }

        // define default fetch options
        git_fetch_options fetch_opts{};
        git_fetch_options_init(&fetch_opts, GIT_FETCH_OPTIONS_VERSION);
        // no proxy
        fetch_opts.proxy_opts.type = GIT_PROXY_NONE;
        // no SSL verification
        fetch_opts.callbacks.certificate_check = certificate_passthrough_cb;
        // disable update of the FETCH_HEAD pointer
        fetch_opts.update_fetchhead = 0;

        // setup fetch refspecs array
        GitStrArray refspecs_array_obj;
        if (branch) {
            // make sure we check for tags as well
            refspecs_array_obj.AddEntry(fmt::format("+refs/tags/{}", *branch));
            refspecs_array_obj.AddEntry(fmt::format("+refs/heads/{}", *branch));
        }

        auto const refspecs_array = refspecs_array_obj.Get();
        if (git_remote_fetch(
                remote.get(), &refspecs_array, &fetch_opts, nullptr) != 0) {
            (*logger)(fmt::format(
                          "Fetching {} in local repository {} failed with:\n{}",
                          branch ? fmt::format("branch {}", *branch) : "all",
                          GetGitPath().string(),
                          GitLastError()),
                      true /*fatal*/);
            return false;
        }
        return true;  // success!
    } catch (std::exception const& ex) {
        Logger::Log(LogLevel::Error,
                    "Fetch {} from local repository {} failed with:\n{}",
                    branch ? fmt::format("branch {}", *branch) : "all",
                    repo_path,
                    ex.what());
        return false;
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::KeepTree(std::string const& tree_id,
                       std::string const& message,
                       anon_logger_ptr const& logger) noexcept
    -> std::optional<std::string> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
    try {
        // only possible for real repository!
        if (IsRepoFake()) {
            (*logger)("cannot commit and tag a tree using a fake repository!",
                      true /*fatal*/);
            return std::nullopt;
        }
        // share the odb lock
        std::shared_lock lock{GetGitCAS()->mutex_};

        // get tree oid
        git_oid tree_oid;
        if (git_oid_fromstr(&tree_oid, tree_id.c_str()) != 0) {
            (*logger)(fmt::format("tree ID parsing in git repository {} failed "
                                  "with:\n{}",
                                  GetGitPath().string(),
                                  GitLastError()),
                      true /*fatal*/);
            return std::nullopt;
        }
        // get tree object from oid
        git_object* target_ptr{nullptr};
        if (git_object_lookup(
                &target_ptr, repo_->Ptr(), &tree_oid, GIT_OBJECT_TREE) != 0) {
            (*logger)(fmt::format("object lookup for tree {} in repository "
                                  "{} failed with:\n{}",
                                  tree_id,
                                  GetGitPath().string(),
                                  GitLastError()),
                      true /*fatal*/);
            git_object_free(target_ptr);
            return std::nullopt;
        }
        auto target = std::unique_ptr<git_object, decltype(&object_closer)>(
            target_ptr, object_closer);

        // set signature
        git_signature* signature_ptr{nullptr};
        if (git_signature_new(
                &signature_ptr, "Nobody", "nobody@example.org", 0, 0) != 0) {
            (*logger)(
                fmt::format("creating signature in git repository {} failed "
                            "with:\n{}",
                            GetGitPath().string(),
                            GitLastError()),
                true /*fatal*/);
            // cleanup resources
            git_signature_free(signature_ptr);
            return std::nullopt;
        }
        auto signature =
            std::unique_ptr<git_signature, decltype(&signature_closer)>(
                signature_ptr, signature_closer);

        // create tag
        git_oid oid;
        auto name = fmt::format("keep-{}", tree_id);
        git_strarray tag_names{};

        // check if tag hasn't already been added by another process
        if (git_tag_list_match(&tag_names, name.c_str(), repo_->Ptr()) == 0 and
            tag_names.count > 0) {
            git_strarray_dispose(&tag_names);
            return name;  // success!
        }
        git_strarray_dispose(&tag_names);  // free any allocated unused space

        size_t max_attempts = kGitLockNumTries;  // number of tries
        int err = 0;
        std::string err_mess{};
        while (max_attempts > 0) {
            --max_attempts;
            err = git_tag_create(&oid,
                                 repo_->Ptr(),
                                 name.c_str(),
                                 target.get(),    /*tree*/
                                 signature.get(), /*tagger*/
                                 message.c_str(),
                                 1 /*force*/);
            if (err == 0) {
                return name;  // success!
            }
            err_mess = GitLastError();  // store last error message
            // only retry if failure is due to locking
            if (err != GIT_ELOCKED) {
                break;
            }
            // check if tag hasn't already been added by another process
            if (git_tag_list_match(&tag_names, name.c_str(), repo_->Ptr()) ==
                    0 and
                tag_names.count > 0) {
                git_strarray_dispose(&tag_names);
                return name;  // success!
            }
            git_strarray_dispose(
                &tag_names);  // free any allocated unused space
            // tag still not in, so sleep and try again
            std::this_thread::sleep_for(
                std::chrono::milliseconds(kGitLockWaitTime));
        }
        (*logger)(fmt::format("tag creation for tree {} in git repository {} "
                              "failed with:\n{}",
                              tree_id,
                              GetGitPath().string(),
                              err_mess),
                  true /*fatal*/);
        return std::nullopt;
    } catch (std::exception const& ex) {
        Logger::Log(LogLevel::Error,
                    "keep tree {} failed with:\n{}",
                    tree_id,
                    ex.what());
        return std::nullopt;
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::GetSubtreeFromCommit(std::string const& commit,
                                   std::string const& subdir,
                                   anon_logger_ptr const& logger) noexcept
    -> expected<std::string, GitLookupError> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return unexpected{GitLookupError::Fatal};
#else
    try {
        // preferably with a "fake" repository!
        if (not IsRepoFake()) {
            Logger::Log(
                LogLevel::Debug,
                "Subtree id retrieval from commit called on a real repository");
        }
        // share the odb lock
        std::shared_lock lock{GetGitCAS()->mutex_};

        // get commit object
        git_oid commit_oid;
        if (git_oid_fromstr(&commit_oid, commit.c_str()) != 0) {
            (*logger)(
                fmt::format("commit ID parsing in git repository {} failed "
                            "with:\n{}",
                            GetGitPath().string(),
                            GitLastError()),
                true /*fatal*/);
            return unexpected{GitLookupError::Fatal};
        }

        git_commit* commit_ptr{nullptr};
        if (git_commit_lookup(&commit_ptr, repo_->Ptr(), &commit_oid) != 0) {
            (*logger)(fmt::format("retrieving commit {} in git repository {} "
                                  "failed with:\n{}",
                                  commit,
                                  GetGitPath().string(),
                                  GitLastError()),
                      true /*fatal*/);
            // cleanup resources
            git_commit_free(commit_ptr);
            return unexpected{GitLookupError::NotFound};  // non-fatal failure
        }
        auto commit_obj = std::unique_ptr<git_commit, decltype(&commit_closer)>(
            commit_ptr, commit_closer);

        // get tree of commit
        git_tree* tree_ptr{nullptr};
        if (git_commit_tree(&tree_ptr, commit_obj.get()) != 0) {
            (*logger)(fmt::format(
                          "retrieving tree for commit {} in git repository {} "
                          "failed with:\n{}",
                          commit,
                          GetGitPath().string(),
                          GitLastError()),
                      true /*fatal*/);
            // cleanup resources
            git_tree_free(tree_ptr);
            return unexpected{GitLookupError::Fatal};
        }
        auto tree = std::unique_ptr<git_tree, decltype(&tree_closer)>(
            tree_ptr, tree_closer);

        if (subdir != ".") {
            // get hash for actual subdir
            git_tree_entry* subtree_entry_ptr{nullptr};
            if (git_tree_entry_bypath(
                    &subtree_entry_ptr, tree.get(), subdir.c_str()) != 0) {
                (*logger)(
                    fmt::format("retrieving subtree at {} in git repository "
                                "{} failed with:\n{}",
                                subdir,
                                GetGitPath().string(),
                                GitLastError()),
                    true /*fatal*/);
                // cleanup resources
                git_tree_entry_free(subtree_entry_ptr);
                return unexpected{GitLookupError::Fatal};
            }
            auto subtree_entry =
                std::unique_ptr<git_tree_entry, decltype(&tree_entry_closer)>(
                    subtree_entry_ptr, tree_entry_closer);

            std::string subtree_hash{
                git_oid_tostr_s(git_tree_entry_id(subtree_entry.get()))};
            return subtree_hash;  // success
        }
        // if no subdir, get hash from tree
        std::string tree_hash{git_oid_tostr_s(git_tree_id(tree.get()))};
        return tree_hash;  // success
    } catch (std::exception const& ex) {
        Logger::Log(LogLevel::Error,
                    "get subtree from commit failed with:\n{}",
                    ex.what());
        return unexpected{GitLookupError::Fatal};
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::GetSubtreeFromTree(std::string const& tree_id,
                                 std::string const& subdir,
                                 anon_logger_ptr const& logger) noexcept
    -> std::optional<std::string> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
    try {
        // check if subdir is not trivial
        if (subdir != ".") {
            // preferably with a "fake" repository!
            if (not IsRepoFake()) {
                Logger::Log(LogLevel::Debug,
                            "Subtree id retrieval from tree called on a real "
                            "repository");
            }
            // share the odb lock
            std::shared_lock lock{GetGitCAS()->mutex_};

            // get tree object from tree id
            git_oid tree_oid;
            if (git_oid_fromstr(&tree_oid, tree_id.c_str()) != 0) {
                (*logger)(
                    fmt::format("tree ID parsing in git repository {} failed "
                                "with:\n{}",
                                GetGitPath().string(),
                                GitLastError()),
                    true /*fatal*/);
                return std::nullopt;
            }

            git_tree* tree_ptr{nullptr};
            if (git_tree_lookup(&tree_ptr, repo_->Ptr(), &tree_oid) != 0) {
                (*logger)(fmt::format(
                              "retrieving tree {} in git repository {} failed "
                              "with:\n{}",
                              tree_id,
                              GetGitPath().string(),
                              GitLastError()),
                          true /*fatal*/);
                // cleanup resources
                git_tree_free(tree_ptr);
                return std::nullopt;
            }
            auto tree = std::unique_ptr<git_tree, decltype(&tree_closer)>(
                tree_ptr, tree_closer);

            // get hash for actual subdir
            git_tree_entry* subtree_entry_ptr{nullptr};
            if (git_tree_entry_bypath(
                    &subtree_entry_ptr, tree.get(), subdir.c_str()) != 0) {
                (*logger)(
                    fmt::format("retrieving subtree at {} in git repository "
                                "{} failed with:\n{}",
                                subdir,
                                GetGitPath().string(),
                                GitLastError()),
                    true /*fatal*/);
                // cleanup resources
                git_tree_entry_free(subtree_entry_ptr);
                return std::nullopt;
            }
            auto subtree_entry =
                std::unique_ptr<git_tree_entry, decltype(&tree_entry_closer)>(
                    subtree_entry_ptr, tree_entry_closer);

            std::string subtree_hash{
                git_oid_tostr_s(git_tree_entry_id(subtree_entry.get()))};
            return subtree_hash;
        }
        // if no subdir, return given tree hash
        return tree_id;
    } catch (std::exception const& ex) {
        Logger::Log(LogLevel::Error,
                    "get subtree from tree failed with:\n{}",
                    ex.what());
        return std::nullopt;
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::GetSubtreeFromPath(std::filesystem::path const& fpath,
                                 std::string const& head_commit,
                                 anon_logger_ptr const& logger) noexcept
    -> std::optional<std::string> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
    try {
        // preferably with a "fake" repository!
        if (not IsRepoFake()) {
            Logger::Log(
                LogLevel::Debug,
                "Subtree id retrieval from path called on a real repository");
        }
        // setup wrapped logger
        auto wrapped_logger = std::make_shared<anon_logger_t>(
            [logger](auto const& msg, bool fatal) {
                (*logger)(
                    fmt::format("While getting repo root from path:\n{}", msg),
                    fatal);
            });
        // find root dir of this repository
        auto root = GetRepoRootFromPath(fpath, wrapped_logger);
        if (root == std::nullopt) {
            return std::nullopt;
        }

        // setup wrapped logger
        wrapped_logger = std::make_shared<anon_logger_t>(
            [logger](auto const& msg, bool fatal) {
                (*logger)(fmt::format("While going subtree hash retrieval from "
                                      "path:\n{}",
                                      msg),
                          fatal);
            });
        // find relative path from root to given path
        auto subdir = std::filesystem::relative(fpath, *root).string();
        // get subtree from head commit and subdir
        auto res = GetSubtreeFromCommit(head_commit, subdir, wrapped_logger);
        if (not res) {
            return std::nullopt;
        }
        return *std::move(res);
    } catch (std::exception const& ex) {
        Logger::Log(LogLevel::Error,
                    "get subtree from path failed with:\n{}",
                    ex.what());
        return std::nullopt;
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::CheckCommitExists(std::string const& commit,
                                anon_logger_ptr const& logger) noexcept
    -> std::optional<bool> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
    try {
        // preferably with a "fake" repository!
        if (not IsRepoFake()) {
            Logger::Log(LogLevel::Debug,
                        "Commit lookup called on a real repository");
        }
        // lookup commit in current repo state
        git_oid commit_oid;
        if (git_oid_fromstr(&commit_oid, commit.c_str()) != 0) {
            (*logger)(
                fmt::format("commit ID parsing in git repository {} failed "
                            "with:\n{}",
                            GetGitPath().string(),
                            GitLastError()),
                true /*fatal*/);
            return std::nullopt;
        }

        git_commit* commit_obj = nullptr;
        int lookup_res{};
        {
            // share the odb lock
            std::shared_lock lock{GetGitCAS()->mutex_};
            lookup_res =
                git_commit_lookup(&commit_obj, repo_->Ptr(), &commit_oid);
        }
        if (lookup_res != 0) {
            if (lookup_res == GIT_ENOTFOUND) {
                // cleanup resources
                git_commit_free(commit_obj);
                return false;  // commit not found
            }
            // failure
            (*logger)(
                fmt::format("lookup of commit {} in git repository {} failed "
                            "with:\n{}",
                            commit,
                            GetGitPath().string(),
                            GitLastError()),
                true /*fatal*/);
            // cleanup resources
            git_commit_free(commit_obj);
            return std::nullopt;
        }
        // cleanup resources
        git_commit_free(commit_obj);
        return true;  // commit exists
    } catch (std::exception const& ex) {
        Logger::Log(
            LogLevel::Error, "check commit exists failed with:\n{}", ex.what());
        return std::nullopt;
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::GetRepoRootFromPath(std::filesystem::path const& fpath,
                                  anon_logger_ptr const& logger) noexcept
    -> std::optional<std::filesystem::path> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
    try {
        GitContext::Create();  // initialize libgit2

        git_buf buffer = GIT_BUF_INIT_CONST(NULL, 0);
        auto res = git_repository_discover(&buffer, fpath.c_str(), 0, nullptr);

        if (res != 0) {
            if (res == GIT_ENOTFOUND) {
                git_buf_dispose(&buffer);
                return std::filesystem::path{};  // empty path cause nothing
                                                 // found
            }
            // failure
            (*logger)(fmt::format(
                          "repository root search failed at path {} with:\n{}!",
                          fpath.string(),
                          GitLastError()),
                      true /*fatal*/);
            git_buf_dispose(&buffer);
            return std::nullopt;
        }
        // found root repo path
        std::string result{buffer.ptr};
        git_buf_dispose(&buffer);
        // normalize root result
        auto actual_root =
            std::filesystem::path{result}.parent_path();  // remove trailing "/"
        if (actual_root.parent_path() / ".git" == actual_root) {
            return actual_root.parent_path();  // remove ".git" folder from path
        }
        return actual_root;
    } catch (std::exception const& ex) {
        Logger::Log(LogLevel::Error,
                    "get repo root from path failed with:\n{}",
                    ex.what());
        return std::nullopt;
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::CheckTreeExists(std::string const& tree_id,
                              anon_logger_ptr const& logger) noexcept
    -> std::optional<bool> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
    try {
        // preferably with a "fake" repository!
        if (not IsRepoFake()) {
            Logger::Log(LogLevel::Debug,
                        "Tree lookup called on a real repository");
        }
        // get git oid
        git_oid tree_oid;
        if (git_oid_fromstr(&tree_oid, tree_id.c_str()) != 0) {
            (*logger)(fmt::format("tree ID parsing in git repository {} failed "
                                  "with:\n{}",
                                  GetGitPath().string(),
                                  GitLastError()),
                      true /*fatal*/);
            return std::nullopt;
        }
        // get tree object
        git_tree* tree_ptr = nullptr;
        int lookup_res{};
        {
            // share the odb lock
            std::shared_lock lock{GetGitCAS()->mutex_};
            lookup_res = git_tree_lookup(&tree_ptr, repo_->Ptr(), &tree_oid);
        }
        git_tree_free(tree_ptr);
        if (lookup_res != 0) {
            if (lookup_res == GIT_ENOTFOUND) {
                return false;  // tree not found
            }
            (*logger)(
                fmt::format("tree lookup in git repository {} failed with:\n{}",
                            GetGitPath().string(),
                            GitLastError()),
                true /*fatal*/);
            return std::nullopt;
        }
        return true;  // tree found
    } catch (std::exception const& ex) {
        Logger::Log(
            LogLevel::Error, "check tree exists failed with:\n{}", ex.what());
        return std::nullopt;
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::CheckBlobExists(std::string const& blob_id,
                              anon_logger_ptr const& logger) noexcept
    -> std::optional<bool> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
    try {
        // preferably with a "fake" repository!
        if (not IsRepoFake()) {
            Logger::Log(LogLevel::Debug,
                        "Blob lookup called on a real repository");
        }
        // get git oid
        git_oid blob_oid;
        if (git_oid_fromstr(&blob_oid, blob_id.c_str()) != 0) {
            (*logger)(fmt::format("blob ID parsing in git repository {} failed "
                                  "with:\n{}",
                                  GetGitPath().string(),
                                  GitLastError()),
                      true /*fatal*/);
            return std::nullopt;
        }
        // get blob object
        git_blob* blob_ptr = nullptr;
        int lookup_res{};
        {
            // share the odb lock
            std::shared_lock lock{GetGitCAS()->mutex_};
            lookup_res = git_blob_lookup(&blob_ptr, repo_->Ptr(), &blob_oid);
        }
        git_blob_free(blob_ptr);
        if (lookup_res != 0) {
            if (lookup_res == GIT_ENOTFOUND) {
                return false;  // blob not found
            }
            (*logger)(fmt::format("blob lookup in git repository {} failed "
                                  "with:\n{}",
                                  GetGitPath().string(),
                                  GitLastError()),
                      true /*fatal*/);
            return std::nullopt;
        }
        return true;  // blob found
    } catch (std::exception const& ex) {
        Logger::Log(
            LogLevel::Error, "check blob exists failed with:\n{}", ex.what());
        return std::nullopt;
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::TryReadBlob(std::string const& blob_id,
                          anon_logger_ptr const& logger) noexcept
    -> std::pair<bool, std::optional<std::string>> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::pair(false, std::nullopt);
#else
    try {
        // preferably with a "fake" repository!
        if (not IsRepoFake()) {
            Logger::Log(LogLevel::Debug,
                        "Blob lookup called on a real repository");
        }
        // get git oid
        git_oid blob_oid;
        if (git_oid_fromstr(&blob_oid, blob_id.c_str()) != 0) {
            (*logger)(fmt::format("blob ID parsing in git repository {} failed "
                                  "with:\n{}",
                                  GetGitPath().string(),
                                  GitLastError()),
                      true /*fatal*/);
            return std::pair(false, std::nullopt);
        }
        // get blob object
        git_blob* blob_ptr = nullptr;
        int lookup_res{};
        {
            // share the odb lock
            std::shared_lock lock{GetGitCAS()->mutex_};
            lookup_res = git_blob_lookup(&blob_ptr, repo_->Ptr(), &blob_oid);
        }
        git_blob_free(blob_ptr);
        if (lookup_res != 0) {
            if (lookup_res == GIT_ENOTFOUND) {
                return std::pair(true, std::nullopt);  // blob not found
            }
            (*logger)(fmt::format("blob lookup in git repository {} failed "
                                  "with:\n{}",
                                  GetGitPath().string(),
                                  GitLastError()),
                      true /*fatal*/);
            return std::pair(false, std::nullopt);
        }
        // get data of found blob
        if (auto data = GetGitCAS()->ReadObject(blob_id, /*is_hex_id=*/true)) {
            return std::pair(true, std::move(*data));
        }
        (*logger)(fmt::format(
                      "failed to read target for blob {} in git repository {}",
                      blob_id,
                      GetGitPath().string()),
                  true /*fatal*/);
        return std::pair(false, std::nullopt);
    } catch (std::exception const& ex) {
        Logger::Log(
            LogLevel::Error, "check blob exists failed with:\n{}", ex.what());
        return std::pair(false, std::nullopt);
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::WriteBlob(std::string const& content,
                        anon_logger_ptr const& logger) noexcept
    -> std::optional<std::string> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
    try {
        // preferably with a "fake" repository!
        if (not IsRepoFake()) {
            Logger::Log(LogLevel::Debug,
                        "Blob writer called on a real repository");
        }
        // share the odb lock
        std::shared_lock lock{GetGitCAS()->mutex_};

        git_oid blob_oid;
        if (git_blob_create_from_buffer(
                &blob_oid, repo_->Ptr(), content.c_str(), content.size()) !=
            0) {
            (*logger)(fmt::format("writing blob into database failed with:\n{}",
                                  GitLastError()),
                      /*fatal=*/true);
            return std::nullopt;
        }
        return std::string{git_oid_tostr_s(&blob_oid)};
    } catch (std::exception const& ex) {
        Logger::Log(LogLevel::Error, "write blob failed with:\n{}", ex.what());
        return std::nullopt;
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::GetObjectByPathFromTree(std::string const& tree_id,
                                      std::string const& rel_path) noexcept
    -> std::optional<TreeEntryInfo> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
    try {
        std::string entry_id{tree_id};
        ObjectType entry_type{ObjectType::Tree};

        // preferably with a "fake" repository!
        if (not IsRepoFake()) {
            Logger::Log(LogLevel::Debug,
                        "Subtree id retrieval from tree called on a real "
                        "repository");
        }
        // check if path is not trivial
        if (rel_path != ".") {
            // share the odb lock
            std::shared_lock lock{GetGitCAS()->mutex_};

            // get tree object from tree id
            git_oid tree_oid;
            if (git_oid_fromstr(&tree_oid, tree_id.c_str()) != 0) {
                Logger::Log(LogLevel::Trace,
                            "tree ID parsing in git repository {} failed "
                            "with:\n{}",
                            GetGitPath().string(),
                            GitLastError());
                return std::nullopt;
            }

            git_tree* tree_ptr{nullptr};
            if (git_tree_lookup(&tree_ptr, repo_->Ptr(), &tree_oid) != 0) {
                Logger::Log(LogLevel::Trace,
                            "retrieving tree {} in git repository {} "
                            "failed with:\n{}",
                            tree_id,
                            GetGitPath().string(),
                            GitLastError());
                // cleanup resources
                git_tree_free(tree_ptr);
                return std::nullopt;
            }
            auto tree = std::unique_ptr<git_tree, decltype(&tree_closer)>(
                tree_ptr, tree_closer);

            // get hash for actual entry
            git_tree_entry* entry_ptr{nullptr};
            if (git_tree_entry_bypath(
                    &entry_ptr, tree.get(), rel_path.c_str()) != 0) {
                Logger::Log(LogLevel::Trace,
                            "retrieving entry at {} in git repository {} "
                            "failed with:\n{}",
                            rel_path,
                            GetGitPath().string(),
                            GitLastError());
                // cleanup resources
                git_tree_entry_free(entry_ptr);
                return std::nullopt;
            }

            auto entry =
                std::unique_ptr<git_tree_entry, decltype(&tree_entry_closer)>(
                    entry_ptr, tree_entry_closer);

            // get id
            entry_id =
                std::string(git_oid_tostr_s(git_tree_entry_id(entry.get())));

            // get type
            if (auto e_type = GitFileModeToObjectType(
                    git_tree_entry_filemode(entry.get()))) {
                entry_type = *e_type;
            }
            else {
                Logger::Log(LogLevel::Trace,
                            "retrieving type of entry {} in git repository "
                            "{} failed with:\n{}",
                            entry_id,
                            GetGitPath().string(),
                            GitLastError());
                return std::nullopt;
            }
        }

        // if symlink, also read target
        if (IsSymlinkObject(entry_type)) {
            if (auto target =
                    GetGitCAS()->ReadObject(entry_id, /*is_hex_id=*/true)) {
                return TreeEntryInfo{.id = entry_id,
                                     .type = entry_type,
                                     .symlink_content = std::move(target)};
            }
            Logger::Log(
                LogLevel::Trace,
                "failed to read target for symlink {} in git repository {}",
                entry_id,
                GetGitPath().string());
            return std::nullopt;
        }
        return TreeEntryInfo{.id = entry_id,
                             .type = entry_type,
                             .symlink_content = std::nullopt};
    } catch (std::exception const& ex) {
        Logger::Log(LogLevel::Debug,
                    "get entry by path from tree failed with:\n{}",
                    ex.what());
        return std::nullopt;
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::LocalFetchViaTmpRepo(StorageConfig const& storage_config,
                                   std::string const& repo_path,
                                   std::optional<std::string> const& branch,
                                   anon_logger_ptr const& logger) noexcept
    -> bool {
#ifdef BOOTSTRAP_BUILD_TOOL
    return false;
#else
    try {
        // preferably with a "fake" repository!
        if (not IsRepoFake()) {
            Logger::Log(LogLevel::Debug,
                        "Branch local fetch called on a real repository");
        }
        auto tmp_dir = storage_config.CreateTypedTmpDir("local_fetch");
        if (not tmp_dir) {
            (*logger)("Failed to create temp dir for Git repository",
                      /*fatal=*/true);
            return false;
        }
        auto const& tmp_path = tmp_dir->GetPath();
        // create the temporary real repository
        // it can be bare, as the refspecs for this fetch will be given
        // explicitly.
        auto tmp_repo = GitRepo::InitAndOpen(tmp_path, /*is_bare=*/true);
        if (tmp_repo == std::nullopt) {
            return false;
        }
        // add backend, with max priority
        FetchIntoODBBackend b{.parent = kFetchIntoODBParent,
                              .target_odb = GetGitOdb().get()};
        if (git_odb_add_backend(
                tmp_repo->GetGitOdb().get(),
                // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
                reinterpret_cast<git_odb_backend*>(&b),
                std::numeric_limits<int>::max()) == 0) {
            // setup wrapped logger
            auto wrapped_logger = std::make_shared<anon_logger_t>(
                [logger](auto const& msg, bool fatal) {
                    (*logger)(fmt::format("While doing branch local fetch via "
                                          "tmp repo:\n{}",
                                          msg),
                              fatal);
                });
            // get the config of the correct target repo
            auto cfg = GetConfigSnapshot();
            if (cfg == nullptr) {
                (*logger)(fmt::format("Retrieving config object in local fetch "
                                      "via tmp repo failed with:\n{}",
                                      GitLastError()),
                          true /*fatal*/);
                return false;
            }
            return tmp_repo->FetchFromPath(
                cfg, repo_path, branch, wrapped_logger);
        }
        (*logger)(fmt::format(
                      "Adding custom backend for local fetch failed with:\n{}",
                      GitLastError()),
                  true /*fatal*/);
        return false;
    } catch (std::exception const& ex) {
        Logger::Log(
            LogLevel::Error,
            "Fetch {} from local repository {} via tmp dir failed with:\n{}",
            branch ? fmt::format("branch {}", *branch) : "all",
            repo_path,
            ex.what());
        return false;
    }
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::GetConfigSnapshot() const noexcept
    -> std::shared_ptr<git_config> {
#ifndef BOOTSTRAP_BUILD_TOOL
    git_config* cfg_ptr{nullptr};
    if (git_repository_config_snapshot(&cfg_ptr, GetRepoRef()->Ptr()) == 0) {
        return std::shared_ptr<git_config>(cfg_ptr, config_closer);
    }
#endif  // BOOTSTRAP_BUILD_TOOL
    return nullptr;
}

auto GitRepo::IsRepoFake() const noexcept -> bool {
    return is_repo_fake_;
}

auto GitRepo::ReadTree(std::string const& id,
                       gsl::not_null<SymlinksCheckFunc> const& check_symlinks,
                       bool is_hex_id,
                       bool ignore_special) const noexcept
    -> std::optional<tree_entries_t> {
#ifndef BOOTSTRAP_BUILD_TOOL
    try {
        // create object id
        auto oid = GitObjectID(id, is_hex_id);
        if (not oid) {
            return std::nullopt;
        }

        // lookup tree
        git_tree* tree_ptr{nullptr};
        {
            // share the odb lock
            std::shared_lock lock{GetGitCAS()->mutex_};
            if (git_tree_lookup(&tree_ptr, repo_->Ptr(), &(*oid)) != 0) {
                Logger::Log(LogLevel::Debug,
                            "failed to lookup Git tree {}",
                            is_hex_id ? std::string{id} : ToHexString(id));
                return std::nullopt;
            }
        }
        auto tree = std::unique_ptr<git_tree, decltype(&tree_closer)>{
            tree_ptr, tree_closer};

        // walk tree (flat) and create entries
        tree_entries_t entries{};
        entries.reserve(git_tree_entrycount(tree.get()));
        if (git_tree_walk(tree.get(),
                          GIT_TREEWALK_PRE,
                          ignore_special ? flat_tree_walker_ignore_special
                                         : flat_tree_walker,
                          &entries) != 0) {
            Logger::Log(LogLevel::Debug,
                        "failed to walk Git tree {}",
                        is_hex_id ? std::string{id} : ToHexString(id));
            return std::nullopt;
        }

        // checking non-upwardness of symlinks can not be easily or safely done
        // during the tree walk, so it is done here. This is only needed for
        // ignore_special==false.
        if (not ignore_special) {
            // we first gather all symlink candidates
            // to check symlinks in bulk, optimized for network-backed repos
            std::vector<ArtifactDigest> symlinks{};
            symlinks.reserve(entries.size());  // at most one symlink per entry
            for (auto const& entry : entries) {
                if (std::any_of(entry.second.begin(),
                                entry.second.end(),
                                [](TreeEntry const& item) {
                                    return IsSymlinkObject(item.type);
                                })) {
                    auto digest = ArtifactDigestFactory::Create(
                        HashFunction::Type::GitSHA1,
                        ToHexString(entry.first),
                        /*size=*/0,
                        /*is_tree=*/false);
                    if (not digest) {
                        Logger::Log(LogLevel::Debug,
                                    "Conversion error in GitRepo:\n {}",
                                    std::move(digest).error());
                        return std::nullopt;
                    }
                    symlinks.emplace_back(*std::move(digest));
                }
            }

            if (not symlinks.empty() and
                not std::invoke(check_symlinks.get(), symlinks)) {
                Logger::Log(LogLevel::Error,
                            "found upwards symlinks in Git tree {}",
                            is_hex_id ? std::string{id} : ToHexString(id));
                return std::nullopt;
            }
        }

#ifndef NDEBUG
        // Check consistency of entries. No need to check if entries exist.
        EnsuresAudit(ValidateEntries(entries));
#endif

        return entries;
    } catch (std::exception const& ex) {
        Logger::Log(
            LogLevel::Error, "reading tree failed with:\n{}", ex.what());
    }
#endif

    return std::nullopt;
}

auto GitRepo::CreateTree(tree_entries_t const& entries) const noexcept
    -> std::optional<std::string> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
#ifndef NDEBUG
    // Check consistency of entries. Also check that entries exist.
    ExpectsAudit(ValidateEntries(entries, GetGitCAS()));
#endif  // NDEBUG
    // share the odb lock
    std::shared_lock lock{GetGitCAS()->mutex_};

    try {
        // As the libgit2 treebuilder checks for magic names and does not allow
        // us to add any and all entries to a Git tree, we resort to
        // constructing the tree content ourselves and add it manually to the
        // repository ODB.

        // We need to sort the filenames according to Git rules: tree entries
        // need to be considered "as if" their filename has a trailing
        // separator ('/').
        std::map<std::string, std::pair<std::string, ObjectType>> sorted;
        for (auto const& [raw_id, es] : entries) {
            for (auto const& entry : es) {
                sorted.emplace(
                    entry.name + (IsTreeObject(entry.type) ? "/" : ""),
                    std::make_pair(raw_id, entry.type));
            }
        }

        // Compute the tree content. For tree entries the trailing slash needs
        // to be removed from filename before appending it.
        std::stringstream tree_content{};
        for (auto const& [name, entry] : sorted) {
            std::string_view const filename{
                name.data(),
                name.size() -
                    static_cast<std::size_t>(IsTreeObject(entry.second))};
            // tree format: "<perm> <filename>\0<binary_hash>[next entries...]"
            tree_content << fmt::format("{} {}",
                                        ObjectTypeToPerm(entry.second),
                                        filename)
                         << '\0' << entry.first;
        }

        // Write tree to ODB and return raw id string
        git_oid oid;
        auto const tree_content_str = tree_content.str();
        if (git_odb_write(&oid,
                          GetGitOdb().get(),
                          tree_content_str.c_str(),
                          tree_content_str.size(),
                          GIT_OBJECT_TREE) != 0) {
            Logger::Log(LogLevel::Debug,
                        "failed writing tree to ODB with:\n{}",
                        GitLastError());
            return std::nullopt;
        }
        return ToRawString(oid);
    } catch (std::exception const& ex) {
        Logger::Log(
            LogLevel::Error, "creating tree failed with:\n{}", ex.what());
        return std::nullopt;
    }
#endif
}

auto GitRepo::ReadTreeData(
    std::string const& data,
    std::string const& id,
    gsl::not_null<SymlinksCheckFunc> const& check_symlinks,
    bool is_hex_id) noexcept -> std::optional<tree_entries_t> {
#ifndef BOOTSTRAP_BUILD_TOOL
    try {
        InMemoryODBBackend b{.parent = kInMemoryODBParent};
        auto cas = std::make_shared<GitCAS>();
        if (auto raw_id =
                is_hex_id ? FromHexString(id) : std::make_optional(id)) {
            try {
                b.trees.emplace(*raw_id, data);
            } catch (...) {
                return std::nullopt;
            }
            // create a GitCAS from a special-purpose in-memory object database.
            git_odb* odb_ptr{nullptr};
            if (git_odb_new(&odb_ptr) == 0 and
                git_odb_add_backend(
                    odb_ptr,
                    reinterpret_cast<git_odb_backend*>(&b),  // NOLINT
                    0) == 0) {
                cas->odb_.reset(odb_ptr);  // take ownership of odb
                // wrap odb in "fake" repo
                auto repo =
                    GitRepo(std::static_pointer_cast<GitCAS const>(cas));
                return repo.ReadTree(
                    *raw_id, check_symlinks, /*is_hex_id=*/false);
            }
        }
    } catch (std::exception const& ex) {
        Logger::Log(
            LogLevel::Error, "reading tree data failed with:\n{}", ex.what());
    }
#endif
    return std::nullopt;
}

auto GitRepo::CreateShallowTree(tree_entries_t const& entries) noexcept
    -> std::optional<std::pair<std::string, std::string>> {
#ifndef BOOTSTRAP_BUILD_TOOL
    try {
        InMemoryODBBackend b{.parent = kInMemoryODBParent, .entries = &entries};
        auto cas = std::make_shared<GitCAS>();
        // create a GitCAS from a special-purpose in-memory object database.
        git_odb* odb_ptr{nullptr};
        if (git_odb_new(&odb_ptr) == 0 and
            git_odb_add_backend(
                odb_ptr,
                reinterpret_cast<git_odb_backend*>(&b),  // NOLINT
                0) == 0) {
            cas->odb_.reset(odb_ptr);  // take ownership of odb
            // wrap odb in "fake" repo
            auto repo = GitRepo(std::static_pointer_cast<GitCAS const>(cas));
            if (auto raw_id = repo.CreateTree(entries)) {
                // read result from in-memory trees
                if (auto it = b.trees.find(*raw_id); it != b.trees.end()) {
                    return std::make_pair(std::move(*raw_id),
                                          std::move(it->second));
                }
            }
        }
    } catch (std::exception const& ex) {
        Logger::Log(LogLevel::Error,
                    "creating shallow tree failed with:\n{}",
                    ex.what());
    }
#endif
    return std::nullopt;
}

[[nodiscard]] auto GitRepo::ReadDirectory(
    std::filesystem::path const& dir,
    StoreDirEntryFunc const& read_and_store_entry,
    anon_logger_ptr const& logger) noexcept -> bool {
    try {
        for (auto const& entry : std::filesystem::directory_iterator{dir}) {
            if (auto type = FileSystemManager::Type(entry.path(),
                                                    /*allow_upwards=*/true)) {
                if (not read_and_store_entry(entry.path().filename(), *type)) {
                    (*logger)(fmt::format("could not read and store to ODB "
                                          "subdir entry {}",
                                          entry.path().string()),
                              /*fatal=*/true);
                    return false;
                }
            }
            else {
                (*logger)(fmt::format("unsupported type for subdir entry {}",
                                      entry.path().string()),
                          /*fatal=*/true);
                return false;
            }
        }
    } catch (std::exception const& ex) {
        Logger::Log(
            LogLevel::Error, "reading subdirectory {} failed", dir.string());
        return false;
    }
    return true;  // success!
}

auto GitRepo::CreateTreeFromDirectory(std::filesystem::path const& dir,
                                      anon_logger_ptr const& logger) noexcept
    -> std::optional<std::string> {
#ifdef BOOTSTRAP_BUILD_TOOL
    return std::nullopt;
#else
    tree_entries_t entries{};
    auto dir_read_and_store = [this, &entries, dir, logger](auto name,
                                                            auto type) {
        const auto full_name = dir / name;
        if (IsTreeObject(type)) {
            // store subdirectory as a tree in the ODB
            if (auto raw_id =
                    this->CreateTreeFromDirectory(full_name, logger)) {
                entries[std::move(*raw_id)].emplace_back(name.string(),
                                                         ObjectType::Tree);
                return true;
            }
            (*logger)(
                fmt::format("failed creating tree {}", full_name.string()),
                /*fatal=*/true);
            return false;
        }
        // for non-tree entries, read content and write it as a blob to the ODB
        if (auto content =
                FileSystemManager::ReadContentAtPath(full_name, type)) {
            if (auto hash = WriteBlob(*content, logger)) {
                if (auto raw_id = FromHexString(*hash)) {
                    entries[std::move(*raw_id)].emplace_back(name.string(),
                                                             type);
                    return true;
                }
            }
        }
        (*logger)(fmt::format("failed creating blob {}", full_name.string()),
                  /*fatal=*/true);
        return false;
    };

    if (ReadDirectory(dir, dir_read_and_store, logger)) {
        return CreateTree(entries);
    }
    return std::nullopt;
#endif  // BOOTSTRAP_BUILD_TOOL
}

auto GitRepo::GitStrArray::Get() & noexcept -> git_strarray {
    return git_strarray{.strings = entry_pointers_.data(),
                        .count = entry_pointers_.size()};
}