Compare commits

..

567 Commits

Author SHA1 Message Date
Scala Steward
c8a4798f86 Update oauth2-oidc-sdk to 11.30 2025-10-16 20:05:41 +09:00
xuwei-k
6b8e9e8892 add JDK 25 CI 2025-10-13 17:57:35 +09:00
xuwei-k
9ab9363d0b fix warnings 2025-10-13 17:56:55 +09:00
Scala Steward
1edb18a147 Update sbt, sbt-dependency-tree, ... to 1.11.7 2025-10-06 06:59:52 +09:00
Scala Steward
d8b4bf3033 Update thumbnailator to 0.4.21 2025-10-03 06:32:36 +09:00
Scala Steward
6597c4490b Update logback-classic to 1.5.19 2025-10-01 06:22:46 +09:00
Scala Steward
daaf1696ad Update oauth2-oidc-sdk to 11.29.2 2025-09-30 21:44:47 +09:00
Scala Steward
53a1ca7874 Update scala-library to 2.13.17 2025-09-30 18:43:32 +09:00
Scala Steward
f045fa4c6a Update h2 to 2.4.240 2025-09-25 06:58:37 +09:00
Scala Steward
53a7c5adf8 Update sbt-license-report to 1.9.0 2025-09-25 04:25:34 +09:00
takezoe
b142eca9a5 Update change log for 4.44.0 2025-09-23 09:56:19 +09:00
Naoki Takezoe
ba753a373b Fix release doc (#3844) 2025-09-23 09:46:49 +09:00
Naoki Takezoe
95ceca75a4 Update change log for 4.44.0 (#3845) 2025-09-23 09:46:35 +09:00
Naoki Takezoe
f16cc117a9 Release 4.44.0 (#3842) 2025-09-23 09:02:24 +09:00
Naoki Takezoe
af66f8f746 Fix Repository Contents Upload API for nested path (#3843) 2025-09-23 09:01:30 +09:00
Scala Steward
d9cc57e8e0 Update oauth2-oidc-sdk to 11.29.1 2025-09-23 06:51:06 +09:00
Scala Steward
72b6dad3a2 Update mockito-core to 5.20.0 2025-09-21 06:10:09 +09:00
Scala Steward
18f396b4a2 Update postgresql to 42.7.8 2025-09-19 13:46:36 +09:00
Scala Steward
9f3fde8de2 Update tika-core to 3.2.3 2025-09-17 07:14:08 +09:00
scala-steward-bot
dfd6f80b63 Update scalafmt-core to 3.9.10 (#3838) 2025-09-16 22:15:57 +09:00
Scala Steward
119d91210c Update typesafe:config to 1.4.5 2025-09-11 17:29:06 +09:00
Scala Steward
75ef30ee03 Update sbt-license-report to 1.8.0 2025-09-11 06:32:21 +09:00
Scala Steward
d1cf9dd600 Update scala3-library to 3.7.3 2025-09-09 06:18:29 +09:00
Scala Steward
9c9fea908c Update sbt, sbt-dependency-tree, ... to 1.11.6 2025-09-07 08:51:05 +09:00
kenji yoshida
1145c4d0f6 update build.sbt. prepare sbt 2 2025-09-05 20:03:01 +09:00
Scala Steward
d847fc6e0f Update github-api to 1.330 2025-09-05 05:36:45 +09:00
Scala Steward
bb9585f7a6 Update oauth2-oidc-sdk to 11.28 2025-08-31 06:58:03 +09:00
Scala Steward
e91411fa45 Update sbt, sbt-dependency-tree, ... to 1.11.5 2025-08-26 08:30:43 +09:00
dependabot[bot]
adbc065a6f Bump actions/setup-java from 4 to 5
Bumps [actions/setup-java](https://github.com/actions/setup-java) from 4 to 5.
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-25 17:59:37 +09:00
Scala Steward
862283b729 Update apache-sshd to 2.16.0 2025-08-24 06:44:33 +09:00
Naoki Takezoe
217df7012c Fix Wiki branch resolution in blob endpoint (#3826) 2025-08-23 17:11:11 +09:00
Naoki Takezoe
e672d41e77 Fix downloading branch that contains slash (#3825) 2025-08-23 16:49:18 +09:00
Scala Steward
d975700bd4 Update HikariCP to 7.0.2 2025-08-20 03:24:57 +09:00
dependabot[bot]
f65e41561a Bump actions/checkout from 4 to 5
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 5.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-18 17:51:52 +09:00
Scala Steward
dab4f33ed9 Update oauth2-oidc-sdk to 11.27.1 2025-08-16 12:30:05 +09:00
Scala Steward
5ff45ef5ae Update jetty-http, jetty-io, jetty-runner, ... to 10.0.26 2025-08-16 06:35:41 +09:00
Scala Steward
af7c622647 Update mockito-core to 5.19.0 2025-08-15 18:58:23 +09:00
Scala Steward
f7027e57df Update HikariCP to 7.0.1 2025-08-09 12:01:30 +09:00
Scala Steward
6a4719469d Update tika-core to 3.2.2 2025-08-08 19:03:31 +09:00
Scala Steward
6ebc865ba5 Update sbt, sbt-dependency-tree, ... to 1.11.4 2025-08-05 07:04:59 +09:00
Naoki Takezoe
0c1e8b932b Reject direct push to branch if branch protection is enabled (#3791) 2025-08-03 11:58:28 +09:00
scala-steward-bot
fda67a32e2 Update scalafmt-core to 3.9.9 (#3815) 2025-08-03 01:31:06 +09:00
Scala Steward
14d7e9ee90 Update commons-net to 3.12.0 2025-08-02 06:56:11 +09:00
Naoki Takezoe
b7b7322cce Fix branch selector in repository viewer (#3813) 2025-08-01 02:33:05 +09:00
Scala Steward
5eb44398d0 Update oauth2-oidc-sdk to 11.27 2025-07-30 10:09:17 +09:00
Scala Steward
be7bb255c3 Update commons-compress to 1.28.0 2025-07-30 09:54:03 +09:00
Scala Steward
cb9522d416 Update github-api to 1.329 2025-07-30 06:56:36 +09:00
Scala Steward
d80afb473b Update scala3-library to 3.7.2 2025-07-30 06:49:49 +09:00
Scala Steward
607d85c661 Update HikariCP to 7.0.0 2025-07-29 05:59:20 +09:00
Scala Steward
a5fab3bc96 Update oauth2-oidc-sdk to 11.26.1 2025-07-25 18:55:51 +09:00
Scala Steward
eb403ada58 Update HikariCP to 6.3.2 2025-07-24 17:34:00 +09:00
Naoki Takezoe
911c102f39 Improve logging in initialization process (#3804) 2025-07-21 12:10:56 +09:00
Naoki Takezoe
bf23e854f8 Exclude sshd-spring-sftp (#3803) 2025-07-21 11:58:22 +09:00
Scala Steward
52427c0a1e Update HikariCP to 6.3.1 2025-07-21 06:15:54 +09:00
Naoki Takezoe
d8e5ac585c Disable blank issue (#3801) 2025-07-20 10:52:14 +09:00
Naoki Takezoe
2fbeef73b0 Move issue_template.yml to .github directory (#3800) 2025-07-20 10:42:25 +09:00
Naoki Takezoe
15e39572dd Update issue template (#3799) 2025-07-20 10:33:40 +09:00
Scala Steward
9eac4f42c5 Update commons-io to 2.20.0 2025-07-20 06:04:11 +09:00
scala-steward-bot
01d18bb5c3 Update typesafe:config to 1.4.4 (#3796) 2025-07-13 08:52:18 +09:00
scala-steward-bot
00258e9125 Update tika-core to 3.2.1 (#3795) 2025-07-13 08:52:02 +09:00
Scala Steward
046b337337 Update java-diff-utils to 4.16 2025-07-08 17:02:18 +09:00
Naoki Takezoe
46cc7b6fd3 Update H2 database migration guide (#3793) 2025-07-06 21:24:28 +09:00
Scala Steward
59344b4f05 Update sbt, sbt-dependency-tree, ... to 1.11.3 2025-07-06 07:11:59 +09:00
Naoki Takezoe
c4d8af02b2 Fix wrong redirect after sign-in when user-defined CSS is used (#3789) 2025-07-05 12:08:20 +09:00
Scala Steward
a10bc3687a Update sbt-twirl, twirl-api to 2.0.9 2025-07-01 06:36:38 +09:00
Scala Steward
b0d21dee42 Update sbt-scalafmt to 2.5.5 2025-06-30 17:35:49 +09:00
Naoki Takezoe
13ea0e7507 Update release procedure doc (#3785) 2025-06-29 13:57:16 +09:00
takezoe
d66fdaede5 Update README and CHANGELOG 2025-06-29 13:33:29 +09:00
takezoe
d6217d89eb Update README and CHANGELOG 2025-06-29 13:01:17 +09:00
Naoki Takezoe
c99ff1cf0f Release 4.43.0 (#3784) 2025-06-29 13:00:21 +09:00
Scala Steward
001b9ae2ae Update mysql, postgresql to 1.21.3 2025-06-29 07:49:01 +09:00
Scala Steward
f63493f1c0 Update scalafmt-core to 3.9.8 2025-06-29 07:48:45 +09:00
Naoki Takezoe
c9095722f8 Redirect from sign-in page to top page if already authenticated (#3781) 2025-06-22 21:23:15 +09:00
Naoki Takezoe
b9d2efa582 UI: Fix bottom margin of branch deletion box in pull request (#3780) 2025-06-21 17:23:23 +09:00
Naoki Takezoe
9c2e09020a Fix warnings in service test cases (#3779) 2025-06-21 17:01:54 +09:00
Naoki Takezoe
1ffcf8c1e9 Bump h2 to 2.3.232 (#3746) 2025-06-21 13:03:48 +09:00
Naoki Takezoe
0124091840 Fix the issue template (#3778) 2025-06-21 12:59:50 +09:00
Naoki Takezoe
2a28a7b35b Migrate templates for issue request (#3777) 2025-06-21 12:48:06 +09:00
Scala Steward
2a68ffc8dc Update mysql, postgresql to 1.21.2 2025-06-19 20:42:59 +09:00
Scala Steward
6b47c49cdd Update oauth2-oidc-sdk to 11.26 2025-06-18 05:15:40 +09:00
Scala Steward
b634967776 Update postgresql to 42.7.7 2025-06-11 19:52:43 +09:00
Scala Steward
172bed760d Update sbt, sbt-dependency-tree, ... to 1.11.2 2025-06-08 07:42:23 +09:00
Naoki Takezoe
1b7eb69083 Migrate from OSSRH to Central Portal (#3770) 2025-06-08 00:17:29 +09:00
scala-steward-bot
185c01db99 Update sbt, sbt-dependency-tree, ... to 1.11.1 (#3767) 2025-06-07 23:56:26 +09:00
Scala Steward
ab548d8c25 Update scala3-library to 3.7.1 2025-06-03 05:24:59 +09:00
kenji yoshida
983975620b Merge pull request #3766 from scala-steward-bot/update/scalafmt-core-3.9.7
Update scalafmt-core to 3.9.7
2025-06-01 08:27:00 +09:00
Scala Steward
b512b08256 Add 'Reformat with scalafmt 3.9.7' to .git-blame-ignore-revs 2025-05-30 14:45:26 +00:00
Scala Steward
a54fb4960f Reformat with scalafmt 3.9.7
Executed command: scalafmt --non-interactive
2025-05-30 14:45:26 +00:00
Scala Steward
93de53d717 Update scalafmt-core to 3.9.7 2025-05-30 14:45:19 +00:00
Scala Steward
f262c0a9eb Update mysql, postgresql to 1.21.1 2025-05-30 17:44:07 +09:00
Scala Steward
e5d15569df Update postgresql to 42.7.6 2025-05-28 20:41:26 +09:00
Scala Steward
369b08eae3 Update tika-core to 3.2.0 2025-05-27 06:49:24 +09:00
Scala Steward
8e6fcb022b Update sbt, sbt-dependency-tree, ... to 1.11.0 2025-05-24 15:52:45 +09:00
Scala Steward
456b1f6571 Update org.eclipse.jgit.archive, ... to 6.10.1.202505221210-r 2025-05-23 11:28:36 +09:00
Scala Steward
6e459ad225 Update oauth2-oidc-sdk to 11.25 2025-05-23 05:51:55 +09:00
Scala Steward
cece4c1c7d Update mockito-core to 5.18.0 2025-05-21 06:47:39 +09:00
Scala Steward
42e7a9fa9f Update ec4j-core to 1.1.1 2025-05-18 06:45:58 +09:00
Scala Steward
f9510aba8e Update scalafmt-core to 3.9.6 2025-05-15 11:47:04 +09:00
Scala Steward
8a7d719025 Update oauth2-oidc-sdk to 11.24 2025-05-07 06:53:07 +09:00
Scala Steward
1293a21450 Update scala3-library to 3.7.0 2025-05-06 06:34:29 +09:00
scala-steward-bot
65dd597ab7 Update scalatra-forms-javax, ... to 3.1.2 (#3752) 2025-05-03 18:42:17 +09:00
Scala Steward
e145b5151e Update scalafmt-core to 3.9.5 2025-04-30 06:38:32 +09:00
Scala Steward
b9684c277b Update mysql, postgresql to 1.21.0 2025-04-24 11:47:26 +09:00
Scala Steward
4accb77533 Update commons-io to 2.19.0 2025-04-12 14:10:18 +09:00
Scala Steward
9eef961025 Update mockito-core to 5.17.0 2025-04-05 07:10:28 +09:00
Scala Steward
546b40cdd1 Update HikariCP to 6.3.0 2025-03-25 06:24:54 +09:00
Scala Steward
274a08c14c Update logback-classic to 1.5.18 2025-03-20 06:35:18 +09:00
Scala Steward
eed4b51189 Update jetty-http, jetty-io, jetty-runner, ... to 10.0.25 2025-03-18 08:00:26 +09:00
Scala Steward
5c2f84367b Update sbt, sbt-dependency-tree, ... to 1.10.11 2025-03-17 19:21:55 +09:00
Scala Steward
d5b625e43f Update mockito-core to 5.16.1 2025-03-16 07:10:45 +09:00
scala-steward-bot
27f9e3dec9 Update scalafmt-core to 3.9.4 (#3737) 2025-03-15 12:53:33 +09:00
Scala Steward
00ef4db9a7 Update testcontainers-scala to 0.43.0 2025-03-12 19:32:26 +09:00
Scala Steward
bf4f814389 Update scalafmt-core to 3.9.3 2025-03-07 19:13:22 +09:00
Scala Steward
23e45afd7f Update scala3-library to 3.6.4 2025-03-07 19:12:26 +09:00
Scala Steward
bfb02eef62 Update mysql, postgresql to 1.20.6 2025-03-05 06:57:03 +09:00
Scala Steward
c129aae73a Update sbt, sbt-dependency-tree, ... to 1.10.10 2025-03-04 16:01:56 +09:00
Scala Steward
a955856cef Update sbt, sbt-dependency-tree, ... to 1.10.9 2025-03-04 07:19:27 +09:00
Scala Steward
a43a3fa55c Update sbt, sbt-dependency-tree, ... to 1.10.8 2025-03-03 20:03:42 +09:00
Scala Steward
a6254ab955 Update mockito-core to 5.16.0 2025-03-03 20:03:13 +09:00
scala-steward-bot
b505c3dc12 Update scalafmt-core to 3.9.2 (#3726) 2025-03-01 15:35:33 +09:00
mnival
9d69b9e980 Add bearer authentification (#3725)
Co-authored-by: mnival <extern.nival_michael@allianz.com>
2025-02-28 09:30:45 +09:00
Scala Steward
44b2320644 Update scalafmt-core to 3.9.1 2025-02-26 19:12:54 +09:00
Scala Steward
8fb9643ea5 Update oauth2-oidc-sdk to 11.23.1 2025-02-26 19:12:31 +09:00
Scala Steward
10ea988298 Update logback-classic to 1.5.17 2025-02-26 04:00:17 +09:00
Scala Steward
7896945519 Update apache-sshd to 2.15.0 2025-02-25 03:36:14 +09:00
Scala Steward
210342d2bc Update sbt-twirl, twirl-api to 2.0.8 2025-02-24 06:45:06 +09:00
Scala Steward
fdacea858b Update sbt-scoverage to 2.3.1 2025-02-21 06:19:43 +09:00
Scala Steward
6825028d37 Update mysql, postgresql to 1.20.5 2025-02-20 07:54:32 +09:00
Scala Steward
2089882d41 Update oauth2-oidc-sdk to 11.23 2025-02-18 06:52:15 +09:00
Scala Steward
8e1d938155 Update github-api to 1.327 2025-02-13 23:30:25 +09:00
Scala Steward
39eb4cef04 Update oauth2-oidc-sdk to 11.22.2 2025-02-13 13:33:44 +09:00
Scala Steward
d4e3adafa6 Update oauth2-oidc-sdk to 11.22.1 2025-02-09 17:45:03 +09:00
Scala Steward
a7b8326499 Update oauth2-oidc-sdk to 11.22 2025-02-07 04:19:11 +09:00
Naoki Takezoe
249f8738d3 Update command to run GitBucket in debug.md (#3708) 2025-02-05 22:52:49 +09:00
Scala Steward
fefe6ef74f Update scalafmt-core to 3.8.6 2025-02-01 17:22:55 +09:00
Scala Steward
9ca6cd1d90 Update tika-core to 3.1.0 2025-02-01 07:18:24 +09:00
Scala Steward
bff7b7c460 Update oauth2-oidc-sdk to 11.21.3 2025-02-01 07:18:01 +09:00
Scala Steward
cfff79758b Update oauth2-oidc-sdk to 11.21.2 2025-01-22 03:38:05 +09:00
Scala Steward
ded8ceb2c6 Update sbt-assembly to 2.3.1 2025-01-21 08:50:51 +09:00
Scala Steward
c502ebfc16 Update testcontainers-scala to 0.41.8 2025-01-21 08:13:08 +09:00
Naoki Takezoe
d3268265cf Release GitBucket 4.42.1 (#3699) 2025-01-20 10:16:31 +09:00
Naoki Takezoe
5eaf59eebb Remove unnecessary setup code for SSL in LDAPUtil (#3697) 2025-01-20 09:41:33 +09:00
Scala Steward
d6d47aa977 Update scalafmt-core to 3.8.5 2025-01-20 07:19:49 +09:00
Naoki Takezoe
dc052e05ce Setup sbt explicitly in GitHub Actions (#3698) 2025-01-20 02:29:51 +09:00
Scala Steward
afb145ca7c Update sbt-scalafmt to 2.5.4 2025-01-17 07:26:49 +09:00
Scala Steward
a8beed33e0 Update scala3-library to 3.6.3 2025-01-16 20:00:10 +09:00
Scala Steward
488599dba5 Update postgresql to 42.7.5 2025-01-15 05:45:47 +09:00
Scala Steward
ef0d08a917 Update sbt-scoverage to 2.3.0 2025-01-14 07:42:48 +09:00
Scala Steward
9fa0d03c99 Update sbt-scalafmt to 2.5.3 2025-01-14 07:36:37 +09:00
kenji yoshida
15b6c5952b update build status badge in README 2025-01-11 16:06:43 +09:00
Scala Steward
cb75e9d312 Update oauth2-oidc-sdk to 11.21 2025-01-11 07:04:42 +09:00
Scala Steward
d542ee3528 Update scala-library to 2.13.16 2025-01-11 06:55:05 +09:00
Scala Steward
608a59cbfd Update oauth2-oidc-sdk to 11.20.2 2025-01-10 07:15:27 +09:00
Scala Steward
768e3a5c91 Update logback-classic to 1.5.16 2025-01-06 10:02:28 +09:00
Naoki Takezoe
f1fc794c0c Fix warnings in JGitUtil (#3683) 2025-01-05 14:35:50 +09:00
kenji yoshida
4cf924bee0 remove unused imports 2025-01-03 12:05:40 +09:00
kenji yoshida
8164efc720 remove unused import 2025-01-03 10:25:25 +09:00
Scala Steward
580a627d9d Update mockito-core to 5.15.2 2025-01-03 07:59:55 +09:00
Naoki Takezoe
1701916209 Update README and CHANGELOG for Java 17 requirement (#3679) 2025-01-02 02:17:06 +09:00
takezoe
811b2bff70 Update README.md and CHANGELOG.md 2024-12-30 05:52:06 +09:00
takezoe
9de9dd8940 Update README.md 2024-12-30 04:59:26 +09:00
Naoki Takezoe
572f83327f Release GitBucket 4.42.0 (#3678) 2024-12-30 04:56:10 +09:00
Naoki Takezoe
2afb37823b Increase max branch name length 100 -> 255 (#3676) 2024-12-30 04:36:24 +09:00
Naoki Takezoe
edc9720a88 Fix warnings in controllers (#3674) 2024-12-25 03:02:45 +09:00
Scala Steward
defc0fa041 Update sbt, sbt-dependency-tree, ... to 1.10.7 2024-12-23 12:51:33 +09:00
Naoki Takezoe
c14b3c5576 Fix warnings in ControllerBase (#3673) 2024-12-22 13:23:31 +09:00
Naoki Takezoe
10fc04cbc9 Return 400 error for invalid query string (#3672) 2024-12-22 12:48:39 +09:00
Scala Steward
67563a8805 Update logback-classic to 1.5.15 2024-12-22 07:13:09 +09:00
Naoki Takezoe
743bdab79b Fix wrong redirection when non-existent branch name is given as default branch (#3669) 2024-12-21 22:13:27 +09:00
Naoki Takezoe
a5a2e4732d Stabilize AccountServiceSpec (#3670) 2024-12-21 18:50:34 +09:00
Scala Steward
3a0cd5df62 Update scalatra-forms-javax, ... to 3.1.1 2024-12-21 14:43:49 +09:00
Naoki Takezoe
ad9a0afc9b Show branch errors when creating pull request (#3667) 2024-12-21 11:54:47 +09:00
Scala Steward
d2fc7a0642 Update logback-classic to 1.5.14 2024-12-20 13:44:08 +09:00
Naoki Takezoe
b1d4a18c9b Fix ref and ssh_url in WebHook payloads (#3656) 2024-12-19 15:19:42 +09:00
Scala Steward
fdfd8ec9b2 Update testcontainers-scala to 0.41.5 2024-12-19 13:31:22 +09:00
Scala Steward
396156c4e3 Update logback-classic to 1.5.13 2024-12-19 06:09:02 +09:00
Naoki Takezoe
8168580d60 Restore the original response of list-repository-tags API (#3662) 2024-12-16 00:27:56 +09:00
Naoki Takezoe
2abdd233e7 Apply user-defined CSS after plugins' JavaScript runs (#3661) 2024-12-15 12:30:07 +09:00
Naoki Takezoe
ef95ce99d2 Suppress Liquibase logs (#3660) 2024-12-14 14:49:38 +09:00
Scala Steward
3a6b2f6f4e Update sbt-pgp to 2.3.1 2024-12-11 07:09:14 +09:00
ziggystar
92304ac8c6 fix: make some methods call JGitUtil.getCommitLog with ObjectId instead of strings (#3653)
Co-authored-by: Thomas Geier <thomas.geier@solidat.de>
2024-12-10 08:25:38 +09:00
Scala Steward
a2242a3cb7 Update scala3-library to 3.6.2 2024-12-10 06:10:34 +09:00
ziggystar
64e8167fcb fix: calculate diffs between commits based on common ancestor; works for force push (#3647)
fixes #3476

Co-authored-by: Thomas Geier <thomas.geier@solidat.de>
2024-12-05 08:51:03 +09:00
Naoki Takezoe
06b93293a6 Update build.md about testing on Jetty from sbt (#3650) 2024-12-01 13:10:20 +09:00
Naoki Takezoe
3dcc0aee3c Use ContainerPlugin instead of JettyPlugin to run newer version of Jetty (#3649) 2024-12-01 12:49:14 +09:00
Scala Steward
c009a39dd7 Update sbt, sbt-dependency-tree, ... to 1.10.6 2024-12-01 07:45:38 +09:00
Scala Steward
b27e8ebb7e Update java-diff-utils to 4.15 2024-11-25 13:39:54 +09:00
Scala Steward
a690d43491 Update mysql, postgresql to 1.20.4 2024-11-21 06:36:53 +09:00
Scala Steward
86bfb68a0c Update commons-io to 2.18.0 2024-11-20 08:13:46 +09:00
Scala Steward
9469801d3d Update HikariCP to 6.2.1 2024-11-19 06:59:42 +09:00
Scala Steward
757a8399c1 Update HikariCP to 6.2.0 2024-11-17 15:49:50 +09:00
Scala Steward
ed00e613c3 Update json4s-jackson to 4.1.0-M8 2024-11-07 16:30:48 +09:00
Scala Steward
6e341116c1 Update HikariCP to 6.1.0 2024-11-06 13:54:48 +09:00
Scala Steward
9ccc2d0f97 Update sbt, sbt-dependency-tree, ... to 1.10.5 2024-11-04 09:16:17 +09:00
Scala Steward
72742306a0 Update sbt, sbt-dependency-tree, ... to 1.10.4 2024-10-30 09:50:35 +09:00
Scala Steward
47c6d61661 Update logback-classic to 1.5.12 2024-10-27 07:13:39 +09:00
Scala Steward
cfc444bcd2 Update sbt-license-report to 1.7.0 2024-10-24 05:24:38 +09:00
Scala Steward
a1f65258ea Update mysql, postgresql to 1.20.3 2024-10-23 10:22:47 +09:00
Scala Steward
5e3b97cf85 Update sbt, sbt-dependency-tree, ... to 1.10.3 2024-10-20 13:31:53 +09:00
kenji yoshida
209e1967d6 fail-fast: false 2024-10-20 13:23:32 +09:00
Scala Steward
4437a4e7a6 Update tika-core to 3.0.0 2024-10-20 09:31:44 +09:00
Scala Steward
e4d92bb494 Update scala3-library to 3.6.1 2024-10-19 19:27:45 +09:00
Scala Steward
d942c8f48a Update scala3-library to 3.6.0 2024-10-19 04:02:52 +09:00
Scala Steward
3a798e152f Update sbt-scoverage to 2.2.2 2024-10-19 04:02:29 +09:00
Scala Steward
91b862970f Update scala3-library to 3.5.2 2024-10-17 04:15:47 +09:00
Scala Steward
2d199e22e7 Update logback-classic to 1.5.11 2024-10-16 08:39:26 +09:00
Scala Steward
757da408d1 Update mockito-core to 5.14.2 2024-10-16 08:01:30 +09:00
Scala Steward
309d6e8b57 Update ec4j-core to 1.1.0 2024-10-13 07:55:33 +09:00
Scala Steward
ec0395a7f3 Update logback-classic to 1.5.10 2024-10-13 06:59:03 +09:00
Scala Steward
7cb4958ca0 Update oauth2-oidc-sdk to 11.20.1 2024-10-11 08:23:57 +09:00
Scala Steward
2d1c917a2c Update logback-classic to 1.5.9 2024-10-09 06:29:26 +09:00
Scala Steward
27dd5120dd Update sbt-assembly to 2.3.0 2024-10-07 12:21:35 +09:00
Scala Steward
9e0f8992c5 Update sbt-pgp to 2.3.0 2024-10-05 21:41:34 +09:00
Scala Steward
5f87a28da6 Update apache-sshd to 2.14.0 2024-10-03 08:07:53 +09:00
Scala Steward
25d5d5eee5 Update mysql, postgresql to 1.20.2 2024-10-01 12:31:19 +09:00
Scala Steward
ec9472b7cc Update mockito-core to 5.14.1 2024-10-01 06:58:02 +09:00
Scala Steward
b967fb93a7 Update oauth2-oidc-sdk to 11.20 2024-09-30 06:14:20 +09:00
Scala Steward
9d1bf3035b Update mockito-core to 5.14.0 2024-09-28 06:34:32 +09:00
Scala Steward
d6cedc2171 Update sbt-scoverage to 2.2.1 2024-09-26 06:39:12 +09:00
Scala Steward
8d8c78966a Update HikariCP to 6.0.0 2024-09-24 06:05:20 +09:00
Scala Steward
cbe1c1c9f6 Update ec4j-core to 1.0.0 2024-09-21 07:48:45 +09:00
Scala Steward
bf946960a7 Update scala-library to 2.13.15 2024-09-21 06:53:23 +09:00
Scala Steward
9677735542 Update github-api to 1.326 2024-09-19 09:30:09 +09:00
Scala Steward
e06c8fe5da Update scala3-library to 3.5.1 2024-09-19 09:27:27 +09:00
Scala Steward
d4ee6c9063 Update commons-io to 2.17.0 2024-09-19 09:26:32 +09:00
Scala Steward
1d0f079bd2 Update sbt, sbt-dependency-tree to 1.10.2 2024-09-16 20:05:08 +09:00
Scala Steward
7cc6972d83 Update github-api to 1.325 2024-09-14 06:52:27 +09:00
kenji yoshida
177da92b39 fix warning 2024-09-11 11:47:54 +09:00
Scala Steward
e1f433573b Update json4s-jackson to 4.1.0-M7 2024-09-10 08:08:14 +09:00
Scala Steward
cd958d7681 Update logback-classic to 1.5.8 2024-09-07 07:12:32 +09:00
Scala Steward
9c8e77f472 Update oauth2-oidc-sdk to 11.19.1 2024-09-06 10:46:21 +09:00
Scala Steward
bf7d3a8f0b Update sbt-scoverage to 2.2.0 2024-09-06 10:46:09 +09:00
Scala Steward
934e17666d Update jetty-http, jetty-io, jetty-security, ... to 10.0.24 2024-09-04 08:20:28 +09:00
Scala Steward
b20c4b3d7d Update oauth2-oidc-sdk to 11.19 2024-08-29 17:39:44 +09:00
Scala Steward
7c4e8b54d0 Update mockito-core to 5.13.0 2024-08-28 08:15:20 +09:00
Scala Steward
1e3794674b Update postgresql to 42.7.4 2024-08-23 10:01:12 +09:00
Scala Steward
5d5706451d Update sbt-scoverage to 2.1.1 2024-08-22 06:28:14 +09:00
Scala Steward
76e8d01846 Update oauth2-oidc-sdk to 11.18 2024-08-21 09:14:20 +09:00
Scala Steward
75e2883f61 Update jetty-http, jetty-io, jetty-security, ... to 10.0.23 2024-08-21 09:14:01 +09:00
Scala Steward
7e7cc1d4c7 Update commons-compress to 1.27.1 2024-08-21 06:25:57 +09:00
Scala Steward
d7623e8b7a Update github-api to 1.324 2024-08-19 19:45:55 +09:00
Scala Steward
7dd1470cd4 Update oauth2-oidc-sdk to 11.17 2024-08-19 06:15:01 +09:00
Scala Steward
9fb8d6fc66 Update oauth2-oidc-sdk to 11.16.1 2024-08-17 06:15:36 +09:00
Scala Steward
4f1869817c Update oauth2-oidc-sdk to 11.16 2024-08-16 07:07:35 +09:00
Scala Steward
6be269c388 Update logback-classic to 1.5.7 2024-08-16 06:32:52 +09:00
Scala Steward
af857853cb Update oauth2-oidc-sdk to 11.15 2024-08-14 07:45:41 +09:00
Scala Steward
1a664c2b6a Update scala3-library to 3.5.0 2024-08-13 06:17:59 +09:00
scala-steward-bot
1feb33fc19 Update commons-compress to 1.27.0 (#3574)
* Update commons-compress to 1.27.0

* Update build.sbt

---------

Co-authored-by: kenji yoshida <6b656e6a69@gmail.com>
2024-08-11 11:32:52 +09:00
Scala Steward
4fc1d9c3b6 Update oauth2-oidc-sdk to 11.14 2024-08-02 05:26:05 +09:00
Scala Steward
7eb77908d4 Update apache-sshd to 2.13.2 2024-08-01 05:58:36 +09:00
Scala Steward
54f9d01c42 Update mysql, postgresql to 1.20.1 2024-08-01 05:57:46 +09:00
Scala Steward
08154af7b1 Update scalafmt-core to 3.8.3 2024-07-27 07:57:11 +09:00
Scala Steward
e7ab376a34 Update mysql, postgresql to 1.20.0 2024-07-18 05:58:08 +09:00
Scala Steward
a680398c54 Update sbt, sbt-dependency-tree to 1.10.1 2024-07-08 08:49:28 +09:00
Scala Steward
6acf1e68ca Update jetty-http, jetty-io, jetty-security, ... to 10.0.22 2024-07-05 16:12:38 +09:00
Scala Steward
fc35e7b83d Update sbt-scoverage to 2.1.0 2024-07-04 02:31:10 +09:00
Scala Steward
1ae6fc7e9e Update github-api to 1.323 2024-07-02 06:12:05 +09:00
scala-steward-bot
884f63e6f4 Update scalatra-forms-javax, ... to 3.1.0 (#3545)
Co-authored-by: kenji yoshida <6b656e6a69@gmail.com>
2024-06-28 09:19:57 +09:00
Scala Steward
4d3e34af8b Update sbt-twirl, twirl-api to 2.0.7 2024-06-28 09:01:31 +09:00
Scala Steward
54426bb456 Update oauth2-oidc-sdk to 11.13 2024-06-26 13:23:20 +09:00
Scala Steward
c86b72bf6b Update oauth2-oidc-sdk to 11.12.1 2024-06-25 19:18:52 +09:00
Scala Steward
e6a5911a39 Update apache-sshd to 2.13.1 2024-06-25 07:08:53 +09:00
Scala Steward
6ea77fa73e Update github-api to 1.322 2024-06-21 19:09:21 +09:00
Scala Steward
32d0b94a7a Update apache-sshd to 2.13.0 2024-06-20 03:37:43 +09:00
scala-steward-bot
4f770adb35 Update sbt-twirl, twirl-api to 2.0.6 (#3553) 2024-06-17 21:32:10 +09:00
kenji yoshida
361f92a08d -Xsource:3-cross 2024-06-17 15:16:42 +09:00
xuwei-k
c2068f58e7 prepare Scala 3 2024-06-17 15:07:53 +09:00
kenji yoshida
67dd604469 Merge pull request #3549 from scala-steward-bot/update/scalafmt-core-3.8.2
Update scalafmt-core to 3.8.2
2024-06-17 11:23:22 +09:00
Scala Steward
d1a2c23cf3 Update json4s-jackson to 4.1.0-M6 2024-06-17 01:26:00 +09:00
Scala Steward
262500508c Add 'Reformat with scalafmt 3.8.2' to .git-blame-ignore-revs 2024-06-14 16:40:55 +00:00
Scala Steward
f1360f44c6 Reformat with scalafmt 3.8.2
Executed command: scalafmt --non-interactive
2024-06-14 16:40:55 +00:00
Scala Steward
1c818f890a Update scalafmt-core to 3.8.2 2024-06-14 16:40:45 +00:00
Scala Steward
16f146b660 Update testcontainers-scala to 0.41.4 2024-06-14 06:12:35 +09:00
Scala Steward
6166eaf0c7 Update org.eclipse.jgit.archive, ... to 6.10.0.202406032230-r 2024-06-13 09:43:42 +09:00
Scala Steward
ad4312cedb Update commons-net to 3.11.1 2024-06-11 05:46:46 +09:00
Scala Steward
15083a5aac Update commons-net to 3.11.0 2024-06-01 07:26:44 +09:00
Scala Steward
9ae420c553 Update commons-compress to 1.26.2 2024-05-25 05:08:23 +09:00
takezoe
4115ea4ab6 Update ChangeLog of 4.41.0 2024-05-18 17:26:23 +09:00
takezoe
024ac313ae Update ChangeLog of 4.41.0 2024-05-18 17:12:06 +09:00
takezoe
598f289311 Update README 2024-05-18 16:16:02 +09:00
Naoki Takezoe
447288db9d Release GitBucket 4.41.0 (#3540) 2024-05-18 16:14:52 +09:00
Naoki Takezoe
2b8c2a5c06 Upgrade json4s to 4.1.0-M5 (#3537) 2024-05-18 11:54:13 +09:00
scala-steward-bot
6fd3a73268 Update mariadb-java-client to 2.7.12 (#3491) 2024-05-18 11:53:10 +09:00
scala-steward-bot
4536e42949 Update sbt-twirl, twirl-api to 2.0.5 (#3525) 2024-05-18 11:52:46 +09:00
scala-steward-bot
fc575388f1 Update solidbase to 1.1.0 (#3538) 2024-05-18 11:48:23 +09:00
Scala Steward
1044d1cc32 Update oauth2-oidc-sdk to 11.12 2024-05-17 21:02:48 +09:00
Scala Steward
253eabf2f2 Update oauth2-oidc-sdk to 11.11 2024-05-17 03:57:20 +09:00
Scala Steward
8219d57b92 Update jetty-http, jetty-io, jetty-security, ... to 10.0.21 2024-05-17 03:53:28 +09:00
Brian Wignall
89381d3314 Fix typo (#3533) 2024-05-15 23:42:48 +09:00
Scala Steward
2e1037e107 Update scala3-library to 3.4.2 2024-05-14 07:00:27 +09:00
Scala Steward
0a77c71278 Update mockito-core to 5.12.0 2024-05-12 07:32:14 +09:00
Scala Steward
275101d11b Update mysql, postgresql to 1.19.8 2024-05-09 11:05:59 +09:00
Scala Steward
bfd7f3b2bc Update sbt, sbt-dependency-tree to 1.10.0 2024-05-06 13:36:40 +09:00
Scala Steward
21fcedf000 Update sbt-scoverage to 2.0.12 2024-05-03 05:13:46 +09:00
Scala Steward
d963070f73 Update scala-library to 2.13.14 2024-04-30 08:05:56 +09:00
Scala Steward
8174c89f9e Update sbt-twirl, twirl-api to 1.6.6 2024-04-26 09:03:01 +09:00
Scala Steward
5bdc74f0a6 Update logback-classic to 1.5.6 2024-04-18 06:50:24 +09:00
Scala Steward
b259386b67 Update logback-classic to 1.5.4 2024-04-10 06:28:37 +09:00
Scala Steward
984b52e7ec Update commons-io to 2.16.1 2024-04-09 08:25:08 +09:00
Scala Steward
d36ef805f6 Update tika-core to 2.9.2 2024-04-03 03:54:23 +09:00
Scala Steward
02bdbd281b Update scalafmt-core to 3.8.1 2024-03-30 07:45:17 +09:00
Scala Steward
b3cca9ea91 Update commons-io to 2.16.0 2024-03-29 09:12:29 +09:00
Scala Steward
7409c08122 Update scala3-library to 3.4.1 2024-03-28 03:43:57 +09:00
Scala Steward
339b54cd4b Update github-api to 1.321 2024-03-21 12:37:31 +09:00
Scala Steward
1bbdf4917b Update github-api to 1.320 2024-03-19 07:43:04 +09:00
Scala Steward
465ed988a9 Update postgresql to 42.7.3 2024-03-15 06:35:07 +09:00
Scala Steward
d5d7fe47d5 Update sbt-assembly to 2.2.0 2024-03-14 15:51:43 +09:00
Scala Steward
81d14dfaf2 Update commons-compress to 1.26.1 2024-03-09 12:29:36 +09:00
Scala Steward
302da30746 Update org.eclipse.jgit.archive, ... to 6.9.0.202403050737-r 2024-03-09 02:29:35 +09:00
Scala Steward
e9110aac80 Update logback-classic to 1.5.3 2024-03-06 06:10:57 +09:00
Scala Steward
6d104bd585 Update mysql, postgresql to 1.19.7 2024-03-06 06:06:10 +09:00
Scala Steward
7c47462de8 Update logback-classic to 1.5.2 2024-03-03 08:22:05 +09:00
Scala Steward
cc8b83cbc5 Update mockito-core to 5.11.0 2024-03-01 20:12:40 +09:00
Scala Steward
07decd00a0 Update logback-classic to 1.5.1 2024-02-29 09:53:45 +09:00
Scala Steward
7c3e82f4dd Update sbt-twirl, twirl-api to 1.6.5 2024-02-28 00:39:35 +09:00
Scala Steward
95c31dd7b7 Update oauth2-oidc-sdk to 11.10.1 2024-02-27 03:36:40 +09:00
Scala Steward
5ea905e3a2 Update sbt-scoverage to 2.0.11 2024-02-24 19:42:15 +09:00
Scala Steward
e40d1f42c7 Update sbt, sbt-dependency-tree to 1.9.9 2024-02-23 15:42:31 +09:00
Scala Steward
aa00351606 Update scala-library to 2.13.13 2024-02-23 08:09:31 +09:00
Scala Steward
6311a1f146 Update mysql, postgresql to 1.19.6 2024-02-22 18:59:34 +09:00
Scala Steward
1517e1f580 Update github-api to 1.319 2024-02-21 22:16:54 +09:00
Scala Steward
833f3584c2 Update postgresql to 42.7.2 2024-02-21 07:05:16 +09:00
Scala Steward
cdc67bffcb Update commons-compress to 1.26.0 2024-02-19 12:01:40 +09:00
Scala Steward
52794aa9ea Update testcontainers-scala to 0.41.3 2024-02-19 01:59:15 +09:00
Scala Steward
9ea3670a56 Update oauth2-oidc-sdk to 11.10 2024-02-18 20:51:42 +09:00
Scala Steward
652ec3e029 Update logback-classic to 1.5.0 2024-02-17 12:19:47 +09:00
Scala Steward
b543bae958 Update apache-sshd to 2.12.1 2024-02-17 07:34:44 +09:00
Scala Steward
4f574cdbcd Update scala3-library to 3.4.0 2024-02-15 06:54:28 +09:00
Scala Steward
29fc2a666b Update sbt-scoverage to 2.0.10 2024-02-15 02:03:44 +09:00
Scala Steward
4498c016a4 Update scala3-library to 3.3.2 2024-02-15 01:51:14 +09:00
Scala Steward
31a1d46175 Update mysql, postgresql to 1.19.5 2024-02-09 04:43:08 +09:00
Scala Steward
e3904ebdfe Update jetty-http, jetty-io, jetty-security, ... to 10.0.20 2024-02-01 03:11:08 +09:00
Scala Steward
6e5ffdf658 Update testcontainers-scala to 0.41.2 2024-01-29 13:46:01 +09:00
Scala Steward
5d0531f00d Update markedj to 1.0.20 2024-01-27 14:06:49 +09:00
Scala Steward
01ea533b97 Update mysql, postgresql to 1.19.4 2024-01-26 04:19:39 +09:00
Scala Steward
86fc492668 Update mockito-core to 5.10.0 2024-01-25 06:51:12 +09:00
dependabot[bot]
3a78356019 Bump actions/cache from 3 to 4
Bumps [actions/cache](https://github.com/actions/cache) from 3 to 4.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-01-22 12:34:32 +09:00
Scala Steward
44f7931ae6 Update apache-sshd to 2.12.0 2024-01-19 13:05:46 +09:00
Scala Steward
7094f99a85 Update mockito-core to 5.9.0 2024-01-15 08:08:49 +09:00
Scala Steward
550c4a6e60 Update java-semver to 0.10.2 2024-01-15 08:08:03 +09:00
Naoki Takezoe
64aeb422c8 Adjust the default branch automatically when cloning external repo (#3466) 2024-01-14 16:17:29 +09:00
Scala Steward
c2265dc44c Update java-semver to 0.10.1 2024-01-13 07:43:41 +09:00
Scala Steward
507085cd56 Update java-semver to 0.10.0 2024-01-11 02:38:03 +09:00
Scala Steward
36ef7ddf94 Update oauth2-oidc-sdk to 11.9.1 2024-01-07 08:10:55 +09:00
Scala Steward
be1fbc8594 Update markedj to 1.0.19 2024-01-07 02:14:14 +09:00
xuwei-k
d73eacfa5d Update scalafmt setting
use new syntax. prepare Scala 3.4
2023-12-30 08:10:39 +09:00
Scala Steward
5d495cfa12 Update oauth2-oidc-sdk to 11.9 2023-12-28 07:32:54 +09:00
dependabot[bot]
acaadff6cb Bump actions/upload-artifact from 3 to 4
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 3 to 4.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-12-24 15:54:17 +09:00
kenji yoshida
e22371e4a5 Update CODEOWNERS 2023-12-24 15:48:07 +09:00
Scala Steward
81c426b112 Update commons-email to 1.6.0 2023-12-23 08:45:55 +09:00
Scala Steward
1481872ddb Update jetty-http, jetty-io, jetty-security, ... to 10.0.19 2023-12-20 07:44:56 +09:00
Scala Steward
523da8afb9 Update sbt, sbt-dependency-tree to 1.9.8 2023-12-17 11:10:19 +09:00
Scala Steward
828dcb7173 Update oauth2-oidc-sdk to 11.8 2023-12-17 08:14:44 +09:00
Scala Steward
eaf7bfb78d Update oauth2-oidc-sdk to 11.7.1 2023-12-08 19:49:02 +09:00
scala-steward-bot
cbcf5ce4b6 Update HikariCP to 5.1.0 (#3413) 2023-12-08 08:01:24 +09:00
Scala Steward
36dce286b5 Update sbt-twirl, twirl-api to 1.6.4 2023-12-08 08:00:56 +09:00
Scala Steward
8ffe75786e Update postgresql to 42.7.1 2023-12-07 08:16:30 +09:00
Scala Steward
5d63bc71aa Update org.eclipse.jgit.archive, ... to 6.8.0.202311291450-r 2023-12-06 10:45:17 +09:00
dependabot[bot]
37f8f7edda Bump actions/setup-java from 3 to 4
Bumps [actions/setup-java](https://github.com/actions/setup-java) from 3 to 4.
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-12-06 10:43:18 +09:00
scala-steward-bot
fd1c85afb2 Update logback-classic to 1.4.14 (#3440) 2023-12-03 21:40:52 +09:00
scala-steward-bot
c08bb6e89f Update mockito-core to 5.8.0 (#3441) 2023-12-03 21:40:35 +09:00
Scala Steward
d25889f6d2 Update json4s-jackson to 4.0.7 2023-12-03 20:03:35 +09:00
ziggystar
dabddf60b1 fix: add GitUtils.findBranchesNoMergeInfo and use it when merge info … (#3436)
* fix: add GitUtils.findBranchesNoMergeInfo and use it when merge info not necessary

* rfr: add some missing override annotations and a return type

---------

Co-authored-by: Thomas Geier <thomas.geier@solidat.de>
2023-11-30 21:01:57 +09:00
Scala Steward
c7ade7ec4d Update commons-io to 2.15.1 2023-11-30 07:43:52 +09:00
scala-steward-bot
9caa73a585 Update logback-classic to 1.4.13 (#3438) 2023-11-29 05:30:27 +09:00
Scala Steward
0ee849c73d Update logback-classic to 1.4.12 2023-11-28 15:51:46 +09:00
Scala Steward
7883d8fd1e Update oauth2-oidc-sdk to 11.7 2023-11-28 15:50:51 +09:00
Naoki Takezoe
783ddfffa3 Make max files and lines limit in showing diff configurable (#3433) 2023-11-26 21:02:40 +09:00
Naoki Takezoe
24b7cade49 Simplify pull request UI (#3417) 2023-11-25 23:48:48 +09:00
Scala Steward
51554d4325 Update github-api to 1.318 2023-11-24 01:53:46 +09:00
Scala Steward
90bcbd212b Update mysql, postgresql to 1.19.3 2023-11-22 03:06:56 +09:00
Naoki Takezoe
4ca3816522 Keyword search for issues and pull requests using search box (#3429) 2023-11-22 01:55:01 +09:00
Scala Steward
fc4819cb29 Update postgresql to 42.7.0 2023-11-21 08:02:24 +09:00
Scala Steward
5291df8e03 Update sbt-assembly to 2.1.5 2023-11-20 17:47:53 +09:00
Scala Steward
5afb0094f6 Update scalafmt-core to 3.7.17 2023-11-17 19:45:20 +09:00
kenji yoshida
e76813cbee remove unnecessary resolvers 2023-11-17 19:39:12 +09:00
kenji yoshida
bc6398ca3b add .git-blame-ignore-revs 2023-11-17 19:29:14 +09:00
xuwei-k
3d5ca44d66 update scalafmt 2023-11-17 19:26:04 +09:00
Scala Steward
8cd7068131 Update sbt-twirl, twirl-api to 1.6.3 2023-11-17 08:13:43 +09:00
xuwei-k
0db23b7f4a commons-compress 1.25.0 2023-11-16 12:07:37 +09:00
Scala Steward
66d9ce328d Update mysql, postgresql to 1.19.2 2023-11-16 04:36:20 +09:00
Naoki Takezoe
36de0b3097 Fix layout of branch selector (#3416) 2023-11-12 22:58:18 +09:00
Scala Steward
4f3cd26cf4 Update oauth2-oidc-sdk to 11.6 2023-11-06 07:35:18 +09:00
Scala Steward
561e1bfec7 Update mockito-core to 5.7.0 2023-11-03 07:25:05 +09:00
Scala Steward
de64206a82 Update jetty-http, jetty-io, jetty-security, ... to 10.0.18 2023-10-31 07:39:16 +09:00
Scala Steward
65ddffde89 Update sbt-assembly to 2.1.4 2023-10-27 17:44:42 +09:00
Scala Steward
1bc6ddc1a3 Update commons-io to 2.15.0 2023-10-26 07:04:36 +09:00
Scala Steward
a404bd0776 Update oauth2-oidc-sdk to 11.5 2023-10-24 07:42:57 +09:00
Scala Steward
ccbdd383ae Update sbt, sbt-dependency-tree to 1.9.7 2023-10-23 07:47:30 +09:00
Naoki Takezoe
acb846e885 Update README.md (#3401) 2023-10-23 02:57:41 +09:00
takezoe
fa23b4c89e Update ChangeLog of GitBucket 4.40.0 2023-10-23 00:09:29 +09:00
Scala Steward
a70e1f53b5 Update sbt-twirl, twirl-api to 1.6.2 2023-10-22 21:04:28 +09:00
Naoki Takezoe
176deb4930 Bump gist plugin to 4.23.0 to support GitBucket 4.40.0 (#3399) 2023-10-22 18:09:00 +09:00
Naoki Takezoe
6e26d090ed Fix executable war for Jetty 10 (#3397) 2023-10-22 17:20:04 +09:00
Naoki Takezoe
070f74e7dc Release GitBucket 4.40.0 (#3396) 2023-10-22 02:26:54 +09:00
Naoki Takezoe
bcd78b3e5b Support custom fields in search condition (#3286) 2023-10-22 02:00:24 +09:00
Scala Steward
be8f45ce49 Update tika-core to 2.9.1 2023-10-21 10:45:17 +09:00
Scala Steward
baa96408a8 Update apache-sshd to 2.11.0 2023-10-20 18:58:23 +09:00
Scala Steward
d2a7548f73 Update github-api to 1.317 2023-10-20 10:53:01 +09:00
Scala Steward
31e3fc64fc Update oauth2-oidc-sdk to 11.4 2023-10-19 07:42:27 +09:00
Scala Steward
01a9883847 Update typesafe:config to 1.4.3 2023-10-17 19:46:41 +09:00
kenji yoshida
3cf2bea01e add JDK 21 test 2023-10-13 08:03:01 +09:00
Scala Steward
7caf11ae83 Update jetty-http, jetty-io, jetty-security, ... to 10.0.17 2023-10-10 14:04:45 +09:00
Scala Steward
b22bc6fef0 Update oauth2-oidc-sdk to 11.2 2023-10-09 18:35:04 +09:00
kenji yoshida
88533c5807 update scala 3 build setting 2023-10-09 10:34:11 +09:00
Scala Steward
53d955f198 Update mockito-core to 5.6.0 2023-10-07 07:52:10 +09:00
Scala Steward
724550ec5f Update commons-net to 3.10.0 2023-10-06 15:26:10 +09:00
Scala Steward
1a63eff8f9 Update oauth2-oidc-sdk to 11.1 2023-10-06 15:25:42 +09:00
Scala Steward
cf1b245229 Update mysql, postgresql to 1.19.1 2023-10-03 08:09:12 +09:00
Scala Steward
c54a76c9b4 Update commons-io to 2.14.0 2023-09-30 08:56:10 +09:00
Scala Steward
1a7213e2f0 Update scalatra-forms-javax, ... to 3.0.0 2023-09-25 08:38:14 +09:00
Naoki Takezoe
a386cda024 Bump to Scalatra 3.0.0-RC1 (#3376) 2023-09-24 10:22:42 +09:00
Scala Steward
f414bb4c79 Update oauth2-oidc-sdk to 11.0 2023-09-21 08:29:55 +09:00
kenji yoshida
6a51c7414a fix warning. avoid deprecated URL constructor 2023-09-20 15:47:09 +09:00
Scala Steward
9718a67a74 Update sbt-assembly to 2.1.3 2023-09-18 20:56:27 +09:00
scala-steward-bot
179f86c904 Update sbt-twirl, twirl-api to 1.6.1 (#3372)
* Update sbt-twirl, twirl-api to 1.6.1

* Revert commit(s) 9cd04872

* Update sbt-twirl, twirl-api to 1.6.1
2023-09-17 23:46:50 +00:00
Scala Steward
e6ae6fc17d Update sbt-assembly to 2.1.2 2023-09-18 07:47:50 +09:00
dependabot[bot]
1f42b52cfd Bump actions/checkout from 3 to 4 (#3366)
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-17 00:00:35 +09:00
scala-steward-bot
cdff342e3d Update sbt-twirl, twirl-api to 1.6.0 (#3369) 2023-09-16 23:59:19 +09:00
Scala Steward
daa8b6acf2 Update sbt, sbt-dependency-tree to 1.9.6 2023-09-16 07:31:13 +09:00
Scala Steward
2ae72c6db4 Update oauth2-oidc-sdk to 10.15 2023-09-15 10:03:01 +09:00
Scala Steward
9e3204d546 Update sbt, sbt-dependency-tree to 1.9.5 2023-09-14 17:45:42 +09:00
kenji yoshida
59e560b8e1 add -Xsource:3 2023-09-11 07:54:58 +09:00
xuwei-k
186269f8ff add explicit type 2023-09-10 20:04:23 +09:00
Scala Steward
e441c40429 Update commons-compress to 1.24.0 2023-09-09 09:05:43 +09:00
Scala Steward
e1fa85848c Update sbt-scoverage to 2.0.9 2023-09-09 08:00:39 +09:00
Scala Steward
8d66348634 Update scala-library to 2.13.12 2023-09-07 07:45:23 +09:00
Scala Steward
f16b7d2c9b Update org.eclipse.jgit.archive, ... to 6.7.0.202309050840-r 2023-09-06 22:25:07 +09:00
Scala Steward
0ae8cc2820 Update scala3-library to 3.3.1 2023-09-06 08:26:29 +09:00
Scala Steward
ca25e7fe90 Update sbt-scalafmt to 2.5.2 2023-09-03 13:33:56 +09:00
Scala Steward
2692e29716 Update org.eclipse.jgit.archive, ... to 6.6.1.202309021850-r 2023-09-03 10:45:43 +09:00
Scala Steward
b71ccfbcc5 Update oauth2-oidc-sdk to 10.14.2 2023-09-02 10:33:01 +09:00
Scala Steward
659a157cb7 Update jetty-http, jetty-io, jetty-security, ... to 10.0.16 2023-08-31 07:47:22 +09:00
Scala Steward
f22fab32cc Update testcontainers-scala to 0.41.0 2023-08-30 07:21:12 +09:00
Scala Steward
631e418733 Update sbt-scalafmt to 2.5.1 2023-08-30 07:20:56 +09:00
Scala Steward
0f57da14e4 Update oauth2-oidc-sdk to 10.14.1 2023-08-30 07:20:40 +09:00
Scala Steward
424790e686 Update tika-core to 2.9.0 2023-08-29 07:37:26 +09:00
Scala Steward
5dc43a7f75 Update sbt, sbt-dependency-tree to 1.9.4 2023-08-25 07:51:17 +09:00
Scala Steward
debb131623 Update mockito-core to 5.5.0 2023-08-22 18:16:15 +09:00
Scala Steward
e3e21e9590 Update github-api to 1.316 2023-08-22 06:57:37 +09:00
Scala Steward
42fa7ea74d Update mysql, postgresql to 1.19.0 2023-08-22 04:59:17 +09:00
Naoki Takezoe
8ada3dde04 Allow to create pull request from default branch of forked repositories (#3339) 2023-08-13 01:48:23 +09:00
xuwei-k
d43a666dfc use mapTo. prepare Scala 3 2023-08-11 10:22:16 +09:00
Naoki Takezoe
5b266229c3 Fix AccountController (#3337) 2023-08-11 03:27:44 +09:00
Naoki Takezoe
d8b0062f2b Show activities of all visible repositories (#3336) 2023-08-11 03:11:51 +09:00
kenji yoshida
7f0859c0a3 update blocking-slick 2023-08-10 07:59:43 +09:00
Scala Steward
38c7fbf589 Update logback-classic to 1.4.11 2023-08-10 07:39:26 +09:00
Scala Steward
41335964b7 Update logback-classic to 1.4.10 2023-08-10 03:13:16 +09:00
Scala Steward
c5464b2099 Update logback-classic to 1.4.9 2023-08-08 06:31:55 +09:00
Scala Steward
dc49b0dace Update oauth2-oidc-sdk to 10.13.2 2023-08-05 10:28:40 +09:00
Scala Steward
365f30b76b Update oauth2-oidc-sdk to 10.13 2023-08-03 06:43:45 +09:00
Scala Steward
ff1bc0fbca Update oauth2-oidc-sdk to 10.12 2023-07-31 20:20:18 +09:00
Scala Steward
41d55372b5 Update sbt-license-report to 1.6.1 2023-07-31 09:52:52 +09:00
Scala Steward
ba8e5fe3cb Update sbt-license-report to 1.6.0 2023-07-30 15:15:42 +09:00
Scala Steward
6e692f70b7 Update sbt, sbt-dependency-tree to 1.9.3 2023-07-25 09:36:29 +09:00
Scala Steward
aab979b78b Update scalatra, scalatra-forms, ... to 3.0.0-M5-javax 2023-07-23 13:26:14 +09:00
scala-steward-bot
9b7856464a Update markedj to 1.0.18 (#3323) 2023-07-22 21:40:27 +09:00
kenji yoshida
903008b417 update blocking-slick 2023-07-11 09:12:15 +09:00
Scala Steward
515cf86e4f Update sbt, sbt-dependency-tree to 1.9.2 2023-07-10 12:21:48 +09:00
Scala Steward
c0b9eb8789 Update oauth2-oidc-sdk to 10.11 2023-07-09 02:31:16 +09:00
Scala Steward
fefbf92f83 Update oauth2-oidc-sdk to 10.10.1 2023-06-30 07:45:44 +09:00
Scala Steward
006fae36c9 Update thumbnailator to 0.4.20 2023-06-29 07:09:36 +09:00
Scala Steward
281f7f37d8 Update sbt, sbt-dependency-tree to 1.9.1 2023-06-26 13:51:18 +09:00
Scala Steward
36c6dd979f Update oauth2-oidc-sdk to 10.9.2 2023-06-23 06:06:28 +09:00
Scala Steward
9f44015003 Update mockito-core to 5.4.0 2023-06-18 19:47:18 +09:00
kenji yoshida
e719533ed9 Update ISSUE_TEMPLATE.md 2023-06-18 12:55:08 +09:00
Scala Steward
773221d65b Update testcontainers-scala to 0.40.17 2023-06-18 07:46:09 +09:00
Scala Steward
6beacb6af3 Update logback-classic to 1.4.8 2023-06-14 07:10:28 +09:00
Scala Steward
f11b92d391 Update org.eclipse.jgit.archive, ... to 6.6.0.202305301015-r 2023-06-13 03:58:06 +09:00
Scala Steward
def222d035 Update commons-io to 2.13.0 2023-06-08 05:36:02 +09:00
Scala Steward
5dee7a9057 Update scalatra, scalatra-forms, ... to 3.0.0-M4 2023-06-08 05:35:20 +09:00
Scala Steward
c20cc1271c Update sbt-scoverage to 2.0.8 2023-06-03 19:48:05 +09:00
Scala Steward
843d429cb2 Update scala-library to 2.13.11 2023-06-03 03:34:17 +09:00
Scala Steward
372e17ea2b Update sbt to 1.9.0 2023-06-02 20:02:47 +09:00
Scala Steward
5490e82411 Update github-api to 1.315 2023-06-01 17:02:45 +09:00
Scala Steward
d30a5d2f92 Update mysql, postgresql to 1.18.3 2023-06-01 07:52:54 +09:00
Scala Steward
ef69763749 Update mysql, postgresql to 1.18.2 2023-05-31 01:06:52 +09:00
Scala Steward
59d1250e36 Update testcontainers-scala to 0.40.16 2023-05-27 07:19:22 +09:00
Scala Steward
33bf0b7b31 Update scala3-library to 3.3.0 2023-05-24 04:35:31 +09:00
Scala Steward
884cd498ce Update commons-io to 2.12.0 2023-05-17 07:02:27 +09:00
Scala Steward
e0b021cb3e Update tika-core to 2.8.0 2023-05-16 05:42:27 +09:00
Scala Steward
57edf101fa Update sbt-license-report to 1.5.0 2023-05-15 14:49:08 +09:00
Scala Steward
a2bf0d86d8 Update apache-sshd to 2.10.0 2023-05-15 06:49:29 +09:00
Scala Steward
32e2ea5061 Update sbt, sbt-dependency-tree to 1.8.3 2023-05-13 06:57:17 +09:00
Scala Steward
e28c0592f6 Update oauth2-oidc-sdk to 10.9.1 2023-05-12 07:07:12 +09:00
Scala Steward
60627060d5 Update mysql, postgresql to 1.18.1 2023-05-11 20:08:12 +09:00
Scala Steward
cea4d7e15f Update oauth2-oidc-sdk to 10.9 2023-05-06 19:47:44 +09:00
Naoki Takezoe
ca1670b21a Make it possible to edit empty custom field value (#3288) 2023-05-06 18:34:54 +09:00
Naoki Takezoe
c9c72faaf1 Improve git push performance (#3284) 2023-05-02 12:36:53 +09:00
kenji yoshida
ba42538775 Update validation.md 2023-05-02 07:29:42 +09:00
kenji yoshida
39141d8996 http => https 2023-05-01 19:27:33 +09:00
takezoe
e3dd099bbb Update version to 4.40.0-SNAPSHOT 2023-05-01 01:20:59 +09:00
Naoki Takezoe
6b37d1027f Make the default branch configurable (#3283) 2023-04-30 22:09:19 +09:00
scala-steward-bot
b521f43c84 Update org.eclipse.jgit.archive, ... to 6.5.0.202303070854-r (#3281)
* Update org.eclipse.jgit.archive, ... to 6.5.0.202303070854-r

* Revert commit(s) 61079bb8

* Update org.eclipse.jgit.archive, ... to 6.5.0.202303070854-r
2023-04-30 14:48:48 +09:00
Scala Steward
7c5a9df759 Update jetty-http, jetty-io, jetty-security, ... to 10.0.15 2023-04-30 13:49:29 +09:00
Scala Steward
04762a3e53 Update mockito-core to 5.3.1 2023-04-30 13:49:06 +09:00
kenji yoshida
d2ba2df2ba Update .scala-steward.conf 2023-04-30 13:15:24 +09:00
kenji yoshida
0e7f34f1d7 fix scala 3 build 2023-04-30 13:13:30 +09:00
xuwei-k
d576bbfaed update scala 3 build settings 2023-04-30 13:10:32 +09:00
kenji yoshida
2bfdca6992 Update build.yml 2023-04-29 16:10:55 +09:00
scala-steward-bot
d18fdb6399 Update logback-classic to 1.4.7 (#3273)
Co-authored-by: Naoki Takezoe <takezoe@gmail.com>
2023-04-29 12:04:02 +09:00
Naoki Takezoe
fe02605544 Upgrade to Scalatra 3.0.0-M3 and drop Java 8 support (#3279)
* Bump to Scalatra 3.0.0-M1
* Bump to Scalatra 3.0.0-M3
* Format build.sbt
* Drop Java 8 support
* Fix scala-xml related warnings
* Bump sbt-scoverage to 2.0.7

---------

Co-authored-by: kenji yoshida <6b656e6a69@gmail.com>
2023-04-29 11:53:30 +09:00
scala-steward-bot
f86ae20791 Update sbt-license-report to 1.4.0 (#3278)
Co-authored-by: kenji yoshida <6b656e6a69@gmail.com>
2023-04-28 22:45:53 +00:00
Naoki Takezoe
df69f88186 Release 4.39.0 (#3277) 2023-04-29 01:46:13 +09:00
Naoki Takezoe
8d1323f354 Delete records in ISSUE_ASSIGNEE when repository is deleted (#3276) 2023-04-24 02:26:21 +09:00
Naoki Takezoe
2f598b618b Fix issues in git refs APIs (#3275) 2023-04-23 22:52:31 +09:00
Scala Steward
baf0b0b92c Update oauth2-oidc-sdk to 10.8 2023-04-23 03:07:02 +09:00
Scala Steward
27a75250a6 Update logback-classic to 1.3.7 2023-04-20 06:32:21 +09:00
Scala Steward
15f60402a5 Update oauth2-oidc-sdk to 10.7.2 2023-04-17 17:49:56 +09:00
Scala Steward
41c6fc90b3 Update testcontainers-scala to 0.40.15 2023-04-17 00:50:22 +09:00
Scala Steward
34356b04a8 Update mysql, postgresql to 1.18.0 2023-04-05 02:14:51 +09:00
Scala Steward
2ca02b6539 Update oauth2-oidc-sdk to 10.7.1 2023-03-31 03:06:07 +09:00
Scala Steward
cd0c71dffb Update commons-compress to 1.23.0 2023-03-23 07:28:32 +09:00
Scala Steward
a59120fe19 Update testcontainers-scala to 0.40.14 2023-03-22 06:59:19 +09:00
Naoki Takezoe
fdc35f48ed Update the developer doc (#3257) 2023-03-19 11:48:07 +09:00
Naoki Takezoe
bae9b7ddc3 Ignore signed-commit verification error (#3256) 2023-03-18 21:58:15 +09:00
Scala Steward
3dd9b7e587 Update postgresql to 42.6.0 2023-03-18 07:48:38 +09:00
Scala Steward
44c905bdab Update logback-classic to 1.3.6 2023-03-17 13:08:58 +09:00
Scala Steward
5214040257 Update jetty-continuation, jetty-http, ... to 9.4.51.v20230217 2023-02-28 07:00:10 +09:00
Scala Steward
7ad9f901dd Update github-api to 1.314 2023-02-27 07:09:28 +09:00
Naoki Takezoe
f472d52954 Add --disable_news_feed option to disable News Feed (#3246) 2023-02-27 02:17:52 +09:00
Naoki Takezoe
1e752af41b Update directory.md 2023-02-26 11:25:50 +09:00
Naoki Takezoe
3ba46c3fc6 Update directory.md 2023-02-26 11:25:30 +09:00
Naoki Takezoe
bf83da476f Update directory.md 2023-02-26 11:21:26 +09:00
Naoki Takezoe
6b8c4cf8d0 Add --disable_cache option to disable cache (#3245) 2023-02-24 09:42:17 +09:00
Scala Steward
445329c07a Update postgresql to 42.5.4 2023-02-17 04:14:01 +09:00
Scala Steward
8f370e19c6 Update oauth2-oidc-sdk to 10.7 2023-02-16 21:44:11 +09:00
Scala Steward
736dbcfb58 Update oauth2-oidc-sdk to 10.6 2023-02-16 03:53:15 +09:00
Scala Steward
c1cb7f87e0 Update oauth2-oidc-sdk to 10.5.2 2023-02-14 07:22:34 +09:00
Scala Steward
3c14fcefc9 Update sbt-assembly to 2.1.1 2023-02-12 15:54:07 +09:00
Scala Steward
831badf8db Update tika-core to 2.7.0 2023-02-04 09:06:43 +09:00
Scala Steward
5f8a6e8d24 Update postgresql to 42.5.3 2023-02-04 07:54:40 +09:00
Scala Steward
a3981493f7 Update postgresql to 42.5.2 2023-02-01 07:33:53 +09:00
Scala Steward
6919cf5d4d Update oauth2-oidc-sdk to 10.5.1 2023-01-27 09:50:55 +09:00
kenji yoshida
f6d1e6bdd6 pin mockito 4.x
https://github.com/mockito/mockito/pull/2804
2023-01-14 18:11:18 +09:00
Scala Steward
a13ff89acd Update oauth2-oidc-sdk to 10.5 2023-01-13 07:20:28 +09:00
Naoki Takezoe
cd5c76279a Fix input JSON schema of add/replace labels to an issue API (#3226) 2023-01-13 02:41:48 +09:00
Scala Steward
debff5e4b8 Update thumbnailator to 0.4.19 2023-01-01 06:56:02 +09:00
Scala Steward
433e207ec5 Update mockito-core to 4.11.0 2022-12-29 01:38:44 +09:00
Naoki Takezoe
3775f6a907 Fix NoSuchElementException in delete issue comment API (#3220) 2022-12-26 09:48:05 +09:00
Naoki Takezoe
10d611c0eb Call OpenID connect logout endpoint when signed-out on GitBucket (#3219) 2022-12-26 09:41:29 +09:00
takezoe
963bc4d672 Change the log file path in local dev mode 2022-12-18 22:53:20 +09:00
Naoki Takezoe
e68a21ee30 Enum support in custom fields (#3195) 2022-12-18 22:46:11 +09:00
Naoki Takezoe
d5c083b70f Upgrade logback-classic to 1.3.5 (#3218) 2022-12-18 19:39:06 +09:00
Scala Steward
2deb9cf417 Update mockito-core to 4.10.0 2022-12-15 07:49:15 +09:00
Scala Steward
fca0cfcdc7 Update oauth2-oidc-sdk to 10.4 2022-12-13 22:09:35 +09:00
Scala Steward
1466e1bdb3 Update oauth2-oidc-sdk to 10.3.1 2022-12-13 20:58:47 +09:00
Naoki Takezoe
dd48bc443a Add option to keep session in the local dev mode (#3205) 2022-12-12 08:22:41 +09:00
Scala Steward
f455738e5f Update sbt-assembly to 2.1.0 2022-12-10 07:37:40 +09:00
Scala Steward
85193803cd Update jetty-continuation, jetty-http, ... to 9.4.50.v20221201 2022-12-08 08:58:51 +09:00
Scala Steward
4e90a6074a Update oauth2-oidc-sdk to 10.3 2022-12-07 08:02:34 +09:00
Scala Steward
ca94fa5184 Update sbt-pgp to 2.2.1 2022-12-06 14:45:21 +09:00
Scala Steward
f14a7c996f Update testcontainers-scala to 0.40.12 2022-12-05 04:53:03 +09:00
Scala Steward
989d22f4d8 Update httpclient to 4.5.14 2022-12-04 22:46:38 +09:00
Scala Steward
400a812343 Update commons-net to 3.9.0 2022-12-02 09:11:27 +09:00
Scala Steward
97284f1ced Update postgresql to 42.5.1 2022-11-24 03:45:39 +09:00
Scala Steward
5e6a0d7e16 Update mysql, postgresql to 1.17.6 2022-11-16 23:28:52 +09:00
Scala Steward
599e11245f Update apache-sshd to 2.9.2 2022-11-16 07:35:21 +09:00
Scala Steward
538d714c96 Update sbt-scalafmt to 2.5.0 2022-11-15 08:53:31 +09:00
Scala Steward
953915ba2a Update mockito-core to 4.9.0 2022-11-15 05:12:27 +09:00
Naoki Takezoe
1a2f5da055 Suppress "scanned from multiple locations" warnings in development (#3194) 2022-11-12 20:17:56 +09:00
Scala Steward
749a469d37 Update tika-core to 2.6.0 2022-11-08 03:15:07 +09:00
scala-steward-bot
c7d084321a Update mariadb-java-client to 2.7.6 (#3190) 2022-11-07 13:33:23 +09:00
Naoki Takezoe
00a61cd6cf Downgrade and pin MariaDB JDBC driver version (#3189) 2022-11-05 15:58:18 +09:00
Naoki Takezoe
d9c6c13c62 Merge 4.38.4 release notes into master (#3187) 2022-11-02 13:30:02 +09:00
Scala Steward
5260c5e889 Update commons-compress to 1.22 2022-11-01 06:47:55 +09:00
Scala Steward
1700f96c62 Update sbt-pgp to 2.2.0 2022-10-30 20:47:40 +09:00
205 changed files with 6309 additions and 5032 deletions

8
.git-blame-ignore-revs Normal file
View File

@@ -0,0 +1,8 @@
# update scalafmt
3d5ca44d66c77a46770a65a895c9737c542690f6
# Scala Steward: Reformat with scalafmt 3.8.2
f1360f44c61f8e12666965c10e79f11cd75d6d30
# Scala Steward: Reformat with scalafmt 3.9.7
a54fb4960ff0762738f4895cdc29bf2715a57f87

1
.github/CODEOWNERS vendored
View File

@@ -2,3 +2,4 @@
build.sbt @xuwei-k build.sbt @xuwei-k
project/* @xuwei-k project/* @xuwei-k
.github/workflows/* @xuwei-k

View File

@@ -1,18 +0,0 @@
### Before submitting an issue to GitBucket I have first:
- [ ] read the [contribution guidelines](https://github.com/gitbucket/gitbucket/blob/master/.github/CONTRIBUTING.md)
- [ ] searched for similar already existing issue
- [ ] read the documentation and [wiki](https://github.com/gitbucket/gitbucket/wiki)
*(if you have performed all the above, remove the paragraph and continue describing the issue with template below)*
## Issue
**Impacted version**: xxxx
**Deployment mode**: *explain here how you use GitBucket : standalone app, under webcontainer (which one), with an http frontend (nginx, httpd, ...)*
**Problem description**:
- *be as explicit as you can*
- *describe the problem and its symptoms*
- *explain how to reproduce*
- *attach whatever information that can help understanding the context (screen capture, log files)*

1
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1 @@
blank_issues_enabled: false

View File

@@ -0,0 +1,41 @@
name: Report issue
description: Report a problem or feature request with GitBucket
body:
- type: markdown
attributes:
value: |
### Before submitting an issue to GitBucket, please ensure you have:
- Read the [contribution guidelines](https://github.com/gitbucket/gitbucket/blob/master/.github/CONTRIBUTING.md)
- Searched for similar existing issues
- Read the documentation and [wiki](https://github.com/gitbucket/gitbucket/wiki)
- You can use [Gitter chat room](https://gitter.im/gitbucket/gitbucket) instead of GitHub Issues for casual discussion or inquiry
- type: checkboxes
id: prerequisites
attributes:
label: Prerequisites
options:
- label: I have read the contribution guidelines
- label: I have searched for similar issues
- label: I have read the documentation and wiki
- type: input
id: impacted_version
attributes:
label: Impacted version
description: Which version of GitBucket is affected?
placeholder: e.g. 4.37.0
- type: input
id: deployment_mode
attributes:
label: Deployment mode
description: How do you use GitBucket? (standalone app, under webcontainer, with an HTTP frontend, etc.)
placeholder: e.g. Standalone app, Tomcat, nginx
- type: textarea
id: problem_description
attributes:
label: Problem description
description: Be as explicit as you can. Describe the problem, its symptoms, how to reproduce, and attach any relevant information (screenshots, logs, etc.)
placeholder: Describe the problem and how to reproduce it

View File

@@ -7,12 +7,13 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 30 timeout-minutes: 30
strategy: strategy:
fail-fast: false
matrix: matrix:
java: [8, 11, 17] java: [17, 25]
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v5
- name: Cache - name: Cache
uses: actions/cache@v3 uses: actions/cache@v4
env: env:
cache-name: cache-sbt-libs cache-name: cache-sbt-libs
with: with:
@@ -22,18 +23,20 @@ jobs:
~/.cache/coursier/v1 ~/.cache/coursier/v1
key: build-${{ env.cache-name }}-${{ hashFiles('build.sbt') }} key: build-${{ env.cache-name }}-${{ hashFiles('build.sbt') }}
- name: Set up JDK - name: Set up JDK
uses: actions/setup-java@v3 uses: actions/setup-java@v5
with: with:
java-version: ${{ matrix.java }} java-version: ${{ matrix.java }}
distribution: adopt distribution: adopt
- name: Setup sbt launcher
uses: sbt/setup-sbt@v1
- name: Run tests - name: Run tests
run: sbt scalafmtSbtCheck scalafmtCheck test:scalafmtCheck test run: sbt scalafmtSbtCheck scalafmtCheckAll test
- name: Scala 3 - name: Scala 3
run: sbt '++ 3.1.2!' update # TODO run: sbt '++ 3.x' update # TODO
- name: Build executable - name: Build executable
run: sbt executable run: sbt executable
- name: Upload artifacts - name: Upload artifacts
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v4
with: with:
name: gitbucket-java${{ matrix.java }}-${{ github.sha }} name: gitbucket-java${{ matrix.java }}-${{ github.sha }}
path: ./target/executable/gitbucket.* path: ./target/executable/gitbucket.*

1
.gitignore vendored
View File

@@ -4,6 +4,7 @@
.ensime_cache .ensime_cache
.DS_Store .DS_Store
.java-version .java-version
.tmp
# sbt specific # sbt specific
dist/* dist/*

View File

@@ -3,7 +3,6 @@ updates.limit = 3
updates.includeScala = true updates.includeScala = true
updates.pin = [ updates.pin = [
{ groupId = "org.eclipse.jetty", version = "9." } { groupId = "org.eclipse.jetty", version = "10." }
{ groupId = "org.eclipse.jgit", version = "5." } { groupId = "org.mariadb.jdbc", version = "2." }
{ groupId = "com.zaxxer", version = "4." }
] ]

View File

@@ -1,12 +1,24 @@
version = "1.5.1" version = "3.9.10"
project.git = true project.git = true
maxColumn = 120 maxColumn = 120
docstrings = JavaDoc docstrings.style = keep
align.tokens = ["%", "%%", {code = "=>", owner = "Case"}] align.tokens = ["%", "%%", {code = "=>", owner = "Case"}]
align.openParenCallSite = false align.openParenCallSite = false
align.openParenDefnSite = false align.openParenDefnSite = false
continuationIndent.callSite = 2 continuationIndent.callSite = 2
continuationIndent.defnSite = 2 continuationIndent.defnSite = 2
danglingParentheses = true danglingParentheses.preset = true
runner.dialect = scala213source3
rewrite.trailingCommas.style = keep
fileOverride {
"glob:**/*.sbt" {
runner.dialect = scala212
rewrite.scala3.convertToNewSyntax = false
}
}
rewrite.scala3.convertToNewSyntax = true
runner.dialectOverride.allowSignificantIndentation = false
runner.dialectOverride.allowAsForImportRename = false
runner.dialectOverride.allowStarWildcardImport = false

View File

@@ -1,6 +1,72 @@
# 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.44.0 - 23 Sep 2025
- Enhanced branch protection which supports the following settings:
- Prevent pushes from non-allowed users
- Whether to apply restrictions to administrator users as well
- Improve logging for initialization errors
## 4.43.0 - 29 Jun 2025
- Upgrade H2 database from 1.x to 2.x
Note that upgrading from h2 1.x to 2.x requires data file migration: https://www.h2database.com/html/migration-to-v2.html
It can't be done automatically using GitBucket's auto migration mechanism because it relies on database itself. So, users who use h2 will have to dump and recreate their database manually with the following steps:
```bash
# Export database using the current version of H2
$ curl -O https://repo1.maven.org/maven2/com/h2database/h2/1.4.199/h2-1.4.199.jar
$ java -cp h2-1.4.199.jar org.h2.tools.Script -url "jdbc:h2:~/.gitbucket/data" -user sa -password sa -script dump.sql
# Recreate database using the new version of H2
$ curl -O https://repo1.maven.org/maven2/com/h2database/h2/2.3.232/h2-2.3.232.jar
$ java -cp h2-2.3.232.jar org.h2.tools.RunScript -url "jdbc:h2:~/.gitbucket/data" -user sa -password sa -script dump.sql
```
In addition, if `~/.gitbucket/database.conf` has the following configuration, remove `;MVCC=true` from `url`.
```
db {
url = "jdbc:h2:${DatabaseHome};MVCC=true" // => "jdbc:h2:${DatabaseHome}"
...
}
```
## 4.42.1 - 20 Jan 2025
- Fix LDAP issue with SSL
## 4.42.0 - 30 Dec 2024
- Increase max branch name length 100 -> 255
- Fix some GitHub incompatible Web APIs
- Apply user-defined CSS after all plugins
- Improve performance of listing commit logs
- Drop Java 11 support. Java 17 is now required
## 4.41.0 - 18 May 2024
- Simplify pull request UI
- Keyword search for issues and pull requests
- New settings for max files and lines limit in showing diff
- Adjust the default branch automatically when cloning external repository
- Fix layout of branch selector
- Performance improvement for listing branches
- Upgrade internal libraries
## 4.40.0 - 22 Oct 2023
- Configurable default branch name
- Support custom fields of issues and pull requests in search condition
- Create pull request from default branch of forked repositories
- News feed shows activities of all visible repositories
- Drop Java 8 support
- Improve git push performance
## 4.39.0 - 29 Apr 2023
- Support enum type in custom fields of Issues and Pull requests
- Hide large diffs by default
- Add new options to make it possible to run GitBucket using multiple machines
- Fix many API issues
## 4.38.4 - 2 Nov 2022
- Downgrade MariaDB JDBC drive to avoid unknown error
## 4.38.3 - 30 Oct 2022 ## 4.38.3 - 30 Oct 2022
- Fix several issues around multiple assignees in issues and pull requests - Fix several issues around multiple assignees in issues and pull requests
- Fix IllegalStateException when returning unknown avatar image - Fix IllegalStateException when returning unknown avatar image

View File

@@ -1,4 +1,4 @@
GitBucket [![Gitter chat](https://badges.gitter.im/gitbucket/gitbucket.svg)](https://gitter.im/gitbucket/gitbucket) [![build](https://github.com/gitbucket/gitbucket/workflows/build/badge.svg?branch=master)](https://github.com/gitbucket/gitbucket/actions?query=workflow%3Abuild+branch%3Amaster) [![gitbucket Scala version support](https://index.scala-lang.org/gitbucket/gitbucket/gitbucket/latest-by-scala-version.svg)](https://index.scala-lang.org/gitbucket/gitbucket/gitbucket) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/gitbucket/gitbucket/blob/master/LICENSE) GitBucket [![Gitter chat](https://badges.gitter.im/gitbucket/gitbucket.svg)](https://gitter.im/gitbucket/gitbucket) [![build](https://github.com/gitbucket/gitbucket/actions/workflows/build.yml/badge.svg)](https://github.com/gitbucket/gitbucket/actions/workflows/build.yml) [![gitbucket Scala version support](https://index.scala-lang.org/gitbucket/gitbucket/gitbucket/latest-by-scala-version.svg)](https://index.scala-lang.org/gitbucket/gitbucket/gitbucket) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/gitbucket/gitbucket/blob/master/LICENSE)
========= =========
GitBucket is a Git web platform powered by Scala offering: GitBucket is a Git web platform powered by Scala offering:
@@ -24,7 +24,7 @@ The current version of GitBucket provides many features such as:
Installation Installation
-------- --------
GitBucket requires **Java8**. You have to install it, if it is not already installed. GitBucket requires **Java 17**. You have to install it, if it is not already installed.
1. Download the latest **gitbucket.war** from [the releases page](https://github.com/gitbucket/gitbucket/releases) and run it by `java -jar gitbucket.war`. 1. Download the latest **gitbucket.war** from [the releases page](https://github.com/gitbucket/gitbucket/releases) and run it by `java -jar gitbucket.war`.
2. Go to `http://[hostname]:8080/` and log in with ID: **root** / Pass: **root**. 2. Go to `http://[hostname]:8080/` and log in with ID: **root** / Pass: **root**.
@@ -56,32 +56,36 @@ Support
-------- --------
- If you have any questions about GitBucket, see [Wiki](https://github.com/gitbucket/gitbucket/wiki) and check issues whether there is a same question or request in the past. - If you have any questions about GitBucket, see [Wiki](https://github.com/gitbucket/gitbucket/wiki) and check issues whether there is a same question or request in the past.
- If you can't find same question and report, send it to our [Gitter room](https://gitter.im/gitbucket/gitbucket) before raising an issue. - If you can't find same question and report, send it to our [Gitter chat 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.38.x What's New in 4.44.x
------------- -------------
## 4.38.3 - 30 Oct 2022 ## 4.44.0 - 23 Sep 2025
- Fix several issues around multiple assignees in issues and pull requests - Enhanced branch protection which supports the following settings:
- Fix IllegalStateException when returning unknown avatar image - Prevent pushes from non-allowed users
- Whether to apply restrictions to administrator users as well
- Improve logging for initialization errors
## 4.38.2 - 20 Sep 2022 Note that you have to migrate h2 database file if you will upgrade GitBucket from 4.42 or before to 4.43 or later and you are using the default h2 database because h2 1.x and h2.x don't have compatibility: https://www.h2database.com/html/migration-to-v2.html
- Resurrect assignee icons on the issue list
## 4.38.1 - 10 Sep 2022 It can't be done automatically using GitBucket's auto migration mechanism because it relies on database itself. So, users who use h2 will have to dump and recreate their database manually with the following steps:
- Fix comment diff in Chrome 105 ```bash
- Fix Markdown table CSS # Export database using the current version of H2
- Fix HTML rendering of multiple asignees $ curl -O https://repo1.maven.org/maven2/com/h2database/h2/1.4.199/h2-1.4.199.jar
$ java -cp h2-1.4.199.jar org.h2.tools.Script -url "jdbc:h2:~/.gitbucket/data" -user sa -password sa -script dump.sql
## 4.38.0 - 3 Sep 2022 # Recreate database using the new version of H2
- Support multiple assignees for Issues and Pull requests $ curl -O https://repo1.maven.org/maven2/com/h2database/h2/2.3.232/h2-2.3.232.jar
- Custom fields for issues and pull requests $ java -cp h2-2.3.232.jar org.h2.tools.RunScript -url "jdbc:h2:~/.gitbucket/data" -user sa -password sa -script dump.sql
- Reset password by users ```
- Allow to configure Jetty idle timeout in standalone mode
- Horizontal scroll for too wide tables in Markdown
- Hide header content on signin and register page
- Fix the default charset of the online editor in the repository viewer
- Fix the milestone count
- Some improvements and bugfixes for WebAPI and WebHook
See the [change log](CHANGELOG.md) for all of the updates. In addition, if `~/.gitbucket/database.conf` has the following configuration, remove `;MVCC=true` from `url`.
```
db {
url = "jdbc:h2:${DatabaseHome};MVCC=true" // => "jdbc:h2:${DatabaseHome}"
...
}
```
See the [change log](CHANGELOG.md) for all the past updates.

184
build.sbt
View File

@@ -1,85 +1,76 @@
import com.typesafe.sbt.license.{DepModuleInfo, LicenseInfo}
import com.jsuereth.sbtpgp.PgpKeys._ import com.jsuereth.sbtpgp.PgpKeys._
val Organization = "io.github.gitbucket" val Organization = "io.github.gitbucket"
val Name = "gitbucket" val Name = "gitbucket"
val GitBucketVersion = "4.38.3" val GitBucketVersion = "4.44.0"
val ScalatraVersion = "2.8.4" val ScalatraVersion = "3.1.2"
val JettyVersion = "9.4.49.v20220914" val JettyVersion = "10.0.26"
val JgitVersion = "5.13.1.202206130422-r" val JgitVersion = "6.10.1.202505221210-r"
lazy val root = (project in file(".")) lazy val root = (project in file("."))
.enablePlugins(SbtTwirl, ScalatraPlugin) .enablePlugins(SbtTwirl, ContainerPlugin)
sourcesInBase := false sourcesInBase := false
organization := Organization organization := Organization
name := Name name := Name
version := GitBucketVersion version := GitBucketVersion
scalaVersion := "2.13.10" scalaVersion := "2.13.17"
crossScalaVersions += "3.7.3"
// scalafmtOnCompile := true // scalafmtOnCompile := true
coverageExcludedPackages := ".*\\.html\\..*" coverageExcludedPackages := ".*\\.html\\..*"
// dependency settings
resolvers ++= Seq(
Classpaths.typesafeReleases,
"sonatype-snapshot" at "https://oss.sonatype.org/content/repositories/snapshots/"
)
libraryDependencies ++= Seq( libraryDependencies ++= Seq(
"org.eclipse.jgit" % "org.eclipse.jgit.http.server" % JgitVersion, "org.eclipse.jgit" % "org.eclipse.jgit.http.server" % JgitVersion,
"org.eclipse.jgit" % "org.eclipse.jgit.archive" % JgitVersion, "org.eclipse.jgit" % "org.eclipse.jgit.archive" % JgitVersion,
"org.scalatra" %% "scalatra" % ScalatraVersion cross CrossVersion.for3Use2_13, "org.scalatra" %% "scalatra-javax" % ScalatraVersion,
"org.scalatra" %% "scalatra-json" % ScalatraVersion cross CrossVersion.for3Use2_13, "org.scalatra" %% "scalatra-json-javax" % ScalatraVersion,
"org.scalatra" %% "scalatra-forms" % ScalatraVersion cross CrossVersion.for3Use2_13, "org.scalatra" %% "scalatra-forms-javax" % ScalatraVersion,
"org.json4s" %% "json4s-jackson" % "4.0.6" cross CrossVersion.for3Use2_13, "org.json4s" %% "json4s-jackson" % "4.1.0-M8",
"commons-io" % "commons-io" % "2.11.0", "commons-io" % "commons-io" % "2.20.0",
"io.github.gitbucket" % "solidbase" % "1.0.5", "io.github.gitbucket" % "solidbase" % "1.1.0",
"io.github.gitbucket" % "markedj" % "1.0.17", "io.github.gitbucket" % "markedj" % "1.0.20",
"org.apache.commons" % "commons-compress" % "1.21", "org.tukaani" % "xz" % "1.10",
"org.apache.commons" % "commons-email" % "1.5", "org.apache.commons" % "commons-compress" % "1.28.0",
"commons-net" % "commons-net" % "3.8.0", "org.apache.commons" % "commons-email" % "1.6.0",
"org.apache.httpcomponents" % "httpclient" % "4.5.13", "commons-net" % "commons-net" % "3.12.0",
"org.apache.sshd" % "apache-sshd" % "2.9.1" exclude ("org.slf4j", "slf4j-jdk14") exclude ("org.apache.sshd", "sshd-mina") exclude ("org.apache.sshd", "sshd-netty"), "org.apache.httpcomponents" % "httpclient" % "4.5.14",
"org.apache.tika" % "tika-core" % "2.5.0", "org.apache.sshd" % "apache-sshd" % "2.16.0" exclude ("org.slf4j", "slf4j-jdk14") exclude (
"com.github.takezoe" %% "blocking-slick-32" % "0.0.12" cross CrossVersion.for3Use2_13, "org.apache.sshd",
"com.novell.ldap" % "jldap" % "2009-10-07", "sshd-mina"
"com.h2database" % "h2" % "1.4.199", ) exclude ("org.apache.sshd", "sshd-netty")
"org.mariadb.jdbc" % "mariadb-java-client" % "3.0.8", exclude ("org.apache.sshd", "sshd-spring-sftp"),
"org.postgresql" % "postgresql" % "42.5.0", "org.apache.tika" % "tika-core" % "3.2.3",
"ch.qos.logback" % "logback-classic" % "1.2.11", "com.github.takezoe" %% "blocking-slick" % "0.0.14",
"com.zaxxer" % "HikariCP" % "4.0.3" exclude ("org.slf4j", "slf4j-api"), "com.novell.ldap" % "jldap" % "2009-10-07",
"com.typesafe" % "config" % "1.4.2", "com.h2database" % "h2" % "2.4.240",
"fr.brouillard.oss.security.xhub" % "xhub4j-core" % "1.1.0", "org.mariadb.jdbc" % "mariadb-java-client" % "2.7.12",
"io.github.java-diff-utils" % "java-diff-utils" % "4.12", "org.postgresql" % "postgresql" % "42.7.8",
"org.cache2k" % "cache2k-all" % "1.6.0.Final", "ch.qos.logback" % "logback-classic" % "1.5.19",
"net.coobird" % "thumbnailator" % "0.4.18", "com.zaxxer" % "HikariCP" % "7.0.2" exclude ("org.slf4j", "slf4j-api"),
"com.github.zafarkhaja" % "java-semver" % "0.9.0", "com.typesafe" % "config" % "1.4.5",
"com.nimbusds" % "oauth2-oidc-sdk" % "10.1", "fr.brouillard.oss.security.xhub" % "xhub4j-core" % "1.1.0",
"org.eclipse.jetty" % "jetty-webapp" % JettyVersion % "provided", "io.github.java-diff-utils" % "java-diff-utils" % "4.16",
"javax.servlet" % "javax.servlet-api" % "3.1.0" % "provided", "org.cache2k" % "cache2k-all" % "1.6.0.Final",
"junit" % "junit" % "4.13.2" % "test", "net.coobird" % "thumbnailator" % "0.4.21",
"org.scalatra" %% "scalatra-scalatest" % ScalatraVersion % "test" cross CrossVersion.for3Use2_13, "com.github.zafarkhaja" % "java-semver" % "0.10.2",
"org.mockito" % "mockito-core" % "4.8.1" % "test", "com.nimbusds" % "oauth2-oidc-sdk" % "11.30",
"com.dimafeng" %% "testcontainers-scala" % "0.40.11" % "test", "org.eclipse.jetty" % "jetty-webapp" % JettyVersion % "provided",
"org.testcontainers" % "mysql" % "1.17.5" % "test", "javax.servlet" % "javax.servlet-api" % "3.1.0" % "provided",
"org.testcontainers" % "postgresql" % "1.17.5" % "test", "junit" % "junit" % "4.13.2" % "test",
"net.i2p.crypto" % "eddsa" % "0.3.0", "org.scalatra" %% "scalatra-scalatest-javax" % ScalatraVersion % "test",
"is.tagomor.woothee" % "woothee-java" % "1.11.0", "org.mockito" % "mockito-core" % "5.20.0" % "test",
"org.ec4j.core" % "ec4j-core" % "0.3.0", "com.dimafeng" %% "testcontainers-scala" % "0.43.0" % "test",
"org.kohsuke" % "github-api" % "1.313" % "test" "org.testcontainers" % "mysql" % "1.21.3" % "test",
"org.testcontainers" % "postgresql" % "1.21.3" % "test",
"net.i2p.crypto" % "eddsa" % "0.3.0",
"is.tagomor.woothee" % "woothee-java" % "1.11.0",
"org.ec4j.core" % "ec4j-core" % "1.1.1",
"org.kohsuke" % "github-api" % "1.330" % "test"
) )
libraryDependencies ~= {
_.map {
case x if x.name == "twirl-api" =>
x cross CrossVersion.for3Use2_13
case x =>
x
}
}
// Compiler settings // Compiler settings
scalacOptions := Seq( scalacOptions := Seq(
"-deprecation", "-deprecation",
@@ -89,8 +80,16 @@ scalacOptions := Seq(
"-Wunused:imports", "-Wunused:imports",
"-Wconf:cat=unused&src=twirl/.*:s,cat=unused&src=scala/gitbucket/core/model/[^/]+\\.scala:s" "-Wconf:cat=unused&src=twirl/.*:s,cat=unused&src=scala/gitbucket/core/model/[^/]+\\.scala:s"
) )
compile / javacOptions ++= Seq("-target", "8", "-source", "8") scalacOptions ++= {
Jetty / javaOptions += "-Dlogback.configurationFile=/logback-dev.xml" scalaBinaryVersion.value match {
case "2.13" =>
Seq("-Xsource:3-cross")
case _ =>
Nil
}
}
compile / javacOptions ++= Seq("-target", "11", "-source", "11")
Container / javaOptions += "-Dlogback.configurationFile=/logback-dev.xml"
// Test settings // Test settings
//testOptions in Test += Tests.Argument("-l", "ExternalDBTest") //testOptions in Test += Tests.Argument("-l", "ExternalDBTest")
@@ -114,8 +113,8 @@ assembly / assemblyMergeStrategy := {
// Exclude a war file from published artifacts // Exclude a war file from published artifacts
signedArtifacts := { signedArtifacts := {
signedArtifacts.value.filterNot { signedArtifacts.value.filterNot { case (_, file) =>
case (_, file) => file.getName.endsWith(".war") || file.getName.endsWith(".war.asc") file.getName.endsWith(".war") || file.getName.endsWith(".war.asc")
} }
} }
@@ -123,15 +122,14 @@ signedArtifacts := {
val ExecutableConfig = config("executable").hide val ExecutableConfig = config("executable").hide
Keys.ivyConfigurations += ExecutableConfig Keys.ivyConfigurations += ExecutableConfig
libraryDependencies ++= Seq( libraryDependencies ++= Seq(
"org.eclipse.jetty" % "jetty-security" % JettyVersion % "executable", "org.eclipse.jetty" % "jetty-security" % JettyVersion % "executable",
"org.eclipse.jetty" % "jetty-webapp" % JettyVersion % "executable", "org.eclipse.jetty" % "jetty-webapp" % JettyVersion % "executable",
"org.eclipse.jetty" % "jetty-continuation" % JettyVersion % "executable", "org.eclipse.jetty" % "jetty-server" % JettyVersion % "executable",
"org.eclipse.jetty" % "jetty-server" % JettyVersion % "executable", "org.eclipse.jetty" % "jetty-xml" % JettyVersion % "executable",
"org.eclipse.jetty" % "jetty-xml" % JettyVersion % "executable", "org.eclipse.jetty" % "jetty-http" % JettyVersion % "executable",
"org.eclipse.jetty" % "jetty-http" % JettyVersion % "executable", "org.eclipse.jetty" % "jetty-servlet" % JettyVersion % "executable",
"org.eclipse.jetty" % "jetty-servlet" % JettyVersion % "executable", "org.eclipse.jetty" % "jetty-io" % JettyVersion % "executable",
"org.eclipse.jetty" % "jetty-io" % JettyVersion % "executable", "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 // Run package task before test to generate target/webapp for integration test
@@ -158,9 +156,11 @@ executableKey := {
// include jetty classes // include jetty classes
val jettyJars = Keys.update.value select configurationFilter(name = ExecutableConfig.name) val jettyJars = Keys.update.value select configurationFilter(name = ExecutableConfig.name)
jettyJars foreach { jar => jettyJars foreach { jar =>
IO unzip (jar, temp, (name: String) => IO unzip (
(name startsWith "javax/") || jar,
(name startsWith "org/")) temp,
(name: String) => (name startsWith "javax/") || (name startsWith "org/") || (name startsWith "META-INF/services/")
)
} }
// include original war file // include original war file
@@ -185,14 +185,14 @@ executableKey := {
val url = "https://github.com/" + val url = "https://github.com/" +
s"gitbucket/gitbucket-${pluginId}-plugin/releases/download/${pluginVersion}/gitbucket-${pluginId}-plugin-${pluginVersion}.jar" s"gitbucket/gitbucket-${pluginId}-plugin/releases/download/${pluginVersion}/gitbucket-${pluginId}-plugin-${pluginVersion}.jar"
log info s"Download: ${url}" log info s"Download: ${url}"
IO transfer (new java.net.URL(url).openStream, pluginsDir / url.substring(url.lastIndexOf("/") + 1)) IO transfer (new java.net.URI(url).toURL.openStream, pluginsDir / url.substring(url.lastIndexOf("/") + 1))
case _ => () case _ => ()
} }
} }
// zip it up // zip it up
IO delete (temp / "META-INF" / "MANIFEST.MF") IO delete (temp / "META-INF" / "MANIFEST.MF")
val contentMappings = (temp.allPaths --- PathFinder(temp)).get pair { file => val contentMappings = (temp.allPaths --- PathFinder(temp)).get() pair { file =>
IO.relativizeFile(temp, file) IO.relativizeFile(temp, file)
} }
val manifest = new JarManifest val manifest = new JarManifest
@@ -206,10 +206,9 @@ executableKey := {
"md5" -> "MD5", "md5" -> "MD5",
"sha1" -> "SHA-1", "sha1" -> "SHA-1",
"sha256" -> "SHA-256" "sha256" -> "SHA-256"
).foreach { ).foreach { case (extension, algorithm) =>
case (extension, algorithm) => val checksumFile = workDir / (warName + "." + extension)
val checksumFile = workDir / (warName + "." + extension) Checksums generate (outputFile, checksumFile, algorithm)
Checksums generate (outputFile, checksumFile, algorithm)
} }
// done // done
@@ -217,9 +216,9 @@ executableKey := {
outputFile outputFile
} }
publishTo := { publishTo := {
val nexus = "https://oss.sonatype.org/" val centralSnapshots = "https://central.sonatype.com/repository/maven-snapshots/"
if (version.value.trim.endsWith("SNAPSHOT")) Some("snapshots" at nexus + "content/repositories/snapshots") if (isSnapshot.value) Some("central-snapshots" at centralSnapshots)
else Some("releases" at nexus + "service/local/staging/deploy/maven2") else localStaging.value
} }
publishMavenStyle := true publishMavenStyle := true
pomIncludeRepository := { _ => pomIncludeRepository := { _ =>
@@ -285,7 +284,12 @@ Test / testOptions ++= {
} }
} }
Jetty / javaOptions ++= Seq( Container / javaOptions ++= Seq(
"-Dlogback.configurationFile=/logback-dev.xml",
"-Xdebug", "-Xdebug",
"-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000" "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000",
"-Dorg.eclipse.jetty.annotations.AnnotationParser.LEVEL=OFF",
// "-Ddev-features=keep-session"
) )
Container / containerLibs := Seq(("org.eclipse.jetty" % "jetty-runner" % JettyVersion).intransitive())
Container / containerMain := "org.eclipse.jetty.runner.Runner"

View File

@@ -1,7 +1,7 @@
How to build and run from the source tree How to build and run from the source tree
======== ========
First of all, Install [sbt](http://www.scala-sbt.org/index.html). First of all, Install [sbt](https://www.scala-sbt.org/index.html).
```shell ```shell
$ brew install sbt $ brew install sbt
@@ -13,12 +13,26 @@ Run for Development
If you want to test GitBucket, type the following command in the root directory of the source tree. If you want to test GitBucket, type the following command in the root directory of the source tree.
```shell ```shell
$ sbt ~jetty:start $ sbt ~container:start
``` ```
Then access `http://localhost:8080/` in your browser. The default administrator account is `root` and password is `root`. Then access `http://localhost:8080/` in your browser. The default administrator account is `root` and password is `root`.
Source code modifications are detected and a reloading happens automatically. You can modify the logging configuration by editing `src/main/resources/logback-dev.xml`. Source code modifications are detected and a reloading happens automatically.
You can modify the logging configuration by editing `src/main/resources/logback-dev.xml`.
Note that HttpSession is cleared when auto-reloading happened.
This is a bit annoying when developing features that requires sign-in.
You can keep HttpSession even if GitBucket is restarted by enabling this configuration in `build.sbt`:
https://github.com/gitbucket/gitbucket/blob/3dcc0aee3c4413b05be7c03476626cb202674afc/build.sbt#L292
Or by launching GitBucket with the following command:
```shell
sbt '; set Container/javaOptions += "-Ddev-features=keep-session" ; ~container:start'
```
Note that this feature serializes HttpSession on the local disk and assigns all requests to the same session
which means you cannot test multi users behavior in this mode.
Build war file Build war file
-------- --------
@@ -37,7 +51,8 @@ To build an executable war file, run
$ sbt executable $ sbt executable
``` ```
at the top of the source tree. It generates executable `gitbucket.war` into `target/executable`. We release this war file as release artifact. at the top of the source tree. It generates executable `gitbucket.war` into `target/executable`.
We release this war file as release artifact.
Run tests spec Run tests spec
--------- ---------

View File

@@ -1,6 +1,6 @@
Debug GitBucket on IntelliJ Debug GitBucket on IntelliJ
======== ========
Add following configuration for allowing remote debugging to `buils.sbt`: Add following configuration for allowing remote debugging to `build.sbt`:
```scala ```scala
javaOptions in Jetty ++= Seq( javaOptions in Jetty ++= Seq(
@@ -12,7 +12,7 @@ javaOptions in Jetty ++= Seq(
Run GitBucket: Run GitBucket:
```shell ```shell
$ sbt ~jetty:start $ sbt ~container:start
``` ```
In IntelliJ, create remote debug configuration as follows. Make sure port number is same as above configuration. In IntelliJ, create remote debug configuration as follows. Make sure port number is same as above configuration.

View File

@@ -5,13 +5,17 @@ GitBucket persists all data into __HOME/.gitbucket__ in default (In 1.9 or befor
This directory has following structure: This directory has following structure:
``` ```
* /HOME/gitbucket * /HOME/.gitbucket
* gitbucket.conf
* database.conf
* activity.log
* data.mv.db, data.trace.db (H2 data files if the default embed H2 is used)
* /repositories * /repositories
* /USER_NAME * /USER_NAME
* /REPO_NAME.git (substance of repository. GitServlet sees this directory) * /REPO_NAME.git (substance of repository. GitServlet sees this directory)
* /REPO_NAME.wiki.git (wiki repository) * /REPO_NAME.wiki.git (wiki repository)
* /REPO_NAME * /REPO_NAME
* /issues (files which are attached to issue) * /issues (files attached to issue)
* /lfs (LFS managed files) * /lfs (LFS managed files)
* /data * /data
* /USER_NAME * /USER_NAME
@@ -20,6 +24,8 @@ This directory has following structure:
* /plugins * /plugins
* plugin.jar * plugin.jar
* /.installed (copied available plugins from the parent directory automatically) * /.installed (copied available plugins from the parent directory automatically)
* /sessions
* HTTP session data created (if '--save_sessions' option is used in the standalone mode)
* /tmp * /tmp
* /_upload * /_upload
* /SESSION_ID (removed at session timeout) * /SESSION_ID (removed at session timeout)

View File

@@ -38,15 +38,26 @@ Generate release files
For plug-in development, we have to publish the GitBucket jar file to the Maven central repository before release GitBucket itself. For plug-in development, we have to publish the GitBucket jar file to the Maven central repository before release GitBucket itself.
First, hit following command to publish artifacts to the sonatype OSS repository: First, stage artifacts on your machine:
```bash ```bash
$ sbt publishSigned $ sbt publishSigned
``` ```
Then logged-in to https://oss.sonatype.org/, close and release the repository. Next, upload artifacts to Sonatype's Central Portal with the following command:
You need to wait up to a day until [gitbucket-notification-plugin](https://plugins.gitbucket-community.org/) which is default bundled plugin is built for new version of GitBucket. ```bash
$ sbt sonaUpload
```
Then logged-in to https://central.sonatype.com/ and publish the deployment.
You need to wait up to a day until default bundled plugins:
- https://github.com/gitbucket/gitbucket-notifications-plugin
- https://github.com/gitbucket/gitbucket-gist-plugin
- https://github.com/gitbucket/gitbucket-pages-plugin
- https://github.com/gitbucket/gitbucket-emoji-plugin
### Make release war file ### Make release war file
@@ -55,5 +66,4 @@ Run `sbt executable`. The release war file and fingerprint are generated into `t
```bash ```bash
$ sbt executable $ sbt executable
``` ```
Create new release from the corresponded tag on GitHub, then upload generated jar file and fingerprints to the release. Create new release from the corresponded tag on GitHub, then upload generated jar file and fingerprints to the release.

View File

@@ -1,6 +1,6 @@
Mapping and Validation Mapping and Validation
======== ========
GitBucket uses [scalatra-forms](http://scalatra.org/guides/2.6/formats/forms.html) to validate request parameters and map them to the scala object. This is inspired by Play2 form mapping / validation. GitBucket uses [scalatra-forms](https://scalatra.org/guides/2.8/formats/forms.html) to validate request parameters and map them to the scala object. This is inspired by Play2 form mapping / validation.
At first, define the mapping as following: At first, define the mapping as following:

View File

@@ -1 +1 @@
sbt.version=1.7.2 sbt.version=1.11.7

View File

@@ -1,11 +1,11 @@
scalacOptions ++= Seq("-unchecked", "-deprecation", "-feature") scalacOptions ++= Seq("-unchecked", "-deprecation", "-feature")
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.6") addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.5")
addSbtPlugin("com.typesafe.sbt" % "sbt-twirl" % "1.5.1") addSbtPlugin("org.playframework.twirl" % "sbt-twirl" % "2.0.9")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.0.0") addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.3.1")
addSbtPlugin("org.scalatra.sbt" % "sbt-scalatra" % "1.0.4") addSbtPlugin("org.scalatra.sbt" % "sbt-scalatra" % "1.0.4")
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2") addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.3.1")
addSbtPlugin("com.typesafe.sbt" % "sbt-license-report" % "1.2.0") addSbtPlugin("com.github.sbt" % "sbt-license-report" % "1.9.0")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.0.0") addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.3.1")
addDependencyTreePlugin addDependencyTreePlugin

View File

@@ -65,9 +65,15 @@ public class JettyLauncher {
boolean saveSessions = false; boolean saveSessions = false;
for(String arg: args) { for(String arg: args) {
if(arg.equals("--save_sessions")) { if (arg.equals("--save_sessions")) {
saveSessions = true; saveSessions = true;
} }
if (arg.equals("--disable_news_feed")) {
System.setProperty("gitbucket.disableNewsFeed", "true");
}
if (arg.equals("--disable_cache")) {
System.setProperty("gitbucket.disableCache", "true");
}
if(arg.startsWith("--") && arg.contains("=")) { if(arg.startsWith("--") && arg.contains("=")) {
String[] dim = arg.split("=", 2); String[] dim = arg.split("=", 2);
if(dim.length == 2) { if(dim.length == 2) {
@@ -149,7 +155,7 @@ public class JettyLauncher {
} }
if (connectorsSet.contains(Connectors.HTTPS)) { if (connectorsSet.contains(Connectors.HTTPS)) {
final SslContextFactory sslContextFactory = new SslContextFactory.Server(); final SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setKeyStorePath(requireNonNull(keyStorePath, sslContextFactory.setKeyStorePath(requireNonNull(keyStorePath,
"You must specify a path to an SSL keystore via the --key_store_path command line argument" + "You must specify a path to an SSL keystore via the --key_store_path command line argument" +

View File

@@ -1,4 +1,4 @@
notifications:1.11.0 notifications:1.11.0
gist:4.22.0 gist:4.23.0
emoji:4.6.0 emoji:4.6.0
pages:1.10.0 pages:1.10.0

View File

@@ -7,7 +7,7 @@
</appender> </appender>
<appender name="FILE" class="ch.qos.logback.core.FileAppender"> <appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>gitbucket.log</file> <file>.tmp/gitbucket.log</file>
<encoder> <encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder> </encoder>
@@ -23,4 +23,4 @@
<logger name="scala.slick.jdbc.JdbcBackend.statement" level="DEBUG" /> <logger name="scala.slick.jdbc.JdbcBackend.statement" level="DEBUG" />
--> -->
</configuration> </configuration>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<changeSet>
<addColumn tableName="CUSTOM_FIELD">
<column name="CONSTRAINTS" type="varchar(200)" nullable="true"/>
</addColumn>
</changeSet>

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<changeSet>
<dropForeignKeyConstraint constraintName="IDX_PROTECTED_BRANCH_REQUIRE_CONTEXT_FK0" baseTableName="PROTECTED_BRANCH_REQUIRE_CONTEXT"/>
<dropPrimaryKey constraintName="IDX_PROTECTED_BRANCH_REQUIRE_CONTEXT_PK" tableName="PROTECTED_BRANCH_REQUIRE_CONTEXT"/>
<dropForeignKeyConstraint constraintName="IDX_PROTECTED_BRANCH_FK0" baseTableName="PROTECTED_BRANCH"/>
<dropPrimaryKey constraintName="IDX_PROTECTED_BRANCH_PK" tableName="PROTECTED_BRANCH"/>
<modifyDataType columnName="DEFAULT_BRANCH" newDataType="varchar(255)" tableName="REPOSITORY"/>
<modifyDataType columnName="BRANCH" newDataType="varchar(255)" tableName="PULL_REQUEST"/>
<modifyDataType columnName="REQUEST_BRANCH" newDataType="varchar(255)" tableName="PULL_REQUEST"/>
<modifyDataType columnName="BRANCH" newDataType="varchar(255)" tableName="PROTECTED_BRANCH"/>
<modifyDataType columnName="BRANCH" newDataType="varchar(255)" tableName="PROTECTED_BRANCH_REQUIRE_CONTEXT"/>
<addPrimaryKey constraintName="IDX_PROTECTED_BRANCH_PK" tableName="PROTECTED_BRANCH" columnNames="USER_NAME, REPOSITORY_NAME, BRANCH"/>
<addForeignKeyConstraint constraintName="IDX_PROTECTED_BRANCH_FK0" baseTableName="PROTECTED_BRANCH" baseColumnNames="USER_NAME, REPOSITORY_NAME" referencedTableName="REPOSITORY" referencedColumnNames="USER_NAME, REPOSITORY_NAME" onDelete="CASCADE" onUpdate="CASCADE"/>
<addPrimaryKey constraintName="IDX_PROTECTED_BRANCH_REQUIRE_CONTEXT_PK" tableName="PROTECTED_BRANCH_REQUIRE_CONTEXT" columnNames="USER_NAME, REPOSITORY_NAME, BRANCH, CONTEXT"/>
<addForeignKeyConstraint constraintName="IDX_PROTECTED_BRANCH_REQUIRE_CONTEXT_FK0" baseTableName="PROTECTED_BRANCH_REQUIRE_CONTEXT" baseColumnNames="USER_NAME, REPOSITORY_NAME, BRANCH" referencedTableName="PROTECTED_BRANCH" referencedColumnNames="USER_NAME, REPOSITORY_NAME, BRANCH" onDelete="CASCADE" onUpdate="CASCADE"/>
</changeSet>

View File

@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<changeSet>
<!--================================================================================================-->
<!-- PROTECTED_BRANCH -->
<!--================================================================================================-->
<addColumn tableName="PROTECTED_BRANCH">
<column name="REQUIRED_STATUS_CHECK" type="boolean" nullable="false" defaultValue="false"/>
<column name="RESTRICTIONS" type="boolean" nullable="false" defaultValue="false"/>
</addColumn>
<sql>
UPDATE PROTECTED_BRANCH SET REQUIRED_STATUS_CHECK = TRUE
WHERE EXISTS (SELECT * FROM PROTECTED_BRANCH_REQUIRE_CONTEXT
WHERE PROTECTED_BRANCH.USER_NAME = PROTECTED_BRANCH_REQUIRE_CONTEXT.USER_NAME
AND PROTECTED_BRANCH.REPOSITORY_NAME = PROTECTED_BRANCH_REQUIRE_CONTEXT.REPOSITORY_NAME
AND PROTECTED_BRANCH.BRANCH = PROTECTED_BRANCH_REQUIRE_CONTEXT.BRANCH)
</sql>
<!--================================================================================================-->
<!-- PROTECTED_BRANCH_RESTRICTIONS_USER -->
<!--================================================================================================-->
<createTable tableName="PROTECTED_BRANCH_RESTRICTION">
<column name="USER_NAME" type="varchar(100)" nullable="false"/>
<column name="REPOSITORY_NAME" type="varchar(100)" nullable="false"/>
<column name="BRANCH" type="varchar(100)" nullable="false"/>
<column name="ALLOWED_USER" type="varchar(255)" nullable="false"/>
</createTable>
<addPrimaryKey constraintName="IDX_PROTECTED_BRANCH_RESTRICTION_PK" tableName="PROTECTED_BRANCH_RESTRICTION" columnNames="USER_NAME, REPOSITORY_NAME, BRANCH, ALLOWED_USER"/>
<addForeignKeyConstraint constraintName="IDX_PROTECTED_BRANCH_RESTRICTION_FK0" baseTableName="PROTECTED_BRANCH_RESTRICTION" baseColumnNames="USER_NAME, REPOSITORY_NAME, BRANCH" referencedTableName="PROTECTED_BRANCH" referencedColumnNames="USER_NAME, REPOSITORY_NAME, BRANCH" onDelete="CASCADE" onUpdate="CASCADE"/>
<addForeignKeyConstraint constraintName="IDX_PROTECTED_BRANCH_RESTRICTION_FK1" baseTableName="PROTECTED_BRANCH_RESTRICTION" baseColumnNames="ALLOWED_USER" referencedTableName="ACCOUNT" referencedColumnNames="USER_NAME"/>
</changeSet>

View File

@@ -4,7 +4,6 @@ import java.io.FileOutputStream
import java.nio.charset.StandardCharsets import java.nio.charset.StandardCharsets
import java.sql.Connection import java.sql.Connection
import java.util.UUID import java.util.UUID
import gitbucket.core.model.Activity import gitbucket.core.model.Activity
import gitbucket.core.util.Directory.ActivityLog import gitbucket.core.util.Directory.ActivityLog
import gitbucket.core.util.JDBCUtil import gitbucket.core.util.JDBCUtil
@@ -15,6 +14,7 @@ import org.json4s.{Formats, NoTypeHints}
import org.json4s.jackson.Serialization import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write import org.json4s.jackson.Serialization.write
import java.util.logging.Level
import scala.util.Using import scala.util.Using
object GitBucketCoreModule object GitBucketCoreModule
@@ -76,21 +76,20 @@ object GitBucketCoreModule
import JDBCUtil._ import JDBCUtil._
val conn = context.get(Solidbase.CONNECTION).asInstanceOf[Connection] val conn = context.get(Solidbase.CONNECTION).asInstanceOf[Connection]
val list = conn.select("SELECT * FROM ACTIVITY ORDER BY ACTIVITY_ID") { val list = conn.select("SELECT * FROM ACTIVITY ORDER BY ACTIVITY_ID") { rs =>
rs => Activity(
Activity( activityId = UUID.randomUUID().toString,
activityId = UUID.randomUUID().toString, userName = rs.getString("USER_NAME"),
userName = rs.getString("USER_NAME"), repositoryName = rs.getString("REPOSITORY_NAME"),
repositoryName = rs.getString("REPOSITORY_NAME"), activityUserName = rs.getString("ACTIVITY_USER_NAME"),
activityUserName = rs.getString("ACTIVITY_USER_NAME"), activityType = rs.getString("ACTIVITY_TYPE"),
activityType = rs.getString("ACTIVITY_TYPE"), message = rs.getString("MESSAGE"),
message = rs.getString("MESSAGE"), additionalInfo = {
additionalInfo = { val additionalInfo = rs.getString("ADDITIONAL_INFO")
val additionalInfo = rs.getString("ADDITIONAL_INFO") if (rs.wasNull()) None else Some(additionalInfo)
if (rs.wasNull()) None else Some(additionalInfo) },
}, activityDate = rs.getTimestamp("ACTIVITY_DATE")
activityDate = rs.getTimestamp("ACTIVITY_DATE") )
)
} }
Using.resource(new FileOutputStream(ActivityLog, true)) { out => Using.resource(new FileOutputStream(ActivityLog, true)) { out =>
list.foreach { activity => list.foreach { activity =>
@@ -114,5 +113,15 @@ object GitBucketCoreModule
new Version("4.38.0", new LiquibaseMigration("update/gitbucket-core_4.38.xml")), new Version("4.38.0", new LiquibaseMigration("update/gitbucket-core_4.38.xml")),
new Version("4.38.1"), new Version("4.38.1"),
new Version("4.38.2"), new Version("4.38.2"),
new Version("4.38.3") new Version("4.38.3"),
) new Version("4.38.4"),
new Version("4.39.0", new LiquibaseMigration("update/gitbucket-core_4.39.xml")),
new Version("4.40.0"),
new Version("4.41.0"),
new Version("4.42.0", new LiquibaseMigration("update/gitbucket-core_4.42.xml")),
new Version("4.42.1"),
new Version("4.43.0"),
new Version("4.44.0", new LiquibaseMigration("update/gitbucket-core_4.44.xml"))
) {
java.util.logging.Logger.getLogger("liquibase").setLevel(Level.SEVERE)
}

View File

@@ -0,0 +1,6 @@
package gitbucket.core.api
/**
* https://developer.github.com/v3/issues/labels/#add-labels-to-an-issue
*/
case class AddLabelsToAnIssue(labels: Seq[String])

View File

@@ -6,7 +6,7 @@ import gitbucket.core.util.RepositoryName
* https://developer.github.com/v3/repos/#get-branch * https://developer.github.com/v3/repos/#get-branch
* https://developer.github.com/v3/repos/#enabling-and-disabling-branch-protection * https://developer.github.com/v3/repos/#enabling-and-disabling-branch-protection
*/ */
case class ApiBranch(name: String, commit: ApiBranchCommit, protection: ApiBranchProtection)( case class ApiBranch(name: String, commit: ApiBranchCommit, protection: ApiBranchProtectionResponse)(
repositoryName: RepositoryName repositoryName: RepositoryName
) extends FieldSerializable { ) extends FieldSerializable {
val _links = val _links =

View File

@@ -0,0 +1,21 @@
package gitbucket.core.api
/** https://developer.github.com/v3/repos/#enabling-and-disabling-branch-protection */
case class ApiBranchProtectionRequest(
enabled: Boolean,
required_status_checks: Option[ApiBranchProtectionRequest.Status],
restrictions: Option[ApiBranchProtectionRequest.Restrictions],
enforce_admins: Option[Boolean]
)
object ApiBranchProtectionRequest {
/** form for enabling-and-disabling-branch-protection */
case class EnablingAndDisabling(protection: ApiBranchProtectionRequest)
case class Status(
contexts: Seq[String]
)
case class Restrictions(users: Seq[String])
}

View File

@@ -4,55 +4,68 @@ 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 ApiBranchProtectionResponse(
url: Option[ApiPath], // for output url: Option[ApiPath], // for output
enabled: Boolean, enabled: Boolean,
required_status_checks: Option[ApiBranchProtection.Status] required_status_checks: Option[ApiBranchProtectionResponse.Status],
restrictions: Option[ApiBranchProtectionResponse.Restrictions],
enforce_admins: Option[ApiBranchProtectionResponse.EnforceAdmins]
) { ) {
def status: ApiBranchProtection.Status = required_status_checks.getOrElse(ApiBranchProtection.statusNone) def status: ApiBranchProtectionResponse.Status =
required_status_checks.getOrElse(ApiBranchProtectionResponse.statusNone)
} }
object ApiBranchProtection { object ApiBranchProtectionResponse {
/** form for enabling-and-disabling-branch-protection */ case class EnforceAdmins(enabled: Boolean)
case class EnablingAndDisabling(protection: ApiBranchProtection)
def apply(info: ProtectedBranchService.ProtectedBranchInfo): ApiBranchProtection = // /** form for enabling-and-disabling-branch-protection */
ApiBranchProtection( // case class EnablingAndDisabling(protection: ApiBranchProtectionResponse)
def apply(info: ProtectedBranchService.ProtectedBranchInfo): ApiBranchProtectionResponse =
ApiBranchProtectionResponse(
url = Some( url = Some(
ApiPath( ApiPath(
s"/api/v3/repos/${info.owner}/${info.repository}/branches/${info.branch}/protection" 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 = info.contexts.map { contexts =>
Status( Status(
Some( Some(
ApiPath( ApiPath(
s"/api/v3/repos/${info.owner}/${info.repository}/branches/${info.branch}/protection/required_status_checks" s"/api/v3/repos/${info.owner}/${info.repository}/branches/${info.branch}/protection/required_status_checks"
) )
), ),
EnforcementLevel(info.enabled && info.contexts.nonEmpty, info.includeAdministrators), EnforcementLevel(info.enabled && info.contexts.nonEmpty, info.enforceAdmins),
info.contexts, contexts,
Some( Some(
ApiPath( ApiPath(
s"/api/v3/repos/${info.owner}/${info.repository}/branches/${info.branch}/protection/required_status_checks/contexts" s"/api/v3/repos/${info.owner}/${info.repository}/branches/${info.branch}/protection/required_status_checks/contexts"
) )
) )
) )
) },
restrictions = info.restrictionsUsers.map { restrictionsUsers =>
Restrictions(restrictionsUsers)
},
enforce_admins = if (info.enabled) Some(EnforceAdmins(info.enforceAdmins)) else None
) )
val statusNone = Status(None, Off, Seq.empty, None)
val statusNone: Status = Status(None, Off, Seq.empty, None)
case class Status( case class Status(
url: Option[ApiPath], // for output url: Option[ApiPath], // for output
enforcement_level: EnforcementLevel, enforcement_level: EnforcementLevel,
contexts: Seq[String], contexts: Seq[String],
contexts_url: Option[ApiPath] // for output 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")
case object Everyone extends EnforcementLevel("everyone") case object Everyone extends EnforcementLevel("everyone")
object EnforcementLevel { object EnforcementLevel {
def apply(enabled: Boolean, includeAdministrators: Boolean): EnforcementLevel = def apply(enabled: Boolean, includeAdministrators: Boolean): EnforcementLevel =
if (enabled) { if (enabled) {
@@ -66,16 +79,19 @@ object ApiBranchProtection {
} }
} }
implicit val enforcementLevelSerializer: CustomSerializer[EnforcementLevel] = new CustomSerializer[EnforcementLevel]( case class Restrictions(users: Seq[String])
format =>
implicit val enforcementLevelSerializer: CustomSerializer[EnforcementLevel] =
new CustomSerializer[EnforcementLevel](format =>
( (
{ {
case JString("off") => Off case JString("off") => Off
case JString("non_admins") => NonAdmins case JString("non_admins") => NonAdmins
case JString("everyone") => Everyone case JString("everyone") => Everyone
}, { },
case x: EnforcementLevel => JString(x.name) { case x: EnforcementLevel =>
JString(x.name)
} }
)
) )
)
} }

View File

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

View File

@@ -29,7 +29,7 @@ case class ApiCommit(
object ApiCommit { object ApiCommit {
def apply(git: Git, repositoryName: RepositoryName, commit: CommitInfo): ApiCommit = { def apply(git: Git, repositoryName: RepositoryName, commit: CommitInfo): ApiCommit = {
val diffs = JGitUtil.getDiffs(git, None, commit.id, false, false) val diffs = JGitUtil.getDiffs(git = git, from = None, to = commit.id, fetchContent = false, makePatch = false)
ApiCommit( ApiCommit(
id = commit.id, id = commit.id,
message = commit.fullMessage, message = commit.fullMessage,

View File

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

View File

@@ -22,16 +22,15 @@ object ApiContents {
ApiContents("dir", fileInfo.name, fileInfo.path, fileInfo.commitId, None, None)(repositoryName) ApiContents("dir", fileInfo.name, fileInfo.path, fileInfo.commitId, None, None)(repositoryName)
} else { } else {
content content
.map( .map(arr =>
arr => ApiContents(
ApiContents( "file",
"file", fileInfo.name,
fileInfo.name, fileInfo.path,
fileInfo.path, fileInfo.id.getName,
fileInfo.id.getName, Some(Base64.getEncoder.encodeToString(arr)),
Some(Base64.getEncoder.encodeToString(arr)), Some("base64")
Some("base64") )(repositoryName)
)(repositoryName)
) )
.getOrElse(ApiContents("file", fileInfo.name, fileInfo.path, fileInfo.commitId, None, None)(repositoryName)) .getOrElse(ApiContents("file", fileInfo.name, fileInfo.path, fileInfo.commitId, None, None)(repositoryName))
} }

View File

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

View File

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

View File

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

View File

@@ -21,7 +21,7 @@ case class ApiRepository(
val url = ApiPath(s"/api/v3/repos/${full_name}") val url = ApiPath(s"/api/v3/repos/${full_name}")
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("")) val ssh_url = Some(SshPath(s"/${full_name}.git"))
} }
object ApiRepository { object ApiRepository {
@@ -61,7 +61,7 @@ object ApiRepository {
watchers = 0, watchers = 0,
forks = 0, forks = 0,
`private` = false, `private` = false,
default_branch = "master", default_branch = "main",
owner = owner, owner = owner,
has_issues = true has_issues = true
) )

View File

@@ -0,0 +1,29 @@
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

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

View File

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

View File

@@ -38,23 +38,11 @@ class AccountController
with RequestCache with RequestCache
trait AccountControllerBase extends AccountManagementControllerBase { trait AccountControllerBase extends AccountManagementControllerBase {
self: AccountService self: AccountService & RepositoryService & ActivityService & WikiService & LabelsService & SshKeyService &
with RepositoryService GpgKeyService & OneselfAuthenticator & UsersAuthenticator & GroupManagerAuthenticator & ReadableUsersAuthenticator &
with ActivityService AccessTokenService & WebHookService & PrioritiesService & RepositoryCreationService =>
with WikiService
with LabelsService
with SshKeyService
with GpgKeyService
with OneselfAuthenticator
with UsersAuthenticator
with GroupManagerAuthenticator
with ReadableUsersAuthenticator
with AccessTokenService
with WebHookService
with PrioritiesService
with RepositoryCreationService =>
case class AccountNewForm( private case class AccountNewForm(
userName: String, userName: String,
password: String, password: String,
fullName: String, fullName: String,
@@ -65,7 +53,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
fileId: Option[String] fileId: Option[String]
) )
case class AccountEditForm( private case class AccountEditForm(
password: Option[String], password: Option[String],
fullName: String, fullName: String,
mailAddress: String, mailAddress: String,
@@ -76,15 +64,15 @@ trait AccountControllerBase extends AccountManagementControllerBase {
clearImage: Boolean clearImage: Boolean
) )
case class SshKeyForm(title: String, publicKey: String) private case class SshKeyForm(title: String, publicKey: String)
case class GpgKeyForm(title: String, publicKey: String) private case class GpgKeyForm(title: String, publicKey: String)
case class PersonalTokenForm(note: String) private case class PersonalTokenForm(note: String)
case class SyntaxHighlighterThemeForm(theme: String) private case class SyntaxHighlighterThemeForm(theme: String)
val newForm = mapping( private 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(40)))), "password" -> trim(label("Password", text(required, maxlength(40)))),
"fullName" -> trim(label("Full Name", text(required, maxlength(100)))), "fullName" -> trim(label("Full Name", text(required, maxlength(100)))),
@@ -97,7 +85,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
"fileId" -> trim(label("File ID", optional(text()))) "fileId" -> trim(label("File ID", optional(text())))
)(AccountNewForm.apply) )(AccountNewForm.apply)
val editForm = mapping( private val editForm = mapping(
"password" -> trim(label("Password", optional(text(maxlength(40))))), "password" -> trim(label("Password", optional(text(maxlength(40))))),
"fullName" -> trim(label("Full Name", text(required, maxlength(100)))), "fullName" -> trim(label("Full Name", text(required, maxlength(100)))),
"mailAddress" -> trim(label("Mail Address", text(required, maxlength(100), uniqueMailAddress("userName")))), "mailAddress" -> trim(label("Mail Address", text(required, maxlength(100), uniqueMailAddress("userName")))),
@@ -110,41 +98,41 @@ trait AccountControllerBase extends AccountManagementControllerBase {
"clearImage" -> trim(label("Clear image", boolean())) "clearImage" -> trim(label("Clear image", boolean()))
)(AccountEditForm.apply) )(AccountEditForm.apply)
val sshKeyForm = mapping( private val sshKeyForm = mapping(
"title" -> trim(label("Title", text(required, maxlength(100)))), "title" -> trim(label("Title", text(required, maxlength(100)))),
"publicKey" -> trim2(label("Key", text(required, validPublicKey))) "publicKey" -> trim2(label("Key", text(required, validPublicKey)))
)(SshKeyForm.apply) )(SshKeyForm.apply)
val gpgKeyForm = mapping( private val gpgKeyForm = mapping(
"title" -> trim(label("Title", text(required, maxlength(100)))), "title" -> trim(label("Title", text(required, maxlength(100)))),
"publicKey" -> label("Key", text(required, validGpgPublicKey)) "publicKey" -> label("Key", text(required, validGpgPublicKey))
)(GpgKeyForm.apply) )(GpgKeyForm.apply)
val personalTokenForm = mapping( private val personalTokenForm = mapping(
"note" -> trim(label("Token", text(required, maxlength(100)))) "note" -> trim(label("Token", text(required, maxlength(100))))
)(PersonalTokenForm.apply) )(PersonalTokenForm.apply)
val syntaxHighlighterThemeForm = mapping( private val syntaxHighlighterThemeForm = mapping(
"highlighterTheme" -> trim(label("Theme", text(required))) "highlighterTheme" -> trim(label("Theme", text(required)))
)(SyntaxHighlighterThemeForm.apply) )(SyntaxHighlighterThemeForm.apply)
val resetPasswordEmailForm = mapping( private val resetPasswordEmailForm = mapping(
"mailAddress" -> trim(label("Email", text(required))) "mailAddress" -> trim(label("Email", text(required)))
)(ResetPasswordEmailForm.apply) )(ResetPasswordEmailForm.apply)
val resetPasswordForm = mapping( private val resetPasswordForm = mapping(
"token" -> trim(label("Token", text(required))), "token" -> trim(label("Token", text(required))),
"password" -> trim(label("Password", text(required, maxlength(40)))) "password" -> trim(label("Password", text(required, maxlength(40))))
)(ResetPasswordForm.apply) )(ResetPasswordForm.apply)
case class NewGroupForm( private case class NewGroupForm(
groupName: String, groupName: String,
description: Option[String], description: Option[String],
url: Option[String], url: Option[String],
fileId: Option[String], fileId: Option[String],
members: String members: String
) )
case class EditGroupForm( private case class EditGroupForm(
groupName: String, groupName: String,
description: Option[String], description: Option[String],
url: Option[String], url: Option[String],
@@ -152,15 +140,15 @@ trait AccountControllerBase extends AccountManagementControllerBase {
members: String, members: String,
clearImage: Boolean clearImage: Boolean
) )
case class ResetPasswordEmailForm( private case class ResetPasswordEmailForm(
mailAddress: String mailAddress: String
) )
case class ResetPasswordForm( private case class ResetPasswordForm(
token: String, token: String,
password: String password: String
) )
val newGroupForm = mapping( private val newGroupForm = mapping(
"groupName" -> trim(label("Group name", text(required, maxlength(100), identifier, uniqueUserName, reservedNames))), "groupName" -> trim(label("Group name", text(required, maxlength(100), identifier, uniqueUserName, reservedNames))),
"description" -> trim(label("Group description", optional(text()))), "description" -> trim(label("Group description", optional(text()))),
"url" -> trim(label("URL", optional(text(maxlength(200))))), "url" -> trim(label("URL", optional(text(maxlength(200))))),
@@ -168,7 +156,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
"members" -> trim(label("Members", text(required, members))) "members" -> trim(label("Members", text(required, members)))
)(NewGroupForm.apply) )(NewGroupForm.apply)
val editGroupForm = mapping( private val editGroupForm = mapping(
"groupName" -> trim(label("Group name", text(required, maxlength(100), identifier))), "groupName" -> trim(label("Group name", text(required, maxlength(100), identifier))),
"description" -> trim(label("Group description", optional(text()))), "description" -> trim(label("Group description", optional(text()))),
"url" -> trim(label("URL", optional(text(maxlength(200))))), "url" -> trim(label("URL", optional(text(maxlength(200))))),
@@ -177,7 +165,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
"clearImage" -> trim(label("Clear image", boolean())) "clearImage" -> trim(label("Clear image", boolean()))
)(EditGroupForm.apply) )(EditGroupForm.apply)
case class RepositoryCreationForm( private case class RepositoryCreationForm(
owner: String, owner: String,
name: String, name: String,
description: Option[String], description: Option[String],
@@ -185,9 +173,8 @@ trait AccountControllerBase extends AccountManagementControllerBase {
initOption: String, initOption: String,
sourceUrl: Option[String] sourceUrl: Option[String]
) )
case class ForkRepositoryForm(owner: String, name: String)
val newRepositoryForm = mapping( private val newRepositoryForm = mapping(
"owner" -> trim(label("Owner", text(required, maxlength(100), identifier, existsAccount))), "owner" -> trim(label("Owner", text(required, maxlength(100), identifier, existsAccount))),
"name" -> trim(label("Repository name", text(required, maxlength(100), repository, uniqueRepository))), "name" -> trim(label("Repository name", text(required, maxlength(100), repository, uniqueRepository))),
"description" -> trim(label("Description", optional(text()))), "description" -> trim(label("Description", optional(text()))),
@@ -196,34 +183,27 @@ trait AccountControllerBase extends AccountManagementControllerBase {
"sourceUrl" -> trim(label("Source URL", optionalRequired(_.value("initOption") == "COPY", text()))) "sourceUrl" -> trim(label("Source URL", optionalRequired(_.value("initOption") == "COPY", text())))
)(RepositoryCreationForm.apply) )(RepositoryCreationForm.apply)
val forkRepositoryForm = mapping( private case class AccountForm(accountName: String)
"owner" -> trim(label("Repository owner", text(required))),
"name" -> trim(label("Repository name", text(required)))
)(ForkRepositoryForm.apply)
case class AccountForm(accountName: String) private val accountForm = mapping(
val accountForm = mapping(
"account" -> trim(label("Group/User name", text(required, validAccountName))) "account" -> trim(label("Group/User name", text(required, validAccountName)))
)(AccountForm.apply) )(AccountForm.apply)
// for account web hook url addition. // for account web hook url addition.
case class AccountWebHookForm( private case class AccountWebHookForm(
url: String, url: String,
events: Set[WebHook.Event], events: Set[WebHook.Event],
ctype: WebHookContentType, ctype: WebHookContentType,
token: Option[String] token: Option[String]
) )
def accountWebHookForm(update: Boolean) = private def accountWebHookForm(update: Boolean) =
mapping( mapping(
"url" -> trim(label("url", text(required, accountWebHook(update)))), "url" -> trim(label("url", text(required, accountWebHook(update)))),
"events" -> accountWebhookEvents, "events" -> accountWebhookEvents,
"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) => AccountWebHookForm(url, events, WebHookContentType.valueOf(ctype), token))
(url, events, ctype, token) => AccountWebHookForm(url, events, WebHookContentType.valueOf(ctype), token)
)
/** /**
* Provides duplication check for web hook url. duplicated from RepositorySettingsController.scala * Provides duplication check for web hook url. duplicated from RepositorySettingsController.scala
@@ -268,12 +248,12 @@ trait AccountControllerBase extends AccountManagementControllerBase {
gitbucket.core.account.html.activity( gitbucket.core.account.html.activity(
account, account,
if (account.isGroupAccount) Nil else getGroupsByUserName(userName), if (account.isGroupAccount) Nil else getGroupsByUserName(userName),
getActivitiesByUser(userName, true), getActivitiesByUser(userName, publicOnly = true),
extraMailAddresses extraMailAddresses
) )
// Members // Members
case "members" if (account.isGroupAccount) => { case "members" if account.isGroupAccount =>
val members = getGroupMembers(account.userName) val members = getGroupMembers(account.userName)
gitbucket.core.account.html.members( gitbucket.core.account.html.members(
account, account,
@@ -281,10 +261,9 @@ trait AccountControllerBase extends AccountManagementControllerBase {
extraMailAddresses, extraMailAddresses,
isGroupManager(context.loginAccount, members) isGroupManager(context.loginAccount, members)
) )
}
// Repositories // Repositories
case _ => { case _ =>
val members = getGroupMembers(account.userName) val members = getGroupMembers(account.userName)
gitbucket.core.account.html.repositories( gitbucket.core.account.html.repositories(
account, account,
@@ -293,7 +272,6 @@ trait AccountControllerBase extends AccountManagementControllerBase {
extraMailAddresses, extraMailAddresses,
isGroupManager(context.loginAccount, members) isGroupManager(context.loginAccount, members)
) )
}
} }
} getOrElse NotFound() } getOrElse NotFound()
} }
@@ -301,7 +279,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
get("/:userName.atom") { get("/:userName.atom") {
val userName = params("userName") val userName = params("userName")
contentType = "application/atom+xml; type=feed" contentType = "application/atom+xml; type=feed"
helper.xml.feed(getActivitiesByUser(userName, true)) helper.xml.feed(getActivitiesByUser(userName, publicOnly = true))
} }
get("/:userName.keys") { get("/:userName.keys") {
@@ -346,22 +324,21 @@ trait AccountControllerBase extends AccountManagementControllerBase {
post("/:userName/_edit", editForm)(oneselfOnly { form => post("/:userName/_edit", editForm)(oneselfOnly { form =>
val userName = params("userName") val userName = params("userName")
getAccountByUserName(userName).map { getAccountByUserName(userName).map { account =>
account => updateAccount(
updateAccount( account.copy(
account.copy( password = form.password.map(pbkdf2_sha256).getOrElse(account.password),
password = form.password.map(pbkdf2_sha256).getOrElse(account.password), fullName = form.fullName,
fullName = form.fullName, mailAddress = form.mailAddress,
mailAddress = form.mailAddress, description = form.description,
description = form.description, url = form.url
url = form.url
)
) )
)
updateImage(userName, form.fileId, form.clearImage) updateImage(userName, form.fileId, form.clearImage)
updateAccountExtraMailAddresses(userName, form.extraMailAddresses.filter(_ != "")) updateAccountExtraMailAddresses(userName, form.extraMailAddresses.filter(_ != ""))
flash.update("info", "Account information has been updated.") flash.update("info", "Account information has been updated.")
redirect(s"/${userName}/_edit") redirect(s"/$userName/_edit")
} getOrElse NotFound() } getOrElse NotFound()
}) })
@@ -369,12 +346,11 @@ trait AccountControllerBase extends AccountManagementControllerBase {
get("/:userName/_delete")(oneselfOnly { get("/:userName/_delete")(oneselfOnly {
val userName = params("userName") val userName = params("userName")
getAccountByUserName(userName, true).map { getAccountByUserName(userName, includeRemoved = true).map { account =>
account => if (isLastAdministrator(account)) {
if (isLastAdministrator(account)) { flash.update("error", "Account can't be removed because this is last one administrator.")
flash.update("error", "Account can't be removed because this is last one administrator.") redirect(s"/$userName/_edit")
redirect(s"/${userName}/_edit") } else {
} else {
// // Remove repositories // // Remove repositories
// getRepositoryNamesOfUser(userName).foreach { repositoryName => // getRepositoryNamesOfUser(userName).foreach { repositoryName =>
// deleteRepository(userName, repositoryName) // deleteRepository(userName, repositoryName)
@@ -382,10 +358,10 @@ trait AccountControllerBase extends AccountManagementControllerBase {
// FileUtils.deleteDirectory(getWikiRepositoryDir(userName, repositoryName)) // FileUtils.deleteDirectory(getWikiRepositoryDir(userName, repositoryName))
// FileUtils.deleteDirectory(getTemporaryDir(userName, repositoryName)) // FileUtils.deleteDirectory(getTemporaryDir(userName, repositoryName))
// } // }
suspendAccount(account) suspendAccount(account)
session.invalidate session.invalidate()
redirect("/") redirect("/")
} }
} getOrElse NotFound() } getOrElse NotFound()
}) })
@@ -399,20 +375,20 @@ trait AccountControllerBase extends AccountManagementControllerBase {
post("/:userName/_ssh", sshKeyForm)(oneselfOnly { form => post("/:userName/_ssh", sshKeyForm)(oneselfOnly { form =>
val userName = params("userName") val userName = params("userName")
addPublicKey(userName, form.title, form.publicKey) addPublicKey(userName, form.title, form.publicKey)
redirect(s"/${userName}/_ssh") redirect(s"/$userName/_ssh")
}) })
get("/:userName/_ssh/delete/:id")(oneselfOnly { get("/:userName/_ssh/delete/:id")(oneselfOnly {
val userName = params("userName") val userName = params("userName")
val sshKeyId = params("id").toInt val sshKeyId = params("id").toInt
deletePublicKey(userName, sshKeyId) deletePublicKey(userName, sshKeyId)
redirect(s"/${userName}/_ssh") redirect(s"/$userName/_ssh")
}) })
get("/:userName/_gpg")(oneselfOnly { get("/:userName/_gpg")(oneselfOnly {
val userName = params("userName") val userName = params("userName")
getAccountByUserName(userName).map { x => getAccountByUserName(userName).map { x =>
//html.ssh(x, getPublicKeys(x.userName)) // html.ssh(x, getPublicKeys(x.userName))
html.gpg(x, getGpgPublicKeys(x.userName)) html.gpg(x, getGpgPublicKeys(x.userName))
} getOrElse NotFound() } getOrElse NotFound()
}) })
@@ -420,14 +396,14 @@ trait AccountControllerBase extends AccountManagementControllerBase {
post("/:userName/_gpg", gpgKeyForm)(oneselfOnly { form => post("/:userName/_gpg", gpgKeyForm)(oneselfOnly { form =>
val userName = params("userName") val userName = params("userName")
addGpgPublicKey(userName, form.title, form.publicKey) addGpgPublicKey(userName, form.title, form.publicKey)
redirect(s"/${userName}/_gpg") redirect(s"/$userName/_gpg")
}) })
get("/:userName/_gpg/delete/:id")(oneselfOnly { get("/:userName/_gpg/delete/:id")(oneselfOnly {
val userName = params("userName") val userName = params("userName")
val keyId = params("id").toInt val keyId = params("id").toInt
deleteGpgPublicKey(userName, keyId) deleteGpgPublicKey(userName, keyId)
redirect(s"/${userName}/_gpg") redirect(s"/$userName/_gpg")
}) })
get("/:userName/_application")(oneselfOnly { get("/:userName/_application")(oneselfOnly {
@@ -435,13 +411,12 @@ trait AccountControllerBase extends AccountManagementControllerBase {
getAccountByUserName(userName).map { x => getAccountByUserName(userName).map { x =>
var tokens = getAccessTokens(x.userName) var tokens = getAccessTokens(x.userName)
val generatedToken = flash.get("generatedToken") match { val generatedToken = flash.get("generatedToken") match {
case Some((tokenId: Int, token: String)) => { case Some((tokenId: Int, token: String)) =>
val gt = tokens.find(_.accessTokenId == tokenId) val gt = tokens.find(_.accessTokenId == tokenId)
gt.map { t => gt.map { t =>
tokens = tokens.filterNot(_ == t) tokens = tokens.filterNot(_ == t)
(t, token) (t, token)
} }
}
case _ => None case _ => None
} }
html.application(x, tokens, generatedToken) html.application(x, tokens, generatedToken)
@@ -450,18 +425,18 @@ trait AccountControllerBase extends AccountManagementControllerBase {
post("/:userName/_personalToken", personalTokenForm)(oneselfOnly { form => post("/:userName/_personalToken", personalTokenForm)(oneselfOnly { form =>
val userName = params("userName") val userName = params("userName")
getAccountByUserName(userName).foreach { x => getAccountByUserName(userName).foreach { _ =>
val (tokenId, token) = generateAccessToken(userName, form.note) val (tokenId, token) = generateAccessToken(userName, form.note)
flash.update("generatedToken", (tokenId, token)) flash.update("generatedToken", (tokenId, token))
} }
redirect(s"/${userName}/_application") redirect(s"/$userName/_application")
}) })
get("/:userName/_personalToken/delete/:id")(oneselfOnly { get("/:userName/_personalToken/delete/:id")(oneselfOnly {
val userName = params("userName") val userName = params("userName")
val tokenId = params("id").toInt val tokenId = params("id").toInt
deleteAccessToken(userName, tokenId) deleteAccessToken(userName, tokenId)
redirect(s"/${userName}/_application") redirect(s"/$userName/_application")
}) })
/** /**
@@ -484,7 +459,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
post("/:userName/_preferences/highlighter", syntaxHighlighterThemeForm)(oneselfOnly { form => post("/:userName/_preferences/highlighter", syntaxHighlighterThemeForm)(oneselfOnly { form =>
val userName = params("userName") val userName = params("userName")
addOrUpdateAccountPreference(userName, form.theme) addOrUpdateAccountPreference(userName, form.theme)
redirect(s"/${userName}/_preferences") redirect(s"/$userName/_preferences")
}) })
get("/:userName/_hooks")(managersOnly { get("/:userName/_hooks")(managersOnly {
@@ -501,7 +476,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
val userName = params("userName") val userName = params("userName")
getAccountByUserName(userName).map { account => getAccountByUserName(userName).map { account =>
val webhook = AccountWebHook(userName, "", WebHookContentType.FORM, None) val webhook = AccountWebHook(userName, "", WebHookContentType.FORM, None)
html.edithook(webhook, Set(WebHook.Push), account, true) html.edithook(webhook, Set(WebHook.Push), account, create = true)
} getOrElse NotFound() } getOrElse NotFound()
}) })
@@ -512,7 +487,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
val userName = params("userName") val userName = params("userName")
addAccountWebHook(userName, form.url, form.events, form.ctype, form.token) addAccountWebHook(userName, form.url, form.events, form.ctype, form.token)
flash.update("info", s"Webhook ${form.url} created") flash.update("info", s"Webhook ${form.url} created")
redirect(s"/${userName}/_hooks") redirect(s"/$userName/_hooks")
}) })
/** /**
@@ -522,7 +497,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
val userName = params("userName") val userName = params("userName")
deleteAccountWebHook(userName, params("url")) deleteAccountWebHook(userName, params("url"))
flash.update("info", s"Webhook ${params("url")} deleted") flash.update("info", s"Webhook ${params("url")} deleted")
redirect(s"/${userName}/_hooks") redirect(s"/$userName/_hooks")
}) })
/** /**
@@ -531,9 +506,8 @@ trait AccountControllerBase extends AccountManagementControllerBase {
get("/:userName/_hooks/edit")(managersOnly { get("/:userName/_hooks/edit")(managersOnly {
val userName = params("userName") val userName = params("userName")
getAccountByUserName(userName).flatMap { account => getAccountByUserName(userName).flatMap { account =>
getAccountWebHook(userName, params("url")).map { getAccountWebHook(userName, params("url")).map { case (webhook, events) =>
case (webhook, events) => html.edithook(webhook, events, account, create = false)
html.edithook(webhook, events, account, false)
} }
} getOrElse NotFound() } getOrElse NotFound()
}) })
@@ -545,7 +519,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
val userName = params("userName") val userName = params("userName")
updateAccountWebHook(userName, form.url, form.events, form.ctype, form.token) updateAccountWebHook(userName, form.url, form.events, form.ctype, form.token)
flash.update("info", s"webhook ${form.url} updated") flash.update("info", s"webhook ${form.url} updated")
redirect(s"/${userName}/_hooks") redirect(s"/$userName/_hooks")
}) })
/** /**
@@ -553,8 +527,8 @@ trait AccountControllerBase extends AccountManagementControllerBase {
*/ */
ajaxPost("/:userName/_hooks/test")(managersOnly { ajaxPost("/:userName/_hooks/test")(managersOnly {
// TODO Is it possible to merge with [[RepositorySettingsController.ajaxPost]]? // TODO Is it possible to merge with [[RepositorySettingsController.ajaxPost]]?
import scala.concurrent.duration._ import scala.concurrent.duration.*
import scala.concurrent._ import scala.concurrent.*
import scala.util.control.NonFatal import scala.util.control.NonFatal
import org.apache.http.util.EntityUtils import org.apache.http.util.EntityUtils
import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.ExecutionContext.Implicits.global
@@ -578,10 +552,10 @@ trait AccountControllerBase extends AccountManagementControllerBase {
callWebHook(WebHook.Push, List(dummyWebHookInfo), dummyPayload, context.settings).head callWebHook(WebHook.Push, List(dummyWebHookInfo), dummyPayload, context.settings).head
val toErrorMap: PartialFunction[Throwable, Map[String, String]] = { val toErrorMap: PartialFunction[Throwable, Map[String, String]] = {
case e: java.net.UnknownHostException => Map("error" -> ("Unknown host " + e.getMessage)) case e: java.net.UnknownHostException => Map("error" -> s"Unknown host ${e.getMessage}")
case e: java.lang.IllegalArgumentException => Map("error" -> ("invalid url")) case _: java.lang.IllegalArgumentException => Map("error" -> "invalid url")
case e: org.apache.http.client.ClientProtocolException => Map("error" -> ("invalid url")) case _: org.apache.http.client.ClientProtocolException => Map("error" -> "invalid url")
case NonFatal(e) => Map("error" -> (s"${e.getClass} ${e.getMessage}")) case NonFatal(e) => Map("error" -> s"${e.getClass} ${e.getMessage}")
} }
contentType = formats("json") contentType = formats("json")
@@ -590,11 +564,10 @@ trait AccountControllerBase extends AccountManagementControllerBase {
"url" -> url, "url" -> url,
"request" -> Await.result( "request" -> Await.result(
reqFuture reqFuture
.map( .map(req =>
req => Map(
Map( "headers" -> _headers(req.getAllHeaders),
"headers" -> _headers(req.getAllHeaders), "payload" -> json
"payload" -> json
) )
) )
.recover(toErrorMap), .recover(toErrorMap),
@@ -602,12 +575,11 @@ trait AccountControllerBase extends AccountManagementControllerBase {
), ),
"response" -> Await.result( "response" -> Await.result(
resFuture resFuture
.map( .map(res =>
res => Map(
Map( "status" -> res.getStatusLine,
"status" -> res.getStatusLine(), "body" -> EntityUtils.toString(res.getEntity),
"body" -> EntityUtils.toString(res.getEntity()), "headers" -> _headers(res.getAllHeaders)
"headers" -> _headers(res.getAllHeaders())
) )
) )
.recover(toErrorMap), .recover(toErrorMap),
@@ -634,11 +606,11 @@ trait AccountControllerBase extends AccountManagementControllerBase {
pbkdf2_sha256(form.password), pbkdf2_sha256(form.password),
form.fullName, form.fullName,
form.mailAddress, form.mailAddress,
false, isAdmin = false,
form.description, form.description,
form.url form.url
) )
updateImage(form.userName, form.fileId, false) updateImage(form.userName, form.fileId, clearImage = false)
updateAccountExtraMailAddresses(form.userName, form.extraMailAddresses.filter(_ != "")) updateAccountExtraMailAddresses(form.userName, form.extraMailAddresses.filter(_ != ""))
redirect("/signin") redirect("/signin")
} else NotFound() } else NotFound()
@@ -663,7 +635,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|You requested to reset the password for your GitBucket account. |You requested to reset the password for your GitBucket account.
|If you are not sure about the request, you can ignore this email. |If you are not sure about the request, you can ignore this email.
|Otherwise, click the following link to set the new password: |Otherwise, click the following link to set the new password:
|${context.baseUrl}/reset/form/${token} |${context.baseUrl}/reset/form/$token
|""".stripMargin |""".stripMargin
) )
} }
@@ -703,7 +675,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
get("/groups/new")(usersOnly { get("/groups/new")(usersOnly {
context.withLoginAccount { loginAccount => context.withLoginAccount { loginAccount =>
html.creategroup(List(GroupMember("", loginAccount.userName, true))) html.creategroup(List(GroupMember("", loginAccount.userName, isManager = true)))
} }
}) })
@@ -720,13 +692,13 @@ trait AccountControllerBase extends AccountManagementControllerBase {
} }
.toList .toList
) )
updateImage(form.groupName, form.fileId, false) updateImage(form.groupName, form.fileId, clearImage = false)
redirect(s"/${form.groupName}") redirect(s"/${form.groupName}")
}) })
get("/:groupName/_editgroup")(managersOnly { get("/:groupName/_editgroup")(managersOnly {
val groupName = params("groupName") val groupName = params("groupName")
getAccountByUserName(groupName, true).map { account => getAccountByUserName(groupName, includeRemoved = true).map { account =>
html.editgroup(account, getGroupMembers(groupName), flash.get("info")) html.editgroup(account, getGroupMembers(groupName), flash.get("info"))
} getOrElse NotFound() } getOrElse NotFound()
}) })
@@ -736,8 +708,8 @@ trait AccountControllerBase extends AccountManagementControllerBase {
// Remove from GROUP_MEMBER // Remove from GROUP_MEMBER
updateGroupMembers(groupName, Nil) updateGroupMembers(groupName, Nil)
// Disable group // Disable group
getAccountByUserName(groupName, false).foreach { account => getAccountByUserName(groupName, includeRemoved = false).foreach { account =>
updateGroup(groupName, account.description, account.url, true) updateGroup(groupName, account.description, account.url, removed = true)
} }
// // Remove repositories // // Remove repositories
// getRepositoryNamesOfUser(groupName).foreach { repositoryName => // getRepositoryNamesOfUser(groupName).foreach { repositoryName =>
@@ -760,8 +732,8 @@ trait AccountControllerBase extends AccountManagementControllerBase {
} }
.toList .toList
getAccountByUserName(groupName, true).map { account => getAccountByUserName(groupName, includeRemoved = true).map { _ =>
updateGroup(groupName, form.description, form.url, false) updateGroup(groupName, form.description, form.url, removed = false)
// Update GROUP_MEMBER // Update GROUP_MEMBER
updateGroupMembers(form.groupName, members) updateGroupMembers(form.groupName, members)
@@ -776,7 +748,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
updateImage(form.groupName, form.fileId, form.clearImage) updateImage(form.groupName, form.fileId, form.clearImage)
flash.update("info", "Account information has been updated.") flash.update("info", "Account information has been updated.")
redirect(s"/${groupName}/_editgroup") redirect(s"/$groupName/_editgroup")
} getOrElse NotFound() } getOrElse NotFound()
}) })
@@ -794,82 +766,83 @@ trait AccountControllerBase extends AccountManagementControllerBase {
* Create new repository. * Create new repository.
*/ */
post("/new", newRepositoryForm)(usersOnly { form => post("/new", newRepositoryForm)(usersOnly { form =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => if (context.settings.basicBehavior.repositoryOperation.create || loginAccount.isAdmin) {
if (context.settings.basicBehavior.repositoryOperation.create || loginAccount.isAdmin) { LockUtil.lock(s"${form.owner}/${form.name}") {
LockUtil.lock(s"${form.owner}/${form.name}") { if (getRepository(form.owner, form.name).isDefined) {
if (getRepository(form.owner, form.name).isDefined) { // redirect to the repository if repository already exists
// redirect to the repository if repository already exists redirect(s"/${form.owner}/${form.name}")
redirect(s"/${form.owner}/${form.name}") } else if (!canCreateRepository(form.owner, loginAccount)) {
} else if (!canCreateRepository(form.owner, loginAccount)) { // Permission error
// Permission error Forbidden()
Forbidden() } else {
} else { // create repository asynchronously
// create repository asynchronously createRepository(
createRepository( loginAccount,
loginAccount, form.owner,
form.owner, form.name,
form.name, form.description,
form.description, form.isPrivate,
form.isPrivate, form.initOption,
form.initOption, form.sourceUrl,
form.sourceUrl context.settings.defaultBranch
) )
// redirect to the repository // redirect to the repository
redirect(s"/${form.owner}/${form.name}") redirect(s"/${form.owner}/${form.name}")
}
} }
} else Forbidden() }
} else Forbidden()
} }
}) })
get("/:owner/:repository/fork")(readableUsersOnly { repository => get("/:owner/:repository/fork")(readableUsersOnly { repository =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => if (
if (repository.repository.options.allowFork && (context.settings.basicBehavior.repositoryOperation.fork || loginAccount.isAdmin)) { repository.repository.options.allowFork && (context.settings.basicBehavior.repositoryOperation.fork || loginAccount.isAdmin)
val loginUserName = loginAccount.userName ) {
val groups = getGroupsByUserName(loginUserName) val loginUserName = loginAccount.userName
groups match { val groups = getGroupsByUserName(loginUserName)
case _: List[String] => groups match {
val managerPermissions = groups.map { group => case _: List[String] =>
val members = getGroupMembers(group) val managerPermissions = groups.map { group =>
context.loginAccount.exists( val members = getGroupMembers(group)
x => context.loginAccount.exists(x =>
members.exists { member => members.exists { member =>
member.userName == x.userName && member.isManager member.userName == x.userName && member.isManager
} }
)
}
helper.html.forkrepository(
repository,
(groups zip managerPermissions).sortBy(_._1)
) )
case _ => redirect(s"/${loginUserName}") }
} helper.html.forkrepository(
} else BadRequest() repository,
(groups zip managerPermissions).sortBy(_._1)
)
case _ => redirect(s"/$loginUserName")
}
} else BadRequest()
} }
}) })
post("/:owner/:repository/fork", accountForm)(readableUsersOnly { (form, repository) => post("/:owner/:repository/fork", accountForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => if (
if (repository.repository.options.allowFork && (context.settings.basicBehavior.repositoryOperation.fork || loginAccount.isAdmin)) { repository.repository.options.allowFork && (context.settings.basicBehavior.repositoryOperation.fork || loginAccount.isAdmin)
val loginUserName = loginAccount.userName ) {
val accountName = form.accountName val loginUserName = loginAccount.userName
val accountName = form.accountName
if (getRepository(accountName, repository.name).isDefined) { if (getRepository(accountName, repository.name).isDefined) {
// redirect to the repository if repository already exists // redirect to the repository if repository already exists
redirect(s"/${accountName}/${repository.name}") redirect(s"/$accountName/${repository.name}")
} else if (!canCreateRepository(accountName, loginAccount)) { } else if (!canCreateRepository(accountName, loginAccount)) {
// Permission error // Permission error
Forbidden() Forbidden()
} else { } else {
// fork repository asynchronously // fork repository asynchronously
forkRepository(accountName, repository, loginUserName) forkRepository(accountName, repository, loginUserName)
// redirect to the repository // redirect to the repository
redirect(s"/${accountName}/${repository.name}") redirect(s"/$accountName/${repository.name}")
} }
} else Forbidden() } else Forbidden()
} }
}) })
@@ -896,9 +869,11 @@ trait AccountControllerBase extends AccountManagementControllerBase {
private def members: Constraint = new Constraint() { private def members: 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 (value.split(",").exists { if (
_.split(":") match { case Array(userName, isManager) => isManager.toBoolean } value.split(",").exists {
}) None _.split(":") match { case Array(userName, isManager) => isManager.toBoolean }
}
) None
else Some("Must select one manager at least.") else Some("Must select one manager at least.")
} }
} }

View File

@@ -1,10 +1,10 @@
package gitbucket.core.controller package gitbucket.core.controller
import gitbucket.core.api._ import gitbucket.core.api.*
import gitbucket.core.controller.api._ import gitbucket.core.controller.api.*
import gitbucket.core.service._ import gitbucket.core.service.*
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits.*
import gitbucket.core.util._ import gitbucket.core.util.*
import gitbucket.core.plugin.PluginRegistry import gitbucket.core.plugin.PluginRegistry
class ApiController class ApiController
@@ -100,16 +100,4 @@ trait ApiControllerBase extends ControllerBase {
get("/api/v3/gitbucket/plugins") { get("/api/v3/gitbucket/plugins") {
PluginRegistry().getPlugins().map { ApiPlugin(_) } PluginRegistry().getPlugins().map { ApiPlugin(_) }
} }
/**
* https://docs.github.com/en/enterprise-server@2.21/rest/reference/meta#get-github-enterprise-server-meta-information
*/
get("/api/v3/meta") {
JsonFormat(
Map(
"https://api.github.com/meta" -> context.loginAccount.isDefined,
"installed_version" -> "2.21.0"
)
)
}
} }

View File

@@ -1,22 +1,21 @@
package gitbucket.core.controller package gitbucket.core.controller
import java.io.{File, FileInputStream} import java.io.{File, FileInputStream, FileOutputStream}
import gitbucket.core.api.{ApiError, JsonFormat} import gitbucket.core.api.{ApiError, JsonFormat}
import gitbucket.core.model.Account import gitbucket.core.model.Account
import gitbucket.core.service.{AccountService, RepositoryService, SystemSettingsService} import gitbucket.core.service.{AccountService, RepositoryService, SystemSettingsService}
import gitbucket.core.util.SyntaxSugars._ import gitbucket.core.util.SyntaxSugars.*
import gitbucket.core.util.Directory._ import gitbucket.core.util.Directory.*
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits.*
import gitbucket.core.util._ import gitbucket.core.util.*
import org.json4s._ import org.json4s.*
import org.scalatra._ import org.scalatra.{MultiParams, *}
import org.scalatra.i18n._ import org.scalatra.i18n.*
import org.scalatra.json._ import org.scalatra.json.*
import org.scalatra.forms._ import org.scalatra.forms.*
import javax.servlet.http.{HttpServletRequest, HttpServletResponse} import javax.servlet.http.{HttpServletRequest, HttpServletResponse}
import javax.servlet.{FilterChain, ServletRequest, ServletResponse} import javax.servlet.{FilterChain, ServletRequest, ServletResponse}
import is.tagomor.woothee.Classifier import is.tagomor.woothee.Classifier
import scala.util.Try import scala.util.Try
@@ -25,10 +24,13 @@ import net.coobird.thumbnailator.Thumbnails
import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.ObjectId import org.eclipse.jgit.lib.ObjectId
import org.eclipse.jgit.revwalk.RevCommit import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.treewalk._ import org.eclipse.jgit.treewalk.*
import org.apache.commons.io.IOUtils import org.apache.commons.io.IOUtils
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import org.json4s.Formats import org.json4s.Formats
import org.json4s.jackson.Serialization
import java.nio.charset.StandardCharsets
/** /**
* Provides generic features for controller implementations. * Provides generic features for controller implementations.
@@ -46,11 +48,21 @@ abstract class ControllerBase
implicit val jsonFormats: Formats = gitbucket.core.api.JsonFormat.jsonFormats implicit val jsonFormats: Formats = gitbucket.core.api.JsonFormat.jsonFormats
private case class HttpException(status: Int) extends RuntimeException
before("/api/v3/*") { before("/api/v3/*") {
contentType = formats("json") contentType = formats("json")
request.setAttribute(Keys.Request.APIv3, true) request.setAttribute(Keys.Request.APIv3, true)
} }
override def multiParams(implicit request: HttpServletRequest): MultiParams = {
try {
super.multiParams
} catch {
case _: Exception => throw HttpException(400)
}
}
override def requestPath(uri: String, idx: Int): String = { override def requestPath(uri: String, idx: Int): String = {
val path = super.requestPath(uri, idx) val path = super.requestPath(uri, idx)
if (path != "/" && path.endsWith("/")) { if (path != "/" && path.endsWith("/")) {
@@ -84,17 +96,24 @@ abstract class ControllerBase
*/ */
implicit def context: Context = { implicit def context: Context = {
contextCache.get match { contextCache.get match {
case null => { case null =>
val context = Context(loadSystemSettings(), LoginAccount, request) val context = Context(loadSystemSettings(), LoginAccount, request)
contextCache.set(context) contextCache.set(context)
context context
}
case context => context case context => context
} }
} }
private def LoginAccount: Option[Account] = private def LoginAccount: Option[Account] = {
request.getAs[Account](Keys.Session.LoginAccount).orElse(session.getAs[Account](Keys.Session.LoginAccount)) request
.getAs[Account](Keys.Session.LoginAccount)
.orElse(session.getAs[Account](Keys.Session.LoginAccount))
.orElse {
if (isDevFeatureEnabled(DevFeatures.KeepSession)) {
getLoginAccountFromLocalFile()
} else None
}
}
def ajaxGet(path: String)(action: => Any): Route = def ajaxGet(path: String)(action: => Any): Route =
super.get(path) { super.get(path) {
@@ -120,7 +139,7 @@ abstract class ControllerBase
action(form) action(form)
} }
protected def NotFound() = protected def NotFound(): ActionResult =
if (request.hasAttribute(Keys.Request.Ajax)) { if (request.hasAttribute(Keys.Request.Ajax)) {
org.scalatra.NotFound() org.scalatra.NotFound()
} else if (request.hasAttribute(Keys.Request.APIv3)) { } else if (request.hasAttribute(Keys.Request.APIv3)) {
@@ -140,7 +159,7 @@ abstract class ControllerBase
} }
} }
protected def Unauthorized()(implicit context: Context) = protected def Unauthorized()(implicit context: Context): ActionResult =
if (request.hasAttribute(Keys.Request.Ajax)) { if (request.hasAttribute(Keys.Request.Ajax)) {
org.scalatra.Unauthorized() org.scalatra.Unauthorized()
} else if (request.hasAttribute(Keys.Request.APIv3)) { } else if (request.hasAttribute(Keys.Request.APIv3)) {
@@ -168,7 +187,9 @@ abstract class ControllerBase
} }
error { error {
case e => { case e: HttpException =>
ActionResult(e.status, (), Map.empty)
case e =>
logger.error(s"Catch unhandled error in request: ${request}", e) logger.error(s"Catch unhandled error in request: ${request}", e)
if (request.hasAttribute(Keys.Request.Ajax)) { if (request.hasAttribute(Keys.Request.Ajax)) {
org.scalatra.InternalServerError() org.scalatra.InternalServerError()
@@ -178,7 +199,6 @@ abstract class ControllerBase
} else { } else {
org.scalatra.InternalServerError(gitbucket.core.html.error("Internal Server Error", Some(e))) org.scalatra.InternalServerError(gitbucket.core.html.error("Internal Server Error", Some(e)))
} }
}
} }
override def url( override def url(
@@ -190,7 +210,7 @@ abstract class ControllerBase
withSessionId: Boolean = true withSessionId: Boolean = true
)(implicit request: HttpServletRequest, response: HttpServletResponse): String = )(implicit request: HttpServletRequest, response: HttpServletResponse): String =
if (path.startsWith("http")) path if (path.startsWith("http")) path
else baseUrl + super.url(path, params, false, false, false) else baseUrl + super.url(path, params, includeContextPath = false, includeServletPath = false, absolutize = false)
/** /**
* Extends scalatra-form's trim rule to eliminate CR and LF. * Extends scalatra-form's trim rule to eliminate CR and LF.
@@ -234,9 +254,9 @@ abstract class ControllerBase
protected def getPathObjectId(git: Git, path: String, revCommit: RevCommit): Option[ObjectId] = { protected def getPathObjectId(git: Git, path: String, revCommit: RevCommit): Option[ObjectId] = {
@scala.annotation.tailrec @scala.annotation.tailrec
def _getPathObjectId(path: String, walk: TreeWalk): Option[ObjectId] = walk.next match { def _getPathObjectId(path: String, walk: TreeWalk): Option[ObjectId] = walk.next match {
case true if (walk.getPathString == path) => Some(walk.getObjectId(0)) case true if walk.getPathString == path => Some(walk.getObjectId(0))
case true => _getPathObjectId(path, walk) case true => _getPathObjectId(path, walk)
case false => None case false => None
} }
Using.resource(new TreeWalk(git.getRepository)) { treeWalk => Using.resource(new TreeWalk(git.getRepository)) { treeWalk =>
@@ -277,6 +297,47 @@ abstract class ControllerBase
} }
} }
} }
protected object DevFeatures {
val KeepSession = "keep-session"
}
private val loginAccountFile = new File(".tmp/login_account.json")
protected def isDevFeatureEnabled(feature: String): Boolean = {
Option(System.getProperty("dev-features")).getOrElse("").split(",").map(_.trim).contains(feature)
}
protected def getLoginAccountFromLocalFile(): Option[Account] = {
if (isDevFeatureEnabled(DevFeatures.KeepSession)) {
if (loginAccountFile.exists()) {
Using.resource(new FileInputStream(loginAccountFile)) { in =>
val json = IOUtils.toString(in, StandardCharsets.UTF_8)
val account = parse(json).extract[Account]
session.setAttribute(Keys.Session.LoginAccount, account)
Some(parse(json).extract[Account])
}
} else None
} else None
}
protected def saveLoginAccountToLocalFile(account: Account): Unit = {
if (isDevFeatureEnabled(DevFeatures.KeepSession)) {
if (!loginAccountFile.getParentFile.exists()) {
loginAccountFile.getParentFile.mkdirs()
}
Using.resource(new FileOutputStream(loginAccountFile)) { in =>
in.write(Serialization.write(account).getBytes(StandardCharsets.UTF_8))
}
}
}
protected def deleteLoginAccountFromLocalFile(): Unit = {
if (isDevFeatureEnabled(DevFeatures.KeepSession)) {
loginAccountFile.delete()
}
}
} }
/** /**
@@ -287,18 +348,18 @@ case class Context(
loginAccount: Option[Account], loginAccount: Option[Account],
request: HttpServletRequest request: HttpServletRequest
) { ) {
val path = settings.baseUrl.getOrElse(request.getContextPath) val path: String = settings.baseUrl.getOrElse(request.getContextPath)
val currentPath = request.getRequestURI.substring(request.getContextPath.length) val currentPath: String = request.getRequestURI.substring(request.getContextPath.length)
val baseUrl = settings.baseUrl(request) val baseUrl: String = settings.baseUrl(request)
val host = new java.net.URL(baseUrl).getHost val host: String = new java.net.URI(baseUrl).toURL.getHost
val platform = request.getHeader("User-Agent") match { val platform: String = request.getHeader("User-Agent") match {
case null => null case null => null
case agent if agent.contains("Mac") => "mac" case agent if agent.contains("Mac") => "mac"
case agent if agent.contains("Linux") => "linux" case agent if agent.contains("Linux") => "linux"
case agent if agent.contains("Win") => "windows" case agent if agent.contains("Win") => "windows"
case _ => null case _ => null
} }
val sidebarCollapse = request.getSession.getAttribute("sidebar-collapse") != null val sidebarCollapse: Boolean = request.getSession.getAttribute("sidebar-collapse") != null
def withLoginAccount(f: Account => Any): Any = { def withLoginAccount(f: Account => Any): Any = {
loginAccount match { loginAccount match {
@@ -372,15 +433,16 @@ trait AccountManagementControllerBase extends ControllerBase {
messages: Messages messages: Messages
): Option[String] = { ): Option[String] = {
val extraMailAddresses = params.view.filterKeys(k => k.startsWith("extraMailAddresses")) val extraMailAddresses = params.view.filterKeys(k => k.startsWith("extraMailAddresses"))
if (extraMailAddresses.exists { if (
case (k, v) => extraMailAddresses.exists { case (k, v) =>
v.contains(value) v.contains(value)
}) { }
) {
Some("These mail addresses are duplicated.") Some("These mail addresses are duplicated.")
} else { } else {
getAccountByMailAddress(value, true) getAccountByMailAddress(value, includeRemoved = true)
.collect { .collect {
case x if paramName.isEmpty || Some(x.userName) != params.optionValue(paramName) => case x if paramName.isEmpty || !params.optionValue(paramName).contains(x.userName) =>
"Mail address is already registered." "Mail address is already registered."
} }
} }
@@ -395,22 +457,23 @@ trait AccountManagementControllerBase extends ControllerBase {
messages: Messages messages: Messages
): Option[String] = { ): Option[String] = {
val extraMailAddresses = params.view.filterKeys(k => k.startsWith("extraMailAddresses")) val extraMailAddresses = params.view.filterKeys(k => k.startsWith("extraMailAddresses"))
if (Some(value) == params.optionValue("mailAddress") || extraMailAddresses.count { if (
case (k, v) => params.optionValue("mailAddress").contains(value) || extraMailAddresses.count { case (k, v) =>
v.contains(value) v.contains(value)
} > 1) { } > 1
) {
Some("These mail addresses are duplicated.") Some("These mail addresses are duplicated.")
} else { } else {
getAccountByMailAddress(value, true) getAccountByMailAddress(value, includeRemoved = true)
.collect { .collect {
case x if paramName.isEmpty || Some(x.userName) != params.optionValue(paramName) => case x if paramName.isEmpty || !params.optionValue(paramName).contains(x.userName) =>
"Mail address is already registered." "Mail address is already registered."
} }
} }
} }
} }
val allReservedNames = Set( private val allReservedNames = Set(
"git", "git",
"admin", "admin",
"upload", "upload",
@@ -429,10 +492,9 @@ trait AccountManagementControllerBase extends ControllerBase {
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")
} else { } else {
None None
} }
} }
} }

View File

@@ -2,10 +2,11 @@ package gitbucket.core.controller
import gitbucket.core.dashboard.html import gitbucket.core.dashboard.html
import gitbucket.core.model.Account import gitbucket.core.model.Account
import gitbucket.core.service._ import gitbucket.core.service.*
import gitbucket.core.util.{Keys, UsersAuthenticator} import gitbucket.core.util.UsersAuthenticator
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits.*
import gitbucket.core.service.IssuesService._ import gitbucket.core.service.IssuesService.*
import gitbucket.core.service.ActivityService.*
class DashboardController class DashboardController
extends DashboardControllerBase extends DashboardControllerBase
@@ -27,12 +28,8 @@ class DashboardController
with RequestCache with RequestCache
trait DashboardControllerBase extends ControllerBase { trait DashboardControllerBase extends ControllerBase {
self: IssuesService self: IssuesService & PullRequestService & RepositoryService & AccountService & CommitStatusService &
with PullRequestService UsersAuthenticator =>
with RepositoryService
with AccountService
with CommitStatusService
with UsersAuthenticator =>
get("/dashboard/repos")(usersOnly { get("/dashboard/repos")(usersOnly {
context.withLoginAccount { loginAccount => context.withLoginAccount { loginAccount =>
@@ -42,7 +39,7 @@ trait DashboardControllerBase extends ControllerBase {
withoutPhysicalInfo = true, withoutPhysicalInfo = true,
limit = context.settings.basicBehavior.limitVisibleRepositories limit = context.settings.basicBehavior.limitVisibleRepositories
) )
html.repos(getGroupNames(loginAccount.userName), repos, repos) html.repos(getGroupNames(loginAccount.userName), repos, repos, isNewsFeedEnabled)
} }
}) })
@@ -94,7 +91,7 @@ trait DashboardControllerBase extends ControllerBase {
} }
}) })
private def getOrCreateCondition(key: String, filter: String, userName: String) = { private def getOrCreateCondition(filter: String, userName: String) = {
val condition = IssueSearchCondition(request) val condition = IssueSearchCondition(request)
filter match { filter match {
@@ -105,19 +102,19 @@ trait DashboardControllerBase extends ControllerBase {
} }
private def searchIssues(loginAccount: Account, filter: String) = { private def searchIssues(loginAccount: Account, filter: String) = {
import IssuesService._ import IssuesService.*
val userName = loginAccount.userName val userName = loginAccount.userName
val condition = getOrCreateCondition(Keys.Session.DashboardIssues, filter, userName) val condition = getOrCreateCondition(filter, userName)
val userRepos = getUserRepositories(userName, true).map(repo => repo.owner -> repo.name) val userRepos = getUserRepositories(userName, withoutPhysicalInfo = 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: _*) val issues = searchIssue(condition, IssueSearchOption.Issues, (page - 1) * IssueLimit, IssueLimit, userRepos*)
html.issues( html.issues(
issues.map(issue => (issue, None)), issues.map(issue => (issue, None)),
page, page,
countIssue(condition.copy(state = "open"), IssueSearchOption.Issues, userRepos: _*), countIssue(condition.copy(state = "open"), IssueSearchOption.Issues, userRepos*),
countIssue(condition.copy(state = "closed"), IssueSearchOption.Issues, userRepos: _*), countIssue(condition.copy(state = "closed"), IssueSearchOption.Issues, 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))
@@ -130,16 +127,17 @@ trait DashboardControllerBase extends ControllerBase {
None, None,
withoutPhysicalInfo = true, withoutPhysicalInfo = true,
limit = context.settings.basicBehavior.limitVisibleRepositories limit = context.settings.basicBehavior.limitVisibleRepositories
) ),
isNewsFeedEnabled
) )
} }
private def searchPullRequests(loginAccount: Account, filter: String) = { private def searchPullRequests(loginAccount: Account, filter: String) = {
import IssuesService._ import IssuesService.*
import PullRequestService._ import PullRequestService.*
val userName = loginAccount.userName val userName = loginAccount.userName
val condition = getOrCreateCondition(Keys.Session.DashboardPulls, filter, userName) val condition = getOrCreateCondition(filter, userName)
val allRepos = getAllRepositories(userName) val allRepos = getAllRepositories(userName)
val page = IssueSearchCondition.page(request) val page = IssueSearchCondition.page(request)
val issues = searchIssue( val issues = searchIssue(
@@ -147,7 +145,7 @@ trait DashboardControllerBase extends ControllerBase {
IssueSearchOption.PullRequests, IssueSearchOption.PullRequests,
(page - 1) * PullRequestLimit, (page - 1) * PullRequestLimit,
PullRequestLimit, PullRequestLimit,
allRepos: _* allRepos*
) )
val status = issues.map { issue => val status = issues.map { issue =>
issue.commitId.flatMap { commitId => issue.commitId.flatMap { commitId =>
@@ -158,8 +156,8 @@ trait DashboardControllerBase extends ControllerBase {
html.pulls( html.pulls(
issues.zip(status), issues.zip(status),
page, page,
countIssue(condition.copy(state = "open"), IssueSearchOption.PullRequests, allRepos: _*), countIssue(condition.copy(state = "open"), IssueSearchOption.PullRequests, allRepos*),
countIssue(condition.copy(state = "closed"), IssueSearchOption.PullRequests, allRepos: _*), countIssue(condition.copy(state = "closed"), IssueSearchOption.PullRequests, 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))
@@ -172,7 +170,8 @@ trait DashboardControllerBase extends ControllerBase {
None, None,
withoutPhysicalInfo = true, withoutPhysicalInfo = true,
limit = context.settings.basicBehavior.limitVisibleRepositories limit = context.settings.basicBehavior.limitVisibleRepositories
) ),
isNewsFeedEnabled
) )
} }

View File

@@ -75,59 +75,57 @@ class FileUploadController
post("/wiki/:owner/:repository") { post("/wiki/:owner/:repository") {
setMultipartConfig() setMultipartConfig()
// Don't accept not logged-in users // Don't accept not logged-in users
session.get(Keys.Session.LoginAccount).collect { session.get(Keys.Session.LoginAccount).collect { case loginAccount: Account =>
case loginAccount: Account => val owner = params("owner")
val owner = params("owner") val repository = params("repository")
val repository = params("repository")
// Check whether logged-in user is collaborator // Check whether logged-in user is collaborator
onlyWikiEditable(owner, repository, loginAccount) { onlyWikiEditable(owner, repository, loginAccount) {
execute( execute(
{ (file, fileId) => { (file, fileId) =>
val fileName = file.getName val fileName = file.getName
LockUtil.lock(s"${owner}/${repository}/wiki") { LockUtil.lock(s"$owner/$repository/wiki") {
Using.resource(Git.open(Directory.getWikiRepositoryDir(owner, repository))) { Using.resource(Git.open(Directory.getWikiRepositoryDir(owner, repository))) { git =>
git => val builder = DirCache.newInCore.builder()
val builder = DirCache.newInCore.builder() val inserter = git.getRepository.newObjectInserter()
val inserter = git.getRepository.newObjectInserter() val headId = git.getRepository.resolve(Constants.HEAD + "^{commit}")
val headId = git.getRepository.resolve(Constants.HEAD + "^{commit}")
if (headId != null) { if (headId != null) {
JGitUtil.processTree(git, headId) { (path, tree) => JGitUtil.processTree(git, headId) { (path, tree) =>
if (path != fileName) { if (path != fileName) {
builder.add(JGitUtil.createDirCacheEntry(path, tree.getEntryFileMode, tree.getEntryObjectId)) builder.add(JGitUtil.createDirCacheEntry(path, tree.getEntryFileMode, tree.getEntryObjectId))
}
}
} }
}
val bytes = IOUtils.toByteArray(file.getInputStream)
builder.add(
JGitUtil.createDirCacheEntry(
fileName,
FileMode.REGULAR_FILE,
inserter.insert(Constants.OBJ_BLOB, bytes)
)
)
builder.finish()
val newHeadId = JGitUtil.createNewCommit(
git,
inserter,
headId,
builder.getDirCache.writeTree(inserter),
Constants.HEAD,
loginAccount.fullName,
loginAccount.mailAddress,
s"Uploaded ${fileName}"
)
fileName
} }
val bytes = IOUtils.toByteArray(file.getInputStream)
builder.add(
JGitUtil.createDirCacheEntry(
fileName,
FileMode.REGULAR_FILE,
inserter.insert(Constants.OBJ_BLOB, bytes)
)
)
builder.finish()
JGitUtil.createNewCommit(
git,
inserter,
headId,
builder.getDirCache.writeTree(inserter),
Constants.HEAD,
loginAccount.fullName,
loginAccount.mailAddress,
s"Uploaded $fileName"
)
fileName
} }
}, }
_ => true },
) _ => true
} )
}
} getOrElse BadRequest() } getOrElse BadRequest()
} }
@@ -135,32 +133,34 @@ class FileUploadController
setMultipartConfigForLargeFile() setMultipartConfigForLargeFile()
session session
.get(Keys.Session.LoginAccount) .get(Keys.Session.LoginAccount)
.collect { .collect { case _: Account =>
case _: Account => val owner = params("owner")
val owner = params("owner") val repository = params("repository")
val repository = params("repository") val tag = multiParams("splat").head
val tag = multiParams("splat").head execute(
execute( { (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 )
)
} }
.getOrElse(BadRequest()) .getOrElse(BadRequest())
} }
post("/import") { post("/import") {
import JDBCUtil._ import JDBCUtil.*
setMultipartConfig() setMultipartConfig()
session.get(Keys.Session.LoginAccount).collect { session.get(Keys.Session.LoginAccount).collect {
case loginAccount: Account if loginAccount.isAdmin => case loginAccount: Account if loginAccount.isAdmin =>
execute({ (file, fileId) => execute(
request2Session(request).conn.importAsSQL(file.getInputStream) { (file, fileId) =>
}, _ => true) request2Session(request).conn.importAsSQL(file.getInputStream)
},
_ => true
)
} }
redirect("/admin/data") redirect("/admin/data")
} }
@@ -168,13 +168,13 @@ class FileUploadController
private def setMultipartConfig(): Unit = { private def setMultipartConfig(): Unit = {
val settings = loadSystemSettings() val settings = loadSystemSettings()
val config = MultipartConfig(maxFileSize = Some(settings.upload.maxFileSize)) val config = MultipartConfig(maxFileSize = Some(settings.upload.maxFileSize))
config.apply(request.getServletContext()) config.apply(request.getServletContext)
} }
private def setMultipartConfigForLargeFile(): Unit = { private def setMultipartConfigForLargeFile(): Unit = {
val settings = loadSystemSettings() val settings = loadSystemSettings()
val config = MultipartConfig(maxFileSize = Some(settings.upload.largeMaxFileSize)) val config = MultipartConfig(maxFileSize = Some(settings.upload.largeMaxFileSize))
config.apply(request.getServletContext()) config.apply(request.getServletContext)
} }
private def onlyWikiEditable(owner: String, repository: String, loginAccount: Account)(action: => Any): Any = { private def onlyWikiEditable(owner: String, repository: String, loginAccount: Account)(action: => Any): Any = {
@@ -191,7 +191,7 @@ class FileUploadController
} }
} }
private def execute(f: (FileItem, String) => Unit, mimeTypeChecker: (String) => Boolean) = private def execute(f: (FileItem, String) => Unit, mimeTypeChecker: String => Boolean) =
fileParams.get("file") match { fileParams.get("file") match {
case Some(file) if mimeTypeChecker(file.name) => case Some(file) if mimeTypeChecker(file.name) =>
val fileId = FileUtil.generateFileId val fileId = FileUtil.generateFileId

View File

@@ -1,17 +1,20 @@
package gitbucket.core.controller package gitbucket.core.controller
import java.net.URI import com.nimbusds.jwt.JWT
import java.net.URI
import com.nimbusds.oauth2.sdk.id.State import com.nimbusds.oauth2.sdk.id.State
import com.nimbusds.openid.connect.sdk.Nonce import com.nimbusds.openid.connect.sdk.Nonce
import gitbucket.core.helper.xml import gitbucket.core.helper.xml
import gitbucket.core.model.Account import gitbucket.core.model.Account
import gitbucket.core.service._ import gitbucket.core.service.*
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits.*
import gitbucket.core.util._ import gitbucket.core.util.*
import gitbucket.core.view.helpers._ import gitbucket.core.view.helpers.*
import org.scalatra.Ok import org.scalatra.Ok
import org.scalatra.forms._ import org.scalatra.forms.*
import gitbucket.core.service.ActivityService.*
class IndexController class IndexController
extends IndexControllerBase extends IndexControllerBase
@@ -31,19 +34,12 @@ class IndexController
with RequestCache with RequestCache
trait IndexControllerBase extends ControllerBase { trait IndexControllerBase extends ControllerBase {
self: RepositoryService self: RepositoryService & ActivityService & AccountService & RepositorySearchService & UsersAuthenticator &
with ActivityService ReferrerAuthenticator & AccessTokenService & AccountFederationService & OpenIDConnectService =>
with AccountService
with RepositorySearchService
with UsersAuthenticator
with ReferrerAuthenticator
with AccessTokenService
with AccountFederationService
with OpenIDConnectService =>
case class SignInForm(userName: String, password: String, hash: Option[String]) private case class SignInForm(userName: String, password: String, hash: Option[String])
val signinForm = mapping( private val signinForm = mapping(
"userName" -> trim(label("Username", text(required))), "userName" -> trim(label("Username", text(required))),
"password" -> trim(label("Password", text(required))), "password" -> trim(label("Password", text(required))),
"hash" -> trim(optional(text())) "hash" -> trim(optional(text()))
@@ -57,38 +53,53 @@ trait IndexControllerBase extends ControllerBase {
// //
// case class SearchForm(query: String, owner: String, repository: String) // case class SearchForm(query: String, owner: String, repository: String)
case class OidcContext(state: State, nonce: Nonce, redirectBackURI: String) private case class OidcAuthContext(state: State, nonce: Nonce, redirectBackURI: String)
private case class OidcSessionContext(token: JWT)
get("/") { get("/") {
context.loginAccount context.loginAccount
.map { account => .map { account =>
val visibleOwnerSet: Set[String] = Set(account.userName) ++ getGroupsByUserName(account.userName) // val visibleOwnerSet: Set[String] = Set(account.userName) ++ getGroupsByUserName(account.userName)
gitbucket.core.html.index( if (!isNewsFeedEnabled) {
getRecentActivitiesByOwners(visibleOwnerSet), redirect("/dashboard/repos")
getVisibleRepositories( } else {
val repos = getVisibleRepositories(
Some(account), Some(account),
None, None,
withoutPhysicalInfo = true, withoutPhysicalInfo = true,
limit = context.settings.basicBehavior.limitVisibleRepositories limit = false
),
showBannerToCreatePersonalAccessToken = hasAccountFederation(account.userName) && !hasAccessToken(
account.userName
) )
)
gitbucket.core.html.index(
activities = getRecentActivitiesByRepos(repos.map(x => (x.owner, x.name)).toSet),
recentRepositories = if (context.settings.basicBehavior.limitVisibleRepositories) {
repos.filter(x => x.owner == account.userName)
} else repos,
showBannerToCreatePersonalAccessToken = hasAccountFederation(account.userName) && !hasAccessToken(
account.userName
),
enableNewsFeed = isNewsFeedEnabled
)
}
} }
.getOrElse { .getOrElse {
gitbucket.core.html.index( gitbucket.core.html.index(
getRecentPublicActivities(), activities = getRecentPublicActivities(),
getVisibleRepositories(None, withoutPhysicalInfo = true), recentRepositories = getVisibleRepositories(None, withoutPhysicalInfo = true),
showBannerToCreatePersonalAccessToken = false showBannerToCreatePersonalAccessToken = false,
enableNewsFeed = isNewsFeedEnabled
) )
} }
} }
get("/signin") { get("/signin") {
val redirect = params.get("redirect") if (context.loginAccount.nonEmpty) {
if (redirect.isDefined && redirect.get.startsWith("/")) { redirect("/")
flash.update(Keys.Flash.Redirect, redirect.get) }
params.get("redirect").foreach { redirect =>
if (redirect.startsWith("/")) {
flash.update(Keys.Flash.Redirect, redirect)
}
} }
gitbucket.core.html.signin(flash.get("userName"), flash.get("password"), flash.get("error")) gitbucket.core.html.signin(flash.get("userName"), flash.get("password"), flash.get("error"))
} }
@@ -120,8 +131,8 @@ trait IndexControllerBase extends ControllerBase {
case _ => "/" case _ => "/"
} }
session.setAttribute( session.setAttribute(
Keys.Session.OidcContext, Keys.Session.OidcAuthContext,
OidcContext(authenticationRequest.getState, authenticationRequest.getNonce, redirectBackURI) OidcAuthContext(authenticationRequest.getState, authenticationRequest.getNonce, redirectBackURI)
) )
redirect(authenticationRequest.toURI.toString) redirect(authenticationRequest.toURI.toString)
} getOrElse { } getOrElse {
@@ -135,9 +146,10 @@ trait IndexControllerBase extends ControllerBase {
get("/signin/oidc") { get("/signin/oidc") {
context.settings.oidc.map { oidc => context.settings.oidc.map { oidc =>
val redirectURI = new URI(s"$baseUrl/signin/oidc") val redirectURI = new URI(s"$baseUrl/signin/oidc")
session.get(Keys.Session.OidcContext) match { session.get(Keys.Session.OidcAuthContext) match {
case Some(context: OidcContext) => case Some(context: OidcAuthContext) =>
authenticate(params.toMap, redirectURI, context.state, context.nonce, oidc).map { account => authenticate(params.toMap, redirectURI, context.state, context.nonce, oidc).map { case (jwt, account) =>
session.setAttribute(Keys.Session.OidcSessionContext, OidcSessionContext(jwt))
signin(account, context.redirectBackURI) signin(account, context.redirectBackURI)
} orElse { } orElse {
flash.update("error", "Sorry, authentication failed. Please try again.") flash.update("error", "Sorry, authentication failed. Please try again.")
@@ -155,7 +167,18 @@ trait IndexControllerBase extends ControllerBase {
} }
get("/signout") { get("/signout") {
session.invalidate context.settings.oidc.foreach { oidc =>
session.get(Keys.Session.OidcSessionContext).foreach { case context: OidcSessionContext =>
val redirectURI = new URI(baseUrl)
val authenticationRequest = createOIDLogoutRequest(oidc.issuer, oidc.clientID, redirectURI, context.token)
session.invalidate()
redirect(authenticationRequest.toURI.toString)
}
}
session.invalidate()
if (isDevFeatureEnabled(DevFeatures.KeepSession)) {
deleteLoginAccountFromLocalFile()
}
redirect("/") redirect("/")
} }
@@ -173,11 +196,24 @@ trait IndexControllerBase extends ControllerBase {
Ok() Ok()
} }
get("/user.css") {
context.settings.userDefinedCss match {
case Some(css) =>
contentType = "text/css"
css
case None =>
NotFound()
}
}
/** /**
* Set account information into HttpSession and redirect. * Set account information into HttpSession and redirect.
*/ */
private def signin(account: Account, redirectUrl: String = "/") = { private def signin(account: Account, redirectUrl: String = "/") = {
session.setAttribute(Keys.Session.LoginAccount, account) session.setAttribute(Keys.Session.LoginAccount, account)
if (isDevFeatureEnabled(DevFeatures.KeepSession)) {
saveLoginAccountToLocalFile(account)
}
updateLastLoginDate(account.userName) updateLastLoginDate(account.userName)
if (LDAPUtil.isDummyMailAddress(account)) { if (LDAPUtil.isDummyMailAddress(account)) {
@@ -200,8 +236,8 @@ trait IndexControllerBase extends ControllerBase {
val group = params("group").toBoolean val group = params("group").toBoolean
org.json4s.jackson.Serialization.write( org.json4s.jackson.Serialization.write(
Map( Map(
"options" -> ( "options" ->
getAllUsers(false) getAllUsers(includeRemoved = false)
.withFilter { t => .withFilter { t =>
(user, group) match { (user, group) match {
case (true, true) => true case (true, true) => true
@@ -213,43 +249,54 @@ 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(
StringUtil.cutTail(t.userName, 25, "...") StringUtil.cutTail(t.userName, 25, "...")
)}</b> ${StringUtil )}</b> ${StringUtil
.escapeHtml(StringUtil.cutTail(t.fullName, 25, "..."))}", .escapeHtml(StringUtil.cutTail(t.fullName, 25, "..."))}",
"value" -> t.userName "value" -> t.userName
) )
} }
)
) )
) )
}) })
/** /**
* JSON API for checking user or group existence. * JSON API for checking user or group existence.
*
* Returns a single string which is any of "group", "user" or "". * Returns a single string which is any of "group", "user" or "".
* Additionally, check whether the user is writable to the repository
* if "owner" and "repository" are given,
*/ */
post("/_user/existence")(usersOnly { post("/_user/existence")(usersOnly {
getAccountByUserNameIgnoreCase(params("userName")).map { account => getAccountByUserNameIgnoreCase(params("userName")).map { account =>
if (account.isGroupAccount) "group" else "user" if (!account.isGroupAccount && params.get("repository").isDefined && params.get("owner").isDefined) {
getRepository(params("owner"), params("repository"))
.collect {
case repository if isWritable(repository.repository, Some(account)) => "user"
}
.getOrElse("")
} else {
if (account.isGroupAccount) "group" else "user"
}
} getOrElse "" } getOrElse ""
}) })
// TODO Move to RepositoryViewrController? // TODO Move to RepositoryViewerController?
get("/:owner/:repository/search")(referrersOnly { repository => get("/:owner/:repository/search")(referrersOnly { repository =>
val query = params.getOrElse("q", "").trim val query = params.getOrElse("q", "").trim
val target = params.getOrElse("type", "code") val target = params.getOrElse("type", "code")
val page = try { val page =
val i = params.getOrElse("page", "1").toInt try {
if (i <= 0) 1 else i val i = params.getOrElse("page", "1").toInt
} catch { if (i <= 0) 1 else i
case _: NumberFormatException => 1 } catch {
} case _: NumberFormatException => 1
}
target.toLowerCase match { target.toLowerCase match {
case "issues" => case "issues" =>
gitbucket.core.search.html.issues( gitbucket.core.search.html.issues(
if (query.nonEmpty) searchIssues(repository.owner, repository.name, query, false) else Nil, if (query.nonEmpty) searchIssues(repository.owner, repository.name, query, pullRequest = false) else Nil,
false, pullRequest = false,
query, query,
page, page,
repository repository
@@ -257,8 +304,8 @@ trait IndexControllerBase extends ControllerBase {
case "pulls" => case "pulls" =>
gitbucket.core.search.html.issues( gitbucket.core.search.html.issues(
if (query.nonEmpty) searchIssues(repository.owner, repository.name, query, true) else Nil, if (query.nonEmpty) searchIssues(repository.owner, repository.name, query, pullRequest = true) else Nil,
true, pullRequest = true,
query, query,
page, page,
repository repository
@@ -293,15 +340,15 @@ trait IndexControllerBase extends ControllerBase {
) )
val repositories = { val repositories = {
context.settings.basicBehavior.limitVisibleRepositories match { if (context.settings.basicBehavior.limitVisibleRepositories) {
case true => getVisibleRepositories(
getVisibleRepositories( context.loginAccount,
context.loginAccount, None,
None, withoutPhysicalInfo = true,
withoutPhysicalInfo = true, limit = false
limit = false )
) } else {
case false => visibleRepositories visibleRepositories
} }
}.filter { repository => }.filter { repository =>
repository.name.toLowerCase.indexOf(query) >= 0 || repository.owner.toLowerCase.indexOf(query) >= 0 repository.name.toLowerCase.indexOf(query) >= 0 || repository.owner.toLowerCase.indexOf(query) >= 0

View File

@@ -2,13 +2,13 @@ package gitbucket.core.controller
import gitbucket.core.issues.html import gitbucket.core.issues.html
import gitbucket.core.model.{Account, CustomFieldBehavior} import gitbucket.core.model.{Account, CustomFieldBehavior}
import gitbucket.core.service.IssuesService._ import gitbucket.core.service.IssuesService.*
import gitbucket.core.service._ import gitbucket.core.service.*
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits.*
import gitbucket.core.util._ import gitbucket.core.util.*
import gitbucket.core.view import gitbucket.core.view
import gitbucket.core.view.Markdown import gitbucket.core.view.Markdown
import org.scalatra.forms._ import org.scalatra.forms.*
import org.scalatra.{BadRequest, Ok} import org.scalatra.{BadRequest, Ok}
class IssuesController class IssuesController
@@ -34,23 +34,12 @@ class IssuesController
with RequestCache with RequestCache
trait IssuesControllerBase extends ControllerBase { trait IssuesControllerBase extends ControllerBase {
self: IssuesService self: IssuesService & RepositoryService & AccountService & LabelsService & MilestonesService & ActivityService &
with RepositoryService HandleCommentService & IssueCreationService & CustomFieldsService & ReadableUsersAuthenticator &
with AccountService ReferrerAuthenticator & WritableUsersAuthenticator & PullRequestService & WebHookIssueCommentService &
with LabelsService PrioritiesService =>
with MilestonesService
with ActivityService
with HandleCommentService
with IssueCreationService
with CustomFieldsService
with ReadableUsersAuthenticator
with ReferrerAuthenticator
with WritableUsersAuthenticator
with PullRequestService
with WebHookIssueCommentService
with PrioritiesService =>
case class IssueCreateForm( private case class IssueCreateForm(
title: String, title: String,
content: Option[String], content: Option[String],
assigneeUserNames: Option[String], assigneeUserNames: Option[String],
@@ -58,10 +47,10 @@ trait IssuesControllerBase extends ControllerBase {
priorityId: Option[Int], priorityId: Option[Int],
labelNames: Option[String] labelNames: Option[String]
) )
case class CommentForm(issueId: Int, content: String) private case class CommentForm(issueId: Int, content: String)
case class IssueStateForm(issueId: Int, content: Option[String]) private case class IssueStateForm(issueId: Int, content: Option[String])
val issueCreateForm = mapping( private val issueCreateForm = mapping(
"title" -> trim(label("Title", text(required))), "title" -> trim(label("Title", text(required))),
"content" -> trim(optional(text())), "content" -> trim(optional(text())),
"assigneeUserNames" -> trim(optional(text())), "assigneeUserNames" -> trim(optional(text())),
@@ -70,55 +59,63 @@ trait IssuesControllerBase extends ControllerBase {
"labelNames" -> trim(optional(text())) "labelNames" -> trim(optional(text()))
)(IssueCreateForm.apply) )(IssueCreateForm.apply)
val issueTitleEditForm = mapping( private val issueTitleEditForm = mapping(
"title" -> trim(label("Title", text(required))) "title" -> trim(label("Title", text(required)))
)(x => x) )(x => x)
val issueEditForm = mapping( private val issueEditForm = mapping(
"content" -> trim(optional(text())) "content" -> trim(optional(text()))
)(x => x) )(x => x)
val commentForm = mapping( private val commentForm = mapping(
"issueId" -> label("Issue Id", number()), "issueId" -> label("Issue Id", number()),
"content" -> trim(label("Comment", text(required))) "content" -> trim(label("Comment", text(required)))
)(CommentForm.apply) )(CommentForm.apply)
val issueStateForm = mapping( private val issueStateForm = mapping(
"issueId" -> label("Issue Id", number()), "issueId" -> label("Issue Id", number()),
"content" -> trim(optional(text())) "content" -> trim(optional(text()))
)(IssueStateForm.apply) )(IssueStateForm.apply)
get("/:owner/:repository/issues")(referrersOnly { repository => get("/:owner/:repository/issues")(referrersOnly { repository =>
val q = request.getParameter("q") val q = request.getParameter("q")
if (Option(q).exists(_.contains("is:pr"))) { Option(q) match {
redirect(s"/${repository.owner}/${repository.name}/pulls?q=${StringUtil.urlEncode(q)}") case Some(filter) if filter.contains("is:pr") =>
} else { redirect(s"/${repository.owner}/${repository.name}/pulls?q=${StringUtil.urlEncode(q)}")
searchIssues(repository) case Some(filter) =>
val condition = IssueSearchCondition(filter)
if (condition.isEmpty) {
// Redirect to keyword search
redirect(s"/${repository.owner}/${repository.name}/search?q=${StringUtil.urlEncode(q)}&type=issues")
} else {
searchIssues(repository, condition, IssueSearchCondition.page(request))
}
case None =>
searchIssues(repository, IssueSearchCondition(request), IssueSearchCondition.page(request))
} }
}) })
get("/:owner/:repository/issues/:id")(referrersOnly { repository => get("/:owner/:repository/issues/:id")(referrersOnly { repository =>
val issueId = params("id") val issueId = params("id")
getIssue(repository.owner, repository.name, issueId) map { getIssue(repository.owner, repository.name, issueId) map { issue =>
issue => if (issue.isPullRequest) {
if (issue.isPullRequest) { redirect(s"/${repository.owner}/${repository.name}/pull/$issueId")
redirect(s"/${repository.owner}/${repository.name}/pull/${issueId}") } else {
} else { html.issue(
html.issue( issue,
issue, getComments(repository.owner, repository.name, issueId.toInt),
getComments(repository.owner, repository.name, issueId.toInt), getIssueLabels(repository.owner, repository.name, issueId.toInt),
getIssueLabels(repository.owner, repository.name, issueId.toInt), getIssueAssignees(repository.owner, repository.name, issueId.toInt),
getIssueAssignees(repository.owner, repository.name, issueId.toInt), getAssignableUserNames(repository.owner, repository.name),
getAssignableUserNames(repository.owner, repository.name), getMilestonesWithIssueCount(repository.owner, repository.name),
getMilestonesWithIssueCount(repository.owner, repository.name), getPriorities(repository.owner, repository.name),
getPriorities(repository.owner, repository.name), getLabels(repository.owner, repository.name),
getLabels(repository.owner, repository.name), getCustomFieldsWithValue(repository.owner, repository.name, issueId.toInt).filter(_._1.enableForIssues),
getCustomFieldsWithValue(repository.owner, repository.name, issueId.toInt).filter(_._1.enableForIssues), isIssueEditable(repository),
isIssueEditable(repository), isIssueManageable(repository),
isIssueManageable(repository), isIssueCommentManageable(repository),
isIssueCommentManageable(repository), repository
repository )
) }
}
} getOrElse NotFound() } getOrElse NotFound()
}) })
@@ -139,130 +136,120 @@ trait IssuesControllerBase extends ControllerBase {
}) })
post("/:owner/:repository/issues/new", issueCreateForm)(readableUsersOnly { (form, repository) => post("/:owner/:repository/issues/new", issueCreateForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => if (isIssueEditable(repository)) { // TODO Should this check is provided by authenticator?
if (isIssueEditable(repository)) { // TODO Should this check is provided by authenticator? val issue = createIssue(
val issue = createIssue( repository,
repository, form.title,
form.title, form.content,
form.content, form.assigneeUserNames.toSeq.flatMap(_.split(",")),
form.assigneeUserNames.toSeq.flatMap(_.split(",")), form.milestoneId,
form.milestoneId, form.priorityId,
form.priorityId, form.labelNames.toSeq.flatMap(_.split(",")),
form.labelNames.toSeq.flatMap(_.split(",")), loginAccount
loginAccount )
)
// Insert custom field values // Insert custom field values
params.toMap.foreach { params.toMap.foreach { case (key, value) =>
case (key, value) => if (key.startsWith("custom-field-")) {
if (key.startsWith("custom-field-")) { getCustomField(
getCustomField( repository.owner,
repository.owner, repository.name,
repository.name, key.replaceFirst("^custom-field-", "").toInt
key.replaceFirst("^custom-field-", "").toInt ).foreach { field =>
).foreach { field => CustomFieldBehavior.validate(field, value, messages) match {
CustomFieldBehavior.validate(field, value, messages) match { case None =>
case None => insertOrUpdateCustomFieldValue(field, repository.owner, repository.name, issue.issueId, value)
insertOrUpdateCustomFieldValue(field, repository.owner, repository.name, issue.issueId, value) case Some(_) => halt(400)
case Some(_) => halt(400)
}
}
} }
}
} }
}
redirect(s"/${issue.userName}/${issue.repositoryName}/issues/${issue.issueId}") redirect(s"/${issue.userName}/${issue.repositoryName}/issues/${issue.issueId}")
} else Unauthorized() } else Unauthorized()
} }
}) })
ajaxPost("/:owner/:repository/issues/edit_title/:id", issueTitleEditForm)(readableUsersOnly { (title, repository) => ajaxPost("/:owner/:repository/issues/edit_title/:id", issueTitleEditForm)(readableUsersOnly { (title, repository) =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => getIssue(repository.owner, repository.name, params("id")).map { issue =>
getIssue(repository.owner, repository.name, params("id")).map { if (isEditableContent(repository.owner, repository.name, issue.openedUserName, loginAccount)) {
issue => if (issue.title != title) {
if (isEditableContent(repository.owner, repository.name, issue.openedUserName, loginAccount)) { // update issue
if (issue.title != title) { updateIssue(repository.owner, repository.name, issue.issueId, title, issue.content)
// update issue // extract references and create refer comment
updateIssue(repository.owner, repository.name, issue.issueId, title, issue.content) createReferComment(repository.owner, repository.name, issue.copy(title = title), title, loginAccount)
// extract references and create refer comment createComment(
createReferComment(repository.owner, repository.name, issue.copy(title = title), title, loginAccount) repository.owner,
createComment( repository.name,
repository.owner, loginAccount.userName,
repository.name, issue.issueId,
loginAccount.userName, issue.title + "\r\n" + title,
issue.issueId, "change_title"
issue.title + "\r\n" + title, )
"change_title" }
) redirect(s"/${repository.owner}/${repository.name}/issues/_data/${issue.issueId}")
} } else Unauthorized()
redirect(s"/${repository.owner}/${repository.name}/issues/_data/${issue.issueId}") } getOrElse NotFound()
} else Unauthorized()
} getOrElse NotFound()
} }
}) })
ajaxPost("/:owner/:repository/issues/edit/:id", issueEditForm)(readableUsersOnly { (content, repository) => ajaxPost("/:owner/:repository/issues/edit/:id", issueEditForm)(readableUsersOnly { (content, repository) =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => getIssue(repository.owner, repository.name, params("id")).map { issue =>
getIssue(repository.owner, repository.name, params("id")).map { issue => if (isEditableContent(repository.owner, repository.name, issue.openedUserName, loginAccount)) {
if (isEditableContent(repository.owner, repository.name, issue.openedUserName, loginAccount)) { // update issue
// update issue updateIssue(repository.owner, repository.name, issue.issueId, issue.title, content)
updateIssue(repository.owner, repository.name, issue.issueId, issue.title, content) // extract references and create refer comment
// extract references and create refer comment createReferComment(repository.owner, repository.name, issue, content.getOrElse(""), loginAccount)
createReferComment(repository.owner, repository.name, issue, content.getOrElse(""), loginAccount)
redirect(s"/${repository.owner}/${repository.name}/issues/_data/${issue.issueId}") redirect(s"/${repository.owner}/${repository.name}/issues/_data/${issue.issueId}")
} else Unauthorized() } else Unauthorized()
} getOrElse NotFound() } getOrElse NotFound()
} }
}) })
post("/:owner/:repository/issue_comments/new", commentForm)(readableUsersOnly { (form, repository) => post("/:owner/:repository/issue_comments/new", commentForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => getIssue(repository.owner, repository.name, form.issueId.toString).flatMap { issue =>
getIssue(repository.owner, repository.name, form.issueId.toString).flatMap { issue => val actionOpt =
val actionOpt = params
params .get("action")
.get("action") .filter(_ => isEditableContent(issue.userName, issue.repositoryName, issue.openedUserName, loginAccount))
.filter(_ => isEditableContent(issue.userName, issue.repositoryName, issue.openedUserName, loginAccount)) handleComment(issue, Some(form.content), repository, actionOpt) map { case (issue, id) =>
handleComment(issue, Some(form.content), repository, actionOpt) map { redirect(
case (issue, id) => s"/${repository.owner}/${repository.name}/${if (issue.isPullRequest) "pull" else "issues"}/${form.issueId}#comment-$id"
redirect( )
s"/${repository.owner}/${repository.name}/${if (issue.isPullRequest) "pull" else "issues"}/${form.issueId}#comment-${id}" }
) } getOrElse NotFound()
}
} getOrElse NotFound()
} }
}) })
post("/:owner/:repository/issue_comments/state", issueStateForm)(readableUsersOnly { (form, repository) => post("/:owner/:repository/issue_comments/state", issueStateForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => getIssue(repository.owner, repository.name, form.issueId.toString).flatMap { issue =>
getIssue(repository.owner, repository.name, form.issueId.toString).flatMap { issue => val actionOpt =
val actionOpt = params
params .get("action")
.get("action") .filter(_ => isEditableContent(issue.userName, issue.repositoryName, issue.openedUserName, loginAccount))
.filter(_ => isEditableContent(issue.userName, issue.repositoryName, issue.openedUserName, loginAccount)) handleComment(issue, form.content, repository, actionOpt) map { case (issue, id) =>
handleComment(issue, form.content, repository, actionOpt) map { redirect(
case (issue, id) => s"/${repository.owner}/${repository.name}/${if (issue.isPullRequest) "pull" else "issues"}/${form.issueId}#comment-$id"
redirect( )
s"/${repository.owner}/${repository.name}/${if (issue.isPullRequest) "pull" else "issues"}/${form.issueId}#comment-${id}" }
) } getOrElse NotFound()
}
} getOrElse NotFound()
} }
}) })
ajaxPost("/:owner/:repository/issue_comments/edit/:id", commentForm)(readableUsersOnly { (form, repository) => ajaxPost("/:owner/:repository/issue_comments/edit/:id", commentForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => getComment(repository.owner, repository.name, params("id")).map { comment =>
getComment(repository.owner, repository.name, params("id")).map { comment => if (isEditableContent(repository.owner, repository.name, comment.commentedUserName, loginAccount)) {
if (isEditableContent(repository.owner, repository.name, comment.commentedUserName, loginAccount)) { updateComment(repository.owner, repository.name, comment.issueId, comment.commentId, form.content)
updateComment(repository.owner, repository.name, comment.issueId, comment.commentId, form.content) redirect(s"/${repository.owner}/${repository.name}/issue_comments/_data/${comment.commentId}")
redirect(s"/${repository.owner}/${repository.name}/issue_comments/_data/${comment.commentId}") } else Unauthorized()
} else Unauthorized() } getOrElse NotFound()
} getOrElse NotFound()
} }
}) })
@@ -277,65 +264,61 @@ trait IssuesControllerBase extends ControllerBase {
}) })
ajaxGet("/:owner/:repository/issues/_data/:id")(readableUsersOnly { repository => ajaxGet("/:owner/:repository/issues/_data/:id")(readableUsersOnly { repository =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => getIssue(repository.owner, repository.name, params("id")) map { x =>
getIssue(repository.owner, repository.name, params("id")) map { if (isEditableContent(x.userName, x.repositoryName, x.openedUserName, loginAccount)) {
x => params.get("dataType") collect {
if (isEditableContent(x.userName, x.repositoryName, x.openedUserName, loginAccount)) { case t if t == "html" => html.editissue(x.content, x.issueId, repository)
params.get("dataType") collect { } getOrElse {
case t if t == "html" => html.editissue(x.content, x.issueId, repository) contentType = formats("json")
} getOrElse { org.json4s.jackson.Serialization.write(
contentType = formats("json") Map(
org.json4s.jackson.Serialization.write( "title" -> x.title,
Map( "content" -> Markdown.toHtml(
"title" -> x.title, markdown = x.content getOrElse "No description given.",
"content" -> Markdown.toHtml( repository = repository,
markdown = x.content getOrElse "No description given.", branch = repository.repository.defaultBranch,
repository = repository, enableWikiLink = false,
branch = repository.repository.defaultBranch, enableRefsLink = true,
enableWikiLink = false, enableAnchor = true,
enableRefsLink = true, enableLineBreaks = true,
enableAnchor = true, enableTaskList = true,
enableLineBreaks = true, hasWritePermission = true
enableTaskList = true,
hasWritePermission = true
)
)
) )
} )
} else Unauthorized() )
} getOrElse NotFound() }
} else Unauthorized()
} getOrElse NotFound()
} }
}) })
ajaxGet("/:owner/:repository/issue_comments/_data/:id")(readableUsersOnly { repository => ajaxGet("/:owner/:repository/issue_comments/_data/:id")(readableUsersOnly { repository =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => getComment(repository.owner, repository.name, params("id")) map { x =>
getComment(repository.owner, repository.name, params("id")) map { if (isEditableContent(x.userName, x.repositoryName, x.commentedUserName, loginAccount)) {
x => params.get("dataType") collect {
if (isEditableContent(x.userName, x.repositoryName, x.commentedUserName, loginAccount)) { case t if t == "html" => html.editcomment(x.content, x.commentId, repository)
params.get("dataType") collect { } getOrElse {
case t if t == "html" => html.editcomment(x.content, x.commentId, repository) contentType = formats("json")
} getOrElse { org.json4s.jackson.Serialization.write(
contentType = formats("json") Map(
org.json4s.jackson.Serialization.write( "content" -> view.Markdown.toHtml(
Map( markdown = x.content,
"content" -> view.Markdown.toHtml( repository = repository,
markdown = x.content, branch = repository.repository.defaultBranch,
repository = repository, enableWikiLink = false,
branch = repository.repository.defaultBranch, enableRefsLink = true,
enableWikiLink = false, enableAnchor = true,
enableRefsLink = true, enableLineBreaks = true,
enableAnchor = true, enableTaskList = true,
enableLineBreaks = true, hasWritePermission = true
enableTaskList = true,
hasWritePermission = true
)
)
) )
} )
} else Unauthorized() )
} getOrElse NotFound() }
} else Unauthorized()
} getOrElse NotFound()
} }
}) })
@@ -347,43 +330,48 @@ trait IssuesControllerBase extends ControllerBase {
ajaxPost("/:owner/:repository/issues/:id/label/new")(writableUsersOnly { repository => ajaxPost("/:owner/:repository/issues/:id/label/new")(writableUsersOnly { repository =>
val issueId = params("id").toInt val issueId = params("id").toInt
registerIssueLabel(repository.owner, repository.name, issueId, params("labelId").toInt, true) registerIssueLabel(repository.owner, repository.name, issueId, params("labelId").toInt, insertComment = true)
html.labellist(getIssueLabels(repository.owner, repository.name, issueId)) html.labellist(getIssueLabels(repository.owner, repository.name, issueId))
}) })
ajaxPost("/:owner/:repository/issues/:id/label/delete")(writableUsersOnly { repository => ajaxPost("/:owner/:repository/issues/:id/label/delete")(writableUsersOnly { repository =>
val issueId = params("id").toInt val issueId = params("id").toInt
deleteIssueLabel(repository.owner, repository.name, issueId, params("labelId").toInt, true) deleteIssueLabel(repository.owner, repository.name, issueId, params("labelId").toInt, insertComment = true)
html.labellist(getIssueLabels(repository.owner, repository.name, issueId)) html.labellist(getIssueLabels(repository.owner, repository.name, issueId))
}) })
ajaxPost("/:owner/:repository/issues/:id/assignee/new")(writableUsersOnly { repository => ajaxPost("/:owner/:repository/issues/:id/assignee/new")(writableUsersOnly { repository =>
val issueId = params("id").toInt val issueId = params("id").toInt
registerIssueAssignee(repository.owner, repository.name, issueId, params("assigneeUserName"), true) registerIssueAssignee(repository.owner, repository.name, issueId, params("assigneeUserName"), insertComment = true)
Ok() Ok()
}) })
ajaxPost("/:owner/:repository/issues/:id/assignee/delete")(writableUsersOnly { repository => ajaxPost("/:owner/:repository/issues/:id/assignee/delete")(writableUsersOnly { repository =>
val issueId = params("id").toInt val issueId = params("id").toInt
deleteIssueAssignee(repository.owner, repository.name, issueId, params("assigneeUserName"), true) deleteIssueAssignee(repository.owner, repository.name, issueId, params("assigneeUserName"), insertComment = true)
Ok() Ok()
}) })
ajaxPost("/:owner/:repository/issues/:id/milestone")(writableUsersOnly { repository => ajaxPost("/:owner/:repository/issues/:id/milestone")(writableUsersOnly { repository =>
updateMilestoneId(repository.owner, repository.name, params("id").toInt, milestoneId("milestoneId"), true) updateMilestoneId(
repository.owner,
repository.name,
params("id").toInt,
milestoneId("milestoneId"),
insertComment = true
)
milestoneId("milestoneId").map { milestoneId => milestoneId("milestoneId").map { milestoneId =>
getMilestonesWithIssueCount(repository.owner, repository.name) getMilestonesWithIssueCount(repository.owner, repository.name)
.find(_._1.milestoneId == milestoneId) .find(_._1.milestoneId == milestoneId)
.map { .map { case (_, openCount, closeCount) =>
case (_, openCount, closeCount) => gitbucket.core.issues.milestones.html.progress(openCount + closeCount, closeCount)
gitbucket.core.issues.milestones.html.progress(openCount + closeCount, closeCount)
} getOrElse NotFound() } getOrElse NotFound()
} getOrElse Ok() } getOrElse Ok()
}) })
ajaxPost("/:owner/:repository/issues/:id/priority")(writableUsersOnly { repository => ajaxPost("/:owner/:repository/issues/:id/priority")(writableUsersOnly { repository =>
val priority = priorityId("priorityId") val priority = priorityId("priorityId")
updatePriorityId(repository.owner, repository.name, params("id").toInt, priority, true) updatePriorityId(repository.owner, repository.name, params("id").toInt, priority, insertComment = true)
Ok("updated") Ok("updated")
}) })
@@ -445,7 +433,7 @@ trait IssuesControllerBase extends ControllerBase {
params("value").toIntOpt.map { labelId => params("value").toIntOpt.map { labelId =>
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, insertComment = true)
if (params("uri").nonEmpty) { if (params("uri").nonEmpty) {
redirect(params("uri")) redirect(params("uri"))
} }
@@ -457,12 +445,12 @@ trait IssuesControllerBase extends ControllerBase {
post("/:owner/:repository/issues/batchedit/assign")(writableUsersOnly { repository => post("/:owner/:repository/issues/batchedit/assign")(writableUsersOnly { repository =>
val value = assignedUserName("value") val value = assignedUserName("value")
executeBatch(repository) { executeBatch(repository) {
//updateAssignedUserName(repository.owner, repository.name, _, value, true) // updateAssignedUserName(repository.owner, repository.name, _, value, true)
value match { value match {
case Some(assignedUserName) => case Some(assignedUserName) =>
registerIssueAssignee(repository.owner, repository.name, _, assignedUserName, true) registerIssueAssignee(repository.owner, repository.name, _, assignedUserName, insertComment = true)
case None => case None =>
deleteAllIssueAssignees(repository.owner, repository.name, _, true) deleteAllIssueAssignees(repository.owner, repository.name, _, insertComment = true)
} }
} }
if (params("uri").nonEmpty) { if (params("uri").nonEmpty) {
@@ -473,20 +461,20 @@ trait IssuesControllerBase extends ControllerBase {
post("/:owner/:repository/issues/batchedit/milestone")(writableUsersOnly { repository => post("/:owner/:repository/issues/batchedit/milestone")(writableUsersOnly { repository =>
val value = milestoneId("value") val value = milestoneId("value")
executeBatch(repository) { executeBatch(repository) {
updateMilestoneId(repository.owner, repository.name, _, value, true) updateMilestoneId(repository.owner, repository.name, _, value, insertComment = true)
} }
}) })
post("/:owner/:repository/issues/batchedit/priority")(writableUsersOnly { repository => post("/:owner/:repository/issues/batchedit/priority")(writableUsersOnly { repository =>
val value = priorityId("value") val value = priorityId("value")
executeBatch(repository) { executeBatch(repository) {
updatePriorityId(repository.owner, repository.name, _, value, true) updatePriorityId(repository.owner, repository.name, _, value, insertComment = true)
} }
}) })
get("/:owner/:repository/_attached/:file")(referrersOnly { repository => get("/:owner/:repository/_attached/:file")(referrersOnly { repository =>
(Directory.getAttachedDir(repository.owner, repository.name) match { (Directory.getAttachedDir(repository.owner, repository.name) match {
case dir if (dir.exists && dir.isDirectory) => case dir if dir.exists && dir.isDirectory =>
dir.listFiles.find(_.getName.startsWith(params("file") + ".")).map { file => dir.listFiles.find(_.getName.startsWith(params("file") + ".")).map { file =>
response.setHeader("Content-Disposition", f"""inline; filename=${file.getName}""") response.setHeader("Content-Disposition", f"""inline; filename=${file.getName}""")
RawData(FileUtil.getSafeMimeType(file.getName), file) RawData(FileUtil.getSafeMimeType(file.getName), file)
@@ -502,27 +490,26 @@ trait IssuesControllerBase extends ControllerBase {
contentType = formats("json") contentType = formats("json")
org.json4s.jackson.Serialization.write( org.json4s.jackson.Serialization.write(
Map( Map(
"options" -> ( "options" ->
getOpenIssues(repository.owner, repository.name) getOpenIssues(repository.owner, repository.name)
.map { t => .map { t =>
Map( Map(
"label" -> s"""${if (t.isPullRequest) "<i class='octicon octicon-git-pull-request'></i>" "label" -> s"""${if (t.isPullRequest) "<i class='octicon octicon-git-pull-request'></i>"
else "<i class='octicon octicon-issue-opened'></i>"}<b> #${StringUtil else "<i class='octicon octicon-issue-opened'></i>"}<b> #${StringUtil
.escapeHtml(t.issueId.toString)} ${StringUtil .escapeHtml(t.issueId.toString)} ${StringUtil
.escapeHtml(StringUtil.cutTail(t.title, 50, "..."))}</b>""", .escapeHtml(StringUtil.cutTail(t.title, 50, "..."))}</b>""",
"value" -> t.issueId.toString "value" -> t.issueId.toString
) )
} }
)
) )
) )
}) })
val assignedUserName = (key: String) => params.get(key) filter (_.trim != "") private val assignedUserName = (key: String) => params.get(key) filter (_.trim != "")
val milestoneId: String => Option[Int] = (key: String) => params.get(key).flatMap(_.toIntOpt) private val milestoneId: String => Option[Int] = (key: String) => params.get(key).flatMap(_.toIntOpt)
val priorityId: String => Option[Int] = (key: String) => params.get(key).flatMap(_.toIntOpt) private val priorityId: String => Option[Int] = (key: String) => params.get(key).flatMap(_.toIntOpt)
private def executeBatch(repository: RepositoryService.RepositoryInfo)(execute: Int => Unit) = { private def executeBatch(repository: RepositoryService.RepositoryInfo)(execute: Int => Unit): Unit = {
params("checked").split(',') map (_.toInt) foreach execute params("checked").split(',') map (_.toInt) foreach execute
params("from") match { params("from") match {
case "issues" => redirect(s"/${repository.owner}/${repository.name}/issues") case "issues" => redirect(s"/${repository.owner}/${repository.name}/issues")
@@ -531,10 +518,7 @@ trait IssuesControllerBase extends ControllerBase {
} }
} }
private def searchIssues(repository: RepositoryService.RepositoryInfo) = { private def searchIssues(repository: RepositoryService.RepositoryInfo, condition: IssueSearchCondition, page: Int) = {
val page = IssueSearchCondition.page(request)
// retrieve search condition
val condition = IssueSearchCondition(request)
// search issues // search issues
val issues = val issues =
searchIssue( searchIssue(
@@ -565,8 +549,8 @@ trait IssuesControllerBase extends ControllerBase {
/** /**
* Tests whether an issue or a comment is editable by a logged-in user. * Tests whether an issue or a comment is editable by a logged-in user.
*/ */
private def isEditableContent(owner: String, repository: String, author: String, loginAccount: Account)( private def isEditableContent(owner: String, repository: String, author: String, loginAccount: Account)(implicit
implicit context: Context context: Context
): Boolean = { ): Boolean = {
hasDeveloperRole(owner, repository, context.loginAccount) || author == loginAccount.userName hasDeveloperRole(owner, repository, context.loginAccount) || author == loginAccount.userName
} }
@@ -574,8 +558,8 @@ trait IssuesControllerBase extends ControllerBase {
/** /**
* Tests whether an issue comment is deletable by a logged-in user. * Tests whether an issue comment is deletable by a logged-in user.
*/ */
private def isDeletableComment(owner: String, repository: String, author: String, loginAccount: Account)( private def isDeletableComment(owner: String, repository: String, author: String, loginAccount: Account)(implicit
implicit context: Context context: Context
): Boolean = { ): Boolean = {
hasOwnerRole(owner, repository, context.loginAccount) || author == loginAccount.userName hasOwnerRole(owner, repository, context.loginAccount) || author == loginAccount.userName
} }

View File

@@ -10,9 +10,9 @@ import gitbucket.core.service.{
PrioritiesService PrioritiesService
} }
import gitbucket.core.util.{ReferrerAuthenticator, WritableUsersAuthenticator} import gitbucket.core.util.{ReferrerAuthenticator, WritableUsersAuthenticator}
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits.*
import gitbucket.core.util.SyntaxSugars._ import gitbucket.core.util.SyntaxSugars.*
import org.scalatra.forms._ import org.scalatra.forms.*
import org.scalatra.i18n.Messages import org.scalatra.i18n.Messages
import org.scalatra.Ok import org.scalatra.Ok
@@ -28,15 +28,11 @@ class LabelsController
with WritableUsersAuthenticator with WritableUsersAuthenticator
trait LabelsControllerBase extends ControllerBase { trait LabelsControllerBase extends ControllerBase {
self: LabelsService self: LabelsService & IssuesService & RepositoryService & ReferrerAuthenticator & WritableUsersAuthenticator =>
with IssuesService
with RepositoryService
with ReferrerAuthenticator
with WritableUsersAuthenticator =>
case class LabelForm(labelName: String, color: String) private case class LabelForm(labelName: String, color: String)
val labelForm = mapping( private val labelForm = mapping(
"labelName" -> trim(label("Label name", text(required, labelName, uniqueLabelName, maxlength(100)))), "labelName" -> trim(label("Label name", text(required, labelName, uniqueLabelName, maxlength(100)))),
"labelColor" -> trim(label("Color", text(required, color))) "labelColor" -> trim(label("Color", text(required, color)))
)(LabelForm.apply) )(LabelForm.apply)
@@ -93,9 +89,9 @@ trait LabelsControllerBase extends ControllerBase {
private def labelName: Constraint = new Constraint() { private def labelName: 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 (value.contains(',')) { if (value.contains(',')) {
Some(s"${name} contains invalid character.") Some(s"$name contains invalid character.")
} else if (value.startsWith("_") || value.startsWith("-")) { } else if (value.startsWith("_") || value.startsWith("-")) {
Some(s"${name} starts with invalid character.") Some(s"$name starts with invalid character.")
} else { } else {
None None
} }

View File

@@ -9,11 +9,11 @@ import gitbucket.core.service.{
MilestonesService, MilestonesService,
RepositoryService 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 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
class MilestonesController class MilestonesController
@@ -26,15 +26,12 @@ class MilestonesController
with WritableUsersAuthenticator with WritableUsersAuthenticator
trait MilestonesControllerBase extends ControllerBase { trait MilestonesControllerBase extends ControllerBase {
self: MilestonesService self: MilestonesService & RepositoryService & CommitStatusService & ReferrerAuthenticator &
with RepositoryService WritableUsersAuthenticator =>
with CommitStatusService
with ReferrerAuthenticator
with WritableUsersAuthenticator =>
case class MilestoneForm(title: String, description: Option[String], dueDate: Option[java.util.Date]) private case class MilestoneForm(title: String, description: Option[String], dueDate: Option[java.util.Date])
val milestoneForm = mapping( private val milestoneForm = mapping(
"title" -> trim(label("Title", text(required, maxlength(100), uniqueMilestone))), "title" -> trim(label("Title", text(required, maxlength(100), uniqueMilestone))),
"description" -> trim(label("Description", optional(text()))), "description" -> trim(label("Description", optional(text()))),
"dueDate" -> trim(label("Due Date", optional(date()))) "dueDate" -> trim(label("Due Date", optional(date())))

View File

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

View File

@@ -28,15 +28,11 @@ class PrioritiesController
with WritableUsersAuthenticator with WritableUsersAuthenticator
trait PrioritiesControllerBase extends ControllerBase { trait PrioritiesControllerBase extends ControllerBase {
self: PrioritiesService self: PrioritiesService & IssuesService & RepositoryService & ReferrerAuthenticator & WritableUsersAuthenticator =>
with IssuesService
with RepositoryService
with ReferrerAuthenticator
with WritableUsersAuthenticator =>
case class PriorityForm(priorityName: String, description: Option[String], color: String) private case class PriorityForm(priorityName: String, description: Option[String], color: String)
val priorityForm = mapping( private val priorityForm = mapping(
"priorityName" -> trim(label("Priority name", text(required, priorityName, uniquePriorityName, maxlength(100)))), "priorityName" -> trim(label("Priority name", text(required, priorityName, uniquePriorityName, maxlength(100)))),
"description" -> trim(label("Description", optional(text(maxlength(255))))), "description" -> trim(label("Description", optional(text(maxlength(255))))),
"priorityColor" -> trim(label("Color", text(required, color))) "priorityColor" -> trim(label("Color", text(required, color)))
@@ -90,7 +86,7 @@ trait PrioritiesControllerBase extends ControllerBase {
) )
}) })
ajaxPost("/:owner/:repository/issues/priorities/reorder")(writableUsersOnly { (repository) => ajaxPost("/:owner/:repository/issues/priorities/reorder")(writableUsersOnly { repository =>
reorderPriorities( reorderPriorities(
repository.owner, repository.owner,
repository.name, repository.name,
@@ -104,7 +100,7 @@ trait PrioritiesControllerBase extends ControllerBase {
Ok() Ok()
}) })
ajaxPost("/:owner/:repository/issues/priorities/default")(writableUsersOnly { (repository) => ajaxPost("/:owner/:repository/issues/priorities/default")(writableUsersOnly { repository =>
setDefaultPriority(repository.owner, repository.name, priorityId("priorityId")) setDefaultPriority(repository.owner, repository.name, priorityId("priorityId"))
Ok() Ok()
}) })
@@ -122,9 +118,9 @@ trait PrioritiesControllerBase extends ControllerBase {
private def priorityName: Constraint = new Constraint() { private def priorityName: 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 (value.contains(',')) { if (value.contains(',')) {
Some(s"${name} contains invalid character.") Some(s"$name contains invalid character.")
} else if (value.startsWith("_") || value.startsWith("-")) { } else if (value.startsWith("_") || value.startsWith("-")) {
Some(s"${name} starts with invalid character.") Some(s"$name starts with invalid character.")
} else { } else {
None None
} }

View File

@@ -4,14 +4,14 @@ 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
import gitbucket.core.service.IssuesService._ import gitbucket.core.service.IssuesService.*
import gitbucket.core.service.PullRequestService._ import gitbucket.core.service.PullRequestService.*
import gitbucket.core.service.RepositoryService.RepositoryInfo import gitbucket.core.service.RepositoryService.RepositoryInfo
import gitbucket.core.service._ import gitbucket.core.service.*
import gitbucket.core.util.Directory._ import gitbucket.core.util.Directory.*
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits.*
import gitbucket.core.util._ import gitbucket.core.util.*
import org.scalatra.forms._ import org.scalatra.forms.*
import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.Git
import org.scalatra.BadRequest import org.scalatra.BadRequest
@@ -40,32 +40,19 @@ class PullRequestsController
with RequestCache with RequestCache
trait PullRequestsControllerBase extends ControllerBase { trait PullRequestsControllerBase extends ControllerBase {
self: RepositoryService self: RepositoryService & AccountService & IssuesService & MilestonesService & LabelsService & CustomFieldsService &
with AccountService CommitsService & ActivityService & PullRequestService & WebHookPullRequestService & ReadableUsersAuthenticator &
with IssuesService ReferrerAuthenticator & WritableUsersAuthenticator & CommitStatusService & MergeService & ProtectedBranchService &
with MilestonesService PrioritiesService =>
with LabelsService
with CustomFieldsService
with CommitsService
with ActivityService
with PullRequestService
with WebHookPullRequestService
with ReadableUsersAuthenticator
with ReferrerAuthenticator
with WritableUsersAuthenticator
with CommitStatusService
with MergeService
with ProtectedBranchService
with PrioritiesService =>
val pullRequestForm = mapping( private val pullRequestForm = mapping(
"title" -> trim(label("Title", text(required))), "title" -> trim(label("Title", text(required))),
"content" -> trim(label("Content", optional(text()))), "content" -> trim(label("Content", optional(text()))),
"targetUserName" -> trim(text(required, maxlength(100))), "targetUserName" -> trim(text(required, maxlength(100))),
"targetBranch" -> trim(text(required, maxlength(100))), "targetBranch" -> trim(text(required, maxlength(255))),
"requestUserName" -> trim(text(required, maxlength(100))), "requestUserName" -> trim(text(required, maxlength(100))),
"requestRepositoryName" -> trim(text(required, maxlength(100))), "requestRepositoryName" -> trim(text(required, maxlength(100))),
"requestBranch" -> trim(text(required, maxlength(100))), "requestBranch" -> trim(text(required, maxlength(255))),
"commitIdFrom" -> trim(text(required, maxlength(40))), "commitIdFrom" -> trim(text(required, maxlength(40))),
"commitIdTo" -> trim(text(required, maxlength(40))), "commitIdTo" -> trim(text(required, maxlength(40))),
"isDraft" -> trim(boolean(required)), "isDraft" -> trim(boolean(required)),
@@ -75,13 +62,13 @@ trait PullRequestsControllerBase extends ControllerBase {
"labelNames" -> trim(optional(text())) "labelNames" -> trim(optional(text()))
)(PullRequestForm.apply) )(PullRequestForm.apply)
val mergeForm = mapping( private val mergeForm = mapping(
"message" -> trim(label("Message", text(required))), "message" -> trim(label("Message", text(required))),
"strategy" -> trim(label("Strategy", text(required))), "strategy" -> trim(label("Strategy", text(required))),
"isDraft" -> trim(boolean(required)) "isDraft" -> trim(boolean(required))
)(MergeForm.apply) )(MergeForm.apply)
case class PullRequestForm( private case class PullRequestForm(
title: String, title: String,
content: Option[String], content: Option[String],
targetUserName: String, targetUserName: String,
@@ -98,161 +85,164 @@ trait PullRequestsControllerBase extends ControllerBase {
labelNames: Option[String] labelNames: Option[String]
) )
case class MergeForm(message: String, strategy: String, isDraft: Boolean) private case class MergeForm(message: String, strategy: String, isDraft: Boolean)
get("/:owner/:repository/pulls")(referrersOnly { repository => get("/:owner/:repository/pulls")(referrersOnly { repository =>
val q = request.getParameter("q") val q = request.getParameter("q")
if (Option(q).exists(_.contains("is:issue"))) { Option(q) match {
redirect(s"/${repository.owner}/${repository.name}/issues?q=" + StringUtil.urlEncode(q)) case Some(filter) if filter.contains("is:issue") =>
} else { redirect(s"/${repository.owner}/${repository.name}/issues?q=${StringUtil.urlEncode(q)}")
searchPullRequests(None, repository) case Some(filter) =>
val condition = IssueSearchCondition(filter)
if (condition.isEmpty) {
// Redirect to keyword search
redirect(s"/${repository.owner}/${repository.name}/search?q=${StringUtil.urlEncode(q)}&type=pulls")
} else {
searchPullRequests(repository, IssueSearchCondition(filter), IssueSearchCondition.page(request))
}
case None =>
searchPullRequests(repository, IssueSearchCondition(request), IssueSearchCondition.page(request))
} }
}) })
get("/:owner/:repository/pull/:id")(referrersOnly { repository => get("/:owner/:repository/pull/:id")(referrersOnly { repository =>
params("id").toIntOpt.flatMap { params("id").toIntOpt.flatMap { issueId =>
issueId => getPullRequest(repository.owner, repository.name, issueId) map { case (issue, pullreq) =>
getPullRequest(repository.owner, repository.name, issueId) map { val (commits, diffs) =
case (issue, pullreq) => getRequestCompareInfo(
val (commits, diffs) = repository.owner,
getRequestCompareInfo( repository.name,
repository.owner, pullreq.commitIdFrom,
repository.name, repository.owner,
pullreq.commitIdFrom, repository.name,
repository.owner, pullreq.commitIdTo,
repository.name, context.settings
pullreq.commitIdTo )
)
html.conversation( html.conversation(
issue, issue,
pullreq, pullreq,
commits.flatten, commits.flatten,
getPullRequestComments(repository.owner, repository.name, issue.issueId, commits.flatten), getPullRequestComments(repository.owner, repository.name, issue.issueId, commits.flatten),
diffs.size, diffs.size,
getIssueLabels(repository.owner, repository.name, issueId), getIssueLabels(repository.owner, repository.name, issueId),
getIssueAssignees(repository.owner, repository.name, issueId), getIssueAssignees(repository.owner, repository.name, issueId),
getAssignableUserNames(repository.owner, repository.name), getAssignableUserNames(repository.owner, repository.name),
getMilestonesWithIssueCount(repository.owner, repository.name), getMilestonesWithIssueCount(repository.owner, repository.name),
getPriorities(repository.owner, repository.name), getPriorities(repository.owner, repository.name),
getLabels(repository.owner, repository.name), getLabels(repository.owner, repository.name),
getCustomFieldsWithValue(repository.owner, repository.name, issueId).filter(_._1.enableForPullRequests), getCustomFieldsWithValue(repository.owner, repository.name, issueId).filter(_._1.enableForPullRequests),
isEditable(repository), isEditable(repository),
isManageable(repository), isManageable(repository),
hasDeveloperRole(pullreq.requestUserName, pullreq.requestRepositoryName, context.loginAccount), hasDeveloperRole(pullreq.requestUserName, pullreq.requestRepositoryName, context.loginAccount),
repository, repository,
getRepository(pullreq.requestUserName, pullreq.requestRepositoryName), getRepository(pullreq.requestUserName, pullreq.requestRepositoryName),
flash.iterator.map(f => f._1 -> f._2.toString).toMap flash.iterator.map(f => f._1 -> f._2.toString).toMap
) )
} }
} getOrElse NotFound() } getOrElse NotFound()
}) })
get("/:owner/:repository/pull/:id/commits")(referrersOnly { repository => get("/:owner/:repository/pull/:id/commits")(referrersOnly { repository =>
params("id").toIntOpt.flatMap { params("id").toIntOpt.flatMap { issueId =>
issueId => getPullRequest(repository.owner, repository.name, issueId) map { case (issue, pullreq) =>
getPullRequest(repository.owner, repository.name, issueId) map { val (commits, diffs) =
case (issue, pullreq) => getRequestCompareInfo(
val (commits, diffs) = repository.owner,
getRequestCompareInfo( repository.name,
repository.owner, pullreq.commitIdFrom,
repository.name, repository.owner,
pullreq.commitIdFrom, repository.name,
repository.owner, pullreq.commitIdTo,
repository.name, context.settings
pullreq.commitIdTo )
)
val commitsWithStatus = commits.map { day => val commitsWithStatus = commits.map { day =>
day.map { commit => day.map { commit =>
(commit, getCommitStatusWithSummary(repository.owner, repository.name, commit.id)) (commit, getCommitStatusWithSummary(repository.owner, repository.name, commit.id))
} }
}
html.commits(
issue,
pullreq,
commitsWithStatus,
getPullRequestComments(repository.owner, repository.name, issue.issueId, commits.flatten),
diffs.size,
isManageable(repository),
repository
)
} }
html.commits(
issue,
pullreq,
commitsWithStatus,
getPullRequestComments(repository.owner, repository.name, issue.issueId, commits.flatten),
diffs.size,
isManageable(repository),
repository
)
}
} getOrElse NotFound() } getOrElse NotFound()
}) })
get("/:owner/:repository/pull/:id/files")(referrersOnly { repository => get("/:owner/:repository/pull/:id/files")(referrersOnly { repository =>
params("id").toIntOpt.flatMap { params("id").toIntOpt.flatMap { issueId =>
issueId => getPullRequest(repository.owner, repository.name, issueId) map { case (issue, pullreq) =>
getPullRequest(repository.owner, repository.name, issueId) map { val (commits, diffs) =
case (issue, pullreq) => getRequestCompareInfo(
val (commits, diffs) = repository.owner,
getRequestCompareInfo( repository.name,
repository.owner, pullreq.commitIdFrom,
repository.name, repository.owner,
pullreq.commitIdFrom, repository.name,
repository.owner, pullreq.commitIdTo,
repository.name, context.settings
pullreq.commitIdTo )
)
html.files( html.files(
issue, issue,
pullreq, pullreq,
diffs, diffs,
commits.flatten, commits.flatten,
getPullRequestComments(repository.owner, repository.name, issue.issueId, commits.flatten), getPullRequestComments(repository.owner, repository.name, issue.issueId, commits.flatten),
isManageable(repository), isManageable(repository),
repository repository
) )
} }
} getOrElse NotFound() } getOrElse NotFound()
}) })
ajaxGet("/:owner/:repository/pull/:id/mergeguide")(referrersOnly { repository => ajaxGet("/:owner/:repository/pull/:id/mergeguide")(referrersOnly { repository =>
params("id").toIntOpt.flatMap { params("id").toIntOpt.flatMap { issueId =>
issueId => getPullRequest(repository.owner, repository.name, issueId) map { case (issue, pullreq) =>
getPullRequest(repository.owner, repository.name, issueId) map { val conflictMessage = LockUtil.lock(s"${repository.owner}/${repository.name}") {
case (issue, pullreq) => checkConflict(repository.owner, repository.name, pullreq.branch, issueId)
val conflictMessage = LockUtil.lock(s"${repository.owner}/${repository.name}") { }
checkConflict(repository.owner, repository.name, pullreq.branch, issueId) val hasMergePermission = hasDeveloperRole(repository.owner, repository.name, context.loginAccount)
} val branchProtection = getProtectedBranchInfo(repository.owner, repository.name, pullreq.branch)
val hasMergePermission = hasDeveloperRole(repository.owner, repository.name, context.loginAccount) val mergeStatus = PullRequestService.MergeStatus(
val branchProtection = getProtectedBranchInfo(repository.owner, repository.name, pullreq.branch) conflictMessage = conflictMessage,
val mergeStatus = PullRequestService.MergeStatus( commitStatuses = getCommitStatuses(repository.owner, repository.name, pullreq.commitIdTo),
conflictMessage = conflictMessage, branchProtection = branchProtection,
commitStatuses = getCommitStatuses(repository.owner, repository.name, pullreq.commitIdTo), branchIsOutOfDate =
branchProtection = branchProtection, !JGitUtil.getShaByRef(repository.owner, repository.name, pullreq.branch).contains(pullreq.commitIdFrom),
branchIsOutOfDate = JGitUtil.getShaByRef(repository.owner, repository.name, pullreq.branch) != Some( needStatusCheck = context.loginAccount.forall { u =>
pullreq.commitIdFrom branchProtection.needStatusCheck(u.userName)
), },
needStatusCheck = context.loginAccount.forall { u => hasUpdatePermission = hasDeveloperRole(
branchProtection.needStatusCheck(u.userName) pullreq.requestUserName,
}, pullreq.requestRepositoryName,
hasUpdatePermission = hasDeveloperRole( context.loginAccount
) &&
context.loginAccount.exists { u =>
!getProtectedBranchInfo(
pullreq.requestUserName, pullreq.requestUserName,
pullreq.requestRepositoryName, pullreq.requestRepositoryName,
context.loginAccount pullreq.requestBranch
) && ).needStatusCheck(u.userName)
context.loginAccount.exists { u => },
!getProtectedBranchInfo( hasMergePermission = hasMergePermission,
pullreq.requestUserName, commitIdTo = pullreq.commitIdTo
pullreq.requestRepositoryName, )
pullreq.requestBranch html.mergeguide(
).needStatusCheck(u.userName) mergeStatus,
}, issue,
hasMergePermission = hasMergePermission, pullreq,
commitIdTo = pullreq.commitIdTo repository,
) getRepository(pullreq.requestUserName, pullreq.requestRepositoryName).get
html.mergeguide( )
mergeStatus, }
issue,
pullreq,
repository,
getRepository(pullreq.requestUserName, pullreq.requestRepositoryName).get
)
}
} getOrElse NotFound() } getOrElse NotFound()
}) })
@@ -260,7 +250,7 @@ trait PullRequestsControllerBase extends ControllerBase {
(for { (for {
issueId <- params("id").toIntOpt issueId <- params("id").toIntOpt
loginAccount <- context.loginAccount loginAccount <- context.loginAccount
(issue, pullreq) <- getPullRequest(baseRepository.owner, baseRepository.name, issueId) case (issue, pullreq) <- getPullRequest(baseRepository.owner, baseRepository.name, issueId)
owner = pullreq.requestUserName owner = pullreq.requestUserName
name = pullreq.requestRepositoryName name = pullreq.requestRepositoryName
if hasDeveloperRole(owner, name, context.loginAccount) if hasDeveloperRole(owner, name, context.loginAccount)
@@ -298,7 +288,7 @@ trait PullRequestsControllerBase extends ControllerBase {
(for { (for {
issueId <- params("id").toIntOpt issueId <- params("id").toIntOpt
loginAccount <- context.loginAccount loginAccount <- context.loginAccount
(issue, pullreq) <- getPullRequest(baseRepository.owner, baseRepository.name, issueId) case (issue, pullreq) <- getPullRequest(baseRepository.owner, baseRepository.name, issueId)
repository <- getRepository(pullreq.requestUserName, pullreq.requestRepositoryName) repository <- getRepository(pullreq.requestUserName, pullreq.requestRepositoryName)
remoteRepository <- getRepository(pullreq.userName, pullreq.repositoryName) remoteRepository <- getRepository(pullreq.userName, pullreq.repositoryName)
owner = pullreq.requestUserName owner = pullreq.requestUserName
@@ -309,34 +299,36 @@ trait PullRequestsControllerBase extends ControllerBase {
if (branchProtection.needStatusCheck(loginAccount.userName)) { if (branchProtection.needStatusCheck(loginAccount.userName)) {
flash.update("error", s"branch ${pullreq.requestBranch} is protected need status check.") flash.update("error", s"branch ${pullreq.requestBranch} is protected need status check.")
} else { } else {
LockUtil.lock(s"${owner}/${name}") { LockUtil.lock(s"$owner/$name") {
val alias = val alias =
if (pullreq.repositoryName == pullreq.requestRepositoryName && pullreq.userName == pullreq.requestUserName) { if (
pullreq.repositoryName == pullreq.requestRepositoryName && pullreq.userName == pullreq.requestUserName
) {
pullreq.branch pullreq.branch
} else { } else {
s"${pullreq.userName}:${pullreq.branch}" s"${pullreq.userName}:${pullreq.branch}"
} }
val existIds = Using // val existIds = Using
.resource(Git.open(Directory.getRepositoryDir(owner, name))) { git => // .resource(Git.open(Directory.getRepositoryDir(owner, name))) { git =>
JGitUtil.getAllCommitIds(git) // JGitUtil.getAllCommitIds(git)
} // }
.toSet // .toSet
pullRemote( pullRemote(
repository, repository,
pullreq.requestBranch, pullreq.requestBranch,
remoteRepository, remoteRepository,
pullreq.branch, pullreq.branch,
loginAccount, loginAccount,
s"Merge branch '${alias}' into ${pullreq.requestBranch}", s"Merge branch '$alias' into ${pullreq.requestBranch}",
Some(pullreq), Some(pullreq),
context.settings context.settings
) match { ) match {
case None => // conflict case None => // conflict
flash.update("error", s"Can't automatic merging branch '${alias}' into ${pullreq.requestBranch}.") flash.update("error", s"Can't automatic merging branch '$alias' into ${pullreq.requestBranch}.")
case Some(oldId) => case Some(oldId) =>
// update pull request // update pull request
updatePullRequests(owner, name, pullreq.requestBranch, loginAccount, "synchronize", context.settings) updatePullRequests(owner, name, pullreq.requestBranch, loginAccount, "synchronize", context.settings)
flash.update("info", s"Merge branch '${alias}' into ${pullreq.requestBranch}") flash.update("info", s"Merge branch '$alias' into ${pullreq.requestBranch}")
} }
} }
} }
@@ -348,7 +340,7 @@ trait PullRequestsControllerBase extends ControllerBase {
post("/:owner/:repository/pull/:id/update_draft")(readableUsersOnly { baseRepository => post("/:owner/:repository/pull/:id/update_draft")(readableUsersOnly { baseRepository =>
(for { (for {
issueId <- params("id").toIntOpt issueId <- params("id").toIntOpt
(_, pullreq) <- getPullRequest(baseRepository.owner, baseRepository.name, issueId) case (_, pullreq) <- getPullRequest(baseRepository.owner, baseRepository.name, issueId)
owner = pullreq.requestUserName owner = pullreq.requestUserName
name = pullreq.requestRepositoryName name = pullreq.requestRepositoryName
if hasDeveloperRole(owner, name, context.loginAccount) if hasDeveloperRole(owner, name, context.loginAccount)
@@ -369,7 +361,7 @@ trait PullRequestsControllerBase extends ControllerBase {
form.isDraft, form.isDraft,
context.settings context.settings
) match { ) match {
case Right(objectId) => redirect(s"/${repository.owner}/${repository.name}/pull/${issueId}") case Right(objectId) => redirect(s"/${repository.owner}/${repository.name}/pull/$issueId")
case Left(message) => Some(BadRequest(message)) case Left(message) => Some(BadRequest(message))
} }
} getOrElse NotFound() } getOrElse NotFound()
@@ -380,29 +372,27 @@ trait PullRequestsControllerBase extends ControllerBase {
val headBranch = params.get("head") val headBranch = params.get("head")
(forkedRepository.repository.originUserName, forkedRepository.repository.originRepositoryName) match { (forkedRepository.repository.originUserName, forkedRepository.repository.originRepositoryName) match {
case (Some(originUserName), Some(originRepositoryName)) => case (Some(originUserName), Some(originRepositoryName)) =>
getRepository(originUserName, originRepositoryName).map { getRepository(originUserName, originRepositoryName).map { originRepository =>
originRepository => Using.resources(
Using.resources( Git.open(getRepositoryDir(originUserName, originRepositoryName)),
Git.open(getRepositoryDir(originUserName, originRepositoryName)), Git.open(getRepositoryDir(forkedRepository.owner, forkedRepository.name))
Git.open(getRepositoryDir(forkedRepository.owner, forkedRepository.name)) ) { (oldGit, newGit) =>
) { (oldGit, newGit) => val newBranch = headBranch.getOrElse(JGitUtil.getDefaultBranch(newGit, forkedRepository).get._2)
val newBranch = headBranch.getOrElse(JGitUtil.getDefaultBranch(newGit, forkedRepository).get._2) val oldBranch = originRepository.branchList
val oldBranch = originRepository.branchList .find(_ == newBranch)
.find(_ == newBranch) .getOrElse(JGitUtil.getDefaultBranch(oldGit, originRepository).get._2)
.getOrElse(JGitUtil.getDefaultBranch(oldGit, originRepository).get._2)
redirect( redirect(
s"/${forkedRepository.owner}/${forkedRepository.name}/compare/${originUserName}:${oldBranch}...${newBranch}" s"/${forkedRepository.owner}/${forkedRepository.name}/compare/$originUserName:$oldBranch...$newBranch"
) )
} }
} getOrElse NotFound() } getOrElse NotFound()
case _ => case _ =>
Using.resource(Git.open(getRepositoryDir(forkedRepository.owner, forkedRepository.name))) { git => Using.resource(Git.open(getRepositoryDir(forkedRepository.owner, forkedRepository.name))) { git =>
JGitUtil.getDefaultBranch(git, forkedRepository).map { JGitUtil.getDefaultBranch(git, forkedRepository).map { case (_, defaultBranch) =>
case (_, defaultBranch) => redirect(
redirect( s"/${forkedRepository.owner}/${forkedRepository.name}/compare/$defaultBranch...${headBranch.getOrElse(defaultBranch)}"
s"/${forkedRepository.owner}/${forkedRepository.name}/compare/${defaultBranch}...${headBranch.getOrElse(defaultBranch)}" )
)
} getOrElse { } getOrElse {
redirect(s"/${forkedRepository.owner}/${forkedRepository.name}") redirect(s"/${forkedRepository.owner}/${forkedRepository.name}")
} }
@@ -423,7 +413,7 @@ trait PullRequestsControllerBase extends ControllerBase {
getForkedRepositories(forkedRepository.owner, forkedRepository.name) getForkedRepositories(forkedRepository.owner, forkedRepository.name)
.find(_.userName == originOwner) .find(_.userName == originOwner)
.map(_.repositoryName) .map(_.repositoryName)
} else if (Some(originOwner) == forkedRepository.repository.originUserName) { } else if (forkedRepository.repository.originUserName.contains(originOwner)) {
// Original repository // Original repository
forkedRepository.repository.originRepositoryName forkedRepository.repository.originRepositoryName
} else { } else {
@@ -442,8 +432,10 @@ trait PullRequestsControllerBase extends ControllerBase {
val (originOwner, originId) = parseCompareIdentifier(origin, forkedRepository.owner) val (originOwner, originId) = parseCompareIdentifier(origin, forkedRepository.owner)
val (forkedOwner, forkedId) = parseCompareIdentifier(forked, forkedRepository.owner) val (forkedOwner, forkedId) = parseCompareIdentifier(forked, forkedRepository.owner)
(for (originRepositoryName <- getOriginRepositoryName(originOwner, forkedOwner, forkedRepository); (for (
originRepository <- getRepository(originOwner, originRepositoryName)) yield { originRepositoryName <- getOriginRepositoryName(originOwner, forkedOwner, forkedRepository);
originRepository <- getRepository(originOwner, originRepositoryName)
) yield {
val (oldId, newId) = val (oldId, newId) =
getPullRequestCommitFromTo(originRepository, forkedRepository, originId, forkedId) getPullRequestCommitFromTo(originRepository, forkedRepository, originId, forkedId)
@@ -455,7 +447,8 @@ trait PullRequestsControllerBase extends ControllerBase {
oldId.getName, oldId.getName,
forkedRepository.owner, forkedRepository.owner,
forkedRepository.name, forkedRepository.name,
newId.getName newId.getName,
context.settings
) )
val title = if (commits.flatten.length == 1) { val title = if (commits.flatten.length == 1) {
@@ -481,7 +474,9 @@ trait PullRequestsControllerBase extends ControllerBase {
(repository.userName, repository.repositoryName, repository.defaultBranch) (repository.userName, repository.repositoryName, repository.defaultBranch)
}, },
commits.flatten commits.flatten
.flatMap(commit => getCommitComments(forkedRepository.owner, forkedRepository.name, commit.id, false)) .flatMap(commit =>
getCommitComments(forkedRepository.owner, forkedRepository.name, commit.id, includePullRequest = false)
)
.toList, .toList,
originId, originId,
forkedId, forkedId,
@@ -502,8 +497,8 @@ trait PullRequestsControllerBase extends ControllerBase {
case (oldId, newId) => case (oldId, newId) =>
redirect( redirect(
s"/${forkedRepository.owner}/${forkedRepository.name}/compare/" + s"/${forkedRepository.owner}/${forkedRepository.name}/compare/" +
s"${originOwner}:${oldId.map(_ => originId).getOrElse(originRepository.repository.defaultBranch)}..." + s"$originOwner:${oldId.map(_ => originId).getOrElse(originRepository.repository.defaultBranch)}..." +
s"${forkedOwner}:${newId.map(_ => forkedId).getOrElse(forkedRepository.repository.defaultBranch)}" s"$forkedOwner:${newId.map(_ => forkedId).getOrElse(forkedRepository.repository.defaultBranch)}"
) )
} }
@@ -563,87 +558,88 @@ trait PullRequestsControllerBase extends ControllerBase {
val (originOwner, tmpOriginBranch) = parseCompareIdentifier(origin, forkedRepository.owner) val (originOwner, tmpOriginBranch) = parseCompareIdentifier(origin, forkedRepository.owner)
val (forkedOwner, tmpForkedBranch) = parseCompareIdentifier(forked, forkedRepository.owner) val (forkedOwner, tmpForkedBranch) = parseCompareIdentifier(forked, forkedRepository.owner)
(for (originRepositoryName <- if (originOwner == forkedOwner) { (for {
Some(forkedRepository.name) originRepositoryName <-
} else { if (originOwner == forkedOwner) {
forkedRepository.repository.originRepositoryName.orElse { Some(forkedRepository.name)
getForkedRepositories(forkedRepository.owner, forkedRepository.name) } else {
.find(_.userName == originOwner) forkedRepository.repository.originRepositoryName.orElse {
.map(_.repositoryName) getForkedRepositories(forkedRepository.owner, forkedRepository.name)
} .find(_.userName == originOwner)
}; .map(_.repositoryName)
originRepository <- getRepository(originOwner, originRepositoryName)) yield { }
}
originRepository <- getRepository(originOwner, originRepositoryName)
} yield {
Using.resources( Using.resources(
Git.open(getRepositoryDir(originRepository.owner, originRepository.name)), Git.open(getRepositoryDir(originRepository.owner, originRepository.name)),
Git.open(getRepositoryDir(forkedRepository.owner, forkedRepository.name)) Git.open(getRepositoryDir(forkedRepository.owner, forkedRepository.name))
) { ) { case (oldGit, newGit) =>
case (oldGit, newGit) => val originBranch = JGitUtil.getDefaultBranch(oldGit, originRepository, tmpOriginBranch).get._2
val originBranch = JGitUtil.getDefaultBranch(oldGit, originRepository, tmpOriginBranch).get._2 val forkedBranch = JGitUtil.getDefaultBranch(newGit, forkedRepository, tmpForkedBranch).get._2
val forkedBranch = JGitUtil.getDefaultBranch(newGit, forkedRepository, tmpForkedBranch).get._2 val conflict = LockUtil.lock(s"${originRepository.owner}/${originRepository.name}") {
val conflict = LockUtil.lock(s"${originRepository.owner}/${originRepository.name}") { checkConflict(
checkConflict( originRepository.owner,
originRepository.owner, originRepository.name,
originRepository.name, originBranch,
originBranch, forkedRepository.owner,
forkedRepository.owner, forkedRepository.name,
forkedRepository.name, forkedBranch
forkedBranch )
) }
} html.mergecheck(conflict.isDefined)
html.mergecheck(conflict.isDefined)
} }
}) getOrElse NotFound() }) getOrElse NotFound()
}) })
post("/:owner/:repository/pulls/new", pullRequestForm)(readableUsersOnly { (form, repository) => post("/:owner/:repository/pulls/new", pullRequestForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => val manageable = isManageable(repository)
val manageable = isManageable(repository)
val issueId = insertIssue( val issueId = insertIssue(
owner = repository.owner, owner = repository.owner,
repository = repository.name, repository = repository.name,
loginUser = loginAccount.userName, loginUser = loginAccount.userName,
title = form.title, title = form.title,
content = form.content, content = form.content,
milestoneId = if (manageable) form.milestoneId else None, milestoneId = if (manageable) form.milestoneId else None,
priorityId = if (manageable) form.priorityId else None, priorityId = if (manageable) form.priorityId else None,
isPullRequest = true isPullRequest = true
) )
createPullRequest( createPullRequest(
originRepository = repository, originRepository = repository,
issueId = issueId, issueId = issueId,
originBranch = form.targetBranch, originBranch = form.targetBranch,
requestUserName = form.requestUserName, requestUserName = form.requestUserName,
requestRepositoryName = form.requestRepositoryName, requestRepositoryName = form.requestRepositoryName,
requestBranch = form.requestBranch, requestBranch = form.requestBranch,
commitIdFrom = form.commitIdFrom, commitIdFrom = form.commitIdFrom,
commitIdTo = form.commitIdTo, commitIdTo = form.commitIdTo,
isDraft = form.isDraft, isDraft = form.isDraft,
loginAccount = loginAccount, loginAccount = loginAccount,
settings = context.settings settings = context.settings
) )
if (manageable) { if (manageable) {
// insert assignees // insert assignees
form.assigneeUserNames.foreach { value => form.assigneeUserNames.foreach { value =>
value.split(",").foreach { userName => value.split(",").foreach { userName =>
registerIssueAssignee(repository.owner, repository.name, issueId, userName) registerIssueAssignee(repository.owner, repository.name, issueId, userName)
}
} }
// insert labels }
form.labelNames.foreach { value => // insert labels
val labels = getLabels(repository.owner, repository.name) form.labelNames.foreach { value =>
value.split(",").foreach { labelName => val labels = getLabels(repository.owner, repository.name)
labels.find(_.labelName == labelName).map { label => value.split(",").foreach { labelName =>
registerIssueLabel(repository.owner, repository.name, issueId, label.labelId) labels.find(_.labelName == labelName).map { label =>
} registerIssueLabel(repository.owner, repository.name, issueId, label.labelId)
} }
} }
} }
}
redirect(s"/${repository.owner}/${repository.name}/pull/${issueId}") redirect(s"/${repository.owner}/${repository.name}/pull/$issueId")
} }
}) })
@@ -653,24 +649,23 @@ trait PullRequestsControllerBase extends ControllerBase {
context.loginAccount.map(x => Seq(x.mailAddress) ++ getAccountExtraMailAddresses(x.userName)).getOrElse(Nil) context.loginAccount.map(x => Seq(x.mailAddress) ++ getAccountExtraMailAddresses(x.userName)).getOrElse(Nil)
val branches = val branches =
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
git => JGitUtil
JGitUtil .getBranches(
.getBranches( git = git,
git = git, defaultBranch = repository.repository.defaultBranch,
defaultBranch = repository.repository.defaultBranch, origin = repository.repository.originUserName.isEmpty
origin = repository.repository.originUserName.isEmpty )
) .filter { x =>
.filter { x => x.mergeInfo.map(_.ahead).getOrElse(0) > 0 && x.mergeInfo.map(_.behind).getOrElse(0) == 0 &&
x.mergeInfo.map(_.ahead).getOrElse(0) > 0 && x.mergeInfo.map(_.behind).getOrElse(0) == 0 && x.commitTime.getTime > thresholdTime &&
x.commitTime.getTime > thresholdTime && mailAddresses.contains(x.committerEmailAddress)
mailAddresses.contains(x.committerEmailAddress) }
} .sortBy { br =>
.sortBy { br => (br.mergeInfo.isEmpty, br.commitTime)
(br.mergeInfo.isEmpty, br.commitTime) }
} .map(_.name)
.map(_.name) .reverse
.reverse
} }
val targetRepository = (for { val targetRepository = (for {
@@ -690,10 +685,11 @@ trait PullRequestsControllerBase extends ControllerBase {
html.proposals(proposedBranches, targetRepository, repository) html.proposals(proposedBranches, targetRepository, repository)
}) })
private def searchPullRequests(userName: Option[String], repository: RepositoryService.RepositoryInfo) = { private def searchPullRequests(
val page = IssueSearchCondition.page(request) repository: RepositoryService.RepositoryInfo,
// retrieve search condition condition: IssueSearchCondition,
val condition = IssueSearchCondition(request) page: Int
) = {
// search issues // search issues
val issues = searchIssue( val issues = searchIssue(
condition, condition,

View File

@@ -11,10 +11,10 @@ import gitbucket.core.service.{
RepositoryService, RepositoryService,
RequestCache 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.*
import org.scalatra.forms._ import org.scalatra.forms.*
import gitbucket.core.releases.html import gitbucket.core.releases.html
import org.apache.commons.io.FileUtils import org.apache.commons.io.FileUtils
import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.Git
@@ -33,20 +33,15 @@ class ReleaseController
with RequestCache with RequestCache
trait ReleaseControllerBase extends ControllerBase { trait ReleaseControllerBase extends ControllerBase {
self: RepositoryService self: RepositoryService & AccountService & ReleaseService & ReadableUsersAuthenticator & ReferrerAuthenticator &
with AccountService WritableUsersAuthenticator & ActivityService =>
with ReleaseService
with ReadableUsersAuthenticator
with ReferrerAuthenticator
with WritableUsersAuthenticator
with ActivityService =>
case class ReleaseForm( private case class ReleaseForm(
name: String, name: String,
content: Option[String] content: Option[String]
) )
val releaseForm = mapping( private val releaseForm = mapping(
"name" -> trim(text(required)), "name" -> trim(text(required)),
"content" -> trim(optional(text())) "content" -> trim(optional(text()))
)(ReleaseForm.apply) )(ReleaseForm.apply)
@@ -106,42 +101,39 @@ trait ReleaseControllerBase extends ControllerBase {
}) })
post("/:owner/:repository/releases/*/create", releaseForm)(writableUsersOnly { (form, repository) => post("/:owner/:repository/releases/*/create", releaseForm)(writableUsersOnly { (form, repository) =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => val tagName = multiParams("splat").head
val tagName = multiParams("splat").head
// Insert into RELEASE // Insert into RELEASE
createRelease(repository.owner, repository.name, form.name, form.content, tagName, loginAccount) createRelease(repository.owner, repository.name, form.name, form.content, tagName, loginAccount)
// Insert into RELEASE_ASSET // Insert into RELEASE_ASSET
val files = params.toMap.collect { val files = params.toMap.collect {
case (name, value) if name.startsWith("file:") => case (name, value) if name.startsWith("file:") =>
val Array(_, fileId) = name.split(":") val Array(_, fileId) = name.split(":")
(fileId, value) (fileId, value)
} }
files.foreach { files.foreach { case (fileId, fileName) =>
case (fileId, fileName) => val size =
val size = new File(
new File( getReleaseFilesDir(repository.owner, repository.name),
getReleaseFilesDir(repository.owner, repository.name), FileUtil.checkFilename(tagName + "/" + fileId)
FileUtil.checkFilename(tagName + "/" + fileId) ).length
).length 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) val releaseInfo = ReleaseInfo(repository.owner, repository.name, loginAccount.userName, form.name, tagName)
recordActivity(releaseInfo) recordActivity(releaseInfo)
redirect(s"/${repository.owner}/${repository.name}/releases/${tagName}") redirect(s"/${repository.owner}/${repository.name}/releases/$tagName")
} }
}) })
get("/:owner/:repository/changelog/*...*")(writableUsersOnly { repository => get("/:owner/:repository/changelog/*...*")(writableUsersOnly { repository =>
val Seq(previousTag, currentTag) = multiParams("splat")
val previousTagId = repository.tags.collectFirst { case x if x.name == previousTag => x.commitId }.getOrElse("")
val commitLog = Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git => val commitLog = Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
val commits = JGitUtil.getCommitLog(git, previousTagId, currentTag).reverse val Seq(previousTag, currentTag) = multiParams("splat")
val commits = JGitUtil.getCommitLog(git, previousTag, currentTag).reverse
commits commits
.map { commit => .map { commit =>
s"- ${commit.shortMessage} ${commit.id}" s"- ${commit.shortMessage} ${commit.id}"
@@ -171,48 +163,45 @@ trait ReleaseControllerBase extends ControllerBase {
}) })
post("/:owner/:repository/releases/*/edit", releaseForm)(writableUsersOnly { (form, repository) => post("/:owner/:repository/releases/*/edit", releaseForm)(writableUsersOnly { (form, repository) =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => val tagName = multiParams("splat").head
val tagName = multiParams("splat").head
getRelease(repository.owner, repository.name, tagName) getRelease(repository.owner, repository.name, tagName)
.map { .map { release =>
release => // Update RELEASE
// Update RELEASE updateRelease(repository.owner, repository.name, tagName, form.name, form.content)
updateRelease(repository.owner, repository.name, tagName, form.name, form.content)
// Delete and Insert RELEASE_ASSET // Delete and Insert RELEASE_ASSET
val assets = getReleaseAssets(repository.owner, repository.name, tagName) val assets = getReleaseAssets(repository.owner, repository.name, tagName)
deleteReleaseAssets(repository.owner, repository.name, tagName) deleteReleaseAssets(repository.owner, repository.name, tagName)
val files = params.toMap.collect { val files = params.toMap.collect {
case (name, value) if name.startsWith("file:") => case (name, value) if name.startsWith("file:") =>
val Array(_, fileId) = name.split(":") val Array(_, fileId) = name.split(":")
(fileId, value) (fileId, value)
}
files.foreach {
case (fileId, fileName) =>
val size =
new File(
getReleaseFilesDir(repository.owner, repository.name),
FileUtil.checkFilename(tagName + "/" + fileId)
).length
createReleaseAsset(repository.owner, repository.name, tagName, fileId, fileName, size, loginAccount)
}
assets.foreach { asset =>
if (!files.exists { case (fileId, _) => fileId == asset.fileName }) {
val file = new File(
getReleaseFilesDir(repository.owner, repository.name),
FileUtil.checkFilename(release.tag + "/" + asset.fileName)
)
FileUtils.forceDelete(file)
}
}
redirect(s"/${release.userName}/${release.repositoryName}/releases/${tagName}")
} }
.getOrElse(NotFound()) files.foreach { case (fileId, fileName) =>
val size =
new File(
getReleaseFilesDir(repository.owner, repository.name),
FileUtil.checkFilename(tagName + "/" + fileId)
).length
createReleaseAsset(repository.owner, repository.name, tagName, fileId, fileName, size, loginAccount)
}
assets.foreach { asset =>
if (!files.exists { case (fileId, _) => fileId == asset.fileName }) {
val file = new File(
getReleaseFilesDir(repository.owner, repository.name),
FileUtil.checkFilename(release.tag + "/" + asset.fileName)
)
FileUtils.forceDelete(file)
}
}
redirect(s"/${release.userName}/${release.repositoryName}/releases/$tagName")
}
.getOrElse(NotFound())
} }
}) })
@@ -228,7 +217,7 @@ trait ReleaseControllerBase extends ControllerBase {
}) })
private def fetchReleases(repository: RepositoryService.RepositoryInfo, page: Int) = { private def fetchReleases(repository: RepositoryService.RepositoryInfo, page: Int) = {
import gitbucket.core.service.ReleaseService._ import gitbucket.core.service.ReleaseService.*
val (offset, limit) = ((page - 1) * ReleaseLimit, ReleaseLimit) val (offset, limit) = ((page - 1) * ReleaseLimit, ReleaseLimit)
val tagsToDisplay = repository.tags.reverse.slice(offset, offset + limit) val tagsToDisplay = repository.tags.reverse.slice(offset, offset + limit)
@@ -237,9 +226,12 @@ trait ReleaseControllerBase extends ControllerBase {
val assets = getReleaseAssetsMap(repository.owner, repository.name, releases) val assets = getReleaseAssetsMap(repository.owner, repository.name, releases)
val tagsWithReleases = tagsToDisplay.map { tag => val tagsWithReleases = tagsToDisplay.map { tag =>
(tag, releases.find(_.tag == tag.name).map { release => (
(release, assets(release)) tag,
}) releases.find(_.tag == tag.name).map { release =>
(release, assets(release))
}
)
} }
tagsWithReleases tagsWithReleases
} }

View File

@@ -4,16 +4,16 @@ import java.time.{LocalDateTime, ZoneOffset}
import java.util.Date import java.util.Date
import gitbucket.core.settings.html import gitbucket.core.settings.html
import gitbucket.core.model.{RepositoryWebHook, WebHook} import gitbucket.core.model.{RepositoryWebHook, WebHook}
import gitbucket.core.service._ import gitbucket.core.service.*
import gitbucket.core.service.WebHookService._ import gitbucket.core.service.WebHookService.*
import gitbucket.core.util._ import gitbucket.core.util.*
import gitbucket.core.util.JGitUtil._ import gitbucket.core.util.JGitUtil.*
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.WebHookContentType import gitbucket.core.model.WebHookContentType
import gitbucket.core.model.activity.RenameRepositoryInfo 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
import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.lib.Constants
@@ -37,19 +37,11 @@ class RepositorySettingsController
with RequestCache with RequestCache
trait RepositorySettingsControllerBase extends ControllerBase { trait RepositorySettingsControllerBase extends ControllerBase {
self: RepositoryService self: RepositoryService & AccountService & WebHookService & ProtectedBranchService & CommitStatusService &
with AccountService DeployKeyService & CustomFieldsService & ActivityService & OwnerAuthenticator & UsersAuthenticator =>
with WebHookService
with ProtectedBranchService
with CommitStatusService
with DeployKeyService
with CustomFieldsService
with ActivityService
with OwnerAuthenticator
with UsersAuthenticator =>
// for repository options // for repository options
case class OptionsForm( private case class OptionsForm(
description: Option[String], description: Option[String],
isPrivate: Boolean, isPrivate: Boolean,
issuesOption: String, issuesOption: String,
@@ -62,7 +54,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
safeMode: Boolean safeMode: Boolean
) )
val optionsForm = mapping( private val optionsForm = mapping(
"description" -> trim(label("Description", optional(text()))), "description" -> trim(label("Description", optional(text()))),
"isPrivate" -> trim(label("Repository Type", boolean())), "isPrivate" -> trim(label("Repository Type", boolean())),
"issuesOption" -> trim(label("Issues Option", text(required, featureOption))), "issuesOption" -> trim(label("Issues Option", text(required, featureOption))),
@@ -80,25 +72,30 @@ trait RepositorySettingsControllerBase extends ControllerBase {
} }
// for default branch // for default branch
case class DefaultBranchForm(defaultBranch: String) private case class DefaultBranchForm(defaultBranch: String)
val defaultBranchForm = mapping( private val defaultBranchForm = mapping(
"defaultBranch" -> trim(label("Default Branch", text(required, maxlength(100)))) "defaultBranch" -> trim(label("Default Branch", text(required, maxlength(100))))
)(DefaultBranchForm.apply) )(DefaultBranchForm.apply)
// for deploy key // for deploy key
case class DeployKeyForm(title: String, publicKey: String, allowWrite: Boolean) private case class DeployKeyForm(title: String, publicKey: String, allowWrite: Boolean)
val deployKeyForm = mapping( private val deployKeyForm = mapping(
"title" -> trim(label("Title", text(required, maxlength(100)))), "title" -> trim(label("Title", text(required, maxlength(100)))),
"publicKey" -> trim2(label("Key", text(required))), // TODO duplication check in the repository? "publicKey" -> trim2(label("Key", text(required))), // TODO duplication check in the repository?
"allowWrite" -> trim(label("Key", boolean())) "allowWrite" -> trim(label("Key", boolean()))
)(DeployKeyForm.apply) )(DeployKeyForm.apply)
// for web hook url addition // for web hook url addition
case class WebHookForm(url: String, events: Set[WebHook.Event], ctype: WebHookContentType, token: Option[String]) private case class WebHookForm(
url: String,
events: Set[WebHook.Event],
ctype: WebHookContentType,
token: Option[String]
)
def webHookForm(update: Boolean) = private def webHookForm(update: Boolean) =
mapping( mapping(
"url" -> trim(label("url", text(required, webHook(update)))), "url" -> trim(label("url", text(required, webHook(update)))),
"events" -> webhookEvents, "events" -> webhookEvents,
@@ -107,32 +104,34 @@ trait RepositorySettingsControllerBase extends ControllerBase {
)((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) private case class RenameRepositoryForm(repositoryName: String)
val renameForm = mapping( private val renameForm = mapping(
"repositoryName" -> trim( "repositoryName" -> trim(
label("New repository name", text(required, maxlength(100), repository, renameRepositoryName)) label("New repository name", text(required, maxlength(100), repository, renameRepositoryName))
) )
)(RenameRepositoryForm.apply) )(RenameRepositoryForm.apply)
// for transfer ownership // for transfer ownership
case class TransferOwnerShipForm(newOwner: String) private case class TransferOwnerShipForm(newOwner: String)
val transferForm = mapping( private val transferForm = mapping(
"newOwner" -> trim(label("New owner", text(required, transferUser))) "newOwner" -> trim(label("New owner", text(required, transferUser)))
)(TransferOwnerShipForm.apply) )(TransferOwnerShipForm.apply)
// for custom field // for custom field
case class CustomFieldForm( private case class CustomFieldForm(
fieldName: String, fieldName: String,
fieldType: String, fieldType: String,
constraints: Option[String],
enableForIssues: Boolean, enableForIssues: Boolean,
enableForPullRequests: Boolean enableForPullRequests: Boolean
) )
val customFieldForm = mapping( private val customFieldForm = mapping(
"fieldName" -> trim(label("Field name", text(required, maxlength(100)))), "fieldName" -> trim(label("Field name", text(required, maxlength(100)))),
"fieldType" -> trim(label("Field type", text(required))), "fieldType" -> trim(label("Field type", text(required))),
"constraints" -> trim(label("Constraints", optional(text()))),
"enableForIssues" -> trim(label("Enable for issues", boolean(required))), "enableForIssues" -> trim(label("Enable for issues", boolean(required))),
"enableForPullRequests" -> trim(label("Enable for pull requests", boolean(required))), "enableForPullRequests" -> trim(label("Enable for pull requests", boolean(required))),
)(CustomFieldForm.apply) )(CustomFieldForm.apply)
@@ -184,7 +183,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
/** Update default branch */ /** Update default branch */
post("/:owner/:repository/settings/update_default_branch", defaultBranchForm)(ownerOnly { (form, repository) => post("/:owner/:repository/settings/update_default_branch", defaultBranchForm)(ownerOnly { (form, repository) =>
if (!repository.branchList.contains(form.defaultBranch)) { if (!repository.branchList.contains(form.defaultBranch)) {
redirect(s"/${repository.owner}/${repository.name}/settings/options") redirect(s"/${repository.owner}/${repository.name}/settings/branches")
} else { } else {
saveRepositoryDefaultBranch(repository.owner, repository.name, form.defaultBranch) saveRepositoryDefaultBranch(repository.owner, repository.name, form.defaultBranch)
// Change repository HEAD // Change repository HEAD
@@ -198,13 +197,13 @@ trait RepositorySettingsControllerBase extends ControllerBase {
/** Branch protection for branch */ /** Branch protection for branch */
get("/:owner/:repository/settings/branches/*")(ownerOnly { repository => get("/:owner/:repository/settings/branches/*")(ownerOnly { repository =>
import gitbucket.core.api._ import gitbucket.core.api.*
val branch = params("splat") val branch = params("splat")
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 = ApiBranchProtectionResponse(getProtectedBranchInfo(repository.owner, repository.name, branch))
val lastWeeks = getRecentStatusContexts( val lastWeeks = getRecentStatusContexts(
repository.owner, repository.owner,
repository.name, repository.name,
@@ -254,7 +253,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
ctype = WebHookContentType.FORM, ctype = WebHookContentType.FORM,
token = None token = None
) )
html.edithook(webhook, Set(WebHook.Push), repository, true) html.edithook(webhook, Set(WebHook.Push), repository, create = true)
}) })
/** /**
@@ -284,93 +283,90 @@ trait RepositorySettingsControllerBase extends ControllerBase {
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 => import scala.concurrent.duration.*
import scala.concurrent.duration._ import scala.concurrent.*
import scala.concurrent._ import scala.jdk.CollectionConverters.*
import scala.jdk.CollectionConverters._ import scala.util.control.NonFatal
import scala.util.control.NonFatal import org.apache.http.util.EntityUtils
import org.apache.http.util.EntityUtils import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.ExecutionContext.Implicits.global
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(
userName = repository.owner, userName = repository.owner,
repositoryName = repository.name, repositoryName = repository.name,
url = url, url = url,
ctype = ctype, ctype = ctype,
token = token token = token
)
val dummyPayload = {
val ownerAccount = getAccountByUserName(repository.owner).get
val commits =
if (JGitUtil.isEmpty(git)) List.empty
else
git.log
.add(git.getRepository.resolve(repository.repository.defaultBranch))
.setMaxCount(4)
.call
.iterator
.asScala
.map(new CommitInfo(_))
.toList
val pushedCommit = commits.drop(1)
WebHookPushPayload(
git = git,
sender = ownerAccount,
refName = "refs/heads/" + repository.repository.defaultBranch,
repositoryInfo = repository,
commits = pushedCommit,
repositoryOwner = ownerAccount,
oldId = commits.lastOption.map(_.id).map(ObjectId.fromString).getOrElse(ObjectId.zeroId()),
newId = commits.headOption.map(_.id).map(ObjectId.fromString).getOrElse(ObjectId.zeroId())
) )
val dummyPayload = { }
val ownerAccount = getAccountByUserName(repository.owner).get
val commits =
if (JGitUtil.isEmpty(git)) List.empty
else
git.log
.add(git.getRepository.resolve(repository.repository.defaultBranch))
.setMaxCount(4)
.call
.iterator
.asScala
.map(new CommitInfo(_))
.toList
val pushedCommit = commits.drop(1)
WebHookPushPayload( val (webHook, json, reqFuture, resFuture) =
git = git, callWebHook(WebHook.Push, List(dummyWebHookInfo), dummyPayload, context.settings).head
sender = ownerAccount,
refName = "refs/heads/" + repository.repository.defaultBranch,
repositoryInfo = repository,
commits = pushedCommit,
repositoryOwner = ownerAccount,
oldId = commits.lastOption.map(_.id).map(ObjectId.fromString).getOrElse(ObjectId.zeroId()),
newId = commits.headOption.map(_.id).map(ObjectId.fromString).getOrElse(ObjectId.zeroId())
)
}
val (webHook, json, reqFuture, resFuture) = val toErrorMap: PartialFunction[Throwable, Map[String, String]] = {
callWebHook(WebHook.Push, List(dummyWebHookInfo), dummyPayload, context.settings).head case e: java.net.UnknownHostException => Map("error" -> s"Unknown host ${e.getMessage}")
case _: java.lang.IllegalArgumentException => Map("error" -> "invalid url")
case _: org.apache.http.client.ClientProtocolException => Map("error" -> "invalid url")
case NonFatal(e) => Map("error" -> s"${e.getClass} ${e.getMessage}")
}
val toErrorMap: PartialFunction[Throwable, Map[String, String]] = { contentType = formats("json")
case e: java.net.UnknownHostException => Map("error" -> ("Unknown host " + e.getMessage)) org.json4s.jackson.Serialization.write(
case e: java.lang.IllegalArgumentException => Map("error" -> ("invalid url")) Map(
case e: org.apache.http.client.ClientProtocolException => Map("error" -> ("invalid url")) "url" -> url,
case NonFatal(e) => Map("error" -> (s"${e.getClass} ${e.getMessage}")) "request" -> Await.result(
} reqFuture
.map(req =>
contentType = formats("json") Map(
org.json4s.jackson.Serialization.write( "headers" -> _headers(req.getAllHeaders),
Map( "payload" -> json
"url" -> url,
"request" -> Await.result(
reqFuture
.map(
req =>
Map(
"headers" -> _headers(req.getAllHeaders),
"payload" -> json
)
) )
.recover(toErrorMap), )
20 seconds .recover(toErrorMap),
), 20 seconds
"response" -> Await.result( ),
resFuture "response" -> Await.result(
.map( resFuture
res => .map(res =>
Map( Map(
"status" -> res.getStatusLine.getStatusCode, "status" -> res.getStatusLine.getStatusCode,
"body" -> EntityUtils.toString(res.getEntity()), "body" -> EntityUtils.toString(res.getEntity),
"headers" -> _headers(res.getAllHeaders()) "headers" -> _headers(res.getAllHeaders)
)
) )
.recover(toErrorMap), )
20 seconds .recover(toErrorMap),
) 20 seconds
) )
) )
)
} }
}) })
@@ -378,9 +374,8 @@ trait RepositorySettingsControllerBase extends ControllerBase {
* Display the web hook edit page. * Display the web hook edit page.
*/ */
get("/:owner/:repository/settings/hooks/edit")(ownerOnly { repository => get("/:owner/:repository/settings/hooks/edit")(ownerOnly { repository =>
getWebHook(repository.owner, repository.name, params("url")).map { getWebHook(repository.owner, repository.name, params("url")).map { case (webhook, events) =>
case (webhook, events) => html.edithook(webhook, events, repository, create = false)
html.edithook(webhook, events, repository, false)
} getOrElse NotFound() } getOrElse NotFound()
}) })
@@ -404,23 +399,22 @@ trait RepositorySettingsControllerBase extends ControllerBase {
* Rename repository. * Rename repository.
*/ */
post("/:owner/:repository/settings/rename", renameForm)(ownerOnly { (form, repository) => post("/:owner/:repository/settings/rename", renameForm)(ownerOnly { (form, repository) =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => if (context.settings.basicBehavior.repositoryOperation.rename || loginAccount.isAdmin) {
if (context.settings.basicBehavior.repositoryOperation.rename || loginAccount.isAdmin) { if (repository.name != form.repositoryName) {
if (repository.name != form.repositoryName) { // Update database and move git repository
// 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
// Record activity log val renameInfo = RenameRepositoryInfo(
val renameInfo = RenameRepositoryInfo( repository.owner,
repository.owner, form.repositoryName,
form.repositoryName, loginAccount.userName,
loginAccount.userName, repository.name
repository.name )
) recordActivity(renameInfo)
recordActivity(renameInfo) }
} redirect(s"/${repository.owner}/${form.repositoryName}")
redirect(s"/${repository.owner}/${form.repositoryName}") } else Forbidden()
} else Forbidden()
} }
}) })
@@ -428,24 +422,23 @@ trait RepositorySettingsControllerBase extends ControllerBase {
* Transfer repository ownership. * Transfer repository ownership.
*/ */
post("/:owner/:repository/settings/transfer", transferForm)(ownerOnly { (form, repository) => post("/:owner/:repository/settings/transfer", transferForm)(ownerOnly { (form, repository) =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => if (context.settings.basicBehavior.repositoryOperation.transfer || loginAccount.isAdmin) {
if (context.settings.basicBehavior.repositoryOperation.transfer || loginAccount.isAdmin) { // Change repository owner
// Change repository owner if (repository.owner != form.newOwner) {
if (repository.owner != form.newOwner) { // Update database and move git repository
// 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
// Record activity log val renameInfo = RenameRepositoryInfo(
val renameInfo = RenameRepositoryInfo( form.newOwner,
form.newOwner, repository.name,
repository.name, loginAccount.userName,
loginAccount.userName, repository.owner
repository.owner )
) recordActivity(renameInfo)
recordActivity(renameInfo) }
} redirect(s"/${form.newOwner}/${repository.name}")
redirect(s"/${form.newOwner}/${repository.name}") } else Forbidden()
} else Forbidden()
} }
}) })
@@ -511,6 +504,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
repository.name, repository.name,
form.fieldName, form.fieldName,
form.fieldType, form.fieldType,
if (form.fieldType == "enum") form.constraints else None,
form.enableForIssues, form.enableForIssues,
form.enableForPullRequests form.enableForPullRequests
) )
@@ -533,6 +527,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
params("fieldId").toInt, params("fieldId").toInt,
form.fieldName, form.fieldName,
form.fieldType, form.fieldType,
if (form.fieldType == "enum") form.constraints else None,
form.enableForIssues, form.enableForIssues,
form.enableForPullRequests form.enableForPullRequests
) )
@@ -633,7 +628,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
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.")

View File

@@ -3,17 +3,17 @@ package gitbucket.core.controller
import java.io.FileInputStream import java.io.FileInputStream
import gitbucket.core.admin.html import gitbucket.core.admin.html
import gitbucket.core.plugin.PluginRegistry import gitbucket.core.plugin.PluginRegistry
import gitbucket.core.service.SystemSettingsService._ import gitbucket.core.service.SystemSettingsService.*
import gitbucket.core.service.{AccountService, RepositoryService} import gitbucket.core.service.{AccountService, RepositoryService}
import gitbucket.core.ssh.SshServer import gitbucket.core.ssh.SshServer
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits.*
import gitbucket.core.util.StringUtil._ import gitbucket.core.util.StringUtil.*
import gitbucket.core.util.{AdminAuthenticator, Mailer} import gitbucket.core.util.{AdminAuthenticator, Mailer}
import org.apache.commons.io.IOUtils import org.apache.commons.io.IOUtils
import org.apache.commons.mail.EmailException import org.apache.commons.mail.EmailException
import org.json4s.jackson.Serialization import org.json4s.jackson.Serialization
import org.scalatra._ import org.scalatra.*
import org.scalatra.forms._ import org.scalatra.forms.*
import org.scalatra.i18n.Messages import org.scalatra.i18n.Messages
import scala.collection.mutable.ListBuffer import scala.collection.mutable.ListBuffer
@@ -29,7 +29,7 @@ case class Table(name: String, columns: Seq[Column])
case class Column(name: String, primaryKey: Boolean) case class Column(name: String, primaryKey: Boolean)
trait SystemSettingsControllerBase extends AccountManagementControllerBase { trait SystemSettingsControllerBase extends AccountManagementControllerBase {
self: AccountService with RepositoryService with AdminAuthenticator => self: AccountService & RepositoryService & AdminAuthenticator =>
private val form = mapping( private val form = mapping(
"baseUrl" -> trim(label("Base URL", optional(text()))), "baseUrl" -> trim(label("Base URL", optional(text()))),
@@ -55,16 +55,14 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
"bindAddress" -> mapping( "bindAddress" -> mapping(
"host" -> trim(label("Bind SSH host", optional(text()))), "host" -> trim(label("Bind SSH host", optional(text()))),
"port" -> trim(label("Bind SSH port", optional(number()))), "port" -> trim(label("Bind SSH port", optional(number()))),
)( )((hostOption, portOption) =>
(hostOption, portOption) => hostOption.map(h => SshAddress(h, portOption.getOrElse(DefaultSshPort), GenericSshUser))
hostOption.map(h => SshAddress(h, portOption.getOrElse(DefaultSshPort), GenericSshUser))
), ),
"publicAddress" -> mapping( "publicAddress" -> mapping(
"host" -> trim(label("Public SSH host", optional(text()))), "host" -> trim(label("Public SSH host", optional(text()))),
"port" -> trim(label("Public SSH port", optional(number()))), "port" -> trim(label("Public SSH port", optional(number()))),
)( )((hostOption, portOption) =>
(hostOption, portOption) => hostOption.map(h => SshAddress(h, portOption.getOrElse(PublicSshPort), GenericSshUser))
hostOption.map(h => SshAddress(h, portOption.getOrElse(PublicSshPort), GenericSshUser))
), ),
)(Ssh.apply), )(Ssh.apply),
"useSMTP" -> trim(label("SMTP", boolean())), "useSMTP" -> trim(label("SMTP", boolean())),
@@ -123,8 +121,11 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
"largeTimeout" -> trim(label("Timeout for large file", long(required))) "largeTimeout" -> trim(label("Timeout for large file", long(required)))
)(Upload.apply), )(Upload.apply),
"repositoryViewer" -> mapping( "repositoryViewer" -> mapping(
"maxFiles" -> trim(label("Max files", number(required))) "maxFiles" -> trim(label("Max files", number(required))),
)(RepositoryViewerSettings.apply) "maxDiffFiles" -> trim(label("Max diff files", number(required))),
"maxDiffLines" -> trim(label("Max diff lines", number(required)))
)(RepositoryViewerSettings.apply),
"defaultBranch" -> trim(label("Default branch", text(required)))
)(SystemSettings.apply).verifying { settings => )(SystemSettings.apply).verifying { settings =>
Vector( Vector(
if (settings.ssh.enabled && settings.baseUrl.isEmpty) { if (settings.ssh.enabled && settings.baseUrl.isEmpty) {
@@ -150,11 +151,11 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
"testAddress" -> trim(label("", text(required))) "testAddress" -> trim(label("", text(required)))
)(SendMailForm.apply) )(SendMailForm.apply)
case class SendMailForm(smtp: Smtp, testAddress: String) private case class SendMailForm(smtp: Smtp, testAddress: String)
case class DataExportForm(tableNames: List[String]) // case class DataExportForm(tableNames: List[String])
case class NewUserForm( private case class NewUserForm(
userName: String, userName: String,
password: String, password: String,
fullName: String, fullName: String,
@@ -166,7 +167,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
fileId: Option[String] fileId: Option[String]
) )
case class EditUserForm( private case class EditUserForm(
userName: String, userName: String,
password: Option[String], password: Option[String],
fullName: String, fullName: String,
@@ -180,7 +181,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
isRemoved: Boolean isRemoved: Boolean
) )
case class NewGroupForm( private case class NewGroupForm(
groupName: String, groupName: String,
description: Option[String], description: Option[String],
url: Option[String], url: Option[String],
@@ -188,7 +189,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
members: String members: String
) )
case class EditGroupForm( private case class EditGroupForm(
groupName: String, groupName: String,
description: Option[String], description: Option[String],
url: Option[String], url: Option[String],
@@ -198,7 +199,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
isRemoved: Boolean isRemoved: Boolean
) )
val newUserForm = mapping( private val newUserForm = mapping(
"userName" -> trim(label("Username", text(required, maxlength(100), identifier, uniqueUserName, reservedNames))), "userName" -> trim(label("Username", text(required, maxlength(100), identifier, uniqueUserName, reservedNames))),
"password" -> trim(label("Password", text(required, maxlength(40)))), "password" -> trim(label("Password", text(required, maxlength(40)))),
"fullName" -> trim(label("Full Name", text(required, maxlength(100)))), "fullName" -> trim(label("Full Name", text(required, maxlength(100)))),
@@ -212,7 +213,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
"fileId" -> trim(label("File ID", optional(text()))) "fileId" -> trim(label("File ID", optional(text())))
)(NewUserForm.apply) )(NewUserForm.apply)
val editUserForm = mapping( private val editUserForm = mapping(
"userName" -> trim(label("Username", text(required, maxlength(100), identifier))), "userName" -> trim(label("Username", text(required, maxlength(100), identifier))),
"password" -> trim(label("Password", optional(text(maxlength(40))))), "password" -> trim(label("Password", optional(text(maxlength(40))))),
"fullName" -> trim(label("Full Name", text(required, maxlength(100)))), "fullName" -> trim(label("Full Name", text(required, maxlength(100)))),
@@ -228,7 +229,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
"removed" -> trim(label("Disable", boolean(disableByNotYourself("userName")))) "removed" -> trim(label("Disable", boolean(disableByNotYourself("userName"))))
)(EditUserForm.apply) )(EditUserForm.apply)
val newGroupForm = mapping( private val newGroupForm = mapping(
"groupName" -> trim(label("Group name", text(required, maxlength(100), identifier, uniqueUserName, reservedNames))), "groupName" -> trim(label("Group name", text(required, maxlength(100), identifier, uniqueUserName, reservedNames))),
"description" -> trim(label("Group description", optional(text()))), "description" -> trim(label("Group description", optional(text()))),
"url" -> trim(label("URL", optional(text(maxlength(200))))), "url" -> trim(label("URL", optional(text(maxlength(200))))),
@@ -236,7 +237,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
"members" -> trim(label("Members", text(required, members))) "members" -> trim(label("Members", text(required, members)))
)(NewGroupForm.apply) )(NewGroupForm.apply)
val editGroupForm = mapping( private val editGroupForm = mapping(
"groupName" -> trim(label("Group name", text(required, maxlength(100), identifier))), "groupName" -> trim(label("Group name", text(required, maxlength(100), identifier))),
"description" -> trim(label("Group description", optional(text()))), "description" -> trim(label("Group description", optional(text()))),
"url" -> trim(label("URL", optional(text(maxlength(200))))), "url" -> trim(label("URL", optional(text(maxlength(200))))),
@@ -250,28 +251,27 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
val conn = request2Session(request).conn val conn = request2Session(request).conn
val meta = conn.getMetaData val meta = conn.getMetaData
val tables = ListBuffer[Table]() val tables = ListBuffer[Table]()
Using.resource(meta.getTables(null, "%", "%", Array("TABLE", "VIEW"))) { Using.resource(meta.getTables(null, "%", "%", Array("TABLE", "VIEW"))) { rs =>
rs => while (rs.next()) {
while (rs.next()) { val tableName = rs.getString("TABLE_NAME")
val tableName = rs.getString("TABLE_NAME")
val pkColumns = ListBuffer[String]() val pkColumns = ListBuffer[String]()
Using.resource(meta.getPrimaryKeys(null, null, tableName)) { rs => Using.resource(meta.getPrimaryKeys(null, null, tableName)) { rs =>
while (rs.next()) { while (rs.next()) {
pkColumns += rs.getString("COLUMN_NAME").toUpperCase pkColumns += rs.getString("COLUMN_NAME").toUpperCase
}
} }
val columns = ListBuffer[Column]()
Using.resource(meta.getColumns(null, "%", tableName, "%")) { rs =>
while (rs.next()) {
val columnName = rs.getString("COLUMN_NAME").toUpperCase
columns += Column(columnName, pkColumns.contains(columnName))
}
}
tables += Table(tableName.toUpperCase, columns.toSeq)
} }
val columns = ListBuffer[Column]()
Using.resource(meta.getColumns(null, "%", tableName, "%")) { rs =>
while (rs.next()) {
val columnName = rs.getString("COLUMN_NAME").toUpperCase
columns += Column(columnName, pkColumns.contains(columnName))
}
}
tables += Table(tableName.toUpperCase, columns.toSeq)
}
} }
html.dbviewer(tables.toSeq) html.dbviewer(tables.toSeq)
}) })
@@ -284,28 +284,26 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
if (trimmedQuery.nonEmpty) { if (trimmedQuery.nonEmpty) {
try { try {
val conn = request2Session(request).conn val conn = request2Session(request).conn
Using.resource(conn.prepareStatement(query)) { Using.resource(conn.prepareStatement(query)) { stmt =>
stmt => if (trimmedQuery.toUpperCase.startsWith("SELECT")) {
if (trimmedQuery.toUpperCase.startsWith("SELECT")) { Using.resource(stmt.executeQuery()) { rs =>
Using.resource(stmt.executeQuery()) { val meta = rs.getMetaData
rs => val columns = for (i <- 1 to meta.getColumnCount) yield {
val meta = rs.getMetaData meta.getColumnName(i)
val columns = for (i <- 1 to meta.getColumnCount) yield {
meta.getColumnName(i)
}
val result = ListBuffer[Map[String, String]]()
while (rs.next()) {
val row = columns.map { columnName =>
columnName -> Option(rs.getObject(columnName)).map(_.toString).getOrElse("<NULL>")
}.toMap
result += row
}
Ok(Serialization.write(Map("type" -> "query", "columns" -> columns, "rows" -> result)))
} }
} else { val result = ListBuffer[Map[String, String]]()
val rows = stmt.executeUpdate() while (rs.next()) {
Ok(Serialization.write(Map("type" -> "update", "rows" -> rows))) val row = columns.map { columnName =>
columnName -> Option(rs.getObject(columnName)).map(_.toString).getOrElse("<NULL>")
}.toMap
result += row
}
Ok(Serialization.write(Map("type" -> "query", "columns" -> columns, "rows" -> result)))
} }
} else {
val rows = stmt.executeUpdate()
Ok(Serialization.write(Map("type" -> "update", "rows" -> rows)))
}
} }
} catch { } catch {
case e: Exception => case e: Exception =>
@@ -322,7 +320,9 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
post("/admin/system", form)(adminOnly { form => post("/admin/system", form)(adminOnly { form =>
saveSystemSettings(form) saveSystemSettings(form)
if (form.ssh.bindAddress != context.settings.sshBindAddress || form.ssh.publicAddress != context.settings.sshPublicAddress) { if (
form.ssh.bindAddress != context.settings.sshBindAddress || form.ssh.publicAddress != context.settings.sshPublicAddress
) {
SshServer.stop() SshServer.stop()
for { for {
bindAddress <- form.ssh.bindAddress bindAddress <- form.ssh.bindAddress
@@ -363,7 +363,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
}) })
post("/admin/plugins/_reload")(adminOnly { post("/admin/plugins/_reload")(adminOnly {
PluginRegistry.reload(request.getServletContext(), loadSystemSettings(), request2Session(request).conn) PluginRegistry.reload(request.getServletContext, loadSystemSettings(), request2Session(request).conn)
flash.update("info", "All plugins were reloaded.") flash.update("info", "All plugins were reloaded.")
redirect("/admin/plugins") redirect("/admin/plugins")
}) })
@@ -385,7 +385,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
val includeGroups = params.get("includeGroups").exists(_.toBoolean) val includeGroups = params.get("includeGroups").exists(_.toBoolean)
val users = getAllUsers(includeRemoved, includeGroups) val users = getAllUsers(includeRemoved, includeGroups)
val members = users.collect { val members = users.collect {
case account if (account.isGroupAccount) => case account if account.isGroupAccount =>
account.userName -> getGroupMembers(account.userName).map(_.userName) account.userName -> getGroupMembers(account.userName).map(_.userName)
}.toMap }.toMap
@@ -406,7 +406,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
form.description, form.description,
form.url form.url
) )
updateImage(form.userName, form.fileId, false) updateImage(form.userName, form.fileId, clearImage = false)
updateAccountExtraMailAddresses(form.userName, form.extraMailAddresses.filter(_ != "")) updateAccountExtraMailAddresses(form.userName, form.extraMailAddresses.filter(_ != ""))
redirect("/admin/users") redirect("/admin/users")
}) })
@@ -414,49 +414,48 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
get("/admin/users/:userName/_edituser")(adminOnly { get("/admin/users/:userName/_edituser")(adminOnly {
val userName = params("userName") val userName = params("userName")
val extraMails = getAccountExtraMailAddresses(userName) val extraMails = getAccountExtraMailAddresses(userName)
html.user(getAccountByUserName(userName, true), extraMails, flash.get("error")) html.user(getAccountByUserName(userName, includeRemoved = true), extraMails, flash.get("error"))
}) })
post("/admin/users/:name/_edituser", editUserForm)(adminOnly { form => post("/admin/users/:name/_edituser", editUserForm)(adminOnly { form =>
val userName = params("userName") val userName = params("userName")
getAccountByUserName(userName, true).map { getAccountByUserName(userName, includeRemoved = true).map { account =>
account => if (account.isAdmin && (form.isRemoved || !form.isAdmin) && isLastAdministrator(account)) {
if (account.isAdmin && (form.isRemoved || !form.isAdmin) && isLastAdministrator(account)) { flash.update("error", "Account can't be turned off because this is last one administrator.")
flash.update("error", "Account can't be turned off because this is last one administrator.") redirect(s"/admin/users/${userName}/_edituser")
redirect(s"/admin/users/${userName}/_edituser") } else {
} else { if (form.isRemoved) {
if (form.isRemoved) { // Remove repositories
// Remove repositories // getRepositoryNamesOfUser(userName).foreach { repositoryName =>
// getRepositoryNamesOfUser(userName).foreach { repositoryName => // deleteRepository(userName, repositoryName)
// deleteRepository(userName, repositoryName) // FileUtils.deleteDirectory(getRepositoryDir(userName, repositoryName))
// FileUtils.deleteDirectory(getRepositoryDir(userName, repositoryName)) // FileUtils.deleteDirectory(getWikiRepositoryDir(userName, repositoryName))
// FileUtils.deleteDirectory(getWikiRepositoryDir(userName, repositoryName)) // FileUtils.deleteDirectory(getTemporaryDir(userName, repositoryName))
// FileUtils.deleteDirectory(getTemporaryDir(userName, repositoryName)) // }
// } // Remove from GROUP_MEMBER and COLLABORATOR
// Remove from GROUP_MEMBER and COLLABORATOR removeUserRelatedData(userName)
removeUserRelatedData(userName)
}
updateAccount(
account.copy(
password = form.password.map(pbkdf2_sha256).getOrElse(account.password),
fullName = form.fullName,
mailAddress = form.mailAddress,
isAdmin = form.isAdmin,
description = form.description,
url = form.url,
isRemoved = form.isRemoved
)
)
updateImage(userName, form.fileId, form.clearImage)
updateAccountExtraMailAddresses(userName, form.extraMailAddresses.filter(_ != ""))
// call hooks
if (form.isRemoved) PluginRegistry().getAccountHooks.foreach(_.deleted(userName))
redirect("/admin/users")
} }
updateAccount(
account.copy(
password = form.password.map(pbkdf2_sha256).getOrElse(account.password),
fullName = form.fullName,
mailAddress = form.mailAddress,
isAdmin = form.isAdmin,
description = form.description,
url = form.url,
isRemoved = form.isRemoved
)
)
updateImage(userName, form.fileId, form.clearImage)
updateAccountExtraMailAddresses(userName, form.extraMailAddresses.filter(_ != ""))
// call hooks
if (form.isRemoved) PluginRegistry().getAccountHooks.foreach(_.deleted(userName))
redirect("/admin/users")
}
} getOrElse NotFound() } getOrElse NotFound()
}) })
@@ -477,13 +476,13 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
} }
.toList .toList
) )
updateImage(form.groupName, form.fileId, false) updateImage(form.groupName, form.fileId, clearImage = false)
redirect("/admin/users") redirect("/admin/users")
}) })
get("/admin/users/:groupName/_editgroup")(adminOnly { get("/admin/users/:groupName/_editgroup")(adminOnly {
val groupName = params("groupName") val groupName = params("groupName")
html.usergroup(getAccountByUserName(groupName, true), getGroupMembers(groupName)) html.usergroup(getAccountByUserName(groupName, includeRemoved = true), getGroupMembers(groupName))
}) })
post("/admin/users/:groupName/_editgroup", editGroupForm)(adminOnly { form => post("/admin/users/:groupName/_editgroup", editGroupForm)(adminOnly { form =>
@@ -497,13 +496,12 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
} }
.toList .toList
getAccountByUserName(groupName, true).map { getAccountByUserName(groupName, includeRemoved = true).map { account =>
account => updateGroup(groupName, form.description, form.url, form.isRemoved)
updateGroup(groupName, form.description, form.url, form.isRemoved)
if (form.isRemoved) { if (form.isRemoved) {
// Remove from GROUP_MEMBER // Remove from GROUP_MEMBER
updateGroupMembers(form.groupName, Nil) updateGroupMembers(form.groupName, Nil)
// // Remove repositories // // Remove repositories
// getRepositoryNamesOfUser(form.groupName).foreach { repositoryName => // getRepositoryNamesOfUser(form.groupName).foreach { repositoryName =>
// deleteRepository(groupName, repositoryName) // deleteRepository(groupName, repositoryName)
@@ -511,9 +509,9 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
// FileUtils.deleteDirectory(getWikiRepositoryDir(groupName, repositoryName)) // FileUtils.deleteDirectory(getWikiRepositoryDir(groupName, repositoryName))
// FileUtils.deleteDirectory(getTemporaryDir(groupName, repositoryName)) // FileUtils.deleteDirectory(getTemporaryDir(groupName, repositoryName))
// } // }
} else { } else {
// Update GROUP_MEMBER // Update GROUP_MEMBER
updateGroupMembers(form.groupName, members) updateGroupMembers(form.groupName, members)
// // Update COLLABORATOR for group repositories // // Update COLLABORATOR for group repositories
// getRepositoryNamesOfUser(form.groupName).foreach { repositoryName => // getRepositoryNamesOfUser(form.groupName).foreach { repositoryName =>
// removeCollaborators(form.groupName, repositoryName) // removeCollaborators(form.groupName, repositoryName)
@@ -521,22 +519,22 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
// addCollaborator(form.groupName, repositoryName, userName) // addCollaborator(form.groupName, repositoryName, userName)
// } // }
// } // }
} }
updateImage(form.groupName, form.fileId, form.clearImage) updateImage(form.groupName, form.fileId, form.clearImage)
redirect("/admin/users") redirect("/admin/users")
} getOrElse NotFound() } getOrElse NotFound()
}) })
get("/admin/data")(adminOnly { get("/admin/data")(adminOnly {
import gitbucket.core.util.JDBCUtil._ import gitbucket.core.util.JDBCUtil.*
val session = request2Session(request) val session = request2Session(request)
html.data(session.conn.allTableNames()) html.data(session.conn.allTableNames())
}) })
post("/admin/export")(adminOnly { post("/admin/export")(adminOnly {
import gitbucket.core.util.JDBCUtil._ import gitbucket.core.util.JDBCUtil.*
val file = request2Session(request).conn.exportAsSQL(request.getParameterValues("tableNames").toSeq) val file = request2Session(request).conn.exportAsSQL(request.getParameterValues("tableNames").toSeq)
contentType = "application/octet-stream" contentType = "application/octet-stream"
@@ -551,7 +549,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
}) })
private def multiLineText(constraints: Constraint*): SingleValueType[Seq[String]] = private def multiLineText(constraints: Constraint*): SingleValueType[Seq[String]] =
new SingleValueType[Seq[String]](constraints: _*) { new SingleValueType[Seq[String]](constraints*) {
def convert(value: String, messages: Messages): Seq[String] = { def convert(value: String, messages: Messages): Seq[String] = {
if (value == null) { if (value == null) {
Nil Nil
@@ -564,9 +562,11 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
private def members: Constraint = private def members: 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 (value.split(",").exists { if (
_.split(":") match { case Array(userName, isManager) => isManager.toBoolean } value.split(",").exists {
}) None _.split(":") match { case Array(userName, isManager) => isManager.toBoolean }
}
) None
else Some("Must select one manager at least.") else Some("Must select one manager at least.")
} }
} }
@@ -577,7 +577,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
for { for {
userName <- params.get(paramName) userName <- params.get(paramName)
loginAccount <- context.loginAccount loginAccount <- context.loginAccount
if userName == loginAccount.userName && params.get("removed") == Some("true") if userName == loginAccount.userName && params.get("removed").contains("true")
} yield "You can't disable your account yourself" } yield "You can't disable your account yourself"
} }
} }

View File

@@ -1,16 +1,16 @@
package gitbucket.core.controller package gitbucket.core.controller
import org.json4s.{JField, JObject, JString} import org.json4s.{JField, JObject, JString}
import org.scalatra._ import org.scalatra.*
import org.scalatra.json._ import org.scalatra.json.*
import org.scalatra.forms._ import org.scalatra.forms.*
import org.scalatra.i18n.I18nSupport import org.scalatra.i18n.I18nSupport
import org.scalatra.servlet.ServletBase import org.scalatra.servlet.ServletBase
/** /**
* Extends scalatra-forms to support the client-side validation and Ajax requests as well. * Extends scalatra-forms to support the client-side validation and Ajax requests as well.
*/ */
trait ValidationSupport extends FormSupport { self: ServletBase with JacksonJsonSupport with I18nSupport => trait ValidationSupport extends FormSupport { self: ServletBase & JacksonJsonSupport & I18nSupport =>
def get[T](path: String, form: ValueType[T])(action: T => Any): Route = { def get[T](path: String, form: ValueType[T])(action: T => Any): Route = {
registerValidate(path, form) registerValidate(path, form)
@@ -84,9 +84,8 @@ trait ValidationSupport extends FormSupport { self: ServletBase with JacksonJson
* Converts errors to JSON. * Converts errors to JSON.
*/ */
private def toJson(errors: Seq[(String, String)]): JObject = private def toJson(errors: Seq[(String, String)]): JObject =
JObject(errors.map { JObject(errors.map { case (key, value) =>
case (key, value) => JField(key, JString(value))
JField(key, JString(value))
}.toList) }.toList)
} }

View File

@@ -5,13 +5,13 @@ import gitbucket.core.model.activity.{CreateWikiPageInfo, DeleteWikiInfo, EditWi
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
import gitbucket.core.service._ import gitbucket.core.service.*
import gitbucket.core.util._ import gitbucket.core.util.*
import gitbucket.core.util.StringUtil._ 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 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
@@ -29,15 +29,10 @@ class WikiController
with RequestCache with RequestCache
trait WikiControllerBase extends ControllerBase { trait WikiControllerBase extends ControllerBase {
self: WikiService self: WikiService & RepositoryService & AccountService & ActivityService & WebHookService &
with RepositoryService ReadableUsersAuthenticator & ReferrerAuthenticator =>
with AccountService
with ActivityService
with WebHookService
with ReadableUsersAuthenticator
with ReferrerAuthenticator =>
case class WikiPageEditForm( private case class WikiPageEditForm(
pageName: String, pageName: String,
content: String, content: String,
message: Option[String], message: Option[String],
@@ -45,16 +40,16 @@ trait WikiControllerBase extends ControllerBase {
id: String id: String
) )
val newForm = mapping( private val newForm = mapping(
"pageName" -> trim(label("Page name", text(required, maxlength(40), pagename, unique))), "pageName" -> trim(label("Page name", text(required, maxlength(40), pageName, unique))),
"content" -> trim(label("Content", text(required, conflictForNew))), "content" -> trim(label("Content", text(required, conflictForNew))),
"message" -> trim(label("Message", optional(text()))), "message" -> trim(label("Message", optional(text()))),
"currentPageName" -> trim(label("Current page name", text())), "currentPageName" -> trim(label("Current page name", text())),
"id" -> trim(label("Latest commit id", text())) "id" -> trim(label("Latest commit id", text()))
)(WikiPageEditForm.apply) )(WikiPageEditForm.apply)
val editForm = mapping( private val editForm = mapping(
"pageName" -> trim(label("Page name", text(required, maxlength(40), pagename))), "pageName" -> trim(label("Page name", text(required, maxlength(40), pageName))),
"content" -> trim(label("Content", text(required, conflictForEdit))), "content" -> trim(label("Content", text(required, conflictForEdit))),
"message" -> trim(label("Message", optional(text()))), "message" -> trim(label("Message", optional(text()))),
"currentPageName" -> trim(label("Current page name", text(required))), "currentPageName" -> trim(label("Current page name", text(required))),
@@ -62,46 +57,56 @@ trait WikiControllerBase extends ControllerBase {
)(WikiPageEditForm.apply) )(WikiPageEditForm.apply)
get("/:owner/:repository/wiki")(referrersOnly { repository => get("/:owner/:repository/wiki")(referrersOnly { repository =>
getWikiPage(repository.owner, repository.name, "Home").map { page => val branch = getWikiBranch(repository.owner, repository.name)
getWikiPage(repository.owner, repository.name, "Home", branch).map { page =>
html.page( html.page(
"Home", "Home",
page, page,
getWikiPageList(repository.owner, repository.name), getWikiPageList(repository.owner, repository.name, branch),
repository, repository,
isEditable(repository), isEditable(repository),
getWikiPage(repository.owner, repository.name, "_Sidebar"), getWikiPage(repository.owner, repository.name, "_Sidebar", branch),
getWikiPage(repository.owner, repository.name, "_Footer") getWikiPage(repository.owner, repository.name, "_Footer", branch)
) )
} getOrElse redirect(s"/${repository.owner}/${repository.name}/wiki/Home/_edit") } getOrElse redirect(s"/${repository.owner}/${repository.name}/wiki/Home/_edit")
}) })
get("/:owner/:repository/wiki/:page")(referrersOnly { repository => get("/:owner/:repository/wiki/:page")(referrersOnly { repository =>
val pageName = StringUtil.urlDecode(params("page")) val pageName = StringUtil.urlDecode(params("page"))
val branch = getWikiBranch(repository.owner, repository.name)
getWikiPage(repository.owner, repository.name, pageName).map { page => getWikiPage(repository.owner, repository.name, pageName, branch).map { page =>
html.page( html.page(
pageName, pageName,
page, page,
getWikiPageList(repository.owner, repository.name), getWikiPageList(repository.owner, repository.name, branch),
repository, repository,
isEditable(repository), isEditable(repository),
getWikiPage(repository.owner, repository.name, "_Sidebar"), getWikiPage(repository.owner, repository.name, "_Sidebar", branch),
getWikiPage(repository.owner, repository.name, "_Footer") getWikiPage(repository.owner, repository.name, "_Footer", branch)
) )
} getOrElse redirect(s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(pageName)}/_edit") } getOrElse redirect(s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(pageName)}/_edit")
}) })
get("/:owner/:repository/wiki/:page/_history")(referrersOnly { repository => get("/:owner/:repository/wiki/:page/_history")(referrersOnly { repository =>
val pageName = StringUtil.urlDecode(params("page")) val pageName = StringUtil.urlDecode(params("page"))
val branch = getWikiBranch(repository.owner, repository.name)
Using.resource(Git.open(getWikiRepositoryDir(repository.owner, repository.name))) { git => Using.resource(Git.open(getWikiRepositoryDir(repository.owner, repository.name))) { git =>
JGitUtil.getCommitLog(git, "master", path = pageName + ".md") match { JGitUtil.getCommitLog(git, branch, path = pageName + ".md") match {
case Right((logs, hasNext)) => html.history(Some(pageName), logs, repository, isEditable(repository)) case Right((logs, hasNext)) => html.history(Some(pageName), logs, repository, isEditable(repository))
case Left(_) => NotFound() case Left(_) => NotFound()
} }
} }
}) })
private def getWikiBranch(owner: String, repository: String): String = {
Using.resource(Git.open(Directory.getWikiRepositoryDir(owner, repository))) { git =>
git.getRepository.getBranch
}
}
get("/:owner/:repository/wiki/:page/_compare/:commitId")(referrersOnly { repository => get("/:owner/:repository/wiki/:page/_compare/:commitId")(referrersOnly { repository =>
val pageName = StringUtil.urlDecode(params("page")) val pageName = StringUtil.urlDecode(params("page"))
val Array(from, to) = params("commitId").split("\\.\\.\\.") val Array(from, to) = params("commitId").split("\\.\\.\\.")
@@ -111,7 +116,17 @@ trait WikiControllerBase extends ControllerBase {
Some(pageName), Some(pageName),
from, from,
to, to,
JGitUtil.getDiffs(git, Some(from), to, true, false).filter(_.newPath == pageName + ".md"), JGitUtil
.getDiffs(
git = git,
from = Some(from),
to = to,
fetchContent = true,
makePatch = false,
maxFiles = context.settings.repositoryViewer.maxDiffFiles,
maxLines = context.settings.repositoryViewer.maxDiffLines
)
.filter(_.newPath == pageName + ".md"),
repository, repository,
isEditable(repository), isEditable(repository),
flash.get("info") flash.get("info")
@@ -127,7 +142,15 @@ trait WikiControllerBase extends ControllerBase {
None, None,
from, from,
to, to,
JGitUtil.getDiffs(git, Some(from), to, true, false), JGitUtil.getDiffs(
git = git,
from = Some(from),
to = to,
fetchContent = true,
makePatch = false,
maxFiles = context.settings.repositoryViewer.maxDiffFiles,
maxLines = context.settings.repositoryViewer.maxDiffLines
),
repository, repository,
isEditable(repository), isEditable(repository),
flash.get("info") flash.get("info")
@@ -136,78 +159,78 @@ trait WikiControllerBase extends ControllerBase {
}) })
get("/:owner/:repository/wiki/:page/_revert/:commitId")(readableUsersOnly { repository => get("/:owner/:repository/wiki/:page/_revert/:commitId")(readableUsersOnly { repository =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => if (isEditable(repository)) {
if (isEditable(repository)) { val pageName = StringUtil.urlDecode(params("page"))
val pageName = StringUtil.urlDecode(params("page")) val Array(from, to) = params("commitId").split("\\.\\.\\.")
val Array(from, to) = params("commitId").split("\\.\\.\\.") val branch = getWikiBranch(repository.owner, repository.name)
if (revertWikiPage(repository.owner, repository.name, from, to, loginAccount, Some(pageName))) { if (revertWikiPage(repository.owner, repository.name, from, to, loginAccount, Some(pageName), branch)) {
redirect(s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(pageName)}") redirect(s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(pageName)}")
} else { } else {
flash.update("info", "This patch was not able to be reversed.") flash.update("info", "This patch was not able to be reversed.")
redirect( redirect(
s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(pageName)}/_compare/${from}...${to}" s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(pageName)}/_compare/$from...$to"
) )
} }
} else Unauthorized() } else Unauthorized()
} }
}) })
get("/:owner/:repository/wiki/_revert/:commitId")(readableUsersOnly { repository => get("/:owner/:repository/wiki/_revert/:commitId")(readableUsersOnly { repository =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => if (isEditable(repository)) {
if (isEditable(repository)) { val Array(from, to) = params("commitId").split("\\.\\.\\.")
val Array(from, to) = params("commitId").split("\\.\\.\\.") val branch = getWikiBranch(repository.owner, repository.name)
if (revertWikiPage(repository.owner, repository.name, from, to, loginAccount, None)) { if (revertWikiPage(repository.owner, repository.name, from, to, loginAccount, None, branch)) {
redirect(s"/${repository.owner}/${repository.name}/wiki") redirect(s"/${repository.owner}/${repository.name}/wiki")
} else { } else {
flash.update("info", "This patch was not able to be reversed.") flash.update("info", "This patch was not able to be reversed.")
redirect(s"/${repository.owner}/${repository.name}/wiki/_compare/${from}...${to}") redirect(s"/${repository.owner}/${repository.name}/wiki/_compare/$from...$to")
} }
} else Unauthorized() } else Unauthorized()
} }
}) })
get("/:owner/:repository/wiki/:page/_edit")(readableUsersOnly { repository => get("/:owner/:repository/wiki/:page/_edit")(readableUsersOnly { repository =>
if (isEditable(repository)) { if (isEditable(repository)) {
val pageName = StringUtil.urlDecode(params("page")) val pageName = StringUtil.urlDecode(params("page"))
html.edit(pageName, getWikiPage(repository.owner, repository.name, pageName), repository) val branch = getWikiBranch(repository.owner, repository.name)
html.edit(pageName, getWikiPage(repository.owner, repository.name, pageName, branch), repository)
} else Unauthorized() } else Unauthorized()
}) })
post("/:owner/:repository/wiki/_edit", editForm)(readableUsersOnly { (form, repository) => post("/:owner/:repository/wiki/_edit", editForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => if (isEditable(repository)) {
if (isEditable(repository)) { saveWikiPage(
saveWikiPage( repository.owner,
repository.owner, repository.name,
repository.name, form.currentPageName,
form.currentPageName, form.pageName,
form.pageName, appendNewLine(convertLineSeparator(form.content, "LF"), "LF"),
appendNewLine(convertLineSeparator(form.content, "LF"), "LF"), loginAccount,
loginAccount, form.message.getOrElse(""),
form.message.getOrElse(""), Some(form.id)
Some(form.id) ).foreach { commitId =>
).foreach { updateLastActivityDate(repository.owner, repository.name)
commitId => val wikiEditInfo =
updateLastActivityDate(repository.owner, repository.name) EditWikiPageInfo(repository.owner, repository.name, loginAccount.userName, form.pageName, commitId)
val wikiEditInfo = recordActivity(wikiEditInfo)
EditWikiPageInfo(repository.owner, repository.name, loginAccount.userName, form.pageName, commitId) callWebHookOf(repository.owner, repository.name, WebHook.Gollum, context.settings) {
recordActivity(wikiEditInfo) getAccountByUserName(repository.owner).map { repositoryUser =>
callWebHookOf(repository.owner, repository.name, WebHook.Gollum, context.settings) { WebHookGollumPayload("edited", form.pageName, commitId, repository, repositoryUser, loginAccount)
getAccountByUserName(repository.owner).map { repositoryUser => }
WebHookGollumPayload("edited", form.pageName, commitId, repository, repositoryUser, loginAccount)
}
}
} }
if (notReservedPageName(form.pageName)) { }
redirect(s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(form.pageName)}") if (notReservedPageName(form.pageName)) {
} else { redirect(s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(form.pageName)}")
redirect(s"/${repository.owner}/${repository.name}/wiki") } else {
} redirect(s"/${repository.owner}/${repository.name}/wiki")
} else Unauthorized() }
} else Unauthorized()
} }
}) })
@@ -218,74 +241,73 @@ trait WikiControllerBase extends ControllerBase {
}) })
post("/:owner/:repository/wiki/_new", newForm)(readableUsersOnly { (form, repository) => post("/:owner/:repository/wiki/_new", newForm)(readableUsersOnly { (form, repository) =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => if (isEditable(repository)) {
if (isEditable(repository)) { saveWikiPage(
saveWikiPage( repository.owner,
repository.owner, repository.name,
repository.name, form.currentPageName,
form.currentPageName, form.pageName,
form.pageName, form.content,
form.content, loginAccount,
loginAccount, form.message.getOrElse(""),
form.message.getOrElse(""), None
None ).foreach { commitId =>
).foreach { updateLastActivityDate(repository.owner, repository.name)
commitId => val createWikiPageInfo =
updateLastActivityDate(repository.owner, repository.name) CreateWikiPageInfo(repository.owner, repository.name, loginAccount.userName, form.pageName)
val createWikiPageInfo = recordActivity(createWikiPageInfo)
CreateWikiPageInfo(repository.owner, repository.name, loginAccount.userName, form.pageName) callWebHookOf(repository.owner, repository.name, WebHook.Gollum, context.settings) {
recordActivity(createWikiPageInfo) getAccountByUserName(repository.owner).map { repositoryUser =>
callWebHookOf(repository.owner, repository.name, WebHook.Gollum, context.settings) { WebHookGollumPayload("created", form.pageName, commitId, repository, repositoryUser, loginAccount)
getAccountByUserName(repository.owner).map { repositoryUser => }
WebHookGollumPayload("created", form.pageName, commitId, repository, repositoryUser, loginAccount)
}
}
} }
}
if (notReservedPageName(form.pageName)) { if (notReservedPageName(form.pageName)) {
redirect(s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(form.pageName)}") redirect(s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(form.pageName)}")
} else { } else {
redirect(s"/${repository.owner}/${repository.name}/wiki") redirect(s"/${repository.owner}/${repository.name}/wiki")
} }
} else Unauthorized() } else Unauthorized()
} }
}) })
get("/:owner/:repository/wiki/:page/_delete")(readableUsersOnly { repository => get("/:owner/:repository/wiki/:page/_delete")(readableUsersOnly { repository =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => if (isEditable(repository)) {
if (isEditable(repository)) { val pageName = StringUtil.urlDecode(params("page"))
val pageName = StringUtil.urlDecode(params("page")) 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}" )
) val deleteWikiInfo = DeleteWikiInfo(
val deleteWikiInfo = DeleteWikiInfo( repository.owner,
repository.owner, repository.name,
repository.name, loginAccount.userName,
loginAccount.userName, pageName
pageName )
) recordActivity(deleteWikiInfo)
recordActivity(deleteWikiInfo) updateLastActivityDate(repository.owner, repository.name)
updateLastActivityDate(repository.owner, repository.name)
redirect(s"/${repository.owner}/${repository.name}/wiki") redirect(s"/${repository.owner}/${repository.name}/wiki")
} else Unauthorized() } else Unauthorized()
} }
}) })
get("/:owner/:repository/wiki/_pages")(referrersOnly { repository => get("/:owner/:repository/wiki/_pages")(referrersOnly { repository =>
html.pages(getWikiPageList(repository.owner, repository.name), repository, isEditable(repository)) val branch = getWikiBranch(repository.owner, repository.name)
html.pages(getWikiPageList(repository.owner, repository.name, branch), repository, isEditable(repository))
}) })
get("/:owner/:repository/wiki/_history")(referrersOnly { repository => get("/:owner/:repository/wiki/_history")(referrersOnly { repository =>
Using.resource(Git.open(getWikiRepositoryDir(repository.owner, repository.name))) { git => Using.resource(Git.open(getWikiRepositoryDir(repository.owner, repository.name))) { git =>
JGitUtil.getCommitLog(git, "master") match { val branch = getWikiBranch(repository.owner, repository.name)
JGitUtil.getCommitLog(git, branch) match {
case Right((logs, hasNext)) => html.history(None, logs, repository, isEditable(repository)) case Right((logs, hasNext)) => html.history(None, logs, repository, isEditable(repository))
case Left(_) => NotFound() case Left(_) => NotFound()
} }
@@ -295,7 +317,8 @@ trait WikiControllerBase extends ControllerBase {
get("/:owner/:repository/wiki/_blob/*")(referrersOnly { repository => get("/:owner/:repository/wiki/_blob/*")(referrersOnly { repository =>
val path = multiParams("splat").head val path = multiParams("splat").head
Using.resource(Git.open(getWikiRepositoryDir(repository.owner, repository.name))) { git => Using.resource(Git.open(getWikiRepositoryDir(repository.owner, repository.name))) { git =>
val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve("master")) val branch = getWikiBranch(repository.owner, repository.name)
val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(branch))
getPathObjectId(git, path, revCommit).map { objectId => getPathObjectId(git, path, revCommit).map { objectId =>
responseRawFile(git, objectId, path, repository) responseRawFile(git, objectId, path, repository)
@@ -309,24 +332,29 @@ trait WikiControllerBase extends ControllerBase {
value: String, value: String,
params: Map[String, Seq[String]], params: Map[String, Seq[String]],
messages: Messages messages: Messages
): Option[String] = ): Option[String] = {
getWikiPageList(params.value("owner"), params.value("repository")) val owner = params.value("owner")
val repository = params.value("repository")
val branch = getWikiBranch(owner, repository)
getWikiPageList(owner, repository, branch)
.find(_ == value) .find(_ == value)
.map(_ => "Page already exists.") .map(_ => "Page already exists.")
}
} }
private def pagename: Constraint = new Constraint() { private def pageName: 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 (value.exists("\\/:*?\"<>|".contains(_))) { if (value.exists("\\/:*?\"<>|".contains(_))) {
Some(s"${name} contains invalid character.") Some(s"$name contains invalid character.")
} else if (notReservedPageName(value) && (value.startsWith("_") || value.startsWith("-"))) { } else if (notReservedPageName(value) && (value.startsWith("_") || value.startsWith("-"))) {
Some(s"${name} starts with invalid character.") Some(s"$name starts with invalid character.")
} else { } else {
None None
} }
} }
private def notReservedPageName(value: String) = !(Array[String]("_Sidebar", "_Footer") contains value) private def notReservedPageName(value: String): Boolean = !(Array[String]("_Sidebar", "_Footer") contains value)
private def conflictForNew: Constraint = new Constraint() { private def conflictForNew: 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] = {
@@ -344,7 +372,13 @@ trait WikiControllerBase extends ControllerBase {
} }
} }
private def targetWikiPage = getWikiPage(params("owner"), params("repository"), params("pageName")) private def targetWikiPage: Option[WikiService.WikiPageInfo] = {
val owner = params("owner")
val repository = params("repository")
val pageName = params("pageName")
val branch = getWikiBranch(owner, repository)
getWikiPage(owner, repository, pageName, branch)
}
private def isEditable(repository: RepositoryInfo)(implicit context: Context): Boolean = { private def isEditable(repository: RepositoryInfo)(implicit context: Context): Boolean = {
repository.repository.options.wikiOption match { repository.repository.options.wikiOption match {

View File

@@ -15,7 +15,7 @@ import scala.jdk.CollectionConverters._
import scala.util.Using import scala.util.Using
trait ApiGitReferenceControllerBase extends ControllerBase { trait ApiGitReferenceControllerBase extends ControllerBase {
self: ReferrerAuthenticator with WritableUsersAuthenticator => self: ReferrerAuthenticator & WritableUsersAuthenticator =>
private val logger = LoggerFactory.getLogger(classOf[ApiGitReferenceControllerBase]) private val logger = LoggerFactory.getLogger(classOf[ApiGitReferenceControllerBase])
@@ -57,23 +57,26 @@ trait ApiGitReferenceControllerBase extends ControllerBase {
* iii. Create a reference * iii. Create a reference
* https://docs.github.com/en/free-pro-team@latest/rest/reference/git#create-a-reference * https://docs.github.com/en/free-pro-team@latest/rest/reference/git#create-a-reference
*/ */
post("/api/v3/repos/:owner/:repository/git/refs")(referrersOnly { repository => post("/api/v3/repos/:owner/:repository/git/refs")(writableUsersOnly { repository =>
extractFromJsonBody[CreateARef].map { extractFromJsonBody[CreateARef].map { data =>
data => Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.owner))) { git => val ref = git.getRepository.findRef(data.ref)
val ref = git.getRepository.findRef(data.ref) if (ref == null) {
if (ref == null) { val update = git.getRepository.updateRef(data.ref)
val update = git.getRepository.updateRef(data.ref) update.setNewObjectId(ObjectId.fromString(data.sha))
update.setNewObjectId(ObjectId.fromString(data.sha)) val result = update.update()
val result = update.update() result match {
result match { case Result.NEW =>
case Result.NEW => JsonFormat(ApiRef.fromRef(RepositoryName(repository.owner, repository.name), ref)) JsonFormat(
case _ => UnprocessableEntity(result.name()) ApiRef
} .fromRef(RepositoryName(repository.owner, repository.name), git.getRepository.findRef(data.ref))
} else { )
UnprocessableEntity("Ref already exists.") case _ => UnprocessableEntity(result.name())
} }
} else {
UnprocessableEntity("Ref already exists.")
} }
}
} getOrElse BadRequest() } getOrElse BadRequest()
}) })
@@ -83,24 +86,23 @@ trait ApiGitReferenceControllerBase extends ControllerBase {
*/ */
patch("/api/v3/repos/:owner/:repository/git/refs/*")(writableUsersOnly { repository => patch("/api/v3/repos/:owner/:repository/git/refs/*")(writableUsersOnly { repository =>
val refName = multiParams("splat").mkString("/") val refName = multiParams("splat").mkString("/")
extractFromJsonBody[UpdateARef].map { extractFromJsonBody[UpdateARef].map { data =>
data => Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.owner))) { git => val ref = git.getRepository.findRef(refName)
val ref = git.getRepository.findRef(refName) if (ref == null) {
if (ref == null) { UnprocessableEntity("Ref does not exist.")
UnprocessableEntity("Ref does not exist.") } else {
} else { val update = git.getRepository.updateRef(ref.getName)
val update = git.getRepository.updateRef(ref.getName) update.setNewObjectId(ObjectId.fromString(data.sha))
update.setNewObjectId(ObjectId.fromString(data.sha)) update.setForceUpdate(data.force)
update.setForceUpdate(data.force) val result = update.update()
val result = update.update() result match {
result match { case Result.FORCED | Result.FAST_FORWARD | Result.NO_CHANGE =>
case Result.FORCED | Result.FAST_FORWARD | Result.NO_CHANGE => JsonFormat(ApiRef.fromRef(RepositoryName(repository), git.getRepository.findRef(refName)))
JsonFormat(ApiRef.fromRef(RepositoryName(repository), update.getRef)) case _ => UnprocessableEntity(result.name())
case _ => UnprocessableEntity(result.name())
}
} }
} }
}
} getOrElse BadRequest() } getOrElse BadRequest()
}) })
@@ -136,7 +138,7 @@ trait ApiGitReferenceControllerBase extends ControllerBase {
val name = RepositoryName(repository) val name = RepositoryName(repository)
val result = JsonFormat(revstr match { val result = JsonFormat(revstr match {
case "tags" => repository.tags.map(ApiRef.fromTag(name, _)) case "tags" => repository.tags.map(ApiRef.fromTag(name, _))
case x if x.startsWith("tags/") => case x if x.startsWith("tags/") =>
val tagName = x.substring("tags/".length) val tagName = x.substring("tags/".length)
repository.tags.find(_.name == tagName) match { repository.tags.find(_.name == tagName) match {

View File

@@ -7,13 +7,8 @@ import gitbucket.core.util.{ReadableUsersAuthenticator, ReferrerAuthenticator, R
import org.scalatra.ActionResult import org.scalatra.ActionResult
trait ApiIssueCommentControllerBase extends ControllerBase { trait ApiIssueCommentControllerBase extends ControllerBase {
self: AccountService self: AccountService & IssuesService & RepositoryService & HandleCommentService & MilestonesService &
with IssuesService ReadableUsersAuthenticator & ReferrerAuthenticator =>
with RepositoryService
with HandleCommentService
with MilestonesService
with ReadableUsersAuthenticator
with ReferrerAuthenticator =>
/* /*
* i. List issue comments for a repository * i. List issue comments for a repository
* https://docs.github.com/en/rest/reference/issues#list-issue-comments-for-a-repository * https://docs.github.com/en/rest/reference/issues#list-issue-comments-for-a-repository
@@ -23,9 +18,8 @@ trait ApiIssueCommentControllerBase extends ControllerBase {
issueId <- params("id").toIntOpt issueId <- params("id").toIntOpt
comments = getCommentsForApi(repository.owner, repository.name, issueId) comments = getCommentsForApi(repository.owner, repository.name, issueId)
} yield { } yield {
JsonFormat(comments.map { JsonFormat(comments.map { case (issueComment, user, issue) =>
case (issueComment, user, issue) => ApiComment(issueComment, RepositoryName(repository), issueId, ApiUser(user), issue.isPullRequest)
ApiComment(issueComment, RepositoryName(repository), issueId, ApiUser(user), issue.isPullRequest)
}) })
}) getOrElse NotFound() }) getOrElse NotFound()
}) })
@@ -85,7 +79,7 @@ trait ApiIssueCommentControllerBase extends ControllerBase {
* iv. Delete a comment * iv. Delete a comment
* https://docs.github.com/en/rest/reference/issues#delete-an-issue-comment * https://docs.github.com/en/rest/reference/issues#delete-an-issue-comment
*/ */
delete("/api/v3/repos/:owner/:repo/issues/comments/:id")(readableUsersOnly { repository => delete("/api/v3/repos/:owner/:repository/issues/comments/:id")(readableUsersOnly { repository =>
val maybeDeleteResponse: Option[Either[ActionResult, Option[Int]]] = val maybeDeleteResponse: Option[Either[ActionResult, Option[Int]]] =
for { for {
commentId <- params("id").toIntOpt commentId <- params("id").toIntOpt

View File

@@ -9,12 +9,8 @@ import gitbucket.core.util.{ReadableUsersAuthenticator, ReferrerAuthenticator, R
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits._
trait ApiIssueControllerBase extends ControllerBase { trait ApiIssueControllerBase extends ControllerBase {
self: AccountService self: AccountService & IssuesService & IssueCreationService & MilestonesService & ReadableUsersAuthenticator &
with IssuesService ReferrerAuthenticator =>
with IssueCreationService
with MilestonesService
with ReadableUsersAuthenticator
with ReferrerAuthenticator =>
/* /*
* i. List issues * i. List issues
* https://developer.github.com/v3/issues/#list-issues * https://developer.github.com/v3/issues/#list-issues
@@ -29,7 +25,7 @@ trait ApiIssueControllerBase extends ControllerBase {
val page = IssueSearchCondition.page(request) val page = IssueSearchCondition.page(request)
// TODO: more api spec condition // TODO: more api spec condition
val condition = IssueSearchCondition(request) val condition = IssueSearchCondition(request)
//val baseOwner = getAccountByUserName(repository.owner).get // val baseOwner = getAccountByUserName(repository.owner).get
val issues: List[(Issue, Account, List[Account])] = val issues: List[(Issue, Account, List[Account])] =
searchIssueByApi( searchIssueByApi(
@@ -39,17 +35,16 @@ trait ApiIssueControllerBase extends ControllerBase {
repos = repository.owner -> repository.name repos = repository.owner -> repository.name
) )
JsonFormat(issues.map { JsonFormat(issues.map { case (issue, issueUser, assigneeUsers) =>
case (issue, issueUser, assigneeUsers) => ApiIssue(
ApiIssue( issue = issue,
issue = issue, repositoryName = RepositoryName(repository),
repositoryName = RepositoryName(repository), user = ApiUser(issueUser),
user = ApiUser(issueUser), assignees = assigneeUsers.map(ApiUser(_)),
assignees = assigneeUsers.map(ApiUser(_)), labels = getIssueLabels(repository.owner, repository.name, issue.issueId)
labels = getIssueLabels(repository.owner, repository.name, issue.issueId) .map(ApiLabel(_, RepositoryName(repository))),
.map(ApiLabel(_, RepositoryName(repository))), issue.milestoneId.flatMap { getApiMilestone(repository, _) }
issue.milestoneId.flatMap { getApiMilestone(repository, _) } )
)
}) })
}) })
@@ -126,7 +121,7 @@ trait ApiIssueControllerBase extends ControllerBase {
*/ */
/* /*
* vii. Unlock an issue * vii. Unlock an issue
* https://developer.github.com/v3/issues/#unlock-an-issue * https://developer.github.com/v3/issues/#unlock-an-issue
*/ */
} }

View File

@@ -1,5 +1,5 @@
package gitbucket.core.controller.api package gitbucket.core.controller.api
import gitbucket.core.api.{ApiError, ApiLabel, CreateALabel, JsonFormat} import gitbucket.core.api.{AddLabelsToAnIssue, ApiError, ApiLabel, CreateALabel, JsonFormat}
import gitbucket.core.controller.ControllerBase import gitbucket.core.controller.ControllerBase
import gitbucket.core.service._ import gitbucket.core.service._
import gitbucket.core.util.Implicits._ import gitbucket.core.util.Implicits._
@@ -7,11 +7,7 @@ import gitbucket.core.util._
import org.scalatra.{Created, NoContent, UnprocessableEntity} import org.scalatra.{Created, NoContent, UnprocessableEntity}
trait ApiIssueLabelControllerBase extends ControllerBase { trait ApiIssueLabelControllerBase extends ControllerBase {
self: AccountService self: AccountService & IssuesService & LabelsService & ReferrerAuthenticator & WritableUsersAuthenticator =>
with IssuesService
with LabelsService
with ReferrerAuthenticator
with WritableUsersAuthenticator =>
/* /*
* i. List all labels for this repository * i. List all labels for this repository
@@ -69,25 +65,24 @@ trait ApiIssueLabelControllerBase extends ControllerBase {
data <- extractFromJsonBody[CreateALabel] if data.isValid data <- extractFromJsonBody[CreateALabel] if data.isValid
} yield { } yield {
LockUtil.lock(RepositoryName(repository).fullName) { LockUtil.lock(RepositoryName(repository).fullName) {
getLabel(repository.owner, repository.name, params("labelName")).map { getLabel(repository.owner, repository.name, params("labelName")).map { label =>
label => if (getLabel(repository.owner, repository.name, data.name).isEmpty) {
if (getLabel(repository.owner, repository.name, data.name).isEmpty) { updateLabel(repository.owner, repository.name, label.labelId, data.name, data.color)
updateLabel(repository.owner, repository.name, label.labelId, data.name, data.color) JsonFormat(
JsonFormat( ApiLabel(
ApiLabel( getLabel(repository.owner, repository.name, label.labelId).get,
getLabel(repository.owner, repository.name, label.labelId).get, RepositoryName(repository)
RepositoryName(repository)
)
) )
} else { )
// TODO ApiError should support errors field to enhance compatibility of GitHub API } else {
UnprocessableEntity( // TODO ApiError should support errors field to enhance compatibility of GitHub API
ApiError( UnprocessableEntity(
"Validation Failed", ApiError(
Some("https://developer.github.com/v3/issues/labels/#create-a-label") "Validation Failed",
) Some("https://developer.github.com/v3/issues/labels/#create-a-label")
) )
} )
}
} getOrElse NotFound() } getOrElse NotFound()
} }
}) getOrElse NotFound() }) getOrElse NotFound()
@@ -121,10 +116,10 @@ trait ApiIssueLabelControllerBase extends ControllerBase {
*/ */
post("/api/v3/repos/:owner/:repository/issues/:id/labels")(writableUsersOnly { repository => post("/api/v3/repos/:owner/:repository/issues/:id/labels")(writableUsersOnly { repository =>
JsonFormat(for { JsonFormat(for {
data <- extractFromJsonBody[Seq[String]] data <- extractFromJsonBody[AddLabelsToAnIssue]
issueId <- params("id").toIntOpt issueId <- params("id").toIntOpt
} yield { } yield {
data.map { labelName => data.labels.map { labelName =>
val label = getLabel(repository.owner, repository.name, labelName).getOrElse( val label = getLabel(repository.owner, repository.name, labelName).getOrElse(
getLabel( getLabel(
repository.owner, repository.owner,
@@ -160,11 +155,11 @@ trait ApiIssueLabelControllerBase extends ControllerBase {
*/ */
put("/api/v3/repos/:owner/:repository/issues/:id/labels")(writableUsersOnly { repository => put("/api/v3/repos/:owner/:repository/issues/:id/labels")(writableUsersOnly { repository =>
JsonFormat(for { JsonFormat(for {
data <- extractFromJsonBody[Seq[String]] data <- extractFromJsonBody[AddLabelsToAnIssue]
issueId <- params("id").toIntOpt issueId <- params("id").toIntOpt
} yield { } yield {
deleteAllIssueLabels(repository.owner, repository.name, issueId, true) deleteAllIssueLabels(repository.owner, repository.name, issueId, true)
data.map { labelName => data.labels.map { labelName =>
val label = getLabel(repository.owner, repository.name, labelName).getOrElse( val label = getLabel(repository.owner, repository.name, labelName).getOrElse(
getLabel( getLabel(
repository.owner, repository.owner,
@@ -189,7 +184,7 @@ trait ApiIssueLabelControllerBase extends ControllerBase {
}) })
/* /*
* xi Get labels for every issue in a milestone * xi Get labels for every issue in a milestone
* https://developer.github.com/v3/issues/labels/#get-labels-for-every-issue-in-a-milestone * https://developer.github.com/v3/issues/labels/#get-labels-for-every-issue-in-a-milestone
*/ */
} }

View File

@@ -7,7 +7,7 @@ import gitbucket.core.util.Implicits._
import org.scalatra.NoContent import org.scalatra.NoContent
trait ApiIssueMilestoneControllerBase extends ControllerBase { trait ApiIssueMilestoneControllerBase extends ControllerBase {
self: MilestonesService with WritableUsersAuthenticator with ReferrerAuthenticator => self: MilestonesService & WritableUsersAuthenticator & ReferrerAuthenticator =>
/* /*
* i. List milestones * i. List milestones
@@ -16,8 +16,10 @@ trait ApiIssueMilestoneControllerBase extends ControllerBase {
get("/api/v3/repos/:owner/:repository/milestones")(referrersOnly { repository => get("/api/v3/repos/:owner/:repository/milestones")(referrersOnly { repository =>
val state = params.getOrElse("state", "all") val state = params.getOrElse("state", "all")
// TODO "sort", "direction" params should be implemented. // TODO "sort", "direction" params should be implemented.
val apiMilestones = (for (milestoneWithIssue <- getMilestonesWithIssueCount(repository.owner, repository.name) val apiMilestones = (for (
.sortBy(p => p._1.milestoneId)) milestoneWithIssue <- getMilestonesWithIssueCount(repository.owner, repository.name)
.sortBy(p => p._1.milestoneId)
)
yield { yield {
ApiMilestone( ApiMilestone(
repository.repository, repository.repository,
@@ -27,7 +29,7 @@ trait ApiIssueMilestoneControllerBase extends ControllerBase {
) )
}).reverse }).reverse
state match { state match {
case "all" => JsonFormat(apiMilestones) case "all" => JsonFormat(apiMilestones)
case "open" | "closed" => case "open" | "closed" =>
JsonFormat( JsonFormat(
apiMilestones.filter(p => p.state == state) apiMilestones.filter(p => p.state == state)

View File

@@ -6,7 +6,7 @@ import gitbucket.core.util.Implicits._
import gitbucket.core.util.{AdminAuthenticator, UsersAuthenticator} import gitbucket.core.util.{AdminAuthenticator, UsersAuthenticator}
trait ApiOrganizationControllerBase extends ControllerBase { trait ApiOrganizationControllerBase extends ControllerBase {
self: RepositoryService with AccountService with AdminAuthenticator with UsersAuthenticator => self: RepositoryService & AccountService & AdminAuthenticator & UsersAuthenticator =>
/* /*
* i. List your organizations * i. List your organizations
@@ -71,6 +71,6 @@ trait ApiOrganizationControllerBase extends ControllerBase {
*/ */
/* /*
* should implement delete an organization API? * should implement delete an organization API?
*/ */
} }

View File

@@ -16,14 +16,8 @@ import scala.util.Using
import scala.jdk.CollectionConverters._ import scala.jdk.CollectionConverters._
trait ApiPullRequestControllerBase extends ControllerBase { trait ApiPullRequestControllerBase extends ControllerBase {
self: AccountService self: AccountService & IssuesService & PullRequestService & RepositoryService & MergeService & ReferrerAuthenticator &
with IssuesService ReadableUsersAuthenticator & WritableUsersAuthenticator =>
with PullRequestService
with RepositoryService
with MergeService
with ReferrerAuthenticator
with ReadableUsersAuthenticator
with WritableUsersAuthenticator =>
/* /*
* i. Link Relations * i. Link Relations
@@ -48,19 +42,18 @@ trait ApiPullRequestControllerBase extends ControllerBase {
repos = repository.owner -> repository.name repos = repository.owner -> repository.name
) )
JsonFormat(issues.map { JsonFormat(issues.map { case (issue, issueUser, commentCount, pullRequest, headRepo, headOwner, assignees) =>
case (issue, issueUser, commentCount, pullRequest, headRepo, headOwner, assignees) => ApiPullRequest(
ApiPullRequest( issue = issue,
issue = issue, pullRequest = pullRequest,
pullRequest = pullRequest, headRepo = ApiRepository(headRepo, ApiUser(headOwner)),
headRepo = ApiRepository(headRepo, ApiUser(headOwner)), baseRepo = ApiRepository(repository, ApiUser(baseOwner)),
baseRepo = ApiRepository(repository, ApiUser(baseOwner)), user = ApiUser(issueUser),
user = ApiUser(issueUser), labels = getIssueLabels(repository.owner, repository.name, issue.issueId)
labels = getIssueLabels(repository.owner, repository.name, issue.issueId) .map(ApiLabel(_, RepositoryName(repository))),
.map(ApiLabel(_, RepositoryName(repository))), assignees = assignees.map(ApiUser.apply),
assignees = assignees.map(ApiUser.apply), mergedComment = getMergedComment(repository.owner, repository.name, issue.issueId)
mergedComment = getMergedComment(repository.owner, repository.name, issue.issueId) )
)
}) })
}) })
@@ -89,38 +82,37 @@ trait ApiPullRequestControllerBase extends ControllerBase {
case Left(createPullReq) => case Left(createPullReq) =>
val (reqOwner, reqBranch) = parseCompareIdentifier(createPullReq.head, repository.owner) val (reqOwner, reqBranch) = parseCompareIdentifier(createPullReq.head, repository.owner)
getRepository(reqOwner, repository.name) getRepository(reqOwner, repository.name)
.flatMap { .flatMap { forkedRepository =>
forkedRepository => getPullRequestCommitFromTo(repository, forkedRepository, createPullReq.base, reqBranch) match {
getPullRequestCommitFromTo(repository, forkedRepository, createPullReq.base, reqBranch) match { case (Some(commitIdFrom), Some(commitIdTo)) =>
case (Some(commitIdFrom), Some(commitIdTo)) => val issueId = insertIssue(
val issueId = insertIssue( owner = repository.owner,
owner = repository.owner, repository = repository.name,
repository = repository.name, loginUser = context.loginAccount.get.userName,
loginUser = context.loginAccount.get.userName, title = createPullReq.title,
title = createPullReq.title, content = createPullReq.body,
content = createPullReq.body, milestoneId = None,
milestoneId = None, priorityId = None,
priorityId = None, isPullRequest = true
isPullRequest = true )
)
createPullRequest( createPullRequest(
originRepository = repository, originRepository = repository,
issueId = issueId, issueId = issueId,
originBranch = createPullReq.base, originBranch = createPullReq.base,
requestUserName = reqOwner, requestUserName = reqOwner,
requestRepositoryName = repository.name, requestRepositoryName = repository.name,
requestBranch = reqBranch, requestBranch = reqBranch,
commitIdFrom = commitIdFrom.getName, commitIdFrom = commitIdFrom.getName,
commitIdTo = commitIdTo.getName, commitIdTo = commitIdTo.getName,
isDraft = createPullReq.draft.getOrElse(false), isDraft = createPullReq.draft.getOrElse(false),
loginAccount = context.loginAccount.get, loginAccount = context.loginAccount.get,
settings = context.settings settings = context.settings
) )
getApiPullRequest(repository, issueId).map(JsonFormat(_)) getApiPullRequest(repository, issueId).map(JsonFormat(_))
case _ => case _ =>
None None
} }
} }
.getOrElse { .getOrElse {
NotFound() NotFound()
@@ -128,28 +120,27 @@ trait ApiPullRequestControllerBase extends ControllerBase {
case Right(createPullReqAlt) => case Right(createPullReqAlt) =>
val (reqOwner, reqBranch) = parseCompareIdentifier(createPullReqAlt.head, repository.owner) val (reqOwner, reqBranch) = parseCompareIdentifier(createPullReqAlt.head, repository.owner)
getRepository(reqOwner, repository.name) getRepository(reqOwner, repository.name)
.flatMap { .flatMap { forkedRepository =>
forkedRepository => getPullRequestCommitFromTo(repository, forkedRepository, createPullReqAlt.base, reqBranch) match {
getPullRequestCommitFromTo(repository, forkedRepository, createPullReqAlt.base, reqBranch) match { case (Some(commitIdFrom), Some(commitIdTo)) =>
case (Some(commitIdFrom), Some(commitIdTo)) => changeIssueToPullRequest(repository.owner, repository.name, createPullReqAlt.issue)
changeIssueToPullRequest(repository.owner, repository.name, createPullReqAlt.issue) createPullRequest(
createPullRequest( originRepository = repository,
originRepository = repository, issueId = createPullReqAlt.issue,
issueId = createPullReqAlt.issue, originBranch = createPullReqAlt.base,
originBranch = createPullReqAlt.base, requestUserName = reqOwner,
requestUserName = reqOwner, requestRepositoryName = repository.name,
requestRepositoryName = repository.name, requestBranch = reqBranch,
requestBranch = reqBranch, commitIdFrom = commitIdFrom.getName,
commitIdFrom = commitIdFrom.getName, commitIdTo = commitIdTo.getName,
commitIdTo = commitIdTo.getName, isDraft = false,
isDraft = false, loginAccount = context.loginAccount.get,
loginAccount = context.loginAccount.get, settings = context.settings
settings = context.settings )
) getApiPullRequest(repository, createPullReqAlt.issue).map(JsonFormat(_))
getApiPullRequest(repository, createPullReqAlt.issue).map(JsonFormat(_)) case _ =>
case _ => None
None }
}
} }
.getOrElse { .getOrElse {
NotFound() NotFound()
@@ -190,26 +181,24 @@ trait ApiPullRequestControllerBase extends ControllerBase {
get("/api/v3/repos/:owner/:repository/pulls/:id/commits")(referrersOnly { repository => get("/api/v3/repos/:owner/:repository/pulls/:id/commits")(referrersOnly { repository =>
val owner = repository.owner val owner = repository.owner
val name = repository.name val name = repository.name
params("id").toIntOpt.flatMap { params("id").toIntOpt.flatMap { issueId =>
issueId => getPullRequest(owner, name, issueId) map { case (issue, pullreq) =>
getPullRequest(owner, name, issueId) map { Using.resource(Git.open(getRepositoryDir(owner, name))) { git =>
case (issue, pullreq) => val oldId = git.getRepository.resolve(pullreq.commitIdFrom)
Using.resource(Git.open(getRepositoryDir(owner, name))) { git => val newId = git.getRepository.resolve(pullreq.commitIdTo)
val oldId = git.getRepository.resolve(pullreq.commitIdFrom) val repoFullName = RepositoryName(repository)
val newId = git.getRepository.resolve(pullreq.commitIdTo) val commits = git.log
val repoFullName = RepositoryName(repository) .addRange(oldId, newId)
val commits = git.log .call
.addRange(oldId, newId) .iterator
.call .asScala
.iterator .map { c =>
.asScala ApiCommitListItem(new CommitInfo(c), repoFullName)
.map { c =>
ApiCommitListItem(new CommitInfo(c), repoFullName)
}
.toList
JsonFormat(commits)
} }
.toList
JsonFormat(commits)
} }
}
} getOrElse NotFound() } getOrElse NotFound()
}) })
/* /*
@@ -240,8 +229,8 @@ trait ApiPullRequestControllerBase extends ControllerBase {
*/ */
put("/api/v3/repos/:owner/:repository/pulls/:id/merge")(referrersOnly { repository => put("/api/v3/repos/:owner/:repository/pulls/:id/merge")(referrersOnly { repository =>
(for { (for {
//TODO: crash when body is empty // TODO: crash when body is empty
//TODO: Implement sha parameter // TODO: Implement sha parameter
data <- extractFromJsonBody[MergeAPullRequest] data <- extractFromJsonBody[MergeAPullRequest]
issueId <- params("id").toIntOpt issueId <- params("id").toIntOpt
(issue, pullReq) <- getPullRequest(repository.owner, repository.name, issueId) (issue, pullReq) <- getPullRequest(repository.owner, repository.name, issueId)
@@ -273,7 +262,7 @@ trait ApiPullRequestControllerBase extends ControllerBase {
repository, repository,
issueId, issueId,
context.loginAccount.get, context.loginAccount.get,
data.commit_message.getOrElse(""), //TODO: Implement commit_title data.commit_message.getOrElse(""), // TODO: Implement commit_title
strategy, strategy,
pullReq.isDraft, pullReq.isDraft,
context.settings context.settings

View File

@@ -11,7 +11,7 @@ import org.apache.commons.io.FileUtils
import org.scalatra.NoContent import org.scalatra.NoContent
trait ApiReleaseControllerBase extends ControllerBase { trait ApiReleaseControllerBase extends ControllerBase {
self: AccountService with ReleaseService with ReferrerAuthenticator with WritableUsersAuthenticator => self: AccountService & ReleaseService & ReferrerAuthenticator & WritableUsersAuthenticator =>
/** /**
* i. List releases for a repository * i. List releases for a repository
@@ -119,40 +119,39 @@ trait ApiReleaseControllerBase extends ControllerBase {
* ix. Upload a release asset * ix. Upload a release asset
* https://developer.github.com/v3/repos/releases/#upload-a-release-asset * https://developer.github.com/v3/repos/releases/#upload-a-release-asset
*/ */
post("/api/v3/repos/:owner/:repository/releases/:tag/assets")(writableUsersOnly { post("/api/v3/repos/:owner/:repository/releases/:tag/assets")(writableUsersOnly { repository =>
repository => val name = params("name")
val name = params("name") val tag = params("tag")
val tag = params("tag") getRelease(repository.owner, repository.name, tag)
getRelease(repository.owner, repository.name, tag) .map { release =>
.map { release => val fileId = FileUtil.generateFileId
val fileId = FileUtil.generateFileId val buf = new Array[Byte](request.inputStream.available())
val buf = new Array[Byte](request.inputStream.available()) request.inputStream.read(buf)
request.inputStream.read(buf) FileUtils.writeByteArrayToFile(
FileUtils.writeByteArrayToFile( new File(
new File( getReleaseFilesDir(repository.owner, repository.name),
getReleaseFilesDir(repository.owner, repository.name), FileUtil.checkFilename(tag + "/" + fileId)
FileUtil.checkFilename(tag + "/" + fileId) ),
), buf
buf )
) createReleaseAsset(
createReleaseAsset( repository.owner,
repository.owner, repository.name,
repository.name, tag,
tag, fileId,
fileId, name,
name, request.contentLength.getOrElse(0),
request.contentLength.getOrElse(0), context.loginAccount.get
context.loginAccount.get )
) getReleaseAsset(repository.owner, repository.name, tag, fileId)
getReleaseAsset(repository.owner, repository.name, tag, fileId) .map { asset =>
.map { asset => JsonFormat(ApiReleaseAsset(asset, RepositoryName(repository)))
JsonFormat(ApiReleaseAsset(asset, RepositoryName(repository))) }
} .getOrElse {
.getOrElse { ApiError("Unknown error")
ApiError("Unknown error") }
} }
} .getOrElse(NotFound())
.getOrElse(NotFound())
}) })
/** /**
@@ -176,7 +175,7 @@ trait ApiReleaseControllerBase extends ControllerBase {
*/ */
/* /*
* xii. Delete a release asset * xii. Delete a release asset
* https://developer.github.com/v3/repos/releases/#edit-a-release-asset * https://developer.github.com/v3/repos/releases/#edit-a-release-asset
*/ */
} }

View File

@@ -1,26 +1,19 @@
package gitbucket.core.controller.api package gitbucket.core.controller.api
import gitbucket.core.api._ import gitbucket.core.api.*
import gitbucket.core.controller.ControllerBase import gitbucket.core.controller.ControllerBase
import gitbucket.core.service.{AccountService, ProtectedBranchService, RepositoryService} import gitbucket.core.service.{AccountService, ProtectedBranchService, RepositoryService}
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.*
import gitbucket.core.util.JGitUtil.getBranches import gitbucket.core.util.JGitUtil.{getBranchesNoMergeInfo, processTree}
import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.Git
import org.scalatra.NoContent import org.scalatra.NoContent
import scala.util.Using import scala.util.Using
trait ApiRepositoryBranchControllerBase extends ControllerBase { trait ApiRepositoryBranchControllerBase extends ControllerBase {
self: RepositoryService self: RepositoryService & AccountService & OwnerAuthenticator & UsersAuthenticator & GroupManagerAuthenticator &
with AccountService ProtectedBranchService & ReferrerAuthenticator & ReadableUsersAuthenticator & WritableUsersAuthenticator =>
with OwnerAuthenticator
with UsersAuthenticator
with GroupManagerAuthenticator
with ProtectedBranchService
with ReferrerAuthenticator
with ReadableUsersAuthenticator
with WritableUsersAuthenticator =>
/** /**
* i. List branches * i. List branches
@@ -30,11 +23,7 @@ trait ApiRepositoryBranchControllerBase extends ControllerBase {
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git => Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
JsonFormat( JsonFormat(
JGitUtil JGitUtil
.getBranches( .getBranchesNoMergeInfo(git)
git = git,
defaultBranch = repository.repository.defaultBranch,
origin = repository.repository.originUserName.isEmpty
)
.map { br => .map { br =>
ApiBranchForList(br.name, ApiBranchCommit(br.commitId)) ApiBranchForList(br.name, ApiBranchCommit(br.commitId))
} }
@@ -47,21 +36,18 @@ trait ApiRepositoryBranchControllerBase extends ControllerBase {
* https://docs.github.com/en/rest/reference/repos#get-a-branch * https://docs.github.com/en/rest/reference/repos#get-a-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))) { git =>
git => (for {
(for { branch <- params.get("splat") if repository.branchList.contains(branch)
branch <- params.get("splat") if repository.branchList.contains(branch) br <- getBranchesNoMergeInfo(git).find(_.name == branch)
br <- getBranches( } yield {
git, val protection = getProtectedBranchInfo(repository.owner, repository.name, branch)
repository.repository.defaultBranch, JsonFormat(
repository.repository.originUserName.isEmpty ApiBranch(branch, ApiBranchCommit(br.commitId), ApiBranchProtectionResponse(protection))(
).find(_.name == branch) RepositoryName(repository)
} yield {
val protection = getProtectedBranchInfo(repository.owner, repository.name, branch)
JsonFormat(
ApiBranch(branch, ApiBranchCommit(br.commitId), ApiBranchProtection(protection))(RepositoryName(repository))
) )
}) getOrElse NotFound() )
}) getOrElse NotFound()
} }
}) })
@@ -74,7 +60,7 @@ trait ApiRepositoryBranchControllerBase extends ControllerBase {
if (repository.branchList.contains(branch)) { if (repository.branchList.contains(branch)) {
val protection = getProtectedBranchInfo(repository.owner, repository.name, branch) val protection = getProtectedBranchInfo(repository.owner, repository.name, branch)
JsonFormat( JsonFormat(
ApiBranchProtection(protection) ApiBranchProtectionResponse(protection)
) )
} else { NotFound() } } else { NotFound() }
}) })
@@ -154,7 +140,7 @@ trait ApiRepositoryBranchControllerBase extends ControllerBase {
if (repository.branchList.contains(branch)) { if (repository.branchList.contains(branch)) {
val protection = getProtectedBranchInfo(repository.owner, repository.name, branch) val protection = getProtectedBranchInfo(repository.owner, repository.name, branch)
JsonFormat( JsonFormat(
ApiBranchProtection(protection).required_status_checks ApiBranchProtectionResponse(protection).required_status_checks
) )
} else { NotFound() } } else { NotFound() }
}) })
@@ -274,31 +260,30 @@ trait ApiRepositoryBranchControllerBase extends ControllerBase {
* https://developer.github.com/v3/repos/#enabling-and-disabling-branch-protection * https://developer.github.com/v3/repos/#enabling-and-disabling-branch-protection
*/ */
patch("/api/v3/repos/:owner/:repository/branches/*")(ownerOnly { repository => patch("/api/v3/repos/:owner/:repository/branches/*")(ownerOnly { repository =>
import gitbucket.core.api._ import gitbucket.core.api.*
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
git => (for {
(for { branch <- params.get("splat") if repository.branchList.contains(branch)
branch <- params.get("splat") if repository.branchList.contains(branch) protection <- extractFromJsonBody[ApiBranchProtectionRequest.EnablingAndDisabling].map(_.protection)
protection <- extractFromJsonBody[ApiBranchProtection.EnablingAndDisabling].map(_.protection) br <- getBranchesNoMergeInfo(git).find(_.name == branch)
br <- getBranches( } yield {
git, if (protection.enabled) {
repository.repository.defaultBranch, enableBranchProtection(
repository.repository.originUserName.isEmpty repository.owner,
).find(_.name == branch) repository.name,
} yield { branch,
if (protection.enabled) { protection.enforce_admins.getOrElse(false),
enableBranchProtection( protection.required_status_checks.isDefined,
repository.owner, protection.required_status_checks.map(_.contexts).getOrElse(Nil),
repository.name, protection.restrictions.isDefined,
branch, protection.restrictions.map(_.users).getOrElse(Nil)
protection.status.enforcement_level == ApiBranchProtection.Everyone, )
protection.status.contexts } else {
) disableBranchProtection(repository.owner, repository.name, branch)
} else { }
disableBranchProtection(repository.owner, repository.name, branch) val response = ApiBranchProtectionResponse(getProtectedBranchInfo(repository.owner, repository.name, branch))
} JsonFormat(ApiBranch(branch, ApiBranchCommit(br.commitId), response)(RepositoryName(repository)))
JsonFormat(ApiBranch(branch, ApiBranchCommit(br.commitId), protection)(RepositoryName(repository))) }) getOrElse NotFound()
}) getOrElse NotFound()
} }
}) })
} }

View File

@@ -7,7 +7,7 @@ import gitbucket.core.util.{OwnerAuthenticator, ReferrerAuthenticator}
import org.scalatra.NoContent import org.scalatra.NoContent
trait ApiRepositoryCollaboratorControllerBase extends ControllerBase { trait ApiRepositoryCollaboratorControllerBase extends ControllerBase {
self: RepositoryService with AccountService with ReferrerAuthenticator with OwnerAuthenticator => self: RepositoryService & AccountService & ReferrerAuthenticator & OwnerAuthenticator =>
/* /*
* i. List repository collaborators * i. List repository collaborators

View File

@@ -4,31 +4,24 @@ 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, ProtectedBranchService}
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, getBranchesNoMergeInfo, getBranchesOfCommit}
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 org.eclipse.jgit.revwalk.filter.{ import org.eclipse.jgit.revwalk.filter.*
AndRevFilter,
AuthorRevFilter,
CommitTimeRevFilter,
MaxCountRevFilter,
RevFilter,
SkipRevFilter
}
import org.eclipse.jgit.treewalk.filter.{AndTreeFilter, PathFilterGroup, TreeFilter} import org.eclipse.jgit.treewalk.filter.{AndTreeFilter, PathFilterGroup, TreeFilter}
import scala.collection.mutable.ListBuffer
import scala.jdk.CollectionConverters._ import java.time.format.DateTimeFormatter.*
import scala.util.Using import java.time.{LocalDateTime, ZoneOffset}
import math.min
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter._
import java.util.Date import java.util.Date
import java.time.ZoneOffset import scala.collection.mutable.ListBuffer
import scala.jdk.CollectionConverters.*
import scala.math.min
import scala.util.Using
trait ApiRepositoryCommitControllerBase extends ControllerBase { trait ApiRepositoryCommitControllerBase extends ControllerBase {
self: AccountService with CommitsService with ProtectedBranchService with ReferrerAuthenticator => self: AccountService & CommitsService & ProtectedBranchService & 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
@@ -43,56 +36,53 @@ trait ApiRepositoryCommitControllerBase extends ControllerBase {
val path = params.get("path").filter(_.nonEmpty) val path = params.get("path").filter(_.nonEmpty)
val since = params.get("since").filter(_.nonEmpty) val since = params.get("since").filter(_.nonEmpty)
val until = params.get("until").filter(_.nonEmpty) val until = params.get("until").filter(_.nonEmpty)
Using.resource(Git.open(getRepositoryDir(owner, name))) { Using.resource(Git.open(getRepositoryDir(owner, name))) { git =>
git => val repo = git.getRepository
val repo = git.getRepository Using.resource(new RevWalk(repo)) { revWalk =>
Using.resource(new RevWalk(repo)) { val objectId = repo.resolve(sha)
revWalk => revWalk.markStart(revWalk.parseCommit(objectId))
val objectId = repo.resolve(sha) if (path.nonEmpty) {
revWalk.markStart(revWalk.parseCommit(objectId)) revWalk.setTreeFilter(
if (path.nonEmpty) { AndTreeFilter.create(PathFilterGroup.createFromStrings(path.get), TreeFilter.ANY_DIFF)
revWalk.setTreeFilter( )
AndTreeFilter.create(PathFilterGroup.createFromStrings(path.get), TreeFilter.ANY_DIFF)
)
}
val revfilters = new ListBuffer[(RevFilter)]()
if (author.nonEmpty) {
revfilters += AuthorRevFilter.create(author.get)
}
if (since.nonEmpty) {
revfilters += CommitTimeRevFilter.after(
Date.from(LocalDateTime.parse(since.get, ISO_DATE_TIME).toInstant(ZoneOffset.UTC))
)
}
if (until.nonEmpty) {
revfilters += CommitTimeRevFilter.before(
Date.from(LocalDateTime.parse(until.get, ISO_DATE_TIME).toInstant(ZoneOffset.UTC))
)
}
if (page > 1) {
revfilters += SkipRevFilter.create(page * per_page - 2)
}
revfilters += MaxCountRevFilter.create(per_page);
revWalk.setRevFilter(
if (revfilters.size > 1) {
AndRevFilter.create(revfilters.toArray)
} else {
revfilters(0)
}
)
JsonFormat(revWalk.asScala.map {
commit =>
val commitInfo = new CommitInfo(commit)
ApiCommits(
repositoryName = RepositoryName(repository),
commitInfo = commitInfo,
diffs = JGitUtil.getDiffs(git, commitInfo.parents.headOption, commitInfo.id, false, true),
author = getAccount(commitInfo.authorName, commitInfo.authorEmailAddress),
committer = getAccount(commitInfo.committerName, commitInfo.committerEmailAddress),
commentCount = getCommitComment(repository.owner, repository.name, commitInfo.id).size
)
})
} }
val revfilters = new ListBuffer[(RevFilter)]()
if (author.nonEmpty) {
revfilters += AuthorRevFilter.create(author.get)
}
if (since.nonEmpty) {
revfilters += CommitTimeRevFilter.after(
Date.from(LocalDateTime.parse(since.get, ISO_DATE_TIME).toInstant(ZoneOffset.UTC))
)
}
if (until.nonEmpty) {
revfilters += CommitTimeRevFilter.before(
Date.from(LocalDateTime.parse(until.get, ISO_DATE_TIME).toInstant(ZoneOffset.UTC))
)
}
if (page > 1) {
revfilters += SkipRevFilter.create(page * per_page - 2)
}
revfilters += MaxCountRevFilter.create(per_page);
revWalk.setRevFilter(
if (revfilters.size > 1) {
AndRevFilter.create(revfilters.toArray)
} else {
revfilters(0)
}
)
JsonFormat(revWalk.asScala.map { commit =>
val commitInfo = new CommitInfo(commit)
ApiCommits(
repositoryName = RepositoryName(repository),
commitInfo = commitInfo,
diffs = JGitUtil.getDiffs(git, commitInfo.parents.headOption, commitInfo.id, false, true),
author = getAccount(commitInfo.authorName, commitInfo.authorEmailAddress),
committer = getAccount(commitInfo.committerName, commitInfo.committerEmailAddress),
commentCount = getCommitComment(repository.owner, repository.name, commitInfo.id).size
)
})
}
} }
}) })
@@ -105,24 +95,23 @@ trait ApiRepositoryCommitControllerBase extends ControllerBase {
val name = repository.name val name = repository.name
val sha = params("sha") val sha = params("sha")
Using.resource(Git.open(getRepositoryDir(owner, name))) { Using.resource(Git.open(getRepositoryDir(owner, name))) { git =>
git => val repo = git.getRepository
val repo = git.getRepository val objectId = repo.resolve(sha)
val objectId = repo.resolve(sha) val commitInfo = Using.resource(new RevWalk(repo)) { revWalk =>
val commitInfo = Using.resource(new RevWalk(repo)) { revWalk => new CommitInfo(revWalk.parseCommit(objectId))
new CommitInfo(revWalk.parseCommit(objectId)) }
}
JsonFormat( JsonFormat(
ApiCommits( ApiCommits(
repositoryName = RepositoryName(repository), repositoryName = RepositoryName(repository),
commitInfo = commitInfo, commitInfo = commitInfo,
diffs = JGitUtil.getDiffs(git, commitInfo.parents.headOption, commitInfo.id, false, true), diffs = JGitUtil.getDiffs(git, commitInfo.parents.headOption, commitInfo.id, false, true),
author = getAccount(commitInfo.authorName, commitInfo.authorEmailAddress), author = getAccount(commitInfo.authorName, commitInfo.authorEmailAddress),
committer = getAccount(commitInfo.committerName, commitInfo.committerEmailAddress), committer = getAccount(commitInfo.committerName, commitInfo.committerEmailAddress),
commentCount = getCommitComment(repository.owner, repository.name, sha).size commentCount = getCommitComment(repository.owner, repository.name, sha).size
)
) )
)
} }
}) })
@@ -170,7 +159,7 @@ trait ApiRepositoryCommitControllerBase extends ControllerBase {
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git => Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
val apiBranchForCommits = for { val apiBranchForCommits = for {
branch <- getBranchesOfCommit(git, sha) branch <- getBranchesOfCommit(git, sha)
br <- getBranches(git, branch, repository.repository.originUserName.isEmpty).find(_.name == branch) br <- getBranchesNoMergeInfo(git).find(_.name == branch)
} yield { } yield {
val protection = getProtectedBranchInfo(repository.owner, repository.name, branch) val protection = getProtectedBranchInfo(repository.owner, repository.name, branch)
ApiBranchForHeadCommit(branch, ApiBranchCommit(br.commitId), protection.enabled) ApiBranchForHeadCommit(branch, ApiBranchCommit(br.commitId), protection.enabled)

View File

@@ -12,24 +12,23 @@ 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 & WritableUsersAuthenticator & RepositoryCommitFileService =>
/** /**
* i. Get a repository README * i. Get a repository README
* https://docs.github.com/en/rest/reference/repos#get-a-repository-readme * https://docs.github.com/en/rest/reference/repos#get-a-repository-readme
*/ */
get("/api/v3/repos/:owner/:repository/readme")(referrersOnly { repository => get("/api/v3/repos/:owner/:repository/readme")(referrersOnly { repository =>
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { git =>
git => val refStr = params.getOrElse("ref", repository.repository.defaultBranch)
val refStr = params.getOrElse("ref", repository.repository.defaultBranch) val files = getFileList(git, refStr, ".", maxFiles = context.settings.repositoryViewer.maxFiles)
val files = getFileList(git, refStr, ".", maxFiles = context.settings.repositoryViewer.maxFiles) files // files should be sorted alphabetically.
files // files should be sorted alphabetically. .find { file =>
.find { file => !file.isDirectory && RepositoryService.readmeFiles.contains(file.name.toLowerCase)
!file.isDirectory && RepositoryService.readmeFiles.contains(file.name.toLowerCase) } match {
} match { case Some(x) => getContents(repository = repository, path = x.name, refStr = refStr, ignoreCase = true)
case Some(x) => getContents(repository = repository, path = x.name, refStr = refStr, ignoreCase = true) case _ => NotFound()
case _ => NotFound() }
}
} }
}) })
@@ -134,67 +133,66 @@ trait ApiRepositoryContentsControllerBase extends ControllerBase {
* requested #2112 * requested #2112
*/ */
put("/api/v3/repos/:owner/:repository/contents/*")(writableUsersOnly { repository => put("/api/v3/repos/:owner/:repository/contents/*")(writableUsersOnly { repository =>
context.withLoginAccount { context.withLoginAccount { loginAccount =>
loginAccount => JsonFormat(for {
JsonFormat(for { data <- extractFromJsonBody[CreateAFile]
data <- extractFromJsonBody[CreateAFile] } yield {
} yield { val branch = data.branch.getOrElse(repository.repository.defaultBranch)
val branch = data.branch.getOrElse(repository.repository.defaultBranch) val commit = Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
val commit = Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git => val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(branch))
val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(branch)) revCommit.name
revCommit.name }
} val fullPath = multiParams("splat").head
val paths = multiParams("splat").head.split("/") val paths = fullPath.split("/")
val path = paths.take(paths.size - 1).toList.mkString("/") val path = paths.take(paths.size - 1).toList.mkString("/")
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { git =>
git => val fileInfo = getFileInfo(git, commit, fullPath, ignoreCase = false)
val fileInfo = getFileInfo(git, commit, path, false)
fileInfo match { fileInfo match {
case Some(f) if !data.sha.contains(f.id.getName) => case Some(f) if !data.sha.contains(f.id.getName) =>
ApiError( ApiError(
"The blob SHA is not matched.", "The blob SHA is not matched.",
Some("https://docs.github.com/en/rest/reference/repos#create-or-update-file-contents") Some("https://docs.github.com/en/rest/reference/repos#create-or-update-file-contents")
)
case _ =>
commitFile(
repository,
branch,
path,
Some(paths.last),
data.sha.map(_ => paths.last),
StringUtil.base64Decode(data.content),
data.message,
commit,
loginAccount,
data.committer.map(_.name).getOrElse(loginAccount.fullName),
data.committer.map(_.email).getOrElse(loginAccount.mailAddress),
context.settings
) match {
case Left(error) =>
ApiError(s"Failed to commit a file: ${error}", None)
case Right((_, None)) =>
ApiError("Failed to commit a file.", None)
case Right((commitId, Some(blobId))) =>
Map(
"content" -> ApiContents(
"file",
paths.last,
path,
blobId.name,
Some(data.content),
Some("base64")
)(RepositoryName(repository)),
"commit" -> ApiCommit(
git,
RepositoryName(repository),
new CommitInfo(JGitUtil.getRevCommitFromId(git, commitId))
)
) )
case _ =>
commitFile(
repository,
branch,
path,
Some(paths.last),
data.sha.map(_ => paths.last),
StringUtil.base64Decode(data.content),
data.message,
commit,
loginAccount,
data.committer.map(_.name).getOrElse(loginAccount.fullName),
data.committer.map(_.email).getOrElse(loginAccount.mailAddress),
context.settings
) match {
case Left(error) =>
ApiError(s"Failed to commit a file: ${error}", None)
case Right((_, None)) =>
ApiError("Failed to commit a file.", None)
case Right((commitId, Some(blobId))) =>
Map(
"content" -> ApiContents(
"file",
paths.last,
path,
blobId.name,
Some(data.content),
Some("base64")
)(RepositoryName(repository)),
"commit" -> ApiCommit(
git,
RepositoryName(repository),
new CommitInfo(JGitUtil.getRevCommitFromId(git, commitId))
)
)
}
} }
} }
}) }
})
} }
}) })
@@ -205,9 +203,9 @@ trait ApiRepositoryContentsControllerBase extends ControllerBase {
*/ */
/* /*
* vi. Download a repository archive (tar/zip) * vi. Download a repository archive (tar/zip)
* https://docs.github.com/en/rest/reference/repos#download-a-repository-archive-tar * https://docs.github.com/en/rest/reference/repos#download-a-repository-archive-tar
* https://docs.github.com/en/rest/reference/repos#download-a-repository-archive-zip * https://docs.github.com/en/rest/reference/repos#download-a-repository-archive-zip
*/ */
} }

View File

@@ -15,16 +15,9 @@ import scala.concurrent.duration.Duration
import scala.util.Using import scala.util.Using
trait ApiRepositoryControllerBase extends ControllerBase { trait ApiRepositoryControllerBase extends ControllerBase {
self: RepositoryService self: RepositoryService & ApiGitReferenceControllerBase & RepositoryCreationService & AccountService &
with ApiGitReferenceControllerBase OwnerAuthenticator & UsersAuthenticator & GroupManagerAuthenticator & ReferrerAuthenticator &
with RepositoryCreationService ReadableUsersAuthenticator & WritableUsersAuthenticator =>
with AccountService
with OwnerAuthenticator
with UsersAuthenticator
with GroupManagerAuthenticator
with ReferrerAuthenticator
with ReadableUsersAuthenticator
with WritableUsersAuthenticator =>
/** /**
* i. List your repositories * i. List your repositories
@@ -93,7 +86,8 @@ trait ApiRepositoryControllerBase extends ControllerBase {
data.name, data.name,
data.description, data.description,
data.`private`, data.`private`,
data.auto_init data.auto_init,
context.settings.defaultBranch
) )
Await.result(f, Duration.Inf) Await.result(f, Duration.Inf)
@@ -130,7 +124,8 @@ trait ApiRepositoryControllerBase extends ControllerBase {
data.name, data.name,
data.description, data.description,
data.`private`, data.`private`,
data.auto_init data.auto_init,
context.settings.defaultBranch
) )
Await.result(f, Duration.Inf) Await.result(f, Duration.Inf)
val repository = Database() withTransaction { session => val repository = Database() withTransaction { session =>
@@ -187,7 +182,7 @@ trait ApiRepositoryControllerBase extends ControllerBase {
get("/api/v3/repos/:owner/:repository/tags")(referrersOnly { repository => get("/api/v3/repos/:owner/:repository/tags")(referrersOnly { repository =>
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git => Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
JsonFormat( JsonFormat(
self.getRef("tags", repository) repository.tags.map(tagInfo => ApiTag(tagInfo.name, RepositoryName(repository), tagInfo.commitId))
) )
} }
}) })

View File

@@ -7,7 +7,7 @@ import gitbucket.core.util.Implicits._
import gitbucket.core.util.{JGitUtil, ReferrerAuthenticator, WritableUsersAuthenticator} import gitbucket.core.util.{JGitUtil, ReferrerAuthenticator, WritableUsersAuthenticator}
trait ApiRepositoryStatusControllerBase extends ControllerBase { trait ApiRepositoryStatusControllerBase extends ControllerBase {
self: AccountService with CommitStatusService with ReferrerAuthenticator with WritableUsersAuthenticator => self: AccountService & CommitStatusService & ReferrerAuthenticator & WritableUsersAuthenticator =>
/* /*
* i. Create a status * i. Create a status
@@ -47,9 +47,8 @@ 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(getCommitStatusesWithCreator(repository.owner, repository.name, sha).map { case (status, creator) =>
case (status, creator) => ApiCommitStatus(status, ApiUser(creator))
ApiCommitStatus(status, ApiUser(creator))
}) })
}) getOrElse NotFound() }) getOrElse NotFound()
}) })

View File

@@ -8,7 +8,7 @@ import gitbucket.core.util.Implicits._
import org.scalatra.NoContent import org.scalatra.NoContent
trait ApiRepositoryWebhookControllerBase extends ControllerBase { trait ApiRepositoryWebhookControllerBase extends ControllerBase {
self: RepositoryService with WebHookService with ReferrerAuthenticator with WritableUsersAuthenticator => self: RepositoryService & WebHookService & ReferrerAuthenticator & WritableUsersAuthenticator =>
/* /*
* i. List repository webhooks * i. List repository webhooks
@@ -113,8 +113,8 @@ trait ApiRepositoryWebhookControllerBase extends ControllerBase {
*/ */
/* /*
* vi. Test the push repository webhook * vi. Test the push repository webhook
* https://docs.github.com/en/rest/reference/repos#test-the-push-repository-webhook * https://docs.github.com/en/rest/reference/repos#test-the-push-repository-webhook
*/ */
} }

View File

@@ -8,7 +8,7 @@ import gitbucket.core.util.StringUtil._
import org.scalatra.NoContent import org.scalatra.NoContent
trait ApiUserControllerBase extends ControllerBase { trait ApiUserControllerBase extends ControllerBase {
self: RepositoryService with AccountService with AdminAuthenticator with UsersAuthenticator => self: RepositoryService & AccountService & AdminAuthenticator & UsersAuthenticator =>
/** /**
* i. Get a single user * i. Get a single user

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).mapTo[AccessToken]
} }
} }
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) ).mapTo[Account]
} }
} }

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).mapTo[AccountExtraMailAddress]
} }
} }

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).mapTo[AccountFederation]
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

@@ -9,7 +9,7 @@ trait AccountPreferenceComponent { self: Profile =>
val userName = column[String]("USER_NAME", O PrimaryKey) val userName = column[String]("USER_NAME", O PrimaryKey)
val highlighterTheme = column[String]("HIGHLIGHTER_THEME") val highlighterTheme = column[String]("HIGHLIGHTER_THEME")
def * = def * =
(userName, highlighterTheme).<>(AccountPreference.tupled, AccountPreference.unapply) (userName, highlighterTheme).mapTo[AccountPreference]
def byPrimaryKey(userName: String): Rep[Boolean] = this.userName === userName.bind def byPrimaryKey(userName: String): Rep[Boolean] = this.userName === userName.bind
} }

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).mapTo[AccountWebHook]
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

@@ -12,7 +12,7 @@ trait AccountWebHookEventComponent 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 * = (userName, url, event).<>((AccountWebHookEvent.apply _).tupled, AccountWebHookEvent.unapply) def * = (userName, url, event).mapTo[AccountWebHookEvent]
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

@@ -11,7 +11,7 @@ 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 * = ??? def * : slick.lifted.ProvenShape[Activity] = ???
} }
} }

View File

@@ -3,7 +3,7 @@ package gitbucket.core.model
protected[model] trait TemplateComponent { self: Profile => protected[model] trait TemplateComponent { self: Profile =>
import profile.api._ import profile.api._
trait BasicTemplate { self: Table[_] => trait BasicTemplate { self: Table[?] =>
val userName = column[String]("USER_NAME") val userName = column[String]("USER_NAME")
val repositoryName = column[String]("REPOSITORY_NAME") val repositoryName = column[String]("REPOSITORY_NAME")
@@ -18,7 +18,7 @@ protected[model] trait TemplateComponent { self: Profile =>
(this.userName === userName) && (this.repositoryName === repositoryName) (this.userName === userName) && (this.repositoryName === repositoryName)
} }
trait IssueTemplate extends BasicTemplate { self: Table[_] => trait IssueTemplate extends BasicTemplate { self: Table[?] =>
val issueId = column[Int]("ISSUE_ID") val issueId = column[Int]("ISSUE_ID")
def byIssue(owner: String, repository: String, issueId: Int) = def byIssue(owner: String, repository: String, issueId: Int) =
@@ -28,7 +28,7 @@ protected[model] trait TemplateComponent { self: Profile =>
byRepository(userName, repositoryName) && (this.issueId === issueId) byRepository(userName, repositoryName) && (this.issueId === issueId)
} }
trait LabelTemplate extends BasicTemplate { self: Table[_] => trait LabelTemplate extends BasicTemplate { self: Table[?] =>
val labelId = column[Int]("LABEL_ID") val labelId = column[Int]("LABEL_ID")
val labelName = column[String]("LABEL_NAME") val labelName = column[String]("LABEL_NAME")
@@ -42,7 +42,7 @@ protected[model] trait TemplateComponent { self: Profile =>
byRepository(owner, repository) && (this.labelName === labelName.bind) byRepository(owner, repository) && (this.labelName === labelName.bind)
} }
trait PriorityTemplate extends BasicTemplate { self: Table[_] => trait PriorityTemplate extends BasicTemplate { self: Table[?] =>
val priorityId = column[Int]("PRIORITY_ID") val priorityId = column[Int]("PRIORITY_ID")
val priorityName = column[String]("PRIORITY_NAME") val priorityName = column[String]("PRIORITY_NAME")
@@ -56,7 +56,7 @@ protected[model] trait TemplateComponent { self: Profile =>
byRepository(owner, repository) && (this.priorityName === priorityName.bind) byRepository(owner, repository) && (this.priorityName === priorityName.bind)
} }
trait MilestoneTemplate extends BasicTemplate { self: Table[_] => trait MilestoneTemplate extends BasicTemplate { self: Table[?] =>
val milestoneId = column[Int]("MILESTONE_ID") val milestoneId = column[Int]("MILESTONE_ID")
def byMilestone(owner: String, repository: String, milestoneId: Int) = def byMilestone(owner: String, repository: String, milestoneId: Int) =
@@ -66,7 +66,7 @@ protected[model] trait TemplateComponent { self: Profile =>
byRepository(userName, repositoryName) && (this.milestoneId === milestoneId) byRepository(userName, repositoryName) && (this.milestoneId === milestoneId)
} }
trait CommitTemplate extends BasicTemplate { self: Table[_] => trait CommitTemplate extends BasicTemplate { self: Table[?] =>
val commitId = column[String]("COMMIT_ID") val commitId = column[String]("COMMIT_ID")
def byCommit(owner: String, repository: String, commitId: String) = def byCommit(owner: String, repository: String, commitId: String) =
@@ -76,7 +76,7 @@ protected[model] trait TemplateComponent { self: Profile =>
byRepository(userName, repositoryName) && (this.commitId === commitId) byRepository(userName, repositoryName) && (this.commitId === commitId)
} }
trait BranchTemplate extends BasicTemplate { self: Table[_] => trait BranchTemplate extends BasicTemplate { self: Table[?] =>
val branch = column[String]("BRANCH") val branch = column[String]("BRANCH")
def byBranch(owner: String, repository: String, branchName: String) = def byBranch(owner: String, repository: String, branchName: String) =
byRepository(owner, repository) && (branch === branchName.bind) byRepository(owner, repository) && (branch === branchName.bind)

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).mapTo[Collaborator]
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

@@ -21,7 +21,7 @@ trait IssueCommentComponent extends TemplateComponent { self: Profile =>
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) .mapTo[IssueComment]
def byPrimaryKey(commentId: Int) = this.commentId === commentId.bind def byPrimaryKey(commentId: Int) = this.commentId === commentId.bind
} }
@@ -75,7 +75,7 @@ trait CommitCommentComponent extends TemplateComponent { self: Profile =>
originalCommitId, originalCommitId,
originalOldLine, originalOldLine,
originalNewLine originalNewLine
).<>(CommitComment.tupled, CommitComment.unapply) ).mapTo[CommitComment]
def byPrimaryKey(commentId: Int) = this.commentId === commentId.bind def byPrimaryKey(commentId: Int) = this.commentId === commentId.bind
} }

View File

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

View File

@@ -5,6 +5,7 @@ import gitbucket.core.service.RepositoryService.RepositoryInfo
import gitbucket.core.util.StringUtil import gitbucket.core.util.StringUtil
import gitbucket.core.view.helpers import gitbucket.core.view.helpers
import org.scalatra.i18n.Messages import org.scalatra.i18n.Messages
import play.twirl.api.Html
trait CustomFieldComponent extends TemplateComponent { self: Profile => trait CustomFieldComponent extends TemplateComponent { self: Profile =>
import profile.api._ import profile.api._
@@ -15,11 +16,12 @@ trait CustomFieldComponent extends TemplateComponent { self: Profile =>
val fieldId = column[Int]("FIELD_ID", O AutoInc) val fieldId = column[Int]("FIELD_ID", O AutoInc)
val fieldName = column[String]("FIELD_NAME") val fieldName = column[String]("FIELD_NAME")
val fieldType = column[String]("FIELD_TYPE") val fieldType = column[String]("FIELD_TYPE")
val constraints = column[Option[String]]("CONSTRAINTS")
val enableForIssues = column[Boolean]("ENABLE_FOR_ISSUES") val enableForIssues = column[Boolean]("ENABLE_FOR_ISSUES")
val enableForPullRequests = column[Boolean]("ENABLE_FOR_PULL_REQUESTS") val enableForPullRequests = column[Boolean]("ENABLE_FOR_PULL_REQUESTS")
def * = def * =
(userName, repositoryName, fieldId, fieldName, fieldType, enableForIssues, enableForPullRequests) (userName, repositoryName, fieldId, fieldName, fieldType, constraints, enableForIssues, enableForPullRequests)
.<>(CustomField.tupled, CustomField.unapply) .mapTo[CustomField]
def byPrimaryKey(userName: String, repositoryName: String, fieldId: Int) = def byPrimaryKey(userName: String, repositoryName: String, fieldId: Int) =
(this.userName === userName.bind) && (this.repositoryName === repositoryName.bind) && (this.fieldId === fieldId.bind) (this.userName === userName.bind) && (this.repositoryName === repositoryName.bind) && (this.fieldId === fieldId.bind)
@@ -31,17 +33,28 @@ case class CustomField(
repositoryName: String, repositoryName: String,
fieldId: Int = 0, fieldId: Int = 0,
fieldName: String, fieldName: String,
fieldType: String, // long, double, string, or date fieldType: String, // long, double, string, date, or enum
constraints: Option[String],
enableForIssues: Boolean, enableForIssues: Boolean,
enableForPullRequests: Boolean enableForPullRequests: Boolean
) )
trait CustomFieldBehavior { trait CustomFieldBehavior {
def createHtml(repository: RepositoryInfo, fieldId: Int)(implicit conext: Context): String def createHtml(repository: RepositoryInfo, fieldId: Int, fieldName: String, constraints: Option[String])(implicit
def fieldHtml(repository: RepositoryInfo, issueId: Int, fieldId: Int, value: String, editable: Boolean)( context: Context
implicit context: Context
): String ): String
def validate(name: String, value: String, messages: Messages): Option[String] def fieldHtml(
repository: RepositoryInfo,
issueId: Int,
fieldId: Int,
fieldName: String,
constraints: Option[String],
value: String,
editable: Boolean
)(implicit
context: Context
): String
def validate(name: String, constraints: Option[String], value: String, messages: Messages): Option[String]
} }
object CustomFieldBehavior { object CustomFieldBehavior {
@@ -49,7 +62,7 @@ object CustomFieldBehavior {
if (value.isEmpty) None if (value.isEmpty) None
else { else {
CustomFieldBehavior(field.fieldType).flatMap { behavior => CustomFieldBehavior(field.fieldType).flatMap { behavior =>
behavior.validate(field.fieldName, value, messages) behavior.validate(field.fieldName, field.constraints, value, messages)
} }
} }
} }
@@ -60,12 +73,18 @@ object CustomFieldBehavior {
case "double" => Some(DoubleFieldBehavior) case "double" => Some(DoubleFieldBehavior)
case "string" => Some(StringFieldBehavior) case "string" => Some(StringFieldBehavior)
case "date" => Some(DateFieldBehavior) case "date" => Some(DateFieldBehavior)
case "enum" => Some(EnumFieldBehavior)
case _ => None case _ => None
} }
} }
case object LongFieldBehavior extends TextFieldBehavior { case object LongFieldBehavior extends TextFieldBehavior {
override def validate(name: String, value: String, messages: Messages): Option[String] = { override def validate(
name: String,
constraints: Option[String],
value: String,
messages: Messages
): Option[String] = {
try { try {
value.toLong value.toLong
None None
@@ -75,7 +94,12 @@ object CustomFieldBehavior {
} }
} }
case object DoubleFieldBehavior extends TextFieldBehavior { case object DoubleFieldBehavior extends TextFieldBehavior {
override def validate(name: String, value: String, messages: Messages): Option[String] = { override def validate(
name: String,
constraints: Option[String],
value: String,
messages: Messages
): Option[String] = {
try { try {
value.toDouble value.toDouble
None None
@@ -89,7 +113,12 @@ object CustomFieldBehavior {
private val pattern = "yyyy-MM-dd" private val pattern = "yyyy-MM-dd"
override protected val fieldType: String = "date" override protected val fieldType: String = "date"
override def validate(name: String, value: String, messages: Messages): Option[String] = { override def validate(
name: String,
constraints: Option[String],
value: String,
messages: Messages
): Option[String] = {
try { try {
new java.text.SimpleDateFormat(pattern).parse(value) new java.text.SimpleDateFormat(pattern).parse(value)
None None
@@ -100,10 +129,140 @@ object CustomFieldBehavior {
} }
} }
case object EnumFieldBehavior extends CustomFieldBehavior {
override def createHtml(repository: RepositoryInfo, fieldId: Int, fieldName: String, constraints: Option[String])(
implicit context: Context
): String = {
createPulldownHtml(repository, fieldId, fieldName, constraints, None, None)
}
override def fieldHtml(
repository: RepositoryInfo,
issueId: Int,
fieldId: Int,
fieldName: String,
constraints: Option[String],
value: String,
editable: Boolean
)(implicit context: Context): String = {
if (!editable) {
val sb = new StringBuilder
sb.append("""</div>""")
sb.append("""<div>""")
if (value == "") {
sb.append(s"""<span id="label-custom-field-$fieldId"><span class="muted small">No ${StringUtil.escapeHtml(
fieldName
)}</span></span>""")
} else {
sb.append(s"""<span id="label-custom-field-$fieldId"><span class="muted small">${StringUtil
.escapeHtml(value)}</span></span>""")
}
sb.toString()
} else {
createPulldownHtml(repository, fieldId, fieldName, constraints, Some(issueId), Some(value))
}
}
private def createPulldownHtml(
repository: RepositoryInfo,
fieldId: Int,
fieldName: String,
constraints: Option[String],
issueId: Option[Int],
value: Option[String]
)(implicit context: Context): String = {
val sb = new StringBuilder
sb.append("""<div class="pull-right">""")
sb.append(
gitbucket.core.helper.html
.dropdown("Edit", right = true, filter = (fieldName, s"Filter $fieldName")) {
val options = new StringBuilder()
options.append(
s"""<li><a href="javascript:void(0);" class="custom-field-option-$fieldId" data-value=""><i class="octicon octicon-x"></i> Clear ${StringUtil
.escapeHtml(fieldName)}</a></li>"""
)
constraints.foreach { x =>
x.split(",").map(_.trim).foreach { item =>
options.append(s"""<li>
| <a href="javascript:void(0);" class="custom-field-option-$fieldId" data-value="${StringUtil
.escapeHtml(item)}">
| ${gitbucket.core.helper.html.checkicon(value.contains(item))}
| ${StringUtil.escapeHtml(item)}
| </a>
|</li>
|""".stripMargin)
}
}
Html(options.toString())
}
.toString()
)
sb.append("""</div>""")
sb.append("""</div>""")
sb.append("""<div>""")
value match {
case None =>
sb.append(s"""<span id="label-custom-field-$fieldId"><span class="muted small">No ${StringUtil.escapeHtml(
fieldName
)}</span></span>""")
case Some(value) =>
sb.append(s"""<span id="label-custom-field-$fieldId"><span class="muted small">${StringUtil
.escapeHtml(value)}</span></span>""")
}
if (value.isEmpty || issueId.isEmpty) {
sb.append(s"""<input type="hidden" id="custom-field-$fieldId" name="custom-field-$fieldId" value=""/>""")
sb.append(s"""<script>
|$$('a.custom-field-option-$fieldId').click(function(){
| const value = $$(this).data('value');
| $$('a.custom-field-option-$fieldId i.octicon-check').removeClass('octicon-check');
| $$('#custom-field-$fieldId').val(value);
| if (value == '') {
| $$('#label-custom-field-$fieldId').html($$('<span class="muted small">').text('No ${StringUtil
.escapeHtml(fieldName)}'));
| } else {
| $$('#label-custom-field-$fieldId').html($$('<span class="muted small">').text(value));
| $$('a.custom-field-option-$fieldId[data-value=' + value + '] i').addClass('octicon-check');
| }
|});
|</script>""".stripMargin)
} else {
sb.append(s"""<script>
|$$('a.custom-field-option-$fieldId').click(function(){
| const value = $$(this).data('value');
| $$.post('${helpers.url(repository)}/issues/${issueId.get}/customfield/$fieldId',
| { value: value },
| function(data){
| $$('a.custom-field-option-$fieldId i.octicon-check').removeClass('octicon-check');
| if (value == '') {
| $$('#label-custom-field-$fieldId').html($$('<span class="muted small">').text('No ${StringUtil
.escapeHtml(fieldName)}'));
| } else {
| $$('#label-custom-field-$fieldId').html($$('<span class="muted small">').text(value));
| $$('a.custom-field-option-$fieldId[data-value=' + value + '] i').addClass('octicon-check');
| }
| }
| );
|});
|</script>
|""".stripMargin)
}
sb.toString()
}
override def validate(
name: String,
constraints: Option[String],
value: String,
messages: Messages
): Option[String] = None
}
trait TextFieldBehavior extends CustomFieldBehavior { trait TextFieldBehavior extends CustomFieldBehavior {
protected val fieldType = "text" protected val fieldType = "text"
def createHtml(repository: RepositoryInfo, fieldId: Int)(implicit context: Context): String = { override def createHtml(repository: RepositoryInfo, fieldId: Int, fieldName: String, constraints: Option[String])(
implicit context: Context
): String = {
val sb = new StringBuilder val sb = new StringBuilder
sb.append( sb.append(
s"""<input type="$fieldType" class="form-control input-sm" id="custom-field-$fieldId" name="custom-field-$fieldId" data-field-id="$fieldId" style="width: 120px;"/>""" s"""<input type="$fieldType" class="form-control input-sm" id="custom-field-$fieldId" name="custom-field-$fieldId" data-field-id="$fieldId" style="width: 120px;"/>"""
@@ -111,8 +270,7 @@ object CustomFieldBehavior {
sb.append(s"""<script> sb.append(s"""<script>
|$$('#custom-field-$fieldId').focusout(function(){ |$$('#custom-field-$fieldId').focusout(function(){
| const $$this = $$(this); | const $$this = $$(this);
| const fieldId = $$this.data('field-id'); | $$.post('${helpers.url(repository)}/issues/customfield_validation/$fieldId',
| $$.post('${helpers.url(repository)}/issues/customfield_validation/' + fieldId,
| { value: $$this.val() }, | { value: $$this.val() },
| function(data){ | function(data){
| if (data != '') { | if (data != '') {
@@ -128,14 +286,34 @@ object CustomFieldBehavior {
sb.toString() sb.toString()
} }
def fieldHtml(repository: RepositoryInfo, issueId: Int, fieldId: Int, value: String, editable: Boolean)( override def fieldHtml(
implicit context: Context repository: RepositoryInfo,
issueId: Int,
fieldId: Int,
fieldName: String,
constraints: Option[String],
value: String,
editable: Boolean
)(implicit
context: Context
): String = { ): String = {
val sb = new StringBuilder val sb = new StringBuilder
sb.append( if (value.nonEmpty) {
s"""<span id="custom-field-$fieldId-label" class="custom-field-label">${StringUtil sb.append(
.escapeHtml(value)}</span>""".stripMargin s"""<span id="custom-field-$fieldId-label" class="custom-field-label">${StringUtil
) .escapeHtml(value)}</span>"""
)
} else {
if (editable) {
sb.append(
s"""<span id="custom-field-$fieldId-label" class="custom-field-label"><i class="octicon octicon-pencil" style="cursor: pointer;"></i></span>"""
)
} else {
sb.append(
s"""<span id="custom-field-$fieldId-label" class="custom-field-label">N/A</span>"""
)
}
}
if (editable) { if (editable) {
sb.append( sb.append(
s"""<input type="$fieldType" id="custom-field-$fieldId-editor" class="form-control input-sm custom-field-editor" data-field-id="$fieldId" style="width: 120px; display: none;"/>""" s"""<input type="$fieldType" id="custom-field-$fieldId-editor" class="form-control input-sm custom-field-editor" data-field-id="$fieldId" style="width: 120px; display: none;"/>"""
@@ -149,19 +327,22 @@ object CustomFieldBehavior {
| |
|$$('#custom-field-$fieldId-editor').focusout(function(){ |$$('#custom-field-$fieldId-editor').focusout(function(){
| const $$this = $$(this); | const $$this = $$(this);
| const fieldId = $$this.data('field-id'); | $$.post('${helpers.url(repository)}/issues/customfield_validation/$fieldId',
| $$.post('${helpers.url(repository)}/issues/customfield_validation/' + fieldId,
| { value: $$this.val() }, | { value: $$this.val() },
| function(data){ | function(data){
| if (data != '') { | if (data != '') {
| $$('#custom-field-$fieldId-error').text(data); | $$('#custom-field-$fieldId-error').text(data);
| } else { | } else {
| $$('#custom-field-$fieldId-error').text(''); | $$('#custom-field-$fieldId-error').text('');
| $$.post('${helpers.url(repository)}/issues/$issueId/customfield/' + fieldId, | $$.post('${helpers.url(repository)}/issues/$issueId/customfield/$fieldId',
| { value: $$this.val() }, | { value: $$this.val() },
| function(data){ | function(data){
| $$this.hide(); | $$this.hide();
| $$this.prev().text(data).show(); | if (data == '') {
| $$this.prev().html('<i class="octicon octicon-pencil" style="cursor: pointer;">').show();
| } else {
| $$this.prev().text(data).show();
| }
| } | }
| ); | );
| } | }
@@ -186,6 +367,11 @@ object CustomFieldBehavior {
sb.toString() sb.toString()
} }
def validate(name: String, value: String, messages: Messages): Option[String] = None override def validate(
name: String,
constraints: Option[String],
value: String,
messages: Messages
): Option[String] = None
} }
} }

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).mapTo[DeployKey]
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).mapTo[GpgKey]
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).mapTo[GroupMember]
} }
} }

View File

@@ -47,7 +47,7 @@ trait IssueComponent extends TemplateComponent { self: Profile =>
registeredDate, registeredDate,
updatedDate, updatedDate,
pullRequest pullRequest
).<>(Issue.tupled, Issue.unapply) ).mapTo[Issue]
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

@@ -9,8 +9,7 @@ trait IssueAssigneeComponent extends TemplateComponent { self: Profile =>
class IssueAssignees(tag: Tag) extends Table[IssueAssignee](tag, "ISSUE_ASSIGNEE") with IssueTemplate { class IssueAssignees(tag: Tag) extends Table[IssueAssignee](tag, "ISSUE_ASSIGNEE") with IssueTemplate {
val assigneeUserName = column[String]("ASSIGNEE_USER_NAME") val assigneeUserName = column[String]("ASSIGNEE_USER_NAME")
def * = def * =
(userName, repositoryName, issueId, assigneeUserName) (userName, repositoryName, issueId, assigneeUserName).mapTo[IssueAssignee]
.<>(IssueAssignee.tupled, IssueAssignee.unapply)
def byPrimaryKey(owner: String, repository: String, issueId: Int, assigneeUserName: String) = { def byPrimaryKey(owner: String, repository: String, issueId: Int, assigneeUserName: String) = {
byIssue(owner, repository, issueId) && this.assigneeUserName === assigneeUserName.bind byIssue(owner, repository, issueId) && this.assigneeUserName === assigneeUserName.bind

View File

@@ -13,8 +13,7 @@ trait IssueCustomFieldComponent extends TemplateComponent { self: Profile =>
val fieldId = column[Int]("FIELD_ID", O.PrimaryKey) val fieldId = column[Int]("FIELD_ID", O.PrimaryKey)
val value = column[String]("VALUE") val value = column[String]("VALUE")
def * = def * =
(userName, repositoryName, issueId, fieldId, value) (userName, repositoryName, issueId, fieldId, value).mapTo[IssueCustomField]
.<>(IssueCustomField.tupled, IssueCustomField.unapply)
def byPrimaryKey(owner: String, repository: String, issueId: Int, fieldId: Int) = { def byPrimaryKey(owner: String, repository: String, issueId: Int, fieldId: Int) = {
this.userName === owner.bind && this.repositoryName === repository.bind && this.issueId === issueId.bind && this.fieldId === fieldId.bind this.userName === owner.bind && this.repositoryName === repository.bind && this.issueId === issueId.bind && this.fieldId === fieldId.bind

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).mapTo[IssueLabel]
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).mapTo[Label]
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).mapTo[Milestone]
.<>(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).mapTo[Priority]
.<>(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

@@ -1,16 +1,18 @@
package gitbucket.core.model package gitbucket.core.model
trait ProtectedBranchComponent extends TemplateComponent { self: Profile => trait ProtectedBranchComponent extends TemplateComponent { self: Profile =>
import profile.api._ import profile.api.*
import self._
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") // enforceAdmins
def * = (userName, repositoryName, branch, statusCheckAdmin).<>(ProtectedBranch.tupled, ProtectedBranch.unapply) val requiredStatusCheck = column[Boolean]("REQUIRED_STATUS_CHECK")
def byPrimaryKey(userName: String, repositoryName: String, branch: String) = val restrictions = column[Boolean]("RESTRICTIONS")
def * =
(userName, repositoryName, branch, statusCheckAdmin, requiredStatusCheck, restrictions).mapTo[ProtectedBranch]
def byPrimaryKey(userName: String, repositoryName: String, branch: String): Rep[Boolean] =
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]): Rep[Boolean] =
byBranch(userName, repositoryName, branch) byBranch(userName, repositoryName, branch)
} }
@@ -20,10 +22,29 @@ 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).mapTo[ProtectedBranchContext]
}
lazy val ProtectedBranchRestrictions = TableQuery[ProtectedBranchRestrictions]
class ProtectedBranchRestrictions(tag: Tag)
extends Table[ProtectedBranchRestriction](tag, "PROTECTED_BRANCH_RESTRICTION")
with BranchTemplate {
val allowedUser = column[String]("ALLOWED_USER")
def * = (userName, repositoryName, branch, allowedUser).mapTo[ProtectedBranchRestriction]
def byPrimaryKey(userName: String, repositoryName: String, branch: String, allowedUser: String): Rep[Boolean] =
this.userName === userName.bind && this.repositoryName === repositoryName.bind && this.branch === branch.bind && this.allowedUser === allowedUser.bind
} }
} }
case class ProtectedBranch(userName: String, repositoryName: String, branch: String, statusCheckAdmin: Boolean) case class ProtectedBranch(
userName: String,
repositoryName: String,
branch: String,
enforceAdmins: Boolean,
requiredStatusCheck: Boolean,
restrictions: Boolean
)
case class ProtectedBranchContext(userName: String, repositoryName: String, branch: String, context: String) case class ProtectedBranchContext(userName: String, repositoryName: String, branch: String, context: String)
case class ProtectedBranchRestriction(userName: String, repositoryName: String, branch: String, allowedUser: String)

View File

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

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