You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sendmail-html.groovy 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. /*
  2. * Copyright 2012 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import com.gitblit.GitBlit
  17. import com.gitblit.Keys
  18. import com.gitblit.models.RepositoryModel
  19. import com.gitblit.models.TeamModel
  20. import com.gitblit.models.UserModel
  21. import com.gitblit.utils.JGitUtils
  22. import java.text.SimpleDateFormat
  23. import org.eclipse.jgit.api.Status;
  24. import org.eclipse.jgit.api.errors.JGitInternalException;
  25. import org.eclipse.jgit.diff.DiffEntry;
  26. import org.eclipse.jgit.diff.DiffFormatter;
  27. import org.eclipse.jgit.diff.RawTextComparator;
  28. import org.eclipse.jgit.diff.DiffEntry.ChangeType;
  29. import org.eclipse.jgit.lib.Constants;
  30. import org.eclipse.jgit.lib.IndexDiff;
  31. import org.eclipse.jgit.lib.ObjectId;
  32. import org.eclipse.jgit.lib.Repository
  33. import org.eclipse.jgit.lib.Config
  34. import org.eclipse.jgit.patch.FileHeader;
  35. import org.eclipse.jgit.revwalk.RevCommit
  36. import org.eclipse.jgit.revwalk.RevWalk;
  37. import org.eclipse.jgit.transport.ReceiveCommand
  38. import org.eclipse.jgit.transport.ReceiveCommand.Result
  39. import org.eclipse.jgit.treewalk.FileTreeIterator;
  40. import org.eclipse.jgit.treewalk.EmptyTreeIterator;
  41. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  42. import org.eclipse.jgit.util.io.DisabledOutputStream;
  43. import org.slf4j.Logger
  44. import groovy.xml.MarkupBuilder
  45. import java.io.IOException;
  46. import java.security.MessageDigest
  47. /**
  48. * Sample Gitblit Post-Receive Hook: sendmail-html
  49. *
  50. * The Post-Receive hook is executed AFTER the pushed commits have been applied
  51. * to the Git repository. This is the appropriate point to trigger an
  52. * integration build or to send a notification.
  53. *
  54. * This script is only executed when pushing to *Gitblit*, not to other Git
  55. * tooling you may be using.
  56. *
  57. * If this script is specified in *groovy.postReceiveScripts* of gitblit.properties
  58. * or web.xml then it will be executed by any repository when it receives a
  59. * push. If you choose to share your script then you may have to consider
  60. * tailoring control-flow based on repository access restrictions.
  61. *
  62. * Scripts may also be specified per-repository in the repository settings page.
  63. * Shared scripts will be excluded from this list of available scripts.
  64. *
  65. * This script is dynamically reloaded and it is executed within it's own
  66. * exception handler so it will not crash another script nor crash Gitblit.
  67. *
  68. * If you want this hook script to fail and abort all subsequent scripts in the
  69. * chain, "return false" at the appropriate failure points.
  70. *
  71. * Bound Variables:
  72. * gitblit Gitblit Server com.gitblit.GitBlit
  73. * repository Gitblit Repository com.gitblit.models.RepositoryModel
  74. * user Gitblit User com.gitblit.models.UserModel
  75. * commands JGit commands Collection<org.eclipse.jgit.transport.ReceiveCommand>
  76. * url Base url for Gitblit java.lang.String
  77. * logger Logs messages to Gitblit org.slf4j.Logger
  78. * clientLogger Logs messages to Git client com.gitblit.utils.ClientLogger
  79. *
  80. * Accessing Gitblit Custom Fields:
  81. * def myCustomField = repository.customFields.myCustomField
  82. *
  83. */
  84. com.gitblit.models.UserModel userModel = user
  85. // Indicate we have started the script
  86. logger.info("sendmail-html hook triggered by ${user.username} for ${repository.name}")
  87. /*
  88. * Primitive email notification.
  89. * This requires the mail settings to be properly configured in Gitblit.
  90. */
  91. Repository r = gitblit.getRepository(repository.name)
  92. // reuse existing repository config settings, if available
  93. Config config = r.getConfig()
  94. def mailinglist = config.getString('hooks', null, 'mailinglist')
  95. def emailprefix = config.getString('hooks', null, 'emailprefix')
  96. // set default values
  97. def toAddresses = []
  98. if (emailprefix == null) {
  99. emailprefix = '[Gitblit]'
  100. }
  101. if (mailinglist != null) {
  102. def addrs = mailinglist.split(/(,|\s)/)
  103. toAddresses.addAll(addrs)
  104. }
  105. // add all mailing lists defined in gitblit.properties or web.xml
  106. toAddresses.addAll(GitBlit.getStrings(Keys.mail.mailingLists))
  107. // add all team mailing lists
  108. def teams = gitblit.getRepositoryTeams(repository)
  109. for (team in teams) {
  110. TeamModel model = gitblit.getTeamModel(team)
  111. if (model.mailingLists) {
  112. toAddresses.addAll(model.mailingLists)
  113. }
  114. }
  115. // add all mailing lists for the repository
  116. toAddresses.addAll(repository.mailingLists)
  117. // define the summary and commit urls
  118. def repo = repository.name
  119. def summaryUrl = url + "/summary?r=$repo"
  120. def baseCommitUrl = url + "/commit?r=$repo&h="
  121. def baseBlobDiffUrl = url + "/blobdiff/?r=$repo&h="
  122. def baseCommitDiffUrl = url + "/commitdiff/?r=$repo&h="
  123. def forwardSlashChar = gitblit.getString(Keys.web.forwardSlashCharacter, '/')
  124. if (gitblit.getBoolean(Keys.web.mountParameters, true)) {
  125. repo = repo.replace('/', forwardSlashChar).replace('/', '%2F')
  126. summaryUrl = url + "/summary/$repo"
  127. baseCommitUrl = url + "/commit/$repo/"
  128. baseBlobDiffUrl = url + "/blobdiff/$repo/"
  129. baseCommitDiffUrl = url + "/commitdiff/$repo/"
  130. }
  131. class HtmlMailWriter {
  132. Repository repository
  133. def url
  134. def baseCommitUrl
  135. def baseCommitDiffUrl
  136. def baseBlobDiffUrl
  137. def mountParameters
  138. def forwardSlashChar
  139. def includeGravatar
  140. def shortCommitIdLength
  141. def commitCount = 0
  142. def commands
  143. def writer = new StringWriter();
  144. def builder = new MarkupBuilder(writer)
  145. def writeStyle() {
  146. builder.style(type:"text/css", '''
  147. .table td {
  148. vertical-align: middle;
  149. }
  150. tr.noborder td {
  151. border: none;
  152. padding-top: 0px;
  153. }
  154. .gravatar-column {
  155. width: 5%;
  156. }
  157. .author-column {
  158. width: 20%;
  159. }
  160. .commit-column {
  161. width: 5%;
  162. }
  163. .status-column {
  164. width: 10%;
  165. }
  166. .table-disable-hover.table tbody tr:hover td,
  167. .table-disable-hover.table tbody tr:hover th {
  168. background-color: inherit;
  169. }
  170. .table-disable-hover.table-striped tbody tr:nth-child(odd):hover td,
  171. .table-disable-hover.table-striped tbody tr:nth-child(odd):hover th {
  172. background-color: #f9f9f9;
  173. }
  174. ''')
  175. }
  176. def writeBranchTitle(type, name, action, number) {
  177. builder.div('class' : 'pageTitle') {
  178. builder.span('class':'project') {
  179. mkp.yield "$type "
  180. span('class': 'repository', name )
  181. if (number > 0) {
  182. mkp.yield " $action ($number commits)"
  183. } else {
  184. mkp.yield " $action"
  185. }
  186. }
  187. }
  188. }
  189. def writeBranchDeletedTitle(type, name) {
  190. builder.div('class' : 'pageTitle', 'style':'color:red') {
  191. builder.span('class':'project') {
  192. mkp.yield "$type "
  193. span('class': 'repository', name )
  194. mkp.yield " deleted"
  195. }
  196. }
  197. }
  198. def commitUrl(RevCommit commit) {
  199. "${baseCommitUrl}$commit.id.name"
  200. }
  201. def commitDiffUrl(RevCommit commit) {
  202. "${baseCommitDiffUrl}$commit.id.name"
  203. }
  204. def encoded(String path) {
  205. path.replace('/', forwardSlashChar).replace('/', '%2F')
  206. }
  207. def blobDiffUrl(objectId, path) {
  208. if (mountParameters) {
  209. // REST style
  210. "${baseBlobDiffUrl}${objectId.name()}/${encoded(path)}"
  211. } else {
  212. "${baseBlobDiffUrl}${objectId.name()}&f=${path}"
  213. }
  214. }
  215. def writeCommitTable(commits, includeChangedPaths=true) {
  216. // Write commits table
  217. builder.table('class':"table table-disable-hover") {
  218. thead {
  219. tr {
  220. th(colspan: includeGravatar ? 2 : 1, "Author")
  221. th( "Commit" )
  222. th( "Message" )
  223. }
  224. }
  225. tbody() {
  226. // Write all the commits
  227. for (commit in commits) {
  228. writeCommit(commit)
  229. if (includeChangedPaths) {
  230. // Write detail on that particular commit
  231. tr('class' : 'noborder') {
  232. td (colspan: includeGravatar ? 3 : 2)
  233. td (colspan:2) { writeStatusTable(commit) }
  234. }
  235. }
  236. }
  237. }
  238. }
  239. }
  240. def writeCommit(commit) {
  241. def abbreviated = repository.newObjectReader().abbreviate(commit.id, shortCommitIdLength).name()
  242. def author = commit.authorIdent.name
  243. def email = commit.authorIdent.emailAddress
  244. def message = commit.shortMessage
  245. builder.tr {
  246. if (includeGravatar) {
  247. td('class':"gravatar-column") {
  248. img(src:gravatarUrl(email), 'class':"gravatar")
  249. }
  250. }
  251. td('class':"author-column", author)
  252. td('class':"commit-column") {
  253. a(href:commitUrl(commit)) {
  254. span('class':"label label-info", abbreviated )
  255. }
  256. }
  257. td {
  258. mkp.yield message
  259. a('class':'link', href:commitDiffUrl(commit), " [commitdiff]" )
  260. }
  261. }
  262. }
  263. def writeStatusLabel(style, tooltip) {
  264. builder.span('class' : style, 'title' : tooltip )
  265. }
  266. def writeAddStatusLine(ObjectId id, FileHeader header) {
  267. builder.td('class':'changeType') {
  268. writeStatusLabel("addition", "addition")
  269. }
  270. builder.td {
  271. a(href:blobDiffUrl(id, header.newPath), header.newPath)
  272. }
  273. }
  274. def writeCopyStatusLine(ObjectId id, FileHeader header) {
  275. builder.td('class':'changeType') {
  276. writeStatusLabel("rename", "rename")
  277. }
  278. builder.td() {
  279. a(href:blobDiffUrl(id, header.newPath), header.oldPath + " copied to " + header.newPath)
  280. }
  281. }
  282. def writeDeleteStatusLine(ObjectId id, FileHeader header) {
  283. builder.td('class':'changeType') {
  284. writeStatusLabel("deletion", "deletion")
  285. }
  286. builder.td() {
  287. a(href:blobDiffUrl(id, header.oldPath), header.oldPath)
  288. }
  289. }
  290. def writeModifyStatusLine(ObjectId id, FileHeader header) {
  291. builder.td('class':'changeType') {
  292. writeStatusLabel("modification", "modification")
  293. }
  294. builder.td() {
  295. a(href:blobDiffUrl(id, header.oldPath), header.oldPath)
  296. }
  297. }
  298. def writeRenameStatusLine(ObjectId id, FileHeader header) {
  299. builder.td('class':'changeType') {
  300. writeStatusLabel("rename", "rename")
  301. }
  302. builder.td() {
  303. mkp.yield header.oldPath
  304. mkp.yieldUnescaped "<b> -&rt; </b>"
  305. a(href:blobDiffUrl(id, header.newPath), header.newPath)
  306. }
  307. }
  308. def writeStatusLine(ObjectId id, FileHeader header) {
  309. builder.tr {
  310. switch (header.changeType) {
  311. case ChangeType.ADD:
  312. writeAddStatusLine(id, header)
  313. break;
  314. case ChangeType.COPY:
  315. writeCopyStatusLine(id, header)
  316. break;
  317. case ChangeType.DELETE:
  318. writeDeleteStatusLine(id, header)
  319. break;
  320. case ChangeType.MODIFY:
  321. writeModifyStatusLine(id, header)
  322. break;
  323. case ChangeType.RENAME:
  324. writeRenameStatusLine(id, header)
  325. break;
  326. }
  327. }
  328. }
  329. def writeStatusTable(RevCommit commit) {
  330. DiffFormatter formatter = new DiffFormatter(DisabledOutputStream.INSTANCE)
  331. formatter.setRepository(repository)
  332. formatter.setDetectRenames(true)
  333. formatter.setDiffComparator(RawTextComparator.DEFAULT);
  334. def diffs
  335. RevWalk rw = new RevWalk(repository)
  336. if (commit.parentCount > 0) {
  337. RevCommit parent = rw.parseCommit(commit.parents[0].id)
  338. diffs = formatter.scan(parent.tree, commit.tree)
  339. } else {
  340. diffs = formatter.scan(new EmptyTreeIterator(),
  341. new CanonicalTreeParser(null, rw.objectReader, commit.tree))
  342. }
  343. rw.dispose()
  344. // Write status table
  345. builder.table('class':"plain") {
  346. tbody() {
  347. for (DiffEntry entry in diffs) {
  348. FileHeader header = formatter.toFileHeader(entry)
  349. writeStatusLine(commit.id, header)
  350. }
  351. }
  352. }
  353. }
  354. def md5(text) {
  355. def digest = MessageDigest.getInstance("MD5")
  356. //Quick MD5 of text
  357. def hash = new BigInteger(1, digest.digest(text.getBytes()))
  358. .toString(16)
  359. .padLeft(32, "0")
  360. hash.toString()
  361. }
  362. def gravatarUrl(email) {
  363. def cleaned = email.trim().toLowerCase()
  364. "http://www.gravatar.com/avatar/${md5(cleaned)}?s=30"
  365. }
  366. def writeNavbar() {
  367. builder.div('class':"navbar navbar-fixed-top") {
  368. div('class':"navbar-inner") {
  369. div('class':"container") {
  370. a('class':"brand", href:"${url}", title:"GitBlit") {
  371. img(src:"${url}/gitblt_25_white.png",
  372. width:"79",
  373. height:"25",
  374. 'class':"logo")
  375. }
  376. }
  377. }
  378. }
  379. }
  380. def write() {
  381. builder.html {
  382. head {
  383. link(rel:"stylesheet", href:"${url}/bootstrap/css/bootstrap.css")
  384. link(rel:"stylesheet", href:"${url}/gitblit.css")
  385. link(rel:"stylesheet", href:"${url}/bootstrap/css/bootstrap-responsive.css")
  386. writeStyle()
  387. }
  388. body {
  389. writeNavbar()
  390. div('class':"container") {
  391. for (command in commands) {
  392. def ref = command.refName
  393. def refType = 'Branch'
  394. if (ref.startsWith('refs/heads/')) {
  395. ref = command.refName.substring('refs/heads/'.length())
  396. } else if (ref.startsWith('refs/tags/')) {
  397. ref = command.refName.substring('refs/tags/'.length())
  398. refType = 'Tag'
  399. }
  400. switch (command.type) {
  401. case ReceiveCommand.Type.CREATE:
  402. def commits = JGitUtils.getRevLog(repository, command.oldId.name, command.newId.name).reverse()
  403. commitCount += commits.size()
  404. if (refType == 'Branch') {
  405. // new branch
  406. writeBranchTitle(refType, ref, "created", commits.size())
  407. writeCommitTable(commits, true)
  408. } else {
  409. // new tag
  410. writeBranchTitle(refType, ref, "created", 0)
  411. writeCommitTable(commits, false)
  412. }
  413. break
  414. case ReceiveCommand.Type.UPDATE:
  415. def commits = JGitUtils.getRevLog(repository, command.oldId.name, command.newId.name).reverse()
  416. commitCount += commits.size()
  417. // fast-forward branch commits table
  418. // Write header
  419. writeBranchTitle(refType, ref, "updated", commits.size())
  420. writeCommitTable(commits)
  421. break
  422. case ReceiveCommand.Type.UPDATE_NONFASTFORWARD:
  423. def commits = JGitUtils.getRevLog(repository, command.oldId.name, command.newId.name).reverse()
  424. commitCount += commits.size()
  425. // non-fast-forward branch commits table
  426. // Write header
  427. writeBranchTitle(refType, ref, "updated [NON fast-forward]", commits.size())
  428. writeCommitTable(commits)
  429. break
  430. case ReceiveCommand.Type.DELETE:
  431. // deleted branch/tag
  432. writeBranchDeletedTitle(refType, ref)
  433. break
  434. default:
  435. break
  436. }
  437. }
  438. }
  439. }
  440. }
  441. writer.toString()
  442. }
  443. }
  444. def mailWriter = new HtmlMailWriter()
  445. mailWriter.repository = r
  446. mailWriter.baseCommitUrl = baseCommitUrl
  447. mailWriter.baseBlobDiffUrl = baseBlobDiffUrl
  448. mailWriter.baseCommitDiffUrl = baseCommitDiffUrl
  449. mailWriter.forwardSlashChar = forwardSlashChar
  450. mailWriter.commands = commands
  451. mailWriter.url = url
  452. mailWriter.mountParameters = GitBlit.getBoolean(Keys.web.mountParameters, true)
  453. mailWriter.includeGravatar = GitBlit.getBoolean(Keys.web.allowGravatar, true)
  454. mailWriter.shortCommitIdLength = GitBlit.getInteger(Keys.web.shortCommitIdLength, 8)
  455. def content = mailWriter.write()
  456. // close the repository reference
  457. r.close()
  458. // tell Gitblit to send the message (Gitblit filters duplicate addresses)
  459. def repositoryName = repository.name.substring(0, repository.name.length() - 4)
  460. gitblit.sendHtmlMail("${emailprefix} ${userModel.displayName} pushed ${mailWriter.commitCount} commits => $repositoryName",
  461. content,
  462. toAddresses)