update scalafmt

This commit is contained in:
xuwei-k
2023-11-16 12:12:33 +09:00
committed by kenji yoshida
parent 8cd7068131
commit 3d5ca44d66
96 changed files with 3065 additions and 3130 deletions

View File

@@ -1,12 +1,14 @@
version = "1.5.1"
version = "3.7.15"
project.git = true
maxColumn = 120
docstrings = JavaDoc
docstrings.style = keep
align.tokens = ["%", "%%", {code = "=>", owner = "Case"}]
align.openParenCallSite = false
align.openParenDefnSite = false
continuationIndent.callSite = 2
continuationIndent.defnSite = 2
danglingParentheses = true
danglingParentheses.preset = true
runner.dialect = scala213source3
rewrite.trailingCommas.style = keep

View File

@@ -115,8 +115,8 @@ assembly / assemblyMergeStrategy := {
// Exclude a war file from published artifacts
signedArtifacts := {
signedArtifacts.value.filterNot {
case (_, file) => file.getName.endsWith(".war") || file.getName.endsWith(".war.asc")
signedArtifacts.value.filterNot { case (_, file) =>
file.getName.endsWith(".war") || file.getName.endsWith(".war.asc")
}
}
@@ -205,8 +205,7 @@ executableKey := {
"md5" -> "MD5",
"sha1" -> "SHA-1",
"sha256" -> "SHA-256"
).foreach {
case (extension, algorithm) =>
).foreach { case (extension, algorithm) =>
val checksumFile = workDir / (warName + "." + extension)
Checksums generate (outputFile, checksumFile, algorithm)
}
@@ -289,5 +288,5 @@ Jetty / javaOptions ++= Seq(
"-Xdebug",
"-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000",
"-Dorg.eclipse.jetty.annotations.AnnotationParser.LEVEL=OFF",
//"-Ddev-features=keep-session"
// "-Ddev-features=keep-session"
)

View File

@@ -76,8 +76,7 @@ object GitBucketCoreModule
import JDBCUtil._
val conn = context.get(Solidbase.CONNECTION).asInstanceOf[Connection]
val list = conn.select("SELECT * FROM ACTIVITY ORDER BY ACTIVITY_ID") {
rs =>
val list = conn.select("SELECT * FROM ACTIVITY ORDER BY ACTIVITY_ID") { rs =>
Activity(
activityId = UUID.randomUUID().toString,
userName = rs.getString("USER_NAME"),

View File

@@ -66,15 +66,16 @@ object ApiBranchProtection {
}
}
implicit val enforcementLevelSerializer: CustomSerializer[EnforcementLevel] = new CustomSerializer[EnforcementLevel](
format =>
implicit val enforcementLevelSerializer: CustomSerializer[EnforcementLevel] =
new CustomSerializer[EnforcementLevel](format =>
(
{
case JString("off") => Off
case JString("non_admins") => NonAdmins
case JString("everyone") => Everyone
}, {
case x: EnforcementLevel => JString(x.name)
},
{ case x: EnforcementLevel =>
JString(x.name)
}
)
)

View File

@@ -14,7 +14,8 @@ case class ApiComment(id: Int, user: ApiUser, body: String, created_at: Date, up
isPullRequest: Boolean
) {
val html_url = ApiPath(
s"/${repositoryName.fullName}/${if (isPullRequest) { "pull" } else { "issues" }}/${issueId}#comment-${id}"
s"/${repositoryName.fullName}/${if (isPullRequest) { "pull" }
else { "issues" }}/${issueId}#comment-${id}"
)
}

View File

@@ -69,7 +69,8 @@ object ApiCommits {
}
File(
filename = if (diff.changeType == ChangeType.DELETE) { diff.oldPath } else { diff.newPath },
filename = if (diff.changeType == ChangeType.DELETE) { diff.oldPath }
else { diff.newPath },
additions = additions,
deletions = deletions,
changes = additions + deletions,
@@ -106,7 +107,9 @@ object ApiCommits {
message = commitInfo.shortMessage,
comment_count = commentCount,
tree = Tree(
url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/tree/${commitInfo.id}"), // TODO This endpoint has not been implemented yet.
url = ApiPath(
s"/api/v3/repos/${repositoryName.fullName}/tree/${commitInfo.id}"
), // TODO This endpoint has not been implemented yet.
sha = commitInfo.id
)
),
@@ -114,7 +117,9 @@ object ApiCommits {
committer = ApiUser(committer),
parents = commitInfo.parents.map { parent =>
Tree(
url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/tree/${parent}"), // TODO This endpoint has not been implemented yet.
url = ApiPath(
s"/api/v3/repos/${repositoryName.fullName}/tree/${parent}"
), // TODO This endpoint has not been implemented yet.
sha = parent
)
},

View File

@@ -22,8 +22,7 @@ object ApiContents {
ApiContents("dir", fileInfo.name, fileInfo.path, fileInfo.commitId, None, None)(repositoryName)
} else {
content
.map(
arr =>
.map(arr =>
ApiContents(
"file",
fileInfo.name,

View File

@@ -23,7 +23,8 @@ case class ApiIssue(
val id = 0 // dummy id
val assignee = assignees.headOption
val comments_url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/issues/${number}/comments")
val html_url = ApiPath(s"/${repositoryName.fullName}/${if (isPullRequest) { "pull" } else { "issues" }}/${number}")
val html_url = ApiPath(s"/${repositoryName.fullName}/${if (isPullRequest) { "pull" }
else { "issues" }}/${number}")
val pull_request = if (isPullRequest) {
Some(
Map(
@@ -54,7 +55,8 @@ object ApiIssue {
assignees = assignees,
labels = labels,
milestone = milestone,
state = if (issue.closed) { "closed" } else { "open" },
state = if (issue.closed) { "closed" }
else { "open" },
body = issue.content.getOrElse(""),
created_at = issue.registeredDate,
updated_at = issue.updatedDate

View File

@@ -27,10 +27,10 @@ case class ApiPullRequest(
val id = 0 // dummy id
val assignee = assignees.headOption
val html_url = ApiPath(s"${base.repo.html_url.path}/pull/${number}")
//val diff_url = ApiPath(s"${base.repo.html_url.path}/pull/${number}.diff")
//val patch_url = ApiPath(s"${base.repo.html_url.path}/pull/${number}.patch")
// val diff_url = ApiPath(s"${base.repo.html_url.path}/pull/${number}.diff")
// val patch_url = ApiPath(s"${base.repo.html_url.path}/pull/${number}.patch")
val url = ApiPath(s"${base.repo.url.path}/pulls/${number}")
//val issue_url = ApiPath(s"${base.repo.url.path}/issues/${number}")
// val issue_url = ApiPath(s"${base.repo.url.path}/issues/${number}")
val commits_url = ApiPath(s"${base.repo.url.path}/pulls/${number}/commits")
val review_comments_url = ApiPath(s"${base.repo.url.path}/pulls/${number}/comments")
val review_comment_url = ApiPath(s"${base.repo.url.path}/pulls/comments/{number}")
@@ -69,7 +69,8 @@ object ApiPullRequest {
)
case class Commit(sha: String, ref: String, repo: ApiRepository)(baseOwner: String) {
val label = if (baseOwner == repo.owner.login) { ref } else { s"${repo.owner.login}:${ref}" }
val label = if (baseOwner == repo.owner.login) { ref }
else { s"${repo.owner.login}:${ref}" }
val user = repo.owner
}

View File

@@ -40,12 +40,12 @@ object ApiRef {
ApiRef(
ref = s"refs/tags/${tagInfo.name}",
url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/git/refs/tags/${tagInfo.name}"),
//the GH api distinguishes between "releases" and plain git tags
//for "releases", the api returns a reference to the release object (with type `tag`)
//this would be something like s"/api/v3/repos/${repositoryName.fullName}/git/tags/<hash-of-tag>"
//with a hash for the tag, which I do not fully understand
//since this is not yet implemented in GB, we always return a link to the plain `commit` object,
//which GH does for tags that are not annotated
// the GH api distinguishes between "releases" and plain git tags
// for "releases", the api returns a reference to the release object (with type `tag`)
// this would be something like s"/api/v3/repos/${repositoryName.fullName}/git/tags/<hash-of-tag>"
// with a hash for the tag, which I do not fully understand
// since this is not yet implemented in GB, we always return a link to the plain `commit` object,
// which GH does for tags that are not annotated
`object` = ApiRefCommit(
sha = tagInfo.objectId,
url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/commits/${tagInfo.objectId}"),

View File

@@ -24,7 +24,8 @@ object ApiUser {
def apply(user: Account): ApiUser = ApiUser(
login = user.userName,
email = user.mailAddress,
`type` = if (user.isGroupAccount) { "Organization" } else { "User" },
`type` = if (user.isGroupAccount) { "Organization" }
else { "User" },
site_admin = user.isAdmin,
created_at = user.registeredDate
)

View File

@@ -15,13 +15,12 @@ object JsonFormat {
val parserISO = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
val jsonFormats = Serialization.formats(NoTypeHints) + new CustomSerializer[Date](
format =>
val jsonFormats = Serialization.formats(NoTypeHints) + new CustomSerializer[Date](format =>
(
{
case JString(s) =>
{ case JString(s) =>
Try(Date.from(Instant.parse(s))).getOrElse(throw new MappingException("Can't convert " + s + " to Date"))
}, { case x: Date => JString(OffsetDateTime.ofInstant(x.toInstant, ZoneId.of("UTC")).format(parserISO)) }
},
{ case x: Date => JString(OffsetDateTime.ofInstant(x.toInstant, ZoneId.of("UTC")).format(parserISO)) }
)
) + FieldSerializer[ApiUser]() +
FieldSerializer[ApiGroup]() +
@@ -48,29 +47,32 @@ object JsonFormat {
ApiBranchProtection.enforcementLevelSerializer
def apiPathSerializer(c: Context) =
new CustomSerializer[ApiPath](
_ =>
({
new CustomSerializer[ApiPath](_ =>
(
{
case JString(s) if s.startsWith(c.baseUrl) => ApiPath(s.substring(c.baseUrl.length))
case JString(s) => throw new MappingException("Can't convert " + s + " to ApiPath")
}, {
case ApiPath(path) => JString(c.baseUrl + path)
})
},
{ case ApiPath(path) =>
JString(c.baseUrl + path)
}
)
)
def sshPathSerializer(c: Context) =
new CustomSerializer[SshPath](
_ =>
({
new CustomSerializer[SshPath](_ =>
(
{
case JString(s) if c.sshUrl.exists(sshUrl => s.startsWith(sshUrl)) =>
SshPath(s.substring(c.sshUrl.get.length))
case JString(s) => throw new MappingException("Can't convert " + s + " to ApiPath")
}, {
case SshPath(path) =>
},
{ case SshPath(path) =>
c.sshUrl.map { sshUrl =>
JString(sshUrl + path)
} getOrElse JNothing
})
}
)
)
/**

View File

@@ -215,9 +215,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
"events" -> accountWebhookEvents,
"ctype" -> label("ctype", text()),
"token" -> optional(trim(label("token", text(maxlength(100)))))
)(
(url, events, ctype, token) => AccountWebHookForm(url, events, WebHookContentType.valueOf(ctype), token)
)
)((url, events, ctype, token) => AccountWebHookForm(url, events, WebHookContentType.valueOf(ctype), token))
/**
* Provides duplication check for web hook url. duplicated from RepositorySettingsController.scala
@@ -340,8 +338,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
post("/:userName/_edit", editForm)(oneselfOnly { form =>
val userName = params("userName")
getAccountByUserName(userName).map {
account =>
getAccountByUserName(userName).map { account =>
updateAccount(
account.copy(
password = form.password.map(pbkdf2_sha256).getOrElse(account.password),
@@ -363,8 +360,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
get("/:userName/_delete")(oneselfOnly {
val userName = params("userName")
getAccountByUserName(userName, true).map {
account =>
getAccountByUserName(userName, true).map { account =>
if (isLastAdministrator(account)) {
flash.update("error", "Account can't be removed because this is last one administrator.")
redirect(s"/${userName}/_edit")
@@ -406,7 +402,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
get("/:userName/_gpg")(oneselfOnly {
val userName = params("userName")
getAccountByUserName(userName).map { x =>
//html.ssh(x, getPublicKeys(x.userName))
// html.ssh(x, getPublicKeys(x.userName))
html.gpg(x, getGpgPublicKeys(x.userName))
} getOrElse NotFound()
})
@@ -525,8 +521,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
get("/:userName/_hooks/edit")(managersOnly {
val userName = params("userName")
getAccountByUserName(userName).flatMap { account =>
getAccountWebHook(userName, params("url")).map {
case (webhook, events) =>
getAccountWebHook(userName, params("url")).map { case (webhook, events) =>
html.edithook(webhook, events, account, false)
}
} getOrElse NotFound()
@@ -584,8 +579,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
"url" -> url,
"request" -> Await.result(
reqFuture
.map(
req =>
.map(req =>
Map(
"headers" -> _headers(req.getAllHeaders),
"payload" -> json
@@ -596,8 +590,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
),
"response" -> Await.result(
resFuture
.map(
res =>
.map(res =>
Map(
"status" -> res.getStatusLine(),
"body" -> EntityUtils.toString(res.getEntity()),
@@ -788,8 +781,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
* Create new repository.
*/
post("/new", newRepositoryForm)(usersOnly { form =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
if (context.settings.basicBehavior.repositoryOperation.create || loginAccount.isAdmin) {
LockUtil.lock(s"${form.owner}/${form.name}") {
if (getRepository(form.owner, form.name).isDefined) {
@@ -819,17 +811,17 @@ trait AccountControllerBase extends AccountManagementControllerBase {
})
get("/:owner/:repository/fork")(readableUsersOnly { repository =>
context.withLoginAccount {
loginAccount =>
if (repository.repository.options.allowFork && (context.settings.basicBehavior.repositoryOperation.fork || loginAccount.isAdmin)) {
context.withLoginAccount { loginAccount =>
if (
repository.repository.options.allowFork && (context.settings.basicBehavior.repositoryOperation.fork || loginAccount.isAdmin)
) {
val loginUserName = loginAccount.userName
val groups = getGroupsByUserName(loginUserName)
groups match {
case _: List[String] =>
val managerPermissions = groups.map { group =>
val members = getGroupMembers(group)
context.loginAccount.exists(
x =>
context.loginAccount.exists(x =>
members.exists { member =>
member.userName == x.userName && member.isManager
}
@@ -846,9 +838,10 @@ trait AccountControllerBase extends AccountManagementControllerBase {
})
post("/:owner/:repository/fork", accountForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount {
loginAccount =>
if (repository.repository.options.allowFork && (context.settings.basicBehavior.repositoryOperation.fork || loginAccount.isAdmin)) {
context.withLoginAccount { loginAccount =>
if (
repository.repository.options.allowFork && (context.settings.basicBehavior.repositoryOperation.fork || loginAccount.isAdmin)
) {
val loginUserName = loginAccount.userName
val accountName = form.accountName
@@ -891,9 +884,11 @@ trait AccountControllerBase extends AccountManagementControllerBase {
private def members: Constraint = new Constraint() {
override def validate(name: String, value: String, messages: Messages): Option[String] = {
if (value.split(",").exists {
if (
value.split(",").exists {
_.split(":") match { case Array(userName, isManager) => isManager.toBoolean }
}) None
}
) None
else Some("Must select one manager at least.")
}
}

View File

@@ -423,10 +423,11 @@ trait AccountManagementControllerBase extends ControllerBase {
messages: Messages
): Option[String] = {
val extraMailAddresses = params.view.filterKeys(k => k.startsWith("extraMailAddresses"))
if (extraMailAddresses.exists {
case (k, v) =>
if (
extraMailAddresses.exists { case (k, v) =>
v.contains(value)
}) {
}
) {
Some("These mail addresses are duplicated.")
} else {
getAccountByMailAddress(value, true)
@@ -446,10 +447,11 @@ trait AccountManagementControllerBase extends ControllerBase {
messages: Messages
): Option[String] = {
val extraMailAddresses = params.view.filterKeys(k => k.startsWith("extraMailAddresses"))
if (Some(value) == params.optionValue("mailAddress") || extraMailAddresses.count {
case (k, v) =>
if (
Some(value) == params.optionValue("mailAddress") || extraMailAddresses.count { case (k, v) =>
v.contains(value)
} > 1) {
} > 1
) {
Some("These mail addresses are duplicated.")
} else {
getAccountByMailAddress(value, true)

View File

@@ -75,8 +75,7 @@ class FileUploadController
post("/wiki/:owner/:repository") {
setMultipartConfig()
// Don't accept not logged-in users
session.get(Keys.Session.LoginAccount).collect {
case loginAccount: Account =>
session.get(Keys.Session.LoginAccount).collect { case loginAccount: Account =>
val owner = params("owner")
val repository = params("repository")
@@ -86,8 +85,7 @@ class FileUploadController
{ (file, fileId) =>
val fileName = file.getName
LockUtil.lock(s"${owner}/${repository}/wiki") {
Using.resource(Git.open(Directory.getWikiRepositoryDir(owner, repository))) {
git =>
Using.resource(Git.open(Directory.getWikiRepositoryDir(owner, repository))) { git =>
val builder = DirCache.newInCore.builder()
val inserter = git.getRepository.newObjectInserter()
val headId = git.getRepository.resolve(Constants.HEAD + "^{commit}")
@@ -135,8 +133,7 @@ class FileUploadController
setMultipartConfigForLargeFile()
session
.get(Keys.Session.LoginAccount)
.collect {
case _: Account =>
.collect { case _: Account =>
val owner = params("owner")
val repository = params("repository")
val tag = multiParams("splat").head
@@ -158,9 +155,12 @@ class FileUploadController
setMultipartConfig()
session.get(Keys.Session.LoginAccount).collect {
case loginAccount: Account if loginAccount.isAdmin =>
execute({ (file, fileId) =>
execute(
{ (file, fileId) =>
request2Session(request).conn.importAsSQL(file.getInputStream)
}, _ => true)
},
_ => true
)
}
redirect("/admin/data")
}

View File

@@ -151,8 +151,7 @@ trait IndexControllerBase extends ControllerBase {
val redirectURI = new URI(s"$baseUrl/signin/oidc")
session.get(Keys.Session.OidcAuthContext) match {
case Some(context: OidcAuthContext) =>
authenticate(params.toMap, redirectURI, context.state, context.nonce, oidc).map {
case (jwt, account) =>
authenticate(params.toMap, redirectURI, context.state, context.nonce, oidc).map { case (jwt, account) =>
session.setAttribute(Keys.Session.OidcSessionContext, OidcSessionContext(jwt))
signin(account, context.redirectBackURI)
} orElse {
@@ -172,8 +171,7 @@ trait IndexControllerBase extends ControllerBase {
get("/signout") {
context.settings.oidc.foreach { oidc =>
session.get(Keys.Session.OidcSessionContext).foreach {
case context: OidcSessionContext =>
session.get(Keys.Session.OidcSessionContext).foreach { case context: OidcSessionContext =>
val redirectURI = new URI(baseUrl)
val authenticationRequest = createOIDLogoutRequest(oidc.issuer, oidc.clientID, redirectURI, context.token)
session.invalidate()
@@ -269,7 +267,8 @@ trait IndexControllerBase extends ControllerBase {
get("/:owner/:repository/search")(referrersOnly { repository =>
val query = params.getOrElse("q", "").trim
val target = params.getOrElse("type", "code")
val page = try {
val page =
try {
val i = params.getOrElse("page", "1").toInt
if (i <= 0) 1 else i
} catch {

View File

@@ -101,8 +101,7 @@ trait IssuesControllerBase extends ControllerBase {
get("/:owner/:repository/issues/:id")(referrersOnly { repository =>
val issueId = params("id")
getIssue(repository.owner, repository.name, issueId) map {
issue =>
getIssue(repository.owner, repository.name, issueId) map { issue =>
if (issue.isPullRequest) {
redirect(s"/${repository.owner}/${repository.name}/pull/${issueId}")
} else {
@@ -142,8 +141,7 @@ trait IssuesControllerBase extends ControllerBase {
})
post("/:owner/:repository/issues/new", issueCreateForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
if (isIssueEditable(repository)) { // TODO Should this check is provided by authenticator?
val issue = createIssue(
repository,
@@ -157,8 +155,7 @@ trait IssuesControllerBase extends ControllerBase {
)
// Insert custom field values
params.toMap.foreach {
case (key, value) =>
params.toMap.foreach { case (key, value) =>
if (key.startsWith("custom-field-")) {
getCustomField(
repository.owner,
@@ -180,10 +177,8 @@ trait IssuesControllerBase extends ControllerBase {
})
ajaxPost("/:owner/:repository/issues/edit_title/:id", issueTitleEditForm)(readableUsersOnly { (title, repository) =>
context.withLoginAccount {
loginAccount =>
getIssue(repository.owner, repository.name, params("id")).map {
issue =>
context.withLoginAccount { loginAccount =>
getIssue(repository.owner, repository.name, params("id")).map { issue =>
if (isEditableContent(repository.owner, repository.name, issue.openedUserName, loginAccount)) {
if (issue.title != title) {
// update issue
@@ -206,8 +201,7 @@ trait IssuesControllerBase extends ControllerBase {
})
ajaxPost("/:owner/:repository/issues/edit/:id", issueEditForm)(readableUsersOnly { (content, repository) =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
getIssue(repository.owner, repository.name, params("id")).map { issue =>
if (isEditableContent(repository.owner, repository.name, issue.openedUserName, loginAccount)) {
// update issue
@@ -222,15 +216,13 @@ trait IssuesControllerBase extends ControllerBase {
})
post("/:owner/:repository/issue_comments/new", commentForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
getIssue(repository.owner, repository.name, form.issueId.toString).flatMap { issue =>
val actionOpt =
params
.get("action")
.filter(_ => isEditableContent(issue.userName, issue.repositoryName, issue.openedUserName, loginAccount))
handleComment(issue, Some(form.content), repository, actionOpt) map {
case (issue, id) =>
handleComment(issue, Some(form.content), repository, actionOpt) map { case (issue, id) =>
redirect(
s"/${repository.owner}/${repository.name}/${if (issue.isPullRequest) "pull" else "issues"}/${form.issueId}#comment-${id}"
)
@@ -240,15 +232,13 @@ trait IssuesControllerBase extends ControllerBase {
})
post("/:owner/:repository/issue_comments/state", issueStateForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
getIssue(repository.owner, repository.name, form.issueId.toString).flatMap { issue =>
val actionOpt =
params
.get("action")
.filter(_ => isEditableContent(issue.userName, issue.repositoryName, issue.openedUserName, loginAccount))
handleComment(issue, form.content, repository, actionOpt) map {
case (issue, id) =>
handleComment(issue, form.content, repository, actionOpt) map { case (issue, id) =>
redirect(
s"/${repository.owner}/${repository.name}/${if (issue.isPullRequest) "pull" else "issues"}/${form.issueId}#comment-${id}"
)
@@ -258,8 +248,7 @@ trait IssuesControllerBase extends ControllerBase {
})
ajaxPost("/:owner/:repository/issue_comments/edit/:id", commentForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
getComment(repository.owner, repository.name, params("id")).map { comment =>
if (isEditableContent(repository.owner, repository.name, comment.commentedUserName, loginAccount)) {
updateComment(repository.owner, repository.name, comment.issueId, comment.commentId, form.content)
@@ -280,10 +269,8 @@ trait IssuesControllerBase extends ControllerBase {
})
ajaxGet("/:owner/:repository/issues/_data/:id")(readableUsersOnly { repository =>
context.withLoginAccount {
loginAccount =>
getIssue(repository.owner, repository.name, params("id")) map {
x =>
context.withLoginAccount { loginAccount =>
getIssue(repository.owner, repository.name, params("id")) map { x =>
if (isEditableContent(x.userName, x.repositoryName, x.openedUserName, loginAccount)) {
params.get("dataType") collect {
case t if t == "html" => html.editissue(x.content, x.issueId, repository)
@@ -312,10 +299,8 @@ trait IssuesControllerBase extends ControllerBase {
})
ajaxGet("/:owner/:repository/issue_comments/_data/:id")(readableUsersOnly { repository =>
context.withLoginAccount {
loginAccount =>
getComment(repository.owner, repository.name, params("id")) map {
x =>
context.withLoginAccount { loginAccount =>
getComment(repository.owner, repository.name, params("id")) map { x =>
if (isEditableContent(x.userName, x.repositoryName, x.commentedUserName, loginAccount)) {
params.get("dataType") collect {
case t if t == "html" => html.editcomment(x.content, x.commentId, repository)
@@ -377,8 +362,7 @@ trait IssuesControllerBase extends ControllerBase {
milestoneId("milestoneId").map { milestoneId =>
getMilestonesWithIssueCount(repository.owner, repository.name)
.find(_._1.milestoneId == milestoneId)
.map {
case (_, openCount, closeCount) =>
.map { case (_, openCount, closeCount) =>
gitbucket.core.issues.milestones.html.progress(openCount + closeCount, closeCount)
} getOrElse NotFound()
} getOrElse Ok()
@@ -460,7 +444,7 @@ trait IssuesControllerBase extends ControllerBase {
post("/:owner/:repository/issues/batchedit/assign")(writableUsersOnly { repository =>
val value = assignedUserName("value")
executeBatch(repository) {
//updateAssignedUserName(repository.owner, repository.name, _, value, true)
// updateAssignedUserName(repository.owner, repository.name, _, value, true)
value match {
case Some(assignedUserName) =>
registerIssueAssignee(repository.owner, repository.name, _, assignedUserName, true)
@@ -565,8 +549,8 @@ trait IssuesControllerBase extends ControllerBase {
/**
* Tests whether an issue or a comment is editable by a logged-in user.
*/
private def isEditableContent(owner: String, repository: String, author: String, loginAccount: Account)(
implicit context: Context
private def isEditableContent(owner: String, repository: String, author: String, loginAccount: Account)(implicit
context: Context
): Boolean = {
hasDeveloperRole(owner, repository, context.loginAccount) || author == loginAccount.userName
}
@@ -574,8 +558,8 @@ trait IssuesControllerBase extends ControllerBase {
/**
* Tests whether an issue comment is deletable by a logged-in user.
*/
private def isDeletableComment(owner: String, repository: String, author: String, loginAccount: Account)(
implicit context: Context
private def isDeletableComment(owner: String, repository: String, author: String, loginAccount: Account)(implicit
context: Context
): Boolean = {
hasOwnerRole(owner, repository, context.loginAccount) || author == loginAccount.userName
}

View File

@@ -30,12 +30,14 @@ trait PreProcessControllerBase extends ControllerBase {
* But if it's not allowed, demands authentication except some paths.
*/
get(!context.settings.basicBehavior.allowAnonymousAccess, context.loginAccount.isEmpty) {
if (!context.currentPath.startsWith("/assets") && !context.currentPath.startsWith("/signin") &&
if (
!context.currentPath.startsWith("/assets") && !context.currentPath.startsWith("/signin") &&
!context.currentPath.startsWith("/register") && !context.currentPath.endsWith("/info/refs") &&
!context.currentPath.startsWith("/plugin-assets") &&
!PluginRegistry().getAnonymousAccessiblePaths().exists { path =>
context.currentPath.startsWith(path)
}) {
}
) {
Unauthorized()
} else {
pass()

View File

@@ -113,10 +113,8 @@ trait PullRequestsControllerBase extends ControllerBase {
})
get("/:owner/:repository/pull/:id")(referrersOnly { repository =>
params("id").toIntOpt.flatMap {
issueId =>
getPullRequest(repository.owner, repository.name, issueId) map {
case (issue, pullreq) =>
params("id").toIntOpt.flatMap { issueId =>
getPullRequest(repository.owner, repository.name, issueId) map { case (issue, pullreq) =>
val (commits, diffs) =
getRequestCompareInfo(
repository.owner,
@@ -152,10 +150,8 @@ trait PullRequestsControllerBase extends ControllerBase {
})
get("/:owner/:repository/pull/:id/commits")(referrersOnly { repository =>
params("id").toIntOpt.flatMap {
issueId =>
getPullRequest(repository.owner, repository.name, issueId) map {
case (issue, pullreq) =>
params("id").toIntOpt.flatMap { issueId =>
getPullRequest(repository.owner, repository.name, issueId) map { case (issue, pullreq) =>
val (commits, diffs) =
getRequestCompareInfo(
repository.owner,
@@ -186,10 +182,8 @@ trait PullRequestsControllerBase extends ControllerBase {
})
get("/:owner/:repository/pull/:id/files")(referrersOnly { repository =>
params("id").toIntOpt.flatMap {
issueId =>
getPullRequest(repository.owner, repository.name, issueId) map {
case (issue, pullreq) =>
params("id").toIntOpt.flatMap { issueId =>
getPullRequest(repository.owner, repository.name, issueId) map { case (issue, pullreq) =>
val (commits, diffs) =
getRequestCompareInfo(
repository.owner,
@@ -214,10 +208,8 @@ trait PullRequestsControllerBase extends ControllerBase {
})
ajaxGet("/:owner/:repository/pull/:id/mergeguide")(referrersOnly { repository =>
params("id").toIntOpt.flatMap {
issueId =>
getPullRequest(repository.owner, repository.name, issueId) map {
case (issue, pullreq) =>
params("id").toIntOpt.flatMap { issueId =>
getPullRequest(repository.owner, repository.name, issueId) map { case (issue, pullreq) =>
val conflictMessage = LockUtil.lock(s"${repository.owner}/${repository.name}") {
checkConflict(repository.owner, repository.name, pullreq.branch, issueId)
}
@@ -314,7 +306,9 @@ trait PullRequestsControllerBase extends ControllerBase {
} else {
LockUtil.lock(s"${owner}/${name}") {
val alias =
if (pullreq.repositoryName == pullreq.requestRepositoryName && pullreq.userName == pullreq.requestUserName) {
if (
pullreq.repositoryName == pullreq.requestRepositoryName && pullreq.userName == pullreq.requestUserName
) {
pullreq.branch
} else {
s"${pullreq.userName}:${pullreq.branch}"
@@ -383,8 +377,7 @@ trait PullRequestsControllerBase extends ControllerBase {
val headBranch = params.get("head")
(forkedRepository.repository.originUserName, forkedRepository.repository.originRepositoryName) match {
case (Some(originUserName), Some(originRepositoryName)) =>
getRepository(originUserName, originRepositoryName).map {
originRepository =>
getRepository(originUserName, originRepositoryName).map { originRepository =>
Using.resources(
Git.open(getRepositoryDir(originUserName, originRepositoryName)),
Git.open(getRepositoryDir(forkedRepository.owner, forkedRepository.name))
@@ -401,8 +394,7 @@ trait PullRequestsControllerBase extends ControllerBase {
} getOrElse NotFound()
case _ =>
Using.resource(Git.open(getRepositoryDir(forkedRepository.owner, forkedRepository.name))) { git =>
JGitUtil.getDefaultBranch(git, forkedRepository).map {
case (_, defaultBranch) =>
JGitUtil.getDefaultBranch(git, forkedRepository).map { case (_, defaultBranch) =>
redirect(
s"/${forkedRepository.owner}/${forkedRepository.name}/compare/${defaultBranch}...${headBranch.getOrElse(defaultBranch)}"
)
@@ -445,8 +437,10 @@ trait PullRequestsControllerBase extends ControllerBase {
val (originOwner, originId) = parseCompareIdentifier(origin, forkedRepository.owner)
val (forkedOwner, forkedId) = parseCompareIdentifier(forked, forkedRepository.owner)
(for (originRepositoryName <- getOriginRepositoryName(originOwner, forkedOwner, forkedRepository);
originRepository <- getRepository(originOwner, originRepositoryName)) yield {
(for (
originRepositoryName <- getOriginRepositoryName(originOwner, forkedOwner, forkedRepository);
originRepository <- getRepository(originOwner, originRepositoryName)
) yield {
val (oldId, newId) =
getPullRequestCommitFromTo(originRepository, forkedRepository, originId, forkedId)
@@ -566,7 +560,9 @@ trait PullRequestsControllerBase extends ControllerBase {
val (originOwner, tmpOriginBranch) = parseCompareIdentifier(origin, forkedRepository.owner)
val (forkedOwner, tmpForkedBranch) = parseCompareIdentifier(forked, forkedRepository.owner)
(for (originRepositoryName <- if (originOwner == forkedOwner) {
(for (
originRepositoryName <-
if (originOwner == forkedOwner) {
Some(forkedRepository.name)
} else {
forkedRepository.repository.originRepositoryName.orElse {
@@ -575,12 +571,12 @@ trait PullRequestsControllerBase extends ControllerBase {
.map(_.repositoryName)
}
};
originRepository <- getRepository(originOwner, originRepositoryName)) yield {
originRepository <- getRepository(originOwner, originRepositoryName)
) yield {
Using.resources(
Git.open(getRepositoryDir(originRepository.owner, originRepository.name)),
Git.open(getRepositoryDir(forkedRepository.owner, forkedRepository.name))
) {
case (oldGit, newGit) =>
) { case (oldGit, newGit) =>
val originBranch = JGitUtil.getDefaultBranch(oldGit, originRepository, tmpOriginBranch).get._2
val forkedBranch = JGitUtil.getDefaultBranch(newGit, forkedRepository, tmpForkedBranch).get._2
val conflict = LockUtil.lock(s"${originRepository.owner}/${originRepository.name}") {
@@ -599,8 +595,7 @@ trait PullRequestsControllerBase extends ControllerBase {
})
post("/:owner/:repository/pulls/new", pullRequestForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
val manageable = isManageable(repository)
val issueId = insertIssue(
@@ -656,8 +651,7 @@ trait PullRequestsControllerBase extends ControllerBase {
context.loginAccount.map(x => Seq(x.mailAddress) ++ getAccountExtraMailAddresses(x.userName)).getOrElse(Nil)
val branches =
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
JGitUtil
.getBranches(
git = git,

View File

@@ -106,8 +106,7 @@ trait ReleaseControllerBase extends ControllerBase {
})
post("/:owner/:repository/releases/*/create", releaseForm)(writableUsersOnly { (form, repository) =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
val tagName = multiParams("splat").head
// Insert into RELEASE
@@ -119,8 +118,7 @@ trait ReleaseControllerBase extends ControllerBase {
val Array(_, fileId) = name.split(":")
(fileId, value)
}
files.foreach {
case (fileId, fileName) =>
files.foreach { case (fileId, fileName) =>
val size =
new File(
getReleaseFilesDir(repository.owner, repository.name),
@@ -171,13 +169,11 @@ trait ReleaseControllerBase extends ControllerBase {
})
post("/:owner/:repository/releases/*/edit", releaseForm)(writableUsersOnly { (form, repository) =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
val tagName = multiParams("splat").head
getRelease(repository.owner, repository.name, tagName)
.map {
release =>
.map { release =>
// Update RELEASE
updateRelease(repository.owner, repository.name, tagName, form.name, form.content)
@@ -190,8 +186,7 @@ trait ReleaseControllerBase extends ControllerBase {
val Array(_, fileId) = name.split(":")
(fileId, value)
}
files.foreach {
case (fileId, fileName) =>
files.foreach { case (fileId, fileName) =>
val size =
new File(
getReleaseFilesDir(repository.owner, repository.name),
@@ -237,9 +232,12 @@ trait ReleaseControllerBase extends ControllerBase {
val assets = getReleaseAssetsMap(repository.owner, repository.name, releases)
val tagsWithReleases = tagsToDisplay.map { tag =>
(tag, releases.find(_.tag == tag.name).map { release =>
(
tag,
releases.find(_.tag == tag.name).map { release =>
(release, assets(release))
})
}
)
}
tagsWithReleases
}

View File

@@ -286,8 +286,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
Array(h.getName, h.getValue)
}
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
import scala.concurrent.duration._
import scala.concurrent._
import scala.jdk.CollectionConverters._
@@ -348,8 +347,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
"url" -> url,
"request" -> Await.result(
reqFuture
.map(
req =>
.map(req =>
Map(
"headers" -> _headers(req.getAllHeaders),
"payload" -> json
@@ -360,8 +358,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
),
"response" -> Await.result(
resFuture
.map(
res =>
.map(res =>
Map(
"status" -> res.getStatusLine.getStatusCode,
"body" -> EntityUtils.toString(res.getEntity()),
@@ -380,8 +377,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
* Display the web hook edit page.
*/
get("/:owner/:repository/settings/hooks/edit")(ownerOnly { repository =>
getWebHook(repository.owner, repository.name, params("url")).map {
case (webhook, events) =>
getWebHook(repository.owner, repository.name, params("url")).map { case (webhook, events) =>
html.edithook(webhook, events, repository, false)
} getOrElse NotFound()
})
@@ -406,8 +402,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
* Rename repository.
*/
post("/:owner/:repository/settings/rename", renameForm)(ownerOnly { (form, repository) =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
if (context.settings.basicBehavior.repositoryOperation.rename || loginAccount.isAdmin) {
if (repository.name != form.repositoryName) {
// Update database and move git repository
@@ -430,8 +425,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
* Transfer repository ownership.
*/
post("/:owner/:repository/settings/transfer", transferForm)(ownerOnly { (form, repository) =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
if (context.settings.basicBehavior.repositoryOperation.transfer || loginAccount.isAdmin) {
// Change repository owner
if (repository.owner != form.newOwner) {

View File

@@ -257,8 +257,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
val (branchName, path) = repository.splitPath(multiParams("splat").head)
val page = params.get("page").flatMap(_.toIntOpt).getOrElse(1)
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
JGitUtil.getCommitLog(git, branchName, page, 30, path) match {
case Right((logs, hasNext)) =>
html.commits(
@@ -273,8 +272,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
getCommitStatusWithSummary(repository.owner, repository.name, commit.id)
)
}
.splitWith {
case ((commit1, _, _), (commit2, _, _)) =>
.splitWith { case ((commit1, _, _), (commit2, _, _)) =>
view.helpers.date(commit1.commitTime) == view.helpers.date(commit2.commitTime)
},
page,
@@ -287,8 +285,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
})
get("/:owner/:repository/new/*")(writableUsersOnly { repository =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
val (branch, path) = repository.splitPath(multiParams("splat").head)
val protectedBranch = getProtectedBranchInfo(repository.owner, repository.name, branch)
.needStatusCheck(loginAccount.userName)
@@ -310,8 +307,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
})
get("/:owner/:repository/upload/*")(writableUsersOnly { repository =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
val (branch, path) = repository.splitPath(multiParams("splat").head)
val protectedBranch = getProtectedBranchInfo(repository.owner, repository.name, branch)
.needStatusCheck(loginAccount.userName)
@@ -340,8 +336,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
message = form.message.getOrElse("Add files via upload"),
loginAccount = loginAccount,
settings = context.settings
) {
case (git, headTip, builder, inserter) =>
) { case (git, headTip, builder, inserter) =>
JGitUtil.processTree(git, headTip) { (path, tree) =>
if (!newFiles.exists(_.name.contains(path))) {
builder.add(JGitUtil.createDirCacheEntry(path, tree.getEntryFileMode, tree.getEntryObjectId))
@@ -359,8 +354,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
}
}
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
val files = form.uploadFiles
.split("\n")
.map { line =>
@@ -407,19 +401,16 @@ trait RepositoryViewerControllerBase extends ControllerBase {
})
get("/:owner/:repository/edit/*")(writableUsersOnly { repository =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
val (branch, path) = repository.splitPath(multiParams("splat").head)
val protectedBranch = getProtectedBranchInfo(repository.owner, repository.name, branch)
.needStatusCheck(loginAccount.userName)
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(branch))
getPathObjectId(git, path, revCommit)
.map {
objectId =>
.map { objectId =>
val paths = path.split("/")
val info = EditorConfigUtil.getEditorConfigInfo(git, branch, path)
@@ -442,8 +433,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
get("/:owner/:repository/remove/*")(writableUsersOnly { repository =>
val (branch, path) = repository.splitPath(multiParams("splat").head)
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(branch))
getPathObjectId(git, path, revCommit).map { objectId =>
@@ -477,8 +467,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
).map(_._1)
}
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
if (form.newBranch) {
val newBranchName = createNewBranchForPullRequest(repository, form.branch, loginAccount)
_commit(newBranchName, loginAccount) match {
@@ -535,8 +524,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
).map(_._1)
}
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
if (form.newBranch) {
val newBranchName = createNewBranchForPullRequest(repository, form.branch, loginAccount)
_commit(newBranchName, loginAccount) match {
@@ -589,8 +577,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
).map(_._1)
}
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
if (form.newBranch) {
val newBranchName = createNewBranchForPullRequest(repository, form.branch, loginAccount)
_commit(newBranchName, loginAccount) match {
@@ -714,11 +701,9 @@ trait RepositoryViewerControllerBase extends ControllerBase {
val (id, path) = repository.splitPath(multiParams("splat").head)
val raw = params.get("raw").getOrElse("false").toBoolean
val highlighterTheme = getSyntaxHighlighterTheme()
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(id))
getPathObjectId(git, path, revCommit).map {
objectId =>
getPathObjectId(git, path, revCommit).map { objectId =>
if (raw) {
// Download (This route is left for backward compatibility)
responseRawFile(git, objectId, path, repository)
@@ -766,8 +751,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
ajaxGet("/:owner/:repository/get-blame/*")(referrersOnly { repository =>
val (id, path) = repository.splitPath(multiParams("splat").head)
contentType = formats("json")
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
val last = git.log.add(git.getRepository.resolve(id)).addPath(path).setMaxCount(1).call.iterator.next.name
Serialization.write(
Map(
@@ -775,8 +759,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
"id" -> id,
"path" -> path,
"last" -> last,
"blame" -> JGitUtil.getBlame(git, id, path).map {
blame =>
"blame" -> JGitUtil.getBlame(git, id, path).map { blame =>
Map(
"id" -> blame.id,
"author" -> view.helpers.user(blame.authorName, blame.authorEmailAddress).toString,
@@ -801,8 +784,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
val id = params("id")
try {
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(id))
val diffs = JGitUtil.getDiffs(git, None, id, true, false)
val oldCommitId = JGitUtil.getParentCommitId(git, id)
@@ -890,8 +872,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
})
ajaxPost("/:owner/:repository/commit/:id/comment/_data/new", commentForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
val id = params("id")
val commentId = createCommitComment(
repository,
@@ -912,10 +893,8 @@ trait RepositoryViewerControllerBase extends ControllerBase {
})
ajaxGet("/:owner/:repository/commit_comments/_data/:id")(readableUsersOnly { repository =>
context.withLoginAccount {
loginAccount =>
getCommitComment(repository.owner, repository.name, params("id")) map {
x =>
context.withLoginAccount { loginAccount =>
getCommitComment(repository.owner, repository.name, params("id")) map { x =>
if (isEditable(x.userName, x.repositoryName, x.commentedUserName, loginAccount)) {
params.get("dataType") collect {
case t if t == "html" => html.editcomment(x.content, x.commentId, repository)
@@ -943,8 +922,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
})
ajaxPost("/:owner/:repository/commit_comments/edit/:id", commentForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
getCommitComment(repository.owner, repository.name, params("id")).map { comment =>
if (isEditable(repository.owner, repository.name, comment.commentedUserName, loginAccount)) {
updateCommitComment(comment.commentId, form.content)
@@ -969,8 +947,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
*/
get("/:owner/:repository/branches")(referrersOnly { repository =>
val protectedBranches = getProtectedBranchList(repository.owner, repository.name).toSet
val branches = Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git =>
val branches = Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
JGitUtil
.getBranches(
git = git,
@@ -978,8 +955,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
origin = repository.repository.originUserName.isEmpty
)
.sortBy(branch => (branch.mergeInfo.isEmpty, branch.commitTime))
.map(
branch =>
.map(branch =>
(
branch,
getPullRequestByRequestCommit(
@@ -1028,8 +1004,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
post("/:owner/:repository/branches")(writableUsersOnly { repository =>
val newBranchName = params.getOrElse("new", halt(400))
val fromBranchName = params.getOrElse("from", halt(400))
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
JGitUtil.createBranch(git, fromBranchName, newBranchName) match {
case Right(message) =>
flash.update("info", message)
@@ -1083,8 +1058,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
* Deletes branch.
*/
get("/:owner/:repository/delete/*")(writableUsersOnly { repository =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
val branchName = multiParams("splat").head
if (repository.repository.defaultBranch != branchName) {
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
@@ -1179,8 +1153,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
html.guide(repository, hasDeveloperRole(repository.owner, repository.name, context.loginAccount))
} else {
// get specified commit
JGitUtil.getDefaultBranch(git, repository, revstr).map {
case (objectId, revision) =>
JGitUtil.getDefaultBranch(git, repository, revstr).map { case (objectId, revision) =>
val revCommit = JGitUtil.getRevCommitFromId(git, objectId)
val lastModifiedCommit =
if (path == ".") revCommit else JGitUtil.getLastModifiedCommit(git, revCommit, path)

View File

@@ -55,15 +55,13 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
"bindAddress" -> mapping(
"host" -> trim(label("Bind SSH host", optional(text()))),
"port" -> trim(label("Bind SSH port", optional(number()))),
)(
(hostOption, portOption) =>
)((hostOption, portOption) =>
hostOption.map(h => SshAddress(h, portOption.getOrElse(DefaultSshPort), GenericSshUser))
),
"publicAddress" -> mapping(
"host" -> trim(label("Public SSH host", optional(text()))),
"port" -> trim(label("Public SSH port", optional(number()))),
)(
(hostOption, portOption) =>
)((hostOption, portOption) =>
hostOption.map(h => SshAddress(h, portOption.getOrElse(PublicSshPort), GenericSshUser))
),
)(Ssh.apply),
@@ -251,8 +249,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
val conn = request2Session(request).conn
val meta = conn.getMetaData
val tables = ListBuffer[Table]()
Using.resource(meta.getTables(null, "%", "%", Array("TABLE", "VIEW"))) {
rs =>
Using.resource(meta.getTables(null, "%", "%", Array("TABLE", "VIEW"))) { rs =>
while (rs.next()) {
val tableName = rs.getString("TABLE_NAME")
@@ -285,11 +282,9 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
if (trimmedQuery.nonEmpty) {
try {
val conn = request2Session(request).conn
Using.resource(conn.prepareStatement(query)) {
stmt =>
Using.resource(conn.prepareStatement(query)) { stmt =>
if (trimmedQuery.toUpperCase.startsWith("SELECT")) {
Using.resource(stmt.executeQuery()) {
rs =>
Using.resource(stmt.executeQuery()) { rs =>
val meta = rs.getMetaData
val columns = for (i <- 1 to meta.getColumnCount) yield {
meta.getColumnName(i)
@@ -323,7 +318,9 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
post("/admin/system", form)(adminOnly { form =>
saveSystemSettings(form)
if (form.ssh.bindAddress != context.settings.sshBindAddress || form.ssh.publicAddress != context.settings.sshPublicAddress) {
if (
form.ssh.bindAddress != context.settings.sshBindAddress || form.ssh.publicAddress != context.settings.sshPublicAddress
) {
SshServer.stop()
for {
bindAddress <- form.ssh.bindAddress
@@ -420,8 +417,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
post("/admin/users/:name/_edituser", editUserForm)(adminOnly { form =>
val userName = params("userName")
getAccountByUserName(userName, true).map {
account =>
getAccountByUserName(userName, true).map { account =>
if (account.isAdmin && (form.isRemoved || !form.isAdmin) && isLastAdministrator(account)) {
flash.update("error", "Account can't be turned off because this is last one administrator.")
redirect(s"/admin/users/${userName}/_edituser")
@@ -498,8 +494,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
}
.toList
getAccountByUserName(groupName, true).map {
account =>
getAccountByUserName(groupName, true).map { account =>
updateGroup(groupName, form.description, form.url, form.isRemoved)
if (form.isRemoved) {
@@ -565,9 +560,11 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
private def members: Constraint =
new Constraint() {
override def validate(name: String, value: String, messages: Messages): Option[String] = {
if (value.split(",").exists {
if (
value.split(",").exists {
_.split(":") match { case Array(userName, isManager) => isManager.toBoolean }
}) None
}
) None
else Some("Must select one manager at least.")
}
}

View File

@@ -84,8 +84,7 @@ trait ValidationSupport extends FormSupport { self: ServletBase with JacksonJson
* Converts errors to JSON.
*/
private def toJson(errors: Seq[(String, String)]): JObject =
JObject(errors.map {
case (key, value) =>
JObject(errors.map { case (key, value) =>
JField(key, JString(value))
}.toList)

View File

@@ -146,8 +146,7 @@ trait WikiControllerBase extends ControllerBase {
})
get("/:owner/:repository/wiki/:page/_revert/:commitId")(readableUsersOnly { repository =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
if (isEditable(repository)) {
val pageName = StringUtil.urlDecode(params("page"))
val Array(from, to) = params("commitId").split("\\.\\.\\.")
@@ -166,8 +165,7 @@ trait WikiControllerBase extends ControllerBase {
})
get("/:owner/:repository/wiki/_revert/:commitId")(readableUsersOnly { repository =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
if (isEditable(repository)) {
val Array(from, to) = params("commitId").split("\\.\\.\\.")
val branch = getWikiBranch(repository.owner, repository.name)
@@ -192,8 +190,7 @@ trait WikiControllerBase extends ControllerBase {
})
post("/:owner/:repository/wiki/_edit", editForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
if (isEditable(repository)) {
saveWikiPage(
repository.owner,
@@ -204,8 +201,7 @@ trait WikiControllerBase extends ControllerBase {
loginAccount,
form.message.getOrElse(""),
Some(form.id)
).foreach {
commitId =>
).foreach { commitId =>
updateLastActivityDate(repository.owner, repository.name)
val wikiEditInfo =
EditWikiPageInfo(repository.owner, repository.name, loginAccount.userName, form.pageName, commitId)
@@ -232,8 +228,7 @@ trait WikiControllerBase extends ControllerBase {
})
post("/:owner/:repository/wiki/_new", newForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
if (isEditable(repository)) {
saveWikiPage(
repository.owner,
@@ -244,8 +239,7 @@ trait WikiControllerBase extends ControllerBase {
loginAccount,
form.message.getOrElse(""),
None
).foreach {
commitId =>
).foreach { commitId =>
updateLastActivityDate(repository.owner, repository.name)
val createWikiPageInfo =
CreateWikiPageInfo(repository.owner, repository.name, loginAccount.userName, form.pageName)
@@ -267,8 +261,7 @@ trait WikiControllerBase extends ControllerBase {
})
get("/:owner/:repository/wiki/:page/_delete")(readableUsersOnly { repository =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
if (isEditable(repository)) {
val pageName = StringUtil.urlDecode(params("page"))
deleteWikiPage(

View File

@@ -58,10 +58,8 @@ trait ApiGitReferenceControllerBase extends ControllerBase {
* https://docs.github.com/en/free-pro-team@latest/rest/reference/git#create-a-reference
*/
post("/api/v3/repos/:owner/:repository/git/refs")(writableUsersOnly { repository =>
extractFromJsonBody[CreateARef].map {
data =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git =>
extractFromJsonBody[CreateARef].map { data =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
val ref = git.getRepository.findRef(data.ref)
if (ref == null) {
val update = git.getRepository.updateRef(data.ref)
@@ -88,8 +86,7 @@ trait ApiGitReferenceControllerBase extends ControllerBase {
*/
patch("/api/v3/repos/:owner/:repository/git/refs/*")(writableUsersOnly { repository =>
val refName = multiParams("splat").mkString("/")
extractFromJsonBody[UpdateARef].map {
data =>
extractFromJsonBody[UpdateARef].map { data =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
val ref = git.getRepository.findRef(refName)
if (ref == null) {

View File

@@ -23,8 +23,7 @@ trait ApiIssueCommentControllerBase extends ControllerBase {
issueId <- params("id").toIntOpt
comments = getCommentsForApi(repository.owner, repository.name, issueId)
} yield {
JsonFormat(comments.map {
case (issueComment, user, issue) =>
JsonFormat(comments.map { case (issueComment, user, issue) =>
ApiComment(issueComment, RepositoryName(repository), issueId, ApiUser(user), issue.isPullRequest)
})
}) getOrElse NotFound()

View File

@@ -29,7 +29,7 @@ trait ApiIssueControllerBase extends ControllerBase {
val page = IssueSearchCondition.page(request)
// TODO: more api spec condition
val condition = IssueSearchCondition(request)
//val baseOwner = getAccountByUserName(repository.owner).get
// val baseOwner = getAccountByUserName(repository.owner).get
val issues: List[(Issue, Account, List[Account])] =
searchIssueByApi(
@@ -39,8 +39,7 @@ trait ApiIssueControllerBase extends ControllerBase {
repos = repository.owner -> repository.name
)
JsonFormat(issues.map {
case (issue, issueUser, assigneeUsers) =>
JsonFormat(issues.map { case (issue, issueUser, assigneeUsers) =>
ApiIssue(
issue = issue,
repositoryName = RepositoryName(repository),

View File

@@ -69,8 +69,7 @@ trait ApiIssueLabelControllerBase extends ControllerBase {
data <- extractFromJsonBody[CreateALabel] if data.isValid
} yield {
LockUtil.lock(RepositoryName(repository).fullName) {
getLabel(repository.owner, repository.name, params("labelName")).map {
label =>
getLabel(repository.owner, repository.name, params("labelName")).map { label =>
if (getLabel(repository.owner, repository.name, data.name).isEmpty) {
updateLabel(repository.owner, repository.name, label.labelId, data.name, data.color)
JsonFormat(

View File

@@ -16,8 +16,10 @@ trait ApiIssueMilestoneControllerBase extends ControllerBase {
get("/api/v3/repos/:owner/:repository/milestones")(referrersOnly { repository =>
val state = params.getOrElse("state", "all")
// TODO "sort", "direction" params should be implemented.
val apiMilestones = (for (milestoneWithIssue <- getMilestonesWithIssueCount(repository.owner, repository.name)
.sortBy(p => p._1.milestoneId))
val apiMilestones = (for (
milestoneWithIssue <- getMilestonesWithIssueCount(repository.owner, repository.name)
.sortBy(p => p._1.milestoneId)
)
yield {
ApiMilestone(
repository.repository,

View File

@@ -48,8 +48,7 @@ trait ApiPullRequestControllerBase extends ControllerBase {
repos = repository.owner -> repository.name
)
JsonFormat(issues.map {
case (issue, issueUser, commentCount, pullRequest, headRepo, headOwner, assignees) =>
JsonFormat(issues.map { case (issue, issueUser, commentCount, pullRequest, headRepo, headOwner, assignees) =>
ApiPullRequest(
issue = issue,
pullRequest = pullRequest,
@@ -89,8 +88,7 @@ trait ApiPullRequestControllerBase extends ControllerBase {
case Left(createPullReq) =>
val (reqOwner, reqBranch) = parseCompareIdentifier(createPullReq.head, repository.owner)
getRepository(reqOwner, repository.name)
.flatMap {
forkedRepository =>
.flatMap { forkedRepository =>
getPullRequestCommitFromTo(repository, forkedRepository, createPullReq.base, reqBranch) match {
case (Some(commitIdFrom), Some(commitIdTo)) =>
val issueId = insertIssue(
@@ -128,8 +126,7 @@ trait ApiPullRequestControllerBase extends ControllerBase {
case Right(createPullReqAlt) =>
val (reqOwner, reqBranch) = parseCompareIdentifier(createPullReqAlt.head, repository.owner)
getRepository(reqOwner, repository.name)
.flatMap {
forkedRepository =>
.flatMap { forkedRepository =>
getPullRequestCommitFromTo(repository, forkedRepository, createPullReqAlt.base, reqBranch) match {
case (Some(commitIdFrom), Some(commitIdTo)) =>
changeIssueToPullRequest(repository.owner, repository.name, createPullReqAlt.issue)
@@ -190,10 +187,8 @@ trait ApiPullRequestControllerBase extends ControllerBase {
get("/api/v3/repos/:owner/:repository/pulls/:id/commits")(referrersOnly { repository =>
val owner = repository.owner
val name = repository.name
params("id").toIntOpt.flatMap {
issueId =>
getPullRequest(owner, name, issueId) map {
case (issue, pullreq) =>
params("id").toIntOpt.flatMap { issueId =>
getPullRequest(owner, name, issueId) map { case (issue, pullreq) =>
Using.resource(Git.open(getRepositoryDir(owner, name))) { git =>
val oldId = git.getRepository.resolve(pullreq.commitIdFrom)
val newId = git.getRepository.resolve(pullreq.commitIdTo)
@@ -240,8 +235,8 @@ trait ApiPullRequestControllerBase extends ControllerBase {
*/
put("/api/v3/repos/:owner/:repository/pulls/:id/merge")(referrersOnly { repository =>
(for {
//TODO: crash when body is empty
//TODO: Implement sha parameter
// TODO: crash when body is empty
// TODO: Implement sha parameter
data <- extractFromJsonBody[MergeAPullRequest]
issueId <- params("id").toIntOpt
(issue, pullReq) <- getPullRequest(repository.owner, repository.name, issueId)
@@ -273,7 +268,7 @@ trait ApiPullRequestControllerBase extends ControllerBase {
repository,
issueId,
context.loginAccount.get,
data.commit_message.getOrElse(""), //TODO: Implement commit_title
data.commit_message.getOrElse(""), // TODO: Implement commit_title
strategy,
pullReq.isDraft,
context.settings

View File

@@ -119,8 +119,7 @@ trait ApiReleaseControllerBase extends ControllerBase {
* ix. Upload a release asset
* https://developer.github.com/v3/repos/releases/#upload-a-release-asset
*/
post("/api/v3/repos/:owner/:repository/releases/:tag/assets")(writableUsersOnly {
repository =>
post("/api/v3/repos/:owner/:repository/releases/:tag/assets")(writableUsersOnly { repository =>
val name = params("name")
val tag = params("tag")
getRelease(repository.owner, repository.name, tag)

View File

@@ -47,8 +47,7 @@ trait ApiRepositoryBranchControllerBase extends ControllerBase {
* https://docs.github.com/en/rest/reference/repos#get-a-branch
*/
get("/api/v3/repos/:owner/:repository/branches/*")(referrersOnly { repository =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
(for {
branch <- params.get("splat") if repository.branchList.contains(branch)
br <- getBranches(
@@ -275,8 +274,7 @@ trait ApiRepositoryBranchControllerBase extends ControllerBase {
*/
patch("/api/v3/repos/:owner/:repository/branches/*")(ownerOnly { repository =>
import gitbucket.core.api._
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
(for {
branch <- params.get("splat") if repository.branchList.contains(branch)
protection <- extractFromJsonBody[ApiBranchProtection.EnablingAndDisabling].map(_.protection)

View File

@@ -43,11 +43,9 @@ trait ApiRepositoryCommitControllerBase extends ControllerBase {
val path = params.get("path").filter(_.nonEmpty)
val since = params.get("since").filter(_.nonEmpty)
val until = params.get("until").filter(_.nonEmpty)
Using.resource(Git.open(getRepositoryDir(owner, name))) {
git =>
Using.resource(Git.open(getRepositoryDir(owner, name))) { git =>
val repo = git.getRepository
Using.resource(new RevWalk(repo)) {
revWalk =>
Using.resource(new RevWalk(repo)) { revWalk =>
val objectId = repo.resolve(sha)
revWalk.markStart(revWalk.parseCommit(objectId))
if (path.nonEmpty) {
@@ -80,8 +78,7 @@ trait ApiRepositoryCommitControllerBase extends ControllerBase {
revfilters(0)
}
)
JsonFormat(revWalk.asScala.map {
commit =>
JsonFormat(revWalk.asScala.map { commit =>
val commitInfo = new CommitInfo(commit)
ApiCommits(
repositoryName = RepositoryName(repository),
@@ -105,8 +102,7 @@ trait ApiRepositoryCommitControllerBase extends ControllerBase {
val name = repository.name
val sha = params("sha")
Using.resource(Git.open(getRepositoryDir(owner, name))) {
git =>
Using.resource(Git.open(getRepositoryDir(owner, name))) { git =>
val repo = git.getRepository
val objectId = repo.resolve(sha)
val commitInfo = Using.resource(new RevWalk(repo)) { revWalk =>

View File

@@ -19,8 +19,7 @@ trait ApiRepositoryContentsControllerBase extends ControllerBase {
* https://docs.github.com/en/rest/reference/repos#get-a-repository-readme
*/
get("/api/v3/repos/:owner/:repository/readme")(referrersOnly { repository =>
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) {
git =>
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { git =>
val refStr = params.getOrElse("ref", repository.repository.defaultBranch)
val files = getFileList(git, refStr, ".", maxFiles = context.settings.repositoryViewer.maxFiles)
files // files should be sorted alphabetically.
@@ -134,8 +133,7 @@ trait ApiRepositoryContentsControllerBase extends ControllerBase {
* requested #2112
*/
put("/api/v3/repos/:owner/:repository/contents/*")(writableUsersOnly { repository =>
context.withLoginAccount {
loginAccount =>
context.withLoginAccount { loginAccount =>
JsonFormat(for {
data <- extractFromJsonBody[CreateAFile]
} yield {
@@ -146,8 +144,7 @@ trait ApiRepositoryContentsControllerBase extends ControllerBase {
}
val paths = multiParams("splat").head.split("/")
val path = paths.take(paths.size - 1).toList.mkString("/")
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) {
git =>
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { git =>
val fileInfo = getFileInfo(git, commit, path, false)
fileInfo match {

View File

@@ -47,8 +47,7 @@ trait ApiRepositoryStatusControllerBase extends ControllerBase {
ref <- params.get("ref")
sha <- JGitUtil.getShaByRef(repository.owner, repository.name, ref)
} yield {
JsonFormat(getCommitStatusesWithCreator(repository.owner, repository.name, sha).map {
case (status, creator) =>
JsonFormat(getCommitStatusesWithCreator(repository.owner, repository.name, sha).map { case (status, creator) =>
ApiCommitStatus(status, ApiUser(creator))
})
}) getOrElse NotFound()

View File

@@ -40,8 +40,8 @@ case class CustomField(
)
trait CustomFieldBehavior {
def createHtml(repository: RepositoryInfo, fieldId: Int, fieldName: String, constraints: Option[String])(
implicit context: Context
def createHtml(repository: RepositoryInfo, fieldId: Int, fieldName: String, constraints: Option[String])(implicit
context: Context
): String
def fieldHtml(
repository: RepositoryInfo,
@@ -51,8 +51,8 @@ trait CustomFieldBehavior {
constraints: Option[String],
value: String,
editable: Boolean
)(
implicit context: Context
)(implicit
context: Context
): String
def validate(name: String, constraints: Option[String], value: String, messages: Messages): Option[String]
}
@@ -181,10 +181,8 @@ object CustomFieldBehavior {
s"""<li><a href="javascript:void(0);" class="custom-field-option-$fieldId" data-value=""><i class="octicon octicon-x"></i> Clear ${StringUtil
.escapeHtml(fieldName)}</a></li>"""
)
constraints.foreach {
x =>
x.split(",").map(_.trim).foreach {
item =>
constraints.foreach { x =>
x.split(",").map(_.trim).foreach { item =>
options.append(s"""<li>
| <a href="javascript:void(0);" class="custom-field-option-$fieldId" data-value="${StringUtil
.escapeHtml(item)}">
@@ -296,8 +294,8 @@ object CustomFieldBehavior {
constraints: Option[String],
value: String,
editable: Boolean
)(
implicit context: Context
)(implicit
context: Context
): String = {
val sb = new StringBuilder
if (value.nonEmpty) {

View File

@@ -53,8 +53,7 @@ trait RepositoryComponent extends TemplateComponent { self: Profile =>
safeMode
)
).shaped.<>(
{
case (repository, options) =>
{ case (repository, options) =>
Repository(
repository._1,
repository._2,
@@ -70,7 +69,8 @@ trait RepositoryComponent extends TemplateComponent { self: Profile =>
repository._12,
RepositoryOptions.tupled.apply(options)
)
}, { (r: Repository) =>
},
{ (r: Repository) =>
Some(
(
(

View File

@@ -41,8 +41,8 @@ trait GitRepositoryFilter {
* @param session the database session
* @return true if allow accessing to repository, otherwise false.
*/
def filter(path: String, userName: Option[String], settings: SystemSettings, isUpdating: Boolean)(
implicit session: Session
def filter(path: String, userName: Option[String], settings: SystemSettings, isUpdating: Boolean)(implicit
session: Session
): Boolean
}

View File

@@ -9,16 +9,16 @@ import profile.api._
trait IssueHook {
def created(issue: Issue, repository: RepositoryInfo)(implicit session: Session, context: Context): Unit = ()
def addedComment(commentId: Int, content: String, issue: Issue, repository: RepositoryInfo)(
implicit session: Session,
def addedComment(commentId: Int, content: String, issue: Issue, repository: RepositoryInfo)(implicit
session: Session,
context: Context
): Unit = ()
def deletedComment(commentId: Int, issue: Issue, repository: RepositoryInfo)(
implicit session: Session,
def deletedComment(commentId: Int, issue: Issue, repository: RepositoryInfo)(implicit
session: Session,
context: Context
): Unit = ()
def updatedComment(commentId: Int, content: String, issue: Issue, repository: RepositoryInfo)(
implicit session: Session,
def updatedComment(commentId: Int, content: String, issue: Issue, repository: RepositoryInfo)(implicit
session: Session,
context: Context
): Unit = ()
def closed(issue: Issue, repository: RepositoryInfo)(implicit session: Session, context: Context): Unit = ()
@@ -29,12 +29,12 @@ trait IssueHook {
assigner: Option[String],
assigned: Option[String],
oldAssigned: Option[String]
)(
implicit session: Session,
)(implicit
session: Session,
context: Context
): Unit = ()
def closedByCommitComment(issue: Issue, repository: RepositoryInfo, message: String, pusher: Account)(
implicit session: Session
def closedByCommitComment(issue: Issue, repository: RepositoryInfo, message: String, pusher: Account)(implicit
session: Session
): Unit = ()
}

View File

@@ -340,24 +340,19 @@ abstract class Plugin {
* Register plugin functionality to PluginRegistry.
*/
def initialize(registry: PluginRegistry, context: ServletContext, settings: SystemSettings): Unit = {
(images ++ images(registry, context, settings)).foreach {
case (id, in) =>
(images ++ images(registry, context, settings)).foreach { case (id, in) =>
registry.addImage(id, in)
}
(controllers ++ controllers(registry, context, settings)).foreach {
case (path, controller) =>
(controllers ++ controllers(registry, context, settings)).foreach { case (path, controller) =>
registry.addController(path, controller)
}
(anonymousAccessiblePaths ++ anonymousAccessiblePaths(registry, context, settings)).foreach {
case (path) =>
(anonymousAccessiblePaths ++ anonymousAccessiblePaths(registry, context, settings)).foreach { case (path) =>
registry.addAnonymousAccessiblePath(path)
}
(javaScripts ++ javaScripts(registry, context, settings)).foreach {
case (path, script) =>
(javaScripts ++ javaScripts(registry, context, settings)).foreach { case (path, script) =>
registry.addJavaScript(path, script)
}
(renderers ++ renderers(registry, context, settings)).foreach {
case (extension, renderer) =>
(renderers ++ renderers(registry, context, settings)).foreach { case (extension, renderer) =>
registry.addRenderer(extension, renderer)
}
(repositoryRoutings ++ repositoryRoutings(registry, context, settings)).foreach { routing =>

View File

@@ -80,7 +80,7 @@ class PluginRegistry {
def getAnonymousAccessiblePaths(): Seq[String] = anonymousAccessiblePaths.asScala.toSeq
def addJavaScript(path: String, script: String): Unit =
javaScripts.add((path, script)) //javaScripts += ((path, script))
javaScripts.add((path, script)) // javaScripts += ((path, script))
def getJavaScript(currentPath: String): List[String] =
javaScripts.asScala.filter(x => currentPath.matches(x._1)).toList.map(_._2)

View File

@@ -13,8 +13,8 @@ trait ReceiveHook {
command: ReceiveCommand,
pusher: String,
mergePullRequest: Boolean
)(
implicit session: Session
)(implicit
session: Session
): Option[String] = None
def postReceive(
@@ -24,8 +24,8 @@ trait ReceiveHook {
command: ReceiveCommand,
pusher: String,
mergePullRequest: Boolean
)(
implicit session: Session
)(implicit
session: Session
): Unit = ()
}

View File

@@ -37,8 +37,7 @@ trait AccessTokenService {
def getAccountByAccessToken(token: String)(implicit s: Session): Option[Account] =
Accounts
.join(AccessTokens)
.filter {
case (ac, t) =>
.filter { case (ac, t) =>
(ac.userName === t.userName) && (t.tokenHash === tokenToHash(token).bind) && (ac.removed === false.bind)
}
.map { case (ac, t) => ac }

View File

@@ -51,8 +51,8 @@ trait AccountFederationService {
* @param preferredUserName Username
* @return Available username
*/
def findAvailableUserName(preferredUserName: Option[String], mailAddress: String)(
implicit s: Session
def findAvailableUserName(preferredUserName: Option[String], mailAddress: String)(implicit
s: Session
): Option[String] = {
preferredUserName
.flatMap(n => extractSafeStringForUserName(n))

View File

@@ -19,8 +19,8 @@ trait AccountService {
private val logger = LoggerFactory.getLogger(classOf[AccountService])
def authenticate(settings: SystemSettings, userName: String, password: String)(
implicit s: Session
def authenticate(settings: SystemSettings, userName: String, password: String)(implicit
s: Session
): Option[Account] = {
val account = if (password.isEmpty) {
None
@@ -58,8 +58,8 @@ trait AccountService {
/**
* Authenticate by LDAP.
*/
private def ldapAuthentication(settings: SystemSettings, userName: String, password: String)(
implicit s: Session
private def ldapAuthentication(settings: SystemSettings, userName: String, password: String)(implicit
s: Session
): Option[Account] = {
LDAPUtil.authenticate(settings.ldap.get, userName, password) match {
case Right(ldapUserInfo) => {
@@ -112,15 +112,15 @@ trait AccountService {
def getAccountByUserName(userName: String, includeRemoved: Boolean = false)(implicit s: Session): Option[Account] =
Accounts filter (t => (t.userName === userName.bind).&&(t.removed === false.bind, !includeRemoved)) firstOption
def getAccountByUserNameIgnoreCase(userName: String, includeRemoved: Boolean = false)(
implicit s: Session
def getAccountByUserNameIgnoreCase(userName: String, includeRemoved: Boolean = false)(implicit
s: Session
): Option[Account] =
Accounts filter (
t => (t.userName.toLowerCase === userName.toLowerCase.bind).&&(t.removed === false.bind, !includeRemoved)
Accounts filter (t =>
(t.userName.toLowerCase === userName.toLowerCase.bind).&&(t.removed === false.bind, !includeRemoved)
) firstOption
def getAccountsByUserNames(userNames: Set[String], knowns: Set[Account], includeRemoved: Boolean = false)(
implicit s: Session
def getAccountsByUserNames(userNames: Set[String], knowns: Set[Account], includeRemoved: Boolean = false)(implicit
s: Session
): Map[String, Account] = {
val map = knowns.map(a => a.userName -> a).toMap
val needs = userNames -- map.keySet
@@ -135,17 +135,15 @@ trait AccountService {
}
}
def getAccountByMailAddress(mailAddress: String, includeRemoved: Boolean = false)(
implicit s: Session
def getAccountByMailAddress(mailAddress: String, includeRemoved: Boolean = false)(implicit
s: Session
): Option[Account] =
(Accounts joinLeft AccountExtraMailAddresses on { case (a, e) => a.userName === e.userName })
.filter {
case (a, x) =>
.filter { case (a, x) =>
((a.mailAddress.toLowerCase === mailAddress.toLowerCase.bind) ||
(x.map { e =>
e.extraMailAddress.toLowerCase === mailAddress.toLowerCase.bind
}
.getOrElse(false.bind))).&&(a.removed === false.bind, !includeRemoved)
}.getOrElse(false.bind))).&&(a.removed === false.bind, !includeRemoved)
}
.map { case (a, e) => a } firstOption
@@ -267,8 +265,8 @@ trait AccountService {
group
}
def updateGroup(groupName: String, description: Option[String], url: Option[String], removed: Boolean)(
implicit s: Session
def updateGroup(groupName: String, description: Option[String], url: Option[String], removed: Boolean)(implicit
s: Session
): Unit =
Accounts
.filter(_.userName === groupName.bind)
@@ -277,8 +275,7 @@ trait AccountService {
def updateGroupMembers(groupName: String, members: List[(String, Boolean)])(implicit s: Session): Unit = {
GroupMembers.filter(_.groupName === groupName.bind).delete
members.foreach {
case (userName, isManager) =>
members.foreach { case (userName, isManager) =>
GroupMembers insert GroupMember(groupName, userName, isManager)
}
}
@@ -318,8 +315,8 @@ trait AccountService {
/*
* For account preference
*/
def getAccountPreference(userName: String)(
implicit s: Session
def getAccountPreference(userName: String)(implicit
s: Session
): Option[AccountPreference] = {
AccountPreferences filter (_.byPrimaryKey(userName)) firstOption
}

View File

@@ -43,8 +43,7 @@ trait ActivityService {
def getRecentActivitiesByRepos(repos: Set[(String, String)])(implicit context: Context): List[Activity] = {
getActivities(includePublic = true) { activity =>
repos.exists {
case (userName, repositoryName) =>
repos.exists { case (userName, repositoryName) =>
activity.userName == userName && activity.repositoryName == repositoryName
}
}
@@ -65,10 +64,12 @@ trait ActivityService {
.get()
) { reader =>
var json: String = null
while (list.length < 50 && {
while (
list.length < 50 && {
json = reader.readLine();
json
} != null) {
} != null
) {
val activity = read[Activity](json)
if (filter(activity)) {
list += activity

View File

@@ -47,8 +47,8 @@ trait CommitStatusService {
)
}
def getCommitStatusWithSummary(userName: String, repositoryName: String, sha: String)(
implicit s: Session
def getCommitStatusWithSummary(userName: String, repositoryName: String, sha: String)(implicit
s: Session
): Option[(CommitState, List[CommitStatus])] = {
val statuses = getCommitStatuses(userName, repositoryName, sha)
if (statuses.isEmpty) {
@@ -62,18 +62,18 @@ trait CommitStatusService {
def getCommitStatus(userName: String, repositoryName: String, id: Int)(implicit s: Session): Option[CommitStatus] =
CommitStatuses.filter(t => t.byPrimaryKey(id) && t.byRepository(userName, repositoryName)).firstOption
def getCommitStatus(userName: String, repositoryName: String, sha: String, context: String)(
implicit s: Session
def getCommitStatus(userName: String, repositoryName: String, sha: String, context: String)(implicit
s: Session
): Option[CommitStatus] =
CommitStatuses.filter(t => t.byCommit(userName, repositoryName, sha) && t.context === context.bind).firstOption
def getCommitStatuses(userName: String, repositoryName: String, sha: String)(
implicit s: Session
def getCommitStatuses(userName: String, repositoryName: String, sha: String)(implicit
s: Session
): List[CommitStatus] =
byCommitStatus(userName, repositoryName, sha).list
def getRecentStatusContexts(userName: String, repositoryName: String, time: java.util.Date)(
implicit s: Session
def getRecentStatusContexts(userName: String, repositoryName: String, time: java.util.Date)(implicit
s: Session
): List[String] =
CommitStatuses
.filter(t => t.byRepository(userName, repositoryName))
@@ -82,8 +82,8 @@ trait CommitStatusService {
.map(_._1)
.list
def getCommitStatusesWithCreator(userName: String, repositoryName: String, sha: String)(
implicit s: Session
def getCommitStatusesWithCreator(userName: String, repositoryName: String, sha: String)(implicit
s: Session
): List[(CommitStatus, Account)] =
byCommitStatus(userName, repositoryName, sha)
.join(Accounts)

View File

@@ -18,8 +18,8 @@ import org.apache.commons.io.FileUtils
trait CommitsService {
self: ActivityService with PullRequestService with WebHookPullRequestReviewCommentService =>
def getCommitComments(owner: String, repository: String, commitId: String, includePullRequest: 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.issueId.isEmpty || includePullRequest)
@@ -79,8 +79,7 @@ trait CommitsService {
val comment = getCommitComment(repository.owner, repository.name, commentId.toString).get
issueId match {
case Some(issueId) =>
getPullRequest(repository.owner, repository.name, issueId).foreach {
case (issue, pullRequest) =>
getPullRequest(repository.owner, repository.name, issueId).foreach { case (issue, pullRequest) =>
val pullRequestCommentInfo =
PullRequestCommentInfo(repository.owner, repository.name, loginAccount.userName, content, issueId)
recordActivity(pullRequestCommentInfo)
@@ -104,8 +103,8 @@ trait CommitsService {
commentId
}
def updateCommitCommentPosition(commentId: Int, commitId: String, oldLine: Option[Int], newLine: Option[Int])(
implicit s: Session
def updateCommitCommentPosition(commentId: Int, commitId: String, oldLine: Option[Int], newLine: Option[Int])(implicit
s: Session
): Unit =
CommitComments
.filter(_.byPrimaryKey(commentId))

View File

@@ -9,8 +9,8 @@ trait CustomFieldsService {
def getCustomFields(owner: String, repository: String)(implicit s: Session): List[CustomField] =
CustomFields.filter(_.byRepository(owner, repository)).sortBy(_.fieldId asc).list
def getCustomFieldsWithValue(owner: String, repository: String, issueId: Int)(
implicit s: Session
def getCustomFieldsWithValue(owner: String, repository: String, issueId: Int)(implicit
s: Session
): List[(CustomField, Option[IssueCustomField])] = {
CustomFields
.filter(_.byRepository(owner, repository))
@@ -52,8 +52,8 @@ trait CustomFieldsService {
constraints: Option[String],
enableForIssues: Boolean,
enableForPullRequests: Boolean
)(
implicit s: Session
)(implicit
s: Session
): Unit =
CustomFields
.filter(_.byPrimaryKey(owner, repository, fieldId))

View File

@@ -17,8 +17,7 @@ trait GpgKeyService {
def addGpgPublicKey(userName: String, title: String, publicKey: String)(implicit s: Session): Unit = {
val pubKeyOf = new BcPGPObjectFactory(new ArmoredInputStream(new ByteArrayInputStream(publicKey.getBytes)))
pubKeyOf.iterator().asScala.foreach {
case keyRing: PGPPublicKeyRing =>
pubKeyOf.iterator().asScala.foreach { case keyRing: PGPPublicKeyRing =>
val key = keyRing.getPublicKey()
GpgKeys.insert(GpgKey(userName = userName, gpgKeyId = key.getKeyID, title = title, publicKey = publicKey))
}

View File

@@ -134,8 +134,8 @@ trait HandleCommentService {
}
}
def deleteCommentByApi(repoInfo: RepositoryInfo, comment: IssueComment, issue: Issue)(
implicit context: Context,
def deleteCommentByApi(repoInfo: RepositoryInfo, comment: IssueComment, issue: Issue)(implicit
context: Context,
s: Session
): Option[IssueComment] = context.loginAccount.flatMap { _ =>
comment.action match {

View File

@@ -41,8 +41,8 @@ trait IssuesService {
IssueComments filter (_.byIssue(owner, repository, issueId)) sortBy (_.commentId asc) list
/** @return IssueComment and commentedUser and Issue */
def getCommentsForApi(owner: String, repository: String, issueId: Int)(
implicit s: Session
def getCommentsForApi(owner: String, repository: String, issueId: Int)(implicit
s: Session
): List[(IssueComment, Account, Issue)] =
IssueComments
.filter(_.byIssue(owner, repository, issueId))
@@ -54,8 +54,8 @@ trait IssuesService {
.map { case t1 ~ t2 ~ t3 => (t1, t2, t3) }
.list
def getMergedComment(owner: String, repository: String, issueId: Int)(
implicit s: Session
def getMergedComment(owner: String, repository: String, issueId: Int)(implicit
s: Session
): Option[(IssueComment, Account)] = {
IssueComments
.filter(_.byIssue(owner, repository, issueId))
@@ -74,8 +74,8 @@ trait IssuesService {
else None
}
def getCommentForApi(owner: String, repository: String, commentId: Int)(
implicit s: Session
def getCommentForApi(owner: String, repository: String, commentId: Int)(implicit
s: Session
): Option[(IssueComment, Account, Issue)] =
IssueComments
.filter(_.byRepository(owner, repository))
@@ -91,8 +91,7 @@ trait IssuesService {
def getIssueLabels(owner: String, repository: String, issueId: Int)(implicit s: Session): List[Label] = {
IssueLabels
.join(Labels)
.on {
case t1 ~ t2 =>
.on { case t1 ~ t2 =>
t1.byLabel(t2.userName, t2.repositoryName, t2.labelId)
}
.filter { case t1 ~ t2 => t1.byIssue(owner, repository, issueId) }
@@ -100,8 +99,8 @@ trait IssuesService {
.list
}
def getIssueLabel(owner: String, repository: String, issueId: Int, labelId: Int)(
implicit s: Session
def getIssueLabel(owner: String, repository: String, issueId: Int, labelId: Int)(implicit
s: Session
): Option[IssueLabel] = {
IssueLabels filter (_.byPrimaryKey(owner, repository, issueId, labelId)) firstOption
}
@@ -114,8 +113,8 @@ trait IssuesService {
* @param repos Tuple of the repository owner and the repository name
* @return the count of the search result
*/
def countIssue(condition: IssueSearchCondition, searchOption: IssueSearchOption, repos: (String, String)*)(
implicit s: Session
def countIssue(condition: IssueSearchCondition, searchOption: IssueSearchOption, repos: (String, String)*)(implicit
s: Session
): Int = {
Query(searchIssueQuery(repos, condition, searchOption).length).first
}
@@ -136,21 +135,17 @@ trait IssuesService {
searchIssueQuery(Seq(owner -> repository), condition.copy(labels = Set.empty), IssueSearchOption.Issues)
.join(IssueLabels)
.on {
case t1 ~ t2 =>
.on { case t1 ~ t2 =>
t1.byIssue(t2.userName, t2.repositoryName, t2.issueId)
}
.join(Labels)
.on {
case t1 ~ t2 ~ t3 =>
.on { case t1 ~ t2 ~ t3 =>
t2.byLabel(t3.userName, t3.repositoryName, t3.labelId)
}
.groupBy {
case t1 ~ t2 ~ t3 =>
.groupBy { case t1 ~ t2 ~ t3 =>
t3.labelName
}
.map {
case (labelName, t) =>
.map { case (labelName, t) =>
labelName -> t.length
}
.list
@@ -173,16 +168,13 @@ trait IssuesService {
searchIssueQuery(Seq(owner -> repository), condition.copy(labels = Set.empty), IssueSearchOption.Issues)
.join(Priorities)
.on {
case t1 ~ t2 =>
.on { case t1 ~ t2 =>
t1.byPriority(t2.userName, t2.repositoryName, t2.priorityId)
}
.groupBy {
case t1 ~ t2 =>
.groupBy { case t1 ~ t2 =>
t2.priorityName
}
.map {
case (priorityName, t) =>
.map { case (priorityName, t) =>
priorityName -> t.length
}
.list
@@ -221,8 +213,7 @@ trait IssuesService {
.joinLeft(IssueAssignees)
.on { case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 ~ t6 ~ t7 ~ t8 => t1.byIssue(t8.userName, t8.repositoryName, t8.issueId) }
.sortBy { case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 ~ t6 ~ t7 ~ t8 => i asc }
.map {
case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 ~ t6 ~ t7 ~ t8 =>
.map { case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 ~ t6 ~ t7 ~ t8 =>
(
t1,
t2.commentCount,
@@ -264,8 +255,8 @@ trait IssuesService {
/** for api
* @return (issue, issueUser, Seq(assigneeUsers))
*/
def searchIssueByApi(condition: IssueSearchCondition, offset: Int, limit: Int, repos: (String, String)*)(
implicit s: Session
def searchIssueByApi(condition: IssueSearchCondition, offset: Int, limit: Int, repos: (String, String)*)(implicit
s: Session
): List[(Issue, Account, List[Account])] = {
// get issues and comment count and labels
searchIssueQueryBase(condition, IssueSearchOption.Issues, offset, limit, repos)
@@ -278,12 +269,10 @@ trait IssuesService {
.sortBy { case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 => i asc }
.map { case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 => (t1, t3, t5) }
.list
.groupBy {
case (issue, account, _) =>
.groupBy { case (issue, account, _) =>
(issue, account)
}
.map {
case (_, values) =>
.map { case (_, values) =>
(values.head._1, values.head._2, values.flatMap(_._3))
}
.toList
@@ -312,12 +301,10 @@ trait IssuesService {
.sortBy { case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 ~ t6 ~ t7 ~ t8 => i asc }
.map { case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 ~ t6 ~ t7 ~ t8 => (t1, t5, t2.commentCount, t3, t4, t6, t8) }
.list
.groupBy {
case (issue, openedUser, commentCount, pullRequest, repository, account, assignedUser) =>
.groupBy { case (issue, openedUser, commentCount, pullRequest, repository, account, assignedUser) =>
(issue, openedUser, commentCount, pullRequest, repository, account)
}
.map {
case (_, values) =>
.map { case (_, values) =>
(
values.head._1,
values.head._2,
@@ -344,8 +331,7 @@ trait IssuesService {
t1.byIssue(t2.userName, t2.repositoryName, t2.issueId)
}
.sortBy { case (t1, t2) => t1.issueId desc }
.sortBy {
case (t1, t2) =>
.sortBy { case (t1, t2) =>
condition.sort match {
case "created" =>
condition.direction match {
@@ -380,8 +366,8 @@ trait IssuesService {
repos: Seq[(String, String)],
condition: IssueSearchCondition,
searchOption: IssueSearchOption
)(
implicit s: Session
)(implicit
s: Session
) = {
val query = Issues filter { t1 =>
(if (repos.sizeIs == 1) {
@@ -395,7 +381,7 @@ trait IssuesService {
case _ => t1.closed === true || t1.closed === false
}).&&(t1.milestoneId.? isEmpty, condition.milestone.contains(None))
.&&(t1.priorityId.? isEmpty, condition.priority.contains(None))
//.&&(t1.assignedUserName.? isEmpty, condition.assigned == Some(None))
// .&&(t1.assignedUserName.? isEmpty, condition.assigned == Some(None))
.&&(t1.openedUserName === condition.author.get.bind, condition.author.isDefined) &&
(searchOption match {
case IssueSearchOption.Issues => t1.pullRequest === false
@@ -451,17 +437,24 @@ trait IssuesService {
// Mentioned filter
.&&(
(t1.openedUserName === condition.mentioned.get.bind) || (IssueAssignees filter { t1 =>
t1.byIssue(t1.userName, t1.repositoryName, t1.issueId) && t1.assigneeUserName === condition.mentioned.get.bind
t1.byIssue(
t1.userName,
t1.repositoryName,
t1.issueId
) && t1.assigneeUserName === condition.mentioned.get.bind
} exists) ||
(IssueComments filter { t2 =>
(t2.byIssue(t1.userName, t1.repositoryName, t1.issueId)) && (t2.commentedUserName === condition.mentioned.get.bind)
(t2.byIssue(
t1.userName,
t1.repositoryName,
t1.issueId
)) && (t2.commentedUserName === condition.mentioned.get.bind)
} exists),
condition.mentioned.isDefined
)
}
condition.others.foldLeft(query) {
case (query, cond) =>
condition.others.foldLeft(query) { case (query, cond) =>
def condQuery(f: Rep[String] => Rep[Boolean]): Query[Profile.Issues, Issue, Seq] = {
query.filter { t1 =>
IssueCustomFields
@@ -469,8 +462,7 @@ trait IssuesService {
.on { (t2, t3) =>
t2.userName === t3.userName && t2.repositoryName === t3.repositoryName && t2.fieldId === t3.fieldId
}
.filter {
case (t2, t3) =>
.filter { case (t2, t3) =>
t1.byIssue(t2.userName, t2.repositoryName, t2.issueId) && t3.fieldName === cond.name.bind && f(
t2.value
)
@@ -527,7 +519,8 @@ trait IssuesService {
}
def registerIssueLabel(owner: String, repository: String, issueId: Int, labelId: Int, insertComment: Boolean = false)(
implicit context: Context,
implicit
context: Context,
s: Session
): Int = {
if (insertComment) {
@@ -546,7 +539,8 @@ trait IssuesService {
}
def deleteIssueLabel(owner: String, repository: String, issueId: Int, labelId: Int, insertComment: Boolean = false)(
implicit context: Context,
implicit
context: Context,
s: Session
): Int = {
if (insertComment) {
@@ -564,8 +558,8 @@ trait IssuesService {
IssueLabels filter (_.byPrimaryKey(owner, repository, issueId, labelId)) delete
}
def deleteAllIssueLabels(owner: String, repository: String, issueId: Int, insertComment: Boolean = false)(
implicit context: Context,
def deleteAllIssueLabels(owner: String, repository: String, issueId: Int, insertComment: Boolean = false)(implicit
context: Context,
s: Session
): Int = {
if (insertComment) {
@@ -604,8 +598,8 @@ trait IssuesService {
)
}
def updateIssue(owner: String, repository: String, issueId: Int, title: String, content: Option[String])(
implicit s: Session
def updateIssue(owner: String, repository: String, issueId: Int, title: String, content: Option[String])(implicit
s: Session
): Int = {
Issues
.filter(_.byPrimaryKey(owner, repository, issueId))
@@ -624,8 +618,8 @@ trait IssuesService {
.update(true)
}
def getIssueAssignees(owner: String, repository: String, issueId: Int)(
implicit s: Session
def getIssueAssignees(owner: String, repository: String, issueId: Int)(implicit
s: Session
): List[IssueAssignee] = {
IssueAssignees.filter(_.byIssue(owner, repository, issueId)).sortBy(_.assigneeUserName).list
}
@@ -636,8 +630,8 @@ trait IssuesService {
issueId: Int,
assigneeUserName: String,
insertComment: Boolean = false
)(
implicit context: Context,
)(implicit
context: Context,
s: Session
): Int = {
val assigner = context.loginAccount.map(_.userName)
@@ -665,8 +659,8 @@ trait IssuesService {
issueId: Int,
assigneeUserName: String,
insertComment: Boolean = false
)(
implicit context: Context,
)(implicit
context: Context,
s: Session
): Int = {
val assigner = context.loginAccount.map(_.userName)
@@ -688,8 +682,8 @@ trait IssuesService {
IssueAssignees filter (_.byPrimaryKey(owner, repository, issueId, assigneeUserName)) delete
}
def deleteAllIssueAssignees(owner: String, repository: String, issueId: Int, insertComment: Boolean = false)(
implicit context: Context,
def deleteAllIssueAssignees(owner: String, repository: String, issueId: Int, insertComment: Boolean = false)(implicit
context: Context,
s: Session
): Int = {
val assigner = context.loginAccount.map(_.userName)
@@ -773,15 +767,15 @@ trait IssuesService {
.update(priorityId, currentDate)
}
def updateComment(owner: String, repository: String, issueId: Int, commentId: Int, content: String)(
implicit s: Session
def updateComment(owner: String, repository: String, issueId: Int, commentId: Int, content: String)(implicit
s: Session
): Int = {
Issues.filter(_.byPrimaryKey(owner, repository, issueId)).map(_.updatedDate).update(currentDate)
IssueComments.filter(_.byPrimaryKey(commentId)).map(t => (t.content, t.updatedDate)).update(content, currentDate)
}
def deleteComment(owner: String, repository: String, issueId: Int, commentId: Int)(
implicit context: Context,
def deleteComment(owner: String, repository: String, issueId: Int, commentId: Int)(implicit
context: Context,
s: Session
): Int = {
Issues.filter(_.byPrimaryKey(owner, repository, issueId)).map(_.updatedDate).update(currentDate)
@@ -820,10 +814,10 @@ trait IssuesService {
* @param query the keywords separated by whitespace.
* @return issues with comment count and matched content of issue or comment
*/
def searchIssuesByKeyword(owner: String, repository: String, query: String, pullRequest: Boolean)(
implicit s: Session
def searchIssuesByKeyword(owner: String, repository: String, query: String, pullRequest: Boolean)(implicit
s: Session
): List[(Issue, Int, String)] = {
//import slick.driver.JdbcDriver.likeEncode
// import slick.driver.JdbcDriver.likeEncode
val keywords = splitWords(query.toLowerCase)
// Search Issue
@@ -832,12 +826,10 @@ trait IssuesService {
t.byRepository(owner, repository) && t.pullRequest === pullRequest.bind
}
.join(IssueOutline)
.on {
case (t1, t2) =>
.on { case (t1, t2) =>
t1.byIssue(t2.userName, t2.repositoryName, t2.issueId)
}
.filter {
case (t1, t2) =>
.filter { case (t1, t2) =>
keywords
.map { keyword =>
(t1.title.toLowerCase.like(s"%${likeEncode(keyword)}%", '^')) ||
@@ -845,8 +837,7 @@ trait IssuesService {
}
.reduceLeft(_ && _)
}
.map {
case (t1, t2) =>
.map { case (t1, t2) =>
(t1, 0, t1.content.?, t2.commentCount)
}
@@ -854,17 +845,14 @@ trait IssuesService {
val comments = IssueComments
.filter(_.byRepository(owner, repository))
.join(Issues)
.on {
case (t1, t2) =>
.on { case (t1, t2) =>
t1.byIssue(t2.userName, t2.repositoryName, t2.issueId)
}
.join(IssueOutline)
.on {
case ((t1, t2), t3) =>
.on { case ((t1, t2), t3) =>
t2.byIssue(t3.userName, t3.repositoryName, t3.issueId)
}
.filter {
case ((t1, t2), t3) =>
.filter { case ((t1, t2), t3) =>
t2.pullRequest === pullRequest.bind &&
keywords
.map { query =>
@@ -872,20 +860,17 @@ trait IssuesService {
}
.reduceLeft(_ && _)
}
.map {
case ((t1, t2), t3) =>
.map { case ((t1, t2), t3) =>
(t2, t1.commentId, t1.content.?, t3.commentCount)
}
issues
.union(comments)
.sortBy {
case (issue, commentId, _, _) =>
.sortBy { case (issue, commentId, _, _) =>
issue.issueId.desc -> commentId
}
.list
.splitWith {
case ((issue1, _, _, _), (issue2, _, _, _)) =>
.splitWith { case ((issue1, _, _, _), (issue2, _, _, _)) =>
issue1.issueId == issue2.issueId
}
.map {
@@ -896,8 +881,8 @@ trait IssuesService {
.toList
}
def closeIssuesFromMessage(message: String, userName: String, owner: String, repository: String)(
implicit s: Session
def closeIssuesFromMessage(message: String, userName: String, owner: String, repository: String)(implicit
s: Session
): Seq[Int] = {
extractCloseId(message).flatMap { issueId =>
for (issue <- getIssue(owner, repository, issueId) if !issue.closed) yield {
@@ -911,8 +896,7 @@ trait IssuesService {
def createReferComment(owner: String, repository: String, fromIssue: Issue, message: String, loginAccount: Account)(
implicit s: Session
): Unit = {
extractGlobalIssueId(message).foreach {
case (_referredOwner, _referredRepository, referredIssueId) =>
extractGlobalIssueId(message).foreach { case (_referredOwner, _referredRepository, referredIssueId) =>
val referredOwner = _referredOwner.getOrElse(owner)
val referredRepository = _referredRepository.getOrElse(repository)
getRepository(referredOwner, referredRepository).foreach { repo =>
@@ -923,12 +907,13 @@ trait IssuesService {
} else {
(s"${fromIssue.issueId}:${owner}:${repository}:${fromIssue.title}", "refer_global")
}
referredIssueId.foreach(
x =>
referredIssueId.foreach(x =>
// Not add if refer comment already exist.
if (!getComments(referredOwner, referredRepository, x.toInt).exists { x =>
if (
!getComments(referredOwner, referredRepository, x.toInt).exists { x =>
(x.action == "refer" || x.action == "refer_global") && x.content == content
}) {
}
) {
createComment(
referredOwner,
referredRepository,
@@ -1090,8 +1075,7 @@ object IssuesService {
dim(0) -> dim(1)
}
.groupBy(_._1)
.map {
case (key, values) =>
.map { case (key, values) =>
key -> values.map(_._2).toSeq
}
@@ -1123,8 +1107,7 @@ object IssuesService {
val dim = x.split(">")
dim(0) -> ("gt", dim(1))
}
.map {
case (key, (operator, value)) =>
.map { case (key, (operator, value)) =>
CustomFieldCondition(key.stripPrefix("custom."), value, operator)
}
.toSeq
@@ -1134,7 +1117,7 @@ object IssuesService {
conditions.get("milestone").flatMap(_.headOption) match {
case None => None
case Some("none") => Some(None)
case Some(x) => Some(Some(x)) //milestones.get(x).map(x => Some(x))
case Some(x) => Some(Some(x)) // milestones.get(x).map(x => Some(x))
},
conditions.get("priority").map(_.headOption), // TODO
conditions.get("author").flatMap(_.headOption),

View File

@@ -30,8 +30,8 @@ trait LabelsService {
createLabel(owner, repository, labelName, color)
}
def updateLabel(owner: String, repository: String, labelId: Int, labelName: String, color: String)(
implicit s: Session
def updateLabel(owner: String, repository: String, labelId: Int, labelName: String, color: String)(implicit
s: Session
): Unit =
Labels
.filter(_.byPrimaryKey(owner, repository, labelId))

View File

@@ -121,8 +121,8 @@ trait MergeService {
afterCommitId: ObjectId,
loginAccount: Account,
settings: SystemSettings
)(
implicit s: Session,
)(implicit
s: Session,
c: JsonFormat.Context
): Unit = {
callWebHookOf(repository.owner, repository.name, WebHook.Push, settings) {
@@ -220,7 +220,14 @@ trait MergeService {
requestRepositoryName: String,
requestBranch: String
): Option[String] =
tryMergeRemote(userName, repositoryName, branch, requestUserName, requestRepositoryName, requestBranch).left.toOption
tryMergeRemote(
userName,
repositoryName,
branch,
requestUserName,
requestRepositoryName,
requestBranch
).left.toOption
def pullRemote(
localRepository: RepositoryInfo,
@@ -236,8 +243,14 @@ trait MergeService {
val localRepositoryName = localRepository.name
val remoteUserName = remoteRepository.owner
val remoteRepositoryName = remoteRepository.name
tryMergeRemote(localUserName, localRepositoryName, localBranch, remoteUserName, remoteRepositoryName, remoteBranch).map {
case (newTreeId, oldBaseId, oldHeadId) =>
tryMergeRemote(
localUserName,
localRepositoryName,
localBranch,
remoteUserName,
remoteRepositoryName,
remoteBranch
).map { case (newTreeId, oldBaseId, oldHeadId) =>
Using.resource(Git.open(getRepositoryDir(localUserName, localRepositoryName))) { git =>
val existIds = JGitUtil.getAllCommitIds(git).toSet
@@ -621,7 +634,8 @@ object MergeService {
def checkConflictForce(): Option[String] = {
val merger = MergeStrategy.RECURSIVE.newMerger(git.getRepository, true)
val conflicted = try {
val conflicted =
try {
!merger.merge(mergeBaseTip, mergeTip)
} catch {
case e: NoMergeBaseException => true

View File

@@ -46,8 +46,8 @@ trait MilestonesService {
def getMilestone(owner: String, repository: String, milestoneId: Int)(implicit s: Session): Option[Milestone] =
Milestones.filter(_.byPrimaryKey(owner, repository, milestoneId)).firstOption
def getMilestonesWithIssueCount(owner: String, repository: String)(
implicit s: Session
def getMilestonesWithIssueCount(owner: String, repository: String)(implicit
s: Session
): List[(Milestone, Int, Int)] = {
val counts = Issues
.filter { t =>
@@ -78,8 +78,7 @@ trait MilestonesService {
def getApiMilestone(repository: RepositoryInfo, milestoneId: Int)(implicit s: Session): Option[ApiMilestone] = {
getMilestonesWithIssueCount(repository.owner, repository.name)
.find(p => p._1.milestoneId == milestoneId)
.map(
milestoneWithIssue =>
.map(milestoneWithIssue =>
ApiMilestone(
repository.repository,
milestoneWithIssue._1,

View File

@@ -59,8 +59,7 @@ trait PrioritiesService {
Priorities
.filter(_.byRepository(owner, repository))
.list
.foreach(
p =>
.foreach(p =>
Priorities
.filter(_.byPrimaryKey(owner, repository, p.priorityId))
.map(_.ordering)
@@ -93,8 +92,7 @@ trait PrioritiesService {
.map(_.isDefault)
.update(false)
priorityId.foreach(
id =>
priorityId.foreach(id =>
Priorities
.filter(_.byPrimaryKey(owner, repository, id))
.map(_.isDefault)

View File

@@ -8,8 +8,8 @@ import org.eclipse.jgit.transport.{ReceiveCommand, ReceivePack}
trait ProtectedBranchService {
import ProtectedBranchService._
private def getProtectedBranchInfoOpt(owner: String, repository: String, branch: String)(
implicit session: Session
private def getProtectedBranchInfoOpt(owner: String, repository: String, branch: String)(implicit
session: Session
): Option[ProtectedBranchInfo] =
ProtectedBranches
.joinLeft(ProtectedBranchContexts)
@@ -22,13 +22,12 @@ trait ProtectedBranchService {
.map { p =>
p._1 -> p._2.flatMap(_._2)
}
.map {
case (t1, contexts) =>
.map { case (t1, contexts) =>
new ProtectedBranchInfo(t1.userName, t1.repositoryName, t1.branch, true, contexts, t1.statusCheckAdmin)
}
def getProtectedBranchInfo(owner: String, repository: String, branch: String)(
implicit session: Session
def getProtectedBranchInfo(owner: String, repository: String, branch: String)(implicit
session: Session
): ProtectedBranchInfo =
getProtectedBranchInfoOpt(owner, repository, branch).getOrElse(
ProtectedBranchInfo.disabled(owner, repository, branch)
@@ -88,9 +87,11 @@ object ProtectedBranchService {
val branch = command.getRefName.stripPrefix("refs/heads/")
if (branch != command.getRefName) {
val repositoryInfo = getRepository(owner, repository)
if (command.getType == ReceiveCommand.Type.DELETE && repositoryInfo.exists(
if (
command.getType == ReceiveCommand.Type.DELETE && repositoryInfo.exists(
_.repository.defaultBranch == branch
)) {
)
) {
Some(s"refusing to delete the branch: ${command.getRefName}.")
} else {
getProtectedBranchInfo(owner, repository, branch).getStopReason(
@@ -128,8 +129,7 @@ object ProtectedBranchService {
def isAdministrator(pusher: String)(implicit session: Session): Boolean =
pusher == owner || getGroupMembers(owner).exists(gm => gm.userName == pusher && gm.isManager) ||
getCollaborators(owner, repository).exists {
case (collaborator, isGroup) =>
getCollaborators(owner, repository).exists { case (collaborator, isGroup) =>
if (collaborator.role == Role.ADMIN.name) {
if (isGroup) {
getGroupMembers(collaborator.collaboratorName).exists(gm => gm.userName == pusher)
@@ -144,8 +144,8 @@ object ProtectedBranchService {
* Can't be deleted
* Can't have changes merged into them until required status checks pass
*/
def getStopReason(isAllowNonFastForwards: Boolean, command: ReceiveCommand, pusher: String)(
implicit session: Session
def getStopReason(isAllowNonFastForwards: Boolean, command: ReceiveCommand, pusher: String)(implicit
session: Session
): Option[String] = {
if (enabled) {
command.getType() match {

View File

@@ -34,8 +34,8 @@ trait PullRequestService {
with ActivityService =>
import PullRequestService._
def getPullRequest(owner: String, repository: String, issueId: Int)(
implicit s: Session
def getPullRequest(owner: String, repository: String, issueId: Int)(implicit
s: Session
): Option[(Issue, PullRequest)] =
getIssue(owner, repository, issueId.toString).flatMap { issue =>
PullRequests.filter(_.byPrimaryKey(owner, repository, issueId)).firstOption.map { pullreq =>
@@ -43,24 +43,24 @@ trait PullRequestService {
}
}
def updateCommitId(owner: String, repository: String, issueId: Int, commitIdTo: String, commitIdFrom: String)(
implicit s: Session
def updateCommitId(owner: String, repository: String, issueId: Int, commitIdTo: String, commitIdFrom: String)(implicit
s: Session
): Unit =
PullRequests
.filter(_.byPrimaryKey(owner, repository, issueId))
.map(pr => pr.commitIdTo -> pr.commitIdFrom)
.update((commitIdTo, commitIdFrom))
def updateDraftToPullRequest(owner: String, repository: String, issueId: Int)(
implicit s: Session
def updateDraftToPullRequest(owner: String, repository: String, issueId: Int)(implicit
s: Session
): Unit =
PullRequests
.filter(_.byPrimaryKey(owner, repository, issueId))
.map(pr => pr.isDraft)
.update(false)
def updateBaseBranch(owner: String, repository: String, issueId: Int, baseBranch: String, commitIdTo: String)(
implicit s: Session
def updateBaseBranch(owner: String, repository: String, issueId: Int, baseBranch: String, commitIdTo: String)(implicit
s: Session
): Unit = {
PullRequests
.filter(_.byPrimaryKey(owner, repository, issueId))
@@ -68,16 +68,15 @@ trait PullRequestService {
.update((baseBranch, commitIdTo))
}
def getPullRequestCountGroupByUser(closed: Boolean, owner: Option[String], repository: Option[String])(
implicit s: Session
def getPullRequestCountGroupByUser(closed: Boolean, owner: Option[String], repository: Option[String])(implicit
s: Session
): List[PullRequestCount] =
PullRequests
.join(Issues)
.on { (t1, t2) =>
t1.byPrimaryKey(t2.userName, t2.repositoryName, t2.issueId)
}
.filter {
case (t1, t2) =>
.filter { case (t1, t2) =>
(t2.closed === closed.bind)
.&&(t1.userName === owner.get.bind, owner.isDefined)
.&&(t1.repositoryName === repository.get.bind, repository.isDefined)
@@ -182,8 +181,7 @@ trait PullRequestService {
.on { (t1, t2) =>
t1.byPrimaryKey(t2.userName, t2.repositoryName, t2.issueId)
}
.filter {
case (t1, t2) =>
.filter { case (t1, t2) =>
(t1.requestUserName === userName.bind)
.&&(t1.requestRepositoryName === repositoryName.bind)
.&&(t1.requestBranch === branch.bind)
@@ -200,8 +198,7 @@ trait PullRequestService {
.on { (t1, t2) =>
t1.byPrimaryKey(t2.userName, t2.repositoryName, t2.issueId)
}
.filter {
case (t1, t2) =>
.filter { case (t1, t2) =>
(t1.requestUserName === userName.bind)
.&&(t1.requestRepositoryName === repositoryName.bind)
.&&(t1.branch === branch.bind)
@@ -217,16 +214,15 @@ trait PullRequestService {
* 2. return if exists pull request to other branch
* 2. return None
*/
def getPullRequestFromBranch(userName: String, repositoryName: String, branch: String, defaultBranch: String)(
implicit s: Session
def getPullRequestFromBranch(userName: String, repositoryName: String, branch: String, defaultBranch: String)(implicit
s: Session
): Option[(PullRequest, Issue)] =
PullRequests
.join(Issues)
.on { (t1, t2) =>
t1.byPrimaryKey(t2.userName, t2.repositoryName, t2.issueId)
}
.filter {
case (t1, t2) =>
.filter { case (t1, t2) =>
(t1.requestUserName === userName.bind) &&
(t1.requestRepositoryName === repositoryName.bind) &&
(t1.requestBranch === branch.bind) &&
@@ -247,8 +243,8 @@ trait PullRequestService {
pusherAccount: Account,
action: String,
settings: SystemSettings
)(
implicit s: Session,
)(implicit
s: Session,
c: JsonFormat.Context
): Unit = {
getPullRequestsByRequest(owner, repository, branch, Some(false)).foreach { pullreq =>
@@ -273,8 +269,7 @@ trait PullRequestService {
(file, commentId, Left(oldLine))
}
.groupBy { case (file, _, _) => file }
.map {
case (file, comments) =>
.map { case (file, comments) =>
file ->
comments.map { case (_, commentId, lineNumber) => (commentId, lineNumber) }
}
@@ -312,12 +307,11 @@ trait PullRequestService {
body: Option[String],
state: Option[String],
base: Option[String]
)(
implicit s: Session,
)(implicit
s: Session,
c: JsonFormat.Context
): Unit = {
getPullRequest(repository.owner, repository.name, issueId).foreach {
case (issue, pr) =>
getPullRequest(repository.owner, repository.name, issueId).foreach { case (issue, pr) =>
if (Repositories.filter(_.byRepository(pr.userName, pr.repositoryName)).exists.run) {
// Update base branch
base.foreach { _base =>
@@ -388,8 +382,7 @@ trait PullRequestService {
.on { (t1, t2) =>
t1.byPrimaryKey(t2.userName, t2.repositoryName, t2.issueId)
}
.filter {
case (t1, t2) =>
.filter { case (t1, t2) =>
(t1.userName === userName.bind) &&
(t1.repositoryName === repositoryName.bind) &&
(t1.branch === toBranch.bind) &&
@@ -412,8 +405,7 @@ trait PullRequestService {
val (_, diffs) = getRequestCompareInfo(userName, repositoryName, oldCommitId, userName, repositoryName, newCommitId)
val patchs = positions.map {
case (file, _) =>
val patchs = positions.map { case (file, _) =>
diffs
.find(x => x.oldPath == file)
.map { diff =>
@@ -432,12 +424,10 @@ trait PullRequestService {
}
}
positions.foreach {
case (file, comments) =>
positions.foreach { case (file, comments) =>
patchs(file) match {
case Some(patch) =>
file -> comments.foreach {
case (commentId, lineNumber) =>
file -> comments.foreach { case (commentId, lineNumber) =>
lineNumber match {
case Left(oldLine) => updateCommitCommentPosition(commentId, newCommitId, Some(oldLine), None)
case Right(newLine) =>
@@ -445,7 +435,9 @@ trait PullRequestService {
patch.getDeltas.asScala.filter(_.getSource.getPosition < newLine).foreach { delta =>
delta.getType match {
case DeltaType.CHANGE =>
if (delta.getSource.getPosition <= newLine - 1 && newLine <= delta.getSource.getPosition + delta.getTarget.getLines.size) {
if (
delta.getSource.getPosition <= newLine - 1 && newLine <= delta.getSource.getPosition + delta.getTarget.getLines.size
) {
counter = -1
} else {
counter = counter + (delta.getTarget.getLines.size - delta.getSource.getLines.size)
@@ -461,8 +453,7 @@ trait PullRequestService {
}
}
case _ =>
comments.foreach {
case (commentId, lineNumber) =>
comments.foreach { case (commentId, lineNumber) =>
lineNumber match {
case Right(oldLine) => updateCommitCommentPosition(commentId, newCommitId, Some(oldLine), None)
case Left(newLine) => updateCommitCommentPosition(commentId, newCommitId, None, Some(newLine))
@@ -540,8 +531,8 @@ trait PullRequestService {
(commits, diffs)
}
def getPullRequestComments(userName: String, repositoryName: String, issueId: Int, commits: Seq[CommitInfo])(
implicit s: Session
def getPullRequestComments(userName: String, repositoryName: String, issueId: Int, commits: Seq[CommitInfo])(implicit
s: Session
): Seq[Comment] = {
(commits.flatMap(commit => getCommitComments(userName, repositoryName, commit.id, true)) ++ getComments(
userName,
@@ -552,8 +543,7 @@ trait PullRequestService {
case x: CommitComment if x.fileName.isEmpty => (Some(x.commentId), None, None, None)
case x: CommitComment => (None, x.fileName, x.originalOldLine, x.originalNewLine)
case x => throw new MatchError(x)
}
.toSeq
}.toSeq
.map {
// Normal comment
case ((Some(_), _, _, _), comments) =>
@@ -578,8 +568,8 @@ trait PullRequestService {
.sortWith(_.registeredDate before _.registeredDate)
}
def markMergeAndClosePullRequest(userName: String, owner: String, repository: String, pull: PullRequest)(
implicit s: Session
def markMergeAndClosePullRequest(userName: String, owner: String, repository: String, pull: PullRequest)(implicit
s: Session
): Unit = {
createComment(owner, repository, userName, pull.issueId, "Merged by user", "merge")
createComment(owner, repository, userName, pull.issueId, "Close", "close")
@@ -609,8 +599,7 @@ trait PullRequestService {
Using.resources(
Git.open(getRepositoryDir(originRepository.owner, originRepository.name)),
Git.open(getRepositoryDir(forkedRepository.owner, forkedRepository.name))
) {
case (oldGit, newGit) =>
) { case (oldGit, newGit) =>
if (originRepository.branchList.contains(originId)) {
val forkedId2 =
forkedRepository.tags.collectFirst { case x if x.name == forkedId => x.commitId }.getOrElse(forkedId)
@@ -661,8 +650,8 @@ object PullRequestService {
val statuses: List[CommitStatus] =
commitStatuses ++ (branchProtection.contexts.toSet -- commitStatuses.map(_.context).toSet)
.map(CommitStatus.pending(branchProtection.owner, branchProtection.repository, _))
val hasRequiredStatusProblem = needStatusCheck && branchProtection.contexts.exists(
context => statuses.find(_.context == context).map(_.state) != Some(CommitState.SUCCESS)
val hasRequiredStatusProblem = needStatusCheck && branchProtection.contexts.exists(context =>
statuses.find(_.context == context).map(_.state) != Some(CommitState.SUCCESS)
)
val hasProblem = hasRequiredStatusProblem || hasConflict || (statuses.nonEmpty && CommitState.combine(
statuses.map(_.state).toSet

View File

@@ -36,14 +36,14 @@ trait ReleaseService {
ReleaseAssets.filter(x => x.byTag(owner, repository, tag)).list
}
def getReleaseAssetsMap(owner: String, repository: String, releases: Seq[ReleaseTag])(
implicit s: Session
def getReleaseAssetsMap(owner: String, repository: String, releases: Seq[ReleaseTag])(implicit
s: Session
): Map[ReleaseTag, Seq[ReleaseAsset]] = {
releases.map(rel => (rel -> getReleaseAssets(owner, repository, rel.tag))).toMap
}
def getReleaseAsset(owner: String, repository: String, tag: String, fileId: String)(
implicit s: Session
def getReleaseAsset(owner: String, repository: String, tag: String, fileId: String)(implicit
s: Session
): Option[ReleaseAsset] = {
ReleaseAssets.filter(x => x.byPrimaryKey(owner, repository, tag, fileId)) firstOption
}
@@ -76,8 +76,8 @@ trait ReleaseService {
ReleaseTags.filter(x => x.byRepository(owner, repository)).sortBy(x => x.updatedDate).list
}
def getReleases(owner: String, repository: String, tags: Seq[JGitUtil.TagInfo])(
implicit s: Session
def getReleases(owner: String, repository: String, tags: Seq[JGitUtil.TagInfo])(implicit
s: Session
): Seq[ReleaseTag] = {
ReleaseTags
.filter(x => x.byRepository(owner, repository))
@@ -89,8 +89,8 @@ trait ReleaseService {
ReleaseTags.filter(_.byTag(owner, repository, tag)).firstOption
}
def updateRelease(owner: String, repository: String, tag: String, title: String, content: Option[String])(
implicit s: Session
def updateRelease(owner: String, repository: String, tag: String, title: String, content: Option[String])(implicit
s: Session
): Int = {
ReleaseTags
.filter(_.byPrimaryKey(owner, repository, tag))

View File

@@ -65,7 +65,8 @@ trait RepositoryCommitFileService {
path,
newFileName,
oldFileName,
if (content.nonEmpty) { content.getBytes(charset) } else { Array.emptyByteArray },
if (content.nonEmpty) { content.getBytes(charset) }
else { Array.emptyByteArray },
message,
commit,
loginAccount,

View File

@@ -92,7 +92,7 @@ trait RepositoryCreationService {
RepositoryCreationService.startCreation(owner, name)
try {
Database() withTransaction { implicit session =>
//val ownerAccount = getAccountByUserName(owner).get
// val ownerAccount = getAccountByUserName(owner).get
val loginUserName = loginAccount.userName
val copyRepositoryDir = if (initOption == "COPY") {
@@ -214,8 +214,7 @@ trait RepositoryCreationService {
// Set default collaborators for the private fork
if (repository.repository.isPrivate) {
// Copy collaborators from the source repository
getCollaborators(repository.owner, repository.name).foreach {
case (collaborator, _) =>
getCollaborators(repository.owner, repository.name).foreach { case (collaborator, _) =>
addCollaborator(accountName, repository.name, collaborator.collaboratorName, collaborator.role)
}
// Register an owner of the source repository as a collaborator

View File

@@ -14,16 +14,15 @@ import scala.util.Using
trait RepositorySearchService { self: IssuesService =>
import RepositorySearchService._
def countIssues(owner: String, repository: String, query: String, pullRequest: Boolean)(
implicit session: Session
def countIssues(owner: String, repository: String, query: String, pullRequest: Boolean)(implicit
session: Session
): Int =
searchIssuesByKeyword(owner, repository, query, pullRequest).length
def searchIssues(owner: String, repository: String, query: String, pullRequest: Boolean)(
implicit session: Session
def searchIssues(owner: String, repository: String, query: String, pullRequest: Boolean)(implicit
session: Session
): List[IssueSearchResult] =
searchIssuesByKeyword(owner, repository, query, pullRequest).map {
case (issue, commentCount, content) =>
searchIssuesByKeyword(owner, repository, query, pullRequest).map { case (issue, commentCount, content) =>
IssueSearchResult(
issue.issueId,
issue.isPullRequest,
@@ -48,8 +47,7 @@ trait RepositorySearchService { self: IssuesService =>
} else {
val files = searchRepositoryFiles(git, query)
val commits = JGitUtil.getLatestCommitFromPaths(git, files.map(_._1), "HEAD")
files.map {
case (path, text) =>
files.map { case (path, text) =>
val (highlightText, lineNumber) = getHighlightText(text, query)
FileSearchResult(path, commits(path).getCommitterIdent.getWhen, highlightText, lineNumber)
}
@@ -68,8 +66,7 @@ trait RepositorySearchService { self: IssuesService =>
} else {
val files = searchRepositoryFiles(git, query)
val commits = JGitUtil.getLatestCommitFromPaths(git, files.map(_._1), "HEAD")
files.map {
case (path, text) =>
files.map { case (path, text) =>
val (highlightText, lineNumber) = getHighlightText(text, query)
FileSearchResult(
path.stripSuffix(".md"),

View File

@@ -187,8 +187,7 @@ trait RepositoryService {
val newLabelMap =
Labels.filter(_.byRepository(newUserName, newRepositoryName)).map(x => (x.labelName, x.labelId)).list.toMap
IssueLabels.insertAll(
issueLabels.map(
x =>
issueLabels.map(x =>
x.copy(
labelId = newLabelMap(oldLabelMap(x.labelId)),
userName = newUserName,
@@ -275,8 +274,7 @@ trait RepositoryService {
(x.userName, x.repositoryName)
}
.list
.foreach {
case (userName, repositoryName) =>
.foreach { case (userName, repositoryName) =>
Repositories
.filter(_.byRepository(userName, repositoryName))
.map(x => (x.originUserName ?, x.originRepositoryName ?))
@@ -292,8 +290,7 @@ trait RepositoryService {
(x.userName, x.repositoryName)
}
.list
.foreach {
case (userName, repositoryName) =>
.foreach { case (userName, repositoryName) =>
Repositories
.filter(_.byRepository(userName, repositoryName))
.map(x => (x.parentUserName ?, x.parentRepositoryName ?))
@@ -321,11 +318,9 @@ trait RepositoryService {
(Repositories
.join(Accounts)
.on(_.userName === _.userName)
.filter {
case (t1, t2) =>
.filter { case (t1, t2) =>
t1.byRepository(userName, repositoryName) && t2.removed === false.bind
} firstOption) map {
case (repository, account) =>
} firstOption) map { case (repository, account) =>
// for getting issue count and pull request count
val issues = Issues
.filter { t =>
@@ -396,8 +391,8 @@ trait RepositoryService {
* Returns the list of repositories which are owned by the specified user.
* This list includes group repositories if the specified user is a member of the group.
*/
def getUserRepositories(userName: String, withoutPhysicalInfo: Boolean = false)(
implicit s: Session
def getUserRepositories(userName: String, withoutPhysicalInfo: Boolean = false)(implicit
s: Session
): List[RepositoryInfo] = {
Repositories
.filter { t1 =>
@@ -464,8 +459,7 @@ trait RepositoryService {
Repositories
.join(Accounts)
.on(_.userName === _.userName)
.filter {
case (t1, t2) =>
.filter { case (t1, t2) =>
(t2.removed === false.bind) && ((t1.isPrivate === false.bind && !limit.bind) || (t1.userName === x.userName) ||
(t1.userName in GroupMembers.filter(_.userName === x.userName.bind).map(_.groupName)) ||
(Collaborators.filter { t3 =>
@@ -486,14 +480,13 @@ trait RepositoryService {
repositoryUserName.map { userName =>
t.userName === userName.bind
} getOrElse LiteralColumn(true)
}
.sortBy(_.lastActivityDate desc)
}.sortBy(_.lastActivityDate desc)
.list
.map(createRepositoryInfo(_, withoutPhysicalInfo))
}
private def createRepositoryInfo(repository: Repository, withoutPhysicalInfo: Boolean = false)(
implicit s: Session
private def createRepositoryInfo(repository: Repository, withoutPhysicalInfo: Boolean = false)(implicit
s: Session
): RepositoryInfo = {
new RepositoryInfo(
if (withoutPhysicalInfo) {
@@ -586,8 +579,8 @@ trait RepositoryService {
)
}
def saveRepositoryDefaultBranch(userName: String, repositoryName: String, defaultBranch: String)(
implicit s: Session
def saveRepositoryDefaultBranch(userName: String, repositoryName: String, defaultBranch: String)(implicit
s: Session
): Unit =
Repositories
.filter(_.byRepository(userName, repositoryName))
@@ -599,16 +592,16 @@ trait RepositoryService {
/**
* Add collaborator (user or group) to the repository.
*/
def addCollaborator(userName: String, repositoryName: String, collaboratorName: String, role: String)(
implicit s: Session
def addCollaborator(userName: String, repositoryName: String, collaboratorName: String, role: String)(implicit
s: Session
): Unit =
Collaborators insert Collaborator(userName, repositoryName, collaboratorName, role)
/**
* Remove specified collaborator from the repository.
*/
def removeCollaborator(userName: String, repositoryName: String, collaboratorName: String)(
implicit s: Session
def removeCollaborator(userName: String, repositoryName: String, collaboratorName: String)(implicit
s: Session
): Unit =
Collaborators.filter(_.byPrimaryKey(userName, repositoryName, collaboratorName)).delete
@@ -634,8 +627,8 @@ trait RepositoryService {
* Returns the list of all collaborator name and permission which is sorted with ascending order.
* If a group is added as a collaborator, this method returns users who are belong to that group.
*/
def getCollaboratorUserNames(userName: String, repositoryName: String, filter: Seq[Role] = Nil)(
implicit s: Session
def getCollaboratorUserNames(userName: String, repositoryName: String, filter: Seq[Role] = Nil)(implicit
s: Session
): List[String] = {
val q1 = Collaborators
.join(Accounts)
@@ -669,8 +662,8 @@ trait RepositoryService {
}
}
def hasDeveloperRole(owner: String, repository: String, loginAccount: Option[Account])(
implicit s: Session
def hasDeveloperRole(owner: String, repository: String, loginAccount: Option[Account])(implicit
s: Session
): Boolean = {
loginAccount match {
case Some(a) if (a.isAdmin) => true
@@ -731,7 +724,7 @@ trait RepositoryService {
(t.originUserName === userName.bind) && (t.originRepositoryName === repositoryName.bind)
}
.sortBy(_.userName asc)
.list //.map(t => t.userName -> t.repositoryName).list
.list // .map(t => t.userName -> t.repositoryName).list
private val templateExtensions = Seq("md", "markdown")

View File

@@ -25,8 +25,8 @@ trait RequestCache
private implicit def context2Session(implicit context: Context): Session =
request2Session(context.request)
def getIssueFromCache(userName: String, repositoryName: String, issueId: String)(
implicit context: Context
def getIssueFromCache(userName: String, repositoryName: String, issueId: String)(implicit
context: Context
): Option[Issue] = {
context.cache(s"issue.${userName}/${repositoryName}#${issueId}") {
super.getIssue(userName, repositoryName, issueId)
@@ -45,19 +45,18 @@ trait RequestCache
}
}
def getRepositoryInfoFromCache(userName: String, repositoryName: String)(
implicit context: Context
def getRepositoryInfoFromCache(userName: String, repositoryName: String)(implicit
context: Context
): Option[Repository] = {
context.cache(s"repository.${userName}/${repositoryName}") {
Repositories
.join(Accounts)
.on(_.userName === _.userName)
.filter {
case (t1, t2) =>
.filter { case (t1, t2) =>
t1.byRepository(userName, repositoryName) && t2.removed === false.bind
}
.map {
case (t1, t2) => t1
.map { case (t1, t2) =>
t1
}
.firstOption
}

View File

@@ -45,8 +45,8 @@ trait WebHookService {
private val logger = LoggerFactory.getLogger(classOf[WebHookService])
/** get All WebHook informations of repository */
def getWebHooks(owner: String, repository: String)(
implicit s: Session
def getWebHooks(owner: String, repository: String)(implicit
s: Session
): List[(RepositoryWebHook, Set[WebHook.Event])] =
RepositoryWebHooks
.filter(_.byRepository(owner, repository))
@@ -63,8 +63,8 @@ trait WebHookService {
.sortBy(_._1.url)
/** get All WebHook informations of repository event */
def getWebHooksByEvent(owner: String, repository: String, event: WebHook.Event)(
implicit s: Session
def getWebHooksByEvent(owner: String, repository: String, event: WebHook.Event)(implicit
s: Session
): List[RepositoryWebHook] =
RepositoryWebHooks
.filter(_.byRepository(owner, repository))
@@ -78,8 +78,8 @@ trait WebHookService {
.distinct
/** get All WebHook information from repository to url */
def getWebHook(owner: String, repository: String, url: String)(
implicit s: Session
def getWebHook(owner: String, repository: String, url: String)(implicit
s: Session
): Option[(RepositoryWebHook, Set[WebHook.Event])] =
RepositoryWebHooks
.filter(_.byRepositoryUrl(owner, repository, url))
@@ -95,8 +95,8 @@ trait WebHookService {
.headOption
/** get All WebHook informations of repository */
def getWebHookById(id: Int)(
implicit s: Session
def getWebHookById(id: Int)(implicit
s: Session
): Option[(RepositoryWebHook, Set[WebHook.Event])] =
RepositoryWebHooks
.filter(_.byId(id))
@@ -451,8 +451,8 @@ trait WebHookPullRequestService extends WebHookService {
}
/** @return Map[(issue, issueUser, pullRequest, baseOwner, headOwner), webHooks] */
def getPullRequestsByRequestForWebhook(userName: String, repositoryName: String, branch: String)(
implicit s: Session
def getPullRequestsByRequestForWebhook(userName: String, repositoryName: String, branch: String)(implicit
s: Session
): Map[(Issue, Account, PullRequest, Account, Account), List[RepositoryWebHook]] =
(for {
is <- Issues if is.closed === false.bind
@@ -878,8 +878,7 @@ object WebHookService {
sender: Account
): WebHookGollumPayload = {
WebHookGollumPayload(
pages = pages.map {
case (action, pageName, sha) =>
pages = pages.map { case (action, pageName, sha) =>
WebHookGollumPagePayload(
action = action,
page_name = pageName,

View File

@@ -20,8 +20,10 @@ abstract class ControllerFilter extends Filter {
requestPath + "/"
}
if (!checkPath.startsWith("/upload/") && !checkPath.startsWith("/git/") && !checkPath.startsWith("/git-lfs/") &&
!checkPath.startsWith("/assets/") && !checkPath.startsWith("/plugin-assets/")) {
if (
!checkPath.startsWith("/upload/") && !checkPath.startsWith("/git/") && !checkPath.startsWith("/git-lfs/") &&
!checkPath.startsWith("/assets/") && !checkPath.startsWith("/plugin-assets/")
) {
val continue = process(request, response, checkPath)
if (!continue) {
return ()
@@ -41,28 +43,24 @@ class CompositeScalatraFilter extends ControllerFilter {
}
override def init(filterConfig: FilterConfig): Unit = {
filters.foreach {
case (filter, _) =>
filters.foreach { case (filter, _) =>
filter.init(filterConfig)
}
}
override def destroy(): Unit = {
filters.foreach {
case (filter, _) =>
filters.foreach { case (filter, _) =>
filter.destroy()
}
}
override def process(request: ServletRequest, response: ServletResponse, checkPath: String): Boolean = {
filters
.filter {
case (_, path) =>
.filter { case (_, path) =>
val start = path.replaceFirst("/\\*$", "/")
checkPath.startsWith(start)
}
.foreach {
case (filter, _) =>
.foreach { case (filter, _) =>
val mockChain = new MockFilterChain()
filter.doFilter(request, response, mockChain)
if (mockChain.continue == false) {

View File

@@ -43,8 +43,7 @@ class GitAuthenticationFilter extends Filter with RepositoryService with Account
try {
PluginRegistry()
.getRepositoryRouting(request.gitRepositoryPath)
.map {
case GitRepositoryRouting(_, _, filter) =>
.map { case GitRepositoryRouting(_, _, filter) =>
// served by plug-ins
pluginRepository(request, wrappedResponse, chain, settings, isUpdating, filter)
@@ -130,16 +129,14 @@ class GitAuthenticationFilter extends Filter with RepositoryService with Account
}
}
case None =>
() =>
{
() => {
logger.debug(s"Repository ${repositoryOwner}/${repositoryName} is not found.")
response.sendError(HttpServletResponse.SC_NOT_FOUND)
}
}
}
case _ =>
() =>
{
() => {
logger.debug(s"Not enough path arguments: ${request.paths.mkString(", ")}")
response.sendError(HttpServletResponse.SC_NOT_FOUND)
}
@@ -159,8 +156,8 @@ class GitAuthenticationFilter extends Filter with RepositoryService with Account
* @param s database session
* @return an account or none
*/
private def authenticateByHeader(authorizationHeader: String, settings: SystemSettings)(
implicit s: Session
private def authenticateByHeader(authorizationHeader: String, settings: SystemSettings)(implicit
s: Session
): Option[Account] = {
val Array(username, password) = AuthUtil.decodeAuthHeader(authorizationHeader).split(":", 2)
authenticate(settings, username, password).orElse {

View File

@@ -171,8 +171,7 @@ class GitBucketRepositoryResolver extends RepositoryResolver[HttpServletRequest]
// Rewrite repository path if routing is marched
PluginRegistry()
.getRepositoryRouting("/" + name)
.map {
case GitRepositoryRouting(urlPattern, localPath, _) =>
.map { case GitRepositoryRouting(urlPattern, localPath, _) =>
val path = urlPattern.r.replaceFirstIn(name, localPath)
new FileRepository(new File(Directory.GitBucketHome, path))
}
@@ -341,7 +340,11 @@ class CommitLogHook(owner: String, repository: String, pusher: String, baseUrl:
pushedIds.add(commit.id)
createIssueComment(owner, repository, commit)
// close issues
if (refName(1) == "heads" && branchName == defaultBranch && command.getType == ReceiveCommand.Type.UPDATE) {
if (
refName(
1
) == "heads" && branchName == defaultBranch && command.getType == ReceiveCommand.Type.UPDATE
) {
getAccountByUserName(pusher).foreach { pusherAccount =>
closeIssuesFromMessage(commit.fullMessage, pusher, owner, repository).foreach { issueId =>
getIssue(owner, repository, issueId.toString).foreach { issue =>
@@ -362,9 +365,11 @@ class CommitLogHook(owner: String, repository: String, pusher: String, baseUrl:
// set PR as merged
val pulls = getPullRequestsByBranch(owner, repository, branchName, Some(false))
pulls.foreach { pull =>
if (commits.exists { c =>
if (
commits.exists { c =>
c.id == pull.commitIdTo
}) {
}
) {
markMergeAndClosePullRequest(pusher, owner, repository, pull)
getAccountByUserName(pusher).foreach { pusherAccount =>
callPullRequestWebHook("closed", repositoryInfo, pull.issueId, pusherAccount, settings)
@@ -490,8 +495,7 @@ class WikiCommitHook(owner: String, repository: String, pusher: String, baseUrl:
}
}
commitIds.foreach {
case (oldCommitId, newCommitId) =>
commitIds.foreach { case (oldCommitId, newCommitId) =>
val commits = Using.resource(Git.open(Directory.getWikiRepositoryDir(owner, repository))) { git =>
JGitUtil.getCommitLog(git, oldCommitId, newCommitId).flatMap { commit =>
val diffs = JGitUtil.getDiffs(git, None, commit.id, false, false)
@@ -508,8 +512,7 @@ class WikiCommitHook(owner: String, repository: String, pusher: String, baseUrl:
val pages = commits
.groupBy { case (_, fileName, _) => fileName }
.map {
case (fileName, commits) =>
.map { case (fileName, commits) =>
val (commitHeadAction, _, _) = commits.head
val (_, _, commitLastId) = commits.last
(commitHeadAction, fileName, commitLastId)

View File

@@ -153,8 +153,8 @@ class InitializeListener extends ServletContextListener with SystemSettingsServi
logger.info(s"Extract to ${file.getAbsolutePath}")
FileUtils.forceMkdirParent(file)
Using.resources(in, new FileOutputStream(file)) {
case (in, out) => IOUtils.copy(in, out)
Using.resources(in, new FileOutputStream(file)) { case (in, out) =>
IOUtils.copy(in, out)
}
}
case _ => ()

View File

@@ -16,8 +16,7 @@ class PluginAssetsServlet extends HttpServlet {
assetsMappings
.find { case (prefix, _, _) => path.startsWith("/plugin-assets" + prefix) }
.foreach {
case (prefix, resourcePath, classLoader) =>
.foreach { case (prefix, resourcePath, classLoader) =>
val ifNoneMatch = req.getHeader("If-None-Match")
PluginRegistry.getPluginInfoFromClassLoader(classLoader).map { info =>
val etag = s""""${info.pluginJar.lastModified}"""" // ETag must wrapped with double quote

View File

@@ -14,8 +14,7 @@ class PluginControllerFilter extends ControllerFilter {
}
override def destroy(): Unit = {
PluginRegistry().getControllers().foreach {
case (controller, _) =>
PluginRegistry().getControllers().foreach { case (controller, _) =>
controller.destroy()
}
}
@@ -23,13 +22,11 @@ class PluginControllerFilter extends ControllerFilter {
override def process(request: ServletRequest, response: ServletResponse, checkPath: String): Boolean = {
PluginRegistry()
.getControllers()
.filter {
case (_, path) =>
.filter { case (_, path) =>
val start = path.replaceFirst("/\\*$", "/")
checkPath.startsWith(start)
}
.foreach {
case (controller, _) =>
.foreach { case (controller, _) =>
controller match {
case x: ControllerBase if (x.config == null) => x.init(filterConfig)
case _ => ()

View File

@@ -101,8 +101,8 @@ abstract class DefaultGitCommand(val owner: String, val repoName: String) extend
}
}
protected def isReadableUser(authType: AuthType, repositoryInfo: RepositoryService.RepositoryInfo)(
implicit session: Session
protected def isReadableUser(authType: AuthType, repositoryInfo: RepositoryService.RepositoryInfo)(implicit
session: Session
): Boolean = {
authType match {
case AuthType.UserAuthType(username) => {
@@ -120,8 +120,8 @@ abstract class DefaultGitCommand(val owner: String, val repoName: String) extend
}
}
protected def isWritableUser(authType: AuthType, repositoryInfo: RepositoryService.RepositoryInfo)(
implicit session: Session
protected def isWritableUser(authType: AuthType, repositoryInfo: RepositoryService.RepositoryInfo)(implicit
session: Session
): Boolean = {
authType match {
case AuthType.UserAuthType(username) => {

View File

@@ -56,8 +56,8 @@ class PublicKeyAuthenticator(genericUser: String)
}
}
private def authenticateLoginUser(userName: String, key: PublicKey, session: ServerSession)(
implicit s: Session
private def authenticateLoginUser(userName: String, key: PublicKey, session: ServerSession)(implicit
s: Session
): Boolean = {
val authenticated = getPublicKeys(userName).map(_.publicKey).flatMap(SshUtil.str2PublicKey).contains(key)

View File

@@ -36,7 +36,7 @@ object DatabaseConfig {
ConfigFactory.parseFile(file)
}
private lazy val dbUrl = getValue("db.url", config.getString) //config.getString("db.url")
private lazy val dbUrl = getValue("db.url", config.getString) // config.getString("db.url")
def url(directory: Option[String]): String = {
val sb = new StringBuilder()

View File

@@ -18,7 +18,7 @@ object Directory {
case None => {
val oldHome = new File(System.getProperty("user.home"), "gitbucket")
if (oldHome.exists && oldHome.isDirectory && new File(oldHome, "version").exists) {
//FileUtils.moveDirectory(oldHome, newHome)
// FileUtils.moveDirectory(oldHome, newHome)
oldHome
} else {
new File(System.getProperty("user.home"), ".gitbucket")

View File

@@ -12,8 +12,7 @@ import org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider
object GpgUtil {
def str2GpgKeyId(keyStr: String): Option[Long] = {
val pubKeyOf = new BcPGPObjectFactory(new ArmoredInputStream(new ByteArrayInputStream(keyStr.getBytes)))
pubKeyOf.iterator().asScala.collectFirst {
case keyRing: PGPPublicKeyRing =>
pubKeyOf.iterator().asScala.collectFirst { case keyRing: PGPPublicKeyRing =>
keyRing.getPublicKey().getKeyID
}
}
@@ -37,8 +36,7 @@ object GpgUtil {
new BcPGPObjectFactory(new ArmoredInputStream(new ByteArrayInputStream(signInfo.signArmored)))
.iterator()
.asScala
.flatMap {
case signList: PGPSignatureList =>
.flatMap { case signList: PGPSignatureList =>
signList
.iterator()
.asScala

View File

@@ -54,8 +54,7 @@ object JDBCUtil {
private def execute[T](sql: String, params: Any*)(f: (PreparedStatement) => T): T = {
Using.resource(conn.prepareStatement(sql)) { stmt =>
params.zipWithIndex.foreach {
case (p, i) =>
params.zipWithIndex.foreach { case (p, i) =>
p match {
case x: Int => stmt.setInt(i + 1, x)
case x: String => stmt.setString(i + 1, x)
@@ -136,8 +135,7 @@ object JDBCUtil {
sb.append(columns.map(_._1).mkString(", "))
sb.append(") VALUES (")
val values = columns.map {
case (columnName, columnType) =>
val values = columns.map { case (columnName, columnType) =>
if (rs.getObject(columnName) == null) {
null
} else {

View File

@@ -454,8 +454,7 @@ object JGitUtil {
def appendLastCommits(
fileList: List[(ObjectId, FileMode, String, String, Option[String])]
): List[(ObjectId, FileMode, String, String, Option[String], Option[RevCommit])] = {
fileList.map {
case (id, mode, name, path, opt) =>
fileList.map { case (id, mode, name, path, opt) =>
if (maxFiles > 0 && fileList.size >= maxFiles) {
// Don't attempt to get the last commit if the number of files is very large.
(id, mode, name, path, opt, None)
@@ -503,8 +502,7 @@ object JGitUtil {
appendLastCommits(fileList)
.map(simplifyPath)
.map {
case (objectId, fileMode, name, path, linkUrl, commit) =>
.map { case (objectId, fileMode, name, path, linkUrl, commit) =>
FileInfo(
objectId,
fileMode == FileMode.TREE || fileMode == FileMode.GITLINK,
@@ -716,8 +714,7 @@ object JGitUtil {
df.scan(
new EmptyTreeIterator(),
new CanonicalTreeParser(null, git.getRepository.newObjectReader(), toCommit.getTree)
)
.asScala
).asScala
case _ => df.scan(toCommit.getParent(0), toCommit.getTree).asScala
}
case Some(from) =>
@@ -788,8 +785,10 @@ object JGitUtil {
} else {
val oldIsImage = FileUtil.isImage(diff.getOldPath)
val newIsImage = FileUtil.isImage(diff.getNewPath)
val patch = if (oldIsImage || newIsImage) None else Some(makePatchFromDiffEntry(git, diff)) // TODO use DiffFormatter
val tooLarge = patch.exists(_.count(_ == '\n') > 1000) // Don't show diff if the file has more than 1000 lines diff
val patch =
if (oldIsImage || newIsImage) None else Some(makePatchFromDiffEntry(git, diff)) // TODO use DiffFormatter
val tooLarge =
patch.exists(_.count(_ == '\n') > 1000) // Don't show diff if the file has more than 1000 lines diff
val includeContent = tooLarge || !fetchContent || oldIsImage || newIsImage
DiffInfo(
changeType = diff.getChangeType,
@@ -923,8 +922,7 @@ object JGitUtil {
).flatMap {
case Some(rev) => Some((git.getRepository.resolve(rev), rev))
case None => None
}
.find(_._1 != null)
}.find(_._1 != null)
}
def createTag(git: Git, name: String, message: Option[String], commitId: String) = {
@@ -1301,7 +1299,8 @@ object JGitUtil {
c.getAuthorIdent.getWhen,
Option(git.log.add(c).addPath(blame.getSourcePath(i)).setSkip(1).setMaxCount(2).call.iterator.next)
.map(_.name),
if (blame.getSourcePath(i) == path) { None } else { Some(blame.getSourcePath(i)) },
if (blame.getSourcePath(i) == path) { None }
else { Some(blame.getSourcePath(i)) },
c.getCommitterIdent.getWhen,
c.getShortMessage,
Set.empty

View File

@@ -128,7 +128,8 @@ object LDAPUtil {
val cachedInstance = provider.get()
if (cachedInstance == null) {
val cls = try {
val cls =
try {
Class.forName("com.sun.net.ssl.internal.ssl.Provider")
} catch {
case e: ClassNotFoundException =>
@@ -234,8 +235,8 @@ object LDAPUtil {
case x => "(&(" + x + ")(" + userNameAttribute + "=" + userName + "))"
}
getEntries(conn.search(baseDN, LDAPConnection.SCOPE_SUB, filterCond, null, false)).collectFirst {
case x => x.getDN
getEntries(conn.search(baseDN, LDAPConnection.SCOPE_SUB, filterCond, null, false)).collectFirst { case x =>
x.getDN
}
}

View File

@@ -62,8 +62,7 @@ class Mailer(settings: SystemSettings) {
smtp.fromAddress
.map(_ -> smtp.fromName.getOrElse(loginAccount.map(_.userName).getOrElse("GitBucket")))
.orElse(Some("notifications@gitbucket.com" -> loginAccount.map(_.userName).getOrElse("GitBucket")))
.foreach {
case (address, name) =>
.foreach { case (address, name) =>
email.setFrom(address, name)
}
email.setCharset("UTF-8")

View File

@@ -19,7 +19,9 @@ trait AvatarImageProvider { self: RequestCache =>
// by user name
getAccountByUserNameFromCache(userName).map { account =>
if (account.image.isEmpty && context.settings.basicBehavior.gravatar) {
s"""https://www.gravatar.com/avatar/${StringUtil.md5(account.mailAddress.toLowerCase)}?s=${size}&d=retro&r=g"""
s"""https://www.gravatar.com/avatar/${StringUtil.md5(
account.mailAddress.toLowerCase
)}?s=${size}&d=retro&r=g"""
} else {
s"""${context.path}/${account.userName}/_avatar?${helpers.hashDate(account.updatedDate)}"""
}
@@ -30,7 +32,9 @@ trait AvatarImageProvider { self: RequestCache =>
// by mail address
getAccountByMailAddressFromCache(mailAddress).map { account =>
if (account.image.isEmpty && context.settings.basicBehavior.gravatar) {
s"""https://www.gravatar.com/avatar/${StringUtil.md5(account.mailAddress.toLowerCase)}?s=${size}&d=retro&r=g"""
s"""https://www.gravatar.com/avatar/${StringUtil.md5(
account.mailAddress.toLowerCase
)}?s=${size}&d=retro&r=g"""
} else {
s"""${context.path}/${account.userName}/_avatar?${helpers.hashDate(account.updatedDate)}"""
}
@@ -45,13 +49,15 @@ trait AvatarImageProvider { self: RequestCache =>
if (tooltip) {
Html(
s"""<img src="${src}" class="${if (size > 20) { "avatar" } else { "avatar-mini" }}" style="width: ${size}px; height: ${size}px;"
s"""<img src="${src}" class="${if (size > 20) { "avatar" }
else { "avatar-mini" }}" style="width: ${size}px; height: ${size}px;"
| alt="@${StringUtil.escapeHtml(userName)}"
| data-toggle="tooltip" title="${StringUtil.escapeHtml(userName)}" />""".stripMargin
)
} else {
Html(
s"""<img src="${src}" class="${if (size > 20) { "avatar" } else { "avatar-mini" }}" style="width: ${size}px; height: ${size}px;"
s"""<img src="${src}" class="${if (size > 20) { "avatar" }
else { "avatar-mini" }}" style="width: ${size}px; height: ${size}px;"
| alt="@${StringUtil.escapeHtml(userName)}" />""".stripMargin
)
}

View File

@@ -10,12 +10,13 @@ trait LinkConverter { self: RequestCache =>
/**
* Creates a link to the issue or the pull request from the issue id.
*/
protected def createIssueLink(owner: String, repository: String, issueId: Int, title: String)(
implicit context: Context
protected def createIssueLink(owner: String, repository: String, issueId: Int, title: String)(implicit
context: Context
): String = {
getIssueFromCache(owner, repository, issueId.toString) match {
case Some(issue) =>
s"""<a href="${context.path}/${owner}/${repository}/${if (issue.isPullRequest) "pull" else "issues"}/${issueId}"><strong>${StringUtil
s"""<a href="${context.path}/${owner}/${repository}/${if (issue.isPullRequest) "pull"
else "issues"}/${issueId}"><strong>${StringUtil
.escapeHtml(title)}</strong> #${issueId}</a>"""
case None =>
s"Unknown #${issueId}"
@@ -25,12 +26,13 @@ trait LinkConverter { self: RequestCache =>
/**
* Creates a global link to the issue or the pull request from the issue id.
*/
protected def createGlobalIssueLink(owner: String, repository: String, issueId: Int, title: String)(
implicit context: Context
protected def createGlobalIssueLink(owner: String, repository: String, issueId: Int, title: String)(implicit
context: Context
): String = {
getIssueFromCache(owner, repository, issueId.toString) match {
case Some(issue) =>
s"""<a href="${context.path}/${owner}/${repository}/${if (issue.isPullRequest) "pull" else "issues"}/${issueId}"><strong>${StringUtil
s"""<a href="${context.path}/${owner}/${repository}/${if (issue.isPullRequest) "pull"
else "issues"}/${issueId}"><strong>${StringUtil
.escapeHtml(title)}</strong> ${owner}/${repository}#${issueId}</a>"""
case None =>
s"Unknown ${owner}/${repository}#${issueId}"

View File

@@ -160,8 +160,8 @@ object helpers extends AvatarImageProvider with LinkConverter with RequestCache
/**
* Creates a link to the issue or the pull request from the issue id.
*/
def issueLink(owner: String, repository: String, issueId: Int, title: String)(
implicit context: Context
def issueLink(owner: String, repository: String, issueId: Int, title: String)(implicit
context: Context
): Html = {
Html(createIssueLink(owner, repository, issueId, title))
}
@@ -169,8 +169,8 @@ object helpers extends AvatarImageProvider with LinkConverter with RequestCache
/**
* Creates a global link to the issue or the pull request from the issue id.
*/
def issueGlobalLink(owner: String, repository: String, issueId: Int, title: String)(
implicit context: Context
def issueGlobalLink(owner: String, repository: String, issueId: Int, title: String)(implicit
context: Context
): Html = {
Html(createGlobalIssueLink(owner, repository, issueId, title))
}
@@ -179,8 +179,8 @@ object helpers extends AvatarImageProvider with LinkConverter with RequestCache
* Returns &lt;img&gt; which displays the avatar icon for the given user name.
* This method looks up Gravatar if avatar icon has not been configured in user settings.
*/
def avatar(userName: String, size: Int, tooltip: Boolean = false, mailAddress: String = "")(
implicit context: Context
def avatar(userName: String, size: Int, tooltip: Boolean = false, mailAddress: String = "")(implicit
context: Context
): Html =
getAvatarImageHtml(userName, size, mailAddress, tooltip)

View File

@@ -443,7 +443,7 @@ object ApiSpecModels {
val apiPusher = ApiPusher(account)
//have both urls as https, as the expected samples are using https
// have both urls as https, as the expected samples are using https
val gitHubContext = JsonFormat.Context("https://api.github.com", Some("https://api.github.com"))
val apiRefHeadsMaster = ApiRef(
@@ -797,7 +797,7 @@ object ApiSpecModels {
val jsonPusher = """{"name":"octocat","email":"octocat@example.com"}"""
//I checked all refs in gitbucket repo, and there appears to be only type "commit" and type "tag"
// I checked all refs in gitbucket repo, and there appears to be only type "commit" and type "tag"
val jsonRef = """{"ref":"refs/heads/featureA","object":{"sha":"6dcb09b5b57875f334f61aebed695e2e4193db5e"}}"""
val jsonRefHeadsMain =

View File

@@ -28,9 +28,19 @@ import MergeServiceSpec._
import org.json4s.JsonAST.{JArray, JString}
class MergeServiceSpec extends AnyFunSpec with ServiceSpecBase {
val service = new MergeService with AccountService with ActivityService with IssuesService with LabelsService
with MilestonesService with RepositoryService with PrioritiesService with PullRequestService with CommitsService
with WebHookPullRequestService with WebHookPullRequestReviewCommentService with RequestCache {
val service = new MergeService
with AccountService
with ActivityService
with IssuesService
with LabelsService
with MilestonesService
with RepositoryService
with PrioritiesService
with PullRequestService
with CommitsService
with WebHookPullRequestService
with WebHookPullRequestReviewCommentService
with RequestCache {
override protected def getReceiveHooks(): Seq[ReceiveHook] = Nil
}
val branch = "master"

View File

@@ -33,7 +33,11 @@ class PullRequestServiceSpec
generateNewUserWithDBRepository("user1", "repo2")
generateNewUserWithDBRepository("user2", "repo1")
generateNewPullRequest("user1/repo1/master", "user1/repo1/head2", loginUser = "root") // not target branch
generateNewPullRequest("user1/repo1/head1", "user1/repo1/master", loginUser = "root") // not target branch ( swap from, to )
generateNewPullRequest(
"user1/repo1/head1",
"user1/repo1/master",
loginUser = "root"
) // not target branch ( swap from, to )
generateNewPullRequest("user1/repo1/master", "user2/repo1/head1", loginUser = "root") // other user
generateNewPullRequest("user1/repo1/master", "user1/repo2/head1", loginUser = "root") // other repository
val r1 = swap(generateNewPullRequest("user1/repo1/master2", "user1/repo1/head1", loginUser = "root"))

View File

@@ -108,10 +108,21 @@ trait ServiceSpecBase {
def user(name: String)(implicit s: Session): Account = AccountService.getAccountByUserName(name).get
lazy val dummyService = new RepositoryService with AccountService with ActivityService with IssuesService
with MergeService with PullRequestService with CommitsService with CommitStatusService with LabelsService
with MilestonesService with PrioritiesService with WebHookService with WebHookPullRequestService
with WebHookPullRequestReviewCommentService with RequestCache {
lazy val dummyService = new RepositoryService
with AccountService
with ActivityService
with IssuesService
with MergeService
with PullRequestService
with CommitsService
with CommitStatusService
with LabelsService
with MilestonesService
with PrioritiesService
with WebHookService
with WebHookPullRequestService
with WebHookPullRequestReviewCommentService
with RequestCache {
override def fetchAsPullRequest(
userName: String,
repositoryName: String,
@@ -133,8 +144,7 @@ trait ServiceSpecBase {
ac
}
def generateNewIssue(userName: String, repositoryName: String, loginUser: String = "root")(
implicit
def generateNewIssue(userName: String, repositoryName: String, loginUser: String = "root")(implicit
s: Session
): Int = {
dummyService.insertIssue(
@@ -149,8 +159,7 @@ trait ServiceSpecBase {
)
}
def generateNewPullRequest(base: String, request: String, loginUser: String)(
implicit
def generateNewPullRequest(base: String, request: String, loginUser: String)(implicit
s: Session
): (Issue, PullRequest) = {
implicit val context = Context(createSystemSettings(), None, this.request)

View File

@@ -5,9 +5,19 @@ import org.scalatest.funsuite.AnyFunSuite
import gitbucket.core.model.WebHookContentType
class WebHookServiceSpec extends AnyFunSuite with ServiceSpecBase {
lazy val service = new WebHookPullRequestService with AccountService with ActivityService with RepositoryService
with MergeService with PullRequestService with IssuesService with CommitsService with LabelsService
with MilestonesService with PrioritiesService with WebHookPullRequestReviewCommentService with RequestCache
lazy val service = new WebHookPullRequestService
with AccountService
with ActivityService
with RepositoryService
with MergeService
with PullRequestService
with IssuesService
with CommitsService
with LabelsService
with MilestonesService
with PrioritiesService
with WebHookPullRequestReviewCommentService
with RequestCache
test("WebHookPullRequestService.getPullRequestsByRequestForWebhook") {
withTestDB { implicit session =>

View File

@@ -101,7 +101,8 @@ object GitSpecUtil {
val merger = MergeStrategy.RECURSIVE.newMerger(repository, true)
val mergeBaseTip = repository.resolve(into)
val mergeTip = repository.resolve(branch)
val conflicted = try {
val conflicted =
try {
!merger.merge(mergeBaseTip, mergeTip)
} catch {
case e: NoMergeBaseException => true

View File

@@ -88,41 +88,65 @@ class StringUtilSpec extends AnyFunSpec {
it("should convert GitBucket repository url") {
assert(
StringUtil
.getRepositoryViewerUrl("http://localhost:8080/git/root/gitbucket.git", baseUrl) == "http://localhost:8080/root/gitbucket"
.getRepositoryViewerUrl(
"http://localhost:8080/git/root/gitbucket.git",
baseUrl
) == "http://localhost:8080/root/gitbucket"
)
assert(
StringUtil
.getRepositoryViewerUrl("http://root@localhost:8080/git/root/gitbucket.git", baseUrl) == "http://localhost:8080/root/gitbucket"
.getRepositoryViewerUrl(
"http://root@localhost:8080/git/root/gitbucket.git",
baseUrl
) == "http://localhost:8080/root/gitbucket"
)
}
it("should convert GitHub repository url") {
assert(
StringUtil
.getRepositoryViewerUrl("https://github.com/root/gitbucket.git", baseUrl) == "https://github.com/root/gitbucket"
.getRepositoryViewerUrl(
"https://github.com/root/gitbucket.git",
baseUrl
) == "https://github.com/root/gitbucket"
)
assert(
StringUtil
.getRepositoryViewerUrl("https://root@github.com/root/gitbucket.git", baseUrl) == "https://github.com/root/gitbucket"
.getRepositoryViewerUrl(
"https://root@github.com/root/gitbucket.git",
baseUrl
) == "https://github.com/root/gitbucket"
)
}
it("should convert BitBucket repository url") {
assert(
StringUtil
.getRepositoryViewerUrl("https://bitbucket.org/root/gitbucket.git", baseUrl) == "https://bitbucket.org/root/gitbucket"
.getRepositoryViewerUrl(
"https://bitbucket.org/root/gitbucket.git",
baseUrl
) == "https://bitbucket.org/root/gitbucket"
)
assert(
StringUtil
.getRepositoryViewerUrl("https://root@bitbucket.org/root/gitbucket.git", baseUrl) == "https://bitbucket.org/root/gitbucket"
.getRepositoryViewerUrl(
"https://root@bitbucket.org/root/gitbucket.git",
baseUrl
) == "https://bitbucket.org/root/gitbucket"
)
}
it("should convert GitLab repository url") {
assert(
StringUtil
.getRepositoryViewerUrl("https://gitlab.com/root/gitbucket.git", baseUrl) == "https://gitlab.com/root/gitbucket"
.getRepositoryViewerUrl(
"https://gitlab.com/root/gitbucket.git",
baseUrl
) == "https://gitlab.com/root/gitbucket"
)
assert(
StringUtil
.getRepositoryViewerUrl("https://root@gitlab.com/root/gitbucket.git", baseUrl) == "https://gitlab.com/root/gitbucket"
.getRepositoryViewerUrl(
"https://root@gitlab.com/root/gitbucket.git",
baseUrl
) == "https://gitlab.com/root/gitbucket"
)
}
}

View File

@@ -202,8 +202,7 @@ class AvatarImageProviderSpec extends AnyFunSpec {
*/
class AvatarImageProviderImpl(account: Option[Account]) extends AvatarImageProvider with RequestCache {
def toHtml(userName: String, size: Int, mailAddress: String = "", tooltip: Boolean = false)(
implicit
def toHtml(userName: String, size: Int, mailAddress: String = "", tooltip: Boolean = false)(implicit
context: Context
): Html = getAvatarImageHtml(userName, size, mailAddress, tooltip)