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