34#include <wx/filename.h>
36#include <wx/textfile.h>
81 const char* workdir = git_repository_workdir(
m_repo );
84 return wxString( workdir );
93 wxCHECK(
m_repo, wxEmptyString );
94 git_reference* head =
nullptr;
96 int retval = git_repository_head( &head,
m_repo );
98 if( retval && retval != GIT_EUNBORNBRANCH && retval != GIT_ENOTFOUND )
102 git_reference* branch;
104 if( git_reference_resolve( &branch, head ) )
106 wxLogTrace(
traceGit,
"Failed to resolve branch" );
107 return wxEmptyString;
111 const char* branchName =
"";
113 if( git_branch_name( &branchName, branch ) )
115 wxLogTrace(
traceGit,
"Failed to get branch name" );
116 return wxEmptyString;
119 return wxString( branchName );
147 std::vector<wxString> branchNames;
148 std::map<git_time_t, wxString> branchNamesMap;
151 git_branch_iterator* branchIterator =
nullptr;
153 if( git_branch_iterator_new( &branchIterator,
m_repo, GIT_BRANCH_LOCAL ) )
155 wxLogTrace(
traceGit,
"Failed to get branch iterator" );
160 git_reference* branchReference =
nullptr;
161 git_branch_t branchType;
163 while( git_branch_next( &branchReference, &branchType, branchIterator ) != GIT_ITEROVER )
165 const char* branchName =
"";
168 if( git_branch_name( &branchName, branchReference ) )
170 wxLogTrace(
traceGit,
"Failed to get branch name in iter loop" );
174 const git_oid* commitId = git_reference_target( branchReference );
176 git_commit* commit =
nullptr;
178 if( git_commit_lookup( &commit,
m_repo, commitId ) )
180 wxLogTrace(
traceGit,
"Failed to get commit in iter loop" );
185 git_time_t commitTime = git_commit_time( commit );
187 if( git_branch_is_head( branchReference ) )
188 firstName = branchName;
190 branchNamesMap.emplace( commitTime, branchName );
194 if( !firstName.IsEmpty() )
195 branchNames.push_back( firstName );
198 for(
auto rit = branchNamesMap.rbegin(); rit != branchNamesMap.rend(); ++rit )
199 branchNames.push_back( rit->second );
208 std::vector<wxString> projDirs;
214 if( git_reference_name_to_id( &oid,
m_repo,
"HEAD" ) != GIT_OK )
220 if( git_commit_lookup( &commit,
m_repo, &oid ) != GIT_OK )
228 if( git_commit_tree( &tree, commit ) != GIT_OK )
238 tree, GIT_TREEWALK_PRE,
239 [](
const char* root,
const git_tree_entry* entry,
void* payload )
241 std::vector<wxString>* prjs =
static_cast<std::vector<wxString>*
>( payload );
242 wxFileName root_fn( git_tree_entry_name( entry ) );
244 root_fn.SetPath( root );
246 if( git_tree_entry_type( entry ) == GIT_OBJECT_BLOB
247 && ( ( root_fn.GetExt() ==
"kicad_pro" ) || ( root_fn.GetExt() ==
"pro" ) ) )
249 prjs->push_back( root_fn.GetFullPath() );
256 std::sort( projDirs.begin(), projDirs.end(),
257 [](
const wxString& a,
const wxString& b )
259 int a_freq = a.Freq( wxFileName::GetPathSeparator() );
260 int b_freq = b.Freq( wxFileName::GetPathSeparator() );
262 if( a_freq == b_freq )
265 return a_freq < b_freq;
275 auto get_modified_files = [&](
const git_oid* from_oid,
const git_oid* to_oid ) -> std::set<wxString>
277 std::set<wxString> modified_set;
278 git_revwalk* walker =
nullptr;
283 if( git_revwalk_new( &walker,
m_repo ) != GIT_OK )
291 if( git_revwalk_push( walker, from_oid ) != GIT_OK )
297 if( to_oid && git_revwalk_hide( walker, to_oid ) != GIT_OK )
306 while( git_revwalk_next( &oid, walker ) == GIT_OK )
312 if( git_commit_lookup( &commit,
m_repo, &oid ) != GIT_OK )
319 git_tree *tree, *parent_tree =
nullptr;
321 if( git_commit_tree( &tree, commit ) != GIT_OK )
330 if( !git_commit_parentcount( commit ) )
333 tree, GIT_TREEWALK_PRE,
334 [](
const char* root,
const git_tree_entry* entry,
void* payload )
336 std::set<wxString>* modified_set_internal =
static_cast<std::set<wxString>*
>( payload );
337 wxString filePath = wxString::Format(
"%s%s", root, git_tree_entry_name( entry ) );
338 modified_set_internal->insert( std::move( filePath ) );
347 if( git_commit_parent( &parent, commit, 0 ) != GIT_OK )
356 if( git_commit_tree( &parent_tree, parent ) != GIT_OK )
366 git_diff_options diff_opts;
367 git_diff_init_options( &diff_opts, GIT_DIFF_OPTIONS_VERSION );
369 if( !
m_repo || !parent_tree || !tree )
372 if( git_diff_tree_to_tree( &diff,
m_repo, parent_tree, tree, &diff_opts ) == GIT_OK )
374 size_t num_deltas = git_diff_num_deltas( diff );
376 for(
size_t i = 0; i < num_deltas; ++i )
378 const git_diff_delta*
delta = git_diff_get_delta( diff, i );
379 modified_set.insert(
delta->new_file.path );
382 git_diff_free( diff );
395 std::pair<std::set<wxString>,std::set<wxString>> modified_files;
398 return modified_files;
400 git_reference* head =
nullptr;
401 git_reference* remote_head =
nullptr;
403 if( git_repository_head( &head,
m_repo ) != GIT_OK )
405 wxLogTrace(
traceGit,
"Failed to get modified HEAD" );
406 return modified_files;
411 if( git_branch_upstream( &remote_head, head ) != GIT_OK )
413 wxLogTrace(
traceGit,
"Failed to get modified remote HEAD" );
418 if( remote_head !=
nullptr && head !=
nullptr )
420 const git_oid* head_oid = git_reference_target( head );
421 const git_oid* remote_oid = git_reference_target( remote_head );
423 modified_files.first = get_modified_files( head_oid, remote_oid );
424 modified_files.second = get_modified_files( remote_oid, head_oid );
427 return modified_files;
436 git_reference* head =
nullptr;
437 git_reference* remote_head =
nullptr;
439 if( git_repository_head( &head,
m_repo ) != GIT_OK )
447 if( git_branch_upstream( &remote_head, head ) != GIT_OK )
455 const git_oid* head_oid = git_reference_target( head );
456 const git_oid* remote_oid = git_reference_target( remote_head );
457 git_revwalk* walker =
nullptr;
459 if( git_revwalk_new( &walker,
m_repo ) != GIT_OK )
467 if( !head_oid || git_revwalk_push( walker, head_oid ) != GIT_OK )
473 if( remote_oid && git_revwalk_hide( walker, remote_oid ) != GIT_OK )
482 if( git_revwalk_next( &oid, walker ) != GIT_OK )
495 git_remote* remote =
nullptr;
497 if( git_remote_lookup( &remote,
m_repo,
"origin" ) != GIT_OK )
499 wxLogTrace(
traceGit,
"Failed to get remote for haspushpull" );
506 const char* fetch_url = git_remote_url( remote );
507 const char* push_url = git_remote_pushurl( remote );
512 wxLogTrace(
traceGit,
"No push URL set, using fetch URL" );
513 push_url = fetch_url;
516 return fetch_url && push_url;
522 wxCHECK(
m_repo, wxEmptyString );
525 git_reference* head =
nullptr;
526 git_reference* upstream =
nullptr;
528 if( git_repository_head( &head,
m_repo ) != GIT_OK )
536 if( git_branch_upstream( &upstream, head ) != GIT_OK )
539 git_strarray remotes = {
nullptr, 0 };
541 if( git_remote_list( &remotes,
m_repo ) == GIT_OK )
543 if( remotes.count == 1 )
544 retval = remotes.strings[0];
546 git_strarray_dispose( &remotes );
555 git_remote* remote =
nullptr;
557 if( git_remote_lookup( &remote,
m_repo,
"origin" ) == GIT_OK )
559 retval = git_remote_name( remote );
560 git_remote_free( remote );
564 wxLogTrace(
traceGit,
"Failed to get remote name from default remote: %s",
573 git_buf remote_name = GIT_BUF_INIT_CONST(
nullptr, 0 );
575 if( git_branch_remote_name( &remote_name,
m_repo, git_reference_name( upstream ) ) == GIT_OK )
577 retval = remote_name.ptr;
578 git_buf_dispose( &remote_name );
583 "Failed to get remote name from upstream branch: %s",
604 return wxEmptyString;
606 const char *
path = git_repository_path(
m_repo );
607 wxString retval =
path;
616 wxFileName keyFile( wxGetHomeDir(), wxEmptyString );
617 keyFile.AppendDir(
".ssh" );
618 keyFile.SetFullName(
"id_rsa" );
620 if( keyFile.FileExists() )
623 keyFile.SetFullName(
"id_dsa" );
625 if( keyFile.FileExists() )
628 keyFile.SetFullName(
"id_ecdsa" );
630 if( keyFile.FileExists() )
633 keyFile.SetFullName(
"id_ed25519" );
635 if( keyFile.FileExists() )
639 wxFileName sshConfig( wxGetHomeDir(), wxEmptyString );
640 sshConfig.AppendDir(
".ssh" );
641 sshConfig.SetFullName(
"config" );
643 if( sshConfig.FileExists() )
645 wxTextFile configFile( sshConfig.GetFullPath() );
650 for( wxString line = configFile.GetFirstLine(); !configFile.Eof(); line = configFile.GetNextLine() )
652 line.Trim(
false ).Trim(
true );
654 if( line.StartsWith(
"Host " ) )
659 if( line.StartsWith(
"Host" ) && line.Contains(
m_hostname ) )
662 if( match && line.StartsWith(
"IdentityFile" ) )
664 wxString keyPath = line.AfterFirst(
' ' ).Trim(
false ).Trim(
true );
667 if( keyPath.StartsWith(
"~" ) )
668 keyPath.Replace(
"~", wxGetHomeDir(),
false );
671 if( wxFileName::FileExists( keyPath ) )
689 git_remote* remote =
nullptr;
695 if( git_remote_lookup( &remote,
m_repo, remote_name.ToStdString().c_str() ) == GIT_OK )
697 const char* url = git_remote_url( remote );
702 git_remote_free( remote );
713 if( remote.IsEmpty() )
716 if( remote.StartsWith(
"https://" ) || remote.StartsWith(
"http://" ) )
720 else if( remote.StartsWith(
"ssh://" ) || remote.StartsWith(
"git@" ) || remote.StartsWith(
"git+ssh://" )
721 || remote.EndsWith(
".git" ) )
741 size_t atPos = uri.find(
'@' );
743 if( atPos != wxString::npos )
745 size_t protoEnd = uri.find(
"//" );
747 if( protoEnd != wxString::npos )
749 wxString credentials = uri.Mid( protoEnd + 2, atPos - protoEnd - 2 );
750 size_t colonPos = credentials.find(
':' );
752 if( colonPos != wxString::npos )
755 m_password = credentials.Mid( colonPos + 1, credentials.Length() - colonPos - 1 );
771 size_t colonPos =
m_remote.find(
':' );
772 if( colonPos != wxString::npos )
778 size_t hostStart =
m_remote.find(
"://" ) + 2;
779 size_t hostEnd =
m_remote.find(
'/', hostStart );
782 if( hostEnd != wxString::npos )
783 host =
m_remote.Mid( hostStart, hostEnd - hostStart );
787 atPos = host.find(
'@' );
789 if( atPos != wxString::npos )
808 if( sshKey.IsEmpty() )
810 wxLogTrace(
traceGit,
"Finished testing all possible ssh keys" );
812 return GIT_PASSTHROUGH;
815 wxString sshPubKey = sshKey +
".pub";
818 wxLogTrace(
traceGit,
"Testing %s\n", sshKey );
820 if( git_credential_ssh_key_new( aOut, aUsername.mbc_str(), sshPubKey.mbc_str(), sshKey.mbc_str(),
821 password.mbc_str() ) != GIT_OK )
823 wxLogTrace(
traceGit,
"Failed to create SSH key credential for %s: %s",
825 return GIT_PASSTHROUGH;
836 git_credential_userpass_plaintext_new( aOut, aUsername.mbc_str(), password.mbc_str() );
844 if( git_credential_ssh_key_from_agent( aOut, aUsername.mbc_str() ) != GIT_OK )
846 wxLogTrace(
traceGit,
"Failed to create SSH agent credential for %s: %s",
848 return GIT_PASSTHROUGH;
857 const git_oid* aOID,
unsigned int aIsMerge,
void* aPayload )
860 git_oid_cpy( (git_oid*) aPayload, aOID );
866extern "C" void clone_progress_cb(
const char* aStr,
size_t aLen,
size_t aTotal,
void* aPayload )
870 wxString progressMessage( aStr );
875extern "C" int progress_cb(
const char* str,
int len,
void* aPayload )
881 wxLogTrace(
traceGit,
"Progress CB cancelled" );
885 wxString progressMessage( str, len );
896 wxString progressMessage = wxString::Format(
_(
"Received %u of %u objects" ),
897 aStats->received_objects,
898 aStats->total_objects );
901 wxLogTrace(
traceGit,
"Transfer progress cancelled" );
905 parent->
UpdateProgress( aStats->received_objects, aStats->total_objects, progressMessage );
911extern "C" int update_cb(
const char* aRefname,
const git_oid* aFirst,
const git_oid* aSecond,
914 constexpr int cstring_len = 8;
915 char a_str[cstring_len + 1];
916 char b_str[cstring_len + 1];
921 git_oid_tostr( b_str, cstring_len, aSecond );
923#if ( LIBGIT2_VER_MAJOR >= 1 ) || ( LIBGIT2_VER_MINOR >= 99 )
924 if( !git_oid_is_zero( aFirst ) )
926 if( !git_oid_iszero( aFirst ) )
929 git_oid_tostr( a_str, cstring_len, aFirst );
930 status = wxString::Format(
_(
"* [updated] %s..%s %s" ), a_str, b_str, aRefname );
934 status = wxString::Format(
_(
"* [new] %s %s" ), b_str, aRefname );
946 long long progress = 100;
951 progress = ( aCurrent * 100ll ) / aTotal;
954 wxString progressMessage = wxString::Format(
_(
"Writing objects: %lld%% (%u/%u), %zu bytes" ),
955 progress, aCurrent, aTotal, aBytes );
965 wxString status( aStatus );
967 if( !status.IsEmpty() )
969 wxString statusMessage = wxString::Format(
_(
"* [rejected] %s (%s)" ), aRefname, aStatus );
974 wxString statusMessage = wxString::Format(
_(
"[updated] %s" ), aRefname );
982extern "C" int credentials_cb( git_cred** aOut,
const char* aUrl,
const char* aUsername,
983 unsigned int aAllowedTypes,
void* aPayload )
988 wxLogTrace(
traceGit,
"Credentials callback for %s, testing %d", aUrl, aAllowedTypes );
992 wxLogTrace(
traceGit,
"Local repository, no credentials needed" );
993 return GIT_PASSTHROUGH;
996 if( aAllowedTypes & GIT_CREDENTIAL_USERNAME
997 && !( parent->
TestedTypes() & GIT_CREDENTIAL_USERNAME ) )
999 wxString username = parent->
GetUsername().Trim().Trim(
false );
1000 wxLogTrace(
traceGit,
"Username credential for %s at %s with allowed type %d",
1001 username, aUrl, aAllowedTypes );
1002 if( git_credential_username_new( aOut, username.ToStdString().c_str() ) != GIT_OK )
1004 wxLogTrace(
traceGit,
"Failed to create username credential for %s: %s",
1009 wxLogTrace(
traceGit,
"Created username credential for %s", username );
1015 && ( aAllowedTypes & GIT_CREDENTIAL_USERPASS_PLAINTEXT )
1016 && !( parent->
TestedTypes() & GIT_CREDENTIAL_USERPASS_PLAINTEXT ) )
1019 wxLogTrace(
traceGit,
"Plaintext authentication for %s at %s with allowed type %d",
1024 && ( aAllowedTypes & GIT_CREDENTIAL_SSH_KEY )
1025 && !( parent->
TestedTypes() & GIT_CREDENTIAL_SSH_KEY ) )
1035 return GIT_PASSTHROUGH;
1038 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.
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 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_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.
wxLogTrace helper definitions.