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