Debian Codegraph @

plugins/vcs/Algorithm.h

raw
1 #pragma once
2
3 #include "imap.h"
4 #include "i18n.h"
5 #include "itextstream.h"
6 #include "Repository.h"
7 #include "gamelib.h"
8 #include "GitException.h"
9 #include "GitModule.h"
10 #include "Commit.h"
11 #include "Diff.h"
12 #include "VersionControlLib.h"
13 #include "command/ExecutionFailure.h"
14 #include "wxutil/dialog/MessageBox.h"
15 #include "ui/CommitDialog.h"
16 #include <git2.h>
17
18 namespace vcs
19 {
20
21 namespace git
22 {
23
24 enum class RequiredMergeStrategy
25 {
26 // The local branch is up to date
27 NoMergeRequired,
28
29 // Only the local branch got commits they can be pushed
30 JustPush,
31
32 // The local branch can be fast-forwarded since there are no local changes
33 FastForward,
34
35 // At most one branch changed the map, the branches can be merged
36 MergeRecursively,
37
38 // Both branches changed the loaded map, a merge is required
39 MergeMap,
40
41 // The local map has uncommitted changes, and the remote is trying to change it
42 MergeMapWithUncommittedChanges,
43
44 // Merge is not possible at this point
45 MergeAlreadyInProgress,
46 };
47
48 struct RemoteStatus
49 {
50 std::size_t localAheadCount;
51 std::size_t remoteAheadCount;
52 std::string label;
53
54 RequiredMergeStrategy strategy;
55 };
56
57 inline RemoteStatus analyseRemoteStatus(const std::shared_ptr<Repository>& repository)
58 {
59 auto mapPath = repository->getRepositoryRelativePath(GlobalMapModule().getMapName());
60
61 if (mapPath.empty() || !repository->getHead())
62 {
63 return RemoteStatus{ 0, 0, _("-") };
64 }
65
66 if (!repository->getHead()->getUpstream())
67 {
68 return RemoteStatus{ 0, 0, _("No tracked remote"), RequiredMergeStrategy::NoMergeRequired };
69 }
70
71 auto status = repository->getSyncStatusOfBranch(*repository->getHead());
72
73 if (repository->mergeIsInProgress())
74 {
75 return RemoteStatus{ status.localCommitsAhead, status.remoteCommitsAhead,
76 _("Merge in progress"), RequiredMergeStrategy::MergeAlreadyInProgress };
77 }
78
79 auto mapFileHasUncommittedChanges = repository->fileHasUncommittedChanges(mapPath);
80
81 if (status.remoteCommitsAhead == 0)
82 {
83 return status.localCommitsAhead == 0 ?
84 RemoteStatus{ status.localCommitsAhead, 0, _("Up to date"), RequiredMergeStrategy::NoMergeRequired } :
85 RemoteStatus{ status.localCommitsAhead, 0, _("Pending Upload"), RequiredMergeStrategy::JustPush };
86 }
87 else if (status.localCommitsAhead == 0 && !mapFileHasUncommittedChanges)
88 {
89 // No local commits and no uncommitted changes, we can fast-forward
90 return RemoteStatus{ 0, status.remoteCommitsAhead, _("Integrate"), RequiredMergeStrategy::FastForward };
91 }
92
93 // Check the incoming commits for modifications of the loaded map
94 auto head = repository->getHead();
95 auto upstream = head->getUpstream();
96
97 // Find the merge base for this ref and its upstream
98 auto mergeBase = repository->findMergeBase(*head, *upstream);
99
100 auto remoteDiffAgainstBase = repository->getDiff(*upstream, *mergeBase);
101
102 bool remoteDiffContainsMap = remoteDiffAgainstBase->containsFile(mapPath);
103
104 if (!remoteDiffContainsMap)
105 {
106 // Remote didn't change the map, we can integrate it without conflicting the loaded map
107 return RemoteStatus{ status.localCommitsAhead, status.remoteCommitsAhead, _("Integrate"),
108 status.localCommitsAhead == 0 ? RequiredMergeStrategy::FastForward : RequiredMergeStrategy::MergeRecursively };
109 }
110
111 if (mapFileHasUncommittedChanges)
112 {
113 return RemoteStatus{ status.localCommitsAhead, status.remoteCommitsAhead, _("Commit, then integrate "),
114 RequiredMergeStrategy::MergeMapWithUncommittedChanges };
115 }
116
117 auto localDiffAgainstBase = repository->getDiff(*head, *mergeBase);
118 bool localDiffContainsMap = localDiffAgainstBase->containsFile(mapPath);
119
120 if (!localDiffContainsMap)
121 {
122 // The local diff doesn't include the map, the remote changes can be integrated
123 return RemoteStatus{ status.localCommitsAhead, status.remoteCommitsAhead, _("Integrate"),
124 RequiredMergeStrategy::MergeRecursively };
125 }
126
127 // Both the local and the remote diff are affecting the map file, this needs resolution
128 return RemoteStatus{ status.localCommitsAhead, status.remoteCommitsAhead, _("Resolve"),
129 RequiredMergeStrategy::MergeMap };
130 }
131
132 inline std::string getInfoFilePath(const std::string& mapPath)
133 {
134 auto format = GlobalMapFormatManager().getMapFormatForFilename(mapPath);
135
136 if (format && format->allowInfoFileCreation())
137 {
138 return os::replaceExtension(mapPath, game::current::getInfoFileExtension());
139 }
140
141 return std::string();
142 }
143
144 inline void resolveMapFileConflictUsingOurs(const std::shared_ptr<Repository>& repository)
145 {
146 auto mapPath = repository->getRepositoryRelativePath(GlobalMapModule().getMapName());
147 auto index = repository->getIndex();
148
149 // Remove the conflict state of the map file after save
150 if (!mapPath.empty() && index->fileIsConflicted(mapPath))
151 {
152 index->resolveByUsingOurs(mapPath);
153
154 auto infoFilePath = getInfoFilePath(mapPath);
155
156 if (!infoFilePath.empty())
157 {
158 index->resolveByUsingOurs(infoFilePath);
159 }
160
161 index->write();
162 }
163 }
164
165 inline void tryToFinishMerge(const std::shared_ptr<Repository>& repository)
166 {
167 auto mapPath = repository->getRepositoryRelativePath(GlobalMapModule().getMapName());
168
169 auto index = repository->getIndex();
170
171 if (index->hasConflicts())
172 {
173 // Remove the conflict state from the map
174 resolveMapFileConflictUsingOurs(repository);
175
176 // If the index still has conflicts, notify the user
177 if (index->hasConflicts())
178 {
179 wxutil::Messagebox::Show(_("Conflicts"),
180 _("There are still unresolved conflicts in the repository.\nPlease use your Git client to resolve them and try again."),
181 ::ui::IDialog::MessageType::MESSAGE_CONFIRM);
182 return;
183 }
184 }
185
186 auto head = repository->getHead();
187 if (!head) throw git::GitException("Cannot resolve repository HEAD");
188
189 auto upstream = head->getUpstream();
190 if (!upstream) throw git::GitException("Cannot resolve upstream ref from HEAD");
191
192 // We need the commit metadata to be valid
193 git::CommitMetadata metadata;
194
195 metadata.name = repository->getConfigValue("user.name");
196 metadata.email = repository->getConfigValue("user.email");
197 metadata.message = "Integrated remote changes from " + upstream->getShorthandName();
198
199 if (metadata.name.empty() || metadata.email.empty())
200 {
201 metadata = ui::CommitDialog::RunDialog(metadata);
202 }
203
204 if (metadata.isValid())
205 {
206 repository->createCommit(metadata, upstream);
207 repository->cleanupState();
208 }
209 }
210
211 inline void performFastForward(const std::shared_ptr<Repository>& repository)
212 {
213 auto head = repository->getHead();
214 auto upstream = head->getUpstream();
215
216 // Find the merge base for this ref and its upstream
217 auto mergeBase = repository->findMergeBase(*head, *upstream);
218
219 auto remoteDiffAgainstBase = repository->getDiff(*upstream, *mergeBase);
220
221 auto mapPath = repository->getRepositoryRelativePath(GlobalMapModule().getMapName());
222 bool remoteDiffContainsMap = remoteDiffAgainstBase->containsFile(mapPath);
223
224 repository->fastForwardToTrackedRemote();
225
226 if (!remoteDiffContainsMap)
227 {
228 return;
229 }
230
231 // The map has been modified on disk, so it might be a good choice to reload the map
232 if (wxutil::Messagebox::Show(_("Map has been updated"),
233 _("The map file has been updated on disk, reload the map file now?"),
234 ::ui::IDialog::MessageType::MESSAGE_ASK) == ::ui::IDialog::RESULT_YES)
235 {
236 GlobalCommandSystem().executeCommand("OpenMap", GlobalMapModule().getMapName());
237 }
238 }
239
240 inline void syncWithRemote(const std::shared_ptr<Repository>& repository)
241 {
242 if (repository->mergeIsInProgress())
243 {
244 throw GitException(_("Merge in progress"));
245 }
246
247 if (GlobalMapModule().isModified())
248 {
249 throw GitException(_("The map file has unsaved changes, please save before merging."));
250 }
251
252 auto mapPath = repository->getRepositoryRelativePath(GlobalMapModule().getMapName());
253
254 RemoteStatus status = analyseRemoteStatus(repository);
255
256 switch (status.strategy)
257 {
258 case RequiredMergeStrategy::NoMergeRequired:
259 rMessage() << "No merge required." << std::endl;
260 return;
261
262 case RequiredMergeStrategy::JustPush:
263 repository->pushToTrackedRemote();
264 return;
265
266 case RequiredMergeStrategy::FastForward:
267 performFastForward(repository);
268 return;
269 }
270
271 // All the other merge strategies include a recursive merge, prepare it
272 if (status.strategy == RequiredMergeStrategy::MergeMapWithUncommittedChanges)
273 {
274 // Commit the current map changes
275 wxutil::Messagebox::Show(_("Pending Commit"),
276 _("The map file has uncommitted changes, please commit first before integrating."),
277 ::ui::IDialog::MessageType::MESSAGE_CONFIRM);
278 return;
279 }
280
281 if (!repository->isReadyForMerge())
282 {
283 throw git::GitException(_("Repository is not ready for a merge at this point"));
284 }
285
286 if (!repository->getHead() || !repository->getHead()->getUpstream())
287 {
288 throw git::GitException(_("Cannot resolve HEAD and the corresponding upstream branch"));
289 }
290
291 git_merge_analysis_t analysis;
292 git_merge_preference_t preference = GIT_MERGE_PREFERENCE_NONE;
293
294 auto upstream = repository->getHead()->getUpstream();
295 git_oid upstreamOid;
296 auto error = git_reference_name_to_id(&upstreamOid, repository->_get(), upstream->getName().c_str());
297
298 git_annotated_commit* mergeHead;
299 error = git_annotated_commit_lookup(&mergeHead, repository->_get(), &upstreamOid);
300 GitException::ThrowOnError(error);
301
302 try
303 {
304 std::vector<const git_annotated_commit*> mergeHeads;
305 mergeHeads.push_back(mergeHead);
306
307 error = git_merge_analysis(&analysis, &preference, repository->_get(), mergeHeads.data(), mergeHeads.size());
308 GitException::ThrowOnError(error);
309
310 // The result of the analysis must be that a three-way merge is required
311 if (analysis != GIT_MERGE_ANALYSIS_NORMAL)
312 {
313 throw GitException("The repository state doesn't require a regular merge, cannot proceed.");
314 }
315
316 git_merge_options mergeOptions = GIT_MERGE_OPTIONS_INIT;
317 git_checkout_options checkoutOptions = GIT_CHECKOUT_OPTIONS_INIT;
318 checkoutOptions.checkout_strategy = GIT_CHECKOUT_FORCE | GIT_CHECKOUT_ALLOW_CONFLICTS;
319
320 error = git_merge(repository->_get(), mergeHeads.data(), mergeHeads.size(), &mergeOptions, &checkoutOptions);
321 GitException::ThrowOnError(error);
322
323 // Check if the loaded map is affected by the merge
324 if (status.strategy != RequiredMergeStrategy::MergeMap)
325 {
326 tryToFinishMerge(repository);
327 return;
328 }
329
330 // A map merge is required
331 wxutil::Messagebox::Show(_("Map Merge Required"),
332 _("The map has been changed both on the server and locally.\n"
333 "DarkRadiant will now switch to Merge Mode to highlight the differences.\n"
334 "Please have a look, resolve possible conflicts and finish the merge."),
335 ::ui::IDialog::MessageType::MESSAGE_CONFIRM);
336
337 auto mergeBase = repository->findMergeBase(*repository->getHead(), *upstream);
338
339 auto baseUri = constructVcsFileUri(GitModule::UriPrefix, Reference::OidToString(mergeBase->getOid()), mapPath);
340 auto sourceUri = constructVcsFileUri(GitModule::UriPrefix, Reference::OidToString(&upstreamOid), mapPath);
341
342 try
343 {
344 // The loaded map merge needs to be confirmed by the user
345 GlobalMapModule().startMergeOperation(sourceUri, baseUri);
346 // Done here, wait until the user finishes or aborts the merge
347 return;
348 }
349 catch (const cmd::ExecutionFailure& ex)
350 {
351 throw GitException(ex.what());
352 }
353 }
354 catch (const GitException& ex)
355 {
356 git_annotated_commit_free(mergeHead);
357 throw ex;
358 }
359 }
360
361 }
362
363 }