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, see <https://www.gnu.org/licenses/>.
18 */
19
20#include "libgit_backend.h"
21
22#include "git_clone_handler.h"
23#include "git_commit_handler.h"
24#include "git_push_handler.h"
25#include "git_status_handler.h"
26#include "git_config_handler.h"
27#include "git_init_handler.h"
28#include "git_branch_handler.h"
29#include "git_pull_handler.h"
30#include "project_git_utils.h"
31#include "kicad_git_common.h"
32#include "kicad_git_memory.h"
33#include "kigit_failure.h"
34#include "kigit_ssh_keys.h"
35#include "kigit_transport.h"
36#include "trace_helpers.h"
37
38#include "kicad_git_compat.h"
39#include <wx/file.h>
40#include <wx/filename.h>
41#include <wx/log.h>
42#include <gestfich.h>
43#include <paths.h>
44#include <algorithm>
45#include <cstring>
46#include <fstream>
47#include <iterator>
48#include <map>
49#include <memory>
50#include <optional>
51#include <set>
52#include <string>
53#include <vector>
54
55
57{
58 git_libgit2_init();
59
61 wxFileName( PATHS::GetUserCachePath(), wxS( "git_ssh_keys.json" ) ).GetFullPath() );
62 KIGIT::SetDerivedPublicKeyFolder( wxFileName( PATHS::GetUserCachePath(), wxS( "ssh_public_keys" ) ).GetFullPath() );
63
64 // libgit2 sets no timeout of its own, so an unreachable remote parks a fetch in connect()
65 // or recv() for as long as the OS allows. SSH remotes stay bounded only by libssh2.
66
67#if ( LIBGIT2_VER_MAJOR > 1 ) || ( LIBGIT2_VER_MAJOR == 1 && LIBGIT2_VER_MINOR >= 7 )
68 constexpr int connectTimeoutMs = 10000;
69 constexpr int transferTimeoutMs = 30000;
70
71 if( git_libgit2_opts( GIT_OPT_SET_SERVER_CONNECT_TIMEOUT, connectTimeoutMs ) != GIT_OK
72 || git_libgit2_opts( GIT_OPT_SET_SERVER_TIMEOUT, transferTimeoutMs ) != GIT_OK )
73 {
74 wxLogTrace( traceGit, "LIBGIT_BACKEND::Init(): could not set server timeouts: %s",
76 }
77#endif
78}
79
80
82{
83 // Wait for any abandoned git cleanup threads to finish before tearing
84 // down libgit2. A worker still inside libgit2 (for example, blocked on
85 // recv() under git_remote_fetch) would otherwise race teardown and
86 // invoke undefined behaviour. Five seconds is long enough to cover a
87 // transport error timeout but short enough to avoid a perceptibly slow
88 // exit when the remote is truly unreachable.
89
90 constexpr auto kOrphanJoinTimeout = std::chrono::seconds( 5 );
91 size_t stuck = m_orphanRegistry.JoinAll( kOrphanJoinTimeout );
92
93 if( stuck > 0 )
94 {
95 wxLogTrace( traceGit, "LIBGIT_BACKEND::Shutdown(): %zu orphan git thread(s) did not finish within %lld ms; "
96 "skipping libgit2 shutdown",
97 stuck, static_cast<long long>( kOrphanJoinTimeout.count() ) );
98
99 // A stuck worker is still executing inside libgit2. Calling
100 // git_libgit2_shutdown() now would free state the worker is actively
101 // reading. Leave libgit2 initialised and let the OS reclaim
102 // resources when the process exits.
103
104 return;
105 }
106
107 git_libgit2_shutdown();
108}
109
110
112{
113#if ( LIBGIT2_VER_MAJOR >= 1 ) || ( LIBGIT2_VER_MINOR >= 99 )
114 int major = 0, minor = 0, rev = 0;
115 return git_libgit2_version( &major, &minor, &rev ) == GIT_OK;
116#else
117 // On older platforms, assume available when building with libgit2
118 return true;
119#endif
120}
121
122
123// git_signature_default answers GIT_ENOTFOUND only when user.name or user.email is not set
125{
126 if( aRc == GIT_ENOTFOUND )
127 return { _( "Set your name and email before committing (gear menu > Set Author...)." ), wxEmptyString };
128
129 return { _( "Could not record the commit author." ), KIGIT_COMMON::GetLastGitError() };
130}
131
132
133static void reportRemoteLookupFailure( KIGIT_ERRORS* aHandler, int aRc, const wxString& aRemoteName )
134{
135 if( aRc == GIT_ENOTFOUND )
136 {
137 aHandler->AddError( wxString::Format( _( "There is no remote named '%s'. Add it on the Remotes page of the "
138 "Advanced Git window." ),
139 aRemoteName ),
140 wxEmptyString );
141 return;
142 }
143
144 aHandler->AddError( wxString::Format( _( "Could not read the remote '%s'." ), aRemoteName ),
146}
147
148
150{
151 KIGIT_COMMON* common = aHandler->GetCommon();
152 std::unique_lock<std::mutex> lock = aHandler->GetActionLock();
153
154 if( !lock.owns_lock() )
155 {
156 wxLogTrace( traceGit, "GIT_CLONE_HANDLER::PerformClone() could not lock" );
157 return false;
158 }
159
160 // Without this the progress dialog's Cancel would set a token nothing reads.
161 KIGIT_COMMON::OPERATION_GUARD operation( common, aHandler->CancelToken() );
162
163 if( aHandler->IsThisOperationCancelled() )
164 return false;
165
166 wxFileName clonePath( aHandler->GetClonePath() );
167
168 if( !clonePath.DirExists() )
169 {
170 if( !clonePath.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
171 {
172 aHandler->AddErrorString( wxString::Format( _( "Could not create directory '%s'" ),
173 aHandler->GetClonePath() ) );
174 return false;
175 }
176 }
177
178 KIGIT::REMOTE_TRANSPORT transport( aHandler );
179 git_repository* newRepo = nullptr;
180
181 if( transport.Clone( common->GetRemote(), aHandler->GetClonePath(), &newRepo ) )
182 {
183 aHandler->ReportTransferFailure( transport.Error(), KIGIT_OPERATION::CLONE, wxEmptyString );
184 return false;
185 }
186
187 common->SetRepo( newRepo );
188
189 return true;
190}
191
192
193// Enough of a path's staged state to tell whether something else restaged it.
195{
196 bool present = false;
197 git_oid id = {};
198 uint32_t mode = 0;
199
200 bool operator==( const SELECTED_STATE& aOther ) const
201 {
202 return present == aOther.present && mode == aOther.mode && ( !present || git_oid_equal( &id, &aOther.id ) );
203 }
204
205 bool operator!=( const SELECTED_STATE& aOther ) const { return !( *this == aOther ); }
206};
207
208
209static std::map<std::string, SELECTED_STATE> readSelectedState( git_index* aIndex,
210 const std::set<std::string>& aSelected )
211{
212 std::map<std::string, SELECTED_STATE> result;
213
214 for( const std::string& path : aSelected )
215 {
216 SELECTED_STATE state;
217
218 if( const git_index_entry* entry = git_index_get_bypath( aIndex, path.c_str(), 0 ) )
219 {
220 state.present = true;
221 state.id = entry->id;
222 state.mode = entry->mode;
223 }
224
225 result[path] = state;
226 }
227
228 return result;
229}
230
231
232static std::map<std::string, SELECTED_STATE> readWholeState( git_index* aIndex )
233{
234 std::map<std::string, SELECTED_STATE> result;
235 size_t count = git_index_entrycount( aIndex );
236
237 for( size_t ii = 0; ii < count; ii++ )
238 {
239 if( const git_index_entry* entry = git_index_get_byindex( aIndex, ii ) )
240 {
241 SELECTED_STATE state;
242 state.present = true;
243 state.id = entry->id;
244 state.mode = entry->mode;
245 result[entry->path] = state;
246 }
247 }
248
249 return result;
250}
251
252
253// The index file itself, not the scratch copy the handle holds. Null when it cannot be read.
254static git_index* openIndexOnDisk( git_index* aRepoIndex )
255{
256 const char* indexPath = git_index_path( aRepoIndex );
257
258 if( !indexPath )
259 return nullptr;
260
261 git_index* fresh = nullptr;
262
263 if( git_index_open( &fresh, indexPath ) != GIT_OK )
264 return nullptr;
265
266 int rc = git_index_read( fresh, 1 );
267
268 // A repository with nothing staged yet has no index file, which reads as empty.
269 if( rc != GIT_OK && rc != GIT_ENOTFOUND )
270 {
271 git_index_free( fresh );
272 return nullptr;
273 }
274
275 return fresh;
276}
277
278
279static bool selectedStateOnDisk( git_index* aRepoIndex, const std::set<std::string>& aSelected,
280 std::map<std::string, SELECTED_STATE>& aOut )
281{
282 git_index* fresh = openIndexOnDisk( aRepoIndex );
283
284 if( !fresh )
285 return false;
286
287 KIGIT::GitIndexPtr freshPtr( fresh );
288 aOut = readSelectedState( fresh, aSelected );
289 return true;
290}
291
292
293static bool wholeStateOnDisk( git_index* aRepoIndex, std::map<std::string, SELECTED_STATE>& aOut )
294{
295 git_index* fresh = openIndexOnDisk( aRepoIndex );
296
297 if( !fresh )
298 return false;
299
300 KIGIT::GitIndexPtr freshPtr( fresh );
301 aOut = readWholeState( fresh );
302 return true;
303}
304
305
306// Owns its path, because index entries point into storage that rebuilding invalidates.
308{
309 std::string path;
310 git_index_entry entry;
311};
312
313
314// The index is scratch until the commit exists, so every way out reloads what the user staged.
316{
317 git_index* index = nullptr;
318 bool armed = true;
319
321 {
322 if( armed && index )
323 git_index_read( index, 1 );
324 }
325};
326
327
328// Keeps staging done outside KiCad, and moves the selected paths to what was just committed.
329// A listed file missing from the working tree is a deletion to record, not a path to add.
330static bool applySelectedPaths( git_repository* aRepo, git_index* aIndex, const std::vector<wxString>& aFiles )
331{
332 const char* workdir = git_repository_workdir( aRepo );
333
334 for( const wxString& file : aFiles )
335 {
336 // Anything at the path counts. A submodule is a directory and a symlink may point at
337 // one or at nothing, and reading those as deletions drops them out of the project.
338 bool onDisk = workdir
339 && wxFileName::Exists( wxString::FromUTF8( workdir ) + file,
340 wxFILE_EXISTS_ANY | wxFILE_EXISTS_NO_FOLLOW );
341
342 // libgit2 paths are UTF-8, so convert explicitly rather than through the locale.
343 std::string path = file.utf8_string();
344
345 int rc =
346 onDisk ? git_index_add_bypath( aIndex, path.c_str() ) : git_index_remove_bypath( aIndex, path.c_str() );
347
348 if( rc != 0 )
349 return false;
350 }
351
352 return true;
353}
354
355
356// A commit landing between the tree build and the parent lookup would be undone by this one.
357static bool branchMovedSince( git_repository* aRepo, const git_oid& aHeadAtStart, bool aHadHead )
358{
359 git_oid headNow;
360 bool hasHeadNow = git_reference_name_to_id( &headNow, aRepo, "HEAD" ) == GIT_OK;
361
362 return hasHeadNow != aHadHead || ( hasHeadNow && !git_oid_equal( &headNow, &aHeadAtStart ) );
363}
364
365
366// Something restaged a file being committed. Moving it on would destroy that record.
367static bool selectedPathsRestaged( git_index* aIndex, const std::set<std::string>& aSelected,
368 const std::map<std::string, SELECTED_STATE>& aAtStart )
369{
370 std::map<std::string, SELECTED_STATE> now;
371
372 return !selectedStateOnDisk( aIndex, aSelected, now ) || now != aAtStart;
373}
374
375
376// Catches a file staged outside KiCad that this commit does not list, which the check above misses.
377static bool indexChangedSince( git_index* aIndex, const std::map<std::string, SELECTED_STATE>& aAtStart )
378{
379 std::map<std::string, SELECTED_STATE> now;
380
381 return !wholeStateOnDisk( aIndex, now ) || now != aAtStart;
382}
383
384
391
392
393// Reread and compare before writing, or staging done elsewhere is overwritten.
394static REPUBLISH_RESULT republishIndex( git_index* aIndex, const std::vector<STAGED_ENTRY>& aCommitted,
395 const std::set<std::string>& aSelected )
396{
397 for( int attempt = 0; attempt < 3; attempt++ )
398 {
399 if( git_index_read( aIndex, 1 ) != 0 )
401
402 std::map<std::string, SELECTED_STATE> readState = readWholeState( aIndex );
403
404 for( const std::string& path : aSelected )
405 git_index_remove_bypath( aIndex, path.c_str() );
406
407 for( const STAGED_ENTRY& staged : aCommitted )
408 {
409 git_index_entry entry = staged.entry;
410 entry.path = staged.path.c_str();
411
412 if( git_index_add( aIndex, &entry ) != 0 )
414 }
415
416 std::map<std::string, SELECTED_STATE> diskState;
417
418 if( !wholeStateOnDisk( aIndex, diskState ) )
420
421 if( diskState != readState )
422 continue;
423
424 if( git_index_write( aIndex ) == 0 )
426
428 }
429
431}
432
433
434// Rebuilding from HEAD drops conflict stages, so markers would commit as resolved content.
435static bool refuseWhileOperationInProgress( git_repository* aRepo, git_index* aIndex, wxString& aError )
436{
437 if( git_index_has_conflicts( aIndex ) )
438 {
439 aError = _( "This project has conflicts that are not resolved yet. Finish or abort the merge "
440 "with git, then commit here." );
441 return true;
442 }
443
444 wxString operation;
445
446 switch( git_repository_state( aRepo ) )
447 {
448 case GIT_REPOSITORY_STATE_NONE: return false;
449 case GIT_REPOSITORY_STATE_MERGE: operation = _( "merge" ); break;
450 case GIT_REPOSITORY_STATE_REVERT:
451 case GIT_REPOSITORY_STATE_REVERT_SEQUENCE: operation = _( "revert" ); break;
452 case GIT_REPOSITORY_STATE_CHERRYPICK:
453 case GIT_REPOSITORY_STATE_CHERRYPICK_SEQUENCE: operation = _( "cherry-pick" ); break;
454 case GIT_REPOSITORY_STATE_BISECT: operation = _( "bisect" ); break;
455 default: operation = _( "rebase" ); break;
456 }
457
458 aError = wxString::Format( _( "This project is in the middle of a %s. Finish or abort it with git, "
459 "then commit here." ),
460 operation );
461 return true;
462}
463
464
465// What Commit and Amend do identically: take the index over as scratch space, remember what it
466// held, stage the chosen files over a base tree, and refuse if anything moved underneath while
467// the tree was being built. Only the base tree and the commit call itself differ between them.
469{
470 git_index* index = nullptr;
472 std::set<std::string> selectedPaths;
473 std::map<std::string, SELECTED_STATE> selectedAtStart;
474 std::map<std::string, SELECTED_STATE> indexAtStart;
475 bool haveIndexAtStart = false;
476 git_oid headAtStart = {};
477 bool hadHeadAtStart = false;
479 std::vector<STAGED_ENTRY> committedEntries;
480
482 bool Begin( git_repository* aRepo, const std::vector<wxString>& aFiles, KIGIT_ERROR_MESSAGE& aError )
483 {
484 if( git_repository_index( &index, aRepo ) != 0 )
485 {
486 aError = { _( "Could not read the list of staged files." ), KIGIT_COMMON::GetLastGitError() };
487 return false;
488 }
489
490 indexPtr.reset( index );
491
492 // The action lock only serializes KiCad, so read what is on disk before judging it.
493 git_index_read( index, 1 );
494
495 wxString blockedError;
496
497 if( refuseWhileOperationInProgress( aRepo, index, blockedError ) )
498 {
499 aError = { blockedError, wxEmptyString };
500 return false;
501 }
502
503 for( const wxString& file : aFiles )
504 selectedPaths.insert( file.utf8_string() );
505
508 hadHeadAtStart = git_reference_name_to_id( &headAtStart, aRepo, "HEAD" ) == GIT_OK;
509
510 // Armed last, so an early return above leaves the real index alone.
511 scratchGuard.index = index;
512 return true;
513 }
514
517 bool BuildTree( git_repository* aRepo, const std::vector<wxString>& aFiles, KIGIT::GitTreePtr& aTreeOut,
518 KIGIT_ERROR_MESSAGE& aError )
519 {
520 if( !applySelectedPaths( aRepo, index, aFiles ) )
521 {
522 aError = { _( "Could not stage the selected files." ), KIGIT_COMMON::GetLastGitError() };
523 return false;
524 }
525
526 // Writing this scratch index is what would unstage everything staged outside KiCad, so
527 // only the tree it describes is written.
528 for( const std::string& path : selectedPaths )
529 {
530 if( const git_index_entry* entry = git_index_get_bypath( index, path.c_str(), 0 ) )
531 committedEntries.push_back( { path, *entry } );
532 }
533
534 git_oid treeId;
535
536 if( git_index_write_tree( &treeId, index ) != 0 )
537 {
538 aError = { _( "Could not prepare the commit." ), KIGIT_COMMON::GetLastGitError() };
539 return false;
540 }
541
542 git_tree* tree = nullptr;
543
544 if( git_tree_lookup( &tree, aRepo, &treeId ) != 0 )
545 {
546 aError = { _( "Could not prepare the commit." ), KIGIT_COMMON::GetLastGitError() };
547 return false;
548 }
549
550 aTreeOut.reset( tree );
551
552 // Nothing is written yet, so the scratch guard puts the real index back on the way out.
554 {
555 aError = { _( "The branch moved while this was running, so nothing was "
556 "committed. Review the changes and try again." ),
557 wxEmptyString };
558 return false;
559 }
560
563 {
564 aError = { _( "The staged files changed outside KiCad while this ran. Nothing "
565 "was committed. Review the changes and try again." ),
566 wxEmptyString };
567 return false;
568 }
569
570 return true;
571 }
572};
573
574
575CommitResult LIBGIT_BACKEND::Commit( GIT_COMMIT_HANDLER* aHandler, const std::vector<wxString>& aFiles,
576 const wxString& aMessage, const wxString& aAuthorName,
577 const wxString& aAuthorEmail )
578{
579 git_repository* repo = aHandler->GetRepo();
580
581 if( !repo )
582 return CommitResult::Error;
583
584 COMMIT_STAGING staging;
585 KIGIT_ERROR_MESSAGE stagingError;
586
587 if( !staging.Begin( repo, aFiles, stagingError ) )
588 {
589 aHandler->AddError( stagingError );
590 return CommitResult::Error;
591 }
592
593 git_index* index = staging.index;
594
595 // Start from the HEAD tree, not the index, so the commit holds exactly the listed files.
596 if( git_repository_head_unborn( repo ) == 0 )
597 {
598 git_reference* headRef = nullptr;
599
600 if( git_repository_head( &headRef, repo ) != 0 )
601 {
602 aHandler->AddGitError( _( "Could not read the current commit." ) );
603 return CommitResult::Error;
604 }
605
606 KIGIT::GitReferencePtr headRefPtr( headRef );
607 git_tree* headTree = nullptr;
608
609 if( git_reference_peel( (git_object**) &headTree, headRef, GIT_OBJECT_TREE ) != 0 )
610 {
611 aHandler->AddGitError( _( "Could not read the current commit." ) );
612 return CommitResult::Error;
613 }
614
615 KIGIT::GitTreePtr headTreePtr( headTree );
616
617 if( git_index_read_tree( index, headTree ) != 0 )
618 {
619 aHandler->AddGitError( _( "Could not prepare the commit." ) );
620 return CommitResult::Error;
621 }
622 }
623 else if( git_index_clear( index ) != 0 )
624 {
625 aHandler->AddGitError( _( "Could not prepare the commit." ) );
626 return CommitResult::Error;
627 }
628
629 KIGIT::GitTreePtr treePtr;
630
631 if( !staging.BuildTree( repo, aFiles, treePtr, stagingError ) )
632 {
633 aHandler->AddError( stagingError );
634 return CommitResult::Error;
635 }
636
637 git_tree* tree = treePtr.get();
638
639 git_commit* parent = nullptr;
640
641 if( git_repository_head_unborn( repo ) == 0 )
642 {
643 git_reference* headRef = nullptr;
644
645 if( git_repository_head( &headRef, repo ) != 0 )
646 {
647 aHandler->AddGitError( _( "Could not read the current commit." ) );
648 return CommitResult::Error;
649 }
650
651 KIGIT::GitReferencePtr headRefPtr( headRef );
652
653 if( git_reference_peel( (git_object**) &parent, headRef, GIT_OBJECT_COMMIT ) != 0 )
654 {
655 aHandler->AddGitError( _( "Could not read the current commit." ) );
656 return CommitResult::Error;
657 }
658 }
659
660 KIGIT::GitCommitPtr parentPtr( parent );
661
662 git_signature* author = nullptr;
663
664 if( git_signature_now( &author, aAuthorName.utf8_string().c_str(), aAuthorEmail.utf8_string().c_str() ) != 0 )
665 {
666 aHandler->AddGitError( _( "Could not record the commit author." ) );
667 return CommitResult::Error;
668 }
669
670 KIGIT::GitSignaturePtr authorPtr( author );
671 git_oid oid;
672 size_t parentsCount = parent ? 1 : 0;
673
674#if( LIBGIT2_VER_MAJOR == 1 && LIBGIT2_VER_MINOR == 8 \
675 && ( LIBGIT2_VER_REVISION < 2 || LIBGIT2_VER_REVISION == 3 ) )
676 git_commit* const parents[1] = { parent };
677 git_commit** const parentsPtr = parent ? parents : nullptr;
678#else
679 const git_commit* parents[1] = { parent };
680 const git_commit** parentsPtr = parent ? parents : nullptr;
681#endif
682
683 if( git_commit_create( &oid, repo, "HEAD", author, author, nullptr, aMessage.utf8_string().c_str(), tree,
684 parentsCount, parentsPtr )
685 != 0 )
686 {
687 aHandler->AddGitError( _( "Could not create the commit." ) );
688 return CommitResult::Error;
689 }
690
691 // The commit exists, so only the index is left. If anything restaged meanwhile, leave it.
693 || ( staging.haveIndexAtStart && indexChangedSince( index, staging.indexAtStart ) ) )
694 {
695 git_index_read( index, 1 );
696 aHandler->AddErrorString( _( "The commit was created, but the list of staged files was left "
697 "alone, because the staged files changed outside KiCad while "
698 "this ran." ) );
700 }
701
702 REPUBLISH_RESULT republished = republishIndex( index, staging.committedEntries, staging.selectedPaths );
703
704 if( republished == REPUBLISH_RESULT::CHANGED_EXTERNALLY )
705 {
706 aHandler->AddErrorString( _( "The commit was created, but the list of staged files was left "
707 "alone, because another program kept changing it." ) );
709 }
710
711 if( republished == REPUBLISH_RESULT::WRITE_FAILED )
712 {
713 aHandler->AddGitError( _( "The commit was created, but the list of staged files could not be updated." ) );
715 }
716
717 staging.scratchGuard.armed = false;
718
720}
721
722
723CommitResult LIBGIT_BACKEND::Amend( GIT_COMMIT_HANDLER* aHandler, const std::vector<wxString>& aFiles,
724 const wxString& aMessage, const wxString& aAuthorName,
725 const wxString& aAuthorEmail )
726{
727 git_repository* repo = aHandler->GetRepo();
728
729 if( !repo )
730 return CommitResult::Error;
731
732 if( git_repository_head_unborn( repo ) != 0 )
733 {
734 aHandler->AddErrorString( _( "Cannot amend: the branch has no commits yet." ) );
735 return CommitResult::Error;
736 }
737
738 git_reference* headRef = nullptr;
739
740 if( git_repository_head( &headRef, repo ) != 0 )
741 {
742 aHandler->AddGitError( _( "Could not read the current commit." ) );
743 return CommitResult::Error;
744 }
745
746 KIGIT::GitReferencePtr headRefPtr( headRef );
747 git_commit* headCommit = nullptr;
748
749 if( git_reference_peel( (git_object**) &headCommit, headRef, GIT_OBJECT_COMMIT ) != 0 )
750 {
751 aHandler->AddGitError( _( "Could not read the current commit." ) );
752 return CommitResult::Error;
753 }
754
755 KIGIT::GitCommitPtr headCommitPtr( headCommit );
756 COMMIT_STAGING staging;
757 KIGIT_ERROR_MESSAGE stagingError;
758
759 if( !staging.Begin( repo, aFiles, stagingError ) )
760 {
761 aHandler->AddError( stagingError );
762 return CommitResult::Error;
763 }
764
765 git_index* index = staging.index;
766
767 // The commit being amended, not its parent, or files it already held would disappear.
768 git_tree* headTree = nullptr;
769
770 if( git_commit_tree( &headTree, headCommit ) != 0 )
771 {
772 aHandler->AddGitError( _( "Could not read the current commit." ) );
773 return CommitResult::Error;
774 }
775
776 KIGIT::GitTreePtr headTreePtr( headTree );
777
778 if( git_index_read_tree( index, headTree ) != 0 )
779 {
780 aHandler->AddGitError( _( "Could not prepare the commit." ) );
781 return CommitResult::Error;
782 }
783
784 KIGIT::GitTreePtr treePtr;
785
786 if( !staging.BuildTree( repo, aFiles, treePtr, stagingError ) )
787 {
788 aHandler->AddError( stagingError );
789 return CommitResult::Error;
790 }
791
792 git_tree* tree = treePtr.get();
793
794 git_signature* author = nullptr;
795
796 if( git_signature_now( &author, aAuthorName.utf8_string().c_str(), aAuthorEmail.utf8_string().c_str() ) != 0 )
797 {
798 aHandler->AddGitError( _( "Could not record the commit author." ) );
799 return CommitResult::Error;
800 }
801
802 KIGIT::GitSignaturePtr authorPtr( author );
803 git_oid oid;
804
805 if( git_commit_amend( &oid, headCommit, "HEAD", author, author, nullptr, aMessage.utf8_string().c_str(), tree )
806 != 0 )
807 {
808 aHandler->AddGitError( _( "Could not amend the commit." ) );
809 return CommitResult::Error;
810 }
811
812 // The commit exists, so only the index is left. If anything restaged meanwhile, leave it.
814 || ( staging.haveIndexAtStart && indexChangedSince( index, staging.indexAtStart ) ) )
815 {
816 git_index_read( index, 1 );
817 aHandler->AddErrorString( _( "The commit was amended, but the list of staged files was left "
818 "alone, because the staged files changed outside KiCad while "
819 "this ran." ) );
821 }
822
823 REPUBLISH_RESULT republished = republishIndex( index, staging.committedEntries, staging.selectedPaths );
824
825 if( republished == REPUBLISH_RESULT::CHANGED_EXTERNALLY )
826 {
827 aHandler->AddErrorString( _( "The commit was amended, but the list of staged files was left "
828 "alone, because another program kept changing it." ) );
830 }
831
832 if( republished == REPUBLISH_RESULT::WRITE_FAILED )
833 {
834 aHandler->AddGitError( _( "The commit was amended, but the list of staged files could not be updated." ) );
836 }
837
838 staging.scratchGuard.armed = false;
839
841}
842
843
844// 1 when a remote-tracking branch already holds aCommit, naming one in aRemoteRef, 0 when none does, negative on a
845// libgit2 error
846static int reachableFromRemote( git_repository* aRepo, const git_oid& aCommit, wxString& aRemoteRef )
847{
848 git_reference_iterator* rawIter = nullptr;
849
850 if( int rc = git_reference_iterator_glob_new( &rawIter, aRepo, "refs/remotes/*" ); rc != GIT_OK )
851 return rc;
852
853 KIGIT::GitReferenceIteratorPtr iter( rawIter );
854 std::vector<git_oid> tips;
855 std::vector<wxString> names;
856 git_reference* rawRef = nullptr;
857 int rc = GIT_OK;
858
859 while( ( rc = git_reference_next( &rawRef, iter.get() ) ) == GIT_OK )
860 {
861 KIGIT::GitReferencePtr ref( rawRef );
862
863 // origin/HEAD names a branch this loop visits anyway, and may dangle
864 if( git_reference_type( ref.get() ) == GIT_REFERENCE_SYMBOLIC )
865 continue;
866
867 git_object* rawTip = nullptr;
868
869 if( int peel = git_reference_peel( &rawTip, ref.get(), GIT_OBJECT_COMMIT ); peel != GIT_OK )
870 return peel;
871
872 KIGIT::GitObjectPtr tip( rawTip );
873 tips.push_back( *git_object_id( tip.get() ) );
874 names.push_back( wxString::FromUTF8( git_reference_shorthand( ref.get() ) ) );
875 }
876
877 if( rc != GIT_ITEROVER )
878 return rc;
879
880 if( tips.empty() )
881 return 0;
882
883#if LIBGIT2_VER_MAJOR > 1 || ( LIBGIT2_VER_MAJOR == 1 && LIBGIT2_VER_MINOR >= 5 )
884 int reachable = git_graph_reachable_from_any( aRepo, &aCommit, tips.data(), tips.size() );
885
886 if( reachable <= 0 ) // Not reachable, or an error occurred
887 return reachable;
888
889 // One walk answers the common unpublished case, so only a published commit pays to find which branch holds it
890 for( size_t ii = 0; ii < tips.size(); ++ii )
891 {
892 reachable = git_graph_reachable_from_any( aRepo, &aCommit, &tips[ii], 1 );
893
894 if( reachable < 0 ) // Error occurred
895 return reachable;
896
897 if( reachable > 0 )
898 {
899 aRemoteRef = names[ii];
900 return 1;
901 }
902 }
903
904 return 1;
905#else
906 for( size_t ii = 0; ii < tips.size(); ++ii )
907 {
908 int reachable =
909 git_oid_equal( &aCommit, &tips[ii] ) ? 1 : git_graph_descendant_of( aRepo, &tips[ii], &aCommit );
910
911 if( reachable < 0 ) // Error occurred
912 return reachable;
913
914 if( reachable > 0 )
915 {
916 aRemoteRef = names[ii];
917 return 1;
918 }
919 }
920
921 return 0;
922#endif
923}
924
925
926UndoCommitResult LIBGIT_BACKEND::UndoLastCommit( GIT_COMMIT_HANDLER* aHandler, const wxString& aExpectedBranch,
927 const git_oid& aExpectedHead, wxString& aMessage )
928{
929 git_repository* repo = aHandler->GetRepo();
930
931 if( !repo )
933
934 git_reference* rawHead = nullptr;
935
936 if( git_reference_lookup( &rawHead, repo, "HEAD" ) != GIT_OK )
937 {
938 aHandler->AddGitError( _( "Could not read the current commit." ) );
940 }
941
942 KIGIT::GitReferencePtr head( rawHead );
943 const char* branchName = git_reference_symbolic_target( head.get() );
944
945 // A detached HEAD has no branch to move back
946 if( !branchName || aExpectedBranch.IsEmpty() || wxString::FromUTF8( branchName ) != aExpectedBranch )
948
949 git_reference* rawBranch = nullptr;
950 int lookup = git_reference_lookup( &rawBranch, repo, branchName );
951
952 if( lookup == GIT_ENOTFOUND )
954
955 if( lookup != GIT_OK )
956 {
957 aHandler->AddGitError( _( "Could not read the current commit." ) );
959 }
960
961 KIGIT::GitReferencePtr branch( rawBranch );
962 const git_oid* tip = git_reference_target( branch.get() );
963
964 if( !tip || !git_oid_equal( tip, &aExpectedHead ) )
966
967 if( aHandler->IsOperationInProgress() )
968 {
969 aHandler->AddErrorString( _( "Finish or abandon the current Git operation before undoing a commit." ) );
971 }
972
973 git_commit* rawCommit = nullptr;
974
975 if( git_commit_lookup( &rawCommit, repo, &aExpectedHead ) != GIT_OK )
976 {
977 aHandler->AddGitError( _( "Could not read the current commit." ) );
979 }
980
981 KIGIT::GitCommitPtr commit( rawCommit );
982 int published = reachableFromRemote( repo, aExpectedHead, aMessage );
983
984 if( published < 0 )
985 {
986 aHandler->AddGitError( _( "Could not check whether the commit was already sent to a remote." ) );
988 }
989
990 if( published > 0 )
992
993 int moved = GIT_OK;
994
995 // Both writes fail if the branch moved since it was read, so a commit made meanwhile is never dropped
996 if( git_commit_parentcount( commit.get() ) == 0 )
997 {
998 // git_reference_delete drops the reflog before comparing, so compare under the ref lock instead
999 git_transaction* rawTransaction = nullptr;
1000 moved = git_transaction_new( &rawTransaction, repo );
1001
1002 std::unique_ptr<git_transaction, decltype( &git_transaction_free )> transaction( rawTransaction,
1003 git_transaction_free );
1004 git_oid current;
1005
1006 if( moved == GIT_OK )
1007 moved = git_transaction_lock_ref( transaction.get(), branchName );
1008
1009 if( moved == GIT_OK )
1010 moved = git_reference_name_to_id( &current, repo, branchName );
1011
1012 if( moved == GIT_OK && !git_oid_equal( &current, &aExpectedHead ) )
1013 moved = GIT_EMODIFIED;
1014
1015 if( moved == GIT_OK )
1016 moved = git_transaction_remove( transaction.get(), branchName );
1017
1018 if( moved == GIT_OK )
1019 moved = git_transaction_commit( transaction.get() );
1020 }
1021 else
1022 {
1023 git_reference* rawMoved = nullptr;
1024 moved = git_reference_create_matching( &rawMoved, repo, branchName, git_commit_parent_id( commit.get(), 0 ), 1,
1025 &aExpectedHead, "undo: moving to parent" );
1026 git_reference_free( rawMoved );
1027 }
1028
1029 if( moved == GIT_EMODIFIED )
1031
1032 if( moved != GIT_OK )
1033 {
1034 aHandler->AddGitError( _( "Could not undo the commit." ) );
1036 }
1037
1038 aMessage = wxString::FromUTF8( git_commit_message( commit.get() ) );
1040}
1041
1042
1044{
1045 KIGIT_COMMON* common = aHandler->GetCommon();
1046 std::unique_lock<std::mutex> lock = aHandler->GetActionLock();
1047
1048 if( !lock.owns_lock() )
1049 {
1050 wxLogTrace( traceGit, "GIT_PUSH_HANDLER::PerformPush: Could not lock mutex" );
1051 return PushResult::Busy;
1052 }
1053
1054 // Publish cancellation only after taking the action lock. A cancelled or closing project
1055 // must not start network work when a preceding read finally releases the repository.
1056 KIGIT_COMMON::OPERATION_GUARD operation( common, aHandler->CancelToken() );
1057
1058 if( aHandler->IsThisOperationCancelled() || !aHandler->GetRepo() )
1059 return PushResult::Error;
1060
1061 const wxString targetChanged = _( "The branch or its last commit changed while the push was waiting. "
1062 "Review the changes and try again." );
1063
1064 auto matchesExpectedTarget = [aHandler]( git_reference* aHead )
1065 {
1066 if( !aHandler->HasExpectedTarget() )
1067 return true;
1068
1069 if( !aHead || !git_reference_is_branch( aHead ) )
1070 return false;
1071
1072 const git_oid* oid = git_reference_target( aHead );
1073 wxString branch = wxString::FromUTF8( git_reference_shorthand( aHead ) );
1074 wxString commit = oid ? wxString::FromUTF8( git_oid_tostr_s( oid ) ) : wxString();
1075 return aHandler->MatchesExpectedTarget( branch, commit );
1076 };
1077
1078 // Reject a changed confirmation before connecting to the remote. The target is checked
1079 // again when selecting the ref below, because another program can update Git during a connect.
1080 if( aHandler->HasExpectedTarget() )
1081 {
1082 git_reference* expectedHead = nullptr;
1083 git_repository_head( &expectedHead, aHandler->GetRepo() );
1084 KIGIT::GitReferencePtr expectedHeadPtr( expectedHead );
1085
1086 if( !matchesExpectedTarget( expectedHead ) )
1087 {
1088 aHandler->AddErrorString( targetChanged );
1089 return PushResult::Error;
1090 }
1091 }
1092
1093 wxString remoteName = common->GetRemoteNameOrDefault();
1094 std::string remoteNameUtf8 = remoteName.utf8_string();
1095 git_remote* remote = nullptr;
1096
1097 if( int rc = git_remote_lookup( &remote, aHandler->GetRepo(), remoteNameUtf8.c_str() ); rc != GIT_OK )
1098 {
1099 reportRemoteLookupFailure( aHandler, rc, remoteName );
1100 return PushResult::Error;
1101 }
1102
1103 KIGIT::GitRemotePtr remotePtr(remote);
1104
1105 // The URL may have changed outside KiCad, and libgit2 connects to the push URL when there is one
1106 const char* pushUrl = git_remote_pushurl( remote ) ? git_remote_pushurl( remote ) : git_remote_url( remote );
1107
1108 // The push dials this remote object, so checking its address here pins where the push goes
1109 if( !aHandler->MatchesExpectedDestination( remoteName, pushUrl ? wxString::FromUTF8( pushUrl ) : wxString() ) )
1110 {
1111 aHandler->AddErrorString( _( "The remote changed while the push was waiting. Review it and try again." ) );
1112 return PushResult::Error;
1113 }
1114
1115 if( pushUrl )
1116 common->SyncRemoteUrl( wxString::FromUTF8( pushUrl ) );
1117
1118 // Cancelled while this task was still queued, so it must not start network work.
1119 if( aHandler->IsThisOperationCancelled() )
1120 return PushResult::Error;
1121
1122 // A redirect would land the pinned push on a server nobody confirmed. Older libgit2 versions
1123 // cannot disable redirects, so this protection is unavailable with those versions.
1124 KIGIT::REMOTE_TRANSPORT transport( aHandler, remote, !aHandler->HasExpectedDestination() );
1125 KIGIT::GitReferencePtr headPtr;
1126 bool refused = false;
1127
1128 auto refuse = [&]( const wxString& aMessage )
1129 {
1130 aHandler->AddErrorString( aMessage );
1131 refused = true;
1132 return wxString();
1133 };
1134
1135 // Another program can update Git during a connect, so the target is chosen and checked only once connected
1136 auto connected = [&]() -> wxString
1137 {
1138 git_reference* head = nullptr;
1139
1140 if( git_repository_head( &head, aHandler->GetRepo() ) != 0 )
1141 return refuse( _( "Could not get the repository head." ) );
1142
1143 headPtr.reset( head );
1144
1145 // A detached HEAD is not a branch, so its name is the literal "HEAD" and the remote has no
1146 // branch for it. Without this the push fails with nothing to show the user.
1147 if( !git_reference_is_branch( head ) )
1148 {
1149 return refuse( _( "This project is showing an old snapshot rather than a branch, so there "
1150 "is nothing to push. Go back to a branch first." ) );
1151 }
1152
1153 if( !matchesExpectedTarget( head ) )
1154 return refuse( targetChanged );
1155
1156 // Force push prepends "+" to the refspec source, matching `git push --force`. The source is the
1157 // checked commit, since another program can move the branch before libgit2 reads it
1158 return wxString::Format( wxS( "%s%s:%s" ), aForce ? wxS( "+" ) : wxS( "" ),
1159 wxString::FromUTF8( git_oid_tostr_s( git_reference_target( head ) ) ),
1160 wxString::FromUTF8( git_reference_name( head ) ) );
1161 };
1162
1163 if( int pushResult = transport.Push( connected ) )
1164 {
1165 if( refused )
1166 return PushResult::Error;
1167
1168 aHandler->ReportTransferFailure( transport.Error(), KIGIT_OPERATION::PUSH, remoteName );
1169
1170 // The return code, not the message, which varies between libgit2 versions.
1171 return pushResult == GIT_ENONFASTFORWARD ? PushResult::NonFastForward : PushResult::Error;
1172 }
1173
1174 // First push from this branch: point it at where we just pushed (git push -u).
1175 git_reference* upstreamRef = nullptr;
1176 int rc = git_branch_upstream( &upstreamRef, headPtr.get() );
1177
1178 if( rc == GIT_ENOTFOUND )
1179 {
1180 wxString upstreamName = wxString::Format( "%s/%s", remoteName, git_reference_shorthand( headPtr.get() ) );
1181 git_branch_set_upstream( headPtr.get(), upstreamName.utf8_string().c_str() );
1182 }
1183 else if( rc == GIT_OK )
1184 {
1185 KIGIT::GitReferencePtr upstreamPtr( upstreamRef );
1186 }
1187
1188 return PushResult::Success;
1189}
1190
1191
1192std::map<wxString, FileStatus> LIBGIT_BACKEND::GetFileStatus( GIT_STATUS_HANDLER* aHandler, const wxString& aPathspec,
1193 bool aChangedOnly )
1194{
1195 std::map<wxString, FileStatus> fileStatusMap;
1196 git_repository* repo = aHandler->GetRepo();
1197
1198 if( !repo )
1199 return fileStatusMap;
1200
1201 git_status_options status_options;
1202 git_status_init_options( &status_options, GIT_STATUS_OPTIONS_VERSION );
1203 status_options.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
1204 status_options.flags = GIT_STATUS_OPT_INCLUDE_UNTRACKED | GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS;
1205
1206 // Per-file icons need an entry for every tracked file, so an icon clears when a file goes
1207 // back to unmodified. Listing only changes does not, and costs a walk of the whole repo.
1208 if( !aChangedOnly )
1209 status_options.flags |= GIT_STATUS_OPT_INCLUDE_UNMODIFIED;
1210
1211 std::string pathspec_str;
1212 std::vector<const char*> pathspec_ptrs;
1213
1214 if( !aPathspec.IsEmpty() )
1215 {
1216 pathspec_str = aPathspec.utf8_string();
1217 pathspec_ptrs.push_back( pathspec_str.c_str() );
1218
1219 status_options.pathspec.strings = const_cast<char**>( pathspec_ptrs.data() );
1220 status_options.pathspec.count = pathspec_ptrs.size();
1221
1222 // Callers pass a folder, not a pattern. Without this a folder name holding a glob
1223 // character would match its neighbours instead of itself.
1224 status_options.flags |= GIT_STATUS_OPT_DISABLE_PATHSPEC_MATCH;
1225 }
1226
1227 git_status_list* status_list = nullptr;
1228
1229 if( git_status_list_new( &status_list, repo, &status_options ) != GIT_OK )
1230 {
1231 wxLogTrace( traceGit, "Failed to get git status list: %s", KIGIT_COMMON::GetLastGitError() );
1232 return fileStatusMap;
1233 }
1234
1235 KIGIT::GitStatusListPtr statusListPtr( status_list );
1236
1237 size_t count = git_status_list_entrycount( status_list );
1238 wxString repoWorkDir = aHandler->GetProjectDir();
1239
1240 for( size_t ii = 0; ii < count; ++ii )
1241 {
1242 const git_status_entry* entry = git_status_byindex( status_list, ii );
1243 std::string path( entry->head_to_index ? entry->head_to_index->old_file.path
1244 : entry->index_to_workdir->old_file.path );
1245
1246 wxString absPath = repoWorkDir + path;
1247 fileStatusMap[absPath] = FileStatus{ absPath,
1248 aHandler->ConvertStatus( entry->status ),
1249 static_cast<unsigned int>( entry->status ) };
1250 }
1251
1252 return fileStatusMap;
1253}
1254
1255
1257{
1258 git_repository* repo = aHandler->GetRepo();
1259
1260 if( !repo )
1261 return wxEmptyString;
1262
1263 git_reference* currentBranchReference = nullptr;
1264 int rc = git_repository_head( &currentBranchReference, repo );
1265 KIGIT::GitReferencePtr currentBranchReferencePtr( currentBranchReference );
1266
1267 if( currentBranchReference )
1268 {
1269 return git_reference_shorthand( currentBranchReference );
1270 }
1271 else if( rc == GIT_EUNBORNBRANCH )
1272 {
1273 return wxEmptyString;
1274 }
1275 else
1276 {
1277 wxLogTrace( traceGit, "Failed to lookup current branch: %s", KIGIT_COMMON::GetLastGitError() );
1278 return wxEmptyString;
1279 }
1280}
1281
1282
1284 const std::set<wxString>& aLocalChanges,
1285 const std::set<wxString>& aRemoteChanges,
1286 std::map<wxString, FileStatus>& aFileStatus )
1287{
1288 git_repository* repo = aHandler->GetRepo();
1289
1290 if( !repo )
1291 return;
1292
1293 wxString repoWorkDir = aHandler->GetProjectDir();
1294
1295 for( auto& [absPath, fileStatus] : aFileStatus )
1296 {
1297 wxString relativePath = absPath;
1298 if( relativePath.StartsWith( repoWorkDir ) )
1299 {
1300 relativePath = relativePath.Mid( repoWorkDir.length() );
1301
1302#ifdef _WIN32
1303 relativePath.Replace( wxS( "\\" ), wxS( "/" ) );
1304#endif
1305 }
1306
1307 std::string relativePathStd = relativePath.ToStdString();
1308
1309 if( fileStatus.status == KIGIT_COMMON::GIT_STATUS::GIT_STATUS_CURRENT )
1310 {
1311 if( aLocalChanges.count( relativePathStd ) )
1313 else if( aRemoteChanges.count( relativePathStd ) )
1315 }
1316 }
1317}
1318
1319
1321{
1322 return aHandler->GetProjectDir();
1323}
1324
1325
1326bool LIBGIT_BACKEND::GetConfigString( GIT_CONFIG_HANDLER* aHandler, const wxString& aKey, wxString& aValue )
1327{
1328 git_repository* repo = aHandler->GetRepo();
1329
1330 if( !repo )
1331 return false;
1332
1333 git_config* config = nullptr;
1334
1335 if( git_repository_config( &config, repo ) != GIT_OK )
1336 {
1337 wxLogTrace( traceGit, "Failed to get repository config: %s", KIGIT_COMMON::GetLastGitError() );
1338 return false;
1339 }
1340
1341 KIGIT::GitConfigPtr configPtr( config );
1342
1343 git_config_entry* entry = nullptr;
1344 int result = git_config_get_entry( &entry, config, aKey.utf8_string().c_str() );
1345 KIGIT::GitConfigEntryPtr entryPtr( entry );
1346
1347 if( result != GIT_OK || entry == nullptr )
1348 {
1349 wxLogTrace( traceGit, "Config key '%s' not found", aKey );
1350 return false;
1351 }
1352
1353 aValue = wxString( entry->value );
1354 return true;
1355}
1356
1357
1358bool LIBGIT_BACKEND::IsRepository( GIT_INIT_HANDLER* aHandler, const wxString& aPath )
1359{
1360 git_repository* repo = nullptr;
1361 int error = git_repository_open( &repo, aPath.utf8_string().c_str() );
1362
1363 if( error == 0 )
1364 {
1365 git_repository_free( repo );
1366 return true;
1367 }
1368
1369 // A repository git refuses to open is still a repository. Answering false here sends the
1370 // initialize path into reinitializing it.
1371#if KIGIT_HAS_EOWNER
1372 return error == GIT_EOWNER;
1373#else
1374 return false;
1375#endif
1376}
1377
1378
1379// Names the unborn branch Add to Version Control created, so a fetch can tell it from a later orphan
1380static const char ADOPT_REMOTE_BRANCH_KEY[] = "kicad.adoptRemoteBranch";
1381
1382
1383static wxString unbornBranchName( git_repository* aRepo )
1384{
1385 git_reference* head = nullptr;
1386 wxString name;
1387
1388 if( git_repository_head_unborn( aRepo ) != 1 || git_reference_lookup( &head, aRepo, "HEAD" ) != GIT_OK )
1389 return name;
1390
1391 KIGIT::GitReferencePtr headPtr( head );
1392
1393 if( const char* target = git_reference_symbolic_target( head ) )
1394 wxString::FromUTF8( target ).StartsWith( wxS( "refs/heads/" ), &name );
1395
1396 return name;
1397}
1398
1399
1401{
1402 const wxString branch = unbornBranchName( aRepo );
1403 git_config* config = nullptr;
1404 git_config* local = nullptr;
1405
1406 if( branch.IsEmpty() || git_repository_config( &config, aRepo ) != GIT_OK )
1407 return false;
1408
1409 KIGIT::GitConfigPtr configPtr( config );
1410
1411 if( git_config_open_level( &local, config, GIT_CONFIG_LEVEL_LOCAL ) != GIT_OK )
1412 return false;
1413
1414 KIGIT::GitConfigPtr localPtr( local );
1415
1416 return git_config_set_string( local, ADOPT_REMOTE_BRANCH_KEY, branch.utf8_str() ) == GIT_OK;
1417}
1418
1419
1421{
1422 if( IsRepository( aHandler, aPath ) )
1423 {
1425 }
1426
1427 git_repository* repo = nullptr;
1428
1429 if( git_repository_init( &repo, aPath.utf8_string().c_str(), 0 ) != GIT_OK )
1430 {
1431 if( repo )
1432 git_repository_free( repo );
1433
1434 aHandler->AddError( wxString::Format( _( "Could not set up version control in %s." ), aPath ),
1436 return InitResult::Error;
1437 }
1438
1439 aHandler->GetCommon()->SetRepo( repo );
1440
1441 if( !markForRemoteBranchAdoption( repo ) )
1442 {
1443 aHandler->AddGitError( wxString::Format( _( "Could not set up version control in %s." ), aPath ) );
1444 return InitResult::Error;
1445 }
1446
1447 wxLogTrace( traceGit, "Successfully initialized Git repository at %s", aPath );
1448 return InitResult::Success;
1449}
1450
1451
1453{
1454 if( aConfig.url.IsEmpty() )
1455 return true;
1456
1457 git_repository* repo = aHandler->GetRepo();
1458
1459 if( !repo )
1460 {
1461 aHandler->AddErrorString( _( "No repository available to set up remote" ) );
1462 return false;
1463 }
1464
1466 git_remote* remote = nullptr;
1467 int error;
1468
1469 if( git_remote_lookup( &remote, repo, "origin" ) == GIT_OK )
1470 {
1471 KIGIT::GitRemotePtr remotePtr( remote );
1472 error = git_remote_set_url( repo, "origin", parsed.url.utf8_str() );
1473 }
1474 else
1475 {
1476 error = git_remote_create_with_fetchspec( &remote, repo, "origin", parsed.url.utf8_str(),
1477 "+refs/heads/*:refs/remotes/origin/*" );
1478 KIGIT::GitRemotePtr remotePtr( remote );
1479 }
1480
1481 if( error != GIT_OK )
1482 {
1483 KIGIT_FAILURE_CONTEXT context;
1485 context.remoteName = wxS( "origin" );
1486 context.url = parsed.url;
1487
1488 KIGIT_FAILURE_REPORT report =
1490 aHandler->AddError( report.summary, report.details );
1491 return false;
1492 }
1493
1494 // SetRemote clears cached credentials, so apply the accepted credentials afterwards.
1495 // The username embedded in the address takes precedence over a saved username.
1496 KIGIT_COMMON* common = aHandler->GetCommon();
1497 common->SetRemote( parsed.url );
1498 common->SetUsername( parsed.username.IsEmpty() ? aConfig.username : parsed.username );
1499 common->SetPassword( aConfig.password.IsEmpty() ? parsed.password : aConfig.password );
1500 common->SetSSHKey( aConfig.sshKey );
1501
1502 wxLogTrace( traceGit, "Successfully set up remote origin" );
1503 return true;
1504}
1505
1506
1507// The short-name lookup's code, since it is the one that tells a missing branch from a bad name
1508static int lookup_branch_reference( git_repository* repo, const wxString& aBranchName, git_reference** aReference )
1509{
1510 if( git_reference_lookup( aReference, repo, aBranchName.utf8_string().c_str() ) == GIT_OK )
1511 return GIT_OK;
1512
1513 return git_reference_dwim( aReference, repo, aBranchName.utf8_string().c_str() );
1514}
1515
1516
1517BranchResult LIBGIT_BACKEND::SwitchToBranch( GIT_BRANCH_HANDLER* aHandler, const wxString& aBranchName )
1518{
1519 git_repository* repo = aHandler->GetRepo();
1520
1521 if( !repo )
1522 {
1523 aHandler->AddErrorString( _( "No repository available" ) );
1524 return BranchResult::Error;
1525 }
1526
1527 git_reference* branchRef = nullptr;
1528
1529 if( int rc = lookup_branch_reference( repo, aBranchName, &branchRef ); rc != GIT_OK )
1530 {
1531 if( rc == GIT_ENOTFOUND )
1532 {
1533 aHandler->AddError( wxString::Format( _( "The branch '%s' no longer exists." ), aBranchName ),
1534 wxEmptyString );
1536 }
1537
1538 aHandler->AddError( wxString::Format( _( "Could not open the branch '%s'." ), aBranchName ),
1540 return BranchResult::Error;
1541 }
1542
1543 KIGIT::GitReferencePtr branchRefPtr( branchRef );
1544
1545 // A remote-tracking branch is a view of someone else's work rather than somewhere to
1546 // stand. Checking one out can only attach HEAD to a local branch of the same name, which
1547 // may sit at another commit, leaving HEAD and the working tree describing different things.
1548 if( git_reference_is_remote( branchRef ) )
1549 {
1550 aHandler->AddErrorString( wxString::Format( _( "'%s' is a branch on the remote, so the project "
1551 "cannot be switched to it. Make a local branch from "
1552 "it instead." ),
1553 aBranchName ) );
1554 return BranchResult::Error;
1555 }
1556
1557 const char* branchRefName = git_reference_name( branchRef );
1558 git_object* branchObj = nullptr;
1559
1560 if( git_revparse_single( &branchObj, repo, aBranchName.utf8_string().c_str() ) != GIT_OK )
1561 {
1562 aHandler->AddError( wxString::Format( _( "Could not open the branch '%s'." ), aBranchName ),
1564 return BranchResult::Error;
1565 }
1566
1567 KIGIT::GitObjectPtr branchObjPtr( branchObj );
1568
1569
1570 git_checkout_options checkoutOpts;
1571 git_checkout_init_options( &checkoutOpts, GIT_CHECKOUT_OPTIONS_VERSION );
1572 checkoutOpts.checkout_strategy = GIT_CHECKOUT_SAFE;
1573
1574 std::vector<wxString> conflictPaths;
1575
1576 checkoutOpts.notify_flags = GIT_CHECKOUT_NOTIFY_CONFLICT;
1577 checkoutOpts.notify_payload = &conflictPaths;
1578 checkoutOpts.notify_cb = []( git_checkout_notify_t aWhy, const char* aPath, const git_diff_file*,
1579 const git_diff_file*, const git_diff_file*, void* aPayload ) -> int
1580 {
1581 if( aWhy == GIT_CHECKOUT_NOTIFY_CONFLICT && aPath )
1582 static_cast<std::vector<wxString>*>( aPayload )->push_back( wxString::FromUTF8( aPath ) );
1583
1584 return 0;
1585 };
1586
1587 if( int rc = git_checkout_tree( repo, branchObj, &checkoutOpts ) )
1588 {
1589 // A stash does not cover never-committed files, so those need their own advice.
1590 if( rc == GIT_ECONFLICT )
1591 {
1592 wxString fileList;
1593 bool anyUntracked = false;
1594 size_t shown = std::min<size_t>( conflictPaths.size(), 10 );
1595
1596 for( size_t i = 0; i < shown; i++ )
1597 {
1598 bool tracked = IsPathInHead( repo, conflictPaths[i] );
1599
1600 anyUntracked |= !tracked;
1601 wxString tag = tracked ? wxString() : wxS( " " ) + _( "(never committed)" );
1602
1603 fileList << conflictPaths[i] << tag << wxS( "\n" );
1604 }
1605
1606 if( conflictPaths.size() > shown )
1607 fileList << wxString::Format( _( "and %zu more\n" ), conflictPaths.size() - shown );
1608
1609 wxString advice = anyUntracked ? _( "Commit or stash your changes first. Files that were never "
1610 "committed are not included in a stash, so commit or discard "
1611 "those from the Version Control panel." )
1612 : _( "Commit or stash your changes first." );
1613
1614 aHandler->AddErrorString( wxString::Format( _( "Switching to branch '%s' would overwrite:\n\n"
1615 "%s\n%s" ),
1616 aBranchName, fileList, advice ) );
1618 }
1619
1620 aHandler->AddError( wxString::Format( _( "Could not switch to the branch '%s'." ), aBranchName ),
1623 }
1624
1625 if( git_repository_set_head( repo, branchRefName ) != GIT_OK )
1626 {
1627 aHandler->AddError( wxString::Format( _( "Could not switch to the branch '%s'." ), aBranchName ),
1629 return BranchResult::Error;
1630 }
1631
1632 wxLogTrace( traceGit, "Successfully switched to branch '%s'", aBranchName );
1633 return BranchResult::Success;
1634}
1635
1636
1637// Use callbacks declared/implemented in kicad_git_common.h/.cpp
1638
1639// A local default of master would otherwise push beside a server created with main. False means
1640// the move was due and failed
1641static bool adoptRemoteBranch( git_repository* aRepo, const wxString& aRemoteName,
1642 const std::vector<wxString>& aRemoteBranches )
1643{
1644 git_config* config = nullptr;
1645 git_config* local = nullptr;
1646
1647 if( git_repository_config( &config, aRepo ) != GIT_OK )
1648 return true;
1649
1650 KIGIT::GitConfigPtr configPtr( config );
1651
1652 if( git_config_open_level( &local, config, GIT_CONFIG_LEVEL_LOCAL ) != GIT_OK )
1653 return true;
1654
1655 KIGIT::GitConfigPtr localPtr( local );
1656
1657 git_buf marked = GIT_BUF_INIT;
1658
1659 if( git_config_get_string_buf( &marked, local, ADOPT_REMOTE_BRANCH_KEY ) != GIT_OK )
1660 return true;
1661
1662 KIGIT::GitBufPtr markedPtr( &marked );
1663 const wxString localName = unbornBranchName( aRepo );
1664
1665 git_branch_iterator* iterator = nullptr;
1666 git_reference* ref = nullptr;
1667 git_branch_t type;
1668
1669 if( git_branch_iterator_new( &iterator, aRepo, GIT_BRANCH_LOCAL ) != GIT_OK )
1670 return false;
1671
1672 KIGIT::GitBranchIteratorPtr iteratorPtr( iterator );
1673 const int rc = git_branch_next( &ref, &type, iterator );
1674 KIGIT::GitReferencePtr refPtr( rc == GIT_OK ? ref : nullptr );
1675
1676 if( rc != GIT_OK && rc != GIT_ITEROVER )
1677 return false;
1678
1679 git_reflog* reflog = nullptr;
1680
1681 if( git_reflog_read( &reflog, aRepo, "HEAD" ) != GIT_OK )
1682 return false;
1683
1684 std::unique_ptr<git_reflog, decltype( &git_reflog_free )> reflogPtr( reflog, git_reflog_free );
1685
1686 // A commit, any branch, or HEAD history means the repository has moved on since it was made
1687 if( rc == GIT_OK || git_reflog_entrycount( reflog ) != 0 || localName.IsEmpty()
1688 || localName != wxString::FromUTF8( marked.ptr ) )
1689 {
1690 git_config_delete_entry( local, ADOPT_REMOTE_BRANCH_KEY );
1691 return true;
1692 }
1693
1694 // An empty remote keeps the question open until the first push gives it a branch
1695 if( aRemoteBranches.empty() )
1696 return true;
1697
1698 // Only a single remote branch says unambiguously where the first commit belongs
1699 if( aRemoteBranches.size() != 1 || aRemoteBranches.front() == localName )
1700 {
1701 git_config_delete_entry( local, ADOPT_REMOTE_BRANCH_KEY );
1702 return true;
1703 }
1704
1705 const wxString branch = aRemoteBranches.front();
1706 const wxString section = wxS( "branch." ) + branch;
1707 git_transaction* transaction = nullptr;
1708
1709 if( git_config_lock( &transaction, local ) != GIT_OK )
1710 return false;
1711
1712 std::unique_ptr<git_transaction, decltype( &git_transaction_free )> transactionPtr( transaction,
1713 git_transaction_free );
1714
1715 // Upstream first, so a failure leaves HEAD where it was rather than on a branch with half its tracking
1716 if( git_config_set_string( local, ( section + wxS( ".remote" ) ).utf8_str(), aRemoteName.utf8_str() ) != GIT_OK
1717 || git_config_set_string( local, ( section + wxS( ".merge" ) ).utf8_str(),
1718 ( wxS( "refs/heads/" ) + branch ).utf8_str() )
1719 != GIT_OK
1720 || git_transaction_commit( transaction ) != GIT_OK
1721 || git_repository_set_head( aRepo, ( wxS( "refs/heads/" ) + branch ).utf8_str() ) != GIT_OK )
1722 {
1723 wxLogTrace( traceGit, "adoptRemoteBranch: could not move %s to %s: %s", localName, branch,
1725 return false;
1726 }
1727
1728 git_config_delete_entry( local, ADOPT_REMOTE_BRANCH_KEY );
1729 wxLogTrace( traceGit, "adoptRemoteBranch: first commit goes to %s instead of %s", branch, localName );
1730 return true;
1731}
1732
1733
1734// aRemoteHasBranches, when given, is false only when the server advertised no branch at all
1735static bool fetchRemote( GIT_PULL_HANDLER* aHandler, bool aSkipLock, bool* aRemoteHasBranches )
1736{
1737 // A pull already holds the lock when it fetches, and relocking from the owner is undefined.
1738 std::unique_lock<std::mutex> lock;
1739
1740 if( !aSkipLock )
1741 {
1742 lock = aHandler->GetActionLock();
1743
1744 if( !lock.owns_lock() )
1745 {
1746 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformFetch() - Could not lock mutex" );
1747 aHandler->AddErrorString( KIGIT::BusyMessage() );
1748 return false;
1749 }
1750 }
1751
1752 // A nested fetch must not republish or retire the pull's token while the pull still runs.
1753 std::optional<KIGIT_COMMON::OPERATION_GUARD> operation;
1754
1755 if( !aSkipLock )
1756 operation.emplace( aHandler->GetCommon(), aHandler->CancelToken() );
1757
1758 // A close or cancellation while waiting also applies before reading remote configuration.
1759 if( aHandler->IsThisOperationCancelled() || !aHandler->GetRepo() )
1760 return false;
1761
1762 wxString remoteName = aHandler->GetCommon()->GetRemoteNameOrDefault();
1763 std::string remoteNameUtf8 = remoteName.utf8_string();
1764 git_remote* remote = nullptr;
1765
1766 if( int rc = git_remote_lookup( &remote, aHandler->GetRepo(), remoteNameUtf8.c_str() ); rc != GIT_OK )
1767 {
1768 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformFetch() - Failed to lookup remote '%s'", remoteName );
1769 reportRemoteLookupFailure( aHandler, rc, remoteName );
1770 return false;
1771 }
1772
1773 KIGIT::GitRemotePtr remotePtr( remote );
1774
1775 // The URL may have changed outside KiCad, so the credentials follow what libgit2 connects to
1776 if( const char* url = git_remote_url( remote ) )
1777 aHandler->GetCommon()->SyncRemoteUrl( wxString::FromUTF8( url ) );
1778
1779 // Do not SetShuttingDown( false ) here. A close or a preference change can raise the flag
1780 // after this fetch starts, and clearing it would strand the caller on the transfer.
1781
1782 // Cancelled while this task was still queued, so it must not start network work.
1783 if( aHandler->IsThisOperationCancelled() )
1784 return false;
1785
1786 KIGIT::REMOTE_TRANSPORT transport( aHandler, remote );
1787 std::vector<wxString> remoteBranches;
1788
1789 if( transport.Fetch( &remoteBranches ) )
1790 {
1791 aHandler->ReportTransferFailure( transport.Error(), KIGIT_OPERATION::FETCH, remoteName );
1792 return false;
1793 }
1794
1795 if( aRemoteHasBranches )
1796 *aRemoteHasBranches = !remoteBranches.empty();
1797
1798 if( !adoptRemoteBranch( aHandler->GetRepo(), remoteName, remoteBranches ) )
1799 {
1800 aHandler->AddGitError( wxString::Format( _( "Fetched from '%s', but could not switch the new repository "
1801 "to the remote's branch." ),
1802 remoteName ) );
1803 return false;
1804 }
1805
1806 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformFetch() - Fetch completed successfully" );
1807 return true;
1808}
1809
1810
1811bool LIBGIT_BACKEND::PerformFetch( GIT_PULL_HANDLER* aHandler, bool aSkipLock )
1812{
1813 return fetchRemote( aHandler, aSkipLock, nullptr );
1814}
1815
1816
1817static bool rollbackWorkingTree( git_repository* aRepo, git_commit* aHeadCommit, git_tree* aWrittenTree );
1818static bool restorePathsFromCommit( git_repository* aRepo, git_commit* aCommit,
1819 const std::vector<std::string>& aPaths );
1820
1821
1822// A failed checkout leaves the cached index ahead of disk, which reads as phantom staged changes.
1824{
1825 git_index* index = nullptr;
1826
1827 if( git_repository_index( &index, aRepo ) == GIT_OK )
1828 {
1829 KIGIT::GitIndexPtr indexPtr( index );
1830 git_index_read( index, 1 );
1831 }
1832}
1833
1834
1841
1842
1843// After a failed operation under the action lock, this is the set that operation disturbed.
1844static std::vector<std::string> changedPaths( git_repository* aRepo )
1845{
1846 std::vector<std::string> paths;
1847
1848 git_status_options statusOpts;
1849 git_status_init_options( &statusOpts, GIT_STATUS_OPTIONS_VERSION );
1850 statusOpts.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
1851
1852 git_status_list* statusList = nullptr;
1853
1854 if( git_status_list_new( &statusList, aRepo, &statusOpts ) != GIT_OK )
1855 return paths;
1856
1857 KIGIT::GitStatusListPtr statusListPtr( statusList );
1858
1859 for( size_t ii = 0; ii < git_status_list_entrycount( statusList ); ii++ )
1860 {
1861 const git_status_entry* entry = git_status_byindex( statusList, ii );
1862
1863 if( entry->head_to_index && entry->head_to_index->new_file.path )
1864 paths.emplace_back( entry->head_to_index->new_file.path );
1865 else if( entry->index_to_workdir && entry->index_to_workdir->new_file.path )
1866 paths.emplace_back( entry->index_to_workdir->new_file.path );
1867 }
1868
1869 return paths;
1870}
1871
1872
1873// Tracked files only. Callers read CLEAN as permission to roll back over the tree, so an
1874// unreadable status gets its own answer rather than passing as clean.
1876{
1877 git_status_options statusOpts;
1878 git_status_init_options( &statusOpts, GIT_STATUS_OPTIONS_VERSION );
1879 statusOpts.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
1880
1881 git_status_list* statusList = nullptr;
1882
1883 if( git_status_list_new( &statusList, aRepo, &statusOpts ) != GIT_OK )
1884 return TREE_STATE::UNKNOWN;
1885
1886 KIGIT::GitStatusListPtr statusListPtr( statusList );
1887
1888 return git_status_list_entrycount( statusList ) > 0 ? TREE_STATE::DIRTY : TREE_STATE::CLEAN;
1889}
1890
1891
1892// libgit2 refuses these with a count and no name, so the caller names them.
1893static bool untrackedFilesOverwrittenBy( git_repository* aRepo, git_tree* aIncomingTree,
1894 std::vector<wxString>& aCollisions )
1895{
1896 git_status_options statusOpts;
1897 git_status_init_options( &statusOpts, GIT_STATUS_OPTIONS_VERSION );
1898 statusOpts.show = GIT_STATUS_SHOW_WORKDIR_ONLY;
1899 statusOpts.flags = GIT_STATUS_OPT_INCLUDE_UNTRACKED | GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS;
1900
1901 git_status_list* statusList = nullptr;
1902
1903 // An unreadable status must not read as nothing in the way, or the checkout overwrites it.
1904 if( git_status_list_new( &statusList, aRepo, &statusOpts ) != GIT_OK )
1905 return false;
1906
1907 KIGIT::GitStatusListPtr statusListPtr( statusList );
1908 size_t count = git_status_list_entrycount( statusList );
1909
1910 for( size_t ii = 0; ii < count; ++ii )
1911 {
1912 const git_status_entry* entry = git_status_byindex( statusList, ii );
1913
1914 if( !( entry->status & GIT_STATUS_WT_NEW ) || !entry->index_to_workdir )
1915 continue;
1916
1917 const char* path = entry->index_to_workdir->new_file.path;
1918 git_tree_entry* treeEntry = nullptr;
1919
1920 if( path && git_tree_entry_bypath( &treeEntry, aIncomingTree, path ) == GIT_OK )
1921 {
1922 KIGIT::GitTreeEntryPtr treeEntryPtr( treeEntry );
1923 aCollisions.push_back( wxString::FromUTF8( path ) );
1924 }
1925 }
1926
1927 return true;
1928}
1929
1930
1931static wxString describeUntrackedCollisions( const std::vector<wxString>& aPaths )
1932{
1933 wxString listed;
1934
1935 for( const wxString& path : aPaths )
1936 listed += wxS( "\n " ) + path;
1937
1938 return wxString::Format( _( "Getting changes would overwrite files that were never committed:%s\n\n"
1939 "Commit or discard them first." ),
1940 listed );
1941}
1942
1943
1944// A local repository pointed at a remote with history has nothing to merge from, so adopt it.
1945static PullResult adoptRemoteHistory( GIT_PULL_HANDLER* aHandler, const git_oid& aRemoteOid )
1946{
1947 git_repository* repo = aHandler->GetRepo();
1948 git_reference* symbolic = nullptr;
1949 std::string branchRefName;
1950
1951 if( git_reference_lookup( &symbolic, repo, "HEAD" ) == GIT_OK )
1952 {
1953 KIGIT::GitReferencePtr symbolicPtr( symbolic );
1954
1955 if( const char* target = git_reference_symbolic_target( symbolic ) )
1956 branchRefName = target;
1957 }
1958
1959 if( branchRefName.empty() )
1960 {
1961 aHandler->AddErrorString( _( "Could not get the repository head." ) );
1962 return PullResult::Error;
1963 }
1964
1965 git_commit* commit = nullptr;
1966
1967 if( git_commit_lookup( &commit, repo, &aRemoteOid ) != GIT_OK )
1968 {
1969 aHandler->AddGitError( _( "Could not read the fetched commit." ) );
1970 return PullResult::Error;
1971 }
1972
1973 KIGIT::GitCommitPtr commitPtr( commit );
1974 git_tree* tree = nullptr;
1975
1976 if( git_commit_tree( &tree, commit ) != GIT_OK )
1977 {
1978 aHandler->AddGitError( _( "Could not read the fetched commit." ) );
1979 return PullResult::Error;
1980 }
1981
1982 KIGIT::GitTreePtr treePtr( tree );
1983 std::vector<wxString> collisions;
1984
1985 if( !untrackedFilesOverwrittenBy( repo, tree, collisions ) )
1986 {
1987 aHandler->AddErrorString( _( "Could not read the status of the project files, so getting changes was "
1988 "stopped. Files that were never committed could have been overwritten." ) );
1989 return PullResult::Error;
1990 }
1991
1992 if( !collisions.empty() )
1993 {
1994 aHandler->AddErrorString( describeUntrackedCollisions( collisions ) );
1996 }
1997
1998 // The reference goes first, because deleting one just created restores the unborn state,
1999 // while a checkout against no previous commit has nothing to undo from.
2000 git_reference* branchRef = nullptr;
2001
2002 wxString shorthand = wxString::FromUTF8( branchRefName );
2003 shorthand.StartsWith( wxS( "refs/heads/" ), &shorthand );
2004
2005 if( git_reference_create( &branchRef, repo, branchRefName.c_str(), &aRemoteOid, 0, "pull: adopt remote history" )
2006 != GIT_OK )
2007 {
2008 aHandler->AddError( wxString::Format( _( "Could not create the branch '%s'." ), shorthand ),
2010 return PullResult::Error;
2011 }
2012
2013 KIGIT::GitReferencePtr branchRefPtr( branchRef );
2014
2015 git_checkout_options checkoutOpts;
2016 git_checkout_options_init( &checkoutOpts, GIT_CHECKOUT_OPTIONS_VERSION );
2017 checkoutOpts.checkout_strategy = GIT_CHECKOUT_SAFE | GIT_CHECKOUT_RECREATE_MISSING;
2018
2019 if( git_checkout_tree( repo, reinterpret_cast<git_object*>( tree ), &checkoutOpts ) != GIT_OK )
2020 {
2021 wxString gitError = KIGIT_COMMON::GetLastGitError();
2022 bool restored = git_reference_delete( branchRef ) == GIT_OK;
2023
2024 refreshCachedIndex( repo );
2025
2026 aHandler->AddError( restored ? _( "Could not check out the remote branch, so nothing was changed." )
2027 : _( "Could not check out the remote branch, and the project may be partly "
2028 "changed." ),
2029 gitError );
2030 return PullResult::Error;
2031 }
2032
2033 wxString upstream = wxString::Format( "%s/%s", aHandler->GetCommon()->GetRemoteNameOrDefault(), shorthand );
2034 git_branch_set_upstream( branchRef, upstream.utf8_string().c_str() );
2035
2037}
2038
2039
2041{
2043 std::unique_lock<std::mutex> lock = aHandler->GetActionLock();
2044
2045 if( !lock.owns_lock() )
2046 {
2047 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Could not lock mutex" );
2048 aHandler->AddErrorString( KIGIT::BusyMessage() );
2049 return PullResult::Error;
2050 }
2051
2052 // The pull owns cancellation for the whole operation, the fetch inside it included.
2053 KIGIT_COMMON::OPERATION_GUARD operation( aHandler->GetCommon(), aHandler->CancelToken() );
2054
2055 if( aHandler->IsThisOperationCancelled() || !aHandler->GetRepo() )
2056 return PullResult::Error;
2057
2058 bool remoteHasBranches = true;
2059
2060 if( !fetchRemote( aHandler, true, &remoteHasBranches ) )
2061 return PullResult::Error;
2062
2063 git_oid pull_merge_oid = {};
2064
2065 if( git_repository_fetchhead_foreach( aHandler->GetRepo(), fetchhead_foreach_cb, &pull_merge_oid ) )
2066 {
2067 aHandler->AddGitError( _( "Could not read the fetched changes." ) );
2068 return PullResult::Error;
2069 }
2070
2071 // Add Version Control doesn't write branch.<name>.merge, so FETCH_HEAD has no
2072 // merge-marked entry. Fall back to refs/remotes/<remote>/<branch> and persist
2073 // the upstream so subsequent pulls take the normal path.
2074#if ( LIBGIT2_VER_MAJOR >= 1 ) || ( LIBGIT2_VER_MINOR >= 99 )
2075 if( git_oid_is_zero( &pull_merge_oid ) )
2076#else
2077 if( git_oid_iszero( &pull_merge_oid ) )
2078#endif
2079 {
2080 git_reference* head_ref = nullptr;
2081 wxString branch_shorthand;
2082
2083 if( git_repository_head( &head_ref, aHandler->GetRepo() ) == GIT_OK )
2084 {
2085 if( git_reference_is_branch( head_ref ) )
2086 branch_shorthand = wxString::FromUTF8( git_reference_shorthand( head_ref ) );
2087 }
2088 else if( git_repository_head_unborn( aHandler->GetRepo() ) == 1 )
2089 {
2090 // No commit yet, so HEAD is only a branch name and the first pull adopts its remote.
2091 git_reference* symbolic = nullptr;
2092
2093 if( git_reference_lookup( &symbolic, aHandler->GetRepo(), "HEAD" ) == GIT_OK )
2094 {
2095 KIGIT::GitReferencePtr symbolicPtr( symbolic );
2096
2097 if( const char* target = git_reference_symbolic_target( symbolic ) )
2098 wxString::FromUTF8( target ).StartsWith( wxS( "refs/heads/" ), &branch_shorthand );
2099 }
2100 }
2101
2102 KIGIT::GitReferencePtr headRefPtr( head_ref );
2103
2104 if( !branch_shorthand.IsEmpty() )
2105 {
2106 wxString remoteName = aHandler->GetCommon()->GetRemoteNameOrDefault();
2107 wxString remoteRefName = wxString::Format( "refs/remotes/%s/%s", remoteName, branch_shorthand );
2108
2109 if( git_reference_name_to_id( &pull_merge_oid, aHandler->GetRepo(), remoteRefName.utf8_string().c_str() )
2110 == GIT_OK
2111 && head_ref )
2112 {
2113 wxString upstream = wxString::Format( "%s/%s", remoteName, branch_shorthand );
2114 git_branch_set_upstream( head_ref, upstream.utf8_string().c_str() );
2115 }
2116 }
2117 }
2118
2119#if ( LIBGIT2_VER_MAJOR >= 1 ) || ( LIBGIT2_VER_MINOR >= 99 )
2120 if( git_oid_is_zero( &pull_merge_oid ) )
2121#else
2122 if( git_oid_iszero( &pull_merge_oid ) )
2123#endif
2124 {
2125 // An empty remote, as right after Add to Version Control, has nothing to pull yet
2126 if( !remoteHasBranches )
2127 return PullResult::UpToDate;
2128
2129 aHandler->AddErrorString( _( "Nothing to pull: the remote has no branch matching the current local "
2130 "branch." ) );
2131 return PullResult::Error;
2132 }
2133
2134 // KiCad runs no filter program, so merging a version that keeps design files in Git LFS
2135 // would put pointer text where the design belongs. Judged before anything is written.
2136 // With libgit2 before 1.3, this checks only current index and working tree attributes.
2137 if( KIGIT_COMMON* common = aHandler->GetCommon() )
2138 {
2139 wxString example;
2140
2141 if( KIGIT::PROJECT_GIT_UTILS::ProjectUsesGitLfs( *common, &example, &pull_merge_oid ) )
2142 {
2143 aHandler->AddErrorString( wxString::Format(
2144 _( "The changes being fetched keep '%s' in Git LFS, which KiCad cannot read or write. "
2145 "Use git on the command line for this repository." ),
2146 example ) );
2147 return PullResult::Error;
2148 }
2149 }
2150
2151 git_annotated_commit* fetchhead_commit;
2152
2153 if( git_annotated_commit_lookup( &fetchhead_commit, aHandler->GetRepo(), &pull_merge_oid ) )
2154 {
2155 aHandler->AddGitError( _( "Could not read the fetched commit." ) );
2156 return PullResult::Error;
2157 }
2158
2159 KIGIT::GitAnnotatedCommitPtr fetchheadCommitPtr( fetchhead_commit );
2160 const git_annotated_commit* merge_commits[] = { fetchhead_commit };
2161 git_merge_analysis_t merge_analysis;
2162 git_merge_preference_t merge_preference = GIT_MERGE_PREFERENCE_NONE;
2163
2164 if( git_merge_analysis( &merge_analysis, &merge_preference, aHandler->GetRepo(), merge_commits, 1 ) )
2165 {
2166 aHandler->AddGitError( _( "Could not compare the fetched changes with this branch." ) );
2167 return PullResult::Error;
2168 }
2169
2170 if( merge_analysis & GIT_MERGE_ANALYSIS_UNBORN )
2171 return adoptRemoteHistory( aHandler, pull_merge_oid );
2172
2173 if( merge_analysis & GIT_MERGE_ANALYSIS_UP_TO_DATE )
2174 {
2175 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Repository is up to date" );
2176 git_repository_state_cleanup( aHandler->GetRepo() );
2177 return PullResult::UpToDate;
2178 }
2179
2180 if( merge_analysis & GIT_MERGE_ANALYSIS_FASTFORWARD )
2181 {
2182 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Fast-forward merge" );
2183 return handleFastForward( aHandler );
2184 }
2185
2186 if( merge_analysis & GIT_MERGE_ANALYSIS_NORMAL )
2187 {
2188 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Normal merge" );
2189
2190 git_config* config = nullptr;
2191
2192 if( git_repository_config( &config, aHandler->GetRepo() ) != GIT_OK )
2193 {
2194 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Failed to get repository config" );
2195 aHandler->AddGitError( _( "Could not read the repository settings." ) );
2196 return PullResult::Error;
2197 }
2198
2199 KIGIT::GitConfigPtr configPtr( config );
2200
2201 int rebase_value = 0;
2202 int ret = git_config_get_bool( &rebase_value, config, "pull.rebase" );
2203
2204 if( ret == GIT_OK && rebase_value )
2205 {
2206 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Using rebase based on config" );
2207 return handleRebase( aHandler, merge_commits, 1 );
2208 }
2209
2210 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Using merge based on config" );
2211 return handleMerge( aHandler, merge_commits, 1 );
2212 }
2213
2214 wxLogTrace( traceGit, "GIT_PULL_HANDLER::PerformPull() - Merge needs resolution" );
2215 return result;
2216}
2217
2218
2220{
2221 git_reference* rawRef = nullptr;
2222
2223 if( git_repository_head( &rawRef, aHandler->GetRepo() ) )
2224 {
2225 aHandler->AddErrorString( _( "Could not get the repository head." ) );
2226 return PullResult::Error;
2227 }
2228
2229 KIGIT::GitReferencePtr headRef( rawRef );
2230
2231 git_oid updatedRefOid;
2232 const char* branch_shorthand = git_reference_shorthand( rawRef );
2233 wxString remote_name = aHandler->GetRemotename();
2234 wxString remoteBranchName;
2235
2236 // The analysis followed branch.<name>.merge, so move to that branch. Without a configured
2237 // upstream, the remote branch of the same name stands in.
2238 git_reference* upstreamRef = nullptr;
2239
2240 if( git_branch_upstream( &upstreamRef, rawRef ) == GIT_OK )
2241 {
2242 KIGIT::GitReferencePtr upstreamPtr( upstreamRef );
2243 remoteBranchName = wxString::FromUTF8( git_reference_name( upstreamRef ) );
2244 }
2245 else
2246 {
2247 remoteBranchName = wxString::Format( "refs/remotes/%s/%s", remote_name, branch_shorthand );
2248 }
2249
2250 if( int rc = git_reference_name_to_id( &updatedRefOid, aHandler->GetRepo(), remoteBranchName.c_str() );
2251 rc != GIT_OK )
2252 {
2253 wxString shownName = remoteBranchName;
2254 shownName.StartsWith( wxS( "refs/remotes/" ), &shownName );
2255
2256 aHandler->AddError( wxString::Format( rc == GIT_ENOTFOUND ? _( "Could not find the remote branch '%s'." )
2257 : _( "Could not read the remote branch '%s'." ),
2258 shownName ),
2260 return PullResult::Error;
2261 }
2262
2263 git_commit* targetCommit = nullptr;
2264
2265 if( git_commit_lookup( &targetCommit, aHandler->GetRepo(), &updatedRefOid ) != GIT_OK )
2266 {
2267 aHandler->AddGitError( _( "Could not read the fetched commit." ) );
2268 return PullResult::Error;
2269 }
2270
2271 KIGIT::GitCommitPtr targetCommitPtr( targetCommit );
2272
2273 git_tree* targetTree = nullptr;
2274
2275 if( git_commit_tree( &targetTree, targetCommit ) != GIT_OK )
2276 {
2277 aHandler->AddGitError( _( "Could not read the fetched commit." ) );
2278 return PullResult::Error;
2279 }
2280
2281 KIGIT::GitTreePtr targetTreePtr( targetTree );
2282
2283 // A skipped file would leave the local edit reading as a reversal of the remote change.
2284 TREE_STATE treeState = trackedTreeState( aHandler->GetRepo() );
2285
2286 if( treeState == TREE_STATE::UNKNOWN )
2287 {
2288 aHandler->AddGitError( _( "Could not read the status of the project files, so getting changes was stopped." ) );
2289 return PullResult::Error;
2290 }
2291
2292 if( treeState == TREE_STATE::DIRTY )
2293 {
2294 aHandler->AddErrorString( _( "There are changes that are not committed yet, and getting changes would "
2295 "run over them. Commit them first." ) );
2297 }
2298
2299 std::vector<wxString> collisions;
2300
2301 if( !untrackedFilesOverwrittenBy( aHandler->GetRepo(), targetTree, collisions ) )
2302 {
2303 aHandler->AddErrorString( _( "Could not read the status of the project files, so getting changes was "
2304 "stopped. Files that were never committed could have been overwritten." ) );
2305 return PullResult::Error;
2306 }
2307
2308 if( !collisions.empty() )
2309 {
2310 aHandler->AddErrorString( describeUntrackedCollisions( collisions ) );
2312 }
2313
2314 git_checkout_options checkoutOptions;
2315 git_checkout_init_options( &checkoutOptions, GIT_CHECKOUT_OPTIONS_VERSION );
2316 auto notify_cb =
2317 []( git_checkout_notify_t why, const char* path, const git_diff_file* baseline,
2318 const git_diff_file* target, const git_diff_file* workdir, void* payload ) -> int
2319 {
2320 switch( why )
2321 {
2322 case GIT_CHECKOUT_NOTIFY_CONFLICT:
2323 wxLogTrace( traceGit, "Checkout conflict: %s", path ? path : "unknown" );
2324 break;
2325 case GIT_CHECKOUT_NOTIFY_DIRTY:
2326 wxLogTrace( traceGit, "Checkout dirty: %s", path ? path : "unknown" );
2327 break;
2328 case GIT_CHECKOUT_NOTIFY_UPDATED:
2329 wxLogTrace( traceGit, "Checkout updated: %s", path ? path : "unknown" );
2330 break;
2331 case GIT_CHECKOUT_NOTIFY_UNTRACKED:
2332 wxLogTrace( traceGit, "Checkout untracked: %s", path ? path : "unknown" );
2333 break;
2334 case GIT_CHECKOUT_NOTIFY_IGNORED:
2335 wxLogTrace( traceGit, "Checkout ignored: %s", path ? path : "unknown" );
2336 break;
2337 default:
2338 break;
2339 }
2340
2341 return 0;
2342 };
2343
2344 checkoutOptions.checkout_strategy = GIT_CHECKOUT_SAFE;
2345 checkoutOptions.notify_flags = GIT_CHECKOUT_NOTIFY_ALL;
2346 checkoutOptions.notify_cb = notify_cb;
2347
2348 // Where the branch is now, so the files can go back if it cannot be moved to match them.
2349 git_commit* previousCommit = nullptr;
2350
2351 if( git_reference_peel( (git_object**) &previousCommit, rawRef, GIT_OBJECT_COMMIT ) != GIT_OK )
2352 {
2353 aHandler->AddErrorString( _( "Could not read the current commit." ) );
2354 return PullResult::Error;
2355 }
2356
2357 KIGIT::GitCommitPtr previousCommitPtr( previousCommit );
2358
2359 if( git_checkout_tree( aHandler->GetRepo(), reinterpret_cast<git_object*>( targetTree ),
2360 &checkoutOptions ) != GIT_OK )
2361 {
2362 wxString gitError = KIGIT_COMMON::GetLastGitError();
2363 bool restored = rollbackWorkingTree( aHandler->GetRepo(), previousCommit, targetTree );
2364
2365 refreshCachedIndex( aHandler->GetRepo() );
2366
2367 aHandler->AddError( restored ? _( "Could not update the project files, so nothing was changed." )
2368 : _( "Could not update the project files, and they may be partly changed." ),
2369 gitError );
2370 return PullResult::Error;
2371 }
2372
2373 git_reference* updatedRef = nullptr;
2374
2375 if( git_reference_set_target( &updatedRef, rawRef, &updatedRefOid, nullptr ) != GIT_OK )
2376 {
2377 // Left here, git reads them as local changes undoing the incoming commit.
2378 wxString gitError = KIGIT_COMMON::GetLastGitError();
2379 bool restored = rollbackWorkingTree( aHandler->GetRepo(), previousCommit, targetTree );
2380
2381 refreshCachedIndex( aHandler->GetRepo() );
2382
2383 aHandler->AddError( restored ? _( "Could not move the branch, so nothing was changed." )
2384 : _( "Could not move the branch, and the project files may be left at the "
2385 "incoming version while the branch is not." ),
2386 gitError );
2387 return PullResult::Error;
2388 }
2389
2390 KIGIT::GitReferencePtr updatedRefPtr( updatedRef );
2391
2392 if( git_repository_state_cleanup( aHandler->GetRepo() ) != GIT_OK )
2393 {
2394 // Branch and files already match, so this is leftover merge state, not a failed pull.
2395 wxLogTrace( traceGit, "handleFastForward: state cleanup failed after a completed fast-forward: %s",
2397 }
2398
2400}
2401
2402
2404{
2405 if( !aRepo )
2406 return false;
2407
2408 git_status_options opts;
2409 git_status_init_options( &opts, GIT_STATUS_OPTIONS_VERSION );
2410
2411 // Only check workdir changes (unstaged), not index changes (staged)
2412 opts.show = GIT_STATUS_SHOW_WORKDIR_ONLY;
2413 opts.flags = GIT_STATUS_OPT_INCLUDE_UNTRACKED;
2414
2415 git_status_list* status_list = nullptr;
2416
2417 if( git_status_list_new( &status_list, aRepo, &opts ) != GIT_OK )
2418 {
2419 wxLogTrace( traceGit, "Failed to get status list: %s", KIGIT_COMMON::GetLastGitError() );
2420 return false;
2421 }
2422
2423 KIGIT::GitStatusListPtr status_list_ptr( status_list );
2424 size_t count = git_status_list_entrycount( status_list );
2425
2426 // Check if any of the entries are actual modifications (not just untracked files)
2427 for( size_t ii = 0; ii < count; ++ii )
2428 {
2429 const git_status_entry* entry = git_status_byindex( status_list, ii );
2430
2431 // Check for actual workdir modifications, not just untracked files
2432 if( entry->status & ( GIT_STATUS_WT_MODIFIED | GIT_STATUS_WT_DELETED | GIT_STATUS_WT_TYPECHANGE ) )
2433 return true;
2434 }
2435
2436 return false;
2437}
2438
2439
2440PullResult LIBGIT_BACKEND::handleMerge( GIT_PULL_HANDLER* aHandler, const git_annotated_commit** aMergeHeads,
2441 size_t aMergeHeadsCount )
2442{
2443 // Check for unstaged changes before attempting merge
2444 if( hasUnstagedChanges( aHandler->GetRepo() ) )
2445 {
2446 aHandler->AddErrorString( _( "Cannot merge: you have unstaged changes. Please commit or stash them "
2447 "before pulling." ) );
2449 }
2450
2451 git_repository* repo = aHandler->GetRepo();
2452
2453 // Probe now, so a missing identity fails with a clean tree rather than a rewritten one.
2454 {
2455 git_signature* probe = nullptr;
2456
2457 if( int rc = git_signature_default( &probe, repo ); rc != GIT_OK )
2458 {
2460 aHandler->AddError( failure );
2462 }
2463
2464 KIGIT::GitSignaturePtr probePtr( probe );
2465 }
2466
2467 {
2468 git_commit* theirs = nullptr;
2469
2470 if( git_commit_lookup( &theirs, repo, git_annotated_commit_id( aMergeHeads[0] ) ) == GIT_OK )
2471 {
2472 KIGIT::GitCommitPtr theirsPtr( theirs );
2473 git_tree* theirsTree = nullptr;
2474
2475 if( git_commit_tree( &theirsTree, theirs ) == GIT_OK )
2476 {
2477 KIGIT::GitTreePtr theirsTreePtr( theirsTree );
2478 std::vector<wxString> collisions;
2479
2480 if( !untrackedFilesOverwrittenBy( repo, theirsTree, collisions ) )
2481 {
2482 aHandler->AddErrorString( _( "Could not read the status of the project files, so getting "
2483 "changes was stopped. Files that were never committed could "
2484 "have been overwritten." ) );
2485 return PullResult::Error;
2486 }
2487
2488 if( !collisions.empty() )
2489 {
2490 aHandler->AddErrorString( describeUntrackedCollisions( collisions ) );
2492 }
2493 }
2494 }
2495 }
2496
2497 if( git_merge( repo, aMergeHeads, aMergeHeadsCount, nullptr, nullptr ) )
2498 {
2499 aHandler->AddGitError( _( "Could not merge the fetched changes." ) );
2501 }
2502
2503 git_index* index = nullptr;
2504
2505 if( git_repository_index( &index, repo ) != GIT_OK )
2506 {
2507 aHandler->AddErrorString( _( "Could not read repository index after merge." ) );
2509 }
2510
2511 KIGIT::GitIndexPtr indexPtr( index );
2512
2513 if( git_index_has_conflicts( index ) )
2514 {
2515 // Abort the merge and restore the pre-pull state
2516 git_object* head_obj = nullptr;
2517
2518 if( git_revparse_single( &head_obj, repo, "HEAD" ) == GIT_OK )
2519 {
2520 KIGIT::GitObjectPtr headObjPtr( head_obj );
2521 git_reset( repo, head_obj, GIT_RESET_HARD, nullptr );
2522 }
2523
2524 git_repository_state_cleanup( repo );
2525
2526 return PullResult::Conflict;
2527 }
2528
2529 git_oid tree_oid;
2530 git_tree* tree = nullptr;
2531 git_reference* head_ref = nullptr;
2532 git_oid head_oid;
2533 git_commit* head_commit = nullptr;
2534 git_commit* merge_commit = nullptr;
2535 git_signature* signature = nullptr;
2536
2537 // Merged on disk but not recorded, so a failure from here puts the tree back at HEAD.
2538 auto undoMerge = [&]()
2539 {
2540 git_object* headObj = nullptr;
2541
2542 if( git_revparse_single( &headObj, repo, "HEAD" ) == GIT_OK )
2543 {
2544 KIGIT::GitObjectPtr headObjPtr( headObj );
2545 git_reset( repo, headObj, GIT_RESET_HARD, nullptr );
2546 }
2547
2548 git_repository_state_cleanup( repo );
2549 };
2550
2551 if( git_index_write_tree( &tree_oid, index ) != GIT_OK || git_tree_lookup( &tree, repo, &tree_oid ) != GIT_OK )
2552 {
2553 aHandler->AddErrorString( _( "Could not write the merge result." ) );
2554 undoMerge();
2556 }
2557
2558 KIGIT::GitTreePtr treePtr( tree );
2559
2560 if( git_repository_head( &head_ref, repo ) != GIT_OK )
2561 {
2562 aHandler->AddErrorString( _( "Could not get the repository head." ) );
2563 undoMerge();
2565 }
2566
2567 KIGIT::GitReferencePtr headRefPtr( head_ref );
2568
2569 if( git_reference_name_to_id( &head_oid, repo, "HEAD" ) != GIT_OK
2570 || git_commit_lookup( &head_commit, repo, &head_oid ) != GIT_OK
2571 || git_commit_lookup( &merge_commit, repo, git_annotated_commit_id( aMergeHeads[0] ) ) != GIT_OK )
2572 {
2573 aHandler->AddErrorString( _( "Could not look up the commits to merge." ) );
2574 undoMerge();
2576 }
2577
2578 KIGIT::GitCommitPtr headCommitPtr( head_commit );
2579 KIGIT::GitCommitPtr mergeCommitPtr( merge_commit );
2580
2581 if( int rc = git_signature_default( &signature, repo ); rc != GIT_OK )
2582 {
2584 aHandler->AddError( failure );
2585 undoMerge();
2587 }
2588
2589 KIGIT::GitSignaturePtr signaturePtr( signature );
2590
2591 const git_commit* parents[] = { head_commit, merge_commit };
2592 wxString message = wxString::Format( _( "Merge remote-tracking branch into %s" ),
2593 git_reference_shorthand( head_ref ) );
2594 git_oid merge_commit_oid;
2595
2596 if( git_commit_create( &merge_commit_oid, repo, "HEAD", signature, signature, nullptr,
2597 message.utf8_string().c_str(), tree, 2, parents ) != GIT_OK )
2598 {
2599 aHandler->AddGitError( _( "Could not create the merge commit." ) );
2600 undoMerge();
2602 }
2603
2604 git_repository_state_cleanup( repo );
2605 return PullResult::Success;
2606}
2607
2608
2609static PullResult rebaseOnto( GIT_PULL_HANDLER* aHandler, git_repository* aRepo, const git_annotated_commit* aOnto )
2610{
2611 git_signature* signature = nullptr;
2612
2613 if( int rc = git_signature_default( &signature, aRepo ); rc != GIT_OK )
2614 {
2616 aHandler->AddError( failure );
2617 return PullResult::Error;
2618 }
2619
2620 KIGIT::GitSignaturePtr signaturePtr( signature );
2621 git_rebase_options rebase_opts;
2622 git_rebase_init_options( &rebase_opts, GIT_REBASE_OPTIONS_VERSION );
2623 git_rebase* rebase = nullptr;
2624
2625 if( git_rebase_init( &rebase, aRepo, nullptr, aOnto, nullptr, &rebase_opts ) != GIT_OK )
2626 {
2627 aHandler->AddGitError( _( "Could not start the rebase." ) );
2628 return PullResult::Error;
2629 }
2630
2631 KIGIT::GitRebasePtr rebasePtr( rebase );
2632 git_rebase_operation* op = nullptr;
2633 int nextResult = GIT_OK;
2634
2635 while( ( nextResult = git_rebase_next( &op, rebase ) ) == GIT_OK )
2636 {
2637 git_oid commit_oid;
2638 int commitResult = git_rebase_commit( &commit_oid, rebase, nullptr, signature, nullptr, nullptr );
2639
2640 // Upstream already has this change, so replaying it would be an empty commit
2641 if( commitResult == GIT_EAPPLIED )
2642 continue;
2643
2644 if( commitResult != GIT_OK )
2645 {
2646 wxString gitError = KIGIT_COMMON::GetLastGitError();
2647 git_rebase_abort( rebase );
2648
2649 if( commitResult == GIT_EUNMERGED )
2650 {
2651 aHandler->AddErrorString( _( "The rebase ran into conflicts. This is best resolved from a "
2652 "git command line." ) );
2653 return PullResult::Conflict;
2654 }
2655
2656 aHandler->AddError( _( "Could not rebase your commits onto the fetched changes." ), gitError );
2657 return PullResult::Error;
2658 }
2659 }
2660
2661 if( nextResult != GIT_ITEROVER )
2662 {
2663 wxString gitError = KIGIT_COMMON::GetLastGitError();
2664 git_rebase_abort( rebase );
2665 aHandler->AddError( _( "Could not rebase your commits onto the fetched changes." ), gitError );
2666 return PullResult::Error;
2667 }
2668
2669 if( git_rebase_finish( rebase, signature ) != GIT_OK )
2670 {
2671 wxString gitError = KIGIT_COMMON::GetLastGitError();
2672 git_rebase_abort( rebase );
2673 aHandler->AddError( _( "Could not finish the rebase." ), gitError );
2674 return PullResult::Error;
2675 }
2676
2677 return PullResult::Success;
2678}
2679
2680
2681PullResult LIBGIT_BACKEND::handleRebase( GIT_PULL_HANDLER* aHandler, const git_annotated_commit** aMergeHeads,
2682 size_t aMergeHeadsCount )
2683{
2684 // Check for unstaged changes before attempting rebase
2685 if( hasUnstagedChanges( aHandler->GetRepo() ) )
2686 {
2687 aHandler->AddErrorString( _( "Cannot pull with rebase: you have unstaged changes. Please commit or stash "
2688 "them before pulling." ) );
2690 }
2691
2692 return rebaseOnto( aHandler, aHandler->GetRepo(), aMergeHeads[0] );
2693}
2694
2695
2696git_repository* LIBGIT_BACKEND::GetRepositoryForFile( const char* aFilename, wxString* aError, wxString* aTrustCommand )
2697{
2698 git_repository* repo = nullptr;
2699
2700 // Searching from the project, as git_repository_discover does, rather than opening the git directory it
2701 // finds keeps a linked .git from moving the working folder to the link's target
2702 if( int rc = git_repository_open_ext( &repo, aFilename, 0, nullptr ); rc != GIT_OK )
2703 {
2704 wxLogTrace( traceGit, "Can't open repo for %s: %s", aFilename, KIGIT_COMMON::GetLastGitError() );
2705
2706#if KIGIT_HAS_EOWNER
2707 // Left unexplained, a repository git refuses to open looks like no repository at all.
2708 if( rc == GIT_EOWNER && aError )
2709 {
2710 git_buf gitDir = GIT_BUF_INIT;
2711
2712 if( git_repository_discover( &gitDir, aFilename, 0, nullptr ) == GIT_OK )
2713 {
2714 KIGIT::GitBufPtr gitDirPtr( &gitDir );
2715 KIGIT_OWNERSHIP_REFUSAL refusal = KIGIT::DescribeOwnershipRefusal( wxString::FromUTF8( aFilename ),
2716 wxString::FromUTF8( gitDir.ptr ) );
2717
2718 // Left as no repository, so Add to Version Control gives the project its own
2719 if( refusal.coversHome )
2720 return nullptr;
2721
2722 *aError = refusal.summary;
2723
2724 if( aTrustCommand )
2725 *aTrustCommand = refusal.trustCommand;
2726 }
2727 }
2728#endif
2729
2730 return nullptr;
2731 }
2732
2733 return repo;
2734}
2735
2736
2737int LIBGIT_BACKEND::CreateBranch( git_repository* aRepo, const wxString& aBranchName, const wxString& aFrom )
2738{
2739 // The start point is a branch name as git would read it, local or remote, or HEAD.
2740 std::string start = aFrom.IsEmpty() ? std::string( "HEAD" ) : aFrom.utf8_string();
2741 git_object* startObj = nullptr;
2742
2743 if( int error = git_revparse_single( &startObj, aRepo, start.c_str() ); error != GIT_OK )
2744 {
2745 wxLogTrace( traceGit, "Failed to resolve branch start point '%s': %s", start, KIGIT_COMMON::GetLastGitError() );
2746 return error;
2747 }
2748
2749 KIGIT::GitObjectPtr startPtr( startObj );
2750 git_object* peeled = nullptr;
2751
2752 if( int error = git_object_peel( &peeled, startObj, GIT_OBJECT_COMMIT ); error != GIT_OK )
2753 {
2754 wxLogTrace( traceGit, "Failed to lookup commit: %s", KIGIT_COMMON::GetLastGitError() );
2755 return error;
2756 }
2757
2758 KIGIT::GitObjectPtr peeledPtr( peeled );
2759 git_commit* commit = reinterpret_cast<git_commit*>( peeled );
2760 git_reference* branchRef = nullptr;
2761
2762 std::string name = aBranchName.utf8_string();
2763
2764 if( int error = git_branch_create( &branchRef, aRepo, name.c_str(), commit, 0 ); error != GIT_OK )
2765 {
2766 wxLogTrace( traceGit, "Failed to create branch: %s", KIGIT_COMMON::GetLastGitError() );
2767 return error;
2768 }
2769
2770 git_reference_free( branchRef );
2771 return 0;
2772}
2773
2774
2775bool LIBGIT_BACKEND::DeleteBranch( git_repository* aRepo, const wxString& aBranchName )
2776{
2777 if( !aRepo || aBranchName.IsEmpty() )
2778 return false;
2779
2780 git_reference* branch = nullptr;
2781
2782 if( git_branch_lookup( &branch, aRepo, aBranchName.utf8_string().c_str(), GIT_BRANCH_LOCAL ) != GIT_OK )
2783 return false;
2784
2785 KIGIT::GitReferencePtr branchPtr( branch );
2786 return git_branch_delete( branch ) == GIT_OK;
2787}
2788
2789
2790bool LIBGIT_BACKEND::StashSave( git_repository* aRepo, const wxString& aMessage )
2791{
2792 if( !aRepo )
2793 return false;
2794
2795 git_signature* signature = nullptr;
2796
2797 if( git_signature_default( &signature, aRepo ) != GIT_OK )
2798 return false;
2799
2800 KIGIT::GitSignaturePtr signaturePtr( signature );
2801
2802 // libgit2 stashes from an unstamped index copy that trusts racily clean entries, so an edit made in the
2803 // index's timestamp tick is stashed as unchanged and then reverted. Writing the index smudges those entries
2804 git_index* index = nullptr;
2805
2806 if( git_repository_index( &index, aRepo ) != GIT_OK )
2807 return false;
2808
2809 KIGIT::GitIndexPtr indexPtr( index );
2810
2811 if( git_index_read( index, true ) != GIT_OK || git_index_write( index ) != GIT_OK )
2812 return false;
2813
2814 std::string message = aMessage.utf8_string();
2815 git_oid stashOid;
2816
2817 return git_stash_save( &stashOid, aRepo, signature, message.empty() ? nullptr : message.c_str(), GIT_STASH_DEFAULT )
2818 == GIT_OK;
2819}
2820
2821
2822static bool rollbackWorkingTree( git_repository* aRepo, git_commit* aHeadCommit, git_tree* aWrittenTree );
2823static bool restorePathsFromCommit( git_repository* aRepo, git_commit* aCommit,
2824 const std::vector<std::string>& aPaths );
2825
2826
2827// libgit2 reports a conflicting apply as applied, so a pop would drop the only copy of the
2828// stashed work. A clean tracked tree makes the rollback lossless.
2829static bool applyStashOntoCleanTree( git_repository* aRepo, size_t aIndex )
2830{
2831 if( !aRepo )
2832 return false;
2833
2834 if( trackedTreeState( aRepo ) != TREE_STATE::CLEAN )
2835 {
2836 git_error_set_str( GIT_ERROR_STASH, _( "Commit or discard the current changes first, so the stash has "
2837 "a clean version to apply to." )
2838 .utf8_string()
2839 .c_str() );
2840 return false;
2841 }
2842
2843 git_oid headOid;
2844
2845 if( git_reference_name_to_id( &headOid, aRepo, "HEAD" ) != GIT_OK )
2846 return false;
2847
2848 git_commit* headCommit = nullptr;
2849
2850 if( git_commit_lookup( &headCommit, aRepo, &headOid ) != GIT_OK )
2851 return false;
2852
2853 KIGIT::GitCommitPtr headCommitPtr( headCommit );
2854
2855 if( git_stash_apply( aRepo, aIndex, nullptr ) != GIT_OK )
2856 return false;
2857
2858 // An unreadable index cannot confirm the apply, and a caller reading success would drop the
2859 // stash, so treat it as a conflict.
2860 git_index* index = nullptr;
2861 bool conflicted = git_repository_index( &index, aRepo ) != GIT_OK || git_index_has_conflicts( index );
2862 KIGIT::GitIndexPtr indexPtr( index );
2863
2864 if( conflicted )
2865 {
2866 // Conflict markers match neither version, so the touched paths come from the status.
2867 restorePathsFromCommit( aRepo, headCommit, changedPaths( aRepo ) );
2868 git_error_set_str( GIT_ERROR_STASH, _( "The stash does not fit on top of the current version of the "
2869 "files, so nothing was changed. Restore the version it was made "
2870 "on from History, then apply it there." )
2871 .utf8_string()
2872 .c_str() );
2873 return false;
2874 }
2875
2876 return true;
2877}
2878
2879
2880bool LIBGIT_BACKEND::StashApply( git_repository* aRepo, size_t aIndex )
2881{
2882 return applyStashOntoCleanTree( aRepo, aIndex );
2883}
2884
2885
2886bool LIBGIT_BACKEND::StashPop( git_repository* aRepo, size_t aIndex )
2887{
2888 return applyStashOntoCleanTree( aRepo, aIndex ) && git_stash_drop( aRepo, aIndex ) == GIT_OK;
2889}
2890
2891
2892bool LIBGIT_BACKEND::StashDrop( git_repository* aRepo, size_t aIndex )
2893{
2894 return aRepo && git_stash_drop( aRepo, aIndex ) == GIT_OK;
2895}
2896
2897
2898bool LIBGIT_BACKEND::CreateTag( git_repository* aRepo, const wxString& aName, const wxString& aMessage )
2899{
2900 if( !aRepo || aName.IsEmpty() )
2901 return false;
2902
2903 git_object* target = nullptr;
2904
2905 if( git_revparse_single( &target, aRepo, "HEAD" ) != GIT_OK )
2906 return false;
2907
2908 KIGIT::GitObjectPtr targetPtr( target );
2909 git_oid oid;
2910
2911 if( aMessage.IsEmpty() )
2912 return git_tag_create_lightweight( &oid, aRepo, aName.utf8_string().c_str(), target, 0 ) == GIT_OK;
2913
2914 // An annotated tag carries the message, and who made it, from the repository's identity.
2915 git_signature* tagger = nullptr;
2916
2917 if( git_signature_default( &tagger, aRepo ) != GIT_OK )
2918 return false;
2919
2920 KIGIT::GitSignaturePtr taggerPtr( tagger );
2921 std::string name = aName.utf8_string();
2922 std::string message = aMessage.utf8_string();
2923
2924 return git_tag_create( &oid, aRepo, name.c_str(), target, tagger, message.c_str(), 0 ) == GIT_OK;
2925}
2926
2927
2928bool LIBGIT_BACKEND::DeleteTag( git_repository* aRepo, const wxString& aName )
2929{
2930 if( !aRepo || aName.IsEmpty() )
2931 return false;
2932
2933 return git_tag_delete( aRepo, aName.utf8_string().c_str() ) == GIT_OK;
2934}
2935
2936
2937bool LIBGIT_BACKEND::CheckoutTag( git_repository* aRepo, const wxString& aName )
2938{
2939 if( !aRepo || aName.IsEmpty() )
2940 return false;
2941
2942 git_object* target = nullptr;
2943 wxString spec = aName + wxT( "^{commit}" );
2944
2945 if( git_revparse_single( &target, aRepo, spec.utf8_string().c_str() ) != GIT_OK )
2946 return false;
2947
2948 KIGIT::GitObjectPtr targetPtr( target );
2949
2950 git_checkout_options opts;
2951 git_checkout_options_init( &opts, GIT_CHECKOUT_OPTIONS_VERSION );
2952 opts.checkout_strategy = GIT_CHECKOUT_SAFE;
2953
2954 if( git_checkout_tree( aRepo, target, &opts ) != GIT_OK )
2955 return false;
2956
2957 return git_repository_set_head_detached( aRepo, git_object_id( target ) ) == GIT_OK;
2958}
2959
2960
2961bool LIBGIT_BACKEND::AddRemote( git_repository* aRepo, const wxString& aName, const wxString& aUrl )
2962{
2963 if( !aRepo || aName.IsEmpty() )
2964 return false;
2965
2966 git_remote* remote = nullptr;
2967
2968 if( git_remote_create( &remote, aRepo, aName.utf8_string().c_str(), aUrl.utf8_string().c_str() ) != GIT_OK )
2969 return false;
2970
2971 KIGIT::GitRemotePtr remotePtr( remote );
2972 return true;
2973}
2974
2975
2976bool LIBGIT_BACKEND::SetRemoteUrl( git_repository* aRepo, const wxString& aName, const wxString& aUrl )
2977{
2978 if( !aRepo || aName.IsEmpty() )
2979 return false;
2980
2981 return git_remote_set_url( aRepo, aName.utf8_string().c_str(), aUrl.utf8_string().c_str() ) == GIT_OK;
2982}
2983
2984
2985bool LIBGIT_BACKEND::RemoveRemote( git_repository* aRepo, const wxString& aName )
2986{
2987 if( !aRepo || aName.IsEmpty() )
2988 return false;
2989
2990 return git_remote_delete( aRepo, aName.utf8_string().c_str() ) == GIT_OK;
2991}
2992
2993
2994bool LIBGIT_BACKEND::SetUserConfig( git_repository* aRepo, const wxString& aName, const wxString& aEmail )
2995{
2996 if( !aRepo )
2997 return false;
2998
2999 git_config* config = nullptr;
3000
3001 if( git_repository_config( &config, aRepo ) != GIT_OK )
3002 return false;
3003
3004 KIGIT::GitConfigPtr configPtr( config );
3005
3006 bool ok = git_config_set_string( config, "user.name", aName.utf8_string().c_str() ) == GIT_OK;
3007 ok = ok && git_config_set_string( config, "user.email", aEmail.utf8_string().c_str() ) == GIT_OK;
3008 return ok;
3009}
3010
3011
3012namespace
3013{
3014
3015// Owner-only, matching the other extracted-content helpers.
3016bool writeConflictSide( git_repository* aRepo, const git_index_entry* aEntry, const wxString& aDest )
3017{
3018 wxFile out;
3019
3020 if( !out.Create( aDest, true, wxS_IRUSR | wxS_IWUSR ) )
3021 return false;
3022
3023 if( !aEntry )
3024 return true;
3025
3026 git_blob* blob = nullptr;
3027
3028 if( git_blob_lookup( &blob, aRepo, &aEntry->id ) != GIT_OK )
3029 return false;
3030
3031 KIGIT::GitBlobPtr blobPtr( blob );
3032
3033 const void* raw = git_blob_rawcontent( blob );
3034 git_off_t size = git_blob_rawsize( blob );
3035
3036 return out.Write( raw, static_cast<size_t>( size ) ) == static_cast<size_t>( size );
3037}
3038
3039
3040// Into a fresh in-memory index, leaving the repository untouched.
3041bool remergeInMemory( git_repository* aRepo, const wxString& aPinnedTheirsOid, KIGIT::GitIndexPtr& aIndexOut,
3042 KIGIT::GitCommitPtr& aOursOut, KIGIT::GitCommitPtr& aTheirsOut, wxString& aError )
3043{
3044 git_oid oursOid;
3045
3046 if( git_reference_name_to_id( &oursOid, aRepo, "HEAD" ) != GIT_OK )
3047 {
3048 aError = _( "Could not get the repository head." );
3049 return false;
3050 }
3051
3052 git_oid theirsOid;
3053
3054 if( !aPinnedTheirsOid.IsEmpty() )
3055 {
3056 // The exact commit the conflicts came from, since the background fetch can move FETCH_HEAD.
3057 if( git_oid_fromstr( &theirsOid, aPinnedTheirsOid.utf8_string().c_str() ) != GIT_OK )
3058 {
3059 aError = _( "Could not find the fetched remote commit." );
3060 return false;
3061 }
3062 }
3063 else
3064 {
3065 git_object* fetchHead = nullptr;
3066
3067 if( git_revparse_single( &fetchHead, aRepo, "FETCH_HEAD" ) != GIT_OK )
3068 {
3069 aError = _( "Could not find the fetched remote commit." );
3070 return false;
3071 }
3072
3073 KIGIT::GitObjectPtr fetchHeadPtr( fetchHead );
3074 theirsOid = *git_object_id( fetchHead );
3075 }
3076
3077 git_commit* ours = nullptr;
3078
3079 if( git_commit_lookup( &ours, aRepo, &oursOid ) != GIT_OK )
3080 {
3081 aError = _( "Could not look up the commits to merge." );
3082 return false;
3083 }
3084
3085 aOursOut.reset( ours );
3086
3087 git_commit* theirs = nullptr;
3088
3089 if( git_commit_lookup( &theirs, aRepo, &theirsOid ) != GIT_OK )
3090 {
3091 aError = _( "Could not look up the commits to merge." );
3092 return false;
3093 }
3094
3095 aTheirsOut.reset( theirs );
3096
3097 git_tree* oursTree = nullptr;
3098
3099 if( git_commit_tree( &oursTree, ours ) != GIT_OK )
3100 {
3101 aError = _( "Could not read the commit trees." );
3102 return false;
3103 }
3104
3105 KIGIT::GitTreePtr oursTreePtr( oursTree );
3106 git_tree* theirsTree = nullptr;
3107
3108 if( git_commit_tree( &theirsTree, theirs ) != GIT_OK )
3109 {
3110 aError = _( "Could not read the commit trees." );
3111 return false;
3112 }
3113
3114 KIGIT::GitTreePtr theirsTreePtr( theirsTree );
3115
3116 // Unrelated histories have no merge base, which git_merge_trees accepts as a null ancestor.
3117 KIGIT::GitTreePtr baseTreePtr;
3118 git_oid baseOid;
3119
3120 if( git_merge_base( &baseOid, aRepo, &oursOid, &theirsOid ) == GIT_OK )
3121 {
3122 git_commit* baseCommit = nullptr;
3123
3124 if( git_commit_lookup( &baseCommit, aRepo, &baseOid ) == GIT_OK )
3125 {
3126 KIGIT::GitCommitPtr baseCommitPtr( baseCommit );
3127 git_tree* baseTree = nullptr;
3128
3129 if( git_commit_tree( &baseTree, baseCommit ) == GIT_OK )
3130 baseTreePtr.reset( baseTree );
3131 }
3132 }
3133
3134 git_merge_options mergeOpts;
3135 git_index* mergedIndex = nullptr;
3136
3137 git_merge_options_init( &mergeOpts, GIT_MERGE_OPTIONS_VERSION );
3138
3139 if( git_merge_trees( &mergedIndex, aRepo, baseTreePtr.get(), oursTree, theirsTree, &mergeOpts ) != GIT_OK )
3140 {
3141 aError = wxString::Format( _( "Merge failed: %s" ), KIGIT_COMMON::GetLastGitError() );
3142 return false;
3143 }
3144
3145 aIndexOut.reset( mergedIndex );
3146 return true;
3147}
3148
3149} // namespace
3150
3151
3152// Just these paths. Everything else is left alone, so a rollback cannot reach an untouched file.
3153static bool restorePathsFromCommit( git_repository* aRepo, git_commit* aCommit, const std::vector<std::string>& aPaths )
3154{
3155 if( aPaths.empty() )
3156 return true;
3157
3158 git_tree* tree = nullptr;
3159
3160 if( git_commit_tree( &tree, aCommit ) != GIT_OK )
3161 return false;
3162
3163 KIGIT::GitTreePtr treePtr( tree );
3164 std::vector<char*> pathSpec;
3165
3166 // git_strarray wants mutable pointers, though checkout only reads them.
3167 for( const std::string& path : aPaths )
3168 pathSpec.push_back( const_cast<char*>( path.c_str() ) );
3169
3170 git_checkout_options checkoutOpts;
3171 git_checkout_init_options( &checkoutOpts, GIT_CHECKOUT_OPTIONS_VERSION );
3172 checkoutOpts.checkout_strategy = GIT_CHECKOUT_FORCE | GIT_CHECKOUT_REMOVE_UNTRACKED;
3173 checkoutOpts.paths.strings = pathSpec.data();
3174 checkoutOpts.paths.count = pathSpec.size();
3175
3176 return git_checkout_tree( aRepo, reinterpret_cast<git_object*>( tree ), &checkoutOpts ) == GIT_OK;
3177}
3178
3179
3180// Whether aPath in aTree holds exactly what is on disk at aOnDisk.
3181static bool treeHolds( git_tree* aTree, const char* aPath, const git_oid& aOnDisk )
3182{
3183 git_tree_entry* entry = nullptr;
3184
3185 if( git_tree_entry_bypath( &entry, aTree, aPath ) != GIT_OK )
3186 return false;
3187
3188 KIGIT::GitTreeEntryPtr entryPtr( entry );
3189
3190 return git_oid_equal( &aOnDisk, git_tree_entry_id( entry ) );
3191}
3192
3193
3194// Safe when nothing is there, or the file still holds what was written or what is being restored.
3195static bool safeToRestore( git_repository* aRepo, const char* aPath, git_tree* aPreviousTree, git_tree* aWrittenTree )
3196{
3197 const char* workdir = git_repository_workdir( aRepo );
3198
3199 if( !workdir )
3200 return false;
3201
3202 // Nothing there is the state a restore is meant to repair, so there is nothing to lose.
3203 if( !wxFileName::Exists( wxString::FromUTF8( workdir ) + wxString::FromUTF8( aPath ) ) )
3204 return true;
3205
3206 git_oid onDisk;
3207
3208 // Not readable as a file, such as a directory of untracked work, so it cannot be shown ours.
3209 if( git_repository_hashfile( &onDisk, aRepo, aPath, GIT_OBJECT_BLOB, nullptr ) != GIT_OK )
3210 return false;
3211
3212 return treeHolds( aWrittenTree, aPath, onDisk ) || treeHolds( aPreviousTree, aPath, onDisk );
3213}
3214
3215
3216// Only the paths the operation wrote, and only while they still hold what it wrote, so an edit
3217// made meanwhile is kept. False when anything had to be left behind.
3218static bool rollbackWorkingTree( git_repository* aRepo, git_commit* aHeadCommit, git_tree* aWrittenTree )
3219{
3220 git_tree* previousTree = nullptr;
3221
3222 if( git_commit_tree( &previousTree, aHeadCommit ) != GIT_OK )
3223 return false;
3224
3225 KIGIT::GitTreePtr previousTreePtr( previousTree );
3226
3227 git_diff* diff = nullptr;
3228
3229 if( git_diff_tree_to_tree( &diff, aRepo, previousTree, aWrittenTree, nullptr ) != GIT_OK )
3230 return false;
3231
3232 KIGIT::GitDiffPtr diffPtr( diff );
3233
3234 std::set<std::string> touched;
3235
3236 for( size_t ii = 0; ii < git_diff_num_deltas( diff ); ii++ )
3237 {
3238 const git_diff_delta* delta = git_diff_get_delta( diff, ii );
3239
3240 // A rename reports two paths, and both need putting back.
3241 for( const char* path : { delta->old_file.path, delta->new_file.path } )
3242 {
3243 if( path )
3244 touched.emplace( path );
3245 }
3246 }
3247
3248 std::vector<std::string> restorable;
3249 bool leftBehind = false;
3250
3251 for( const std::string& path : touched )
3252 {
3253 if( safeToRestore( aRepo, path.c_str(), previousTree, aWrittenTree ) )
3254 restorable.push_back( path );
3255 else
3256 leftBehind = true;
3257 }
3258
3259 if( restorable.empty() )
3260 return !leftBehind;
3261
3262 return restorePathsFromCommit( aRepo, aHeadCommit, restorable ) && !leftBehind;
3263}
3264
3265
3266// So each operation can word the same underlying failure its own way.
3275
3276
3277// Working tree first, branch last, so any failure leaves the branch and its history untouched.
3278static PUBLISH_RESULT publishPreparedCommit( git_repository* aRepo, git_tree* aTree, const git_oid& aCommitOid,
3279 git_reference* aHeadRef, git_commit* aRollbackCommit,
3280 const char* aReflogLabel, wxString& aGitError )
3281{
3282 git_checkout_options checkoutOpts;
3283 git_checkout_options_init( &checkoutOpts, GIT_CHECKOUT_OPTIONS_VERSION );
3284 checkoutOpts.checkout_strategy = GIT_CHECKOUT_FORCE;
3285
3286 if( git_checkout_tree( aRepo, reinterpret_cast<git_object*>( aTree ), &checkoutOpts ) != GIT_OK )
3287 {
3288 aGitError = KIGIT_COMMON::GetLastGitError();
3289
3290 bool rolledBack = rollbackWorkingTree( aRepo, aRollbackCommit, aTree );
3291
3292 refreshCachedIndex( aRepo );
3293
3295 }
3296
3297 git_reference* updatedRef = nullptr;
3298
3299 if( git_reference_set_target( &updatedRef, aHeadRef, &aCommitOid, aReflogLabel ) != GIT_OK )
3300 {
3301 aGitError = KIGIT_COMMON::GetLastGitError();
3302
3303 bool rolledBack = rollbackWorkingTree( aRepo, aRollbackCommit, aTree );
3304
3305 refreshCachedIndex( aRepo );
3306
3308 }
3309
3310 KIGIT::GitReferencePtr updatedRefPtr( updatedRef );
3311
3313}
3314
3315
3316RestoreResult LIBGIT_BACKEND::RestoreVersion( KIGIT_COMMON& aCommon, const wxString& aCommitHash,
3317 KIGIT_ERROR_MESSAGE& aError )
3318{
3319 git_repository* repo = aCommon.GetRepo();
3320
3321 if( !repo )
3322 {
3323 aError.details = _( "The project has no git repository." );
3324 return RestoreResult::Error;
3325 }
3326
3327 const std::optional<wxString> projectPrefix = aCommon.GetProjectPrefix();
3328
3329 if( !projectPrefix )
3330 {
3331 aError.details = _( "Could not work out which folder this project occupies in the repository, "
3332 "so nothing was restored." );
3333 return RestoreResult::Error;
3334 }
3335
3336 git_object* targetObj = nullptr;
3337
3338 if( git_revparse_single( &targetObj, repo, aCommitHash.utf8_string().c_str() ) != GIT_OK )
3339 {
3340 aError.details = _( "Could not find that version." );
3341 return RestoreResult::Error;
3342 }
3343
3344 KIGIT::GitObjectPtr targetObjPtr( targetObj );
3345 git_commit* targetCommit = nullptr;
3346
3347 if( git_object_type( targetObj ) != GIT_OBJECT_COMMIT
3348 || git_commit_lookup( &targetCommit, repo, git_object_id( targetObj ) ) != GIT_OK )
3349 {
3350 aError.details = _( "Could not find that version." );
3351 return RestoreResult::Error;
3352 }
3353
3354 KIGIT::GitCommitPtr targetCommitPtr( targetCommit );
3355 git_tree* targetTree = nullptr;
3356
3357 if( git_commit_tree( &targetTree, targetCommit ) != GIT_OK )
3358 {
3359 aError.details = _( "Could not read that version's contents." );
3360 return RestoreResult::Error;
3361 }
3362
3363 KIGIT::GitTreePtr targetTreePtr( targetTree );
3364
3365 git_reference* headRef = nullptr;
3366
3367 if( git_repository_head( &headRef, repo ) != GIT_OK )
3368 {
3369 aError.details = _( "Could not get the repository head." );
3370 return RestoreResult::Error;
3371 }
3372
3373 KIGIT::GitReferencePtr headRefPtr( headRef );
3374 git_commit* headCommit = nullptr;
3375
3376 if( git_reference_peel( (git_object**) &headCommit, headRef, GIT_OBJECT_COMMIT ) != GIT_OK )
3377 {
3378 aError.details = _( "Could not get the repository head." );
3379 return RestoreResult::Error;
3380 }
3381
3382 KIGIT::GitCommitPtr headCommitPtr( headCommit );
3383 git_tree* headTree = nullptr;
3384
3385 if( git_commit_tree( &headTree, headCommit ) != GIT_OK )
3386 {
3387 aError.details = _( "Could not get the repository head." );
3388 return RestoreResult::Error;
3389 }
3390
3391 KIGIT::GitTreePtr headTreePtr( headTree );
3392
3393 // A repository can hold several projects, so graft only this one's subtree onto the head.
3394 KIGIT::GitTreePtr effectiveTreePtr;
3395 git_tree* effectiveTree = targetTree;
3396
3397 if( !projectPrefix->IsEmpty() )
3398 {
3399 // libgit2 expects the folder path without a trailing slash.
3400 std::string prefixUtf8( projectPrefix->BeforeLast( '/' ).utf8_string() );
3401 git_tree_entry* subtreeEntry = nullptr;
3402
3403 if( git_tree_entry_bypath( &subtreeEntry, targetTree, prefixUtf8.c_str() ) != GIT_OK )
3404 {
3405 aError.details = _( "That version does not contain this project's folder." );
3406 return RestoreResult::Error;
3407 }
3408
3409 KIGIT::GitTreeEntryPtr subtreeEntryPtr( subtreeEntry );
3410
3411 if( git_tree_entry_type( subtreeEntry ) != GIT_OBJECT_TREE )
3412 {
3413 aError.details = _( "That version does not contain this project's folder." );
3414 return RestoreResult::Error;
3415 }
3416
3417 git_tree_update update;
3418 update.action = GIT_TREE_UPDATE_UPSERT;
3419 update.id = *git_tree_entry_id( subtreeEntry );
3420 update.filemode = GIT_FILEMODE_TREE;
3421 update.path = prefixUtf8.c_str();
3422
3423 git_oid combinedOid;
3424
3425 if( git_tree_create_updated( &combinedOid, repo, headTree, 1, &update ) != GIT_OK )
3426 {
3427 aError.details = wxString::Format( _( "Could not build the restored content: %s" ),
3429 return RestoreResult::Error;
3430 }
3431
3432 git_tree* combined = nullptr;
3433
3434 if( git_tree_lookup( &combined, repo, &combinedOid ) != GIT_OK )
3435 {
3436 aError.details = _( "Could not build the restored content." );
3437 return RestoreResult::Error;
3438 }
3439
3440 effectiveTreePtr.reset( combined );
3441 effectiveTree = combined;
3442 }
3443
3444 // The checkout is forced, so refuse when uncommitted work would be overwritten. An untracked
3445 // file only counts when the restored content carries its path.
3446 {
3447 git_status_options statusOpts;
3448 git_status_init_options( &statusOpts, GIT_STATUS_OPTIONS_VERSION );
3449 statusOpts.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
3450 statusOpts.flags = GIT_STATUS_OPT_INCLUDE_UNTRACKED | GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS;
3451
3452 git_status_list* statusList = nullptr;
3453
3454 if( git_status_list_new( &statusList, repo, &statusOpts ) != GIT_OK )
3455 {
3456 aError.details = _( "Could not read the repository status." );
3457 return RestoreResult::Error;
3458 }
3459
3460 KIGIT::GitStatusListPtr statusListPtr( statusList );
3461 bool dirty = false;
3462 size_t count = git_status_list_entrycount( statusList );
3463
3464 for( size_t ii = 0; ii < count && !dirty; ++ii )
3465 {
3466 const git_status_entry* entry = git_status_byindex( statusList, ii );
3467
3468 if( entry->status == GIT_STATUS_WT_NEW )
3469 {
3470 const char* path = entry->index_to_workdir ? entry->index_to_workdir->new_file.path : nullptr;
3471
3472 if( path )
3473 {
3474 git_tree_entry* treeEntry = nullptr;
3475
3476 if( git_tree_entry_bypath( &treeEntry, effectiveTree, path ) == GIT_OK )
3477 {
3478 KIGIT::GitTreeEntryPtr treeEntryPtr( treeEntry );
3479 dirty = true;
3480 }
3481 }
3482 }
3483 else
3484 {
3485 dirty = true;
3486 }
3487 }
3488
3489 if( dirty )
3490 return RestoreResult::Dirty;
3491 }
3492
3493 if( git_oid_equal( git_commit_tree_id( headCommit ), git_tree_id( effectiveTree ) ) )
3495
3496 git_signature* signature = nullptr;
3497
3498 if( int rc = git_signature_default( &signature, repo ); rc != GIT_OK )
3499 {
3500 aError = describeSignatureFailure( rc );
3501 return RestoreResult::Error;
3502 }
3503
3504 KIGIT::GitSignaturePtr signaturePtr( signature );
3505
3506 char shortHash[13] = { 0 };
3507 git_oid_tostr( shortHash, sizeof( shortHash ), git_commit_id( targetCommit ) );
3508
3509 // The commit stays dangling until the checkout succeeds, so a failure leaves the branch as
3510 // it was.
3511 const git_commit* parents[] = { headCommit };
3512 wxString message = wxString::Format( _( "Restore version %s" ), shortHash );
3513 git_oid restoreCommitOid;
3514
3515 if( git_commit_create( &restoreCommitOid, repo, nullptr, signature, signature, nullptr,
3516 message.utf8_string().c_str(), effectiveTree, 1, parents )
3517 != GIT_OK )
3518 {
3519 aError.details =
3520 wxString::Format( _( "Could not create the restore commit: %s" ), KIGIT_COMMON::GetLastGitError() );
3521 return RestoreResult::Error;
3522 }
3523
3524 wxString gitError;
3525
3526 switch( publishPreparedCommit( repo, effectiveTree, restoreCommitOid, headRef, headCommit, "restore", gitError ) )
3527 {
3529
3531 aError.details =
3532 wxString::Format( _( "Could not update the working files, so nothing was changed: %s" ), gitError );
3533 return RestoreResult::Error;
3534
3536 aError.details = wxString::Format( _( "Could not update the working files, and they may be partially "
3537 "changed: %s" ),
3538 gitError );
3539 return RestoreResult::Error;
3540
3542 aError.details =
3543 wxString::Format( _( "Could not record the restore commit, so nothing was changed: %s" ), gitError );
3544 return RestoreResult::Error;
3545
3547 aError.details = wxString::Format( _( "Could not record the restore commit, and the working files may "
3548 "have been changed: %s" ),
3549 gitError );
3550 return RestoreResult::Error;
3551 }
3552
3553 return RestoreResult::Error;
3554}
3555
3556
3557bool LIBGIT_BACKEND::DiscardChanges( git_repository* aRepo, const std::vector<wxString>& aPaths, wxString& aError )
3558{
3559 if( !aRepo )
3560 {
3561 aError = _( "The project has no git repository." );
3562 return false;
3563 }
3564
3565 if( aPaths.empty() )
3566 return true;
3567
3568 std::vector<std::string> pathStorage;
3569 std::vector<char*> pathPtrs;
3570 std::vector<wxString> neverCommitted;
3571
3572 for( const wxString& path : aPaths )
3573 {
3574 if( IsPathInHead( aRepo, path ) )
3575 pathStorage.push_back( path.utf8_string() );
3576 else
3577 neverCommitted.push_back( path );
3578 }
3579
3580 // HEAD has nothing to restore for these, so discarding means dropping the staged entry.
3581 if( !neverCommitted.empty() )
3582 {
3583 git_index* index = nullptr;
3584
3585 if( git_repository_index( &index, aRepo ) != GIT_OK )
3586 {
3588 return false;
3589 }
3590
3591 KIGIT::GitIndexPtr indexPtr( index );
3592
3593 for( const wxString& path : neverCommitted )
3594 git_index_remove_bypath( index, path.utf8_string().c_str() );
3595
3596 if( git_index_write( index ) != GIT_OK )
3597 {
3599 return false;
3600 }
3601 }
3602
3603 if( pathStorage.empty() )
3604 return true;
3605
3606 for( std::string& path : pathStorage )
3607 pathPtrs.push_back( path.data() );
3608
3609 git_checkout_options opts;
3610 git_checkout_init_options( &opts, GIT_CHECKOUT_OPTIONS_VERSION );
3611
3612 // Without DISABLE_PATHSPEC_MATCH these are wildmatch patterns, so a file name holding a
3613 // glob character would discard its neighbours too.
3614 opts.checkout_strategy = GIT_CHECKOUT_FORCE | GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH;
3615 opts.paths.strings = pathPtrs.data();
3616 opts.paths.count = pathPtrs.size();
3617
3618 if( git_checkout_head( aRepo, &opts ) != GIT_OK )
3619 {
3621 return false;
3622 }
3623
3624 return true;
3625}
3626
3627
3628bool LIBGIT_BACKEND::IsPathInHead( git_repository* aRepo, const wxString& aPath )
3629{
3630 if( !aRepo )
3631 return false;
3632
3633 git_oid headOid;
3634
3635 if( git_reference_name_to_id( &headOid, aRepo, "HEAD" ) != GIT_OK )
3636 return false;
3637
3638 git_commit* headCommit = nullptr;
3639
3640 if( git_commit_lookup( &headCommit, aRepo, &headOid ) != GIT_OK )
3641 return false;
3642
3643 KIGIT::GitCommitPtr headCommitPtr( headCommit );
3644 git_tree* headTree = nullptr;
3645
3646 if( git_commit_tree( &headTree, headCommit ) != GIT_OK )
3647 return false;
3648
3649 KIGIT::GitTreePtr headTreePtr( headTree );
3650 git_tree_entry* entry = nullptr;
3651
3652 if( git_tree_entry_bypath( &entry, headTree, aPath.utf8_string().c_str() ) != GIT_OK )
3653 return false;
3654
3655 KIGIT::GitTreeEntryPtr entryPtr( entry );
3656
3657 return true;
3658}
3659
3660
3661bool LIBGIT_BACKEND::AbandonOperation( git_repository* aRepo, wxString& aError )
3662{
3663 if( !aRepo )
3664 {
3665 aError = _( "The project has no git repository." );
3666 return false;
3667 }
3668
3669 // One wording for every rebase we cannot end. The user cannot act on the difference
3670 // between the states.
3671 const wxString rebaseIsAnotherProgram =
3672 _( "This rebase was started by another program, and only that program can finish or abort it." );
3673
3674 switch( git_repository_state( aRepo ) )
3675 {
3676 case GIT_REPOSITORY_STATE_NONE: return true;
3677
3678 case GIT_REPOSITORY_STATE_REBASE_MERGE:
3679 case GIT_REPOSITORY_STATE_REBASE_INTERACTIVE:
3680 {
3681 // Aborting restores the branch and its starting commit. A reset to the detached HEAD
3682 // would not.
3683 git_rebase* rebase = nullptr;
3684
3685 if( git_rebase_open( &rebase, aRepo, nullptr ) != GIT_OK )
3686 {
3687 aError = rebaseIsAnotherProgram;
3688 return false;
3689 }
3690
3691 KIGIT::GitRebasePtr rebasePtr( rebase );
3692
3693 if( git_rebase_abort( rebase ) != GIT_OK )
3694 {
3695 aError = rebaseIsAnotherProgram;
3696 return false;
3697 }
3698
3699 return true;
3700 }
3701
3702 case GIT_REPOSITORY_STATE_BISECT:
3703 // A bisect is a search through the history, not a half-finished change. A reset would
3704 // leave the project on whichever commit the search had reached.
3705 aError = _( "This project is in the middle of a search through its history, started by another "
3706 "program. Only that program can end the search and bring the project back." );
3707 return false;
3708
3709 case GIT_REPOSITORY_STATE_REBASE:
3710 case GIT_REPOSITORY_STATE_APPLY_MAILBOX:
3711 case GIT_REPOSITORY_STATE_APPLY_MAILBOX_OR_REBASE:
3712 aError = rebaseIsAnotherProgram;
3713 return false;
3714
3715 default: break;
3716 }
3717
3718 git_object* head = nullptr;
3719
3720 if( git_revparse_single( &head, aRepo, "HEAD" ) != GIT_OK )
3721 {
3723 return false;
3724 }
3725
3726 KIGIT::GitObjectPtr headPtr( head );
3727 git_tree* headTree = nullptr;
3728
3729 if( git_object_peel( reinterpret_cast<git_object**>( &headTree ), head, GIT_OBJECT_TREE ) != GIT_OK )
3730 {
3732 return false;
3733 }
3734
3735 KIGIT::GitTreePtr headTreePtr( headTree );
3736 git_index* index = nullptr;
3737
3738 if( git_repository_index( &index, aRepo ) != GIT_OK )
3739 {
3741 return false;
3742 }
3743
3744 KIGIT::GitIndexPtr indexPtr( index );
3745
3746 // Only what the operation touched, as git's own merge abort does. Going back over the whole
3747 // repository would throw away uncommitted work in files it never went near, and a
3748 // repository can hold more than one project.
3749 std::set<std::string> touched;
3750
3751 // A conflicted file has no stage zero, so the diff below does not report it.
3752 git_index_conflict_iterator* conflicts = nullptr;
3753
3754 if( git_index_conflict_iterator_new( &conflicts, index ) == GIT_OK )
3755 {
3756 const git_index_entry* ancestor = nullptr;
3757 const git_index_entry* ours = nullptr;
3758 const git_index_entry* theirs = nullptr;
3759
3760 while( git_index_conflict_next( &ancestor, &ours, &theirs, conflicts ) == GIT_OK )
3761 {
3762 for( const git_index_entry* entry : { ancestor, ours, theirs } )
3763 {
3764 if( entry && entry->path )
3765 touched.insert( entry->path );
3766 }
3767 }
3768
3769 git_index_conflict_iterator_free( conflicts );
3770 }
3771
3772 git_diff* diff = nullptr;
3773
3774 if( git_diff_tree_to_index( &diff, aRepo, headTree, index, nullptr ) != GIT_OK )
3775 {
3777 return false;
3778 }
3779
3780 KIGIT::GitDiffPtr diffPtr( diff );
3781
3783 [&touched]( const git_diff_delta& aDelta )
3784 {
3785 if( aDelta.old_file.path )
3786 touched.insert( aDelta.old_file.path );
3787
3788 if( aDelta.new_file.path )
3789 touched.insert( aDelta.new_file.path );
3790 } );
3791
3792 if( !touched.empty() )
3793 {
3794 std::vector<char*> paths;
3795
3796 for( const std::string& path : touched )
3797 paths.push_back( const_cast<char*>( path.c_str() ) );
3798
3799 git_checkout_options checkoutOpts;
3800 git_checkout_options_init( &checkoutOpts, GIT_CHECKOUT_OPTIONS_VERSION );
3801 checkoutOpts.checkout_strategy = GIT_CHECKOUT_FORCE;
3802 checkoutOpts.paths.strings = paths.data();
3803 checkoutOpts.paths.count = paths.size();
3804
3805 if( git_checkout_head( aRepo, &checkoutOpts ) != GIT_OK )
3806 {
3808 return false;
3809 }
3810 }
3811
3812 if( git_repository_state_cleanup( aRepo ) != GIT_OK )
3813 {
3815 return false;
3816 }
3817
3818 return true;
3819}
3820
3821
3822bool LIBGIT_BACKEND::GetMergeConflicts( git_repository* aRepo, const wxString& aStageDir, wxString& aHeadOid,
3823 wxString& aTheirsOid, std::vector<KIGIT_CONFLICT_SIDES>& aConflicts,
3824 wxString& aError )
3825{
3826 aConflicts.clear();
3827
3828 if( !aRepo )
3829 {
3830 aError = _( "The project has no git repository." );
3831 return false;
3832 }
3833
3834 KIGIT::GitIndexPtr mergedIndex;
3836 KIGIT::GitCommitPtr theirs;
3837
3838 if( !remergeInMemory( aRepo, wxEmptyString, mergedIndex, ours, theirs, aError ) )
3839 return false;
3840
3841 {
3842 char theirsStr[GIT_OID_HEXSZ + 1] = { 0 };
3843 git_oid_tostr( theirsStr, sizeof( theirsStr ), git_commit_id( theirs.get() ) );
3844 aTheirsOid = wxString::FromUTF8( theirsStr );
3845 }
3846
3847 if( !git_index_has_conflicts( mergedIndex.get() ) )
3848 {
3849 aError = _( "The merge has no conflicts." );
3850 return false;
3851 }
3852
3853 if( !wxFileName::Mkdir( aStageDir, 0700, wxPATH_MKDIR_FULL ) )
3854 {
3855 aError = _( "Could not create a temporary directory." );
3856 return false;
3857 }
3858
3859 char oidStr[GIT_OID_HEXSZ + 1] = { 0 };
3860 git_oid_tostr( oidStr, sizeof( oidStr ), git_commit_id( ours.get() ) );
3861 aHeadOid = wxString::FromUTF8( oidStr );
3862
3863 git_index_conflict_iterator* iter = nullptr;
3864
3865 if( git_index_conflict_iterator_new( &iter, mergedIndex.get() ) != GIT_OK )
3866 {
3867 aError = _( "Could not list the merge conflicts." );
3868 return false;
3869 }
3870
3871 KIGIT::GitIndexConflictIteratorPtr iterPtr( iter );
3872
3873 const git_index_entry* ancestor = nullptr;
3874 const git_index_entry* mine = nullptr;
3875 const git_index_entry* remote = nullptr;
3876 const wxString sep = wxFileName::GetPathSeparator();
3877 int n = 0;
3878
3879 while( git_index_conflict_next( &ancestor, &mine, &remote, iter ) == GIT_OK )
3880 {
3881 const git_index_entry* named = mine ? mine : ( remote ? remote : ancestor );
3882
3883 if( !named )
3884 continue;
3885
3887 sides.path = wxString::FromUTF8( named->path );
3888 sides.hasAncestor = ancestor != nullptr;
3889 sides.hasOurs = mine != nullptr;
3890 sides.hasTheirs = remote != nullptr;
3891
3892 wxString base = wxFileName( sides.path ).GetFullName();
3893 sides.ancestorFile = aStageDir + sep + wxString::Format( wxS( "c%d_base_%s" ), n, base );
3894 sides.oursFile = aStageDir + sep + wxString::Format( wxS( "c%d_mine_%s" ), n, base );
3895 sides.theirsFile = aStageDir + sep + wxString::Format( wxS( "c%d_remote_%s" ), n, base );
3896 n++;
3897
3898 if( !writeConflictSide( aRepo, ancestor, sides.ancestorFile )
3899 || !writeConflictSide( aRepo, mine, sides.oursFile )
3900 || !writeConflictSide( aRepo, remote, sides.theirsFile ) )
3901 {
3902 aError = _( "Could not extract the conflicting file versions." );
3903 return false;
3904 }
3905
3906 aConflicts.push_back( sides );
3907 }
3908
3909 return !aConflicts.empty();
3910}
3911
3912
3914 const wxString& aTheirsOid,
3915 const std::vector<std::pair<wxString, wxString>>& aResolvedFiles,
3916 KIGIT_ERROR_MESSAGE& aError )
3917{
3918 if( !aRepo )
3919 {
3920 aError.details = _( "The project has no git repository." );
3922 }
3923
3924 // The lock is released while the user resolves, so anything dirty now appeared during
3925 // resolution and the checkout below would revert it. Untracked files do not count, since
3926 // the recovery copies the panel writes beside a conflicted file are untracked.
3927 {
3928 git_status_options statusOpts;
3929 git_status_init_options( &statusOpts, GIT_STATUS_OPTIONS_VERSION );
3930 statusOpts.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
3931
3932 git_status_list* statusList = nullptr;
3933
3934 if( git_status_list_new( &statusList, aRepo, &statusOpts ) != GIT_OK )
3935 {
3936 aError.details = _( "Could not read the repository status." );
3938 }
3939
3940 KIGIT::GitStatusListPtr statusListPtr( statusList );
3941
3942 if( git_status_list_entrycount( statusList ) > 0 )
3943 {
3944 aError.details = _( "Files changed while the conflicts were being resolved, and finishing the "
3945 "merge would overwrite those changes. Get changes again to redo the merge "
3946 "with the current files." );
3948 }
3949 }
3950
3951 KIGIT::GitIndexPtr mergedIndex;
3953 KIGIT::GitCommitPtr theirs;
3954
3955 if( !remergeInMemory( aRepo, aTheirsOid, mergedIndex, ours, theirs, aError.details ) )
3957
3958 char oidStr[GIT_OID_HEXSZ + 1] = { 0 };
3959 git_oid_tostr( oidStr, sizeof( oidStr ), git_commit_id( ours.get() ) );
3960
3961 // The resolutions were made against this head. If the branch moved, they no longer apply.
3962 if( aExpectedHeadOid != wxString::FromUTF8( oidStr ) )
3963 {
3964 aError.details = _( "The repository changed while resolving. Get changes again." );
3966 }
3967
3968 for( const auto& [path, resolvedFile] : aResolvedFiles )
3969 {
3970 std::string pathUtf8( path.utf8_string() );
3971 const git_index_entry* mine = nullptr;
3972 const git_index_entry* remote = nullptr;
3973 const git_index_entry* ancestor = nullptr;
3974
3975 git_index_conflict_get( &ancestor, &mine, &remote, mergedIndex.get(), pathUtf8.c_str() );
3976
3977 // An empty path means deleted. An empty file would commit a zero byte document instead.
3978 if( resolvedFile.IsEmpty() )
3979 {
3980 if( git_index_conflict_remove( mergedIndex.get(), pathUtf8.c_str() ) != GIT_OK )
3981 {
3982 aError.details = wxString::Format( _( "Could not mark '%s' as resolved." ), path );
3984 }
3985
3986 continue;
3987 }
3988
3989 std::ifstream in( resolvedFile.fn_str(), std::ios::binary );
3990
3991 if( !in )
3992 {
3993 aError.details = wxString::Format( _( "Could not read the resolved file for '%s'." ), path );
3995 }
3996
3997 std::string bytes( ( std::istreambuf_iterator<char>( in ) ), std::istreambuf_iterator<char>() );
3998
3999 git_oid blobOid;
4000 git_writestream* stream = nullptr;
4001
4002 // The path picks the clean filters that core.autocrlf and .gitattributes name, as "git add" would
4003 bool stored = git_blob_create_from_stream( &stream, aRepo, pathUtf8.c_str() ) == GIT_OK;
4004
4005 if( stored && stream->write( stream, bytes.data(), bytes.size() ) != GIT_OK )
4006 {
4007 stream->free( stream );
4008 stored = false;
4009 }
4010
4011 if( !stored || git_blob_create_from_stream_commit( &blobOid, stream ) != GIT_OK )
4012 {
4013 aError.details = wxString::Format( _( "Could not store the resolved file for '%s'." ), path );
4015 }
4016
4017 git_index_entry entry;
4018 memset( &entry, 0, sizeof( entry ) );
4019 entry.path = pathUtf8.c_str();
4020 entry.id = blobOid;
4021 entry.mode = mine ? mine->mode : ( remote ? remote->mode : GIT_FILEMODE_BLOB );
4022
4023 if( git_index_conflict_remove( mergedIndex.get(), pathUtf8.c_str() ) != GIT_OK
4024 || git_index_add( mergedIndex.get(), &entry ) != GIT_OK )
4025 {
4026 aError.details = wxString::Format( _( "Could not mark '%s' as resolved." ), path );
4028 }
4029 }
4030
4031 if( git_index_has_conflicts( mergedIndex.get() ) )
4032 {
4033 aError.details = _( "Not every conflict was resolved." );
4035 }
4036
4037 git_oid treeOid;
4038
4039 if( git_index_write_tree_to( &treeOid, mergedIndex.get(), aRepo ) != GIT_OK )
4040 {
4041 aError.details = _( "Could not write the merge result." );
4043 }
4044
4045 git_tree* tree = nullptr;
4046
4047 if( git_tree_lookup( &tree, aRepo, &treeOid ) != GIT_OK )
4048 {
4049 aError.details = _( "Could not write the merge result." );
4051 }
4052
4053 KIGIT::GitTreePtr treePtr( tree );
4054
4055 git_signature* signature = nullptr;
4056
4057 if( int rc = git_signature_default( &signature, aRepo ); rc != GIT_OK )
4058 {
4059 aError = describeSignatureFailure( rc );
4061 }
4062
4063 KIGIT::GitSignaturePtr signaturePtr( signature );
4064
4065 git_reference* headRef = nullptr;
4066
4067 if( git_repository_head( &headRef, aRepo ) != GIT_OK )
4068 {
4069 aError.details = _( "Could not get the repository head." );
4071 }
4072
4073 KIGIT::GitReferencePtr headRefPtr( headRef );
4074
4075 const git_commit* parents[] = { ours.get(), theirs.get() };
4076 wxString message =
4077 wxString::Format( _( "Merge remote-tracking branch into %s" ), git_reference_shorthand( headRef ) );
4078 git_oid mergeCommitOid;
4079
4080 // Branch last, because the checkout is the step that can fail.
4081 if( git_commit_create( &mergeCommitOid, aRepo, nullptr, signature, signature, nullptr,
4082 message.utf8_string().c_str(), tree, 2, parents )
4083 != GIT_OK )
4084 {
4085 aError.details = wxString::Format( _( "Could not create merge commit: %s" ), KIGIT_COMMON::GetLastGitError() );
4087 }
4088
4089 // Bring the working tree and the real index to the merged content.
4090 wxString gitError;
4091
4092 switch( publishPreparedCommit( aRepo, tree, mergeCommitOid, headRef, ours.get(), "merge", gitError ) )
4093 {
4095
4097 aError.details =
4098 wxString::Format( _( "Could not update the working files, so nothing was changed: %s" ), gitError );
4100
4102 aError.details = wxString::Format( _( "Could not update the working files, and they may be partially "
4103 "changed: %s" ),
4104 gitError );
4106
4108 aError.details =
4109 wxString::Format( _( "Could not record the merge commit, so nothing was changed: %s" ), gitError );
4111
4113 aError.details = wxString::Format( _( "Could not record the merge commit, and the working files may "
4114 "have been changed: %s" ),
4115 gitError );
4117 }
4118
4120}
4121
4122
4123bool LIBGIT_BACKEND::RemoveVCS( git_repository*& aRepo, const wxString& aProjectPath, bool aRemoveGitDir,
4124 wxString* aErrors )
4125{
4126 if( aRepo )
4127 {
4128 git_repository_free( aRepo );
4129 aRepo = nullptr;
4130 }
4131
4132 if( aRemoveGitDir )
4133 {
4134 wxFileName gitDir( aProjectPath, wxEmptyString );
4135 gitDir.AppendDir( ".git" );
4136
4137 if( gitDir.DirExists() )
4138 {
4139 wxString errors;
4140
4141 if( !RmDirRecursive( gitDir.GetPath(), &errors ) )
4142 {
4143 if( aErrors )
4144 *aErrors = errors;
4145
4146 wxLogTrace( traceGit, "Failed to remove .git directory: %s", errors );
4147 return false;
4148 }
4149 }
4150 }
4151
4152 wxLogTrace( traceGit, "Successfully removed VCS from project" );
4153 return true;
4154}
int index
const char * name
KIGIT_ORPHAN_REGISTRY m_orphanRegistry
wxString GetClonePath() const
bool MatchesExpectedDestination(const wxString &aRemoteName, const wxString &aPushUrl) const
True without an expectation, or when both values match the confirmed destination.
bool MatchesExpectedTarget(const wxString &aBranch, const wxString &aHeadOid) const
True without an expectation, or when both values match the captured target.
bool HasExpectedDestination() const
bool HasExpectedTarget() const
KIGIT_COMMON::GIT_STATUS ConvertStatus(unsigned int aGitStatus)
Convert git status flags to KIGIT_COMMON::GIT_STATUS.
static bool ProjectUsesGitLfs(const KIGIT_COMMON &aCommon, wxString *aExample=nullptr, const git_oid *aCommit=nullptr)
Whether any committed file in the project's folder goes through Git LFS.
const KIGIT_ERROR_INFO & Error() const
libgit2's error for the last call that failed, read before anything else could replace it
int Fetch(std::vector< wxString > *aBranches=nullptr)
Fetch as git fetch would. aBranches, when given, receives the branches the remote advertised.
int Clone(const wxString &aUrl, const wxString &aPath, git_repository **aRepo)
Clone aUrl into aPath. The new repository is returned in aRepo for the caller to free.
int Push(const std::function< wxString()> &aConnected)
Connect, then push the refspec aConnected answers, so the caller can check what it pushes after a con...
Publishes a token for as long as its operation runs.
The project's git session.
void SyncRemoteUrl(const wxString &aRawUrl)
Bind the session to the URL a transfer is about to connect to.
std::optional< wxString > GetProjectPrefix() const
Project folder relative to the repository, with a trailing slash.
wxString GetRemote() const
bool IsOperationInProgress() const
True while a merge, rebase, cherry-pick or revert is in progress, which refuses commits.
void SetSSHKey(const wxString &aSSHKey)
void SetUsername(const wxString &aUsername)
wxString GetRemoteNameOrDefault() const
Returns GetRemotename() when non-empty, otherwise "origin".
static KIGIT_ERROR_INFO GetLastGitErrorInfo(int aCode)
The error libgit2 holds for a call that returned aCode.
git_repository * GetRepo() const
static wxString GetLastGitError()
libgit2's last message, without credentials from any URL it quotes, so it is safe to show or trace.
static REMOTE_URL ParseRemoteURL(const wxString &aURL)
void SetPassword(const wxString &aPassword)
void SetRemote(const wxString &aRemote)
void SetRepo(git_repository *aRepo)
void AddErrorString(const wxString aErrorString)
void AddError(const wxString &aSummary, const wxString &aDetails)
A summary the user can act on, with the raw text that explains it kept apart for the details.
void AddGitError(const wxString &aSummary)
Queue the summary with libgit2's last error as its details.
wxString GetProjectDir() const
Get the project directory path, preserving symlinks if set.
KIGIT_FAILURE_REPORT ReportTransferFailure(const KIGIT_ERROR_INFO &aError, KIGIT_OPERATION aOperation, const wxString &aRemoteName)
Classify a failed libgit2 transfer call and queue its summary and details.
git_repository * GetRepo() const
Get a pointer to the git repository.
const KIGIT_COMMON::CANCEL_TOKEN & CancelToken() const
bool IsThisOperationCancelled() const
std::unique_lock< std::mutex > GetActionLock() const
KIGIT_COMMON * GetCommon() const
Get the common object.
wxString GetRemotename() const
Get the remote name.
bool DiscardChanges(git_repository *aRepo, const std::vector< wxString > &aPaths, wxString &aError) override
bool AddRemote(git_repository *aRepo, const wxString &aName, const wxString &aUrl) override
bool SetRemoteUrl(git_repository *aRepo, const wxString &aName, const wxString &aUrl) 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)
RestoreResult RestoreVersion(KIGIT_COMMON &aCommon, const wxString &aCommitHash, KIGIT_ERROR_MESSAGE &aError) override
bool CheckoutTag(git_repository *aRepo, const wxString &aName) override
bool RemoveVCS(git_repository *&aRepo, const wxString &aProjectPath, bool aRemoveGitDir, wxString *aErrors) override
UndoCommitResult UndoLastCommit(GIT_COMMIT_HANDLER *aHandler, const wxString &aExpectedBranch, const git_oid &aExpectedHead, wxString &aMessage) override
Move aExpectedBranch back to the parent of aExpectedHead, leaving the index and working files as they...
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
bool StashSave(git_repository *aRepo, const wxString &aMessage) override
bool IsPathInHead(git_repository *aRepo, const wxString &aPath) override
git_repository * GetRepositoryForFile(const char *aFilename, wxString *aError, wxString *aTrustCommand) override
aError receives why git refused to open the repository, and aTrustCommand the command that trusts it ...
void Init() override
bool DeleteTag(git_repository *aRepo, const wxString &aName) override
bool StashPop(git_repository *aRepo, size_t aIndex) 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
bool GetConfigString(GIT_CONFIG_HANDLER *aHandler, const wxString &aKey, wxString &aValue) override
bool DeleteBranch(git_repository *aRepo, const wxString &aBranchName) override
bool SetupRemote(GIT_INIT_HANDLER *aHandler, const RemoteConfig &aConfig) override
MergeCommitResult CreateMergedCommit(git_repository *aRepo, const wxString &aExpectedHeadOid, const wxString &aTheirsOid, const std::vector< std::pair< wxString, wxString > > &aResolvedFiles, KIGIT_ERROR_MESSAGE &aError) override
bool IsRepository(GIT_INIT_HANDLER *aHandler, const wxString &aPath) override
int CreateBranch(git_repository *aRepo, const wxString &aBranchName, const wxString &aFrom) override
bool IsLibraryAvailable() override
void Shutdown() override
std::map< wxString, FileStatus > GetFileStatus(GIT_STATUS_HANDLER *aHandler, const wxString &aPathspec, bool aChangedOnly) override
bool StashApply(git_repository *aRepo, size_t aIndex) override
PushResult Push(GIT_PUSH_HANDLER *aHandler, bool aForce=false) override
wxString GetWorkingDirectory(GIT_STATUS_HANDLER *aHandler) override
CommitResult Amend(GIT_COMMIT_HANDLER *aHandler, const std::vector< wxString > &aFiles, const wxString &aMessage, const wxString &aAuthorName, const wxString &aAuthorEmail) override
bool GetMergeConflicts(git_repository *aRepo, const wxString &aStageDir, wxString &aHeadOid, wxString &aTheirsOid, std::vector< KIGIT_CONFLICT_SIDES > &aConflicts, wxString &aError) override
InitResult InitializeRepository(GIT_INIT_HANDLER *aHandler, const wxString &aPath) override
bool SetUserConfig(git_repository *aRepo, const wxString &aName, const wxString &aEmail) override
bool CreateTag(git_repository *aRepo, const wxString &aName, const wxString &aMessage) override
bool StashDrop(git_repository *aRepo, size_t aIndex) override
PullResult PerformPull(GIT_PULL_HANDLER *aHandler) override
bool RemoveRemote(git_repository *aRepo, const wxString &aName) override
bool AbandonOperation(git_repository *aRepo, wxString &aError) override
Drop a merge, rebase, cherry-pick or revert left in progress and return to the last commit.
static wxString GetUserCachePath()
Gets the stock (install) 3d viewer plugins path.
Definition paths.cpp:422
#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:512
CommitResult
Definition git_backend.h:55
@ SuccessIndexStale
Committed, but the staged list was left as another program had it. Never retry on this.
Definition git_backend.h:59
MergeCommitResult
Definition git_backend.h:83
UndoCommitResult
Definition git_backend.h:67
@ TargetChanged
The branch or its last commit is no longer the one the caller saw.
Definition git_backend.h:74
@ Published
A remote-tracking branch already holds the commit, so taking it back would rewrite shared history.
Definition git_backend.h:71
static KIGIT::PROMPT_ANSWER refusal(const wxWeakRef< wxWindow > &aParent, bool aHadParent)
InitResult
PullResult
PushResult
@ Busy
Another git operation held the action lock, so nothing was pushed.
const wxChar *const traceGit
Flag to enable Git debugging output.
std::string message
int fetchhead_foreach_cb(const char *, const char *, const git_oid *aOID, unsigned int aIsMerge, void *aPayload)
RestoreResult
@ AlreadyCurrent
The chosen version's content matches the current head.
@ Restored
A new commit carrying the old version's content was created.
@ Error
The restore failed. See the error string.
@ Dirty
Uncommitted changes exist, and restoring would overwrite them.
#define GIT_BUF_INIT
The one place a fetch, push, clone or connection check reaches a remote.
static bool indexChangedSince(git_index *aIndex, const std::map< std::string, SELECTED_STATE > &aAtStart)
static void refreshCachedIndex(git_repository *aRepo)
static int lookup_branch_reference(git_repository *repo, const wxString &aBranchName, git_reference **aReference)
static bool rollbackWorkingTree(git_repository *aRepo, git_commit *aHeadCommit, git_tree *aWrittenTree)
static std::map< std::string, SELECTED_STATE > readSelectedState(git_index *aIndex, const std::set< std::string > &aSelected)
static bool fetchRemote(GIT_PULL_HANDLER *aHandler, bool aSkipLock, bool *aRemoteHasBranches)
static bool safeToRestore(git_repository *aRepo, const char *aPath, git_tree *aPreviousTree, git_tree *aWrittenTree)
static bool untrackedFilesOverwrittenBy(git_repository *aRepo, git_tree *aIncomingTree, std::vector< wxString > &aCollisions)
static bool branchMovedSince(git_repository *aRepo, const git_oid &aHeadAtStart, bool aHadHead)
static PUBLISH_RESULT publishPreparedCommit(git_repository *aRepo, git_tree *aTree, const git_oid &aCommitOid, git_reference *aHeadRef, git_commit *aRollbackCommit, const char *aReflogLabel, wxString &aGitError)
PUBLISH_RESULT
static bool applyStashOntoCleanTree(git_repository *aRepo, size_t aIndex)
static int reachableFromRemote(git_repository *aRepo, const git_oid &aCommit, wxString &aRemoteRef)
static PullResult rebaseOnto(GIT_PULL_HANDLER *aHandler, git_repository *aRepo, const git_annotated_commit *aOnto)
static bool refuseWhileOperationInProgress(git_repository *aRepo, git_index *aIndex, wxString &aError)
static PullResult adoptRemoteHistory(GIT_PULL_HANDLER *aHandler, const git_oid &aRemoteOid)
static TREE_STATE trackedTreeState(git_repository *aRepo)
REPUBLISH_RESULT
static git_index * openIndexOnDisk(git_index *aRepoIndex)
static wxString describeUntrackedCollisions(const std::vector< wxString > &aPaths)
static bool selectedPathsRestaged(git_index *aIndex, const std::set< std::string > &aSelected, const std::map< std::string, SELECTED_STATE > &aAtStart)
static bool treeHolds(git_tree *aTree, const char *aPath, const git_oid &aOnDisk)
static bool wholeStateOnDisk(git_index *aRepoIndex, std::map< std::string, SELECTED_STATE > &aOut)
static std::vector< std::string > changedPaths(git_repository *aRepo)
static bool selectedStateOnDisk(git_index *aRepoIndex, const std::set< std::string > &aSelected, std::map< std::string, SELECTED_STATE > &aOut)
static void reportRemoteLookupFailure(KIGIT_ERRORS *aHandler, int aRc, const wxString &aRemoteName)
static bool restorePathsFromCommit(git_repository *aRepo, git_commit *aCommit, const std::vector< std::string > &aPaths)
static const char ADOPT_REMOTE_BRANCH_KEY[]
static wxString unbornBranchName(git_repository *aRepo)
static std::map< std::string, SELECTED_STATE > readWholeState(git_index *aIndex)
static REPUBLISH_RESULT republishIndex(git_index *aIndex, const std::vector< STAGED_ENTRY > &aCommitted, const std::set< std::string > &aSelected)
static KIGIT_ERROR_MESSAGE describeSignatureFailure(int aRc)
static bool adoptRemoteBranch(git_repository *aRepo, const wxString &aRemoteName, const std::vector< wxString > &aRemoteBranches)
static bool markForRemoteBranchAdoption(git_repository *aRepo)
static bool applySelectedPaths(git_repository *aRepo, git_index *aIndex, const std::vector< wxString > &aFiles)
std::unique_ptr< git_tree, decltype([](git_tree *aTree) { git_tree_free(aTree); })> GitTreePtr
A unique pointer for git_tree objects with automatic cleanup.
wxString BusyMessage()
What every caller says when it finds the session already busy.
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_index_conflict_iterator, decltype([](git_index_conflict_iterator *aIterator) { git_index_conflict_iterator_free(aIterator); })> GitIndexConflictIteratorPtr
A unique pointer for git_index_conflict_iterator objects with automatic cleanup.
void CollectDiffDeltas(git_diff *aDiff, const std::function< void(const git_diff_delta &)> &aCallback)
Walk every delta in a computed diff, invoking aCallback once per delta.
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.
APIEXPORT KIGIT_OWNERSHIP_REFUSAL DescribeOwnershipRefusal(const wxString &aStartDir, const wxString &aGitDir)
The message for a repository git refuses to open because another user owns it.
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.
APIEXPORT void SetDerivedPublicKeyFolder(const wxString &aDir)
Keep public key files written by EnsurePublicKeyFile in aDir.
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_reference_iterator, decltype([](git_reference_iterator *aIter) { git_reference_iterator_free(aIter); })> GitReferenceIteratorPtr
A unique pointer for git_reference_iterator objects with automatic cleanup.
APIEXPORT void SetRememberedSSHKeyStore(const wxString &aPath)
Keep remembered keys in aPath.
APIEXPORT KIGIT_FAILURE_REPORT DescribeGitFailure(const KIGIT_ERROR_INFO &aError, const KIGIT_AUTH_ATTEMPT &aAuth, const KIGIT_FAILURE_CONTEXT &aContext)
Turn a failed transfer into a message the user can act on.
std::unique_ptr< git_tree_entry, decltype([](git_tree_entry *aEntry) { git_tree_entry_free(aEntry); })> GitTreeEntryPtr
A unique pointer for git_tree_entry objects with automatic cleanup.
std::unique_ptr< git_blob, decltype([](git_blob *aBlob) { git_blob_free(aBlob); })> GitBlobPtr
A unique pointer for git_blob 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_branch_iterator, decltype([](git_branch_iterator *aIter) { git_branch_iterator_free(aIter); })> GitBranchIteratorPtr
A unique pointer for git_branch_iterator 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_diff, decltype([](git_diff *aDiff) { git_diff_free(aDiff); })> GitDiffPtr
A unique pointer for git_diff 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.
SCRATCH_INDEX_GUARD scratchGuard
std::map< std::string, SELECTED_STATE > indexAtStart
std::map< std::string, SELECTED_STATE > selectedAtStart
bool BuildTree(git_repository *aRepo, const std::vector< wxString > &aFiles, KIGIT::GitTreePtr &aTreeOut, KIGIT_ERROR_MESSAGE &aError)
Stage the chosen files over whatever the index already holds and write the tree they make.
bool Begin(git_repository *aRepo, const std::vector< wxString > &aFiles, KIGIT_ERROR_MESSAGE &aError)
Read the index, record what it holds and take it over. False leaves the reason in aError.
std::set< std::string > selectedPaths
std::vector< STAGED_ENTRY > committedEntries
KIGIT::GitIndexPtr indexPtr
A transport address with any embedded credentials extracted.
wxString url
Keeps the SSH username, scheme and port, but never a password.
wxString theirsFile
Extracted remote version, an empty file when absent.
wxString ancestorFile
Extracted common-ancestor version, an empty file when absent.
wxString oursFile
Extracted local version, an empty file when absent.
bool hasOurs
False when the local side deleted the file.
wxString path
Repository-relative path of the conflicted file.
bool hasTheirs
False when the remote side deleted the file.
bool hasAncestor
False when the file did not exist in the common ancestor.
A summary the user can act on, with the raw text that explains it kept apart for the details.
What the failed operation was doing, as far as the message needs it.
KIGIT_OPERATION operation
wxString url
The address connected to. Messages show only its host and its stripped form.
wxString remoteName
Empty when the operation has no named remote, as for a clone.
wxString summary
What happened and what to do next, in the user's terms. Never raw text.
wxString details
The raw error, the server's text and the address without its password.
Why git will not open a repository another user owns, and the command that trusts it.
bool operator==(const SELECTED_STATE &aOther) const
bool operator!=(const SELECTED_STATE &aOther) const
git_index_entry entry
std::string path
static std::vector< uint8_t > bytes(const std::string &aText)
bool moved
std::string path
wxString result
Test unit parsing edge cases and error handling.
int delta
wxLogTrace helper definitions.