KiCad PCB EDA Suite
Loading...
Searching...
No Matches
libgit_backend.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright The KiCad Developers, see AUTHORS.TXT for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 3
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, you may find one here:
18 * http://www.gnu.org/licenses/gpl-3.0.html
19 * or you may search the http://www.gnu.org website for the version 3 license,
20 * or you may write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 */
23
24#include "libgit_backend.h"
25
26#include "git_clone_handler.h"
27#include "git_commit_handler.h"
28#include "git_push_handler.h"
31#include "git_status_handler.h"
32#include "git_config_handler.h"
33#include "git_init_handler.h"
34#include "git_branch_handler.h"
35#include "git_pull_handler.h"
36#include "git_revert_handler.h"
37#include "project_git_utils.h"
38#include "kicad_git_common.h"
39#include "kicad_git_memory.h"
40#include "trace_helpers.h"
41
42#include "kicad_git_compat.h"
43#include <wx/filename.h>
44#include <wx/log.h>
45#include <gestfich.h>
46#include <algorithm>
47#include <iterator>
48#include <memory>
49#include <time.h>
50
51static std::string getFirstLineFromCommitMessage( const std::string& aMessage )
52{
53 if( aMessage.empty() )
54 return aMessage;
55
56 size_t firstLineEnd = aMessage.find_first_of( '\n' );
57
58 if( firstLineEnd != std::string::npos )
59 return aMessage.substr( 0, firstLineEnd );
60
61 return aMessage;
62}
63
64
65static std::string getFormattedCommitDate( const git_time& aTime )
66{
67 char dateBuffer[64];
68 time_t time = static_cast<time_t>( aTime.time );
69 struct tm timeInfo;
70
71#ifdef _WIN32
72 localtime_s( &timeInfo, &time );
73#else
74 gmtime_r( &time, &timeInfo );
75#endif
76
77 strftime( dateBuffer, sizeof( dateBuffer ), "%Y-%b-%d %H:%M:%S", &timeInfo );
78 return dateBuffer;
79}
80
81
83{
84 git_libgit2_init();
85}
86
87
89{
90 // Wait for any abandoned git cleanup threads to finish before tearing
91 // down libgit2. A worker still inside libgit2 (for example, blocked on
92 // recv() under git_remote_fetch) would otherwise race teardown and
93 // invoke undefined behaviour. Five seconds is long enough to cover a
94 // transport error timeout but short enough to avoid a perceptibly slow
95 // exit when the remote is truly unreachable.
96
97 constexpr auto kOrphanJoinTimeout = std::chrono::seconds( 5 );
98 size_t stuck = m_orphanRegistry.JoinAll( kOrphanJoinTimeout );
99
100 if( stuck > 0 )
101 {
102 wxLogTrace( traceGit,
103 "LIBGIT_BACKEND::Shutdown(): %zu orphan git thread(s) "
104 "did not finish within %lld ms; skipping libgit2 shutdown",
105 stuck,
106 static_cast<long long>( kOrphanJoinTimeout.count() ) );
107
108 // A stuck worker is still executing inside libgit2. Calling
109 // git_libgit2_shutdown() now would free state the worker is actively
110 // reading. Leave libgit2 initialised and let the OS reclaim
111 // resources when the process exits.
112
113 return;
114 }
115
116 git_libgit2_shutdown();
117}
118
119
121{
122#if ( LIBGIT2_VER_MAJOR >= 1 ) || ( LIBGIT2_VER_MINOR >= 99 )
123 int major = 0, minor = 0, rev = 0;
124 return git_libgit2_version( &major, &minor, &rev ) == GIT_OK;
125#else
126 // On older platforms, assume available when building with libgit2
127 return true;
128#endif
129}
130
131
133{
134 KIGIT_COMMON* common = aHandler->GetCommon();
135 std::unique_lock<std::mutex> lock( common->m_gitActionMutex, std::try_to_lock );
136
137 if( !lock.owns_lock() )
138 {
139 wxLogTrace( traceGit, "GIT_CLONE_HANDLER::PerformClone() could not lock" );
140 return false;
141 }
142
143 wxFileName clonePath( aHandler->GetClonePath() );
144
145 if( !clonePath.DirExists() )
146 {
147 if( !clonePath.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
148 {
149 aHandler->AddErrorString( wxString::Format( _( "Could not create directory '%s'" ),
150 aHandler->GetClonePath() ) );
151 return false;
152 }
153 }
154
155 git_clone_options cloneOptions;
156 git_clone_init_options( &cloneOptions, GIT_CLONE_OPTIONS_VERSION );
157 cloneOptions.checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE;
158 cloneOptions.checkout_opts.progress_cb = clone_progress_cb;
159 cloneOptions.checkout_opts.progress_payload = aHandler;
160 cloneOptions.fetch_opts.callbacks.transfer_progress = transfer_progress_cb;
161 cloneOptions.fetch_opts.callbacks.credentials = credentials_cb;
162 cloneOptions.fetch_opts.callbacks.payload = aHandler;
163
164 aHandler->TestedTypes() = 0;
165 aHandler->ResetNextKey();
166 git_repository* newRepo = nullptr;
167 wxString remote = common->m_remote;
168
169 if( git_clone( &newRepo, remote.mbc_str(), aHandler->GetClonePath().mbc_str(),
170 &cloneOptions ) != 0 )
171 {
172 aHandler->AddErrorString( wxString::Format( _( "Could not clone repository '%s' : %s" ), remote, KIGIT_COMMON::GetLastGitError() ) );
173 return false;
174 }
175
176 common->SetRepo( newRepo );
177
178 return true;
179}
180
181
183 const std::vector<wxString>& aFiles,
184 const wxString& aMessage,
185 const wxString& aAuthorName,
186 const wxString& aAuthorEmail )
187{
188 git_repository* repo = aHandler->GetRepo();
189
190 if( !repo )
191 return CommitResult::Error;
192
193 git_index* index = nullptr;
194
195 if( git_repository_index( &index, repo ) != 0 )
196 {
197 aHandler->AddErrorString( wxString::Format( _( "Failed to get repository index: %s" ),
199 return CommitResult::Error;
200 }
201
202 KIGIT::GitIndexPtr indexPtr( index );
203
204 for( const wxString& file : aFiles )
205 {
206 if( git_index_add_bypath( index, file.mb_str() ) != 0 )
207 {
208 aHandler->AddErrorString( wxString::Format( _( "Failed to add file to index: %s" ),
210 return CommitResult::Error;
211 }
212 }
213
214 if( git_index_write( index ) != 0 )
215 {
216 aHandler->AddErrorString( wxString::Format( _( "Failed to write index: %s" ),
218 return CommitResult::Error;
219 }
220
221 git_oid tree_id;
222
223 if( git_index_write_tree( &tree_id, index ) != 0 )
224 {
225 aHandler->AddErrorString( wxString::Format( _( "Failed to write tree: %s" ),
227 return CommitResult::Error;
228 }
229
230 git_tree* tree = nullptr;
231
232 if( git_tree_lookup( &tree, repo, &tree_id ) != 0 )
233 {
234 aHandler->AddErrorString( wxString::Format( _( "Failed to lookup tree: %s" ),
236 return CommitResult::Error;
237 }
238
239 KIGIT::GitTreePtr treePtr( tree );
240 git_commit* parent = nullptr;
241
242 if( git_repository_head_unborn( repo ) == 0 )
243 {
244 git_reference* headRef = nullptr;
245
246 if( git_repository_head( &headRef, repo ) != 0 )
247 {
248 aHandler->AddErrorString( wxString::Format( _( "Failed to get HEAD reference: %s" ),
250 return CommitResult::Error;
251 }
252
253 KIGIT::GitReferencePtr headRefPtr( headRef );
254
255 if( git_reference_peel( (git_object**) &parent, headRef, GIT_OBJECT_COMMIT ) != 0 )
256 {
257 aHandler->AddErrorString( wxString::Format( _( "Failed to get commit: %s" ),
259 return CommitResult::Error;
260 }
261 }
262
263 KIGIT::GitCommitPtr parentPtr( parent );
264
265 git_signature* author = nullptr;
266
267 if( git_signature_now( &author, aAuthorName.mb_str(), aAuthorEmail.mb_str() ) != 0 )
268 {
269 aHandler->AddErrorString( wxString::Format( _( "Failed to create author signature: %s" ),
271 return CommitResult::Error;
272 }
273
274 KIGIT::GitSignaturePtr authorPtr( author );
275 git_oid oid;
276 size_t parentsCount = parent ? 1 : 0;
277
278#if( LIBGIT2_VER_MAJOR == 1 && LIBGIT2_VER_MINOR == 8 \
279 && ( LIBGIT2_VER_REVISION < 2 || LIBGIT2_VER_REVISION == 3 ) )
280 git_commit* const parents[1] = { parent };
281 git_commit** const parentsPtr = parent ? parents : nullptr;
282#else
283 const git_commit* parents[1] = { parent };
284 const git_commit** parentsPtr = parent ? parents : nullptr;
285#endif
286
287 if( git_commit_create( &oid, repo, "HEAD", author, author, nullptr,
288 aMessage.mb_str(), tree, parentsCount, parentsPtr ) != 0 )
289 {
290 aHandler->AddErrorString( wxString::Format( _( "Failed to create commit: %s" ),
292 return CommitResult::Error;
293 }
294
296}
297
298
300{
301 KIGIT_COMMON* common = aHandler->GetCommon();
302 std::unique_lock<std::mutex> lock( common->m_gitActionMutex, std::try_to_lock );
303
304 if( !lock.owns_lock() )
305 {
306 wxLogTrace( traceGit, "GIT_PUSH_HANDLER::PerformPush: Could not lock mutex" );
307 return PushResult::Error;
308 }
309
311
312 git_remote* remote = nullptr;
313
314 if( git_remote_lookup( &remote, aHandler->GetRepo(), "origin" ) != 0 )
315 {
316 aHandler->AddErrorString( _( "Could not lookup remote" ) );
317 return PushResult::Error;
318 }
319
320 KIGIT::GitRemotePtr remotePtr(remote);
321
322 git_remote_callbacks remoteCallbacks;
323 git_remote_init_callbacks( &remoteCallbacks, GIT_REMOTE_CALLBACKS_VERSION );
324 remoteCallbacks.sideband_progress = progress_cb;
325 remoteCallbacks.transfer_progress = transfer_progress_cb;
326 remoteCallbacks.update_tips = update_cb;
327 remoteCallbacks.push_transfer_progress = push_transfer_progress_cb;
328 remoteCallbacks.credentials = credentials_cb;
329 remoteCallbacks.payload = aHandler;
330 common->SetCancelled( false );
331
332 aHandler->TestedTypes() = 0;
333 aHandler->ResetNextKey();
334
335 if( git_remote_connect( remote, GIT_DIRECTION_PUSH, &remoteCallbacks, nullptr, nullptr ) )
336 {
337 aHandler->AddErrorString( wxString::Format( _( "Could not connect to remote: %s" ),
339 return PushResult::Error;
340 }
341
342 git_push_options pushOptions;
343 git_push_init_options( &pushOptions, GIT_PUSH_OPTIONS_VERSION );
344 pushOptions.callbacks = remoteCallbacks;
345
346 git_reference* head = nullptr;
347
348 if( git_repository_head( &head, aHandler->GetRepo() ) != 0 )
349 {
350 git_remote_disconnect( remote );
351 aHandler->AddErrorString( _( "Could not get repository head" ) );
352 return PushResult::Error;
353 }
354
355 KIGIT::GitReferencePtr headPtr( head );
356
357 const char* refs[1];
358 refs[0] = git_reference_name( head );
359 const git_strarray refspecs = { (char**) refs, 1 };
360
361 if( git_remote_push( remote, &refspecs, &pushOptions ) )
362 {
363 aHandler->AddErrorString( wxString::Format( _( "Could not push to remote: %s" ),
365 git_remote_disconnect( remote );
366 return PushResult::Error;
367 }
368
369 git_remote_disconnect( remote );
370
371 return result;
372}
373
374
376{
377 git_repository* repo = aHandler->GetRepo();
378
379 if( !repo )
380 return false;
381
382 git_status_options opts;
383 git_status_init_options( &opts, GIT_STATUS_OPTIONS_VERSION );
384
385 opts.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
386 opts.flags = GIT_STATUS_OPT_INCLUDE_UNTRACKED | GIT_STATUS_OPT_RENAMES_HEAD_TO_INDEX
387 | GIT_STATUS_OPT_SORT_CASE_SENSITIVELY;
388
389 git_status_list* status_list = nullptr;
390
391 if( git_status_list_new( &status_list, repo, &opts ) != GIT_OK )
392 {
393 wxLogTrace( traceGit, "Failed to get status list: %s", KIGIT_COMMON::GetLastGitError() );
394 return false;
395 }
396
397 KIGIT::GitStatusListPtr status_list_ptr( status_list );
398 bool hasChanges = ( git_status_list_entrycount( status_list ) > 0 );
399
400 return hasChanges;
401}
402
403
404std::map<wxString, FileStatus> LIBGIT_BACKEND::GetFileStatus( GIT_STATUS_HANDLER* aHandler,
405 const wxString& aPathspec )
406{
407 std::map<wxString, FileStatus> fileStatusMap;
408 git_repository* repo = aHandler->GetRepo();
409
410 if( !repo )
411 return fileStatusMap;
412
413 git_status_options status_options;
414 git_status_init_options( &status_options, GIT_STATUS_OPTIONS_VERSION );
415 status_options.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
416 status_options.flags = GIT_STATUS_OPT_INCLUDE_UNTRACKED | GIT_STATUS_OPT_INCLUDE_UNMODIFIED;
417
418 std::string pathspec_str;
419 std::vector<const char*> pathspec_ptrs;
420
421 if( !aPathspec.IsEmpty() )
422 {
423 pathspec_str = aPathspec.ToStdString();
424 pathspec_ptrs.push_back( pathspec_str.c_str() );
425
426 status_options.pathspec.strings = const_cast<char**>( pathspec_ptrs.data() );
427 status_options.pathspec.count = pathspec_ptrs.size();
428 }
429
430 git_status_list* status_list = nullptr;
431
432 if( git_status_list_new( &status_list, repo, &status_options ) != GIT_OK )
433 {
434 wxLogTrace( traceGit, "Failed to get git status list: %s", KIGIT_COMMON::GetLastGitError() );
435 return fileStatusMap;
436 }
437
438 KIGIT::GitStatusListPtr statusListPtr( status_list );
439
440 size_t count = git_status_list_entrycount( status_list );
441 wxString repoWorkDir = aHandler->GetProjectDir();
442
443 for( size_t ii = 0; ii < count; ++ii )
444 {
445 const git_status_entry* entry = git_status_byindex( status_list, ii );
446 std::string path( entry->head_to_index ? entry->head_to_index->old_file.path
447 : entry->index_to_workdir->old_file.path );
448
449 wxString absPath = repoWorkDir + path;
450 fileStatusMap[absPath] = FileStatus{ absPath,
451 aHandler->ConvertStatus( entry->status ),
452 static_cast<unsigned int>( entry->status ) };
453 }
454
455 return fileStatusMap;
456}
457
458
460{
461 git_repository* repo = aHandler->GetRepo();
462
463 if( !repo )
464 return wxEmptyString;
465
466 git_reference* currentBranchReference = nullptr;
467 int rc = git_repository_head( &currentBranchReference, repo );
468 KIGIT::GitReferencePtr currentBranchReferencePtr( currentBranchReference );
469
470 if( currentBranchReference )
471 {
472 return git_reference_shorthand( currentBranchReference );
473 }
474 else if( rc == GIT_EUNBORNBRANCH )
475 {
476 return wxEmptyString;
477 }
478 else
479 {
480 wxLogTrace( traceGit, "Failed to lookup current branch: %s", KIGIT_COMMON::GetLastGitError() );
481 return wxEmptyString;
482 }
483}
484
485
487 const std::set<wxString>& aLocalChanges,
488 const std::set<wxString>& aRemoteChanges,
489 std::map<wxString, FileStatus>& aFileStatus )
490{
491 git_repository* repo = aHandler->GetRepo();
492
493 if( !repo )
494 return;
495
496 wxString repoWorkDir = aHandler->GetProjectDir();
497
498 for( auto& [absPath, fileStatus] : aFileStatus )
499 {
500 wxString relativePath = absPath;
501 if( relativePath.StartsWith( repoWorkDir ) )
502 {
503 relativePath = relativePath.Mid( repoWorkDir.length() );
504
505#ifdef _WIN32
506 relativePath.Replace( wxS( "\\" ), wxS( "/" ) );
507#endif
508 }
509
510 std::string relativePathStd = relativePath.ToStdString();
511
512 if( fileStatus.status == KIGIT_COMMON::GIT_STATUS::GIT_STATUS_CURRENT )
513 {
514 if( aLocalChanges.count( relativePathStd ) )
515 {
517 }
518 else if( aRemoteChanges.count( relativePathStd ) )
519 {
521 }
522 }
523 }
524}
525
526
528{
529 return aHandler->GetProjectDir();
530}
531
532
534{
535 return aHandler->GetProjectDir();
536}
537
538
539bool LIBGIT_BACKEND::GetConfigString( GIT_CONFIG_HANDLER* aHandler, const wxString& aKey, wxString& aValue )
540{
541 git_repository* repo = aHandler->GetRepo();
542
543 if( !repo )
544 return false;
545
546 git_config* config = nullptr;
547
548 if( git_repository_config( &config, repo ) != GIT_OK )
549 {
550 wxLogTrace( traceGit, "Failed to get repository config: %s", KIGIT_COMMON::GetLastGitError() );
551 return false;
552 }
553
554 KIGIT::GitConfigPtr configPtr( config );
555
556 git_config_entry* entry = nullptr;
557 int result = git_config_get_entry( &entry, config, aKey.mb_str() );
558 KIGIT::GitConfigEntryPtr entryPtr( entry );
559
560 if( result != GIT_OK || entry == nullptr )
561 {
562 wxLogTrace( traceGit, "Config key '%s' not found", aKey );
563 return false;
564 }
565
566 aValue = wxString( entry->value );
567 return true;
568}
569
570
571bool LIBGIT_BACKEND::IsRepository( GIT_INIT_HANDLER* aHandler, const wxString& aPath )
572{
573 git_repository* repo = nullptr;
574 int error = git_repository_open( &repo, aPath.mb_str() );
575
576 if( error == 0 )
577 {
578 git_repository_free( repo );
579 return true;
580 }
581
582 return false;
583}
584
585
587{
588 if( IsRepository( aHandler, aPath ) )
589 {
591 }
592
593 git_repository* repo = nullptr;
594
595 if( git_repository_init( &repo, aPath.mb_str(), 0 ) != GIT_OK )
596 {
597 if( repo )
598 git_repository_free( repo );
599
600 aHandler->AddErrorString( wxString::Format( _( "Failed to initialize Git repository: %s" ),
602 return InitResult::Error;
603 }
604
605 aHandler->GetCommon()->SetRepo( repo );
606
607 wxLogTrace( traceGit, "Successfully initialized Git repository at %s", aPath );
608 return InitResult::Success;
609}
610
611
613{
614 if( aConfig.url.IsEmpty() )
615 return true;
616
617 git_repository* repo = aHandler->GetRepo();
618
619 if( !repo )
620 {
621 aHandler->AddErrorString( _( "No repository available to set up remote" ) );
622 return false;
623 }
624
625 aHandler->GetCommon()->SetUsername( aConfig.username );
626 aHandler->GetCommon()->SetPassword( aConfig.password );
627 aHandler->GetCommon()->SetSSHKey( aConfig.sshKey );
628
629 git_remote* remote = nullptr;
630 wxString fullURL;
631
633 {
634 fullURL = aConfig.username + "@" + aConfig.url;
635 }
637 {
638 fullURL = aConfig.url.StartsWith( "https" ) ? "https://" : "http://";
639
640 if( !aConfig.username.empty() )
641 {
642 fullURL.append( aConfig.username );
643
644 if( !aConfig.password.empty() )
645 {
646 fullURL.append( wxS( ":" ) );
647 fullURL.append( aConfig.password );
648 }
649
650 fullURL.append( wxS( "@" ) );
651 }
652
653 wxString bareURL = aConfig.url;
654
655 if( bareURL.StartsWith( "https://" ) )
656 bareURL = bareURL.Mid( 8 );
657 else if( bareURL.StartsWith( "http://" ) )
658 bareURL = bareURL.Mid( 7 );
659
660 fullURL.append( bareURL );
661 }
662 else
663 {
664 fullURL = aConfig.url;
665 }
666
667 int error = git_remote_create_with_fetchspec( &remote, repo, "origin",
668 fullURL.ToStdString().c_str(),
669 "+refs/heads/*:refs/remotes/origin/*" );
670
671 KIGIT::GitRemotePtr remotePtr( remote );
672
673 if( error != GIT_OK )
674 {
675 aHandler->AddErrorString( wxString::Format( _( "Failed to create remote: %s" ),
677 return false;
678 }
679
680 wxLogTrace( traceGit, "Successfully set up remote origin" );
681 return true;
682}
683
684
685static bool lookup_branch_reference( git_repository* repo, const wxString& aBranchName,
686 git_reference** aReference )
687{
688 if( git_reference_lookup( aReference, repo, aBranchName.mb_str() ) == GIT_OK )
689 return true;
690
691 if( git_reference_dwim( aReference, repo, aBranchName.mb_str() ) == GIT_OK )
692 return true;
693
694 return false;
695}
696
697
698BranchResult LIBGIT_BACKEND::SwitchToBranch( GIT_BRANCH_HANDLER* aHandler, const wxString& aBranchName )
699{
700 git_repository* repo = aHandler->GetRepo();
701
702 if( !repo )
703 {
704 aHandler->AddErrorString( _( "No repository available" ) );
705 return BranchResult::Error;
706 }
707
708 git_reference* branchRef = nullptr;
709
710 if( !lookup_branch_reference( repo, aBranchName, &branchRef ) )
711 {
712 aHandler->AddErrorString( wxString::Format( _( "Failed to lookup branch '%s': %s" ),
713 aBranchName, KIGIT_COMMON::GetLastGitError() ) );
715 }
716
717 KIGIT::GitReferencePtr branchRefPtr( branchRef );
718 const char* branchRefName = git_reference_name( branchRef );
719 git_object* branchObj = nullptr;
720
721 if( git_revparse_single( &branchObj, repo, aBranchName.mb_str() ) != GIT_OK )
722 {
723 aHandler->AddErrorString( wxString::Format( _( "Failed to find branch head for '%s': %s" ),
724 aBranchName, KIGIT_COMMON::GetLastGitError() ) );
725 return BranchResult::Error;
726 }
727
728 KIGIT::GitObjectPtr branchObjPtr( branchObj );
729
730 if( git_checkout_tree( repo, branchObj, nullptr ) != GIT_OK )
731 {
732 aHandler->AddErrorString( wxString::Format( _( "Failed to switch to branch '%s': %s" ),
733 aBranchName, KIGIT_COMMON::GetLastGitError() ) );
735 }
736
737 if( git_repository_set_head( repo, branchRefName ) != GIT_OK )
738 {
739 aHandler->AddErrorString( wxString::Format( _( "Failed to update HEAD reference for branch '%s': %s" ),
740 aBranchName, KIGIT_COMMON::GetLastGitError() ) );
741 return BranchResult::Error;
742 }
743
744 wxLogTrace( traceGit, "Successfully switched to branch '%s'", aBranchName );
746}
747
748
749bool LIBGIT_BACKEND::BranchExists( GIT_BRANCH_HANDLER* aHandler, const wxString& aBranchName )
750{
751 git_repository* repo = aHandler->GetRepo();
752
753 if( !repo )
754 return false;
755
756 git_reference* branchRef = nullptr;
757 bool exists = lookup_branch_reference( repo, aBranchName, &branchRef );
758
759 if( branchRef )
760 git_reference_free( branchRef );
761
762 return exists;
763}
764
765
766// Use callbacks declared/implemented in kicad_git_common.h/.cpp
767
768bool LIBGIT_BACKEND::PerformFetch( GIT_PULL_HANDLER* aHandler, bool aSkipLock )
769{
770 if( !aHandler->GetRepo() )
771 {
772 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformFetch() - No repository found" );
773 return false;
774 }
775
776 std::unique_lock<std::mutex> lock( aHandler->GetCommon()->m_gitActionMutex, std::try_to_lock );
777
778 if( !aSkipLock && !lock.owns_lock() )
779 {
780 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformFetch() - Could not lock mutex" );
781 return false;
782 }
783
784 git_remote* remote = nullptr;
785
786 if( git_remote_lookup( &remote, aHandler->GetRepo(), "origin" ) != 0 )
787 {
788 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformFetch() - Failed to lookup remote 'origin'" );
789 aHandler->AddErrorString( wxString::Format( _( "Could not lookup remote '%s'" ), "origin" ) );
790 return false;
791 }
792
793 KIGIT::GitRemotePtr remotePtr( remote );
794
795 git_remote_callbacks remoteCallbacks;
796 git_remote_init_callbacks( &remoteCallbacks, GIT_REMOTE_CALLBACKS_VERSION );
797 remoteCallbacks.sideband_progress = progress_cb;
798 remoteCallbacks.transfer_progress = transfer_progress_cb;
799 remoteCallbacks.credentials = credentials_cb;
800 remoteCallbacks.payload = aHandler;
801 aHandler->GetCommon()->SetCancelled( false );
802
803 aHandler->TestedTypes() = 0;
804 aHandler->ResetNextKey();
805
806 if( git_remote_connect( remote, GIT_DIRECTION_FETCH, &remoteCallbacks, nullptr, nullptr ) )
807 {
808 wxString errorMsg = KIGIT_COMMON::GetLastGitError();
809 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformFetch() - Failed to connect to remote: %s", errorMsg );
810 aHandler->AddErrorString( wxString::Format( _( "Could not connect to remote '%s': %s" ), "origin",
811 errorMsg ) );
812 return false;
813 }
814
815 git_fetch_options fetchOptions;
816 git_fetch_init_options( &fetchOptions, GIT_FETCH_OPTIONS_VERSION );
817 fetchOptions.callbacks = remoteCallbacks;
818
819 if( git_remote_fetch( remote, nullptr, &fetchOptions, nullptr ) )
820 {
821 wxString errorMsg = KIGIT_COMMON::GetLastGitError();
822 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformFetch() - Failed to fetch from remote: %s", errorMsg );
823 aHandler->AddErrorString( wxString::Format( _( "Could not fetch data from remote '%s': %s" ), "origin",
824 errorMsg ) );
825 return false;
826 }
827
828 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformFetch() - Fetch completed successfully" );
829 return true;
830}
831
832
834{
836 std::unique_lock<std::mutex> lock( aHandler->GetCommon()->m_gitActionMutex, std::try_to_lock );
837
838 if( !lock.owns_lock() )
839 {
840 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Could not lock mutex" );
841 return PullResult::Error;
842 }
843
844 if( !PerformFetch( aHandler, true ) )
845 return PullResult::Error;
846
847 git_oid pull_merge_oid = {};
848
849 if( git_repository_fetchhead_foreach( aHandler->GetRepo(), fetchhead_foreach_cb, &pull_merge_oid ) )
850 {
851 aHandler->AddErrorString( _( "Could not read 'FETCH_HEAD'" ) );
852 return PullResult::Error;
853 }
854
855 git_annotated_commit* fetchhead_commit;
856
857 if( git_annotated_commit_lookup( &fetchhead_commit, aHandler->GetRepo(), &pull_merge_oid ) )
858 {
859 aHandler->AddErrorString( _( "Could not lookup commit" ) );
860 return PullResult::Error;
861 }
862
863 KIGIT::GitAnnotatedCommitPtr fetchheadCommitPtr( fetchhead_commit );
864 const git_annotated_commit* merge_commits[] = { fetchhead_commit };
865 git_merge_analysis_t merge_analysis;
866 git_merge_preference_t merge_preference = GIT_MERGE_PREFERENCE_NONE;
867
868 if( git_merge_analysis( &merge_analysis, &merge_preference, aHandler->GetRepo(), merge_commits, 1 ) )
869 {
870 aHandler->AddErrorString( _( "Could not analyze merge" ) );
871 return PullResult::Error;
872 }
873
874 if( merge_analysis & GIT_MERGE_ANALYSIS_UNBORN )
875 {
876 aHandler->AddErrorString( _( "Invalid HEAD. Cannot merge." ) );
878 }
879
880 if( merge_analysis & GIT_MERGE_ANALYSIS_UP_TO_DATE )
881 {
882 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Repository is up to date" );
883 git_repository_state_cleanup( aHandler->GetRepo() );
885 }
886
887 if( merge_analysis & GIT_MERGE_ANALYSIS_FASTFORWARD )
888 {
889 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Fast-forward merge" );
890 return handleFastForward( aHandler );
891 }
892
893 if( merge_analysis & GIT_MERGE_ANALYSIS_NORMAL )
894 {
895 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Normal merge" );
896
897 git_config* config = nullptr;
898
899 if( git_repository_config( &config, aHandler->GetRepo() ) != GIT_OK )
900 {
901 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Failed to get repository config" );
902 aHandler->AddErrorString( _( "Could not access repository configuration" ) );
903 return PullResult::Error;
904 }
905
906 KIGIT::GitConfigPtr configPtr( config );
907
908 int rebase_value = 0;
909 int ret = git_config_get_bool( &rebase_value, config, "pull.rebase" );
910
911 if( ret == GIT_OK && rebase_value )
912 {
913 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Using rebase based on config" );
914 return handleRebase( aHandler, merge_commits, 1 );
915 }
916
917 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Using merge based on config" );
918 return handleMerge( aHandler, merge_commits, 1 );
919 }
920
921 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Merge needs resolution" );
922 return result;
923}
924
925
927{
928 git_reference* rawRef = nullptr;
929
930 if( git_repository_head( &rawRef, aHandler->GetRepo() ) )
931 {
932 aHandler->AddErrorString( _( "Could not get repository head" ) );
933 return PullResult::Error;
934 }
935
936 KIGIT::GitReferencePtr headRef( rawRef );
937
938 git_oid updatedRefOid;
939 const char* currentBranchName = git_reference_name( rawRef );
940 const char* branch_shorthand = git_reference_shorthand( rawRef );
941 wxString remote_name = aHandler->GetRemotename();
942 wxString remoteBranchName = wxString::Format( "refs/remotes/%s/%s", remote_name, branch_shorthand );
943
944 if( git_reference_name_to_id( &updatedRefOid, aHandler->GetRepo(), remoteBranchName.c_str() ) != GIT_OK )
945 {
946 aHandler->AddErrorString( wxString::Format( _( "Could not get reference OID for reference '%s'" ),
947 remoteBranchName ) );
948 return PullResult::Error;
949 }
950
951 git_commit* targetCommit = nullptr;
952
953 if( git_commit_lookup( &targetCommit, aHandler->GetRepo(), &updatedRefOid ) != GIT_OK )
954 {
955 aHandler->AddErrorString( _( "Could not look up target commit" ) );
956 return PullResult::Error;
957 }
958
959 KIGIT::GitCommitPtr targetCommitPtr( targetCommit );
960
961 git_tree* targetTree = nullptr;
962
963 if( git_commit_tree( &targetTree, targetCommit ) != GIT_OK )
964 {
965 git_commit_free( targetCommit );
966 aHandler->AddErrorString( _( "Could not get tree from target commit" ) );
967 return PullResult::Error;
968 }
969
970 KIGIT::GitTreePtr targetTreePtr( targetTree );
971
972 git_checkout_options checkoutOptions;
973 git_checkout_init_options( &checkoutOptions, GIT_CHECKOUT_OPTIONS_VERSION );
974 auto notify_cb = []( git_checkout_notify_t why, const char* path, const git_diff_file* baseline,
975 const git_diff_file* target, const git_diff_file* workdir, void* payload ) -> int
976 {
977 switch( why )
978 {
979 case GIT_CHECKOUT_NOTIFY_CONFLICT:
980 wxLogTrace( traceGit, "Checkout conflict: %s", path ? path : "unknown" );
981 break;
982 case GIT_CHECKOUT_NOTIFY_DIRTY:
983 wxLogTrace( traceGit, "Checkout dirty: %s", path ? path : "unknown" );
984 break;
985 case GIT_CHECKOUT_NOTIFY_UPDATED:
986 wxLogTrace( traceGit, "Checkout updated: %s", path ? path : "unknown" );
987 break;
988 case GIT_CHECKOUT_NOTIFY_UNTRACKED:
989 wxLogTrace( traceGit, "Checkout untracked: %s", path ? path : "unknown" );
990 break;
991 case GIT_CHECKOUT_NOTIFY_IGNORED:
992 wxLogTrace( traceGit, "Checkout ignored: %s", path ? path : "unknown" );
993 break;
994 default:
995 break;
996 }
997
998 return 0;
999 };
1000
1001 checkoutOptions.checkout_strategy = GIT_CHECKOUT_SAFE | GIT_CHECKOUT_ALLOW_CONFLICTS;
1002 checkoutOptions.notify_flags = GIT_CHECKOUT_NOTIFY_ALL;
1003 checkoutOptions.notify_cb = notify_cb;
1004
1005 if( git_checkout_tree( aHandler->GetRepo(), reinterpret_cast<git_object*>( targetTree ),
1006 &checkoutOptions ) != GIT_OK )
1007 {
1008 aHandler->AddErrorString( _( "Failed to perform checkout operation." ) );
1009 return PullResult::Error;
1010 }
1011
1012 git_reference* updatedRef = nullptr;
1013
1014 if( git_reference_set_target( &updatedRef, rawRef, &updatedRefOid, nullptr ) != GIT_OK )
1015 {
1016 aHandler->AddErrorString( wxString::Format( _( "Failed to update reference '%s' to point to '%s'" ),
1017 currentBranchName, git_oid_tostr_s( &updatedRefOid ) ) );
1018 return PullResult::Error;
1019 }
1020
1021 KIGIT::GitReferencePtr updatedRefPtr( updatedRef );
1022
1023 if( git_repository_state_cleanup( aHandler->GetRepo() ) != GIT_OK )
1024 {
1025 aHandler->AddErrorString( _( "Failed to clean up repository state after fast-forward." ) );
1026 return PullResult::Error;
1027 }
1028
1029 git_revwalk* revWalker = nullptr;
1030
1031 if( git_revwalk_new( &revWalker, aHandler->GetRepo() ) != GIT_OK )
1032 {
1033 aHandler->AddErrorString( _( "Failed to initialize revision walker." ) );
1034 return PullResult::Error;
1035 }
1036
1037 KIGIT::GitRevWalkPtr revWalkerPtr( revWalker );
1038 git_revwalk_sorting( revWalker, GIT_SORT_TIME );
1039
1040 if( git_revwalk_push_glob( revWalker, currentBranchName ) != GIT_OK )
1041 {
1042 aHandler->AddErrorString( _( "Failed to push reference to revision walker." ) );
1043 return PullResult::Error;
1044 }
1045
1046 std::pair<std::string, std::vector<CommitDetails>>& branchCommits = aHandler->m_fetchResults.emplace_back();
1047 branchCommits.first = currentBranchName;
1048
1049 git_oid commitOid;
1050
1051 while( git_revwalk_next( &commitOid, revWalker ) == GIT_OK )
1052 {
1053 git_commit* commit = nullptr;
1054
1055 if( git_commit_lookup( &commit, aHandler->GetRepo(), &commitOid ) )
1056 {
1057 aHandler->AddErrorString( wxString::Format( _( "Could not lookup commit '%s'" ),
1058 git_oid_tostr_s( &commitOid ) ) );
1059 return PullResult::Error;
1060 }
1061
1062 KIGIT::GitCommitPtr commitPtr( commit );
1063
1064 CommitDetails details;
1065 details.m_sha = git_oid_tostr_s( &commitOid );
1066 details.m_firstLine = getFirstLineFromCommitMessage( git_commit_message( commit ) );
1067 details.m_author = git_commit_author( commit )->name;
1068 details.m_date = getFormattedCommitDate( git_commit_author( commit )->when );
1069
1070 branchCommits.second.push_back( details );
1071 }
1072
1074}
1075
1076
1077bool LIBGIT_BACKEND::hasUnstagedChanges( git_repository* aRepo )
1078{
1079 if( !aRepo )
1080 return false;
1081
1082 git_status_options opts;
1083 git_status_init_options( &opts, GIT_STATUS_OPTIONS_VERSION );
1084
1085 // Only check workdir changes (unstaged), not index changes (staged)
1086 opts.show = GIT_STATUS_SHOW_WORKDIR_ONLY;
1087 opts.flags = GIT_STATUS_OPT_INCLUDE_UNTRACKED;
1088
1089 git_status_list* status_list = nullptr;
1090
1091 if( git_status_list_new( &status_list, aRepo, &opts ) != GIT_OK )
1092 {
1093 wxLogTrace( traceGit, "Failed to get status list: %s", KIGIT_COMMON::GetLastGitError() );
1094 return false;
1095 }
1096
1097 KIGIT::GitStatusListPtr status_list_ptr( status_list );
1098 size_t count = git_status_list_entrycount( status_list );
1099
1100 // Check if any of the entries are actual modifications (not just untracked files)
1101 for( size_t ii = 0; ii < count; ++ii )
1102 {
1103 const git_status_entry* entry = git_status_byindex( status_list, ii );
1104
1105 // Check for actual workdir modifications, not just untracked files
1106 if( entry->status & ( GIT_STATUS_WT_MODIFIED | GIT_STATUS_WT_DELETED | GIT_STATUS_WT_TYPECHANGE ) )
1107 {
1108 return true;
1109 }
1110 }
1111
1112 return false;
1113}
1114
1115
1117 const git_annotated_commit** aMergeHeads,
1118 size_t aMergeHeadsCount )
1119{
1120 // Check for unstaged changes before attempting merge
1121 if( hasUnstagedChanges( aHandler->GetRepo() ) )
1122 {
1123 aHandler->AddErrorString(
1124 _( "Cannot merge: you have unstaged changes. "
1125 "Please commit or stash them before pulling." ) );
1127 }
1128
1129 if( git_merge( aHandler->GetRepo(), aMergeHeads, aMergeHeadsCount, nullptr, nullptr ) )
1130 {
1131 wxString errorMsg = KIGIT_COMMON::GetLastGitError();
1132 aHandler->AddErrorString( wxString::Format( _( "Merge failed: %s" ), errorMsg ) );
1134 }
1135
1136 return PullResult::Success;
1137}
1138
1139
1141 const git_annotated_commit** aMergeHeads,
1142 size_t aMergeHeadsCount )
1143{
1144 // Check for unstaged changes before attempting rebase
1145 if( hasUnstagedChanges( aHandler->GetRepo() ) )
1146 {
1147 aHandler->AddErrorString(
1148 _( "Cannot pull with rebase: you have unstaged changes. "
1149 "Please commit or stash them before pulling." ) );
1151 }
1152
1153 git_rebase_options rebase_opts;
1154 git_rebase_init_options( &rebase_opts, GIT_REBASE_OPTIONS_VERSION );
1155
1156 git_rebase* rebase = nullptr;
1157
1158 if( git_rebase_init( &rebase, aHandler->GetRepo(), nullptr, aMergeHeads[0], nullptr, &rebase_opts ) )
1159 {
1160 wxString errorMsg = KIGIT_COMMON::GetLastGitError();
1161 aHandler->AddErrorString( wxString::Format( _( "Rebase failed to start: %s" ), errorMsg ) );
1163 }
1164
1165 KIGIT::GitRebasePtr rebasePtr( rebase );
1166
1167 while( true )
1168 {
1169 git_rebase_operation* op = nullptr;
1170
1171 if( git_rebase_next( &op, rebase ) != 0 )
1172 break;
1173
1174 if( git_rebase_commit( nullptr, rebase, nullptr, nullptr, nullptr, nullptr ) )
1175 {
1176 wxString errorMsg = KIGIT_COMMON::GetLastGitError();
1177 aHandler->AddErrorString( wxString::Format( _( "Rebase commit failed: %s" ), errorMsg ) );
1179 }
1180 }
1181
1182 if( git_rebase_finish( rebase, nullptr ) )
1183 {
1184 wxString errorMsg = KIGIT_COMMON::GetLastGitError();
1185 aHandler->AddErrorString( wxString::Format( _( "Rebase finish failed: %s" ), errorMsg ) );
1187 }
1188
1189 return PullResult::Success;
1190}
1191
1192
1194{
1195 git_object* head_commit = NULL;
1196 git_checkout_options opts;
1197 git_checkout_init_options( &opts, GIT_CHECKOUT_OPTIONS_VERSION );
1198
1199 if( git_revparse_single( &head_commit, aHandler->m_repository, "HEAD" ) != 0 )
1200 {
1201 return;
1202 }
1203
1204 opts.checkout_strategy = GIT_CHECKOUT_FORCE;
1205 char** paths = new char*[aHandler->m_filesToRevert.size()];
1206
1207 for( size_t ii = 0; ii < aHandler->m_filesToRevert.size(); ii++ )
1208 {
1209 paths[ii] = wxStrdup( aHandler->m_filesToRevert[ii].ToUTF8() );
1210 }
1211
1212 git_strarray arr = { paths, aHandler->m_filesToRevert.size() };
1213
1214 opts.paths = arr;
1215 opts.progress_cb = nullptr;
1216 opts.notify_cb = nullptr;
1217 opts.notify_payload = static_cast<void*>( aHandler );
1218
1219 if( git_checkout_tree( aHandler->m_repository, head_commit, &opts ) != 0 )
1220 {
1221 const git_error* e = git_error_last();
1222
1223 if( e )
1224 {
1225 wxLogTrace( traceGit, wxS( "Checkout failed: %d: %s" ), e->klass, e->message );
1226 }
1227 }
1228
1229 for( size_t ii = 0; ii < aHandler->m_filesToRevert.size(); ii++ )
1230 delete( paths[ii] );
1231
1232 delete[] paths;
1233
1234 git_object_free( head_commit );
1235}
1236
1237
1238git_repository* LIBGIT_BACKEND::GetRepositoryForFile( const char* aFilename )
1239{
1240 git_repository* repo = nullptr;
1241 git_buf repo_path = GIT_BUF_INIT;
1242
1243 if( git_repository_discover( &repo_path, aFilename, 0, nullptr ) != GIT_OK )
1244 {
1245 wxLogTrace( traceGit, "Can't repo discover %s: %s", aFilename,
1247 return nullptr;
1248 }
1249
1250 KIGIT::GitBufPtr repo_path_ptr( &repo_path );
1251
1252 if( git_repository_open( &repo, repo_path.ptr ) != GIT_OK )
1253 {
1254 wxLogTrace( traceGit, "Can't open repo for %s: %s", repo_path.ptr,
1256 return nullptr;
1257 }
1258
1259 return repo;
1260}
1261
1262
1263int LIBGIT_BACKEND::CreateBranch( git_repository* aRepo, const wxString& aBranchName )
1264{
1265 git_oid head_oid;
1266
1267 if( int error = git_reference_name_to_id( &head_oid, aRepo, "HEAD" ); error != GIT_OK )
1268 {
1269 wxLogTrace( traceGit, "Failed to lookup HEAD reference: %s",
1271 return error;
1272 }
1273
1274 git_commit* commit = nullptr;
1275
1276 if( int error = git_commit_lookup( &commit, aRepo, &head_oid ); error != GIT_OK )
1277 {
1278 wxLogTrace( traceGit, "Failed to lookup commit: %s",
1280 return error;
1281 }
1282
1283 KIGIT::GitCommitPtr commitPtr( commit );
1284 git_reference* branchRef = nullptr;
1285
1286 if( int error = git_branch_create( &branchRef, aRepo, aBranchName.mb_str(), commit, 0 ); error != GIT_OK )
1287 {
1288 wxLogTrace( traceGit, "Failed to create branch: %s",
1290 return error;
1291 }
1292
1293 git_reference_free( branchRef );
1294 return 0;
1295}
1296
1297
1298bool LIBGIT_BACKEND::RemoveVCS( git_repository*& aRepo, const wxString& aProjectPath,
1299 bool aRemoveGitDir, wxString* aErrors )
1300{
1301 if( aRepo )
1302 {
1303 git_repository_free( aRepo );
1304 aRepo = nullptr;
1305 }
1306
1307 if( aRemoveGitDir )
1308 {
1309 wxFileName gitDir( aProjectPath, wxEmptyString );
1310 gitDir.AppendDir( ".git" );
1311
1312 if( gitDir.DirExists() )
1313 {
1314 wxString errors;
1315
1316 if( !RmDirRecursive( gitDir.GetPath(), &errors ) )
1317 {
1318 if( aErrors )
1319 *aErrors = errors;
1320
1321 wxLogTrace( traceGit, "Failed to remove .git directory: %s", errors );
1322 return false;
1323 }
1324 }
1325 }
1326
1327 wxLogTrace( traceGit, "Successfully removed VCS from project" );
1328 return true;
1329}
1330
1331
1332bool LIBGIT_BACKEND::AddToIndex( GIT_ADD_TO_INDEX_HANDLER* aHandler, const wxString& aFilePath )
1333{
1334 git_repository* repo = aHandler->GetRepo();
1335
1336 git_index* index = nullptr;
1337 size_t at_pos = 0;
1338
1339 if( git_repository_index( &index, repo ) != 0 )
1340 {
1341 wxLogError( "Failed to get repository index" );
1342 return false;
1343 }
1344
1345 KIGIT::GitIndexPtr indexPtr( index );
1346
1347 if( git_index_find( &at_pos, index, aFilePath.ToUTF8().data() ) == GIT_OK )
1348 {
1349 wxLogError( "%s already in index", aFilePath );
1350 return false;
1351 }
1352
1353 aHandler->m_filesToAdd.push_back( aFilePath );
1354 return true;
1355}
1356
1357
1359{
1360 git_repository* repo = aHandler->GetRepo();
1361 git_index* index = nullptr;
1362
1363 aHandler->m_filesFailedToAdd.clear();
1364
1365 if( git_repository_index( &index, repo ) != 0 )
1366 {
1367 wxLogError( "Failed to get repository index" );
1368 std::copy( aHandler->m_filesToAdd.begin(), aHandler->m_filesToAdd.end(),
1369 std::back_inserter( aHandler->m_filesFailedToAdd ) );
1370 return false;
1371 }
1372
1373 KIGIT::GitIndexPtr indexPtr( index );
1374
1375 for( auto& file : aHandler->m_filesToAdd )
1376 {
1377 if( git_index_add_bypath( index, file.ToUTF8().data() ) != 0 )
1378 {
1379 wxLogError( "Failed to add %s to index", file );
1380 aHandler->m_filesFailedToAdd.push_back( file );
1381 continue;
1382 }
1383 }
1384
1385 if( git_index_write( index ) != 0 )
1386 {
1387 wxLogError( "Failed to write index" );
1388 aHandler->m_filesFailedToAdd.clear();
1389 std::copy( aHandler->m_filesToAdd.begin(), aHandler->m_filesToAdd.end(),
1390 std::back_inserter( aHandler->m_filesFailedToAdd ) );
1391 return false;
1392 }
1393
1394 return true;
1395}
1396
1397
1398bool LIBGIT_BACKEND::RemoveFromIndex( GIT_REMOVE_FROM_INDEX_HANDLER* aHandler, const wxString& aFilePath )
1399{
1400 git_repository* repo = aHandler->GetRepo();
1401 git_index* index = nullptr;
1402 size_t at_pos = 0;
1403
1404 if( git_repository_index( &index, repo ) != 0 )
1405 {
1406 wxLogError( "Failed to get repository index" );
1407 return false;
1408 }
1409
1410 KIGIT::GitIndexPtr indexPtr( index );
1411
1412 if( git_index_find( &at_pos, index, aFilePath.ToUTF8().data() ) != 0 )
1413 {
1414 wxLogError( "Failed to find index entry for %s", aFilePath );
1415 return false;
1416 }
1417
1418 aHandler->m_filesToRemove.push_back( aFilePath );
1419 return true;
1420}
1421
1422
1424{
1425 git_repository* repo = aHandler->GetRepo();
1426
1427 for( auto& file : aHandler->m_filesToRemove )
1428 {
1429 git_index* index = nullptr;
1430 git_oid oid;
1431
1432 if( git_repository_index( &index, repo ) != 0 )
1433 {
1434 wxLogError( "Failed to get repository index" );
1435 return;
1436 }
1437
1438 KIGIT::GitIndexPtr indexPtr( index );
1439
1440 if( git_index_remove_bypath( index, file.ToUTF8().data() ) != 0 )
1441 {
1442 wxLogError( "Failed to remove index entry for %s", file );
1443 return;
1444 }
1445
1446 if( git_index_write( index ) != 0 )
1447 {
1448 wxLogError( "Failed to write index" );
1449 return;
1450 }
1451
1452 if( git_index_write_tree( &oid, index ) != 0 )
1453 {
1454 wxLogError( "Failed to write index tree" );
1455 return;
1456 }
1457 }
1458}
int index
std::vector< wxString > m_filesToAdd
std::vector< wxString > m_filesFailedToAdd
KIGIT_ORPHAN_REGISTRY m_orphanRegistry
wxString GetClonePath() const
void AddErrorString(const wxString &aErrorString)
std::vector< std::pair< std::string, std::vector< CommitDetails > > > m_fetchResults
std::vector< wxString > m_filesToRevert
git_repository * m_repository
KIGIT_COMMON::GIT_STATUS ConvertStatus(unsigned int aGitStatus)
Convert git status flags to KIGIT_COMMON::GIT_STATUS.
std::mutex m_gitActionMutex
static wxString GetLastGitError()
void SetSSHKey(const wxString &aSSHKey)
void SetUsername(const wxString &aUsername)
git_repository * GetRepo() const
void SetCancelled(bool aCancel)
void SetPassword(const wxString &aPassword)
void SetRepo(git_repository *aRepo)
void AddErrorString(const wxString aErrorString)
wxString GetProjectDir() const
Get the project directory path, preserving symlinks if set.
git_repository * GetRepo() const
Get a pointer to the git repository.
unsigned & TestedTypes()
Return the connection types that have been tested for authentication.
KIGIT_COMMON * GetCommon() const
Get the common object.
wxString GetRemotename() const
Get the remote name.
void ResetNextKey()
Reset the next public key to test.
bool PerformAddToIndex(GIT_ADD_TO_INDEX_HANDLER *aHandler) override
void PerformRevert(GIT_REVERT_HANDLER *aHandler) override
PullResult handleMerge(GIT_PULL_HANDLER *aHandler, const git_annotated_commit **aMergeHeads, size_t aMergeHeadsCount)
bool PerformFetch(GIT_PULL_HANDLER *aHandler, bool aSkipLock) override
static bool hasUnstagedChanges(git_repository *aRepo)
bool Clone(GIT_CLONE_HANDLER *aHandler) override
PullResult handleRebase(GIT_PULL_HANDLER *aHandler, const git_annotated_commit **aMergeHeads, size_t aMergeHeadsCount)
void PerformRemoveFromIndex(GIT_REMOVE_FROM_INDEX_HANDLER *aHandler) override
bool RemoveVCS(git_repository *&aRepo, const wxString &aProjectPath, bool aRemoveGitDir, wxString *aErrors) override
bool RemoveFromIndex(GIT_REMOVE_FROM_INDEX_HANDLER *aHandler, const wxString &aFilePath) override
BranchResult SwitchToBranch(GIT_BRANCH_HANDLER *aHandler, const wxString &aBranchName) override
PullResult handleFastForward(GIT_PULL_HANDLER *aHandler)
CommitResult Commit(GIT_COMMIT_HANDLER *aHandler, const std::vector< wxString > &aFiles, const wxString &aMessage, const wxString &aAuthorName, const wxString &aAuthorEmail) override
std::map< wxString, FileStatus > GetFileStatus(GIT_STATUS_HANDLER *aHandler, const wxString &aPathspec) override
bool HasChangedFiles(GIT_STATUS_HANDLER *aHandler) override
void Init() override
void UpdateRemoteStatus(GIT_STATUS_HANDLER *aHandler, const std::set< wxString > &aLocalChanges, const std::set< wxString > &aRemoteChanges, std::map< wxString, FileStatus > &aFileStatus) override
wxString GetCurrentBranchName(GIT_STATUS_HANDLER *aHandler) override
PushResult Push(GIT_PUSH_HANDLER *aHandler) override
bool GetConfigString(GIT_CONFIG_HANDLER *aHandler, const wxString &aKey, wxString &aValue) override
git_repository * GetRepositoryForFile(const char *aFilename) override
bool AddToIndex(GIT_ADD_TO_INDEX_HANDLER *aHandler, const wxString &aFilePath) override
bool SetupRemote(GIT_INIT_HANDLER *aHandler, const RemoteConfig &aConfig) override
bool IsRepository(GIT_INIT_HANDLER *aHandler, const wxString &aPath) override
bool IsLibraryAvailable() override
void Shutdown() override
wxString GetWorkingDirectory(GIT_STATUS_HANDLER *aHandler) override
bool BranchExists(GIT_BRANCH_HANDLER *aHandler, const wxString &aBranchName) override
InitResult InitializeRepository(GIT_INIT_HANDLER *aHandler, const wxString &aPath) override
PullResult PerformPull(GIT_PULL_HANDLER *aHandler) override
int CreateBranch(git_repository *aRepo, const wxString &aBranchName) override
#define _(s)
bool RmDirRecursive(const wxString &aFileName, wxString *aErrors)
Remove the directory aDirName and all its contents including subdirectories and their files.
Definition gestfich.cpp:390
CommitResult
Definition git_backend.h:56
InitResult
PullResult
PushResult
const wxChar *const traceGit
Flag to enable Git debugging output.
int fetchhead_foreach_cb(const char *, const char *, const git_oid *aOID, unsigned int aIsMerge, void *aPayload)
int progress_cb(const char *str, int len, void *aPayload)
int update_cb(const char *aRefname, const git_oid *aFirst, const git_oid *aSecond, void *aPayload)
int transfer_progress_cb(const git_transfer_progress *aStats, void *aPayload)
int credentials_cb(git_cred **aOut, const char *aUrl, const char *aUsername, unsigned int aAllowedTypes, void *aPayload)
void clone_progress_cb(const char *aStr, size_t aLen, size_t aTotal, void *aPayload)
int push_transfer_progress_cb(unsigned int aCurrent, unsigned int aTotal, size_t aBytes, void *aPayload)
#define GIT_BUF_INIT
static bool lookup_branch_reference(git_repository *repo, const wxString &aBranchName, git_reference **aReference)
static std::string getFormattedCommitDate(const git_time &aTime)
static std::string getFirstLineFromCommitMessage(const std::string &aMessage)
std::unique_ptr< git_tree, decltype([](git_tree *aTree) { git_tree_free(aTree); })> GitTreePtr
A unique pointer for git_tree objects with automatic cleanup.
std::unique_ptr< git_revwalk, decltype([](git_revwalk *aWalker) { git_revwalk_free(aWalker); })> GitRevWalkPtr
A unique pointer for git_revwalk objects with automatic cleanup.
std::unique_ptr< git_commit, decltype([](git_commit *aCommit) { git_commit_free(aCommit); })> GitCommitPtr
A unique pointer for git_commit objects with automatic cleanup.
std::unique_ptr< git_buf, decltype([](git_buf *aBuf) { git_buf_free(aBuf); })> GitBufPtr
A unique pointer for git_buf objects with automatic cleanup.
std::unique_ptr< git_annotated_commit, decltype([](git_annotated_commit *aCommit) { git_annotated_commit_free(aCommit); })> GitAnnotatedCommitPtr
A unique pointer for git_annotated_commit objects with automatic cleanup.
std::unique_ptr< git_status_list, decltype([](git_status_list *aList) { git_status_list_free(aList); })> GitStatusListPtr
A unique pointer for git_status_list objects with automatic cleanup.
std::unique_ptr< git_config, decltype([](git_config *aConfig) { git_config_free(aConfig); })> GitConfigPtr
A unique pointer for git_config objects with automatic cleanup.
std::unique_ptr< git_reference, decltype([](git_reference *aRef) { git_reference_free(aRef); })> GitReferencePtr
A unique pointer for git_reference objects with automatic cleanup.
std::unique_ptr< git_config_entry, decltype([](git_config_entry *aEntry) { git_config_entry_free(aEntry); })> GitConfigEntryPtr
A unique pointer for git_config_entry objects with automatic cleanup.
std::unique_ptr< git_signature, decltype([](git_signature *aSignature) { git_signature_free(aSignature); })> GitSignaturePtr
A unique pointer for git_signature objects with automatic cleanup.
std::unique_ptr< git_rebase, decltype([](git_rebase *aRebase) { git_rebase_free(aRebase); })> GitRebasePtr
A unique pointer for git_rebase objects with automatic cleanup.
std::unique_ptr< git_index, decltype([](git_index *aIndex) { git_index_free(aIndex); })> GitIndexPtr
A unique pointer for git_index objects with automatic cleanup.
std::unique_ptr< git_object, decltype([](git_object *aObject) { git_object_free(aObject); })> GitObjectPtr
A unique pointer for git_object objects with automatic cleanup.
std::unique_ptr< git_remote, decltype([](git_remote *aRemote) { git_remote_free(aRemote); })> GitRemotePtr
A unique pointer for git_remote objects with automatic cleanup.
std::string m_sha
std::string m_date
std::string m_firstLine
std::string m_author
KIGIT_COMMON::GIT_CONN_TYPE connType
std::string path
wxString result
Test unit parsing edge cases and error handling.
wxLogTrace helper definitions.