-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathlibgit2.cpp
More file actions
1496 lines (1312 loc) · 61.2 KB
/
libgit2.cpp
File metadata and controls
1496 lines (1312 loc) · 61.2 KB
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
//*****************************************************************************
// Copyright 2025 Intel Corporation
//
// 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 "libgit2.hpp"
#include <algorithm>
#include <array>
#include <atomic>
#include <cctype>
#include <functional>
#include <fstream>
#include <iostream>
#include <memory>
#include <set>
#include <string>
#include <sstream>
#include <utility>
#include <vector>
#include <assert.h>
#include <fcntl.h>
#include <git2.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "cmd_exec.hpp"
#include "src/filesystem/filesystem.hpp"
#include "src/filesystem/localfilesystem.hpp"
#include "../logging.hpp"
#include "../shutdown_state.hpp"
#include "../stringutils.hpp"
#include "../status.hpp"
#ifndef PRIuZ
/* Define the printf format specifier to use for size_t output */
#if defined(_MSC_VER) || defined(__MINGW32__)
#define PRIuZ "Iu"
#else
#define PRIuZ "zu"
#endif
#endif
/* Exported cancellation accessors in libgit2 patch – used to abort
* ongoing LFS downloads from OVMS. On Windows the import declarations must
* be marked dllimport so MSVC binds them to the git2.dll exports rather than
* (silently) to a duplicate static-archive copy with its own backing storage. */
#if defined(_WIN32)
#define OVMS_LIBGIT2_LFS_IMPORT __declspec(dllimport)
#else
#define OVMS_LIBGIT2_LFS_IMPORT
#endif
extern "C" {
OVMS_LIBGIT2_LFS_IMPORT void git_lfs_cancel_set(int value);
OVMS_LIBGIT2_LFS_IMPORT int git_lfs_cancel_get(void);
}
namespace ovms {
namespace fs = std::filesystem;
namespace libgit2 {
/**
* Builds the side-marker path used to track interrupted LFS operations.
* The marker lives next to the repository directory as <repo>.lfswip
* (i.e. it is a SIBLING of the repo directory, not a file inside it).
* Example: repositoryPath "/opt/models/OV/model1" produces
* "/opt/models/OV/model1.lfswip".
*/
fs::path getLfsWipMarkerPath(const std::string& repositoryPath) {
const fs::path repository = fs::path(repositoryPath);
return repository.parent_path() / (repository.filename().string() + ".lfswip");
}
/**
* Creates or truncates the .lfswip marker file for the target repository.
* Marker presence indicates clone/download interruption handling is in progress.
* Returns true on success, false on filesystem error.
*/
bool createLfsWipMarker(const std::string& repositoryPath) {
const fs::path markerPath = getLfsWipMarkerPath(repositoryPath);
std::error_code ec;
if (!markerPath.parent_path().empty()) {
fs::create_directories(markerPath.parent_path(), ec);
}
std::ofstream marker(markerPath, std::ios::trunc);
return static_cast<bool>(marker);
}
bool hasLfsWipMarker(const std::string& repositoryPath) {
const fs::path markerPath = getLfsWipMarkerPath(repositoryPath);
std::error_code ec;
return fs::exists(markerPath, ec) && fs::is_regular_file(markerPath, ec);
}
void removeLfsWipMarker(const std::string& repositoryPath) {
const fs::path markerPath = getLfsWipMarkerPath(repositoryPath);
std::error_code ec;
if (!fs::remove(markerPath, ec) && ec) {
SPDLOG_WARN("Failed to remove .lfswip marker {}: {}", markerPath.string(), ec.message());
}
}
/**
* Attempts to remove stale lfs_error.txt file from a repository.
* If the file cannot be checked or deleted, logs a warning but does not fail the operation.
* This function clears error artifacts that would otherwise interfere with resume/clone detection.
*
* @param repositoryPath Path to the git repository root directory.
* @note Logs warnings if file operations fail; operation continues on error.
*/
static void clearStaleErrorFile(const std::string& repositoryPath) {
std::error_code ec;
const fs::path errorFilePath = fs::path(repositoryPath) / "lfs_error.txt";
bool fileExists = fs::exists(errorFilePath, ec);
if (ec) {
SPDLOG_WARN("Failed to check if lfs_error.txt exists at {}: {}. May interfere with resume/clone detection.",
errorFilePath.string(), ec.message());
return;
}
if (fileExists) {
if (!fs::remove(errorFilePath, ec)) {
SPDLOG_WARN("Failed to remove stale lfs_error.txt at {}: {}. May interfere with resume/clone detection.",
errorFilePath.string(), ec.message());
}
}
}
} // namespace libgit2
namespace {
std::atomic<int> g_activeLibgit2Guards{0};
/**
* Sets the LFS (Large File Storage) cancellation flag.
* This signal is checked by the patched libgit2 library to abort ongoing LFS downloads.
*/
static void setLfsCancelRequested(int value) {
git_lfs_cancel_set(value != 0 ? 1 : 0);
}
#define RETURN_IF_OVMS_CLONE_CANCELLED() \
do { \
if (libgit2::isCloneCancellationRequestedFromServer()) { \
setLfsCancelRequested(1); \
return -1; \
} \
} while (0)
int checkCloneCancellationTransferProgressCallback(const git_indexer_progress*, void*) {
RETURN_IF_OVMS_CLONE_CANCELLED();
return 0;
}
int checkCloneCancellationSidebandProgressCallback(const char*, int, void*) {
RETURN_IF_OVMS_CLONE_CANCELLED();
return 0;
}
int checkCloneCancellationUpdateTipsCallback(const char*, const git_oid*, const git_oid*, void*) {
RETURN_IF_OVMS_CLONE_CANCELLED();
return 0;
}
/**
* Callback fired during git checkout to notify about files being modified in the working tree.
* Raised when files are created, updated, or deleted during clone or checkout operations.
*
* @param why Notification type (GIT_CHECKOUT_NOTIFY_*) indicating what changed.
* @param path Path of the file being checked out in the working directory.
* @param baseline Diff file info at HEAD (unused).
* @param target Diff file info being checked out (unused).
* @param workdir Current working directory file state (unused).
* @param payload User-supplied payload pointer (unused).
* @return -1 if cancellation requested (aborts checkout), 0 otherwise.
* @note Works on the git repository working directory; modifies local filesystem.
*/
int checkCloneCancellationCheckoutNotifyCallback(git_checkout_notify_t,
const char*,
const git_diff_file*,
const git_diff_file*,
const git_diff_file*,
void*) {
RETURN_IF_OVMS_CLONE_CANCELLED();
return 0;
}
} // namespace
/**
* Callback for acquiring authentication credentials during git clone operations.
* Attempts to use HF_TOKEN environment variable for Hugging Face authentication.
*
* @param out [out] Pointer to git_credential structure to fill with credentials.
* @param url The repository URL requiring authentication.
* @param username_from_url Username parsed from URL (if any).
* @param allowed_types Bitmask of credential types supported by the remote.
* @param payload User-supplied payload pointer (unused).
* @return 0 on success, -1 on error, 1 if credential type not supported.
* @note Connects to internet for authentication; reads HF_TOKEN environment variable.
* @note Limited LFS support: LFS downloads may fail if HF_TOKEN is not set.
*/
int cred_acquire_cb(git_credential** out,
const char* /*url*/,
const char* /*username_from_url*/,
unsigned int allowed_types,
void* /*payload*/) {
char *username = NULL, *password = NULL;
int error = -1;
fprintf(stdout, "Authentication is required for repository clone or model is missing.\n");
if (allowed_types & GIT_CREDENTIAL_USERPASS_PLAINTEXT) {
const char* env_cred = std::getenv("HF_TOKEN");
if (env_cred) {
#ifdef __linux__
username = strdup(env_cred);
password = strdup(username);
#elif _WIN32
username = _strdup(env_cred);
password = _strdup(username);
#endif
} else {
fprintf(stderr, "[ERROR] HF_TOKEN env variable is not set.\n");
return -1;
}
error = git_credential_userpass_plaintext_new(out, username, password);
if (error < 0) {
fprintf(stderr, "[ERROR] Creating credentials failed.\n");
error = -1;
}
} else {
fprintf(stderr, "[ERROR] Only USERPASS_PLAINTEXT supported in OVMS.\n");
return 1;
}
free(username);
free(password);
return error;
}
// C-style callback functions section used in libgt2 library ENDS ********************************
#define IF_ERROR_SET_MSG_AND_RETURN() \
do { \
if (this->status < 0) { \
const git_error* err = git_error_last(); \
const char* msg = err ? err->message : "unknown failure"; \
errMsg = std::string(msg); \
return; \
} else { \
errMsg = ""; \
} \
} while (0)
/**
* Initializes the libgit2 library with server connection settings.
* Sets timeouts for server connections and LFS operations, and configures SSL certificate locations.
* Maintains a reference count of active guards to ensure single initialization.
*
* @param opts Configuration options including server timeouts and SSL certificate path.
* @note Thread-safe initialization; uses atomic counter to track active guards.
* @note Connects to internet: configures timeouts for remote git/LFS operations.
*/
Libgt2InitGuard::Libgt2InitGuard(const Libgit2Options& opts) {
SPDLOG_DEBUG("Initializing libgit2");
this->status = git_libgit2_init();
IF_ERROR_SET_MSG_AND_RETURN();
SPDLOG_TRACE("Setting libgit2 server connection timeout:{}", opts.serverConnectTimeoutMs);
this->status = git_libgit2_opts(GIT_OPT_SET_SERVER_CONNECT_TIMEOUT, opts.serverConnectTimeoutMs);
IF_ERROR_SET_MSG_AND_RETURN();
SPDLOG_TRACE("Setting libgit2 server timeout:{}", opts.serverTimeoutMs);
this->status = git_libgit2_opts(GIT_OPT_SET_SERVER_TIMEOUT, opts.serverTimeoutMs);
IF_ERROR_SET_MSG_AND_RETURN();
if (opts.sslCertificateLocation != "") {
SPDLOG_TRACE("Setting libgit2 ssl certificate location:{}", opts.sslCertificateLocation);
this->status = git_libgit2_opts(GIT_OPT_SET_SSL_CERT_LOCATIONS, NULL, opts.sslCertificateLocation.c_str());
IF_ERROR_SET_MSG_AND_RETURN();
}
this->countedAsInitialized = true;
g_activeLibgit2Guards.fetch_add(1, std::memory_order_relaxed);
}
Libgt2InitGuard::~Libgt2InitGuard() {
SPDLOG_DEBUG("Shutdown libgit2");
if (this->countedAsInitialized) {
g_activeLibgit2Guards.fetch_sub(1, std::memory_order_relaxed);
}
git_libgit2_shutdown();
}
const std::string PROTOCOL_SEPARATOR = "://";
bool HfDownloader::CheckIfProxySet() {
if (this->httpProxy != "")
return true;
return false;
}
std::string HfDownloader::GetRepositoryUrlWithPassword() {
std::string repoPass = "";
if (this->hfToken != "") {
repoPass += this->hfToken + ":" + this->hfToken + "@";
} else {
SPDLOG_DEBUG("HF_TOKEN environment variable not set");
return this->hfEndpoint + this->sourceModel;
}
std::string outputWithPass = "";
size_t match = this->hfEndpoint.find(PROTOCOL_SEPARATOR);
if (match != std::string::npos) {
// https://huggingface.co
// protocol[match]//address
std::string protocol = this->hfEndpoint.substr(0, match);
std::string address = this->hfEndpoint.substr(match + PROTOCOL_SEPARATOR.size());
outputWithPass = protocol + PROTOCOL_SEPARATOR + repoPass + address + this->sourceModel;
} else {
outputWithPass = repoPass + this->hfEndpoint + this->sourceModel;
}
return outputWithPass;
}
std::string HfDownloader::GetRepoUrl() {
std::string repoUrl = "";
repoUrl += this->hfEndpoint + this->sourceModel;
return repoUrl;
}
HfDownloader::HfDownloader(const std::string& inSourceModel, const std::string& inDownloadPath, const std::string& inHfEndpoint, const std::string& inHfToken, const std::string& inHttpProxy, bool inOverwrite) :
IModelDownloader(inSourceModel, inDownloadPath, inOverwrite),
hfEndpoint(inHfEndpoint),
hfToken(inHfToken),
httpProxy(inHttpProxy) {}
Status HfDownloader::RemoveReadonlyFileAttributeFromDir(const std::string& directoryPath) {
for (const std::filesystem::directory_entry& dir_entry : std::filesystem::recursive_directory_iterator(directoryPath)) {
try {
std::filesystem::permissions(dir_entry, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write, std::filesystem::perm_options::add);
} catch (const std::exception& e) {
SPDLOG_ERROR("Failed to set permission for: {} .Exception caught: {}", dir_entry.path().string(), e.what());
return StatusCode::PATH_INVALID;
}
}
return StatusCode::OK;
}
class GitRepositoryGuard {
public:
git_repository* repo = nullptr;
int git_error_class = 0;
/**
* Opens a git repository at the specified filesystem path.
*
* @param path Absolute or relative path to the git repository directory.
* @note Opens the repository only at the provided path; parent directories
* are not searched for a .git directory.
*/
explicit GitRepositoryGuard(const std::string& path) {
// GIT_REPOSITORY_OPEN_NO_SEARCH: open the repository ONLY at `path`.
// Without this flag (i.e. flags=0) libgit2 walks up the parent directory
// tree looking for a .git, which on hosts where the model directory is
// nested under another git checkout (e.g. Jenkins workspace) would
// misidentify the outer repo as ours and skip the download silently.
int error = git_repository_open_ext(&repo, path.c_str(), GIT_REPOSITORY_OPEN_NO_SEARCH, nullptr);
if (error < 0) {
const git_error* err = git_error_last();
if (err) {
SPDLOG_ERROR("Repository open failed: {} {}", err->klass, err->message);
git_error_class = err->klass;
} else {
SPDLOG_ERROR("Repository open failed: {}", error);
}
if (repo) {
git_repository_free(repo);
repo = nullptr;
}
}
}
/**
* Destructor: safely releases the git repository resource.
*/
~GitRepositoryGuard() {
if (repo) {
git_repository_free(repo);
}
}
// Allow implicit access to the raw pointer
git_repository* get() const { return repo; }
operator git_repository*() const { return repo; }
// Non-copyable
GitRepositoryGuard(const GitRepositoryGuard&) = delete;
GitRepositoryGuard& operator=(const GitRepositoryGuard&) = delete;
// Movable
GitRepositoryGuard(GitRepositoryGuard&& other) noexcept {
repo = other.repo;
other.repo = nullptr;
}
GitRepositoryGuard& operator=(GitRepositoryGuard&& other) noexcept {
if (this != &other) {
if (repo)
git_repository_free(repo);
repo = other.repo;
other.repo = nullptr;
}
return *this;
}
};
namespace {
Status mapRepositoryOpenFailureToStatus(const GitRepositoryGuard& repoGuard) {
if (repoGuard.git_error_class == GIT_ERROR_OS)
return StatusCode::HF_GIT_STATUS_FAILED_TO_RESOLVE_PATH;
if (repoGuard.git_error_class == GIT_ERROR_INVALID)
return StatusCode::HF_GIT_LIBGIT2_NOT_INITIALIZED;
return StatusCode::HF_GIT_STATUS_FAILED;
}
} // namespace
/**
* Verifies the cleanliness of a git repository after clone or download operations.
* Checks for staged changes, unstaged modifications, untracked files, and merge conflicts.
*
* @param checkUntracked If true, also check for untracked files (more expensive on large repos).
* @return StatusCode::OK if repository is clean, StatusCode::HF_GIT_STATUS_UNCLEAN if changes exist,
* or error status if repository check fails.
* @note Works on specific git repository (at downloadPath);scans the entire working directory.
* @note Part of the git domain: analyzes HEAD state, index, and working directory.
*/
Status HfDownloader::CheckRepositoryStatus(bool checkUntracked) {
if (g_activeLibgit2Guards.load(std::memory_order_relaxed) <= 0) {
return StatusCode::HF_GIT_LIBGIT2_NOT_INITIALIZED;
}
GitRepositoryGuard repoGuard(this->downloadPath);
if (!repoGuard.get()) {
return mapRepositoryOpenFailureToStatus(repoGuard);
}
// HEAD state info
bool is_detached = git_repository_head_detached(repoGuard.get()) == 1;
bool is_unborn = git_repository_head_unborn(repoGuard.get()) == 1;
// Collect status (staged/unstaged/untracked)
git_status_options opts = GIT_STATUS_OPTIONS_INIT;
opts.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
opts.flags = GIT_STATUS_OPT_SORT_CASE_SENSITIVELY;
if (checkUntracked) {
// Include untracked files only when requested, as this can be expensive on large repositories.
opts.flags |= GIT_STATUS_OPT_INCLUDE_UNTRACKED; // | GIT_STATUS_OPT_RENAMES_HEAD_TO_INDEX // detect renames HEAD->index - not required currently and impacts performance
}
git_status_list* status_list = nullptr;
int error = git_status_list_new(&status_list, repoGuard.get(), &opts);
if (error != 0) {
return StatusCode::HF_GIT_STATUS_FAILED;
}
size_t staged = 0, unstaged = 0, untracked = 0, conflicted = 0;
const size_t n = git_status_list_entrycount(status_list); // iterate entries
for (size_t i = 0; i < n; ++i) {
const git_status_entry* e = git_status_byindex(status_list, i);
if (!e)
continue;
unsigned s = e->status;
// Staged (index) changes
if (s & (GIT_STATUS_INDEX_NEW |
GIT_STATUS_INDEX_MODIFIED |
GIT_STATUS_INDEX_DELETED |
GIT_STATUS_INDEX_RENAMED |
GIT_STATUS_INDEX_TYPECHANGE))
++staged;
// Unstaged (workdir) changes
if (s & (GIT_STATUS_WT_MODIFIED |
GIT_STATUS_WT_DELETED |
GIT_STATUS_WT_RENAMED |
GIT_STATUS_WT_TYPECHANGE))
++unstaged;
// Untracked
if (s & GIT_STATUS_WT_NEW)
++untracked;
// libgit2 will also flag conflicted entries via status/diff machinery
if (s & GIT_STATUS_CONFLICTED)
++conflicted;
}
std::stringstream ss;
ss << "HEAD state : "
<< (is_unborn ? "unborn (no commits)" : (is_detached ? "detached" : "attached"))
<< "\n";
ss << "Staged changes : " << staged << "\n";
ss << "Unstaged changes: " << unstaged << "\n";
ss << "Untracked files : " << untracked << "\n";
if (conflicted)
ss << " (" << conflicted << " paths flagged)";
SPDLOG_DEBUG(ss.str());
git_status_list_free(status_list);
// We do not care about untracked until after git clone
if (is_unborn || is_detached || staged || unstaged || conflicted || (checkUntracked && untracked)) {
return StatusCode::HF_GIT_STATUS_UNCLEAN;
}
return StatusCode::OK;
}
namespace libgit2 {
bool isCloneCancellationRequestedFromServer() {
if (isSignalShutdownRequested()) {
processSignalShutdownRequest();
setLfsCancelRequested(getShutdownRequestValue());
}
return getShutdownRequestValue() != 0;
}
bool hasLfsErrorFile(const std::string& repositoryRootPath) {
const fs::path errorFilePath = fs::path(repositoryRootPath) / "lfs_error.txt";
std::error_code ec;
return fs::exists(errorFilePath, ec) && fs::is_regular_file(errorFilePath, ec);
}
void rtrimCrLfWhitespace(std::string& s) {
auto isAsciiWhitespace = [](unsigned char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
};
while (!s.empty() && isAsciiWhitespace(static_cast<unsigned char>(s.back())))
s.pop_back(); // trailing ws
size_t i = 0;
while (i < s.size() && isAsciiWhitespace(static_cast<unsigned char>(s[i])))
++i; // leading ws
if (i > 0)
s.erase(0, i);
}
bool containsCaseInsensitive(const std::string& hay, const std::string& needle) {
auto toLower = [](std::string v) {
std::transform(v.begin(), v.end(), v.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return v;
};
std::string hayLower = toLower(hay);
std::string needleLower = toLower(needle);
return hayLower.find(needleLower) != std::string::npos;
}
bool readFirstThreeLines(const std::filesystem::path& p, std::vector<std::string>& out, size_t maxLineBytes) {
out.clear();
if (maxLineBytes == 0)
return false;
std::ifstream in(p, std::ios::binary);
if (!in)
return false;
std::string line;
line.reserve(256); // small optimization
int c;
while (out.size() < 3 && (c = in.get()) != EOF) {
if (c == '\r') {
// Handle CR or CRLF as one line ending
int next = in.peek();
if (next == '\n') {
in.get(); // consume '\n'
}
// finalize current line
rtrimCrLfWhitespace(line);
out.push_back(std::move(line));
line.clear();
} else if (c == '\n') {
// LF line ending
rtrimCrLfWhitespace(line);
out.push_back(std::move(line));
line.clear();
} else {
line.push_back(static_cast<char>(c));
if (line.size() > maxLineBytes) {
out.clear();
return false;
}
}
}
// Handle the last line if file did not end with EOL
if (!line.empty() && out.size() < 3) {
rtrimCrLfWhitespace(line);
out.push_back(std::move(line));
}
return true;
}
bool fileHasLfsKeywordsFirst3Positional(const fs::path& p) {
std::error_code ec;
if (!fs::is_regular_file(p, ec))
return false;
std::vector<std::string> lines;
if (!readFirstThreeLines(p, lines))
return false;
if (lines.size() < 3)
return false;
return containsCaseInsensitive(lines[0], "version") &&
containsCaseInsensitive(lines[1], "oid") &&
containsCaseInsensitive(lines[2], "size");
}
bool hasLfsKeywordsFirst3Positional(std::string_view content) {
std::array<std::string, 3> lines;
size_t lineIndex = 0;
size_t position = 0;
while (lineIndex < lines.size() && position < content.size()) {
size_t next = content.find_first_of("\r\n", position);
auto line = content.substr(position, next == std::string_view::npos ? content.size() - position : next - position);
lines[lineIndex] = std::string(line);
rtrimCrLfWhitespace(lines[lineIndex]);
++lineIndex;
if (next == std::string_view::npos)
break;
position = next + 1;
if (next + 1 < content.size() && content[next] == '\r' && content[next + 1] == '\n')
++position;
}
if (lineIndex < lines.size())
return false;
return containsCaseInsensitive(lines[0], "version") &&
containsCaseInsensitive(lines[1], "oid") &&
containsCaseInsensitive(lines[2], "size");
}
bool blobHasLfsKeywordsFirst3Positional(git_blob* blob) {
if (!blob)
return false;
const void* raw = git_blob_rawcontent(blob);
if (!raw)
return false;
size_t rawSize = git_blob_rawsize(blob);
return hasLfsKeywordsFirst3Positional(std::string_view(static_cast<const char*>(raw), rawSize));
}
fs::path makeRelativeToBase(const fs::path& path, const fs::path& base) {
// Root-like paths (e.g. "/" or "C:\\") have no filename component.
// Keep them unchanged instead of converting to a cwd/base-dependent ".." chain.
if (!path.has_filename())
return path;
std::error_code ec;
// Try fs::relative first (handles canonical comparisons, may fail if on different roots)
fs::path rel = fs::relative(path, base, ec);
if (!ec && !rel.empty())
return rel;
// Fallback: purely lexical relative (doesn't access filesystem)
rel = path.lexically_relative(base);
if (!rel.empty())
return rel;
// Last resort: return filename only (better than absolute when nothing else works)
if (path.has_filename())
return path.filename();
return path;
}
/**
* Recursively/non-recursively searches a directory for files matching the LFS pointer format.
* Skips .git directories to avoid searching the repository metadata.
*
* @param directory Root directory to search for LFS-like files.
* @param recursive If true, search subdirectories; if false, only search directory root.
* @return Vector of relative paths (relative to directory) of files matching LFS format.
* @note Works on local filesystem; scans directory tree (may be expensive on large repos).
* @note Part of the git LFS domain: identifies LFS pointer files in the working directory.
*/
std::vector<fs::path> findLfsLikeFiles(const std::string& directory, bool recursive) {
std::vector<fs::path> matches;
try {
std::error_code ec;
if (!fs::exists(directory, ec) || !fs::is_directory(directory, ec)) {
return matches;
}
if (recursive) {
for (fs::recursive_directory_iterator it(directory), end; it != end; ++it) {
const auto& p = it->path();
std::error_code dirEc;
if (it->is_directory(dirEc) && !dirEc && p.filename() == ".git") {
it.disable_recursion_pending();
continue;
}
if (fileHasLfsKeywordsFirst3Positional(p)) {
matches.push_back(makeRelativeToBase(p, directory));
}
}
} else {
for (fs::directory_iterator it(directory), end; it != end; ++it) {
const auto& p = it->path();
if (fileHasLfsKeywordsFirst3Positional(p)) {
matches.push_back(makeRelativeToBase(p, directory));
}
}
}
return matches;
} catch (const fs::filesystem_error& e) {
const std::error_code code = e.code();
const bool expectedTransient =
(code == std::make_error_code(std::errc::no_such_file_or_directory)) ||
(code == std::make_error_code(std::errc::not_a_directory));
SPDLOG_WARN("findLfsLikeFiles {} {} recursive={} error:{}; returning {} partial match(es)",
expectedTransient ? "directory contents changed during scan" : "failed while scanning",
directory,
recursive,
e.what(),
matches.size());
} catch (const std::exception& e) {
SPDLOG_WARN("findLfsLikeFiles failed while scanning {} recursive={} error:{}; returning {} partial match(es)",
directory,
recursive,
e.what(),
matches.size());
}
return matches;
}
struct MissingLfsPathsWalkPayload {
git_repository* repo;
fs::path worktreeRoot;
std::set<fs::path>* matches;
};
struct MissingNonLfsPathsWalkPayload {
git_repository* repo;
fs::path worktreeRoot;
std::set<fs::path>* matches;
};
/**
* Tree-walk callback that collects paths from HEAD tree that have LFS pointers but missing worktree files.
* Used to identify LFS files that need to be downloaded/resumed during clone recovery.
*
* @param root Current directory path in the tree traversal (accumulates parent directories).
* @param entry Current git_tree_entry being visited.
* @param payloadPtr Pointer to MissingLfsPathsWalkPayload containing repo, worktree path, and output set.
* @return 0 to continue tree walk; non-zero aborts the walk.
* @note Works on git repository object database (ODB) and working directory.
* @note Part of the git domain: walks the HEAD commit tree to find tracked LFS files.
*/
int collectMissingLfsPathsFromHeadTreeCb(const char* root, const git_tree_entry* entry, void* payloadPtr) {
auto* payload = reinterpret_cast<MissingLfsPathsWalkPayload*>(payloadPtr);
if (!payload || git_tree_entry_type(entry) != GIT_OBJECT_BLOB)
return 0;
fs::path relativePath = fs::path(root ? root : "") / git_tree_entry_name(entry);
std::error_code ec;
if (fs::exists(payload->worktreeRoot / relativePath, ec))
return 0;
git_blob* blob = nullptr;
if (git_blob_lookup(&blob, payload->repo, git_tree_entry_id(entry)) != 0)
return 0;
std::unique_ptr<git_blob, decltype(&git_blob_free)> blobGuard(blob, git_blob_free);
if (blobHasLfsKeywordsFirst3Positional(blob))
payload->matches->insert(relativePath);
return 0;
}
/**
* Tree-walk callback that collects missing tracked non-LFS files from HEAD tree.
* Paths are included only when missing in worktree and blob is not an LFS pointer.
*
* @param root Current directory path in the tree traversal.
* @param entry Current git_tree_entry being visited.
* @param payloadPtr Pointer to MissingNonLfsPathsWalkPayload with output set.
* @return 0 to continue walk; non-zero aborts traversal.
* @note Works on git object database and local worktree metadata.
*/
int collectMissingNonLfsPathsFromHeadTreeCb(const char* root, const git_tree_entry* entry, void* payloadPtr) {
auto* payload = reinterpret_cast<MissingNonLfsPathsWalkPayload*>(payloadPtr);
if (!payload || git_tree_entry_type(entry) != GIT_OBJECT_BLOB)
return 0;
fs::path relativePath = fs::path(root ? root : "") / git_tree_entry_name(entry);
std::error_code ec;
if (fs::exists(payload->worktreeRoot / relativePath, ec))
return 0;
git_blob* blob = nullptr;
if (git_blob_lookup(&blob, payload->repo, git_tree_entry_id(entry)) != 0)
return 0;
std::unique_ptr<git_blob, decltype(&git_blob_free)> blobGuard(blob, git_blob_free);
if (!blobHasLfsKeywordsFirst3Positional(blob))
payload->matches->insert(relativePath);
return 0;
}
/**
* Identifies LFS files that are safe to resume downloading after interruption.
* Combines working directory LFS pointers with missing LFS blobs from the HEAD tree.
* Useful for recovery after abrupt clone termination.
*
* @param repo Pointer to the git repository object.
* @param directory Root directory of the git working tree to search.
* @param parseHeadTreeIfInterrupted If true, also scan HEAD tree for missing tracked LFS blobs.
* @return Vector of relative paths to all resumable LFS files needing download completion.
* @note Works on specific git repository; scans both working directory and object database.
* @note Part of the git LFS domain: identifies candidates for partial-clone recovery.
*/
std::vector<fs::path> findResumableLfsFiles(git_repository* repo, const std::string& directory, bool parseHeadTreeIfInterrupted) {
std::set<fs::path> uniqueMatches;
auto existingMatches = findLfsLikeFiles(directory, true);
uniqueMatches.insert(existingMatches.begin(), existingMatches.end());
if (parseHeadTreeIfInterrupted) {
git_object* headTreeObject = nullptr;
if (git_revparse_single(&headTreeObject, repo, "HEAD^{tree}") == 0) {
std::unique_ptr<git_object, decltype(&git_object_free)> headTreeGuard(headTreeObject, git_object_free);
MissingLfsPathsWalkPayload payload{repo, fs::path(directory), &uniqueMatches};
(void)git_tree_walk(reinterpret_cast<git_tree*>(headTreeObject), GIT_TREEWALK_PRE, collectMissingLfsPathsFromHeadTreeCb, &payload);
}
}
return std::vector<fs::path>(uniqueMatches.begin(), uniqueMatches.end());
}
/**
* Finds tracked non-LFS files present in HEAD but missing in worktree.
* Used during resume flow to restore required metadata/config artifacts.
*
* @param repo Pointer to the git repository object.
* @param directory Repository worktree root directory.
* @return Vector of relative paths for missing tracked non-LFS files.
* @note Works on specific git repository; scans HEAD tree and filesystem.
*/
std::vector<fs::path> findMissingTrackedNonLfsFiles(git_repository* repo, const std::string& directory) {
std::set<fs::path> uniqueMatches;
git_object* headTreeObject = nullptr;
if (git_revparse_single(&headTreeObject, repo, "HEAD^{tree}") == 0) {
std::unique_ptr<git_object, decltype(&git_object_free)> headTreeGuard(headTreeObject, git_object_free);
MissingNonLfsPathsWalkPayload payload{repo, fs::path(directory), &uniqueMatches};
(void)git_tree_walk(reinterpret_cast<git_tree*>(headTreeObject), GIT_TREEWALK_PRE, collectMissingNonLfsPathsFromHeadTreeCb, &payload);
}
return std::vector<fs::path>(uniqueMatches.begin(), uniqueMatches.end());
}
/**
* Checks for LFS download errors recorded by libgit2 patch in the repository root.
* Reads and logs error messages from lfs_error.txt, then removes the file for cleanup.
*
* @param repositoryRootPath Absolute path to the git repository root directory.
* @return true if error file exists (even if unreadable); false if no error file found.
* @note Works on specific git repository location; reads and deletes lfs_error.txt.
* @note Part of the git LFS domain: detects LFS download failures recorded by patched libgit2.
*/
bool ifHasLfsErrorFileLogContentAndRemove(const std::string& repositoryRootPath) {
const fs::path errorFilePath = fs::path(repositoryRootPath) / "lfs_error.txt";
std::error_code ec;
if (!fs::exists(errorFilePath, ec) || !fs::is_regular_file(errorFilePath, ec)) {
return false;
}
std::ifstream errorFile(errorFilePath, std::ios::binary);
if (!errorFile) {
SPDLOG_ERROR("Detected lfs_error.txt but failed to open file: {}", errorFilePath.string());
// Still attempt to remove the stale error file for clean state
fs::remove(errorFilePath, ec);
return true;
}
std::ostringstream content;
content << errorFile.rdbuf();
errorFile.close();
SPDLOG_ERROR("{}", content.str());
// Remove the error file to ensure clean state for subsequent download/resume attempts
std::error_code removeEc;
if (fs::remove(errorFilePath, removeEc)) {
SPDLOG_DEBUG("Removed lfs_error.txt from repository root");
} else if (removeEc) {
SPDLOG_WARN("Failed to remove lfs_error.txt: {}", removeEc.message());
}
return true;
}
} // namespace libgit2
/**
* Restores missing tracked non-LFS files after interrupted clone/resume.
* Rebuilds index entries from HEAD and checks out selected paths into worktree.
*
* @param repo Pointer to the git repository object.
* @param missingPaths Relative paths of tracked non-LFS files missing in worktree.
* @return StatusCode::OK on success, cancellation/error status otherwise.
* @note Works on repository index and working directory; does not download data from remote.
*/
Status restoreMissingTrackedNonLfsFiles(git_repository* repo, const std::vector<fs::path>& missingPaths) {
if (missingPaths.empty())
return StatusCode::OK;
auto runGitCall = [&](int rc, const char* callName) -> Status {
if (rc >= 0) {
return StatusCode::OK;
}
if (libgit2::isCloneCancellationRequestedFromServer() || rc == GIT_EUSER) {
setLfsCancelRequested(1);
SPDLOG_DEBUG("Pull restore cancelled for non-lfs filesin {}.", callName);
return StatusCode::HF_GIT_CLONE_CANCELLED;
}
const git_error* e = git_error_last();
SPDLOG_ERROR("Pull restore failed for non-lfs files in {} rc:{} msg:{}", callName, rc, e && e->message ? e->message : "no message");
return StatusCode::HF_GIT_STATUS_FAILED;
};
// Repair index entries from HEAD for missing tracked non-LFS files before checkout.
// Interrupted clone may leave these paths absent in index, which later surfaces as staged changes.
{
git_object* headObj = nullptr;
if (auto s = runGitCall(git_revparse_single(&headObj, repo, "HEAD^{tree}"), "git_revparse_single"); !s.ok())
return s;
auto headGuard = std::unique_ptr<git_object, decltype(&git_object_free)>{headObj, git_object_free};
git_tree* headTree = reinterpret_cast<git_tree*>(headObj);
git_index* index = nullptr;
if (auto s = runGitCall(git_repository_index(&index, repo), "git_repository_index"); !s.ok())
return s;
auto indexGuard = std::unique_ptr<git_index, decltype(&git_index_free)>{index, git_index_free};
std::vector<std::string> repairedPaths;
repairedPaths.reserve(missingPaths.size());
for (const auto& p : missingPaths) {
std::string path = p.generic_string();
git_tree_entry* treeEntry = nullptr;
if (auto s = runGitCall(git_tree_entry_bypath(&treeEntry, headTree, path.c_str()), "git_tree_entry_bypath"); !s.ok())
return s;
auto treeEntryGuard = std::unique_ptr<git_tree_entry, decltype(&git_tree_entry_free)>{treeEntry, git_tree_entry_free};
git_index_entry idxEntry = {};
idxEntry.id = *git_tree_entry_id(treeEntry);
idxEntry.mode = git_tree_entry_filemode_raw(treeEntry);
idxEntry.path = path.c_str();
if (auto s = runGitCall(git_index_add(index, &idxEntry), "git_index_add"); !s.ok())
return s;
repairedPaths.emplace_back(std::move(path));
}
if (auto s = runGitCall(git_index_write(index), "git_index_write"); !s.ok())
return s;
}
std::vector<std::string> ownedPaths;
ownedPaths.reserve(missingPaths.size());
for (const auto& p : missingPaths) {
ownedPaths.emplace_back(p.generic_string());
}
std::vector<char*> checkoutPaths;
checkoutPaths.reserve(ownedPaths.size());
for (auto& p : ownedPaths) {
checkoutPaths.push_back(const_cast<char*>(p.c_str()));
}