/
JGitUtil.scala
1280 lines (1186 loc) · 42.2 KB
/
JGitUtil.scala
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
package gitbucket.core.util
import java.io.{ByteArrayOutputStream, File, FileInputStream, InputStream}
import gitbucket.core.service.RepositoryService
import org.eclipse.jgit.api.Git
import Directory._
import StringUtil._
import SyntaxSugars._
import scala.annotation.tailrec
import scala.collection.JavaConverters._
import org.eclipse.jgit.lib._
import org.eclipse.jgit.revwalk._
import org.eclipse.jgit.revwalk.filter._
import org.eclipse.jgit.treewalk._
import org.eclipse.jgit.treewalk.filter._
import org.eclipse.jgit.diff.DiffEntry.ChangeType
import org.eclipse.jgit.errors.{ConfigInvalidException, IncorrectObjectTypeException, MissingObjectException}
import org.eclipse.jgit.transport.RefSpec
import java.util.Date
import java.util.concurrent.TimeUnit
import java.util.function.Consumer
import org.cache2k.Cache2kBuilder
import org.eclipse.jgit.api.errors.{
InvalidRefNameException,
JGitInternalException,
NoHeadException,
RefAlreadyExistsException
}
import org.eclipse.jgit.diff.{DiffEntry, DiffFormatter, RawTextComparator}
import org.eclipse.jgit.dircache.DirCacheEntry
import org.eclipse.jgit.util.io.DisabledOutputStream
import org.slf4j.LoggerFactory
/**
* Provides complex JGit operations.
*/
object JGitUtil {
private val logger = LoggerFactory.getLogger(JGitUtil.getClass)
/**
* The repository data.
*
* @param owner the user name of the repository owner
* @param name the repository name
* @param branchList the list of branch names
* @param tags the list of tags
*/
case class RepositoryInfo(owner: String, name: String, branchList: List[String], tags: List[TagInfo]) {
def this(owner: String, name: String) = this(owner, name, Nil, Nil)
}
/**
* The file data for the file list of the repository viewer.
*
* @param id the object id
* @param isDirectory whether is it directory
* @param name the file (or directory) name
* @param path the file (or directory) complete path
* @param message the last commit message
* @param commitId the last commit id
* @param time the last modified time
* @param author the last committer name
* @param mailAddress the committer's mail address
* @param linkUrl the url of submodule
*/
case class FileInfo(
id: ObjectId,
isDirectory: Boolean,
name: String,
path: String,
message: String,
commitId: String,
time: Date,
author: String,
mailAddress: String,
linkUrl: Option[String]
)
/**
* The commit data.
*
* @param id the commit id
* @param shortMessage the short message
* @param fullMessage the full message
* @param parents the list of parent commit id
* @param authorTime the author time
* @param authorName the author name
* @param authorEmailAddress the mail address of the author
* @param commitTime the commit time
* @param committerName the committer name
* @param committerEmailAddress the mail address of the committer
*/
case class CommitInfo(
id: String,
shortMessage: String,
fullMessage: String,
parents: List[String],
authorTime: Date,
authorName: String,
authorEmailAddress: String,
commitTime: Date,
committerName: String,
committerEmailAddress: String
) {
def this(rev: org.eclipse.jgit.revwalk.RevCommit) =
this(
rev.getName,
rev.getShortMessage,
rev.getFullMessage,
rev.getParents().map(_.name).toList,
rev.getAuthorIdent.getWhen,
rev.getAuthorIdent.getName,
rev.getAuthorIdent.getEmailAddress,
rev.getCommitterIdent.getWhen,
rev.getCommitterIdent.getName,
rev.getCommitterIdent.getEmailAddress
)
val summary = getSummaryMessage(fullMessage, shortMessage)
val description = defining(fullMessage.trim.indexOf('\n')) { i =>
if (i >= 0) {
Some(fullMessage.trim.substring(i).trim)
} else None
}
def isDifferentFromAuthor: Boolean = authorName != committerName || authorEmailAddress != committerEmailAddress
}
case class DiffInfo(
changeType: ChangeType,
oldPath: String,
newPath: String,
oldContent: Option[String],
newContent: Option[String],
oldIsImage: Boolean,
newIsImage: Boolean,
oldObjectId: Option[String],
newObjectId: Option[String],
oldMode: String,
newMode: String,
tooLarge: Boolean,
patch: Option[String]
)
/**
* The file content data for the file content view of the repository viewer.
*
* @param viewType "image", "large" or "other"
* @param size total size of object in bytes
* @param content the string content
* @param charset the character encoding
*/
case class ContentInfo(viewType: String, size: Option[Long], content: Option[String], charset: Option[String]) {
/**
* the line separator of this content ("LF" or "CRLF")
*/
val lineSeparator: String = if (content.exists(_.indexOf("\r\n") >= 0)) "CRLF" else "LF"
}
/**
* The tag data.
*
* @param name the tag name
* @param time the tagged date
* @param id the commit id
* @param message the message of the tagged commit
*/
case class TagInfo(name: String, time: Date, id: String, message: String)
/**
* The submodule data
*
* @param name the module name
* @param path the path in the repository
* @param repositoryUrl the repository url of this module
* @param viewerUrl the repository viewer url of this module
*/
case class SubmoduleInfo(name: String, path: String, repositoryUrl: String, viewerUrl: String)
case class BranchMergeInfo(ahead: Int, behind: Int, isMerged: Boolean)
case class BranchInfo(
name: String,
committerName: String,
commitTime: Date,
committerEmailAddress: String,
mergeInfo: Option[BranchMergeInfo],
commitId: String
)
case class BlameInfo(
id: String,
authorName: String,
authorEmailAddress: String,
authorTime: java.util.Date,
prev: Option[String],
prevPath: Option[String],
commitTime: java.util.Date,
message: String,
lines: Set[Int]
)
/**
* Returns RevCommit from the commit or tag id.
*
* @param git the Git object
* @param objectId the ObjectId of the commit or tag
* @return the RevCommit for the specified commit or tag
*/
def getRevCommitFromId(git: Git, objectId: ObjectId): RevCommit = {
val revWalk = new RevWalk(git.getRepository)
val revCommit = revWalk.parseAny(objectId) match {
case r: RevTag => revWalk.parseCommit(r.getObject)
case _ => revWalk.parseCommit(objectId)
}
revWalk.dispose
revCommit
}
private val cache = new Cache2kBuilder[String, Int]() {}
.name("commit-count")
.expireAfterWrite(24, TimeUnit.HOURS)
.entryCapacity(10000)
.build()
def removeCache(git: Git): Unit = {
val dir = git.getRepository.getDirectory
val keyPrefix = dir.getAbsolutePath + "@"
cache.keys.forEach(key => {
if (key.startsWith(keyPrefix)) {
cache.remove(key)
}
})
}
/**
* Returns the number of commits in the specified branch or commit.
* If the specified branch has over 10000 commits, this method returns 100001.
*/
def getCommitCount(owner: String, repository: String, branch: String): Int = {
val dir = getRepositoryDir(owner, repository)
val key = dir.getAbsolutePath + "@" + branch
val entry = cache.getEntry(key)
if (entry == null) {
using(Git.open(dir)) { git =>
val commitId = git.getRepository.resolve(branch)
val commitCount = git.log.add(commitId).call.iterator.asScala.take(10001).size
cache.put(key, commitCount)
commitCount
}
} else {
entry.getValue
}
}
/**
* Returns the repository information. It contains branch names and tag names.
*/
def getRepositoryInfo(owner: String, repository: String): RepositoryInfo = {
using(Git.open(getRepositoryDir(owner, repository))) { git =>
try {
RepositoryInfo(
owner,
repository,
// branches
git.branchList.call.asScala.map { ref =>
ref.getName.stripPrefix("refs/heads/")
}.toList,
// tags
git.tagList.call.asScala
.flatMap { ref =>
try {
val revCommit = getRevCommitFromId(git, ref.getObjectId)
Some(
TagInfo(
ref.getName.stripPrefix("refs/tags/"),
revCommit.getCommitterIdent.getWhen,
revCommit.getName,
revCommit.getShortMessage
)
)
} catch {
case _: IncorrectObjectTypeException =>
None
}
}
.sortBy(_.time)
.toList
)
} catch {
// not initialized
case e: NoHeadException => RepositoryInfo(owner, repository, Nil, Nil)
}
}
}
/**
* Returns the file list of the specified path.
*
* @param git the Git object
* @param revision the branch name or commit id
* @param path the directory path (optional)
* @param baseUrl the base url of GitBucket instance. This parameter is used to generate links of submodules (optional)
* @return HTML of the file list
*/
def getFileList(git: Git, revision: String, path: String = ".", baseUrl: Option[String] = None): List[FileInfo] = {
using(new RevWalk(git.getRepository)) { revWalk =>
val objectId = git.getRepository.resolve(revision)
if (objectId == null) return Nil
val revCommit = revWalk.parseCommit(objectId)
def useTreeWalk(rev: RevCommit)(f: TreeWalk => Any): Unit =
if (path == ".") {
val treeWalk = new TreeWalk(git.getRepository)
treeWalk.addTree(rev.getTree)
using(treeWalk)(f)
} else {
val treeWalk = TreeWalk.forPath(git.getRepository, path, rev.getTree)
if (treeWalk != null) {
treeWalk.enterSubtree
using(treeWalk)(f)
}
}
@tailrec
def simplifyPath(
tuple: (ObjectId, FileMode, String, String, Option[String], RevCommit)
): (ObjectId, FileMode, String, String, Option[String], RevCommit) = tuple match {
case (oid, FileMode.TREE, name, path, _, commit) =>
(using(new TreeWalk(git.getRepository)) { walk =>
walk.addTree(oid)
// single tree child, or None
if (walk.next() && walk.getFileMode(0) == FileMode.TREE) {
Some(
(
walk.getObjectId(0),
walk.getFileMode(0),
name + "/" + walk.getNameString,
path + "/" + walk.getNameString,
None,
commit
)
).filterNot(_ => walk.next())
} else {
None
}
}) match {
case Some(child) => simplifyPath(child)
case _ => tuple
}
case _ => tuple
}
def tupleAdd(tuple: (ObjectId, FileMode, String, String, Option[String]), rev: RevCommit) = tuple match {
case (oid, fmode, name, path, opt) => (oid, fmode, name, path, opt, rev)
}
@tailrec
def findLastCommits(
result: List[(ObjectId, FileMode, String, String, Option[String], RevCommit)],
restList: List[((ObjectId, FileMode, String, String, Option[String]), Map[RevCommit, RevCommit])],
revIterator: java.util.Iterator[RevCommit]
): List[(ObjectId, FileMode, String, String, Option[String], RevCommit)] = {
if (restList.isEmpty) {
result
} else if (!revIterator.hasNext) { // maybe, revCommit has only 1 log. other case, restList be empty
result ++ restList.map { case (tuple, map) => tupleAdd(tuple, map.values.headOption.getOrElse(revCommit)) }
} else {
val newCommit = revIterator.next
val (thisTimeChecks, skips) = restList.partition {
case (tuple, parentsMap) => parentsMap.contains(newCommit)
}
if (thisTimeChecks.isEmpty) {
findLastCommits(result, restList, revIterator)
} else {
var nextRest = skips
var nextResult = result
// Map[(name, oid), (tuple, parentsMap)]
val rest = scala.collection.mutable.Map(thisTimeChecks.map { t =>
(t._1._3 -> t._1._1) -> t
}: _*)
lazy val newParentsMap = newCommit.getParents.map(_ -> newCommit).toMap
useTreeWalk(newCommit) { walk =>
while (walk.next) {
rest.remove(walk.getNameString -> walk.getObjectId(0)).map {
case (tuple, _) =>
if (newParentsMap.isEmpty) {
nextResult +:= tupleAdd(tuple, newCommit)
} else {
nextRest +:= tuple -> newParentsMap
}
}
}
}
rest.values.map {
case (tuple, parentsMap) =>
val restParentsMap = parentsMap - newCommit
if (restParentsMap.isEmpty) {
nextResult +:= tupleAdd(tuple, parentsMap(newCommit))
} else {
nextRest +:= tuple -> restParentsMap
}
}
findLastCommits(nextResult, nextRest, revIterator)
}
}
}
var fileList: List[(ObjectId, FileMode, String, String, Option[String])] = Nil
useTreeWalk(revCommit) { treeWalk =>
while (treeWalk.next()) {
val linkUrl = if (treeWalk.getFileMode(0) == FileMode.GITLINK) {
getSubmodules(git, revCommit.getTree, baseUrl).find(_.path == treeWalk.getPathString).map(_.viewerUrl)
} else None
fileList +:= (treeWalk.getObjectId(0), treeWalk.getFileMode(0), treeWalk.getNameString, treeWalk.getPathString, linkUrl)
}
}
revWalk.markStart(revCommit)
val it = revWalk.iterator
val lastCommit = it.next
val nextParentsMap = Option(lastCommit).map(_.getParents.map(_ -> lastCommit).toMap).getOrElse(Map())
findLastCommits(List.empty, fileList.map(a => a -> nextParentsMap), it)
.map(simplifyPath)
.map {
case (objectId, fileMode, name, path, linkUrl, commit) =>
FileInfo(
objectId,
fileMode == FileMode.TREE || fileMode == FileMode.GITLINK,
name,
path,
getSummaryMessage(commit.getFullMessage, commit.getShortMessage),
commit.getName,
commit.getAuthorIdent.getWhen,
commit.getAuthorIdent.getName,
commit.getAuthorIdent.getEmailAddress,
linkUrl
)
}
.sortWith { (file1, file2) =>
(file1.isDirectory, file2.isDirectory) match {
case (true, false) => true
case (false, true) => false
case _ => file1.name.compareTo(file2.name) < 0
}
}
}
}
/**
* Returns the first line of the commit message.
*/
private def getSummaryMessage(fullMessage: String, shortMessage: String): String = {
defining(fullMessage.trim.indexOf('\n')) { i =>
defining(if (i >= 0) fullMessage.trim.substring(0, i).trim else fullMessage) { firstLine =>
if (firstLine.length > shortMessage.length) shortMessage else firstLine
}
}
}
/**
* get all file list by revision. only file.
*/
def getTreeId(git: Git, revision: String): Option[String] = {
using(new RevWalk(git.getRepository)) { revWalk =>
val objectId = git.getRepository.resolve(revision)
if (objectId == null) return None
val revCommit = revWalk.parseCommit(objectId)
Some(revCommit.getTree.name)
}
}
/**
* get all file list by tree object id.
*/
def getAllFileListByTreeId(git: Git, treeId: String): List[String] = {
using(new RevWalk(git.getRepository)) { revWalk =>
val objectId = git.getRepository.resolve(treeId + "^{tree}")
if (objectId == null) return Nil
using(new TreeWalk(git.getRepository)) { treeWalk =>
treeWalk.addTree(objectId)
treeWalk.setRecursive(true)
var ret: List[String] = Nil
if (treeWalk != null) {
while (treeWalk.next()) {
ret +:= treeWalk.getPathString
}
}
ret.reverse
}
}
}
/**
* Returns the commit list of the specified branch.
*
* @param git the Git object
* @param revision the branch name or commit id
* @param page the page number (1-)
* @param limit the number of commit info per page. 0 (default) means unlimited.
* @param path filters by this path. default is no filter.
* @return a tuple of the commit list and whether has next, or the error message
*/
def getCommitLog(
git: Git,
revision: String,
page: Int = 1,
limit: Int = 0,
path: String = ""
): Either[String, (List[CommitInfo], Boolean)] = {
val fixedPage = if (page <= 0) 1 else page
@scala.annotation.tailrec
def getCommitLog(
i: java.util.Iterator[RevCommit],
count: Int,
logs: List[CommitInfo]
): (List[CommitInfo], Boolean) =
i.hasNext match {
case true if (limit <= 0 || logs.size < limit) => {
val commit = i.next
getCommitLog(
i,
count + 1,
if (limit <= 0 || (fixedPage - 1) * limit <= count) logs :+ new CommitInfo(commit) else logs
)
}
case _ => (logs, i.hasNext)
}
using(new RevWalk(git.getRepository)) { revWalk =>
defining(git.getRepository.resolve(revision)) { objectId =>
if (objectId == null) {
Left(s"${revision} can't be resolved.")
} else {
revWalk.markStart(revWalk.parseCommit(objectId))
if (path.nonEmpty) {
revWalk.setTreeFilter(AndTreeFilter.create(PathFilter.create(path), TreeFilter.ANY_DIFF))
}
Right(getCommitLog(revWalk.iterator, 0, Nil))
}
}
}
}
def getCommitLogs(git: Git, begin: String, includesLastCommit: Boolean = false)(
endCondition: RevCommit => Boolean
): List[CommitInfo] = {
@scala.annotation.tailrec
def getCommitLog(i: java.util.Iterator[RevCommit], logs: List[CommitInfo]): List[CommitInfo] =
i.hasNext match {
case true => {
val revCommit = i.next
if (endCondition(revCommit)) {
if (includesLastCommit) logs :+ new CommitInfo(revCommit) else logs
} else {
getCommitLog(i, logs :+ new CommitInfo(revCommit))
}
}
case false => logs
}
using(new RevWalk(git.getRepository)) { revWalk =>
revWalk.markStart(revWalk.parseCommit(git.getRepository.resolve(begin)))
getCommitLog(revWalk.iterator, Nil).reverse
}
}
/**
* Returns the commit list between two revisions.
*
* @param git the Git object
* @param from the from revision
* @param to the to revision
* @return the commit list
*/
// TODO swap parameters 'from' and 'to'!?
def getCommitLog(git: Git, from: String, to: String): List[CommitInfo] =
getCommitLogs(git, to)(_.getName == from)
/**
* Returns the latest RevCommit of the specified path.
*
* @param git the Git object
* @param path the path
* @param revision the branch name or commit id
* @return the latest commit
*/
def getLatestCommitFromPath(git: Git, path: String, revision: String): Option[RevCommit] =
getLatestCommitFromPaths(git, List(path), revision).get(path)
/**
* Returns the list of latest RevCommit of the specified paths.
*
* @param git the Git object
* @param paths the list of paths
* @param revision the branch name or commit id
* @return the list of latest commit
*/
def getLatestCommitFromPaths(git: Git, paths: List[String], revision: String): Map[String, RevCommit] = {
val start = getRevCommitFromId(git, git.getRepository.resolve(revision))
paths.map { path =>
val commit = git.log.add(start).addPath(path).setMaxCount(1).call.iterator.next
(path, commit)
}.toMap
}
def getPatch(git: Git, from: Option[String], to: String): String = {
val out = new ByteArrayOutputStream()
val df = new DiffFormatter(out)
df.setRepository(git.getRepository)
df.setDiffComparator(RawTextComparator.DEFAULT)
df.setDetectRenames(true)
df.format(getDiffEntries(git, from, to).head)
new String(out.toByteArray, "UTF-8")
}
private def getDiffEntries(git: Git, from: Option[String], to: String): Seq[DiffEntry] = {
using(new RevWalk(git.getRepository)) { revWalk =>
val df = new DiffFormatter(DisabledOutputStream.INSTANCE)
df.setRepository(git.getRepository)
val toCommit = revWalk.parseCommit(git.getRepository.resolve(to))
from match {
case None => {
toCommit.getParentCount match {
case 0 =>
df.scan(
new EmptyTreeIterator(),
new CanonicalTreeParser(null, git.getRepository.newObjectReader(), toCommit.getTree)
)
.asScala
case _ => df.scan(toCommit.getParent(0), toCommit.getTree).asScala
}
}
case Some(from) => {
val fromCommit = revWalk.parseCommit(git.getRepository.resolve(from))
df.scan(fromCommit.getTree, toCommit.getTree).asScala
}
}
}
}
def getParentCommitId(git: Git, id: String): Option[String] = {
using(new RevWalk(git.getRepository)) { revWalk =>
val commit = revWalk.parseCommit(git.getRepository.resolve(id))
commit.getParentCount match {
case 0 => None
case _ => Some(commit.getParent(0).getName)
}
}
}
def getDiffs(
git: Git,
from: Option[String],
to: String,
fetchContent: Boolean,
makePatch: Boolean
): List[DiffInfo] = {
val diffs = getDiffEntries(git, from, to)
diffs.map { diff =>
if (diffs.size > 100) {
DiffInfo(
changeType = diff.getChangeType,
oldPath = diff.getOldPath,
newPath = diff.getNewPath,
oldContent = None,
newContent = None,
oldIsImage = false,
newIsImage = false,
oldObjectId = Option(diff.getOldId).map(_.name),
newObjectId = Option(diff.getNewId).map(_.name),
oldMode = diff.getOldMode.toString,
newMode = diff.getNewMode.toString,
tooLarge = true,
patch = None
)
} else {
val oldIsImage = FileUtil.isImage(diff.getOldPath)
val newIsImage = FileUtil.isImage(diff.getNewPath)
if (!fetchContent || oldIsImage || newIsImage) {
DiffInfo(
changeType = diff.getChangeType,
oldPath = diff.getOldPath,
newPath = diff.getNewPath,
oldContent = None,
newContent = None,
oldIsImage = oldIsImage,
newIsImage = newIsImage,
oldObjectId = Option(diff.getOldId).map(_.name),
newObjectId = Option(diff.getNewId).map(_.name),
oldMode = diff.getOldMode.toString,
newMode = diff.getNewMode.toString,
tooLarge = false,
patch = (if (makePatch) Some(makePatchFromDiffEntry(git, diff)) else None) // TODO use DiffFormatter
)
} else {
DiffInfo(
changeType = diff.getChangeType,
oldPath = diff.getOldPath,
newPath = diff.getNewPath,
oldContent = JGitUtil
.getContentFromId(git, diff.getOldId.toObjectId, false)
.filter(FileUtil.isText)
.map(convertFromByteArray),
newContent = JGitUtil
.getContentFromId(git, diff.getNewId.toObjectId, false)
.filter(FileUtil.isText)
.map(convertFromByteArray),
oldIsImage = oldIsImage,
newIsImage = newIsImage,
oldObjectId = Option(diff.getOldId).map(_.name),
newObjectId = Option(diff.getNewId).map(_.name),
oldMode = diff.getOldMode.toString,
newMode = diff.getNewMode.toString,
tooLarge = false,
patch = (if (makePatch) Some(makePatchFromDiffEntry(git, diff)) else None) // TODO use DiffFormatter
)
}
}
}.toList
}
private def makePatchFromDiffEntry(git: Git, diff: DiffEntry): String = {
val out = new ByteArrayOutputStream()
using(new DiffFormatter(out)) { formatter =>
formatter.setRepository(git.getRepository)
formatter.format(diff)
val patch = new String(out.toByteArray) // TODO charset???
patch.split("\n").drop(4).mkString("\n")
}
}
/**
* Returns the list of branch names of the specified commit.
*/
def getBranchesOfCommit(git: Git, commitId: String): List[String] =
using(new RevWalk(git.getRepository)) { revWalk =>
defining(revWalk.parseCommit(git.getRepository.resolve(commitId + "^0"))) { commit =>
git.getRepository.getAllRefs.entrySet.asScala
.filter { e =>
(e.getKey.startsWith(Constants.R_HEADS) && revWalk.isMergedInto(
commit,
revWalk.parseCommit(e.getValue.getObjectId)
))
}
.map { e =>
e.getValue.getName.substring(org.eclipse.jgit.lib.Constants.R_HEADS.length)
}
.toList
.sorted
}
}
/**
* Returns the list of tags which pointed on the specified commit.
*/
def getTagsOnCommit(git: Git, commitId: String): List[String] = {
git.getRepository.getAllRefsByPeeledObjectId.asScala
.get(git.getRepository.resolve(commitId + "^0"))
.map {
_.asScala
.collect {
case x if x.getName.startsWith(Constants.R_TAGS) =>
x.getName.substring(Constants.R_TAGS.length)
}
.toList
.sorted
}
.getOrElse {
List.empty
}
}
/**
* Returns the list of tags which contains the specified commit.
*/
def getTagsOfCommit(git: Git, commitId: String): List[String] =
using(new RevWalk(git.getRepository)) { revWalk =>
defining(revWalk.parseCommit(git.getRepository.resolve(commitId + "^0"))) { commit =>
git.getRepository.getAllRefs.entrySet.asScala
.filter { e =>
(e.getKey.startsWith(Constants.R_TAGS) && revWalk.isMergedInto(
commit,
revWalk.parseCommit(e.getValue.getObjectId)
))
}
.map { e =>
e.getValue.getName.substring(org.eclipse.jgit.lib.Constants.R_TAGS.length)
}
.toList
.sorted
.reverse
}
}
def initRepository(dir: java.io.File): Unit =
using(new RepositoryBuilder().setGitDir(dir).setBare.build) { repository =>
repository.create(true)
setReceivePack(repository)
}
def cloneRepository(from: java.io.File, to: java.io.File): Unit =
using(Git.cloneRepository.setURI(from.toURI.toString).setDirectory(to).setBare(true).call) { git =>
setReceivePack(git.getRepository)
}
def isEmpty(git: Git): Boolean = git.getRepository.resolve(Constants.HEAD) == null
private def setReceivePack(repository: org.eclipse.jgit.lib.Repository): Unit =
defining(repository.getConfig) { config =>
config.setBoolean("http", null, "receivepack", true)
config.save
}
def getDefaultBranch(
git: Git,
repository: RepositoryService.RepositoryInfo,
revstr: String = ""
): Option[(ObjectId, String)] = {
Seq(
Some(if (revstr.isEmpty) repository.repository.defaultBranch else revstr),
repository.branchList.headOption
).flatMap {
case Some(rev) => Some((git.getRepository.resolve(rev), rev))
case None => None
}
.find(_._1 != null)
}
def createBranch(git: Git, fromBranch: String, newBranch: String) = {
try {
git.branchCreate().setStartPoint(fromBranch).setName(newBranch).call()
Right("Branch created.")
} catch {
case e: RefAlreadyExistsException => Left("Sorry, that branch already exists.")
// JGitInternalException occurs when new branch name is 'a' and the branch whose name is 'a/*' exists.
case _: InvalidRefNameException | _: JGitInternalException => Left("Sorry, that name is invalid.")
}
}
def createDirCacheEntry(path: String, mode: FileMode, objectId: ObjectId): DirCacheEntry = {
val entry = new DirCacheEntry(path)
entry.setFileMode(mode)
entry.setObjectId(objectId)
entry
}
def createNewCommit(
git: Git,
inserter: ObjectInserter,
headId: AnyObjectId,
treeId: AnyObjectId,
ref: String,
fullName: String,
mailAddress: String,
message: String
): ObjectId = {
val newCommit = new CommitBuilder()
newCommit.setCommitter(new PersonIdent(fullName, mailAddress))
newCommit.setAuthor(new PersonIdent(fullName, mailAddress))
newCommit.setMessage(message)
if (headId != null) {
newCommit.setParentIds(List(headId).asJava)
}
newCommit.setTreeId(treeId)
val newHeadId = inserter.insert(newCommit)
inserter.flush()
inserter.close()
val refUpdate = git.getRepository.updateRef(ref)
refUpdate.setNewObjectId(newHeadId)
refUpdate.update()
removeCache(git)
newHeadId
}
/**
* Read submodule information from .gitmodules
*/
def getSubmodules(git: Git, tree: RevTree, baseUrl: Option[String]): List[SubmoduleInfo] = {
val repository = git.getRepository
getContentFromPath(git, tree, ".gitmodules", true).map { bytes =>
(try {
val config = new BlobBasedConfig(repository.getConfig(), bytes)
config.getSubsections("submodule").asScala.map { module =>
val path = config.getString("submodule", module, "path")
val url = config.getString("submodule", module, "url")
SubmoduleInfo(module, path, url, StringUtil.getRepositoryViewerUrl(url, baseUrl))
}
} catch {
case e: ConfigInvalidException => {
logger.error("Failed to load .gitmodules file for " + repository.getDirectory(), e)
Nil
}
}).toList
} getOrElse Nil
}
/**
* Get object content of the given path as byte array from the Git repository.
*
* @param git the Git object
* @param revTree the rev tree
* @param path the path
* @param fetchLargeFile if false then returns None for the large file
* @return the byte array of content or None if object does not exist
*/
def getContentFromPath(git: Git, revTree: RevTree, path: String, fetchLargeFile: Boolean): Option[Array[Byte]] = {
@scala.annotation.tailrec
def getPathObjectId(path: String, walk: TreeWalk): Option[ObjectId] = walk.next match {
case true if (walk.getPathString == path) => Some(walk.getObjectId(0))
case true => getPathObjectId(path, walk)
case false => None
}
using(new TreeWalk(git.getRepository)) { treeWalk =>
treeWalk.addTree(revTree)
treeWalk.setRecursive(true)
getPathObjectId(path, treeWalk)
} flatMap { objectId =>
getContentFromId(git, objectId, fetchLargeFile)
}
}
def getLfsObjects(text: String): Map[String, String] = {
if (text.startsWith("version https://git-lfs.github.com/spec/v1")) {
// LFS objects
text
.split("\n")
.map { line =>
val dim = line.split(" ")
dim(0) -> dim(1)
}
.toMap
} else {
Map.empty
}
}
def getContentSize(loader: ObjectLoader): Long = {
if (loader.isLarge) {
loader.getSize
} else {
val bytes = loader.getCachedBytes
val text = new String(bytes, "UTF-8")
val attr = getLfsObjects(text)
attr.get("size") match {
case Some(size) => size.toLong
case None => loader.getSize
}
}
}
def isLfsPointer(loader: ObjectLoader): Boolean = {
!loader.isLarge && new String(loader.getBytes(), "UTF-8").startsWith("version https://git-lfs.github.com/spec/v1")
}
def getContentInfo(git: Git, path: String, objectId: ObjectId): ContentInfo = {
// Viewer
using(git.getRepository.getObjectDatabase) { db =>
val loader = db.open(objectId)
val isLfs = isLfsPointer(loader)
val large = FileUtil.isLarge(loader.getSize)
val viewer = if (FileUtil.isImage(path)) "image" else if (large) "large" else "other"
val bytes = if (viewer == "other") JGitUtil.getContentFromId(git, objectId, false) else None
val size = Some(getContentSize(loader))
if (viewer == "other") {
if (!isLfs && bytes.isDefined && FileUtil.isText(bytes.get)) {
// text
ContentInfo(
"text",
size,
Some(StringUtil.convertFromByteArray(bytes.get)),
Some(StringUtil.detectEncoding(bytes.get))
)
} else {
// binary
ContentInfo("binary", size, None, None)
}
} else {
// image or large
ContentInfo(viewer, size, None, None)
}
}
}