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 package org.eclipse.jgit.lib;
50
51 import static org.eclipse.jgit.lib.Constants.LOCK_SUFFIX;
52 import static java.nio.charset.StandardCharsets.UTF_8;
53
54 import java.io.BufferedOutputStream;
55 import java.io.File;
56 import java.io.FileNotFoundException;
57 import java.io.FileOutputStream;
58 import java.io.IOException;
59 import java.io.OutputStream;
60 import java.io.UncheckedIOException;
61 import java.net.URISyntaxException;
62 import java.text.MessageFormat;
63 import java.util.Collection;
64 import java.util.Collections;
65 import java.util.HashMap;
66 import java.util.HashSet;
67 import java.util.LinkedList;
68 import java.util.List;
69 import java.util.Map;
70 import java.util.Set;
71 import java.util.concurrent.atomic.AtomicInteger;
72 import java.util.concurrent.atomic.AtomicLong;
73 import java.util.regex.Pattern;
74
75 import org.eclipse.jgit.annotations.NonNull;
76 import org.eclipse.jgit.annotations.Nullable;
77 import org.eclipse.jgit.attributes.AttributesNodeProvider;
78 import org.eclipse.jgit.dircache.DirCache;
79 import org.eclipse.jgit.errors.AmbiguousObjectException;
80 import org.eclipse.jgit.errors.CorruptObjectException;
81 import org.eclipse.jgit.errors.IncorrectObjectTypeException;
82 import org.eclipse.jgit.errors.MissingObjectException;
83 import org.eclipse.jgit.errors.NoWorkTreeException;
84 import org.eclipse.jgit.errors.RevisionSyntaxException;
85 import org.eclipse.jgit.events.IndexChangedEvent;
86 import org.eclipse.jgit.events.IndexChangedListener;
87 import org.eclipse.jgit.events.ListenerList;
88 import org.eclipse.jgit.events.RepositoryEvent;
89 import org.eclipse.jgit.internal.JGitText;
90 import org.eclipse.jgit.revwalk.RevBlob;
91 import org.eclipse.jgit.revwalk.RevCommit;
92 import org.eclipse.jgit.revwalk.RevObject;
93 import org.eclipse.jgit.revwalk.RevTree;
94 import org.eclipse.jgit.revwalk.RevWalk;
95 import org.eclipse.jgit.transport.RefSpec;
96 import org.eclipse.jgit.transport.RemoteConfig;
97 import org.eclipse.jgit.treewalk.TreeWalk;
98 import org.eclipse.jgit.util.FS;
99 import org.eclipse.jgit.util.FileUtils;
100 import org.eclipse.jgit.util.IO;
101 import org.eclipse.jgit.util.RawParseUtils;
102 import org.eclipse.jgit.util.SystemReader;
103 import org.slf4j.Logger;
104 import org.slf4j.LoggerFactory;
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120 public abstract class Repository implements AutoCloseable {
121 private static final Logger LOG = LoggerFactory.getLogger(Repository.class);
122 private static final ListenerLististenerList">ListenerList globalListeners = new ListenerList();
123
124
125
126
127
128
129
130 private static final Pattern FORBIDDEN_BRANCH_NAME_COMPONENTS = Pattern
131 .compile(
132 "(^|/)(aux|com[1-9]|con|lpt[1-9]|nul|prn)(\\.[^/]*)?",
133 Pattern.CASE_INSENSITIVE);
134
135
136
137
138
139
140 public static ListenerList getGlobalListenerList() {
141 return globalListeners;
142 }
143
144
145 final AtomicInteger useCnt = new AtomicInteger(1);
146
147 final AtomicLong closedAt = new AtomicLong();
148
149
150 private final File gitDir;
151
152
153 private final FS fs;
154
155 private final ListenerListml#ListenerList">ListenerList myListeners = new ListenerList();
156
157
158 private final File workTree;
159
160
161 private final File indexFile;
162
163
164
165
166
167
168
169 protected Repository(BaseRepositoryBuilder options) {
170 gitDir = options.getGitDir();
171 fs = options.getFS();
172 workTree = options.getWorkTree();
173 indexFile = options.getIndexFile();
174 }
175
176
177
178
179
180
181 @NonNull
182 public ListenerList getListenerList() {
183 return myListeners;
184 }
185
186
187
188
189
190
191
192
193
194
195 public void fireEvent(RepositoryEvent<?> event) {
196 event.setRepository(this);
197 myListeners.dispatch(event);
198 globalListeners.dispatch(event);
199 }
200
201
202
203
204
205
206
207
208
209
210 public void create() throws IOException {
211 create(false);
212 }
213
214
215
216
217
218
219
220
221
222
223
224 public abstract void create(boolean bare) throws IOException;
225
226
227
228
229
230
231
232
233
234
235
236
237
238 public File getDirectory() {
239 return gitDir;
240 }
241
242
243
244
245
246
247
248
249 public abstract String getIdentifier();
250
251
252
253
254
255
256 @NonNull
257 public abstract ObjectDatabase getObjectDatabase();
258
259
260
261
262
263
264 @NonNull
265 public ObjectInserter newObjectInserter() {
266 return getObjectDatabase().newInserter();
267 }
268
269
270
271
272
273
274 @NonNull
275 public ObjectReader newObjectReader() {
276 return getObjectDatabase().newReader();
277 }
278
279
280
281
282
283
284 @NonNull
285 public abstract RefDatabase getRefDatabase();
286
287
288
289
290
291
292 @NonNull
293 public abstract StoredConfig getConfig();
294
295
296
297
298
299
300
301
302
303
304 @NonNull
305 public abstract AttributesNodeProvider createAttributesNodeProvider();
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320 public FS getFS() {
321 return fs;
322 }
323
324
325
326
327
328
329
330
331
332
333
334 @Deprecated
335 public boolean hasObject(AnyObjectId objectId) {
336 try {
337 return getObjectDatabase().has(objectId);
338 } catch (IOException e) {
339 throw new UncheckedIOException(e);
340 }
341 }
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358 @NonNull
359 public ObjectLoader open(AnyObjectId objectId)
360 throws MissingObjectException, IOException {
361 return getObjectDatabase().open(objectId);
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 @NonNull
388 public ObjectLoader open(AnyObjectId objectId, int typeHint)
389 throws MissingObjectException, IncorrectObjectTypeException,
390 IOException {
391 return getObjectDatabase().open(objectId, typeHint);
392 }
393
394
395
396
397
398
399
400
401
402
403
404
405
406 @NonNull
407 public RefUpdate updateRef(String ref) throws IOException {
408 return updateRef(ref, false);
409 }
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425 @NonNull
426 public RefUpdate updateRef(String ref, boolean detach) throws IOException {
427 return getRefDatabase().newUpdate(ref, detach);
428 }
429
430
431
432
433
434
435
436
437
438
439
440
441 @NonNull
442 public RefRename renameRef(String fromRef, String toRef) throws IOException {
443 return getRefDatabase().newRename(fromRef, toRef);
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 @Nullable
497 public ObjectId resolve(String revstr)
498 throws AmbiguousObjectException, IncorrectObjectTypeException,
499 RevisionSyntaxException, IOException {
500 try (RevWalkRevWalk.html#RevWalk">RevWalk rw = new RevWalk(this)) {
501 rw.setRetainBody(false);
502 Object resolved = resolve(rw, revstr);
503 if (resolved instanceof String) {
504 final Ref ref = findRef((String) resolved);
505 return ref != null ? ref.getLeaf().getObjectId() : null;
506 }
507 return (ObjectId) resolved;
508 }
509 }
510
511
512
513
514
515
516
517
518
519
520
521
522
523 @Nullable
524 public String simplify(String revstr)
525 throws AmbiguousObjectException, IOException {
526 try (RevWalkRevWalk.html#RevWalk">RevWalk rw = new RevWalk(this)) {
527 rw.setRetainBody(true);
528 Object resolved = resolve(rw, revstr);
529 if (resolved != null) {
530 if (resolved instanceof String) {
531 return (String) resolved;
532 }
533 return ((AnyObjectId) resolved).getName();
534 }
535 return null;
536 }
537 }
538
539 @Nullable
540 private Object resolve(RevWalk rw, String revstr)
541 throws IOException {
542 char[] revChars = revstr.toCharArray();
543 RevObject rev = null;
544 String name = null;
545 int done = 0;
546 for (int i = 0; i < revChars.length; ++i) {
547 switch (revChars[i]) {
548 case '^':
549 if (rev == null) {
550 if (name == null)
551 if (done == 0)
552 name = new String(revChars, done, i);
553 else {
554 done = i + 1;
555 break;
556 }
557 rev = parseSimple(rw, name);
558 name = null;
559 if (rev == null)
560 return null;
561 }
562 if (i + 1 < revChars.length) {
563 switch (revChars[i + 1]) {
564 case '0':
565 case '1':
566 case '2':
567 case '3':
568 case '4':
569 case '5':
570 case '6':
571 case '7':
572 case '8':
573 case '9':
574 int j;
575 rev = rw.parseCommit(rev);
576 for (j = i + 1; j < revChars.length; ++j) {
577 if (!Character.isDigit(revChars[j]))
578 break;
579 }
580 String parentnum = new String(revChars, i + 1, j - i
581 - 1);
582 int pnum;
583 try {
584 pnum = Integer.parseInt(parentnum);
585 } catch (NumberFormatException e) {
586 throw new RevisionSyntaxException(
587 JGitText.get().invalidCommitParentNumber,
588 revstr);
589 }
590 if (pnum != 0) {
591 RevCommit commit = (RevCommit) rev;
592 if (pnum > commit.getParentCount())
593 rev = null;
594 else
595 rev = commit.getParent(pnum - 1);
596 }
597 i = j - 1;
598 done = j;
599 break;
600 case '{':
601 int k;
602 String item = null;
603 for (k = i + 2; k < revChars.length; ++k) {
604 if (revChars[k] == '}') {
605 item = new String(revChars, i + 2, k - i - 2);
606 break;
607 }
608 }
609 i = k;
610 if (item != null)
611 if (item.equals("tree")) {
612 rev = rw.parseTree(rev);
613 } else if (item.equals("commit")) {
614 rev = rw.parseCommit(rev);
615 } else if (item.equals("blob")) {
616 rev = rw.peel(rev);
617 if (!(rev instanceof RevBlob))
618 throw new IncorrectObjectTypeException(rev,
619 Constants.TYPE_BLOB);
620 } else if (item.isEmpty()) {
621 rev = rw.peel(rev);
622 } else
623 throw new RevisionSyntaxException(revstr);
624 else
625 throw new RevisionSyntaxException(revstr);
626 done = k;
627 break;
628 default:
629 rev = rw.peel(rev);
630 if (rev instanceof RevCommit) {
631 RevCommit commit = ((RevCommit) rev);
632 if (commit.getParentCount() == 0)
633 rev = null;
634 else
635 rev = commit.getParent(0);
636 } else
637 throw new IncorrectObjectTypeException(rev,
638 Constants.TYPE_COMMIT);
639 }
640 } else {
641 rev = rw.peel(rev);
642 if (rev instanceof RevCommit) {
643 RevCommit commit = ((RevCommit) rev);
644 if (commit.getParentCount() == 0)
645 rev = null;
646 else
647 rev = commit.getParent(0);
648 } else
649 throw new IncorrectObjectTypeException(rev,
650 Constants.TYPE_COMMIT);
651 }
652 done = i + 1;
653 break;
654 case '~':
655 if (rev == null) {
656 if (name == null)
657 if (done == 0)
658 name = new String(revChars, done, i);
659 else {
660 done = i + 1;
661 break;
662 }
663 rev = parseSimple(rw, name);
664 name = null;
665 if (rev == null)
666 return null;
667 }
668 rev = rw.peel(rev);
669 if (!(rev instanceof RevCommit))
670 throw new IncorrectObjectTypeException(rev,
671 Constants.TYPE_COMMIT);
672 int l;
673 for (l = i + 1; l < revChars.length; ++l) {
674 if (!Character.isDigit(revChars[l]))
675 break;
676 }
677 int dist;
678 if (l - i > 1) {
679 String distnum = new String(revChars, i + 1, l - i - 1);
680 try {
681 dist = Integer.parseInt(distnum);
682 } catch (NumberFormatException e) {
683 throw new RevisionSyntaxException(
684 JGitText.get().invalidAncestryLength, revstr);
685 }
686 } else
687 dist = 1;
688 while (dist > 0) {
689 RevCommit commit = (RevCommit) rev;
690 if (commit.getParentCount() == 0) {
691 rev = null;
692 break;
693 }
694 commit = commit.getParent(0);
695 rw.parseHeaders(commit);
696 rev = commit;
697 --dist;
698 }
699 i = l - 1;
700 done = l;
701 break;
702 case '@':
703 if (rev != null)
704 throw new RevisionSyntaxException(revstr);
705 if (i + 1 == revChars.length)
706 continue;
707 if (i + 1 < revChars.length && revChars[i + 1] != '{')
708 continue;
709 int m;
710 String time = null;
711 for (m = i + 2; m < revChars.length; ++m) {
712 if (revChars[m] == '}') {
713 time = new String(revChars, i + 2, m - i - 2);
714 break;
715 }
716 }
717 if (time != null) {
718 if (time.equals("upstream")) {
719 if (name == null)
720 name = new String(revChars, done, i);
721 if (name.isEmpty())
722
723
724 name = Constants.HEAD;
725 if (!Repository.isValidRefName("x/" + name))
726 throw new RevisionSyntaxException(MessageFormat
727 .format(JGitText.get().invalidRefName,
728 name),
729 revstr);
730 Ref ref = findRef(name);
731 name = null;
732 if (ref == null)
733 return null;
734 if (ref.isSymbolic())
735 ref = ref.getLeaf();
736 name = ref.getName();
737
738 RemoteConfig remoteConfig;
739 try {
740 remoteConfig = new RemoteConfig(getConfig(),
741 "origin");
742 } catch (URISyntaxException e) {
743 throw new RevisionSyntaxException(revstr);
744 }
745 String remoteBranchName = getConfig()
746 .getString(
747 ConfigConstants.CONFIG_BRANCH_SECTION,
748 Repository.shortenRefName(ref.getName()),
749 ConfigConstants.CONFIG_KEY_MERGE);
750 List<RefSpec> fetchRefSpecs = remoteConfig
751 .getFetchRefSpecs();
752 for (RefSpec refSpec : fetchRefSpecs) {
753 if (refSpec.matchSource(remoteBranchName)) {
754 RefSpec expandFromSource = refSpec
755 .expandFromSource(remoteBranchName);
756 name = expandFromSource.getDestination();
757 break;
758 }
759 }
760 if (name == null)
761 throw new RevisionSyntaxException(revstr);
762 } else if (time.matches("^-\\d+$")) {
763 if (name != null) {
764 throw new RevisionSyntaxException(revstr);
765 }
766 String previousCheckout = resolveReflogCheckout(
767 -Integer.parseInt(time));
768 if (ObjectId.isId(previousCheckout)) {
769 rev = parseSimple(rw, previousCheckout);
770 } else {
771 name = previousCheckout;
772 }
773 } else {
774 if (name == null)
775 name = new String(revChars, done, i);
776 if (name.isEmpty())
777 name = Constants.HEAD;
778 if (!Repository.isValidRefName("x/" + name))
779 throw new RevisionSyntaxException(MessageFormat
780 .format(JGitText.get().invalidRefName,
781 name),
782 revstr);
783 Ref ref = findRef(name);
784 name = null;
785 if (ref == null)
786 return null;
787
788
789 if (ref.isSymbolic())
790 ref = ref.getLeaf();
791 rev = resolveReflog(rw, ref, time);
792 }
793 i = m;
794 } else
795 throw new RevisionSyntaxException(revstr);
796 break;
797 case ':': {
798 RevTree tree;
799 if (rev == null) {
800 if (name == null)
801 name = new String(revChars, done, i);
802 if (name.isEmpty())
803 name = Constants.HEAD;
804 rev = parseSimple(rw, name);
805 name = null;
806 }
807 if (rev == null)
808 return null;
809 tree = rw.parseTree(rev);
810 if (i == revChars.length - 1)
811 return tree.copy();
812
813 TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(),
814 new String(revChars, i + 1, revChars.length - i - 1),
815 tree);
816 return tw != null ? tw.getObjectId(0) : null;
817 }
818 default:
819 if (rev != null)
820 throw new RevisionSyntaxException(revstr);
821 }
822 }
823 if (rev != null)
824 return rev.copy();
825 if (name != null)
826 return name;
827 if (done == revstr.length())
828 return null;
829 name = revstr.substring(done);
830 if (!Repository.isValidRefName("x/" + name))
831 throw new RevisionSyntaxException(
832 MessageFormat.format(JGitText.get().invalidRefName, name),
833 revstr);
834 if (findRef(name) != null)
835 return name;
836 return resolveSimple(name);
837 }
838
839 private static boolean isHex(char c) {
840 return ('0' <= c && c <= '9')
841 || ('a' <= c && c <= 'f')
842 || ('A' <= c && c <= 'F');
843 }
844
845 private static boolean isAllHex(String str, int ptr) {
846 while (ptr < str.length()) {
847 if (!isHex(str.charAt(ptr++)))
848 return false;
849 }
850 return true;
851 }
852
853 @Nullable
854 private RevObject parseSimple(RevWalk rw, String revstr) throws IOException {
855 ObjectId id = resolveSimple(revstr);
856 return id != null ? rw.parseAny(id) : null;
857 }
858
859 @Nullable
860 private ObjectId resolveSimple(String revstr) throws IOException {
861 if (ObjectId.isId(revstr))
862 return ObjectId.fromString(revstr);
863
864 if (Repository.isValidRefName("x/" + revstr)) {
865 Ref r = getRefDatabase().findRef(revstr);
866 if (r != null)
867 return r.getObjectId();
868 }
869
870 if (AbbreviatedObjectId.isId(revstr))
871 return resolveAbbreviation(revstr);
872
873 int dashg = revstr.indexOf("-g");
874 if ((dashg + 5) < revstr.length() && 0 <= dashg
875 && isHex(revstr.charAt(dashg + 2))
876 && isHex(revstr.charAt(dashg + 3))
877 && isAllHex(revstr, dashg + 4)) {
878
879 String s = revstr.substring(dashg + 2);
880 if (AbbreviatedObjectId.isId(s))
881 return resolveAbbreviation(s);
882 }
883
884 return null;
885 }
886
887 @Nullable
888 private String resolveReflogCheckout(int checkoutNo)
889 throws IOException {
890 ReflogReader reader = getReflogReader(Constants.HEAD);
891 if (reader == null) {
892 return null;
893 }
894 List<ReflogEntry> reflogEntries = reader.getReverseEntries();
895 for (ReflogEntry entry : reflogEntries) {
896 CheckoutEntry checkout = entry.parseCheckout();
897 if (checkout != null)
898 if (checkoutNo-- == 1)
899 return checkout.getFromBranch();
900 }
901 return null;
902 }
903
904 private RevCommit resolveReflog(RevWalk rw, Ref ref, String time)
905 throws IOException {
906 int number;
907 try {
908 number = Integer.parseInt(time);
909 } catch (NumberFormatException nfe) {
910 throw new RevisionSyntaxException(MessageFormat.format(
911 JGitText.get().invalidReflogRevision, time));
912 }
913 assert number >= 0;
914 ReflogReader reader = getReflogReader(ref.getName());
915 if (reader == null) {
916 throw new RevisionSyntaxException(
917 MessageFormat.format(JGitText.get().reflogEntryNotFound,
918 Integer.valueOf(number), ref.getName()));
919 }
920 ReflogEntry entry = reader.getReverseEntry(number);
921 if (entry == null)
922 throw new RevisionSyntaxException(MessageFormat.format(
923 JGitText.get().reflogEntryNotFound,
924 Integer.valueOf(number), ref.getName()));
925
926 return rw.parseCommit(entry.getNewId());
927 }
928
929 @Nullable
930 private ObjectId resolveAbbreviation(String revstr) throws IOException,
931 AmbiguousObjectException {
932 AbbreviatedObjectId id = AbbreviatedObjectId.fromString(revstr);
933 try (ObjectReader reader = newObjectReader()) {
934 Collection<ObjectId> matches = reader.resolve(id);
935 if (matches.isEmpty())
936 return null;
937 else if (matches.size() == 1)
938 return matches.iterator().next();
939 else
940 throw new AmbiguousObjectException(id, matches);
941 }
942 }
943
944
945
946
947 public void incrementOpen() {
948 useCnt.incrementAndGet();
949 }
950
951
952
953
954
955
956 @Override
957 public void close() {
958 int newCount = useCnt.decrementAndGet();
959 if (newCount == 0) {
960 if (RepositoryCache.isCached(this)) {
961 closedAt.set(System.currentTimeMillis());
962 } else {
963 doClose();
964 }
965 } else if (newCount == -1) {
966
967
968 String message = MessageFormat.format(JGitText.get().corruptUseCnt,
969 toString());
970 if (LOG.isDebugEnabled()) {
971 LOG.debug(message, new IllegalStateException());
972 } else {
973 LOG.warn(message);
974 }
975 if (RepositoryCache.isCached(this)) {
976 closedAt.set(System.currentTimeMillis());
977 }
978 }
979 }
980
981
982
983
984
985
986 protected void doClose() {
987 getObjectDatabase().close();
988 getRefDatabase().close();
989 }
990
991
992 @Override
993 @NonNull
994 public String toString() {
995 String desc;
996 File directory = getDirectory();
997 if (directory != null)
998 desc = directory.getPath();
999 else
1000 desc = getClass().getSimpleName() + "-"
1001 + System.identityHashCode(this);
1002 return "Repository[" + desc + "]";
1003 }
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023 @Nullable
1024 public String getFullBranch() throws IOException {
1025 Ref head = exactRef(Constants.HEAD);
1026 if (head == null) {
1027 return null;
1028 }
1029 if (head.isSymbolic()) {
1030 return head.getTarget().getName();
1031 }
1032 ObjectId objectId = head.getObjectId();
1033 if (objectId != null) {
1034 return objectId.name();
1035 }
1036 return null;
1037 }
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051 @Nullable
1052 public String getBranch() throws IOException {
1053 String name = getFullBranch();
1054 if (name != null)
1055 return shortenRefName(name);
1056 return null;
1057 }
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069 @NonNull
1070 public Set<ObjectId> getAdditionalHaves() {
1071 return Collections.emptySet();
1072 }
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085 @Nullable
1086 public final Ref exactRef(String name) throws IOException {
1087 return getRefDatabase().exactRef(name);
1088 }
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101 @Nullable
1102 public final Ref findRef(String name) throws IOException {
1103 return getRefDatabase().findRef(name);
1104 }
1105
1106
1107
1108
1109
1110
1111
1112
1113 @Deprecated
1114 @NonNull
1115 public Map<String, Ref> getAllRefs() {
1116 try {
1117 return getRefDatabase().getRefs(RefDatabase.ALL);
1118 } catch (IOException e) {
1119 throw new UncheckedIOException(e);
1120 }
1121 }
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131 @Deprecated
1132 @NonNull
1133 public Map<String, Ref> getTags() {
1134 try {
1135 return getRefDatabase().getRefs(Constants.R_TAGS);
1136 } catch (IOException e) {
1137 throw new UncheckedIOException(e);
1138 }
1139 }
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156 @Deprecated
1157 @NonNull
1158 public Ref" href="../../../../org/eclipse/jgit/lib/Ref.html#Ref">Ref peel(Ref ref) {
1159 try {
1160 return getRefDatabase().peel(ref);
1161 } catch (IOException e) {
1162
1163
1164
1165 return ref;
1166 }
1167 }
1168
1169
1170
1171
1172
1173
1174 @NonNull
1175 public Map<AnyObjectId, Set<Ref>> getAllRefsByPeeledObjectId() {
1176 Map<String, Ref> allRefs = getAllRefs();
1177 Map<AnyObjectId, Set<Ref>> ret = new HashMap<>(allRefs.size());
1178 for (Ref ref : allRefs.values()) {
1179 ref = peel(ref);
1180 AnyObjectId target = ref.getPeeledObjectId();
1181 if (target == null)
1182 target = ref.getObjectId();
1183
1184 Set<Ref> oset = ret.put(target, Collections.singleton(ref));
1185 if (oset != null) {
1186
1187 if (oset.size() == 1) {
1188
1189 oset = new HashSet<>(oset);
1190 }
1191 ret.put(target, oset);
1192 oset.add(ref);
1193 }
1194 }
1195 return ret;
1196 }
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207 @NonNull
1208 public File getIndexFile() throws NoWorkTreeException {
1209 if (isBare())
1210 throw new NoWorkTreeException();
1211 return indexFile;
1212 }
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231 public RevCommit parseCommit(AnyObjectId id) throws IncorrectObjectTypeException,
1232 IOException, MissingObjectException {
1233 if (id instanceof RevCommit../../org/eclipse/jgit/revwalk/RevCommit.html#RevCommit">RevCommit && ((RevCommit) id).getRawBuffer() != null) {
1234 return (RevCommit) id;
1235 }
1236 try (RevWalkvWalk.html#RevWalk">RevWalk walk = new RevWalk(this)) {
1237 return walk.parseCommit(id);
1238 }
1239 }
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259 @NonNull
1260 public DirCache readDirCache() throws NoWorkTreeException,
1261 CorruptObjectException, IOException {
1262 return DirCache.read(this);
1263 }
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284 @NonNull
1285 public DirCache lockDirCache() throws NoWorkTreeException,
1286 CorruptObjectException, IOException {
1287
1288
1289 IndexChangedListener l = (IndexChangedEvent event) -> {
1290 notifyIndexChanged(true);
1291 };
1292 return DirCache.lock(this, l);
1293 }
1294
1295
1296
1297
1298
1299
1300 @NonNull
1301 public RepositoryState getRepositoryState() {
1302 if (isBare() || getDirectory() == null)
1303 return RepositoryState.BARE;
1304
1305
1306 if (new File(getWorkTree(), ".dotest").exists())
1307 return RepositoryState.REBASING;
1308 if (new File(getDirectory(), ".dotest-merge").exists())
1309 return RepositoryState.REBASING_INTERACTIVE;
1310
1311
1312 if (new File(getDirectory(),"rebase-apply/rebasing").exists())
1313 return RepositoryState.REBASING_REBASING;
1314 if (new File(getDirectory(),"rebase-apply/applying").exists())
1315 return RepositoryState.APPLY;
1316 if (new File(getDirectory(),"rebase-apply").exists())
1317 return RepositoryState.REBASING;
1318
1319 if (new File(getDirectory(),"rebase-merge/interactive").exists())
1320 return RepositoryState.REBASING_INTERACTIVE;
1321 if (new File(getDirectory(),"rebase-merge").exists())
1322 return RepositoryState.REBASING_MERGE;
1323
1324
1325 if (new File(getDirectory(), Constants.MERGE_HEAD).exists()) {
1326
1327 try {
1328 if (!readDirCache().hasUnmergedPaths()) {
1329
1330 return RepositoryState.MERGING_RESOLVED;
1331 }
1332 } catch (IOException e) {
1333 throw new UncheckedIOException(e);
1334 }
1335 return RepositoryState.MERGING;
1336 }
1337
1338 if (new File(getDirectory(), "BISECT_LOG").exists())
1339 return RepositoryState.BISECTING;
1340
1341 if (new File(getDirectory(), Constants.CHERRY_PICK_HEAD).exists()) {
1342 try {
1343 if (!readDirCache().hasUnmergedPaths()) {
1344
1345 return RepositoryState.CHERRY_PICKING_RESOLVED;
1346 }
1347 } catch (IOException e) {
1348 throw new UncheckedIOException(e);
1349 }
1350
1351 return RepositoryState.CHERRY_PICKING;
1352 }
1353
1354 if (new File(getDirectory(), Constants.REVERT_HEAD).exists()) {
1355 try {
1356 if (!readDirCache().hasUnmergedPaths()) {
1357
1358 return RepositoryState.REVERTING_RESOLVED;
1359 }
1360 } catch (IOException e) {
1361 throw new UncheckedIOException(e);
1362 }
1363
1364 return RepositoryState.REVERTING;
1365 }
1366
1367 return RepositoryState.SAFE;
1368 }
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380 public static boolean isValidRefName(String refName) {
1381 final int len = refName.length();
1382 if (len == 0) {
1383 return false;
1384 }
1385 if (refName.endsWith(LOCK_SUFFIX)) {
1386 return false;
1387 }
1388
1389
1390
1391 try {
1392 SystemReader.getInstance().checkPath(refName);
1393 } catch (CorruptObjectException e) {
1394 return false;
1395 }
1396
1397 int components = 1;
1398 char p = '\0';
1399 for (int i = 0; i < len; i++) {
1400 final char c = refName.charAt(i);
1401 if (c <= ' ')
1402 return false;
1403 switch (c) {
1404 case '.':
1405 switch (p) {
1406 case '\0': case '/': case '.':
1407 return false;
1408 }
1409 if (i == len -1)
1410 return false;
1411 break;
1412 case '/':
1413 if (i == 0 || i == len - 1)
1414 return false;
1415 if (p == '/')
1416 return false;
1417 components++;
1418 break;
1419 case '{':
1420 if (p == '@')
1421 return false;
1422 break;
1423 case '~': case '^': case ':':
1424 case '?': case '[': case '*':
1425 case '\\':
1426 case '\u007F':
1427 return false;
1428 }
1429 p = c;
1430 }
1431 return components > 1;
1432 }
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455 public static String normalizeBranchName(String name) {
1456 if (name == null || name.isEmpty()) {
1457 return "";
1458 }
1459 String result = name.trim();
1460 String fullName = result.startsWith(Constants.R_HEADS) ? result
1461 : Constants.R_HEADS + result;
1462 if (isValidRefName(fullName)) {
1463 return result;
1464 }
1465
1466
1467 result = result.replaceAll("(?:\\h|\\v)+", "_");
1468 StringBuilder b = new StringBuilder();
1469 char p = '/';
1470 for (int i = 0, len = result.length(); i < len; i++) {
1471 char c = result.charAt(i);
1472 if (c < ' ' || c == 127) {
1473 continue;
1474 }
1475
1476 switch (c) {
1477 case '\\':
1478 case '^':
1479 case '~':
1480 case ':':
1481 case '?':
1482 case '*':
1483 case '[':
1484 case '@':
1485 case '<':
1486 case '>':
1487 case '|':
1488 case '"':
1489 c = '-';
1490 break;
1491 default:
1492 break;
1493 }
1494
1495
1496 switch (c) {
1497 case '/':
1498 if (p == '/') {
1499 continue;
1500 }
1501 p = '/';
1502 break;
1503 case '.':
1504 case '_':
1505 case '-':
1506 if (p == '/' || p == '-') {
1507 continue;
1508 }
1509 p = '-';
1510 break;
1511 default:
1512 p = c;
1513 break;
1514 }
1515 b.append(c);
1516 }
1517
1518 result = b.toString().replaceFirst("[/_.-]+$", "")
1519 .replaceAll("\\.lock($|/)", "_lock$1");
1520 return FORBIDDEN_BRANCH_NAME_COMPONENTS.matcher(result)
1521 .replaceAll("$1+$2$3");
1522 }
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534 @NonNull
1535 public static String stripWorkDir(File workDir, File file) {
1536 final String filePath = file.getPath();
1537 final String workDirPath = workDir.getPath();
1538
1539 if (filePath.length() <= workDirPath.length()
1540 || filePath.charAt(workDirPath.length()) != File.separatorChar
1541 || !filePath.startsWith(workDirPath)) {
1542 File absWd = workDir.isAbsolute() ? workDir
1543 : workDir.getAbsoluteFile();
1544 File absFile = file.isAbsolute() ? file : file.getAbsoluteFile();
1545 if (absWd.equals(workDir) && absFile.equals(file)) {
1546 return "";
1547 }
1548 return stripWorkDir(absWd, absFile);
1549 }
1550
1551 String relName = filePath.substring(workDirPath.length() + 1);
1552 if (File.separatorChar != '/') {
1553 relName = relName.replace(File.separatorChar, '/');
1554 }
1555 return relName;
1556 }
1557
1558
1559
1560
1561
1562
1563 public boolean isBare() {
1564 return workTree == null;
1565 }
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577 @NonNull
1578 public File getWorkTree() throws NoWorkTreeException {
1579 if (isBare())
1580 throw new NoWorkTreeException();
1581 return workTree;
1582 }
1583
1584
1585
1586
1587
1588
1589
1590 public abstract void scanForRepoChanges() throws IOException;
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600 public abstract void notifyIndexChanged(boolean internal);
1601
1602
1603
1604
1605
1606
1607
1608
1609 @NonNull
1610 public static String shortenRefName(String refName) {
1611 if (refName.startsWith(Constants.R_HEADS))
1612 return refName.substring(Constants.R_HEADS.length());
1613 if (refName.startsWith(Constants.R_TAGS))
1614 return refName.substring(Constants.R_TAGS.length());
1615 if (refName.startsWith(Constants.R_REMOTES))
1616 return refName.substring(Constants.R_REMOTES.length());
1617 return refName;
1618 }
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631 @Nullable
1632 public String shortenRemoteBranchName(String refName) {
1633 for (String remote : getRemoteNames()) {
1634 String remotePrefix = Constants.R_REMOTES + remote + "/";
1635 if (refName.startsWith(remotePrefix))
1636 return refName.substring(remotePrefix.length());
1637 }
1638 return null;
1639 }
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652 @Nullable
1653 public String getRemoteName(String refName) {
1654 for (String remote : getRemoteNames()) {
1655 String remotePrefix = Constants.R_REMOTES + remote + "/";
1656 if (refName.startsWith(remotePrefix))
1657 return remote;
1658 }
1659 return null;
1660 }
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670 @Nullable
1671 public String getGitwebDescription() throws IOException {
1672 return null;
1673 }
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684 public void setGitwebDescription(@Nullable String description)
1685 throws IOException {
1686 throw new IOException(JGitText.get().unsupportedRepositoryDescription);
1687 }
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700 @Nullable
1701 public abstract ReflogReader getReflogReader(String refName)
1702 throws IOException;
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716 @Nullable
1717 public String readMergeCommitMsg() throws IOException, NoWorkTreeException {
1718 return readCommitMsgFile(Constants.MERGE_MSG);
1719 }
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732 public void writeMergeCommitMsg(String msg) throws IOException {
1733 File mergeMsgFile = new File(gitDir, Constants.MERGE_MSG);
1734 writeCommitMsg(mergeMsgFile, msg);
1735 }
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750 @Nullable
1751 public String readCommitEditMsg() throws IOException, NoWorkTreeException {
1752 return readCommitMsgFile(Constants.COMMIT_EDITMSG);
1753 }
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766 public void writeCommitEditMsg(String msg) throws IOException {
1767 File commiEditMsgFile = new File(gitDir, Constants.COMMIT_EDITMSG);
1768 writeCommitMsg(commiEditMsgFile, msg);
1769 }
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784 @Nullable
1785 public List<ObjectId> readMergeHeads() throws IOException, NoWorkTreeException {
1786 if (isBare() || getDirectory() == null)
1787 throw new NoWorkTreeException();
1788
1789 byte[] raw = readGitDirectoryFile(Constants.MERGE_HEAD);
1790 if (raw == null)
1791 return null;
1792
1793 LinkedList<ObjectId> heads = new LinkedList<>();
1794 for (int p = 0; p < raw.length;) {
1795 heads.add(ObjectId.fromString(raw, p));
1796 p = RawParseUtils
1797 .nextLF(raw, p + Constants.OBJECT_ID_STRING_LENGTH);
1798 }
1799 return heads;
1800 }
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813 public void writeMergeHeads(List<? extends ObjectId> heads) throws IOException {
1814 writeHeadsFile(heads, Constants.MERGE_HEAD);
1815 }
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828 @Nullable
1829 public ObjectId readCherryPickHead() throws IOException,
1830 NoWorkTreeException {
1831 if (isBare() || getDirectory() == null)
1832 throw new NoWorkTreeException();
1833
1834 byte[] raw = readGitDirectoryFile(Constants.CHERRY_PICK_HEAD);
1835 if (raw == null)
1836 return null;
1837
1838 return ObjectId.fromString(raw, 0);
1839 }
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852 @Nullable
1853 public ObjectId readRevertHead() throws IOException, NoWorkTreeException {
1854 if (isBare() || getDirectory() == null)
1855 throw new NoWorkTreeException();
1856
1857 byte[] raw = readGitDirectoryFile(Constants.REVERT_HEAD);
1858 if (raw == null)
1859 return null;
1860 return ObjectId.fromString(raw, 0);
1861 }
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872 public void writeCherryPickHead(ObjectId head) throws IOException {
1873 List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
1874 : null;
1875 writeHeadsFile(heads, Constants.CHERRY_PICK_HEAD);
1876 }
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887 public void writeRevertHead(ObjectId head) throws IOException {
1888 List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
1889 : null;
1890 writeHeadsFile(heads, Constants.REVERT_HEAD);
1891 }
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901 public void writeOrigHead(ObjectId head) throws IOException {
1902 List<ObjectId> heads = head != null ? Collections.singletonList(head)
1903 : null;
1904 writeHeadsFile(heads, Constants.ORIG_HEAD);
1905 }
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918 @Nullable
1919 public ObjectId readOrigHead() throws IOException, NoWorkTreeException {
1920 if (isBare() || getDirectory() == null)
1921 throw new NoWorkTreeException();
1922
1923 byte[] raw = readGitDirectoryFile(Constants.ORIG_HEAD);
1924 return raw != null ? ObjectId.fromString(raw, 0) : null;
1925 }
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939 @Nullable
1940 public String readSquashCommitMsg() throws IOException {
1941 return readCommitMsgFile(Constants.SQUASH_MSG);
1942 }
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955 public void writeSquashCommitMsg(String msg) throws IOException {
1956 File squashMsgFile = new File(gitDir, Constants.SQUASH_MSG);
1957 writeCommitMsg(squashMsgFile, msg);
1958 }
1959
1960 @Nullable
1961 private String readCommitMsgFile(String msgFilename) throws IOException {
1962 if (isBare() || getDirectory() == null)
1963 throw new NoWorkTreeException();
1964
1965 File mergeMsgFile = new File(getDirectory(), msgFilename);
1966 try {
1967 return RawParseUtils.decode(IO.readFully(mergeMsgFile));
1968 } catch (FileNotFoundException e) {
1969 if (mergeMsgFile.exists()) {
1970 throw e;
1971 }
1972
1973 return null;
1974 }
1975 }
1976
1977 private void writeCommitMsg(File msgFile, String msg) throws IOException {
1978 if (msg != null) {
1979 try (FileOutputStream fos = new FileOutputStream(msgFile)) {
1980 fos.write(msg.getBytes(UTF_8));
1981 }
1982 } else {
1983 FileUtils.delete(msgFile, FileUtils.SKIP_MISSING);
1984 }
1985 }
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995 private byte[] readGitDirectoryFile(String filename) throws IOException {
1996 File file = new File(getDirectory(), filename);
1997 try {
1998 byte[] raw = IO.readFully(file);
1999 return raw.length > 0 ? raw : null;
2000 } catch (FileNotFoundException notFound) {
2001 if (file.exists()) {
2002 throw notFound;
2003 }
2004 return null;
2005 }
2006 }
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018 private void writeHeadsFile(List<? extends ObjectId> heads, String filename)
2019 throws FileNotFoundException, IOException {
2020 File headsFile = new File(getDirectory(), filename);
2021 if (heads != null) {
2022 try (OutputStream bos = new BufferedOutputStream(
2023 new FileOutputStream(headsFile))) {
2024 for (ObjectId id : heads) {
2025 id.copyTo(bos);
2026 bos.write('\n');
2027 }
2028 }
2029 } else {
2030 FileUtils.delete(headsFile, FileUtils.SKIP_MISSING);
2031 }
2032 }
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048 @NonNull
2049 public List<RebaseTodoLine> readRebaseTodo(String path,
2050 boolean includeComments)
2051 throws IOException {
2052 return new RebaseTodoFile(this).readRebaseTodo(path, includeComments);
2053 }
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068 public void writeRebaseTodoFile(String path, List<RebaseTodoLine> steps,
2069 boolean append)
2070 throws IOException {
2071 new RebaseTodoFile(this).writeRebaseTodoFile(path, steps, append);
2072 }
2073
2074
2075
2076
2077
2078
2079
2080 @NonNull
2081 public Set<String> getRemoteNames() {
2082 return getConfig()
2083 .getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
2084 }
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101 public void autoGC(ProgressMonitor monitor) {
2102
2103 }
2104 }