KiCad PCB EDA Suite
Loading...
Searching...
No Matches
kicad_git_common.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 "kicad_git_common.h"
21#include "kicad_git_memory.h"
22#include "git_repo_mixin.h"
23#include "git_backend.h"
24#include "kigit_ssh_keys.h"
25#include "project_git_utils.h"
26
27#include <git/git_progress.h>
29#include <kiplatform/secrets.h>
30#include <trace_helpers.h>
31
32#include <git2.h>
33#include <wx/arrstr.h>
34#include <wx/base64.h>
35#include <wx/ffile.h>
36#include <wx/filename.h>
37#include <wx/log.h>
38#include <wx/utils.h>
39#include <algorithm>
40#include <cctype>
41#include <cerrno>
42#include <chrono>
43#include <cstdlib>
44#include <cstring>
45#include <map>
46#include <set>
47#include <string>
48#include <thread>
49#include <vector>
50
51
53{
54 static wxWindow* window = nullptr;
55
56 return window;
57}
58
59
60KIGIT_COMMON::KIGIT_COMMON( git_repository* aRepo, const wxString& aProjectPath ) :
61 m_repo( aRepo ),
62 m_projectPath( aProjectPath ),
64 m_nextPublicKey( 0 ),
65 m_secretFetched( false )
66{}
67
68
70 // Initialize base class and member variables
71 m_repo( aOther.m_repo ),
72 m_projectDir( aOther.m_projectDir ),
74 m_connType( aOther.m_connType ),
75 m_remote( aOther.m_remote ),
77 m_hostname( aOther.m_hostname ),
78 m_port( aOther.m_port ),
79 m_username( aOther.m_username ),
80 m_password( aOther.m_password ),
81
82 // The mutex is default-initialized, not copied
85 m_publicKeys( aOther.m_publicKeys ),
91{
92}
93
94
97
98
100{
101 return m_repo;
102}
103
104
106{
107 if( !m_projectDir.IsEmpty() )
108 return m_projectDir;
109
110 if( m_repo )
111 {
112 const char* workdir = git_repository_workdir( m_repo );
113
114 if( workdir )
115 return wxString( workdir );
116 }
117
118 return wxEmptyString;
119}
120
121
122std::optional<wxString> KIGIT_COMMON::GetProjectPrefix() const
123{
124 if( !m_repo || !git_repository_workdir( m_repo ) )
125 return std::nullopt;
126
128}
129
130
132{
133 if( !m_repo )
134 return wxEmptyString;
135
136 git_reference* head = nullptr;
137
138 int retval = git_repository_head( &head, m_repo );
139
140 if( retval && retval != GIT_EUNBORNBRANCH && retval != GIT_ENOTFOUND )
141 return wxEmptyString;
142
143 // An unborn or missing HEAD leaves head null, so there is no branch to resolve.
144 if( !head )
145 return wxEmptyString;
146
147 KIGIT::GitReferencePtr headPtr( head );
148 git_reference* branch;
149
150 if( git_reference_resolve( &branch, head ) )
151 {
152 wxLogTrace( traceGit, "Failed to resolve branch" );
153 return wxEmptyString;
154 }
155
156 KIGIT::GitReferencePtr branchPtr( branch );
157 const char* branchName = "";
158
159 if( git_branch_name( &branchName, branch ) )
160 {
161 wxLogTrace( traceGit, "Failed to get branch name" );
162 return wxEmptyString;
163 }
164
165 return wxString( branchName );
166}
167
168
170{
171 git_oid oid;
172
173 if( !m_repo || git_reference_name_to_id( &oid, m_repo, "HEAD" ) != GIT_OK )
174 return wxEmptyString;
175
176 return wxString::FromUTF8( git_oid_tostr_s( &oid ) );
177}
178
179
181{
182 wxString remote;
183 wxString username;
184
185 {
186 std::lock_guard<std::mutex> lock( m_credentialsMutex );
187
188 if( m_secretFetched )
189 return m_password;
190
192 {
193 m_secretFetched = true;
194 return m_password;
195 }
196
197 remote = m_remote;
198 username = m_username;
199 }
200
201 // Transfer workers call this, so a locked keyring reads as empty rather than prompting off the UI
202 // thread. DeferForSecret reads it with a prompt first
203 wxString secret;
204 bool found = KIPLATFORM::SECRETS::GetSecretNoPrompt( remote, username, secret );
205
206 std::lock_guard<std::mutex> lock( m_credentialsMutex );
207
208 // The user may have typed a password, or changed the remote, while the keychain was being
209 // asked. Either way this answer is about the wrong thing and is dropped.
210 if( m_secretFetched || m_remote != remote || m_username != username )
211 return m_password;
212
213 // A miss may be a locked keyring, which DeferForSecret must still get to unlock
214 if( found )
215 {
216 m_password = secret;
217 m_secretFetched = true;
218 }
219
220 return m_password;
221}
222
223
224bool KIGIT_COMMON::DeferForSecret( const std::shared_ptr<KIGIT_COMMON>& aCommon, const std::weak_ptr<bool>& aOwner,
225 std::function<void()> aRetry )
226{
227 wxString remote;
228 wxString username;
229
230 {
231 std::lock_guard<std::mutex> lock( aCommon->m_credentialsMutex );
232
233 if( aCommon->secretReadLocked() )
234 return false;
235
236 remote = aCommon->m_remote;
237 username = aCommon->m_username;
238 }
239
240 auto finish = [weak = std::weak_ptr<KIGIT_COMMON>( aCommon ), aOwner, remote, username,
241 retry = std::move( aRetry )]( bool aFound, const wxString& aSecret )
242 {
243 // Held here because a project teardown can drop the last owner on a worker
244 std::shared_ptr<KIGIT_COMMON> common = weak.lock();
245
246 if( !common || aOwner.expired() )
247 return;
248
249 {
250 std::lock_guard<std::mutex> lock( common->m_credentialsMutex );
251
252 // A password typed meanwhile wins, and an answer about another remote is dropped
253 if( !common->m_secretFetched && common->m_remote == remote && common->m_username == username )
254 {
255 if( aFound )
256 common->m_password = aSecret;
257
258 common->m_secretFetched = true;
259 }
260 }
261
262 retry();
263 };
264
265 KIPLATFORM::SECRETS::GetSecretAsync( remote, username, std::move( finish ) );
266 return true;
267}
268
269
271{
272 if( !m_repo )
273 return wxEmptyString;
274
275 git_oid headOid;
276
277 if( git_reference_name_to_id( &headOid, m_repo, "HEAD" ) != GIT_OK )
278 return wxEmptyString;
279
280 git_commit* commit = nullptr;
281
282 if( git_commit_lookup( &commit, m_repo, &headOid ) != GIT_OK )
283 return wxEmptyString;
284
285 KIGIT::GitCommitPtr commitPtr( commit );
286 const char* message = git_commit_message( commit );
287
288 return message ? KIGIT::DecodeRepoText( message ) : wxString();
289}
290
291
293{
294 if( aReadOk )
295 *aReadOk = false;
296
297 if( !m_repo )
298 return false;
299
300 git_status_options statusOpts;
301 git_status_init_options( &statusOpts, GIT_STATUS_OPTIONS_VERSION );
302 statusOpts.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
303
304 git_status_list* statusList = nullptr;
305
306 if( git_status_list_new( &statusList, m_repo, &statusOpts ) != GIT_OK )
307 return false;
308
309 KIGIT::GitStatusListPtr statusListPtr( statusList );
310
311 if( aReadOk )
312 *aReadOk = true;
313
314 return git_status_list_entrycount( statusList ) > 0;
315}
316
317
318namespace
319{
320
321// The refs pointing at each commit, keyed by the commit's full hash, HEAD first.
322std::map<std::string, std::vector<wxString>> collectRefNames( git_repository* aRepo )
323{
324 std::map<std::string, std::vector<wxString>> names;
325
326 git_oid headOid;
327
328 if( git_reference_name_to_id( &headOid, aRepo, "HEAD" ) == GIT_OK )
329 names[git_oid_tostr_s( &headOid )].push_back( wxS( "HEAD" ) );
330
331 git_reference_iterator* iter = nullptr;
332
333 if( git_reference_iterator_new( &iter, aRepo ) != GIT_OK )
334 return names;
335
336 KIGIT::GitReferenceIteratorPtr iterPtr( iter );
337 git_reference* ref = nullptr;
338
339 // Iteration is by ref name, which puts local branches before remote ones and tags last.
340 while( git_reference_next( &ref, iter ) == GIT_OK )
341 {
342 KIGIT::GitReferencePtr refPtr( ref );
343
344 if( !git_reference_is_branch( ref ) && !git_reference_is_remote( ref ) && !git_reference_is_tag( ref ) )
345 continue;
346
347 git_object* target = nullptr;
348
349 if( git_reference_peel( &target, ref, GIT_OBJECT_COMMIT ) != GIT_OK )
350 continue;
351
352 KIGIT::GitObjectPtr targetPtr( target );
353
354 std::string hash = git_oid_tostr_s( git_object_id( target ) );
355 names[hash].push_back( KIGIT::DecodeRepoText( git_reference_shorthand( ref ) ) );
356 }
357
358 return names;
359}
360
361
362wxString shortHashOf( const git_oid* aOid )
363{
364 // A 7-char abbreviation can be ambiguous in a large repository, which makes a later
365 // revparse of the hash fail. Twelve characters is what git uses for big repos.
366 char shortHash[13] = { 0 };
367 git_oid_tostr( shortHash, sizeof( shortHash ), aOid );
368 return wxString::FromUTF8( shortHash );
369}
370
371
372KIGIT::FILE_CHANGE_STATUS deltaStatus( git_delta_t aDelta )
373{
374 switch( aDelta )
375 {
376 case GIT_DELTA_ADDED: return KIGIT::FILE_CHANGE_STATUS::ADDED;
377 case GIT_DELTA_DELETED: return KIGIT::FILE_CHANGE_STATUS::REMOVED;
378 case GIT_DELTA_RENAMED: return KIGIT::FILE_CHANGE_STATUS::RENAMED;
379 case GIT_DELTA_COPIED: return KIGIT::FILE_CHANGE_STATUS::COPIED;
380 case GIT_DELTA_TYPECHANGE: return KIGIT::FILE_CHANGE_STATUS::TYPECHANGE;
382 }
383}
384
385} // namespace
386
387
389{
390 if( !m_repo )
391 return wxDateTime();
392
393 const char* gitDir = git_repository_path( m_repo );
394
395 if( !gitDir )
396 return wxDateTime();
397
398 // Git rewrites FETCH_HEAD on every fetch, so its timestamp is the last one.
399 wxFileName fetchHead( wxString::FromUTF8( gitDir ), wxS( "FETCH_HEAD" ) );
400
401 if( !fetchHead.FileExists() )
402 return wxDateTime();
403
404 return fetchHead.GetModificationTime();
405}
406
407
409{
411
412 if( !m_repo )
413 return detail;
414
415 git_oid oid;
416
417 if( git_oid_fromstr( &oid, aId.utf8_string().c_str() ) != GIT_OK )
418 return detail;
419
420 git_commit* commit = nullptr;
421
422 if( git_commit_lookup( &commit, m_repo, &oid ) != GIT_OK )
423 return detail;
424
425 KIGIT::GitCommitPtr commitPtr( commit );
426
427 detail.found = true;
428 detail.when = wxDateTime( static_cast<time_t>( git_commit_time( commit ) ) );
429
430 // Git writes "WIP on <branch>: <commit> <subject>", or "On <branch>: <message>" for a
431 // message of the user's own. The branch is kept apart from the rest.
432 wxString raw;
433
434 if( const char* message = git_commit_message( commit ) )
436
437 raw.Trim();
438 detail.message = raw;
439
440 wxString rest;
441
442 if( raw.StartsWith( wxS( "WIP on " ), &rest ) || raw.StartsWith( wxS( "On " ), &rest ) )
443 {
444 int colon = rest.Find( wxS( ": " ) );
445
446 if( colon != wxNOT_FOUND )
447 {
448 detail.branch = rest.Left( colon );
449 detail.message = rest.Mid( colon + 2 );
450 }
451 }
452
453 // The first parent is the commit the stash was taken on. A third parent, when there is
454 // one, holds the untracked files.
455 git_commit* base = nullptr;
456
457 if( git_commit_parent( &base, commit, 0 ) != GIT_OK )
458 return detail;
459
460 KIGIT::GitCommitPtr basePtr( base );
461 detail.baseHash = shortHashOf( git_commit_id( base ) );
462
463 git_tree* baseTree = nullptr;
464 git_tree* stashTree = nullptr;
465
466 if( git_commit_tree( &baseTree, base ) != GIT_OK || git_commit_tree( &stashTree, commit ) != GIT_OK )
467 return detail;
468
469 KIGIT::GitTreePtr baseTreePtr( baseTree );
470 KIGIT::GitTreePtr stashTreePtr( stashTree );
471 git_diff* diff = nullptr;
472
473 if( git_diff_tree_to_tree( &diff, m_repo, baseTree, stashTree, nullptr ) == GIT_OK )
474 {
475 KIGIT::GitDiffPtr diffPtr( diff );
476
478 [&detail]( const git_diff_delta& aDelta )
479 {
480 const char* path =
481 aDelta.new_file.path ? aDelta.new_file.path : aDelta.old_file.path;
482 detail.files.push_back( wxString::FromUTF8( path ) );
483 } );
484 }
485
486 if( git_commit_parentcount( commit ) > 2 )
487 {
488 git_commit* untracked = nullptr;
489
490 if( git_commit_parent( &untracked, commit, 2 ) == GIT_OK )
491 {
492 KIGIT::GitCommitPtr untrackedPtr( untracked );
493 git_tree* untrackedTree = nullptr;
494
495 if( git_commit_tree( &untrackedTree, untracked ) == GIT_OK )
496 {
497 KIGIT::GitTreePtr untrackedTreePtr( untrackedTree );
498
499 git_tree_walk(
500 untrackedTree, GIT_TREEWALK_PRE,
501 []( const char* aRoot, const git_tree_entry* aEntry, void* aPayload ) -> int
502 {
503 if( git_tree_entry_type( aEntry ) == GIT_OBJECT_BLOB )
504 {
505 auto* files = static_cast<std::vector<wxString>*>( aPayload );
506 files->push_back( wxString::FromUTF8( aRoot )
507 + wxString::FromUTF8( git_tree_entry_name( aEntry ) ) );
508 }
509
510 return 0;
511 },
512 &detail.files );
513 }
514 }
515 }
516
517 return detail;
518}
519
520
521std::pair<int, int> KIGIT_COMMON::GetWorkingTreeLineStats( const std::set<wxString>& aPaths ) const
522{
523 if( !m_repo )
524 return { 0, 0 };
525
526 // An unborn repository has no HEAD tree, and then everything in the tree is new.
527 KIGIT::GitTreePtr headTree;
528 git_object* headObj = nullptr;
529
530 if( git_revparse_single( &headObj, m_repo, "HEAD^{tree}" ) == GIT_OK )
531 headTree.reset( reinterpret_cast<git_tree*>( headObj ) );
532
533 git_diff_options opts;
534 git_diff_options_init( &opts, GIT_DIFF_OPTIONS_VERSION );
535 opts.flags = GIT_DIFF_INCLUDE_UNTRACKED | GIT_DIFF_RECURSE_UNTRACKED_DIRS | GIT_DIFF_SHOW_UNTRACKED_CONTENT;
536
537 git_diff* diff = nullptr;
538
539 if( git_diff_tree_to_workdir_with_index( &diff, m_repo, headTree.get(), &opts ) != GIT_OK )
540 return { 0, 0 };
541
542 KIGIT::GitDiffPtr diffPtr( diff );
543 std::pair<int, int> total{ 0, 0 };
544
545 for( size_t ii = 0; ii < git_diff_num_deltas( diff ); ++ii )
546 {
547 git_patch* patch = nullptr;
548
549 if( git_patch_from_diff( &patch, diff, ii ) != GIT_OK )
550 continue;
551
552 KIGIT::GitPatchPtr patchPtr( patch );
553 const git_diff_delta* delta = git_patch_get_delta( patch );
554 const char* path = delta->new_file.path ? delta->new_file.path : delta->old_file.path;
555
556 if( !path || aPaths.count( wxString::FromUTF8( path ) ) == 0 )
557 continue;
558
559 size_t added = 0;
560 size_t removed = 0;
561
562 if( git_patch_line_stats( nullptr, &added, &removed, patch ) == GIT_OK )
563 {
564 total.first += static_cast<int>( added );
565 total.second += static_cast<int>( removed );
566 }
567 }
568
569 return total;
570}
571
572
573std::vector<KIGIT_BRANCH_INFO> KIGIT_COMMON::GetBranches() const
574{
575 if( !m_repo )
576 return {};
577
578 std::vector<KIGIT_BRANCH_INFO> branches;
579
580 git_branch_iterator* branchIterator = nullptr;
581
582 if( git_branch_iterator_new( &branchIterator, m_repo, GIT_BRANCH_ALL ) )
583 {
584 wxLogTrace( traceGit, "Failed to get branch iterator" );
585 return {};
586 }
587
588 KIGIT::GitBranchIteratorPtr branchIteratorPtr( branchIterator );
589 git_reference* branchReference = nullptr;
590 git_branch_t branchType;
591
592 // Only GIT_ITEROVER means the end. Any other error leaves the reference invalid.
593 while( true )
594 {
595 branchReference = nullptr;
596
597 int rc = git_branch_next( &branchReference, &branchType, branchIterator );
598
599 if( rc == GIT_ITEROVER )
600 break;
601
602 if( rc != GIT_OK )
603 {
604 wxLogTrace( traceGit, "Failed to iterate branches: %s", KIGIT_COMMON::GetLastGitError() );
605 break;
606 }
607
608 const char* branchName = "";
609 KIGIT::GitReferencePtr branchReferencePtr( branchReference );
610
611 // origin/HEAD and other symbolic aliases do not name a separate branch.
612 if( git_reference_type( branchReference ) != GIT_REFERENCE_DIRECT )
613 continue;
614
615 if( git_branch_name( &branchName, branchReference ) )
616 {
617 wxLogTrace( traceGit, "Failed to get branch name in iter loop" );
618 continue;
619 }
620
621 const git_oid* commitId = git_reference_target( branchReference );
622 git_commit* commit = nullptr;
623
624 if( !commitId || git_commit_lookup( &commit, m_repo, commitId ) != GIT_OK )
625 {
626 wxLogTrace( traceGit, "Failed to get commit in iter loop" );
627 continue;
628 }
629
630 KIGIT::GitCommitPtr commitPtr( commit );
631 git_time_t commitTime = git_commit_time( commit );
632
634 info.name = KIGIT::DecodeRepoText( branchName );
635 info.isRemote = branchType == GIT_BRANCH_REMOTE;
636 info.isCurrent = !info.isRemote && git_branch_is_head( branchReference ) == 1;
637 info.tipHash = shortHashOf( commitId );
638 info.message = KIGIT::DecodeRepoText( git_commit_message( commit ) );
639 info.when = wxDateTime( static_cast<time_t>( commitTime ) );
640
641 branches.push_back( std::move( info ) );
642 }
643
644 return branches;
645}
646
647
649{
651
652 if( !m_repo )
653 return detail;
654
655 // The short name as the Branches page lists it, local or remote, resolved as git would.
656 git_reference* ref = nullptr;
657
658 if( git_reference_dwim( &ref, m_repo, aBranch.utf8_string().c_str() ) != GIT_OK )
659 return detail;
660
661 KIGIT::GitReferencePtr refPtr( ref );
662 git_object* target = nullptr;
663
664 if( git_reference_peel( &target, ref, GIT_OBJECT_COMMIT ) != GIT_OK )
665 return detail;
666
667 KIGIT::GitObjectPtr targetPtr( target );
668 git_commit* commit = reinterpret_cast<git_commit*>( target );
669
670 detail.found = true;
671 detail.name = aBranch;
672 detail.tipHash = shortHashOf( git_commit_id( commit ) );
673 detail.when = wxDateTime( static_cast<time_t>( git_commit_time( commit ) ) );
674
675 if( const git_signature* author = git_commit_author( commit ) )
676 {
677 detail.author = KIGIT::DecodeRepoText( author->name );
678 detail.email = KIGIT::DecodeRepoText( author->email );
679 }
680
681 if( const char* message = git_commit_message( commit ) )
683
684 detail.message.Trim();
685
686 // Only a local branch tracks another. A remote-tracking branch has nothing to compare with.
687 git_reference* upstream = nullptr;
688
689 if( !git_reference_is_branch( ref ) || git_branch_upstream( &upstream, ref ) != GIT_OK )
690 return detail;
691
692 KIGIT::GitReferencePtr upstreamPtr( upstream );
693 const char* upstreamName = "";
694
695 if( git_branch_name( &upstreamName, upstream ) == GIT_OK )
696 detail.upstream = KIGIT::DecodeRepoText( upstreamName );
697
698 detail.divergence = compareRefs( ref, upstream );
699
700 return detail;
701}
702
703
704std::vector<wxString> KIGIT_COMMON::GetProjectDirs()
705{
706 if( !m_repo )
707 return {};
708
709 std::vector<wxString> projDirs;
710
711 git_oid oid;
712 git_commit* commit;
713 git_tree *tree;
714
715 if( git_reference_name_to_id( &oid, m_repo, "HEAD" ) != GIT_OK )
716 {
717 wxLogTrace( traceGit, "An error occurred: %s", KIGIT_COMMON::GetLastGitError() );
718 return projDirs;
719 }
720
721 if( git_commit_lookup( &commit, m_repo, &oid ) != GIT_OK )
722 {
723 wxLogTrace( traceGit, "An error occurred: %s", KIGIT_COMMON::GetLastGitError() );
724 return projDirs;
725 }
726
727 KIGIT::GitCommitPtr commitPtr( commit );
728
729 if( git_commit_tree( &tree, commit ) != GIT_OK )
730 {
731 wxLogTrace( traceGit, "An error occurred: %s", KIGIT_COMMON::GetLastGitError() );
732 return projDirs;
733 }
734
735 KIGIT::GitTreePtr treePtr( tree );
736
737 // Define callback
738 git_tree_walk(
739 tree, GIT_TREEWALK_PRE,
740 []( const char* root, const git_tree_entry* entry, void* payload )
741 {
742 std::vector<wxString>* prjs = static_cast<std::vector<wxString>*>( payload );
743 wxFileName root_fn( git_tree_entry_name( entry ) );
744
745 root_fn.SetPath( root );
746
747 if( git_tree_entry_type( entry ) == GIT_OBJECT_BLOB
748 && ( ( root_fn.GetExt() == "kicad_pro" ) || ( root_fn.GetExt() == "pro" ) ) )
749 {
750 prjs->push_back( root_fn.GetFullPath() );
751 }
752
753 return 0; // continue walking
754 },
755 &projDirs );
756
757 std::sort( projDirs.begin(), projDirs.end(),
758 []( const wxString& a, const wxString& b )
759 {
760 int a_freq = a.Freq( wxFileName::GetPathSeparator() );
761 int b_freq = b.Freq( wxFileName::GetPathSeparator() );
762
763 if( a_freq == b_freq )
764 return a < b;
765 else
766 return a_freq < b_freq;
767 } );
768
769 return projDirs;
770}
771
772
773std::pair<std::set<wxString>, std::set<wxString>> KIGIT_COMMON::GetDifferentFiles() const
774{
775 std::pair<std::set<wxString>, std::set<wxString>> modified_files;
776
777 if( !m_repo || IsShuttingDown() )
778 return modified_files;
779
780 git_reference* head = nullptr;
781 git_reference* remote_head = nullptr;
782
783 if( git_repository_head( &head, m_repo ) != GIT_OK )
784 {
785 wxLogTrace( traceGit, "Failed to get modified HEAD" );
786 return modified_files;
787 }
788
789 KIGIT::GitReferencePtr headPtr( head );
790
791 if( git_branch_upstream( &remote_head, head ) != GIT_OK )
792 {
793 // Branch has no upstream tracking ref configured. Without an upstream there is
794 // nothing to compare against, so leave both sets empty. Walking commits unbounded
795 // would otherwise dump the entire history's root tree into the result.
796 wxLogTrace( traceGit, "Failed to get modified remote HEAD" );
797 return modified_files;
798 }
799
800 KIGIT::GitReferencePtr remoteHeadPtr( remote_head );
801
802 const git_oid* head_oid = git_reference_target( head );
803 const git_oid* remote_oid = git_reference_target( remote_head );
804
805 if( !head_oid || !remote_oid )
806 return modified_files;
807
808 auto load_tree = [this]( const git_oid* aOid ) -> git_tree*
809 {
810 git_commit* commit = nullptr;
811
812 if( git_commit_lookup( &commit, m_repo, aOid ) != GIT_OK )
813 {
814 wxLogTrace( traceGit, "Failed to lookup commit for diff: %s", KIGIT_COMMON::GetLastGitError() );
815 return nullptr;
816 }
817
818 KIGIT::GitCommitPtr commitPtr( commit );
819 git_tree* tree = nullptr;
820
821 if( git_commit_tree( &tree, commit ) != GIT_OK )
822 {
823 wxLogTrace( traceGit, "Failed to get commit tree for diff: %s", KIGIT_COMMON::GetLastGitError() );
824 return nullptr;
825 }
826
827 return tree;
828 };
829
830 git_tree* head_tree = load_tree( head_oid );
831 KIGIT::GitTreePtr headTreePtr( head_tree );
832
833 git_tree* remote_tree = load_tree( remote_oid );
834 KIGIT::GitTreePtr remoteTreePtr( remote_tree );
835
836 if( !head_tree || !remote_tree )
837 return modified_files;
838
839 // Find the merge-base so AHEAD and BEHIND can be distinguished. AHEAD = files that
840 // changed between merge-base and HEAD (only in local commits). BEHIND = files that
841 // changed between merge-base and the remote tip (only in remote commits). Without a
842 // shared history the merge-base lookup fails; in that case we treat both sets as empty
843 // because there is no meaningful "ahead vs behind" partition to compute.
844 git_oid base_oid;
845
846 if( git_merge_base( &base_oid, m_repo, head_oid, remote_oid ) != GIT_OK )
847 {
848 wxLogTrace( traceGit, "No merge base between local and remote: %s", KIGIT_COMMON::GetLastGitError() );
849 return modified_files;
850 }
851
852 git_tree* base_tree = load_tree( &base_oid );
853 KIGIT::GitTreePtr baseTreePtr( base_tree );
854
855 if( !base_tree )
856 return modified_files;
857
858 auto collect_paths = [this]( git_tree* aOldTree, git_tree* aNewTree, std::set<wxString>& aOut )
859 {
860 if( IsShuttingDown() )
861 return;
862
863 git_diff_options localOpts;
864 git_diff_init_options( &localOpts, GIT_DIFF_OPTIONS_VERSION );
865
866 git_diff* diff = nullptr;
867
868 if( git_diff_tree_to_tree( &diff, m_repo, aOldTree, aNewTree, &localOpts ) != GIT_OK )
869 {
870 wxLogTrace( traceGit, "Failed to diff trees: %s", KIGIT_COMMON::GetLastGitError() );
871 return;
872 }
873
875 [&aOut]( const git_diff_delta& aDelta )
876 {
877 if( aDelta.new_file.path )
878 aOut.insert( wxString::FromUTF8( aDelta.new_file.path ) );
879
880 if( aDelta.old_file.path )
881 aOut.insert( wxString::FromUTF8( aDelta.old_file.path ) );
882 } );
883
884 git_diff_free( diff );
885 };
886
887 collect_paths( base_tree, head_tree, modified_files.first ); // AHEAD
888 collect_paths( base_tree, remote_tree, modified_files.second ); // BEHIND
889
890 // Filter both sets to files whose content actually differs between HEAD and remote.
891 // Without this, a file touched by a commit that has since been replaced with an
892 // identical-tree commit (e.g. a message-only amend) keeps an AHEAD marker even
893 // though its blob matches the remote's blob.
894 std::set<wxString> actuallyDifferent;
895 collect_paths( head_tree, remote_tree, actuallyDifferent );
896
897 auto filterToDifferent = [&]( std::set<wxString>& aSet )
898 {
899 for( auto it = aSet.begin(); it != aSet.end(); )
900 it = actuallyDifferent.count( *it ) ? std::next( it ) : aSet.erase( it );
901 };
902
903 filterToDifferent( modified_files.first );
904 filterToDifferent( modified_files.second );
905
906 return modified_files;
907}
908
909
910std::optional<KIGIT_AHEAD_BEHIND> KIGIT_COMMON::compareRefs( const git_reference* aBranch,
911 const git_reference* aBase ) const
912{
913 if( !m_repo || !aBranch || !aBase )
914 return std::nullopt;
915
916 git_object* branchCommit = nullptr;
917
918 if( git_reference_peel( &branchCommit, aBranch, GIT_OBJECT_COMMIT ) != GIT_OK )
919 return std::nullopt;
920
921 KIGIT::GitObjectPtr branchPtr( branchCommit );
922 git_object* baseCommit = nullptr;
923
924 if( git_reference_peel( &baseCommit, aBase, GIT_OBJECT_COMMIT ) != GIT_OK )
925 return std::nullopt;
926
927 KIGIT::GitObjectPtr basePtr( baseCommit );
928 KIGIT_AHEAD_BEHIND counts;
929
930 int result = git_graph_ahead_behind( &counts.ahead, &counts.behind, m_repo, git_object_id( branchCommit ),
931 git_object_id( baseCommit ) );
932
933 if( result != GIT_OK )
934 return std::nullopt;
935
936 return counts;
937}
938
939
941{
942 std::optional<KIGIT_UPSTREAM_STATUS> status = UpstreamStatus();
943
944 return status && status->HasLocalCommits();
945}
946
947
949{
950 return m_repo && git_repository_head_detached( m_repo ) == 1;
951}
952
953
955{
956 if( !m_repo )
957 return false;
958
959 git_config* config = nullptr;
960
961 if( git_repository_config( &config, m_repo ) != GIT_OK )
962 return false;
963
964 KIGIT::GitConfigPtr configPtr( config );
965 int rebase = 0;
966
967 return git_config_get_bool( &rebase, config, "pull.rebase" ) == GIT_OK && rebase;
968}
969
970
971std::optional<KIGIT_UPSTREAM_STATUS> KIGIT_COMMON::UpstreamStatus() const
972{
973 if( !m_repo || IsHeadDetached() )
974 return std::nullopt;
975
976 git_reference* head = nullptr;
977
978 if( git_repository_head( &head, m_repo ) != GIT_OK )
979 return std::nullopt;
980
981 KIGIT::GitReferencePtr headPtr( head );
982 git_reference* upstream = nullptr;
983 int result = git_branch_upstream( &upstream, head );
984
985 if( result == GIT_ENOTFOUND )
986 return KIGIT_UPSTREAM_STATUS();
987
988 if( result != GIT_OK )
989 return std::nullopt;
990
991 KIGIT::GitReferencePtr upstreamPtr( upstream );
992 std::optional<KIGIT_AHEAD_BEHIND> counts = compareRefs( head, upstream );
993
994 if( !counts )
995 return std::nullopt;
996
997 return KIGIT_UPSTREAM_STATUS{ true, *counts };
998}
999
1000
1001std::optional<size_t> KIGIT_COMMON::GetUnmergedCommitCount( const wxString& aBranch ) const
1002{
1003 if( !m_repo )
1004 return std::nullopt;
1005
1006 git_reference* branch = nullptr;
1007
1008 if( git_branch_lookup( &branch, m_repo, aBranch.utf8_string().c_str(), GIT_BRANCH_LOCAL ) != GIT_OK )
1009 return std::nullopt;
1010
1011 KIGIT::GitReferencePtr branchPtr( branch );
1012 git_reference* head = nullptr;
1013
1014 if( git_repository_head( &head, m_repo ) != GIT_OK )
1015 return std::nullopt;
1016
1017 KIGIT::GitReferencePtr headPtr( head );
1018 std::optional<KIGIT_AHEAD_BEHIND> counts = compareRefs( branch, head );
1019
1020 if( !counts )
1021 return std::nullopt;
1022
1023 return counts->ahead;
1024}
1025
1026
1027std::vector<wxString> KIGIT_COMMON::GetRecentCommitMessages( size_t aMax ) const
1028{
1029 std::vector<wxString> messages;
1030
1031 if( !m_repo )
1032 return messages;
1033
1034 git_revwalk* walker = nullptr;
1035
1036 if( git_revwalk_new( &walker, m_repo ) != GIT_OK )
1037 return messages;
1038
1039 KIGIT::GitRevWalkPtr walkerPtr( walker );
1040 git_revwalk_sorting( walker, GIT_SORT_TIME | GIT_SORT_TOPOLOGICAL );
1041
1042 if( git_revwalk_push_head( walker ) != GIT_OK )
1043 return messages;
1044
1045 std::set<wxString> seen;
1046 git_oid oid;
1047
1048 while( messages.size() < aMax && git_revwalk_next( &oid, walker ) == GIT_OK )
1049 {
1050 git_commit* commit = nullptr;
1051
1052 if( git_commit_lookup( &commit, m_repo, &oid ) != GIT_OK )
1053 continue;
1054
1055 KIGIT::GitCommitPtr commitPtr( commit );
1056 wxString message;
1057
1058 // git writes a merge's message, so it is no message the user would start from
1059 if( git_commit_parentcount( commit ) > 1 )
1060 continue;
1061
1062 if( const char* text = git_commit_message( commit ) )
1064
1065 message.Trim();
1066
1067 if( !message.IsEmpty() && seen.insert( message ).second )
1068 messages.push_back( message );
1069 }
1070
1071 return messages;
1072}
1073
1074
1075namespace
1076{
1077
1078// The id of the tree entry at aPath in aCommit's tree, or empty when there is none.
1079std::string treeEntryIdAt( git_commit* aCommit, const char* aPath )
1080{
1081 git_tree* tree = nullptr;
1082
1083 if( git_commit_tree( &tree, aCommit ) != GIT_OK )
1084 return {};
1085
1086 KIGIT::GitTreePtr treePtr( tree );
1087 git_tree_entry* entry = nullptr;
1088
1089 if( git_tree_entry_bypath( &entry, tree, aPath ) != GIT_OK )
1090 return {};
1091
1092 KIGIT::GitTreeEntryPtr entryPtr( entry );
1093
1094 return git_oid_tostr_s( git_tree_entry_id( entry ) );
1095}
1096
1097
1098// True when aCommit changed what sits at aPath, judged against its first parent. A folder works
1099// like a file, since a folder's entry id changes with anything under it.
1100bool commitTouchesPath( git_commit* aCommit, const std::string& aPath )
1101{
1102 std::string after = treeEntryIdAt( aCommit, aPath.c_str() );
1103 std::string before;
1104
1105 if( git_commit_parentcount( aCommit ) > 0 )
1106 {
1107 git_commit* parent = nullptr;
1108
1109 if( git_commit_parent( &parent, aCommit, 0 ) == GIT_OK )
1110 {
1111 KIGIT::GitCommitPtr parentPtr( parent );
1112 before = treeEntryIdAt( parent, aPath.c_str() );
1113 }
1114 }
1115
1116 return after != before;
1117}
1118
1119} // namespace
1120
1121
1122std::vector<KIGIT_COMMIT_INFO> KIGIT_COMMON::GetRecentCommits( size_t aMax, const KIGIT_HISTORY_FILTER& aFilter ) const
1123{
1124 std::vector<KIGIT_COMMIT_INFO> commits;
1126
1127 if( !m_repo || IsShuttingDown() || ( cancel && cancel->load() ) )
1128 return commits;
1129
1130 git_revwalk* walker = nullptr;
1131
1132 if( git_revwalk_new( &walker, m_repo ) != GIT_OK )
1133 return commits;
1134
1135 KIGIT::GitRevWalkPtr walkerPtr( walker );
1136
1137 // Time order, but a child always before its parent, so two tips made in the same second
1138 // still list in a fixed order.
1139 git_revwalk_sorting( walker, GIT_SORT_TIME | GIT_SORT_TOPOLOGICAL );
1140
1141 if( aFilter.branch.IsEmpty() )
1142 {
1143 git_revwalk_push_head( walker );
1144 git_revwalk_push_glob( walker, "refs/heads/*" );
1145 git_revwalk_push_glob( walker, "refs/remotes/*" );
1146 }
1147 else
1148 {
1149 // The short name as the Branches page lists it, local or remote, resolved as git would.
1150 git_reference* ref = nullptr;
1151
1152 if( git_reference_dwim( &ref, m_repo, aFilter.branch.utf8_string().c_str() ) != GIT_OK )
1153 return commits;
1154
1155 KIGIT::GitReferencePtr refPtr( ref );
1156 git_object* target = nullptr;
1157
1158 if( git_reference_peel( &target, ref, GIT_OBJECT_COMMIT ) != GIT_OK )
1159 return commits;
1160
1161 KIGIT::GitObjectPtr targetPtr( target );
1162 git_revwalk_push( walker, git_object_id( target ) );
1163 }
1164
1165 std::map<std::string, std::vector<wxString>> refNames = collectRefNames( m_repo );
1166 wxString search = aFilter.search.Lower();
1167 std::string path = aFilter.path.utf8_string();
1168 git_oid oid;
1169
1170 while( commits.size() < aMax && git_revwalk_next( &oid, walker ) == GIT_OK )
1171 {
1172 // A search without matches can walk the entire repository. Let a newer query or a
1173 // closing project release the action lock before that walk reaches its end.
1174 if( ( cancel && cancel->load() ) || IsShuttingDown() )
1175 break;
1176
1177 git_commit* commit = nullptr;
1178
1179 if( git_commit_lookup( &commit, m_repo, &oid ) != GIT_OK )
1180 continue;
1181
1182 KIGIT::GitCommitPtr commitPtr( commit );
1183
1184 if( !path.empty() && !commitTouchesPath( commit, path ) )
1185 continue;
1186
1188 info.hash = shortHashOf( &oid );
1189
1190 if( const char* summary = git_commit_summary( commit ) )
1191 info.summary = KIGIT::DecodeRepoText( summary );
1192
1193 if( const git_signature* author = git_commit_author( commit ) )
1194 {
1195 info.author = KIGIT::DecodeRepoText( author->name );
1196 info.email = KIGIT::DecodeRepoText( author->email );
1197 }
1198
1199 info.when = wxDateTime( static_cast<time_t>( git_commit_time( commit ) ) );
1200
1201 std::string fullHash = git_oid_tostr_s( &oid );
1202
1203 auto matches = [&]( const wxString& aText )
1204 {
1205 return aText.Lower().Contains( search );
1206 };
1207
1208 if( !search.IsEmpty() && !matches( info.summary ) && !matches( info.author ) && !matches( info.email )
1209 && !matches( fullHash ) )
1210 {
1211 continue;
1212 }
1213
1214 auto named = refNames.find( fullHash );
1215
1216 if( named != refNames.end() )
1217 info.refs = named->second;
1218
1219 commits.push_back( info );
1220 }
1221
1222 return commits;
1223}
1224
1225
1227{
1229
1230 if( !m_repo )
1231 return detail;
1232
1233 git_object* obj = nullptr;
1234
1235 if( git_revparse_single( &obj, m_repo, aHash.utf8_string().c_str() ) != GIT_OK )
1236 return detail;
1237
1238 KIGIT::GitObjectPtr objPtr( obj );
1239
1240 if( git_object_type( obj ) != GIT_OBJECT_COMMIT )
1241 return detail;
1242
1243 git_commit* commit = reinterpret_cast<git_commit*>( obj );
1244 const git_oid* oid = git_commit_id( commit );
1245
1246 detail.found = true;
1247 detail.hash = wxString::FromUTF8( git_oid_tostr_s( oid ) );
1248 detail.shortHash = shortHashOf( oid );
1249
1250 if( const char* message = git_commit_message( commit ) )
1252
1253 detail.message.Trim();
1254
1255 if( const git_signature* author = git_commit_author( commit ) )
1256 {
1257 detail.author = KIGIT::DecodeRepoText( author->name );
1258 detail.email = KIGIT::DecodeRepoText( author->email );
1259 }
1260
1261 detail.when = wxDateTime( static_cast<time_t>( git_commit_time( commit ) ) );
1262
1263 for( unsigned ii = 0; ii < git_commit_parentcount( commit ); ++ii )
1264 detail.parents.push_back( shortHashOf( git_commit_parent_id( commit, ii ) ) );
1265
1266 std::map<std::string, std::vector<wxString>> refNames = collectRefNames( m_repo );
1267 auto named = refNames.find( git_oid_tostr_s( oid ) );
1268
1269 if( named != refNames.end() )
1270 detail.refs = named->second;
1271
1272 git_tree* tree = nullptr;
1273
1274 if( git_commit_tree( &tree, commit ) != GIT_OK )
1275 return detail;
1276
1277 KIGIT::GitTreePtr treePtr( tree );
1278
1279 // A root commit diffs against the empty tree, so its files all count as added.
1280 KIGIT::GitTreePtr parentTree;
1281
1282 if( git_commit_parentcount( commit ) > 0 )
1283 {
1284 git_commit* parent = nullptr;
1285
1286 if( git_commit_parent( &parent, commit, 0 ) == GIT_OK )
1287 {
1288 KIGIT::GitCommitPtr parentPtr( parent );
1289 git_tree* raw = nullptr;
1290
1291 if( git_commit_tree( &raw, parent ) == GIT_OK )
1292 parentTree.reset( raw );
1293 }
1294 }
1295
1296 git_diff* diff = nullptr;
1297
1298 if( git_diff_tree_to_tree( &diff, m_repo, parentTree.get(), tree, nullptr ) != GIT_OK )
1299 return detail;
1300
1301 KIGIT::GitDiffPtr diffPtr( diff );
1302
1303 git_diff_find_options findOpts;
1304 git_diff_find_options_init( &findOpts, GIT_DIFF_FIND_OPTIONS_VERSION );
1305 findOpts.flags = GIT_DIFF_FIND_RENAMES | GIT_DIFF_FIND_COPIES;
1306 git_diff_find_similar( diff, &findOpts );
1307
1308 for( size_t ii = 0; ii < git_diff_num_deltas( diff ); ++ii )
1309 {
1310 git_patch* patch = nullptr;
1311
1312 if( git_patch_from_diff( &patch, diff, ii ) != GIT_OK )
1313 continue;
1314
1315 KIGIT::GitPatchPtr patchPtr( patch );
1316 const git_diff_delta* delta = git_patch_get_delta( patch );
1317
1318 KIGIT_COMMIT_FILE file;
1319 file.path = wxString::FromUTF8( delta->new_file.path ? delta->new_file.path : delta->old_file.path );
1320 file.status = deltaStatus( delta->status );
1321 file.binary = ( delta->flags & GIT_DIFF_FLAG_BINARY ) != 0;
1322
1323 if( delta->status == GIT_DELTA_RENAMED || delta->status == GIT_DELTA_COPIED )
1324 file.oldPath = wxString::FromUTF8( delta->old_file.path );
1325
1326 size_t added = 0;
1327 size_t removed = 0;
1328
1329 if( git_patch_line_stats( nullptr, &added, &removed, patch ) == GIT_OK )
1330 {
1331 file.added = static_cast<int>( added );
1332 file.removed = static_cast<int>( removed );
1333 }
1334
1335 detail.added += file.added;
1336 detail.removed += file.removed;
1337 detail.files.push_back( file );
1338 }
1339
1340 return detail;
1341}
1342
1343
1344namespace
1345{
1346struct STASH_COLLECT
1347{
1348 git_repository* repo;
1349 std::vector<KIGIT_STASH_INFO>* out;
1350};
1351
1352
1353int collectStash( size_t aIndex, const char* aMessage, const git_oid* aStashId, void* aPayload )
1354{
1355 STASH_COLLECT* ctx = static_cast<STASH_COLLECT*>( aPayload );
1356
1358 info.index = aIndex;
1359 info.message = KIGIT::DecodeRepoText( aMessage );
1360
1361 char hash[GIT_OID_HEXSZ + 1] = { 0 };
1362 git_oid_tostr( hash, sizeof( hash ), aStashId );
1363 info.id = wxString::FromUTF8( hash );
1364
1365 git_commit* commit = nullptr;
1366
1367 if( git_commit_lookup( &commit, ctx->repo, aStashId ) == GIT_OK )
1368 {
1369 KIGIT::GitCommitPtr commitPtr( commit );
1370 info.when = wxDateTime( static_cast<time_t>( git_commit_time( commit ) ) );
1371 }
1372
1373 ctx->out->push_back( info );
1374 return 0;
1375}
1376} // namespace
1377
1378
1379std::vector<KIGIT_STASH_INFO> KIGIT_COMMON::GetStashes() const
1380{
1381 std::vector<KIGIT_STASH_INFO> stashes;
1382
1383 if( !m_repo )
1384 return stashes;
1385
1386 STASH_COLLECT ctx{ m_repo, &stashes };
1387 git_stash_foreach( m_repo, collectStash, &ctx );
1388
1389 return stashes;
1390}
1391
1392
1393std::vector<KIGIT_TAG_INFO> KIGIT_COMMON::GetTags() const
1394{
1395 std::vector<KIGIT_TAG_INFO> tags;
1396
1397 if( !m_repo )
1398 return tags;
1399
1400 git_strarray tagNames = { nullptr, 0 };
1401
1402 if( git_tag_list( &tagNames, m_repo ) != GIT_OK )
1403 return tags;
1404
1405 KIGIT::GitStrArrayPtr tagNamesPtr( &tagNames );
1406
1407 for( size_t i = 0; i < tagNames.count; ++i )
1408 {
1409 wxString tagName = KIGIT::DecodeRepoText( tagNames.strings[i] );
1412 info.name = tagName;
1413
1414 // A tag on a tree or blob has no commit to show, but it is still a tag.
1415 if( detail.found )
1416 {
1417 info.hash = detail.hash;
1418 info.summary = detail.message.BeforeFirst( '\n' );
1419 info.when = detail.when;
1420 }
1421
1422 tags.push_back( info );
1423 }
1424
1425 // Newest first, as the History page lists commits. A tag with no date goes last.
1426 std::stable_sort( tags.begin(), tags.end(),
1427 []( const KIGIT_TAG_INFO& a, const KIGIT_TAG_INFO& b )
1428 {
1429 if( !a.when.IsValid() || !b.when.IsValid() )
1430 return a.when.IsValid();
1431
1432 return a.when > b.when;
1433 } );
1434
1435 return tags;
1436}
1437
1438
1439std::vector<std::pair<wxString, wxString>> KIGIT_COMMON::GetRemotes() const
1440{
1441 std::vector<std::pair<wxString, wxString>> remotes;
1442
1443 if( !m_repo )
1444 return remotes;
1445
1446 git_strarray names = { nullptr, 0 };
1447
1448 if( git_remote_list( &names, m_repo ) != GIT_OK )
1449 return remotes;
1450
1451 KIGIT::GitStrArrayPtr namesPtr( &names );
1452
1453 for( size_t i = 0; i < names.count; ++i )
1454 {
1455 wxString name = wxString::FromUTF8( names.strings[i] );
1456 git_remote* remote = nullptr;
1457
1458 if( git_remote_lookup( &remote, m_repo, names.strings[i] ) != GIT_OK )
1459 continue;
1460
1461 KIGIT::GitRemotePtr remotePtr( remote );
1462
1463 const char* url = git_remote_url( remote );
1464 remotes.emplace_back( name, url ? KIGIT::StripEmbeddedUserinfo( wxString::FromUTF8( url ) ) : wxString() );
1465 }
1466
1467 return remotes;
1468}
1469
1470
1472{
1473 return m_repo && git_repository_head_unborn( m_repo ) == 1;
1474}
1475
1476
1477bool KIGIT_COMMON::StartUnbornBranch( const wxString& aName )
1478{
1479 // Pointing HEAD at a name does not check it the way creating a branch does.
1480 if( !m_repo || !IsHeadUnborn() || !KIGIT::BranchNameError( aName ).IsEmpty() )
1481 return false;
1482
1483 wxString ref = wxS( "refs/heads/" ) + aName;
1484
1485 return git_repository_set_head( m_repo, ref.utf8_string().c_str() ) == GIT_OK;
1486}
1487
1488
1489bool KIGIT_COMMON::CreateBranch( const wxString& aName, const wxString& aFrom )
1490{
1491 if( !m_repo || !KIGIT::BranchNameError( aName ).IsEmpty() )
1492 return false;
1493
1494 return GetGitBackend()->CreateBranch( m_repo, aName, aFrom ) == 0;
1495}
1496
1497
1498bool KIGIT_COMMON::DeleteBranch( const wxString& aName )
1499{
1500 return GetGitBackend()->DeleteBranch( m_repo, aName );
1501}
1502
1503
1504bool KIGIT_COMMON::StashSave( const wxString& aMessage )
1505{
1506 return GetGitBackend()->StashSave( m_repo, aMessage );
1507}
1508
1509
1510bool KIGIT_COMMON::StashApply( size_t aIndex )
1511{
1512 return GetGitBackend()->StashApply( m_repo, aIndex );
1513}
1514
1515
1516bool KIGIT_COMMON::StashPop( size_t aIndex )
1517{
1518 return GetGitBackend()->StashPop( m_repo, aIndex );
1519}
1520
1521
1522bool KIGIT_COMMON::StashDrop( size_t aIndex )
1523{
1524 return GetGitBackend()->StashDrop( m_repo, aIndex );
1525}
1526
1527
1528bool KIGIT_COMMON::CreateTag( const wxString& aName, const wxString& aMessage )
1529{
1530 return GetGitBackend()->CreateTag( m_repo, aName, aMessage );
1531}
1532
1533
1534KIGIT_TAG_DETAIL KIGIT_COMMON::GetTagDetail( const wxString& aName ) const
1535{
1537
1538 if( !m_repo )
1539 return detail;
1540
1541 git_object* obj = nullptr;
1542 wxString spec = wxS( "refs/tags/" ) + aName;
1543
1544 if( git_revparse_single( &obj, m_repo, spec.utf8_string().c_str() ) != GIT_OK )
1545 return detail;
1546
1547 KIGIT::GitObjectPtr objPtr( obj );
1548
1549 // An annotated tag is its own object on the way to the commit, with a message and a tagger
1550 // of its own.
1551 git_object* peeled = nullptr;
1552
1553 if( git_object_peel( &peeled, obj, GIT_OBJECT_COMMIT ) != GIT_OK )
1554 return detail;
1555
1556 KIGIT::GitObjectPtr peeledPtr( peeled );
1557 git_commit* commit = reinterpret_cast<git_commit*>( peeled );
1558
1559 detail.found = true;
1560 detail.name = aName;
1561 detail.hash = shortHashOf( git_commit_id( commit ) );
1562
1563 const char* message = nullptr;
1564 const git_signature* who = nullptr;
1565
1566 if( git_object_type( obj ) == GIT_OBJECT_TAG )
1567 {
1568 git_tag* tag = reinterpret_cast<git_tag*>( obj );
1569 message = git_tag_message( tag );
1570 who = git_tag_tagger( tag );
1571 }
1572
1573 if( !message )
1574 message = git_commit_message( commit );
1575
1576 bool annotated = who != nullptr;
1577
1578 if( !who )
1579 who = git_commit_author( commit );
1580
1581 if( message )
1583
1584 detail.message.Trim();
1585
1586 if( who )
1587 {
1588 detail.author = KIGIT::DecodeRepoText( who->name );
1589 detail.email = KIGIT::DecodeRepoText( who->email );
1590 detail.when = wxDateTime( static_cast<time_t>( annotated ? who->when.time : git_commit_time( commit ) ) );
1591 }
1592
1593 return detail;
1594}
1595
1596
1597bool KIGIT_COMMON::DeleteTag( const wxString& aName )
1598{
1599 return GetGitBackend()->DeleteTag( m_repo, aName );
1600}
1601
1602
1603bool KIGIT_COMMON::CheckoutTag( const wxString& aName )
1604{
1605 return GetGitBackend()->CheckoutTag( m_repo, aName );
1606}
1607
1608
1609bool KIGIT_COMMON::AddRemote( const wxString& aName, const wxString& aUrl )
1610{
1611 return GetGitBackend()->AddRemote( m_repo, aName, aUrl );
1612}
1613
1614
1615bool KIGIT_COMMON::SetRemoteUrl( const wxString& aName, const wxString& aUrl )
1616{
1617 return GetGitBackend()->SetRemoteUrl( m_repo, aName, aUrl );
1618}
1619
1620
1621bool KIGIT_COMMON::RemoveRemote( const wxString& aName )
1622{
1623 return GetGitBackend()->RemoveRemote( m_repo, aName );
1624}
1625
1626
1627bool KIGIT_COMMON::SetUserConfig( const wxString& aName, const wxString& aEmail )
1628{
1629 return GetGitBackend()->SetUserConfig( m_repo, aName, aEmail );
1630}
1631
1632
1634{
1635 return GetGitBackend()->RestoreVersion( *this, aCommitHash, aError );
1636}
1637
1638
1639bool KIGIT_COMMON::DiscardChanges( const std::vector<wxString>& aPaths, wxString& aError )
1640{
1641 return GetGitBackend()->DiscardChanges( m_repo, aPaths, aError );
1642}
1643
1644
1645bool KIGIT_COMMON::IsPathInHead( const wxString& aPath )
1646{
1647 return GetGitBackend()->IsPathInHead( m_repo, aPath );
1648}
1649
1650
1651bool KIGIT_COMMON::IsPathConflicted( const wxString& aPath ) const
1652{
1653 if( !m_repo || aPath.IsEmpty() )
1654 return false;
1655
1656 git_index* index = nullptr;
1657
1658 if( git_repository_index( &index, m_repo ) != GIT_OK )
1659 return false;
1660
1661 KIGIT::GitIndexPtr indexPtr( index );
1662
1663 const git_index_entry* ancestor = nullptr;
1664 const git_index_entry* ours = nullptr;
1665 const git_index_entry* theirs = nullptr;
1666
1667 return git_index_conflict_get( &ancestor, &ours, &theirs, index, aPath.utf8_string().c_str() ) == GIT_OK;
1668}
1669
1670
1672{
1673 return m_repo && git_repository_state( m_repo ) != GIT_REPOSITORY_STATE_NONE;
1674}
1675
1676
1678{
1679 if( !m_repo )
1680 return GitOperation::None;
1681
1682 switch( git_repository_state( m_repo ) )
1683 {
1684 case GIT_REPOSITORY_STATE_NONE: return GitOperation::None;
1685 case GIT_REPOSITORY_STATE_MERGE: return GitOperation::Merge;
1686 case GIT_REPOSITORY_STATE_REBASE:
1687 case GIT_REPOSITORY_STATE_REBASE_INTERACTIVE:
1688 case GIT_REPOSITORY_STATE_REBASE_MERGE:
1689 case GIT_REPOSITORY_STATE_APPLY_MAILBOX_OR_REBASE: return GitOperation::Rebase;
1690 case GIT_REPOSITORY_STATE_CHERRYPICK:
1691 case GIT_REPOSITORY_STATE_CHERRYPICK_SEQUENCE: return GitOperation::CherryPick;
1692 case GIT_REPOSITORY_STATE_REVERT:
1693 case GIT_REPOSITORY_STATE_REVERT_SEQUENCE: return GitOperation::Revert;
1694 default: return GitOperation::Other;
1695 }
1696}
1697
1698
1699bool KIGIT_COMMON::AbandonOperation( wxString& aError )
1700{
1701 return GetGitBackend()->AbandonOperation( m_repo, aError );
1702}
1703
1704
1705bool KIGIT_COMMON::GetMergeConflicts( const wxString& aStageDir, wxString& aHeadOid, wxString& aTheirsOid,
1706 std::vector<KIGIT_CONFLICT_SIDES>& aConflicts, wxString& aError )
1707{
1708 return GetGitBackend()->GetMergeConflicts( m_repo, aStageDir, aHeadOid, aTheirsOid, aConflicts, aError );
1709}
1710
1711
1712MergeCommitResult KIGIT_COMMON::CreateMergedCommit( const wxString& aExpectedHeadOid, const wxString& aTheirsOid,
1713 const std::vector<std::pair<wxString, wxString>>& aResolvedFiles,
1714 KIGIT_ERROR_MESSAGE& aError )
1715{
1716 return GetGitBackend()->CreateMergedCommit( m_repo, aExpectedHeadOid, aTheirsOid, aResolvedFiles, aError );
1717}
1718
1719
1720void KIGIT_COMMON::AddRefreshListener( void* aOwner, std::function<void()> aCallback )
1721{
1722 m_refreshListeners.emplace_back( aOwner, std::move( aCallback ) );
1723}
1724
1725
1727{
1728 std::erase_if( m_refreshListeners,
1729 [aOwner]( const auto& aEntry )
1730 {
1731 return aEntry.first == aOwner;
1732 } );
1733}
1734
1735
1737{
1738 // Copy first: a listener could add or remove one while it runs.
1739 std::vector<std::pair<void*, std::function<void()>>> listeners = m_refreshListeners;
1740
1741 for( const auto& [owner, callback] : listeners )
1742 {
1743 // An earlier listener in this round can have removed this one.
1744 bool registered = std::any_of( m_refreshListeners.begin(), m_refreshListeners.end(),
1745 [target = owner]( const auto& aEntry )
1746 {
1747 return aEntry.first == target;
1748 } );
1749
1750 if( registered )
1751 callback();
1752 }
1753}
1754
1755
1757{
1758 if( !m_repo )
1759 return false;
1760
1761
1762 // Prefer the upstream remote configured for the current branch. Fall back to
1763 // "origin" and then to any remote that exposes a fetch URL so that repos
1764 // cloned with non-default remote names also enable push/pull operations.
1765 auto checkRemote =
1766 [this]( const char* aName ) -> bool
1767 {
1768 git_remote* remote = nullptr;
1769
1770 if( git_remote_lookup( &remote, m_repo, aName ) != GIT_OK )
1771 return false;
1772
1773 KIGIT::GitRemotePtr remotePtr( remote );
1774
1775 const char* fetch_url = git_remote_url( remote );
1776 const char* push_url = git_remote_pushurl( remote );
1777
1778 // libgit2 defaults to the fetch URL for pushing when no push URL is set
1779 if( !push_url )
1780 push_url = fetch_url;
1781
1782 return fetch_url && push_url;
1783 };
1784
1785 std::string preferred = GetRemoteNameOrDefault().utf8_string();
1786
1787 if( checkRemote( preferred.c_str() ) )
1788 return true;
1789
1790 if( preferred != "origin" && checkRemote( "origin" ) )
1791 return true;
1792
1793 git_strarray remotes = { nullptr, 0 };
1794
1795 if( git_remote_list( &remotes, m_repo ) != GIT_OK )
1796 {
1797 wxLogTrace( traceGit, "Failed to enumerate remotes for haspushpull" );
1798 return false;
1799 }
1800
1801 KIGIT::GitStrArrayPtr remotesPtr( &remotes );
1802
1803 for( size_t ii = 0; ii < remotes.count; ++ii )
1804 {
1805 if( checkRemote( remotes.strings[ii] ) )
1806 return true;
1807 }
1808
1809 return false;
1810}
1811
1812
1814{
1815 wxString remoteName = GetRemotename();
1816
1817 if( remoteName.IsEmpty() )
1818 remoteName = wxS( "origin" );
1819
1820 return remoteName;
1821}
1822
1823
1824wxString KIGIT_COMMON::GetPushUrl( const wxString& aRemoteName ) const
1825{
1826 git_remote* remote = nullptr;
1827
1828 if( !m_repo || git_remote_lookup( &remote, m_repo, aRemoteName.utf8_string().c_str() ) != GIT_OK )
1829 return wxEmptyString;
1830
1831 KIGIT::GitRemotePtr remotePtr( remote );
1832 const char* url = git_remote_pushurl( remote ) ? git_remote_pushurl( remote ) : git_remote_url( remote );
1833
1834 return url ? wxString::FromUTF8( url ) : wxString();
1835}
1836
1837
1839{
1840 wxString retval;
1841 git_strarray remotes = { nullptr, 0 };
1842
1843 if( git_remote_list( &remotes, m_repo ) == GIT_OK )
1844 {
1845 // No upstream tracking branch. Prefer "origin" when present, otherwise pick the
1846 // single configured remote. Returning empty for ambiguous (multiple) remotes
1847 // tells callers to fall back to whatever default they want.
1848 if( remotes.count == 1 )
1849 {
1850 retval = remotes.strings[0];
1851 }
1852 else
1853 {
1854 for( size_t ii = 0; ii < remotes.count; ++ii )
1855 {
1856 if( strcmp( remotes.strings[ii], "origin" ) == 0 )
1857 {
1858 retval = remotes.strings[ii];
1859 break;
1860 }
1861 }
1862 }
1863
1864 git_strarray_dispose( &remotes );
1865 }
1866 else
1867 {
1868 wxLogTrace( traceGit, "Failed to list remotes: %s", KIGIT_COMMON::GetLastGitError() );
1869
1870 // If we can't get the remote name from the upstream branch or the list of remotes,
1871 // just return the default remote name
1872
1873 git_remote* remote = nullptr;
1874
1875 if( git_remote_lookup( &remote, m_repo, "origin" ) == GIT_OK )
1876 {
1877 retval = git_remote_name( remote );
1878 git_remote_free( remote );
1879 }
1880 else
1881 {
1882 wxLogTrace( traceGit, "Failed to get remote name from default remote: %s",
1884 }
1885 }
1886
1887 return retval;
1888}
1889
1890
1892{
1893 if( !m_repo )
1894 return wxEmptyString;
1895
1896
1897 wxString retval;
1898 git_reference* head = nullptr;
1899 git_reference* upstream = nullptr;
1900
1901 // An unborn HEAD has no branch to track, but the remote still exists
1902 if( git_repository_head( &head, m_repo ) != GIT_OK )
1903 {
1904 wxLogTrace( traceGit, "Failed to get remote name: %s", KIGIT_COMMON::GetLastGitError() );
1906 }
1907
1908 KIGIT::GitReferencePtr headPtr( head );
1909
1910 if( git_branch_upstream( &upstream, head ) != GIT_OK )
1911 {
1912 wxLogTrace( traceGit, "Failed to get upstream branch: %s", KIGIT_COMMON::GetLastGitError() );
1914 }
1915
1916 KIGIT::GitReferencePtr upstreamPtr( upstream );
1917 git_buf remote_name = GIT_BUF_INIT_CONST( nullptr, 0 );
1918
1919 if( git_branch_remote_name( &remote_name, m_repo, git_reference_name( upstream ) ) == GIT_OK )
1920 {
1921 retval = remote_name.ptr;
1922 git_buf_dispose( &remote_name );
1923 }
1924 else
1925 {
1926 wxLogTrace( traceGit,
1927 "Failed to get remote name from upstream branch: %s",
1929 }
1930
1931 return retval;
1932}
1933
1934
1935void KIGIT_COMMON::SetSSHKey( const wxString& aKey )
1936{
1937 // GetNextPublicKey reads an empty result as the end of the list, so an empty key at the
1938 // front would hide every key behind it.
1939 if( aKey.IsEmpty() )
1940 return;
1941
1942 std::lock_guard<std::mutex> lock( m_credentialsMutex );
1943 m_projectSSHKey = aKey;
1945}
1946
1947
1949{
1950 std::lock_guard<std::mutex> lock( m_credentialsMutex );
1951
1952 if( !m_projectSSHKey.IsEmpty() )
1953 return m_projectSSHKey;
1954
1955 return m_publicKeys.empty() ? wxString() : m_publicKeys.front();
1956}
1957
1958
1960{
1961 std::lock_guard<std::mutex> lock( m_credentialsMutex );
1962
1964 return m_projectSSHKey;
1965
1966 for( const wxString& key : m_publicKeys )
1967 {
1968 if( KIGIT::IsOfferableSSHKey( key ) )
1969 return key;
1970 }
1971
1972 return wxEmptyString;
1973}
1974
1975
1977{
1978 std::lock_guard<std::mutex> lock( m_credentialsMutex );
1979 return m_acceptedSSHKey;
1980}
1981
1982
1983void KIGIT_COMMON::SetAcceptedSSHKey( const wxString& aKey )
1984{
1985 std::lock_guard<std::mutex> lock( m_credentialsMutex );
1986 m_acceptedSSHKey = aKey;
1987}
1988
1989
1991{
1992 std::lock_guard<std::mutex> lock( m_credentialsMutex );
1993 return { m_remote, m_connType, m_username };
1994}
1995
1996
1998{
1999 std::lock_guard<std::mutex> lock( m_credentialsMutex );
2000
2001 if( m_remote != aFor.remote || m_connType != aFor.connType || m_username != aFor.username )
2002 return false;
2003
2004 m_connType = aEntered.connType;
2005
2006 if( aEntered.username )
2007 m_username = *aEntered.username;
2008
2009 m_password = aEntered.password;
2010 m_secretFetched = true;
2011
2012 // As SetSSHKey, which also refuses an empty key
2013 if( !aEntered.sshKey.IsEmpty() )
2014 {
2015 m_projectSSHKey = aEntered.sshKey;
2017 }
2018
2019 m_nextPublicKey = 0;
2020 return true;
2021}
2022
2023
2024int KIGIT_COMMON::SSHPortFor( const wxString& aHost ) const
2025{
2026 std::lock_guard<std::mutex> lock( m_credentialsMutex );
2027
2028 if( m_port < 0 || !m_hostname.IsSameAs( aHost, false ) )
2029 return -1;
2030
2031 return m_port == 0 ? 22 : m_port;
2032}
2033
2034
2035std::unique_lock<std::mutex> KIGIT_COMMON::TryLockActionFor( std::chrono::milliseconds aWait )
2036{
2037 const auto deadline = std::chrono::steady_clock::now() + aWait;
2038 std::unique_lock<std::mutex> lock( m_gitActionMutex, std::defer_lock );
2039
2040 // Not a timed mutex, so poll. A status read lets go within a few of these
2041 while( !lock.try_lock() && std::chrono::steady_clock::now() < deadline )
2042 std::this_thread::sleep_for( std::chrono::milliseconds( 20 ) );
2043
2044 return lock;
2045}
2046
2047
2049{
2050 m_publicKeys.clear();
2051 m_nextPublicKey = 0;
2052
2054 m_publicKeys.push_back( m_projectSSHKey );
2055 else if( !m_projectSSHKey.IsEmpty() )
2056 wxLogTrace( traceGit, "Not offering project SSH key %s, it or its .pub is missing", m_projectSSHKey );
2057
2058 // A refused key still counts toward the server's limit on attempts, and the right one can come too late.
2059 // Only a key still found for the host moves up, so one dropped from the ssh config stays dropped
2060 wxString remembered = KIGIT::RememberedSSHKey( m_remote );
2061
2062 bool current = std::any_of( m_discoveredKeys.begin(), m_discoveredKeys.end(),
2063 [&]( const wxString& aKey )
2064 {
2065 return KIGIT::IsSameSSHKey( aKey, remembered );
2066 } );
2067
2068 if( !current || KIGIT::IsSameSSHKey( remembered, m_projectSSHKey ) )
2069 remembered.clear();
2070 else
2071 m_publicKeys.push_back( remembered );
2072
2073 for( const wxString& key : m_discoveredKeys )
2074 {
2075 if( !KIGIT::IsSameSSHKey( key, m_projectSSHKey ) && !KIGIT::IsSameSSHKey( key, remembered ) )
2076 m_publicKeys.push_back( key );
2077 }
2078}
2079
2080
2082{
2083 std::lock_guard<std::mutex> lock( m_credentialsMutex );
2085}
2086
2087
2089{
2090 // libgit2 asks for nothing more once a credential works, so the last key offered is the one that did
2091 if( aAttempt.connType != GIT_CONN_TYPE::GIT_CONN_SSH || aAttempt.keysTried.empty() )
2092 return;
2093
2094 KIGIT::RememberSSHKey( GetRemote(), aAttempt.keysTried.back() );
2095}
2096
2097
2099{
2100 std::lock_guard<std::mutex> lock( m_credentialsMutex );
2101
2102 // A key deleted since discovery would end the whole attempt instead of failing over to the next one
2103 while( m_nextPublicKey < static_cast<int>( m_publicKeys.size() ) )
2104 {
2105 wxString key = m_publicKeys[m_nextPublicKey++];
2106
2107 if( KIGIT::IsOfferableSSHKey( key ) )
2108 return key;
2109 }
2110
2111 return wxEmptyString;
2112}
2113
2114
2116{
2117 if( !m_repo )
2118 return wxEmptyString;
2119
2120 // Prefer the working directory (the user-visible project root). Fall back to
2121 // git_repository_path (the .git directory) only for bare repositories.
2122 if( const char* workdir = git_repository_workdir( m_repo ) )
2123 return wxString::FromUTF8( workdir );
2124
2125 if( const char* path = git_repository_path( m_repo ) )
2126 return wxString::FromUTF8( path );
2127
2128 return wxEmptyString;
2129}
2130
2131
2133{
2134 // Deadlocks if the credentials lock is already held. SyncRemoteUrl releases it
2135 // first for that reason.
2136 std::lock_guard<std::mutex> lock( m_credentialsMutex );
2137
2142}
2143
2144
2146{
2147 if( !m_repo )
2148 return;
2149
2150
2151 // We want to get the current branch's upstream url as well as the stored password
2152 // if one exists given the url and username.
2153
2154 wxString remote_name = GetRemotename();
2155 wxString url;
2156 git_remote* remote = nullptr;
2157
2158 if( git_remote_lookup( &remote, m_repo, remote_name.ToStdString().c_str() ) == GIT_OK )
2159 {
2160 // UTF-8 as the transfers read it, or a non-ASCII path would look changed on every fetch
2161 if( const char* remoteUrl = git_remote_url( remote ) )
2162 url = wxString::FromUTF8( remoteUrl );
2163
2164 git_remote_free( remote );
2165 }
2166
2167 SyncRemoteUrl( url );
2168}
2169
2170
2171void KIGIT_COMMON::SyncRemoteUrl( const wxString& aRawUrl )
2172{
2173 REMOTE_URL parsed = ParseRemoteURL( aRawUrl );
2174 bool keysStale = false;
2175
2176 {
2177 // The authentication callback reads these on a worker thread, so update them together
2178 std::lock_guard<std::mutex> lock( m_credentialsMutex );
2179
2180 // HTTPS drops the username from the stored URL, so it is compared on its own
2181 if( parsed.url != m_remote || parsed.username != m_urlUsername )
2182 {
2183 m_remote = parsed.url;
2184 m_urlUsername = parsed.username;
2185 m_connType = parsed.connType;
2186 m_hostname = parsed.hostname;
2187 m_port = parsed.port;
2188 m_username = parsed.username;
2189 m_password = parsed.password;
2190 m_secretFetched = !m_password.IsEmpty();
2191 m_acceptedSSHKey.clear();
2192
2193 // Another address on the same host can have a different key remembered for it
2195 }
2196
2197 // SetRemote can move the host without gathering keys, so compare against the gathered list
2198 keysStale = m_hostname != m_publicKeysHost;
2199 }
2200
2201 if( keysStale )
2203}
2204
2205
2206void KIGIT_COMMON::FollowRewrittenUrl( const wxString& aRawUrl )
2207{
2208 wxString username;
2209 wxString password;
2210 bool secretFetched;
2211
2212 {
2213 std::lock_guard<std::mutex> lock( m_credentialsMutex );
2214 username = m_username;
2215 password = m_password;
2216 secretFetched = m_secretFetched;
2217 }
2218
2219 SyncRemoteUrl( aRawUrl );
2220
2221 std::lock_guard<std::mutex> lock( m_credentialsMutex );
2222 m_username = username;
2223 m_password = password;
2224 m_secretFetched = secretFetched;
2225}
2226
2227
2229{
2230 std::lock_guard<std::mutex> lock( m_credentialsMutex );
2231 return m_connType;
2232}
2233
2234
2236{
2237 std::lock_guard<std::mutex> lock( m_credentialsMutex );
2238 m_connType = aConnType;
2239}
2240
2241
2242// Index of the '@' ending the userinfo of proto://user:password@host/path, or npos. The last
2243// one, since the first would split inside a password that contains an '@'.
2244static size_t findUserinfoAt( const wxString& aUrl )
2245{
2246 size_t protoSep = aUrl.find( "://" );
2247
2248 if( protoSep == wxString::npos )
2249 return wxString::npos;
2250
2251 size_t hostStart = protoSep + 3;
2252 size_t pathStart = aUrl.find_first_of( "/?#", hostStart );
2253 size_t searchEnd = ( pathStart == wxString::npos ) ? aUrl.length() : pathStart;
2254
2255 if( searchEnd <= hostStart )
2256 return wxString::npos;
2257
2258 size_t at = aUrl.rfind( '@', searchEnd - 1 );
2259
2260 return ( at != wxString::npos && at >= hostStart ) ? at : wxString::npos;
2261}
2262
2263
2265{
2266 const git_error* error = git_error_last();
2267
2268 if( error == nullptr )
2269 return wxString( "No error" );
2270
2271 // libgit2 quotes config lines and URLs verbatim, passwords included
2272 return KIGIT::StripEmbeddedUserinfo( wxString::FromUTF8( error->message ? error->message : "" ) );
2273}
2274
2275
2277{
2279 info.code = aCode;
2280
2281 // libgit2 before 1.8 answers null rather than "no error"
2282 if( const git_error* error = git_error_last() )
2283 {
2284 info.klass = error->klass;
2285 info.message = wxString::FromUTF8( error->message ? error->message : "" );
2286 }
2287
2288 return info;
2289}
2290
2291
2292// libgit2's git_str_decode_percent when the whole result is UTF-8; otherwise the component stays as written
2293static wxString decodePercent( const wxString& aText )
2294{
2295 const std::string text = aText.utf8_string();
2296 std::string decoded;
2297
2298 for( size_t ii = 0; ii < text.size(); ++ii )
2299 {
2300 if( text[ii] == '%' && ii + 2 < text.size() && isxdigit( (unsigned char) text[ii + 1] )
2301 && isxdigit( (unsigned char) text[ii + 2] ) )
2302 {
2303 decoded += static_cast<char>( std::stoi( text.substr( ii + 1, 2 ), nullptr, 16 ) );
2304 ii += 2;
2305 }
2306 else
2307 {
2308 decoded += text[ii];
2309 }
2310 }
2311
2312 wxString result = wxString::FromUTF8( decoded );
2313
2314 // wxString cannot hold bytes that are not UTF-8, so such text stays as written
2315 return result.IsEmpty() && !decoded.empty() ? aText : result;
2316}
2317
2318
2319// 0 when the address names no port, -1 when it names one that cannot be used
2320static int parsePort( const wxString& aPort )
2321{
2322 long port = 0;
2323
2324 if( aPort.IsEmpty() )
2325 return 0;
2326
2327 if( !aPort.ToLong( &port ) || port <= 0 || port > 65535 )
2328 return -1;
2329
2330 return static_cast<int>( port );
2331}
2332
2333
2334static bool isScpIpv6( const wxString& aText, size_t aBracket )
2335{
2336 size_t colons = 0;
2337
2338 for( size_t ii = aBracket + 1; ii < aText.length(); ++ii )
2339 {
2340 wxUniChar c = aText[ii];
2341
2342 if( c == ':' )
2343 colons++;
2344
2345 if( c == ']' )
2346 return colons > 1;
2347
2348 if( c != ':' && !wxIsxdigit( c ) )
2349 return false;
2350 }
2351
2352 return false;
2353}
2354
2355
2356static bool scpHasUser( const wxString& aText, size_t aStart )
2357{
2358 for( size_t ii = aStart; ii < aText.length(); ++ii )
2359 {
2360 if( aText[ii] == '@' )
2361 return true;
2362
2363 if( aText[ii] == ':' )
2364 return false;
2365 }
2366
2367 return false;
2368}
2369
2370
2371// libgit2's git_net_url_parse_scp, state for state, so the host key check binds the host and port it dials
2372static bool parseScpAddress( const wxString& aURL, wxString& aUser, wxString& aHost, wxString& aPort )
2373{
2374 enum
2375 {
2376 NONE,
2377 USER,
2378 HOST_START,
2379 HOST,
2380 HOST_END,
2381 IPV6,
2382 IPV6_END,
2383 PORT_START,
2384 PORT,
2385 PORT_END,
2386 PATH_START
2387 } state = NONE;
2388
2389 size_t user = 0, userLen = 0, host = 0, hostLen = 0, port = 0, portLen = 0;
2390 int bracket = 0;
2391 bool havePath = false;
2392
2393 for( size_t ii = 0; ii < aURL.length() && !havePath; ++ii )
2394 {
2395 wxUniChar c = aURL[ii];
2396
2397 switch( state )
2398 {
2399 case NONE:
2400 if( c == '@' || c == ':' )
2401 return false;
2402
2403 if( c == '[' )
2404 {
2405 if( isScpIpv6( aURL, ii ) )
2406 {
2407 state = IPV6;
2408 host = ii;
2409 }
2410 else if( bracket++ > 1 )
2411 {
2412 return false;
2413 }
2414 }
2415 else if( scpHasUser( aURL, ii ) )
2416 {
2417 state = USER;
2418 user = ii;
2419 }
2420 else
2421 {
2422 state = HOST;
2423 host = ii;
2424 }
2425
2426 break;
2427
2428 case USER:
2429 if( c == '@' )
2430 {
2431 userLen = ii - user;
2432 state = HOST_START;
2433 }
2434
2435 break;
2436
2437 case HOST_START:
2438 state = c == '[' ? IPV6 : HOST;
2439 host = ii;
2440 break;
2441
2442 case HOST:
2443 if( c == ':' )
2444 {
2445 hostLen = ii - host;
2446 state = bracket ? PORT_START : PATH_START;
2447 }
2448 else if( c == ']' )
2449 {
2450 if( bracket-- == 0 )
2451 return false;
2452
2453 hostLen = ii - host;
2454 state = HOST_END;
2455 }
2456
2457 break;
2458
2459 case HOST_END:
2460 if( c != ':' )
2461 return false;
2462
2463 state = PATH_START;
2464 break;
2465
2466 case IPV6:
2467 if( c == ']' )
2468 state = IPV6_END;
2469
2470 break;
2471
2472 case IPV6_END:
2473 if( c != ':' )
2474 return false;
2475
2476 hostLen = ii - host;
2477 state = bracket ? PORT_START : PATH_START;
2478 break;
2479
2480 case PORT_START:
2481 port = ii;
2482 state = PORT;
2483 break;
2484
2485 case PORT:
2486 if( c == ']' )
2487 {
2488 if( bracket-- == 0 )
2489 return false;
2490
2491 portLen = ii - port;
2492 state = PORT_END;
2493 }
2494
2495 break;
2496
2497 case PORT_END:
2498 if( c != ':' )
2499 return false;
2500
2501 state = PATH_START;
2502 break;
2503
2504 case PATH_START: havePath = true; break;
2505 }
2506 }
2507
2508 if( !havePath || hostLen == 0 )
2509 return false;
2510
2511 aUser = aURL.Mid( user, userLen );
2512 aHost = aURL.Mid( host, hostLen );
2513 aPort = aURL.Mid( port, portLen );
2514
2515 // libgit2 keeps an IPv6 host in its brackets here, but hands it out without them for URLs
2516 if( aHost.StartsWith( "[" ) && aHost.EndsWith( "]" ) )
2517 aHost = aHost.Mid( 1, aHost.length() - 2 );
2518
2519 return true;
2520}
2521
2522
2524{
2526 result.url = aURL;
2527
2528 size_t schemeEnd = aURL.find( "://" );
2529 size_t hostStart = 0;
2530 size_t hostEnd;
2531
2532 if( schemeEnd != wxString::npos )
2533 {
2534 wxString scheme = aURL.Left( schemeEnd ).Lower();
2535
2536 if( scheme == "https" || scheme == "http" )
2538 else if( scheme == "ssh" || scheme == "ssh+git" || scheme == "git+ssh" )
2540 else
2541 return result;
2542
2543 hostStart = schemeEnd + 3;
2544 hostEnd = aURL.find_first_of( "/?#", hostStart );
2545 size_t at = findUserinfoAt( aURL );
2546
2547 if( at != wxString::npos )
2548 {
2549 wxString credentials = aURL.Mid( hostStart, at - hostStart );
2550 size_t colon = credentials.find( ':' );
2551 wxString user = credentials.Left( colon );
2552 result.username = decodePercent( user );
2553
2554 if( colon != wxString::npos )
2555 result.password = decodePercent( credentials.Mid( colon + 1 ) );
2556
2557 wxString userPrefix;
2558
2559 if( result.connType == GIT_CONN_TYPE::GIT_CONN_SSH && !user.IsEmpty() )
2560 userPrefix = user + "@";
2561
2562 result.url = aURL.Left( hostStart ) + userPrefix + aURL.Mid( at + 1 );
2563 hostStart = at + 1;
2564 }
2565 }
2566 else
2567 {
2568 // A colon before the path marks an SCP address, except for Windows drive paths.
2569 if( aURL.length() >= 2 && wxIsalpha( aURL[0] ) && aURL[1] == ':' )
2570 return result;
2571
2572 hostEnd = aURL.find( ':' );
2573 size_t bracket = aURL.find( '[' );
2574
2575 if( bracket != wxString::npos && bracket < hostEnd )
2576 {
2577 size_t endBracket = aURL.find( ']', bracket );
2578
2579 if( endBracket != wxString::npos )
2580 hostEnd = aURL.find( ':', endBracket + 1 );
2581 }
2582
2583 size_t slash = aURL.find_first_of( "/\\" );
2584
2585 if( hostEnd == wxString::npos || hostEnd == 0 || ( slash != wxString::npos && slash < hostEnd ) )
2586 {
2587 return result;
2588 }
2589
2591 wxString port;
2592
2593 // An address libgit2 cannot read leaves no host, which the host key check refuses
2594 if( parseScpAddress( aURL, result.username, result.hostname, port ) )
2595 result.port = parsePort( port );
2596
2597 return result;
2598 }
2599
2600 wxString host = aURL.Mid( hostStart, hostEnd == wxString::npos ? wxString::npos : hostEnd - hostStart );
2601 wxString port;
2602
2603 if( host.StartsWith( "[" ) )
2604 {
2605 result.hostname = host.AfterFirst( '[' ).BeforeFirst( ']' );
2606 port = host.AfterFirst( ']' ).AfterFirst( ':' );
2607 }
2608 else
2609 {
2610 result.hostname = host.BeforeFirst( ':' );
2611 port = host.AfterFirst( ':' );
2612 }
2613
2614 // libgit2 connects to the decoded name, so %67he.example is ghe.example
2615 result.hostname = decodePercent( result.hostname );
2616 result.port = parsePort( port );
2617
2618 return result;
2619}
2620
2621
2623{
2624 std::lock_guard<std::mutex> lock( m_credentialsMutex );
2626}
2627
2628
2630{
2632 m_connType = parsed.connType;
2633 m_remote = parsed.url;
2634 m_urlUsername = parsed.username;
2635 m_hostname = parsed.hostname;
2636 m_port = parsed.port;
2637
2638 if( !parsed.username.IsEmpty() )
2639 m_username = parsed.username;
2640
2641 if( !parsed.password.IsEmpty() )
2642 m_password = parsed.password;
2643
2644 m_secretFetched = !m_password.IsEmpty();
2645}
2646
2647
2648// libgit2 marks at most one entry to merge, the branch the current one tracks, so the name is
2649// not needed to tell them apart. FetchHeadMarksAtMostOneBranchToMerge holds that to account.
2650extern "C" int fetchhead_foreach_cb( const char*, const char*,
2651 const git_oid* aOID, unsigned int aIsMerge, void* aPayload )
2652{
2653 if( aIsMerge )
2654 git_oid_cpy( (git_oid*) aPayload, aOID );
2655
2656 return 0;
2657}
2658
2659
2660namespace KIGIT
2661{
2662
2663bool IsPrivateKeyEncrypted( const wxString& aKeyText )
2664{
2665 wxArrayString lines = wxSplit( aKeyText, '\n', '\0' );
2666
2667 if( lines.IsEmpty() || !lines[0].Contains( wxS( "PRIVATE KEY" ) ) )
2668 return false;
2669
2670 if( lines[0].Contains( wxS( "ENCRYPTED" ) ) )
2671 return true;
2672
2673 // A PEM key carries Proc-Type in the header block, which ends at the blank line.
2674 for( size_t ii = 1; ii < lines.GetCount(); ++ii )
2675 {
2676 if( lines[ii].Trim().IsEmpty() )
2677 break;
2678
2679 if( lines[ii].StartsWith( wxS( "Proc-Type:" ) ) && lines[ii].Contains( wxS( "ENCRYPTED" ) ) )
2680 return true;
2681 }
2682
2683 if( !lines[0].Contains( wxS( "OPENSSH PRIVATE KEY" ) ) )
2684 return false;
2685
2686 // An OpenSSH key carries its cipher name in the body, right after the magic.
2687 wxString body;
2688
2689 for( size_t ii = 1; ii < lines.GetCount(); ++ii )
2690 {
2691 if( lines[ii].StartsWith( wxS( "-----" ) ) )
2692 break;
2693
2694 body += lines[ii];
2695 }
2696
2697 wxMemoryBuffer raw = wxBase64Decode( body, wxBase64DecodeMode_SkipWS );
2698
2699 const char magic[] = "openssh-key-v1";
2700 const size_t magicLen = sizeof( magic );
2701 const unsigned char* data = static_cast<const unsigned char*>( raw.GetData() );
2702
2703 if( raw.GetDataLen() < magicLen + 4 || std::memcmp( data, magic, magicLen ) != 0 )
2704 return false;
2705
2706 uint32_t nameLen =
2707 ( static_cast<uint32_t>( data[magicLen] ) << 24 ) | ( static_cast<uint32_t>( data[magicLen + 1] ) << 16 )
2708 | ( static_cast<uint32_t>( data[magicLen + 2] ) << 8 ) | static_cast<uint32_t>( data[magicLen + 3] );
2709
2710 if( nameLen == 0 || raw.GetDataLen() < magicLen + 4 + nameLen )
2711 return false;
2712
2713 std::string cipher( reinterpret_cast<const char*>( data + magicLen + 4 ), nameLen );
2714
2715 return cipher != "none";
2716}
2717
2718
2719bool IsPrivateKeyFileEncrypted( const wxString& aKey )
2720{
2721 // wxFFile reports an unopenable file to the user, and a key that is gone is simply not encrypted
2722 if( aKey.IsEmpty() || !wxFileName::IsFileReadable( aKey ) )
2723 return false;
2724
2725 wxFFile file( aKey, wxS( "rb" ) );
2726 wxString text;
2727
2728 return file.IsOpened() && file.ReadAll( &text ) && IsPrivateKeyEncrypted( text );
2729}
2730
2731
2733{
2734 git_config* config = nullptr;
2735
2736 if( ( aRepo ? git_repository_config( &config, aRepo ) : git_config_open_default( &config ) ) != 0 )
2737 return wxEmptyString;
2738
2739 GitConfigPtr configPtr( config );
2740 git_config_entry* entry = nullptr;
2741
2742 if( git_config_get_entry( &entry, config, "core.sshCommand" ) != 0 )
2743 return wxEmptyString;
2744
2745 GitConfigEntryPtr entryPtr( entry );
2746 return wxString::FromUTF8( entry->value );
2747}
2748
2749
2750git_tree* ResolveRefToTree( git_repository* aRepo, const wxString& aRef )
2751{
2752 if( !aRepo )
2753 return nullptr;
2754
2755 git_object* obj = nullptr;
2756 std::string refStr( aRef.ToUTF8() );
2757
2758 if( git_revparse_single( &obj, aRepo, refStr.c_str() ) != 0 )
2759 {
2760 wxLogTrace( traceGit, "git_revparse_single failed for ref '%s': %s",
2762 return nullptr;
2763 }
2764
2765 KIGIT::GitObjectPtr objPtr( obj );
2766 git_tree* tree = nullptr;
2767
2768 if( git_object_peel( reinterpret_cast<git_object**>( &tree ), obj, GIT_OBJECT_TREE ) != 0 )
2769 {
2770 wxLogTrace( traceGit, "git_object_peel to tree failed for '%s': %s",
2772 return nullptr;
2773 }
2774
2775 return tree;
2776}
2777
2778
2779std::vector<wxString> CompareBranchRefs( git_repository* aRepo )
2780{
2781 std::vector<wxString> refs;
2782
2783 if( !aRepo )
2784 return refs;
2785
2786 auto resolves = [&]( const wxString& aRef )
2787 {
2788 return !aRef.IsEmpty() && KIGIT::GitTreePtr( ResolveRefToTree( aRepo, aRef ) ) != nullptr;
2789 };
2790
2791 auto add = [&]( const wxString& aRef )
2792 {
2793 if( resolves( aRef ) && std::find( refs.begin(), refs.end(), aRef ) == refs.end() )
2794 refs.push_back( aRef );
2795 };
2796
2797 wxString current;
2798 wxString upstream;
2799 git_reference* head = nullptr;
2800
2801 if( git_repository_head( &head, aRepo ) == 0 )
2802 {
2803 KIGIT::GitReferencePtr headPtr( head );
2804
2805 if( git_reference_is_branch( head ) )
2806 {
2807 current = wxString::FromUTF8( git_reference_shorthand( head ) );
2808
2809 git_reference* tracking = nullptr;
2810
2811 if( git_branch_upstream( &tracking, head ) == 0 )
2812 {
2813 KIGIT::GitReferencePtr trackingPtr( tracking );
2814 upstream = wxString::FromUTF8( git_reference_shorthand( tracking ) );
2815 }
2816 }
2817 }
2818
2819 const wxString main = wxS( "main" );
2820 const wxString master = wxS( "master" );
2821
2822 for( const wxString& base : { main, master, upstream } )
2823 {
2824 if( base != current && resolves( base ) )
2825 {
2826 refs.push_back( base );
2827 break;
2828 }
2829 }
2830
2831 add( current.IsEmpty() ? wxString( wxS( "HEAD" ) ) : current );
2832 add( main );
2833 add( master );
2834 add( upstream );
2835 add( wxS( "HEAD" ) );
2836
2837 return refs;
2838}
2839
2840
2841void CollectDiffDeltas( git_diff* aDiff,
2842 const std::function<void( const git_diff_delta& )>& aCallback )
2843{
2844 if( !aDiff )
2845 return;
2846
2847 std::size_t numDeltas = git_diff_num_deltas( aDiff );
2848
2849 for( std::size_t ii = 0; ii < numDeltas; ++ii )
2850 {
2851 const git_diff_delta* delta = git_diff_get_delta( aDiff, ii );
2852
2853 if( !delta )
2854 continue;
2855
2856 aCallback( *delta );
2857 }
2858}
2859
2860
2861wxString BranchNameError( const wxString& aName )
2862{
2863 if( aName.IsEmpty() )
2864 return _( "Enter a name for the branch." );
2865
2866 // git refuses all of these, but says so in its own words. Name them while the user can
2867 // still fix the name.
2868 if( aName.Contains( wxS( " " ) ) )
2869 return _( "A branch name cannot contain spaces." );
2870
2871 if( aName.StartsWith( wxS( "-" ) ) )
2872 return _( "A branch name cannot start with a dash." );
2873
2874 if( aName.Contains( wxS( ".." ) ) )
2875 return _( "A branch name cannot contain two dots in a row." );
2876
2877 if( aName.EndsWith( wxS( "/" ) ) )
2878 return _( "A branch name cannot end with a slash." );
2879
2880 int valid = 0;
2881
2882#if LIBGIT2_VER_MAJOR > 1 || ( LIBGIT2_VER_MAJOR == 1 && LIBGIT2_VER_MINOR >= 5 )
2883 valid = git_branch_name_is_valid( &valid, aName.utf8_string().c_str() ) == GIT_OK && valid;
2884#else
2885 std::string refName = "refs/heads/" + aName.utf8_string();
2886 valid = aName != wxS( "HEAD" ) && git_reference_is_valid_name( refName.c_str() );
2887#endif
2888
2889 if( !valid )
2890 return wxString::Format( _( "'%s' is not a valid branch name." ), aName );
2891
2892 return wxEmptyString;
2893}
2894
2895
2896wxString DecodeRepoText( const char* aText )
2897{
2898 if( !aText || !*aText )
2899 return wxString();
2900
2901 wxString decoded = wxString::FromUTF8( aText );
2902
2903 if( !decoded.IsEmpty() )
2904 return decoded;
2905
2906 return wxString( aText, wxConvISO8859_1 );
2907}
2908
2909
2910wxString BusyMessage()
2911{
2912 return _( "Another git operation is in progress. Try again in a moment." );
2913}
2914
2915
2916wxString ComposeCommitMessage( const wxString& aSummary, const wxString& aDescription, const wxString& aSignOff )
2917{
2918 wxString message = aSummary;
2919 message.Replace( wxS( "\r\n" ), wxS( "\n" ) );
2920 message.Trim( true ).Trim( false );
2921
2922 wxString description = aDescription;
2923 description.Replace( wxS( "\r\n" ), wxS( "\n" ) );
2924 description.Trim( true ).Trim( false );
2925
2926 if( !description.IsEmpty() )
2927 message << wxS( "\n\n" ) << description;
2928
2929 if( !aSignOff.IsEmpty() )
2930 {
2931 wxString trailer = wxS( "Signed-off-by: " ) + aSignOff;
2932 bool signedOff = false;
2933
2934 // An amended message already carries its own sign off line.
2935 for( wxString line : wxSplit( message, '\n' ) )
2936 {
2937 if( line.Trim() == trailer )
2938 signedOff = true;
2939 }
2940
2941 if( !signedOff )
2942 message << wxS( "\n\n" ) << trailer;
2943 }
2944
2945 return message;
2946}
2947
2948
2949void SplitCommitMessage( const wxString& aMessage, wxString& aSummary, wxString& aDescription )
2950{
2951 wxString message = aMessage;
2952 message.Replace( wxS( "\r\n" ), wxS( "\n" ) );
2953 message.Trim( true ).Trim( false );
2954
2955 aSummary = message.BeforeFirst( '\n' );
2956 aDescription = message.AfterFirst( '\n' );
2957 aDescription.Trim( false );
2958}
2959
2960} // namespace KIGIT
int index
const char * name
virtual RestoreResult RestoreVersion(KIGIT_COMMON &aCommon, const wxString &aCommitHash, KIGIT_ERROR_MESSAGE &aError)=0
virtual bool CreateTag(git_repository *aRepo, const wxString &aName, const wxString &aMessage)=0
virtual bool CheckoutTag(git_repository *aRepo, const wxString &aName)=0
virtual int CreateBranch(git_repository *aRepo, const wxString &aBranchName, const wxString &aFrom)=0
virtual bool DeleteTag(git_repository *aRepo, const wxString &aName)=0
virtual bool SetRemoteUrl(git_repository *aRepo, const wxString &aName, const wxString &aUrl)=0
virtual bool AbandonOperation(git_repository *aRepo, wxString &aError)=0
Drop a merge, rebase, cherry-pick or revert left in progress and return to the last commit.
virtual bool GetMergeConflicts(git_repository *aRepo, const wxString &aStageDir, wxString &aHeadOid, wxString &aTheirsOid, std::vector< KIGIT_CONFLICT_SIDES > &aConflicts, wxString &aError)=0
virtual bool DeleteBranch(git_repository *aRepo, const wxString &aBranchName)=0
virtual bool AddRemote(git_repository *aRepo, const wxString &aName, const wxString &aUrl)=0
virtual bool StashPop(git_repository *aRepo, size_t aIndex)=0
virtual MergeCommitResult CreateMergedCommit(git_repository *aRepo, const wxString &aExpectedHeadOid, const wxString &aTheirsOid, const std::vector< std::pair< wxString, wxString > > &aResolvedFiles, KIGIT_ERROR_MESSAGE &aError)=0
virtual bool StashApply(git_repository *aRepo, size_t aIndex)=0
virtual bool SetUserConfig(git_repository *aRepo, const wxString &aName, const wxString &aEmail)=0
virtual bool IsPathInHead(git_repository *aRepo, const wxString &aPath)=0
virtual bool DiscardChanges(git_repository *aRepo, const std::vector< wxString > &aPaths, wxString &aError)=0
virtual bool StashSave(git_repository *aRepo, const wxString &aMessage)=0
virtual bool StashDrop(git_repository *aRepo, size_t aIndex)=0
virtual bool RemoveRemote(git_repository *aRepo, const wxString &aName)=0
static std::optional< wxString > ProjectPrefix(const wxString &aWorkDir, const wxString &aProjectPath)
The project's folder inside the repository, ending in a slash.
std::mutex m_gitActionMutex
void FollowRewrittenUrl(const wxString &aRawUrl)
Bind the session to a URL that url.insteadOf rewrote, keeping the username, password and key entered ...
static bool DeferForSecret(const std::shared_ptr< KIGIT_COMMON > &aCommon, const std::weak_ptr< bool > &aOwner, std::function< void()> aRetry)
Read the remote's secret from the keyring on the UI thread without blocking it, so an unlock prompt c...
git_repository * m_repo
std::pair< int, int > GetWorkingTreeLineStats(const std::set< wxString > &aPaths) const
wxString GetAcceptedSSHKey() const
The encrypted key the server last accepted for this remote, so the credential prompt asks for the rig...
void ResetNextKey()
Start the next attempt from the first key, with the key that last connected to the current remote mov...
std::shared_ptr< std::atomic< bool > > CANCEL_TOKEN
One token per operation.
GIT_CONN_TYPE GetConnType() const
std::vector< KIGIT_COMMIT_INFO > GetRecentCommits(size_t aMax=50, const KIGIT_HISTORY_FILTER &aFilter={}) const
bool HasUncommittedTrackedChanges(bool *aReadOk=nullptr) const
void SyncRemoteUrl(const wxString &aRawUrl)
Bind the session to the URL a transfer is about to connect to.
CANCEL_TOKEN ActiveCancelToken() const
bool StashPop(size_t aIndex)
std::optional< wxString > GetProjectPrefix() const
Project folder relative to the repository, with a trailing slash.
void SetConnType(GIT_CONN_TYPE aConnType)
For a remote whose address names no transport, the user picks one in the prompt.
wxString GetRemote() const
wxString GetLastCommitMessage() const
std::mutex m_credentialsMutex
Serializes the credential fields between the UI thread and the authentication callback's worker threa...
wxString GetCurrentBranchName() const
wxString GetGitRootDirectory() const
bool IsOperationInProgress() const
True while a merge, rebase, cherry-pick or revert is in progress, which refuses commits.
KIGIT_TAG_DETAIL GetTagDetail(const wxString &aName) const
wxString GetSSHKey() const
The key the project was set up with, even when its file is gone, otherwise the first key offered.
void SetSSHKey(const wxString &aSSHKey)
bool IsPullRebaseConfigured() const
True when the repository is set to rebase rather than merge when getting changes.
KIGIT_COMMIT_DETAIL GetCommitDetail(const wxString &aHash) const
wxString m_projectPath
wxString m_urlUsername
bool CheckoutTag(const wxString &aName)
wxString remoteNameWithoutUpstream() const
Remote to use when HEAD names no upstream, empty when several remotes leave it ambiguous.
wxString m_publicKeysHost
bool DeleteTag(const wxString &aName)
std::vector< wxString > GetProjectDirs()
Return a vector of project files in the repository.
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.
wxString m_acceptedSSHKey
git_repository * GetRepo() const
KIGIT_COMMON(git_repository *aRepo, const wxString &aProjectPath=wxEmptyString)
aProjectPath is the absolute project directory.
CREDENTIAL_IDENTITY GetCredentialIdentity() const
wxString GetPushUrl(const wxString &aRemoteName) const
The address a push to aRemoteName connects to, its push URL or else its URL. Empty without one.
std::vector< wxString > GetRecentCommitMessages(size_t aMax) const
wxString GetProjectDir() const
Return the path set by SetProjectDir(), or the repository's working directory.
bool RemoveRemote(const wxString &aName)
std::optional< size_t > GetUnmergedCommitCount(const wxString &aBranch) const
Commits in aBranch that HEAD does not contain. No value when either cannot be read.
bool CreateBranch(const wxString &aName, const wxString &aFrom=wxEmptyString)
wxString GetNextPublicKey()
By value, so the caller never holds a pointer into the vector.
bool AddRemote(const wxString &aName, const wxString &aUrl)
int SSHPortFor(const wxString &aHost) const
The SSH port the session's remote names for aHost, 22 when it names none, or -1 when the remote is on...
bool GetMergeConflicts(const wxString &aStageDir, wxString &aHeadOid, wxString &aTheirsOid, std::vector< KIGIT_CONFLICT_SIDES > &aConflicts, wxString &aError)
Recompute the merge in memory and extract each conflicted file's three versions into aStageDir,...
void AddRefreshListener(void *aOwner, std::function< void()> aCallback)
std::vector< KIGIT_STASH_INFO > GetStashes() const
std::unique_lock< std::mutex > TryLockActionFor(std::chrono::milliseconds aWait)
TryLockAction that keeps trying for aWait before giving up.
bool StartUnbornBranch(const wxString &aName)
Point HEAD at a branch that does not exist yet, so the first commit creates it.
std::pair< std::set< wxString >, std::set< wxString > > GetDifferentFiles() const
Return a pair of sets of files that differ locally from the remote repository The first set is files ...
bool IsHeadUnborn() const
True while the repository has no commits, so HEAD names a branch that does not exist yet.
bool ApplyPromptedCredentials(const CREDENTIAL_IDENTITY &aFor, const PROMPTED_CREDENTIALS &aEntered)
Apply what the prompt collected, unless the session has moved to another remote since aFor was taken.
std::vector< std::pair< void *, std::function< void()> > > m_refreshListeners
std::vector< wxString > m_publicKeys
wxString m_projectDir
bool IsShuttingDown() const
Background timers ask this before starting work of their own.
KIGIT_BRANCH_DETAIL GetBranchDetail(const wxString &aBranch) const
wxString GetHeadCommitId() const
Full commit ID at HEAD, or empty for an unborn or missing HEAD.
bool HasPushAndPullRemote() const
bool StashApply(size_t aIndex)
bool DiscardChanges(const std::vector< wxString > &aPaths, wxString &aError)
Put the given working directory relative paths back to their committed state.
void rebuildPublicKeysUnlocked()
Rebuild m_publicKeys as the project key, when offerable, then the key that last connected to m_remote...
GIT_CONN_TYPE m_connType
bool SetUserConfig(const wxString &aName, const wxString &aEmail)
void updateConnectionTypeUnlocked()
Body of updateConnectionType, for callers that already hold m_credentialsMutex.
bool IsPathInHead(const wxString &aPath)
True when the working directory relative path exists in the HEAD commit's tree.
std::optional< KIGIT_UPSTREAM_STATUS > UpstreamStatus() const
The current branch against its upstream.
KIGIT_STASH_DETAIL GetStashDetail(const wxString &aId) const
std::vector< std::pair< wxString, wxString > > GetRemotes() const
Returns every remote as a (name, URL) pair.
static wxString GetLastGitError()
libgit2's last message, without credentials from any URL it quotes, so it is safe to show or trace.
bool CreateTag(const wxString &aName, const wxString &aMessage=wxEmptyString)
MergeCommitResult CreateMergedCommit(const wxString &aExpectedHeadOid, const wxString &aTheirsOid, const std::vector< std::pair< wxString, wxString > > &aResolvedFiles, KIGIT_ERROR_MESSAGE &aError)
Redo the merge with each conflicted path replaced by its resolved file, then commit and check out.
bool AbandonOperation(wxString &aError)
Drop that operation and return to the last commit. The caller holds the action lock.
wxString GetFirstOfferedSSHKey() const
The key the next attempt will try first, for the credential prompt to show.
void RemoveRefreshListener(void *aOwner)
bool StashDrop(size_t aIndex)
bool HasLocalCommits() const
True when HEAD has commits its upstream does not, or has no upstream yet.
std::vector< wxString > m_discoveredKeys
void RememberWorkingSSHKey(const KIGIT_AUTH_ATTEMPT &aAttempt)
Remember the key that connected for aAttempt, so the next connection offers it first.
bool StashSave(const wxString &aMessage)
Set the uncommitted tracked changes aside as a new stash, as git stash push would.
wxDateTime GetLastFetchTime() const
static REMOTE_URL ParseRemoteURL(const wxString &aURL)
wxString GetPassword()
The secret for the remote, read without ever prompting, so it is safe on a transfer worker.
GitOperation OperationInProgress() const
Which operation that is, so the panel can name it.
std::optional< KIGIT_AHEAD_BEHIND > compareRefs(const git_reference *aBranch, const git_reference *aBase) const
Count commits unique to aBranch and aBase. No value if the history cannot be read.
RestoreResult RestoreVersion(const wxString &aCommitHash, KIGIT_ERROR_MESSAGE &aError)
Restore the project as it was at aCommitHash, recorded as a new commit on top of the current head.
void SetAcceptedSSHKey(const wxString &aKey)
std::vector< KIGIT_TAG_INFO > GetTags() const
std::vector< KIGIT_BRANCH_INFO > GetBranches() const
Local and remote branches with their tip commits.
bool DeleteBranch(const wxString &aName)
wxString m_projectSSHKey
bool IsPathConflicted(const wxString &aPath) const
True while aPath is one of the files a merge or rebase stopped on.
wxString GetRemotename() const
bool IsHeadDetached() const
True when HEAD points at a commit rather than a branch, as after checking out a tag.
bool SetRemoteUrl(const wxString &aName, const wxString &aUrl)
static bool registered
#define _(s)
@ NONE
Definition eda_fill.h:42
GIT_BACKEND * GetGitBackend()
MergeCommitResult
Definition git_backend.h:83
const wxChar *const traceGit
Flag to enable Git debugging output.
std::string message
@ USER
The main config directory (e.g. ~/.config/kicad/)
int fetchhead_foreach_cb(const char *, const char *, const git_oid *aOID, unsigned int aIsMerge, void *aPayload)
static size_t findUserinfoAt(const wxString &aUrl)
static bool scpHasUser(const wxString &aText, size_t aStart)
static bool isScpIpv6(const wxString &aText, size_t aBracket)
static int parsePort(const wxString &aPort)
static bool parseScpAddress(const wxString &aURL, wxString &aUser, wxString &aHost, wxString &aPort)
static wxString decodePercent(const wxString &aText)
GitOperation
RestoreResult
bool IsPrivateKeyFileEncrypted(const wxString &aKey)
IsPrivateKeyEncrypted for the key file aKey. A file that cannot be read is reported as unencrypted.
std::unique_ptr< git_tree, decltype([](git_tree *aTree) { git_tree_free(aTree); })> GitTreePtr
A unique pointer for git_tree objects with automatic cleanup.
APIEXPORT wxString StripEmbeddedUserinfo(const wxString &aText)
Remove the user and password from every URL quoted in a message, since the remote's can carry a passw...
bool IsPrivateKeyEncrypted(const wxString &aKeyText)
Report whether an SSH private key is protected by a passphrase.
void SplitCommitMessage(const wxString &aMessage, wxString &aSummary, wxString &aDescription)
Split a commit message into its first line and the description after the first blank line.
APIEXPORT bool IsOfferableSSHKey(const wxString &aKey)
Whether aKey can be offered to a server.
wxString BranchNameError(const wxString &aName)
Empty when aName is a branch name git would accept, otherwise why it would not, in the words to show ...
git_tree * ResolveRefToTree(git_repository *aRepo, const wxString &aRef)
Resolve a string ref (branch name, short OID, full OID, tag) to its tree.
std::unique_ptr< git_revwalk, decltype([](git_revwalk *aWalker) { git_revwalk_free(aWalker); })> GitRevWalkPtr
A unique pointer for git_revwalk 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.
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.
wxString ConfiguredSSHCommand(git_repository *aRepo)
git's core.sshCommand for aRepo, or from the user's git config when aRepo is null....
APIEXPORT wxString RememberedSSHKey(const wxString &aRemote)
The key that last connected to aRemote, or empty.
std::unique_ptr< git_status_list, decltype([](git_status_list *aList) { git_status_list_free(aList); })> GitStatusListPtr
A unique pointer for git_status_list objects with automatic cleanup.
std::unique_ptr< git_config, decltype([](git_config *aConfig) { git_config_free(aConfig); })> GitConfigPtr
A unique pointer for git_config objects with automatic cleanup.
std::unique_ptr< git_patch, decltype([](git_patch *aPatch) { git_patch_free(aPatch); })> GitPatchPtr
A unique pointer for git_patch objects with automatic cleanup.
APIEXPORT std::vector< wxString > DefaultSSHKeyCandidates(const wxString &aHomeDir, const wxString &aHost, const wxString &aSSHCommand=wxEmptyString)
Private keys to offer aHost, best first.
std::unique_ptr< git_reference, decltype([](git_reference *aRef) { git_reference_free(aRef); })> GitReferencePtr
A unique pointer for git_reference objects with automatic cleanup.
wxString ComposeCommitMessage(const wxString &aSummary, const wxString &aDescription, const wxString &aSignOff)
Join a summary line, an optional description and an optional sign-off into one commit message.
std::unique_ptr< git_strarray, decltype([](git_strarray *aArray) { git_strarray_free(aArray); })> GitStrArrayPtr
A unique pointer for git_strarray 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.
APIEXPORT wxString HomeDir()
The user's home folder, where ssh looks for its config and default keys: the first candidate with a ....
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 wxWindow *& ActiveAdvancedGitWindow()
The advanced git window, or null when none is open.
APIEXPORT void RememberSSHKey(const wxString &aRemote, const wxString &aKey)
Remember aKey as the key that connected to aRemote. Safe to call from any thread.
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.
wxString DecodeRepoText(const char *aText)
Decode text that came out of a repository.
std::vector< wxString > CompareBranchRefs(git_repository *aRepo)
Refs to offer when comparing branches, base first and head second.
APIEXPORT bool IsSameSSHKey(const wxString &aKey, const wxString &aOther)
Whether two key paths name the same file.
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_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.
bool GetSecretNoPrompt(const wxString &aService, const wxString &aKey, wxString &aSecret)
Like GetSecret(), but never waits on the user.
void GetSecretAsync(const wxString &aService, const wxString &aKey, std::function< void(bool, const wxString &)> aDone)
Like GetSecret(), but never blocks the event loop while the platform asks the user to unlock the stor...
size_t behind
Commits only in the second reference.
size_t ahead
Commits only in the first reference.
What the credential callback handed out during one operation, kept to explain a rejection.
KIGIT_COMMON::GIT_CONN_TYPE connType
std::vector< wxString > keysTried
Key files offered, in order.
wxString oldPath
For a rename or copy, where the file came from.
KIGIT::FILE_CHANGE_STATUS status
The remote the credential prompt was opened for.
What the credential prompt collected.
std::optional< wxString > username
A transport address with any embedded credentials extracted.
int port
0 when the address names none.
wxString url
Keeps the SSH username, scheme and port, but never a password.
What libgit2 reported for a failed call, read before anything else can replace it.
A summary the user can act on, with the raw text that explains it kept apart for the details.
wxString search
Keep only commits whose summary, author or hash contains this.
wxString path
Keep only commits that changed this file or folder, relative to the root.
wxString branch
One branch, local or remote, or empty for every branch and HEAD.
Where the current branch stands against its upstream.
static std::string decoded(const std::string &aBase64)
std::string path
wxString result
Test unit parsing edge cases and error handling.
int delta
wxLogTrace helper definitions.