This repository has been archived by the owner on Feb 9, 2021. It is now read-only.
/
JGitUtil.java
1532 lines (1328 loc) · 60.2 KB
/
JGitUtil.java
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
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uberfire.java.nio.fs.jgit.util;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import org.apache.commons.io.FileUtils;
import org.eclipse.jgit.api.CreateBranchCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ListBranchCommand;
import org.eclipse.jgit.api.LogCommand;
import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.JGitInternalException;
import org.eclipse.jgit.api.errors.MultipleParentsNotAllowedException;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.dircache.DirCache;
import org.eclipse.jgit.dircache.DirCacheEditor;
import org.eclipse.jgit.dircache.DirCacheEntry;
import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryCache;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.FetchResult;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.treewalk.CanonicalTreeParser;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.treewalk.filter.PathFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uberfire.commons.config.ConfigProperties;
import org.uberfire.commons.data.Pair;
import org.uberfire.java.nio.IOException;
import org.uberfire.java.nio.base.FileTimeImpl;
import org.uberfire.java.nio.base.version.VersionAttributes;
import org.uberfire.java.nio.base.version.VersionHistory;
import org.uberfire.java.nio.base.version.VersionRecord;
import org.uberfire.java.nio.file.NoSuchFileException;
import org.uberfire.java.nio.file.attribute.BasicFileAttributes;
import org.uberfire.java.nio.file.attribute.FileTime;
import org.uberfire.java.nio.fs.jgit.CommitInfo;
import org.uberfire.java.nio.fs.jgit.JGitFileSystem;
import static java.util.Collections.*;
import static org.apache.commons.io.FileUtils.*;
import static org.eclipse.jgit.lib.Constants.*;
import static org.eclipse.jgit.lib.FileMode.*;
import static org.eclipse.jgit.treewalk.filter.PathFilterGroup.*;
import static org.eclipse.jgit.util.FS.*;
import static org.uberfire.commons.data.Pair.*;
import static org.uberfire.commons.validation.Preconditions.*;
public final class JGitUtil {
private static final Logger LOG = LoggerFactory.getLogger( JGitUtil.class );
private static String DEFAULT_JGIT_RETRY_SLEEP_TIME = "50";
private static int JGIT_RETRY_TIMES = initRetryValue();
private static int JGIT_RETRY_SLEEP_TIME = initSleepTime();
private static int initSleepTime() {
final ConfigProperties config = new ConfigProperties( System.getProperties() );
return config.get( "org.uberfire.nio.git.retry.onfail.sleep", DEFAULT_JGIT_RETRY_SLEEP_TIME ).getIntValue();
}
private static int initRetryValue() {
final ConfigProperties config = new ConfigProperties( System.getProperties() );
final String osName = config.get( "os.name", "any" ).getValue();
final String defaultRetryTimes;
if ( osName.toLowerCase().contains( "windows" ) ) {
defaultRetryTimes = "10";
} else {
defaultRetryTimes = "0";
}
try {
return config.get( "org.uberfire.nio.git.retry.onfail.times", defaultRetryTimes ).getIntValue();
} catch ( NumberFormatException ex ) {
return 0;
}
}
//just for test purposes
static void setRetryTimes( int retryTimes ) {
JGIT_RETRY_TIMES = retryTimes;
}
private JGitUtil() {
}
public static Git newRepository( final File repoFolder,
final boolean bare ) throws IOException {
checkNotNull( "repoFolder", repoFolder );
try {
return Git.init().setBare( bare ).setDirectory( repoFolder ).call();
} catch ( GitAPIException e ) {
throw new IOException( e );
}
}
public static Git newRepository( final File repoFolder,
final boolean bare,
final File hookDir ) throws IOException {
final Git git = newRepository( repoFolder, bare );
if ( hookDir == null ) {
return git;
}
final File repoHookDir;
if ( bare ) {
repoHookDir = new File( repoFolder, "hooks" );
} else {
repoHookDir = new File( repoFolder, ".git/hooks" );
}
try {
FileUtils.copyDirectory( hookDir, repoHookDir );
} catch ( final Exception ex ) {
throw new RuntimeException( ex );
}
for ( final File file : repoHookDir.listFiles() ) {
if ( file != null && file.isFile() ) {
file.setExecutable( true );
}
}
return git;
}
public static List<Ref> branchList( final Git git ) {
checkNotNull( "git", git );
return branchList( git, null );
}
public static List<Ref> branchList( final Git git,
final ListBranchCommand.ListMode listMode ) {
checkNotNull( "git", git );
try {
return git.branchList().setListMode( listMode ).call();
} catch ( GitAPIException e ) {
throw new RuntimeException( e );
}
}
public static InputStream resolveInputStream( final Git git,
final String treeRef,
final String path ) {
checkNotNull( "git", git );
checkNotEmpty( "treeRef", treeRef );
checkNotEmpty( "path", path );
final String gitPath = fixPath( path );
return retryIfNeeded( NoSuchFileException.class, new ThrowableSupplier<InputStream>() {
@Override
public InputStream get() throws Throwable {
RevWalk rw = null;
TreeWalk tw = null;
try {
final ObjectId tree = git.getRepository().resolve( treeRef + "^{tree}" );
rw = new RevWalk( git.getRepository() );
tw = new TreeWalk( git.getRepository() );
tw.setFilter( createFromStrings( singleton( gitPath ) ) );
tw.reset( tree );
while ( tw.next() ) {
if ( tw.isSubtree() && !gitPath.equals( tw.getPathString() ) ) {
tw.enterSubtree();
continue;
}
return new ByteArrayInputStream( git.getRepository().open( tw.getObjectId( 0 ), Constants.OBJ_BLOB ).getBytes() );
}
} catch ( final Throwable t ) {
throw new NoSuchFileException( "Can't find '" + gitPath + "' in tree '" + treeRef + "'" );
} finally {
if ( rw != null ) {
rw.dispose();
}
if ( tw != null ) {
tw.close();
}
}
throw new NoSuchFileException( "Can't find '" + gitPath + "' in tree '" + treeRef + "'" );
}
} );
}
public static String fixPath( final String path ) {
if ( path.equals( "/" ) ) {
return "";
}
boolean startsWith = path.startsWith( "/" );
boolean endsWith = path.endsWith( "/" );
if ( startsWith && endsWith ) {
return path.substring( 1, path.length() - 1 );
}
if ( startsWith ) {
return path.substring( 1 );
}
if ( endsWith ) {
return path.substring( 0, path.length() - 1 );
}
return path;
}
public static Git cloneRepository( final File repoFolder,
final String fromURI,
final boolean bare,
final CredentialsProvider credentialsProvider ) {
if ( !repoFolder.getName().endsWith( DOT_GIT_EXT ) ) {
throw new RuntimeException( "Invalid name" );
}
try {
final File gitDir = RepositoryCache.FileKey.resolve( repoFolder, DETECTED );
final Repository repository;
final Git git;
if ( gitDir != null && gitDir.exists() ) {
repository = new FileRepository( gitDir );
git = new Git( repository );
} else {
git = Git.cloneRepository()
.setBare( bare )
.setCloneAllBranches( true )
.setURI( fromURI )
.setDirectory( repoFolder )
.setCredentialsProvider( credentialsProvider )
.call();
repository = git.getRepository();
}
fetchRepository( git, credentialsProvider );
repository.close();
return git;
} catch ( final Exception ex ) {
try {
forceDelete( repoFolder );
} catch ( final java.io.IOException e ) {
throw new RuntimeException( e );
}
throw new RuntimeException( ex );
}
}
public static void fetchRepository( final Git git,
final CredentialsProvider credentialsProvider,
final RefSpec... refSpecs )
throws InvalidRemoteException {
final List<RefSpec> specs = new ArrayList<RefSpec>();
if ( refSpecs == null || refSpecs.length == 0 ) {
specs.add( new RefSpec( "+refs/heads/*:refs/remotes/origin/*" ) );
specs.add( new RefSpec( "+refs/tags/*:refs/tags/*" ) );
specs.add( new RefSpec( "+refs/notes/*:refs/notes/*" ) );
} else {
specs.addAll( Arrays.asList( refSpecs ) );
}
try {
final FetchResult result = git.fetch()
.setCredentialsProvider( credentialsProvider )
.setRefSpecs( specs )
.call();
} catch ( final InvalidRemoteException e ) {
throw e;
} catch ( final Exception ex ) {
throw new RuntimeException( ex );
}
}
public static void syncRepository( final Git git,
final CredentialsProvider credentialsProvider,
final String origin,
boolean force )
throws InvalidRemoteException {
if ( origin == null || origin.isEmpty() ) {
fetchRepository( git, credentialsProvider );
} else {
try {
final StoredConfig config = git.getRepository().getConfig();
config.setString( "remote", "upstream", "url", origin );
config.save();
} catch ( final Exception ex ) {
throw new RuntimeException( ex );
}
final List<RefSpec> specs = new ArrayList<RefSpec>();
specs.add( new RefSpec( "+refs/heads/*:refs/remotes/upstream/*" ) );
specs.add( new RefSpec( "+refs/tags/*:refs/tags/*" ) );
specs.add( new RefSpec( "+refs/notes/*:refs/notes/*" ) );
try {
git.fetch()
.setCredentialsProvider( credentialsProvider )
.setRefSpecs( specs )
.setRemote( origin )
.call();
final List<Ref> branches = git.branchList().setListMode( ListBranchCommand.ListMode.ALL ).call();
final Set<String> remoteBranches = new HashSet<String>();
final Set<String> localBranches = new HashSet<String>();
for ( final Ref branch : branches ) {
final String branchName = branch.getName().substring( branch.getName().lastIndexOf( "/" ) + 1 );
if ( branch.getName().startsWith( "refs/remotes" ) ) {
remoteBranches.add( branchName );
} else {
localBranches.add( branchName );
}
}
for ( final String localBranch : localBranches ) {
if ( remoteBranches.contains( localBranch ) ) {
git.branchCreate()
.setName( localBranch )
.setUpstreamMode( CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM )
.setStartPoint( "upstream/" + localBranch )
.setForce( true )
.call();
}
}
remoteBranches.removeAll( localBranches );
for ( final String branch : remoteBranches ) {
git.branchCreate()
.setName( branch )
.setUpstreamMode( CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM )
.setStartPoint( "upstream/" + branch )
.setForce( true )
.call();
}
} catch ( final InvalidRemoteException e ) {
throw e;
} catch ( final Exception ex ) {
throw new RuntimeException( ex );
}
}
}
public static void pushRepository( final Git git,
final CredentialsProvider credentialsProvider,
final String origin,
boolean force )
throws InvalidRemoteException {
if ( origin != null && !origin.isEmpty() ) {
try {
final StoredConfig config = git.getRepository().getConfig();
config.setString( "remote", "upstream", "url", origin );
config.save();
} catch ( final Exception ex ) {
throw new RuntimeException( ex );
}
final List<RefSpec> specs = new ArrayList<RefSpec>();
specs.add( new RefSpec( "+refs/heads/*:refs/remotes/upstream/*" ) );
specs.add( new RefSpec( "+refs/tags/*:refs/tags/*" ) );
specs.add( new RefSpec( "+refs/notes/*:refs/notes/*" ) );
try {
git.push()
.setCredentialsProvider( credentialsProvider )
.setRefSpecs( specs )
.setRemote( origin )
.setForce( force )
.setPushAll()
.call();
} catch ( final InvalidRemoteException e ) {
throw e;
} catch ( final Exception ex ) {
throw new RuntimeException( ex );
}
}
}
public static void cherryPick( final Repository repo,
final String targetBranch,
final String... _commits ) {
final String reflogPrefix = "cherry-pick:";
final Git git = new Git( repo );
RevCommit newHead = null;
final RevWalk revWalk = new RevWalk( repo );
final ObjectId[] commits = resolveObjectIds( git, _commits );
if ( _commits.length != commits.length ) {
throw new IOException( "Couldn't resolve some commits." );
}
try {
final Ref headRef = getBranch( git, targetBranch );
newHead = revWalk.parseCommit( headRef.getObjectId() );
// loop through all refs to be cherry-picked
for ( final ObjectId src : commits ) {
final RevCommit srcCommit = revWalk.parseCommit( src );
// get the parent of the commit to cherry-pick
if ( srcCommit.getParentCount() != 1 ) {
throw new IOException( new MultipleParentsNotAllowedException(
MessageFormat.format(
JGitText.get().canOnlyCherryPickCommitsWithOneParent,
srcCommit.name(),
Integer.valueOf( srcCommit.getParentCount() ) ) ) );
}
final RevCommit srcParent = srcCommit.getParent( 0 );
revWalk.parseHeaders( srcParent );
final RevCommit revCommit = revWalk.parseCommit( src );
final RefUpdate ru = git.getRepository().updateRef( "refs/heads/" + targetBranch );
if ( newHead == null ) {
ru.setExpectedOldObjectId( ObjectId.zeroId() );
} else {
ru.setExpectedOldObjectId( newHead );
}
ru.setNewObjectId( src );
ru.setRefLogMessage( reflogPrefix + " " + srcCommit.getShortMessage(), false );
final RefUpdate.Result rc = ru.forceUpdate();
switch ( rc ) {
case NEW:
case FORCED:
case FAST_FORWARD:
newHead = revCommit;
break;
case REJECTED:
case LOCK_FAILURE:
throw new ConcurrentRefUpdateException( JGitText.get().couldNotLockHEAD, ru.getRef(), rc );
default:
throw new JGitInternalException( MessageFormat.format( JGitText.get().updatingRefFailed, Constants.HEAD, src.toString(), rc ) );
}
}
} catch ( final java.io.IOException e ) {
throw new IOException( new JGitInternalException(
MessageFormat.format(
JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand,
e ), e ) );
} catch ( final Exception e ) {
throw new IOException( e );
} finally {
revWalk.close();
}
}
public static ObjectId getTreeRefObjectId( final Repository repo,
final String treeRef ) {
try {
return repo.resolve( treeRef + "^{tree}" );
} catch ( java.io.IOException ex ) {
throw new RuntimeException( ex );
}
}
public static List<DiffEntry> getDiff( final Repository repo,
final ObjectId oldRef,
final ObjectId newRef ) {
if ( newRef == null || repo == null ) {
return emptyList();
}
try {
ObjectReader reader = repo.newObjectReader();
CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
if ( oldRef != null ) {
oldTreeIter.reset( reader, oldRef );
}
CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
newTreeIter.reset( reader, newRef );
return new CustomDiffCommand( repo ).setNewTree( newTreeIter ).setOldTree( oldTreeIter ).setShowNameAndStatusOnly( true ).call();
} catch ( final Exception ex ) {
throw new RuntimeException( ex );
}
}
public static List<RevCommit> getCommits( final JGitFileSystem fs,
final String branch,
final ObjectId startRange,
final ObjectId endRange ) {
return retryIfNeeded( RuntimeException.class, new ThrowableSupplier<List<RevCommit>>() {
@Override
public List<RevCommit> get() throws Throwable {
final List<RevCommit> list = new ArrayList<RevCommit>();
RevWalk rw = null;
try {
// resolve branch
rw = new RevWalk( fs.gitRepo().getRepository() );
rw.markStart( rw.parseCommit( endRange ) );
if ( startRange != null ) {
rw.markUninteresting( rw.parseCommit( startRange ) );
}
for ( RevCommit rev : rw ) {
list.add( rev );
}
} catch ( final Exception ex ) {
throw ex;
} finally {
if ( rw != null ) {
rw.dispose();
}
}
return list;
}
} );
}
public static void commit( final Git git,
final String branchName,
final String name,
final String email,
final String message,
final TimeZone timeZone,
final Date when,
final boolean amend,
final Map<String, File> content ) {
commit( git, branchName, new CommitInfo( null, name, email, message, timeZone, when ), amend, new DefaultCommitContent( content ) );
}
public static boolean commit( final Git git,
final String branchName,
final CommitInfo commitInfo,
final boolean amend,
final CommitContent content ) {
if ( content instanceof RevertCommitContent ) {
return commit( git, branchName, commitInfo, amend, resolveObjectId( git, ( (RevertCommitContent) content ).getRefTree() ), content );
} else {
return commit( git, branchName, commitInfo, amend, null, content );
}
}
private static boolean commit( final Git git,
final String branchName,
final CommitInfo commitInfo,
final boolean amend,
final ObjectId _originId,
final CommitContent content ) {
boolean hadEffecitiveCommit = true;
final PersonIdent author = buildPersonIdent( git, commitInfo.getName(), commitInfo.getEmail(), commitInfo.getTimeZone(), commitInfo.getWhen() );
try {
final ObjectInserter odi = git.getRepository().newObjectInserter();
try {
// Create the in-memory index of the new/updated issue.
final ObjectId headId = git.getRepository().resolve( branchName + "^{commit}" );
final ObjectId originId;
if ( _originId == null ) {
originId = git.getRepository().resolve( branchName + "^{commit}" );
} else {
originId = _originId;
}
final DirCache index;
if ( content instanceof DefaultCommitContent ) {
index = createTemporaryIndex( git, originId, (DefaultCommitContent) content );
} else if ( content instanceof MoveCommitContent ) {
index = createTemporaryIndex( git, originId, (MoveCommitContent) content );
} else if ( content instanceof CopyCommitContent ) {
index = createTemporaryIndex( git, originId, (CopyCommitContent) content );
} else if ( content instanceof RevertCommitContent ) {
index = createTemporaryIndex( git, originId );
} else {
index = null;
}
if ( index != null ) {
final ObjectId indexTreeId = index.writeTree( odi );
// Create a commit object
final CommitBuilder commit = new CommitBuilder();
commit.setAuthor( author );
commit.setCommitter( author );
commit.setEncoding( Constants.CHARACTER_ENCODING );
commit.setMessage( commitInfo.getMessage() );
//headId can be null if the repository has no commit yet
if ( headId != null ) {
if ( amend ) {
final List<ObjectId> parents = new LinkedList<ObjectId>();
final RevCommit previousCommit = new RevWalk( git.getRepository() ).parseCommit( headId );
final RevCommit[] p = previousCommit.getParents();
for ( final RevCommit revCommit : p ) {
parents.add( 0, revCommit.getId() );
}
commit.setParentIds( parents );
} else {
commit.setParentId( headId );
}
}
commit.setTreeId( indexTreeId );
// Insert the commit into the repository
final ObjectId commitId = odi.insert( commit );
odi.flush();
final RevWalk revWalk = new RevWalk( git.getRepository() );
try {
final RevCommit revCommit = revWalk.parseCommit( commitId );
final RefUpdate ru = git.getRepository().updateRef( "refs/heads/" + branchName );
if ( headId == null ) {
ru.setExpectedOldObjectId( ObjectId.zeroId() );
} else {
ru.setExpectedOldObjectId( headId );
}
ru.setNewObjectId( commitId );
ru.setRefLogMessage( "commit: " + revCommit.getShortMessage(), false );
final RefUpdate.Result rc = ru.forceUpdate();
switch ( rc ) {
case NEW:
case FORCED:
case FAST_FORWARD:
break;
case REJECTED:
case LOCK_FAILURE:
throw new ConcurrentRefUpdateException( JGitText.get().couldNotLockHEAD, ru.getRef(), rc );
default:
throw new JGitInternalException( MessageFormat.format( JGitText.get().updatingRefFailed, Constants.HEAD, commitId.toString(), rc ) );
}
} finally {
revWalk.close();
}
} else {
hadEffecitiveCommit = false;
}
} finally {
odi.close();
}
} catch ( final Throwable t ) {
throw new RuntimeException( t );
}
return hadEffecitiveCommit;
}
private static PersonIdent buildPersonIdent( final Git git,
final String name,
final String _email,
final TimeZone timeZone,
final Date when ) {
final TimeZone tz = timeZone == null ? TimeZone.getDefault() : timeZone;
final String email = _email == null ? "" : _email;
if ( name != null ) {
if ( when != null ) {
return new PersonIdent( name, email, when, tz );
} else {
return new PersonIdent( name, email );
}
}
return new PersonIdent( git.getRepository() );
}
/**
* Creates an in-memory index of the issue change.
*/
private static DirCache createTemporaryIndex( final Git git,
final ObjectId headId,
final DefaultCommitContent commitContent ) {
final Map<String, File> content = commitContent.getContent();
final Map<String, Pair<File, ObjectId>> paths = new HashMap<String, Pair<File, ObjectId>>( content.size() );
final Set<String> path2delete = new HashSet<String>();
final DirCache inCoreIndex = DirCache.newInCore();
final ObjectInserter inserter = git.getRepository().newObjectInserter();
final DirCacheEditor editor = inCoreIndex.editor();
try {
for ( final Map.Entry<String, File> pathAndContent : content.entrySet() ) {
final String gPath = fixPath( pathAndContent.getKey() );
if ( pathAndContent.getValue() == null ) {
final TreeWalk treeWalk = new TreeWalk( git.getRepository() );
treeWalk.addTree( new RevWalk( git.getRepository() ).parseTree( headId ) );
treeWalk.setRecursive( true );
treeWalk.setFilter( PathFilter.create( gPath ) );
while ( treeWalk.next() ) {
path2delete.add( treeWalk.getPathString() );
}
treeWalk.close();
} else {
try {
final InputStream inputStream = new FileInputStream( pathAndContent.getValue() );
try {
final ObjectId objectId = inserter.insert( Constants.OBJ_BLOB, pathAndContent.getValue().length(), inputStream );
paths.put( gPath, Pair.newPair( pathAndContent.getValue(), objectId ) );
} finally {
inputStream.close();
}
} catch ( final Exception ex ) {
throw new RuntimeException( ex );
}
}
}
if ( headId != null ) {
final TreeWalk treeWalk = new TreeWalk( git.getRepository() );
final int hIdx = treeWalk.addTree( new RevWalk( git.getRepository() ).parseTree( headId ) );
treeWalk.setRecursive( true );
while ( treeWalk.next() ) {
final String walkPath = treeWalk.getPathString();
final CanonicalTreeParser hTree = treeWalk.getTree( hIdx, CanonicalTreeParser.class );
if ( paths.containsKey( walkPath ) && paths.get( walkPath ).getK2().equals( hTree.getEntryObjectId() ) ) {
paths.remove( walkPath );
}
if ( paths.get( walkPath ) == null && !path2delete.contains( walkPath ) ) {
final DirCacheEntry dcEntry = new DirCacheEntry( walkPath );
final ObjectId _objectId = hTree.getEntryObjectId();
final FileMode _fileMode = hTree.getEntryFileMode();
// add to temporary in-core index
editor.add( new DirCacheEditor.PathEdit( dcEntry ) {
@Override
public void apply( final DirCacheEntry ent ) {
ent.setObjectId( _objectId );
ent.setFileMode( _fileMode );
}
} );
}
}
treeWalk.close();
}
for ( final Map.Entry<String, Pair<File, ObjectId>> pathAndContent : paths.entrySet() ) {
if ( pathAndContent.getValue().getK1() != null ) {
editor.add( new DirCacheEditor.PathEdit( new DirCacheEntry( pathAndContent.getKey() ) ) {
@Override
public void apply( final DirCacheEntry ent ) {
ent.setLength( pathAndContent.getValue().getK1().length() );
ent.setLastModified( pathAndContent.getValue().getK1().lastModified() );
ent.setFileMode( REGULAR_FILE );
ent.setObjectId( pathAndContent.getValue().getK2() );
}
} );
}
}
editor.finish();
} catch ( Exception e ) {
throw new RuntimeException( e );
} finally {
inserter.close();
}
if ( path2delete.isEmpty() && paths.isEmpty() ) {
//no changes!
return null;
}
return inCoreIndex;
}
private static DirCache createTemporaryIndex( final Git git,
final ObjectId headId,
final MoveCommitContent commitContent ) {
final Map<String, String> content = commitContent.getContent();
final DirCache inCoreIndex = DirCache.newInCore();
final DirCacheEditor editor = inCoreIndex.editor();
try {
if ( headId != null ) {
final TreeWalk treeWalk = new TreeWalk( git.getRepository() );
final int hIdx = treeWalk.addTree( new RevWalk( git.getRepository() ).parseTree( headId ) );
treeWalk.setRecursive( true );
while ( treeWalk.next() ) {
final String walkPath = treeWalk.getPathString();
final CanonicalTreeParser hTree = treeWalk.getTree( hIdx, CanonicalTreeParser.class );
final String toPath = content.get( walkPath );
if ( toPath == null ) {
final DirCacheEntry dcEntry = new DirCacheEntry( walkPath );
final ObjectId _objectId = hTree.getEntryObjectId();
final FileMode _fileMode = hTree.getEntryFileMode();
// add to temporary in-core index
editor.add( new DirCacheEditor.PathEdit( dcEntry ) {
@Override
public void apply( final DirCacheEntry ent ) {
ent.setObjectId( _objectId );
ent.setFileMode( _fileMode );
}
} );
} else {
final DirCacheEntry dcEntry = new DirCacheEntry( toPath );
final ObjectId _objectId = hTree.getEntryObjectId();
final FileMode _fileMode = hTree.getEntryFileMode();
editor.add( new DirCacheEditor.PathEdit( dcEntry ) {
@Override
public void apply( final DirCacheEntry ent ) {
ent.setFileMode( _fileMode );
ent.setObjectId( _objectId );
}
} );
}
}
treeWalk.close();
}
editor.finish();
} catch ( final Exception e ) {
throw new RuntimeException( e );
}
return inCoreIndex;
}
private static DirCache createTemporaryIndex( final Git git,
final ObjectId headId,
final CopyCommitContent commitContent ) {
final Map<String, String> content = commitContent.getContent();
final DirCache inCoreIndex = DirCache.newInCore();
final DirCacheEditor editor = inCoreIndex.editor();
try {
if ( headId != null ) {
final TreeWalk treeWalk = new TreeWalk( git.getRepository() );
final int hIdx = treeWalk.addTree( new RevWalk( git.getRepository() ).parseTree( headId ) );
treeWalk.setRecursive( true );
while ( treeWalk.next() ) {
final String walkPath = treeWalk.getPathString();
final CanonicalTreeParser hTree = treeWalk.getTree( hIdx, CanonicalTreeParser.class );
final String toPath = content.get( walkPath );
final DirCacheEntry dcEntry = new DirCacheEntry( walkPath );
final ObjectId _objectId = hTree.getEntryObjectId();
final FileMode _fileMode = hTree.getEntryFileMode();
// add to temporary in-core index
editor.add( new DirCacheEditor.PathEdit( dcEntry ) {
@Override
public void apply( final DirCacheEntry ent ) {
ent.setObjectId( _objectId );
ent.setFileMode( _fileMode );
}
} );
if ( toPath != null ) {
final DirCacheEntry newdcEntry = new DirCacheEntry( toPath );
final ObjectId newObjectId = hTree.getEntryObjectId();
final FileMode newFileMode = hTree.getEntryFileMode();
editor.add( new DirCacheEditor.PathEdit( newdcEntry ) {
@Override
public void apply( final DirCacheEntry ent ) {
ent.setFileMode( newFileMode );
ent.setObjectId( newObjectId );
}
} );
}
}
treeWalk.close();
}
editor.finish();
} catch ( final Exception e ) {
throw new RuntimeException( e );
}
return inCoreIndex;
}
private static DirCache createTemporaryIndex( final Git git,
final ObjectId headId ) {
final DirCache inCoreIndex = DirCache.newInCore();
final DirCacheEditor editor = inCoreIndex.editor();
try {
if ( headId != null ) {
final TreeWalk treeWalk = new TreeWalk( git.getRepository() );
final int hIdx = treeWalk.addTree( new RevWalk( git.getRepository() ).parseTree( headId ) );
treeWalk.setRecursive( true );
while ( treeWalk.next() ) {
final String walkPath = treeWalk.getPathString();
final CanonicalTreeParser hTree = treeWalk.getTree( hIdx, CanonicalTreeParser.class );
final DirCacheEntry dcEntry = new DirCacheEntry( walkPath );
final ObjectId _objectId = hTree.getEntryObjectId();
final FileMode _fileMode = hTree.getEntryFileMode();
// add to temporary in-core index
editor.add( new DirCacheEditor.PathEdit( dcEntry ) {
@Override
public void apply( final DirCacheEntry ent ) {
ent.setObjectId( _objectId );
ent.setFileMode( _fileMode );
}
} );
}
treeWalk.close();
}
editor.finish();
} catch ( final Exception e ) {
throw new RuntimeException( e );
}
return inCoreIndex;
}
public static ObjectId resolveObjectId( final Git git,
final String name ) {
final ObjectId[] result = resolveObjectIds( git, name );
if ( result == null || result.length == 0 ) {
return null;
}
return result[ 0 ];
}
public static ObjectId[] resolveObjectIds( final Git git,
final String... ids ) {
final Collection<ObjectId> result = new ArrayList<ObjectId>();
for ( final String id : ids ) {
try {
final Ref refName = getBranch( git, id );
if ( refName != null ) {
result.add( refName.getObjectId() );
continue;
}
try {
final ObjectId _id = ObjectId.fromString( id );
if ( git.getRepository().getObjectDatabase().has( _id ) ) {
result.add( _id );
}
} catch ( final IllegalArgumentException ignored ) {
}
} catch ( final java.io.IOException ignored ) {
}
}