Compare commits

..

1 Commits

Author SHA1 Message Date
Naoki Takezoe
f16f395539 Disable GitHub Actions cache 2020-07-06 09:59:59 +09:00
274 changed files with 2058 additions and 9798 deletions

View File

@@ -5,10 +5,6 @@ trim_trailing_whitespace = true
insert_final_newline = true insert_final_newline = true
indent_style = space indent_style = space
indent_size = 2 indent_size = 2
end_of_line = lf
[*.md]
trim_trailing_whitespace = false
[*.java] [*.java]
trim_trailing_whitespace = true trim_trailing_whitespace = true

View File

@@ -1,6 +1,6 @@
# The guidelines for contributing # The guidelines for contributing
- At first, see [Wiki](https://github.com/gitbucket/gitbucket/wiki) and check issues and pull requests whether there is a same request in the past. - At first, see [Wiki](https://github.com/gitbucket/gitbucket/wiki) and check issues and pull requests whether there is a same request in the past.
- The highest priority of GitBucket is the ease of installation and API compatibility with GitHub, so your feature request might be rejected if they go against those principles. If you don't wanna waste your time to make a pull request, ask us about your idea at [gitter room](https://gitter.im/gitbucket/gitbucket) before starting your work. - The highest priority of GitBucket is the ease of installation and API compatibility with GitHub, so your feature request might be rejected if they go against those principles. If you don't wanna waste your time to make a pull request, ask us about your idea at [gitter room](https://gitter.im/gitbucket/gitbucket) before staring your work.
- You can edit the GitBucket documentation on Wiki if you have a GitHub account. When you find any mistakes or lacks in the documentation, please update it directly. - You can edit the GitBucket documentation on Wiki if you have a GitHub account. When you find any mistakes or lacks in the documentation, please update it directly.
- All your contributions are handled as [Apache Software License, Version 2.0](https://github.com/gitbucket/gitbucket/blob/master/LICENSE). When you create a pull request or update the documentation, we assume you agreed this clause. - All your contributions are handled as [Apache Software License, Version 2.0](https://github.com/gitbucket/gitbucket/blob/master/LICENSE). When you create a pull request or update the documentation, we assume you agreed this clause.

View File

@@ -1,6 +0,0 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"

View File

@@ -1,25 +1,19 @@
name: build name: build
on: [push, pull_request] on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy: strategy:
matrix: matrix:
java: [8, 11] java: [8, 11]
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Cache
uses: actions/cache@v2
env:
cache-name: cache-sbt-libs
with:
path: |
~/.ivy2/cache
~/.sbt
~/.cache/coursier/v1
key: build-${{ env.cache-name }}-${{ hashFiles('build.sbt') }}
- name: Set up JDK - name: Set up JDK
uses: actions/setup-java@v1 uses: actions/setup-java@v1
with: with:

7
.gitignore vendored
View File

@@ -10,7 +10,6 @@ lib_managed/
src_managed/ src_managed/
project/boot/ project/boot/
project/plugins/project/ project/plugins/project/
.bsp/
# Scala-IDE specific # Scala-IDE specific
.scala_dependencies .scala_dependencies
@@ -29,8 +28,4 @@ project/plugins/project/
# Metals specific # Metals specific
.metals .metals
.bloop .bloop
**/metals.sbt project/metals.sbt
# Visual Studio Code specific
.vscode

View File

@@ -1,51 +1,15 @@
# Changelog # Changelog
All changes to the project will be documented in this file. All changes to the project will be documented in this file.
### 4.35.3 - 14 Jan 2021 ### 4.33.0 - 31 Dec 2019
- Fix a bug that Wiki page cannot be deleted
- Fix a deployment issue on Tomcat
### 4.35.2 - 30 Dec 2020
- Upgrade gitbucket-notifications-plugin to 1.10.0
- Upgrade oauth2-oidc-sdk to 8.29.1 to solve dependency issue
### 4.35.1 - 29 Dec 2020
- Fix database migration issue which happens if webhook is configured
- Call push webhook when pull request is merged
- Show commit status at commits tab of pull request
### 4.35.0 - 25 Dec 2020
- Editor and source viewer color theme
- Auto completion for issues and pull requests
- Upload image from clipboard
- Close multiple issues by commit comment
- Create pull request from online editor
- Milestone overview
- Commit status at various places
- WebAPI coverage improvements
## 4.34.0 - 26 Jul 2020
- Enhancement admin settings UI
- File upload settings
- Restrict repository operations
- User-defined CSS
- Limit the repository list in the sidebar
- Improve MariaDB support
- Improve activity logging
- CLI option to persist session on disk in the standalone mode
- Web API updates
- Add [list commits API](https://developer.github.com/v3/repos/commits/#list-commits)
- Bundled plugins updates
- [gitbucket-gist-plugin](https://github.com/gitbucket/gitbucket-gist-plugin) 4.18.0 -> 4.19.0
- [gitbucket-notifications-plugin](https://github.com/gitbucket/gitbucket-notifications-plugin) 1.8.0 -> 1.9.0
## 4.33.0 - 31 Dec 2019
- All CLI options are configurable by environment variables - All CLI options are configurable by environment variables
- Folding pull request files - Folding pull request files
- WebHook security options - WebHook security options
- Add assignee and assignees properties to some Web APIs' response - Add assignee and assignees properties to some Web APIs' response
## 4.32.0 - 7 Aug 2019 ### 4.32.0 - 7 Aug 2019
- Bump to Scala 2.13.0 and Scalatra 2.7.0 - Bump to Scala 2.13.0 and Scalatra 2.7.0
- Draft pull request - Draft pull request
- Drop network installation of plugins - Drop network installation of plugins
@@ -53,20 +17,20 @@ All changes to the project will be documented in this file.
- Apply default priority to pull requests - Apply default priority to pull requests
- Focus title after clicking issue / pull request edit button - Focus title after clicking issue / pull request edit button
## 4.31.2 - 7 Apr 2019 ### 4.31.2 - 7 Apr 2019
- Bug and security fix - Bug and security fix
## 4.31.1 - 17 Mar 2019 ### 4.31.1 - 17 Mar 2019
- Bug fix - Bug fix
## 4.31.0 - 17 Mar 2019 ### 4.31.0 - 17 Mar 2019
- Docker support in CI plugin - Docker support in CI plugin
- Verify GPG key signed commit - Verify GPG key signed commit
- OAuth2 Token (sent as a parameter) authentication support and new APIs in Web API - OAuth2 Token (sent as a parameter) authentication support and new APIs in Web API
- OGP (Open Graph protocol) support - OGP (Open Graph protocol) support
- Username completion with avatars - Username completion with avatars
## 4.30.1 - 22 Dec 2018 ### 4.30.1 - 22 Dec 2018
- Bug fix for several WebHooks and Web API - Bug fix for several WebHooks and Web API
## 4.30.0 - 15 Dec 2018 ## 4.30.0 - 15 Dec 2018
@@ -153,7 +117,7 @@ All changes to the project will be documented in this file.
- Submodule links to web page - Submodule links to web page
- Clarify close/reopen button - Clarify close/reopen button
## 4.20.0 - 23 Dec 2017 # 4.20.0 - 23 Dec 2017
- Squash and rebase merge strategy for pull requests - Squash and rebase merge strategy for pull requests
- Quick pull request creation - Quick pull request creation
- Download patch from the diff view - Download patch from the diff view

View File

@@ -8,8 +8,6 @@ GitBucket is a Git web platform powered by Scala offering:
- High extensibility by plugins - High extensibility by plugins
- API compatibility with GitHub - API compatibility with GitHub
![GitBucket](https://gitbucket.github.io/img/screenshots/screenshot-repository_viewer.png)
You can try an [online demo](https://gitbucket.herokuapp.com/) *(ID: root / Pass: root)* of GitBucket, and also get the latest information at [GitBucket News](https://gitbucket.github.io/gitbucket-news/). You can try an [online demo](https://gitbucket.herokuapp.com/) *(ID: root / Pass: root)* of GitBucket, and also get the latest information at [GitBucket News](https://gitbucket.github.io/gitbucket-news/).
Features Features
@@ -57,31 +55,13 @@ Support
- If you can't find same question and report, send it to [gitter room](https://gitter.im/gitbucket/gitbucket) before raising an issue. - If you can't find same question and report, send it to [gitter room](https://gitter.im/gitbucket/gitbucket) before raising an issue.
- The highest priority of GitBucket is the ease of installation and API compatibility with GitHub, so your feature request might be rejected if they go against those principles. - The highest priority of GitBucket is the ease of installation and API compatibility with GitHub, so your feature request might be rejected if they go against those principles.
What's New in 4.35.x What's New in 4.33.x
------------- -------------
### 4.35.3 - 14 Jan 2021 ### 4.33.0 - 31 Dec 2019
- Fix a bug that Wiki page cannot be deleted
- Fix a deployment issue on Tomcat
### 4.35.2 - 30 Dec 2020 - All CLI options are configurable by environment variables
- Upgrade gitbucket-notifications-plugin to 1.10.0 - Folding pull request files
- Upgrade oauth2-oidc-sdk to 8.29.1 to solve dependency issue - WebHook security options
- Add assignee and assignees properties to some Web APIs' response
### 4.35.1 - 29 Dec 2020
- Fix database migration issue which happens if webhook is configured
- Call push webhook when pull request is merged
- Show commit status at commits tab of pull request
### 4.35.0 - 25 Dec 2020
- Editor and source viewer color theme
- Auto completion for issues and pull requests
- Upload image from clipboard
- Close multiple issues by commit comment
- Create pull request from online editor
- Milestone overview
- Commit status at various places
- WebAPI coverage improvements
See the [change log](CHANGELOG.md) for all of the updates. See the [change log](CHANGELOG.md) for all of the updates.

View File

@@ -3,10 +3,10 @@ import com.typesafe.sbt.pgp.PgpKeys._
val Organization = "io.github.gitbucket" val Organization = "io.github.gitbucket"
val Name = "gitbucket" val Name = "gitbucket"
val GitBucketVersion = "4.35.3" val GitBucketVersion = "4.33.0"
val ScalatraVersion = "2.7.1" val ScalatraVersion = "2.7.0-RC1"
val JettyVersion = "9.4.32.v20200930" val JettyVersion = "9.4.30.v20200611"
val JgitVersion = "5.9.0.202009080501-r" val JgitVersion = "5.8.0.202006091008-r"
lazy val root = (project in file(".")) lazy val root = (project in file("."))
.enablePlugins(SbtTwirl, ScalatraPlugin) .enablePlugins(SbtTwirl, ScalatraPlugin)
@@ -17,7 +17,7 @@ sourcesInBase := false
organization := Organization organization := Organization
name := Name name := Name
version := GitBucketVersion version := GitBucketVersion
scalaVersion := "2.13.3" scalaVersion := "2.13.1"
scalafmtOnCompile := true scalafmtOnCompile := true
@@ -36,30 +36,32 @@ libraryDependencies ++= Seq(
"org.scalatra" %% "scalatra" % ScalatraVersion, "org.scalatra" %% "scalatra" % ScalatraVersion,
"org.scalatra" %% "scalatra-json" % ScalatraVersion, "org.scalatra" %% "scalatra-json" % ScalatraVersion,
"org.scalatra" %% "scalatra-forms" % ScalatraVersion, "org.scalatra" %% "scalatra-forms" % ScalatraVersion,
"org.json4s" %% "json4s-jackson" % "3.6.10", "org.json4s" %% "json4s-jackson" % "3.6.9",
"commons-io" % "commons-io" % "2.8.0", "commons-io" % "commons-io" % "2.7",
"io.github.gitbucket" % "solidbase" % "1.0.3", "io.github.gitbucket" % "solidbase" % "1.0.3",
"io.github.gitbucket" % "markedj" % "1.0.16", "io.github.gitbucket" % "markedj" % "1.0.16",
"org.apache.commons" % "commons-compress" % "1.20", "org.apache.commons" % "commons-compress" % "1.20",
"org.apache.commons" % "commons-email" % "1.5", "org.apache.commons" % "commons-email" % "1.5",
"commons-net" % "commons-net" % "3.7", "commons-net" % "commons-net" % "3.6",
"org.apache.httpcomponents" % "httpclient" % "4.5.12", "org.apache.httpcomponents" % "httpclient" % "4.5.12",
"org.apache.sshd" % "apache-sshd" % "2.1.0" exclude ("org.slf4j", "slf4j-jdk14") exclude ("org.apache.sshd", "sshd-mina") exclude ("org.apache.sshd", "sshd-netty"), "org.apache.sshd" % "apache-sshd" % "2.1.0" exclude ("org.slf4j", "slf4j-jdk14") exclude ("org.apache.sshd", "sshd-mina") exclude ("org.apache.sshd", "sshd-netty"),
"org.apache.tika" % "tika-core" % "1.24.1", "org.apache.tika" % "tika-core" % "1.24.1",
"com.github.takezoe" %% "blocking-slick-32" % "0.0.12", "com.github.takezoe" %% "blocking-slick-32" % "0.0.12",
"com.novell.ldap" % "jldap" % "2009-10-07", "com.novell.ldap" % "jldap" % "2009-10-07",
"com.h2database" % "h2" % "1.4.199", "com.h2database" % "h2" % "1.4.199",
"org.mariadb.jdbc" % "mariadb-java-client" % "2.7.0", "org.mariadb.jdbc" % "mariadb-java-client" % "2.6.0",
"org.postgresql" % "postgresql" % "42.2.6", "org.postgresql" % "postgresql" % "42.2.6",
"ch.qos.logback" % "logback-classic" % "1.2.3", "ch.qos.logback" % "logback-classic" % "1.2.3",
"com.zaxxer" % "HikariCP" % "3.4.5", "com.zaxxer" % "HikariCP" % "3.4.5",
"com.typesafe" % "config" % "1.4.0", "com.typesafe" % "config" % "1.4.0",
"com.typesafe.akka" %% "akka-actor" % "2.5.27",
"fr.brouillard.oss.security.xhub" % "xhub4j-core" % "1.1.0", "fr.brouillard.oss.security.xhub" % "xhub4j-core" % "1.1.0",
"com.github.bkromhout" % "java-diff-utils" % "2.1.1", "com.github.bkromhout" % "java-diff-utils" % "2.1.1",
"org.cache2k" % "cache2k-all" % "1.2.4.Final", "org.cache2k" % "cache2k-all" % "1.2.4.Final",
"net.coobird" % "thumbnailator" % "0.4.12", "com.enragedginger" %% "akka-quartz-scheduler" % "1.8.1-akka-2.5.x" exclude ("com.mchange", "c3p0") exclude ("com.zaxxer", "HikariCP-java6"),
"net.coobird" % "thumbnailator" % "0.4.11",
"com.github.zafarkhaja" % "java-semver" % "0.9.0", "com.github.zafarkhaja" % "java-semver" % "0.9.0",
"com.nimbusds" % "oauth2-oidc-sdk" % "8.29.1", "com.nimbusds" % "oauth2-oidc-sdk" % "5.64.4",
"org.eclipse.jetty" % "jetty-webapp" % JettyVersion % "provided", "org.eclipse.jetty" % "jetty-webapp" % JettyVersion % "provided",
"javax.servlet" % "javax.servlet-api" % "3.1.0" % "provided", "javax.servlet" % "javax.servlet-api" % "3.1.0" % "provided",
"junit" % "junit" % "4.13" % "test", "junit" % "junit" % "4.13" % "test",
@@ -70,12 +72,11 @@ libraryDependencies ++= Seq(
"org.testcontainers" % "postgresql" % "1.14.3" % "test", "org.testcontainers" % "postgresql" % "1.14.3" % "test",
"net.i2p.crypto" % "eddsa" % "0.3.0", "net.i2p.crypto" % "eddsa" % "0.3.0",
"is.tagomor.woothee" % "woothee-java" % "1.11.0", "is.tagomor.woothee" % "woothee-java" % "1.11.0",
"org.ec4j.core" % "ec4j-core" % "0.0.3", "org.ec4j.core" % "ec4j-core" % "0.0.3"
"org.kohsuke" % "github-api" % "1.116" % "test"
) )
// Compiler settings // Compiler settings
scalacOptions := Seq("-deprecation", "-language:postfixOps", "-opt:l:method", "-feature") scalacOptions := Seq("-deprecation", "-language:postfixOps", "-opt:l:method")
javacOptions in compile ++= Seq("-target", "8", "-source", "8") javacOptions in compile ++= Seq("-target", "8", "-source", "8")
javaOptions in Jetty += "-Dlogback.configurationFile=/logback-dev.xml" javaOptions in Jetty += "-Dlogback.configurationFile=/logback-dev.xml"
@@ -121,12 +122,6 @@ libraryDependencies ++= Seq(
"org.eclipse.jetty" % "jetty-util" % JettyVersion % "executable" "org.eclipse.jetty" % "jetty-util" % JettyVersion % "executable"
) )
// Run package task before test to generate target/webapp for integration test
test in Test := {
_root_.sbt.Keys.`package`.value
(test in Test).value
}
val executableKey = TaskKey[File]("executable") val executableKey = TaskKey[File]("executable")
executableKey := { executableKey := {
import java.util.jar.Attributes.{Name => AttrName} import java.util.jar.Attributes.{Name => AttrName}
@@ -186,9 +181,7 @@ executableKey := {
manifest.getMainAttributes put (AttrName.MANIFEST_VERSION, "1.0") manifest.getMainAttributes put (AttrName.MANIFEST_VERSION, "1.0")
manifest.getMainAttributes put (AttrName.MAIN_CLASS, "JettyLauncher") manifest.getMainAttributes put (AttrName.MAIN_CLASS, "JettyLauncher")
val outputFile = workDir / warName val outputFile = workDir / warName
IO jar (contentMappings.map { case (file, path) => (file, path.toString) }, outputFile, manifest, Some( IO jar (contentMappings.map { case (file, path) => (file, path.toString) }, outputFile, manifest)
System.currentTimeMillis()
))
// generate checksums // generate checksums
Seq( Seq(

View File

@@ -1 +1 @@
sbt.version=1.4.6 sbt.version=1.3.12

View File

@@ -1,4 +1,4 @@
notifications:1.10.0 notifications:1.8.0
gist:4.20.0 gist:4.18.0
emoji:4.6.0 emoji:4.6.0
pages:1.9.0 pages:1.8.0

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<changeSet>
<dropTable tableName="ACTIVITY" />
</changeSet>

View File

@@ -1,39 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<changeSet>
<!--================================================================================================-->
<!-- WEB_HOOK -->
<!--================================================================================================-->
<dropForeignKeyConstraint constraintName="IDX_WEB_HOOK_EVENT_FK0" baseTableName="WEB_HOOK_EVENT"/>
<dropForeignKeyConstraint constraintName="IDX_WEB_HOOK_FK0" baseTableName="WEB_HOOK"/>
<dropPrimaryKey constraintName="IDX_WEB_HOOK_PK" tableName="WEB_HOOK"/>
<createTable tableName="WEB_HOOK_2">
<column name="HOOK_ID" type="int" nullable="true" autoIncrement="true" unique="false" primaryKeyName="IDX_WEB_HOOK_PK" primaryKey="true" />
<column name="USER_NAME" type="varchar(100)" nullable="false"/>
<column name="REPOSITORY_NAME" type="varchar(100)" nullable="false"/>
<column name="URL" type="varchar(200)" nullable="false"/>
<column name="TOKEN" type="varchar(100)" nullable="true"/>
<column name="CTYPE" type="varchar(10)" nullable="true"/>
</createTable>
<sql>
INSERT INTO WEB_HOOK_2 (USER_NAME, REPOSITORY_NAME, URL, TOKEN, CTYPE) SELECT USER_NAME, REPOSITORY_NAME, URL, TOKEN, CTYPE FROM WEB_HOOK
</sql>
<renameTable newTableName="WEB_HOOK_BK" oldTableName="WEB_HOOK"/>
<renameTable newTableName="WEB_HOOK" oldTableName="WEB_HOOK_2"/>
<addUniqueConstraint constraintName="IDX_WEB_HOOK_1" tableName="WEB_HOOK" columnNames="USER_NAME, REPOSITORY_NAME, URL"/>
<addForeignKeyConstraint constraintName="IDX_WEB_HOOK_FK0" baseTableName="WEB_HOOK" baseColumnNames="USER_NAME, REPOSITORY_NAME" referencedTableName="REPOSITORY" referencedColumnNames="USER_NAME, REPOSITORY_NAME"/>
<addForeignKeyConstraint constraintName="IDX_WEB_HOOK_EVENT_FK0" baseTableName="WEB_HOOK_EVENT" baseColumnNames="USER_NAME, REPOSITORY_NAME, URL" referencedTableName="WEB_HOOK" referencedColumnNames="USER_NAME, REPOSITORY_NAME, URL" onDelete="CASCADE" onUpdate="CASCADE"/>
<!--================================================================================================-->
<!-- ACCOUNT_PREFERENCE -->
<!--================================================================================================-->
<createTable tableName="ACCOUNT_PREFERENCE">
<column name="USER_NAME" type="varchar(100)" nullable="false"/>
<column name="HIGHLIGHTER_THEME" type="varchar(100)" nullable="false" defaultValue="prettify"/>
</createTable>
<addPrimaryKey constraintName="IDX_ACCOUNT_PREFERENCE_PK" tableName="ACCOUNT_PREFERENCE" columnNames="USER_NAME"/>
<addForeignKeyConstraint constraintName="IDX_ACCOUNT_PREFERENCE_FK0" baseTableName="ACCOUNT_PREFERENCE" baseColumnNames="USER_NAME" referencedTableName="ACCOUNT" referencedColumnNames="USER_NAME" onDelete="CASCADE" onUpdate="CASCADE"/>
</changeSet>

View File

@@ -1,22 +1,7 @@
package gitbucket.core package gitbucket.core
import java.io.FileOutputStream import io.github.gitbucket.solidbase.migration.{SqlMigration, LiquibaseMigration}
import java.nio.charset.StandardCharsets import io.github.gitbucket.solidbase.model.{Version, Module}
import java.sql.Connection
import java.util
import java.util.UUID
import gitbucket.core.model.Activity
import gitbucket.core.util.Directory.ActivityLog
import gitbucket.core.util.JDBCUtil
import io.github.gitbucket.solidbase.Solidbase
import io.github.gitbucket.solidbase.migration.{LiquibaseMigration, Migration, SqlMigration}
import io.github.gitbucket.solidbase.model.{Module, Version}
import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write
import scala.util.Using
object GitBucketCoreModule object GitBucketCoreModule
extends Module( extends Module(
@@ -80,42 +65,5 @@ object GitBucketCoreModule
new Version("4.31.1"), new Version("4.31.1"),
new Version("4.31.2"), new Version("4.31.2"),
new Version("4.32.0", new LiquibaseMigration("update/gitbucket-core_4.32.xml")), new Version("4.32.0", new LiquibaseMigration("update/gitbucket-core_4.32.xml")),
new Version("4.33.0"), new Version("4.33.0")
new Version(
"4.34.0",
new Migration() {
override def migrate(moduleId: String, version: String, context: util.Map[String, AnyRef]): Unit = {
implicit val formats = Serialization.formats(NoTypeHints)
import JDBCUtil._
val conn = context.get(Solidbase.CONNECTION).asInstanceOf[Connection]
val list = conn.select("SELECT * FROM ACTIVITY ORDER BY ACTIVITY_ID") {
rs =>
Activity(
activityId = UUID.randomUUID().toString,
userName = rs.getString("USER_NAME"),
repositoryName = rs.getString("REPOSITORY_NAME"),
activityUserName = rs.getString("ACTIVITY_USER_NAME"),
activityType = rs.getString("ACTIVITY_TYPE"),
message = rs.getString("MESSAGE"),
additionalInfo = {
val additionalInfo = rs.getString("ADDITIONAL_INFO")
if (rs.wasNull()) None else Some(additionalInfo)
},
activityDate = rs.getTimestamp("ACTIVITY_DATE")
)
}
Using.resource(new FileOutputStream(ActivityLog, true)) { out =>
list.foreach { activity =>
out.write((write(activity) + "\n").getBytes(StandardCharsets.UTF_8))
}
}
}
},
new LiquibaseMigration("update/gitbucket-core_4.34.xml")
),
new Version("4.35.0", new LiquibaseMigration("update/gitbucket-core_4.35.xml")),
new Version("4.35.1"),
new Version("4.35.2"),
new Version("4.35.3"),
) )

View File

@@ -22,12 +22,3 @@ case class ApiBranchForList(
name: String, name: String,
commit: ApiBranchCommit commit: ApiBranchCommit
) )
/**
* https://docs.github.com/en/rest/reference/repos#list-branches-for-head-commit
*/
case class ApiBranchForHeadCommit(
name: String,
commit: ApiBranchCommit,
`protected`: Boolean
)

View File

@@ -4,11 +4,7 @@ import gitbucket.core.service.ProtectedBranchService
import org.json4s._ import org.json4s._
/** https://developer.github.com/v3/repos/#enabling-and-disabling-branch-protection */ /** https://developer.github.com/v3/repos/#enabling-and-disabling-branch-protection */
case class ApiBranchProtection( case class ApiBranchProtection(enabled: Boolean, required_status_checks: Option[ApiBranchProtection.Status]) {
url: Option[ApiPath], // for output
enabled: Boolean,
required_status_checks: Option[ApiBranchProtection.Status]
) {
def status: ApiBranchProtection.Status = required_status_checks.getOrElse(ApiBranchProtection.statusNone) def status: ApiBranchProtection.Status = required_status_checks.getOrElse(ApiBranchProtection.statusNone)
} }
@@ -19,36 +15,13 @@ object ApiBranchProtection {
def apply(info: ProtectedBranchService.ProtectedBranchInfo): ApiBranchProtection = def apply(info: ProtectedBranchService.ProtectedBranchInfo): ApiBranchProtection =
ApiBranchProtection( ApiBranchProtection(
url = Some(
ApiPath(
s"/api/v3/repos/${info.owner}/${info.repository}/branches/${info.branch}/protection"
)
),
enabled = info.enabled, enabled = info.enabled,
required_status_checks = Some( required_status_checks = Some(
Status( Status(EnforcementLevel(info.enabled && info.contexts.nonEmpty, info.includeAdministrators), info.contexts)
Some(
ApiPath(
s"/api/v3/repos/${info.owner}/${info.repository}/branches/${info.branch}/protection/required_status_checks"
)
),
EnforcementLevel(info.enabled && info.contexts.nonEmpty, info.includeAdministrators),
info.contexts,
Some(
ApiPath(
s"/api/v3/repos/${info.owner}/${info.repository}/branches/${info.branch}/protection/required_status_checks/contexts"
)
)
)
) )
) )
val statusNone = Status(None, Off, Seq.empty, None) val statusNone = Status(Off, Seq.empty)
case class Status( case class Status(enforcement_level: EnforcementLevel, contexts: Seq[String])
url: Option[ApiPath], // for output
enforcement_level: EnforcementLevel,
contexts: Seq[String],
contexts_url: Option[ApiPath] // for output
)
sealed class EnforcementLevel(val name: String) sealed class EnforcementLevel(val name: String)
case object Off extends EnforcementLevel("off") case object Off extends EnforcementLevel("off")
case object NonAdmins extends EnforcementLevel("non_admins") case object NonAdmins extends EnforcementLevel("non_admins")

View File

@@ -1,49 +0,0 @@
package gitbucket.core.api
import gitbucket.core.model.{Milestone, Repository}
import gitbucket.core.util.RepositoryName
import java.util.Date
/**
* https://docs.github.com/en/rest/reference/issues#milestones
*/
case class ApiMilestone(
url: ApiPath,
html_url: ApiPath,
// label_url: ApiPath,
id: Int,
number: Int,
state: String,
title: String,
description: String,
// creator: ApiUser, // MILESTONE table does not have created user column
open_issues: Int,
closed_issues: Int,
// created_at: Option[Date],
// updated_at: Option[Date],
closed_at: Option[Date],
due_on: Option[Date]
)
object ApiMilestone {
def apply(
repository: Repository,
milestone: Milestone,
open_issue_count: Int = 0,
closed_issue_count: Int = 0
): ApiMilestone =
ApiMilestone(
url = ApiPath(s"/api/v3/repos/${RepositoryName(repository).fullName}/milestones/${milestone.milestoneId}"),
html_url = ApiPath(s"/${RepositoryName(repository).fullName}/milestone/${milestone.milestoneId}"),
// label_url = ApiPath(s"/api/v3/repos/${RepositoryName(repository).fullName}/milestones/${milestone_number}/labels"),
id = milestone.milestoneId,
number = milestone.milestoneId, // use milestoneId as number
state = if (milestone.closedDate.isDefined) "closed" else "open",
title = milestone.title,
description = milestone.description.getOrElse(""),
open_issues = open_issue_count,
closed_issues = closed_issue_count,
closed_at = milestone.closedDate,
due_on = milestone.dueDate
)
}

View File

@@ -12,13 +12,13 @@ case class ApiRepository(
forks: Int, forks: Int,
`private`: Boolean, `private`: Boolean,
default_branch: String, default_branch: String,
owner: ApiUser, owner: ApiUser
has_issues: Boolean
) { ) {
val id = 0 // dummy id val id = 0 // dummy id
val forks_count = forks val forks_count = forks
val watchers_count = watchers val watchers_count = watchers
val url = ApiPath(s"/api/v3/repos/${full_name}") val url = ApiPath(s"/api/v3/repos/${full_name}")
val http_url = ApiPath(s"/git/${full_name}.git")
val clone_url = ApiPath(s"/git/${full_name}.git") val clone_url = ApiPath(s"/git/${full_name}.git")
val html_url = ApiPath(s"/${full_name}") val html_url = ApiPath(s"/${full_name}")
val ssh_url = Some(SshPath(s":${full_name}.git")) val ssh_url = Some(SshPath(s":${full_name}.git"))
@@ -39,16 +39,11 @@ object ApiRepository {
forks = forkedCount, forks = forkedCount,
`private` = repository.isPrivate, `private` = repository.isPrivate,
default_branch = repository.defaultBranch, default_branch = repository.defaultBranch,
owner = owner, owner = owner
has_issues = if (repository.options.issuesOption == "DISABLE") false else true
) )
def apply(repositoryInfo: RepositoryInfo, owner: ApiUser): ApiRepository = def apply(repositoryInfo: RepositoryInfo, owner: ApiUser): ApiRepository =
ApiRepository( ApiRepository(repositoryInfo.repository, owner, forkedCount = repositoryInfo.forkedCount)
repositoryInfo.repository,
owner,
forkedCount = repositoryInfo.forkedCount
)
def apply(repositoryInfo: RepositoryInfo, owner: Account): ApiRepository = def apply(repositoryInfo: RepositoryInfo, owner: Account): ApiRepository =
this(repositoryInfo, ApiUser(owner)) this(repositoryInfo, ApiUser(owner))
@@ -62,7 +57,6 @@ object ApiRepository {
forks = 0, forks = 0,
`private` = false, `private` = false,
default_branch = "master", default_branch = "master",
owner = owner, owner = owner
has_issues = true
) )
} }

View File

@@ -1,6 +0,0 @@
package gitbucket.core.api
case class ApiRepositoryCollaborator(
permission: String,
user: ApiUser
)

View File

@@ -1,29 +0,0 @@
package gitbucket.core.api
import gitbucket.core.util.RepositoryName
case class ApiTagCommit(
sha: String,
url: ApiPath
)
case class ApiTag(
name: String,
commit: ApiTagCommit,
zipball_url: ApiPath,
tarball_url: ApiPath
)
object ApiTag {
def apply(
tagName: String,
repositoryName: RepositoryName,
commitId: String
): ApiTag =
ApiTag(
name = tagName,
commit = ApiTagCommit(sha = commitId, url = ApiPath(s"/${repositoryName.fullName}/commits/${commitId}")),
zipball_url = ApiPath(s"/${repositoryName.fullName}/archive/${tagName}.zip"),
tarball_url = ApiPath(s"/${repositoryName.fullName}/archive/${tagName}.tar.gz")
)
}

View File

@@ -1,46 +0,0 @@
package gitbucket.core.api
import gitbucket.core.model.Profile.{RepositoryWebHookEvents, RepositoryWebHooks}
import gitbucket.core.model.{RepositoryWebHook, WebHook}
import gitbucket.core.util.RepositoryName
/**
* https://docs.github.com/en/rest/reference/repos#webhooks
*/
case class ApiWebhookConfig(
content_type: String,
// insecure_ssl: String,
url: String
)
case class ApiWebhook(
`type`: String,
id: Int,
name: String,
active: Boolean,
events: List[String],
config: ApiWebhookConfig,
// updated_at: Option[Date],
// created_at: Option[Date],
url: ApiPath,
// test_url: ApiPath,
// ping_url: ApiPath,
// last_response: ...
)
object ApiWebhook {
def apply(
_type: String,
hook: RepositoryWebHook,
hookEvents: Set[WebHook.Event]
): ApiWebhook =
ApiWebhook(
`type` = _type,
id = hook.hookId,
name = "web", // dummy
active = true, // dummy
events = hookEvents.toList.map(_.name),
config = ApiWebhookConfig(hook.ctype.code, hook.url),
url = ApiPath(s"/api/v3/${hook.userName}/${hook.repositoryName}/hooks/${hook.hookId}")
)
}

View File

@@ -1,14 +0,0 @@
package gitbucket.core.api
import java.util.Date
case class CreateAMilestone(
title: String,
state: String = "open",
description: Option[String],
due_on: Option[Date]
) {
def isValid: Boolean = {
title.length <= 100 && title.matches("[a-zA-Z0-9\\-\\+_.]+")
}
}

View File

@@ -15,11 +15,3 @@ case class CreateAPullRequestAlt(
base: String, base: String,
maintainer_can_modify: Option[Boolean] maintainer_can_modify: Option[Boolean]
) )
case class UpdateAPullRequest(
title: Option[String],
body: Option[String],
state: Option[String],
base: Option[String],
maintainer_can_modify: Option[Boolean],
)

View File

@@ -1,7 +0,0 @@
package gitbucket.core.api
/**
* https://docs.github.com/en/free-pro-team@latest/rest/reference/git#create-a-reference
* api form
*/
case class CreateARef(ref: String, sha: String)

View File

@@ -1,35 +0,0 @@
package gitbucket.core.api
case class CreateARepositoryWebhookConfig(
url: String,
content_type: String = "form",
insecure_ssl: String = "0",
secret: Option[String]
)
/**
* https://docs.github.com/en/rest/reference/repos#create-a-repository-webhook
*/
case class CreateARepositoryWebhook(
name: String = "web",
config: CreateARepositoryWebhookConfig,
events: List[String] = List("push"),
active: Boolean = true
) {
def isValid: Boolean = {
config.content_type == "form" || config.content_type == "json"
}
}
case class UpdateARepositoryWebhook(
name: String = "web",
config: CreateARepositoryWebhookConfig,
events: List[String] = List("push"),
add_events: List[String] = List(),
remove_events: List[String] = List(),
active: Boolean = true
) {
def isValid: Boolean = {
config.content_type == "form" || config.content_type == "json"
}
}

View File

@@ -1,23 +0,0 @@
package gitbucket.core.api
/**
* https://docs.github.com/en/rest/reference/pulls#merge-a-pull-request
*/
case class MergeAPullRequest(
commit_title: Option[String],
commit_message: Option[String],
/* TODO: Not Implemented
sha: Option[String],*/
merge_method: Option[String]
)
case class SuccessToMergePrResponse(
sha: String,
merged: Boolean,
message: String
)
case class FailToMergePrResponse(
documentation_url: String,
message: String
)

View File

@@ -1,7 +0,0 @@
package gitbucket.core.api
/**
* https://docs.github.com/en/free-pro-team@latest/rest/reference/git#update-a-reference
* api form
*/
case class UpdateARef(sha: String, force: Boolean)

View File

@@ -35,7 +35,6 @@ class AccountController
with WebHookService with WebHookService
with PrioritiesService with PrioritiesService
with RepositoryCreationService with RepositoryCreationService
with RequestCache
trait AccountControllerBase extends AccountManagementControllerBase { trait AccountControllerBase extends AccountManagementControllerBase {
self: AccountService self: AccountService
@@ -82,8 +81,6 @@ trait AccountControllerBase extends AccountManagementControllerBase {
case class PersonalTokenForm(note: String) case class PersonalTokenForm(note: String)
case class SyntaxHighlighterThemeForm(theme: String)
val newForm = mapping( val newForm = mapping(
"userName" -> trim(label("User name", text(required, maxlength(100), identifier, uniqueUserName, reservedNames))), "userName" -> trim(label("User name", text(required, maxlength(100), identifier, uniqueUserName, reservedNames))),
"password" -> trim(label("Password", text(required, maxlength(20)))), "password" -> trim(label("Password", text(required, maxlength(20)))),
@@ -124,10 +121,6 @@ trait AccountControllerBase extends AccountManagementControllerBase {
"note" -> trim(label("Token", text(required, maxlength(100)))) "note" -> trim(label("Token", text(required, maxlength(100))))
)(PersonalTokenForm.apply) )(PersonalTokenForm.apply)
val syntaxHighlighterThemeForm = mapping(
"highlighterTheme" -> trim(label("Theme", text(required)))
)(SyntaxHighlighterThemeForm.apply)
case class NewGroupForm( case class NewGroupForm(
groupName: String, groupName: String,
description: Option[String], description: Option[String],
@@ -448,29 +441,6 @@ trait AccountControllerBase extends AccountManagementControllerBase {
redirect(s"/${userName}/_application") redirect(s"/${userName}/_application")
}) })
/**
* Display the user preference settings page
*/
get("/:userName/_preferences")(oneselfOnly {
val userName = params("userName")
val currentTheme = getAccountPreference(userName) match {
case Some(accountHighlighter) => accountHighlighter.highlighterTheme
case _ => "github-v2"
}
getAccountByUserName(userName).map { x =>
html.preferences(x, currentTheme)
} getOrElse NotFound()
})
/**
* Update the syntax highlighter setting of user
*/
post("/:userName/_preferences/highlighter", syntaxHighlighterThemeForm)(oneselfOnly { form =>
val userName = params("userName")
addOrUpdateAccountPreference(userName, form.theme)
redirect(s"/${userName}/_preferences")
})
get("/:userName/_hooks")(managersOnly { get("/:userName/_hooks")(managersOnly {
val userName = params("userName") val userName = params("userName")
getAccountByUserName(userName).map { account => getAccountByUserName(userName).map { account =>
@@ -551,8 +521,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
val url = params("url") val url = params("url")
val token = Some(params("token")) val token = Some(params("token"))
val ctype = WebHookContentType.valueOf(params("ctype")) val ctype = WebHookContentType.valueOf(params("ctype"))
val dummyWebHookInfo = val dummyWebHookInfo = RepositoryWebHook(userName, "dummy", url, ctype, token)
RepositoryWebHook(userName = userName, repositoryName = "dummy", url = url, ctype = ctype, token = token)
val dummyPayload = { val dummyPayload = {
val ownerAccount = getAccountByUserName(userName).get val ownerAccount = getAccountByUserName(userName).get
WebHookPushPayload.createDummyPayload(ownerAccount) WebHookPushPayload.createDummyPayload(ownerAccount)

View File

@@ -13,7 +13,6 @@ class ApiController
with ApiIssueCommentControllerBase with ApiIssueCommentControllerBase
with ApiIssueControllerBase with ApiIssueControllerBase
with ApiIssueLabelControllerBase with ApiIssueLabelControllerBase
with ApiIssueMilestoneControllerBase
with ApiOrganizationControllerBase with ApiOrganizationControllerBase
with ApiPullRequestControllerBase with ApiPullRequestControllerBase
with ApiReleaseControllerBase with ApiReleaseControllerBase
@@ -23,7 +22,6 @@ class ApiController
with ApiRepositoryContentsControllerBase with ApiRepositoryContentsControllerBase
with ApiRepositoryControllerBase with ApiRepositoryControllerBase
with ApiRepositoryStatusControllerBase with ApiRepositoryStatusControllerBase
with ApiRepositoryWebhookControllerBase
with ApiUserControllerBase with ApiUserControllerBase
with RepositoryService with RepositoryService
with AccountService with AccountService
@@ -54,7 +52,6 @@ class ApiController
with ReferrerAuthenticator with ReferrerAuthenticator
with ReadableUsersAuthenticator with ReadableUsersAuthenticator
with WritableUsersAuthenticator with WritableUsersAuthenticator
with RequestCache
trait ApiControllerBase extends ControllerBase { trait ApiControllerBase extends ControllerBase {

View File

@@ -421,7 +421,7 @@ trait AccountManagementControllerBase extends ControllerBase {
"new" "new"
) )
protected def reservedNames: Constraint = new Constraint() { protected def reservedNames(): Constraint = new Constraint() {
override def validate(name: String, value: String, messages: Messages): Option[String] = override def validate(name: String, value: String, messages: Messages): Option[String] =
if (allReservedNames.contains(value.toLowerCase)) { if (allReservedNames.contains(value.toLowerCase)) {
Some(s"${value} is reserved") Some(s"${value} is reserved")

View File

@@ -21,17 +21,10 @@ class DashboardController
with WebHookPullRequestService with WebHookPullRequestService
with WebHookPullRequestReviewCommentService with WebHookPullRequestReviewCommentService
with MilestonesService with MilestonesService
with CommitStatusService
with UsersAuthenticator with UsersAuthenticator
with RequestCache
trait DashboardControllerBase extends ControllerBase { trait DashboardControllerBase extends ControllerBase {
self: IssuesService self: IssuesService with PullRequestService with RepositoryService with AccountService with UsersAuthenticator =>
with PullRequestService
with RepositoryService
with AccountService
with CommitStatusService
with UsersAuthenticator =>
get("/dashboard/repos")(usersOnly { get("/dashboard/repos")(usersOnly {
val repos = getVisibleRepositories( val repos = getVisibleRepositories(
@@ -92,13 +85,12 @@ trait DashboardControllerBase extends ControllerBase {
val condition = getOrCreateCondition(Keys.Session.DashboardIssues, filter, userName) val condition = getOrCreateCondition(Keys.Session.DashboardIssues, filter, userName)
val userRepos = getUserRepositories(userName, true).map(repo => repo.owner -> repo.name) val userRepos = getUserRepositories(userName, true).map(repo => repo.owner -> repo.name)
val page = IssueSearchCondition.page(request) val page = IssueSearchCondition.page(request)
val issues = searchIssue(condition, IssueSearchOption.Issues, (page - 1) * IssueLimit, IssueLimit, userRepos: _*)
html.issues( html.issues(
issues.map(issue => (issue, None)), searchIssue(condition, false, (page - 1) * IssueLimit, IssueLimit, userRepos: _*),
page, page,
countIssue(condition.copy(state = "open"), IssueSearchOption.Issues, userRepos: _*), countIssue(condition.copy(state = "open"), false, userRepos: _*),
countIssue(condition.copy(state = "closed"), IssueSearchOption.Issues, userRepos: _*), countIssue(condition.copy(state = "closed"), false, userRepos: _*),
filter match { filter match {
case "assigned" => condition.copy(assigned = Some(Some(userName))) case "assigned" => condition.copy(assigned = Some(Some(userName)))
case "mentioned" => condition.copy(mentioned = Some(userName)) case "mentioned" => condition.copy(mentioned = Some(userName))
@@ -123,24 +115,12 @@ trait DashboardControllerBase extends ControllerBase {
val condition = getOrCreateCondition(Keys.Session.DashboardPulls, filter, userName) val condition = getOrCreateCondition(Keys.Session.DashboardPulls, filter, userName)
val allRepos = getAllRepositories(userName) val allRepos = getAllRepositories(userName)
val page = IssueSearchCondition.page(request) val page = IssueSearchCondition.page(request)
val issues = searchIssue(
condition,
IssueSearchOption.PullRequests,
(page - 1) * PullRequestLimit,
PullRequestLimit,
allRepos: _*
)
val status = issues.map { issue =>
issue.commitId.flatMap { commitId =>
getCommitStatusWithSummary(issue.issue.userName, issue.issue.repositoryName, commitId)
}
}
html.pulls( html.pulls(
issues.zip(status), searchIssue(condition, true, (page - 1) * PullRequestLimit, PullRequestLimit, allRepos: _*),
page, page,
countIssue(condition.copy(state = "open"), IssueSearchOption.PullRequests, allRepos: _*), countIssue(condition.copy(state = "open"), true, allRepos: _*),
countIssue(condition.copy(state = "closed"), IssueSearchOption.PullRequests, allRepos: _*), countIssue(condition.copy(state = "closed"), true, allRepos: _*),
filter match { filter match {
case "assigned" => condition.copy(assigned = Some(Some(userName))) case "assigned" => condition.copy(assigned = Some(Some(userName)))
case "mentioned" => condition.copy(mentioned = Some(userName)) case "mentioned" => condition.copy(mentioned = Some(userName))

View File

@@ -37,7 +37,7 @@ class FileUploadController
execute( execute(
{ (file, fileId) => { (file, fileId) =>
FileUtils FileUtils
.writeByteArrayToFile(new File(getTemporaryDir(session.getId), FileUtil.checkFilename(fileId)), file.get()) .writeByteArrayToFile(new File(getTemporaryDir(session.getId), FileUtil.checkFilename(fileId)), file.get)
session += Keys.Session.Upload(fileId) -> file.name session += Keys.Session.Upload(fileId) -> file.name
}, },
FileUtil.isImage FileUtil.isImage
@@ -49,7 +49,7 @@ class FileUploadController
execute( execute(
{ (file, fileId) => { (file, fileId) =>
FileUtils FileUtils
.writeByteArrayToFile(new File(getTemporaryDir(session.getId), FileUtil.checkFilename(fileId)), file.get()) .writeByteArrayToFile(new File(getTemporaryDir(session.getId), FileUtil.checkFilename(fileId)), file.get)
session += Keys.Session.Upload(fileId) -> file.name session += Keys.Session.Upload(fileId) -> file.name
}, },
_ => true _ => true
@@ -65,7 +65,7 @@ class FileUploadController
getAttachedDir(params("owner"), params("repository")), getAttachedDir(params("owner"), params("repository")),
FileUtil.checkFilename(fileId + "." + FileUtil.getExtension(file.getName)) FileUtil.checkFilename(fileId + "." + FileUtil.getExtension(file.getName))
), ),
file.get() file.get
) )
}, },
_ => true _ => true
@@ -144,7 +144,7 @@ class FileUploadController
{ (file, fileId) => { (file, fileId) =>
FileUtils.writeByteArrayToFile( FileUtils.writeByteArrayToFile(
new File(getReleaseFilesDir(owner, repository), FileUtil.checkFilename(tag + "/" + fileId)), new File(getReleaseFilesDir(owner, repository), FileUtil.checkFilename(tag + "/" + fileId)),
file.get() file.get
) )
}, },
_ => true _ => true

View File

@@ -29,7 +29,6 @@ class IndexController
with AccessTokenService with AccessTokenService
with AccountFederationService with AccountFederationService
with OpenIDConnectService with OpenIDConnectService
with RequestCache
trait IndexControllerBase extends ControllerBase { trait IndexControllerBase extends ControllerBase {
self: RepositoryService self: RepositoryService
@@ -79,7 +78,7 @@ trait IndexControllerBase extends ControllerBase {
} }
.getOrElse { .getOrElse {
gitbucket.core.html.index( gitbucket.core.html.index(
getRecentPublicActivities(), getRecentActivities(),
getVisibleRepositories(None, withoutPhysicalInfo = true), getVisibleRepositories(None, withoutPhysicalInfo = true),
showBannerToCreatePersonalAccessToken = false showBannerToCreatePersonalAccessToken = false
) )
@@ -162,7 +161,7 @@ trait IndexControllerBase extends ControllerBase {
get("/activities.atom") { get("/activities.atom") {
contentType = "application/atom+xml; type=feed" contentType = "application/atom+xml; type=feed"
xml.feed(getRecentPublicActivities()) xml.feed(getRecentActivities())
} }
post("/sidebar-collapse") { post("/sidebar-collapse") {
@@ -213,10 +212,8 @@ trait IndexControllerBase extends ControllerBase {
} }
.map { t => .map { t =>
Map( Map(
"label" -> s"${avatar(t.userName, 16)}<b>@${StringUtil.escapeHtml( "label" -> s"${avatar(t.userName, 16)}<b>@${StringUtil.escapeHtml(t.userName)}</b> ${StringUtil
StringUtil.cutTail(t.userName, 25, "...") .escapeHtml(t.fullName)}",
)}</b> ${StringUtil
.escapeHtml(StringUtil.cutTail(t.fullName, 25, "..."))}",
"value" -> t.userName "value" -> t.userName
) )
} }

View File

@@ -30,7 +30,6 @@ class IssuesController
with WebHookPullRequestReviewCommentService with WebHookPullRequestReviewCommentService
with CommitsService with CommitsService
with PrioritiesService with PrioritiesService
with RequestCache
trait IssuesControllerBase extends ControllerBase { trait IssuesControllerBase extends ControllerBase {
self: IssuesService self: IssuesService
@@ -112,7 +111,6 @@ trait IssuesControllerBase extends ControllerBase {
getLabels(owner, name), getLabels(owner, name),
isIssueEditable(repository), isIssueEditable(repository),
isIssueManageable(repository), isIssueManageable(repository),
isIssueCommentManageable(repository),
repository repository
) )
} }
@@ -239,8 +237,8 @@ trait IssuesControllerBase extends ControllerBase {
defining(repository.owner, repository.name) { defining(repository.owner, repository.name) {
case (owner, name) => case (owner, name) =>
getComment(owner, name, params("id")).map { comment => getComment(owner, name, params("id")).map { comment =>
if (isDeletableComment(owner, name, comment.commentedUserName)) { if (isEditableContent(owner, name, comment.commentedUserName)) {
Ok(deleteComment(repository.owner, repository.name, comment.issueId, comment.commentId)) Ok(deleteComment(comment.issueId, comment.commentId))
} else Unauthorized() } else Unauthorized()
} getOrElse NotFound() } getOrElse NotFound()
} }
@@ -370,9 +368,6 @@ trait IssuesControllerBase extends ControllerBase {
} }
case _ => BadRequest() case _ => BadRequest()
} }
if (params("uri").nonEmpty) {
redirect(params("uri"))
}
} }
}) })
@@ -381,9 +376,6 @@ trait IssuesControllerBase extends ControllerBase {
executeBatch(repository) { issueId => executeBatch(repository) { issueId =>
getIssueLabel(repository.owner, repository.name, issueId, labelId) getOrElse { getIssueLabel(repository.owner, repository.name, issueId, labelId) getOrElse {
registerIssueLabel(repository.owner, repository.name, issueId, labelId, true) registerIssueLabel(repository.owner, repository.name, issueId, labelId, true)
if (params("uri").nonEmpty) {
redirect(params("uri"))
}
} }
} }
} getOrElse NotFound() } getOrElse NotFound()
@@ -394,9 +386,6 @@ trait IssuesControllerBase extends ControllerBase {
executeBatch(repository) { executeBatch(repository) {
updateAssignedUserName(repository.owner, repository.name, _, value, true) updateAssignedUserName(repository.owner, repository.name, _, value, true)
} }
if (params("uri").nonEmpty) {
redirect(params("uri"))
}
} }
}) })
@@ -427,29 +416,6 @@ trait IssuesControllerBase extends ControllerBase {
}) getOrElse NotFound() }) getOrElse NotFound()
}) })
/**
* JSON API for issue and PR completion.
*/
ajaxGet("/:owner/:repository/_issue/proposals")(writableUsersOnly { repository =>
contentType = formats("json")
org.json4s.jackson.Serialization.write(
Map(
"options" -> (
getOpenIssues(repository.owner, repository.name)
.map { t =>
Map(
"label" -> s"""${if (t.isPullRequest) "<i class='octicon octicon-git-pull-request'></i>"
else "<i class='octicon octicon-issue-opened'></i>"}<b> #${StringUtil
.escapeHtml(t.issueId.toString)} ${StringUtil
.escapeHtml(StringUtil.cutTail(t.title, 50, "..."))}</b>""",
"value" -> t.issueId.toString
)
}
)
)
)
})
val assignedUserName = (key: String) => params.get(key) filter (_.trim != "") val assignedUserName = (key: String) => params.get(key) filter (_.trim != "")
val milestoneId: String => Option[Int] = (key: String) => params.get(key).flatMap(_.toIntOpt) val milestoneId: String => Option[Int] = (key: String) => params.get(key).flatMap(_.toIntOpt)
val priorityId: String => Option[Int] = (key: String) => params.get(key).flatMap(_.toIntOpt) val priorityId: String => Option[Int] = (key: String) => params.get(key).flatMap(_.toIntOpt)
@@ -459,7 +425,6 @@ trait IssuesControllerBase extends ControllerBase {
params("from") match { params("from") match {
case "issues" => redirect(s"/${repository.owner}/${repository.name}/issues") case "issues" => redirect(s"/${repository.owner}/${repository.name}/issues")
case "pulls" => redirect(s"/${repository.owner}/${repository.name}/pulls") case "pulls" => redirect(s"/${repository.owner}/${repository.name}/pulls")
case _ =>
} }
} }
@@ -467,22 +432,20 @@ trait IssuesControllerBase extends ControllerBase {
defining(repository.owner, repository.name) { defining(repository.owner, repository.name) {
case (owner, repoName) => case (owner, repoName) =>
val page = IssueSearchCondition.page(request) val page = IssueSearchCondition.page(request)
// retrieve search condition // retrieve search condition
val condition = IssueSearchCondition(request) val condition = IssueSearchCondition(request)
// search issues
val issues =
searchIssue(condition, IssueSearchOption.Issues, (page - 1) * IssueLimit, IssueLimit, owner -> repoName)
html.list( html.list(
"issues", "issues",
issues.map(issue => (issue, None)), searchIssue(condition, false, (page - 1) * IssueLimit, IssueLimit, owner -> repoName),
page, page,
getAssignableUserNames(owner, repoName), getAssignableUserNames(owner, repoName),
getMilestones(owner, repoName), getMilestones(owner, repoName),
getPriorities(owner, repoName), getPriorities(owner, repoName),
getLabels(owner, repoName), getLabels(owner, repoName),
countIssue(condition.copy(state = "open"), IssueSearchOption.Issues, owner -> repoName), countIssue(condition.copy(state = "open"), false, owner -> repoName),
countIssue(condition.copy(state = "closed"), IssueSearchOption.Issues, owner -> repoName), countIssue(condition.copy(state = "closed"), false, owner -> repoName),
condition, condition,
repository, repository,
isIssueEditable(repository), isIssueEditable(repository),
@@ -499,13 +462,4 @@ trait IssuesControllerBase extends ControllerBase {
): Boolean = { ): Boolean = {
hasDeveloperRole(owner, repository, context.loginAccount) || author == context.loginAccount.get.userName hasDeveloperRole(owner, repository, context.loginAccount) || author == context.loginAccount.get.userName
} }
/**
* Tests whether an issue comment is deletable by a logged-in user.
*/
private def isDeletableComment(owner: String, repository: String, author: String)(
implicit context: Context
): Boolean = {
hasOwnerRole(owner, repository, context.loginAccount) || author == context.loginAccount.get.userName
}
} }

View File

@@ -1,18 +1,10 @@
package gitbucket.core.controller package gitbucket.core.controller
import gitbucket.core.issues.milestones.html import gitbucket.core.issues.milestones.html
import gitbucket.core.service.IssuesService.{IssueLimit, IssueSearchCondition} import gitbucket.core.service.{AccountService, MilestonesService, RepositoryService}
import gitbucket.core.service.{
AccountService,
CommitStatusService,
IssueSearchOption,
MilestonesService,
RepositoryService
}
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits._
import gitbucket.core.util.{ReferrerAuthenticator, WritableUsersAuthenticator} import gitbucket.core.util.{ReferrerAuthenticator, WritableUsersAuthenticator}
import gitbucket.core.util.SyntaxSugars._ import gitbucket.core.util.SyntaxSugars._
import gitbucket.core.view.helpers.{getAssignableUserNames, getLabels, getPriorities, searchIssue}
import org.scalatra.forms._ import org.scalatra.forms._
import org.scalatra.i18n.Messages import org.scalatra.i18n.Messages
@@ -21,16 +13,11 @@ class MilestonesController
with MilestonesService with MilestonesService
with RepositoryService with RepositoryService
with AccountService with AccountService
with CommitStatusService
with ReferrerAuthenticator with ReferrerAuthenticator
with WritableUsersAuthenticator with WritableUsersAuthenticator
trait MilestonesControllerBase extends ControllerBase { trait MilestonesControllerBase extends ControllerBase {
self: MilestonesService self: MilestonesService with RepositoryService with ReferrerAuthenticator with WritableUsersAuthenticator =>
with RepositoryService
with CommitStatusService
with ReferrerAuthenticator
with WritableUsersAuthenticator =>
case class MilestoneForm(title: String, description: Option[String], dueDate: Option[java.util.Date]) case class MilestoneForm(title: String, description: Option[String], dueDate: Option[java.util.Date])
@@ -49,41 +36,6 @@ trait MilestonesControllerBase extends ControllerBase {
) )
}) })
get("/:owner/:repository/milestone/:id")(referrersOnly { repository =>
val milestone = getMilestone(repository.owner, repository.name, params("id").toInt)
val page = IssueSearchCondition.page(request)
val condition = IssueSearchCondition(
request,
milestone.get.title
)
val issues = searchIssue(
condition,
IssueSearchOption.Both,
(page - 1) * IssueLimit,
IssueLimit,
repository.owner -> repository.name
)
val status = issues.map { issue =>
issue.commitId.flatMap { commitId =>
getCommitStatusWithSummary(issue.issue.userName, issue.issue.repositoryName, commitId)
}
}
html.milestone(
condition.state,
issues.zip(status),
page,
getAssignableUserNames(repository.owner, repository.name),
getPriorities(repository.owner, repository.name),
getLabels(repository.owner, repository.name),
condition,
getMilestonesWithIssueCount(repository.owner, repository.name)
.filter(p => p._1.milestoneId == milestone.get.milestoneId),
repository,
hasDeveloperRole(repository.owner, repository.name, context.loginAccount)
)
})
get("/:owner/:repository/issues/milestones/new")(writableUsersOnly { get("/:owner/:repository/issues/milestones/new")(writableUsersOnly {
html.edit(None, _) html.edit(None, _)
}) })

View File

@@ -1,6 +1,5 @@
package gitbucket.core.controller package gitbucket.core.controller
import gitbucket.core.model.activity.DeleteBranchInfo
import gitbucket.core.pulls.html import gitbucket.core.pulls.html
import gitbucket.core.service.CommitStatusService import gitbucket.core.service.CommitStatusService
import gitbucket.core.service.MergeService import gitbucket.core.service.MergeService
@@ -37,7 +36,6 @@ class PullRequestsController
with MergeService with MergeService
with ProtectedBranchService with ProtectedBranchService
with PrioritiesService with PrioritiesService
with RequestCache
trait PullRequestsControllerBase extends ControllerBase { trait PullRequestsControllerBase extends ControllerBase {
self: RepositoryService self: RepositoryService
@@ -169,16 +167,10 @@ trait PullRequestsControllerBase extends ControllerBase {
val (commits, diffs) = val (commits, diffs) =
getRequestCompareInfo(owner, name, pullreq.commitIdFrom, owner, name, pullreq.commitIdTo) getRequestCompareInfo(owner, name, pullreq.commitIdFrom, owner, name, pullreq.commitIdTo)
val commitsWithStatus = commits.map { day =>
day.map { commit =>
(commit, getCommitStatusWithSummary(repository.owner, repository.name, commit.id))
}
}
html.commits( html.commits(
issue, issue,
pullreq, pullreq,
commitsWithStatus, commits,
getPullRequestComments(owner, name, issue.issueId, commits.flatten), getPullRequestComments(owner, name, issue.issueId, commits.flatten),
diffs.size, diffs.size,
isManageable(repository), isManageable(repository),
@@ -225,7 +217,7 @@ trait PullRequestsControllerBase extends ControllerBase {
val branchProtection = getProtectedBranchInfo(owner, name, pullreq.branch) val branchProtection = getProtectedBranchInfo(owner, name, pullreq.branch)
val mergeStatus = PullRequestService.MergeStatus( val mergeStatus = PullRequestService.MergeStatus(
conflictMessage = conflictMessage, conflictMessage = conflictMessage,
commitStatuses = getCommitStatuses(owner, name, pullreq.commitIdTo), commitStatues = getCommitStatues(owner, name, pullreq.commitIdTo),
branchProtection = branchProtection, branchProtection = branchProtection,
branchIsOutOfDate = JGitUtil.getShaByRef(owner, name, pullreq.branch) != Some(pullreq.commitIdFrom), branchIsOutOfDate = JGitUtil.getShaByRef(owner, name, pullreq.branch) != Some(pullreq.commitIdFrom),
needStatusCheck = context.loginAccount needStatusCheck = context.loginAccount
@@ -279,8 +271,7 @@ trait PullRequestsControllerBase extends ControllerBase {
val userName = context.loginAccount.get.userName val userName = context.loginAccount.get.userName
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git => Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
git.branchDelete().setForce(true).setBranchNames(pullreq.requestBranch).call() git.branchDelete().setForce(true).setBranchNames(pullreq.requestBranch).call()
val deleteBranchInfo = DeleteBranchInfo(repository.owner, repository.name, userName, pullreq.requestBranch) recordDeleteBranchActivity(repository.owner, repository.name, userName, pullreq.requestBranch)
recordActivity(deleteBranchInfo)
} }
createComment( createComment(
baseRepository.owner, baseRepository.owner,
@@ -643,33 +634,20 @@ trait PullRequestsControllerBase extends ControllerBase {
defining(repository.owner, repository.name) { defining(repository.owner, repository.name) {
case (owner, repoName) => case (owner, repoName) =>
val page = IssueSearchCondition.page(request) val page = IssueSearchCondition.page(request)
// retrieve search condition // retrieve search condition
val condition = IssueSearchCondition(request) val condition = IssueSearchCondition(request)
// search issues
val issues = searchIssue(
condition,
IssueSearchOption.PullRequests,
(page - 1) * PullRequestLimit,
PullRequestLimit,
owner -> repoName
)
// commit status
val status = issues.map { issue =>
issue.commitId.flatMap { commitId =>
getCommitStatusWithSummary(owner, repoName, commitId)
}
}
gitbucket.core.issues.html.list( gitbucket.core.issues.html.list(
"pulls", "pulls",
issues.zip(status), searchIssue(condition, true, (page - 1) * PullRequestLimit, PullRequestLimit, owner -> repoName),
page, page,
getAssignableUserNames(owner, repoName), getAssignableUserNames(owner, repoName),
getMilestones(owner, repoName), getMilestones(owner, repoName),
getPriorities(owner, repoName), getPriorities(owner, repoName),
getLabels(owner, repoName), getLabels(owner, repoName),
countIssue(condition.copy(state = "open"), IssueSearchOption.PullRequests, owner -> repoName), countIssue(condition.copy(state = "open"), true, owner -> repoName),
countIssue(condition.copy(state = "closed"), IssueSearchOption.PullRequests, owner -> repoName), countIssue(condition.copy(state = "closed"), true, owner -> repoName),
condition, condition,
repository, repository,
isEditable(repository), isEditable(repository),

View File

@@ -2,15 +2,7 @@ package gitbucket.core.controller
import java.io.File import java.io.File
import gitbucket.core.model.activity.ReleaseInfo import gitbucket.core.service.{AccountService, ActivityService, PaginationHelper, ReleaseService, RepositoryService}
import gitbucket.core.service.{
AccountService,
ActivityService,
PaginationHelper,
ReleaseService,
RepositoryService,
RequestCache
}
import gitbucket.core.util._ import gitbucket.core.util._
import gitbucket.core.util.Directory._ import gitbucket.core.util.Directory._
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits._
@@ -30,7 +22,6 @@ class ReleaseController
with ReadableUsersAuthenticator with ReadableUsersAuthenticator
with ReferrerAuthenticator with ReferrerAuthenticator
with WritableUsersAuthenticator with WritableUsersAuthenticator
with RequestCache
trait ReleaseControllerBase extends ControllerBase { trait ReleaseControllerBase extends ControllerBase {
self: RepositoryService self: RepositoryService
@@ -128,8 +119,7 @@ trait ReleaseControllerBase extends ControllerBase {
createReleaseAsset(repository.owner, repository.name, tagName, fileId, fileName, size, loginAccount) createReleaseAsset(repository.owner, repository.name, tagName, fileId, fileName, size, loginAccount)
} }
val releaseInfo = ReleaseInfo(repository.owner, repository.name, loginAccount.userName, form.name, tagName) recordReleaseActivity(repository.owner, repository.name, loginAccount.userName, form.name, tagName)
recordActivity(releaseInfo)
redirect(s"/${repository.owner}/${repository.name}/releases/${tagName}") redirect(s"/${repository.owner}/${repository.name}/releases/${tagName}")
}) })

View File

@@ -13,7 +13,6 @@ import gitbucket.core.util.SyntaxSugars._
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits._
import gitbucket.core.util.Directory._ import gitbucket.core.util.Directory._
import gitbucket.core.model.WebHookContentType import gitbucket.core.model.WebHookContentType
import gitbucket.core.model.activity.RenameRepositoryInfo
import org.scalatra.forms._ import org.scalatra.forms._
import org.scalatra.i18n.Messages import org.scalatra.i18n.Messages
import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.Git
@@ -31,10 +30,8 @@ class RepositorySettingsController
with ProtectedBranchService with ProtectedBranchService
with CommitStatusService with CommitStatusService
with DeployKeyService with DeployKeyService
with ActivityService
with OwnerAuthenticator with OwnerAuthenticator
with UsersAuthenticator with UsersAuthenticator
with RequestCache
trait RepositorySettingsControllerBase extends ControllerBase { trait RepositorySettingsControllerBase extends ControllerBase {
self: RepositoryService self: RepositoryService
@@ -43,7 +40,6 @@ trait RepositorySettingsControllerBase extends ControllerBase {
with ProtectedBranchService with ProtectedBranchService
with CommitStatusService with CommitStatusService
with DeployKeyService with DeployKeyService
with ActivityService
with OwnerAuthenticator with OwnerAuthenticator
with UsersAuthenticator => with UsersAuthenticator =>
@@ -101,7 +97,9 @@ trait RepositorySettingsControllerBase extends ControllerBase {
"events" -> webhookEvents, "events" -> webhookEvents,
"ctype" -> label("ctype", text()), "ctype" -> label("ctype", text()),
"token" -> optional(trim(label("token", text(maxlength(100))))) "token" -> optional(trim(label("token", text(maxlength(100)))))
)((url, events, ctype, token) => WebHookForm(url, events, WebHookContentType.valueOf(ctype), token)) )(
(url, events, ctype, token) => WebHookForm(url, events, WebHookContentType.valueOf(ctype), token)
)
// for rename repository // for rename repository
case class RenameRepositoryForm(repositoryName: String) case class RenameRepositoryForm(repositoryName: String)
@@ -178,15 +176,14 @@ trait RepositorySettingsControllerBase extends ControllerBase {
}) })
/** Branch protection for branch */ /** Branch protection for branch */
get("/:owner/:repository/settings/branches/*")(ownerOnly { repository => get("/:owner/:repository/settings/branches/:branch")(ownerOnly { repository =>
import gitbucket.core.api._ import gitbucket.core.api._
val branch = params("splat") val branch = params("branch")
if (!repository.branchList.contains(branch)) { if (!repository.branchList.contains(branch)) {
redirect(s"/${repository.owner}/${repository.name}/settings/branches") redirect(s"/${repository.owner}/${repository.name}/settings/branches")
} else { } else {
val protection = ApiBranchProtection(getProtectedBranchInfo(repository.owner, repository.name, branch)) val protection = ApiBranchProtection(getProtectedBranchInfo(repository.owner, repository.name, branch))
val lastWeeks = getRecentStatusContexts( val lastWeeks = getRecentStatuesContexts(
repository.owner, repository.owner,
repository.name, repository.name,
Date.from(LocalDateTime.now.minusWeeks(1).toInstant(ZoneOffset.UTC)) Date.from(LocalDateTime.now.minusWeeks(1).toInstant(ZoneOffset.UTC))
@@ -228,13 +225,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
* Display the web hook edit page. * Display the web hook edit page.
*/ */
get("/:owner/:repository/settings/hooks/new")(ownerOnly { repository => get("/:owner/:repository/settings/hooks/new")(ownerOnly { repository =>
val webhook = RepositoryWebHook( val webhook = RepositoryWebHook(repository.owner, repository.name, "", WebHookContentType.FORM, None)
userName = repository.owner,
repositoryName = repository.name,
url = "",
ctype = WebHookContentType.FORM,
token = None
)
html.edithook(webhook, Set(WebHook.Push), repository, true) html.edithook(webhook, Set(WebHook.Push), repository, true)
}) })
@@ -260,10 +251,9 @@ trait RepositorySettingsControllerBase extends ControllerBase {
* Send the test request to registered web hook URLs. * Send the test request to registered web hook URLs.
*/ */
ajaxPost("/:owner/:repository/settings/hooks/test")(ownerOnly { repository => ajaxPost("/:owner/:repository/settings/hooks/test")(ownerOnly { repository =>
def _headers(h: Array[org.apache.http.Header]): Array[Array[String]] = def _headers(h: Array[org.apache.http.Header]): Array[Array[String]] = h.map { h =>
h.map { h => Array(h.getName, h.getValue)
Array(h.getName, h.getValue) }
}
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git => git =>
@@ -277,13 +267,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
val url = params("url") val url = params("url")
val token = Some(params("token")) val token = Some(params("token"))
val ctype = WebHookContentType.valueOf(params("ctype")) val ctype = WebHookContentType.valueOf(params("ctype"))
val dummyWebHookInfo = RepositoryWebHook( val dummyWebHookInfo = RepositoryWebHook(repository.owner, repository.name, url, ctype, token)
userName = repository.owner,
repositoryName = repository.name,
url = url,
ctype = ctype,
token = token
)
val dummyPayload = { val dummyPayload = {
val ownerAccount = getAccountByUserName(repository.owner).get val ownerAccount = getAccountByUserName(repository.owner).get
val commits = val commits =
@@ -387,16 +371,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
post("/:owner/:repository/settings/rename", renameForm)(ownerOnly { (form, repository) => post("/:owner/:repository/settings/rename", renameForm)(ownerOnly { (form, repository) =>
if (context.settings.repositoryOperation.rename || context.loginAccount.get.isAdmin) { if (context.settings.repositoryOperation.rename || context.loginAccount.get.isAdmin) {
if (repository.name != form.repositoryName) { if (repository.name != form.repositoryName) {
// Update database and move git repository
renameRepository(repository.owner, repository.name, repository.owner, form.repositoryName) renameRepository(repository.owner, repository.name, repository.owner, form.repositoryName)
// Record activity log
val renameInfo = RenameRepositoryInfo(
repository.owner,
form.repositoryName,
context.loginAccount.get.userName,
repository.name
)
recordActivity(renameInfo)
} }
redirect(s"/${repository.owner}/${form.repositoryName}") redirect(s"/${repository.owner}/${form.repositoryName}")
} else Forbidden() } else Forbidden()
@@ -409,16 +384,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
if (context.settings.repositoryOperation.transfer || context.loginAccount.get.isAdmin) { if (context.settings.repositoryOperation.transfer || context.loginAccount.get.isAdmin) {
// Change repository owner // Change repository owner
if (repository.owner != form.newOwner) { if (repository.owner != form.newOwner) {
// Update database and move git repository
renameRepository(repository.owner, repository.name, form.newOwner, repository.name) renameRepository(repository.owner, repository.name, form.newOwner, repository.name)
// Record activity log
val renameInfo = RenameRepositoryInfo(
form.newOwner,
repository.name,
context.loginAccount.get.userName,
repository.owner
)
recordActivity(renameInfo)
} }
redirect(s"/${form.newOwner}/${repository.name}") redirect(s"/${form.newOwner}/${repository.name}")
} else Forbidden() } else Forbidden()
@@ -469,34 +435,32 @@ trait RepositorySettingsControllerBase extends ControllerBase {
/** /**
* Provides duplication check for web hook url. * Provides duplication check for web hook url.
*/ */
private def webHook(needExists: Boolean): Constraint = private def webHook(needExists: Boolean): Constraint = new Constraint() {
new Constraint() { override def validate(name: String, value: String, messages: Messages): Option[String] =
override def validate(name: String, value: String, messages: Messages): Option[String] = if (getWebHook(params("owner"), params("repository"), value).isDefined != needExists) {
if (getWebHook(params("owner"), params("repository"), value).isDefined != needExists) { Some(if (needExists) {
Some(if (needExists) { "URL had not been registered yet."
"URL had not been registered yet."
} else {
"URL had been registered already."
})
} else { } else {
None "URL had been registered already."
} })
} } else {
None
private def webhookEvents =
new ValueType[Set[WebHook.Event]] {
def convert(name: String, params: Map[String, Seq[String]], messages: Messages): Set[WebHook.Event] = {
WebHook.Event.values.flatMap { t =>
params.get(name + "." + t.name).map(_ => t)
}.toSet
} }
def validate(name: String, params: Map[String, Seq[String]], messages: Messages): Seq[(String, String)] = }
if (convert(name, params, messages).isEmpty) {
Seq(name -> messages("error.required").format(name)) private def webhookEvents = new ValueType[Set[WebHook.Event]] {
} else { def convert(name: String, params: Map[String, Seq[String]], messages: Messages): Set[WebHook.Event] = {
Nil WebHook.Event.values.flatMap { t =>
} params.get(name + "." + t.name).map(_ => t)
}.toSet
} }
def validate(name: String, params: Map[String, Seq[String]], messages: Messages): Seq[(String, String)] =
if (convert(name, params, messages).isEmpty) {
Seq(name -> messages("error.required").format(name))
} else {
Nil
}
}
// /** // /**
// * Provides Constraint to validate the collaborator name. // * Provides Constraint to validate the collaborator name.
@@ -516,77 +480,70 @@ trait RepositorySettingsControllerBase extends ControllerBase {
/** /**
* Duplicate check for the rename repository name. * Duplicate check for the rename repository name.
*/ */
private def renameRepositoryName: Constraint = private def renameRepositoryName: Constraint = new Constraint() {
new Constraint() { override def validate(
override def validate( name: String,
name: String, value: String,
value: String, params: Map[String, Seq[String]],
params: Map[String, Seq[String]], messages: Messages
messages: Messages ): Option[String] = {
): Option[String] = { for {
for { repoName <- params.optionValue("repository") if repoName != value
repoName <- params.optionValue("repository") if repoName != value userName <- params.optionValue("owner")
userName <- params.optionValue("owner") _ <- getRepositoryNamesOfUser(userName).find(_ == value)
_ <- getRepositoryNamesOfUser(userName).find(_ == value) } yield {
} yield { "Repository already exists."
"Repository already exists."
}
} }
} }
}
/** /**
*
*/ */
private def featureOption: Constraint = private def featureOption: Constraint = new Constraint() {
new Constraint() { override def validate(
override def validate( name: String,
name: String, value: String,
value: String, params: Map[String, Seq[String]],
params: Map[String, Seq[String]], messages: Messages
messages: Messages ): Option[String] =
): Option[String] = if (Seq("DISABLE", "PRIVATE", "PUBLIC", "ALL").contains(value)) None else Some("Option is invalid.")
if (Seq("DISABLE", "PRIVATE", "PUBLIC", "ALL").contains(value)) None else Some("Option is invalid.") }
}
/** /**
* Provides Constraint to validate the repository transfer user. * Provides Constraint to validate the repository transfer user.
*/ */
private def transferUser: Constraint = private def transferUser: Constraint = new Constraint() {
new Constraint() { override def validate(name: String, value: String, messages: Messages): Option[String] =
override def validate(name: String, value: String, messages: Messages): Option[String] = getAccountByUserName(value) match {
getAccountByUserName(value) match { case None => Some("User does not exist.")
case None => Some("User does not exist.") case Some(x) =>
case Some(x) => if (x.userName == params("owner")) {
if (x.userName == params("owner")) { Some("This is current repository owner.")
Some("This is current repository owner.") } else {
} else { params.get("repository").flatMap { repositoryName =>
params.get("repository").flatMap { repositoryName => getRepositoryNamesOfUser(x.userName).find(_ == repositoryName).map { _ =>
getRepositoryNamesOfUser(x.userName).find(_ == repositoryName).map { _ => "User already has same repository."
"User already has same repository."
}
} }
} }
} }
} }
}
private def mergeOptions = private def mergeOptions = new ValueType[Seq[String]] {
new ValueType[Seq[String]] { override def convert(name: String, params: Map[String, Seq[String]], messages: Messages): Seq[String] = {
override def convert(name: String, params: Map[String, Seq[String]], messages: Messages): Seq[String] = { params.getOrElse("mergeOptions", Nil)
params.getOrElse("mergeOptions", Nil) }
} override def validate(name: String, params: Map[String, Seq[String]], messages: Messages): Seq[(String, String)] = {
override def validate( val mergeOptions = params.getOrElse("mergeOptions", Nil)
name: String, if (mergeOptions.isEmpty) {
params: Map[String, Seq[String]], Seq("mergeOptions" -> "At least one option must be enabled.")
messages: Messages } else if (!mergeOptions.forall(x => Seq("merge-commit", "squash", "rebase").contains(x))) {
): Seq[(String, String)] = { Seq("mergeOptions" -> "mergeOptions are invalid.")
val mergeOptions = params.getOrElse("mergeOptions", Nil) } else {
if (mergeOptions.isEmpty) { Nil
Seq("mergeOptions" -> "At least one option must be enabled.")
} else if (!mergeOptions.forall(x => Seq("merge-commit", "squash", "rebase").contains(x))) {
Seq("mergeOptions" -> "mergeOptions are invalid.")
} else {
Nil
}
} }
} }
}
} }

View File

@@ -4,9 +4,9 @@ import java.io.{File, FileInputStream, FileOutputStream}
import scala.util.Using import scala.util.Using
import javax.servlet.http.{HttpServletRequest, HttpServletResponse} import javax.servlet.http.{HttpServletRequest, HttpServletResponse}
import gitbucket.core.plugin.PluginRegistry
import gitbucket.core.repo.html import gitbucket.core.repo.html
import gitbucket.core.helper import gitbucket.core.helper
import gitbucket.core.model.activity.DeleteBranchInfo
import gitbucket.core.service._ import gitbucket.core.service._
import gitbucket.core.service.RepositoryCommitFileService.CommitFile import gitbucket.core.service.RepositoryCommitFileService.CommitFile
import gitbucket.core.util._ import gitbucket.core.util._
@@ -14,8 +14,7 @@ import gitbucket.core.util.StringUtil._
import gitbucket.core.util.SyntaxSugars._ import gitbucket.core.util.SyntaxSugars._
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits._
import gitbucket.core.util.Directory._ import gitbucket.core.util.Directory._
import gitbucket.core.model.Account import gitbucket.core.model.{Account, CommitState, CommitStatus}
import gitbucket.core.service.RepositoryService.RepositoryInfo
import gitbucket.core.util.JGitUtil.CommitInfo import gitbucket.core.util.JGitUtil.CommitInfo
import gitbucket.core.view import gitbucket.core.view
import gitbucket.core.view.helpers import gitbucket.core.view.helpers
@@ -61,7 +60,6 @@ class RepositoryViewerController
with WebHookPullRequestService with WebHookPullRequestService
with WebHookPullRequestReviewCommentService with WebHookPullRequestReviewCommentService
with ProtectedBranchService with ProtectedBranchService
with RequestCache
/** /**
* The repository viewer. * The repository viewer.
@@ -90,9 +88,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
branch: String, branch: String,
path: String, path: String,
uploadFiles: String, uploadFiles: String,
message: Option[String], message: Option[String]
commit: String,
newBranch: Boolean
) )
case class EditorForm( case class EditorForm(
@@ -104,8 +100,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
lineSeparator: String, lineSeparator: String,
newFileName: String, newFileName: String,
oldFileName: Option[String], oldFileName: Option[String],
commit: String, commit: String
newBranch: Boolean
) )
case class DeleteForm( case class DeleteForm(
@@ -113,8 +108,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
path: String, path: String,
message: Option[String], message: Option[String],
fileName: String, fileName: String,
commit: String, commit: String
newBranch: Boolean
) )
case class CommentForm( case class CommentForm(
@@ -137,8 +131,6 @@ trait RepositoryViewerControllerBase extends ControllerBase {
"path" -> trim(label("Path", text())), "path" -> trim(label("Path", text())),
"uploadFiles" -> trim(label("Upload files", text(required))), "uploadFiles" -> trim(label("Upload files", text(required))),
"message" -> trim(label("Message", optional(text()))), "message" -> trim(label("Message", optional(text()))),
"commit" -> trim(label("Commit", text(required, conflict))),
"newBranch" -> trim(label("New Branch", boolean()))
)(UploadForm.apply) )(UploadForm.apply)
val editorForm = mapping( val editorForm = mapping(
@@ -150,8 +142,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
"lineSeparator" -> trim(label("Line Separator", text(required))), "lineSeparator" -> trim(label("Line Separator", text(required))),
"newFileName" -> trim(label("Filename", text(required))), "newFileName" -> trim(label("Filename", text(required))),
"oldFileName" -> trim(label("Old filename", optional(text()))), "oldFileName" -> trim(label("Old filename", optional(text()))),
"commit" -> trim(label("Commit", text(required, conflict))), "commit" -> trim(label("Commit", text(required, conflict)))
"newBranch" -> trim(label("New Branch", boolean()))
)(EditorForm.apply) )(EditorForm.apply)
val deleteForm = mapping( val deleteForm = mapping(
@@ -159,8 +150,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
"path" -> trim(label("Path", text())), "path" -> trim(label("Path", text())),
"message" -> trim(label("Message", optional(text()))), "message" -> trim(label("Message", optional(text()))),
"fileName" -> trim(label("Filename", text(required))), "fileName" -> trim(label("Filename", text(required))),
"commit" -> trim(label("Commit", text(required, conflict))), "commit" -> trim(label("Commit", text(required, conflict)))
"newBranch" -> trim(label("New Branch", boolean()))
)(DeleteForm.apply) )(DeleteForm.apply)
val commentForm = mapping( val commentForm = mapping(
@@ -262,8 +252,23 @@ trait RepositoryViewerControllerBase extends ControllerBase {
val (branchName, path) = repository.splitPath(multiParams("splat").head) val (branchName, path) = repository.splitPath(multiParams("splat").head)
val page = params.get("page").flatMap(_.toIntOpt).getOrElse(1) val page = params.get("page").flatMap(_.toIntOpt).getOrElse(1)
def getStatuses(sha: String): List[CommitStatus] = {
getCommitStatues(repository.owner, repository.name, sha)
}
def getSummary(statuses: List[CommitStatus]): (CommitState, String) = {
val stateMap = statuses.groupBy(_.state)
val state = CommitState.combine(stateMap.keySet)
val summary = stateMap.map { case (keyState, states) => s"${states.size} ${keyState.name}" }.mkString(", ")
state -> summary
}
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git => git =>
def getTags(sha: String): List[String] = {
JGitUtil.getTagsOnCommit(git, sha)
}
JGitUtil.getCommitLog(git, branchName, page, 30, path) match { JGitUtil.getCommitLog(git, branchName, page, 30, path) match {
case Right((logs, hasNext)) => case Right((logs, hasNext)) =>
html.commits( html.commits(
@@ -272,33 +277,34 @@ trait RepositoryViewerControllerBase extends ControllerBase {
repository, repository,
logs logs
.map { .map {
commit => c =>
( CommitInfo(
CommitInfo( id = c.id,
id = commit.id, shortMessage = c.shortMessage,
shortMessage = commit.shortMessage, fullMessage = c.fullMessage,
fullMessage = commit.fullMessage, parents = c.parents,
parents = commit.parents, authorTime = c.authorTime,
authorTime = commit.authorTime, authorName = c.authorName,
authorName = commit.authorName, authorEmailAddress = c.authorEmailAddress,
authorEmailAddress = commit.authorEmailAddress, commitTime = c.commitTime,
commitTime = commit.commitTime, committerName = c.committerName,
committerName = commit.committerName, committerEmailAddress = c.committerEmailAddress,
committerEmailAddress = commit.committerEmailAddress, commitSign = c.commitSign,
commitSign = commit.commitSign, verified = c.commitSign
verified = commit.commitSign.flatMap(GpgUtil.verifySign) .flatMap { s =>
), GpgUtil.verifySign(s)
JGitUtil.getTagsOnCommit(git, commit.id), }
getCommitStatusWithSummary(repository.owner, repository.name, commit.id)
) )
} }
.splitWith { .splitWith { (commit1, commit2) =>
case ((commit1, _, _), (commit2, _, _)) => view.helpers.date(commit1.commitTime) == view.helpers.date(commit2.commitTime)
view.helpers.date(commit1.commitTime) == view.helpers.date(commit2.commitTime)
}, },
page, page,
hasNext, hasNext,
hasDeveloperRole(repository.owner, repository.name, context.loginAccount) hasDeveloperRole(repository.owner, repository.name, context.loginAccount),
getStatuses,
getSummary,
getTags
) )
case Left(_) => NotFound() case Left(_) => NotFound()
} }
@@ -329,16 +335,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
val (branch, path) = repository.splitPath(multiParams("splat").head) val (branch, path) = repository.splitPath(multiParams("splat").head)
val protectedBranch = getProtectedBranchInfo(repository.owner, repository.name, branch) val protectedBranch = getProtectedBranchInfo(repository.owner, repository.name, branch)
.needStatusCheck(context.loginAccount.get.userName) .needStatusCheck(context.loginAccount.get.userName)
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git => html.upload(branch, repository, if (path.length == 0) Nil else path.split("/").toList, protectedBranch)
val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(branch))
html.upload(
branch,
repository,
if (path.length == 0) Nil else path.split("/").toList,
protectedBranch,
revCommit.name
)
}
}) })
post("/:owner/:repository/upload", uploadForm)(writableUsersOnly { (form, repository) => post("/:owner/:repository/upload", uploadForm)(writableUsersOnly { (form, repository) =>
@@ -351,47 +348,36 @@ trait RepositoryViewerControllerBase extends ControllerBase {
file.copy(name = if (form.path.length == 0) file.name else s"${form.path}/${file.name}") file.copy(name = if (form.path.length == 0) file.name else s"${form.path}/${file.name}")
} }
if (form.newBranch) { commitFiles(
val newBranchName = createNewBranchForPullRequest(repository, form.branch) repository = repository,
val objectId = _commit(newBranchName) branch = form.branch,
val issueId = path = form.path,
createIssueAndPullRequest(repository, form.branch, newBranchName, form.commit, objectId.name, form.message) files = files.toIndexedSeq,
redirect(s"/${repository.owner}/${repository.name}/pull/${issueId}") message = form.message.getOrElse("Add files via upload"),
} else { loginAccount = context.loginAccount.get,
_commit(form.branch) settings = context.settings
if (form.path.length == 0) { ) {
redirect(s"/${repository.owner}/${repository.name}/tree/${form.branch}") case (git, headTip, builder, inserter) =>
} else { JGitUtil.processTree(git, headTip) { (path, tree) =>
redirect(s"/${repository.owner}/${repository.name}/tree/${form.branch}/${form.path}") if (!newFiles.exists(_.name.contains(path))) {
} builder.add(JGitUtil.createDirCacheEntry(path, tree.getEntryFileMode, tree.getEntryObjectId))
}
}
newFiles.foreach { file =>
val bytes =
FileUtils.readFileToByteArray(new File(getTemporaryDir(session.getId), FileUtil.checkFilename(file.id)))
builder.add(
JGitUtil.createDirCacheEntry(file.name, FileMode.REGULAR_FILE, inserter.insert(Constants.OBJ_BLOB, bytes))
)
builder.finish()
}
} }
def _commit(branchName: String): ObjectId = { if (form.path.length == 0) {
commitFiles( redirect(s"/${repository.owner}/${repository.name}/tree/${form.branch}")
repository = repository, } else {
branch = branchName, redirect(s"/${repository.owner}/${repository.name}/tree/${form.branch}/${form.path}")
path = form.path,
files = files.toIndexedSeq,
message = form.message.getOrElse("Add files via upload"),
loginAccount = context.loginAccount.get,
settings = context.settings
) {
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))
}
}
newFiles.foreach { file =>
val bytes =
FileUtils.readFileToByteArray(new File(getTemporaryDir(session.getId), FileUtil.checkFilename(file.id)))
builder.add(
JGitUtil.createDirCacheEntry(file.name, FileMode.REGULAR_FILE, inserter.insert(Constants.OBJ_BLOB, bytes))
)
builder.finish()
}
}
} }
}) })
@@ -446,156 +432,70 @@ trait RepositoryViewerControllerBase extends ControllerBase {
}) })
post("/:owner/:repository/create", editorForm)(writableUsersOnly { (form, repository) => post("/:owner/:repository/create", editorForm)(writableUsersOnly { (form, repository) =>
if (form.newBranch) { commitFile(
val newBranchName = createNewBranchForPullRequest(repository, form.branch) repository = repository,
val objectId = _commit(newBranchName) branch = form.branch,
val issueId = path = form.path,
createIssueAndPullRequest(repository, form.branch, newBranchName, form.commit, objectId.name, form.message) newFileName = Some(form.newFileName),
redirect(s"/${repository.owner}/${repository.name}/pull/${issueId}") oldFileName = None,
} else { content = appendNewLine(convertLineSeparator(form.content, form.lineSeparator), form.lineSeparator),
_commit(form.branch) charset = form.charset,
redirect( message = form.message.getOrElse(s"Create ${form.newFileName}"),
s"/${repository.owner}/${repository.name}/blob/${form.branch}/${if (form.path.length == 0) urlEncode(form.newFileName) commit = form.commit,
else s"${form.path}/${urlEncode(form.newFileName)}"}"
)
}
def _commit(branchName: String): ObjectId = {
commitFile(
repository = repository,
branch = branchName,
path = form.path,
newFileName = Some(form.newFileName),
oldFileName = None,
content = appendNewLine(convertLineSeparator(form.content, form.lineSeparator), form.lineSeparator),
charset = form.charset,
message = form.message.getOrElse(s"Create ${form.newFileName}"),
commit = form.commit,
loginAccount = context.loginAccount.get,
settings = context.settings
)
}
})
post("/:owner/:repository/update", editorForm)(writableUsersOnly { (form, repository) =>
if (form.newBranch) {
val newBranchName = createNewBranchForPullRequest(repository, form.branch)
val objectId = _commit(newBranchName)
val issueId =
createIssueAndPullRequest(repository, form.branch, newBranchName, form.commit, objectId.name, form.message)
redirect(s"/${repository.owner}/${repository.name}/pull/${issueId}")
} else {
_commit(form.branch)
redirect(
s"/${repository.owner}/${repository.name}/blob/${urlEncode(form.branch)}/${if (form.path.length == 0) urlEncode(form.newFileName)
else s"${form.path}/${urlEncode(form.newFileName)}"}"
)
}
def _commit(branchName: String): ObjectId = {
commitFile(
repository = repository,
branch = branchName,
path = form.path,
newFileName = Some(form.newFileName),
oldFileName = form.oldFileName,
content = appendNewLine(convertLineSeparator(form.content, form.lineSeparator), form.lineSeparator),
charset = form.charset,
message = if (form.oldFileName.contains(form.newFileName)) {
form.message.getOrElse(s"Update ${form.newFileName}")
} else {
form.message.getOrElse(s"Rename ${form.oldFileName.get} to ${form.newFileName}")
},
commit = form.commit,
loginAccount = context.loginAccount.get,
settings = context.settings
)
}
})
post("/:owner/:repository/remove", deleteForm)(writableUsersOnly { (form, repository) =>
if (form.newBranch) {
val newBranchName = createNewBranchForPullRequest(repository, form.branch)
val objectId = _commit(newBranchName)
val issueId =
createIssueAndPullRequest(repository, form.branch, newBranchName, form.commit, objectId.name, form.message)
redirect(s"/${repository.owner}/${repository.name}/pull/${issueId}")
} else {
_commit(form.branch)
redirect(
s"/${repository.owner}/${repository.name}/tree/${form.branch}${if (form.path.length == 0) ""
else "/" + form.path}"
)
}
def _commit(branchName: String): ObjectId = {
commitFile(
repository = repository,
branch = branchName,
path = form.path,
newFileName = None,
oldFileName = Some(form.fileName),
content = "",
charset = "",
message = form.message.getOrElse(s"Delete ${form.fileName}"),
commit = form.commit,
loginAccount = context.loginAccount.get,
settings = context.settings
)
}
})
private def getNewBranchName(repository: RepositoryInfo): String = {
var i = 1
val branchNamePrefix = cutTail(context.loginAccount.get.userName.replaceAll("[^a-zA-Z0-9-_]", "-"), 25)
while (repository.branchList.exists(p => p.contains(s"$branchNamePrefix-patch-$i"))) {
i += 1
}
s"$branchNamePrefix-patch-$i"
}
private def createNewBranchForPullRequest(repository: RepositoryInfo, baseBranchName: String): String = {
val newBranchName = getNewBranchName(repository)
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
JGitUtil.createBranch(git, baseBranchName, newBranchName)
}
newBranchName
}
private def createIssueAndPullRequest(
repository: RepositoryInfo,
baseBranch: String,
requestBranch: String,
commitIdFrom: String,
commitIdTo: String,
commitMessage: Option[String]
): Int = {
val issueId = insertIssue(
owner = repository.owner,
repository = repository.name,
loginUser = context.loginAccount.get.userName,
title = requestBranch,
content = commitMessage,
assignedUserName = None,
milestoneId = None,
priorityId = None,
isPullRequest = true
)
createPullRequest(
originRepository = repository,
issueId = issueId,
originBranch = baseBranch,
requestUserName = repository.owner,
requestRepositoryName = repository.name,
requestBranch = requestBranch,
commitIdFrom = commitIdFrom,
commitIdTo = commitIdTo,
isDraft = false,
loginAccount = context.loginAccount.get, loginAccount = context.loginAccount.get,
settings = context.settings settings = context.settings
) )
issueId
} redirect(
s"/${repository.owner}/${repository.name}/blob/${form.branch}/${if (form.path.length == 0) urlEncode(form.newFileName)
else s"${form.path}/${urlEncode(form.newFileName)}"}"
)
})
post("/:owner/:repository/update", editorForm)(writableUsersOnly { (form, repository) =>
commitFile(
repository = repository,
branch = form.branch,
path = form.path,
newFileName = Some(form.newFileName),
oldFileName = form.oldFileName,
content = appendNewLine(convertLineSeparator(form.content, form.lineSeparator), form.lineSeparator),
charset = form.charset,
message = if (form.oldFileName.contains(form.newFileName)) {
form.message.getOrElse(s"Update ${form.newFileName}")
} else {
form.message.getOrElse(s"Rename ${form.oldFileName.get} to ${form.newFileName}")
},
commit = form.commit,
loginAccount = context.loginAccount.get,
settings = context.settings
)
redirect(
s"/${repository.owner}/${repository.name}/blob/${urlEncode(form.branch)}/${if (form.path.length == 0) urlEncode(form.newFileName)
else s"${form.path}/${urlEncode(form.newFileName)}"}"
)
})
post("/:owner/:repository/remove", deleteForm)(writableUsersOnly { (form, repository) =>
commitFile(
repository = repository,
branch = form.branch,
path = form.path,
newFileName = None,
oldFileName = Some(form.fileName),
content = "",
charset = "",
message = form.message.getOrElse(s"Delete ${form.fileName}"),
commit = form.commit,
loginAccount = context.loginAccount.get,
settings = context.settings
)
redirect(
s"/${repository.owner}/${repository.name}/tree/${form.branch}${if (form.path.length == 0) "" else "/" + form.path}"
)
})
get("/:owner/:repository/raw/*")(referrersOnly { repository => get("/:owner/:repository/raw/*")(referrersOnly { repository =>
val (id, path) = repository.splitPath(multiParams("splat").head) val (id, path) = repository.splitPath(multiParams("splat").head)
@@ -614,7 +514,6 @@ trait RepositoryViewerControllerBase extends ControllerBase {
val blobRoute = get("/:owner/:repository/blob/*")(referrersOnly { repository => val blobRoute = get("/:owner/:repository/blob/*")(referrersOnly { repository =>
val (id, path) = repository.splitPath(multiParams("splat").head) val (id, path) = repository.splitPath(multiParams("splat").head)
val raw = params.get("raw").getOrElse("false").toBoolean val raw = params.get("raw").getOrElse("false").toBoolean
val highlighterTheme = getSyntaxHighlighterTheme()
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
git => git =>
val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(id)) val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(id))
@@ -634,25 +533,13 @@ trait RepositoryViewerControllerBase extends ControllerBase {
hasWritePermission = hasDeveloperRole(repository.owner, repository.name, context.loginAccount), hasWritePermission = hasDeveloperRole(repository.owner, repository.name, context.loginAccount),
isBlame = request.paths(2) == "blame", isBlame = request.paths(2) == "blame",
isLfsFile = isLfsFile(git, objectId), isLfsFile = isLfsFile(git, objectId),
tabSize = info.tabSize, tabSize = info.tabSize
highlighterTheme = highlighterTheme
) )
} }
} getOrElse NotFound() } getOrElse NotFound()
} }
}) })
private def getSyntaxHighlighterTheme()(implicit context: Context): String = {
context.loginAccount match {
case Some(account) =>
getAccountPreference(account.userName) match {
case Some(x) => x.highlighterTheme
case _ => "github-v2"
}
case _ => "github-v2"
}
}
private def isLfsFile(git: Git, objectId: ObjectId): Boolean = { private def isLfsFile(git: Git, objectId: ObjectId): Boolean = {
JGitUtil.getObjectLoaderFromId(git, objectId)(JGitUtil.isLfsPointer).getOrElse(false) JGitUtil.getObjectLoaderFromId(git, objectId)(JGitUtil.isLfsPointer).getOrElse(false)
} }
@@ -714,7 +601,6 @@ trait RepositoryViewerControllerBase extends ControllerBase {
new JGitUtil.CommitInfo(revCommit), new JGitUtil.CommitInfo(revCommit),
JGitUtil.getBranchesOfCommit(git, revCommit.getName), JGitUtil.getBranchesOfCommit(git, revCommit.getName),
JGitUtil.getTagsOfCommit(git, revCommit.getName), JGitUtil.getTagsOfCommit(git, revCommit.getName),
getCommitStatusWithSummary(repository.owner, repository.name, revCommit.getName),
getCommitComments(repository.owner, repository.name, id, true), getCommitComments(repository.owner, repository.name, id, true),
repository, repository,
diffs, diffs,
@@ -873,20 +759,19 @@ trait RepositoryViewerControllerBase extends ControllerBase {
defaultBranch = repository.repository.defaultBranch, defaultBranch = repository.repository.defaultBranch,
origin = repository.repository.originUserName.isEmpty origin = repository.repository.originUserName.isEmpty
) )
.sortBy(branch => (branch.mergeInfo.isEmpty, branch.commitTime)) .sortBy(br => (br.mergeInfo.isEmpty, br.commitTime))
.map( .map(
branch => br =>
( (
branch, br,
getPullRequestByRequestCommit( getPullRequestByRequestCommit(
repository.owner, repository.owner,
repository.name, repository.name,
repository.repository.defaultBranch, repository.repository.defaultBranch,
branch.name, br.name,
branch.commitId br.commitId
), ),
protectedBranches.contains(branch.name), protectedBranches.contains(br.name)
getCommitStatusWithSummary(repository.owner, repository.name, branch.commitId)
) )
) )
.reverse .reverse
@@ -947,8 +832,7 @@ trait RepositoryViewerControllerBase extends ControllerBase {
if (repository.repository.defaultBranch != branchName) { if (repository.repository.defaultBranch != branchName) {
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git => Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
git.branchDelete().setForce(true).setBranchNames(branchName).call() git.branchDelete().setForce(true).setBranchNames(branchName).call()
val deleteBranchInfo = DeleteBranchInfo(repository.owner, repository.name, userName, branchName) recordDeleteBranchActivity(repository.owner, repository.name, userName, branchName)
recordActivity(deleteBranchInfo)
} }
} }
redirect(s"/${repository.owner}/${repository.name}/branches") redirect(s"/${repository.owner}/${repository.name}/branches")
@@ -1021,6 +905,10 @@ trait RepositoryViewerControllerBase extends ControllerBase {
lazy val isValid: Boolean = fileIds.nonEmpty lazy val isValid: Boolean = fileIds.nonEmpty
} }
private val readmeFiles = PluginRegistry().renderableExtensions.map { extension =>
s"readme.${extension}"
} ++ Seq("readme.txt", "readme")
/** /**
* Provides HTML of the file list. * Provides HTML of the file list.
* *
@@ -1042,19 +930,12 @@ trait RepositoryViewerControllerBase extends ControllerBase {
if (path == ".") revCommit else JGitUtil.getLastModifiedCommit(git, revCommit, path) if (path == ".") revCommit else JGitUtil.getLastModifiedCommit(git, revCommit, path)
val commitCount = JGitUtil.getCommitCount(git, lastModifiedCommit.getName) val commitCount = JGitUtil.getCommitCount(git, lastModifiedCommit.getName)
// get files // get files
val files = JGitUtil.getFileList( val files = JGitUtil.getFileList(git, revision, path, context.settings.baseUrl, commitCount)
git,
revision,
path,
context.settings.baseUrl,
commitCount,
context.settings.repositoryViewer.maxFiles
)
val parentPath = if (path == ".") Nil else path.split("/").toList val parentPath = if (path == ".") Nil else path.split("/").toList
// process README // process README.md or README.markdown
val readme = files // files should be sorted alphabetically. val readme = files
.find { file => .find { file =>
!file.isDirectory && RepositoryService.readmeFiles.contains(file.name.toLowerCase) !file.isDirectory && readmeFiles.contains(file.name.toLowerCase)
} }
.map { file => .map { file =>
val path = (file.name :: parentPath.reverse).reverse val path = (file.name :: parentPath.reverse).reverse
@@ -1070,7 +951,6 @@ trait RepositoryViewerControllerBase extends ControllerBase {
repository, repository,
if (path == ".") Nil else path.split("/").toList, // current path if (path == ".") Nil else path.split("/").toList, // current path
new JGitUtil.CommitInfo(lastModifiedCommit), // last modified commit new JGitUtil.CommitInfo(lastModifiedCommit), // last modified commit
getCommitStatusWithSummary(repository.owner, repository.name, lastModifiedCommit.getName),
commitCount, commitCount,
files, files,
readme, readme,

View File

@@ -48,6 +48,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
)(RepositoryOperation.apply), )(RepositoryOperation.apply),
"gravatar" -> trim(label("Gravatar", boolean())), "gravatar" -> trim(label("Gravatar", boolean())),
"notification" -> trim(label("Notification", boolean())), "notification" -> trim(label("Notification", boolean())),
"activityLogLimit" -> trim(label("Limit of activity logs", optional(number()))),
"limitVisibleRepositories" -> trim(label("limitVisibleRepositories", boolean())), "limitVisibleRepositories" -> trim(label("limitVisibleRepositories", boolean())),
"ssh" -> mapping( "ssh" -> mapping(
"enabled" -> trim(label("SSH access", boolean())), "enabled" -> trim(label("SSH access", boolean())),
@@ -108,10 +109,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
"timeout" -> trim(label("Timeout", long(required))), "timeout" -> trim(label("Timeout", long(required))),
"largeMaxFileSize" -> trim(label("Max file size for large file", long(required))), "largeMaxFileSize" -> trim(label("Max file size for large file", long(required))),
"largeTimeout" -> trim(label("Timeout for large file", long(required))) "largeTimeout" -> trim(label("Timeout for large file", long(required)))
)(Upload.apply), )(Upload.apply)
"repositoryViewer" -> mapping(
"maxFiles" -> trim(label("Max files", number(required)))
)(RepositoryViewerSettings.apply)
)(SystemSettings.apply).verifying { settings => )(SystemSettings.apply).verifying { settings =>
Vector( Vector(
if (settings.ssh.enabled && settings.baseUrl.isEmpty) { if (settings.ssh.enabled && settings.baseUrl.isEmpty) {

View File

@@ -1,7 +1,6 @@
package gitbucket.core.controller package gitbucket.core.controller
import gitbucket.core.model.WebHook import gitbucket.core.model.WebHook
import gitbucket.core.model.activity.{CreateWikiPageInfo, DeleteWikiInfo, EditWikiPageInfo}
import gitbucket.core.service.RepositoryService.RepositoryInfo import gitbucket.core.service.RepositoryService.RepositoryInfo
import gitbucket.core.service.WebHookService.WebHookGollumPayload import gitbucket.core.service.WebHookService.WebHookGollumPayload
import gitbucket.core.wiki.html import gitbucket.core.wiki.html
@@ -14,7 +13,6 @@ import gitbucket.core.util.Directory._
import org.scalatra.forms._ import org.scalatra.forms._
import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.Git
import org.scalatra.i18n.Messages import org.scalatra.i18n.Messages
import scala.util.Using import scala.util.Using
class WikiController class WikiController
@@ -26,7 +24,6 @@ class WikiController
with WebHookService with WebHookService
with ReadableUsersAuthenticator with ReadableUsersAuthenticator
with ReferrerAuthenticator with ReferrerAuthenticator
with RequestCache
trait WikiControllerBase extends ControllerBase { trait WikiControllerBase extends ControllerBase {
self: WikiService self: WikiService
@@ -187,9 +184,13 @@ trait WikiControllerBase extends ControllerBase {
).foreach { ).foreach {
commitId => commitId =>
updateLastActivityDate(repository.owner, repository.name) updateLastActivityDate(repository.owner, repository.name)
val wikiEditInfo = recordEditWikiPageActivity(
EditWikiPageInfo(repository.owner, repository.name, loginAccount.userName, form.pageName, commitId) repository.owner,
recordActivity(wikiEditInfo) repository.name,
loginAccount.userName,
form.pageName,
commitId
)
callWebHookOf(repository.owner, repository.name, WebHook.Gollum, context.settings) { callWebHookOf(repository.owner, repository.name, WebHook.Gollum, context.settings) {
getAccountByUserName(repository.owner).map { repositoryUser => getAccountByUserName(repository.owner).map { repositoryUser =>
WebHookGollumPayload("edited", form.pageName, commitId, repository, repositoryUser, loginAccount) WebHookGollumPayload("edited", form.pageName, commitId, repository, repositoryUser, loginAccount)
@@ -227,9 +228,7 @@ trait WikiControllerBase extends ControllerBase {
).foreach { ).foreach {
commitId => commitId =>
updateLastActivityDate(repository.owner, repository.name) updateLastActivityDate(repository.owner, repository.name)
val createWikiPageInfo = recordCreateWikiPageActivity(repository.owner, repository.name, loginAccount.userName, form.pageName)
CreateWikiPageInfo(repository.owner, repository.name, loginAccount.userName, form.pageName)
recordActivity(createWikiPageInfo)
callWebHookOf(repository.owner, repository.name, WebHook.Gollum, context.settings) { callWebHookOf(repository.owner, repository.name, WebHook.Gollum, context.settings) {
getAccountByUserName(repository.owner).map { repositoryUser => getAccountByUserName(repository.owner).map { repositoryUser =>
WebHookGollumPayload("created", form.pageName, commitId, repository, repositoryUser, loginAccount) WebHookGollumPayload("created", form.pageName, commitId, repository, repositoryUser, loginAccount)
@@ -250,26 +249,18 @@ trait WikiControllerBase extends ControllerBase {
if (isEditable(repository)) { if (isEditable(repository)) {
val pageName = StringUtil.urlDecode(params("page")) val pageName = StringUtil.urlDecode(params("page"))
defining(context.loginAccount.get) { defining(context.loginAccount.get) { loginAccount =>
loginAccount => deleteWikiPage(
deleteWikiPage( repository.owner,
repository.owner, repository.name,
repository.name, pageName,
pageName, loginAccount.fullName,
loginAccount.fullName, loginAccount.mailAddress,
loginAccount.mailAddress, s"Destroyed ${pageName}"
s"Destroyed ${pageName}" )
) updateLastActivityDate(repository.owner, repository.name)
val deleteWikiInfo = DeleteWikiInfo(
repository.owner,
repository.name,
loginAccount.userName,
pageName
)
recordActivity(deleteWikiInfo)
updateLastActivityDate(repository.owner, repository.name)
redirect(s"/${repository.owner}/${repository.name}/wiki") redirect(s"/${repository.owner}/${repository.name}/wiki")
} }
} else Unauthorized() } else Unauthorized()
}) })

View File

@@ -1,13 +1,10 @@
package gitbucket.core.controller.api package gitbucket.core.controller.api
import gitbucket.core.api.{ApiObject, ApiRef, CreateARef, JsonFormat, UpdateARef} import gitbucket.core.api.{ApiObject, ApiRef, JsonFormat}
import gitbucket.core.controller.ControllerBase import gitbucket.core.controller.ControllerBase
import gitbucket.core.util.Directory.getRepositoryDir import gitbucket.core.util.Directory.getRepositoryDir
import gitbucket.core.util.ReferrerAuthenticator import gitbucket.core.util.ReferrerAuthenticator
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits._
import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.ObjectId
import org.eclipse.jgit.lib.RefUpdate.Result
import org.scalatra.{BadRequest, NoContent, UnprocessableEntity}
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import scala.jdk.CollectionConverters._ import scala.jdk.CollectionConverters._
@@ -20,7 +17,7 @@ trait ApiGitReferenceControllerBase extends ControllerBase {
/* /*
* i. Get a reference * i. Get a reference
* https://docs.github.com/en/free-pro-team@latest/rest/reference/git#get-a-reference * https://developer.github.com/v3/git/refs/#get-a-reference
*/ */
get("/api/v3/repos/:owner/:repository/git/ref/*")(referrersOnly { repository => get("/api/v3/repos/:owner/:repository/git/ref/*")(referrersOnly { repository =>
getRef() getRef()
@@ -58,79 +55,21 @@ trait ApiGitReferenceControllerBase extends ControllerBase {
/* /*
* ii. Get all references * ii. Get all references
* https://docs.github.com/en/free-pro-team@latest/rest/reference/git#list-matching-references * https://developer.github.com/v3/git/refs/#get-all-references
*/ */
/* /*
* iii. Create a reference * iii. Create a reference
* https://docs.github.com/en/free-pro-team@latest/rest/reference/git#create-a-reference * https://developer.github.com/v3/git/refs/#create-a-reference
*/ */
post("/api/v3/repos/:owner/:repository/git/refs")(referrersOnly { _ =>
extractFromJsonBody[CreateARef].map {
data =>
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { git =>
val ref = git.getRepository.findRef(data.ref)
if (ref == null) {
val update = git.getRepository.updateRef(data.ref)
update.setNewObjectId(ObjectId.fromString(data.sha))
val result = update.update()
result match {
case Result.NEW => JsonFormat(ApiRef(update.getName, ApiObject(update.getNewObjectId.getName)))
case _ => UnprocessableEntity(result.name())
}
} else {
UnprocessableEntity("Ref already exists.")
}
}
} getOrElse BadRequest()
})
/* /*
* iv. Update a reference * iv. Update a reference
* https://docs.github.com/en/free-pro-team@latest/rest/reference/git#update-a-reference * https://developer.github.com/v3/git/refs/#update-a-reference
*/ */
patch("/api/v3/repos/:owner/:repository/git/refs/*")(referrersOnly { _ =>
val refName = multiParams("splat").mkString("/")
extractFromJsonBody[UpdateARef].map {
data =>
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { git =>
val ref = git.getRepository.findRef(refName)
if (ref == null) {
UnprocessableEntity("Ref does not exist.")
} else {
val update = git.getRepository.updateRef(ref.getName)
update.setNewObjectId(ObjectId.fromString(data.sha))
update.setForceUpdate(data.force)
val result = update.update()
result match {
case Result.FORCED | Result.FAST_FORWARD | Result.NO_CHANGE =>
JsonFormat(ApiRef(update.getName, ApiObject(update.getNewObjectId.getName)))
case _ => UnprocessableEntity(result.name())
}
}
}
} getOrElse BadRequest()
})
/* /*
* v. Delete a reference * v. Delete a reference
* https://docs.github.com/en/free-pro-team@latest/rest/reference/git#delete-a-reference * https://developer.github.com/v3/git/refs/#delete-a-reference
*/ */
delete("/api/v3/repos/:owner/:repository/git/refs/*")(referrersOnly { _ =>
val refName = multiParams("splat").mkString("/")
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { git =>
val ref = git.getRepository.findRef(refName)
if (ref == null) {
UnprocessableEntity("Ref does not exist.")
} else {
val update = git.getRepository.updateRef(ref.getName)
update.setForceUpdate(true)
val result = update.delete()
result match {
case Result.FORCED => NoContent()
case _ => UnprocessableEntity(result.name())
}
}
}
})
} }

View File

@@ -4,7 +4,6 @@ import gitbucket.core.controller.{Context, ControllerBase}
import gitbucket.core.service._ import gitbucket.core.service._
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits._
import gitbucket.core.util.{ReadableUsersAuthenticator, ReferrerAuthenticator, RepositoryName} import gitbucket.core.util.{ReadableUsersAuthenticator, ReferrerAuthenticator, RepositoryName}
import org.scalatra.{ActionResult, NoContent}
trait ApiIssueCommentControllerBase extends ControllerBase { trait ApiIssueCommentControllerBase extends ControllerBase {
self: AccountService self: AccountService
@@ -15,8 +14,8 @@ trait ApiIssueCommentControllerBase extends ControllerBase {
with ReadableUsersAuthenticator with ReadableUsersAuthenticator
with ReferrerAuthenticator => with ReferrerAuthenticator =>
/* /*
* i. List issue comments for a repository * i. List comments on an issue
* https://docs.github.com/en/rest/reference/issues#list-issue-comments-for-a-repository * https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue
*/ */
get("/api/v3/repos/:owner/:repository/issues/:id/comments")(referrersOnly { repository => get("/api/v3/repos/:owner/:repository/issues/:id/comments")(referrersOnly { repository =>
(for { (for {
@@ -31,90 +30,18 @@ trait ApiIssueCommentControllerBase extends ControllerBase {
}) })
/* /*
* ii. Get an issue comment * ii. List comments in a repository
* https://docs.github.com/en/rest/reference/issues#get-an-issue-comment * https://developer.github.com/v3/issues/comments/#list-comments-in-a-repository
*/
get("/api/v3/repos/:owner/:repository/issues/comments/:id")(referrersOnly { repository =>
val commentId = params("id").toInt
getCommentForApi(repository.owner, repository.name, commentId) match {
case Some((issueComment, user, issue)) =>
JsonFormat(
ApiComment(issueComment, RepositoryName(repository), issue.issueId, ApiUser(user), issue.isPullRequest)
)
case _ => NotFound()
}
})
/*
* iii. Update an issue comment
* https://docs.github.com/en/rest/reference/issues#update-an-issue-comment
*/
patch("/api/v3/repos/:owner/:repository/issues/comments/:id")(readableUsersOnly { repository =>
val commentId = params("id")
val result = for {
issueComment <- getComment(repository.owner, repository.name, commentId)
issue <- getIssue(repository.owner, repository.name, issueComment.issueId.toString)
} yield {
if (isEditable(repository.owner, repository.name, issueComment.commentedUserName)) {
val body = extractFromJsonBody[CreateAComment].map(_.body)
updateCommentByApi(repository, issue, issueComment.commentId.toString, body)
getComment(repository.owner, repository.name, commentId) match {
case Some(issueComment) =>
JsonFormat(
ApiComment(
issueComment,
RepositoryName(repository),
issue.issueId,
ApiUser(context.loginAccount.get),
issue.isPullRequest
)
)
case _ =>
}
} else {
Unauthorized()
}
}
result match {
case Some(response) => response
case None => NotFound()
}
})
/*
* iv. Delete a comment
* https://docs.github.com/en/rest/reference/issues#delete-an-issue-comment
*/
delete("/api/v3/repos/:owner/:repo/issues/comments/:id")(readableUsersOnly { repository =>
val maybeDeleteResponse: Option[Either[ActionResult, Option[Int]]] =
for {
commentId <- params("id").toIntOpt
comment <- getComment(repository.owner, repository.name, commentId.toString)
issue <- getIssue(repository.owner, repository.name, comment.issueId.toString)
} yield {
if (isEditable(repository.owner, repository.name, comment.commentedUserName)) {
val maybeDeletedComment = deleteCommentByApi(repository, comment, issue)
Right(maybeDeletedComment.map(_.commentId))
} else {
Left(Unauthorized())
}
}
maybeDeleteResponse
.map {
case Right(maybeDeletedCommentId) => maybeDeletedCommentId.getOrElse(NotFound())
case Left(err) => err
}
.getOrElse(NotFound())
})
/*
* v. List issue comments
* https://docs.github.com/en/rest/reference/issues#list-issue-comments
*/ */
/* /*
* vi. Create an issue comment * iii. Get a single comment
* https://docs.github.com/en/rest/reference/issues#create-an-issue-comment * https://developer.github.com/v3/issues/comments/#get-a-single-comment
*/
/*
* iv. Create a comment
* https://developer.github.com/v3/issues/comments/#create-a-comment
*/ */
post("/api/v3/repos/:owner/:repository/issues/:id/comments")(readableUsersOnly { repository => post("/api/v3/repos/:owner/:repository/issues/:id/comments")(readableUsersOnly { repository =>
(for { (for {
@@ -137,6 +64,16 @@ trait ApiIssueCommentControllerBase extends ControllerBase {
}) getOrElse NotFound() }) getOrElse NotFound()
}) })
/*
* v. Edit a comment
* https://developer.github.com/v3/issues/comments/#edit-a-comment
*/
/*
* vi. Delete a comment
* https://developer.github.com/v3/issues/comments/#delete-a-comment
*/
private def isEditable(owner: String, repository: String, author: String)(implicit context: Context): Boolean = private def isEditable(owner: String, repository: String, author: String)(implicit context: Context): Boolean =
hasDeveloperRole(owner, repository, context.loginAccount) || author == context.loginAccount.get.userName hasDeveloperRole(owner, repository, context.loginAccount) || author == context.loginAccount.get.userName
} }

View File

@@ -1,118 +0,0 @@
package gitbucket.core.controller.api
import gitbucket.core.api._
import gitbucket.core.controller.ControllerBase
import gitbucket.core.service.MilestonesService
import gitbucket.core.service.RepositoryService.RepositoryInfo
import gitbucket.core.util.{ReferrerAuthenticator, WritableUsersAuthenticator}
import gitbucket.core.util.Implicits._
import org.scalatra.NoContent
trait ApiIssueMilestoneControllerBase extends ControllerBase {
self: MilestonesService with WritableUsersAuthenticator with ReferrerAuthenticator =>
/*
* i. List milestones
* https://docs.github.com/en/rest/reference/issues#list-milestones
*/
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))
yield {
ApiMilestone(
repository.repository,
milestoneWithIssue._1,
milestoneWithIssue._2,
milestoneWithIssue._3
)
}).reverse
state match {
case "all" => JsonFormat(apiMilestones)
case "open" | "closed" =>
JsonFormat(
apiMilestones.filter(p => p.state == state)
)
case _ => NotFound()
}
})
/*
* ii. Create a milestone
* https://docs.github.com/en/rest/reference/issues#create-a-milestone
*/
post("/api/v3/repos/:owner/:repository/milestones")(writableUsersOnly { repository =>
(for {
data <- extractFromJsonBody[CreateAMilestone] if data.isValid
milestoneId = createMilestone(
repository.owner,
repository.name,
data.title,
data.description,
data.due_on
)
apiMilestone <- getApiMilestone(repository, milestoneId)
} yield {
JsonFormat(apiMilestone)
}) getOrElse NotFound()
})
/*
* iii. Get a milestone
* https://docs.github.com/en/rest/reference/issues#get-a-milestone
*/
get("/api/v3/repos/:owner/:repository/milestones/:number")(referrersOnly { repository =>
val milestoneId = params("number").toInt // use milestoneId as number
(for (apiMilestone <- getApiMilestone(repository, milestoneId)) yield {
JsonFormat(apiMilestone)
}) getOrElse NotFound()
})
/*
* iv.Update a milestone
* https://docs.github.com/en/rest/reference/issues#update-a-milestone
*/
patch("/api/v3/repos/:owner/:repository/milestones/:number")(writableUsersOnly { repository =>
val milestoneId = params("number").toInt
(for {
data <- extractFromJsonBody[CreateAMilestone] if data.isValid
milestone <- getMilestone(repository.owner, repository.name, milestoneId)
_ = (data.state, milestone.closedDate) match {
case ("open", Some(_)) =>
openMilestone(milestone)
case ("closed", None) =>
closeMilestone(milestone)
case _ =>
}
milestone <- getMilestone(repository.owner, repository.name, milestoneId)
_ = updateMilestone(milestone.copy(title = data.title, description = data.description, dueDate = data.due_on))
apiMilestone <- getApiMilestone(repository, milestoneId)
} yield {
JsonFormat(apiMilestone)
}) getOrElse NotFound()
})
/*
* v. Delete a milestone
* https://docs.github.com/en/rest/reference/issues#delete-a-milestone
*/
delete("/api/v3/repos/:owner/:repository/milestones/:number")(writableUsersOnly { repository =>
val milestoneId = params("number").toInt // use milestoneId as number
deleteMilestone(repository.owner, repository.name, milestoneId)
NoContent()
})
private def getApiMilestone(repository: RepositoryInfo, milestoneId: Int): Option[ApiMilestone] = {
getMilestonesWithIssueCount(repository.owner, repository.name)
.find(p => p._1.milestoneId == milestoneId)
.map(
milestoneWithIssue =>
ApiMilestone(
repository.repository,
milestoneWithIssue._1,
milestoneWithIssue._2,
milestoneWithIssue._3
)
)
}
}

View File

@@ -10,7 +10,7 @@ import gitbucket.core.util.Implicits._
import gitbucket.core.util.JGitUtil.CommitInfo import gitbucket.core.util.JGitUtil.CommitInfo
import gitbucket.core.util._ import gitbucket.core.util._
import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.Git
import org.scalatra.{Conflict, MethodNotAllowed, NoContent, Ok} import org.scalatra.NoContent
import scala.util.Using import scala.util.Using
import scala.jdk.CollectionConverters._ import scala.jdk.CollectionConverters._
@@ -161,28 +161,8 @@ trait ApiPullRequestControllerBase extends ControllerBase {
/* /*
* v. Update a pull request * v. Update a pull request
* https://docs.github.com/en/rest/reference/pulls#update-a-pull-request * https://developer.github.com/v3/pulls/#update-a-pull-request
*/ */
patch("/api/v3/repos/:owner/:repository/pulls/:id")(referrersOnly { repository =>
(for {
issueId <- params("id").toIntOpt
account <- context.loginAccount
settings = context.settings
data <- extractFromJsonBody[UpdateAPullRequest]
} yield {
updatePullRequestsByApi(
repository,
issueId,
account,
settings,
data.title,
data.body,
data.state,
data.base
)
JsonFormat(getApiPullRequest(repository, issueId))
}) getOrElse NotFound()
})
/* /*
* vi. List commits on a pull request * vi. List commits on a pull request
@@ -230,79 +210,15 @@ trait ApiPullRequestControllerBase extends ControllerBase {
if (checkConflict(repository.owner, repository.name, pullReq.branch, issueId).isDefined) { if (checkConflict(repository.owner, repository.name, pullReq.branch, issueId).isDefined) {
NoContent NoContent
} else { } else {
NotFound() NotFound
} }
}).getOrElse(NotFound()) }).getOrElse(NotFound)
}) })
/* /*
* ix. Merge a pull request (Merge Button) * ix. Merge a pull request (Merge Button)
* https://docs.github.com/en/rest/reference/pulls#merge-a-pull-request * https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
*/ */
put("/api/v3/repos/:owner/:repository/pulls/:id/merge")(referrersOnly { repository =>
(for {
//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)
} yield {
if (checkConflict(repository.owner, repository.name, pullReq.branch, issueId).isDefined) {
Conflict(
JsonFormat(
FailToMergePrResponse(
message = "Head branch was modified. Review and try the merge again.",
documentation_url = "https://docs.github.com/en/rest/reference/pulls#merge-a-pull-request",
)
)
)
} else {
if (issue.closed) {
MethodNotAllowed(
JsonFormat(
FailToMergePrResponse(
message = "Pull Request is not mergeable, Closed",
documentation_url = "https://docs.github.com/en/rest/reference/pulls#merge-a-pull-request",
)
)
)
} else {
val strategy =
if (data.merge_method.getOrElse("merge-commit") == "merge") "merge-commit"
else data.merge_method.getOrElse("merge-commit")
mergePullRequest(
repository,
issueId,
context.loginAccount.get,
data.commit_message.getOrElse(""), //TODO: Implement commit_title
strategy,
pullReq.isDraft,
context.settings
) match {
case Right(objectId) =>
Ok(
JsonFormat(
SuccessToMergePrResponse(
sha = objectId.toString,
merged = true,
message = "Pull Request successfully merged"
)
)
)
case Left(message) =>
MethodNotAllowed(
JsonFormat(
FailToMergePrResponse(
message = "Pull Request is not mergeable",
documentation_url = "https://docs.github.com/en/rest/reference/pulls#merge-a-pull-request",
)
)
)
}
}
}
})
})
/* /*
* x. Labels, assignees, and milestones * x. Labels, assignees, and milestones

View File

@@ -7,8 +7,6 @@ import gitbucket.core.util.Directory._
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits._
import gitbucket.core.util.JGitUtil.getBranches import gitbucket.core.util.JGitUtil.getBranches
import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.Git
import org.scalatra.NoContent
import scala.util.Using import scala.util.Using
trait ApiRepositoryBranchControllerBase extends ControllerBase { trait ApiRepositoryBranchControllerBase extends ControllerBase {
@@ -24,7 +22,7 @@ trait ApiRepositoryBranchControllerBase extends ControllerBase {
/** /**
* i. List branches * i. List branches
* https://docs.github.com/en/rest/reference/repos#list-branches * https://developer.github.com/v3/repos/branches/#list-branches
*/ */
get("/api/v3/repos/:owner/:repository/branches")(referrersOnly { repository => 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 =>
@@ -43,8 +41,8 @@ trait ApiRepositoryBranchControllerBase extends ControllerBase {
}) })
/** /**
* ii. Get a branch * ii. Get branch
* https://docs.github.com/en/rest/reference/repos#get-a-branch * https://developer.github.com/v3/repos/branches/#get-branch
*/ */
get("/api/v3/repos/:owner/:repository/branches/*")(referrersOnly { repository => get("/api/v3/repos/:owner/:repository/branches/*")(referrersOnly { repository =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
@@ -67,206 +65,147 @@ trait ApiRepositoryBranchControllerBase extends ControllerBase {
/* /*
* iii. Get branch protection * iii. Get branch protection
* https://docs.github.com/en/rest/reference/repos#get-branch-protection * https://developer.github.com/v3/repos/branches/#get-branch-protection
*/ */
get("/api/v3/repos/:owner/:repository/branches/:branch/protection")(referrersOnly { repository =>
val branch = params("branch")
if (repository.branchList.contains(branch)) {
val protection = getProtectedBranchInfo(repository.owner, repository.name, branch)
JsonFormat(
ApiBranchProtection(protection)
)
} else { NotFound() }
})
/* /*
* iv. Update branch protection * iv. Update branch protection
* https://docs.github.com/en/rest/reference/repos#update-branch-protection * https://developer.github.com/v3/repos/branches/#update-branch-protection
*/ */
/* /*
* v. Delete branch protection * v. Remove branch protection
* https://docs.github.com/en/rest/reference/repos#delete-branch-protection * https://developer.github.com/v3/repos/branches/#remove-branch-protection
*/
delete("/api/v3/repos/:owner/:repository/branches/:branch/protection")(writableUsersOnly { repository =>
val branch = params("branch")
if (repository.branchList.contains(branch)) {
val protection = getProtectedBranchInfo(repository.owner, repository.name, branch)
if (protection.enabled) {
disableBranchProtection(repository.owner, repository.name, branch)
NoContent()
} else NotFound()
} else NotFound()
})
/*
* vi. Get admin branch protection
* https://docs.github.com/en/rest/reference/repos#get-admin-branch-protection
*/ */
/* /*
* vii. Set admin branch protection * vi. Get required status checks of protected branch
* https://docs.github.com/en/rest/reference/repos#set-admin-branch-protection * https://developer.github.com/v3/repos/branches/#get-required-status-checks-of-protected-branch
*/ */
/* /*
* viii. Delete admin branch protection * vii. Update required status checks of protected branch
* https://docs.github.com/en/rest/reference/repos#delete-admin-branch-protection * https://developer.github.com/v3/repos/branches/#update-required-status-checks-of-protected-branch
*/ */
/* /*
* ix. Get pull request review protection * viii. Remove required status checks of protected branch
* https://docs.github.com/en/rest/reference/repos#get-pull-request-review-protection * https://developer.github.com/v3/repos/branches/#remove-required-status-checks-of-protected-branch
*/ */
/* /*
* x. Update pull request review protection * ix. List required status checks contexts of protected branch
* https://docs.github.com/en/rest/reference/repos#update-pull-request-review-protection * https://developer.github.com/v3/repos/branches/#list-required-status-checks-contexts-of-protected-branch
*/ */
/* /*
* xi. Delete pull request review protection * x. Replace required status checks contexts of protected branch
* https://docs.github.com/en/rest/reference/repos#delete-pull-request-review-protection * https://developer.github.com/v3/repos/branches/#replace-required-status-checks-contexts-of-protected-branch
*/ */
/* /*
* xii. Get commit signature protection * xi. Add required status checks contexts of protected branch
* https://docs.github.com/en/rest/reference/repos#get-commit-signature-protection * https://developer.github.com/v3/repos/branches/#remove-required-status-checks-contexts-of-protected-branch
*/ */
/* /*
* xiii. Create commit signature protection * xii. Remove required status checks contexts of protected branch
* https://docs.github.com/en/rest/reference/repos#create-commit-signature-protection * https://developer.github.com/v3/repos/branches/#remove-required-status-checks-contexts-of-protected-branch
*/ */
/* /*
* xiv. Delete commit signature protection * xiii. Get pull request review enforcement of protected branch
* https://docs.github.com/en/rest/reference/repos#delete-commit-signature-protection * https://developer.github.com/v3/repos/branches/#get-pull-request-review-enforcement-of-protected-branch
*/ */
/* /*
* xv. Get status checks protection * xiv. Update pull request review enforcement of protected branch
* https://docs.github.com/en/rest/reference/repos#get-status-checks-protection * https://developer.github.com/v3/repos/branches/#update-pull-request-review-enforcement-of-protected-branch
*/
get("/api/v3/repos/:owner/:repository/branches/:branch/protection/required_status_checks")(referrersOnly {
repository =>
val branch = params("branch")
if (repository.branchList.contains(branch)) {
val protection = getProtectedBranchInfo(repository.owner, repository.name, branch)
JsonFormat(
ApiBranchProtection(protection).required_status_checks
)
} else { NotFound() }
})
/*
* xvi. Update status check protection
* https://docs.github.com/en/rest/reference/repos#update-status-check-protection
*/ */
/* /*
* xvii. Remove status check protection * xv. Remove pull request review enforcement of protected branch
* https://docs.github.com/en/rest/reference/repos#remove-status-check-protection * https://developer.github.com/v3/repos/branches/#remove-pull-request-review-enforcement-of-protected-branch
*/ */
/* /*
* xviii. Get all status check contexts * xvi. Get required signatures of protected branch
* https://docs.github.com/en/free-pro-team@latest/rest/reference/repos#get-all-status-check-contexts * https://developer.github.com/v3/repos/branches/#get-required-signatures-of-protected-branch
*/
get("/api/v3/repos/:owner/:repository/branches/:branch/protection/required_status_checks/contexts")(referrersOnly {
repository =>
val branch = params("branch")
if (repository.branchList.contains(branch)) {
val protection = getProtectedBranchInfo(repository.owner, repository.name, branch)
if (protection.enabled) {
protection.contexts.toList
} else NotFound()
} else NotFound()
})
/*
* xix. Add status check contexts
* https://docs.github.com/en/rest/reference/repos#add-status-check-contexts
*/ */
/* /*
* xx. Set status check contexts * xvii. Add required signatures of protected branch
* https://docs.github.com/en/rest/reference/repos#set-status-check-contexts * https://developer.github.com/v3/repos/branches/#add-required-signatures-of-protected-branch
*/ */
/* /*
* xxi. Remove status check contexts * xviii. Remove required signatures of protected branch
* https://docs.github.com/en/rest/reference/repos#remove-status-check-contexts * https://developer.github.com/v3/repos/branches/#remove-required-signatures-of-protected-branch
*/ */
/* /*
* xxii. Get access restrictions * xix. Get admin enforcement of protected branch
* https://docs.github.com/en/rest/reference/repos#get-access-restrictions * https://developer.github.com/v3/repos/branches/#get-admin-enforcement-of-protected-branch
*/ */
/* /*
* xxiii. Delete access restrictions * xx. Add admin enforcement of protected branch
* https://docs.github.com/en/rest/reference/repos#delete-access-restrictions * https://developer.github.com/v3/repos/branches/#add-admin-enforcement-of-protected-branch
*/ */
/* /*
* xxiv. Get apps with access to the protected branch * xxi. Remove admin enforcement of protected branch
* https://docs.github.com/en/rest/reference/repos#get-apps-with-access-to-the-protected-branch * https://developer.github.com/v3/repos/branches/#remove-admin-enforcement-of-protected-branch
*/ */
/* /*
* xxv. Add app access restrictions * xxii. Get restrictions of protected branch
* https://docs.github.com/en/rest/reference/repos#add-app-access-restrictions * https://developer.github.com/v3/repos/branches/#get-restrictions-of-protected-branch
*/ */
/* /*
* xxvi. Set app access restrictions * xxiii. Remove restrictions of protected branch
* https://docs.github.com/en/rest/reference/repos#set-app-access-restrictions * https://developer.github.com/v3/repos/branches/#remove-restrictions-of-protected-branch
*/ */
/* /*
* xxvii. Remove app access restrictions * xxiv. List team restrictions of protected branch
* https://docs.github.com/en/rest/reference/repos#remove-app-access-restrictions * https://developer.github.com/v3/repos/branches/#list-team-restrictions-of-protected-branch
*/ */
/* /*
* xxviii. Get teams with access to the protected branch * xxv. Replace team restrictions of protected branch
* https://docs.github.com/en/rest/reference/repos#get-teams-with-access-to-the-protected-branch * https://developer.github.com/v3/repos/branches/#replace-team-restrictions-of-protected-branch
*/ */
/* /*
* xxix. Add team access restrictions * xxvi. Add team restrictions of protected branch
* https://docs.github.com/en/rest/reference/repos#add-team-access-restrictions * https://developer.github.com/v3/repos/branches/#add-team-restrictions-of-protected-branch
*/ */
/* /*
* xxx. Set team access restrictions * xxvii. Remove team restrictions of protected branch
* https://docs.github.com/en/rest/reference/repos#set-team-access-restrictions * https://developer.github.com/v3/repos/branches/#remove-team-restrictions-of-protected-branch
*/ */
/* /*
* xxxi. Remove team access restrictions * xxviii. List user restrictions of protected branch
* https://docs.github.com/en/rest/reference/repos#remove-team-access-restrictions * https://developer.github.com/v3/repos/branches/#list-user-restrictions-of-protected-branch
*/ */
/* /*
* xxxii. Get users with access to the protected branch * xxix. Replace user restrictions of protected branch
* https://docs.github.com/en/rest/reference/repos#get-users-with-access-to-the-protected-branch * https://developer.github.com/v3/repos/branches/#replace-user-restrictions-of-protected-branch
*/ */
/* /*
* xxxiii. Add user access restrictions * xxx. Add user restrictions of protected branch
* https://docs.github.com/en/rest/reference/repos#add-user-access-restrictions * https://developer.github.com/v3/repos/branches/#add-user-restrictions-of-protected-branch
*/ */
/* /*
* xxxiv. Set user access restrictions * xxxi. Remove user restrictions of protected branch
* https://docs.github.com/en/rest/reference/repos#set-user-access-restrictions * https://developer.github.com/v3/repos/branches/#remove-user-restrictions-of-protected-branch
*/
/*
* xxxv. Remove user access restrictions
* https://docs.github.com/en/rest/reference/repos#remove-user-access-restrictions
*/ */
/** /**

View File

@@ -1,5 +1,5 @@
package gitbucket.core.controller.api package gitbucket.core.controller.api
import gitbucket.core.api.{AddACollaborator, ApiRepositoryCollaborator, ApiUser, JsonFormat} import gitbucket.core.api.{AddACollaborator, ApiUser, JsonFormat}
import gitbucket.core.controller.ControllerBase import gitbucket.core.controller.ControllerBase
import gitbucket.core.service.{AccountService, RepositoryService} import gitbucket.core.service.{AccountService, RepositoryService}
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits._
@@ -10,8 +10,8 @@ trait ApiRepositoryCollaboratorControllerBase extends ControllerBase {
self: RepositoryService with AccountService with ReferrerAuthenticator with OwnerAuthenticator => self: RepositoryService with AccountService with ReferrerAuthenticator with OwnerAuthenticator =>
/* /*
* i. List repository collaborators * i. List collaborators
* https://docs.github.com/en/free-pro-team@latest/rest/reference/repos#list-repository-collaborators * https://developer.github.com/v3/repos/collaborators/#list-collaborators
*/ */
get("/api/v3/repos/:owner/:repository/collaborators")(referrersOnly { repository => get("/api/v3/repos/:owner/:repository/collaborators")(referrersOnly { repository =>
// TODO Should ApiUser take permission? getCollaboratorUserNames does not return owner group members. // TODO Should ApiUser take permission? getCollaboratorUserNames does not return owner group members.
@@ -19,40 +19,19 @@ trait ApiRepositoryCollaboratorControllerBase extends ControllerBase {
getCollaboratorUserNames(params("owner"), params("repository")).map(u => ApiUser(getAccountByUserName(u).get)) getCollaboratorUserNames(params("owner"), params("repository")).map(u => ApiUser(getAccountByUserName(u).get))
) )
}) })
/* /*
* ii. Check if a user is a collaborator * ii. Check if a user is a collaborator
* https://docs.github.com/en/free-pro-team@latest/rest/reference/repos#check-if-a-user-is-a-repository-collaborator * https://developer.github.com/v3/repos/collaborators/#check-if-a-user-is-a-collaborator
*/ */
get("/api/v3/repos/:owner/:repository/collaborators/:userName")(referrersOnly { repository =>
(for (account <- getAccountByUserName(params("userName"))) yield {
if (getCollaboratorUserNames(repository.owner, repository.name).contains(account.userName)) {
NoContent()
} else {
NotFound()
}
}) getOrElse NotFound()
})
/* /*
* iii. Get repository permissions for a user * iii. Review a user's permission level
* https://docs.github.com/en/free-pro-team@latest/rest/reference/repos#get-repository-permissions-for-a-user * https://developer.github.com/v3/repos/collaborators/#review-a-users-permission-level
*/ */
get("/api/v3/repos/:owner/:repository/collaborators/:userName/permission")(referrersOnly { repository =>
(for {
account <- getAccountByUserName(params("userName"))
collaborator <- getCollaborators(repository.owner, repository.name)
.find(p => p._1.collaboratorName == account.userName)
} yield {
JsonFormat(
ApiRepositoryCollaborator(collaborator._1.role, ApiUser(account))
)
}) getOrElse NotFound()
})
/* /*
* iv. Add a repository collaborator * iv. Add user as a collaborator
* https://docs.github.com/en/free-pro-team@latest/rest/reference/repos#add-a-repository-collaborator * https://developer.github.com/v3/repos/collaborators/#add-user-as-a-collaborator
* requested #1586 * requested #1586
*/ */
put("/api/v3/repos/:owner/:repository/collaborators/:userName")(ownerOnly { repository => put("/api/v3/repos/:owner/:repository/collaborators/:userName")(ownerOnly { repository =>
@@ -65,8 +44,8 @@ trait ApiRepositoryCollaboratorControllerBase extends ControllerBase {
}) })
/* /*
* v. Remove a repository collaborator * v. Remove user as a collaborator
* https://docs.github.com/en/free-pro-team@latest/rest/reference/repos#remove-a-repository-collaborator * https://developer.github.com/v3/repos/collaborators/#remove-user-as-a-collaborator
* requested #1586 * requested #1586
*/ */
delete("/api/v3/repos/:owner/:repository/collaborators/:userName")(ownerOnly { repository => delete("/api/v3/repos/:owner/:repository/collaborators/:userName")(ownerOnly { repository =>

View File

@@ -1,20 +1,19 @@
package gitbucket.core.controller.api package gitbucket.core.controller.api
import gitbucket.core.api.{ApiBranchCommit, ApiBranchForHeadCommit, ApiCommits, JsonFormat} import gitbucket.core.api.{ApiCommits, JsonFormat}
import gitbucket.core.controller.ControllerBase import gitbucket.core.controller.ControllerBase
import gitbucket.core.model.Account import gitbucket.core.model.Account
import gitbucket.core.service.{AccountService, CommitsService, ProtectedBranchService} import gitbucket.core.service.{AccountService, CommitsService}
import gitbucket.core.util.Directory.getRepositoryDir import gitbucket.core.util.Directory.getRepositoryDir
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits._
import gitbucket.core.util.JGitUtil.{CommitInfo, getBranches, getBranchesOfCommit} import gitbucket.core.util.JGitUtil.CommitInfo
import gitbucket.core.util.{JGitUtil, ReferrerAuthenticator, RepositoryName} import gitbucket.core.util.{JGitUtil, ReferrerAuthenticator, RepositoryName}
import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.Git
import org.eclipse.jgit.revwalk.RevWalk import org.eclipse.jgit.revwalk.RevWalk
import scala.jdk.CollectionConverters._ import scala.jdk.CollectionConverters._
import scala.util.Using import scala.util.Using
trait ApiRepositoryCommitControllerBase extends ControllerBase { trait ApiRepositoryCommitControllerBase extends ControllerBase {
self: AccountService with CommitsService with ProtectedBranchService with ReferrerAuthenticator => self: AccountService with CommitsService with ReferrerAuthenticator =>
/* /*
* i. List commits on a repository * i. List commits on a repository
* https://developer.github.com/v3/repos/commits/#list-commits-on-a-repository * https://developer.github.com/v3/repos/commits/#list-commits-on-a-repository
@@ -23,7 +22,7 @@ trait ApiRepositoryCommitControllerBase extends ControllerBase {
val owner = repository.owner val owner = repository.owner
val name = repository.name val name = repository.name
// TODO: The following parameters need to be implemented. [:path, :author, :since, :until] // TODO: The following parameters need to be implemented. [:path, :author, :since, :until]
val sha = params.getOrElse("sha", "refs/heads/master") val sha = if (request.body.nonEmpty) (parse(request.body) \ "sha").extract[String] else "refs/heads/master";
Using.resource(Git.open(getRepositoryDir(owner, name))) { Using.resource(Git.open(getRepositoryDir(owner, name))) {
git => git =>
val repo = git.getRepository val repo = git.getRepository
@@ -108,25 +107,7 @@ trait ApiRepositoryCommitControllerBase extends ControllerBase {
*/ */
/* /*
* v. Commit signature verification * v. Commit signature verification
* https://developer.github.com/v3/repos/commits/#commit-signature-verification * https://developer.github.com/v3/repos/commits/#commit-signature-verification
*/ */
/*
* vi. List branches for HEAD commit
* https://docs.github.com/en/rest/reference/repos#list-branches-for-head-commit
*/
get("/api/v3/repos/:owner/:repository/commits/:sha/branches-where-head")(referrersOnly { repository =>
val sha = params("sha")
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
val apiBranchForCommits = for {
branch <- getBranchesOfCommit(git, sha)
br <- getBranches(git, branch, repository.repository.originUserName.isEmpty).find(_.name == branch)
} yield {
val protection = getProtectedBranchInfo(repository.owner, repository.name, branch)
ApiBranchForHeadCommit(branch, ApiBranchCommit(br.commitId), protection.enabled)
}
JsonFormat(apiBranchForCommits)
}
})
} }

View File

@@ -1,7 +1,6 @@
package gitbucket.core.controller.api package gitbucket.core.controller.api
import gitbucket.core.api.{ApiContents, ApiError, CreateAFile, JsonFormat} import gitbucket.core.api.{ApiContents, ApiError, CreateAFile, JsonFormat}
import gitbucket.core.controller.ControllerBase import gitbucket.core.controller.ControllerBase
import gitbucket.core.plugin.PluginRegistry
import gitbucket.core.service.{RepositoryCommitFileService, RepositoryService} import gitbucket.core.service.{RepositoryCommitFileService, RepositoryService}
import gitbucket.core.util.Directory.getRepositoryDir import gitbucket.core.util.Directory.getRepositoryDir
import gitbucket.core.util.JGitUtil.{FileInfo, getContentFromId, getFileList} import gitbucket.core.util.JGitUtil.{FileInfo, getContentFromId, getFileList}
@@ -9,30 +8,15 @@ import gitbucket.core.util._
import gitbucket.core.view.helpers.{isRenderable, renderMarkup} import gitbucket.core.view.helpers.{isRenderable, renderMarkup}
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits._
import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.Git
import scala.util.Using import scala.util.Using
trait ApiRepositoryContentsControllerBase extends ControllerBase { trait ApiRepositoryContentsControllerBase extends ControllerBase {
self: ReferrerAuthenticator with WritableUsersAuthenticator with RepositoryCommitFileService => self: ReferrerAuthenticator with WritableUsersAuthenticator with RepositoryCommitFileService =>
/** /*
* i. Get a repository README * i. Get the README
* https://docs.github.com/en/rest/reference/repos#get-a-repository-readme * https://developer.github.com/v3/repos/contents/#get-the-readme
*/ */
get("/api/v3/repos/:owner/:repository/readme")(referrersOnly { repository =>
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.
.find { file =>
!file.isDirectory && RepositoryService.readmeFiles.contains(file.name.toLowerCase)
} match {
case Some(x) => getContents(repository = repository, path = x.name, refStr = refStr, ignoreCase = true)
case _ => NotFound()
}
}
})
/** /**
* ii. Get contents * ii. Get contents
@@ -50,32 +34,21 @@ trait ApiRepositoryContentsControllerBase extends ControllerBase {
getContents(repository, multiParams("splat").head, params.getOrElse("ref", repository.repository.defaultBranch)) getContents(repository, multiParams("splat").head, params.getOrElse("ref", repository.repository.defaultBranch))
}) })
private def getContents( private def getContents(repository: RepositoryService.RepositoryInfo, path: String, refStr: String) = {
repository: RepositoryService.RepositoryInfo, def getFileInfo(git: Git, revision: String, pathStr: String): Option[FileInfo] = {
path: String,
refStr: String,
ignoreCase: Boolean = false
) = {
def getFileInfo(git: Git, revision: String, pathStr: String, ignoreCase: Boolean): Option[FileInfo] = {
val (dirName, fileName) = pathStr.lastIndexOf('/') match { val (dirName, fileName) = pathStr.lastIndexOf('/') match {
case -1 => case -1 =>
(".", pathStr) (".", pathStr)
case n => case n =>
(pathStr.take(n), pathStr.drop(n + 1)) (pathStr.take(n), pathStr.drop(n + 1))
} }
if (ignoreCase) { getFileList(git, revision, dirName).find(f => f.name.equals(fileName))
getFileList(git, revision, dirName, maxFiles = context.settings.repositoryViewer.maxFiles)
.find(_.name.toLowerCase.equals(fileName.toLowerCase))
} else {
getFileList(git, revision, dirName, maxFiles = context.settings.repositoryViewer.maxFiles)
.find(_.name.equals(fileName))
}
} }
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { git => Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { git =>
val fileList = getFileList(git, refStr, path, maxFiles = context.settings.repositoryViewer.maxFiles) val fileList = getFileList(git, refStr, path)
if (fileList.isEmpty) { // file or NotFound if (fileList.isEmpty) { // file or NotFound
getFileInfo(git, refStr, path, ignoreCase) getFileInfo(git, refStr, path)
.flatMap { f => .flatMap { f =>
val largeFile = params.get("large_file").exists(s => s.equals("true")) val largeFile = params.get("large_file").exists(s => s.equals("true"))
val content = getContentFromId(git, f.id, largeFile) val content = getContentFromId(git, f.id, largeFile)

View File

@@ -54,15 +54,11 @@ trait ApiRepositoryControllerBase extends ControllerBase {
}) })
} }
/** /*
* iv. List all public repositories * iv. List all public repositories
* https://developer.github.com/v3/repos/#list-public-repositories * https://developer.github.com/v3/repos/#list-all-public-repositories
* Not implemented
*/ */
get("/api/v3/repositories") {
JsonFormat(getPublicRepositories().map { r =>
ApiRepository(r, getAccountByUserName(r.owner).get)
})
}
/* /*
* v. Create * v. Create
@@ -178,14 +174,9 @@ trait ApiRepositoryControllerBase extends ControllerBase {
*/ */
/* /*
* xiii. List repository tags * xiii. List tags
* https://docs.github.com/en/rest/reference/repos#list-repository-tags * https://developer.github.com/v3/repos/#list-tags
*/ */
get("/api/v3/repos/:owner/:repository/tags")(referrersOnly { repository =>
JsonFormat(
repository.tags.map(tagInfo => ApiTag(tagInfo.name, RepositoryName(repository), tagInfo.id))
)
})
/* /*
* xiv. Delete a repository * xiv. Delete a repository

View File

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

View File

@@ -1,120 +0,0 @@
package gitbucket.core.controller.api
import gitbucket.core.api._
import gitbucket.core.controller.ControllerBase
import gitbucket.core.model.{WebHook, WebHookContentType}
import gitbucket.core.service.{RepositoryService, WebHookService}
import gitbucket.core.util._
import gitbucket.core.util.Implicits._
import org.scalatra.NoContent
trait ApiRepositoryWebhookControllerBase extends ControllerBase {
self: RepositoryService with WebHookService with ReferrerAuthenticator with WritableUsersAuthenticator =>
/*
* i. List repository webhooks
* https://docs.github.com/en/rest/reference/repos#list-repository-webhooks
*/
get("/api/v3/repos/:owner/:repository/hooks")(referrersOnly { repository =>
val apiWebhooks = for {
(hook, events) <- getWebHooks(repository.owner, repository.name)
} yield {
ApiWebhook("Repository", hook, events)
}
JsonFormat(apiWebhooks)
})
/*
* ii. Create a repository webhook
* https://docs.github.com/en/rest/reference/repos#create-a-repository-webhook
*/
post("/api/v3/repos/:owner/:repository/hooks")(writableUsersOnly { repository =>
(for {
data <- extractFromJsonBody[CreateARepositoryWebhook] if data.isValid
ctype = if (data.config.content_type == "form") WebHookContentType.FORM else WebHookContentType.JSON
events = data.events.map(p => WebHook.Event.valueOf(p)).toSet
} yield {
addWebHook(
repository.owner,
repository.name,
data.config.url,
events,
ctype,
data.config.secret
)
getWebHook(repository.owner, repository.name, data.config.url) match {
case Some(createdHook) => JsonFormat(ApiWebhook("Repository", createdHook._1, createdHook._2))
case _ =>
}
}) getOrElse NotFound()
})
/*
* iii. Get a repository webhook
* https://docs.github.com/en/rest/reference/repos#get-a-repository-webhook
*/
get("/api/v3/repos/:owner/:repository/hooks/:id")(referrersOnly { repository =>
val hookId = params("id").toInt
getWebHookById(hookId) match {
case Some(hook) => JsonFormat(ApiWebhook("Repository", hook._1, hook._2))
case _ => NotFound()
}
})
/*
* iv. Update a repository webhook
* https://docs.github.com/en/rest/reference/repos#update-a-repository-webhook
*/
patch("/api/v3/repos/:owner/:repository/hooks/:id")(writableUsersOnly { repository =>
val hookId = params("id").toInt
(for {
data <- extractFromJsonBody[UpdateARepositoryWebhook] if data.isValid
ctype = data.config.content_type match {
case "json" => WebHookContentType.JSON
case _ => WebHookContentType.FORM
}
} yield {
val events = (data.events ++ data.add_events)
.filterNot(p => data.remove_events.contains(p))
.map(p => WebHook.Event.valueOf(p))
.toSet
updateWebHookByApi(
hookId,
repository.owner,
repository.name,
data.config.url,
events,
ctype,
data.config.secret
)
getWebHookById(hookId) match {
case Some(updatedHook) => JsonFormat(ApiWebhook("Repository", updatedHook._1, updatedHook._2))
case _ =>
}
}) getOrElse NotFound()
})
/*
* v. Delete a repository webhook
* https://docs.github.com/en/rest/reference/repos#delete-a-repository-webhook
*/
delete("/api/v3/repos/:owner/:repository/hooks/:id")(writableUsersOnly { repository =>
val hookId = params("id").toInt
getWebHookById(hookId) match {
case Some(_) =>
deleteWebHookById(params("id").toInt)
NoContent()
case _ => NotFound()
}
})
/*
* vi. Ping a repository webhook
* https://docs.github.com/en/rest/reference/repos#ping-a-repository-webhook
*/
/*
* vi. Test the push repository webhook
* https://docs.github.com/en/rest/reference/repos#test-the-push-repository-webhook
*/
}

View File

@@ -10,7 +10,7 @@ trait AccessTokenComponent { self: Profile =>
val userName = column[String]("USER_NAME") val userName = column[String]("USER_NAME")
val tokenHash = column[String]("TOKEN_HASH") val tokenHash = column[String]("TOKEN_HASH")
val note = column[String]("NOTE") val note = column[String]("NOTE")
def * = (accessTokenId, userName, tokenHash, note).<>(AccessToken.tupled, AccessToken.unapply) def * = (accessTokenId, userName, tokenHash, note) <> (AccessToken.tupled, AccessToken.unapply)
} }
} }
case class AccessToken( case class AccessToken(

View File

@@ -35,7 +35,7 @@ trait AccountComponent { self: Profile =>
groupAccount, groupAccount,
removed, removed,
description.? description.?
).<>(Account.tupled, Account.unapply) ) <> (Account.tupled, Account.unapply)
} }
} }

View File

@@ -9,7 +9,7 @@ trait AccountExtraMailAddressComponent { self: Profile =>
val userName = column[String]("USER_NAME", O PrimaryKey) val userName = column[String]("USER_NAME", O PrimaryKey)
val extraMailAddress = column[String]("EXTRA_MAIL_ADDRESS", O PrimaryKey) val extraMailAddress = column[String]("EXTRA_MAIL_ADDRESS", O PrimaryKey)
def * = def * =
(userName, extraMailAddress).<>(AccountExtraMailAddress.tupled, AccountExtraMailAddress.unapply) (userName, extraMailAddress) <> (AccountExtraMailAddress.tupled, AccountExtraMailAddress.unapply)
} }
} }

View File

@@ -9,7 +9,7 @@ trait AccountFederationComponent { self: Profile =>
val issuer = column[String]("ISSUER") val issuer = column[String]("ISSUER")
val subject = column[String]("SUBJECT") val subject = column[String]("SUBJECT")
val userName = column[String]("USER_NAME") val userName = column[String]("USER_NAME")
def * = (issuer, subject, userName).<>(AccountFederation.tupled, AccountFederation.unapply) def * = (issuer, subject, userName) <> (AccountFederation.tupled, AccountFederation.unapply)
def byPrimaryKey(issuer: String, subject: String): Rep[Boolean] = def byPrimaryKey(issuer: String, subject: String): Rep[Boolean] =
(this.issuer === issuer.bind) && (this.subject === subject.bind) (this.issuer === issuer.bind) && (this.subject === subject.bind)

View File

@@ -1,21 +0,0 @@
package gitbucket.core.model
trait AccountPreferenceComponent { self: Profile =>
import profile.api._
lazy val AccountPreferences = TableQuery[AccountPreferences]
class AccountPreferences(tag: Tag) extends Table[AccountPreference](tag, "ACCOUNT_PREFERENCE") {
val userName = column[String]("USER_NAME", O PrimaryKey)
val highlighterTheme = column[String]("HIGHLIGHTER_THEME")
def * =
(userName, highlighterTheme).<>(AccountPreference.tupled, AccountPreference.unapply)
def byPrimaryKey(userName: String): Rep[Boolean] = this.userName === userName.bind
}
}
case class AccountPreference(
userName: String,
highlighterTheme: String = "prettify"
)

View File

@@ -12,7 +12,7 @@ trait AccountWebHookComponent extends TemplateComponent { self: Profile =>
val url = column[String]("URL") val url = column[String]("URL")
val token = column[Option[String]]("TOKEN") val token = column[Option[String]]("TOKEN")
val ctype = column[WebHookContentType]("CTYPE") val ctype = column[WebHookContentType]("CTYPE")
def * = (userName, url, ctype, token).<>((AccountWebHook.apply _).tupled, AccountWebHook.unapply) def * = (userName, url, ctype, token) <> ((AccountWebHook.apply _).tupled, AccountWebHook.unapply)
def byPrimaryKey(userName: String, url: String) = (this.userName === userName.bind) && (this.url === url.bind) def byPrimaryKey(userName: String, url: String) = (this.userName === userName.bind) && (this.url === url.bind)
} }

View File

@@ -14,7 +14,7 @@ trait AccountWebHookEventComponent extends TemplateComponent {
val url = column[String]("URL") val url = column[String]("URL")
val event = column[WebHook.Event]("EVENT") val event = column[WebHook.Event]("EVENT")
def * = (userName, url, event).<>((AccountWebHookEvent.apply _).tupled, AccountWebHookEvent.unapply) def * = (userName, url, event) <> ((AccountWebHookEvent.apply _).tupled, AccountWebHookEvent.unapply)
def byAccountWebHook(userName: String, url: String) = (this.userName === userName.bind) && (this.url === url.bind) def byAccountWebHook(userName: String, url: String) = (this.userName === userName.bind) && (this.url === url.bind)

View File

@@ -1,9 +1,5 @@
package gitbucket.core.model package gitbucket.core.model
/**
* ActivityComponent has been deprecated, but keep it for binary compatibility.
*/
@deprecated("ActivityComponent has been deprecated, but keep it for binary compatibility.", "4.34.0")
trait ActivityComponent extends TemplateComponent { self: Profile => trait ActivityComponent extends TemplateComponent { self: Profile =>
import profile.api._ import profile.api._
import self._ import self._
@@ -11,7 +7,14 @@ trait ActivityComponent extends TemplateComponent { self: Profile =>
lazy val Activities = TableQuery[Activities] lazy val Activities = TableQuery[Activities]
class Activities(tag: Tag) extends Table[Activity](tag, "ACTIVITY") with BasicTemplate { class Activities(tag: Tag) extends Table[Activity](tag, "ACTIVITY") with BasicTemplate {
def * = ??? val activityId = column[Int]("ACTIVITY_ID", O AutoInc)
val activityUserName = column[String]("ACTIVITY_USER_NAME")
val activityType = column[String]("ACTIVITY_TYPE")
val message = column[String]("MESSAGE")
val additionalInfo = column[String]("ADDITIONAL_INFO")
val activityDate = column[java.util.Date]("ACTIVITY_DATE")
def * =
(userName, repositoryName, activityUserName, activityType, message, additionalInfo.?, activityDate, activityId) <> (Activity.tupled, Activity.unapply)
} }
} }
@@ -23,5 +26,5 @@ case class Activity(
message: String, message: String,
additionalInfo: Option[String], additionalInfo: Option[String],
activityDate: java.util.Date, activityDate: java.util.Date,
activityId: String activityId: Int = 0
) )

View File

@@ -8,7 +8,7 @@ trait CollaboratorComponent extends TemplateComponent { self: Profile =>
class Collaborators(tag: Tag) extends Table[Collaborator](tag, "COLLABORATOR") with BasicTemplate { class Collaborators(tag: Tag) extends Table[Collaborator](tag, "COLLABORATOR") with BasicTemplate {
val collaboratorName = column[String]("COLLABORATOR_NAME") val collaboratorName = column[String]("COLLABORATOR_NAME")
val role = column[String]("ROLE") val role = column[String]("ROLE")
def * = (userName, repositoryName, collaboratorName, role).<>(Collaborator.tupled, Collaborator.unapply) def * = (userName, repositoryName, collaboratorName, role) <> (Collaborator.tupled, Collaborator.unapply)
def byPrimaryKey(owner: String, repository: String, collaborator: String) = def byPrimaryKey(owner: String, repository: String, collaborator: String) =
byRepository(owner, repository) && (collaboratorName === collaborator.bind) byRepository(owner, repository) && (collaboratorName === collaborator.bind)

View File

@@ -20,8 +20,7 @@ trait IssueCommentComponent extends TemplateComponent { self: Profile =>
val registeredDate = column[java.util.Date]("REGISTERED_DATE") val registeredDate = column[java.util.Date]("REGISTERED_DATE")
val updatedDate = column[java.util.Date]("UPDATED_DATE") val updatedDate = column[java.util.Date]("UPDATED_DATE")
def * = def * =
(userName, repositoryName, issueId, commentId, action, commentedUserName, content, registeredDate, updatedDate) (userName, repositoryName, issueId, commentId, action, commentedUserName, content, registeredDate, updatedDate) <> (IssueComment.tupled, IssueComment.unapply)
.<>(IssueComment.tupled, IssueComment.unapply)
def byPrimaryKey(commentId: Int) = this.commentId === commentId.bind def byPrimaryKey(commentId: Int) = this.commentId === commentId.bind
} }
@@ -75,7 +74,7 @@ trait CommitCommentComponent extends TemplateComponent { self: Profile =>
originalCommitId, originalCommitId,
originalOldLine, originalOldLine,
originalNewLine originalNewLine
).<>(CommitComment.tupled, CommitComment.unapply) ) <> (CommitComment.tupled, CommitComment.unapply)
def byPrimaryKey(commentId: Int) = this.commentId === commentId.bind def byPrimaryKey(commentId: Int) = this.commentId === commentId.bind
} }

View File

@@ -29,7 +29,7 @@ trait CommitStatusComponent extends TemplateComponent { self: Profile =>
creator, creator,
registeredDate, registeredDate,
updatedDate updatedDate
).<>((CommitStatus.apply _).tupled, CommitStatus.unapply) ) <> ((CommitStatus.apply _).tupled, CommitStatus.unapply)
def byPrimaryKey(id: Int) = commitStatusId === id.bind def byPrimaryKey(id: Int) = commitStatusId === id.bind
} }
} }

View File

@@ -11,7 +11,7 @@ trait DeployKeyComponent extends TemplateComponent { self: Profile =>
val publicKey = column[String]("PUBLIC_KEY") val publicKey = column[String]("PUBLIC_KEY")
val allowWrite = column[Boolean]("ALLOW_WRITE") val allowWrite = column[Boolean]("ALLOW_WRITE")
def * = def * =
(userName, repositoryName, deployKeyId, title, publicKey, allowWrite).<>(DeployKey.tupled, DeployKey.unapply) (userName, repositoryName, deployKeyId, title, publicKey, allowWrite) <> (DeployKey.tupled, DeployKey.unapply)
def byPrimaryKey(userName: String, repositoryName: String, deployKeyId: Int) = def byPrimaryKey(userName: String, repositoryName: String, deployKeyId: Int) =
(this.userName === userName.bind) && (this.repositoryName === repositoryName.bind) && (this.deployKeyId === deployKeyId.bind) (this.userName === userName.bind) && (this.repositoryName === repositoryName.bind) && (this.deployKeyId === deployKeyId.bind)

View File

@@ -11,7 +11,7 @@ trait GpgKeyComponent { self: Profile =>
val gpgKeyId = column[Long]("GPG_KEY_ID") val gpgKeyId = column[Long]("GPG_KEY_ID")
val title = column[String]("TITLE") val title = column[String]("TITLE")
val publicKey = column[String]("PUBLIC_KEY") val publicKey = column[String]("PUBLIC_KEY")
def * = (userName, keyId, gpgKeyId, title, publicKey).<>(GpgKey.tupled, GpgKey.unapply) def * = (userName, keyId, gpgKeyId, title, publicKey) <> (GpgKey.tupled, GpgKey.unapply)
def byPrimaryKey(userName: String, keyId: Int) = def byPrimaryKey(userName: String, keyId: Int) =
(this.userName === userName.bind) && (this.keyId === keyId.bind) (this.userName === userName.bind) && (this.keyId === keyId.bind)

View File

@@ -9,7 +9,7 @@ trait GroupMemberComponent { self: Profile =>
val groupName = column[String]("GROUP_NAME", O PrimaryKey) val groupName = column[String]("GROUP_NAME", O PrimaryKey)
val userName = column[String]("USER_NAME", O PrimaryKey) val userName = column[String]("USER_NAME", O PrimaryKey)
val isManager = column[Boolean]("MANAGER") val isManager = column[Boolean]("MANAGER")
def * = (groupName, userName, isManager).<>(GroupMember.tupled, GroupMember.unapply) def * = (groupName, userName, isManager) <> (GroupMember.tupled, GroupMember.unapply)
} }
} }

View File

@@ -49,7 +49,7 @@ trait IssueComponent extends TemplateComponent { self: Profile =>
registeredDate, registeredDate,
updatedDate, updatedDate,
pullRequest pullRequest
).<>(Issue.tupled, Issue.unapply) ) <> (Issue.tupled, Issue.unapply)
def byPrimaryKey(owner: String, repository: String, issueId: Int) = byIssue(owner, repository, issueId) def byPrimaryKey(owner: String, repository: String, issueId: Int) = byIssue(owner, repository, issueId)
} }

View File

@@ -6,7 +6,7 @@ trait IssueLabelComponent extends TemplateComponent { self: Profile =>
lazy val IssueLabels = TableQuery[IssueLabels] lazy val IssueLabels = TableQuery[IssueLabels]
class IssueLabels(tag: Tag) extends Table[IssueLabel](tag, "ISSUE_LABEL") with IssueTemplate with LabelTemplate { class IssueLabels(tag: Tag) extends Table[IssueLabel](tag, "ISSUE_LABEL") with IssueTemplate with LabelTemplate {
def * = (userName, repositoryName, issueId, labelId).<>(IssueLabel.tupled, IssueLabel.unapply) def * = (userName, repositoryName, issueId, labelId) <> (IssueLabel.tupled, IssueLabel.unapply)
def byPrimaryKey(owner: String, repository: String, issueId: Int, labelId: Int) = def byPrimaryKey(owner: String, repository: String, issueId: Int, labelId: Int) =
byIssue(owner, repository, issueId) && (this.labelId === labelId.bind) byIssue(owner, repository, issueId) && (this.labelId === labelId.bind)
} }

View File

@@ -9,7 +9,7 @@ trait LabelComponent extends TemplateComponent { self: Profile =>
override val labelId = column[Int]("LABEL_ID", O AutoInc) override val labelId = column[Int]("LABEL_ID", O AutoInc)
override val labelName = column[String]("LABEL_NAME") override val labelName = column[String]("LABEL_NAME")
val color = column[String]("COLOR") val color = column[String]("COLOR")
def * = (userName, repositoryName, labelId, labelName, color).<>(Label.tupled, Label.unapply) def * = (userName, repositoryName, labelId, labelName, color) <> (Label.tupled, Label.unapply)
def byPrimaryKey(owner: String, repository: String, labelId: Int) = byLabel(owner, repository, labelId) def byPrimaryKey(owner: String, repository: String, labelId: Int) = byLabel(owner, repository, labelId)
def byPrimaryKey(userName: Rep[String], repositoryName: Rep[String], labelId: Rep[Int]) = def byPrimaryKey(userName: Rep[String], repositoryName: Rep[String], labelId: Rep[Int]) =

View File

@@ -13,8 +13,7 @@ trait MilestoneComponent extends TemplateComponent { self: Profile =>
val dueDate = column[Option[java.util.Date]]("DUE_DATE") val dueDate = column[Option[java.util.Date]]("DUE_DATE")
val closedDate = column[Option[java.util.Date]]("CLOSED_DATE") val closedDate = column[Option[java.util.Date]]("CLOSED_DATE")
def * = def * =
(userName, repositoryName, milestoneId, title, description, dueDate, closedDate) (userName, repositoryName, milestoneId, title, description, dueDate, closedDate) <> (Milestone.tupled, Milestone.unapply)
.<>(Milestone.tupled, Milestone.unapply)
def byPrimaryKey(owner: String, repository: String, milestoneId: Int) = byMilestone(owner, repository, milestoneId) def byPrimaryKey(owner: String, repository: String, milestoneId: Int) = byMilestone(owner, repository, milestoneId)
def byPrimaryKey(userName: Rep[String], repositoryName: Rep[String], milestoneId: Rep[Int]) = def byPrimaryKey(userName: Rep[String], repositoryName: Rep[String], milestoneId: Rep[Int]) =

View File

@@ -13,8 +13,7 @@ trait PriorityComponent extends TemplateComponent { self: Profile =>
val isDefault = column[Boolean]("IS_DEFAULT") val isDefault = column[Boolean]("IS_DEFAULT")
val color = column[String]("COLOR") val color = column[String]("COLOR")
def * = def * =
(userName, repositoryName, priorityId, priorityName, description.?, isDefault, ordering, color) (userName, repositoryName, priorityId, priorityName, description.?, isDefault, ordering, color) <> (Priority.tupled, Priority.unapply)
.<>(Priority.tupled, Priority.unapply)
def byPrimaryKey(owner: String, repository: String, priorityId: Int) = byPriority(owner, repository, priorityId) def byPrimaryKey(owner: String, repository: String, priorityId: Int) = byPriority(owner, repository, priorityId)
def byPrimaryKey(userName: Rep[String], repositoryName: Rep[String], priorityId: Rep[Int]) = def byPrimaryKey(userName: Rep[String], repositoryName: Rep[String], priorityId: Rep[Int]) =

View File

@@ -70,6 +70,5 @@ trait CoreProfile
with ReleaseTagComponent with ReleaseTagComponent
with ReleaseAssetComponent with ReleaseAssetComponent
with AccountExtraMailAddressComponent with AccountExtraMailAddressComponent
with AccountPreferenceComponent
object Profile extends CoreProfile object Profile extends CoreProfile

View File

@@ -7,7 +7,7 @@ trait ProtectedBranchComponent extends TemplateComponent { self: Profile =>
lazy val ProtectedBranches = TableQuery[ProtectedBranches] lazy val ProtectedBranches = TableQuery[ProtectedBranches]
class ProtectedBranches(tag: Tag) extends Table[ProtectedBranch](tag, "PROTECTED_BRANCH") with BranchTemplate { class ProtectedBranches(tag: Tag) extends Table[ProtectedBranch](tag, "PROTECTED_BRANCH") with BranchTemplate {
val statusCheckAdmin = column[Boolean]("STATUS_CHECK_ADMIN") val statusCheckAdmin = column[Boolean]("STATUS_CHECK_ADMIN")
def * = (userName, repositoryName, branch, statusCheckAdmin).<>(ProtectedBranch.tupled, ProtectedBranch.unapply) def * = (userName, repositoryName, branch, statusCheckAdmin) <> (ProtectedBranch.tupled, ProtectedBranch.unapply)
def byPrimaryKey(userName: String, repositoryName: String, branch: String) = def byPrimaryKey(userName: String, repositoryName: String, branch: String) =
byBranch(userName, repositoryName, branch) byBranch(userName, repositoryName, branch)
def byPrimaryKey(userName: Rep[String], repositoryName: Rep[String], branch: Rep[String]) = def byPrimaryKey(userName: Rep[String], repositoryName: Rep[String], branch: Rep[String]) =
@@ -20,7 +20,7 @@ trait ProtectedBranchComponent extends TemplateComponent { self: Profile =>
with BranchTemplate { with BranchTemplate {
val context = column[String]("CONTEXT") val context = column[String]("CONTEXT")
def * = def * =
(userName, repositoryName, branch, context).<>(ProtectedBranchContext.tupled, ProtectedBranchContext.unapply) (userName, repositoryName, branch, context) <> (ProtectedBranchContext.tupled, ProtectedBranchContext.unapply)
} }
} }

View File

@@ -25,7 +25,7 @@ trait PullRequestComponent extends TemplateComponent { self: Profile =>
commitIdFrom, commitIdFrom,
commitIdTo, commitIdTo,
isDraft isDraft
).<>(PullRequest.tupled, PullRequest.unapply) ) <> (PullRequest.tupled, PullRequest.unapply)
def byPrimaryKey(userName: String, repositoryName: String, issueId: Int) = def byPrimaryKey(userName: String, repositoryName: String, issueId: Int) =
byIssue(userName, repositoryName, issueId) byIssue(userName, repositoryName, issueId)

View File

@@ -21,8 +21,7 @@ trait ReleaseAssetComponent extends TemplateComponent {
val updatedDate = column[Date]("UPDATED_DATE") val updatedDate = column[Date]("UPDATED_DATE")
def * = def * =
(userName, repositoryName, tag, releaseAssetId, fileName, label, size, uploader, registeredDate, updatedDate) (userName, repositoryName, tag, releaseAssetId, fileName, label, size, uploader, registeredDate, updatedDate) <> (ReleaseAsset.tupled, ReleaseAsset.unapply)
.<>(ReleaseAsset.tupled, ReleaseAsset.unapply)
def byPrimaryKey(owner: String, repository: String, tag: String, fileName: String) = def byPrimaryKey(owner: String, repository: String, tag: String, fileName: String) =
byTag(owner, repository, tag) && (this.fileName === fileName.bind) byTag(owner, repository, tag) && (this.fileName === fileName.bind)
def byTag(owner: String, repository: String, tag: String) = def byTag(owner: String, repository: String, tag: String) =

View File

@@ -17,8 +17,7 @@ trait ReleaseTagComponent extends TemplateComponent {
val updatedDate = column[java.util.Date]("UPDATED_DATE") val updatedDate = column[java.util.Date]("UPDATED_DATE")
def * = def * =
(userName, repositoryName, name, tag, author, content, registeredDate, updatedDate) (userName, repositoryName, name, tag, author, content, registeredDate, updatedDate) <> (ReleaseTag.tupled, ReleaseTag.unapply)
.<>(ReleaseTag.tupled, ReleaseTag.unapply)
def byPrimaryKey(owner: String, repository: String, tag: String) = byTag(owner, repository, tag) def byPrimaryKey(owner: String, repository: String, tag: String) = byTag(owner, repository, tag)
def byTag(owner: String, repository: String, tag: String) = def byTag(owner: String, repository: String, tag: String) =
byRepository(owner, repository) && (this.tag === tag.bind) byRepository(owner, repository) && (this.tag === tag.bind)

View File

@@ -42,48 +42,46 @@ trait RepositoryComponent extends TemplateComponent { self: Profile =>
parentRepositoryName.? parentRepositoryName.?
), ),
(issuesOption, externalIssuesUrl.?, wikiOption, externalWikiUrl.?, allowFork, mergeOptions, defaultMergeOption) (issuesOption, externalIssuesUrl.?, wikiOption, externalWikiUrl.?, allowFork, mergeOptions, defaultMergeOption)
).shaped.<>( ).shaped <> ({
{ case (repository, options) =>
case (repository, options) => Repository(
Repository( repository._1,
repository._1, repository._2,
repository._2, repository._3,
repository._3, repository._4,
repository._4, repository._5,
repository._5, repository._6,
repository._6, repository._7,
repository._7, repository._8,
repository._8, repository._9,
repository._9, repository._10,
repository._10, repository._11,
repository._11, repository._12,
repository._12, RepositoryOptions.tupled.apply(options)
RepositoryOptions.tupled.apply(options) )
) }, { (r: Repository) =>
}, { (r: Repository) => Some(
Some( (
( (
( r.userName,
r.userName, r.repositoryName,
r.repositoryName, r.isPrivate,
r.isPrivate, r.description,
r.description, r.defaultBranch,
r.defaultBranch, r.registeredDate,
r.registeredDate, r.updatedDate,
r.updatedDate, r.lastActivityDate,
r.lastActivityDate, r.originUserName,
r.originUserName, r.originRepositoryName,
r.originRepositoryName, r.parentUserName,
r.parentUserName, r.parentRepositoryName
r.parentRepositoryName ),
), (
( RepositoryOptions.unapply(r.options).get
RepositoryOptions.unapply(r.options).get
)
) )
) )
} )
) })
def byPrimaryKey(owner: String, repository: String) = byRepository(owner, repository) def byPrimaryKey(owner: String, repository: String) = byRepository(owner, repository)
} }

View File

@@ -9,26 +9,20 @@ trait RepositoryWebHookComponent extends TemplateComponent { self: Profile =>
lazy val RepositoryWebHooks = TableQuery[RepositoryWebHooks] lazy val RepositoryWebHooks = TableQuery[RepositoryWebHooks]
class RepositoryWebHooks(tag: Tag) extends Table[RepositoryWebHook](tag, "WEB_HOOK") with BasicTemplate { class RepositoryWebHooks(tag: Tag) extends Table[RepositoryWebHook](tag, "WEB_HOOK") with BasicTemplate {
val hookId = column[Int]("HOOK_ID", O AutoInc)
val url = column[String]("URL") val url = column[String]("URL")
val token = column[Option[String]]("TOKEN") val token = column[Option[String]]("TOKEN")
val ctype = column[WebHookContentType]("CTYPE") val ctype = column[WebHookContentType]("CTYPE")
def * = def * =
(userName, repositoryName, hookId, url, ctype, token) (userName, repositoryName, url, ctype, token) <> ((RepositoryWebHook.apply _).tupled, RepositoryWebHook.unapply)
.<>((RepositoryWebHook.apply _).tupled, RepositoryWebHook.unapply)
def byRepositoryUrl(owner: String, repository: String, url: String) = def byPrimaryKey(owner: String, repository: String, url: String) =
byRepository(owner, repository) && (this.url === url.bind) byRepository(owner, repository) && (this.url === url.bind)
def byId(id: Int) =
(this.hookId === id.bind)
} }
} }
case class RepositoryWebHook( case class RepositoryWebHook(
userName: String, userName: String,
repositoryName: String, repositoryName: String,
hookId: Int = 0,
url: String, url: String,
ctype: WebHookContentType, ctype: WebHookContentType,
token: Option[String] token: Option[String]

View File

@@ -12,7 +12,7 @@ trait RepositoryWebHookEventComponent extends TemplateComponent { self: Profile
val url = column[String]("URL") val url = column[String]("URL")
val event = column[WebHook.Event]("EVENT") val event = column[WebHook.Event]("EVENT")
def * = def * =
(userName, repositoryName, url, event).<>((RepositoryWebHookEvent.apply _).tupled, RepositoryWebHookEvent.unapply) (userName, repositoryName, url, event) <> ((RepositoryWebHookEvent.apply _).tupled, RepositoryWebHookEvent.unapply)
def byRepositoryWebHook(owner: String, repository: String, url: String) = def byRepositoryWebHook(owner: String, repository: String, url: String) =
byRepository(owner, repository) && (this.url === url.bind) byRepository(owner, repository) && (this.url === url.bind)

View File

@@ -10,7 +10,7 @@ trait SshKeyComponent { self: Profile =>
val sshKeyId = column[Int]("SSH_KEY_ID", O AutoInc) val sshKeyId = column[Int]("SSH_KEY_ID", O AutoInc)
val title = column[String]("TITLE") val title = column[String]("TITLE")
val publicKey = column[String]("PUBLIC_KEY") val publicKey = column[String]("PUBLIC_KEY")
def * = (userName, sshKeyId, title, publicKey).<>(SshKey.tupled, SshKey.unapply) def * = (userName, sshKeyId, title, publicKey) <> (SshKey.tupled, SshKey.unapply)
def byPrimaryKey(userName: String, sshKeyId: Int) = def byPrimaryKey(userName: String, sshKeyId: Int) =
(this.userName === userName.bind) && (this.sshKeyId === sshKeyId.bind) (this.userName === userName.bind) && (this.sshKeyId === sshKeyId.bind)

View File

@@ -1,12 +0,0 @@
package gitbucket.core.model.activity
import gitbucket.core.model.Activity
trait BaseActivityInfo {
def toActivity: Activity
protected def trimInfoString(str: String, maxLen: Int): String =
if (str.length > maxLen) s"${str.substring(0, maxLen)}..."
else str
}

View File

@@ -1,74 +0,0 @@
package gitbucket.core.model.activity
import java.util.UUID
import gitbucket.core.model.Activity
import gitbucket.core.model.Profile.currentDate
import gitbucket.core.util.JGitUtil.CommitInfo
final case class PushInfo(
userName: String,
repositoryName: String,
activityUserName: String,
branchName: String,
commits: List[CommitInfo]
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"push",
s"[user:$activityUserName] pushed to [branch:$userName/$repositoryName#$branchName] at [repo:$userName/$repositoryName]",
Some(buildCommitSummary(commits)),
currentDate,
UUID.randomUUID().toString
)
private[this] def buildCommitSummary(commits: List[CommitInfo]): String =
commits
.take(5)
.map(commit => s"${commit.id}:${commit.shortMessage}")
.mkString("\n")
}
final case class CreateBranchInfo(
userName: String,
repositoryName: String,
activityUserName: String,
branchName: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"create_branch",
s"[user:$activityUserName] created branch [branch:$userName/$repositoryName#$branchName] at [repo:$userName/$repositoryName]",
None,
currentDate,
UUID.randomUUID().toString
)
}
final case class DeleteBranchInfo(
userName: String,
repositoryName: String,
activityUserName: String,
branchName: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"delete_branch",
s"[user:$activityUserName] deleted branch $branchName at [repo:$userName/$repositoryName]",
None,
currentDate,
UUID.randomUUID().toString
)
}

View File

@@ -1,69 +0,0 @@
package gitbucket.core.model.activity
import java.util.UUID
import gitbucket.core.model.Activity
import gitbucket.core.model.Profile.currentDate
final case class IssueCommentInfo(
userName: String,
repositoryName: String,
activityUserName: String,
comment: String,
issueId: Int
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"comment_issue",
s"[user:${activityUserName}] commented on issue [issue:${userName}/${repositoryName}#${issueId}]",
Some(trimInfoString(comment, 200)),
currentDate,
UUID.randomUUID().toString
)
}
final case class PullRequestCommentInfo(
userName: String,
repositoryName: String,
activityUserName: String,
comment: String,
issueId: Int
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"comment_issue",
s"[user:$activityUserName] commented on pull request [pullreq:$userName/$repositoryName#$issueId]",
Some(trimInfoString(comment, 200)),
currentDate,
UUID.randomUUID().toString
)
}
final case class CommitCommentInfo(
userName: String,
repositoryName: String,
activityUserName: String,
comment: String,
commitId: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"comment_commit",
s"[user:$activityUserName] commented on commit [commit:$userName/$repositoryName@$commitId]",
Some(trimInfoString(comment, 200)),
currentDate,
UUID.randomUUID().toString
)
}

View File

@@ -1,26 +0,0 @@
package gitbucket.core.model.activity
import java.util.UUID
import gitbucket.core.model.Activity
import gitbucket.core.model.Profile.currentDate
final case class ForkInfo(
userName: String,
repositoryName: String,
activityUserName: String,
forkedUserName: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"fork",
s"[user:$activityUserName] forked [repo:$userName/$repositoryName] to [repo:$forkedUserName/$repositoryName]",
None,
currentDate,
UUID.randomUUID().toString
)
}

View File

@@ -1,132 +0,0 @@
package gitbucket.core.model.activity
import java.util.UUID
import gitbucket.core.model.Activity
import gitbucket.core.model.Profile.currentDate
final case class CreateIssueInfo(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
title: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"open_issue",
s"[user:$activityUserName] opened issue [issue:$userName/$repositoryName#$issueId]",
Some(title),
currentDate,
UUID.randomUUID().toString
)
}
final case class CloseIssueInfo(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
title: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"close_issue",
s"[user:$activityUserName] closed issue [issue:$userName/$repositoryName#$issueId]",
Some(title),
currentDate,
UUID.randomUUID().toString
)
}
final case class ReopenIssueInfo(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
title: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"reopen_issue",
s"[user:$activityUserName] reopened issue [issue:$userName/$repositoryName#$issueId]",
Some(title),
currentDate,
UUID.randomUUID().toString
)
}
final case class OpenPullRequestInfo(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
title: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"open_pullreq",
s"[user:${activityUserName}] opened pull request [pullreq:${userName}/${repositoryName}#${issueId}]",
Some(title),
currentDate,
UUID.randomUUID().toString
)
}
final case class ClosePullRequestInfo(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
title: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"close_issue",
s"[user:$activityUserName] closed pull request [pullreq:$userName/$repositoryName#$issueId]",
Some(title),
currentDate,
UUID.randomUUID().toString
)
}
final case class ReopenPullRequestInfo(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
title: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"reopen_issue",
s"[user:$activityUserName] reopened pull request [issue:$userName/$repositoryName#$issueId]",
Some(title),
currentDate,
UUID.randomUUID().toString
)
}

View File

@@ -1,27 +0,0 @@
package gitbucket.core.model.activity
import java.util.UUID
import gitbucket.core.model.Activity
import gitbucket.core.model.Profile.currentDate
final case class MergeInfo(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
message: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"merge_pullreq",
s"[user:$activityUserName] merged pull request [pullreq:$userName/$repositoryName#$issueId]",
Some(message),
currentDate,
UUID.randomUUID().toString
)
}

View File

@@ -1,27 +0,0 @@
package gitbucket.core.model.activity
import java.util.UUID
import gitbucket.core.model.Activity
import gitbucket.core.model.Profile.currentDate
final case class ReleaseInfo(
userName: String,
repositoryName: String,
activityUserName: String,
releaseName: String,
tagName: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"release",
s"[user:$activityUserName] released [release:$userName/$repositoryName/$tagName:$releaseName] at [repo:$userName/$repositoryName]",
None,
currentDate,
UUID.randomUUID().toString
)
}

View File

@@ -1,84 +0,0 @@
package gitbucket.core.model.activity
import java.util.UUID
import gitbucket.core.model.Activity
import gitbucket.core.model.Profile.currentDate
final case class CreateRepositoryInfo(
userName: String,
repositoryName: String,
activityUserName: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"create_repository",
s"[user:$activityUserName] created [repo:$userName/$repositoryName]",
None,
currentDate,
UUID.randomUUID().toString
)
}
final case class DeleteRepositoryInfo(
userName: String,
repositoryName: String,
activityUserName: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"delete_repository",
s"[user:$activityUserName] deleted [repo:$userName/$repositoryName]",
None,
currentDate,
UUID.randomUUID().toString
)
}
final case class TransferRepositoryInfo(
userName: String,
repositoryName: String,
activityUserName: String,
oldUserName: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"transfer_repository",
s"[user:$activityUserName] transferred [repo:$oldUserName/$repositoryName] to [repo:$userName/$repositoryName]",
None,
currentDate,
UUID.randomUUID().toString
)
}
final case class RenameRepositoryInfo(
userName: String,
repositoryName: String,
activityUserName: String,
oldRepositoryName: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"rename_repository",
s"[user:$activityUserName] renamed [repo:$userName/$oldRepositoryName] at [repo:$userName/$repositoryName]",
None,
currentDate,
UUID.randomUUID().toString
)
}

View File

@@ -1,46 +0,0 @@
package gitbucket.core.model.activity
import java.util.UUID
import gitbucket.core.model.Activity
import gitbucket.core.model.Profile.currentDate
final case class CreateTagInfo(
userName: String,
repositoryName: String,
activityUserName: String,
tagName: String,
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"create_tag",
s"[user:$activityUserName] created tag [tag:$userName/$repositoryName#$tagName] at [repo:$userName/$repositoryName]",
None,
currentDate,
UUID.randomUUID().toString
)
}
final case class DeleteTagInfo(
userName: String,
repositoryName: String,
activityUserName: String,
tagName: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"delete_tag",
s"[user:$activityUserName] deleted tag $tagName at [repo:$userName/$repositoryName]",
None,
currentDate,
UUID.randomUUID().toString
)
}

View File

@@ -1,67 +0,0 @@
package gitbucket.core.model.activity
import java.util.UUID
import gitbucket.core.model.Activity
import gitbucket.core.model.Profile.currentDate
final case class CreateWikiPageInfo(
userName: String,
repositoryName: String,
activityUserName: String,
pageName: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"create_wiki",
s"[user:$activityUserName] created the [repo:$userName/$repositoryName] wiki",
Some(pageName),
currentDate,
UUID.randomUUID().toString
)
}
final case class EditWikiPageInfo(
userName: String,
repositoryName: String,
activityUserName: String,
pageName: String,
commitId: String
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"edit_wiki",
s"[user:$activityUserName] edited the [repo:$userName/$repositoryName] wiki",
Some(s"$pageName:$commitId"),
currentDate,
UUID.randomUUID().toString
)
}
final case class DeleteWikiInfo(
userName: String,
repositoryName: String,
activityUserName: String,
pageName: String,
) extends BaseActivityInfo {
override def toActivity: Activity =
Activity(
userName,
repositoryName,
activityUserName,
"delete_wiki",
s"[user:$activityUserName] deleted the page [$pageName] in the [repo:$userName/$repositoryName] wiki",
additionalInfo = None,
currentDate,
UUID.randomUUID().toString
)
}

View File

@@ -13,14 +13,6 @@ trait IssueHook {
implicit session: Session, implicit session: Session,
context: Context context: Context
): Unit = () ): Unit = ()
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,
context: Context
): Unit = ()
def closed(issue: Issue, repository: RepositoryInfo)(implicit session: Session, context: Context): Unit = () def closed(issue: Issue, repository: RepositoryInfo)(implicit session: Session, context: Context): Unit = ()
def reopened(issue: Issue, repository: RepositoryInfo)(implicit session: Session, context: Context): Unit = () def reopened(issue: Issue, repository: RepositoryInfo)(implicit session: Session, context: Context): Unit = ()
def assigned( def assigned(

View File

@@ -57,7 +57,6 @@ class PluginRegistry {
private val textDecorators = new ConcurrentLinkedQueue[TextDecorator] private val textDecorators = new ConcurrentLinkedQueue[TextDecorator]
private val suggestionProviders = new ConcurrentLinkedQueue[SuggestionProvider] private val suggestionProviders = new ConcurrentLinkedQueue[SuggestionProvider]
suggestionProviders.add(new UserNameSuggestionProvider()) suggestionProviders.add(new UserNameSuggestionProvider())
suggestionProviders.add(new IssueSuggestionProvider())
private val sshCommandProviders = new ConcurrentLinkedQueue[PartialFunction[String, Command]]() private val sshCommandProviders = new ConcurrentLinkedQueue[PartialFunction[String, Command]]()
def addPlugin(pluginInfo: PluginInfo): Unit = plugins.add(pluginInfo) def addPlugin(pluginInfo: PluginInfo): Unit = plugins.add(pluginInfo)

View File

@@ -6,25 +6,11 @@ import profile.api._
trait ReceiveHook { trait ReceiveHook {
def preReceive( def preReceive(owner: String, repository: String, receivePack: ReceivePack, command: ReceiveCommand, pusher: String)(
owner: String,
repository: String,
receivePack: ReceivePack,
command: ReceiveCommand,
pusher: String,
mergePullRequest: Boolean
)(
implicit session: Session implicit session: Session
): Option[String] = None ): Option[String] = None
def postReceive( def postReceive(owner: String, repository: String, receivePack: ReceivePack, command: ReceiveCommand, pusher: String)(
owner: String,
repository: String,
receivePack: ReceivePack,
command: ReceiveCommand,
pusher: String,
mergePullRequest: Boolean
)(
implicit session: Session implicit session: Session
): Unit = () ): Unit = ()

View File

@@ -91,7 +91,7 @@ trait SuggestionProvider {
* If this suggestion provider needs some additional process to assemble the proposal list (e.g. It need to use Ajax * If this suggestion provider needs some additional process to assemble the proposal list (e.g. It need to use Ajax
* to get a proposal list from the server), then override this method and return any JavaScript code. * to get a proposal list from the server), then override this method and return any JavaScript code.
*/ */
def additionalScript(repository: RepositoryInfo)(implicit context: Context): String = "" def additionalScript(implicit context: Context): String = ""
} }
@@ -99,14 +99,6 @@ class UserNameSuggestionProvider extends SuggestionProvider {
override val id: String = "user" override val id: String = "user"
override val prefix: String = "@" override val prefix: String = "@"
override val context: Seq[String] = Seq("issues") override val context: Seq[String] = Seq("issues")
override def additionalScript(repository: RepositoryInfo)(implicit context: Context): String = override def additionalScript(implicit context: Context): String =
s"""$$.get('${context.path}/_user/proposals', { query: '', user: true, group: false }, function (data) { user = data.options; });""" s"""$$.get('${context.path}/_user/proposals', { query: '', user: true, group: false }, function (data) { user = data.options; });"""
} }
class IssueSuggestionProvider extends SuggestionProvider {
override val id: String = "issue"
override val prefix: String = "#"
override val context: Seq[String] = Seq("issues")
override def additionalScript(repository: RepositoryInfo)(implicit context: Context): String =
s"""$$.get('${context.path}/${repository.owner}/${repository.name}/_issue/proposals', function (data) { issue = data.options; });"""
}

View File

@@ -1,7 +1,7 @@
package gitbucket.core.service package gitbucket.core.service
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import gitbucket.core.model.{Account, AccountExtraMailAddress, AccountPreference, GroupMember} import gitbucket.core.model.{Account, AccountExtraMailAddress, GroupMember}
import gitbucket.core.model.Profile._ import gitbucket.core.model.Profile._
import gitbucket.core.model.Profile.profile.blockingApi._ import gitbucket.core.model.Profile.profile.blockingApi._
import gitbucket.core.model.Profile.dateColumnType import gitbucket.core.model.Profile.dateColumnType
@@ -17,9 +17,7 @@ trait AccountService {
def authenticate(settings: SystemSettings, userName: String, password: String)( def authenticate(settings: SystemSettings, userName: String, password: String)(
implicit s: Session implicit s: Session
): Option[Account] = { ): Option[Account] = {
val account = if (password.isEmpty) { val account = if (settings.ldapAuthentication) {
None
} else if (settings.ldapAuthentication) {
ldapAuthentication(settings, userName, password) ldapAuthentication(settings, userName, password)
} else { } else {
defaultAuthentication(userName, password) defaultAuthentication(userName, password)
@@ -105,13 +103,13 @@ trait AccountService {
} }
def getAccountByUserName(userName: String, includeRemoved: Boolean = false)(implicit s: Session): Option[Account] = 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 Accounts filter (t => (t.userName === userName.bind) && (t.removed === false.bind, !includeRemoved)) firstOption
def getAccountByUserNameIgnoreCase(userName: String, includeRemoved: Boolean = false)( def getAccountByUserNameIgnoreCase(userName: String, includeRemoved: Boolean = false)(
implicit s: Session implicit s: Session
): Option[Account] = ): Option[Account] =
Accounts filter ( Accounts filter (
t => (t.userName.toLowerCase === userName.toLowerCase.bind).&&(t.removed === false.bind, !includeRemoved) t => (t.userName.toLowerCase === userName.toLowerCase.bind) && (t.removed === false.bind, !includeRemoved)
) firstOption ) firstOption
def getAccountsByUserNames(userNames: Set[String], knowns: Set[Account], includeRemoved: Boolean = false)( def getAccountsByUserNames(userNames: Set[String], knowns: Set[Account], includeRemoved: Boolean = false)(
@@ -123,7 +121,7 @@ trait AccountService {
map map
} else { } else {
map ++ Accounts map ++ Accounts
.filter(t => (t.userName inSetBind needs).&&(t.removed === false.bind, !includeRemoved)) .filter(t => (t.userName inSetBind needs) && (t.removed === false.bind, !includeRemoved))
.list .list
.map(a => a.userName -> a) .map(a => a.userName -> a)
.toMap .toMap
@@ -140,15 +138,15 @@ trait AccountService {
(x.map { e => (x.map { e =>
e.extraMailAddress.toLowerCase === mailAddress.toLowerCase.bind 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 .map { case (a, e) => a } firstOption
def getAllUsers(includeRemoved: Boolean = true, includeGroups: Boolean = true)(implicit s: Session): List[Account] = { def getAllUsers(includeRemoved: Boolean = true, includeGroups: Boolean = true)(implicit s: Session): List[Account] = {
Accounts filter { t => Accounts filter { t =>
(1.bind === 1.bind) (1.bind === 1.bind) &&
.&&(t.groupAccount === false.bind, !includeGroups) (t.groupAccount === false.bind, !includeGroups) &&
.&&(t.removed === false.bind, !includeRemoved) (t.removed === false.bind, !includeRemoved)
} sortBy (_.userName) list } sortBy (_.userName) list
} }
@@ -310,33 +308,6 @@ trait AccountService {
Collaborators.filter(_.collaboratorName === userName.bind).sortBy(_.userName).map(_.userName).list.distinct Collaborators.filter(_.collaboratorName === userName.bind).sortBy(_.userName).map(_.userName).list.distinct
} }
/*
* For account preference
*/
def getAccountPreference(userName: String)(
implicit s: Session
): Option[AccountPreference] = {
AccountPreferences filter (_.byPrimaryKey(userName)) firstOption
}
def addAccountPreference(userName: String, highlighterTheme: String)(implicit s: Session): Unit = {
AccountPreferences insert AccountPreference(userName = userName, highlighterTheme = highlighterTheme)
}
def updateAccountPreference(userName: String, highlighterTheme: String)(implicit s: Session): Unit = {
AccountPreferences
.filter(_.byPrimaryKey(userName))
.map(t => t.highlighterTheme)
.update(highlighterTheme)
}
def addOrUpdateAccountPreference(userName: String, highlighterTheme: String)(implicit s: Session): Unit = {
getAccountPreference(userName) match {
case Some(_) => updateAccountPreference(userName, highlighterTheme)
case _ => addAccountPreference(userName, highlighterTheme)
}
}
} }
object AccountService extends AccountService object AccountService extends AccountService

View File

@@ -3,103 +3,389 @@ package gitbucket.core.service
import gitbucket.core.model.Activity import gitbucket.core.model.Activity
import gitbucket.core.util.JGitUtil import gitbucket.core.util.JGitUtil
import gitbucket.core.model.Profile._ import gitbucket.core.model.Profile._
import gitbucket.core.util.Directory._ import gitbucket.core.model.Profile.profile.blockingApi._
import org.json4s._
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.{read, write}
import scala.util.Using
import java.io.FileOutputStream
import java.nio.charset.StandardCharsets
import java.util.UUID
import gitbucket.core.controller.Context
import gitbucket.core.model.activity.BaseActivityInfo
import org.apache.commons.io.input.ReversedLinesFileReader
import scala.collection.mutable.ListBuffer
trait ActivityService { trait ActivityService {
self: RequestCache =>
private implicit val formats = Serialization.formats(NoTypeHints) def deleteOldActivities(limit: Int)(implicit s: Session): Int = {
Activities.map(_.activityId).sortBy(_ desc).drop(limit).firstOption.map { id =>
private def writeLog(activity: Activity): Unit = { Activities.filter(_.activityId <= id.bind).delete
Using.resource(new FileOutputStream(ActivityLog, true)) { out => } getOrElse 0
out.write((write(activity) + "\n").getBytes(StandardCharsets.UTF_8))
}
} }
def getActivitiesByUser(activityUserName: String, isPublic: Boolean)(implicit context: Context): List[Activity] = { def getActivitiesByUser(activityUserName: String, isPublic: Boolean)(implicit s: Session): List[Activity] =
if (!ActivityLog.exists()) { Activities
List.empty .join(Repositories)
} else { .on((t1, t2) => t1.byRepository(t2.userName, t2.repositoryName))
val list = new ListBuffer[Activity] .filter {
Using.resource(new ReversedLinesFileReader(ActivityLog, StandardCharsets.UTF_8)) { reader => case (t1, t2) =>
var json: String = null if (isPublic) {
while (list.length < 50 && { json = reader.readLine(); json } != null) { (t1.activityUserName === activityUserName.bind) && (t2.isPrivate === false.bind)
val activity = read[Activity](json) } else {
if (activity.activityUserName == activityUserName) { (t1.activityUserName === activityUserName.bind)
if (isPublic == false) {
list += activity
} else {
if (!getRepositoryInfoFromCache(activity.userName, activity.repositoryName)
.map(_.isPrivate)
.getOrElse(true)) {
list += activity
}
}
} }
}
} }
list.toList .sortBy { case (t1, t2) => t1.activityId desc }
} .map { case (t1, t2) => t1 }
} .take(30)
.list
def getRecentPublicActivities()(implicit context: Context): List[Activity] = { def getRecentActivities()(implicit s: Session): List[Activity] =
if (!ActivityLog.exists()) { Activities
List.empty .join(Repositories)
} else { .on((t1, t2) => t1.byRepository(t2.userName, t2.repositoryName))
val list = new ListBuffer[Activity] .filter { case (t1, t2) => t2.isPrivate === false.bind }
Using.resource(new ReversedLinesFileReader(ActivityLog, StandardCharsets.UTF_8)) { reader => .sortBy { case (t1, t2) => t1.activityId desc }
var json: String = null .map { case (t1, t2) => t1 }
while (list.length < 50 && { json = reader.readLine(); json } != null) { .take(30)
val activity = read[Activity](json) .list
if (!getRepositoryInfoFromCache(activity.userName, activity.repositoryName)
.map(_.isPrivate) def getRecentActivitiesByOwners(owners: Set[String])(implicit s: Session): List[Activity] =
.getOrElse(true)) { Activities
list += activity .join(Repositories)
.on((t1, t2) => t1.byRepository(t2.userName, t2.repositoryName))
.filter { case (t1, t2) => (t2.isPrivate === false.bind) || (t2.userName inSetBind owners) }
.sortBy { case (t1, t2) => t1.activityId desc }
.map { case (t1, t2) => t1 }
.take(30)
.list
def recordCreateRepositoryActivity(userName: String, repositoryName: String, activityUserName: String)(
implicit s: Session
): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"create_repository",
s"[user:${activityUserName}] created [repo:${userName}/${repositoryName}]",
None,
currentDate
)
def recordCreateIssueActivity(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
title: String
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"open_issue",
s"[user:${activityUserName}] opened issue [issue:${userName}/${repositoryName}#${issueId}]",
Some(title),
currentDate
)
def recordCloseIssueActivity(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
title: String
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"close_issue",
s"[user:${activityUserName}] closed issue [issue:${userName}/${repositoryName}#${issueId}]",
Some(title),
currentDate
)
def recordClosePullRequestActivity(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
title: String
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"close_issue",
s"[user:${activityUserName}] closed pull request [pullreq:${userName}/${repositoryName}#${issueId}]",
Some(title),
currentDate
)
def recordReopenIssueActivity(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
title: String
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"reopen_issue",
s"[user:${activityUserName}] reopened issue [issue:${userName}/${repositoryName}#${issueId}]",
Some(title),
currentDate
)
def recordReopenPullRequestActivity(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
title: String
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"reopen_issue",
s"[user:${activityUserName}] reopened pull request [issue:${userName}/${repositoryName}#${issueId}]",
Some(title),
currentDate
)
def recordCommentIssueActivity(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
comment: String
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"comment_issue",
s"[user:${activityUserName}] commented on issue [issue:${userName}/${repositoryName}#${issueId}]",
Some(cut(comment, 200)),
currentDate
)
def recordCommentPullRequestActivity(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
comment: String
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"comment_issue",
s"[user:${activityUserName}] commented on pull request [pullreq:${userName}/${repositoryName}#${issueId}]",
Some(cut(comment, 200)),
currentDate
)
def recordCommentCommitActivity(
userName: String,
repositoryName: String,
activityUserName: String,
commitId: String,
comment: String
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"comment_commit",
s"[user:${activityUserName}] commented on commit [commit:${userName}/${repositoryName}@${commitId}]",
Some(cut(comment, 200)),
currentDate
)
def recordCreateWikiPageActivity(
userName: String,
repositoryName: String,
activityUserName: String,
pageName: String
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"create_wiki",
s"[user:${activityUserName}] created the [repo:${userName}/${repositoryName}] wiki",
Some(pageName),
currentDate
)
def recordEditWikiPageActivity(
userName: String,
repositoryName: String,
activityUserName: String,
pageName: String,
commitId: String
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"edit_wiki",
s"[user:${activityUserName}] edited the [repo:${userName}/${repositoryName}] wiki",
Some(pageName + ":" + commitId),
currentDate
)
def recordPushActivity(
userName: String,
repositoryName: String,
activityUserName: String,
branchName: String,
commits: List[JGitUtil.CommitInfo]
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"push",
s"[user:${activityUserName}] pushed to [branch:${userName}/${repositoryName}#${branchName}] at [repo:${userName}/${repositoryName}]",
Some(
commits
.take(5)
.map { commit =>
commit.id + ":" + commit.shortMessage
} }
} .mkString("\n")
} ),
list.toList currentDate
} )
}
def getRecentActivitiesByOwners(owners: Set[String])(implicit context: Context): List[Activity] = { def recordCreateTagActivity(
if (!ActivityLog.exists()) { userName: String,
List.empty repositoryName: String,
} else { activityUserName: String,
val list = new ListBuffer[Activity] tagName: String,
Using.resource(new ReversedLinesFileReader(ActivityLog, StandardCharsets.UTF_8)) { reader => commits: List[JGitUtil.CommitInfo]
var json: String = null )(implicit s: Session): Unit =
while (list.length < 50 && { json = reader.readLine(); json } != null) { Activities insert Activity(
val activity = read[Activity](json) userName,
if (owners.contains(activity.userName)) { repositoryName,
list += activity activityUserName,
} else if (!getRepositoryInfoFromCache(activity.userName, activity.repositoryName) "create_tag",
.map(_.isPrivate) s"[user:${activityUserName}] created tag [tag:${userName}/${repositoryName}#${tagName}] at [repo:${userName}/${repositoryName}]",
.getOrElse(true)) { None,
list += activity currentDate
} )
}
}
list.toList
}
}
def recordActivity[T <: { def toActivity: Activity }](info: T): Unit = { def recordDeleteTagActivity(
import scala.language.reflectiveCalls userName: String,
writeLog(info.toActivity) repositoryName: String,
} activityUserName: String,
tagName: String,
commits: List[JGitUtil.CommitInfo]
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"delete_tag",
s"[user:${activityUserName}] deleted tag ${tagName} at [repo:${userName}/${repositoryName}]",
None,
currentDate
)
def recordCreateBranchActivity(
userName: String,
repositoryName: String,
activityUserName: String,
branchName: String
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"create_branch",
s"[user:${activityUserName}] created branch [branch:${userName}/${repositoryName}#${branchName}] at [repo:${userName}/${repositoryName}]",
None,
currentDate
)
def recordDeleteBranchActivity(
userName: String,
repositoryName: String,
activityUserName: String,
branchName: String
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"delete_branch",
s"[user:${activityUserName}] deleted branch ${branchName} at [repo:${userName}/${repositoryName}]",
None,
currentDate
)
def recordForkActivity(userName: String, repositoryName: String, activityUserName: String, forkedUserName: String)(
implicit s: Session
): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"fork",
s"[user:${activityUserName}] forked [repo:${userName}/${repositoryName}] to [repo:${forkedUserName}/${repositoryName}]",
None,
currentDate
)
def recordPullRequestActivity(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
title: String
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"open_pullreq",
s"[user:${activityUserName}] opened pull request [pullreq:${userName}/${repositoryName}#${issueId}]",
Some(title),
currentDate
)
def recordMergeActivity(
userName: String,
repositoryName: String,
activityUserName: String,
issueId: Int,
message: String
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"merge_pullreq",
s"[user:${activityUserName}] merged pull request [pullreq:${userName}/${repositoryName}#${issueId}]",
Some(message),
currentDate
)
def recordReleaseActivity(
userName: String,
repositoryName: String,
activityUserName: String,
releaseName: String,
tagName: String
)(implicit s: Session): Unit =
Activities insert Activity(
userName,
repositoryName,
activityUserName,
"release",
s"[user:${activityUserName}] released [release:${userName}/${repositoryName}/${tagName}:${releaseName}] at [repo:${userName}/${repositoryName}]",
None,
currentDate
)
private def cut(value: String, length: Int): String =
if (value.length > length) value.substring(0, length) + "..." else value
} }

View File

@@ -47,18 +47,6 @@ trait CommitStatusService {
) )
} }
def getCommitStatusWithSummary(userName: String, repositoryName: String, sha: String)(
implicit s: Session
): Option[(CommitState, List[CommitStatus])] = {
val statuses = getCommitStatuses(userName, repositoryName, sha)
if (statuses.isEmpty) {
None
} else {
val summary = CommitState.combine(statuses.groupBy(_.state).keySet)
Some((summary, statuses))
}
}
def getCommitStatus(userName: String, repositoryName: String, id: Int)(implicit s: Session): Option[CommitStatus] = def getCommitStatus(userName: String, repositoryName: String, id: Int)(implicit s: Session): Option[CommitStatus] =
CommitStatuses.filter(t => t.byPrimaryKey(id) && t.byRepository(userName, repositoryName)).firstOption CommitStatuses.filter(t => t.byPrimaryKey(id) && t.byRepository(userName, repositoryName)).firstOption
@@ -67,12 +55,10 @@ trait CommitStatusService {
): Option[CommitStatus] = ): Option[CommitStatus] =
CommitStatuses.filter(t => t.byCommit(userName, repositoryName, sha) && t.context === context.bind).firstOption CommitStatuses.filter(t => t.byCommit(userName, repositoryName, sha) && t.context === context.bind).firstOption
def getCommitStatuses(userName: String, repositoryName: String, sha: String)( def getCommitStatues(userName: String, repositoryName: String, sha: String)(implicit s: Session): List[CommitStatus] =
implicit s: Session byCommitStatues(userName, repositoryName, sha).list
): List[CommitStatus] =
byCommitStatus(userName, repositoryName, sha).list
def getRecentStatusContexts(userName: String, repositoryName: String, time: java.util.Date)( def getRecentStatuesContexts(userName: String, repositoryName: String, time: java.util.Date)(
implicit s: Session implicit s: Session
): List[String] = ): List[String] =
CommitStatuses CommitStatuses
@@ -82,15 +68,15 @@ trait CommitStatusService {
.map(_._1) .map(_._1)
.list .list
def getCommitStatusesWithCreator(userName: String, repositoryName: String, sha: String)( def getCommitStatuesWithCreator(userName: String, repositoryName: String, sha: String)(
implicit s: Session implicit s: Session
): List[(CommitStatus, Account)] = ): List[(CommitStatus, Account)] =
byCommitStatus(userName, repositoryName, sha) byCommitStatues(userName, repositoryName, sha)
.join(Accounts) .join(Accounts)
.filter { case (t, a) => t.creator === a.userName } .filter { case (t, a) => t.creator === a.userName }
.list .list
protected def byCommitStatus(userName: String, repositoryName: String, sha: String)(implicit s: Session) = protected def byCommitStatues(userName: String, repositoryName: String, sha: String)(implicit s: Session) =
CommitStatuses.filter(t => t.byCommit(userName, repositoryName, sha)).sortBy(_.updatedDate desc) CommitStatuses.filter(t => t.byCommit(userName, repositoryName, sha)).sortBy(_.updatedDate desc)
} }

View File

@@ -8,7 +8,6 @@ import gitbucket.core.model.{Account, CommitComment}
import gitbucket.core.model.Profile._ import gitbucket.core.model.Profile._
import gitbucket.core.model.Profile.profile.blockingApi._ import gitbucket.core.model.Profile.profile.blockingApi._
import gitbucket.core.model.Profile.dateColumnType import gitbucket.core.model.Profile.dateColumnType
import gitbucket.core.model.activity.{CommitCommentInfo, PullRequestCommentInfo}
import gitbucket.core.plugin.PluginRegistry import gitbucket.core.plugin.PluginRegistry
import gitbucket.core.service.RepositoryService.RepositoryInfo import gitbucket.core.service.RepositoryService.RepositoryInfo
import gitbucket.core.util.Directory._ import gitbucket.core.util.Directory._
@@ -81,9 +80,13 @@ trait CommitsService {
case Some(issueId) => case Some(issueId) =>
getPullRequest(repository.owner, repository.name, issueId).foreach { getPullRequest(repository.owner, repository.name, issueId).foreach {
case (issue, pullRequest) => case (issue, pullRequest) =>
val pullRequestCommentInfo = recordCommentPullRequestActivity(
PullRequestCommentInfo(repository.owner, repository.name, loginAccount.userName, content, issueId) repository.owner,
recordActivity(pullRequestCommentInfo) repository.name,
loginAccount.userName,
issueId,
content
)
PluginRegistry().getPullRequestHooks.foreach(_.addedComment(commentId, content, issue, repository)) PluginRegistry().getPullRequestHooks.foreach(_.addedComment(commentId, content, issue, repository))
callPullRequestReviewCommentWebHook( callPullRequestReviewCommentWebHook(
"create", "create",
@@ -96,9 +99,13 @@ trait CommitsService {
) )
} }
case None => case None =>
val commitCommentInfo = recordCommentCommitActivity(
CommitCommentInfo(repository.owner, repository.name, loginAccount.userName, content, commitId) repository.owner,
recordActivity(commitCommentInfo) repository.name,
loginAccount.userName,
commitId,
content
)
} }
commentId commentId

View File

@@ -1,18 +1,9 @@
package gitbucket.core.service package gitbucket.core.service
import gitbucket.core.controller.Context import gitbucket.core.controller.Context
import gitbucket.core.model.{Issue, IssueComment} import gitbucket.core.model.Issue
import gitbucket.core.model.Profile.profile.blockingApi._ import gitbucket.core.model.Profile.profile.blockingApi._
import gitbucket.core.model.activity.{ import gitbucket.core.plugin.PluginRegistry
CloseIssueInfo,
ClosePullRequestInfo,
IssueCommentInfo,
PullRequestCommentInfo,
ReopenIssueInfo,
ReopenPullRequestInfo
}
import gitbucket.core.plugin.{IssueHook, PluginRegistry}
import gitbucket.core.service.RepositoryService.RepositoryInfo
import gitbucket.core.util.SyntaxSugars._ import gitbucket.core.util.SyntaxSugars._
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits._
@@ -38,31 +29,25 @@ trait HandleCommentService {
case (owner, name) => case (owner, name) =>
val userName = loginAccount.userName val userName = loginAccount.userName
actionOpt.collect { val (action, actionActivity) = actionOpt
case "close" if !issue.closed =>
updateClosed(owner, name, issue.issueId, true)
case "reopen" if issue.closed =>
updateClosed(owner, name, issue.issueId, false)
}
val (action, _) = actionOpt
.collect { .collect {
case "close" if !issue.closed => case "close" if (!issue.closed) =>
val info = if (issue.isPullRequest) { true ->
ClosePullRequestInfo(owner, name, userName, issue.issueId, issue.title) (Some("close") -> Some(
} else { if (issue.isPullRequest) recordClosePullRequestActivity _
CloseIssueInfo(owner, name, userName, issue.issueId, issue.title) else recordCloseIssueActivity _
} ))
recordActivity(info) case "reopen" if (issue.closed) =>
Some("close") -> info false ->
case "reopen" if issue.closed => (Some("reopen") -> Some(
val info = if (issue.isPullRequest) { if (issue.isPullRequest) recordReopenPullRequestActivity _
ReopenPullRequestInfo(owner, name, userName, issue.issueId, issue.title) else recordReopenIssueActivity _
} else { ))
ReopenIssueInfo(owner, name, userName, issue.issueId, issue.title) }
} .map {
recordActivity(info) case (closed, t) =>
Some("reopen") -> info updateClosed(owner, name, issue.issueId, closed)
t
} }
.getOrElse(None -> None) .getOrElse(None -> None)
@@ -83,12 +68,8 @@ trait HandleCommentService {
) )
// record comment activity // record comment activity
val commentInfo = if (issue.isPullRequest) { if (issue.isPullRequest) recordCommentPullRequestActivity(owner, name, userName, issue.issueId, content)
PullRequestCommentInfo(owner, name, userName, content, issue.issueId) else recordCommentIssueActivity(owner, name, userName, issue.issueId, content)
} else {
IssueCommentInfo(owner, name, userName, content, issue.issueId)
}
recordActivity(commentInfo)
// extract references and create refer comment // extract references and create refer comment
createReferComment(owner, name, issue, content, loginAccount) createReferComment(owner, name, issue, content, loginAccount)
@@ -96,6 +77,10 @@ trait HandleCommentService {
id id
} }
actionActivity.foreach { f =>
f(owner, name, userName, issue.issueId, issue.title)
}
// call web hooks // call web hooks
action match { action match {
case None => case None =>
@@ -136,59 +121,4 @@ trait HandleCommentService {
} }
} }
def deleteCommentByApi(repoInfo: RepositoryInfo, comment: IssueComment, issue: Issue)(
implicit context: Context,
s: Session
): Option[IssueComment] = context.loginAccount.flatMap { _ =>
comment.action match {
case "comment" =>
val deleteResult = deleteComment(repoInfo.owner, repoInfo.name, comment.issueId, comment.commentId)
val registry = PluginRegistry()
val hooks: Seq[IssueHook] = if (issue.isPullRequest) registry.getPullRequestHooks else registry.getIssueHooks
hooks.foreach(_.deletedComment(comment.commentId, issue, repoInfo))
deleteResult match {
case n if n > 0 => Some(comment)
case _ => None
}
case _ => None
}
}
def updateCommentByApi(
repository: RepositoryService.RepositoryInfo,
issue: Issue,
commentId: String,
content: Option[String]
)(implicit context: Context, s: Session): Option[(Issue, Int)] = {
context.loginAccount.flatMap { loginAccount =>
defining(repository.owner, repository.name) {
case (owner, name) =>
val userName = loginAccount.userName
content match {
case Some(content) =>
// Update comment
val _commentId = Some(updateComment(issue.issueId, commentId.toInt, content))
// Record comment activity
val commentInfo = if (issue.isPullRequest) {
PullRequestCommentInfo(owner, name, userName, content, issue.issueId)
} else {
IssueCommentInfo(owner, name, userName, content, issue.issueId)
}
recordActivity(commentInfo)
// extract references and create refer comment
createReferComment(owner, name, issue, content, loginAccount)
// call web hooks
commentId foreach (callIssueCommentWebHook(repository, issue, _, loginAccount, context.settings))
// call hooks
if (issue.isPullRequest)
PluginRegistry().getPullRequestHooks
.foreach(_.updatedComment(commentId.toInt, content, issue, repository))
else
PluginRegistry().getIssueHooks.foreach(_.updatedComment(commentId.toInt, content, issue, repository))
_commentId.map(issue -> _)
case _ => None
}
}
}
}
} }

View File

@@ -3,7 +3,6 @@ package gitbucket.core.service
import gitbucket.core.controller.Context import gitbucket.core.controller.Context
import gitbucket.core.model.{Account, Issue} import gitbucket.core.model.{Account, Issue}
import gitbucket.core.model.Profile.profile.blockingApi._ import gitbucket.core.model.Profile.profile.blockingApi._
import gitbucket.core.model.activity.CreateIssueInfo
import gitbucket.core.plugin.PluginRegistry import gitbucket.core.plugin.PluginRegistry
import gitbucket.core.service.RepositoryService.RepositoryInfo import gitbucket.core.service.RepositoryService.RepositoryInfo
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits._
@@ -52,8 +51,7 @@ trait IssueCreationService {
} }
// record activity // record activity
val createIssueInfo = CreateIssueInfo(owner, name, userName, issueId, title) recordCreateIssueActivity(owner, name, userName, issueId, title)
recordActivity(createIssueInfo)
// extract references and create refer comment // extract references and create refer comment
createReferComment(owner, name, issue, title + " " + body.getOrElse(""), loginAccount) createReferComment(owner, name, issue, title + " " + body.getOrElse(""), loginAccount)
@@ -74,13 +72,6 @@ trait IssueCreationService {
hasDeveloperRole(repository.owner, repository.name, context.loginAccount) hasDeveloperRole(repository.owner, repository.name, context.loginAccount)
} }
/**
* Tests whether an logged-in user can manage issues comment.
*/
protected def isIssueCommentManageable(repository: RepositoryInfo)(implicit context: Context, s: Session): Boolean = {
hasOwnerRole(repository.owner, repository.name, context.loginAccount)
}
/** /**
* Tests whether an logged-in user can post issues. * Tests whether an logged-in user can post issues.
*/ */

View File

@@ -31,9 +31,6 @@ trait IssuesService {
Issues filter (_.byPrimaryKey(owner, repository, issueId.toInt)) firstOption Issues filter (_.byPrimaryKey(owner, repository, issueId.toInt)) firstOption
else None else None
def getOpenIssues(owner: String, repository: String)(implicit s: Session): List[Issue] =
Issues filter (_.byRepository(owner, repository)) filterNot (_.closed) sortBy (_.issueId desc) list
def getComments(owner: String, repository: String, issueId: Int)(implicit s: Session) = def getComments(owner: String, repository: String, issueId: Int)(implicit s: Session) =
IssueComments filter (_.byIssue(owner, repository, issueId)) sortBy (_.commentId asc) list IssueComments filter (_.byIssue(owner, repository, issueId)) sortBy (_.commentId asc) list
@@ -71,20 +68,6 @@ trait IssuesService {
else None else None
} }
def getCommentForApi(owner: String, repository: String, commentId: Int)(
implicit s: Session
): Option[(IssueComment, Account, Issue)] =
IssueComments
.filter(_.byRepository(owner, repository))
.filter(_.commentId === commentId)
.filter(_.action inSetBind Set("comment", "close_comment", "reopen_comment"))
.join(Accounts)
.on { case t1 ~ t2 => t1.commentedUserName === t2.userName }
.join(Issues)
.on { case t1 ~ t2 ~ t3 => t3.byIssue(t1.userName, t1.repositoryName, t1.issueId) }
.map { case t1 ~ t2 ~ t3 => (t1, t2, t3) }
.firstOption
def getIssueLabels(owner: String, repository: String, issueId: Int)(implicit s: Session): List[Label] = { def getIssueLabels(owner: String, repository: String, issueId: Int)(implicit s: Session): List[Label] = {
IssueLabels IssueLabels
.join(Labels) .join(Labels)
@@ -107,14 +90,14 @@ trait IssuesService {
* Returns the count of the search result against issues. * Returns the count of the search result against issues.
* *
* @param condition the search condition * @param condition the search condition
* @param searchOption if true then counts only pull request, false then counts both of issue and pull request. * @param onlyPullRequest if true then counts only pull request, false then counts both of issue and pull request.
* @param repos Tuple of the repository owner and the repository name * @param repos Tuple of the repository owner and the repository name
* @return the count of the search result * @return the count of the search result
*/ */
def countIssue(condition: IssueSearchCondition, searchOption: IssueSearchOption, repos: (String, String)*)( def countIssue(condition: IssueSearchCondition, onlyPullRequest: Boolean, repos: (String, String)*)(
implicit s: Session implicit s: Session
): Int = { ): Int = {
Query(searchIssueQuery(repos, condition, searchOption).length).first Query(searchIssueQuery(repos, condition, onlyPullRequest).length).first
} }
/** /**
@@ -132,7 +115,7 @@ trait IssuesService {
filterUser: Map[String, String] filterUser: Map[String, String]
)(implicit s: Session): Map[String, Int] = { )(implicit s: Session): Map[String, Int] = {
searchIssueQuery(Seq(owner -> repository), condition.copy(labels = Set.empty), IssueSearchOption.Issues) searchIssueQuery(Seq(owner -> repository), condition.copy(labels = Set.empty), false)
.join(IssueLabels) .join(IssueLabels)
.on { .on {
case t1 ~ t2 => case t1 ~ t2 =>
@@ -170,7 +153,7 @@ trait IssuesService {
filterUser: Map[String, String] filterUser: Map[String, String]
)(implicit s: Session): Map[String, Int] = { )(implicit s: Session): Map[String, Int] = {
searchIssueQuery(Seq(owner -> repository), condition.copy(labels = Set.empty), IssueSearchOption.Issues) searchIssueQuery(Seq(owner -> repository), condition.copy(labels = Set.empty), false)
.join(Priorities) .join(Priorities)
.on { .on {
case t1 ~ t2 => case t1 ~ t2 =>
@@ -188,11 +171,42 @@ trait IssuesService {
.toMap .toMap
} }
def getCommitStatues(userName: String, repositoryName: String, issueId: Int)(
implicit s: Session
): Option[CommitStatusInfo] = {
val status = PullRequests
.filter { pr =>
pr.userName === userName.bind && pr.repositoryName === repositoryName.bind && pr.issueId === issueId.bind
}
.join(CommitStatuses)
.on {
case pr ~ cs =>
pr.userName === cs.userName && pr.repositoryName === cs.repositoryName && pr.commitIdTo === cs.commitId
}
.list
if (status.nonEmpty) {
val (_, cs) = status.head
Some(
CommitStatusInfo(
count = status.length,
successCount = status.count(_._2.state == CommitState.SUCCESS),
context = (if (status.length == 1) Some(cs.context) else None),
state = (if (status.length == 1) Some(cs.state) else None),
targetUrl = (if (status.length == 1) cs.targetUrl else None),
description = (if (status.length == 1) cs.description else None)
)
)
} else {
None
}
}
/** /**
* Returns the search result against issues. * Returns the search result against issues.
* *
* @param condition the search condition * @param condition the search condition
* @param searchOption if true then returns only pull requests, false then returns only issues. * @param pullRequest if true then returns only pull requests, false then returns only issues.
* @param offset the offset for pagination * @param offset the offset for pagination
* @param limit the limit for pagination * @param limit the limit for pagination
* @param repos Tuple of the repository owner and the repository name * @param repos Tuple of the repository owner and the repository name
@@ -200,13 +214,13 @@ trait IssuesService {
*/ */
def searchIssue( def searchIssue(
condition: IssueSearchCondition, condition: IssueSearchCondition,
searchOption: IssueSearchOption, pullRequest: Boolean,
offset: Int, offset: Int,
limit: Int, limit: Int,
repos: (String, String)* repos: (String, String)*
)(implicit s: Session): List[IssueInfo] = { )(implicit s: Session): List[IssueInfo] = {
// get issues and comment count and labels // get issues and comment count and labels
val result = searchIssueQueryBase(condition, searchOption, offset, limit, repos) val result = searchIssueQueryBase(condition, pullRequest, offset, limit, repos)
.joinLeft(IssueLabels) .joinLeft(IssueLabels)
.on { case t1 ~ t2 ~ i ~ t3 => t1.byIssue(t3.userName, t3.repositoryName, t3.issueId) } .on { case t1 ~ t2 ~ i ~ t3 => t1.byIssue(t3.userName, t3.repositoryName, t3.issueId) }
.joinLeft(Labels) .joinLeft(Labels)
@@ -215,11 +229,9 @@ trait IssuesService {
.on { case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 => t1.byMilestone(t5.userName, t5.repositoryName, t5.milestoneId) } .on { case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 => t1.byMilestone(t5.userName, t5.repositoryName, t5.milestoneId) }
.joinLeft(Priorities) .joinLeft(Priorities)
.on { case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 ~ t6 => t1.byPriority(t6.userName, t6.repositoryName, t6.priorityId) } .on { case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 ~ t6 => t1.byPriority(t6.userName, t6.repositoryName, t6.priorityId) }
.joinLeft(PullRequests) .sortBy { case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 ~ t6 => i asc }
.on { case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 ~ t6 ~ t7 => t1.byIssue(t7.userName, t7.repositoryName, t7.issueId) }
.sortBy { case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 ~ t6 ~ t7 => i asc }
.map { .map {
case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 ~ t6 ~ t7 => case t1 ~ t2 ~ i ~ t3 ~ t4 ~ t5 ~ t6 =>
( (
t1, t1,
t2.commentCount, t2.commentCount,
@@ -227,8 +239,7 @@ trait IssuesService {
t4.map(_.labelName), t4.map(_.labelName),
t4.map(_.color), t4.map(_.color),
t5.map(_.title), t5.map(_.title),
t6.map(_.priorityName), t6.map(_.priorityName)
t7.map(_.commitIdTo)
) )
} }
.list .list
@@ -238,7 +249,7 @@ trait IssuesService {
result.map { issues => result.map { issues =>
issues.head match { issues.head match {
case (issue, commentCount, _, _, _, milestone, priority, commitId) => case (issue, commentCount, _, _, _, milestone, priority) =>
IssueInfo( IssueInfo(
issue, issue,
issues.flatMap { t => issues.flatMap { t =>
@@ -247,7 +258,7 @@ trait IssuesService {
milestone, milestone,
priority, priority,
commentCount, commentCount,
commitId getCommitStatues(issue.userName, issue.repositoryName, issue.issueId)
) )
} }
} toList } toList
@@ -260,7 +271,7 @@ trait IssuesService {
implicit s: Session implicit s: Session
): List[(Issue, Account, Option[Account])] = { ): List[(Issue, Account, Option[Account])] = {
// get issues and comment count and labels // get issues and comment count and labels
searchIssueQueryBase(condition, IssueSearchOption.Issues, offset, limit, repos) searchIssueQueryBase(condition, false, offset, limit, repos)
.join(Accounts) .join(Accounts)
.on { case t1 ~ t2 ~ i ~ t3 => t3.userName === t1.openedUserName } .on { case t1 ~ t2 ~ i ~ t3 => t3.userName === t1.openedUserName }
.joinLeft(Accounts) .joinLeft(Accounts)
@@ -277,7 +288,7 @@ trait IssuesService {
implicit s: Session implicit s: Session
): List[(Issue, Account, Int, PullRequest, Repository, Account, Option[Account])] = { ): List[(Issue, Account, Int, PullRequest, Repository, Account, Option[Account])] = {
// get issues and comment count and labels // get issues and comment count and labels
searchIssueQueryBase(condition, IssueSearchOption.PullRequests, offset, limit, repos) searchIssueQueryBase(condition, true, offset, limit, repos)
.join(PullRequests) .join(PullRequests)
.on { case t1 ~ t2 ~ i ~ t3 => t3.byPrimaryKey(t1.userName, t1.repositoryName, t1.issueId) } .on { case t1 ~ t2 ~ i ~ t3 => t3.byPrimaryKey(t1.userName, t1.repositoryName, t1.issueId) }
.join(Repositories) .join(Repositories)
@@ -295,12 +306,12 @@ trait IssuesService {
private def searchIssueQueryBase( private def searchIssueQueryBase(
condition: IssueSearchCondition, condition: IssueSearchCondition,
searchOption: IssueSearchOption, pullRequest: Boolean,
offset: Int, offset: Int,
limit: Int, limit: Int,
repos: Seq[(String, String)] repos: Seq[(String, String)]
)(implicit s: Session) = )(implicit s: Session) =
searchIssueQuery(repos, condition, searchOption) searchIssueQuery(repos, condition, pullRequest)
.join(IssueOutline) .join(IssueOutline)
.on { (t1, t2) => .on { (t1, t2) =>
t1.byIssue(t2.userName, t2.repositoryName, t2.issueId) t1.byIssue(t2.userName, t2.repositoryName, t2.issueId)
@@ -338,11 +349,7 @@ trait IssuesService {
/** /**
* Assembles query for conditional issue searching. * Assembles query for conditional issue searching.
*/ */
private def searchIssueQuery( private def searchIssueQuery(repos: Seq[(String, String)], condition: IssueSearchCondition, pullRequest: Boolean)(
repos: Seq[(String, String)],
condition: IssueSearchCondition,
searchOption: IssueSearchOption
)(
implicit s: Session implicit s: Session
) = ) =
Issues filter { t1 => Issues filter { t1 =>
@@ -351,64 +358,45 @@ trait IssuesService {
} else { } else {
((t1.userName ++ "/" ++ t1.repositoryName) inSetBind (repos.map { case (owner, repo) => s"$owner/$repo" })) ((t1.userName ++ "/" ++ t1.repositoryName) inSetBind (repos.map { case (owner, repo) => s"$owner/$repo" }))
}) && }) &&
(t1.closed === (condition.state == "closed").bind) (t1.closed === (condition.state == "closed").bind) &&
.&&(t1.milestoneId.? isEmpty, condition.milestone == Some(None)) (t1.milestoneId.? isEmpty, condition.milestone == Some(None)) &&
.&&(t1.priorityId.? isEmpty, condition.priority == Some(None)) (t1.priorityId.? isEmpty, condition.priority == Some(None)) &&
.&&(t1.assignedUserName.? isEmpty, condition.assigned == Some(None)) (t1.assignedUserName.? isEmpty, condition.assigned == Some(None)) &&
.&&(t1.openedUserName === condition.author.get.bind, condition.author.isDefined) && (t1.openedUserName === condition.author.get.bind, condition.author.isDefined) &&
(searchOption match { (t1.pullRequest === pullRequest.bind) &&
case IssueSearchOption.Issues => t1.pullRequest === false
case IssueSearchOption.PullRequests => t1.pullRequest === true
case IssueSearchOption.Both => t1.pullRequest === false || t1.pullRequest === true
})
// Milestone filter // Milestone filter
.&&( (Milestones filter { t2 =>
Milestones filter { t2 => (t2.byPrimaryKey(t1.userName, t1.repositoryName, t1.milestoneId)) &&
(t2.byPrimaryKey(t1.userName, t1.repositoryName, t1.milestoneId)) && (t2.title === condition.milestone.get.get.bind)
(t2.title === condition.milestone.get.get.bind) } exists, condition.milestone.flatten.isDefined) &&
} exists, // Priority filter
condition.milestone.flatten.isDefined (Priorities filter { t2 =>
) (t2.byPrimaryKey(t1.userName, t1.repositoryName, t1.priorityId)) &&
// Priority filter (t2.priorityName === condition.priority.get.get.bind)
.&&( } exists, condition.priority.flatten.isDefined) &&
Priorities filter { t2 => // Assignee filter
(t2.byPrimaryKey(t1.userName, t1.repositoryName, t1.priorityId)) && (t1.assignedUserName === condition.assigned.get.get.bind, condition.assigned.flatten.isDefined) &&
(t2.priorityName === condition.priority.get.get.bind) // Label filter
} exists, (IssueLabels filter { t2 =>
condition.priority.flatten.isDefined (t2.byIssue(t1.userName, t1.repositoryName, t1.issueId)) &&
) (t2.labelId in
// Assignee filter (Labels filter { t3 =>
.&&(t1.assignedUserName === condition.assigned.get.get.bind, condition.assigned.flatten.isDefined) (t3.byRepository(t1.userName, t1.repositoryName)) &&
// Label filter (t3.labelName inSetBind condition.labels)
.&&( } map (_.labelId)))
IssueLabels filter { t2 => } exists, condition.labels.nonEmpty) &&
(t2.byIssue(t1.userName, t1.repositoryName, t1.issueId)) && // Visibility filter
(t2.labelId in (Repositories filter { t2 =>
(Labels filter { t3 => (t2.byRepository(t1.userName, t1.repositoryName)) &&
(t3.byRepository(t1.userName, t1.repositoryName)) && (t2.isPrivate === (condition.visibility == Some("private")).bind)
(t3.labelName inSetBind condition.labels) } exists, condition.visibility.nonEmpty) &&
} map (_.labelId))) // Organization (group) filter
} exists, (t1.userName inSetBind condition.groups, condition.groups.nonEmpty) &&
condition.labels.nonEmpty // Mentioned filter
) ((t1.openedUserName === condition.mentioned.get.bind) || t1.assignedUserName === condition.mentioned.get.bind ||
// Visibility filter (IssueComments filter { t2 =>
.&&( (t2.byIssue(t1.userName, t1.repositoryName, t1.issueId)) && (t2.commentedUserName === condition.mentioned.get.bind)
Repositories filter { t2 => } exists), condition.mentioned.isDefined)
(t2.byRepository(t1.userName, t1.repositoryName)) &&
(t2.isPrivate === (condition.visibility == Some("private")).bind)
} exists,
condition.visibility.nonEmpty
)
// Organization (group) filter
.&&(t1.userName inSetBind condition.groups, condition.groups.nonEmpty)
// Mentioned filter
.&&(
(t1.openedUserName === condition.mentioned.get.bind) || t1.assignedUserName === condition.mentioned.get.bind ||
(IssueComments filter { t2 =>
(t2.byIssue(t1.userName, t1.repositoryName, t1.issueId)) && (t2.commentedUserName === condition.mentioned.get.bind)
} exists),
condition.mentioned.isDefined
)
} }
def insertIssue( def insertIssue(
@@ -647,10 +635,7 @@ trait IssuesService {
IssueComments.filter(_.byPrimaryKey(commentId)).map(t => (t.content, t.updatedDate)).update(content, currentDate) IssueComments.filter(_.byPrimaryKey(commentId)).map(t => (t.content, t.updatedDate)).update(content, currentDate)
} }
def deleteComment(owner: String, repository: String, issueId: Int, commentId: Int)( def deleteComment(issueId: Int, commentId: Int)(implicit s: Session): Int = {
implicit context: Context,
s: Session
): Int = {
Issues.filter(_.issueId === issueId.bind).map(_.updatedDate).update(currentDate) Issues.filter(_.issueId === issueId.bind).map(_.updatedDate).update(currentDate)
IssueComments.filter(_.byPrimaryKey(commentId)).firstOption match { IssueComments.filter(_.byPrimaryKey(commentId)).firstOption match {
case Some(c) if c.action == "reopen_comment" => case Some(c) if c.action == "reopen_comment" =>
@@ -659,16 +644,6 @@ trait IssuesService {
IssueComments.filter(_.byPrimaryKey(commentId)).map(t => (t.content, t.action)).update("Close", "close") IssueComments.filter(_.byPrimaryKey(commentId)).map(t => (t.content, t.action)).update("Close", "close")
case Some(_) => case Some(_) =>
IssueComments.filter(_.byPrimaryKey(commentId)).delete IssueComments.filter(_.byPrimaryKey(commentId)).delete
IssueComments insert IssueComment(
userName = owner,
repositoryName = repository,
issueId = issueId,
action = "delete_comment",
commentedUserName = context.loginAccount.map(_.userName).getOrElse("Unknown user"),
content = s"",
registeredDate = currentDate,
updatedDate = currentDate
)
} }
} }
@@ -707,8 +682,8 @@ trait IssuesService {
case (t1, t2) => case (t1, t2) =>
keywords keywords
.map { keyword => .map { keyword =>
(t1.title.toLowerCase.like(s"%${likeEncode(keyword)}%", '^')) || (t1.title.toLowerCase like (s"%${likeEncode(keyword)}%", '^')) ||
(t1.content.toLowerCase.like(s"%${likeEncode(keyword)}%", '^')) (t1.content.toLowerCase like (s"%${likeEncode(keyword)}%", '^'))
} }
.reduceLeft(_ && _) .reduceLeft(_ && _)
} }
@@ -735,7 +710,7 @@ trait IssuesService {
t2.pullRequest === pullRequest.bind && t2.pullRequest === pullRequest.bind &&
keywords keywords
.map { query => .map { query =>
t1.content.toLowerCase.like(s"%${likeEncode(query)}%", '^') t1.content.toLowerCase like (s"%${likeEncode(query)}%", '^')
} }
.reduceLeft(_ && _) .reduceLeft(_ && _)
} }
@@ -935,46 +910,27 @@ object IssuesService {
param(request, "groups").map(_.split(",").toSet).getOrElse(Set.empty) param(request, "groups").map(_.split(",").toSet).getOrElse(Set.empty)
) )
def apply(request: HttpServletRequest, milestone: String): IssueSearchCondition =
IssueSearchCondition(
param(request, "labels").map(_.split(",").toSet).getOrElse(Set.empty),
Some(Some(milestone)),
param(request, "priority").map {
case "none" => None
case x => Some(x)
},
param(request, "author"),
param(request, "assigned").map {
case "none" => None
case x => Some(x)
},
param(request, "mentioned"),
param(request, "state", Seq("open", "closed")).getOrElse("open"),
param(request, "sort", Seq("created", "comments", "updated", "priority")).getOrElse("created"),
param(request, "direction", Seq("asc", "desc")).getOrElse("desc"),
param(request, "visibility"),
param(request, "groups").map(_.split(",").toSet).getOrElse(Set.empty)
)
def page(request: HttpServletRequest) = { def page(request: HttpServletRequest) = {
PaginationHelper.page(param(request, "page")) PaginationHelper.page(param(request, "page"))
} }
} }
case class CommitStatusInfo(
count: Int,
successCount: Int,
context: Option[String],
state: Option[CommitState],
targetUrl: Option[String],
description: Option[String]
)
case class IssueInfo( case class IssueInfo(
issue: Issue, issue: Issue,
labels: List[Label], labels: List[Label],
milestone: Option[String], milestone: Option[String],
priority: Option[String], priority: Option[String],
commentCount: Int, commentCount: Int,
commitId: Option[String] status: Option[CommitStatusInfo]
) )
}
sealed trait IssueSearchOption
object IssueSearchOption {
case object Issues extends IssueSearchOption
case object PullRequests extends IssueSearchOption
case object Both extends IssueSearchOption
} }

Some files were not shown because too many files have changed in this diff Show More