KiCad PCB EDA Suite
Loading...
Searching...
No Matches
git_pull_handler.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 (C) 2023 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, you may find one here:
18 * http://www.gnu.org/licenses/gpl-3.0.html
19 * or you may search the http://www.gnu.org website for the version 3 license,
20 * or you may write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 */
23
24#include "git_pull_handler.h"
26
27#include <wx/log.h>
28
29#include <iostream>
30#include <time.h>
31
32GIT_PULL_HANDLER::GIT_PULL_HANDLER( git_repository* aRepo ) : KIGIT_COMMON( aRepo )
33{}
34
36{}
37
38
40{
41 // Fetch updates from remote repository
42 git_remote* remote = nullptr;
43
44 if( git_remote_lookup( &remote, m_repo, "origin" ) != 0 )
45 {
46 AddErrorString( wxString::Format( _( "Could not lookup remote '%s'" ), "origin" ).ToStdString() );
47 return false;
48 }
49
50 git_remote_callbacks remoteCallbacks = GIT_REMOTE_CALLBACKS_INIT;
51 remoteCallbacks.sideband_progress = progress_cb;
52 remoteCallbacks.transfer_progress = transfer_progress_cb;
53 remoteCallbacks.credentials = credentials_cb;
54 remoteCallbacks.payload = this;
55
56 if( git_remote_connect( remote, GIT_DIRECTION_FETCH, &remoteCallbacks, nullptr, nullptr ) )
57 {
58 git_remote_free( remote );
59 AddErrorString( wxString::Format( _( "Could not connect to remote '%s'" ), "origin" ).ToStdString() );
60 return false;
61 }
62
63 git_fetch_options fetchOptions = GIT_FETCH_OPTIONS_INIT;
64 fetchOptions.callbacks = remoteCallbacks;
65
66 if( git_remote_fetch( remote, nullptr, &fetchOptions, nullptr ) )
67 {
68 git_remote_free( remote );
69 AddErrorString( wxString::Format( _( "Could not fetch data from remote '%s'" ), "origin" ) );
70 return false;
71 }
72
73 git_remote_free( remote );
74
75 return true;
76}
77
78
80{
81 PullResult result = PullResult::Success;
82
83 if( !PerformFetch() )
84 return PullResult::Error;
85
86 git_oid pull_merge_oid = {};
87
88 if( git_repository_fetchhead_foreach( m_repo, fetchhead_foreach_cb, &pull_merge_oid ) )
89 {
90 AddErrorString( _( "Could not read 'FETCH_HEAD'" ) );
91 return PullResult::Error;
92 }
93
94 git_annotated_commit* fetchhead_commit;
95
96 if( git_annotated_commit_lookup( &fetchhead_commit, m_repo, &pull_merge_oid ) )
97 {
98 AddErrorString( _( "Could not lookup commit" ) );
99 return PullResult::Error;
100 }
101
102 const git_annotated_commit* merge_commits[] = { fetchhead_commit };
103 git_merge_analysis_t merge_analysis;
104 git_merge_preference_t merge_preference = GIT_MERGE_PREFERENCE_NONE;
105
106 if( git_merge_analysis( &merge_analysis, &merge_preference, m_repo, merge_commits, 1 ) )
107 {
108 AddErrorString( _( "Could not analyze merge" ) );
109 git_annotated_commit_free( fetchhead_commit );
110 return PullResult::Error;
111 }
112
113 if( !( merge_analysis & GIT_MERGE_ANALYSIS_NORMAL ) )
114 git_annotated_commit_free( fetchhead_commit );
115
116 if( merge_analysis & GIT_MERGE_ANALYSIS_UNBORN )
117 {
118 AddErrorString( _( "Invalid HEAD. Cannot merge." ) );
119 return PullResult::MergeFailed;
120 }
121
122 // Nothing to do if the repository is up to date
123 if( merge_analysis & GIT_MERGE_ANALYSIS_UP_TO_DATE )
124 {
125 git_repository_state_cleanup( m_repo );
126 return PullResult::UpToDate;
127 }
128
129 // Fast-forward is easy, just update the local reference
130 if( merge_analysis & GIT_MERGE_ANALYSIS_FASTFORWARD )
131 {
132 return handleFastForward();
133 }
134
135 if( merge_analysis & GIT_MERGE_ANALYSIS_NORMAL )
136 {
137 PullResult ret = handleMerge( merge_commits, 1 );
138 git_annotated_commit_free( fetchhead_commit );
139 return ret;
140 }
141
142 //TODO: handle merges when they need to be resolved
143
144 return result;
145}
146
147const std::vector<std::pair<std::string, std::vector<CommitDetails>>>& GIT_PULL_HANDLER::GetFetchResults() const {
148 return m_fetchResults;
149}
150
151std::string GIT_PULL_HANDLER::getFirstLineFromCommitMessage( const std::string& aMessage )
152{
153 size_t firstLineEnd = aMessage.find_first_of( '\n' );
154
155 if( firstLineEnd != std::string::npos )
156 return aMessage.substr( 0, firstLineEnd );
157
158 return aMessage;
159}
160
161std::string GIT_PULL_HANDLER::getFormattedCommitDate( const git_time& aTime )
162{
163 char dateBuffer[64];
164 time_t time = static_cast<time_t>( aTime.time );
165 strftime( dateBuffer, sizeof( dateBuffer ), "%Y-%b-%d %H:%M:%S", gmtime( &time ) );
166 return dateBuffer;
167}
168
169
171{
172 // Update local references with fetched data
173 git_reference* updatedRef = nullptr;
174
175 if( git_repository_head( &updatedRef, m_repo ) )
176 {
177 AddErrorString( _( "Could not get repository head" ) );
178 return PullResult::Error;
179 }
180
181 const char* updatedRefName = git_reference_name( updatedRef );
182 git_reference_free( updatedRef );
183
184 git_oid updatedRefOid;
185 if( git_reference_name_to_id( &updatedRefOid, m_repo, updatedRefName ) )
186 {
187 AddErrorString( wxString::Format( _( "Could not get reference OID for reference '%s'" ), updatedRefName ) );
188 return PullResult::Error;
189 }
190
191 git_checkout_options checkoutOptions = GIT_CHECKOUT_OPTIONS_INIT;
192 checkoutOptions.checkout_strategy = GIT_CHECKOUT_SAFE;
193 if( git_checkout_head( m_repo, &checkoutOptions ) )
194 {
195 AddErrorString( _( "Failed to perform checkout operation." ) );
196 return PullResult::Error;
197 }
198
199 // Collect commit details for updated references
200 git_revwalk* revWalker = nullptr;
201 git_revwalk_new( &revWalker, m_repo );
202 git_revwalk_sorting( revWalker, GIT_SORT_TIME );
203 git_revwalk_push_glob( revWalker, updatedRefName );
204
205 git_oid commitOid;
206 while( git_revwalk_next( &commitOid, revWalker ) == 0 )
207 {
208 git_commit* commit = nullptr;
209
210 if( git_commit_lookup( &commit, m_repo, &commitOid ) )
211 {
212 AddErrorString( wxString::Format( _( "Could not lookup commit '{}'" ), git_oid_tostr_s( &commitOid ) ) );
213 git_revwalk_free( revWalker );
214 return PullResult::Error;
215 }
216
217 CommitDetails details;
218 details.m_sha = git_oid_tostr_s( &commitOid );
219 details.m_firstLine = getFirstLineFromCommitMessage( git_commit_message( commit ) );
220 details.m_author = git_commit_author( commit )->name;
221 details.m_date = getFormattedCommitDate( git_commit_author( commit )->when );
222
223 std::pair<std::string, std::vector<CommitDetails>>& branchCommits =
224 m_fetchResults.emplace_back();
225 branchCommits.first = updatedRefName;
226 branchCommits.second.push_back( details );
227
228 //TODO: log these to the parent
229 git_commit_free( commit );
230 }
231
232 git_revwalk_free( revWalker );
233
234 git_repository_state_cleanup( m_repo );
235 return PullResult::FastForward;
236}
237
238
239PullResult GIT_PULL_HANDLER::handleMerge( const git_annotated_commit** aMergeHeads,
240 size_t aMergeHeadsCount )
241{
242 git_merge_options merge_opts = GIT_MERGE_OPTIONS_INIT;
243 git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT;
244
245 checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE;
246
247 if( git_merge( m_repo, aMergeHeads, aMergeHeadsCount, &merge_opts, &checkout_opts ) )
248 {
249 AddErrorString( _( "Could not merge commits" ) );
250 return PullResult::Error;
251 }
252
253 // Get the repository index
254 git_index* index = nullptr;
255 if( git_repository_index( &index, m_repo ) )
256 {
257 AddErrorString( _( "Could not get repository index" ) );
258 return PullResult::Error;
259 }
260
261 // Check for conflicts
262 git_index_conflict_iterator* conflicts = nullptr;
263 if( git_index_conflict_iterator_new( &conflicts, index ) )
264 {
265 AddErrorString( _( "Could not get conflict iterator" ) );
266 return PullResult::Error;
267 }
268
269 const git_index_entry* ancestor = nullptr;
270 const git_index_entry* our = nullptr;
271 const git_index_entry* their = nullptr;
272 std::vector<ConflictData> conflict_data;
273
274 while( git_index_conflict_next( &ancestor, &our, &their, conflicts ) == 0 )
275 {
276 // Case 3: Both files have changed
277 if( ancestor && our && their )
278 {
279 ConflictData conflict_datum;
280 conflict_datum.filename = our->path;
281 conflict_datum.our_oid = our->id;
282 conflict_datum.their_oid = their->id;
283 conflict_datum.our_commit_time = our->mtime.seconds;
284 conflict_datum.their_commit_time = their->mtime.seconds;
285 conflict_datum.our_status = _( "Changed" );
286 conflict_datum.their_status = _( "Changed" );
287 conflict_datum.use_ours = true;
288
289 conflict_data.push_back( conflict_datum );
290 }
291 // Case 4: File added in both ours and theirs
292 else if( !ancestor && our && their )
293 {
294 ConflictData conflict_datum;
295 conflict_datum.filename = our->path;
296 conflict_datum.our_oid = our->id;
297 conflict_datum.their_oid = their->id;
298 conflict_datum.our_commit_time = our->mtime.seconds;
299 conflict_datum.their_commit_time = their->mtime.seconds;
300 conflict_datum.our_status = _( "Added" );
301 conflict_datum.their_status = _( "Added" );
302 conflict_datum.use_ours = true;
303
304 conflict_data.push_back( conflict_datum );
305 }
306 // Case 1: Remote file has changed or been added, local file has not
307 else if( their && !our )
308 {
309 // Accept their changes
310 git_index_add( index, their );
311 }
312 // Case 2: Local file has changed or been added, remote file has not
313 else if( our && !their )
314 {
315 // Accept our changes
316 git_index_add( index, our );
317 }
318 else
319 {
320 wxLogError( wxS( "Unexpected conflict state" ) );
321 }
322 }
323
324 if( conflict_data.empty() )
325 {
326 git_index_conflict_cleanup( index );
327 git_index_write( index );
328 }
329
330 git_index_conflict_iterator_free( conflicts );
331 git_index_free( index );
332
333 return conflict_data.empty() ? PullResult::Success : PullResult::MergeFailed;
334}
335
336
337void GIT_PULL_HANDLER::UpdateProgress( int aCurrent, int aTotal, const wxString& aMessage )
338{
339 ReportProgress( aCurrent, aTotal, aMessage );
340}
void ReportProgress(int aCurrent, int aTotal, const wxString &aMessage)
Definition: git_progress.h:45
GIT_PULL_HANDLER(git_repository *aRepo)
std::string getFirstLineFromCommitMessage(const std::string &aMessage)
PullResult handleFastForward()
PullResult handleMerge(const git_annotated_commit **aMergeHeads, size_t aMergeHeadsCount)
const std::vector< std::pair< std::string, std::vector< CommitDetails > > > & GetFetchResults() const
void UpdateProgress(int aCurrent, int aTotal, const wxString &aMessage) override
std::string getFormattedCommitDate(const git_time &aTime)
std::vector< std::pair< std::string, std::vector< CommitDetails > > > m_fetchResults
PullResult PerformPull()
git_repository * m_repo
void AddErrorString(const wxString aErrorString)
#define _(s)
PullResult
int fetchhead_foreach_cb(const char *, const char *, const git_oid *aOID, unsigned int aIsMerge, 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)
int progress_cb(const char *str, int len, void *data)
std::string m_sha
std::string m_date
std::string m_firstLine
std::string m_author
std::string their_status
std::string our_status
std::string filename
git_time_t their_commit_time
git_time_t our_commit_time