-
Notifications
You must be signed in to change notification settings - Fork 2
/
Repository.cpp
1479 lines (1186 loc) · 48.9 KB
/
Repository.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Repository.h"
#include "GitEnvironment.h"
#include "SmartLibGitHeapPointerTemplate.hpp"
#include "LibGitException.h"
#include <stdexcept>
#include <cstring>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
using Repository = Git::Repository;
using Commit = Git::Commit;
using Branch = Git::Branch;
using Tag = Git::Tag;
using Remote = Git::Remote;
using LibGitException = Git::LibGitException;
Repository::Repository(const std::string& _pathToRepo) : RepositoryDependant(_pathToRepo)
{
if(0 != getRemoteCount() && 1 != getRemoteCount())
{
throw std::domain_error("Currently only repositories with one or no remotes are supported.");
}
if(git_repository_is_bare(smartLibGitRepository.get()))
{
throw std::domain_error("Currently bare repositories are not supported.");
}
}
bool Repository::hasConflicts() const
{
git_index* indexRaw = nullptr;
checkLibGitError( git_repository_index(&indexRaw, smartLibGitRepository.get()) );
uniquePtr<git_index> index(indexRaw, git_index_free);
std::size_t conflicts = git_index_has_conflicts(index.get());
return (1 == conflicts);
}
void Repository::stash(const std::string& message /* = "" */)
{
git_oid oid;
uint32_t flags = GIT_STASH_DEFAULT;
git_signature* stasherRaw = nullptr;
checkLibGitError( git_signature_default(&stasherRaw, smartLibGitRepository.get()) );
uniquePtr<git_signature> stasher(stasherRaw, git_signature_free);
checkLibGitError( git_stash_save(&oid, smartLibGitRepository.get(), stasherRaw, message.c_str(), flags) );
}
void Repository::commit(const std::string& message)
{
bool inMergeState = isInMergeState();
bool inNormalState = isInNormalState();
if(!inMergeState && !inNormalState)
{
throw std::logic_error("Repository state prevents operation.");
}
if(getStagedFiles().size() < 1)
{
throw std::logic_error("There is nothing to commit");
}
if(hasConflicts())
{
std::logic_error("Cannot commit to conflicted repository.");
}
git_oid treeOid, commitOid;
git_index* indexRaw = nullptr;
checkLibGitError( git_repository_index(&indexRaw, smartLibGitRepository.get()) );
uniquePtr<git_index> index(indexRaw, git_index_free);
checkLibGitError( git_index_write_tree(&treeOid, index.get()) );
git_signature* signatureRaw = nullptr;
checkLibGitError( git_signature_default(&signatureRaw, smartLibGitRepository.get()) );
uniquePtr<git_signature> signature(signatureRaw, git_signature_free);
git_tree* treeRaw = nullptr;
checkLibGitError( git_tree_lookup(&treeRaw, smartLibGitRepository.get(), &treeOid) );
uniquePtr<git_tree> tree(treeRaw, git_tree_free);
if(inNormalState)
{
bool isInitialCommit = git_repository_head_unborn(smartLibGitRepository.get());
if(isInitialCommit)
{
checkLibGitError( git_commit_create_v( &commitOid
, smartLibGitRepository.get()
, "HEAD"
, signature.get()
, signature.get()
, "UTF-8"
, messagePrettify(message).c_str()
, tree.get()
, 0) );
}
else
{
uniquePtr<git_commit> parent = getHeadLibGitCommit();
const git_commit *parents[] = { parent.get() };
checkLibGitError( git_commit_create( &commitOid
, smartLibGitRepository.get()
, "HEAD"
, signature.get()
, signature.get()
, "UTF-8"
, messagePrettify(message).c_str()
, tree.get()
, 1
, parents) );
}
}
else if(inMergeState)
{
std::vector<git_oid> oids;
oids.push_back(*git_commit_id(getHeadLibGitCommit().get())); //head commit have to come first
auto callback = [](const git_oid *oid, void *payload) -> int
{
static_cast<std::vector<git_oid>*>(payload)->push_back(*oid);
return 0;
};
checkLibGitError( git_repository_mergehead_foreach(smartLibGitRepository.get(), callback, &oids) );
if(2 != oids.size())
{
throw std::domain_error("Currently only merges with two parents are supported.");
}
const git_commit** parents = new const git_commit*[oids.size()];
std::vector<uniquePtr<git_commit>> parentLibGitCommits;
for(std::size_t i = 0; i < oids.size(); ++i)
{
git_commit* commitRaw;
try
{
checkLibGitError(git_commit_lookup(&commitRaw, smartLibGitRepository.get(), &oids[i]) );
}
catch(LibGitException& e)
{
delete[] parents;
throw e;
}
uniquePtr<git_commit> commit(commitRaw, git_commit_free);
parentLibGitCommits.push_back(std::move(commit));
parents[i] = parentLibGitCommits[i].get();
}
checkLibGitError( git_commit_create( &commitOid,
smartLibGitRepository.get(),
"HEAD",
signature.get(),
signature.get(),
"UTF-8",
messagePrettify(message).c_str(),
tree.get(),
oids.size(),
parents) );
delete[] parents;
checkLibGitError( git_repository_state_cleanup(smartLibGitRepository.get()) );
}
}
void Repository::stage(const std::vector<std::string>& relativePaths)
{
git_index* indexRaw = nullptr;
checkLibGitError( git_repository_index(&indexRaw, smartLibGitRepository.get()) );
uniquePtr<git_index> index(indexRaw, git_index_free);
for(const auto& relativePath : relativePaths)
{
if(!isFileInRepository(relativePath))
{
throw std::invalid_argument("File is not in repository: " + relativePath);
}
if(doesGitIgnoreApply(relativePath))
{
throw std::invalid_argument("Gitignore rule applies for file: " + relativePath);
}
}
for(const auto& relativePath : relativePaths)
{
unsigned int status;
checkLibGitError( git_status_file(&status, smartLibGitRepository.get(), relativePath.c_str()) );
if(GIT_STATUS_WT_DELETED & status)
{
checkLibGitError( git_index_remove_bypath(index.get(), relativePath.c_str()) );
}
else
{
checkLibGitError( git_index_add_bypath(index.get(), relativePath.c_str()) );
}
}
checkLibGitError( git_index_write(index.get()) );
}
void Repository::unstage(const std::vector<std::string>& relativePaths)
{
for(const auto& relativePath : relativePaths)
{
if(!isFileInRepository(relativePath))
{
throw std::invalid_argument("File is not in repository: " + relativePath);
}
}
for(const auto& file : relativePaths)
{
if (isStaged(file))
{
// get head as libgit object
git_oid headOid;
checkLibGitError( git_reference_name_to_id( &headOid, smartLibGitRepository.get(), "HEAD" ) );
git_object* targetObjectRaw = nullptr;
checkLibGitError( git_object_lookup(&targetObjectRaw
, smartLibGitRepository.get()
, &headOid
, GIT_OBJ_COMMIT
)
);
uniquePtr<git_object> targetObject(targetObjectRaw, git_object_free);
char** cStrings = new char*[relativePaths.size()];
for(std::size_t i = 0; i < relativePaths.size(); ++i)
{
char* cString = new char[relativePaths[i].size() + 1];
strcpy(cString, relativePaths[i].c_str());
cStrings[i] = cString;
}
git_strarray pathArray = {cStrings, relativePaths.size()};
//we will free the heap because it was allocated with new (not malloc)
//no "uniquePtr<git_strarray> pathArrayWrapper(&pathArray, git_strarray_free);" for you
int error = ( git_reset_default(smartLibGitRepository.get()
, targetObject.get()
, &pathArray
)
);
for(std::size_t i = 0; i < relativePaths.size(); ++i)
{
delete[] cStrings[i];
}
delete[] cStrings;
checkLibGitError(error);
}
}
}
void Repository::hardReset()
{
checkLibGitError(git_repository_state_cleanup(smartLibGitRepository.get()));
git_checkout_options options;
checkLibGitError( git_checkout_init_options(&options, GIT_CHECKOUT_OPTIONS_VERSION) );
git_oid headOid = shaToLibGitOid(getHead()->getSha());
git_object* targetObjectRaw = nullptr;
checkLibGitError( git_object_lookup(&targetObjectRaw
, smartLibGitRepository.get()
, &headOid
, GIT_OBJ_COMMIT
)
);
uniquePtr<git_object> targetObject(targetObjectRaw, git_object_free);
checkLibGitError( git_reset(smartLibGitRepository.get(), targetObject.get(), GIT_RESET_HARD, &options) );
}
void Repository::abortRebase()
{
if(isInRebaseState())
{
git_rebase* currentRebaseRaw = nullptr;
checkLibGitError( git_rebase_open(¤tRebaseRaw, smartLibGitRepository.get(), nullptr) );
uniquePtr<git_rebase> currentRebase(currentRebaseRaw, git_rebase_free);
checkLibGitError(git_rebase_abort(currentRebase.get()));
}
else
{
throw std::logic_error("Repository state prevents operation.");
}
}
void Repository::tag(const std::string& name)
{
git_commit* head = getHeadLibGitCommit().get();
std::string sha = getLibGitCommitSha(head);
tag(*getHead(), name);
}
void Repository::tag(const Commit& toTag, const std::string& name)
{
if(!isOwnedByRepo(toTag))
{
throw std::invalid_argument("Argument is not owned by the repository.");
}
std::string targetCommitSha = toTag.getSha();
git_oid oid = shaToLibGitOid(targetCommitSha);
git_object* parentCommitRaw = nullptr;
checkLibGitError( git_object_lookup_prefix( &parentCommitRaw
, smartLibGitRepository.get()
, &oid
, targetCommitSha.size()
, GIT_OBJ_COMMIT)
);
uniquePtr<git_object> parentCommit(parentCommitRaw, git_object_free);
checkLibGitError( git_tag_create_lightweight( &oid /* target ID */
, smartLibGitRepository.get() /* repository */
, name.c_str() /* name */
, parentCommit.get() /* target */
, false /* force? */
)
);
}
void Repository::branch(const std::string& name)
{
branch(*getHead(), name);
}
void Repository::branch(const Commit& toStartBranchFrom, const std::string& name)
{
if(!isOwnedByRepo(toStartBranchFrom))
{
throw std::invalid_argument("Argument is not owned by the repository.");
}
uniquePtr<git_commit> libGitCommit = getLibGitCommit(toStartBranchFrom.getSha());
/* create branch */
git_reference* branchRaw = nullptr;
checkLibGitError( git_branch_create( &branchRaw
, smartLibGitRepository.get()
, name.c_str()
, libGitCommit.get()
, 0
)
);
uniquePtr<git_reference> branch(branchRaw, git_reference_free);
// Make HEAD point to this branch - would imitate `git checkout -b`
//git_reference* headRaw = nullptr;
//checkLibGitError( git_reference_symbolic_create( &headRaw
// , smartLibGitRepository.get()
// , "HEAD"
// , git_reference_name( branch.get() )
// , 0
// , ""
// )
// );
//uniquePtr<git_reference> head(headRaw, git_reference_free);
}
//after this command you need to explicitly delete it from all remotes (see deleteTag)
void Repository::deleteBranch(const Branch& toDelete)
{
if(!isOwnedByRepo(toDelete))
{
throw std::invalid_argument("Argument is not owned by the repository.");
}
if(!toDelete.isLocal())
{
throw std::invalid_argument("Cannot delete remote tracking branches.");
}
std::string fullReferenceName = "refs/heads/" + toDelete.getName();
git_reference* branchRaw = nullptr;
checkLibGitError( git_reference_lookup(&branchRaw, smartLibGitRepository.get(), fullReferenceName.c_str()) );
uniquePtr<git_reference> branch(branchRaw, git_reference_free);
checkLibGitError( git_branch_delete(branch.get()) );
}
//after this command you need to explicitly delete it from all remotes as explained in:
//http://stackoverflow.com/questions/1028649/how-do-you-rename-a-git-tag
void Repository::deleteTag(const Tag& toDelete)
{
if(!isOwnedByRepo(toDelete))
{
throw std::invalid_argument("Argument is not owned by the repository.");
}
checkLibGitError( git_tag_delete(smartLibGitRepository.get(), toDelete.getName().c_str()) );
}
std::vector<std::unique_ptr<Branch>> Repository::getBranches() const
{
std::vector<std::unique_ptr<Branch>> branches;
//GIT_BRANCH_LOCAL GIT_BRANCH_REMOTE GIT_BRANCH_ALL
git_branch_t branchType = GIT_BRANCH_ALL;
git_branch_iterator* branchIteratorRaw = nullptr;
checkLibGitError( git_branch_iterator_new(&branchIteratorRaw, smartLibGitRepository.get(), branchType) );
uniquePtr<git_branch_iterator> branchIterator(branchIteratorRaw, git_branch_iterator_free);
git_reference* branchRaw = nullptr;
int error = git_branch_next(&branchRaw, &branchType, branchIterator.get());
uniquePtr<git_reference> branch(branchRaw, git_reference_free);
while( GIT_ITEROVER != error )
{
checkLibGitError(error);
const char* branchNameAsCharArray;
checkLibGitError( git_branch_name(&branchNameAsCharArray, branch.get()) );
std::string branchName = std::string(branchNameAsCharArray);
branches.push_back( std::unique_ptr<Branch>( new Branch( pathToRepository
, branchName
, !git_reference_is_remote(branch.get())
)
)
);
branchRaw = nullptr;
error = git_branch_next(&branchRaw, &branchType, branchIterator.get());
branch.reset(branchRaw); //calls deleter
}
return branches;
}
std::vector<std::unique_ptr<Tag>> Repository::getTags() const
{
std::vector<std::unique_ptr<Tag>> tags;
git_reference_iterator* referenceIteratorRaw = nullptr;
checkLibGitError( git_reference_iterator_new(&referenceIteratorRaw, smartLibGitRepository.get()) );
uniquePtr<git_reference_iterator> referenceIterator(referenceIteratorRaw, git_reference_iterator_free);
git_reference* referenceRaw = nullptr;
int error = git_reference_next(&referenceRaw, referenceIterator.get());
uniquePtr<git_reference> reference(referenceRaw, git_reference_free);
while( GIT_ITEROVER != error )
{
checkLibGitError(error);
if(git_reference_is_tag(reference.get()))
{
std::string tagName = std::string(git_reference_name(reference.get()));
std::string normalizedTagName = tagName.substr(tagName.rfind('/') + 1, tagName.size());
tags.push_back(std::unique_ptr<Tag>(new Tag(pathToRepository, normalizedTagName)));
}
referenceRaw = nullptr;
error = git_reference_next(&referenceRaw, referenceIterator.get());
reference.reset(referenceRaw); //calls deleter
}
return tags;
}
std::vector<std::string> Repository::getStagedFiles() const
{
std::vector<std::string> stagedFiles;
auto callback = [](const char *path, unsigned int status_flags, void *payload)
{
if(status_flags & (GIT_STATUS_INDEX_NEW | GIT_STATUS_INDEX_MODIFIED | GIT_STATUS_INDEX_DELETED |
GIT_STATUS_INDEX_RENAMED | GIT_STATUS_INDEX_TYPECHANGE))
static_cast<std::vector<std::string>*>(payload)->push_back(path);
return 0;
};
checkLibGitError( git_status_foreach(smartLibGitRepository.get(), callback, &stagedFiles) );
return stagedFiles;
}
std::vector<std::string> Repository::getDirtyFiles() const
{
std::vector<std::string> unstagedFiles;
auto callback = [](const char *path, unsigned int status_flags, void *payload)
{
if(status_flags & (GIT_STATUS_WT_NEW | GIT_STATUS_WT_MODIFIED | GIT_STATUS_WT_DELETED |
GIT_STATUS_WT_TYPECHANGE | GIT_STATUS_WT_RENAMED | GIT_STATUS_WT_UNREADABLE)
)
static_cast<std::vector<std::string>*>(payload)->push_back(path);
return 0;
};
checkLibGitError( git_status_foreach(smartLibGitRepository.get(), callback, &unstagedFiles) );
return unstagedFiles;
}
std::vector<std::string> Repository::getConflictedFiles() const
{
std::vector<std::string> conflictedFiles;
auto callback = [](const char *path, unsigned int status_flags, void *payload)
{
if(status_flags & GIT_STATUS_CONFLICTED)
static_cast<std::vector<std::string>*>(payload)->push_back(path);
return 0;
};
checkLibGitError( git_status_foreach(smartLibGitRepository.get(), callback, &conflictedFiles) );
return conflictedFiles;
}
void Repository::checkout(const Commit& toCheckout)
{
forceableCheckout(toCheckout, false);
}
/* private */ void Repository::forceableCheckout(const Commit& toCheckout, bool force)
{
if(!isOwnedByRepo(toCheckout))
{
throw std::invalid_argument("Argument is not owned by the repository.");
}
if(!isInNormalState())
{
throw std::logic_error("Repository state prevents operation.");
}
git_checkout_options options;
checkLibGitError( git_checkout_init_options(&options, GIT_CHECKOUT_OPTIONS_VERSION) );
if(force)
{
options.checkout_strategy = GIT_CHECKOUT_SAFE;
}
else
{
options.checkout_strategy = GIT_CHECKOUT_FORCE;
}
auto smartLibGitCommit = getLibGitCommit(toCheckout.getSha());
git_oid treeOid;
git_oid_cpy(&treeOid, git_commit_tree_id(smartLibGitCommit.get()));
git_object* treeishRaw = nullptr;
checkLibGitError( git_object_lookup( &treeishRaw
, smartLibGitRepository.get()
, &treeOid
, GIT_OBJ_TREE
)
);
uniquePtr<git_object> treeish(treeishRaw, git_object_free);
git_oid_cpy(&treeOid, git_object_id(treeish.get()));
checkLibGitError( git_checkout_tree(smartLibGitRepository.get(), treeish.get(), &options) );
git_oid commitOid;
git_oid_cpy(&commitOid, git_commit_id(smartLibGitCommit.get()));
checkLibGitError( git_repository_set_head_detached(smartLibGitRepository.get(), &commitOid) );
}
void Repository::checkout(const Branch& toCheckout)
{
forceableCheckout(toCheckout, false);
}
void Repository::forceableCheckout(const Branch& toCheckout, bool force)
{
if(!isInNormalState())
{
throw std::logic_error("Repository state prevents operation.");
}
if(!isOwnedByRepo(toCheckout))
{
throw std::invalid_argument("Argument is not owned by the repository.");
}
std::string fullReferenceName;
if(toCheckout.isLocal())
{
fullReferenceName = "refs/heads/" + toCheckout.getName();
}
else
{
fullReferenceName = "refs/remotes/" + toCheckout.getName();
}
git_checkout_options options;
checkLibGitError( git_checkout_init_options(&options, GIT_CHECKOUT_OPTIONS_VERSION) );
if(force)
{
options.checkout_strategy = GIT_CHECKOUT_SAFE;
}
else
{
options.checkout_strategy = GIT_CHECKOUT_FORCE;
}
git_reference* branchRaw = nullptr;
checkLibGitError( git_reference_lookup(&branchRaw, smartLibGitRepository.get(), fullReferenceName.c_str()) );
uniquePtr<git_reference> branch(branchRaw, git_reference_free);
git_object* treeishRaw = nullptr;
checkLibGitError( git_reference_peel(&treeishRaw, branch.get(), GIT_OBJ_TREE) );
uniquePtr<git_object> treeish(treeishRaw, git_object_free);
checkLibGitError( git_checkout_tree(smartLibGitRepository.get(), treeish.get(), &options) );
checkLibGitError( git_repository_set_head(smartLibGitRepository.get(), fullReferenceName.c_str()) );
}
void Repository::merge(const Branch& toMergeIntoHead) //git merge --no-commit -Srecursive -Xno-renames
{
if(!isInNormalState())
{
throw std::logic_error("Repository state prevents operation.");
}
if(!isOwnedByRepo(toMergeIntoHead))
{
throw std::invalid_argument("Argument is not owned by the repository.");
}
if(isCheckedOut(*toMergeIntoHead.getHead()))
{
throw std::invalid_argument("Source and destination are the same.");
}
if(isHeadDetached()) //cannot checkout a remote branch so head is on a local one
{
throw std::domain_error("Currently merge is only supported between branches but head is detached.");
}
std::string fullMergeeBranchName;
if(toMergeIntoHead.isLocal())
{
fullMergeeBranchName = "refs/heads/" + toMergeIntoHead.getName();
}
else
{
fullMergeeBranchName = "refs/remotes/" + toMergeIntoHead.getName();
}
git_reference* branchRaw = nullptr;
checkLibGitError( git_reference_lookup(&branchRaw, smartLibGitRepository.get(), fullMergeeBranchName.c_str()) );
uniquePtr<git_reference> branch(branchRaw, git_reference_free);
git_annotated_commit* headToMergeRaw = nullptr;
checkLibGitError( git_annotated_commit_from_ref(&headToMergeRaw, smartLibGitRepository.get(), branch.get()) );
uniquePtr<git_annotated_commit> headToMerge(headToMergeRaw, git_annotated_commit_free);
git_merge_analysis_t analysis;
git_merge_preference_t preference;
headToMergeRaw = headToMerge.get();
checkLibGitError( git_merge_analysis( &analysis
, &preference
, smartLibGitRepository.get()
, const_cast<const git_annotated_commit **>(&headToMergeRaw)
, 1)
);
if(GIT_MERGE_ANALYSIS_UNBORN & analysis)
{
throw std::domain_error("Currently the Repository class does not support bare repositories.");
}
if(GIT_MERGE_ANALYSIS_UP_TO_DATE & analysis)
{
return;
}
if((GIT_MERGE_PREFERENCE_FASTFORWARD_ONLY & preference) && !(GIT_MERGE_ANALYSIS_FASTFORWARD & analysis))
{
return;
}
if(!(GIT_MERGE_PREFERENCE_NO_FASTFORWARD & preference) && (GIT_MERGE_ANALYSIS_FASTFORWARD & analysis))
{
git_reference* headBranchRaw = nullptr;
checkLibGitError( git_repository_head(&headBranchRaw, smartLibGitRepository.get()) );
uniquePtr<git_reference> headBranch(headBranchRaw, git_reference_free);
checkout(toMergeIntoHead);
std::string fastforwardSha = toMergeIntoHead.getHead()->getSha();
git_oid fastforwardOid = shaToLibGitOid(fastforwardSha);
//we know the checked out branch is local
std::string fullHeadBranchName = std::string(git_reference_name(headBranch.get()));
std::string reflogMessage = std::string("branch ")
+ fullHeadBranchName
+ " fast-forwarded to "
+ toMergeIntoHead.getHead()->getSha();
git_reference* newHeadBranchRaw = nullptr;
checkLibGitError( git_reference_set_target(&newHeadBranchRaw
, headBranch.get()
, &fastforwardOid
, reflogMessage.c_str()
)
);
uniquePtr<git_reference> newHeadBranch(newHeadBranchRaw, git_reference_free);
checkLibGitError( git_repository_set_head(smartLibGitRepository.get(), fullHeadBranchName.c_str()) );
}
else
{
if(getStagedFiles().size() > 0)
{
std::logic_error("Cannot non-fastforward merge when staged files are in the repository.");
}
git_checkout_options checkoutOptions;
checkLibGitError( git_checkout_init_options(&checkoutOptions, GIT_CHECKOUT_OPTIONS_VERSION) );
checkoutOptions.checkout_strategy = GIT_CHECKOUT_SAFE;
checkoutOptions.checkout_strategy |= GIT_CHECKOUT_RECREATE_MISSING;
git_merge_options mergeOptions;
checkLibGitError( git_merge_init_options(&mergeOptions, GIT_MERGE_OPTIONS_VERSION) );
headToMergeRaw = headToMerge.get();
checkLibGitError( git_merge( smartLibGitRepository.get()
, const_cast<const git_annotated_commit **>(&headToMergeRaw)
, 1
, &mergeOptions
, &checkoutOptions
)
);
}
}
void Repository::startRebase(const Branch& toRebaseTo) // you cannot call this without a valid branch => then you can
// neither do so before init commit
{
if(!isInNormalState())
{
throw std::logic_error("Repository state prevents operation.");
}
if(!isOwnedByRepo(toRebaseTo))
{
throw std::invalid_argument("Argument is not owned by the repository.");
}
if(isHeadDetached())
{
throw std::domain_error("Currently rebase is not supported in detached HEAD state.");
}
std::string toRebaseToSha = toRebaseTo.getHead()->getSha();
std::string headSha = getHead()->getSha();
if(toRebaseToSha == headSha)
{
return;
}
std::string fullToRebaseToName = "refs/heads/" + toRebaseTo.getName(); //if it would be remote it would make this
//detached HEAD
std::string fullHeadBranchName = "refs/heads/" + getHeadBranch()->getName(); // currently no rebase allowed in
//detached head state
git_oid toRebaseToOid = shaToLibGitOid(toRebaseToSha);
git_oid headOid = shaToLibGitOid(headSha);
int errorCode = git_graph_descendant_of( smartLibGitRepository.get()
, &toRebaseToOid
, &headOid
);
if(1 == errorCode) // head is ancestor of toRebaseTo -> needs fastforward
{
git_reference* headBranchRaw = nullptr;
checkLibGitError( git_repository_head(&headBranchRaw, smartLibGitRepository.get()) );
uniquePtr<git_reference> headBranch(headBranchRaw, git_reference_free);
std::string reflogMessage = std::string("branch ")
+ fullHeadBranchName
+ " fast-forwarded to "
+ toRebaseToSha;
git_reference* newHeadBranchRaw = nullptr;
checkLibGitError( git_reference_set_target( &newHeadBranchRaw
, headBranch.get()
, &toRebaseToOid
, reflogMessage.c_str()
)
);
uniquePtr<git_reference> newHeadBranch(newHeadBranchRaw, git_reference_free);
checkLibGitError( git_repository_set_head(smartLibGitRepository.get(), fullToRebaseToName.c_str()) );
hardReset();
return;
}
else if(0 != errorCode)
{
checkLibGitError(errorCode);
}
else
{
int errorCode = git_graph_descendant_of( smartLibGitRepository.get()
, &headOid
, &toRebaseToOid
);
if(1 == errorCode) // toRebaseTo is ancestor of head
{
return;
}
else if(0 != errorCode)
{
checkLibGitError(errorCode);
}
}
git_reference* branchToRebaseToRaw = nullptr;
checkLibGitError( git_reference_lookup( &branchToRebaseToRaw
, smartLibGitRepository.get()
, fullToRebaseToName.c_str()
)
);
uniquePtr<git_reference> branchToRebaseTo(branchToRebaseToRaw, git_reference_free);
git_annotated_commit* headToRebaseToRaw = nullptr;
checkLibGitError( git_annotated_commit_from_ref( &headToRebaseToRaw
, smartLibGitRepository.get()
, branchToRebaseTo.get()
)
);
uniquePtr<git_annotated_commit> headToRebaseTo(headToRebaseToRaw, git_annotated_commit_free);
startRebase(std::move(headToRebaseTo));
}
/* private */ void Repository::startRebase(uniquePtr<git_annotated_commit> headToRebaseTo)
{
git_rebase_options options;
checkLibGitError( git_rebase_init_options(&options, GIT_REBASE_OPTIONS_VERSION) );
//nullptr -> const git_annotated_commit* The terminal commit to rebase, or NULL to rebase the current branch
//nullptr -> const git_annotated_commit* The commit to begin rebasing from, or NULL to rebase all reachable commits
git_rebase* rebaseObjectRaw = nullptr;
checkLibGitError( git_rebase_init( &rebaseObjectRaw
, smartLibGitRepository.get()
, nullptr
, nullptr
, headToRebaseTo.get()
, &options
)
);
uniquePtr<git_rebase> rebaseObject(rebaseObjectRaw, git_rebase_free);
}
void Repository::applyNextRebasePatch()
{
if(!isInRebaseState())
{
throw std::logic_error("Repository state prevents operation.");
}
git_rebase_options options;
checkLibGitError( git_rebase_init_options(&options, GIT_REBASE_OPTIONS_VERSION) );
git_rebase* rebaseRaw = nullptr;
checkLibGitError( git_rebase_open(&rebaseRaw, smartLibGitRepository.get(), &options) );
uniquePtr<git_rebase> rebase(rebaseRaw, git_rebase_free);
std::size_t operationIndex = git_rebase_operation_current(rebase.get());
git_rebase_operation* operation = nullptr;
if(GIT_REBASE_NO_OPERATION != operationIndex)
{
git_rebase_operation* operation = git_rebase_operation_byindex(rebase.get(), operationIndex);
if(nullptr == operation)
{
throw std::logic_error("Rebase operation out of index.");
}
}
checkLibGitError( git_rebase_next(&operation, rebase.get()) );
}
//including the current one
std::size_t Repository::numOfRemainingRebasePatches() const
{
if(!isInRebaseState())
{
return 0;
}
git_rebase_options options;
checkLibGitError( git_rebase_init_options(&options, GIT_REBASE_OPTIONS_VERSION) );
git_rebase* rebaseRaw = nullptr;
checkLibGitError( git_rebase_open(&rebaseRaw, smartLibGitRepository.get(), &options) );
uniquePtr<git_rebase> rebase(rebaseRaw, git_rebase_free);
std::size_t operationIndex = git_rebase_operation_current(rebase.get());
if(GIT_REBASE_NO_OPERATION == operationIndex)
{
return git_rebase_operation_entrycount(rebase.get());
}
return git_rebase_operation_entrycount(rebase.get()) - operationIndex - 1;
}
void Repository::commitCurrentRebasePatch()
{
if(!isInRebaseState())
{
throw std::logic_error("Repository state prevents operation.");
}
git_rebase_options options;
checkLibGitError( git_rebase_init_options(&options, GIT_REBASE_OPTIONS_VERSION) );
git_rebase* rebaseRaw = nullptr;
checkLibGitError( git_rebase_open(&rebaseRaw, smartLibGitRepository.get(), &options) );
uniquePtr<git_rebase> rebase(rebaseRaw, git_rebase_free);
git_signature* signatureRaw = nullptr;
checkLibGitError( git_signature_default(&signatureRaw, smartLibGitRepository.get()) );
uniquePtr<git_signature> signature(signatureRaw, git_signature_free);
git_oid oid;
//null -> keep original commit author
//null -> keep original commit message encoding
//null -> keep original commit message
int error = git_rebase_commit(&oid, rebase.get(), nullptr, signature.get(), nullptr, nullptr);
if(GIT_EAPPLIED == error)
{
//nothing to do in this case
}
else
{
checkLibGitError( error );
}
if(numOfRemainingRebasePatches() == 0)
{
checkLibGitError( git_rebase_finish(rebase.get(), signature.get()) );
}
}
std::unique_ptr<Remote> Repository::getRemote() const
{
git_strarray remoteNameList = {nullptr, 0};
int error = git_remote_list(&remoteNameList, smartLibGitRepository.get());
if(error)
{