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