Compare commits

...

45 Commits
3.8 ... 3.9

Author SHA1 Message Date
Naoki Takezoe
9477cca8e8 Fix box style 2015-12-05 19:54:32 +09:00
Naoki Takezoe
176e427058 Update README.md for 3.9 release 2015-12-05 19:48:44 +09:00
Naoki Takezoe
1bf26cacb9 Update version to 3.9.0 2015-12-05 19:46:29 +09:00
Naoki Takezoe
711aee1c8b Fix markedj version as 1.0.5 2015-12-05 03:54:51 +09:00
Naoki Takezoe
51be1048d5 (refs #987)Remove user related data when users delete themselves 2015-12-05 03:45:26 +09:00
Naoki Takezoe
50166f04d8 Disable auto completion in the select user field 2015-12-05 03:43:57 +09:00
Naoki Takezoe
7eb6fea08b Fix typo in comment 2015-12-05 03:12:21 +09:00
Naoki Takezoe
8e3c054da4 Merge pull request #983 from team-lab/feature/webhook-review-comment
Send webhook on create pull request review comment
2015-12-05 01:14:54 +09:00
nazoking
5249b67df1 Merge branch 'master' into feature/webhook-review-comment 2015-12-03 20:09:46 +09:00
Naoki Takezoe
dc5cb74f4d Merge branch 'master' of https://github.com/takezoe/gitbucket 2015-11-18 01:48:47 +09:00
Naoki Takezoe
446a524b5a Upgrade scalatra-forms to 0.2.0 to solve performance issue 2015-11-18 01:48:40 +09:00
Naoki Takezoe
121110aede Fix markdown header style 2015-11-17 23:19:08 +09:00
Naoki Takezoe
c76a8562ea Merge pull request #995 from uli-heller/patch-2
extensibility is probably the right word?
2015-11-17 19:28:00 +09:00
uli-heller
495d8069f5 extensibility is probably the right word? 2015-11-17 09:51:50 +01:00
Naoki Takezoe
70af6d0c35 Update README.md 2015-11-17 16:04:58 +09:00
Naoki Takezoe
abfc6eea1e Fix repository setting pages presentation 2015-11-17 01:52:14 +09:00
Naoki Takezoe
fd2f3e252c Fix webhook editing presentation and performance issue 2015-11-17 01:51:55 +09:00
Naoki Takezoe
3b6d0065a2 Once delete editHooks.scala.html to rename 2015-11-17 01:48:13 +09:00
Naoki Takezoe
30f072f925 Merge pull request #992 from team-lab/fix/lost-webhook-events-on-rename-repository
fix lost web hook events on repository renamed.
2015-11-14 15:02:41 +09:00
nazoking
72d0282613 Merge branch 'master' into feature/webhook-review-comment 2015-11-14 13:27:40 +09:00
nazoking
a56f766497 fix lost web hook events on repository renamed. 2015-11-14 13:16:13 +09:00
Naoki Takezoe
fc41e282ce Merge pull request #973 from gitbucket/commit_comment_count
Count COMMIT_COMMENT as issue comment
2015-11-10 11:48:20 +09:00
Naoki Takezoe
d3b21a4e39 Drop PULL_REQUEST column from COMMIT_COMMENT table 2015-11-10 11:35:59 +09:00
nazoking
84d97817e3 add comment 2015-11-09 13:57:37 +09:00
nazoking
2c6d2176bb fix space 2015-11-09 13:57:26 +09:00
nazoking
7840d28ed2 add webhook pull-request-review-comment 2015-11-09 12:20:07 +09:00
Naoki Takezoe
d4fd2e6cd6 Remove bottom margin of inline comment in diff view 2015-11-09 01:20:44 +09:00
Naoki Takezoe
70e8385246 (refs #974)Not hide add-comment icon when adding comment form is active. 2015-11-09 01:15:04 +09:00
Naoki Takezoe
3fd23f1749 Fix markdown preview style 2015-11-08 22:26:43 +09:00
Naoki Takezoe
a3e3aea4e0 Fix styles 2015-11-08 19:08:05 +09:00
Naoki Takezoe
dcfb8ad8eb (refs #976)Enable GFM line breaks 2015-11-08 18:03:44 +09:00
Naoki Takezoe
35f82e91bc (refs #976)Upgrade markedj to 1.0.5-SNAPSHOT 2015-11-08 17:49:25 +09:00
Naoki Takezoe
f1533cb168 Count COMMIT_COMMENT as issue comment 2015-11-08 04:06:14 +09:00
Naoki Takezoe
763fbec0ca Update README.md 2015-11-08 02:58:54 +09:00
Naoki Takezoe
111c893d94 Merge pull request #968 from justinpitts/master
Correct typo on system administration page.
2015-11-07 03:35:39 +09:00
Naoki Takezoe
80c38a45c5 Merge pull request #941 from team-lab/feature/webhook-scope
feature/can select event trigger of webhook.
2015-11-07 03:35:09 +09:00
nazoking
548860607b update migration version to 3.9 from 3.8 2015-11-06 14:52:36 +09:00
nazoking
66b5fe7337 Merge branch 'master' into feature/webhook-scope 2015-11-06 14:48:03 +09:00
Justin Pitts
2b2a117912 Correct typo on system administration page. 2015-11-04 08:51:48 -05:00
Naoki Takezoe
39a10fd167 Update README.md 2015-11-04 02:00:14 +09:00
Naoki Takezoe
93f8dbd42a Fix markedj version 2015-11-02 08:58:29 +09:00
Naoki Takezoe
4f280d0df8 Fix blockquote font size 2015-11-02 02:33:06 +09:00
Naoki Takezoe
5e9ff3278a Fix the default number of displayed repositories 2015-11-02 00:32:46 +09:00
Naoki Takezoe
b4b68f0e17 Update README.md 2015-10-31 11:55:16 +09:00
nazoking
a08a212fdc feature/can select webhook events 2015-10-13 18:48:02 +09:00
39 changed files with 799 additions and 140 deletions

View File

@@ -1,8 +1,7 @@
GitBucket [![Gitter chat](https://badges.gitter.im/gitbucket/gitbucket.png)](https://gitter.im/gitbucket/gitbucket) [![Build Status](https://travis-ci.org/gitbucket/gitbucket.svg?branch=master)](https://travis-ci.org/gitbucket/gitbucket)
=========
GitBucket is the easily installable GitHub clone powered by Scala.
GitBucket is a GitHub clone powered by Scala which has easy installation and high extensibility.
Features
--------
@@ -40,7 +39,7 @@ or you can start GitBucket by `java -jar gitbucket.war` without servlet containe
- --host=[HOSTNAME]
- --gitbucket.home=[DATA_DIR]
To upgrade GitBucket, only replace gitbucket.war. All GitBucket data is stored in HOME/.gitbucket. So if you want to back up GitBucket data, copy this directory to the other disk.
To upgrade GitBucket, only replace gitbucket.war after stop GitBucket. All GitBucket data is stored in HOME/.gitbucket. So if you want to back up GitBucket data, copy this directory to the other disk.
For Installation on Windows Server with IIS see [this wiki page](https://github.com/gitbucket/gitbucket/wiki/Installation-on-IIS-and-Helicontech-Zoo)
@@ -81,6 +80,7 @@ GitBucket has the plug-in system to extend GitBucket from outside of GitBucket.
- [gitbucket-h2-backup-plugin](https://github.com/gitbucket-plugins/gitbucket-h2-backup-plugin)
- [gitbucket-desktopnotify-plugin](https://github.com/yoshiyoshifujii/gitbucket-desktopnotify-plugin)
- [gitbucket-commitgraphs-plugin](https://github.com/yoshiyoshifujii/gitbucket-commitgraphs-plugin)
- [gitbucket-asciidoctor-plugin](https://github.com/lefou/gitbucket-asciidoctor-plugin)
You can find community plugins other than them at [gitbucket community plugins](http://gitbucket-plugins.github.io/).
@@ -95,8 +95,13 @@ Support
Release Notes
--------
### 3.9 - 5 Dec 2015
- GFM inline breaks support in Markdown
- WebHook on create review comment is available
- WebHook event trigger is selectable
### 3.8 - 31 Oct 2015
- Moved to organization
- Moved to GitHub organization
- Omit diff view for large differences
- Repository creation API
- Render url as link in repository description

View File

@@ -10,7 +10,7 @@ import sbtassembly.AssemblyKeys._
object MyBuild extends Build {
val Organization = "gitbucket"
val Name = "gitbucket"
val Version = "3.8.0"
val Version = "3.9.0"
val ScalaVersion = "2.11.6"
val ScalatraVersion = "2.3.1"
@@ -49,9 +49,9 @@ object MyBuild extends Build {
"org.scalatra" %% "scalatra-specs2" % ScalatraVersion % "test",
"org.scalatra" %% "scalatra-json" % ScalatraVersion,
"org.json4s" %% "json4s-jackson" % "3.2.11",
"jp.sf.amateras" %% "scalatra-forms" % "0.1.0",
"jp.sf.amateras" %% "scalatra-forms" % "0.2.0",
"commons-io" % "commons-io" % "2.4",
"io.github.gitbucket" % "markedj" % "1.0.4-SNAPSHOT",
"io.github.gitbucket" % "markedj" % "1.0.5",
"org.apache.commons" % "commons-compress" % "1.9",
"org.apache.commons" % "commons-email" % "1.3.3",
"org.apache.httpcomponents" % "httpclient" % "4.3.6",

View File

@@ -0,0 +1,55 @@
DROP TABLE IF EXISTS WEB_HOOK_EVENT;
CREATE TABLE WEB_HOOK_EVENT(
USER_NAME VARCHAR(100) NOT NULL,
REPOSITORY_NAME VARCHAR(100) NOT NULL,
URL VARCHAR(200) NOT NULL,
EVENT VARCHAR(30) NOT NULL
);
ALTER TABLE WEB_HOOK_EVENT ADD CONSTRAINT IDX_WEB_HOOK_EVENT_PK PRIMARY KEY (USER_NAME, REPOSITORY_NAME, URL, EVENT);
ALTER TABLE WEB_HOOK_EVENT ADD CONSTRAINT IDX_WEB_HOOK_EVENT_FK0 FOREIGN KEY (USER_NAME, REPOSITORY_NAME, URL) REFERENCES WEB_HOOK (USER_NAME, REPOSITORY_NAME, URL)
ON DELETE CASCADE ON UPDATE CASCADE;
CREATE TEMPORARY TABLE TMP_EVENTS (EVENT VARCHAR(30));
INSERT INTO TMP_EVENTS VALUES ('push'),('issue_comment'),('issues'),('pull_request');
INSERT INTO WEB_HOOK_EVENT (USER_NAME, REPOSITORY_NAME, URL, EVENT)
SELECT USER_NAME, REPOSITORY_NAME, URL, EVENT
FROM WEB_HOOK, TMP_EVENTS;
DROP TABLE TMP_EVENTS;
ALTER TABLE COMMIT_COMMENT ADD COLUMN ISSUE_ID INT;
CREATE OR REPLACE VIEW ISSUE_OUTLINE_VIEW AS
SELECT
A.USER_NAME,
A.REPOSITORY_NAME,
A.ISSUE_ID,
NVL(B.COMMENT_COUNT, 0) + NVL(C.COMMENT_COUNT, 0) AS COMMENT_COUNT
FROM ISSUE A
LEFT OUTER JOIN (
SELECT USER_NAME, REPOSITORY_NAME, ISSUE_ID, COUNT(COMMENT_ID) AS COMMENT_COUNT FROM ISSUE_COMMENT
WHERE ACTION IN ('comment', 'close_comment', 'reopen_comment')
GROUP BY USER_NAME, REPOSITORY_NAME, ISSUE_ID
) B
ON (A.USER_NAME = B.USER_NAME AND A.REPOSITORY_NAME = B.REPOSITORY_NAME AND A.ISSUE_ID = B.ISSUE_ID)
LEFT OUTER JOIN (
SELECT USER_NAME, REPOSITORY_NAME, ISSUE_ID, COUNT(COMMENT_ID) AS COMMENT_COUNT FROM COMMIT_COMMENT
GROUP BY USER_NAME, REPOSITORY_NAME, ISSUE_ID
) C
ON (A.USER_NAME = C.USER_NAME AND A.REPOSITORY_NAME = C.REPOSITORY_NAME AND A.ISSUE_ID = C.ISSUE_ID);
UPDATE COMMIT_COMMENT C SET (ISSUE_ID) = (
SELECT MAX(P.ISSUE_ID)
FROM PULL_REQUEST P
WHERE
C.USER_NAME = P.USER_NAME AND
C.REPOSITORY_NAME = P.REPOSITORY_NAME AND
C.COMMIT_ID = P.COMMIT_ID_TO
);
ALTER TABLE COMMIT_COMMENT DROP COLUMN PULL_REQUEST;

View File

@@ -0,0 +1,61 @@
package gitbucket.core.api
import gitbucket.core.util.RepositoryName
import gitbucket.core.model.CommitComment
import java.util.Date
/**
* https://developer.github.com/v3/activity/events/types/#pullrequestreviewcommentevent
*/
case class ApiPullRequestReviewComment(
id: Int, // 29724692
// "diff_hunk": "@@ -1 +1 @@\n-# public-repo",
path: String, // "README.md",
// "position": 1,
// "original_position": 1,
commit_id: String, // "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c",
// "original_commit_id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c",
user: ApiUser,
body: String, // "Maybe you should use more emojji on this line.",
created_at: Date, // "2015-05-05T23:40:27Z",
updated_at: Date // "2015-05-05T23:40:27Z",
)(repositoryName:RepositoryName, issueId: Int) extends FieldSerializable {
// "url": "https://api.github.com/repos/baxterthehacker/public-repo/pulls/comments/29724692",
val url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/pulls/comments/${id}")
// "html_url": "https://github.com/baxterthehacker/public-repo/pull/1#discussion_r29724692",
val html_url = ApiPath(s"/${repositoryName.fullName}/pull/${issueId}#discussion_r${id}")
// "pull_request_url": "https://api.github.com/repos/baxterthehacker/public-repo/pulls/1",
val pull_request_url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/pulls/${issueId}")
/*
"_links": {
"self": {
"href": "https://api.github.com/repos/baxterthehacker/public-repo/pulls/comments/29724692"
},
"html": {
"href": "https://github.com/baxterthehacker/public-repo/pull/1#discussion_r29724692"
},
"pull_request": {
"href": "https://api.github.com/repos/baxterthehacker/public-repo/pulls/1"
}
}
*/
val _links = Map(
"self" -> Map("href" -> url),
"html" -> Map("href" -> html_url),
"pull_request" -> Map("href" -> pull_request_url))
}
object ApiPullRequestReviewComment{
def apply(comment: CommitComment, commentedUser: ApiUser, repositoryName: RepositoryName, issueId: Int): ApiPullRequestReviewComment =
new ApiPullRequestReviewComment(
id = comment.commentId,
path = comment.fileName.getOrElse(""),
commit_id = comment.commitId,
user = commentedUser,
body = comment.content,
created_at = comment.registeredDate,
updated_at = comment.updatedDate
)(repositoryName, issueId)
}

View File

@@ -212,6 +212,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
// // Remove from GROUP_MEMBER, COLLABORATOR and REPOSITORY
// removeUserRelatedData(userName)
removeUserRelatedData(userName)
updateAccount(account.copy(isRemoved = true))
}

View File

@@ -104,7 +104,7 @@ trait IndexControllerBase extends ControllerBase {
})
/**
* JSON APU for checking user existence.
* JSON API for checking user existence.
*/
post("/_user/existence")(usersOnly {
getAccountByUserName(params("userName")).isDefined

View File

@@ -14,6 +14,7 @@ import org.apache.commons.io.FileUtils
import org.scalatra.i18n.Messages
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.Constants
import scala.util.{Success, Failure}
import org.eclipse.jgit.lib.ObjectId
@@ -43,10 +44,11 @@ trait RepositorySettingsControllerBase extends ControllerBase {
)(CollaboratorForm.apply)
// for web hook url addition
case class WebHookForm(url: String)
case class WebHookForm(url: String, events: Set[WebHook.Event])
val webHookForm = mapping(
"url" -> trim(label("url", text(required, webHook)))
def webHookForm(update:Boolean) = mapping(
"url" -> trim(label("url", text(required, webHook(update)))),
"events" -> webhookEvents
)(WebHookForm.apply)
// for transfer ownership
@@ -139,14 +141,23 @@ trait RepositorySettingsControllerBase extends ControllerBase {
* Display the web hook page.
*/
get("/:owner/:repository/settings/hooks")(ownerOnly { repository =>
html.hooks(getWebHookURLs(repository.owner, repository.name), flash.get("url"), repository, flash.get("info"))
html.hooks(getWebHooks(repository.owner, repository.name), repository, flash.get("info"))
})
/**
* Display the web hook edit page.
*/
get("/:owner/:repository/settings/hooks/new")(ownerOnly { repository =>
val webhook = WebHook(repository.owner, repository.name, "")
html.edithooks(webhook, Set(WebHook.Push), repository, flash.get("info"), true)
})
/**
* Add the web hook URL.
*/
post("/:owner/:repository/settings/hooks/add", webHookForm)(ownerOnly { (form, repository) =>
addWebHookURL(repository.owner, repository.name, form.url)
post("/:owner/:repository/settings/hooks/new", webHookForm(false))(ownerOnly { (form, repository) =>
addWebHook(repository.owner, repository.name, form.url, form.events)
flash += "info" -> s"Webhook ${form.url} created"
redirect(s"/${repository.owner}/${repository.name}/settings/hooks")
})
@@ -154,32 +165,77 @@ trait RepositorySettingsControllerBase extends ControllerBase {
* Delete the web hook URL.
*/
get("/:owner/:repository/settings/hooks/delete")(ownerOnly { repository =>
deleteWebHookURL(repository.owner, repository.name, params("url"))
deleteWebHook(repository.owner, repository.name, params("url"))
flash += "info" -> s"Webhook ${params("url")} deleted"
redirect(s"/${repository.owner}/${repository.name}/settings/hooks")
})
/**
* Send the test request to registered web hook URLs.
*/
post("/:owner/:repository/settings/hooks/test", webHookForm)(ownerOnly { (form, repository) =>
ajaxPost("/:owner/:repository/settings/hooks/test")(ownerOnly { repository =>
using(Git.open(getRepositoryDir(repository.owner, repository.name))){ git =>
import scala.collection.JavaConverters._
val commits = if(repository.commitCount == 0) List.empty else git.log
.add(git.getRepository.resolve(repository.repository.defaultBranch))
.setMaxCount(4)
.call.iterator.asScala.map(new CommitInfo(_)).toList
import scala.concurrent.duration._
import scala.concurrent._
import scala.util.control.NonFatal
import org.apache.http.util.EntityUtils
import scala.concurrent.ExecutionContext.Implicits.global
getAccountByUserName(repository.owner).foreach { ownerAccount =>
callWebHook("push",
List(WebHook(repository.owner, repository.name, form.url)),
WebHookPushPayload(git, ownerAccount, "refs/heads/" + repository.repository.defaultBranch, repository, (if(commits.isEmpty){Nil}else{commits.tail}), ownerAccount,
oldId = commits.lastOption.map(_.id).map(ObjectId.fromString).getOrElse(ObjectId.zeroId()),
newId = commits.headOption.map(_.id).map(ObjectId.fromString).getOrElse(ObjectId.zeroId()))
)
val url = params("url")
val dummyPayload = {
val ownerAccount = getAccountByUserName(repository.owner).get
val commits = if(repository.commitCount == 0) List.empty else git.log
.add(git.getRepository.resolve(repository.repository.defaultBranch))
.setMaxCount(4)
.call.iterator.asScala.map(new CommitInfo(_)).toList
val pushedCommit = commits.drop(1)
WebHookPushPayload(git, ownerAccount, "refs/heads/" + repository.repository.defaultBranch, repository, pushedCommit, ownerAccount,
oldId = commits.lastOption.map(_.id).map(ObjectId.fromString).getOrElse(ObjectId.zeroId()),
newId = commits.headOption.map(_.id).map(ObjectId.fromString).getOrElse(ObjectId.zeroId()))
}
flash += "url" -> form.url
flash += "info" -> "Test payload deployed!"
val dummyWebHookInfo = WebHook(repository.owner, repository.name, url)
val (webHook, json, reqFuture, resFuture) = callWebHook(WebHook.Push, List(dummyWebHookInfo), dummyPayload).head
def headers(h: Array[org.apache.http.Header]): Array[Array[String]] = h.map{ h => Array(h.getName, h.getValue) }
val toErrorMap:PartialFunction[Throwable, Map[String,String]] = {
case e:java.net.UnknownHostException => Map("error"-> ("Unknown host "+ e.getMessage))
case e:java.lang.IllegalArgumentException => Map("error"-> ("invalid url"))
case e:org.apache.http.client.ClientProtocolException => Map("error"-> ("invalid url"))
case NonFatal(e) => Map("error"-> (e.getClass + " "+ e.getMessage))
}
contentType = formats("json")
var result = Map(
"url" -> url,
"request" -> Await.result(reqFuture.map(req => Map(
"headers" -> headers(req.getAllHeaders),
"payload" -> json
)).recover(toErrorMap), 20 seconds),
"responce" -> Await.result(resFuture.map(res => Map(
"status" -> res.getStatusLine(),
"body" -> EntityUtils.toString(res.getEntity()),
"headers" -> headers(res.getAllHeaders())
)).recover(toErrorMap), 20 seconds))
org.json4s.jackson.Serialization.write(result)
}
})
/**
* Display the web hook edit page.
*/
get("/:owner/:repository/settings/hooks/edit/:url")(ownerOnly { repository =>
getWebHook(repository.owner, repository.name, params("url")).map{ case (webhook, events) =>
html.edithooks(webhook, events, repository, flash.get("info"), false)
} getOrElse NotFound
})
/**
* Update web hook settings.
*/
post("/:owner/:repository/settings/hooks/edit/:url", webHookForm(true))(ownerOnly { (form, repository) =>
updateWebHook(repository.owner, repository.name, form.url, form.events)
flash += "info" -> s"webhook ${form.url} updated"
redirect(s"/${repository.owner}/${repository.name}/settings/hooks")
})
@@ -229,9 +285,30 @@ trait RepositorySettingsControllerBase extends ControllerBase {
/**
* Provides duplication check for web hook url.
*/
private def webHook: Constraint = new Constraint(){
private def webHook(needExists: Boolean): Constraint = new Constraint(){
override def validate(name: String, value: String, messages: Messages): Option[String] =
getWebHookURLs(params("owner"), params("repository")).map(_.url).find(_ == value).map(_ => "URL had been registered already.")
if(getWebHook(params("owner"), params("repository"), value).isDefined != needExists){
Some(if(needExists){
"URL had not been registered yet."
} else {
"URL had been registered already."
})
} else {
None
}
}
private def webhookEvents = new ValueType[Set[WebHook.Event]]{
def convert(name: String, params: Map[String, String], messages: Messages): Set[WebHook.Event] = {
WebHook.Event.values.flatMap { t =>
params.get(name + "." + t.name).map(_ => t)
}.toSet
}
def validate(name: String, params: Map[String, String], messages: Messages): Seq[(String, String)] = if(convert(name,params,messages).isEmpty){
Seq(name -> messages("error.required").format(name))
} else {
Nil
}
}
/**

View File

@@ -11,7 +11,7 @@ import gitbucket.core.util.StringUtil._
import gitbucket.core.util.ControlUtil._
import gitbucket.core.util.Implicits._
import gitbucket.core.util.Directory._
import gitbucket.core.model.{Account, CommitState}
import gitbucket.core.model.{Account, CommitState, WebHook}
import gitbucket.core.service.CommitStatusService
import gitbucket.core.service.WebHookService._
import gitbucket.core.view
@@ -32,7 +32,7 @@ import org.scalatra._
class RepositoryViewerController extends RepositoryViewerControllerBase
with RepositoryService with AccountService with ActivityService with IssuesService with WebHookService with CommitsService
with ReadableUsersAuthenticator with ReferrerAuthenticator with CollaboratorsAuthenticator with PullRequestService with CommitStatusService
with WebHookPullRequestService
with WebHookPullRequestService with WebHookPullRequestReviewCommentService
/**
* The repository viewer.
@@ -40,7 +40,7 @@ class RepositoryViewerController extends RepositoryViewerControllerBase
trait RepositoryViewerControllerBase extends ControllerBase {
self: RepositoryService with AccountService with ActivityService with IssuesService with WebHookService with CommitsService
with ReadableUsersAuthenticator with ReferrerAuthenticator with CollaboratorsAuthenticator with PullRequestService with CommitStatusService
with WebHookPullRequestService =>
with WebHookPullRequestService with WebHookPullRequestReviewCommentService =>
ArchiveCommand.registerFormat("zip", new ZipFormat)
ArchiveCommand.registerFormat("tar.gz", new TgzFormat)
@@ -370,7 +370,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
post("/:owner/:repository/commit/:id/comment/new", commentForm)(readableUsersOnly { (form, repository) =>
val id = params("id")
createCommitComment(repository.owner, repository.name, id, context.loginAccount.get.userName, form.content,
form.fileName, form.oldLineNumber, form.newLineNumber, form.issueId.isDefined)
form.fileName, form.oldLineNumber, form.newLineNumber, form.issueId)
form.issueId match {
case Some(issueId) => recordCommentPullRequestActivity(repository.owner, repository.name, context.loginAccount.get.userName, issueId, form.content)
case None => recordCommentCommitActivity(repository.owner, repository.name, context.loginAccount.get.userName, id, form.content)
@@ -395,13 +395,15 @@ trait RepositoryViewerControllerBase extends ControllerBase {
ajaxPost("/:owner/:repository/commit/:id/comment/_data/new", commentForm)(readableUsersOnly { (form, repository) =>
val id = params("id")
val commentId = createCommitComment(repository.owner, repository.name, id, context.loginAccount.get.userName,
form.content, form.fileName, form.oldLineNumber, form.newLineNumber, form.issueId.isDefined)
form.content, form.fileName, form.oldLineNumber, form.newLineNumber, form.issueId)
val comment = getCommitComment(repository.owner, repository.name, commentId.toString).get
form.issueId match {
case Some(issueId) => recordCommentPullRequestActivity(repository.owner, repository.name, context.loginAccount.get.userName, issueId, form.content)
case Some(issueId) =>
recordCommentPullRequestActivity(repository.owner, repository.name, context.loginAccount.get.userName, issueId, form.content)
callPullRequestReviewCommentWebHook("create", comment, repository, issueId, context.baseUrl, context.loginAccount.get)
case None => recordCommentCommitActivity(repository.owner, repository.name, context.loginAccount.get.userName, id, form.content)
}
helper.html.commitcomment(getCommitComment(repository.owner, repository.name, commentId.toString).get,
hasWritePermission(repository.owner, repository.name, context.loginAccount), repository)
helper.html.commitcomment(comment, hasWritePermission(repository.owner, repository.name, context.loginAccount), repository)
})
ajaxGet("/:owner/:repository/commit_comments/_data/:id")(readableUsersOnly { repository =>
@@ -667,7 +669,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
// call web hook
callPullRequestWebHookByRequestBranch("synchronize", repository, branch, context.baseUrl, loginAccount)
val commit = new JGitUtil.CommitInfo(JGitUtil.getRevCommitFromId(git, commitId))
callWebHookOf(repository.owner, repository.name, "push") {
callWebHookOf(repository.owner, repository.name, WebHook.Push) {
getAccountByUserName(repository.owner).map{ ownerAccount =>
WebHookPushPayload(git, loginAccount, headName, repository, List(commit), ownerAccount,
oldId = headTip, newId = commitId)

View File

@@ -100,12 +100,12 @@ trait UserManagementControllerBase extends AccountManagementControllerBase {
if(form.isRemoved){
// Remove repositories
getRepositoryNamesOfUser(userName).foreach { repositoryName =>
deleteRepository(userName, repositoryName)
FileUtils.deleteDirectory(getRepositoryDir(userName, repositoryName))
FileUtils.deleteDirectory(getWikiRepositoryDir(userName, repositoryName))
FileUtils.deleteDirectory(getTemporaryDir(userName, repositoryName))
}
// getRepositoryNamesOfUser(userName).foreach { repositoryName =>
// deleteRepository(userName, repositoryName)
// FileUtils.deleteDirectory(getRepositoryDir(userName, repositoryName))
// FileUtils.deleteDirectory(getWikiRepositoryDir(userName, repositoryName))
// FileUtils.deleteDirectory(getTemporaryDir(userName, repositoryName))
// }
// Remove from GROUP_MEMBER, COLLABORATOR and REPOSITORY
removeUserRelatedData(userName)
}

View File

@@ -55,8 +55,8 @@ trait CommitCommentComponent extends TemplateComponent { self: Profile =>
val newLine = column[Option[Int]]("NEW_LINE_NUMBER")
val registeredDate = column[java.util.Date]("REGISTERED_DATE")
val updatedDate = column[java.util.Date]("UPDATED_DATE")
val pullRequest = column[Boolean]("PULL_REQUEST")
def * = (userName, repositoryName, commitId, commentId, commentedUserName, content, fileName, oldLine, newLine, registeredDate, updatedDate, pullRequest) <> (CommitComment.tupled, CommitComment.unapply)
val issueId = column[Option[Int]]("ISSUE_ID")
def * = (userName, repositoryName, commitId, commentId, commentedUserName, content, fileName, oldLine, newLine, registeredDate, updatedDate, issueId) <> (CommitComment.tupled, CommitComment.unapply)
def byPrimaryKey(commentId: Int) = this.commentId === commentId.bind
}
@@ -74,5 +74,5 @@ case class CommitComment(
newLine: Option[Int],
registeredDate: java.util.Date,
updatedDate: java.util.Date,
pullRequest: Boolean
issueId: Option[Int]
) extends Comment

View File

@@ -48,6 +48,7 @@ trait CoreProfile extends ProfileProvider with Profile
with RepositoryComponent
with SshKeyComponent
with WebHookComponent
with WebHookEventComponent
with PluginComponent
object Profile extends CoreProfile

View File

@@ -7,7 +7,7 @@ trait WebHookComponent extends TemplateComponent { self: Profile =>
class WebHooks(tag: Tag) extends Table[WebHook](tag, "WEB_HOOK") with BasicTemplate {
val url = column[String]("URL")
def * = (userName, repositoryName, url) <> (WebHook.tupled, WebHook.unapply)
def * = (userName, repositoryName, url) <> ((WebHook.apply _).tupled, WebHook.unapply)
def byPrimaryKey(owner: String, repository: String, url: String) = byRepository(owner, repository) && (this.url === url.bind)
}
@@ -18,3 +18,32 @@ case class WebHook(
repositoryName: String,
url: String
)
object WebHook {
sealed class Event(var name: String)
case object CommitComment extends Event("commit_comment")
case object Create extends Event("create")
case object Delete extends Event("delete")
case object Deployment extends Event("deployment")
case object DeploymentStatus extends Event("deployment_status")
case object Fork extends Event("fork")
case object Gollum extends Event("gollum")
case object IssueComment extends Event("issue_comment")
case object Issues extends Event("issues")
case object Member extends Event("member")
case object PageBuild extends Event("page_build")
case object Public extends Event("public")
case object PullRequest extends Event("pull_request")
case object PullRequestReviewComment extends Event("pull_request_review_comment")
case object Push extends Event("push")
case object Release extends Event("release")
case object Status extends Event("status")
case object TeamAdd extends Event("team_add")
case object Watch extends Event("watch")
object Event{
val values = List(CommitComment,Create,Delete,Deployment,DeploymentStatus,Fork,Gollum,IssueComment,Issues,Member,PageBuild,Public,PullRequest,PullRequestReviewComment,Push,Release,Status,TeamAdd,Watch)
private val map:Map[String,Event] = values.map(e => e.name -> e).toMap
def valueOf(name: String): Event = map(name)
def valueOpt(name: String): Option[Event] = map.get(name)
}
}

View File

@@ -0,0 +1,30 @@
package gitbucket.core.model
trait WebHookEventComponent extends TemplateComponent { self: Profile =>
import profile.simple._
import gitbucket.core.model.Profile.WebHooks
lazy val WebHookEvents = TableQuery[WebHookEvents]
implicit val typedType = MappedColumnType.base[WebHook.Event, String](_.name, WebHook.Event.valueOf(_))
class WebHookEvents(tag: Tag) extends Table[WebHookEvent](tag, "WEB_HOOK_EVENT") with BasicTemplate {
val url = column[String]("URL")
val event = column[WebHook.Event]("EVENT")
def * = (userName, repositoryName, url, event) <> ((WebHookEvent.apply _).tupled, WebHookEvent.unapply)
def byWebHook(owner: String, repository: String, url: String) = byRepository(owner, repository) && (this.url === url.bind)
def byWebHook(owner: Column[String], repository: Column[String], url: Column[String]) =
byRepository(userName, repositoryName) && (this.url === url)
def byWebHook(webhook: WebHooks) =
byRepository(webhook.userName, webhook.repositoryName) && (this.url === webhook.url)
def byPrimaryKey(owner: String, repository: String, url: String, event: WebHook.Event) = byWebHook(owner, repository, url) && (this.event === event.bind)
}
}
case class WebHookEvent(
userName: String,
repositoryName: String,
url: String,
event: WebHook.Event
)

View File

@@ -13,9 +13,9 @@ import StringUtil._
trait CommitsService {
def getCommitComments(owner: String, repository: String, commitId: String, pullRequest: Boolean)(implicit s: Session) =
def getCommitComments(owner: String, repository: String, commitId: String, includePullRequest: Boolean)(implicit s: Session) =
CommitComments filter {
t => t.byCommit(owner, repository, commitId) && (t.pullRequest === pullRequest || pullRequest)
t => t.byCommit(owner, repository, commitId) && (t.issueId.isEmpty || includePullRequest)
} list
def getCommitComment(owner: String, repository: String, commentId: String)(implicit s: Session) =
@@ -27,7 +27,8 @@ trait CommitsService {
None
def createCommitComment(owner: String, repository: String, commitId: String, loginUser: String,
content: String, fileName: Option[String], oldLine: Option[Int], newLine: Option[Int], pullRequest: Boolean)(implicit s: Session): Int =
content: String, fileName: Option[String], oldLine: Option[Int], newLine: Option[Int],
issueId: Option[Int])(implicit s: Session): Int =
CommitComments.autoInc insert CommitComment(
userName = owner,
repositoryName = repository,
@@ -39,7 +40,7 @@ trait CommitsService {
newLine = newLine,
registeredDate = currentDate,
updatedDate = currentDate,
pullRequest = pullRequest)
issueId = issueId)
def updateCommitComment(commentId: Int, content: String)(implicit s: Session) =
CommitComments

View File

@@ -47,6 +47,7 @@ trait RepositoryService { self: AccountService =>
Repositories insert repository.copy(userName = newUserName, repositoryName = newRepositoryName)
val webHooks = WebHooks .filter(_.byRepository(oldUserName, oldRepositoryName)).list
val webHookEvents = WebHookEvents .filter(_.byRepository(oldUserName, oldRepositoryName)).list
val milestones = Milestones .filter(_.byRepository(oldUserName, oldRepositoryName)).list
val issueId = IssueId .filter(_.byRepository(oldUserName, oldRepositoryName)).list
val issues = Issues .filter(_.byRepository(oldUserName, oldRepositoryName)).list
@@ -75,9 +76,10 @@ trait RepositoryService { self: AccountService =>
deleteRepository(oldUserName, oldRepositoryName)
WebHooks .insertAll(webHooks .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*)
Milestones.insertAll(milestones .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*)
IssueId .insertAll(issueId .map(_.copy(_1 = newUserName, _2 = newRepositoryName)) :_*)
WebHooks .insertAll(webHooks .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*)
WebHookEvents.insertAll(webHookEvents .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*)
Milestones .insertAll(milestones .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*)
IssueId .insertAll(issueId .map(_.copy(_1 = newUserName, _2 = newRepositoryName)) :_*)
val newMilestones = Milestones.filter(_.byRepository(newUserName, newRepositoryName)).list
Issues.insertAll(issues.map { x => x.copy(
@@ -146,6 +148,7 @@ trait RepositoryService { self: AccountService =>
IssueId .filter(_.byRepository(userName, repositoryName)).delete
Milestones .filter(_.byRepository(userName, repositoryName)).delete
WebHooks .filter(_.byRepository(userName, repositoryName)).delete
WebHookEvents .filter(_.byRepository(userName, repositoryName)).delete
Repositories .filter(_.byRepository(userName, repositoryName)).delete
// Update ORIGIN_USER_NAME and ORIGIN_REPOSITORY_NAME

View File

@@ -1,7 +1,7 @@
package gitbucket.core.service
import gitbucket.core.api._
import gitbucket.core.model.{WebHook, Account, Issue, PullRequest, IssueComment}
import gitbucket.core.model.{WebHook, Account, Issue, PullRequest, IssueComment, WebHookEvent, CommitComment}
import gitbucket.core.model.Profile._
import profile.simple._
import gitbucket.core.util.JGitUtil.CommitInfo
@@ -14,6 +14,9 @@ import org.apache.http.message.BasicNameValuePair
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.ObjectId
import org.slf4j.LoggerFactory
import scala.concurrent._
import org.apache.http.HttpRequest
import org.apache.http.HttpResponse
trait WebHookService {
@@ -21,46 +24,91 @@ trait WebHookService {
private val logger = LoggerFactory.getLogger(classOf[WebHookService])
def getWebHookURLs(owner: String, repository: String)(implicit s: Session): List[WebHook] =
WebHooks.filter(_.byRepository(owner, repository)).sortBy(_.url).list
/** get All WebHook informations of repository */
def getWebHooks(owner: String, repository: String)(implicit s: Session): List[(WebHook, Set[WebHook.Event])] =
WebHooks.filter(_.byRepository(owner, repository))
.innerJoin(WebHookEvents).on { (w, t) => t.byWebHook(w) }
.map{ case (w,t) => w -> t.event }
.list.groupBy(_._1).mapValues(_.map(_._2).toSet).toList.sortBy(_._1.url)
def addWebHookURL(owner: String, repository: String, url :String)(implicit s: Session): Unit =
/** get All WebHook informations of repository event */
def getWebHooksByEvent(owner: String, repository: String, event: WebHook.Event)(implicit s: Session): List[WebHook] =
WebHookEvents.filter(t => t.byRepository(owner, repository) && t.event === event.bind)
.list.map(t => WebHook(t.userName, t.repositoryName, t.url))
/** get All WebHook information from repository to url */
def getWebHook(owner: String, repository: String, url: String)(implicit s: Session): Option[(WebHook, Set[WebHook.Event])] =
WebHooks
.filter(_.byPrimaryKey(owner, repository, url))
.innerJoin(WebHookEvents).on { (w, t) => t.byWebHook(w) }
.map{ case (w,t) => w -> t.event }
.list.groupBy(_._1).mapValues(_.map(_._2).toSet).headOption
def addWebHook(owner: String, repository: String, url :String, events: Set[WebHook.Event])(implicit s: Session): Unit = {
WebHooks insert WebHook(owner, repository, url)
def deleteWebHookURL(owner: String, repository: String, url :String)(implicit s: Session): Unit =
WebHooks.filter(_.byPrimaryKey(owner, repository, url)).delete
def callWebHookOf(owner: String, repository: String, eventName: String)(makePayload: => Option[WebHookPayload])(implicit s: Session, c: JsonFormat.Context): Unit = {
val webHookURLs = getWebHookURLs(owner, repository)
if(webHookURLs.nonEmpty){
makePayload.map(callWebHook(eventName, webHookURLs, _))
events.toSet.map{ event: WebHook.Event =>
WebHookEvents insert WebHookEvent(owner, repository, url, event)
}
}
def callWebHook(eventName: String, webHookURLs: List[WebHook], payload: WebHookPayload)(implicit c: JsonFormat.Context): Unit = {
import org.apache.http.client.methods.HttpPost
def updateWebHook(owner: String, repository: String, url :String, events: Set[WebHook.Event])(implicit s: Session): Unit = {
WebHookEvents.filter(_.byWebHook(owner, repository, url)).delete
events.toSet.map{ event: WebHook.Event =>
WebHookEvents insert WebHookEvent(owner, repository, url, event)
}
}
def deleteWebHook(owner: String, repository: String, url :String)(implicit s: Session): Unit =
WebHooks.filter(_.byPrimaryKey(owner, repository, url)).delete
def callWebHookOf(owner: String, repository: String, event: WebHook.Event)(makePayload: => Option[WebHookPayload])(implicit s: Session, c: JsonFormat.Context): Unit = {
val webHooks = getWebHooksByEvent(owner, repository, event)
if(webHooks.nonEmpty){
makePayload.map(callWebHook(event, webHooks, _))
}
}
def callWebHook(event: WebHook.Event, webHookURLs: List[WebHook], payload: WebHookPayload)(implicit c: JsonFormat.Context): List[(WebHook, String, Future[HttpRequest], Future[HttpResponse])] = {
import org.apache.http.impl.client.HttpClientBuilder
import scala.concurrent._
import ExecutionContext.Implicits.global
import org.apache.http.protocol.HttpContext
import org.apache.http.client.methods.HttpPost
if(webHookURLs.nonEmpty){
val json = JsonFormat(payload)
val httpClient = HttpClientBuilder.create.build
webHookURLs.foreach { webHookUrl =>
webHookURLs.map { webHookUrl =>
val reqPromise = Promise[HttpRequest]
val f = Future {
logger.debug(s"start web hook invocation for ${webHookUrl}")
val httpPost = new HttpPost(webHookUrl.url)
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded")
httpPost.addHeader("X-Github-Event", eventName)
val itcp = new org.apache.http.HttpRequestInterceptor{
def process(res: HttpRequest, ctx: HttpContext): Unit = {
reqPromise.success(res)
}
}
try{
val httpClient = HttpClientBuilder.create.addInterceptorLast(itcp).build
logger.debug(s"start web hook invocation for ${webHookUrl.url}")
val httpPost = new HttpPost(webHookUrl.url)
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded")
httpPost.addHeader("X-Github-Event", event.name)
httpPost.addHeader("X-Github-Delivery", java.util.UUID.randomUUID().toString)
val params: java.util.List[NameValuePair] = new java.util.ArrayList()
params.add(new BasicNameValuePair("payload", json))
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"))
val params: java.util.List[NameValuePair] = new java.util.ArrayList()
params.add(new BasicNameValuePair("payload", json))
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"))
httpClient.execute(httpPost)
httpPost.releaseConnection()
logger.debug(s"end web hook invocation for ${webHookUrl}")
val res = httpClient.execute(httpPost)
httpPost.releaseConnection()
logger.debug(s"end web hook invocation for ${webHookUrl}")
res
}catch{
case e:Throwable => {
if(!reqPromise.isCompleted){
reqPromise.failure(e)
}
throw e
}
}
}
f.onSuccess {
case s => logger.debug(s"Success: web hook request to ${webHookUrl.url}")
@@ -68,9 +116,12 @@ trait WebHookService {
f.onFailure {
case t => logger.error(s"Failed: web hook request to ${webHookUrl.url}", t)
}
(webHookUrl, json, reqPromise.future, f)
}
} else {
Nil
}
logger.debug("end callWebHook")
// logger.debug("end callWebHook")
}
}
@@ -81,7 +132,7 @@ trait WebHookPullRequestService extends WebHookService {
import WebHookService._
// https://developer.github.com/v3/activity/events/types/#issuesevent
def callIssuesWebHook(action: String, repository: RepositoryService.RepositoryInfo, issue: Issue, baseUrl: String, sender: Account)(implicit s: Session, context:JsonFormat.Context): Unit = {
callWebHookOf(repository.owner, repository.name, "issues"){
callWebHookOf(repository.owner, repository.name, WebHook.Issues){
val users = getAccountsByUserNames(Set(repository.owner, issue.openedUserName), Set(sender))
for{
repoOwner <- users.get(repository.owner)
@@ -99,7 +150,7 @@ trait WebHookPullRequestService extends WebHookService {
def callPullRequestWebHook(action: String, repository: RepositoryService.RepositoryInfo, issueId: Int, baseUrl: String, sender: Account)(implicit s: Session, context:JsonFormat.Context): Unit = {
import WebHookService._
callWebHookOf(repository.owner, repository.name, "pull_request"){
callWebHookOf(repository.owner, repository.name, WebHook.PullRequest){
for{
(issue, pullRequest) <- getPullRequest(repository.owner, repository.name, issueId)
users = getAccountsByUserNames(Set(repository.owner, pullRequest.requestUserName, issue.openedUserName), Set(sender))
@@ -135,6 +186,7 @@ trait WebHookPullRequestService extends WebHookService {
ru <- Accounts if ru.userName === pr.requestUserName
iu <- Accounts if iu.userName === is.openedUserName
wh <- WebHooks if wh.byRepository(is.userName , is.repositoryName)
wht <- WebHookEvents if wht.event === WebHook.PullRequest.asInstanceOf[WebHook.Event].bind && wht.byWebHook(wh)
} yield {
((is, iu, pr, bu, ru), wh)
}).list.groupBy(_._1).mapValues(_.map(_._2))
@@ -155,7 +207,36 @@ trait WebHookPullRequestService extends WebHookService {
baseRepository = baseRepo,
baseOwner = baseOwner,
sender = sender)
callWebHook("pull_request", webHooks, payload)
callWebHook(WebHook.PullRequest, webHooks, payload)
}
}
}
trait WebHookPullRequestReviewCommentService extends WebHookService {
self: AccountService with RepositoryService with PullRequestService with IssuesService with CommitsService =>
def callPullRequestReviewCommentWebHook(action: String, comment: CommitComment, repository: RepositoryService.RepositoryInfo, issueId: Int, baseUrl: String, sender: Account)(implicit s: Session, context:JsonFormat.Context): Unit = {
import WebHookService._
callWebHookOf(repository.owner, repository.name, WebHook.PullRequestReviewComment){
for{
(issue, pullRequest) <- getPullRequest(repository.owner, repository.name, issueId)
users = getAccountsByUserNames(Set(repository.owner, pullRequest.requestUserName, issue.openedUserName), Set(sender))
baseOwner <- users.get(repository.owner)
headOwner <- users.get(pullRequest.requestUserName)
issueUser <- users.get(issue.openedUserName)
headRepo <- getRepository(pullRequest.requestUserName, pullRequest.requestRepositoryName, baseUrl)
} yield {
WebHookPullRequestReviewCommentPayload(
action = action,
comment = comment,
issue = issue,
issueUser = issueUser,
pullRequest = pullRequest,
headRepository = headRepo,
headOwner = headOwner,
baseRepository = repository,
baseOwner = baseOwner,
sender = sender)
}
}
}
}
@@ -165,7 +246,7 @@ trait WebHookIssueCommentService extends WebHookPullRequestService {
import WebHookService._
def callIssueCommentWebHook(repository: RepositoryService.RepositoryInfo, issue: Issue, issueCommentId: Int, sender: Account)(implicit s: Session, context:JsonFormat.Context): Unit = {
callWebHookOf(repository.owner, repository.name, "issue_comment"){
callWebHookOf(repository.owner, repository.name, WebHook.IssueComment){
for{
issueComment <- getComment(repository.owner, repository.name, issueCommentId.toString())
users = getAccountsByUserNames(Set(issue.openedUserName, repository.owner, issueComment.commentedUserName), Set(sender))
@@ -289,4 +370,38 @@ object WebHookService {
comment = ApiComment(comment, RepositoryName(repository), issue.issueId, ApiUser(commentUser), issue.isPullRequest),
sender = ApiUser(sender))
}
// https://developer.github.com/v3/activity/events/types/#pullrequestreviewcommentevent
case class WebHookPullRequestReviewCommentPayload(
action: String,
comment: ApiPullRequestReviewComment,
pull_request: ApiPullRequest,
repository: ApiRepository,
sender: ApiUser
) extends WebHookPayload
object WebHookPullRequestReviewCommentPayload{
def apply(
action: String,
comment: CommitComment,
issue: Issue,
issueUser: Account,
pullRequest: PullRequest,
headRepository: RepositoryInfo,
headOwner: Account,
baseRepository: RepositoryInfo,
baseOwner: Account,
sender: Account
) : WebHookPullRequestReviewCommentPayload = {
val headRepoPayload = ApiRepository(headRepository, headOwner)
val baseRepoPayload = ApiRepository(baseRepository, baseOwner)
val senderPayload = ApiUser(sender)
WebHookPullRequestReviewCommentPayload(
action = action,
comment = ApiPullRequestReviewComment(comment, senderPayload, RepositoryName(baseRepository), issue.issueId),
pull_request = ApiPullRequest(issue, pullRequest, headRepoPayload, baseRepoPayload, ApiUser(issueUser)),
repository = baseRepoPayload,
sender = senderPayload)
}
}
}

View File

@@ -21,6 +21,7 @@ object AutoUpdate {
* The history of versions. A head of this sequence is the current BitBucket version.
*/
val versions = Seq(
new Version(3, 9),
new Version(3, 8),
new Version(3, 7) with SystemSettingsService {
override def update(conn: Connection, cl: ClassLoader): Unit = {

View File

@@ -3,7 +3,7 @@ package gitbucket.core.servlet
import java.io.File
import gitbucket.core.api
import gitbucket.core.model.Session
import gitbucket.core.model.{Session, WebHook}
import gitbucket.core.plugin.{GitRepositoryRouting, PluginRegistry}
import gitbucket.core.service.IssuesService.IssueSearchCondition
import gitbucket.core.service.WebHookService._
@@ -200,7 +200,7 @@ class CommitLogHook(owner: String, repository: String, pusher: String, baseUrl:
}
// call web hook
callWebHookOf(owner, repository, "push"){
callWebHookOf(owner, repository, WebHook.Push){
for(pusherAccount <- getAccountByUserName(pusher);
ownerAccount <- getAccountByUserName(owner)) yield {
WebHookPushPayload(git, pusherAccount, command.getRefName, repositoryInfo, newCommits, ownerAccount,

View File

@@ -43,6 +43,7 @@ object Markdown {
val options = new Options()
options.setSanitize(true)
options.setBreaks(true)
val renderer = new GitBucketMarkedRenderer(options, repository, enableWikiLink, enableRefsLink, enableAnchor, enableTaskList, hasWritePermission, pages)
Marked.marked(source, options, renderer)
}

View File

@@ -12,7 +12,7 @@
<div class="span9">
<div class="box">
<div class="box-header">Personal access tokens</div>
<div class="box-content">
<div class="box-content-bottom">
@if(personalTokens.isEmpty && gneratedToken.isEmpty){
No tokens.
}else{
@@ -40,7 +40,7 @@
<form method="POST" action="@path/@account.userName/_personalToken" validate="true">
<div class="box">
<div class="box-header">Generate new token</div>
<div class="box-content">
<div class="box-content-bottom">
<fieldset>
<label for="note" class="strong">Token description</label>
<div><span id="error-note" class="error"></span></div>

View File

@@ -14,7 +14,7 @@
<form action="@url(account.userName)/_edit" method="POST" validate="true">
<div class="box">
<div class="box-header">Profile</div>
<div class="box-content">
<div class="box-content-bottom">
<div class="row-fluid">
<div class="span6">
@if(account.password.nonEmpty){

View File

@@ -11,7 +11,7 @@
<div class="span9">
<div class="box">
<div class="box-header">SSH Keys</div>
<div class="box-content">
<div class="box-content-bottom">
@if(sshKeys.isEmpty){
No keys
}
@@ -27,7 +27,7 @@
<form method="POST" action="@path/@account.userName/_ssh" validate="true">
<div class="box">
<div class="box-header">Add an SSH Key</div>
<div class="box-content">
<div class="box-content-bottom">
<fieldset>
<label for="title" class="strong">Title</label>
<div><span id="error-title" class="error"></span></div>

View File

@@ -15,7 +15,7 @@
@plugins.map {plugin =>
<div class="box">
<div class="box-header">@plugin.pluginName</div>
<div class="box-content">
<div class="box-content-bottom">
<p><span class="strong">Id:&nbsp;</span>@plugin.pluginId</p>
<p><span class="strong">Version:&nbsp;</span>@plugin.version</p>
<p><span class="strong">Name:&nbsp;</span>@plugin.pluginName</p>

View File

@@ -8,7 +8,7 @@
<form action="@path/admin/system" method="POST" validate="true">
<div class="box">
<div class="box-header">System Settings</div>
<div class="box-content">
<div class="box-content-bottom">
<!--====================================================================-->
<!-- GITBUCKET_HOME -->
<!--====================================================================-->
@@ -289,7 +289,7 @@
</div>
</div>
<p class="muted">
Enable notification not only SMTP configuration if you want to send nitification email.
Enable notification not only SMTP configuration if you want to send notification email.
</p>
</div>
</div>

View File

@@ -1,6 +1,6 @@
@(id: String, width: Int)(implicit context: gitbucket.core.controller.Context)
@import context._
<input type="text" name="@id" id="@id" style="width: @{width}px; margin-bottom: 0px;"/>
<input type="text" name="@id" id="@id" autocomplete="off" style="width: @{width}px; margin-bottom: 0px;"/>
<script>
$(function(){
$('#@id').typeahead({

View File

@@ -6,6 +6,7 @@
@import gitbucket.core._
@import gitbucket.core.view.helpers._
<div class="@if(comment.fileName.isDefined && (!latestCommitId.isDefined || latestCommitId.get == comment.commitId)){inline-comment}"
id="discussion_r@comment.commentId"
@if(comment.fileName.isDefined){filename="@comment.fileName.get"}
@if(comment.newLine.isDefined){newline="@comment.newLine.get"}
@if(comment.oldLine.isDefined){oldline="@comment.oldLine.get"}>
@@ -15,9 +16,9 @@
@user(comment.commentedUserName, styleClass="username strong")
<span class="muted">
commented
@if(comment.pullRequest){
@if(comment.issueId.isDefined){
on this Pull Request
}else{
} else {
@if(comment.fileName.isDefined){
on @comment.fileName.get
}
@@ -32,7 +33,7 @@
}
</span>
</div>
<div class="box-content-bottom commit-commentContent-@comment.commentId markdown-body">
<div class="box-content-bottom issue-content commit-commentContent-@comment.commentId markdown-body">
@markdown(comment.content, repository, false, true, true, hasWritePermission)
</div>
</div>

View File

@@ -220,7 +220,6 @@ $(function(){
dataType : 'html'
},
function(responseContent) {
$this.hide();
var tmp;
if (!isNaN(oldLineNumber) && oldLineNumber) {
if (!isNaN(newLineNumber) && newLineNumber) {

View File

@@ -36,7 +36,7 @@
</div>
} else {
<div class="box-content-bottom" style="padding: 0px;">
@defining(3){ max =>
@defining(20){ max =>
@userRepositories.zipWithIndex.map { case (repository, i) =>
<div class="box-content-row repo-link" style="@if(i > max - 1){display:none;}">
@helper.html.repositoryicon(repository, false)

View File

@@ -46,11 +46,11 @@
}
</span>
</div>
<div class="box-content-bottom issue-content" id="commentContent-@comment.commentId">
<div class="box-content-bottom issue-content markdown-body" id="commentContent-@comment.commentId">
@if(comment.action == "commit" && comment.content.split(" ").last.matches("[a-f0-9]{40}")){
@defining(comment.content.substring(comment.content.length - 40)){ id =>
<div class="pull-right"><a href="@path/@repository.owner/@repository.name/commit/@id" class="monospace">@id.substring(0, 7)</a></div>
<div class="markdown-body">@markdown(comment.content.substring(0, comment.content.length - 41), repository, false, true, true, hasWritePermission)</div>
@markdown(comment.content.substring(0, comment.content.length - 41), repository, false, true, true, hasWritePermission)
}
} else {
@if(comment.action == "refer"){
@@ -58,7 +58,7 @@
<strong>@issueLink(repository, issueId.toInt): @rest.mkString(":")</strong>
}
} else {
<div class="markdown-body">@markdown(comment.content, repository, false, true, true, hasWritePermission)</div>
@markdown(comment.content, repository, false, true, true, hasWritePermission)
}
}
</div>

View File

@@ -69,7 +69,7 @@
@if(content.viewType == "text"){
@defining(isRenderable(pathList.reverse.head)){ isRrenderable =>
@if(!isBlame && isRrenderable) {
<div class="box-content-bottom markdown-body" style="padding-left: 16px; padding-right: 16px;">
<div class="box-content-bottom markdown-body" style="padding-left: 20px; padding-right: 20px;">
@renderMarkup(pathList, content.content.get, branch, repository, false, false, true)
</div>
} else {

View File

@@ -130,7 +130,7 @@ $(function(){
enableTaskList : false
}, function(data){
$('#preview').empty().append(
$('<div class="markdown-body" style="padding-left: 16px; padding-right: 16px;">').html(data));
$('<div class="markdown-body" style="padding-left: 20px; padding-right: 20px;">').html(data));
prettyPrint();
});
} else {

View File

@@ -127,7 +127,7 @@
@readme.map { case(filePath, content) =>
<div id="readme">
<div class="box-header">@filePath.reverse.head</div>
<div class="box-content-bottom markdown-body" style="padding-left: 16px; padding-right: 16px;">@renderMarkup(filePath, content, branch, repository, false, false, true)</div>
<div class="box-content-bottom markdown-body" style="padding-left: 20px; padding-right: 20px;">@renderMarkup(filePath, content, branch, repository, false, false, true)</div>
</div>
}
}

View File

@@ -6,7 +6,7 @@
@menu("danger", repository){
<div class="box">
<div class="box-header">Danger Zone</div>
<div class="box-content">
<div class="box-content-bottom">
<form id="transfer-form" method="post" action="@url(repository)/settings/transfer" validate="true" autocomplete="off">
<fieldset>
<label class="strong">Transfer Ownership</label>

View File

@@ -0,0 +1,164 @@
@(webHook: gitbucket.core.model.WebHook,
events: Set[gitbucket.core.model.WebHook.Event],
repository: gitbucket.core.service.RepositoryService.RepositoryInfo,
info: Option[Any],
create: Boolean)(implicit context: gitbucket.core.controller.Context)
@import context._
@import gitbucket.core.view.helpers._
@import gitbucket.core.model.WebHook._
@check(name: String, event: Event)={
name="@(name).@event.name" value="on" @if(events(event)){checked}
}
@html.main("Settings", Some(repository)){
@html.menu("settings", repository){
@menu("hooks", repository){
@helper.html.information(info)
<div class="box">
<div class="box-header">
Webhook / Manage webhook
</div>
<div class="box-content-bottom">
<form method="POST" validate="true">
<div>
<span class="error" id="error-url"></span>
</div>
<label class="strong">Payload URL</label>
@if(create){
<input type="text" name="url" id="url" value="@webHook.url" class="input-xxlarge" style="margin-bottom: 0px;" required />
} else {
<input type="text" value="@webHook.url" style="margin-bottom: 0px;" class="input-xxlarge" disabled />
<input type="hidden" value="@webHook.url" name="url" />
}
<button class="btn" id="test">Test Hook</button>
<hr />
<div>
<span class="error" id="error-events"></span>
</div>
<label class="strong">Which events would you like to trigger this webhook?</label>
<!--
<label class="checkbox"><input type="checkbox" @check("events",CommitComment) />Commit comment <small class="help-block">Commit or diff commented on. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",Create) />Create <small class="help-block">Branch, or tag created. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",Delete) />Delete <small class="help-block">Branch, or tag deleted. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",Deployment) />Deployment <small class="help-block">Repository deployed. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",DeploymentStatus) />Deployment status <small class="help-block">Deployment status updated from the API. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",Fork) />Fork <small class="help-block">Repository forked. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",Gollum) />Gollum <small class="help-block">Wiki page updated. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",Member) />Member <small class="help-block">Collaborator added to a non-organization repository. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",PageBuild) />Page build <small class="help-block">Pages site built. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",Public) />Public <small class="help-block">Repository changes from private to public. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",Release) />Release <small class="help-block">Release published in a repository. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",TeamAdd) />Team add <small class="help-block">Team added or modified on a repository. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",Watch) />Watch <small class="help-block">User stars a repository.</small></label>
<label class="checkbox"><input type="checkbox" @check("events",Status) />Status <small class="help-block">Commit status updated from the API. </small> </label>
-->
<label class="checkbox"><input type="checkbox" @check("events",IssueComment) />Issue comment <small class="help-block">Issue commented on. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",Issues) />Issues <small class="help-block">Issue opened, closed<!-- , assigned, or labeled -->. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",PullRequest) />Pull Request <small class="help-block">Pull Request opened, closed<!-- , assigned, labeled -->, or synchronized. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",PullRequestReviewComment) />Pull Request review comment <small class="help-block">Pull Request diff commented on. </small> </label>
<label class="checkbox"><input type="checkbox" @check("events",Push) />Push <small class="help-block">Git push to a repository. </small> </label>
<hr />
@if(!create){
<input type="submit" class="btn btn-success" value="Update webhook" formaction="@url(repository)/settings/hooks/edit/@urlEncode(webHook.url)" />
<a href="@url(repository)/settings/hooks/delete?url=@urlEncode(webHook.url)" class="btn text-error" onclick="return confirm('delete webhook for @webHook.url ?')">
Delete webhook
</a>
} else {
<input type="submit" class="btn" value="Add webhook" formaction="@url(repository)/settings/hooks/new" />
}
</form>
</div>
</div>
<div class="modal hide" id="test-report-modal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h3>WebHook Test</h3>
</div>
<div class="modal-body">
<p>request to <span id="test-modal-url" style="word-break: break-all; word-wrap: break-word; white-space: pre; white-space: pre-wrap;"></span></p>
<div id="test-report" style="display:none">
<ul class="nav nav-tabs" id="test-report-tab">
<li class="active"><a href="#REQUEST">REQUEST</a></li>
<li><a href="#RESPONCE">RESPONCE <span class="badge badge-success" id="res-status"></span></a></li>
</ul>
<div class="tab-content" style="max-height: 300px;">
<div class="tab-pane active" id="REQUEST">
<div id="req-errors" class="alert alert-error">
ERROR<span id="req-errors-body"></span>
</div>
<div id="req-success" style="display:none">
Headers
<pre id="req-headers"></pre>
Payload
<pre id="req-payload"></pre>
</div>
</div>
<div class="tab-pane" id="RESPONCE">
<div id="res-errors" class="alert alert-error">
ERROR<span id="res-errors-body"></span>
</div>
<div id="res-success" style="display:none">
Headers
<pre id="res-headers"></pre>
Body
<pre id="res-body"></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(function(){
$('#test-report-tab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
$('#test').click(function(e){
e.stopPropagation();
e.stopImmediatePropagation();
e.preventDefault();
var url = this.form.url.value;
if(!/^https?:\/\/.+/.test(url)){
alert("invalid url");
return;
}
$("#test-modal-url").text(url)
$("#test-report-modal").modal('show')
$("#test-report").hide();
$.ajax({
method:'POST',
url:'@url(repository)/settings/hooks/test?url=' + encodeURIComponent(url),
success: function(e){
//console.log(e);
$('#test-report-tab a:first').tab('show');
$("#test-report").show();
$("#req-success").toggle(e.request&&!e.request.error);
$("#req-errors").toggle(e.request&&!!e.request.error);
$("#req-errors-body").text(e.request.error);
function headers(h){
h = h["headers"];
return h ? $.map(h, function(h){
return $("<div>").append($('<b>').text(h[0] + ":"),$('<span>').text(" " + h[1]))
}):"";
}
$("#req-headers").html(headers(e.request));
$("#req-payload").text(e.request && e.request.payload ? JSON.stringify(JSON.parse(e.request.payload),undefined,4) : "");
$("#res-success").toggle(e.responce && !e.responce.error);
$("#res-errors").toggle(e.responce && !!e.responce.error);
$("#res-errors-body").text(e.responce.error);
var success = !!(e.responce && e.responce.status && /^2\d\d$/.test(e.responce.status.statusCode));
$("#res-status").text((e.responce && e.responce.status && e.responce.status.statusCode) || "ERROR");
$("#res-status").toggleClass("badge-success", success).toggleClass("badge-important", !success);
$("#res-headers").html(headers(e.responce));
$("#res-body").text(e.responce && e.responce.body ? e.responce.body : "");
},
});
return false;
});
})
</script>
}
}
}

View File

@@ -1,5 +1,4 @@
@(webHooks: List[gitbucket.core.model.WebHook],
enteredUrl: Option[Any],
@(webHooks: List[(gitbucket.core.model.WebHook, Set[gitbucket.core.model.WebHook.Event])],
repository: gitbucket.core.service.RepositoryService.RepositoryInfo,
info: Option[Any])(implicit context: gitbucket.core.controller.Context)
@import context._
@@ -8,20 +7,42 @@
@html.menu("settings", repository){
@menu("hooks", repository){
@helper.html.information(info)
<h3>WebHook URLs</h3>
<ul>
@webHooks.map { webHook =>
<li>@webHook.url <a href="@url(repository)/settings/hooks/delete?url=@urlEncode(webHook.url)" class="remove">(remove)</a></li>
}
</ul>
<form method="POST" validate="true">
<div>
<span class="error" id="error-url"></span>
</div>
<input type="text" name="url" id="url" value="@enteredUrl" style="width: 300px; margin-bottom: 0px;"/>
<input type="submit" class="btn" formaction="@url(repository)/settings/hooks/add" value="Add"/>
<input type="submit" class="btn" formaction="@url(repository)/settings/hooks/test" value="Test Hook"/>
</form>
<div class="box">
<div class="box-header">
<a href="@url(repository)/settings/hooks/new" class="btn btn-mini pull-right">Add webhook</a>
Webhooks
</div>
<div class="box-content-bottom">
<p>
Webhooks allow external services to be notified when certain events happen within your repository.
When the specified events happen, well send a POST request to each of the URLs you provide.
Learn more in <a href="https://github.com/takezoe/gitbucket/wiki/API-WebHook" target="_blank">GitBucket Wiki Webhook Page</a>.
</p>
<table class="table table-condensed" style="margin-bottom:0">
@webHooks.map { case (webHook, events) =>
<tr><td style="vertical-align: middle;">
<a href="@url(repository)/settings/hooks/edit/@urlEncode(webHook.url)" class="css-truncate" style="max-width:360px">
<span class="css-truncate-target">@webHook.url</span>
</a>
<em class="css-truncate" style="max-width: 225px;">(<span class="css-truncate-target">@events.map(_.name).mkString(", ")</span>)</em>
</td><td>
<div class="btn-group pull-right">
<a href="@url(repository)/settings/hooks/edit/@urlEncode(webHook.url)" class="btn btn-small">
<span class="octicon octicon-pencil"></span>
</a>
<a href="@url(repository)/settings/hooks/delete?url=@urlEncode(webHook.url)" class="btn btn-small btn-danger" onclick="return confirm('delete webhook for @webHook.url ?')">
<span class="octicon octicon-x"></span>
</a>
</div>
</td></tr>
}
</table>
</div>
</div>
}
}
}

View File

@@ -8,7 +8,7 @@
<form id="form" method="post" action="@url(repository)/settings/options" validate="true">
<div class="box">
<div class="box-header">Settings</div>
<div class="box-content">
<div class="box-content-bottom">
<fieldset>
<label for="repositoryName" class="strong">Repository Name:</label>
<input type="text" name="repositoryName" id="repositoryName" value="@repository.name"/>

View File

@@ -64,6 +64,11 @@ h6 {
.align-right {
text-align: right;
}
blockquote p {
font-size: 15px;
}
/* ======================================================================== */
/* Global Header */
/* ======================================================================== */
@@ -251,6 +256,10 @@ div.box-header {
background: #f2f8fa;
}
.inline-comment div.box-content-bottom {
margin-bottom: 0px;
}
.commit-list {
position: relative;
}
@@ -1525,7 +1534,7 @@ div.markdown-body li {
div.markdown-body p {
margin: 15px 0;
line-height: 1.7;
line-height: 1.5;
}
div.markdown-body pre {
@@ -1681,15 +1690,13 @@ div.markdown-body table colgroup + tbody tr:first-child td:last-child {
}
.markdown-head {
left: -18px;
padding-left: 18px;
position: relative;
line-height: 1.7;
}
a.markdown-anchor-link {
position: absolute;
left: 0px;
left: -18px;
display: none;
color: #999;
/* From octicon style */

View File

@@ -7,7 +7,7 @@ import org.json4s.jackson.JsonMethods.{pretty, parse}
import org.json4s._
import org.specs2.matcher._
import java.util.{Calendar, TimeZone}
import java.util.{Calendar, TimeZone, Date}
@@ -17,6 +17,11 @@ class JsonFormatSpec extends Specification {
d.set(2011,3,14,16,0,49)
d.getTime
}
def date(date:String): Date = {
val f = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
f.setTimeZone(TimeZone.getTimeZone("UTC"))
f.parse(date)
}
val sha1 = "6dcb09b5b57875f334f61aebed695e2e4193db5e"
val repo1Name = RepositoryName("octocat/Hello-World")
implicit val context = JsonFormat.Context("http://gitbucket.exmple.com")
@@ -305,6 +310,51 @@ class JsonFormatSpec extends Specification {
// "deletions": 3,
// "changed_files": 5
}"""
// https://developer.github.com/v3/activity/events/types/#pullrequestreviewcommentevent
val apiPullRequestReviewComment = ApiPullRequestReviewComment(
id = 29724692,
// "diff_hunk": "@@ -1 +1 @@\n-# public-repo",
path = "README.md",
// "position": 1,
// "original_position": 1,
commit_id = "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c",
// "original_commit_id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c",
user = apiUser,
body = "Maybe you should use more emojji on this line.",
created_at = date("2015-05-05T23:40:27Z"),
updated_at = date("2015-05-05T23:40:27Z")
)(RepositoryName("baxterthehacker/public-repo"), 1)
val apiPullRequestReviewCommentJson = s"""{
"url": "http://gitbucket.exmple.com/api/v3/repos/baxterthehacker/public-repo/pulls/comments/29724692",
"id": 29724692,
// "diff_hunk": "@@ -1 +1 @@\\n-# public-repo",
"path": "README.md",
// "position": 1,
// "original_position": 1,
"commit_id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c",
// "original_commit_id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c",
"user": $apiUserJson,
"body": "Maybe you should use more emojji on this line.",
"created_at": "2015-05-05T23:40:27Z",
"updated_at": "2015-05-05T23:40:27Z",
"html_url": "http://gitbucket.exmple.com/baxterthehacker/public-repo/pull/1#discussion_r29724692",
"pull_request_url": "http://gitbucket.exmple.com/api/v3/repos/baxterthehacker/public-repo/pulls/1",
"_links": {
"self": {
"href": "http://gitbucket.exmple.com/api/v3/repos/baxterthehacker/public-repo/pulls/comments/29724692"
},
"html": {
"href": "http://gitbucket.exmple.com/baxterthehacker/public-repo/pull/1#discussion_r29724692"
},
"pull_request": {
"href": "http://gitbucket.exmple.com/api/v3/repos/baxterthehacker/public-repo/pulls/1"
}
}
}"""
def beFormatted(json2Arg:String) = new Matcher[String] {
def apply[S <: String](e: Expectable[S]) = {
import java.util.regex.Pattern
@@ -358,5 +408,8 @@ class JsonFormatSpec extends Specification {
"apiPullRequest" in {
JsonFormat(apiPullRequest) must beFormatted(apiPullRequestJson)
}
"apiPullRequestReviewComment" in {
JsonFormat(apiPullRequestReviewComment) must beFormatted(apiPullRequestReviewCommentJson)
}
}
}

View File

@@ -1,6 +1,7 @@
package gitbucket.core.service
import org.specs2.mutable.Specification
import gitbucket.core.model.WebHook
class WebHookServiceSpec extends Specification with ServiceSpecBase {
@@ -16,12 +17,12 @@ class WebHookServiceSpec extends Specification with ServiceSpecBase {
val (issue3, pullreq3) = generateNewPullRequest("user3/repo3/master3", "user2/repo2/master2", loginUser="root")
val (issue32, pullreq32) = generateNewPullRequest("user3/repo3/master32", "user2/repo2/master2", loginUser="root")
generateNewPullRequest("user2/repo2/master2", "user1/repo1/master2")
service.addWebHookURL("user1", "repo1", "webhook1-1")
service.addWebHookURL("user1", "repo1", "webhook1-2")
service.addWebHookURL("user2", "repo2", "webhook2-1")
service.addWebHookURL("user2", "repo2", "webhook2-2")
service.addWebHookURL("user3", "repo3", "webhook3-1")
service.addWebHookURL("user3", "repo3", "webhook3-2")
service.addWebHook("user1", "repo1", "webhook1-1", Set(WebHook.PullRequest))
service.addWebHook("user1", "repo1", "webhook1-2", Set(WebHook.PullRequest))
service.addWebHook("user2", "repo2", "webhook2-1", Set(WebHook.PullRequest))
service.addWebHook("user2", "repo2", "webhook2-2", Set(WebHook.PullRequest))
service.addWebHook("user3", "repo3", "webhook3-1", Set(WebHook.PullRequest))
service.addWebHook("user3", "repo3", "webhook3-2", Set(WebHook.PullRequest))
service.getPullRequestsByRequestForWebhook("user1","repo1","master1") must_== Map.empty
@@ -41,4 +42,35 @@ class WebHookServiceSpec extends Specification with ServiceSpecBase {
r2((issue32, issueUser, pullreq32, user3, user2)) must_== Set("webhook3-1","webhook3-2")
} }
}
"add and get and update and delete" in { withTestDB { implicit session =>
val user1 = generateNewUserWithDBRepository("user1","repo1")
service.addWebHook("user1", "repo1", "http://example.com", Set(WebHook.PullRequest))
service.getWebHooks("user1", "repo1") must_== List((WebHook("user1","repo1","http://example.com"),Set(WebHook.PullRequest)))
service.getWebHook("user1", "repo1", "http://example.com") must_== Some((WebHook("user1","repo1","http://example.com"),Set(WebHook.PullRequest)))
service.getWebHooksByEvent("user1", "repo1", WebHook.PullRequest) must_== List((WebHook("user1","repo1","http://example.com")))
service.getWebHooksByEvent("user1", "repo1", WebHook.Push) must_== Nil
service.getWebHook("user1", "repo1", "http://example.com2") must_== None
service.getWebHook("user2", "repo1", "http://example.com") must_== None
service.getWebHook("user1", "repo2", "http://example.com") must_== None
service.updateWebHook("user1", "repo1", "http://example.com", Set(WebHook.Push, WebHook.Issues))
service.getWebHook("user1", "repo1", "http://example.com") must_== Some((WebHook("user1","repo1","http://example.com"),Set(WebHook.Push, WebHook.Issues)))
service.getWebHooksByEvent("user1", "repo1", WebHook.PullRequest) must_== Nil
service.getWebHooksByEvent("user1", "repo1", WebHook.Push) must_== List((WebHook("user1","repo1","http://example.com")))
service.deleteWebHook("user1", "repo1", "http://example.com")
service.getWebHook("user1", "repo1", "http://example.com") must_== None
} }
"getWebHooks, getWebHooksByEvent" in { withTestDB { implicit session =>
val user1 = generateNewUserWithDBRepository("user1","repo1")
service.addWebHook("user1", "repo1", "http://example.com/1", Set(WebHook.PullRequest))
service.addWebHook("user1", "repo1", "http://example.com/2", Set(WebHook.Push))
service.addWebHook("user1", "repo1", "http://example.com/3", Set(WebHook.PullRequest,WebHook.Push))
service.getWebHooks("user1", "repo1") must_== List(
WebHook("user1","repo1","http://example.com/1")->Set(WebHook.PullRequest),
WebHook("user1","repo1","http://example.com/2")->Set(WebHook.Push),
WebHook("user1","repo1","http://example.com/3")->Set(WebHook.PullRequest,WebHook.Push))
service.getWebHooksByEvent("user1", "repo1", WebHook.PullRequest) must_== List(
WebHook("user1","repo1","http://example.com/1"),
WebHook("user1","repo1","http://example.com/3"))
} }
}