Debian Codegraph @

plugins/vcs/Repository.cpp

raw
1 #include "Repository.h"
2
3 #include "i18n.h"
4 #include <git2.h>
5 #include "itextstream.h"
6 #include "imap.h"
7 #include "Remote.h"
8 #include "Commit.h"
9 #include "Tree.h"
10 #include "Diff.h"
11 #include "GitException.h"
12 #include "Signature.h"
13 #include "os/path.h"
14 #include "os/file.h"
15 #include "fmt/format.h"
16
17 #if LIBGIT2_VER_MAJOR <= 0 && LIBGIT2_VER_MINOR < 28
18 // Compatibility to older libgit2
19 #define GIT_OBJECT_COMMIT GIT_OBJ_COMMIT
20 #endif
21
22 namespace vcs
23 {
24
25 namespace git
26 {
27
28 Repository::Repository(const std::string& path) :
29 _repository(nullptr),
30 _isOk(false),
31 _path(os::standardPathWithSlash(path))
32 {
33 if (git_repository_open(&_repository, _path.c_str()) == 0)
34 {
35 _isOk = true;
36 }
37 else
38 {
39 rMessage() << "Failed to open repository at " << _path << std::endl;
40 }
41 }
42
43 Repository::~Repository()
44 {
45 git_repository_free(_repository);
46 }
47
48 bool Repository::isOk() const
49 {
50 return _isOk;
51 }
52
53 const std::string& Repository::getPath() const
54 {
55 return _path;
56 }
57
58 std::string Repository::getRepositoryRelativePath(const std::string& path)
59 {
60 if (!os::fileOrDirExists(path))
61 {
62 return ""; // doesn't exist
63 }
64
65 auto relativePath = os::getRelativePath(path, getPath());
66
67 if (relativePath == path)
68 {
69 return ""; // outside VCS
70 }
71
72 return relativePath;
73 }
74
75 std::shared_ptr<Repository> Repository::clone()
76 {
77 return std::make_shared<Repository>(_path);
78 }
79
80 std::shared_ptr<Remote> Repository::getRemote(const std::string& name)
81 {
82 return Remote::CreateFromName(*this, name);
83 }
84
85 Reference::Ptr Repository::getHead()
86 {
87 git_reference* head;
88 int error = git_repository_head(&head, _repository);
89
90 if (error == GIT_EUNBORNBRANCH || error == GIT_ENOTFOUND)
91 {
92 return Reference::Ptr();
93 }
94
95 return std::make_shared<Reference>(head);
96 }
97
98 std::string Repository::getCurrentBranchName()
99 {
100 auto head = getHead();
101 return head ? head->getShorthandName() : std::string();
102 }
103
104 std::string Repository::getUpstreamRemoteName(const Reference& reference)
105 {
106 git_buf buf;
107 memset(&buf, 0, sizeof(git_buf));
108
109 auto error = git_branch_upstream_remote(&buf, _repository, reference.getName().c_str());
110 GitException::ThrowOnError(error);
111
112 std::string upstreamRemote = buf.ptr;
113 #if LIBGIT2_VER_MAJOR <= 0 && LIBGIT2_VER_MINOR < 28
114 git_buf_free(&buf); // git_buf_dispose was introduced in 0.28
115 #else
116 git_buf_dispose(&buf);
117 #endif
118
119 return upstreamRemote;
120 }
121
122 Remote::Ptr Repository::getTrackedRemote()
123 {
124 auto head = getHead();
125
126 if (!head)
127 {
128 throw GitException(_("Could not retrieve HEAD reference from repository"));
129 }
130
131 auto trackedBranch = head->getUpstream();
132
133 rMessage() << head->getShorthandName() << " is set up to track " << (trackedBranch ? trackedBranch->getShorthandName() : "-") << std::endl;
134
135 if (!trackedBranch)
136 {
137 throw GitException(_("No tracked remote branch configured"));
138 }
139
140 auto remoteName = getUpstreamRemoteName(*head);
141 rMessage() << head->getShorthandName() << " is set up to track remote " << remoteName << std::endl;
142
143 auto remote = getRemote(remoteName);
144
145 if (!remote)
146 {
147 throw GitException(fmt::format(_("Failed to get the named remote: {0}"), remoteName));
148 }
149
150 return remote;
151 }
152
153 void Repository::fetchFromTrackedRemote()
154 {
155 auto remote = getTrackedRemote();
156 remote->fetch();
157 }
158
159 void Repository::pushToTrackedRemote()
160 {
161 auto remote = getTrackedRemote();
162 remote->push(*getHead()); // getHead will succeed because getTrackedRemote did
163 }
164
165 void Repository::fastForwardToTrackedRemote()
166 {
167 auto head = getHead();
168 if (!head) throw GitException(_("Could not retrieve HEAD reference from repository"));
169
170 auto upstream = head->getUpstream();
171 if (!upstream) throw GitException(_("No tracked remote branch configured"));
172
173 // Lookup the target object
174 git_oid targetOid;
175 git_reference_name_to_id(&targetOid, _repository, upstream->getName().c_str());
176
177 git_object* target;
178 auto error = git_object_lookup(&target, _repository, &targetOid, GIT_OBJECT_COMMIT);
179 GitException::ThrowOnError(error);
180
181 rMessage() << "Fast-fowarding " << head->getName() << " to upstream " << upstream->getName() << std::endl;
182
183 try
184 {
185 // Checkout the result so the workdir is in the expected state
186 git_checkout_options checkoutOptions = GIT_CHECKOUT_OPTIONS_INIT;
187 checkoutOptions.checkout_strategy = GIT_CHECKOUT_SAFE;
188
189 error = git_checkout_tree(_repository, target, &checkoutOptions);
190 GitException::ThrowOnError(error);
191
192 // Move the target reference to the target OID
193 head->setTarget(&targetOid);
194
195 rMessage() << "Fast-foward done, " << head->getName() << " is now at " << Reference::OidToString(&targetOid) << std::endl;
196 }
197 catch (const GitException& ex)
198 {
199 git_object_free(target);
200 throw ex;
201 }
202 }
203
204 RefSyncStatus Repository::getSyncStatusOfBranch(const Reference& reference)
205 {
206 RefSyncStatus status;
207
208 auto trackedBranch = reference.getUpstream();
209
210 if (!trackedBranch) throw GitException(_("The current branch doesn't track a remote, cannot check sync status"));
211
212 git_revwalk* walker = nullptr;
213 git_revwalk_new(&walker, _repository);
214
215 // Start from remote
216 git_revwalk_push_ref(walker, trackedBranch->getName().c_str());
217
218 // End at local
219 git_oid refOid;
220 git_reference_name_to_id(&refOid, _repository, reference.getName().c_str());
221 git_revwalk_hide(walker, &refOid);
222
223 git_oid id;
224 while (!git_revwalk_next(&id, walker))
225 {
226 //rMessage() << Reference::OidToString(&id) << " => ";
227 ++status.remoteCommitsAhead;
228 }
229 //rMessage() << std::endl;
230
231 git_revwalk_free(walker);
232
233 // Another walk from local to remote
234 git_revwalk_new(&walker, _repository);
235
236 git_revwalk_push(walker, &refOid);
237 git_revwalk_hide_ref(walker, trackedBranch->getName().c_str());
238
239 while (!git_revwalk_next(&id, walker))
240 {
241 //rMessage() << Reference::OidToString(&id) << " => ";
242 ++status.localCommitsAhead;
243 }
244 //rMessage() << std::endl;
245
246 git_revwalk_free(walker);
247
248 // Initialise the convenience flags
249 status.localIsUpToDate = status.localCommitsAhead == 0 && status.remoteCommitsAhead == 0;
250 status.localCanBePushed = status.localCommitsAhead > 0 && status.remoteCommitsAhead == 0;
251
252 return status;
253 }
254
255 bool Repository::isUpToDateWithRemote()
256 {
257 auto head = getHead();
258
259 if (!head)
260 {
261 rWarning() << "Could not retrieve HEAD reference from repository" << std::endl;
262 return false;
263 }
264
265 return getSyncStatusOfBranch(*head).localIsUpToDate;
266 }
267
268 unsigned int Repository::getFileStatus(const std::string& relativePath)
269 {
270 git_status_options options = GIT_STATUS_OPTIONS_INIT;
271
272 char* paths[] = { const_cast<char*>(relativePath.c_str()) };
273
274 options.pathspec.count = 1;
275 options.pathspec.strings = paths;
276 options.flags |= GIT_STATUS_OPT_INCLUDE_UNTRACKED | GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS;
277 options.show = GIT_STATUS_SHOW_WORKDIR_ONLY;
278
279 unsigned int statusFlags = 0;
280
281 auto error = git_status_foreach_ext(_repository, &options, [](const char* path, unsigned int flags, void* payload)
282 {
283 *reinterpret_cast<unsigned int*>(payload) = flags;
284 return 0;
285 }, &statusFlags);
286 GitException::ThrowOnError(error);
287
288 return statusFlags;
289 }
290
291 bool Repository::fileIsIndexed(const std::string& relativePath)
292 {
293 return (getFileStatus(relativePath) & GIT_STATUS_WT_NEW) == 0;
294 }
295
296 bool Repository::fileHasUncommittedChanges(const std::string& relativePath)
297 {
298 return (getFileStatus(relativePath) & GIT_STATUS_WT_MODIFIED) != 0;
299 }
300
301 Index::Ptr Repository::getIndex()
302 {
303 git_index* index;
304 auto error = git_repository_index(&index, _repository);
305 GitException::ThrowOnError(error);
306
307 return std::make_shared<Index>(index);
308 }
309
310 std::shared_ptr<Tree> Repository::getTreeByRevision(const std::string& revision)
311 {
312 git_oid revisionOid;
313 auto error = git_oid_fromstr(&revisionOid, revision.c_str());
314 GitException::ThrowOnError(error);
315
316 auto commit = Commit::LookupFromOid(_repository, &revisionOid);
317 return commit->getTree();
318 }
319
320 void Repository::createCommit(const CommitMetadata& metadata)
321 {
322 createCommit(metadata, Reference::Ptr());
323 }
324
325 void Repository::createCommit(const CommitMetadata& metadata, const Reference::Ptr& additionalParent)
326 {
327 auto head = getHead();
328 auto index = getIndex();
329
330 rMessage() << "Creating commit with user " << metadata.name << std::endl;
331
332 Signature signature(metadata.name, metadata.email);
333
334 // Add all working copy changes
335 index->updateAll();
336
337 auto tree = index->writeTree(*this);
338
339 std::vector<const git_commit*> parentCommits;
340
341 // It's possible that there is no HEAD yet (first commit in the repo)
342 if (head)
343 {
344 git_oid headOid;
345 auto error = git_reference_name_to_id(&headOid, _repository, head->getName().c_str());
346 GitException::ThrowOnError(error);
347
348 auto parentCommit = Commit::LookupFromOid(_repository, &headOid);
349 parentCommits.push_back(parentCommit->_get());
350 }
351
352 // Check if we have an additional parent
353 if (additionalParent)
354 {
355 git_oid parentOid;
356 auto error = git_reference_name_to_id(&parentOid, _repository, additionalParent->getName().c_str());
357 GitException::ThrowOnError(error);
358
359 auto additionalParentCommit = Commit::LookupFromOid(_repository, &parentOid);
360
361 parentCommits.push_back(additionalParentCommit->_get());
362 }
363
364 git_oid commitOid;
365 auto error = git_commit_create(&commitOid,
366 _repository, head ? head->getName().c_str() : "HEAD",
367 signature.get(), signature.get(),
368 nullptr, metadata.message.c_str(),
369 tree->_get(),
370 parentCommits.size(), parentCommits.data());
371 GitException::ThrowOnError(error);
372
373 index->write();
374
375 rMessage() << "Commit created: " << Reference::OidToString(&commitOid) << std::endl;
376 }
377
378 std::string Repository::getConfigValue(const std::string& key)
379 {
380 git_config* config;
381 auto error = git_repository_config_snapshot(&config, _repository);
382 GitException::ThrowOnError(error);
383
384 try
385 {
386 const char* value;
387 auto error = git_config_get_string(&value, config, key.c_str());
388 GitException::ThrowOnError(error);
389
390 // Copy the value before free-ing the config
391 std::string returnValue(value);
392
393 git_config_free(config);
394
395 return returnValue;
396 }
397 catch (const GitException& ex)
398 {
399 git_config_free(config);
400 throw ex;
401 }
402 }
403
404 void Repository::cleanupState()
405 {
406 auto error = git_repository_state_cleanup(_repository);
407 GitException::ThrowOnError(error);
408 }
409
410 bool Repository::isReadyForMerge()
411 {
412 auto state = git_repository_state(_repository);
413 return state == GIT_REPOSITORY_STATE_NONE;
414 }
415
416 bool Repository::mergeIsInProgress()
417 {
418 auto state = git_repository_state(_repository);
419 return state == GIT_REPOSITORY_STATE_MERGE;
420 }
421
422 void Repository::abortMerge()
423 {
424 if (!mergeIsInProgress())
425 {
426 return;
427 }
428
429 auto head = getHead();
430
431 git_oid targetOid;
432 auto error = git_reference_name_to_id(&targetOid, _repository, head->getName().c_str());
433 GitException::ThrowOnError(error);
434
435 git_object* target;
436 error = git_object_lookup(&target, _repository, &targetOid, GIT_OBJECT_COMMIT);
437 GitException::ThrowOnError(error);
438
439 git_checkout_options checkoutOptions = GIT_CHECKOUT_OPTIONS_INIT;
440 checkoutOptions.checkout_strategy = GIT_CHECKOUT_FORCE;
441
442 error = git_reset(_repository, target, GIT_RESET_HARD, &checkoutOptions);
443 GitException::ThrowOnError(error);
444 }
445
446 Commit::Ptr Repository::findMergeBase(const Reference& first, const Reference& second)
447 {
448 git_oid firstOid;
449 auto error = git_reference_name_to_id(&firstOid, _repository, first.getName().c_str());
450 GitException::ThrowOnError(error);
451
452 git_oid secondOid;
453 error = git_reference_name_to_id(&secondOid, _repository, second.getName().c_str());
454 GitException::ThrowOnError(error);
455
456 git_oid mergeBase;
457 error = git_merge_base(&mergeBase, _repository, &firstOid, &secondOid);
458 GitException::ThrowOnError(error);
459
460 git_commit* commit;
461 error = git_commit_lookup(&commit, _repository, &mergeBase);
462 GitException::ThrowOnError(error);
463
464 return std::make_shared<Commit>(commit);
465 }
466
467 std::shared_ptr<Diff> Repository::getDiff(const Reference& ref, Commit& commit)
468 {
469 git_oid refOid;
470 auto error = git_reference_name_to_id(&refOid, _repository, ref.getName().c_str());
471 GitException::ThrowOnError(error);
472
473 auto refCommit = Commit::LookupFromOid(_repository, &refOid);
474 auto refTree = refCommit->getTree();
475
476 git_diff* diff;
477 auto baseTree = commit.getTree();
478 error = git_diff_tree_to_tree(&diff, _repository, baseTree->_get(), refTree->_get(), nullptr);
479 GitException::ThrowOnError(error);
480
481 return std::make_shared<Diff>(diff);
482 }
483
484 git_repository* Repository::_get()
485 {
486 return _repository;
487 }
488
489 }
490
491 }