34#include <wx/filename.h>
36#include <wx/textfile.h>
84 const char* workdir = git_repository_workdir(
m_repo );
87 return wxString( workdir );
96 wxCHECK(
m_repo, wxEmptyString );
98 git_reference* head =
nullptr;
100 if( git_repository_head( &head,
m_repo ) != GIT_OK )
101 return wxEmptyString;
105 if( !git_reference_is_branch( head ) )
106 return wxEmptyString;
108 git_reference* upstream =
nullptr;
110 if( git_branch_upstream( &upstream, head ) == GIT_OK )
113 const char* shorthand = git_reference_shorthand( upstream );
116 return wxString::FromUTF8( shorthand );
121 const char* branch_shorthand = git_reference_shorthand( head );
123 if( !branch_shorthand )
124 return wxEmptyString;
132 wxCHECK(
m_repo, wxEmptyString );
133 git_reference* head =
nullptr;
135 int retval = git_repository_head( &head,
m_repo );
137 if( retval && retval != GIT_EUNBORNBRANCH && retval != GIT_ENOTFOUND )
138 return wxEmptyString;
141 git_reference* branch;
143 if( git_reference_resolve( &branch, head ) )
145 wxLogTrace(
traceGit,
"Failed to resolve branch" );
146 return wxEmptyString;
150 const char* branchName =
"";
152 if( git_branch_name( &branchName, branch ) )
154 wxLogTrace(
traceGit,
"Failed to get branch name" );
155 return wxEmptyString;
158 return wxString( branchName );
186 std::vector<wxString> branchNames;
187 std::map<git_time_t, wxString> branchNamesMap;
190 git_branch_iterator* branchIterator =
nullptr;
192 if( git_branch_iterator_new( &branchIterator,
m_repo, GIT_BRANCH_LOCAL ) )
194 wxLogTrace(
traceGit,
"Failed to get branch iterator" );
199 git_reference* branchReference =
nullptr;
200 git_branch_t branchType;
202 while( git_branch_next( &branchReference, &branchType, branchIterator ) != GIT_ITEROVER )
204 const char* branchName =
"";
207 if( git_branch_name( &branchName, branchReference ) )
209 wxLogTrace(
traceGit,
"Failed to get branch name in iter loop" );
213 const git_oid* commitId = git_reference_target( branchReference );
215 git_commit* commit =
nullptr;
217 if( git_commit_lookup( &commit,
m_repo, commitId ) )
219 wxLogTrace(
traceGit,
"Failed to get commit in iter loop" );
224 git_time_t commitTime = git_commit_time( commit );
226 if( git_branch_is_head( branchReference ) )
227 firstName = branchName;
229 branchNamesMap.emplace( commitTime, branchName );
233 if( !firstName.IsEmpty() )
234 branchNames.push_back( firstName );
237 for(
auto rit = branchNamesMap.rbegin(); rit != branchNamesMap.rend(); ++rit )
238 branchNames.push_back( rit->second );
247 std::vector<wxString> projDirs;
253 if( git_reference_name_to_id( &oid,
m_repo,
"HEAD" ) != GIT_OK )
259 if( git_commit_lookup( &commit,
m_repo, &oid ) != GIT_OK )
267 if( git_commit_tree( &tree, commit ) != GIT_OK )
277 tree, GIT_TREEWALK_PRE,
278 [](
const char* root,
const git_tree_entry* entry,
void* payload )
280 std::vector<wxString>* prjs =
static_cast<std::vector<wxString>*
>( payload );
281 wxFileName root_fn( git_tree_entry_name( entry ) );
283 root_fn.SetPath( root );
285 if( git_tree_entry_type( entry ) == GIT_OBJECT_BLOB
286 && ( ( root_fn.GetExt() ==
"kicad_pro" ) || ( root_fn.GetExt() ==
"pro" ) ) )
288 prjs->push_back( root_fn.GetFullPath() );
295 std::sort( projDirs.begin(), projDirs.end(),
296 [](
const wxString& a,
const wxString& b )
298 int a_freq = a.Freq( wxFileName::GetPathSeparator() );
299 int b_freq = b.Freq( wxFileName::GetPathSeparator() );
301 if( a_freq == b_freq )
304 return a_freq < b_freq;
314 std::pair<std::set<wxString>, std::set<wxString>> modified_files;
317 return modified_files;
319 git_reference* head =
nullptr;
320 git_reference* remote_head =
nullptr;
322 if( git_repository_head( &head,
m_repo ) != GIT_OK )
324 wxLogTrace(
traceGit,
"Failed to get modified HEAD" );
325 return modified_files;
330 if( git_branch_upstream( &remote_head, head ) != GIT_OK )
335 wxLogTrace(
traceGit,
"Failed to get modified remote HEAD" );
336 return modified_files;
341 const git_oid* head_oid = git_reference_target( head );
342 const git_oid* remote_oid = git_reference_target( remote_head );
344 if( !head_oid || !remote_oid )
345 return modified_files;
348 [
this](
const git_oid* aOid ) -> git_tree*
350 git_commit* commit =
nullptr;
352 if( git_commit_lookup( &commit,
m_repo, aOid ) != GIT_OK )
354 wxLogTrace(
traceGit,
"Failed to lookup commit for diff: %s",
360 git_tree* tree =
nullptr;
362 if( git_commit_tree( &tree, commit ) != GIT_OK )
364 wxLogTrace(
traceGit,
"Failed to get commit tree for diff: %s",
372 git_tree* head_tree = load_tree( head_oid );
375 git_tree* remote_tree = load_tree( remote_oid );
378 if( !head_tree || !remote_tree )
379 return modified_files;
388 if( git_merge_base( &base_oid,
m_repo, head_oid, remote_oid ) != GIT_OK )
390 wxLogTrace(
traceGit,
"No merge base between local and remote: %s",
392 return modified_files;
395 git_tree* base_tree = load_tree( &base_oid );
399 return modified_files;
402 [
this]( git_tree* aOldTree, git_tree* aNewTree, std::set<wxString>& aOut )
407 git_diff_options localOpts;
408 git_diff_init_options( &localOpts, GIT_DIFF_OPTIONS_VERSION );
410 git_diff* diff =
nullptr;
412 if( git_diff_tree_to_tree( &diff,
m_repo, aOldTree, aNewTree, &localOpts )
415 wxLogTrace(
traceGit,
"Failed to diff trees: %s",
420 size_t numDeltas = git_diff_num_deltas( diff );
422 for(
size_t ii = 0; ii < numDeltas; ++ii )
424 const git_diff_delta*
delta = git_diff_get_delta( diff, ii );
426 if(
delta->new_file.path )
427 aOut.insert( wxString::FromUTF8(
delta->new_file.path ) );
429 if(
delta->old_file.path )
430 aOut.insert( wxString::FromUTF8(
delta->old_file.path ) );
433 git_diff_free( diff );
436 collect_paths( base_tree, head_tree, modified_files.first );
437 collect_paths( base_tree, remote_tree, modified_files.second );
443 std::set<wxString> actuallyDifferent;
444 collect_paths( head_tree, remote_tree, actuallyDifferent );
446 auto filterToDifferent = [&]( std::set<wxString>& aSet )
448 for(
auto it = aSet.begin(); it != aSet.end(); )
449 it = actuallyDifferent.count( *it ) ? std::next( it ) : aSet.erase( it );
452 filterToDifferent( modified_files.first );
453 filterToDifferent( modified_files.second );
455 return modified_files;
464 git_reference* head =
nullptr;
465 git_reference* remote_head =
nullptr;
467 if( git_repository_head( &head,
m_repo ) != GIT_OK )
475 if( git_branch_upstream( &remote_head, head ) != GIT_OK )
483 const git_oid* head_oid = git_reference_target( head );
484 const git_oid* remote_oid = git_reference_target( remote_head );
485 git_revwalk* walker =
nullptr;
487 if( git_revwalk_new( &walker,
m_repo ) != GIT_OK )
495 if( !head_oid || git_revwalk_push( walker, head_oid ) != GIT_OK )
501 if( remote_oid && git_revwalk_hide( walker, remote_oid ) != GIT_OK )
510 if( git_revwalk_next( &oid, walker ) != GIT_OK )
528 [
this](
const char* aName ) ->
bool
530 git_remote* remote =
nullptr;
532 if( git_remote_lookup( &remote,
m_repo, aName ) != GIT_OK )
537 const char* fetch_url = git_remote_url( remote );
538 const char* push_url = git_remote_pushurl( remote );
542 push_url = fetch_url;
544 return fetch_url && push_url;
549 if( checkRemote( preferred.c_str() ) )
552 if( preferred !=
"origin" && checkRemote(
"origin" ) )
555 git_strarray remotes = {
nullptr, 0 };
557 if( git_remote_list( &remotes,
m_repo ) != GIT_OK )
559 wxLogTrace(
traceGit,
"Failed to enumerate remotes for haspushpull" );
565 for(
size_t ii = 0; ii < remotes.count; ++ii )
567 if( checkRemote( remotes.strings[ii] ) )
579 if( remoteName.IsEmpty() )
580 remoteName = wxS(
"origin" );
588 wxCHECK(
m_repo, wxEmptyString );
591 git_reference* head =
nullptr;
592 git_reference* upstream =
nullptr;
594 if( git_repository_head( &head,
m_repo ) != GIT_OK )
602 if( git_branch_upstream( &upstream, head ) != GIT_OK )
605 git_strarray remotes = {
nullptr, 0 };
607 if( git_remote_list( &remotes,
m_repo ) == GIT_OK )
612 if( remotes.count == 1 )
614 retval = remotes.strings[0];
618 for(
size_t ii = 0; ii < remotes.count; ++ii )
620 if( strcmp( remotes.strings[ii],
"origin" ) == 0 )
622 retval = remotes.strings[ii];
628 git_strarray_dispose( &remotes );
637 git_remote* remote =
nullptr;
639 if( git_remote_lookup( &remote,
m_repo,
"origin" ) == GIT_OK )
641 retval = git_remote_name( remote );
642 git_remote_free( remote );
646 wxLogTrace(
traceGit,
"Failed to get remote name from default remote: %s",
655 git_buf remote_name = GIT_BUF_INIT_CONST(
nullptr, 0 );
657 if( git_branch_remote_name( &remote_name,
m_repo, git_reference_name( upstream ) ) == GIT_OK )
659 retval = remote_name.ptr;
660 git_buf_dispose( &remote_name );
665 "Failed to get remote name from upstream branch: %s",
687 return wxEmptyString;
691 if(
const char* workdir = git_repository_workdir(
m_repo ) )
692 return wxString::FromUTF8( workdir );
694 if(
const char*
path = git_repository_path(
m_repo ) )
695 return wxString::FromUTF8(
path );
697 return wxEmptyString;
705 wxFileName keyFile( wxGetHomeDir(), wxEmptyString );
706 keyFile.AppendDir(
".ssh" );
707 keyFile.SetFullName(
"id_rsa" );
709 if( keyFile.FileExists() )
712 keyFile.SetFullName(
"id_dsa" );
714 if( keyFile.FileExists() )
717 keyFile.SetFullName(
"id_ecdsa" );
719 if( keyFile.FileExists() )
722 keyFile.SetFullName(
"id_ed25519" );
724 if( keyFile.FileExists() )
728 wxFileName sshConfig( wxGetHomeDir(), wxEmptyString );
729 sshConfig.AppendDir(
".ssh" );
730 sshConfig.SetFullName(
"config" );
732 if( sshConfig.FileExists() )
734 wxTextFile configFile( sshConfig.GetFullPath() );
739 for( wxString line = configFile.GetFirstLine(); !configFile.Eof(); line = configFile.GetNextLine() )
741 line.Trim(
false ).Trim(
true );
743 if( line.StartsWith(
"Host " ) )
748 if( line.StartsWith(
"Host" ) && line.Contains(
m_hostname ) )
751 if( match && line.StartsWith(
"IdentityFile" ) )
753 wxString keyPath = line.AfterFirst(
' ' ).Trim(
false ).Trim(
true );
756 if( keyPath.StartsWith(
"~" ) )
757 keyPath.Replace(
"~", wxGetHomeDir(),
false );
760 if( wxFileName::FileExists( keyPath ) )
778 git_remote* remote =
nullptr;
784 if( git_remote_lookup( &remote,
m_repo, remote_name.ToStdString().c_str() ) == GIT_OK )
786 const char* url = git_remote_url( remote );
791 git_remote_free( remote );
803 if( remote.IsEmpty() )
806 if( remote.StartsWith(
"https://" ) || remote.StartsWith(
"http://" ) )
810 else if( remote.StartsWith(
"ssh://" ) || remote.StartsWith(
"git@" ) || remote.StartsWith(
"git+ssh://" )
811 || remote.EndsWith(
".git" ) )
832 size_t atPos = uri.find(
'@' );
834 if( atPos != wxString::npos )
836 size_t protoEnd = uri.find(
"//" );
838 if( protoEnd != wxString::npos )
840 wxString credentials = uri.Mid( protoEnd + 2, atPos - protoEnd - 2 );
841 size_t colonPos = credentials.find(
':' );
843 if( colonPos != wxString::npos )
846 m_password = credentials.Mid( colonPos + 1, credentials.Length() - colonPos - 1 );
862 size_t colonPos =
m_remote.find(
':' );
864 if( colonPos != wxString::npos )
870 size_t hostStart =
m_remote.find(
"://" ) + 2;
871 size_t hostEnd =
m_remote.find(
'/', hostStart );
874 if( hostEnd != wxString::npos )
875 host =
m_remote.Mid( hostStart, hostEnd - hostStart );
879 atPos = host.find(
'@' );
881 if( atPos != wxString::npos )
904 if( sshKey.IsEmpty() )
906 wxLogTrace(
traceGit,
"Finished testing all possible ssh keys" );
908 return GIT_PASSTHROUGH;
911 wxString sshPubKey = sshKey +
".pub";
914 wxLogTrace(
traceGit,
"Testing %s\n", sshKey );
916 if( git_credential_ssh_key_new( aOut, aUsername.mbc_str(), sshPubKey.mbc_str(), sshKey.mbc_str(),
917 password.mbc_str() ) != GIT_OK )
919 wxLogTrace(
traceGit,
"Failed to create SSH key credential for %s: %s",
921 return GIT_PASSTHROUGH;
932 git_credential_userpass_plaintext_new( aOut, aUsername.mbc_str(), password.mbc_str() );
943 if( git_credential_ssh_key_from_agent( aOut, aUsername.mbc_str() ) != GIT_OK )
945 wxLogTrace(
traceGit,
"Failed to create SSH agent credential for %s: %s",
947 return GIT_PASSTHROUGH;
955 const git_oid* aOID,
unsigned int aIsMerge,
void* aPayload )
958 git_oid_cpy( (git_oid*) aPayload, aOID );
964extern "C" void clone_progress_cb(
const char* aStr,
size_t aLen,
size_t aTotal,
void* aPayload )
968 wxString progressMessage( aStr );
973extern "C" int progress_cb(
const char* str,
int len,
void* aPayload )
979 wxLogTrace(
traceGit,
"Progress CB cancelled" );
983 wxString progressMessage( str, len );
994 wxString progressMessage = wxString::Format(
_(
"Received %u of %u objects" ),
995 aStats->received_objects,
996 aStats->total_objects );
999 wxLogTrace(
traceGit,
"Transfer progress cancelled" );
1003 parent->
UpdateProgress( aStats->received_objects, aStats->total_objects, progressMessage );
1009extern "C" int update_cb(
const char* aRefname,
const git_oid* aFirst,
const git_oid* aSecond,
1012 constexpr int cstring_len = 8;
1013 char a_str[cstring_len + 1];
1014 char b_str[cstring_len + 1];
1019 git_oid_tostr( b_str, cstring_len, aSecond );
1021#if ( LIBGIT2_VER_MAJOR >= 1 ) || ( LIBGIT2_VER_MINOR >= 99 )
1022 if( !git_oid_is_zero( aFirst ) )
1024 if( !git_oid_iszero( aFirst ) )
1027 git_oid_tostr( a_str, cstring_len, aFirst );
1028 status = wxString::Format(
_(
"* [updated] %s..%s %s" ), a_str, b_str, aRefname );
1032 status = wxString::Format(
_(
"* [new] %s %s" ), b_str, aRefname );
1044 long long progress = 100;
1049 progress = ( aCurrent * 100ll ) / aTotal;
1052 wxString progressMessage = wxString::Format(
_(
"Writing objects: %lld%% (%u/%u), %zu bytes" ),
1053 progress, aCurrent, aTotal, aBytes );
1063 wxString status( aStatus );
1065 if( !status.IsEmpty() )
1067 wxString statusMessage = wxString::Format(
_(
"* [rejected] %s (%s)" ), aRefname, aStatus );
1072 wxString statusMessage = wxString::Format(
_(
"[updated] %s" ), aRefname );
1080extern "C" int credentials_cb( git_cred** aOut,
const char* aUrl,
const char* aUsername,
1081 unsigned int aAllowedTypes,
void* aPayload )
1086 wxLogTrace(
traceGit,
"Credentials callback for %s, testing %d", aUrl, aAllowedTypes );
1090 wxLogTrace(
traceGit,
"Local repository, no credentials needed" );
1091 return GIT_PASSTHROUGH;
1094 if( aAllowedTypes & GIT_CREDENTIAL_USERNAME
1095 && !( parent->
TestedTypes() & GIT_CREDENTIAL_USERNAME ) )
1097 wxString username = parent->
GetUsername().Trim().Trim(
false );
1098 wxLogTrace(
traceGit,
"Username credential for %s at %s with allowed type %d",
1099 username, aUrl, aAllowedTypes );
1101 if( git_credential_username_new( aOut, username.ToStdString().c_str() ) != GIT_OK )
1103 wxLogTrace(
traceGit,
"Failed to create username credential for %s: %s",
1108 wxLogTrace(
traceGit,
"Created username credential for %s", username );
1114 && ( aAllowedTypes & GIT_CREDENTIAL_USERPASS_PLAINTEXT )
1115 && !( parent->
TestedTypes() & GIT_CREDENTIAL_USERPASS_PLAINTEXT )
1119 wxLogTrace(
traceGit,
"Plaintext authentication for %s at %s with allowed type %d",
1124 && ( aAllowedTypes & GIT_CREDENTIAL_SSH_KEY )
1125 && !( parent->
TestedTypes() & GIT_CREDENTIAL_SSH_KEY ) )
1132 if(
result == GIT_PASSTHROUGH )
1135 git_error_set_str( GIT_ERROR_NET,
_(
"Unable to authenticate" ).mbc_str() );
1147 return GIT_PASSTHROUGH;
1150 git_error_set_str( GIT_ERROR_NET,
_(
"Unable to authenticate" ).mbc_str() );
virtual void UpdateProgress(int aCurrent, int aTotal, const wxString &aMessage)
std::mutex m_gitActionMutex
std::vector< wxString > GetBranchNames() const
void updateConnectionType()
GIT_CONN_TYPE GetConnType() const
static wxString GetLastGitError()
wxString GetCurrentBranchName() const
wxString GetGitRootDirectory() const
void SetSSHKey(const wxString &aSSHKey)
static const unsigned KIGIT_CREDENTIAL_SSH_AGENT
int HandlePlaintextAuthentication(git_cred **aOut, const wxString &aUsername)
std::vector< wxString > GetProjectDirs()
Return a vector of project files in the repository.
wxString GetRemoteNameOrDefault() const
Returns GetRemotename() when non-empty, otherwise "origin".
git_repository * GetRepo() const
wxString GetProjectDir() const
Get the project directory path.
wxString GetNextPublicKey()
KIGIT_COMMON(git_repository *aRepo)
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 ...
std::vector< wxString > m_publicKeys
bool HasPushAndPullRemote() const
void UpdateCurrentBranchInfo()
bool HasLocalCommits() const
int HandleSSHAgentAuthentication(git_cred **aOut, const wxString &aUsername)
wxString GetUpstreamShorthand() const
Returns the upstream shorthand for the current branch (e.g.
wxString GetRemotename() const
int HandleSSHKeyAuthentication(git_cred **aOut, const wxString &aUsername)
wxString GetUsername() const
Get the username.
unsigned & TestedTypes()
Return the connection types that have been tested for authentication.
KIGIT_COMMON * GetCommon() const
Get the common object.
KIGIT_COMMON::GIT_CONN_TYPE GetConnType() const
Get the connection type.
const wxChar *const traceGit
Flag to enable Git debugging output.
int fetchhead_foreach_cb(const char *, const char *, const git_oid *aOID, unsigned int aIsMerge, void *aPayload)
int progress_cb(const char *str, int len, void *aPayload)
int push_update_reference_cb(const char *aRefname, const char *aStatus, void *aPayload)
int update_cb(const char *aRefname, const git_oid *aFirst, const git_oid *aSecond, void *aPayload)
int transfer_progress_cb(const git_transfer_progress *aStats, void *aPayload)
int credentials_cb(git_cred **aOut, const char *aUrl, const char *aUsername, unsigned int aAllowedTypes, void *aPayload)
void clone_progress_cb(const char *aStr, size_t aLen, size_t aTotal, void *aPayload)
int push_transfer_progress_cb(unsigned int aCurrent, unsigned int aTotal, size_t aBytes, void *aPayload)
std::unique_ptr< git_tree, decltype([](git_tree *aTree) { git_tree_free(aTree); })> GitTreePtr
A unique pointer for git_tree objects with automatic cleanup.
std::unique_ptr< git_revwalk, decltype([](git_revwalk *aWalker) { git_revwalk_free(aWalker); })> GitRevWalkPtr
A unique pointer for git_revwalk objects with automatic cleanup.
std::unique_ptr< git_commit, decltype([](git_commit *aCommit) { git_commit_free(aCommit); })> GitCommitPtr
A unique pointer for git_commit objects with automatic cleanup.
std::unique_ptr< git_reference, decltype([](git_reference *aRef) { git_reference_free(aRef); })> GitReferencePtr
A unique pointer for git_reference objects with automatic cleanup.
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_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_remote, decltype([](git_remote *aRemote) { git_remote_free(aRemote); })> GitRemotePtr
A unique pointer for git_remote objects with automatic cleanup.
wxString result
Test unit parsing edge cases and error handling.
wxLogTrace helper definitions.