34#include <wx/filename.h>
36#include <wx/textfile.h>
74 wxCHECK(
m_repo, wxEmptyString );
75 git_reference* head =
nullptr;
77 int retval = git_repository_head( &head,
m_repo );
79 if( retval && retval != GIT_EUNBORNBRANCH && retval != GIT_ENOTFOUND )
83 git_reference* branch;
85 if( git_reference_resolve( &branch, head ) )
87 wxLogTrace(
traceGit,
"Failed to resolve branch" );
92 const char* branchName =
"";
94 if( git_branch_name( &branchName, branch ) )
96 wxLogTrace(
traceGit,
"Failed to get branch name" );
100 return wxString( branchName );
128 std::vector<wxString> branchNames;
129 std::map<git_time_t, wxString> branchNamesMap;
132 git_branch_iterator* branchIterator =
nullptr;
134 if( git_branch_iterator_new( &branchIterator,
m_repo, GIT_BRANCH_LOCAL ) )
136 wxLogTrace(
traceGit,
"Failed to get branch iterator" );
141 git_reference* branchReference =
nullptr;
142 git_branch_t branchType;
144 while( git_branch_next( &branchReference, &branchType, branchIterator ) != GIT_ITEROVER )
146 const char* branchName =
"";
149 if( git_branch_name( &branchName, branchReference ) )
151 wxLogTrace(
traceGit,
"Failed to get branch name in iter loop" );
155 const git_oid* commitId = git_reference_target( branchReference );
157 git_commit* commit =
nullptr;
159 if( git_commit_lookup( &commit,
m_repo, commitId ) )
161 wxLogTrace(
traceGit,
"Failed to get commit in iter loop" );
166 git_time_t commitTime = git_commit_time( commit );
168 if( git_branch_is_head( branchReference ) )
169 firstName = branchName;
171 branchNamesMap.emplace( commitTime, branchName );
175 if( !firstName.IsEmpty() )
176 branchNames.push_back( firstName );
179 for(
auto rit = branchNamesMap.rbegin(); rit != branchNamesMap.rend(); ++rit )
180 branchNames.push_back( rit->second );
189 std::vector<wxString> projDirs;
195 if( git_reference_name_to_id( &oid,
m_repo,
"HEAD" ) != GIT_OK )
201 if( git_commit_lookup( &commit,
m_repo, &oid ) != GIT_OK )
209 if( git_commit_tree( &tree, commit ) != GIT_OK )
219 tree, GIT_TREEWALK_PRE,
220 [](
const char* root,
const git_tree_entry* entry,
void* payload )
222 std::vector<wxString>* prjs =
static_cast<std::vector<wxString>*
>( payload );
223 wxFileName root_fn( git_tree_entry_name( entry ) );
225 root_fn.SetPath( root );
227 if( git_tree_entry_type( entry ) == GIT_OBJECT_BLOB
228 && ( ( root_fn.GetExt() ==
"kicad_pro" ) || ( root_fn.GetExt() ==
"pro" ) ) )
230 prjs->push_back( root_fn.GetFullPath() );
237 std::sort( projDirs.begin(), projDirs.end(),
238 [](
const wxString& a,
const wxString& b )
240 int a_freq = a.Freq( wxFileName::GetPathSeparator() );
241 int b_freq = b.Freq( wxFileName::GetPathSeparator() );
243 if( a_freq == b_freq )
246 return a_freq < b_freq;
256 auto get_modified_files = [&](
const git_oid* from_oid,
const git_oid* to_oid ) -> std::set<wxString>
258 std::set<wxString> modified_set;
259 git_revwalk* walker =
nullptr;
264 if( git_revwalk_new( &walker,
m_repo ) != GIT_OK )
272 if( git_revwalk_push( walker, from_oid ) != GIT_OK )
278 if( to_oid && git_revwalk_hide( walker, to_oid ) != GIT_OK )
287 while( git_revwalk_next( &oid, walker ) == GIT_OK )
293 if( git_commit_lookup( &commit,
m_repo, &oid ) != GIT_OK )
300 git_tree *tree, *parent_tree =
nullptr;
302 if( git_commit_tree( &tree, commit ) != GIT_OK )
311 if( !git_commit_parentcount( commit ) )
314 tree, GIT_TREEWALK_PRE,
315 [](
const char* root,
const git_tree_entry* entry,
void* payload )
317 std::set<wxString>* modified_set_internal =
static_cast<std::set<wxString>*
>( payload );
318 wxString filePath = wxString::Format(
"%s%s", root, git_tree_entry_name( entry ) );
319 modified_set_internal->insert( std::move( filePath ) );
328 if( git_commit_parent( &parent, commit, 0 ) != GIT_OK )
337 if( git_commit_tree( &parent_tree, parent ) != GIT_OK )
347 git_diff_options diff_opts;
348 git_diff_init_options( &diff_opts, GIT_DIFF_OPTIONS_VERSION );
350 if( !
m_repo || !parent_tree || !tree )
353 if( git_diff_tree_to_tree( &diff,
m_repo, parent_tree, tree, &diff_opts ) == GIT_OK )
355 size_t num_deltas = git_diff_num_deltas( diff );
357 for(
size_t i = 0; i < num_deltas; ++i )
359 const git_diff_delta*
delta = git_diff_get_delta( diff, i );
360 modified_set.insert(
delta->new_file.path );
363 git_diff_free( diff );
376 std::pair<std::set<wxString>,std::set<wxString>> modified_files;
379 return modified_files;
381 git_reference* head =
nullptr;
382 git_reference* remote_head =
nullptr;
384 if( git_repository_head( &head,
m_repo ) != GIT_OK )
386 wxLogTrace(
traceGit,
"Failed to get modified HEAD" );
387 return modified_files;
392 if( git_branch_upstream( &remote_head, head ) != GIT_OK )
394 wxLogTrace(
traceGit,
"Failed to get modified remote HEAD" );
399 if( remote_head !=
nullptr && head !=
nullptr )
401 const git_oid* head_oid = git_reference_target( head );
402 const git_oid* remote_oid = git_reference_target( remote_head );
404 modified_files.first = get_modified_files( head_oid, remote_oid );
405 modified_files.second = get_modified_files( remote_oid, head_oid );
408 return modified_files;
417 git_reference* head =
nullptr;
418 git_reference* remote_head =
nullptr;
420 if( git_repository_head( &head,
m_repo ) != GIT_OK )
428 if( git_branch_upstream( &remote_head, head ) != GIT_OK )
436 const git_oid* head_oid = git_reference_target( head );
437 const git_oid* remote_oid = git_reference_target( remote_head );
438 git_revwalk* walker =
nullptr;
440 if( git_revwalk_new( &walker,
m_repo ) != GIT_OK )
448 if( !head_oid || git_revwalk_push( walker, head_oid ) != GIT_OK )
454 if( remote_oid && git_revwalk_hide( walker, remote_oid ) != GIT_OK )
463 if( git_revwalk_next( &oid, walker ) != GIT_OK )
476 git_remote* remote =
nullptr;
478 if( git_remote_lookup( &remote,
m_repo,
"origin" ) != GIT_OK )
480 wxLogTrace(
traceGit,
"Failed to get remote for haspushpull" );
487 const char* fetch_url = git_remote_url( remote );
488 const char* push_url = git_remote_pushurl( remote );
493 wxLogTrace(
traceGit,
"No push URL set, using fetch URL" );
494 push_url = fetch_url;
497 return fetch_url && push_url;
503 wxCHECK(
m_repo, wxEmptyString );
506 git_reference* head =
nullptr;
507 git_reference* upstream =
nullptr;
509 if( git_repository_head( &head,
m_repo ) != GIT_OK )
517 if( git_branch_upstream( &upstream, head ) != GIT_OK )
520 git_strarray remotes = {
nullptr, 0 };
522 if( git_remote_list( &remotes,
m_repo ) == GIT_OK )
524 if( remotes.count == 1 )
525 retval = remotes.strings[0];
527 git_strarray_dispose( &remotes );
536 git_remote* remote =
nullptr;
538 if( git_remote_lookup( &remote,
m_repo,
"origin" ) == GIT_OK )
540 retval = git_remote_name( remote );
541 git_remote_free( remote );
545 wxLogTrace(
traceGit,
"Failed to get remote name from default remote: %s",
554 git_buf remote_name = GIT_BUF_INIT_CONST(
nullptr, 0 );
556 if( git_branch_remote_name( &remote_name,
m_repo, git_reference_name( upstream ) ) == GIT_OK )
558 retval = remote_name.ptr;
559 git_buf_dispose( &remote_name );
564 "Failed to get remote name from upstream branch: %s",
585 return wxEmptyString;
587 const char *
path = git_repository_path(
m_repo );
588 wxString retval =
path;
597 wxFileName keyFile( wxGetHomeDir(), wxEmptyString );
598 keyFile.AppendDir(
".ssh" );
599 keyFile.SetFullName(
"id_rsa" );
601 if( keyFile.FileExists() )
604 keyFile.SetFullName(
"id_dsa" );
606 if( keyFile.FileExists() )
609 keyFile.SetFullName(
"id_ecdsa" );
611 if( keyFile.FileExists() )
614 keyFile.SetFullName(
"id_ed25519" );
616 if( keyFile.FileExists() )
620 wxFileName sshConfig( wxGetHomeDir(), wxEmptyString );
621 sshConfig.AppendDir(
".ssh" );
622 sshConfig.SetFullName(
"config" );
624 if( sshConfig.FileExists() )
626 wxTextFile configFile( sshConfig.GetFullPath() );
631 for( wxString line = configFile.GetFirstLine(); !configFile.Eof(); line = configFile.GetNextLine() )
633 line.Trim(
false ).Trim(
true );
635 if( line.StartsWith(
"Host " ) )
640 if( line.StartsWith(
"Host" ) && line.Contains(
m_hostname ) )
643 if( match && line.StartsWith(
"IdentityFile" ) )
645 wxString keyPath = line.AfterFirst(
' ' ).Trim(
false ).Trim(
true );
648 if( keyPath.StartsWith(
"~" ) )
649 keyPath.Replace(
"~", wxGetHomeDir(),
false );
652 if( wxFileName::FileExists( keyPath ) )
670 git_remote* remote =
nullptr;
676 if( git_remote_lookup( &remote,
m_repo, remote_name.ToStdString().c_str() ) == GIT_OK )
678 const char* url = git_remote_url( remote );
683 git_remote_free( remote );
694 if( remote.IsEmpty() )
697 if( remote.StartsWith(
"https://" ) || remote.StartsWith(
"http://" ) )
701 else if( remote.StartsWith(
"ssh://" ) || remote.StartsWith(
"git@" ) || remote.StartsWith(
"git+ssh://" )
702 || remote.EndsWith(
".git" ) )
722 size_t atPos = uri.find(
'@' );
724 if( atPos != wxString::npos )
726 size_t protoEnd = uri.find(
"//" );
728 if( protoEnd != wxString::npos )
730 wxString credentials = uri.Mid( protoEnd + 2, atPos - protoEnd - 2 );
731 size_t colonPos = credentials.find(
':' );
733 if( colonPos != wxString::npos )
736 m_password = credentials.Mid( colonPos + 1, credentials.Length() - colonPos - 1 );
752 size_t colonPos =
m_remote.find(
':' );
753 if( colonPos != wxString::npos )
759 size_t hostStart =
m_remote.find(
"://" ) + 2;
760 size_t hostEnd =
m_remote.find(
'/', hostStart );
763 if( hostEnd != wxString::npos )
764 host =
m_remote.Mid( hostStart, hostEnd - hostStart );
768 atPos = host.find(
'@' );
770 if( atPos != wxString::npos )
789 if( sshKey.IsEmpty() )
791 wxLogTrace(
traceGit,
"Finished testing all possible ssh keys" );
793 return GIT_PASSTHROUGH;
796 wxString sshPubKey = sshKey +
".pub";
799 wxLogTrace(
traceGit,
"Testing %s\n", sshKey );
801 if( git_credential_ssh_key_new( aOut, aUsername.mbc_str(), sshPubKey.mbc_str(), sshKey.mbc_str(),
802 password.mbc_str() ) != GIT_OK )
804 wxLogTrace(
traceGit,
"Failed to create SSH key credential for %s: %s",
806 return GIT_PASSTHROUGH;
817 git_credential_userpass_plaintext_new( aOut, aUsername.mbc_str(), password.mbc_str() );
825 if( git_credential_ssh_key_from_agent( aOut, aUsername.mbc_str() ) != GIT_OK )
827 wxLogTrace(
traceGit,
"Failed to create SSH agent credential for %s: %s",
829 return GIT_PASSTHROUGH;
838 const git_oid* aOID,
unsigned int aIsMerge,
void* aPayload )
841 git_oid_cpy( (git_oid*) aPayload, aOID );
847extern "C" void clone_progress_cb(
const char* aStr,
size_t aLen,
size_t aTotal,
void* aPayload )
851 wxString progressMessage( aStr );
856extern "C" int progress_cb(
const char* str,
int len,
void* aPayload )
862 wxLogTrace(
traceGit,
"Progress CB cancelled" );
866 wxString progressMessage( str, len );
877 wxString progressMessage = wxString::Format(
_(
"Received %u of %u objects" ),
878 aStats->received_objects,
879 aStats->total_objects );
882 wxLogTrace(
traceGit,
"Transfer progress cancelled" );
886 parent->
UpdateProgress( aStats->received_objects, aStats->total_objects, progressMessage );
892extern "C" int update_cb(
const char* aRefname,
const git_oid* aFirst,
const git_oid* aSecond,
895 constexpr int cstring_len = 8;
896 char a_str[cstring_len + 1];
897 char b_str[cstring_len + 1];
902 git_oid_tostr( b_str, cstring_len, aSecond );
904#if ( LIBGIT2_VER_MAJOR >= 1 ) || ( LIBGIT2_VER_MINOR >= 99 )
905 if( !git_oid_is_zero( aFirst ) )
907 if( !git_oid_iszero( aFirst ) )
910 git_oid_tostr( a_str, cstring_len, aFirst );
911 status = wxString::Format(
_(
"* [updated] %s..%s %s" ), a_str, b_str, aRefname );
915 status = wxString::Format(
_(
"* [new] %s %s" ), b_str, aRefname );
927 long long progress = 100;
932 progress = ( aCurrent * 100ll ) / aTotal;
935 wxString progressMessage = wxString::Format(
_(
"Writing objects: %lld%% (%u/%u), %zu bytes" ),
936 progress, aCurrent, aTotal, aBytes );
946 wxString status( aStatus );
948 if( !status.IsEmpty() )
950 wxString statusMessage = wxString::Format(
_(
"* [rejected] %s (%s)" ), aRefname, aStatus );
955 wxString statusMessage = wxString::Format(
_(
"[updated] %s" ), aRefname );
963extern "C" int credentials_cb( git_cred** aOut,
const char* aUrl,
const char* aUsername,
964 unsigned int aAllowedTypes,
void* aPayload )
969 wxLogTrace(
traceGit,
"Credentials callback for %s, testing %d", aUrl, aAllowedTypes );
973 wxLogTrace(
traceGit,
"Local repository, no credentials needed" );
974 return GIT_PASSTHROUGH;
977 if( aAllowedTypes & GIT_CREDENTIAL_USERNAME
978 && !( parent->
TestedTypes() & GIT_CREDENTIAL_USERNAME ) )
980 wxString username = parent->
GetUsername().Trim().Trim(
false );
981 wxLogTrace(
traceGit,
"Username credential for %s at %s with allowed type %d",
982 username, aUrl, aAllowedTypes );
983 if( git_credential_username_new( aOut, username.ToStdString().c_str() ) != GIT_OK )
985 wxLogTrace(
traceGit,
"Failed to create username credential for %s: %s",
990 wxLogTrace(
traceGit,
"Created username credential for %s", username );
996 && ( aAllowedTypes & GIT_CREDENTIAL_USERPASS_PLAINTEXT )
997 && !( parent->
TestedTypes() & GIT_CREDENTIAL_USERPASS_PLAINTEXT ) )
1000 wxLogTrace(
traceGit,
"Plaintext authentication for %s at %s with allowed type %d",
1005 && ( aAllowedTypes & GIT_CREDENTIAL_SSH_KEY )
1006 && !( parent->
TestedTypes() & GIT_CREDENTIAL_SSH_KEY ) )
1016 return GIT_PASSTHROUGH;
1019 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 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.