mirror of
https://github.com/gitbucket/gitbucket.git
synced 2025-10-29 09:36:16 +01:00
Compare commits
792 Commits
optimize-c
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6fe903afab | ||
|
|
0d94865633 | ||
|
|
2fbdead64b | ||
|
|
72a354931e | ||
|
|
cb8affcd0d | ||
|
|
a5a997eb40 | ||
|
|
b4220aab68 | ||
|
|
c8a4798f86 | ||
|
|
6b8e9e8892 | ||
|
|
9ab9363d0b | ||
|
|
1edb18a147 | ||
|
|
d8b4bf3033 | ||
|
|
6597c4490b | ||
|
|
daaf1696ad | ||
|
|
53a1ca7874 | ||
|
|
f045fa4c6a | ||
|
|
53a7c5adf8 | ||
|
|
b142eca9a5 | ||
|
|
ba753a373b | ||
|
|
95ceca75a4 | ||
|
|
f16cc117a9 | ||
|
|
af66f8f746 | ||
|
|
d9cc57e8e0 | ||
|
|
72b6dad3a2 | ||
|
|
18f396b4a2 | ||
|
|
9f3fde8de2 | ||
|
|
dfd6f80b63 | ||
|
|
119d91210c | ||
|
|
75ef30ee03 | ||
|
|
d1cf9dd600 | ||
|
|
9c9fea908c | ||
|
|
1145c4d0f6 | ||
|
|
d847fc6e0f | ||
|
|
bb9585f7a6 | ||
|
|
e91411fa45 | ||
|
|
adbc065a6f | ||
|
|
862283b729 | ||
|
|
217df7012c | ||
|
|
e672d41e77 | ||
|
|
d975700bd4 | ||
|
|
f65e41561a | ||
|
|
dab4f33ed9 | ||
|
|
5ff45ef5ae | ||
|
|
af7c622647 | ||
|
|
f7027e57df | ||
|
|
6a4719469d | ||
|
|
6ebc865ba5 | ||
|
|
0c1e8b932b | ||
|
|
fda67a32e2 | ||
|
|
14d7e9ee90 | ||
|
|
b7b7322cce | ||
|
|
5eb44398d0 | ||
|
|
be7bb255c3 | ||
|
|
cb9522d416 | ||
|
|
d80afb473b | ||
|
|
607d85c661 | ||
|
|
a5fab3bc96 | ||
|
|
eb403ada58 | ||
|
|
911c102f39 | ||
|
|
bf23e854f8 | ||
|
|
52427c0a1e | ||
|
|
d8e5ac585c | ||
|
|
2fbeef73b0 | ||
|
|
15e39572dd | ||
|
|
9eac4f42c5 | ||
|
|
01d18bb5c3 | ||
|
|
00258e9125 | ||
|
|
046b337337 | ||
|
|
46cc7b6fd3 | ||
|
|
59344b4f05 | ||
|
|
c4d8af02b2 | ||
|
|
a10bc3687a | ||
|
|
b0d21dee42 | ||
|
|
13ea0e7507 | ||
|
|
d66fdaede5 | ||
|
|
d6217d89eb | ||
|
|
c99ff1cf0f | ||
|
|
001b9ae2ae | ||
|
|
f63493f1c0 | ||
|
|
c9095722f8 | ||
|
|
b9d2efa582 | ||
|
|
9c2e09020a | ||
|
|
1ffcf8c1e9 | ||
|
|
0124091840 | ||
|
|
2a28a7b35b | ||
|
|
2a68ffc8dc | ||
|
|
6b47c49cdd | ||
|
|
b634967776 | ||
|
|
172bed760d | ||
|
|
1b7eb69083 | ||
|
|
185c01db99 | ||
|
|
ab548d8c25 | ||
|
|
983975620b | ||
|
|
b512b08256 | ||
|
|
a54fb4960f | ||
|
|
93de53d717 | ||
|
|
f262c0a9eb | ||
|
|
e5d15569df | ||
|
|
369b08eae3 | ||
|
|
8e6fcb022b | ||
|
|
456b1f6571 | ||
|
|
6e459ad225 | ||
|
|
cece4c1c7d | ||
|
|
42e7a9fa9f | ||
|
|
f9510aba8e | ||
|
|
8a7d719025 | ||
|
|
1293a21450 | ||
|
|
65dd597ab7 | ||
|
|
e145b5151e | ||
|
|
b9684c277b | ||
|
|
4accb77533 | ||
|
|
9eef961025 | ||
|
|
546b40cdd1 | ||
|
|
274a08c14c | ||
|
|
eed4b51189 | ||
|
|
5c2f84367b | ||
|
|
d5b625e43f | ||
|
|
27f9e3dec9 | ||
|
|
00ef4db9a7 | ||
|
|
bf4f814389 | ||
|
|
23e45afd7f | ||
|
|
bfb02eef62 | ||
|
|
c129aae73a | ||
|
|
a955856cef | ||
|
|
a43a3fa55c | ||
|
|
a6254ab955 | ||
|
|
b505c3dc12 | ||
|
|
9d69b9e980 | ||
|
|
44b2320644 | ||
|
|
8fb9643ea5 | ||
|
|
10ea988298 | ||
|
|
7896945519 | ||
|
|
210342d2bc | ||
|
|
fdacea858b | ||
|
|
6825028d37 | ||
|
|
2089882d41 | ||
|
|
8e1d938155 | ||
|
|
39eb4cef04 | ||
|
|
d4e3adafa6 | ||
|
|
a7b8326499 | ||
|
|
249f8738d3 | ||
|
|
fefe6ef74f | ||
|
|
9ca6cd1d90 | ||
|
|
bff7b7c460 | ||
|
|
cfff79758b | ||
|
|
ded8ceb2c6 | ||
|
|
c502ebfc16 | ||
|
|
d3268265cf | ||
|
|
5eaf59eebb | ||
|
|
d6d47aa977 | ||
|
|
dc052e05ce | ||
|
|
afb145ca7c | ||
|
|
a8beed33e0 | ||
|
|
488599dba5 | ||
|
|
ef0d08a917 | ||
|
|
9fa0d03c99 | ||
|
|
15b6c5952b | ||
|
|
cb75e9d312 | ||
|
|
d542ee3528 | ||
|
|
608a59cbfd | ||
|
|
768e3a5c91 | ||
|
|
f1fc794c0c | ||
|
|
4cf924bee0 | ||
|
|
8164efc720 | ||
|
|
580a627d9d | ||
|
|
1701916209 | ||
|
|
811b2bff70 | ||
|
|
9de9dd8940 | ||
|
|
572f83327f | ||
|
|
2afb37823b | ||
|
|
edc9720a88 | ||
|
|
defc0fa041 | ||
|
|
c14b3c5576 | ||
|
|
10fc04cbc9 | ||
|
|
67563a8805 | ||
|
|
743bdab79b | ||
|
|
a5a2e4732d | ||
|
|
3a0cd5df62 | ||
|
|
ad9a0afc9b | ||
|
|
d2fc7a0642 | ||
|
|
b1d4a18c9b | ||
|
|
fdfd8ec9b2 | ||
|
|
396156c4e3 | ||
|
|
8168580d60 | ||
|
|
2abdd233e7 | ||
|
|
ef95ce99d2 | ||
|
|
3a6b2f6f4e | ||
|
|
92304ac8c6 | ||
|
|
a2242a3cb7 | ||
|
|
64e8167fcb | ||
|
|
06b93293a6 | ||
|
|
3dcc0aee3c | ||
|
|
c009a39dd7 | ||
|
|
b27e8ebb7e | ||
|
|
a690d43491 | ||
|
|
86bfb68a0c | ||
|
|
9469801d3d | ||
|
|
757a8399c1 | ||
|
|
ed00e613c3 | ||
|
|
6e341116c1 | ||
|
|
9ccc2d0f97 | ||
|
|
72742306a0 | ||
|
|
47c6d61661 | ||
|
|
cfc444bcd2 | ||
|
|
a1f65258ea | ||
|
|
5e3b97cf85 | ||
|
|
209e1967d6 | ||
|
|
4437a4e7a6 | ||
|
|
e4d92bb494 | ||
|
|
d942c8f48a | ||
|
|
3a798e152f | ||
|
|
91b862970f | ||
|
|
2d199e22e7 | ||
|
|
757da408d1 | ||
|
|
309d6e8b57 | ||
|
|
ec0395a7f3 | ||
|
|
7cb4958ca0 | ||
|
|
2d1c917a2c | ||
|
|
27dd5120dd | ||
|
|
9e0f8992c5 | ||
|
|
5f87a28da6 | ||
|
|
25d5d5eee5 | ||
|
|
ec9472b7cc | ||
|
|
b967fb93a7 | ||
|
|
9d1bf3035b | ||
|
|
d6cedc2171 | ||
|
|
8d8c78966a | ||
|
|
cbe1c1c9f6 | ||
|
|
bf946960a7 | ||
|
|
9677735542 | ||
|
|
e06c8fe5da | ||
|
|
d4ee6c9063 | ||
|
|
1d0f079bd2 | ||
|
|
7cc6972d83 | ||
|
|
177da92b39 | ||
|
|
e1f433573b | ||
|
|
cd958d7681 | ||
|
|
9c8e77f472 | ||
|
|
bf7d3a8f0b | ||
|
|
934e17666d | ||
|
|
b20c4b3d7d | ||
|
|
7c4e8b54d0 | ||
|
|
1e3794674b | ||
|
|
5d5706451d | ||
|
|
76e8d01846 | ||
|
|
75e2883f61 | ||
|
|
7e7cc1d4c7 | ||
|
|
d7623e8b7a | ||
|
|
7dd1470cd4 | ||
|
|
9fb8d6fc66 | ||
|
|
4f1869817c | ||
|
|
6be269c388 | ||
|
|
af857853cb | ||
|
|
1a664c2b6a | ||
|
|
1feb33fc19 | ||
|
|
4fc1d9c3b6 | ||
|
|
7eb77908d4 | ||
|
|
54f9d01c42 | ||
|
|
08154af7b1 | ||
|
|
e7ab376a34 | ||
|
|
a680398c54 | ||
|
|
6acf1e68ca | ||
|
|
fc35e7b83d | ||
|
|
1ae6fc7e9e | ||
|
|
884f63e6f4 | ||
|
|
4d3e34af8b | ||
|
|
54426bb456 | ||
|
|
c86b72bf6b | ||
|
|
e6a5911a39 | ||
|
|
6ea77fa73e | ||
|
|
32d0b94a7a | ||
|
|
4f770adb35 | ||
|
|
361f92a08d | ||
|
|
c2068f58e7 | ||
|
|
67dd604469 | ||
|
|
d1a2c23cf3 | ||
|
|
262500508c | ||
|
|
f1360f44c6 | ||
|
|
1c818f890a | ||
|
|
16f146b660 | ||
|
|
6166eaf0c7 | ||
|
|
ad4312cedb | ||
|
|
15083a5aac | ||
|
|
9ae420c553 | ||
|
|
4115ea4ab6 | ||
|
|
024ac313ae | ||
|
|
598f289311 | ||
|
|
447288db9d | ||
|
|
2b8c2a5c06 | ||
|
|
6fd3a73268 | ||
|
|
4536e42949 | ||
|
|
fc575388f1 | ||
|
|
1044d1cc32 | ||
|
|
253eabf2f2 | ||
|
|
8219d57b92 | ||
|
|
89381d3314 | ||
|
|
2e1037e107 | ||
|
|
0a77c71278 | ||
|
|
275101d11b | ||
|
|
bfd7f3b2bc | ||
|
|
21fcedf000 | ||
|
|
d963070f73 | ||
|
|
8174c89f9e | ||
|
|
5bdc74f0a6 | ||
|
|
b259386b67 | ||
|
|
984b52e7ec | ||
|
|
d36ef805f6 | ||
|
|
02bdbd281b | ||
|
|
b3cca9ea91 | ||
|
|
7409c08122 | ||
|
|
339b54cd4b | ||
|
|
1bbdf4917b | ||
|
|
465ed988a9 | ||
|
|
d5d7fe47d5 | ||
|
|
81d14dfaf2 | ||
|
|
302da30746 | ||
|
|
e9110aac80 | ||
|
|
6d104bd585 | ||
|
|
7c47462de8 | ||
|
|
cc8b83cbc5 | ||
|
|
07decd00a0 | ||
|
|
7c3e82f4dd | ||
|
|
95c31dd7b7 | ||
|
|
5ea905e3a2 | ||
|
|
e40d1f42c7 | ||
|
|
aa00351606 | ||
|
|
6311a1f146 | ||
|
|
1517e1f580 | ||
|
|
833f3584c2 | ||
|
|
cdc67bffcb | ||
|
|
52794aa9ea | ||
|
|
9ea3670a56 | ||
|
|
652ec3e029 | ||
|
|
b543bae958 | ||
|
|
4f574cdbcd | ||
|
|
29fc2a666b | ||
|
|
4498c016a4 | ||
|
|
31a1d46175 | ||
|
|
e3904ebdfe | ||
|
|
6e5ffdf658 | ||
|
|
5d0531f00d | ||
|
|
01ea533b97 | ||
|
|
86fc492668 | ||
|
|
3a78356019 | ||
|
|
44f7931ae6 | ||
|
|
7094f99a85 | ||
|
|
550c4a6e60 | ||
|
|
64aeb422c8 | ||
|
|
c2265dc44c | ||
|
|
507085cd56 | ||
|
|
36ef7ddf94 | ||
|
|
be1fbc8594 | ||
|
|
d73eacfa5d | ||
|
|
5d495cfa12 | ||
|
|
acaadff6cb | ||
|
|
e22371e4a5 | ||
|
|
81c426b112 | ||
|
|
1481872ddb | ||
|
|
523da8afb9 | ||
|
|
828dcb7173 | ||
|
|
eaf7bfb78d | ||
|
|
cbcf5ce4b6 | ||
|
|
36dce286b5 | ||
|
|
8ffe75786e | ||
|
|
5d63bc71aa | ||
|
|
37f8f7edda | ||
|
|
fd1c85afb2 | ||
|
|
c08bb6e89f | ||
|
|
d25889f6d2 | ||
|
|
dabddf60b1 | ||
|
|
c7ade7ec4d | ||
|
|
9caa73a585 | ||
|
|
0ee849c73d | ||
|
|
7883d8fd1e | ||
|
|
783ddfffa3 | ||
|
|
24b7cade49 | ||
|
|
51554d4325 | ||
|
|
90bcbd212b | ||
|
|
4ca3816522 | ||
|
|
fc4819cb29 | ||
|
|
5291df8e03 | ||
|
|
5afb0094f6 | ||
|
|
e76813cbee | ||
|
|
bc6398ca3b | ||
|
|
3d5ca44d66 | ||
|
|
8cd7068131 | ||
|
|
0db23b7f4a | ||
|
|
66d9ce328d | ||
|
|
36de0b3097 | ||
|
|
4f3cd26cf4 | ||
|
|
561e1bfec7 | ||
|
|
de64206a82 | ||
|
|
65ddffde89 | ||
|
|
1bc6ddc1a3 | ||
|
|
a404bd0776 | ||
|
|
ccbdd383ae | ||
|
|
acb846e885 | ||
|
|
fa23b4c89e | ||
|
|
a70e1f53b5 | ||
|
|
176deb4930 | ||
|
|
6e26d090ed | ||
|
|
070f74e7dc | ||
|
|
bcd78b3e5b | ||
|
|
be8f45ce49 | ||
|
|
baa96408a8 | ||
|
|
d2a7548f73 | ||
|
|
31e3fc64fc | ||
|
|
01a9883847 | ||
|
|
3cf2bea01e | ||
|
|
7caf11ae83 | ||
|
|
b22bc6fef0 | ||
|
|
88533c5807 | ||
|
|
53d955f198 | ||
|
|
724550ec5f | ||
|
|
1a63eff8f9 | ||
|
|
cf1b245229 | ||
|
|
c54a76c9b4 | ||
|
|
1a7213e2f0 | ||
|
|
a386cda024 | ||
|
|
f414bb4c79 | ||
|
|
6a51c7414a | ||
|
|
9718a67a74 | ||
|
|
179f86c904 | ||
|
|
e6ae6fc17d | ||
|
|
1f42b52cfd | ||
|
|
cdff342e3d | ||
|
|
daa8b6acf2 | ||
|
|
2ae72c6db4 | ||
|
|
9e3204d546 | ||
|
|
59e560b8e1 | ||
|
|
186269f8ff | ||
|
|
e441c40429 | ||
|
|
e1fa85848c | ||
|
|
8d66348634 | ||
|
|
f16b7d2c9b | ||
|
|
0ae8cc2820 | ||
|
|
ca25e7fe90 | ||
|
|
2692e29716 | ||
|
|
b71ccfbcc5 | ||
|
|
659a157cb7 | ||
|
|
f22fab32cc | ||
|
|
631e418733 | ||
|
|
0f57da14e4 | ||
|
|
424790e686 | ||
|
|
5dc43a7f75 | ||
|
|
debb131623 | ||
|
|
e3e21e9590 | ||
|
|
42fa7ea74d | ||
|
|
8ada3dde04 | ||
|
|
d43a666dfc | ||
|
|
5b266229c3 | ||
|
|
d8b0062f2b | ||
|
|
7f0859c0a3 | ||
|
|
38c7fbf589 | ||
|
|
41335964b7 | ||
|
|
c5464b2099 | ||
|
|
dc49b0dace | ||
|
|
365f30b76b | ||
|
|
ff1bc0fbca | ||
|
|
41d55372b5 | ||
|
|
ba8e5fe3cb | ||
|
|
6e692f70b7 | ||
|
|
aab979b78b | ||
|
|
9b7856464a | ||
|
|
903008b417 | ||
|
|
515cf86e4f | ||
|
|
c0b9eb8789 | ||
|
|
fefbf92f83 | ||
|
|
006fae36c9 | ||
|
|
281f7f37d8 | ||
|
|
36c6dd979f | ||
|
|
9f44015003 | ||
|
|
e719533ed9 | ||
|
|
773221d65b | ||
|
|
6beacb6af3 | ||
|
|
f11b92d391 | ||
|
|
def222d035 | ||
|
|
5dee7a9057 | ||
|
|
c20cc1271c | ||
|
|
843d429cb2 | ||
|
|
372e17ea2b | ||
|
|
5490e82411 | ||
|
|
d30a5d2f92 | ||
|
|
ef69763749 | ||
|
|
59d1250e36 | ||
|
|
33bf0b7b31 | ||
|
|
884cd498ce | ||
|
|
e0b021cb3e | ||
|
|
57edf101fa | ||
|
|
a2bf0d86d8 | ||
|
|
32e2ea5061 | ||
|
|
e28c0592f6 | ||
|
|
60627060d5 | ||
|
|
cea4d7e15f | ||
|
|
ca1670b21a | ||
|
|
c9c72faaf1 | ||
|
|
ba42538775 | ||
|
|
39141d8996 | ||
|
|
e3dd099bbb | ||
|
|
6b37d1027f | ||
|
|
b521f43c84 | ||
|
|
7c5a9df759 | ||
|
|
04762a3e53 | ||
|
|
d2ba2df2ba | ||
|
|
0e7f34f1d7 | ||
|
|
d576bbfaed | ||
|
|
2bfdca6992 | ||
|
|
d18fdb6399 | ||
|
|
fe02605544 | ||
|
|
f86ae20791 | ||
|
|
df69f88186 | ||
|
|
8d1323f354 | ||
|
|
2f598b618b | ||
|
|
baf0b0b92c | ||
|
|
27a75250a6 | ||
|
|
15f60402a5 | ||
|
|
41c6fc90b3 | ||
|
|
34356b04a8 | ||
|
|
2ca02b6539 | ||
|
|
cd0c71dffb | ||
|
|
a59120fe19 | ||
|
|
fdc35f48ed | ||
|
|
bae9b7ddc3 | ||
|
|
3dd9b7e587 | ||
|
|
44c905bdab | ||
|
|
5214040257 | ||
|
|
7ad9f901dd | ||
|
|
f472d52954 | ||
|
|
1e752af41b | ||
|
|
3ba46c3fc6 | ||
|
|
bf83da476f | ||
|
|
6b8c4cf8d0 | ||
|
|
445329c07a | ||
|
|
8f370e19c6 | ||
|
|
736dbcfb58 | ||
|
|
c1cb7f87e0 | ||
|
|
3c14fcefc9 | ||
|
|
831badf8db | ||
|
|
5f8a6e8d24 | ||
|
|
a3981493f7 | ||
|
|
6919cf5d4d | ||
|
|
f6d1e6bdd6 | ||
|
|
a13ff89acd | ||
|
|
cd5c76279a | ||
|
|
debff5e4b8 | ||
|
|
433e207ec5 | ||
|
|
3775f6a907 | ||
|
|
10d611c0eb | ||
|
|
963bc4d672 | ||
|
|
e68a21ee30 | ||
|
|
d5c083b70f | ||
|
|
2deb9cf417 | ||
|
|
fca0cfcdc7 | ||
|
|
1466e1bdb3 | ||
|
|
dd48bc443a | ||
|
|
f455738e5f | ||
|
|
85193803cd | ||
|
|
4e90a6074a | ||
|
|
ca94fa5184 | ||
|
|
f14a7c996f | ||
|
|
989d22f4d8 | ||
|
|
400a812343 | ||
|
|
97284f1ced | ||
|
|
5e6a0d7e16 | ||
|
|
599e11245f | ||
|
|
538d714c96 | ||
|
|
953915ba2a | ||
|
|
1a2f5da055 | ||
|
|
749a469d37 | ||
|
|
c7d084321a | ||
|
|
00a61cd6cf | ||
|
|
d9c6c13c62 | ||
|
|
5260c5e889 | ||
|
|
1700f96c62 | ||
|
|
5a0f9f8bbb | ||
|
|
8fa22b4de2 | ||
|
|
d17cae16fd | ||
|
|
c4c48962cf | ||
|
|
4140e92f0b | ||
|
|
887e560a1b | ||
|
|
e2d70181e8 | ||
|
|
148c453dbc | ||
|
|
f6ee9d311d | ||
|
|
35209e43bb | ||
|
|
4a3ecf063d | ||
|
|
4c79101624 | ||
|
|
921b01661b | ||
|
|
c63301d8e6 | ||
|
|
c9ed9d2237 | ||
|
|
ca55cbe456 | ||
|
|
d4828613ee | ||
|
|
a0be02ce2f | ||
|
|
9b8016a4d5 | ||
|
|
8fdd3bfd21 | ||
|
|
695a061e3c | ||
|
|
bd50d9218e | ||
|
|
d8f13bc1ce | ||
|
|
ed84d1a3c9 | ||
|
|
3c765d879c | ||
|
|
4c76b6dd96 | ||
|
|
7e66917993 | ||
|
|
eb0f985399 | ||
|
|
3a2908c3a3 | ||
|
|
f13c10859f | ||
|
|
8e8a314c91 | ||
|
|
dad0478b87 | ||
|
|
240b34016d | ||
|
|
2c164d630c | ||
|
|
3d12a9038f | ||
|
|
71fc02b5cd | ||
|
|
74caaa3d94 | ||
|
|
e024c12521 | ||
|
|
1d0c364947 | ||
|
|
88e59405c5 | ||
|
|
8160c93c15 | ||
|
|
3c8113d607 | ||
|
|
8e2f421e76 | ||
|
|
56df833b4a | ||
|
|
119d7d0be0 | ||
|
|
d4d2ca19a1 | ||
|
|
4ce5597d67 | ||
|
|
17888327b3 | ||
|
|
997def54ab | ||
|
|
a407e75459 | ||
|
|
cece53aad9 | ||
|
|
a2d63bc5f8 | ||
|
|
0c81c63ab7 | ||
|
|
3e8f1eee22 | ||
|
|
a91d1def45 | ||
|
|
032e6d1c57 | ||
|
|
93eb133cba | ||
|
|
b7b78842da | ||
|
|
8100ccaf5f | ||
|
|
936e1c0e96 | ||
|
|
1a7274e475 | ||
|
|
ac7b83b6ed | ||
|
|
e298279032 | ||
|
|
f7e58c28c6 | ||
|
|
18f3bc4056 | ||
|
|
4638f82889 | ||
|
|
4396b6eab5 | ||
|
|
594ae2bb7e | ||
|
|
429cf54bd4 | ||
|
|
274357abc4 | ||
|
|
0e21247755 | ||
|
|
37f2868ff3 | ||
|
|
6a85e25a62 | ||
|
|
a91b1c7e79 | ||
|
|
bfd9ecd130 | ||
|
|
ec888e94fd | ||
|
|
a19c80bef2 | ||
|
|
7b9ade2698 | ||
|
|
d03f28eeb9 | ||
|
|
288dd788bc | ||
|
|
2069a5a931 | ||
|
|
8a434cbd15 | ||
|
|
faafe49848 | ||
|
|
17a72292ce | ||
|
|
9ae09f1801 | ||
|
|
abbba17e4b | ||
|
|
479d5da17e | ||
|
|
dec7890d04 | ||
|
|
61910a6667 | ||
|
|
ac2119ac3b | ||
|
|
8c71cd7369 | ||
|
|
ec8b6ff18f | ||
|
|
e214804d57 | ||
|
|
39448f2e3c | ||
|
|
79dc6fc247 | ||
|
|
a800f305f2 | ||
|
|
67e0fb6b3f | ||
|
|
e401d30159 | ||
|
|
504e651828 | ||
|
|
7a8da2f074 | ||
|
|
1e47e96634 | ||
|
|
69502480b4 | ||
|
|
5833e3fcca | ||
|
|
4e47ffb1d2 | ||
|
|
3056333a7c | ||
|
|
ad0cd7f625 | ||
|
|
dedaa263ce | ||
|
|
bccf729102 | ||
|
|
a244c61e56 | ||
|
|
37594935f0 | ||
|
|
e521c2158b | ||
|
|
b1c8a8c76e | ||
|
|
8d92f210f0 | ||
|
|
287281923c | ||
|
|
6f18135574 | ||
|
|
58cf9bec3b | ||
|
|
b7a45e9901 | ||
|
|
f5585b39c6 | ||
|
|
9c3ef37274 | ||
|
|
e904c0b689 | ||
|
|
237f97f069 | ||
|
|
1eb2a04090 | ||
|
|
cda6106858 | ||
|
|
8c4ce5e5f4 | ||
|
|
b5ee6431c4 | ||
|
|
bd06e6d4dc | ||
|
|
3b607e74ed | ||
|
|
dc16474ed3 | ||
|
|
dc0f088be0 | ||
|
|
2718e10044 | ||
|
|
4213dcb8a2 | ||
|
|
39afb31200 | ||
|
|
8e1ce1c96a | ||
|
|
fdfd8293d6 | ||
|
|
b7d3be6a14 | ||
|
|
bb5c809749 | ||
|
|
a2cbe7cbf5 | ||
|
|
b1fb09ac99 | ||
|
|
201ae7e7db | ||
|
|
2978decb84 | ||
|
|
5fbbd4d5f3 | ||
|
|
4abd363f62 | ||
|
|
8288db60a9 | ||
|
|
6cdf679571 | ||
|
|
51179acc12 | ||
|
|
1ff27d3e17 | ||
|
|
1e9bce3d5a | ||
|
|
8811ea2b58 | ||
|
|
be7cdd0a28 | ||
|
|
611a05aa48 | ||
|
|
9f95a757a2 | ||
|
|
58b577453c | ||
|
|
78acfd87e8 | ||
|
|
bf9cb26164 | ||
|
|
68a99ada0b | ||
|
|
1d841ce171 | ||
|
|
ccfdbfd276 | ||
|
|
70d584d56d | ||
|
|
a49ffb07be | ||
|
|
baa9caf010 | ||
|
|
22025c875f | ||
|
|
3806995a50 | ||
|
|
94d2650491 | ||
|
|
844f24afa4 | ||
|
|
083396a8e4 | ||
|
|
e02769056b | ||
|
|
024f8e8d80 | ||
|
|
3b4a7c3c47 | ||
|
|
d9838d9cba | ||
|
|
b3ca4468cd | ||
|
|
452e41603a | ||
|
|
b41de4a770 | ||
|
|
3423d2f2f3 | ||
|
|
9269acc64d | ||
|
|
18b5f20f1c | ||
|
|
68d592a8ff | ||
|
|
ee18d96f98 | ||
|
|
6d3687cbdf | ||
|
|
1ef1a2983b | ||
|
|
47850fe0fa | ||
|
|
055a37cac0 | ||
|
|
333deb4756 | ||
|
|
34cde4b09a | ||
|
|
5091b4838c | ||
|
|
2e83289061 | ||
|
|
e11f651002 | ||
|
|
be684a567d | ||
|
|
97e552b10f | ||
|
|
5bb8046c32 | ||
|
|
e7192655f7 | ||
|
|
19ba09740c | ||
|
|
d169777722 | ||
|
|
ff8a5f6b77 | ||
|
|
ec953df156 | ||
|
|
d6a191d95b | ||
|
|
aba428bba1 | ||
|
|
6ab37fd596 | ||
|
|
73fc70f55b | ||
|
|
aad18b7a50 | ||
|
|
cc278be5cd | ||
|
|
d0f4f82a0f | ||
|
|
1dcbf386b1 | ||
|
|
414afd285c | ||
|
|
35b645d8b5 | ||
|
|
b3cba53866 | ||
|
|
a4773bb3ca | ||
|
|
863d8a4af5 | ||
|
|
3fccd7b53c | ||
|
|
dd2760eaf7 | ||
|
|
824bafa739 | ||
|
|
60cdaec05f | ||
|
|
c204a435b3 | ||
|
|
37accd92d6 | ||
|
|
01fd0ee1f0 | ||
|
|
fab1c74473 | ||
|
|
0d8fcfd28d | ||
|
|
b91a7c32a6 | ||
|
|
e7a6f0930b |
8
.git-blame-ignore-revs
Normal file
8
.git-blame-ignore-revs
Normal 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
1
.github/CODEOWNERS
vendored
@@ -2,3 +2,4 @@
|
||||
|
||||
build.sbt @xuwei-k
|
||||
project/* @xuwei-k
|
||||
.github/workflows/* @xuwei-k
|
||||
|
||||
18
.github/ISSUE_TEMPLATE.md
vendored
18
.github/ISSUE_TEMPLATE.md
vendored
@@ -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
1
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@@ -0,0 +1 @@
|
||||
blank_issues_enabled: false
|
||||
41
.github/ISSUE_TEMPLATE/issue_template.yml
vendored
Normal file
41
.github/ISSUE_TEMPLATE/issue_template.yml
vendored
Normal 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
|
||||
17
.github/workflows/build.yml
vendored
17
.github/workflows/build.yml
vendored
@@ -7,12 +7,13 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
java: [8, 11, 17]
|
||||
java: [17, 25]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v5
|
||||
- name: Cache
|
||||
uses: actions/cache@v2.1.6
|
||||
uses: actions/cache@v4
|
||||
env:
|
||||
cache-name: cache-sbt-libs
|
||||
with:
|
||||
@@ -22,18 +23,20 @@ jobs:
|
||||
~/.cache/coursier/v1
|
||||
key: build-${{ env.cache-name }}-${{ hashFiles('build.sbt') }}
|
||||
- name: Set up JDK
|
||||
uses: actions/setup-java@v2
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: ${{ matrix.java }}
|
||||
distribution: adopt
|
||||
- name: Setup sbt launcher
|
||||
uses: sbt/setup-sbt@v1
|
||||
- name: Run tests
|
||||
run: sbt scalafmtSbtCheck scalafmtCheck test:scalafmtCheck test
|
||||
run: sbt scalafmtSbtCheck scalafmtCheckAll test
|
||||
- name: Scala 3
|
||||
run: sbt '++ 3.0.1!' update # TODO
|
||||
run: sbt '++ 3.x' update # TODO
|
||||
- name: Build executable
|
||||
run: sbt executable
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v2
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: gitbucket-java${{ matrix.java }}-${{ github.sha }}
|
||||
path: ./target/executable/gitbucket.*
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -2,6 +2,9 @@
|
||||
*.log
|
||||
.ensime
|
||||
.ensime_cache
|
||||
.DS_Store
|
||||
.java-version
|
||||
.tmp
|
||||
|
||||
# sbt specific
|
||||
dist/*
|
||||
|
||||
@@ -3,5 +3,6 @@ updates.limit = 3
|
||||
updates.includeScala = true
|
||||
|
||||
updates.pin = [
|
||||
{ groupId = "org.eclipse.jetty", version = "9." }
|
||||
{ groupId = "org.eclipse.jetty", version = "10." }
|
||||
{ groupId = "org.mariadb.jdbc", version = "2." }
|
||||
]
|
||||
|
||||
@@ -1,12 +1,24 @@
|
||||
version = "1.5.1"
|
||||
version = "3.10.1"
|
||||
project.git = true
|
||||
|
||||
maxColumn = 120
|
||||
docstrings = JavaDoc
|
||||
docstrings.style = keep
|
||||
|
||||
align.tokens = ["%", "%%", {code = "=>", owner = "Case"}]
|
||||
align.openParenCallSite = false
|
||||
align.openParenDefnSite = false
|
||||
continuationIndent.callSite = 2
|
||||
continuationIndent.defnSite = 2
|
||||
danglingParentheses = true
|
||||
danglingParentheses.preset = true
|
||||
runner.dialect = scala213source3
|
||||
rewrite.trailingCommas.style = keep
|
||||
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
|
||||
|
||||
119
CHANGELOG.md
119
CHANGELOG.md
@@ -1,32 +1,137 @@
|
||||
# Changelog
|
||||
All changes to the project will be documented in this file.
|
||||
|
||||
### 4.36.2 - 16 Aug 2021
|
||||
## 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
|
||||
- Fix several issues around multiple assignees in issues and pull requests
|
||||
- Fix IllegalStateException when returning unknown avatar image
|
||||
|
||||
## 4.38.2 - 20 Sep 2022
|
||||
- Resurrect assignee icons on the issue list
|
||||
|
||||
## 4.38.1 - 10 Sep 2022
|
||||
- Fix comment diff in Chrome 105
|
||||
- Fix Markdown table CSS
|
||||
- Fix HTML rendering of multiple asignees
|
||||
|
||||
## 4.38.0 - 3 Sep 2022
|
||||
- Support multiple assignees for Issues and Pull requests
|
||||
- Custom fields for issues and pull requests
|
||||
- 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
|
||||
|
||||
## 4.37.2 - 16 Jan 2022
|
||||
- Fixed a security issue reported by [Positive Technologies](https://www.ptsecurity.com/ww-en/). Great thanks for their detailed report and close support!
|
||||
|
||||
## 4.37.1 - 14 Dec 2021
|
||||
- Update gist-plugin and notification-plugin
|
||||
- Fix SSHCommand extension point for apache-sshd 2.x
|
||||
|
||||
## 4.37.0 - 11 Dec 2021
|
||||
- Enhance Git Reference APIs
|
||||
- Add milestone data to issue list API
|
||||
- Support "all" in issue list API
|
||||
- Support EDDSA in signed commit verification
|
||||
- Support custom SSH url
|
||||
- Relax max passward length limitation
|
||||
- Relax max webhook url length limitation
|
||||
|
||||
## 4.36.2 - 16 Aug 2021
|
||||
- Escape user name in avatar image tag
|
||||
|
||||
### 4.36.1 - 22 Jul 2021
|
||||
## 4.36.1 - 22 Jul 2021
|
||||
- Bump gitbucket-gist-plugin to 4.21.0
|
||||
|
||||
### 4.36.0 - 17 Jul 2021
|
||||
## 4.36.0 - 17 Jul 2021
|
||||
- Tag selector in the repository viewer
|
||||
- Link issues/pull requests of other repositories
|
||||
- Files and lines can be linked in the diff view
|
||||
- Option to disable XSS protection
|
||||
|
||||
### 4.35.3 - 14 Jan 2021
|
||||
## 4.35.3 - 14 Jan 2021
|
||||
- Fix a bug that Wiki page cannot be deleted
|
||||
- Fix a deployment issue on Tomcat
|
||||
|
||||
### 4.35.2 - 30 Dec 2020
|
||||
## 4.35.2 - 30 Dec 2020
|
||||
- Upgrade gitbucket-notifications-plugin to 1.10.0
|
||||
- Upgrade oauth2-oidc-sdk to 8.29.1 to solve dependency issue
|
||||
|
||||
### 4.35.1 - 29 Dec 2020
|
||||
## 4.35.1 - 29 Dec 2020
|
||||
- Fix database migration issue which happens if webhook is configured
|
||||
- Call push webhook when pull request is merged
|
||||
- Show commit status at commits tab of pull request
|
||||
|
||||
### 4.35.0 - 25 Dec 2020
|
||||
## 4.35.0 - 25 Dec 2020
|
||||
- Editor and source viewer color theme
|
||||
- Auto completion for issues and pull requests
|
||||
- Upload image from clipboard
|
||||
|
||||
47
README.md
47
README.md
@@ -1,4 +1,4 @@
|
||||
GitBucket [](https://gitter.im/gitbucket/gitbucket) [](https://github.com/gitbucket/gitbucket/actions?query=workflow%3Abuild+branch%3Amaster) [](https://maven-badges.herokuapp.com/maven-central/io.github.gitbucket/gitbucket_2.13) [](https://github.com/gitbucket/gitbucket/blob/master/LICENSE)
|
||||
GitBucket [](https://gitter.im/gitbucket/gitbucket) [](https://github.com/gitbucket/gitbucket/actions/workflows/build.yml) [](https://index.scala-lang.org/gitbucket/gitbucket/gitbucket) [](https://github.com/gitbucket/gitbucket/blob/master/LICENSE)
|
||||
=========
|
||||
|
||||
GitBucket is a Git web platform powered by Scala offering:
|
||||
@@ -10,8 +10,6 @@ GitBucket is a Git web platform powered by Scala offering:
|
||||
|
||||

|
||||
|
||||
You can try an [online demo](https://gitbucket.herokuapp.com/) *(ID: root / Pass: root)* of GitBucket, and also get the latest information at [GitBucket News](https://gitbucket.github.io/gitbucket-news/).
|
||||
|
||||
Features
|
||||
--------
|
||||
The current version of GitBucket provides many features such as:
|
||||
@@ -26,12 +24,12 @@ The current version of GitBucket provides many features such as:
|
||||
|
||||
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`.
|
||||
2. Go to `http://[hostname]:8080/` and log in with ID: **root** / Pass: **root**.
|
||||
|
||||
You can also deploy `gitbucket.war` to a servlet container which supports Servlet 3.0 (like Jetty, Tomcat, JBoss, etc)
|
||||
You can also deploy `gitbucket.war` to a servlet container which supports Servlet 3.0 (like Jetty, Tomcat, JBoss, etc). Note that GitBucket doesn't support Jakarta EE yet.
|
||||
|
||||
For more information about installation on Mac or Windows Server (with IIS), or configuration of Apache or Nginx and also integration with other tools or services such as Jenkins or Slack, see [Wiki](https://github.com/gitbucket/gitbucket/wiki).
|
||||
|
||||
@@ -58,21 +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 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.
|
||||
|
||||
What's New in 4.36.x
|
||||
What's New in 4.44.x
|
||||
-------------
|
||||
### 4.36.2 - 16 Aug 2021
|
||||
- Escape user name in avatar image tag
|
||||
## 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.36.1 - 22 Jul 2021
|
||||
- Bump gitbucket-gist-plugin to 4.21.0
|
||||
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
|
||||
|
||||
### 4.36.0 - 17 Jul 2021
|
||||
- Tag selector in the repository viewer
|
||||
- Link issues/pull requests of other repositories
|
||||
- Files and lines can be linked in the diff view
|
||||
- Option to disable XSS protection
|
||||
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
|
||||
|
||||
See the [change log](CHANGELOG.md) for all of the updates.
|
||||
# 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}"
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
See the [change log](CHANGELOG.md) for all the past updates.
|
||||
|
||||
186
build.sbt
186
build.sbt
@@ -1,86 +1,75 @@
|
||||
import com.typesafe.sbt.license.{DepModuleInfo, LicenseInfo}
|
||||
import com.jsuereth.sbtpgp.PgpKeys._
|
||||
|
||||
val Organization = "io.github.gitbucket"
|
||||
val Name = "gitbucket"
|
||||
val GitBucketVersion = "4.36.2"
|
||||
val ScalatraVersion = "2.8.2"
|
||||
val JettyVersion = "9.4.44.v20210927"
|
||||
val JgitVersion = "5.13.0.202109080827-r"
|
||||
val GitBucketVersion = "4.44.0"
|
||||
val ScalatraVersion = "3.1.2"
|
||||
val JettyVersion = "10.0.26"
|
||||
val JgitVersion = "6.10.1.202505221210-r"
|
||||
|
||||
lazy val root = (project in file("."))
|
||||
.enablePlugins(SbtTwirl, ScalatraPlugin)
|
||||
.enablePlugins(SbtTwirl, ContainerPlugin)
|
||||
|
||||
sourcesInBase := false
|
||||
organization := Organization
|
||||
name := Name
|
||||
version := GitBucketVersion
|
||||
scalaVersion := "2.13.7"
|
||||
scalaVersion := "2.13.17"
|
||||
|
||||
scalafmtOnCompile := true
|
||||
crossScalaVersions += "3.7.3"
|
||||
|
||||
// scalafmtOnCompile := true
|
||||
|
||||
coverageExcludedPackages := ".*\\.html\\..*"
|
||||
|
||||
// dependency settings
|
||||
resolvers ++= Seq(
|
||||
Classpaths.typesafeReleases,
|
||||
Resolver.jcenterRepo,
|
||||
"sonatype-snapshot" at "https://oss.sonatype.org/content/repositories/snapshots/"
|
||||
)
|
||||
|
||||
libraryDependencies ++= Seq(
|
||||
"org.eclipse.jgit" % "org.eclipse.jgit.http.server" % JgitVersion,
|
||||
"org.eclipse.jgit" % "org.eclipse.jgit.archive" % JgitVersion,
|
||||
"org.scalatra" %% "scalatra" % ScalatraVersion cross CrossVersion.for3Use2_13,
|
||||
"org.scalatra" %% "scalatra-json" % ScalatraVersion cross CrossVersion.for3Use2_13,
|
||||
"org.scalatra" %% "scalatra-forms" % ScalatraVersion cross CrossVersion.for3Use2_13,
|
||||
"org.json4s" %% "json4s-jackson" % "4.0.3" cross CrossVersion.for3Use2_13,
|
||||
"commons-io" % "commons-io" % "2.11.0",
|
||||
"io.github.gitbucket" % "solidbase" % "1.0.3",
|
||||
"io.github.gitbucket" % "markedj" % "1.0.16",
|
||||
"org.apache.commons" % "commons-compress" % "1.21",
|
||||
"org.apache.commons" % "commons-email" % "1.5",
|
||||
"commons-net" % "commons-net" % "3.8.0",
|
||||
"org.apache.httpcomponents" % "httpclient" % "4.5.13",
|
||||
"org.apache.sshd" % "apache-sshd" % "2.1.0" exclude ("org.slf4j", "slf4j-jdk14") exclude ("org.apache.sshd", "sshd-mina") exclude ("org.apache.sshd", "sshd-netty"),
|
||||
"org.apache.tika" % "tika-core" % "2.1.0",
|
||||
"com.github.takezoe" %% "blocking-slick-32" % "0.0.12" cross CrossVersion.for3Use2_13,
|
||||
"com.novell.ldap" % "jldap" % "2009-10-07",
|
||||
"com.h2database" % "h2" % "1.4.199",
|
||||
"org.mariadb.jdbc" % "mariadb-java-client" % "2.7.4",
|
||||
"org.postgresql" % "postgresql" % "42.3.1",
|
||||
"ch.qos.logback" % "logback-classic" % "1.2.6",
|
||||
"com.zaxxer" % "HikariCP" % "4.0.3" exclude ("org.slf4j", "slf4j-api"),
|
||||
"com.typesafe" % "config" % "1.4.1",
|
||||
"fr.brouillard.oss.security.xhub" % "xhub4j-core" % "1.1.0",
|
||||
"io.github.java-diff-utils" % "java-diff-utils" % "4.11",
|
||||
"org.cache2k" % "cache2k-all" % "1.6.0.Final",
|
||||
"net.coobird" % "thumbnailator" % "0.4.14",
|
||||
"com.github.zafarkhaja" % "java-semver" % "0.9.0",
|
||||
"com.nimbusds" % "oauth2-oidc-sdk" % "9.19",
|
||||
"org.eclipse.jetty" % "jetty-webapp" % JettyVersion % "provided",
|
||||
"javax.servlet" % "javax.servlet-api" % "3.1.0" % "provided",
|
||||
"junit" % "junit" % "4.13.2" % "test",
|
||||
"org.scalatra" %% "scalatra-scalatest" % ScalatraVersion % "test" cross CrossVersion.for3Use2_13,
|
||||
"org.mockito" % "mockito-core" % "4.0.0" % "test",
|
||||
"com.dimafeng" %% "testcontainers-scala" % "0.39.11" % "test",
|
||||
"org.testcontainers" % "mysql" % "1.16.2" % "test",
|
||||
"org.testcontainers" % "postgresql" % "1.16.2" % "test",
|
||||
"net.i2p.crypto" % "eddsa" % "0.3.0",
|
||||
"is.tagomor.woothee" % "woothee-java" % "1.11.0",
|
||||
"org.ec4j.core" % "ec4j-core" % "0.3.0",
|
||||
"org.kohsuke" % "github-api" % "1.135" % "test"
|
||||
"org.eclipse.jgit" % "org.eclipse.jgit.http.server" % JgitVersion,
|
||||
"org.eclipse.jgit" % "org.eclipse.jgit.archive" % JgitVersion,
|
||||
"org.scalatra" %% "scalatra-javax" % ScalatraVersion,
|
||||
"org.scalatra" %% "scalatra-json-javax" % ScalatraVersion,
|
||||
"org.scalatra" %% "scalatra-forms-javax" % ScalatraVersion,
|
||||
"org.json4s" %% "json4s-jackson" % "4.1.0-M8",
|
||||
"commons-io" % "commons-io" % "2.20.0",
|
||||
"io.github.gitbucket" % "solidbase" % "1.1.0",
|
||||
"io.github.gitbucket" % "markedj" % "1.0.20",
|
||||
"org.tukaani" % "xz" % "1.10",
|
||||
"org.apache.commons" % "commons-compress" % "1.28.0",
|
||||
"org.apache.commons" % "commons-email" % "1.6.0",
|
||||
"commons-net" % "commons-net" % "3.12.0",
|
||||
"org.apache.httpcomponents" % "httpclient" % "4.5.14",
|
||||
"org.apache.sshd" % "apache-sshd" % "2.16.0" exclude ("org.slf4j", "slf4j-jdk14") exclude (
|
||||
"org.apache.sshd",
|
||||
"sshd-mina"
|
||||
) exclude ("org.apache.sshd", "sshd-netty")
|
||||
exclude ("org.apache.sshd", "sshd-spring-sftp"),
|
||||
"org.apache.tika" % "tika-core" % "3.2.3",
|
||||
"com.github.takezoe" %% "blocking-slick" % "0.0.14",
|
||||
"com.novell.ldap" % "jldap" % "2009-10-07",
|
||||
"com.h2database" % "h2" % "2.4.240",
|
||||
"org.mariadb.jdbc" % "mariadb-java-client" % "2.7.12",
|
||||
"org.postgresql" % "postgresql" % "42.7.8",
|
||||
"ch.qos.logback" % "logback-classic" % "1.5.20",
|
||||
"com.zaxxer" % "HikariCP" % "7.0.2" exclude ("org.slf4j", "slf4j-api"),
|
||||
"com.typesafe" % "config" % "1.4.5",
|
||||
"fr.brouillard.oss.security.xhub" % "xhub4j-core" % "1.1.0",
|
||||
"io.github.java-diff-utils" % "java-diff-utils" % "4.16",
|
||||
"org.cache2k" % "cache2k-all" % "1.6.0.Final",
|
||||
"net.coobird" % "thumbnailator" % "0.4.21",
|
||||
"com.github.zafarkhaja" % "java-semver" % "0.10.2",
|
||||
"com.nimbusds" % "oauth2-oidc-sdk" % "11.30",
|
||||
"org.eclipse.jetty" % "jetty-webapp" % JettyVersion % "provided",
|
||||
"javax.servlet" % "javax.servlet-api" % "3.1.0" % "provided",
|
||||
"junit" % "junit" % "4.13.2" % "test",
|
||||
"org.scalatra" %% "scalatra-scalatest-javax" % ScalatraVersion % "test",
|
||||
"org.mockito" % "mockito-core" % "5.20.0" % "test",
|
||||
"org.testcontainers" % "testcontainers-mysql" % "2.0.1" % "test",
|
||||
"org.testcontainers" % "testcontainers-postgresql" % "2.0.1" % "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
|
||||
scalacOptions := Seq(
|
||||
"-deprecation",
|
||||
@@ -90,8 +79,16 @@ scalacOptions := Seq(
|
||||
"-Wunused:imports",
|
||||
"-Wconf:cat=unused&src=twirl/.*:s,cat=unused&src=scala/gitbucket/core/model/[^/]+\\.scala:s"
|
||||
)
|
||||
compile / javacOptions ++= Seq("-target", "8", "-source", "8")
|
||||
Jetty / javaOptions += "-Dlogback.configurationFile=/logback-dev.xml"
|
||||
scalacOptions ++= {
|
||||
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
|
||||
//testOptions in Test += Tests.Argument("-l", "ExternalDBTest")
|
||||
@@ -115,8 +112,8 @@ assembly / assemblyMergeStrategy := {
|
||||
|
||||
// Exclude a war file from published artifacts
|
||||
signedArtifacts := {
|
||||
signedArtifacts.value.filterNot {
|
||||
case (_, file) => file.getName.endsWith(".war") || file.getName.endsWith(".war.asc")
|
||||
signedArtifacts.value.filterNot { case (_, file) =>
|
||||
file.getName.endsWith(".war") || file.getName.endsWith(".war.asc")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,15 +121,14 @@ signedArtifacts := {
|
||||
val ExecutableConfig = config("executable").hide
|
||||
Keys.ivyConfigurations += ExecutableConfig
|
||||
libraryDependencies ++= Seq(
|
||||
"org.eclipse.jetty" % "jetty-security" % 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-xml" % JettyVersion % "executable",
|
||||
"org.eclipse.jetty" % "jetty-http" % JettyVersion % "executable",
|
||||
"org.eclipse.jetty" % "jetty-servlet" % JettyVersion % "executable",
|
||||
"org.eclipse.jetty" % "jetty-io" % JettyVersion % "executable",
|
||||
"org.eclipse.jetty" % "jetty-util" % JettyVersion % "executable"
|
||||
"org.eclipse.jetty" % "jetty-security" % JettyVersion % "executable",
|
||||
"org.eclipse.jetty" % "jetty-webapp" % JettyVersion % "executable",
|
||||
"org.eclipse.jetty" % "jetty-server" % JettyVersion % "executable",
|
||||
"org.eclipse.jetty" % "jetty-xml" % JettyVersion % "executable",
|
||||
"org.eclipse.jetty" % "jetty-http" % JettyVersion % "executable",
|
||||
"org.eclipse.jetty" % "jetty-servlet" % JettyVersion % "executable",
|
||||
"org.eclipse.jetty" % "jetty-io" % JettyVersion % "executable",
|
||||
"org.eclipse.jetty" % "jetty-util" % JettyVersion % "executable"
|
||||
)
|
||||
|
||||
// Run package task before test to generate target/webapp for integration test
|
||||
@@ -159,9 +155,11 @@ executableKey := {
|
||||
// include jetty classes
|
||||
val jettyJars = Keys.update.value select configurationFilter(name = ExecutableConfig.name)
|
||||
jettyJars foreach { jar =>
|
||||
IO unzip (jar, temp, (name: String) =>
|
||||
(name startsWith "javax/") ||
|
||||
(name startsWith "org/"))
|
||||
IO unzip (
|
||||
jar,
|
||||
temp,
|
||||
(name: String) => (name startsWith "javax/") || (name startsWith "org/") || (name startsWith "META-INF/services/")
|
||||
)
|
||||
}
|
||||
|
||||
// include original war file
|
||||
@@ -186,14 +184,14 @@ executableKey := {
|
||||
val url = "https://github.com/" +
|
||||
s"gitbucket/gitbucket-${pluginId}-plugin/releases/download/${pluginVersion}/gitbucket-${pluginId}-plugin-${pluginVersion}.jar"
|
||||
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 _ => ()
|
||||
}
|
||||
}
|
||||
|
||||
// zip it up
|
||||
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)
|
||||
}
|
||||
val manifest = new JarManifest
|
||||
@@ -207,10 +205,9 @@ executableKey := {
|
||||
"md5" -> "MD5",
|
||||
"sha1" -> "SHA-1",
|
||||
"sha256" -> "SHA-256"
|
||||
).foreach {
|
||||
case (extension, algorithm) =>
|
||||
val checksumFile = workDir / (warName + "." + extension)
|
||||
Checksums generate (outputFile, checksumFile, algorithm)
|
||||
).foreach { case (extension, algorithm) =>
|
||||
val checksumFile = workDir / (warName + "." + extension)
|
||||
Checksums generate (outputFile, checksumFile, algorithm)
|
||||
}
|
||||
|
||||
// done
|
||||
@@ -218,9 +215,9 @@ executableKey := {
|
||||
outputFile
|
||||
}
|
||||
publishTo := {
|
||||
val nexus = "https://oss.sonatype.org/"
|
||||
if (version.value.trim.endsWith("SNAPSHOT")) Some("snapshots" at nexus + "content/repositories/snapshots")
|
||||
else Some("releases" at nexus + "service/local/staging/deploy/maven2")
|
||||
val centralSnapshots = "https://central.sonatype.com/repository/maven-snapshots/"
|
||||
if (isSnapshot.value) Some("central-snapshots" at centralSnapshots)
|
||||
else localStaging.value
|
||||
}
|
||||
publishMavenStyle := true
|
||||
pomIncludeRepository := { _ =>
|
||||
@@ -286,7 +283,12 @@ Test / testOptions ++= {
|
||||
}
|
||||
}
|
||||
|
||||
Jetty / javaOptions ++= Seq(
|
||||
Container / javaOptions ++= Seq(
|
||||
"-Dlogback.configurationFile=/logback-dev.xml",
|
||||
"-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"
|
||||
|
||||
23
doc/build.md
23
doc/build.md
@@ -1,7 +1,7 @@
|
||||
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
|
||||
$ 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.
|
||||
|
||||
```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`.
|
||||
|
||||
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
|
||||
--------
|
||||
@@ -37,7 +51,8 @@ To build an executable war file, run
|
||||
$ 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
|
||||
---------
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
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
|
||||
javaOptions in Jetty ++= Seq(
|
||||
@@ -12,7 +12,7 @@ javaOptions in Jetty ++= Seq(
|
||||
Run GitBucket:
|
||||
|
||||
```shell
|
||||
$ sbt ~jetty:start
|
||||
$ sbt ~container:start
|
||||
```
|
||||
|
||||
In IntelliJ, create remote debug configuration as follows. Make sure port number is same as above configuration.
|
||||
|
||||
@@ -5,13 +5,17 @@ GitBucket persists all data into __HOME/.gitbucket__ in default (In 1.9 or befor
|
||||
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
|
||||
* /USER_NAME
|
||||
* /REPO_NAME.git (substance of repository. GitServlet sees this directory)
|
||||
* /REPO_NAME.wiki.git (wiki repository)
|
||||
* /REPO_NAME
|
||||
* /issues (files which are attached to issue)
|
||||
* /issues (files attached to issue)
|
||||
* /lfs (LFS managed files)
|
||||
* /data
|
||||
* /USER_NAME
|
||||
@@ -20,6 +24,8 @@ This directory has following structure:
|
||||
* /plugins
|
||||
* plugin.jar
|
||||
* /.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
|
||||
* /_upload
|
||||
* /SESSION_ID (removed at session timeout)
|
||||
|
||||
@@ -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.
|
||||
|
||||
First, hit following command to publish artifacts to the sonatype OSS repository:
|
||||
First, stage artifacts on your machine:
|
||||
|
||||
```bash
|
||||
$ 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
|
||||
|
||||
@@ -55,5 +66,4 @@ Run `sbt executable`. The release war file and fingerprint are generated into `t
|
||||
```bash
|
||||
$ sbt executable
|
||||
```
|
||||
|
||||
Create new release from the corresponded tag on GitHub, then upload generated jar file and fingerprints to the release.
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 203 KiB After Width: | Height: | Size: 112 KiB |
@@ -1,6 +1,6 @@
|
||||
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:
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
sbt.version=1.5.5
|
||||
sbt.version=1.11.7
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
scalacOptions ++= Seq("-unchecked", "-deprecation", "-feature")
|
||||
|
||||
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.3")
|
||||
addSbtPlugin("com.typesafe.sbt" % "sbt-twirl" % "1.5.1")
|
||||
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "1.1.0")
|
||||
addSbtPlugin("org.scalatra.sbt" % "sbt-scalatra" % "1.0.4")
|
||||
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2")
|
||||
addSbtPlugin("com.typesafe.sbt" % "sbt-license-report" % "1.2.0")
|
||||
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.9.2")
|
||||
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.5")
|
||||
addSbtPlugin("org.playframework.twirl" % "sbt-twirl" % "2.0.9")
|
||||
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.3.1")
|
||||
addSbtPlugin("org.scalatra.sbt" % "sbt-scalatra" % "1.0.4")
|
||||
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.3.1")
|
||||
addSbtPlugin("com.github.sbt" % "sbt-license-report" % "1.9.0")
|
||||
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.4.0")
|
||||
|
||||
addDependencyTreePlugin
|
||||
|
||||
@@ -61,12 +61,19 @@ public class JettyLauncher {
|
||||
String redirectHttps = getEnvironmentVariable("gitbucket.redirectHttps");
|
||||
String contextPath = getEnvironmentVariable("gitbucket.prefix");
|
||||
String tmpDirPath = getEnvironmentVariable("gitbucket.tempDir");
|
||||
String jettyIdleTimeout = getEnvironmentVariable("gitbucket.jettyIdleTimeout");
|
||||
boolean saveSessions = false;
|
||||
|
||||
for(String arg: args) {
|
||||
if(arg.equals("--save_sessions")) {
|
||||
if (arg.equals("--save_sessions")) {
|
||||
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("=")) {
|
||||
String[] dim = arg.split("=", 2);
|
||||
if(dim.length == 2) {
|
||||
@@ -107,6 +114,9 @@ public class JettyLauncher {
|
||||
case "--plugin_dir":
|
||||
System.setProperty("gitbucket.pluginDir", dim[1]);
|
||||
break;
|
||||
case "--jetty_idle_timeout":
|
||||
jettyIdleTimeout = dim[1];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,6 +140,11 @@ public class JettyLauncher {
|
||||
if (connectorsSet.contains(Connectors.HTTPS)) {
|
||||
httpConfig.setSecurePort(fallback(securePort, Defaults.HTTPS_PORT, Integer::parseInt));
|
||||
}
|
||||
if (jettyIdleTimeout != null && jettyIdleTimeout.trim().length() != 0) {
|
||||
httpConfig.setIdleTimeout(Long.parseLong(jettyIdleTimeout.trim()));
|
||||
} else {
|
||||
httpConfig.setIdleTimeout(300000L); // default is 5min
|
||||
}
|
||||
|
||||
if (connectorsSet.contains(Connectors.HTTP)) {
|
||||
final ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
|
||||
@@ -140,7 +155,7 @@ public class JettyLauncher {
|
||||
}
|
||||
|
||||
if (connectorsSet.contains(Connectors.HTTPS)) {
|
||||
final SslContextFactory sslContextFactory = new SslContextFactory.Server();
|
||||
final SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
|
||||
|
||||
sslContextFactory.setKeyStorePath(requireNonNull(keyStorePath,
|
||||
"You must specify a path to an SSL keystore via the --key_store_path command line argument" +
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
notifications:1.10.0
|
||||
gist:4.21.0
|
||||
notifications:1.11.0
|
||||
gist:4.23.0
|
||||
emoji:4.6.0
|
||||
pages:1.10.0
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
</appender>
|
||||
|
||||
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
|
||||
<file>gitbucket.log</file>
|
||||
<file>.tmp/gitbucket.log</file>
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
@@ -23,4 +23,4 @@
|
||||
<logger name="scala.slick.jdbc.JdbcBackend.statement" level="DEBUG" />
|
||||
-->
|
||||
|
||||
</configuration>
|
||||
</configuration>
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 3.0 KiB After Width: | Height: | Size: 1.5 KiB |
@@ -1,18 +0,0 @@
|
||||
CREATE OR REPLACE VIEW ISSUE_OUTLINE_VIEW AS
|
||||
SELECT
|
||||
A.USER_NAME,
|
||||
A.REPOSITORY_NAME,
|
||||
A.ISSUE_ID,
|
||||
COALESCE(B.COMMENT_COUNT, 0) + COALESCE(C.COMMENT_COUNT, 0) AS COMMENT_COUNT
|
||||
FROM ISSUE A
|
||||
LEFT OUTER JOIN (
|
||||
SELECT USER_NAME, REPOSITORY_NAME, ISSUE_ID, COUNT(COMMENT_ID) AS COMMENT_COUNT FROM ISSUE_COMMENT
|
||||
WHERE ACTION IN ('comment', 'close_comment', 'reopen_comment')
|
||||
GROUP BY USER_NAME, REPOSITORY_NAME, ISSUE_ID
|
||||
) B
|
||||
ON (A.USER_NAME = B.USER_NAME AND A.REPOSITORY_NAME = B.REPOSITORY_NAME AND A.ISSUE_ID = B.ISSUE_ID)
|
||||
LEFT OUTER JOIN (
|
||||
SELECT USER_NAME, REPOSITORY_NAME, ISSUE_ID, COUNT(COMMENT_ID) AS COMMENT_COUNT FROM COMMIT_COMMENT
|
||||
GROUP BY USER_NAME, REPOSITORY_NAME, ISSUE_ID
|
||||
) C
|
||||
ON (A.USER_NAME = C.USER_NAME AND A.REPOSITORY_NAME = C.REPOSITORY_NAME AND A.ISSUE_ID = C.ISSUE_ID);
|
||||
@@ -343,4 +343,28 @@
|
||||
<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"/>
|
||||
|
||||
<!--================================================================================================-->
|
||||
<!-- ISSUE_OUTLINE_VIEW -->
|
||||
<!--================================================================================================-->
|
||||
<sql>
|
||||
CREATE OR REPLACE VIEW ISSUE_OUTLINE_VIEW AS
|
||||
SELECT
|
||||
A.USER_NAME,
|
||||
A.REPOSITORY_NAME,
|
||||
A.ISSUE_ID,
|
||||
COALESCE(B.COMMENT_COUNT, 0) + COALESCE(C.COMMENT_COUNT, 0) AS COMMENT_COUNT
|
||||
FROM ISSUE A
|
||||
LEFT OUTER JOIN (
|
||||
SELECT USER_NAME, REPOSITORY_NAME, ISSUE_ID, COUNT(COMMENT_ID) AS COMMENT_COUNT FROM ISSUE_COMMENT
|
||||
WHERE ACTION IN ('comment', 'close_comment', 'reopen_comment')
|
||||
GROUP BY USER_NAME, REPOSITORY_NAME, ISSUE_ID
|
||||
) B
|
||||
ON (A.USER_NAME = B.USER_NAME AND A.REPOSITORY_NAME = B.REPOSITORY_NAME AND A.ISSUE_ID = B.ISSUE_ID)
|
||||
LEFT OUTER JOIN (
|
||||
SELECT USER_NAME, REPOSITORY_NAME, ISSUE_ID, COUNT(COMMENT_ID) AS COMMENT_COUNT FROM COMMIT_COMMENT
|
||||
GROUP BY USER_NAME, REPOSITORY_NAME, ISSUE_ID
|
||||
) C
|
||||
ON (A.USER_NAME = C.USER_NAME AND A.REPOSITORY_NAME = C.REPOSITORY_NAME AND A.ISSUE_ID = C.ISSUE_ID)
|
||||
</sql>
|
||||
|
||||
</changeSet>
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
CREATE OR REPLACE VIEW ISSUE_OUTLINE_VIEW AS
|
||||
|
||||
SELECT
|
||||
A.USER_NAME,
|
||||
A.REPOSITORY_NAME,
|
||||
A.ISSUE_ID,
|
||||
COALESCE(B.COMMENT_COUNT, 0) + COALESCE(C.COMMENT_COUNT, 0) AS COMMENT_COUNT,
|
||||
COALESCE(D.ORDERING, 9999) AS PRIORITY
|
||||
|
||||
FROM ISSUE A
|
||||
|
||||
LEFT OUTER JOIN (
|
||||
SELECT USER_NAME, REPOSITORY_NAME, ISSUE_ID, COUNT(COMMENT_ID) AS COMMENT_COUNT FROM ISSUE_COMMENT
|
||||
WHERE ACTION IN ('comment', 'close_comment', 'reopen_comment')
|
||||
GROUP BY USER_NAME, REPOSITORY_NAME, ISSUE_ID
|
||||
) B
|
||||
ON (A.USER_NAME = B.USER_NAME AND A.REPOSITORY_NAME = B.REPOSITORY_NAME AND A.ISSUE_ID = B.ISSUE_ID)
|
||||
|
||||
LEFT OUTER JOIN (
|
||||
SELECT USER_NAME, REPOSITORY_NAME, ISSUE_ID, COUNT(COMMENT_ID) AS COMMENT_COUNT FROM COMMIT_COMMENT
|
||||
GROUP BY USER_NAME, REPOSITORY_NAME, ISSUE_ID
|
||||
) C
|
||||
ON (A.USER_NAME = C.USER_NAME AND A.REPOSITORY_NAME = C.REPOSITORY_NAME AND A.ISSUE_ID = C.ISSUE_ID)
|
||||
|
||||
LEFT OUTER JOIN PRIORITY D
|
||||
ON (A.PRIORITY_ID = D.PRIORITY_ID);
|
||||
@@ -35,4 +35,28 @@
|
||||
<column name="URL" type="varchar(200)" nullable="false"/>
|
||||
<column name="EVENT" type="varchar(30)" nullable="false"/>
|
||||
</createTable>
|
||||
|
||||
<sql>
|
||||
CREATE OR REPLACE VIEW ISSUE_OUTLINE_VIEW AS
|
||||
SELECT
|
||||
A.USER_NAME,
|
||||
A.REPOSITORY_NAME,
|
||||
A.ISSUE_ID,
|
||||
COALESCE(B.COMMENT_COUNT, 0) + COALESCE(C.COMMENT_COUNT, 0) AS COMMENT_COUNT,
|
||||
COALESCE(D.ORDERING, 9999) AS PRIORITY
|
||||
FROM ISSUE A
|
||||
LEFT OUTER JOIN (
|
||||
SELECT USER_NAME, REPOSITORY_NAME, ISSUE_ID, COUNT(COMMENT_ID) AS COMMENT_COUNT FROM ISSUE_COMMENT
|
||||
WHERE ACTION IN ('comment', 'close_comment', 'reopen_comment')
|
||||
GROUP BY USER_NAME, REPOSITORY_NAME, ISSUE_ID
|
||||
) B
|
||||
ON (A.USER_NAME = B.USER_NAME AND A.REPOSITORY_NAME = B.REPOSITORY_NAME AND A.ISSUE_ID = B.ISSUE_ID)
|
||||
LEFT OUTER JOIN (
|
||||
SELECT USER_NAME, REPOSITORY_NAME, ISSUE_ID, COUNT(COMMENT_ID) AS COMMENT_COUNT FROM COMMIT_COMMENT
|
||||
GROUP BY USER_NAME, REPOSITORY_NAME, ISSUE_ID
|
||||
) C
|
||||
ON (A.USER_NAME = C.USER_NAME AND A.REPOSITORY_NAME = C.REPOSITORY_NAME AND A.ISSUE_ID = C.ISSUE_ID)
|
||||
LEFT OUTER JOIN PRIORITY D
|
||||
ON (A.PRIORITY_ID = D.PRIORITY_ID);
|
||||
</sql>
|
||||
</changeSet>
|
||||
|
||||
7
src/main/resources/update/gitbucket-core_4.37.xml
Normal file
7
src/main/resources/update/gitbucket-core_4.37.xml
Normal file
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<changeSet>
|
||||
<dropForeignKeyConstraint constraintName="IDX_WEB_HOOK_EVENT_FK0" baseTableName="WEB_HOOK_EVENT"/>
|
||||
<modifyDataType columnName="URL" newDataType="varchar(400)" tableName="WEB_HOOK_EVENT"/>
|
||||
<modifyDataType columnName="URL" newDataType="varchar(400)" tableName="WEB_HOOK"/>
|
||||
<addForeignKeyConstraint constraintName="IDX_WEB_HOOK_EVENT_FK0" baseTableName="WEB_HOOK_EVENT" baseColumnNames="USER_NAME, REPOSITORY_NAME, URL" referencedTableName="WEB_HOOK" referencedColumnNames="USER_NAME, REPOSITORY_NAME, URL" onDelete="CASCADE" onUpdate="CASCADE"/>
|
||||
</changeSet>
|
||||
53
src/main/resources/update/gitbucket-core_4.38.xml
Normal file
53
src/main/resources/update/gitbucket-core_4.38.xml
Normal file
@@ -0,0 +1,53 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<changeSet>
|
||||
<!--================================================================================================-->
|
||||
<!-- CUSTOM_FIELD -->
|
||||
<!--================================================================================================-->
|
||||
<createTable tableName="CUSTOM_FIELD">
|
||||
<column name="USER_NAME" type="varchar(100)" nullable="false"/>
|
||||
<column name="REPOSITORY_NAME" type="varchar(100)" nullable="false"/>
|
||||
<column name="FIELD_ID" type="int" nullable="false" autoIncrement="true" unique="true"/>
|
||||
<column name="FIELD_NAME" type="varchar(100)" nullable="false"/>
|
||||
<column name="FIELD_TYPE" type="varchar(100)" nullable="false"/>
|
||||
<column name="ENABLE_FOR_ISSUES" type="boolean" nullable="false"/>
|
||||
<column name="ENABLE_FOR_PULL_REQUESTS" type="boolean" nullable="false"/>
|
||||
</createTable>
|
||||
<addPrimaryKey constraintName="IDX_CUSTOM_FIELD_PK" tableName="CUSTOM_FIELD" columnNames="USER_NAME, REPOSITORY_NAME, FIELD_ID"/>
|
||||
<addForeignKeyConstraint constraintName="IDX_CUSTOM_FIELD_FK0" baseTableName="CUSTOM_FIELD" baseColumnNames="USER_NAME, REPOSITORY_NAME" referencedTableName="REPOSITORY" referencedColumnNames="USER_NAME, REPOSITORY_NAME"/>
|
||||
|
||||
<!--================================================================================================-->
|
||||
<!-- ISSUE_CUSTOM_FIELD -->
|
||||
<!--================================================================================================-->
|
||||
<createTable tableName="ISSUE_CUSTOM_FIELD">
|
||||
<column name="USER_NAME" type="varchar(100)" nullable="false"/>
|
||||
<column name="REPOSITORY_NAME" type="varchar(100)" nullable="false"/>
|
||||
<column name="ISSUE_ID" type="int" nullable="false"/>
|
||||
<column name="FIELD_ID" type="int" nullable="false"/>
|
||||
<column name="VALUE" type="varchar(200)" nullable="true"/>
|
||||
</createTable>
|
||||
<addPrimaryKey constraintName="IDX_ISSUE_CUSTOM_FIELD_PK" tableName="ISSUE_CUSTOM_FIELD" columnNames="USER_NAME, REPOSITORY_NAME, ISSUE_ID, FIELD_ID"/>
|
||||
<addForeignKeyConstraint constraintName="IDX_ISSUE_CUSTOM_FIELD_FK0" baseTableName="ISSUE_CUSTOM_FIELD" baseColumnNames="USER_NAME, REPOSITORY_NAME, ISSUE_ID" referencedTableName="ISSUE" referencedColumnNames="USER_NAME, REPOSITORY_NAME, ISSUE_ID"/>
|
||||
<addForeignKeyConstraint constraintName="IDX_ISSUE_CUSTOM_FIELD_FK1" baseTableName="ISSUE_CUSTOM_FIELD" baseColumnNames="USER_NAME, REPOSITORY_NAME, FIELD_ID" referencedTableName="CUSTOM_FIELD" referencedColumnNames="USER_NAME, REPOSITORY_NAME, FIELD_ID"/>
|
||||
|
||||
<!--================================================================================================-->
|
||||
<!-- ISSUE_ASSIGNEE -->
|
||||
<!--================================================================================================-->
|
||||
<createTable tableName="ISSUE_ASSIGNEE">
|
||||
<column name="USER_NAME" type="varchar(100)" nullable="false"/>
|
||||
<column name="REPOSITORY_NAME" type="varchar(100)" nullable="false"/>
|
||||
<column name="ISSUE_ID" type="int" nullable="false"/>
|
||||
<column name="ASSIGNEE_USER_NAME" type="varchar(100)" nullable="false"/>
|
||||
</createTable>
|
||||
<addPrimaryKey constraintName="IDX_ISSUE_ASSIGNEE_PK" tableName="ISSUE_ASSIGNEE" columnNames="USER_NAME, REPOSITORY_NAME, ISSUE_ID, ASSIGNEE_USER_NAME"/>
|
||||
<addForeignKeyConstraint constraintName="IDX_ISSUE_ASSIGNEE_FK0" baseTableName="ISSUE_ASSIGNEE" baseColumnNames="USER_NAME, REPOSITORY_NAME, ISSUE_ID" referencedTableName="ISSUE" referencedColumnNames="USER_NAME, REPOSITORY_NAME, ISSUE_ID"/>
|
||||
<!--
|
||||
<addForeignKeyConstraint constraintName="IDX_ISSUE_ASSIGNEE_FK1" baseTableName="ISSUE_ASSIGNEE" baseColumnNames="ASSIGNEE_USER_NAME" referencedTableName="ACCOUNT" referencedColumnNames="USER_NAME"/>
|
||||
-->
|
||||
|
||||
<sql>
|
||||
INSERT INTO ISSUE_ASSIGNEE (USER_NAME, REPOSITORY_NAME, ISSUE_ID, ASSIGNEE_USER_NAME)
|
||||
SELECT USER_NAME, REPOSITORY_NAME, ISSUE_ID, ASSIGNED_USER_NAME FROM ISSUE WHERE ASSIGNED_USER_NAME IS NOT NULL
|
||||
</sql>
|
||||
|
||||
<dropColumn tableName="ISSUE" columnName="ASSIGNED_USER_NAME"/>
|
||||
</changeSet>
|
||||
6
src/main/resources/update/gitbucket-core_4.39.xml
Normal file
6
src/main/resources/update/gitbucket-core_4.39.xml
Normal 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>
|
||||
20
src/main/resources/update/gitbucket-core_4.42.xml
Normal file
20
src/main/resources/update/gitbucket-core_4.42.xml
Normal 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>
|
||||
32
src/main/resources/update/gitbucket-core_4.44.xml
Normal file
32
src/main/resources/update/gitbucket-core_4.44.xml
Normal 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>
|
||||
@@ -1,2 +0,0 @@
|
||||
-- DELETE COLLABORATORS IN GROUP REPOSITORIES
|
||||
DELETE FROM COLLABORATOR WHERE USER_NAME IN (SELECT USER_NAME FROM ACCOUNT WHERE GROUP_ACCOUNT = TRUE)
|
||||
@@ -30,4 +30,9 @@
|
||||
<dropColumn tableName="REPOSITORY" columnName="ENABLE_WIKI"/>
|
||||
<dropColumn tableName="REPOSITORY" columnName="ALLOW_WIKI_EDITING"/>
|
||||
<dropColumn tableName="REPOSITORY" columnName="ENABLE_ISSUES"/>
|
||||
|
||||
<!-- DELETE COLLABORATORS IN GROUP REPOSITORIES -->
|
||||
<sql>
|
||||
DELETE FROM COLLABORATOR WHERE USER_NAME IN (SELECT USER_NAME FROM ACCOUNT WHERE GROUP_ACCOUNT = TRUE)
|
||||
</sql>
|
||||
</changeSet>
|
||||
|
||||
@@ -4,27 +4,23 @@ import java.io.FileOutputStream
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.sql.Connection
|
||||
import java.util.UUID
|
||||
|
||||
import gitbucket.core.model.Activity
|
||||
import gitbucket.core.util.Directory.ActivityLog
|
||||
import gitbucket.core.util.JDBCUtil
|
||||
import io.github.gitbucket.solidbase.Solidbase
|
||||
import io.github.gitbucket.solidbase.migration.{LiquibaseMigration, Migration, SqlMigration}
|
||||
import io.github.gitbucket.solidbase.migration.{LiquibaseMigration, Migration}
|
||||
import io.github.gitbucket.solidbase.model.{Module, Version}
|
||||
import org.json4s.{Formats, NoTypeHints}
|
||||
import org.json4s.jackson.Serialization
|
||||
import org.json4s.jackson.Serialization.write
|
||||
|
||||
import java.util.logging.Level
|
||||
import scala.util.Using
|
||||
|
||||
object GitBucketCoreModule
|
||||
extends Module(
|
||||
"gitbucket-core",
|
||||
new Version(
|
||||
"4.0.0",
|
||||
new LiquibaseMigration("update/gitbucket-core_4.0.xml"),
|
||||
new SqlMigration("update/gitbucket-core_4.0.sql")
|
||||
),
|
||||
new Version("4.0.0", new LiquibaseMigration("update/gitbucket-core_4.0.xml")),
|
||||
new Version("4.1.0"),
|
||||
new Version("4.2.0", new LiquibaseMigration("update/gitbucket-core_4.2.xml")),
|
||||
new Version("4.2.1"),
|
||||
@@ -32,11 +28,7 @@ object GitBucketCoreModule
|
||||
new Version("4.4.0"),
|
||||
new Version("4.5.0"),
|
||||
new Version("4.6.0", new LiquibaseMigration("update/gitbucket-core_4.6.xml")),
|
||||
new Version(
|
||||
"4.7.0",
|
||||
new LiquibaseMigration("update/gitbucket-core_4.7.xml"),
|
||||
new SqlMigration("update/gitbucket-core_4.7.sql")
|
||||
),
|
||||
new Version("4.7.0", new LiquibaseMigration("update/gitbucket-core_4.7.xml")),
|
||||
new Version("4.7.1"),
|
||||
new Version("4.8"),
|
||||
new Version("4.9.0", new LiquibaseMigration("update/gitbucket-core_4.9.xml")),
|
||||
@@ -45,11 +37,7 @@ object GitBucketCoreModule
|
||||
new Version("4.12.0"),
|
||||
new Version("4.12.1"),
|
||||
new Version("4.13.0"),
|
||||
new Version(
|
||||
"4.14.0",
|
||||
new LiquibaseMigration("update/gitbucket-core_4.14.xml"),
|
||||
new SqlMigration("update/gitbucket-core_4.14.sql")
|
||||
),
|
||||
new Version("4.14.0", new LiquibaseMigration("update/gitbucket-core_4.14.xml")),
|
||||
new Version("4.14.1"),
|
||||
new Version("4.15.0"),
|
||||
new Version("4.16.0"),
|
||||
@@ -88,21 +76,20 @@ object GitBucketCoreModule
|
||||
import JDBCUtil._
|
||||
|
||||
val conn = context.get(Solidbase.CONNECTION).asInstanceOf[Connection]
|
||||
val list = conn.select("SELECT * FROM ACTIVITY ORDER BY ACTIVITY_ID") {
|
||||
rs =>
|
||||
Activity(
|
||||
activityId = UUID.randomUUID().toString,
|
||||
userName = rs.getString("USER_NAME"),
|
||||
repositoryName = rs.getString("REPOSITORY_NAME"),
|
||||
activityUserName = rs.getString("ACTIVITY_USER_NAME"),
|
||||
activityType = rs.getString("ACTIVITY_TYPE"),
|
||||
message = rs.getString("MESSAGE"),
|
||||
additionalInfo = {
|
||||
val additionalInfo = rs.getString("ADDITIONAL_INFO")
|
||||
if (rs.wasNull()) None else Some(additionalInfo)
|
||||
},
|
||||
activityDate = rs.getTimestamp("ACTIVITY_DATE")
|
||||
)
|
||||
val list = conn.select("SELECT * FROM ACTIVITY ORDER BY ACTIVITY_ID") { rs =>
|
||||
Activity(
|
||||
activityId = UUID.randomUUID().toString,
|
||||
userName = rs.getString("USER_NAME"),
|
||||
repositoryName = rs.getString("REPOSITORY_NAME"),
|
||||
activityUserName = rs.getString("ACTIVITY_USER_NAME"),
|
||||
activityType = rs.getString("ACTIVITY_TYPE"),
|
||||
message = rs.getString("MESSAGE"),
|
||||
additionalInfo = {
|
||||
val additionalInfo = rs.getString("ADDITIONAL_INFO")
|
||||
if (rs.wasNull()) None else Some(additionalInfo)
|
||||
},
|
||||
activityDate = rs.getTimestamp("ACTIVITY_DATE")
|
||||
)
|
||||
}
|
||||
Using.resource(new FileOutputStream(ActivityLog, true)) { out =>
|
||||
list.foreach { activity =>
|
||||
@@ -119,5 +106,22 @@ object GitBucketCoreModule
|
||||
new Version("4.35.3"),
|
||||
new Version("4.36.0", new LiquibaseMigration("update/gitbucket-core_4.36.xml")),
|
||||
new Version("4.36.1"),
|
||||
new Version("4.36.2")
|
||||
)
|
||||
new Version("4.36.2"),
|
||||
new Version("4.37.0", new LiquibaseMigration("update/gitbucket-core_4.37.xml")),
|
||||
new Version("4.37.1"),
|
||||
new Version("4.37.2"),
|
||||
new Version("4.38.0", new LiquibaseMigration("update/gitbucket-core_4.38.xml")),
|
||||
new Version("4.38.1"),
|
||||
new Version("4.38.2"),
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -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])
|
||||
@@ -6,7 +6,7 @@ import gitbucket.core.util.RepositoryName
|
||||
* https://developer.github.com/v3/repos/#get-branch
|
||||
* 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
|
||||
) extends FieldSerializable {
|
||||
val _links =
|
||||
|
||||
@@ -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])
|
||||
}
|
||||
@@ -4,55 +4,68 @@ import gitbucket.core.service.ProtectedBranchService
|
||||
import org.json4s._
|
||||
|
||||
/** https://developer.github.com/v3/repos/#enabling-and-disabling-branch-protection */
|
||||
case class ApiBranchProtection(
|
||||
case class ApiBranchProtectionResponse(
|
||||
url: Option[ApiPath], // for output
|
||||
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 EnablingAndDisabling(protection: ApiBranchProtection)
|
||||
case class EnforceAdmins(enabled: Boolean)
|
||||
|
||||
def apply(info: ProtectedBranchService.ProtectedBranchInfo): ApiBranchProtection =
|
||||
ApiBranchProtection(
|
||||
// /** form for enabling-and-disabling-branch-protection */
|
||||
// case class EnablingAndDisabling(protection: ApiBranchProtectionResponse)
|
||||
|
||||
def apply(info: ProtectedBranchService.ProtectedBranchInfo): ApiBranchProtectionResponse =
|
||||
ApiBranchProtectionResponse(
|
||||
url = Some(
|
||||
ApiPath(
|
||||
s"/api/v3/repos/${info.owner}/${info.repository}/branches/${info.branch}/protection"
|
||||
)
|
||||
),
|
||||
enabled = info.enabled,
|
||||
required_status_checks = Some(
|
||||
required_status_checks = info.contexts.map { contexts =>
|
||||
Status(
|
||||
Some(
|
||||
ApiPath(
|
||||
s"/api/v3/repos/${info.owner}/${info.repository}/branches/${info.branch}/protection/required_status_checks"
|
||||
)
|
||||
),
|
||||
EnforcementLevel(info.enabled && info.contexts.nonEmpty, info.includeAdministrators),
|
||||
info.contexts,
|
||||
EnforcementLevel(info.enabled && info.contexts.nonEmpty, info.enforceAdmins),
|
||||
contexts,
|
||||
Some(
|
||||
ApiPath(
|
||||
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(
|
||||
url: Option[ApiPath], // for output
|
||||
enforcement_level: EnforcementLevel,
|
||||
contexts: Seq[String],
|
||||
contexts_url: Option[ApiPath] // for output
|
||||
)
|
||||
|
||||
sealed class EnforcementLevel(val name: String)
|
||||
case object Off extends EnforcementLevel("off")
|
||||
case object NonAdmins extends EnforcementLevel("non_admins")
|
||||
case object Everyone extends EnforcementLevel("everyone")
|
||||
|
||||
object EnforcementLevel {
|
||||
def apply(enabled: Boolean, includeAdministrators: Boolean): EnforcementLevel =
|
||||
if (enabled) {
|
||||
@@ -66,16 +79,19 @@ object ApiBranchProtection {
|
||||
}
|
||||
}
|
||||
|
||||
implicit val enforcementLevelSerializer: CustomSerializer[EnforcementLevel] = new CustomSerializer[EnforcementLevel](
|
||||
format =>
|
||||
case class Restrictions(users: Seq[String])
|
||||
|
||||
implicit val enforcementLevelSerializer: CustomSerializer[EnforcementLevel] =
|
||||
new CustomSerializer[EnforcementLevel](format =>
|
||||
(
|
||||
{
|
||||
case JString("off") => Off
|
||||
case JString("non_admins") => NonAdmins
|
||||
case JString("everyone") => Everyone
|
||||
}, {
|
||||
case x: EnforcementLevel => JString(x.name)
|
||||
},
|
||||
{ case x: EnforcementLevel =>
|
||||
JString(x.name)
|
||||
}
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -14,7 +14,8 @@ case class ApiComment(id: Int, user: ApiUser, body: String, created_at: Date, up
|
||||
isPullRequest: Boolean
|
||||
) {
|
||||
val html_url = ApiPath(
|
||||
s"/${repositoryName.fullName}/${if (isPullRequest) { "pull" } else { "issues" }}/${issueId}#comment-${id}"
|
||||
s"/${repositoryName.fullName}/${if (isPullRequest) { "pull" }
|
||||
else { "issues" }}/${issueId}#comment-${id}"
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ case class ApiCommit(
|
||||
|
||||
object 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(
|
||||
id = commit.id,
|
||||
message = commit.fullMessage,
|
||||
|
||||
@@ -69,7 +69,8 @@ object ApiCommits {
|
||||
}
|
||||
|
||||
File(
|
||||
filename = if (diff.changeType == ChangeType.DELETE) { diff.oldPath } else { diff.newPath },
|
||||
filename = if (diff.changeType == ChangeType.DELETE) { diff.oldPath }
|
||||
else { diff.newPath },
|
||||
additions = additions,
|
||||
deletions = deletions,
|
||||
changes = additions + deletions,
|
||||
@@ -97,7 +98,7 @@ object ApiCommits {
|
||||
ApiCommits(
|
||||
url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/commits/${commitInfo.id}"),
|
||||
sha = commitInfo.id,
|
||||
html_url = ApiPath(s"${repositoryName.fullName}/commit/${commitInfo.id}"),
|
||||
html_url = ApiPath(s"/${repositoryName.fullName}/commit/${commitInfo.id}"),
|
||||
comment_url = ApiPath(""), // TODO no API for commit comment
|
||||
commit = Commit(
|
||||
url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/commits/${commitInfo.id}"),
|
||||
@@ -106,7 +107,9 @@ object ApiCommits {
|
||||
message = commitInfo.shortMessage,
|
||||
comment_count = commentCount,
|
||||
tree = Tree(
|
||||
url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/tree/${commitInfo.id}"), // TODO This endpoint has not been implemented yet.
|
||||
url = ApiPath(
|
||||
s"/api/v3/repos/${repositoryName.fullName}/tree/${commitInfo.id}"
|
||||
), // TODO This endpoint has not been implemented yet.
|
||||
sha = commitInfo.id
|
||||
)
|
||||
),
|
||||
@@ -114,7 +117,9 @@ object ApiCommits {
|
||||
committer = ApiUser(committer),
|
||||
parents = commitInfo.parents.map { parent =>
|
||||
Tree(
|
||||
url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/tree/${parent}"), // TODO This endpoint has not been implemented yet.
|
||||
url = ApiPath(
|
||||
s"/api/v3/repos/${repositoryName.fullName}/tree/${parent}"
|
||||
), // TODO This endpoint has not been implemented yet.
|
||||
sha = parent
|
||||
)
|
||||
},
|
||||
|
||||
@@ -22,16 +22,15 @@ object ApiContents {
|
||||
ApiContents("dir", fileInfo.name, fileInfo.path, fileInfo.commitId, None, None)(repositoryName)
|
||||
} else {
|
||||
content
|
||||
.map(
|
||||
arr =>
|
||||
ApiContents(
|
||||
"file",
|
||||
fileInfo.name,
|
||||
fileInfo.path,
|
||||
fileInfo.id.getName,
|
||||
Some(Base64.getEncoder.encodeToString(arr)),
|
||||
Some("base64")
|
||||
)(repositoryName)
|
||||
.map(arr =>
|
||||
ApiContents(
|
||||
"file",
|
||||
fileInfo.name,
|
||||
fileInfo.path,
|
||||
fileInfo.id.getName,
|
||||
Some(Base64.getEncoder.encodeToString(arr)),
|
||||
Some("base64")
|
||||
)(repositoryName)
|
||||
)
|
||||
.getOrElse(ApiContents("file", fileInfo.name, fileInfo.path, fileInfo.commitId, None, None)(repositoryName))
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ case class ApiIssue(
|
||||
number: Int,
|
||||
title: String,
|
||||
user: ApiUser,
|
||||
assignee: Option[ApiUser],
|
||||
assignees: List[ApiUser],
|
||||
labels: List[ApiLabel],
|
||||
state: String,
|
||||
created_at: Date,
|
||||
@@ -21,9 +21,10 @@ case class ApiIssue(
|
||||
milestone: Option[ApiMilestone]
|
||||
)(repositoryName: RepositoryName, isPullRequest: Boolean) {
|
||||
val id = 0 // dummy id
|
||||
val assignees = List(assignee).flatten
|
||||
val assignee = assignees.headOption
|
||||
val comments_url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/issues/${number}/comments")
|
||||
val html_url = ApiPath(s"/${repositoryName.fullName}/${if (isPullRequest) { "pull" } else { "issues" }}/${number}")
|
||||
val html_url = ApiPath(s"/${repositoryName.fullName}/${if (isPullRequest) { "pull" }
|
||||
else { "issues" }}/${number}")
|
||||
val pull_request = if (isPullRequest) {
|
||||
Some(
|
||||
Map(
|
||||
@@ -43,7 +44,7 @@ object ApiIssue {
|
||||
issue: Issue,
|
||||
repositoryName: RepositoryName,
|
||||
user: ApiUser,
|
||||
assignee: Option[ApiUser],
|
||||
assignees: List[ApiUser],
|
||||
labels: List[ApiLabel],
|
||||
milestone: Option[ApiMilestone]
|
||||
): ApiIssue =
|
||||
@@ -51,10 +52,11 @@ object ApiIssue {
|
||||
number = issue.issueId,
|
||||
title = issue.title,
|
||||
user = user,
|
||||
assignee = assignee,
|
||||
assignees = assignees,
|
||||
labels = labels,
|
||||
milestone = milestone,
|
||||
state = if (issue.closed) { "closed" } else { "open" },
|
||||
state = if (issue.closed) { "closed" }
|
||||
else { "open" },
|
||||
body = issue.content.getOrElse(""),
|
||||
created_at = issue.registeredDate,
|
||||
updated_at = issue.updatedDate
|
||||
|
||||
@@ -21,15 +21,16 @@ case class ApiPullRequest(
|
||||
body: String,
|
||||
user: ApiUser,
|
||||
labels: List[ApiLabel],
|
||||
assignee: Option[ApiUser],
|
||||
assignees: List[ApiUser],
|
||||
draft: Option[Boolean]
|
||||
) {
|
||||
val id = 0 // dummy id
|
||||
val assignee = assignees.headOption
|
||||
val html_url = ApiPath(s"${base.repo.html_url.path}/pull/${number}")
|
||||
//val diff_url = ApiPath(s"${base.repo.html_url.path}/pull/${number}.diff")
|
||||
//val patch_url = ApiPath(s"${base.repo.html_url.path}/pull/${number}.patch")
|
||||
// val diff_url = ApiPath(s"${base.repo.html_url.path}/pull/${number}.diff")
|
||||
// val patch_url = ApiPath(s"${base.repo.html_url.path}/pull/${number}.patch")
|
||||
val url = ApiPath(s"${base.repo.url.path}/pulls/${number}")
|
||||
//val issue_url = ApiPath(s"${base.repo.url.path}/issues/${number}")
|
||||
// val issue_url = ApiPath(s"${base.repo.url.path}/issues/${number}")
|
||||
val commits_url = ApiPath(s"${base.repo.url.path}/pulls/${number}/commits")
|
||||
val review_comments_url = ApiPath(s"${base.repo.url.path}/pulls/${number}/comments")
|
||||
val review_comment_url = ApiPath(s"${base.repo.url.path}/pulls/comments/{number}")
|
||||
@@ -45,7 +46,7 @@ object ApiPullRequest {
|
||||
baseRepo: ApiRepository,
|
||||
user: ApiUser,
|
||||
labels: List[ApiLabel],
|
||||
assignee: Option[ApiUser],
|
||||
assignees: List[ApiUser],
|
||||
mergedComment: Option[(IssueComment, Account)]
|
||||
): ApiPullRequest =
|
||||
ApiPullRequest(
|
||||
@@ -63,12 +64,13 @@ object ApiPullRequest {
|
||||
body = issue.content.getOrElse(""),
|
||||
user = user,
|
||||
labels = labels,
|
||||
assignee = assignee,
|
||||
assignees = assignees,
|
||||
draft = Some(pullRequest.isDraft)
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,55 @@
|
||||
package gitbucket.core.api
|
||||
|
||||
case class ApiObject(sha: String)
|
||||
import gitbucket.core.util.JGitUtil.TagInfo
|
||||
import gitbucket.core.util.RepositoryName
|
||||
import org.eclipse.jgit.lib.Ref
|
||||
|
||||
case class ApiRef(ref: String, `object`: ApiObject)
|
||||
case class ApiRefCommit(
|
||||
sha: String,
|
||||
`type`: String,
|
||||
url: ApiPath
|
||||
)
|
||||
|
||||
case class ApiRef(
|
||||
ref: String,
|
||||
node_id: String = "",
|
||||
url: ApiPath,
|
||||
`object`: ApiRefCommit,
|
||||
)
|
||||
|
||||
object ApiRef {
|
||||
|
||||
def fromRef(
|
||||
repositoryName: RepositoryName,
|
||||
ref: Ref
|
||||
): ApiRef =
|
||||
ApiRef(
|
||||
ref = ref.getName,
|
||||
url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/git/${ref.getName}"),
|
||||
`object` = ApiRefCommit(
|
||||
sha = ref.getObjectId.getName,
|
||||
url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/commits/${ref.getObjectId.getName}"),
|
||||
`type` = "commit"
|
||||
)
|
||||
)
|
||||
|
||||
def fromTag(
|
||||
repositoryName: RepositoryName,
|
||||
tagInfo: TagInfo
|
||||
): ApiRef =
|
||||
ApiRef(
|
||||
ref = s"refs/tags/${tagInfo.name}",
|
||||
url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/git/refs/tags/${tagInfo.name}"),
|
||||
// the GH api distinguishes between "releases" and plain git tags
|
||||
// for "releases", the api returns a reference to the release object (with type `tag`)
|
||||
// this would be something like s"/api/v3/repos/${repositoryName.fullName}/git/tags/<hash-of-tag>"
|
||||
// with a hash for the tag, which I do not fully understand
|
||||
// since this is not yet implemented in GB, we always return a link to the plain `commit` object,
|
||||
// which GH does for tags that are not annotated
|
||||
`object` = ApiRefCommit(
|
||||
sha = tagInfo.objectId,
|
||||
url = ApiPath(s"/api/v3/repos/${repositoryName.fullName}/commits/${tagInfo.objectId}"),
|
||||
`type` = "commit"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ case class ApiRepository(
|
||||
val url = ApiPath(s"/api/v3/repos/${full_name}")
|
||||
val clone_url = ApiPath(s"/git/${full_name}.git")
|
||||
val html_url = ApiPath(s"/${full_name}")
|
||||
val ssh_url = Some(SshPath(s":${full_name}.git"))
|
||||
val ssh_url = Some(SshPath(s"/${full_name}.git"))
|
||||
}
|
||||
|
||||
object ApiRepository {
|
||||
@@ -61,7 +61,7 @@ object ApiRepository {
|
||||
watchers = 0,
|
||||
forks = 0,
|
||||
`private` = false,
|
||||
default_branch = "master",
|
||||
default_branch = "main",
|
||||
owner = owner,
|
||||
has_issues = true
|
||||
)
|
||||
|
||||
@@ -24,7 +24,8 @@ object ApiUser {
|
||||
def apply(user: Account): ApiUser = ApiUser(
|
||||
login = user.userName,
|
||||
email = user.mailAddress,
|
||||
`type` = if (user.isGroupAccount) { "Organization" } else { "User" },
|
||||
`type` = if (user.isGroupAccount) { "Organization" }
|
||||
else { "User" },
|
||||
site_admin = user.isAdmin,
|
||||
created_at = user.registeredDate
|
||||
)
|
||||
|
||||
@@ -15,13 +15,12 @@ object JsonFormat {
|
||||
|
||||
val parserISO = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
|
||||
|
||||
val jsonFormats = Serialization.formats(NoTypeHints) + new CustomSerializer[Date](
|
||||
format =>
|
||||
(
|
||||
{
|
||||
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)) }
|
||||
val jsonFormats = Serialization.formats(NoTypeHints) + new CustomSerializer[Date](format =>
|
||||
(
|
||||
{ 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)) }
|
||||
)
|
||||
) + FieldSerializer[ApiUser]() +
|
||||
FieldSerializer[ApiGroup]() +
|
||||
@@ -45,32 +44,35 @@ object JsonFormat {
|
||||
FieldSerializer[ApiCommits.File]() +
|
||||
FieldSerializer[ApiRelease]() +
|
||||
FieldSerializer[ApiReleaseAsset]() +
|
||||
ApiBranchProtection.enforcementLevelSerializer
|
||||
ApiBranchProtectionResponse.enforcementLevelSerializer
|
||||
|
||||
def apiPathSerializer(c: Context) =
|
||||
new CustomSerializer[ApiPath](
|
||||
_ =>
|
||||
({
|
||||
new CustomSerializer[ApiPath](_ =>
|
||||
(
|
||||
{
|
||||
case JString(s) if s.startsWith(c.baseUrl) => ApiPath(s.substring(c.baseUrl.length))
|
||||
case JString(s) => throw new MappingException("Can't convert " + s + " to ApiPath")
|
||||
}, {
|
||||
case ApiPath(path) => JString(c.baseUrl + path)
|
||||
})
|
||||
},
|
||||
{ case ApiPath(path) =>
|
||||
JString(c.baseUrl + path)
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
def sshPathSerializer(c: Context) =
|
||||
new CustomSerializer[SshPath](
|
||||
_ =>
|
||||
({
|
||||
new CustomSerializer[SshPath](_ =>
|
||||
(
|
||||
{
|
||||
case JString(s) if c.sshUrl.exists(sshUrl => s.startsWith(sshUrl)) =>
|
||||
SshPath(s.substring(c.sshUrl.get.length))
|
||||
case JString(s) => throw new MappingException("Can't convert " + s + " to ApiPath")
|
||||
}, {
|
||||
case SshPath(path) =>
|
||||
c.sshUrl.map { sshUrl =>
|
||||
JString(sshUrl + path)
|
||||
} getOrElse JNothing
|
||||
})
|
||||
},
|
||||
{ case SshPath(path) =>
|
||||
c.sshUrl.map { sshUrl =>
|
||||
JString(sshUrl + path)
|
||||
} getOrElse JNothing
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
/**
|
||||
|
||||
@@ -38,23 +38,11 @@ class AccountController
|
||||
with RequestCache
|
||||
|
||||
trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
self: AccountService
|
||||
with RepositoryService
|
||||
with ActivityService
|
||||
with WikiService
|
||||
with LabelsService
|
||||
with SshKeyService
|
||||
with GpgKeyService
|
||||
with OneselfAuthenticator
|
||||
with UsersAuthenticator
|
||||
with GroupManagerAuthenticator
|
||||
with ReadableUsersAuthenticator
|
||||
with AccessTokenService
|
||||
with WebHookService
|
||||
with PrioritiesService
|
||||
with RepositoryCreationService =>
|
||||
self: AccountService & RepositoryService & ActivityService & WikiService & LabelsService & SshKeyService &
|
||||
GpgKeyService & OneselfAuthenticator & UsersAuthenticator & GroupManagerAuthenticator & ReadableUsersAuthenticator &
|
||||
AccessTokenService & WebHookService & PrioritiesService & RepositoryCreationService =>
|
||||
|
||||
case class AccountNewForm(
|
||||
private case class AccountNewForm(
|
||||
userName: String,
|
||||
password: String,
|
||||
fullName: String,
|
||||
@@ -65,7 +53,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
fileId: Option[String]
|
||||
)
|
||||
|
||||
case class AccountEditForm(
|
||||
private case class AccountEditForm(
|
||||
password: Option[String],
|
||||
fullName: String,
|
||||
mailAddress: String,
|
||||
@@ -76,15 +64,15 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
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))),
|
||||
"password" -> trim(label("Password", text(required, maxlength(40)))),
|
||||
"fullName" -> trim(label("Full Name", text(required, maxlength(100)))),
|
||||
@@ -97,7 +85,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
"fileId" -> trim(label("File ID", optional(text())))
|
||||
)(AccountNewForm.apply)
|
||||
|
||||
val editForm = mapping(
|
||||
private val editForm = mapping(
|
||||
"password" -> trim(label("Password", optional(text(maxlength(40))))),
|
||||
"fullName" -> trim(label("Full Name", text(required, maxlength(100)))),
|
||||
"mailAddress" -> trim(label("Mail Address", text(required, maxlength(100), uniqueMailAddress("userName")))),
|
||||
@@ -110,32 +98,41 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
"clearImage" -> trim(label("Clear image", boolean()))
|
||||
)(AccountEditForm.apply)
|
||||
|
||||
val sshKeyForm = mapping(
|
||||
private val sshKeyForm = mapping(
|
||||
"title" -> trim(label("Title", text(required, maxlength(100)))),
|
||||
"publicKey" -> trim2(label("Key", text(required, validPublicKey)))
|
||||
)(SshKeyForm.apply)
|
||||
|
||||
val gpgKeyForm = mapping(
|
||||
private val gpgKeyForm = mapping(
|
||||
"title" -> trim(label("Title", text(required, maxlength(100)))),
|
||||
"publicKey" -> label("Key", text(required, validGpgPublicKey))
|
||||
)(GpgKeyForm.apply)
|
||||
|
||||
val personalTokenForm = mapping(
|
||||
private val personalTokenForm = mapping(
|
||||
"note" -> trim(label("Token", text(required, maxlength(100))))
|
||||
)(PersonalTokenForm.apply)
|
||||
|
||||
val syntaxHighlighterThemeForm = mapping(
|
||||
private val syntaxHighlighterThemeForm = mapping(
|
||||
"highlighterTheme" -> trim(label("Theme", text(required)))
|
||||
)(SyntaxHighlighterThemeForm.apply)
|
||||
|
||||
case class NewGroupForm(
|
||||
private val resetPasswordEmailForm = mapping(
|
||||
"mailAddress" -> trim(label("Email", text(required)))
|
||||
)(ResetPasswordEmailForm.apply)
|
||||
|
||||
private val resetPasswordForm = mapping(
|
||||
"token" -> trim(label("Token", text(required))),
|
||||
"password" -> trim(label("Password", text(required, maxlength(40))))
|
||||
)(ResetPasswordForm.apply)
|
||||
|
||||
private case class NewGroupForm(
|
||||
groupName: String,
|
||||
description: Option[String],
|
||||
url: Option[String],
|
||||
fileId: Option[String],
|
||||
members: String
|
||||
)
|
||||
case class EditGroupForm(
|
||||
private case class EditGroupForm(
|
||||
groupName: String,
|
||||
description: Option[String],
|
||||
url: Option[String],
|
||||
@@ -143,8 +140,15 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
members: String,
|
||||
clearImage: Boolean
|
||||
)
|
||||
private case class ResetPasswordEmailForm(
|
||||
mailAddress: String
|
||||
)
|
||||
private case class ResetPasswordForm(
|
||||
token: String,
|
||||
password: String
|
||||
)
|
||||
|
||||
val newGroupForm = mapping(
|
||||
private val newGroupForm = mapping(
|
||||
"groupName" -> trim(label("Group name", text(required, maxlength(100), identifier, uniqueUserName, reservedNames))),
|
||||
"description" -> trim(label("Group description", optional(text()))),
|
||||
"url" -> trim(label("URL", optional(text(maxlength(200))))),
|
||||
@@ -152,7 +156,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
"members" -> trim(label("Members", text(required, members)))
|
||||
)(NewGroupForm.apply)
|
||||
|
||||
val editGroupForm = mapping(
|
||||
private val editGroupForm = mapping(
|
||||
"groupName" -> trim(label("Group name", text(required, maxlength(100), identifier))),
|
||||
"description" -> trim(label("Group description", optional(text()))),
|
||||
"url" -> trim(label("URL", optional(text(maxlength(200))))),
|
||||
@@ -161,7 +165,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
"clearImage" -> trim(label("Clear image", boolean()))
|
||||
)(EditGroupForm.apply)
|
||||
|
||||
case class RepositoryCreationForm(
|
||||
private case class RepositoryCreationForm(
|
||||
owner: String,
|
||||
name: String,
|
||||
description: Option[String],
|
||||
@@ -169,9 +173,8 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
initOption: 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))),
|
||||
"name" -> trim(label("Repository name", text(required, maxlength(100), repository, uniqueRepository))),
|
||||
"description" -> trim(label("Description", optional(text()))),
|
||||
@@ -180,34 +183,27 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
"sourceUrl" -> trim(label("Source URL", optionalRequired(_.value("initOption") == "COPY", text())))
|
||||
)(RepositoryCreationForm.apply)
|
||||
|
||||
val forkRepositoryForm = mapping(
|
||||
"owner" -> trim(label("Repository owner", text(required))),
|
||||
"name" -> trim(label("Repository name", text(required)))
|
||||
)(ForkRepositoryForm.apply)
|
||||
private case class AccountForm(accountName: String)
|
||||
|
||||
case class AccountForm(accountName: String)
|
||||
|
||||
val accountForm = mapping(
|
||||
private val accountForm = mapping(
|
||||
"account" -> trim(label("Group/User name", text(required, validAccountName)))
|
||||
)(AccountForm.apply)
|
||||
|
||||
// for account web hook url addition.
|
||||
case class AccountWebHookForm(
|
||||
private case class AccountWebHookForm(
|
||||
url: String,
|
||||
events: Set[WebHook.Event],
|
||||
ctype: WebHookContentType,
|
||||
token: Option[String]
|
||||
)
|
||||
|
||||
def accountWebHookForm(update: Boolean) =
|
||||
private def accountWebHookForm(update: Boolean) =
|
||||
mapping(
|
||||
"url" -> trim(label("url", text(required, accountWebHook(update)))),
|
||||
"events" -> accountWebhookEvents,
|
||||
"ctype" -> label("ctype", text()),
|
||||
"token" -> optional(trim(label("token", text(maxlength(100)))))
|
||||
)(
|
||||
(url, events, ctype, token) => AccountWebHookForm(url, events, WebHookContentType.valueOf(ctype), token)
|
||||
)
|
||||
)((url, events, ctype, token) => AccountWebHookForm(url, events, WebHookContentType.valueOf(ctype), token))
|
||||
|
||||
/**
|
||||
* Provides duplication check for web hook url. duplicated from RepositorySettingsController.scala
|
||||
@@ -252,12 +248,12 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
gitbucket.core.account.html.activity(
|
||||
account,
|
||||
if (account.isGroupAccount) Nil else getGroupsByUserName(userName),
|
||||
getActivitiesByUser(userName, true),
|
||||
getActivitiesByUser(userName, publicOnly = true),
|
||||
extraMailAddresses
|
||||
)
|
||||
|
||||
// Members
|
||||
case "members" if (account.isGroupAccount) => {
|
||||
case "members" if account.isGroupAccount =>
|
||||
val members = getGroupMembers(account.userName)
|
||||
gitbucket.core.account.html.members(
|
||||
account,
|
||||
@@ -265,10 +261,9 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
extraMailAddresses,
|
||||
isGroupManager(context.loginAccount, members)
|
||||
)
|
||||
}
|
||||
|
||||
// Repositories
|
||||
case _ => {
|
||||
case _ =>
|
||||
val members = getGroupMembers(account.userName)
|
||||
gitbucket.core.account.html.repositories(
|
||||
account,
|
||||
@@ -277,7 +272,6 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
extraMailAddresses,
|
||||
isGroupManager(context.loginAccount, members)
|
||||
)
|
||||
}
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
}
|
||||
@@ -285,7 +279,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
get("/:userName.atom") {
|
||||
val userName = params("userName")
|
||||
contentType = "application/atom+xml; type=feed"
|
||||
helper.xml.feed(getActivitiesByUser(userName, true))
|
||||
helper.xml.feed(getActivitiesByUser(userName, publicOnly = true))
|
||||
}
|
||||
|
||||
get("/:userName.keys") {
|
||||
@@ -330,22 +324,21 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
|
||||
post("/:userName/_edit", editForm)(oneselfOnly { form =>
|
||||
val userName = params("userName")
|
||||
getAccountByUserName(userName).map {
|
||||
account =>
|
||||
updateAccount(
|
||||
account.copy(
|
||||
password = form.password.map(pbkdf2_sha256).getOrElse(account.password),
|
||||
fullName = form.fullName,
|
||||
mailAddress = form.mailAddress,
|
||||
description = form.description,
|
||||
url = form.url
|
||||
)
|
||||
getAccountByUserName(userName).map { account =>
|
||||
updateAccount(
|
||||
account.copy(
|
||||
password = form.password.map(pbkdf2_sha256).getOrElse(account.password),
|
||||
fullName = form.fullName,
|
||||
mailAddress = form.mailAddress,
|
||||
description = form.description,
|
||||
url = form.url
|
||||
)
|
||||
)
|
||||
|
||||
updateImage(userName, form.fileId, form.clearImage)
|
||||
updateAccountExtraMailAddresses(userName, form.extraMailAddresses.filter(_ != ""))
|
||||
flash.update("info", "Account information has been updated.")
|
||||
redirect(s"/${userName}/_edit")
|
||||
updateImage(userName, form.fileId, form.clearImage)
|
||||
updateAccountExtraMailAddresses(userName, form.extraMailAddresses.filter(_ != ""))
|
||||
flash.update("info", "Account information has been updated.")
|
||||
redirect(s"/$userName/_edit")
|
||||
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
@@ -353,12 +346,11 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
get("/:userName/_delete")(oneselfOnly {
|
||||
val userName = params("userName")
|
||||
|
||||
getAccountByUserName(userName, true).map {
|
||||
account =>
|
||||
if (isLastAdministrator(account)) {
|
||||
flash.update("error", "Account can't be removed because this is last one administrator.")
|
||||
redirect(s"/${userName}/_edit")
|
||||
} else {
|
||||
getAccountByUserName(userName, includeRemoved = true).map { account =>
|
||||
if (isLastAdministrator(account)) {
|
||||
flash.update("error", "Account can't be removed because this is last one administrator.")
|
||||
redirect(s"/$userName/_edit")
|
||||
} else {
|
||||
// // Remove repositories
|
||||
// getRepositoryNamesOfUser(userName).foreach { repositoryName =>
|
||||
// deleteRepository(userName, repositoryName)
|
||||
@@ -366,10 +358,10 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
// FileUtils.deleteDirectory(getWikiRepositoryDir(userName, repositoryName))
|
||||
// FileUtils.deleteDirectory(getTemporaryDir(userName, repositoryName))
|
||||
// }
|
||||
suspendAccount(account)
|
||||
session.invalidate
|
||||
redirect("/")
|
||||
}
|
||||
suspendAccount(account)
|
||||
session.invalidate()
|
||||
redirect("/")
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
|
||||
@@ -383,20 +375,20 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
post("/:userName/_ssh", sshKeyForm)(oneselfOnly { form =>
|
||||
val userName = params("userName")
|
||||
addPublicKey(userName, form.title, form.publicKey)
|
||||
redirect(s"/${userName}/_ssh")
|
||||
redirect(s"/$userName/_ssh")
|
||||
})
|
||||
|
||||
get("/:userName/_ssh/delete/:id")(oneselfOnly {
|
||||
val userName = params("userName")
|
||||
val sshKeyId = params("id").toInt
|
||||
deletePublicKey(userName, sshKeyId)
|
||||
redirect(s"/${userName}/_ssh")
|
||||
redirect(s"/$userName/_ssh")
|
||||
})
|
||||
|
||||
get("/:userName/_gpg")(oneselfOnly {
|
||||
val userName = params("userName")
|
||||
getAccountByUserName(userName).map { x =>
|
||||
//html.ssh(x, getPublicKeys(x.userName))
|
||||
// html.ssh(x, getPublicKeys(x.userName))
|
||||
html.gpg(x, getGpgPublicKeys(x.userName))
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
@@ -404,14 +396,14 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
post("/:userName/_gpg", gpgKeyForm)(oneselfOnly { form =>
|
||||
val userName = params("userName")
|
||||
addGpgPublicKey(userName, form.title, form.publicKey)
|
||||
redirect(s"/${userName}/_gpg")
|
||||
redirect(s"/$userName/_gpg")
|
||||
})
|
||||
|
||||
get("/:userName/_gpg/delete/:id")(oneselfOnly {
|
||||
val userName = params("userName")
|
||||
val keyId = params("id").toInt
|
||||
deleteGpgPublicKey(userName, keyId)
|
||||
redirect(s"/${userName}/_gpg")
|
||||
redirect(s"/$userName/_gpg")
|
||||
})
|
||||
|
||||
get("/:userName/_application")(oneselfOnly {
|
||||
@@ -419,13 +411,12 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
getAccountByUserName(userName).map { x =>
|
||||
var tokens = getAccessTokens(x.userName)
|
||||
val generatedToken = flash.get("generatedToken") match {
|
||||
case Some((tokenId: Int, token: String)) => {
|
||||
case Some((tokenId: Int, token: String)) =>
|
||||
val gt = tokens.find(_.accessTokenId == tokenId)
|
||||
gt.map { t =>
|
||||
tokens = tokens.filterNot(_ == t)
|
||||
(t, token)
|
||||
}
|
||||
}
|
||||
case _ => None
|
||||
}
|
||||
html.application(x, tokens, generatedToken)
|
||||
@@ -434,18 +425,18 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
|
||||
post("/:userName/_personalToken", personalTokenForm)(oneselfOnly { form =>
|
||||
val userName = params("userName")
|
||||
getAccountByUserName(userName).foreach { x =>
|
||||
getAccountByUserName(userName).foreach { _ =>
|
||||
val (tokenId, token) = generateAccessToken(userName, form.note)
|
||||
flash.update("generatedToken", (tokenId, token))
|
||||
}
|
||||
redirect(s"/${userName}/_application")
|
||||
redirect(s"/$userName/_application")
|
||||
})
|
||||
|
||||
get("/:userName/_personalToken/delete/:id")(oneselfOnly {
|
||||
val userName = params("userName")
|
||||
val tokenId = params("id").toInt
|
||||
deleteAccessToken(userName, tokenId)
|
||||
redirect(s"/${userName}/_application")
|
||||
redirect(s"/$userName/_application")
|
||||
})
|
||||
|
||||
/**
|
||||
@@ -468,7 +459,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
post("/:userName/_preferences/highlighter", syntaxHighlighterThemeForm)(oneselfOnly { form =>
|
||||
val userName = params("userName")
|
||||
addOrUpdateAccountPreference(userName, form.theme)
|
||||
redirect(s"/${userName}/_preferences")
|
||||
redirect(s"/$userName/_preferences")
|
||||
})
|
||||
|
||||
get("/:userName/_hooks")(managersOnly {
|
||||
@@ -485,7 +476,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
val userName = params("userName")
|
||||
getAccountByUserName(userName).map { account =>
|
||||
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()
|
||||
})
|
||||
|
||||
@@ -496,7 +487,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
val userName = params("userName")
|
||||
addAccountWebHook(userName, form.url, form.events, form.ctype, form.token)
|
||||
flash.update("info", s"Webhook ${form.url} created")
|
||||
redirect(s"/${userName}/_hooks")
|
||||
redirect(s"/$userName/_hooks")
|
||||
})
|
||||
|
||||
/**
|
||||
@@ -506,7 +497,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
val userName = params("userName")
|
||||
deleteAccountWebHook(userName, params("url"))
|
||||
flash.update("info", s"Webhook ${params("url")} deleted")
|
||||
redirect(s"/${userName}/_hooks")
|
||||
redirect(s"/$userName/_hooks")
|
||||
})
|
||||
|
||||
/**
|
||||
@@ -515,9 +506,8 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
get("/:userName/_hooks/edit")(managersOnly {
|
||||
val userName = params("userName")
|
||||
getAccountByUserName(userName).flatMap { account =>
|
||||
getAccountWebHook(userName, params("url")).map {
|
||||
case (webhook, events) =>
|
||||
html.edithook(webhook, events, account, false)
|
||||
getAccountWebHook(userName, params("url")).map { case (webhook, events) =>
|
||||
html.edithook(webhook, events, account, create = false)
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
@@ -529,7 +519,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
val userName = params("userName")
|
||||
updateAccountWebHook(userName, form.url, form.events, form.ctype, form.token)
|
||||
flash.update("info", s"webhook ${form.url} updated")
|
||||
redirect(s"/${userName}/_hooks")
|
||||
redirect(s"/$userName/_hooks")
|
||||
})
|
||||
|
||||
/**
|
||||
@@ -537,8 +527,8 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
*/
|
||||
ajaxPost("/:userName/_hooks/test")(managersOnly {
|
||||
// TODO Is it possible to merge with [[RepositorySettingsController.ajaxPost]]?
|
||||
import scala.concurrent.duration._
|
||||
import scala.concurrent._
|
||||
import scala.concurrent.duration.*
|
||||
import scala.concurrent.*
|
||||
import scala.util.control.NonFatal
|
||||
import org.apache.http.util.EntityUtils
|
||||
import scala.concurrent.ExecutionContext.Implicits.global
|
||||
@@ -562,10 +552,10 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
callWebHook(WebHook.Push, List(dummyWebHookInfo), dummyPayload, context.settings).head
|
||||
|
||||
val toErrorMap: PartialFunction[Throwable, Map[String, String]] = {
|
||||
case e: java.net.UnknownHostException => Map("error" -> ("Unknown host " + e.getMessage))
|
||||
case e: java.lang.IllegalArgumentException => Map("error" -> ("invalid url"))
|
||||
case e: org.apache.http.client.ClientProtocolException => Map("error" -> ("invalid url"))
|
||||
case NonFatal(e) => Map("error" -> (s"${e.getClass} ${e.getMessage}"))
|
||||
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}")
|
||||
}
|
||||
|
||||
contentType = formats("json")
|
||||
@@ -574,11 +564,10 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
"url" -> url,
|
||||
"request" -> Await.result(
|
||||
reqFuture
|
||||
.map(
|
||||
req =>
|
||||
Map(
|
||||
"headers" -> _headers(req.getAllHeaders),
|
||||
"payload" -> json
|
||||
.map(req =>
|
||||
Map(
|
||||
"headers" -> _headers(req.getAllHeaders),
|
||||
"payload" -> json
|
||||
)
|
||||
)
|
||||
.recover(toErrorMap),
|
||||
@@ -586,12 +575,11 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
),
|
||||
"response" -> Await.result(
|
||||
resFuture
|
||||
.map(
|
||||
res =>
|
||||
Map(
|
||||
"status" -> res.getStatusLine(),
|
||||
"body" -> EntityUtils.toString(res.getEntity()),
|
||||
"headers" -> _headers(res.getAllHeaders())
|
||||
.map(res =>
|
||||
Map(
|
||||
"status" -> res.getStatusLine,
|
||||
"body" -> EntityUtils.toString(res.getEntity),
|
||||
"headers" -> _headers(res.getAllHeaders)
|
||||
)
|
||||
)
|
||||
.recover(toErrorMap),
|
||||
@@ -602,7 +590,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
})
|
||||
|
||||
get("/register") {
|
||||
if (context.settings.allowAccountRegistration) {
|
||||
if (context.settings.basicBehavior.allowAccountRegistration) {
|
||||
if (context.loginAccount.isDefined) {
|
||||
redirect("/")
|
||||
} else {
|
||||
@@ -612,25 +600,82 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
}
|
||||
|
||||
post("/register", newForm) { form =>
|
||||
if (context.settings.allowAccountRegistration) {
|
||||
if (context.settings.basicBehavior.allowAccountRegistration) {
|
||||
createAccount(
|
||||
form.userName,
|
||||
pbkdf2_sha256(form.password),
|
||||
form.fullName,
|
||||
form.mailAddress,
|
||||
false,
|
||||
isAdmin = false,
|
||||
form.description,
|
||||
form.url
|
||||
)
|
||||
updateImage(form.userName, form.fileId, false)
|
||||
updateImage(form.userName, form.fileId, clearImage = false)
|
||||
updateAccountExtraMailAddresses(form.userName, form.extraMailAddresses.filter(_ != ""))
|
||||
redirect("/signin")
|
||||
} else NotFound()
|
||||
}
|
||||
|
||||
get("/reset") {
|
||||
if (context.settings.basicBehavior.allowResetPassword) {
|
||||
html.reset()
|
||||
} else NotFound()
|
||||
}
|
||||
|
||||
post("/reset", resetPasswordEmailForm) { form =>
|
||||
if (context.settings.basicBehavior.allowResetPassword) {
|
||||
getAccountByMailAddress(form.mailAddress).foreach { account =>
|
||||
val token = generateResetPasswordToken(form.mailAddress)
|
||||
val mailer = new Mailer(context.settings)
|
||||
mailer.send(
|
||||
form.mailAddress,
|
||||
"Reset password",
|
||||
s"""Hello, ${account.fullName}!
|
||||
|
|
||||
|You requested to reset the password for your GitBucket account.
|
||||
|If you are not sure about the request, you can ignore this email.
|
||||
|Otherwise, click the following link to set the new password:
|
||||
|${context.baseUrl}/reset/form/$token
|
||||
|""".stripMargin
|
||||
)
|
||||
}
|
||||
redirect("/reset/sent")
|
||||
} else NotFound()
|
||||
}
|
||||
|
||||
get("/reset/sent") {
|
||||
if (context.settings.basicBehavior.allowResetPassword) {
|
||||
html.resetsent()
|
||||
} else NotFound()
|
||||
}
|
||||
|
||||
get("/reset/form/:token") {
|
||||
if (context.settings.basicBehavior.allowResetPassword) {
|
||||
val token = params("token")
|
||||
decodeResetPasswordToken(token)
|
||||
.map { _ =>
|
||||
html.resetform(token)
|
||||
}
|
||||
.getOrElse(NotFound())
|
||||
} else NotFound()
|
||||
}
|
||||
|
||||
post("/reset/form", resetPasswordForm) { form =>
|
||||
if (context.settings.basicBehavior.allowResetPassword) {
|
||||
decodeResetPasswordToken(form.token)
|
||||
.flatMap { mailAddress =>
|
||||
getAccountByMailAddress(mailAddress).map { account =>
|
||||
updateAccount(account.copy(password = pbkdf2_sha256(form.password)))
|
||||
html.resetcomplete()
|
||||
}
|
||||
}
|
||||
.getOrElse(NotFound())
|
||||
} else NotFound()
|
||||
}
|
||||
|
||||
get("/groups/new")(usersOnly {
|
||||
context.withLoginAccount { loginAccount =>
|
||||
html.creategroup(List(GroupMember("", loginAccount.userName, true)))
|
||||
html.creategroup(List(GroupMember("", loginAccount.userName, isManager = true)))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -647,13 +692,13 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
}
|
||||
.toList
|
||||
)
|
||||
updateImage(form.groupName, form.fileId, false)
|
||||
updateImage(form.groupName, form.fileId, clearImage = false)
|
||||
redirect(s"/${form.groupName}")
|
||||
})
|
||||
|
||||
get("/:groupName/_editgroup")(managersOnly {
|
||||
val groupName = params("groupName")
|
||||
getAccountByUserName(groupName, true).map { account =>
|
||||
getAccountByUserName(groupName, includeRemoved = true).map { account =>
|
||||
html.editgroup(account, getGroupMembers(groupName), flash.get("info"))
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
@@ -663,8 +708,8 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
// Remove from GROUP_MEMBER
|
||||
updateGroupMembers(groupName, Nil)
|
||||
// Disable group
|
||||
getAccountByUserName(groupName, false).foreach { account =>
|
||||
updateGroup(groupName, account.description, account.url, true)
|
||||
getAccountByUserName(groupName, includeRemoved = false).foreach { account =>
|
||||
updateGroup(groupName, account.description, account.url, removed = true)
|
||||
}
|
||||
// // Remove repositories
|
||||
// getRepositoryNamesOfUser(groupName).foreach { repositoryName =>
|
||||
@@ -687,8 +732,8 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
}
|
||||
.toList
|
||||
|
||||
getAccountByUserName(groupName, true).map { account =>
|
||||
updateGroup(groupName, form.description, form.url, false)
|
||||
getAccountByUserName(groupName, includeRemoved = true).map { _ =>
|
||||
updateGroup(groupName, form.description, form.url, removed = false)
|
||||
|
||||
// Update GROUP_MEMBER
|
||||
updateGroupMembers(form.groupName, members)
|
||||
@@ -703,7 +748,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
updateImage(form.groupName, form.fileId, form.clearImage)
|
||||
|
||||
flash.update("info", "Account information has been updated.")
|
||||
redirect(s"/${groupName}/_editgroup")
|
||||
redirect(s"/$groupName/_editgroup")
|
||||
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
@@ -713,7 +758,7 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
*/
|
||||
get("/new")(usersOnly {
|
||||
context.withLoginAccount { loginAccount =>
|
||||
html.newrepo(getGroupsByUserName(loginAccount.userName), context.settings.isCreateRepoOptionPublic)
|
||||
html.newrepo(getGroupsByUserName(loginAccount.userName), context.settings.basicBehavior.isCreateRepoOptionPublic)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -721,82 +766,83 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
* Create new repository.
|
||||
*/
|
||||
post("/new", newRepositoryForm)(usersOnly { form =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
if (context.settings.repositoryOperation.create || loginAccount.isAdmin) {
|
||||
LockUtil.lock(s"${form.owner}/${form.name}") {
|
||||
if (getRepository(form.owner, form.name).isDefined) {
|
||||
// redirect to the repository if repository already exists
|
||||
redirect(s"/${form.owner}/${form.name}")
|
||||
} else if (!canCreateRepository(form.owner, loginAccount)) {
|
||||
// Permission error
|
||||
Forbidden()
|
||||
} else {
|
||||
// create repository asynchronously
|
||||
createRepository(
|
||||
loginAccount,
|
||||
form.owner,
|
||||
form.name,
|
||||
form.description,
|
||||
form.isPrivate,
|
||||
form.initOption,
|
||||
form.sourceUrl
|
||||
)
|
||||
// redirect to the repository
|
||||
redirect(s"/${form.owner}/${form.name}")
|
||||
}
|
||||
context.withLoginAccount { loginAccount =>
|
||||
if (context.settings.basicBehavior.repositoryOperation.create || loginAccount.isAdmin) {
|
||||
LockUtil.lock(s"${form.owner}/${form.name}") {
|
||||
if (getRepository(form.owner, form.name).isDefined) {
|
||||
// redirect to the repository if repository already exists
|
||||
redirect(s"/${form.owner}/${form.name}")
|
||||
} else if (!canCreateRepository(form.owner, loginAccount)) {
|
||||
// Permission error
|
||||
Forbidden()
|
||||
} else {
|
||||
// create repository asynchronously
|
||||
createRepository(
|
||||
loginAccount,
|
||||
form.owner,
|
||||
form.name,
|
||||
form.description,
|
||||
form.isPrivate,
|
||||
form.initOption,
|
||||
form.sourceUrl,
|
||||
context.settings.defaultBranch
|
||||
)
|
||||
// redirect to the repository
|
||||
redirect(s"/${form.owner}/${form.name}")
|
||||
}
|
||||
} else Forbidden()
|
||||
}
|
||||
} else Forbidden()
|
||||
}
|
||||
})
|
||||
|
||||
get("/:owner/:repository/fork")(readableUsersOnly { repository =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
if (repository.repository.options.allowFork && (context.settings.repositoryOperation.fork || loginAccount.isAdmin)) {
|
||||
val loginUserName = loginAccount.userName
|
||||
val groups = getGroupsByUserName(loginUserName)
|
||||
groups match {
|
||||
case _: List[String] =>
|
||||
val managerPermissions = groups.map { group =>
|
||||
val members = getGroupMembers(group)
|
||||
context.loginAccount.exists(
|
||||
x =>
|
||||
members.exists { member =>
|
||||
member.userName == x.userName && member.isManager
|
||||
}
|
||||
)
|
||||
}
|
||||
helper.html.forkrepository(
|
||||
repository,
|
||||
(groups zip managerPermissions).sortBy(_._1)
|
||||
context.withLoginAccount { loginAccount =>
|
||||
if (
|
||||
repository.repository.options.allowFork && (context.settings.basicBehavior.repositoryOperation.fork || loginAccount.isAdmin)
|
||||
) {
|
||||
val loginUserName = loginAccount.userName
|
||||
val groups = getGroupsByUserName(loginUserName)
|
||||
groups match {
|
||||
case _: List[String] =>
|
||||
val managerPermissions = groups.map { group =>
|
||||
val members = getGroupMembers(group)
|
||||
context.loginAccount.exists(x =>
|
||||
members.exists { member =>
|
||||
member.userName == x.userName && member.isManager
|
||||
}
|
||||
)
|
||||
case _ => redirect(s"/${loginUserName}")
|
||||
}
|
||||
} else BadRequest()
|
||||
}
|
||||
helper.html.forkrepository(
|
||||
repository,
|
||||
(groups zip managerPermissions).sortBy(_._1)
|
||||
)
|
||||
case _ => redirect(s"/$loginUserName")
|
||||
}
|
||||
} else BadRequest()
|
||||
}
|
||||
})
|
||||
|
||||
post("/:owner/:repository/fork", accountForm)(readableUsersOnly { (form, repository) =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
if (repository.repository.options.allowFork && (context.settings.repositoryOperation.fork || loginAccount.isAdmin)) {
|
||||
val loginUserName = loginAccount.userName
|
||||
val accountName = form.accountName
|
||||
context.withLoginAccount { loginAccount =>
|
||||
if (
|
||||
repository.repository.options.allowFork && (context.settings.basicBehavior.repositoryOperation.fork || loginAccount.isAdmin)
|
||||
) {
|
||||
val loginUserName = loginAccount.userName
|
||||
val accountName = form.accountName
|
||||
|
||||
if (getRepository(accountName, repository.name).isDefined) {
|
||||
// redirect to the repository if repository already exists
|
||||
redirect(s"/${accountName}/${repository.name}")
|
||||
} else if (!canCreateRepository(accountName, loginAccount)) {
|
||||
// Permission error
|
||||
Forbidden()
|
||||
} else {
|
||||
// fork repository asynchronously
|
||||
forkRepository(accountName, repository, loginUserName)
|
||||
// redirect to the repository
|
||||
redirect(s"/${accountName}/${repository.name}")
|
||||
}
|
||||
} else Forbidden()
|
||||
if (getRepository(accountName, repository.name).isDefined) {
|
||||
// redirect to the repository if repository already exists
|
||||
redirect(s"/$accountName/${repository.name}")
|
||||
} else if (!canCreateRepository(accountName, loginAccount)) {
|
||||
// Permission error
|
||||
Forbidden()
|
||||
} else {
|
||||
// fork repository asynchronously
|
||||
forkRepository(accountName, repository, loginUserName)
|
||||
// redirect to the repository
|
||||
redirect(s"/$accountName/${repository.name}")
|
||||
}
|
||||
} else Forbidden()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -823,9 +869,11 @@ trait AccountControllerBase extends AccountManagementControllerBase {
|
||||
|
||||
private def members: Constraint = new Constraint() {
|
||||
override def validate(name: String, value: String, messages: Messages): Option[String] = {
|
||||
if (value.split(",").exists {
|
||||
_.split(":") match { case Array(userName, isManager) => isManager.toBoolean }
|
||||
}) None
|
||||
if (
|
||||
value.split(",").exists {
|
||||
_.split(":") match { case Array(userName, isManager) => isManager.toBoolean }
|
||||
}
|
||||
) None
|
||||
else Some("Must select one manager at least.")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package gitbucket.core.controller
|
||||
|
||||
import gitbucket.core.api._
|
||||
import gitbucket.core.controller.api._
|
||||
import gitbucket.core.service._
|
||||
import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.util._
|
||||
import gitbucket.core.api.*
|
||||
import gitbucket.core.controller.api.*
|
||||
import gitbucket.core.service.*
|
||||
import gitbucket.core.util.Implicits.*
|
||||
import gitbucket.core.util.*
|
||||
import gitbucket.core.plugin.PluginRegistry
|
||||
|
||||
class ApiController
|
||||
|
||||
@@ -1,22 +1,21 @@
|
||||
package gitbucket.core.controller
|
||||
|
||||
import java.io.{File, FileInputStream}
|
||||
|
||||
import java.io.{File, FileInputStream, FileOutputStream}
|
||||
import gitbucket.core.api.{ApiError, JsonFormat}
|
||||
import gitbucket.core.model.Account
|
||||
import gitbucket.core.service.{AccountService, RepositoryService, SystemSettingsService}
|
||||
import gitbucket.core.util.SyntaxSugars._
|
||||
import gitbucket.core.util.Directory._
|
||||
import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.util._
|
||||
import org.json4s._
|
||||
import org.scalatra._
|
||||
import org.scalatra.i18n._
|
||||
import org.scalatra.json._
|
||||
import org.scalatra.forms._
|
||||
import gitbucket.core.util.SyntaxSugars.*
|
||||
import gitbucket.core.util.Directory.*
|
||||
import gitbucket.core.util.Implicits.*
|
||||
import gitbucket.core.util.*
|
||||
import org.json4s.*
|
||||
import org.scalatra.{MultiParams, *}
|
||||
import org.scalatra.i18n.*
|
||||
import org.scalatra.json.*
|
||||
import org.scalatra.forms.*
|
||||
|
||||
import javax.servlet.http.{HttpServletRequest, HttpServletResponse}
|
||||
import javax.servlet.{FilterChain, ServletRequest, ServletResponse}
|
||||
|
||||
import is.tagomor.woothee.Classifier
|
||||
|
||||
import scala.util.Try
|
||||
@@ -25,10 +24,13 @@ import net.coobird.thumbnailator.Thumbnails
|
||||
import org.eclipse.jgit.api.Git
|
||||
import org.eclipse.jgit.lib.ObjectId
|
||||
import org.eclipse.jgit.revwalk.RevCommit
|
||||
import org.eclipse.jgit.treewalk._
|
||||
import org.eclipse.jgit.treewalk.*
|
||||
import org.apache.commons.io.IOUtils
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.json4s.Formats
|
||||
import org.json4s.jackson.Serialization
|
||||
|
||||
import java.nio.charset.StandardCharsets
|
||||
|
||||
/**
|
||||
* Provides generic features for controller implementations.
|
||||
@@ -46,11 +48,21 @@ abstract class ControllerBase
|
||||
|
||||
implicit val jsonFormats: Formats = gitbucket.core.api.JsonFormat.jsonFormats
|
||||
|
||||
private case class HttpException(status: Int) extends RuntimeException
|
||||
|
||||
before("/api/v3/*") {
|
||||
contentType = formats("json")
|
||||
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 = {
|
||||
val path = super.requestPath(uri, idx)
|
||||
if (path != "/" && path.endsWith("/")) {
|
||||
@@ -84,17 +96,24 @@ abstract class ControllerBase
|
||||
*/
|
||||
implicit def context: Context = {
|
||||
contextCache.get match {
|
||||
case null => {
|
||||
case null =>
|
||||
val context = Context(loadSystemSettings(), LoginAccount, request)
|
||||
contextCache.set(context)
|
||||
context
|
||||
}
|
||||
case context => context
|
||||
}
|
||||
}
|
||||
|
||||
private def LoginAccount: Option[Account] =
|
||||
request.getAs[Account](Keys.Session.LoginAccount).orElse(session.getAs[Account](Keys.Session.LoginAccount))
|
||||
private def LoginAccount: Option[Account] = {
|
||||
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 =
|
||||
super.get(path) {
|
||||
@@ -120,7 +139,7 @@ abstract class ControllerBase
|
||||
action(form)
|
||||
}
|
||||
|
||||
protected def NotFound() =
|
||||
protected def NotFound(): ActionResult =
|
||||
if (request.hasAttribute(Keys.Request.Ajax)) {
|
||||
org.scalatra.NotFound()
|
||||
} 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)) {
|
||||
org.scalatra.Unauthorized()
|
||||
} else if (request.hasAttribute(Keys.Request.APIv3)) {
|
||||
@@ -168,7 +187,9 @@ abstract class ControllerBase
|
||||
}
|
||||
|
||||
error {
|
||||
case e => {
|
||||
case e: HttpException =>
|
||||
ActionResult(e.status, (), Map.empty)
|
||||
case e =>
|
||||
logger.error(s"Catch unhandled error in request: ${request}", e)
|
||||
if (request.hasAttribute(Keys.Request.Ajax)) {
|
||||
org.scalatra.InternalServerError()
|
||||
@@ -178,7 +199,6 @@ abstract class ControllerBase
|
||||
} else {
|
||||
org.scalatra.InternalServerError(gitbucket.core.html.error("Internal Server Error", Some(e)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override def url(
|
||||
@@ -190,7 +210,7 @@ abstract class ControllerBase
|
||||
withSessionId: Boolean = true
|
||||
)(implicit request: HttpServletRequest, response: HttpServletResponse): String =
|
||||
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.
|
||||
@@ -234,9 +254,9 @@ abstract class ControllerBase
|
||||
protected def getPathObjectId(git: Git, path: String, revCommit: RevCommit): Option[ObjectId] = {
|
||||
@scala.annotation.tailrec
|
||||
def _getPathObjectId(path: String, walk: TreeWalk): Option[ObjectId] = walk.next match {
|
||||
case true if (walk.getPathString == path) => Some(walk.getObjectId(0))
|
||||
case true => _getPathObjectId(path, walk)
|
||||
case false => None
|
||||
case true if walk.getPathString == path => Some(walk.getObjectId(0))
|
||||
case true => _getPathObjectId(path, walk)
|
||||
case false => None
|
||||
}
|
||||
|
||||
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],
|
||||
request: HttpServletRequest
|
||||
) {
|
||||
val path = settings.baseUrl.getOrElse(request.getContextPath)
|
||||
val currentPath = request.getRequestURI.substring(request.getContextPath.length)
|
||||
val baseUrl = settings.baseUrl(request)
|
||||
val host = new java.net.URL(baseUrl).getHost
|
||||
val platform = request.getHeader("User-Agent") match {
|
||||
val path: String = settings.baseUrl.getOrElse(request.getContextPath)
|
||||
val currentPath: String = request.getRequestURI.substring(request.getContextPath.length)
|
||||
val baseUrl: String = settings.baseUrl(request)
|
||||
val host: String = new java.net.URI(baseUrl).toURL.getHost
|
||||
val platform: String = request.getHeader("User-Agent") match {
|
||||
case null => null
|
||||
case agent if agent.contains("Mac") => "mac"
|
||||
case agent if agent.contains("Linux") => "linux"
|
||||
case agent if agent.contains("Win") => "windows"
|
||||
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 = {
|
||||
loginAccount match {
|
||||
@@ -372,15 +433,16 @@ trait AccountManagementControllerBase extends ControllerBase {
|
||||
messages: Messages
|
||||
): Option[String] = {
|
||||
val extraMailAddresses = params.view.filterKeys(k => k.startsWith("extraMailAddresses"))
|
||||
if (extraMailAddresses.exists {
|
||||
case (k, v) =>
|
||||
v.contains(value)
|
||||
}) {
|
||||
if (
|
||||
extraMailAddresses.exists { case (k, v) =>
|
||||
v.contains(value)
|
||||
}
|
||||
) {
|
||||
Some("These mail addresses are duplicated.")
|
||||
} else {
|
||||
getAccountByMailAddress(value, true)
|
||||
getAccountByMailAddress(value, includeRemoved = true)
|
||||
.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."
|
||||
}
|
||||
}
|
||||
@@ -395,22 +457,23 @@ trait AccountManagementControllerBase extends ControllerBase {
|
||||
messages: Messages
|
||||
): Option[String] = {
|
||||
val extraMailAddresses = params.view.filterKeys(k => k.startsWith("extraMailAddresses"))
|
||||
if (Some(value) == params.optionValue("mailAddress") || extraMailAddresses.count {
|
||||
case (k, v) =>
|
||||
v.contains(value)
|
||||
} > 1) {
|
||||
if (
|
||||
params.optionValue("mailAddress").contains(value) || extraMailAddresses.count { case (k, v) =>
|
||||
v.contains(value)
|
||||
} > 1
|
||||
) {
|
||||
Some("These mail addresses are duplicated.")
|
||||
} else {
|
||||
getAccountByMailAddress(value, true)
|
||||
getAccountByMailAddress(value, includeRemoved = true)
|
||||
.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."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val allReservedNames = Set(
|
||||
private val allReservedNames = Set(
|
||||
"git",
|
||||
"admin",
|
||||
"upload",
|
||||
@@ -429,10 +492,9 @@ trait AccountManagementControllerBase extends ControllerBase {
|
||||
protected def reservedNames: Constraint = new Constraint() {
|
||||
override def validate(name: String, value: String, messages: Messages): Option[String] =
|
||||
if (allReservedNames.contains(value.toLowerCase)) {
|
||||
Some(s"${value} is reserved")
|
||||
Some(s"$value is reserved")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2,10 +2,11 @@ package gitbucket.core.controller
|
||||
|
||||
import gitbucket.core.dashboard.html
|
||||
import gitbucket.core.model.Account
|
||||
import gitbucket.core.service._
|
||||
import gitbucket.core.util.{Keys, UsersAuthenticator}
|
||||
import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.service.IssuesService._
|
||||
import gitbucket.core.service.*
|
||||
import gitbucket.core.util.UsersAuthenticator
|
||||
import gitbucket.core.util.Implicits.*
|
||||
import gitbucket.core.service.IssuesService.*
|
||||
import gitbucket.core.service.ActivityService.*
|
||||
|
||||
class DashboardController
|
||||
extends DashboardControllerBase
|
||||
@@ -27,12 +28,8 @@ class DashboardController
|
||||
with RequestCache
|
||||
|
||||
trait DashboardControllerBase extends ControllerBase {
|
||||
self: IssuesService
|
||||
with PullRequestService
|
||||
with RepositoryService
|
||||
with AccountService
|
||||
with CommitStatusService
|
||||
with UsersAuthenticator =>
|
||||
self: IssuesService & PullRequestService & RepositoryService & AccountService & CommitStatusService &
|
||||
UsersAuthenticator =>
|
||||
|
||||
get("/dashboard/repos")(usersOnly {
|
||||
context.withLoginAccount { loginAccount =>
|
||||
@@ -40,9 +37,9 @@ trait DashboardControllerBase extends ControllerBase {
|
||||
context.loginAccount,
|
||||
None,
|
||||
withoutPhysicalInfo = true,
|
||||
limit = context.settings.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)
|
||||
|
||||
filter match {
|
||||
@@ -105,19 +102,19 @@ trait DashboardControllerBase extends ControllerBase {
|
||||
}
|
||||
|
||||
private def searchIssues(loginAccount: Account, filter: String) = {
|
||||
import IssuesService._
|
||||
import IssuesService.*
|
||||
|
||||
val userName = loginAccount.userName
|
||||
val condition = getOrCreateCondition(Keys.Session.DashboardIssues, filter, userName)
|
||||
val userRepos = getUserRepositories(userName, true).map(repo => repo.owner -> repo.name)
|
||||
val condition = getOrCreateCondition(filter, userName)
|
||||
val userRepos = getUserRepositories(userName, withoutPhysicalInfo = true).map(repo => repo.owner -> repo.name)
|
||||
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(
|
||||
issues.map(issue => (issue, None)),
|
||||
page,
|
||||
countIssue(condition.copy(state = "open"), IssueSearchOption.Issues, userRepos: _*),
|
||||
countIssue(condition.copy(state = "closed"), IssueSearchOption.Issues, userRepos: _*),
|
||||
countIssue(condition.copy(state = "open"), IssueSearchOption.Issues, userRepos*),
|
||||
countIssue(condition.copy(state = "closed"), IssueSearchOption.Issues, userRepos*),
|
||||
filter match {
|
||||
case "assigned" => condition.copy(assigned = Some(Some(userName)))
|
||||
case "mentioned" => condition.copy(mentioned = Some(userName))
|
||||
@@ -129,17 +126,18 @@ trait DashboardControllerBase extends ControllerBase {
|
||||
context.loginAccount,
|
||||
None,
|
||||
withoutPhysicalInfo = true,
|
||||
limit = context.settings.limitVisibleRepositories
|
||||
)
|
||||
limit = context.settings.basicBehavior.limitVisibleRepositories
|
||||
),
|
||||
isNewsFeedEnabled
|
||||
)
|
||||
}
|
||||
|
||||
private def searchPullRequests(loginAccount: Account, filter: String) = {
|
||||
import IssuesService._
|
||||
import PullRequestService._
|
||||
import IssuesService.*
|
||||
import PullRequestService.*
|
||||
|
||||
val userName = loginAccount.userName
|
||||
val condition = getOrCreateCondition(Keys.Session.DashboardPulls, filter, userName)
|
||||
val condition = getOrCreateCondition(filter, userName)
|
||||
val allRepos = getAllRepositories(userName)
|
||||
val page = IssueSearchCondition.page(request)
|
||||
val issues = searchIssue(
|
||||
@@ -147,7 +145,7 @@ trait DashboardControllerBase extends ControllerBase {
|
||||
IssueSearchOption.PullRequests,
|
||||
(page - 1) * PullRequestLimit,
|
||||
PullRequestLimit,
|
||||
allRepos: _*
|
||||
allRepos*
|
||||
)
|
||||
val status = issues.map { issue =>
|
||||
issue.commitId.flatMap { commitId =>
|
||||
@@ -158,8 +156,8 @@ trait DashboardControllerBase extends ControllerBase {
|
||||
html.pulls(
|
||||
issues.zip(status),
|
||||
page,
|
||||
countIssue(condition.copy(state = "open"), IssueSearchOption.PullRequests, allRepos: _*),
|
||||
countIssue(condition.copy(state = "closed"), IssueSearchOption.PullRequests, allRepos: _*),
|
||||
countIssue(condition.copy(state = "open"), IssueSearchOption.PullRequests, allRepos*),
|
||||
countIssue(condition.copy(state = "closed"), IssueSearchOption.PullRequests, allRepos*),
|
||||
filter match {
|
||||
case "assigned" => condition.copy(assigned = Some(Some(userName)))
|
||||
case "mentioned" => condition.copy(mentioned = Some(userName))
|
||||
@@ -171,8 +169,9 @@ trait DashboardControllerBase extends ControllerBase {
|
||||
context.loginAccount,
|
||||
None,
|
||||
withoutPhysicalInfo = true,
|
||||
limit = context.settings.limitVisibleRepositories
|
||||
)
|
||||
limit = context.settings.basicBehavior.limitVisibleRepositories
|
||||
),
|
||||
isNewsFeedEnabled
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -75,59 +75,57 @@ class FileUploadController
|
||||
post("/wiki/:owner/:repository") {
|
||||
setMultipartConfig()
|
||||
// Don't accept not logged-in users
|
||||
session.get(Keys.Session.LoginAccount).collect {
|
||||
case loginAccount: Account =>
|
||||
val owner = params("owner")
|
||||
val repository = params("repository")
|
||||
session.get(Keys.Session.LoginAccount).collect { case loginAccount: Account =>
|
||||
val owner = params("owner")
|
||||
val repository = params("repository")
|
||||
|
||||
// Check whether logged-in user is collaborator
|
||||
onlyWikiEditable(owner, repository, loginAccount) {
|
||||
execute(
|
||||
{ (file, fileId) =>
|
||||
val fileName = file.getName
|
||||
LockUtil.lock(s"${owner}/${repository}/wiki") {
|
||||
Using.resource(Git.open(Directory.getWikiRepositoryDir(owner, repository))) {
|
||||
git =>
|
||||
val builder = DirCache.newInCore.builder()
|
||||
val inserter = git.getRepository.newObjectInserter()
|
||||
val headId = git.getRepository.resolve(Constants.HEAD + "^{commit}")
|
||||
// Check whether logged-in user is collaborator
|
||||
onlyWikiEditable(owner, repository, loginAccount) {
|
||||
execute(
|
||||
{ (file, fileId) =>
|
||||
val fileName = file.getName
|
||||
LockUtil.lock(s"$owner/$repository/wiki") {
|
||||
Using.resource(Git.open(Directory.getWikiRepositoryDir(owner, repository))) { git =>
|
||||
val builder = DirCache.newInCore.builder()
|
||||
val inserter = git.getRepository.newObjectInserter()
|
||||
val headId = git.getRepository.resolve(Constants.HEAD + "^{commit}")
|
||||
|
||||
if (headId != null) {
|
||||
JGitUtil.processTree(git, headId) { (path, tree) =>
|
||||
if (path != fileName) {
|
||||
builder.add(JGitUtil.createDirCacheEntry(path, tree.getEntryFileMode, tree.getEntryObjectId))
|
||||
}
|
||||
}
|
||||
if (headId != null) {
|
||||
JGitUtil.processTree(git, headId) { (path, tree) =>
|
||||
if (path != fileName) {
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -135,32 +133,34 @@ class FileUploadController
|
||||
setMultipartConfigForLargeFile()
|
||||
session
|
||||
.get(Keys.Session.LoginAccount)
|
||||
.collect {
|
||||
case _: Account =>
|
||||
val owner = params("owner")
|
||||
val repository = params("repository")
|
||||
val tag = multiParams("splat").head
|
||||
execute(
|
||||
{ (file, fileId) =>
|
||||
FileUtils.writeByteArrayToFile(
|
||||
new File(getReleaseFilesDir(owner, repository), FileUtil.checkFilename(tag + "/" + fileId)),
|
||||
file.get()
|
||||
)
|
||||
},
|
||||
_ => true
|
||||
)
|
||||
.collect { case _: Account =>
|
||||
val owner = params("owner")
|
||||
val repository = params("repository")
|
||||
val tag = multiParams("splat").head
|
||||
execute(
|
||||
{ (file, fileId) =>
|
||||
FileUtils.writeByteArrayToFile(
|
||||
new File(getReleaseFilesDir(owner, repository), FileUtil.checkFilename(tag + "/" + fileId)),
|
||||
file.get()
|
||||
)
|
||||
},
|
||||
_ => true
|
||||
)
|
||||
}
|
||||
.getOrElse(BadRequest())
|
||||
}
|
||||
|
||||
post("/import") {
|
||||
import JDBCUtil._
|
||||
import JDBCUtil.*
|
||||
setMultipartConfig()
|
||||
session.get(Keys.Session.LoginAccount).collect {
|
||||
case loginAccount: Account if loginAccount.isAdmin =>
|
||||
execute({ (file, fileId) =>
|
||||
request2Session(request).conn.importAsSQL(file.getInputStream)
|
||||
}, _ => true)
|
||||
execute(
|
||||
{ (file, fileId) =>
|
||||
request2Session(request).conn.importAsSQL(file.getInputStream)
|
||||
},
|
||||
_ => true
|
||||
)
|
||||
}
|
||||
redirect("/admin/data")
|
||||
}
|
||||
@@ -168,13 +168,13 @@ class FileUploadController
|
||||
private def setMultipartConfig(): Unit = {
|
||||
val settings = loadSystemSettings()
|
||||
val config = MultipartConfig(maxFileSize = Some(settings.upload.maxFileSize))
|
||||
config.apply(request.getServletContext())
|
||||
config.apply(request.getServletContext)
|
||||
}
|
||||
|
||||
private def setMultipartConfigForLargeFile(): Unit = {
|
||||
val settings = loadSystemSettings()
|
||||
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 = {
|
||||
@@ -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 {
|
||||
case Some(file) if mimeTypeChecker(file.name) =>
|
||||
val fileId = FileUtil.generateFileId
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
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.openid.connect.sdk.Nonce
|
||||
import gitbucket.core.helper.xml
|
||||
import gitbucket.core.model.Account
|
||||
import gitbucket.core.service._
|
||||
import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.util._
|
||||
import gitbucket.core.view.helpers._
|
||||
import gitbucket.core.service.*
|
||||
import gitbucket.core.util.Implicits.*
|
||||
import gitbucket.core.util.*
|
||||
import gitbucket.core.view.helpers.*
|
||||
import org.scalatra.Ok
|
||||
import org.scalatra.forms._
|
||||
import org.scalatra.forms.*
|
||||
|
||||
import gitbucket.core.service.ActivityService.*
|
||||
|
||||
class IndexController
|
||||
extends IndexControllerBase
|
||||
@@ -31,19 +34,12 @@ class IndexController
|
||||
with RequestCache
|
||||
|
||||
trait IndexControllerBase extends ControllerBase {
|
||||
self: RepositoryService
|
||||
with ActivityService
|
||||
with AccountService
|
||||
with RepositorySearchService
|
||||
with UsersAuthenticator
|
||||
with ReferrerAuthenticator
|
||||
with AccessTokenService
|
||||
with AccountFederationService
|
||||
with OpenIDConnectService =>
|
||||
self: RepositoryService & ActivityService & AccountService & RepositorySearchService & UsersAuthenticator &
|
||||
ReferrerAuthenticator & AccessTokenService & AccountFederationService & 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))),
|
||||
"password" -> trim(label("Password", text(required))),
|
||||
"hash" -> trim(optional(text()))
|
||||
@@ -57,38 +53,53 @@ trait IndexControllerBase extends ControllerBase {
|
||||
//
|
||||
// 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("/") {
|
||||
context.loginAccount
|
||||
.map { account =>
|
||||
val visibleOwnerSet: Set[String] = Set(account.userName) ++ getGroupsByUserName(account.userName)
|
||||
gitbucket.core.html.index(
|
||||
getRecentActivitiesByOwners(visibleOwnerSet),
|
||||
getVisibleRepositories(
|
||||
// val visibleOwnerSet: Set[String] = Set(account.userName) ++ getGroupsByUserName(account.userName)
|
||||
if (!isNewsFeedEnabled) {
|
||||
redirect("/dashboard/repos")
|
||||
} else {
|
||||
val repos = getVisibleRepositories(
|
||||
Some(account),
|
||||
None,
|
||||
withoutPhysicalInfo = true,
|
||||
limit = context.settings.limitVisibleRepositories
|
||||
),
|
||||
showBannerToCreatePersonalAccessToken = hasAccountFederation(account.userName) && !hasAccessToken(
|
||||
account.userName
|
||||
limit = false
|
||||
)
|
||||
)
|
||||
|
||||
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 {
|
||||
gitbucket.core.html.index(
|
||||
getRecentPublicActivities(),
|
||||
getVisibleRepositories(None, withoutPhysicalInfo = true),
|
||||
showBannerToCreatePersonalAccessToken = false
|
||||
activities = getRecentPublicActivities(),
|
||||
recentRepositories = getVisibleRepositories(None, withoutPhysicalInfo = true),
|
||||
showBannerToCreatePersonalAccessToken = false,
|
||||
enableNewsFeed = isNewsFeedEnabled
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
get("/signin") {
|
||||
val redirect = params.get("redirect")
|
||||
if (redirect.isDefined && redirect.get.startsWith("/")) {
|
||||
flash.update(Keys.Flash.Redirect, redirect.get)
|
||||
if (context.loginAccount.nonEmpty) {
|
||||
redirect("/")
|
||||
}
|
||||
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"))
|
||||
}
|
||||
@@ -120,8 +131,8 @@ trait IndexControllerBase extends ControllerBase {
|
||||
case _ => "/"
|
||||
}
|
||||
session.setAttribute(
|
||||
Keys.Session.OidcContext,
|
||||
OidcContext(authenticationRequest.getState, authenticationRequest.getNonce, redirectBackURI)
|
||||
Keys.Session.OidcAuthContext,
|
||||
OidcAuthContext(authenticationRequest.getState, authenticationRequest.getNonce, redirectBackURI)
|
||||
)
|
||||
redirect(authenticationRequest.toURI.toString)
|
||||
} getOrElse {
|
||||
@@ -135,9 +146,10 @@ trait IndexControllerBase extends ControllerBase {
|
||||
get("/signin/oidc") {
|
||||
context.settings.oidc.map { oidc =>
|
||||
val redirectURI = new URI(s"$baseUrl/signin/oidc")
|
||||
session.get(Keys.Session.OidcContext) match {
|
||||
case Some(context: OidcContext) =>
|
||||
authenticate(params.toMap, redirectURI, context.state, context.nonce, oidc).map { account =>
|
||||
session.get(Keys.Session.OidcAuthContext) match {
|
||||
case Some(context: OidcAuthContext) =>
|
||||
authenticate(params.toMap, redirectURI, context.state, context.nonce, oidc).map { case (jwt, account) =>
|
||||
session.setAttribute(Keys.Session.OidcSessionContext, OidcSessionContext(jwt))
|
||||
signin(account, context.redirectBackURI)
|
||||
} orElse {
|
||||
flash.update("error", "Sorry, authentication failed. Please try again.")
|
||||
@@ -155,7 +167,18 @@ trait IndexControllerBase extends ControllerBase {
|
||||
}
|
||||
|
||||
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("/")
|
||||
}
|
||||
|
||||
@@ -173,11 +196,24 @@ trait IndexControllerBase extends ControllerBase {
|
||||
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.
|
||||
*/
|
||||
private def signin(account: Account, redirectUrl: String = "/") = {
|
||||
session.setAttribute(Keys.Session.LoginAccount, account)
|
||||
if (isDevFeatureEnabled(DevFeatures.KeepSession)) {
|
||||
saveLoginAccountToLocalFile(account)
|
||||
}
|
||||
updateLastLoginDate(account.userName)
|
||||
|
||||
if (LDAPUtil.isDummyMailAddress(account)) {
|
||||
@@ -200,8 +236,8 @@ trait IndexControllerBase extends ControllerBase {
|
||||
val group = params("group").toBoolean
|
||||
org.json4s.jackson.Serialization.write(
|
||||
Map(
|
||||
"options" -> (
|
||||
getAllUsers(false)
|
||||
"options" ->
|
||||
getAllUsers(includeRemoved = false)
|
||||
.withFilter { t =>
|
||||
(user, group) match {
|
||||
case (true, true) => true
|
||||
@@ -213,43 +249,54 @@ trait IndexControllerBase extends ControllerBase {
|
||||
.map { t =>
|
||||
Map(
|
||||
"label" -> s"${avatar(t.userName, 16)}<b>@${StringUtil.escapeHtml(
|
||||
StringUtil.cutTail(t.userName, 25, "...")
|
||||
)}</b> ${StringUtil
|
||||
.escapeHtml(StringUtil.cutTail(t.fullName, 25, "..."))}",
|
||||
StringUtil.cutTail(t.userName, 25, "...")
|
||||
)}</b> ${StringUtil
|
||||
.escapeHtml(StringUtil.cutTail(t.fullName, 25, "..."))}",
|
||||
"value" -> t.userName
|
||||
)
|
||||
}
|
||||
)
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
/**
|
||||
* JSON API for checking user or group existence.
|
||||
*
|
||||
* 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 {
|
||||
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 ""
|
||||
})
|
||||
|
||||
// TODO Move to RepositoryViewrController?
|
||||
// TODO Move to RepositoryViewerController?
|
||||
get("/:owner/:repository/search")(referrersOnly { repository =>
|
||||
val query = params.getOrElse("q", "").trim
|
||||
val target = params.getOrElse("type", "code")
|
||||
val page = try {
|
||||
val i = params.getOrElse("page", "1").toInt
|
||||
if (i <= 0) 1 else i
|
||||
} catch {
|
||||
case _: NumberFormatException => 1
|
||||
}
|
||||
val page =
|
||||
try {
|
||||
val i = params.getOrElse("page", "1").toInt
|
||||
if (i <= 0) 1 else i
|
||||
} catch {
|
||||
case _: NumberFormatException => 1
|
||||
}
|
||||
|
||||
target.toLowerCase match {
|
||||
case "issues" =>
|
||||
gitbucket.core.search.html.issues(
|
||||
if (query.nonEmpty) searchIssues(repository.owner, repository.name, query, false) else Nil,
|
||||
false,
|
||||
if (query.nonEmpty) searchIssues(repository.owner, repository.name, query, pullRequest = false) else Nil,
|
||||
pullRequest = false,
|
||||
query,
|
||||
page,
|
||||
repository
|
||||
@@ -257,8 +304,8 @@ trait IndexControllerBase extends ControllerBase {
|
||||
|
||||
case "pulls" =>
|
||||
gitbucket.core.search.html.issues(
|
||||
if (query.nonEmpty) searchIssues(repository.owner, repository.name, query, true) else Nil,
|
||||
true,
|
||||
if (query.nonEmpty) searchIssues(repository.owner, repository.name, query, pullRequest = true) else Nil,
|
||||
pullRequest = true,
|
||||
query,
|
||||
page,
|
||||
repository
|
||||
@@ -289,19 +336,19 @@ trait IndexControllerBase extends ControllerBase {
|
||||
context.loginAccount,
|
||||
None,
|
||||
withoutPhysicalInfo = true,
|
||||
limit = context.settings.limitVisibleRepositories
|
||||
limit = context.settings.basicBehavior.limitVisibleRepositories
|
||||
)
|
||||
|
||||
val repositories = {
|
||||
context.settings.limitVisibleRepositories match {
|
||||
case true =>
|
||||
getVisibleRepositories(
|
||||
context.loginAccount,
|
||||
None,
|
||||
withoutPhysicalInfo = true,
|
||||
limit = false
|
||||
)
|
||||
case false => visibleRepositories
|
||||
if (context.settings.basicBehavior.limitVisibleRepositories) {
|
||||
getVisibleRepositories(
|
||||
context.loginAccount,
|
||||
None,
|
||||
withoutPhysicalInfo = true,
|
||||
limit = false
|
||||
)
|
||||
} else {
|
||||
visibleRepositories
|
||||
}
|
||||
}.filter { repository =>
|
||||
repository.name.toLowerCase.indexOf(query) >= 0 || repository.owner.toLowerCase.indexOf(query) >= 0
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
package gitbucket.core.controller
|
||||
|
||||
import gitbucket.core.issues.html
|
||||
import gitbucket.core.model.Account
|
||||
import gitbucket.core.service.IssuesService._
|
||||
import gitbucket.core.service._
|
||||
import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.util._
|
||||
import gitbucket.core.model.{Account, CustomFieldBehavior}
|
||||
import gitbucket.core.service.IssuesService.*
|
||||
import gitbucket.core.service.*
|
||||
import gitbucket.core.util.Implicits.*
|
||||
import gitbucket.core.util.*
|
||||
import gitbucket.core.view
|
||||
import gitbucket.core.view.Markdown
|
||||
import org.scalatra.forms._
|
||||
import org.scalatra.forms.*
|
||||
import org.scalatra.{BadRequest, Ok}
|
||||
|
||||
class IssuesController
|
||||
@@ -21,6 +21,7 @@ class IssuesController
|
||||
with ActivityService
|
||||
with HandleCommentService
|
||||
with IssueCreationService
|
||||
with CustomFieldsService
|
||||
with ReadableUsersAuthenticator
|
||||
with ReferrerAuthenticator
|
||||
with WritableUsersAuthenticator
|
||||
@@ -33,88 +34,88 @@ class IssuesController
|
||||
with RequestCache
|
||||
|
||||
trait IssuesControllerBase extends ControllerBase {
|
||||
self: IssuesService
|
||||
with RepositoryService
|
||||
with AccountService
|
||||
with LabelsService
|
||||
with MilestonesService
|
||||
with ActivityService
|
||||
with HandleCommentService
|
||||
with IssueCreationService
|
||||
with ReadableUsersAuthenticator
|
||||
with ReferrerAuthenticator
|
||||
with WritableUsersAuthenticator
|
||||
with PullRequestService
|
||||
with WebHookIssueCommentService
|
||||
with PrioritiesService =>
|
||||
self: IssuesService & RepositoryService & AccountService & LabelsService & MilestonesService & ActivityService &
|
||||
HandleCommentService & IssueCreationService & CustomFieldsService & ReadableUsersAuthenticator &
|
||||
ReferrerAuthenticator & WritableUsersAuthenticator & PullRequestService & WebHookIssueCommentService &
|
||||
PrioritiesService =>
|
||||
|
||||
case class IssueCreateForm(
|
||||
private case class IssueCreateForm(
|
||||
title: String,
|
||||
content: Option[String],
|
||||
assignedUserName: Option[String],
|
||||
assigneeUserNames: Option[String],
|
||||
milestoneId: Option[Int],
|
||||
priorityId: Option[Int],
|
||||
labelNames: Option[String]
|
||||
)
|
||||
case class CommentForm(issueId: Int, content: String)
|
||||
case class IssueStateForm(issueId: Int, content: Option[String])
|
||||
private case class CommentForm(issueId: Int, content: String)
|
||||
private case class IssueStateForm(issueId: Int, content: Option[String])
|
||||
|
||||
val issueCreateForm = mapping(
|
||||
private val issueCreateForm = mapping(
|
||||
"title" -> trim(label("Title", text(required))),
|
||||
"content" -> trim(optional(text())),
|
||||
"assignedUserName" -> trim(optional(text())),
|
||||
"assigneeUserNames" -> trim(optional(text())),
|
||||
"milestoneId" -> trim(optional(number())),
|
||||
"priorityId" -> trim(optional(number())),
|
||||
"labelNames" -> trim(optional(text()))
|
||||
)(IssueCreateForm.apply)
|
||||
|
||||
val issueTitleEditForm = mapping(
|
||||
private val issueTitleEditForm = mapping(
|
||||
"title" -> trim(label("Title", text(required)))
|
||||
)(x => x)
|
||||
val issueEditForm = mapping(
|
||||
private val issueEditForm = mapping(
|
||||
"content" -> trim(optional(text()))
|
||||
)(x => x)
|
||||
|
||||
val commentForm = mapping(
|
||||
private val commentForm = mapping(
|
||||
"issueId" -> label("Issue Id", number()),
|
||||
"content" -> trim(label("Comment", text(required)))
|
||||
)(CommentForm.apply)
|
||||
|
||||
val issueStateForm = mapping(
|
||||
private val issueStateForm = mapping(
|
||||
"issueId" -> label("Issue Id", number()),
|
||||
"content" -> trim(optional(text()))
|
||||
)(IssueStateForm.apply)
|
||||
|
||||
get("/:owner/:repository/issues")(referrersOnly { repository =>
|
||||
val q = request.getParameter("q")
|
||||
if (Option(q).exists(_.contains("is:pr"))) {
|
||||
redirect(s"/${repository.owner}/${repository.name}/pulls?q=${StringUtil.urlEncode(q)}")
|
||||
} else {
|
||||
searchIssues(repository)
|
||||
Option(q) match {
|
||||
case Some(filter) if filter.contains("is:pr") =>
|
||||
redirect(s"/${repository.owner}/${repository.name}/pulls?q=${StringUtil.urlEncode(q)}")
|
||||
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 =>
|
||||
val issueId = params("id")
|
||||
getIssue(repository.owner, repository.name, issueId) map {
|
||||
issue =>
|
||||
if (issue.isPullRequest) {
|
||||
redirect(s"/${repository.owner}/${repository.name}/pull/${issueId}")
|
||||
} else {
|
||||
html.issue(
|
||||
issue,
|
||||
getComments(repository.owner, repository.name, issueId.toInt),
|
||||
getIssueLabels(repository.owner, repository.name, issueId.toInt),
|
||||
getAssignableUserNames(repository.owner, repository.name),
|
||||
getMilestonesWithIssueCount(repository.owner, repository.name),
|
||||
getPriorities(repository.owner, repository.name),
|
||||
getLabels(repository.owner, repository.name),
|
||||
isIssueEditable(repository),
|
||||
isIssueManageable(repository),
|
||||
isIssueCommentManageable(repository),
|
||||
repository
|
||||
)
|
||||
}
|
||||
getIssue(repository.owner, repository.name, issueId) map { issue =>
|
||||
if (issue.isPullRequest) {
|
||||
redirect(s"/${repository.owner}/${repository.name}/pull/$issueId")
|
||||
} else {
|
||||
html.issue(
|
||||
issue,
|
||||
getComments(repository.owner, repository.name, issueId.toInt),
|
||||
getIssueLabels(repository.owner, repository.name, issueId.toInt),
|
||||
getIssueAssignees(repository.owner, repository.name, issueId.toInt),
|
||||
getAssignableUserNames(repository.owner, repository.name),
|
||||
getMilestonesWithIssueCount(repository.owner, repository.name),
|
||||
getPriorities(repository.owner, repository.name),
|
||||
getLabels(repository.owner, repository.name),
|
||||
getCustomFieldsWithValue(repository.owner, repository.name, issueId.toInt).filter(_._1.enableForIssues),
|
||||
isIssueEditable(repository),
|
||||
isIssueManageable(repository),
|
||||
isIssueCommentManageable(repository),
|
||||
repository
|
||||
)
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
|
||||
@@ -126,6 +127,7 @@ trait IssuesControllerBase extends ControllerBase {
|
||||
getPriorities(repository.owner, repository.name),
|
||||
getDefaultPriority(repository.owner, repository.name),
|
||||
getLabels(repository.owner, repository.name),
|
||||
getCustomFields(repository.owner, repository.name).filter(_.enableForIssues),
|
||||
isIssueManageable(repository),
|
||||
getContentTemplate(repository, "ISSUE_TEMPLATE"),
|
||||
repository
|
||||
@@ -134,111 +136,120 @@ trait IssuesControllerBase extends ControllerBase {
|
||||
})
|
||||
|
||||
post("/:owner/:repository/issues/new", issueCreateForm)(readableUsersOnly { (form, repository) =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
if (isIssueEditable(repository)) { // TODO Should this check is provided by authenticator?
|
||||
val issue = createIssue(
|
||||
repository,
|
||||
form.title,
|
||||
form.content,
|
||||
form.assignedUserName,
|
||||
form.milestoneId,
|
||||
form.priorityId,
|
||||
form.labelNames.toSeq.flatMap(_.split(",")),
|
||||
loginAccount
|
||||
)
|
||||
redirect(s"/${issue.userName}/${issue.repositoryName}/issues/${issue.issueId}")
|
||||
} else Unauthorized()
|
||||
context.withLoginAccount { loginAccount =>
|
||||
if (isIssueEditable(repository)) { // TODO Should this check is provided by authenticator?
|
||||
val issue = createIssue(
|
||||
repository,
|
||||
form.title,
|
||||
form.content,
|
||||
form.assigneeUserNames.toSeq.flatMap(_.split(",")),
|
||||
form.milestoneId,
|
||||
form.priorityId,
|
||||
form.labelNames.toSeq.flatMap(_.split(",")),
|
||||
loginAccount
|
||||
)
|
||||
|
||||
// Insert custom field values
|
||||
params.toMap.foreach { case (key, value) =>
|
||||
if (key.startsWith("custom-field-")) {
|
||||
getCustomField(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
key.replaceFirst("^custom-field-", "").toInt
|
||||
).foreach { field =>
|
||||
CustomFieldBehavior.validate(field, value, messages) match {
|
||||
case None =>
|
||||
insertOrUpdateCustomFieldValue(field, repository.owner, repository.name, issue.issueId, value)
|
||||
case Some(_) => halt(400)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
redirect(s"/${issue.userName}/${issue.repositoryName}/issues/${issue.issueId}")
|
||||
} else Unauthorized()
|
||||
}
|
||||
})
|
||||
|
||||
ajaxPost("/:owner/:repository/issues/edit_title/:id", issueTitleEditForm)(readableUsersOnly { (title, repository) =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
getIssue(repository.owner, repository.name, params("id")).map {
|
||||
issue =>
|
||||
if (isEditableContent(repository.owner, repository.name, issue.openedUserName, loginAccount)) {
|
||||
if (issue.title != title) {
|
||||
// update issue
|
||||
updateIssue(repository.owner, repository.name, issue.issueId, title, issue.content)
|
||||
// extract references and create refer comment
|
||||
createReferComment(repository.owner, repository.name, issue.copy(title = title), title, loginAccount)
|
||||
createComment(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
loginAccount.userName,
|
||||
issue.issueId,
|
||||
issue.title + "\r\n" + title,
|
||||
"change_title"
|
||||
)
|
||||
}
|
||||
redirect(s"/${repository.owner}/${repository.name}/issues/_data/${issue.issueId}")
|
||||
} else Unauthorized()
|
||||
} getOrElse NotFound()
|
||||
context.withLoginAccount { loginAccount =>
|
||||
getIssue(repository.owner, repository.name, params("id")).map { issue =>
|
||||
if (isEditableContent(repository.owner, repository.name, issue.openedUserName, loginAccount)) {
|
||||
if (issue.title != title) {
|
||||
// update issue
|
||||
updateIssue(repository.owner, repository.name, issue.issueId, title, issue.content)
|
||||
// extract references and create refer comment
|
||||
createReferComment(repository.owner, repository.name, issue.copy(title = title), title, loginAccount)
|
||||
createComment(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
loginAccount.userName,
|
||||
issue.issueId,
|
||||
issue.title + "\r\n" + title,
|
||||
"change_title"
|
||||
)
|
||||
}
|
||||
redirect(s"/${repository.owner}/${repository.name}/issues/_data/${issue.issueId}")
|
||||
} else Unauthorized()
|
||||
} getOrElse NotFound()
|
||||
}
|
||||
})
|
||||
|
||||
ajaxPost("/:owner/:repository/issues/edit/:id", issueEditForm)(readableUsersOnly { (content, repository) =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
getIssue(repository.owner, repository.name, params("id")).map { issue =>
|
||||
if (isEditableContent(repository.owner, repository.name, issue.openedUserName, loginAccount)) {
|
||||
// update issue
|
||||
updateIssue(repository.owner, repository.name, issue.issueId, issue.title, content)
|
||||
// extract references and create refer comment
|
||||
createReferComment(repository.owner, repository.name, issue, content.getOrElse(""), loginAccount)
|
||||
context.withLoginAccount { loginAccount =>
|
||||
getIssue(repository.owner, repository.name, params("id")).map { issue =>
|
||||
if (isEditableContent(repository.owner, repository.name, issue.openedUserName, loginAccount)) {
|
||||
// update issue
|
||||
updateIssue(repository.owner, repository.name, issue.issueId, issue.title, content)
|
||||
// extract references and create refer comment
|
||||
createReferComment(repository.owner, repository.name, issue, content.getOrElse(""), loginAccount)
|
||||
|
||||
redirect(s"/${repository.owner}/${repository.name}/issues/_data/${issue.issueId}")
|
||||
} else Unauthorized()
|
||||
} getOrElse NotFound()
|
||||
redirect(s"/${repository.owner}/${repository.name}/issues/_data/${issue.issueId}")
|
||||
} else Unauthorized()
|
||||
} getOrElse NotFound()
|
||||
}
|
||||
})
|
||||
|
||||
post("/:owner/:repository/issue_comments/new", commentForm)(readableUsersOnly { (form, repository) =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
getIssue(repository.owner, repository.name, form.issueId.toString).flatMap { issue =>
|
||||
val actionOpt =
|
||||
params
|
||||
.get("action")
|
||||
.filter(_ => isEditableContent(issue.userName, issue.repositoryName, issue.openedUserName, loginAccount))
|
||||
handleComment(issue, Some(form.content), repository, actionOpt) map {
|
||||
case (issue, id) =>
|
||||
redirect(
|
||||
s"/${repository.owner}/${repository.name}/${if (issue.isPullRequest) "pull" else "issues"}/${form.issueId}#comment-${id}"
|
||||
)
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
context.withLoginAccount { loginAccount =>
|
||||
getIssue(repository.owner, repository.name, form.issueId.toString).flatMap { issue =>
|
||||
val actionOpt =
|
||||
params
|
||||
.get("action")
|
||||
.filter(_ => isEditableContent(issue.userName, issue.repositoryName, issue.openedUserName, loginAccount))
|
||||
handleComment(issue, Some(form.content), repository, actionOpt) map { case (issue, id) =>
|
||||
redirect(
|
||||
s"/${repository.owner}/${repository.name}/${if (issue.isPullRequest) "pull" else "issues"}/${form.issueId}#comment-$id"
|
||||
)
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
}
|
||||
})
|
||||
|
||||
post("/:owner/:repository/issue_comments/state", issueStateForm)(readableUsersOnly { (form, repository) =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
getIssue(repository.owner, repository.name, form.issueId.toString).flatMap { issue =>
|
||||
val actionOpt =
|
||||
params
|
||||
.get("action")
|
||||
.filter(_ => isEditableContent(issue.userName, issue.repositoryName, issue.openedUserName, loginAccount))
|
||||
handleComment(issue, form.content, repository, actionOpt) map {
|
||||
case (issue, id) =>
|
||||
redirect(
|
||||
s"/${repository.owner}/${repository.name}/${if (issue.isPullRequest) "pull" else "issues"}/${form.issueId}#comment-${id}"
|
||||
)
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
context.withLoginAccount { loginAccount =>
|
||||
getIssue(repository.owner, repository.name, form.issueId.toString).flatMap { issue =>
|
||||
val actionOpt =
|
||||
params
|
||||
.get("action")
|
||||
.filter(_ => isEditableContent(issue.userName, issue.repositoryName, issue.openedUserName, loginAccount))
|
||||
handleComment(issue, form.content, repository, actionOpt) map { case (issue, id) =>
|
||||
redirect(
|
||||
s"/${repository.owner}/${repository.name}/${if (issue.isPullRequest) "pull" else "issues"}/${form.issueId}#comment-$id"
|
||||
)
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
}
|
||||
})
|
||||
|
||||
ajaxPost("/:owner/:repository/issue_comments/edit/:id", commentForm)(readableUsersOnly { (form, repository) =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
getComment(repository.owner, repository.name, params("id")).map { comment =>
|
||||
if (isEditableContent(repository.owner, repository.name, comment.commentedUserName, loginAccount)) {
|
||||
updateComment(comment.issueId, comment.commentId, form.content)
|
||||
redirect(s"/${repository.owner}/${repository.name}/issue_comments/_data/${comment.commentId}")
|
||||
} else Unauthorized()
|
||||
} getOrElse NotFound()
|
||||
context.withLoginAccount { loginAccount =>
|
||||
getComment(repository.owner, repository.name, params("id")).map { comment =>
|
||||
if (isEditableContent(repository.owner, repository.name, comment.commentedUserName, loginAccount)) {
|
||||
updateComment(repository.owner, repository.name, comment.issueId, comment.commentId, form.content)
|
||||
redirect(s"/${repository.owner}/${repository.name}/issue_comments/_data/${comment.commentId}")
|
||||
} else Unauthorized()
|
||||
} getOrElse NotFound()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -253,65 +264,61 @@ trait IssuesControllerBase extends ControllerBase {
|
||||
})
|
||||
|
||||
ajaxGet("/:owner/:repository/issues/_data/:id")(readableUsersOnly { repository =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
getIssue(repository.owner, repository.name, params("id")) map {
|
||||
x =>
|
||||
if (isEditableContent(x.userName, x.repositoryName, x.openedUserName, loginAccount)) {
|
||||
params.get("dataType") collect {
|
||||
case t if t == "html" => html.editissue(x.content, x.issueId, repository)
|
||||
} getOrElse {
|
||||
contentType = formats("json")
|
||||
org.json4s.jackson.Serialization.write(
|
||||
Map(
|
||||
"title" -> x.title,
|
||||
"content" -> Markdown.toHtml(
|
||||
markdown = x.content getOrElse "No description given.",
|
||||
repository = repository,
|
||||
branch = repository.repository.defaultBranch,
|
||||
enableWikiLink = false,
|
||||
enableRefsLink = true,
|
||||
enableAnchor = true,
|
||||
enableLineBreaks = true,
|
||||
enableTaskList = true,
|
||||
hasWritePermission = true
|
||||
)
|
||||
)
|
||||
context.withLoginAccount { loginAccount =>
|
||||
getIssue(repository.owner, repository.name, params("id")) map { x =>
|
||||
if (isEditableContent(x.userName, x.repositoryName, x.openedUserName, loginAccount)) {
|
||||
params.get("dataType") collect {
|
||||
case t if t == "html" => html.editissue(x.content, x.issueId, repository)
|
||||
} getOrElse {
|
||||
contentType = formats("json")
|
||||
org.json4s.jackson.Serialization.write(
|
||||
Map(
|
||||
"title" -> x.title,
|
||||
"content" -> Markdown.toHtml(
|
||||
markdown = x.content getOrElse "No description given.",
|
||||
repository = repository,
|
||||
branch = repository.repository.defaultBranch,
|
||||
enableWikiLink = false,
|
||||
enableRefsLink = true,
|
||||
enableAnchor = true,
|
||||
enableLineBreaks = true,
|
||||
enableTaskList = true,
|
||||
hasWritePermission = true
|
||||
)
|
||||
}
|
||||
} else Unauthorized()
|
||||
} getOrElse NotFound()
|
||||
)
|
||||
)
|
||||
}
|
||||
} else Unauthorized()
|
||||
} getOrElse NotFound()
|
||||
}
|
||||
})
|
||||
|
||||
ajaxGet("/:owner/:repository/issue_comments/_data/:id")(readableUsersOnly { repository =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
getComment(repository.owner, repository.name, params("id")) map {
|
||||
x =>
|
||||
if (isEditableContent(x.userName, x.repositoryName, x.commentedUserName, loginAccount)) {
|
||||
params.get("dataType") collect {
|
||||
case t if t == "html" => html.editcomment(x.content, x.commentId, repository)
|
||||
} getOrElse {
|
||||
contentType = formats("json")
|
||||
org.json4s.jackson.Serialization.write(
|
||||
Map(
|
||||
"content" -> view.Markdown.toHtml(
|
||||
markdown = x.content,
|
||||
repository = repository,
|
||||
branch = repository.repository.defaultBranch,
|
||||
enableWikiLink = false,
|
||||
enableRefsLink = true,
|
||||
enableAnchor = true,
|
||||
enableLineBreaks = true,
|
||||
enableTaskList = true,
|
||||
hasWritePermission = true
|
||||
)
|
||||
)
|
||||
context.withLoginAccount { loginAccount =>
|
||||
getComment(repository.owner, repository.name, params("id")) map { x =>
|
||||
if (isEditableContent(x.userName, x.repositoryName, x.commentedUserName, loginAccount)) {
|
||||
params.get("dataType") collect {
|
||||
case t if t == "html" => html.editcomment(x.content, x.commentId, repository)
|
||||
} getOrElse {
|
||||
contentType = formats("json")
|
||||
org.json4s.jackson.Serialization.write(
|
||||
Map(
|
||||
"content" -> view.Markdown.toHtml(
|
||||
markdown = x.content,
|
||||
repository = repository,
|
||||
branch = repository.repository.defaultBranch,
|
||||
enableWikiLink = false,
|
||||
enableRefsLink = true,
|
||||
enableAnchor = true,
|
||||
enableLineBreaks = true,
|
||||
enableTaskList = true,
|
||||
hasWritePermission = true
|
||||
)
|
||||
}
|
||||
} else Unauthorized()
|
||||
} getOrElse NotFound()
|
||||
)
|
||||
)
|
||||
}
|
||||
} else Unauthorized()
|
||||
} getOrElse NotFound()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -323,45 +330,80 @@ trait IssuesControllerBase extends ControllerBase {
|
||||
|
||||
ajaxPost("/:owner/:repository/issues/:id/label/new")(writableUsersOnly { repository =>
|
||||
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))
|
||||
})
|
||||
|
||||
ajaxPost("/:owner/:repository/issues/:id/label/delete")(writableUsersOnly { repository =>
|
||||
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))
|
||||
})
|
||||
|
||||
ajaxPost("/:owner/:repository/issues/:id/assign")(writableUsersOnly { repository =>
|
||||
updateAssignedUserName(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
params("id").toInt,
|
||||
assignedUserName("assignedUserName"),
|
||||
true
|
||||
)
|
||||
Ok("updated")
|
||||
ajaxPost("/:owner/:repository/issues/:id/assignee/new")(writableUsersOnly { repository =>
|
||||
val issueId = params("id").toInt
|
||||
registerIssueAssignee(repository.owner, repository.name, issueId, params("assigneeUserName"), insertComment = true)
|
||||
Ok()
|
||||
})
|
||||
|
||||
ajaxPost("/:owner/:repository/issues/:id/assignee/delete")(writableUsersOnly { repository =>
|
||||
val issueId = params("id").toInt
|
||||
deleteIssueAssignee(repository.owner, repository.name, issueId, params("assigneeUserName"), insertComment = true)
|
||||
Ok()
|
||||
})
|
||||
|
||||
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 =>
|
||||
getMilestonesWithIssueCount(repository.owner, repository.name)
|
||||
.find(_._1.milestoneId == milestoneId)
|
||||
.map {
|
||||
case (_, openCount, closeCount) =>
|
||||
gitbucket.core.issues.milestones.html.progress(openCount + closeCount, closeCount)
|
||||
.map { case (_, openCount, closeCount) =>
|
||||
gitbucket.core.issues.milestones.html.progress(openCount + closeCount, closeCount)
|
||||
} getOrElse NotFound()
|
||||
} getOrElse Ok()
|
||||
})
|
||||
|
||||
ajaxPost("/:owner/:repository/issues/:id/priority")(writableUsersOnly { repository =>
|
||||
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")
|
||||
})
|
||||
|
||||
ajaxPost("/:owner/:repository/issues/customfield_validation/:fieldId")(writableUsersOnly { repository =>
|
||||
val fieldId = params("fieldId").toInt
|
||||
val value = params("value")
|
||||
getCustomField(repository.owner, repository.name, fieldId)
|
||||
.flatMap { field =>
|
||||
CustomFieldBehavior.validate(field, value, messages).map { error =>
|
||||
Ok(error)
|
||||
}
|
||||
}
|
||||
.getOrElse(Ok())
|
||||
})
|
||||
|
||||
ajaxPost("/:owner/:repository/issues/:id/customfield/:fieldId")(writableUsersOnly { repository =>
|
||||
val issueId = params("id").toInt
|
||||
val fieldId = params("fieldId").toInt
|
||||
val value = params("value")
|
||||
|
||||
for {
|
||||
_ <- getIssue(repository.owner, repository.name, issueId.toString)
|
||||
field <- getCustomField(repository.owner, repository.name, fieldId)
|
||||
} {
|
||||
CustomFieldBehavior.validate(field, value, messages) match {
|
||||
case None => insertOrUpdateCustomFieldValue(field, repository.owner, repository.name, issueId, value)
|
||||
case Some(_) => halt(400)
|
||||
}
|
||||
}
|
||||
Ok(value)
|
||||
})
|
||||
|
||||
post("/:owner/:repository/issues/batchedit/state")(writableUsersOnly { repository =>
|
||||
val action = params.get("value")
|
||||
action match {
|
||||
@@ -391,7 +433,7 @@ trait IssuesControllerBase extends ControllerBase {
|
||||
params("value").toIntOpt.map { labelId =>
|
||||
executeBatch(repository) { issueId =>
|
||||
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) {
|
||||
redirect(params("uri"))
|
||||
}
|
||||
@@ -403,7 +445,13 @@ trait IssuesControllerBase extends ControllerBase {
|
||||
post("/:owner/:repository/issues/batchedit/assign")(writableUsersOnly { repository =>
|
||||
val value = assignedUserName("value")
|
||||
executeBatch(repository) {
|
||||
updateAssignedUserName(repository.owner, repository.name, _, value, true)
|
||||
// updateAssignedUserName(repository.owner, repository.name, _, value, true)
|
||||
value match {
|
||||
case Some(assignedUserName) =>
|
||||
registerIssueAssignee(repository.owner, repository.name, _, assignedUserName, insertComment = true)
|
||||
case None =>
|
||||
deleteAllIssueAssignees(repository.owner, repository.name, _, insertComment = true)
|
||||
}
|
||||
}
|
||||
if (params("uri").nonEmpty) {
|
||||
redirect(params("uri"))
|
||||
@@ -413,20 +461,20 @@ trait IssuesControllerBase extends ControllerBase {
|
||||
post("/:owner/:repository/issues/batchedit/milestone")(writableUsersOnly { repository =>
|
||||
val value = milestoneId("value")
|
||||
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 =>
|
||||
val value = priorityId("value")
|
||||
executeBatch(repository) {
|
||||
updatePriorityId(repository.owner, repository.name, _, value, true)
|
||||
updatePriorityId(repository.owner, repository.name, _, value, insertComment = true)
|
||||
}
|
||||
})
|
||||
|
||||
get("/:owner/:repository/_attached/:file")(referrersOnly { repository =>
|
||||
(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 =>
|
||||
response.setHeader("Content-Disposition", f"""inline; filename=${file.getName}""")
|
||||
RawData(FileUtil.getSafeMimeType(file.getName), file)
|
||||
@@ -442,27 +490,26 @@ trait IssuesControllerBase extends ControllerBase {
|
||||
contentType = formats("json")
|
||||
org.json4s.jackson.Serialization.write(
|
||||
Map(
|
||||
"options" -> (
|
||||
"options" ->
|
||||
getOpenIssues(repository.owner, repository.name)
|
||||
.map { t =>
|
||||
Map(
|
||||
"label" -> s"""${if (t.isPullRequest) "<i class='octicon octicon-git-pull-request'></i>"
|
||||
else "<i class='octicon octicon-issue-opened'></i>"}<b> #${StringUtil
|
||||
.escapeHtml(t.issueId.toString)} ${StringUtil
|
||||
.escapeHtml(StringUtil.cutTail(t.title, 50, "..."))}</b>""",
|
||||
else "<i class='octicon octicon-issue-opened'></i>"}<b> #${StringUtil
|
||||
.escapeHtml(t.issueId.toString)} ${StringUtil
|
||||
.escapeHtml(StringUtil.cutTail(t.title, 50, "..."))}</b>""",
|
||||
"value" -> t.issueId.toString
|
||||
)
|
||||
}
|
||||
)
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
val assignedUserName = (key: String) => params.get(key) filter (_.trim != "")
|
||||
val 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 assignedUserName = (key: String) => params.get(key) filter (_.trim != "")
|
||||
private val milestoneId: 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("from") match {
|
||||
case "issues" => redirect(s"/${repository.owner}/${repository.name}/issues")
|
||||
@@ -471,10 +518,7 @@ trait IssuesControllerBase extends ControllerBase {
|
||||
}
|
||||
}
|
||||
|
||||
private def searchIssues(repository: RepositoryService.RepositoryInfo) = {
|
||||
val page = IssueSearchCondition.page(request)
|
||||
// retrieve search condition
|
||||
val condition = IssueSearchCondition(request)
|
||||
private def searchIssues(repository: RepositoryService.RepositoryInfo, condition: IssueSearchCondition, page: Int) = {
|
||||
// search issues
|
||||
val issues =
|
||||
searchIssue(
|
||||
@@ -505,8 +549,8 @@ trait IssuesControllerBase extends ControllerBase {
|
||||
/**
|
||||
* Tests whether an issue or a comment is editable by a logged-in user.
|
||||
*/
|
||||
private def isEditableContent(owner: String, repository: String, author: String, loginAccount: Account)(
|
||||
implicit context: Context
|
||||
private def isEditableContent(owner: String, repository: String, author: String, loginAccount: Account)(implicit
|
||||
context: Context
|
||||
): Boolean = {
|
||||
hasDeveloperRole(owner, repository, context.loginAccount) || author == loginAccount.userName
|
||||
}
|
||||
@@ -514,8 +558,8 @@ trait IssuesControllerBase extends ControllerBase {
|
||||
/**
|
||||
* Tests whether an issue comment is deletable by a logged-in user.
|
||||
*/
|
||||
private def isDeletableComment(owner: String, repository: String, author: String, loginAccount: Account)(
|
||||
implicit context: Context
|
||||
private def isDeletableComment(owner: String, repository: String, author: String, loginAccount: Account)(implicit
|
||||
context: Context
|
||||
): Boolean = {
|
||||
hasOwnerRole(owner, repository, context.loginAccount) || author == loginAccount.userName
|
||||
}
|
||||
|
||||
@@ -10,9 +10,9 @@ import gitbucket.core.service.{
|
||||
PrioritiesService
|
||||
}
|
||||
import gitbucket.core.util.{ReferrerAuthenticator, WritableUsersAuthenticator}
|
||||
import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.util.SyntaxSugars._
|
||||
import org.scalatra.forms._
|
||||
import gitbucket.core.util.Implicits.*
|
||||
import gitbucket.core.util.SyntaxSugars.*
|
||||
import org.scalatra.forms.*
|
||||
import org.scalatra.i18n.Messages
|
||||
import org.scalatra.Ok
|
||||
|
||||
@@ -28,15 +28,11 @@ class LabelsController
|
||||
with WritableUsersAuthenticator
|
||||
|
||||
trait LabelsControllerBase extends ControllerBase {
|
||||
self: LabelsService
|
||||
with IssuesService
|
||||
with RepositoryService
|
||||
with ReferrerAuthenticator
|
||||
with WritableUsersAuthenticator =>
|
||||
self: LabelsService & IssuesService & RepositoryService & ReferrerAuthenticator & 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)))),
|
||||
"labelColor" -> trim(label("Color", text(required, color)))
|
||||
)(LabelForm.apply)
|
||||
@@ -44,7 +40,7 @@ trait LabelsControllerBase extends ControllerBase {
|
||||
get("/:owner/:repository/issues/labels")(referrersOnly { repository =>
|
||||
html.list(
|
||||
getLabels(repository.owner, repository.name),
|
||||
countIssueGroupByLabels(repository.owner, repository.name, IssuesService.IssueSearchCondition(), Map.empty),
|
||||
countIssueGroupByLabels(repository.owner, repository.name, IssuesService.IssueSearchCondition()),
|
||||
repository,
|
||||
hasDeveloperRole(repository.owner, repository.name, context.loginAccount)
|
||||
)
|
||||
@@ -59,7 +55,7 @@ trait LabelsControllerBase extends ControllerBase {
|
||||
html.label(
|
||||
getLabel(repository.owner, repository.name, labelId).get,
|
||||
// TODO futility
|
||||
countIssueGroupByLabels(repository.owner, repository.name, IssuesService.IssueSearchCondition(), Map.empty),
|
||||
countIssueGroupByLabels(repository.owner, repository.name, IssuesService.IssueSearchCondition()),
|
||||
repository,
|
||||
hasDeveloperRole(repository.owner, repository.name, context.loginAccount)
|
||||
)
|
||||
@@ -76,7 +72,7 @@ trait LabelsControllerBase extends ControllerBase {
|
||||
html.label(
|
||||
getLabel(repository.owner, repository.name, params("labelId").toInt).get,
|
||||
// TODO futility
|
||||
countIssueGroupByLabels(repository.owner, repository.name, IssuesService.IssueSearchCondition(), Map.empty),
|
||||
countIssueGroupByLabels(repository.owner, repository.name, IssuesService.IssueSearchCondition()),
|
||||
repository,
|
||||
hasDeveloperRole(repository.owner, repository.name, context.loginAccount)
|
||||
)
|
||||
@@ -93,9 +89,9 @@ trait LabelsControllerBase extends ControllerBase {
|
||||
private def labelName: Constraint = new Constraint() {
|
||||
override def validate(name: String, value: String, messages: Messages): Option[String] =
|
||||
if (value.contains(',')) {
|
||||
Some(s"${name} contains invalid character.")
|
||||
Some(s"$name contains invalid character.")
|
||||
} else if (value.startsWith("_") || value.startsWith("-")) {
|
||||
Some(s"${name} starts with invalid character.")
|
||||
Some(s"$name starts with invalid character.")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
||||
@@ -9,11 +9,11 @@ import gitbucket.core.service.{
|
||||
MilestonesService,
|
||||
RepositoryService
|
||||
}
|
||||
import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.util.Implicits.*
|
||||
import gitbucket.core.util.{ReferrerAuthenticator, WritableUsersAuthenticator}
|
||||
import gitbucket.core.util.SyntaxSugars._
|
||||
import gitbucket.core.util.SyntaxSugars.*
|
||||
import gitbucket.core.view.helpers.{getAssignableUserNames, getLabels, getPriorities, searchIssue}
|
||||
import org.scalatra.forms._
|
||||
import org.scalatra.forms.*
|
||||
import org.scalatra.i18n.Messages
|
||||
|
||||
class MilestonesController
|
||||
@@ -26,15 +26,12 @@ class MilestonesController
|
||||
with WritableUsersAuthenticator
|
||||
|
||||
trait MilestonesControllerBase extends ControllerBase {
|
||||
self: MilestonesService
|
||||
with RepositoryService
|
||||
with CommitStatusService
|
||||
with ReferrerAuthenticator
|
||||
with WritableUsersAuthenticator =>
|
||||
self: MilestonesService & RepositoryService & CommitStatusService & ReferrerAuthenticator &
|
||||
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))),
|
||||
"description" -> trim(label("Description", optional(text()))),
|
||||
"dueDate" -> trim(label("Due Date", optional(date())))
|
||||
|
||||
@@ -29,13 +29,15 @@ trait PreProcessControllerBase extends ControllerBase {
|
||||
* If anonymous access is allowed, pass all requests.
|
||||
* But if it's not allowed, demands authentication except some paths.
|
||||
*/
|
||||
get(!context.settings.allowAnonymousAccess, context.loginAccount.isEmpty) {
|
||||
if (!context.currentPath.startsWith("/assets") && !context.currentPath.startsWith("/signin") &&
|
||||
!context.currentPath.startsWith("/register") && !context.currentPath.endsWith("/info/refs") &&
|
||||
!context.currentPath.startsWith("/plugin-assets") &&
|
||||
!PluginRegistry().getAnonymousAccessiblePaths().exists { path =>
|
||||
context.currentPath.startsWith(path)
|
||||
}) {
|
||||
get(!context.settings.basicBehavior.allowAnonymousAccess, context.loginAccount.isEmpty) {
|
||||
if (
|
||||
!context.currentPath.startsWith("/assets") && !context.currentPath.startsWith("/signin") &&
|
||||
!context.currentPath.startsWith("/register") && !context.currentPath.endsWith("/info/refs") &&
|
||||
!context.currentPath.startsWith("/plugin-assets") && !context.currentPath.equals("/user.css") &&
|
||||
!PluginRegistry().getAnonymousAccessiblePaths().exists { path =>
|
||||
context.currentPath.startsWith(path)
|
||||
}
|
||||
) {
|
||||
Unauthorized()
|
||||
} else {
|
||||
pass()
|
||||
|
||||
@@ -28,15 +28,11 @@ class PrioritiesController
|
||||
with WritableUsersAuthenticator
|
||||
|
||||
trait PrioritiesControllerBase extends ControllerBase {
|
||||
self: PrioritiesService
|
||||
with IssuesService
|
||||
with RepositoryService
|
||||
with ReferrerAuthenticator
|
||||
with WritableUsersAuthenticator =>
|
||||
self: PrioritiesService & IssuesService & RepositoryService & ReferrerAuthenticator & 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)))),
|
||||
"description" -> trim(label("Description", optional(text(maxlength(255))))),
|
||||
"priorityColor" -> trim(label("Color", text(required, color)))
|
||||
@@ -45,7 +41,7 @@ trait PrioritiesControllerBase extends ControllerBase {
|
||||
get("/:owner/:repository/issues/priorities")(referrersOnly { repository =>
|
||||
html.list(
|
||||
getPriorities(repository.owner, repository.name),
|
||||
countIssueGroupByPriorities(repository.owner, repository.name, IssuesService.IssueSearchCondition(), Map.empty),
|
||||
countIssueGroupByPriorities(repository.owner, repository.name, IssuesService.IssueSearchCondition()),
|
||||
repository,
|
||||
hasDeveloperRole(repository.owner, repository.name, context.loginAccount)
|
||||
)
|
||||
@@ -60,7 +56,7 @@ trait PrioritiesControllerBase extends ControllerBase {
|
||||
createPriority(repository.owner, repository.name, form.priorityName, form.description, form.color.substring(1))
|
||||
html.priority(
|
||||
getPriority(repository.owner, repository.name, priorityId).get,
|
||||
countIssueGroupByPriorities(repository.owner, repository.name, IssuesService.IssueSearchCondition(), Map.empty),
|
||||
countIssueGroupByPriorities(repository.owner, repository.name, IssuesService.IssueSearchCondition()),
|
||||
repository,
|
||||
hasDeveloperRole(repository.owner, repository.name, context.loginAccount)
|
||||
)
|
||||
@@ -84,13 +80,13 @@ trait PrioritiesControllerBase extends ControllerBase {
|
||||
)
|
||||
html.priority(
|
||||
getPriority(repository.owner, repository.name, params("priorityId").toInt).get,
|
||||
countIssueGroupByPriorities(repository.owner, repository.name, IssuesService.IssueSearchCondition(), Map.empty),
|
||||
countIssueGroupByPriorities(repository.owner, repository.name, IssuesService.IssueSearchCondition()),
|
||||
repository,
|
||||
hasDeveloperRole(repository.owner, repository.name, context.loginAccount)
|
||||
)
|
||||
})
|
||||
|
||||
ajaxPost("/:owner/:repository/issues/priorities/reorder")(writableUsersOnly { (repository) =>
|
||||
ajaxPost("/:owner/:repository/issues/priorities/reorder")(writableUsersOnly { repository =>
|
||||
reorderPriorities(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
@@ -104,7 +100,7 @@ trait PrioritiesControllerBase extends ControllerBase {
|
||||
Ok()
|
||||
})
|
||||
|
||||
ajaxPost("/:owner/:repository/issues/priorities/default")(writableUsersOnly { (repository) =>
|
||||
ajaxPost("/:owner/:repository/issues/priorities/default")(writableUsersOnly { repository =>
|
||||
setDefaultPriority(repository.owner, repository.name, priorityId("priorityId"))
|
||||
Ok()
|
||||
})
|
||||
@@ -122,9 +118,9 @@ trait PrioritiesControllerBase extends ControllerBase {
|
||||
private def priorityName: Constraint = new Constraint() {
|
||||
override def validate(name: String, value: String, messages: Messages): Option[String] =
|
||||
if (value.contains(',')) {
|
||||
Some(s"${name} contains invalid character.")
|
||||
Some(s"$name contains invalid character.")
|
||||
} else if (value.startsWith("_") || value.startsWith("-")) {
|
||||
Some(s"${name} starts with invalid character.")
|
||||
Some(s"$name starts with invalid character.")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
||||
@@ -4,14 +4,14 @@ import gitbucket.core.model.activity.DeleteBranchInfo
|
||||
import gitbucket.core.pulls.html
|
||||
import gitbucket.core.service.CommitStatusService
|
||||
import gitbucket.core.service.MergeService
|
||||
import gitbucket.core.service.IssuesService._
|
||||
import gitbucket.core.service.PullRequestService._
|
||||
import gitbucket.core.service.IssuesService.*
|
||||
import gitbucket.core.service.PullRequestService.*
|
||||
import gitbucket.core.service.RepositoryService.RepositoryInfo
|
||||
import gitbucket.core.service._
|
||||
import gitbucket.core.util.Directory._
|
||||
import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.util._
|
||||
import org.scalatra.forms._
|
||||
import gitbucket.core.service.*
|
||||
import gitbucket.core.util.Directory.*
|
||||
import gitbucket.core.util.Implicits.*
|
||||
import gitbucket.core.util.*
|
||||
import org.scalatra.forms.*
|
||||
import org.eclipse.jgit.api.Git
|
||||
import org.scalatra.BadRequest
|
||||
|
||||
@@ -25,6 +25,7 @@ class PullRequestsController
|
||||
with PullRequestService
|
||||
with MilestonesService
|
||||
with LabelsService
|
||||
with CustomFieldsService
|
||||
with CommitsService
|
||||
with ActivityService
|
||||
with WebHookPullRequestService
|
||||
@@ -39,47 +40,35 @@ class PullRequestsController
|
||||
with RequestCache
|
||||
|
||||
trait PullRequestsControllerBase extends ControllerBase {
|
||||
self: RepositoryService
|
||||
with AccountService
|
||||
with IssuesService
|
||||
with MilestonesService
|
||||
with LabelsService
|
||||
with CommitsService
|
||||
with ActivityService
|
||||
with PullRequestService
|
||||
with WebHookPullRequestService
|
||||
with ReadableUsersAuthenticator
|
||||
with ReferrerAuthenticator
|
||||
with WritableUsersAuthenticator
|
||||
with CommitStatusService
|
||||
with MergeService
|
||||
with ProtectedBranchService
|
||||
with PrioritiesService =>
|
||||
self: RepositoryService & AccountService & IssuesService & MilestonesService & LabelsService & CustomFieldsService &
|
||||
CommitsService & ActivityService & PullRequestService & WebHookPullRequestService & ReadableUsersAuthenticator &
|
||||
ReferrerAuthenticator & WritableUsersAuthenticator & CommitStatusService & MergeService & ProtectedBranchService &
|
||||
PrioritiesService =>
|
||||
|
||||
val pullRequestForm = mapping(
|
||||
private val pullRequestForm = mapping(
|
||||
"title" -> trim(label("Title", text(required))),
|
||||
"content" -> trim(label("Content", optional(text()))),
|
||||
"targetUserName" -> trim(text(required, maxlength(100))),
|
||||
"targetBranch" -> trim(text(required, maxlength(100))),
|
||||
"targetBranch" -> trim(text(required, maxlength(255))),
|
||||
"requestUserName" -> 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))),
|
||||
"commitIdTo" -> trim(text(required, maxlength(40))),
|
||||
"isDraft" -> trim(boolean(required)),
|
||||
"assignedUserName" -> trim(optional(text())),
|
||||
"assigneeUserNames" -> trim(optional(text())),
|
||||
"milestoneId" -> trim(optional(number())),
|
||||
"priorityId" -> trim(optional(number())),
|
||||
"labelNames" -> trim(optional(text()))
|
||||
)(PullRequestForm.apply)
|
||||
|
||||
val mergeForm = mapping(
|
||||
private val mergeForm = mapping(
|
||||
"message" -> trim(label("Message", text(required))),
|
||||
"strategy" -> trim(label("Strategy", text(required))),
|
||||
"isDraft" -> trim(boolean(required))
|
||||
)(MergeForm.apply)
|
||||
|
||||
case class PullRequestForm(
|
||||
private case class PullRequestForm(
|
||||
title: String,
|
||||
content: Option[String],
|
||||
targetUserName: String,
|
||||
@@ -90,184 +79,170 @@ trait PullRequestsControllerBase extends ControllerBase {
|
||||
commitIdFrom: String,
|
||||
commitIdTo: String,
|
||||
isDraft: Boolean,
|
||||
assignedUserName: Option[String],
|
||||
assigneeUserNames: Option[String],
|
||||
milestoneId: Option[Int],
|
||||
priorityId: Option[Int],
|
||||
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 =>
|
||||
val q = request.getParameter("q")
|
||||
if (Option(q).exists(_.contains("is:issue"))) {
|
||||
redirect(s"/${repository.owner}/${repository.name}/issues?q=" + StringUtil.urlEncode(q))
|
||||
} else {
|
||||
searchPullRequests(None, repository)
|
||||
Option(q) match {
|
||||
case Some(filter) if filter.contains("is:issue") =>
|
||||
redirect(s"/${repository.owner}/${repository.name}/issues?q=${StringUtil.urlEncode(q)}")
|
||||
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 =>
|
||||
params("id").toIntOpt.flatMap {
|
||||
issueId =>
|
||||
getPullRequest(repository.owner, repository.name, issueId) map {
|
||||
case (issue, pullreq) =>
|
||||
val (commits, diffs) =
|
||||
getRequestCompareInfo(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
pullreq.commitIdFrom,
|
||||
repository.owner,
|
||||
repository.name,
|
||||
pullreq.commitIdTo
|
||||
)
|
||||
params("id").toIntOpt.flatMap { issueId =>
|
||||
getPullRequest(repository.owner, repository.name, issueId) map { case (issue, pullreq) =>
|
||||
val (commits, diffs) =
|
||||
getRequestCompareInfo(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
pullreq.commitIdFrom,
|
||||
repository.owner,
|
||||
repository.name,
|
||||
pullreq.commitIdTo,
|
||||
context.settings
|
||||
)
|
||||
|
||||
html.conversation(
|
||||
issue,
|
||||
pullreq,
|
||||
commits.flatten,
|
||||
getPullRequestComments(repository.owner, repository.name, issue.issueId, commits.flatten),
|
||||
diffs.size,
|
||||
getIssueLabels(repository.owner, repository.name, issueId),
|
||||
getAssignableUserNames(repository.owner, repository.name),
|
||||
getMilestonesWithIssueCount(repository.owner, repository.name),
|
||||
getPriorities(repository.owner, repository.name),
|
||||
getLabels(repository.owner, repository.name),
|
||||
isEditable(repository),
|
||||
isManageable(repository),
|
||||
hasDeveloperRole(pullreq.requestUserName, pullreq.requestRepositoryName, context.loginAccount),
|
||||
repository,
|
||||
getRepository(pullreq.requestUserName, pullreq.requestRepositoryName),
|
||||
flash.iterator.map(f => f._1 -> f._2.toString).toMap
|
||||
)
|
||||
|
||||
// html.pullreq(
|
||||
// issue,
|
||||
// pullreq,
|
||||
// comments,
|
||||
// getIssueLabels(owner, name, issueId),
|
||||
// getAssignableUserNames(owner, name),
|
||||
// getMilestonesWithIssueCount(owner, name),
|
||||
// getPriorities(owner, name),
|
||||
// getLabels(owner, name),
|
||||
// commits,
|
||||
// diffs,
|
||||
// isEditable(repository),
|
||||
// isManageable(repository),
|
||||
// hasDeveloperRole(pullreq.requestUserName, pullreq.requestRepositoryName, context.loginAccount),
|
||||
// repository,
|
||||
// getRepository(pullreq.requestUserName, pullreq.requestRepositoryName),
|
||||
// flash.toMap.map(f => f._1 -> f._2.toString)
|
||||
// )
|
||||
}
|
||||
html.conversation(
|
||||
issue,
|
||||
pullreq,
|
||||
commits.flatten,
|
||||
getPullRequestComments(repository.owner, repository.name, issue.issueId, commits.flatten),
|
||||
diffs.size,
|
||||
getIssueLabels(repository.owner, repository.name, issueId),
|
||||
getIssueAssignees(repository.owner, repository.name, issueId),
|
||||
getAssignableUserNames(repository.owner, repository.name),
|
||||
getMilestonesWithIssueCount(repository.owner, repository.name),
|
||||
getPriorities(repository.owner, repository.name),
|
||||
getLabels(repository.owner, repository.name),
|
||||
getCustomFieldsWithValue(repository.owner, repository.name, issueId).filter(_._1.enableForPullRequests),
|
||||
isEditable(repository),
|
||||
isManageable(repository),
|
||||
hasDeveloperRole(pullreq.requestUserName, pullreq.requestRepositoryName, context.loginAccount),
|
||||
repository,
|
||||
getRepository(pullreq.requestUserName, pullreq.requestRepositoryName),
|
||||
flash.iterator.map(f => f._1 -> f._2.toString).toMap
|
||||
)
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
|
||||
get("/:owner/:repository/pull/:id/commits")(referrersOnly { repository =>
|
||||
params("id").toIntOpt.flatMap {
|
||||
issueId =>
|
||||
getPullRequest(repository.owner, repository.name, issueId) map {
|
||||
case (issue, pullreq) =>
|
||||
val (commits, diffs) =
|
||||
getRequestCompareInfo(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
pullreq.commitIdFrom,
|
||||
repository.owner,
|
||||
repository.name,
|
||||
pullreq.commitIdTo
|
||||
)
|
||||
params("id").toIntOpt.flatMap { issueId =>
|
||||
getPullRequest(repository.owner, repository.name, issueId) map { case (issue, pullreq) =>
|
||||
val (commits, diffs) =
|
||||
getRequestCompareInfo(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
pullreq.commitIdFrom,
|
||||
repository.owner,
|
||||
repository.name,
|
||||
pullreq.commitIdTo,
|
||||
context.settings
|
||||
)
|
||||
|
||||
val commitsWithStatus = commits.map { day =>
|
||||
day.map { commit =>
|
||||
(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
|
||||
)
|
||||
val commitsWithStatus = commits.map { day =>
|
||||
day.map { commit =>
|
||||
(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
|
||||
)
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
|
||||
get("/:owner/:repository/pull/:id/files")(referrersOnly { repository =>
|
||||
params("id").toIntOpt.flatMap {
|
||||
issueId =>
|
||||
getPullRequest(repository.owner, repository.name, issueId) map {
|
||||
case (issue, pullreq) =>
|
||||
val (commits, diffs) =
|
||||
getRequestCompareInfo(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
pullreq.commitIdFrom,
|
||||
repository.owner,
|
||||
repository.name,
|
||||
pullreq.commitIdTo
|
||||
)
|
||||
params("id").toIntOpt.flatMap { issueId =>
|
||||
getPullRequest(repository.owner, repository.name, issueId) map { case (issue, pullreq) =>
|
||||
val (commits, diffs) =
|
||||
getRequestCompareInfo(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
pullreq.commitIdFrom,
|
||||
repository.owner,
|
||||
repository.name,
|
||||
pullreq.commitIdTo,
|
||||
context.settings
|
||||
)
|
||||
|
||||
html.files(
|
||||
issue,
|
||||
pullreq,
|
||||
diffs,
|
||||
commits.flatten,
|
||||
getPullRequestComments(repository.owner, repository.name, issue.issueId, commits.flatten),
|
||||
isManageable(repository),
|
||||
repository
|
||||
)
|
||||
}
|
||||
html.files(
|
||||
issue,
|
||||
pullreq,
|
||||
diffs,
|
||||
commits.flatten,
|
||||
getPullRequestComments(repository.owner, repository.name, issue.issueId, commits.flatten),
|
||||
isManageable(repository),
|
||||
repository
|
||||
)
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
|
||||
ajaxGet("/:owner/:repository/pull/:id/mergeguide")(referrersOnly { repository =>
|
||||
params("id").toIntOpt.flatMap {
|
||||
issueId =>
|
||||
getPullRequest(repository.owner, repository.name, issueId) map {
|
||||
case (issue, pullreq) =>
|
||||
val conflictMessage = LockUtil.lock(s"${repository.owner}/${repository.name}") {
|
||||
checkConflict(repository.owner, repository.name, pullreq.branch, issueId)
|
||||
}
|
||||
val hasMergePermission = hasDeveloperRole(repository.owner, repository.name, context.loginAccount)
|
||||
val branchProtection = getProtectedBranchInfo(repository.owner, repository.name, pullreq.branch)
|
||||
val mergeStatus = PullRequestService.MergeStatus(
|
||||
conflictMessage = conflictMessage,
|
||||
commitStatuses = getCommitStatuses(repository.owner, repository.name, pullreq.commitIdTo),
|
||||
branchProtection = branchProtection,
|
||||
branchIsOutOfDate = JGitUtil.getShaByRef(repository.owner, repository.name, pullreq.branch) != Some(
|
||||
pullreq.commitIdFrom
|
||||
),
|
||||
needStatusCheck = context.loginAccount.forall { u =>
|
||||
branchProtection.needStatusCheck(u.userName)
|
||||
},
|
||||
hasUpdatePermission = hasDeveloperRole(
|
||||
params("id").toIntOpt.flatMap { issueId =>
|
||||
getPullRequest(repository.owner, repository.name, issueId) map { case (issue, pullreq) =>
|
||||
val conflictMessage = LockUtil.lock(s"${repository.owner}/${repository.name}") {
|
||||
checkConflict(repository.owner, repository.name, pullreq.branch, issueId)
|
||||
}
|
||||
val hasMergePermission = hasDeveloperRole(repository.owner, repository.name, context.loginAccount)
|
||||
val branchProtection = getProtectedBranchInfo(repository.owner, repository.name, pullreq.branch)
|
||||
val mergeStatus = PullRequestService.MergeStatus(
|
||||
conflictMessage = conflictMessage,
|
||||
commitStatuses = getCommitStatuses(repository.owner, repository.name, pullreq.commitIdTo),
|
||||
branchProtection = branchProtection,
|
||||
branchIsOutOfDate =
|
||||
!JGitUtil.getShaByRef(repository.owner, repository.name, pullreq.branch).contains(pullreq.commitIdFrom),
|
||||
needStatusCheck = context.loginAccount.forall { u =>
|
||||
branchProtection.needStatusCheck(u.userName)
|
||||
},
|
||||
hasUpdatePermission = hasDeveloperRole(
|
||||
pullreq.requestUserName,
|
||||
pullreq.requestRepositoryName,
|
||||
context.loginAccount
|
||||
) &&
|
||||
context.loginAccount.exists { u =>
|
||||
!getProtectedBranchInfo(
|
||||
pullreq.requestUserName,
|
||||
pullreq.requestRepositoryName,
|
||||
context.loginAccount
|
||||
) &&
|
||||
context.loginAccount.exists { u =>
|
||||
!getProtectedBranchInfo(
|
||||
pullreq.requestUserName,
|
||||
pullreq.requestRepositoryName,
|
||||
pullreq.requestBranch
|
||||
).needStatusCheck(u.userName)
|
||||
},
|
||||
hasMergePermission = hasMergePermission,
|
||||
commitIdTo = pullreq.commitIdTo
|
||||
)
|
||||
html.mergeguide(
|
||||
mergeStatus,
|
||||
issue,
|
||||
pullreq,
|
||||
repository,
|
||||
getRepository(pullreq.requestUserName, pullreq.requestRepositoryName).get
|
||||
)
|
||||
}
|
||||
pullreq.requestBranch
|
||||
).needStatusCheck(u.userName)
|
||||
},
|
||||
hasMergePermission = hasMergePermission,
|
||||
commitIdTo = pullreq.commitIdTo
|
||||
)
|
||||
html.mergeguide(
|
||||
mergeStatus,
|
||||
issue,
|
||||
pullreq,
|
||||
repository,
|
||||
getRepository(pullreq.requestUserName, pullreq.requestRepositoryName).get
|
||||
)
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
|
||||
@@ -275,7 +250,7 @@ trait PullRequestsControllerBase extends ControllerBase {
|
||||
(for {
|
||||
issueId <- params("id").toIntOpt
|
||||
loginAccount <- context.loginAccount
|
||||
(issue, pullreq) <- getPullRequest(baseRepository.owner, baseRepository.name, issueId)
|
||||
case (issue, pullreq) <- getPullRequest(baseRepository.owner, baseRepository.name, issueId)
|
||||
owner = pullreq.requestUserName
|
||||
name = pullreq.requestRepositoryName
|
||||
if hasDeveloperRole(owner, name, context.loginAccount)
|
||||
@@ -313,7 +288,7 @@ trait PullRequestsControllerBase extends ControllerBase {
|
||||
(for {
|
||||
issueId <- params("id").toIntOpt
|
||||
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)
|
||||
remoteRepository <- getRepository(pullreq.userName, pullreq.repositoryName)
|
||||
owner = pullreq.requestUserName
|
||||
@@ -324,34 +299,36 @@ trait PullRequestsControllerBase extends ControllerBase {
|
||||
if (branchProtection.needStatusCheck(loginAccount.userName)) {
|
||||
flash.update("error", s"branch ${pullreq.requestBranch} is protected need status check.")
|
||||
} else {
|
||||
LockUtil.lock(s"${owner}/${name}") {
|
||||
LockUtil.lock(s"$owner/$name") {
|
||||
val alias =
|
||||
if (pullreq.repositoryName == pullreq.requestRepositoryName && pullreq.userName == pullreq.requestUserName) {
|
||||
if (
|
||||
pullreq.repositoryName == pullreq.requestRepositoryName && pullreq.userName == pullreq.requestUserName
|
||||
) {
|
||||
pullreq.branch
|
||||
} else {
|
||||
s"${pullreq.userName}:${pullreq.branch}"
|
||||
}
|
||||
val existIds = Using
|
||||
.resource(Git.open(Directory.getRepositoryDir(owner, name))) { git =>
|
||||
JGitUtil.getAllCommitIds(git)
|
||||
}
|
||||
.toSet
|
||||
// val existIds = Using
|
||||
// .resource(Git.open(Directory.getRepositoryDir(owner, name))) { git =>
|
||||
// JGitUtil.getAllCommitIds(git)
|
||||
// }
|
||||
// .toSet
|
||||
pullRemote(
|
||||
repository,
|
||||
pullreq.requestBranch,
|
||||
remoteRepository,
|
||||
pullreq.branch,
|
||||
loginAccount,
|
||||
s"Merge branch '${alias}' into ${pullreq.requestBranch}",
|
||||
s"Merge branch '$alias' into ${pullreq.requestBranch}",
|
||||
Some(pullreq),
|
||||
context.settings
|
||||
) match {
|
||||
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) =>
|
||||
// update pull request
|
||||
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}")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -363,7 +340,7 @@ trait PullRequestsControllerBase extends ControllerBase {
|
||||
post("/:owner/:repository/pull/:id/update_draft")(readableUsersOnly { baseRepository =>
|
||||
(for {
|
||||
issueId <- params("id").toIntOpt
|
||||
(_, pullreq) <- getPullRequest(baseRepository.owner, baseRepository.name, issueId)
|
||||
case (_, pullreq) <- getPullRequest(baseRepository.owner, baseRepository.name, issueId)
|
||||
owner = pullreq.requestUserName
|
||||
name = pullreq.requestRepositoryName
|
||||
if hasDeveloperRole(owner, name, context.loginAccount)
|
||||
@@ -384,7 +361,7 @@ trait PullRequestsControllerBase extends ControllerBase {
|
||||
form.isDraft,
|
||||
context.settings
|
||||
) 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))
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
@@ -392,79 +369,86 @@ trait PullRequestsControllerBase extends ControllerBase {
|
||||
})
|
||||
|
||||
get("/:owner/:repository/compare")(referrersOnly { forkedRepository =>
|
||||
val headBranch: Option[String] = params.get("head")
|
||||
val headBranch = params.get("head")
|
||||
(forkedRepository.repository.originUserName, forkedRepository.repository.originRepositoryName) match {
|
||||
case (Some(originUserName), Some(originRepositoryName)) => {
|
||||
getRepository(originUserName, originRepositoryName).map {
|
||||
originRepository =>
|
||||
Using.resources(
|
||||
Git.open(getRepositoryDir(originUserName, originRepositoryName)),
|
||||
Git.open(getRepositoryDir(forkedRepository.owner, forkedRepository.name))
|
||||
) { (oldGit, newGit) =>
|
||||
val newBranch = headBranch.getOrElse(JGitUtil.getDefaultBranch(newGit, forkedRepository).get._2)
|
||||
val oldBranch = originRepository.branchList
|
||||
.find(_ == newBranch)
|
||||
.getOrElse(JGitUtil.getDefaultBranch(oldGit, originRepository).get._2)
|
||||
case (Some(originUserName), Some(originRepositoryName)) =>
|
||||
getRepository(originUserName, originRepositoryName).map { originRepository =>
|
||||
Using.resources(
|
||||
Git.open(getRepositoryDir(originUserName, originRepositoryName)),
|
||||
Git.open(getRepositoryDir(forkedRepository.owner, forkedRepository.name))
|
||||
) { (oldGit, newGit) =>
|
||||
val newBranch = headBranch.getOrElse(JGitUtil.getDefaultBranch(newGit, forkedRepository).get._2)
|
||||
val oldBranch = originRepository.branchList
|
||||
.find(_ == newBranch)
|
||||
.getOrElse(JGitUtil.getDefaultBranch(oldGit, originRepository).get._2)
|
||||
|
||||
redirect(
|
||||
s"/${forkedRepository.owner}/${forkedRepository.name}/compare/${originUserName}:${oldBranch}...${newBranch}"
|
||||
)
|
||||
}
|
||||
redirect(
|
||||
s"/${forkedRepository.owner}/${forkedRepository.name}/compare/$originUserName:$oldBranch...$newBranch"
|
||||
)
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
}
|
||||
case _ => {
|
||||
case _ =>
|
||||
Using.resource(Git.open(getRepositoryDir(forkedRepository.owner, forkedRepository.name))) { git =>
|
||||
JGitUtil.getDefaultBranch(git, forkedRepository).map {
|
||||
case (_, defaultBranch) =>
|
||||
redirect(
|
||||
s"/${forkedRepository.owner}/${forkedRepository.name}/compare/${defaultBranch}...${headBranch.getOrElse(defaultBranch)}"
|
||||
)
|
||||
JGitUtil.getDefaultBranch(git, forkedRepository).map { case (_, defaultBranch) =>
|
||||
redirect(
|
||||
s"/${forkedRepository.owner}/${forkedRepository.name}/compare/$defaultBranch...${headBranch.getOrElse(defaultBranch)}"
|
||||
)
|
||||
} getOrElse {
|
||||
redirect(s"/${forkedRepository.owner}/${forkedRepository.name}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
private def getOriginRepositoryName(
|
||||
originOwner: String,
|
||||
forkedOwner: String,
|
||||
forkedRepository: RepositoryInfo
|
||||
): Option[String] = {
|
||||
if (originOwner == forkedOwner) {
|
||||
// Self repository
|
||||
Some(forkedRepository.name)
|
||||
} else if (forkedRepository.repository.originUserName.isEmpty) {
|
||||
// when ForkedRepository is the original repository
|
||||
getForkedRepositories(forkedRepository.owner, forkedRepository.name)
|
||||
.find(_.userName == originOwner)
|
||||
.map(_.repositoryName)
|
||||
} else if (forkedRepository.repository.originUserName.contains(originOwner)) {
|
||||
// Original repository
|
||||
forkedRepository.repository.originRepositoryName
|
||||
} else {
|
||||
// Sibling repository
|
||||
getUserRepositories(originOwner)
|
||||
.find { x =>
|
||||
x.repository.originUserName == forkedRepository.repository.originUserName &&
|
||||
x.repository.originRepositoryName == forkedRepository.repository.originRepositoryName
|
||||
}
|
||||
.map(_.repository.repositoryName)
|
||||
}
|
||||
}
|
||||
|
||||
get("/:owner/:repository/compare/*...*")(referrersOnly { forkedRepository =>
|
||||
val Seq(origin, forked) = multiParams("splat")
|
||||
val (originOwner, originId) = parseCompareIdentifier(origin, forkedRepository.owner)
|
||||
val (forkedOwner, forkedId) = parseCompareIdentifier(forked, forkedRepository.owner)
|
||||
|
||||
(for (originRepositoryName <- if (originOwner == forkedOwner) {
|
||||
// Self repository
|
||||
Some(forkedRepository.name)
|
||||
} else if (forkedRepository.repository.originUserName.isEmpty) {
|
||||
// when ForkedRepository is the original repository
|
||||
getForkedRepositories(forkedRepository.owner, forkedRepository.name)
|
||||
.find(_.userName == originOwner)
|
||||
.map(_.repositoryName)
|
||||
} else if (Some(originOwner) == forkedRepository.repository.originUserName) {
|
||||
// Original repository
|
||||
forkedRepository.repository.originRepositoryName
|
||||
} else {
|
||||
// Sibling repository
|
||||
getUserRepositories(originOwner)
|
||||
.find { x =>
|
||||
x.repository.originUserName == forkedRepository.repository.originUserName &&
|
||||
x.repository.originRepositoryName == forkedRepository.repository.originRepositoryName
|
||||
}
|
||||
.map(_.repository.repositoryName)
|
||||
};
|
||||
originRepository <- getRepository(originOwner, originRepositoryName)) yield {
|
||||
(for (
|
||||
originRepositoryName <- getOriginRepositoryName(originOwner, forkedOwner, forkedRepository);
|
||||
originRepository <- getRepository(originOwner, originRepositoryName)
|
||||
) yield {
|
||||
val (oldId, newId) =
|
||||
getPullRequestCommitFromTo(originRepository, forkedRepository, originId, forkedId)
|
||||
|
||||
(oldId, newId) match {
|
||||
case (Some(oldId), Some(newId)) => {
|
||||
case (Some(oldId), Some(newId)) =>
|
||||
val (commits, diffs) = getRequestCompareInfo(
|
||||
originRepository.owner,
|
||||
originRepository.name,
|
||||
oldId.getName,
|
||||
forkedRepository.owner,
|
||||
forkedRepository.name,
|
||||
newId.getName
|
||||
newId.getName,
|
||||
context.settings
|
||||
)
|
||||
|
||||
val title = if (commits.flatten.length == 1) {
|
||||
@@ -490,7 +474,9 @@ trait PullRequestsControllerBase extends ControllerBase {
|
||||
(repository.userName, repository.repositoryName, repository.defaultBranch)
|
||||
},
|
||||
commits.flatten
|
||||
.flatMap(commit => getCommitComments(forkedRepository.owner, forkedRepository.name, commit.id, false))
|
||||
.flatMap(commit =>
|
||||
getCommitComments(forkedRepository.owner, forkedRepository.name, commit.id, includePullRequest = false)
|
||||
)
|
||||
.toList,
|
||||
originId,
|
||||
forkedId,
|
||||
@@ -505,101 +491,155 @@ trait PullRequestsControllerBase extends ControllerBase {
|
||||
getMilestones(originRepository.owner, originRepository.name),
|
||||
getPriorities(originRepository.owner, originRepository.name),
|
||||
getDefaultPriority(originRepository.owner, originRepository.name),
|
||||
getLabels(originRepository.owner, originRepository.name)
|
||||
getLabels(originRepository.owner, originRepository.name),
|
||||
getCustomFields(originRepository.owner, originRepository.name).filter(_.enableForPullRequests)
|
||||
)
|
||||
}
|
||||
case (oldId, newId) =>
|
||||
redirect(
|
||||
s"/${forkedRepository.owner}/${forkedRepository.name}/compare/" +
|
||||
s"${originOwner}:${oldId.map(_ => originId).getOrElse(originRepository.repository.defaultBranch)}..." +
|
||||
s"${forkedOwner}:${newId.map(_ => forkedId).getOrElse(forkedRepository.repository.defaultBranch)}"
|
||||
s"$originOwner:${oldId.map(_ => originId).getOrElse(originRepository.repository.defaultBranch)}..." +
|
||||
s"$forkedOwner:${newId.map(_ => forkedId).getOrElse(forkedRepository.repository.defaultBranch)}"
|
||||
)
|
||||
|
||||
}
|
||||
}) getOrElse NotFound()
|
||||
})
|
||||
|
||||
ajaxGet("/:owner/:repository/diff/:id")(referrersOnly { repository =>
|
||||
(for {
|
||||
commitId <- params.get("id")
|
||||
path <- params.get("path")
|
||||
diff <- getSingleDiff(repository.owner, repository.name, commitId, path)
|
||||
} yield {
|
||||
contentType = formats("json")
|
||||
org.json4s.jackson.Serialization.write(
|
||||
Map(
|
||||
"oldContent" -> diff.oldContent,
|
||||
"newContent" -> diff.newContent
|
||||
)
|
||||
)
|
||||
}) getOrElse NotFound()
|
||||
})
|
||||
|
||||
ajaxGet("/:owner/:repository/diff/*...*")(referrersOnly { forkedRepository =>
|
||||
val Seq(origin, forked) = multiParams("splat")
|
||||
val (originOwner, originId) = parseCompareIdentifier(origin, forkedRepository.owner)
|
||||
val (forkedOwner, forkedId) = parseCompareIdentifier(forked, forkedRepository.owner)
|
||||
|
||||
(for {
|
||||
path <- params.get("path")
|
||||
originRepositoryName <- getOriginRepositoryName(originOwner, forkedOwner, forkedRepository)
|
||||
originRepository <- getRepository(originOwner, originRepositoryName)
|
||||
(oldId, newId) = getPullRequestCommitFromTo(originRepository, forkedRepository, originId, forkedId)
|
||||
oldId <- oldId
|
||||
newId <- newId
|
||||
diff <- getSingleDiff(
|
||||
originRepository.owner,
|
||||
originRepository.name,
|
||||
oldId.getName,
|
||||
forkedRepository.owner,
|
||||
forkedRepository.name,
|
||||
newId.getName,
|
||||
path
|
||||
)
|
||||
} yield {
|
||||
contentType = formats("json")
|
||||
org.json4s.jackson.Serialization.write(
|
||||
Map(
|
||||
"oldContent" -> diff.oldContent,
|
||||
"newContent" -> diff.newContent
|
||||
)
|
||||
)
|
||||
}) getOrElse NotFound()
|
||||
})
|
||||
|
||||
ajaxGet("/:owner/:repository/compare/*...*/mergecheck")(readableUsersOnly { forkedRepository =>
|
||||
val Seq(origin, forked) = multiParams("splat")
|
||||
val (originOwner, tmpOriginBranch) = parseCompareIdentifier(origin, forkedRepository.owner)
|
||||
val (forkedOwner, tmpForkedBranch) = parseCompareIdentifier(forked, forkedRepository.owner)
|
||||
|
||||
(for (originRepositoryName <- if (originOwner == forkedOwner) {
|
||||
Some(forkedRepository.name)
|
||||
} else {
|
||||
forkedRepository.repository.originRepositoryName.orElse {
|
||||
getForkedRepositories(forkedRepository.owner, forkedRepository.name)
|
||||
.find(_.userName == originOwner)
|
||||
.map(_.repositoryName)
|
||||
}
|
||||
};
|
||||
originRepository <- getRepository(originOwner, originRepositoryName)) yield {
|
||||
(for {
|
||||
originRepositoryName <-
|
||||
if (originOwner == forkedOwner) {
|
||||
Some(forkedRepository.name)
|
||||
} else {
|
||||
forkedRepository.repository.originRepositoryName.orElse {
|
||||
getForkedRepositories(forkedRepository.owner, forkedRepository.name)
|
||||
.find(_.userName == originOwner)
|
||||
.map(_.repositoryName)
|
||||
}
|
||||
}
|
||||
originRepository <- getRepository(originOwner, originRepositoryName)
|
||||
} yield {
|
||||
Using.resources(
|
||||
Git.open(getRepositoryDir(originRepository.owner, originRepository.name)),
|
||||
Git.open(getRepositoryDir(forkedRepository.owner, forkedRepository.name))
|
||||
) {
|
||||
case (oldGit, newGit) =>
|
||||
val originBranch = JGitUtil.getDefaultBranch(oldGit, originRepository, tmpOriginBranch).get._2
|
||||
val forkedBranch = JGitUtil.getDefaultBranch(newGit, forkedRepository, tmpForkedBranch).get._2
|
||||
val conflict = LockUtil.lock(s"${originRepository.owner}/${originRepository.name}") {
|
||||
checkConflict(
|
||||
originRepository.owner,
|
||||
originRepository.name,
|
||||
originBranch,
|
||||
forkedRepository.owner,
|
||||
forkedRepository.name,
|
||||
forkedBranch
|
||||
)
|
||||
}
|
||||
html.mergecheck(conflict.isDefined)
|
||||
) { case (oldGit, newGit) =>
|
||||
val originBranch = JGitUtil.getDefaultBranch(oldGit, originRepository, tmpOriginBranch).get._2
|
||||
val forkedBranch = JGitUtil.getDefaultBranch(newGit, forkedRepository, tmpForkedBranch).get._2
|
||||
val conflict = LockUtil.lock(s"${originRepository.owner}/${originRepository.name}") {
|
||||
checkConflict(
|
||||
originRepository.owner,
|
||||
originRepository.name,
|
||||
originBranch,
|
||||
forkedRepository.owner,
|
||||
forkedRepository.name,
|
||||
forkedBranch
|
||||
)
|
||||
}
|
||||
html.mergecheck(conflict.isDefined)
|
||||
}
|
||||
}) getOrElse NotFound()
|
||||
})
|
||||
|
||||
post("/:owner/:repository/pulls/new", pullRequestForm)(readableUsersOnly { (form, repository) =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
val manageable = isManageable(repository)
|
||||
context.withLoginAccount { loginAccount =>
|
||||
val manageable = isManageable(repository)
|
||||
|
||||
val issueId = insertIssue(
|
||||
owner = repository.owner,
|
||||
repository = repository.name,
|
||||
loginUser = loginAccount.userName,
|
||||
title = form.title,
|
||||
content = form.content,
|
||||
assignedUserName = if (manageable) form.assignedUserName else None,
|
||||
milestoneId = if (manageable) form.milestoneId else None,
|
||||
priorityId = if (manageable) form.priorityId else None,
|
||||
isPullRequest = true
|
||||
)
|
||||
val issueId = insertIssue(
|
||||
owner = repository.owner,
|
||||
repository = repository.name,
|
||||
loginUser = loginAccount.userName,
|
||||
title = form.title,
|
||||
content = form.content,
|
||||
milestoneId = if (manageable) form.milestoneId else None,
|
||||
priorityId = if (manageable) form.priorityId else None,
|
||||
isPullRequest = true
|
||||
)
|
||||
|
||||
createPullRequest(
|
||||
originRepository = repository,
|
||||
issueId = issueId,
|
||||
originBranch = form.targetBranch,
|
||||
requestUserName = form.requestUserName,
|
||||
requestRepositoryName = form.requestRepositoryName,
|
||||
requestBranch = form.requestBranch,
|
||||
commitIdFrom = form.commitIdFrom,
|
||||
commitIdTo = form.commitIdTo,
|
||||
isDraft = form.isDraft,
|
||||
loginAccount = loginAccount,
|
||||
settings = context.settings
|
||||
)
|
||||
createPullRequest(
|
||||
originRepository = repository,
|
||||
issueId = issueId,
|
||||
originBranch = form.targetBranch,
|
||||
requestUserName = form.requestUserName,
|
||||
requestRepositoryName = form.requestRepositoryName,
|
||||
requestBranch = form.requestBranch,
|
||||
commitIdFrom = form.commitIdFrom,
|
||||
commitIdTo = form.commitIdTo,
|
||||
isDraft = form.isDraft,
|
||||
loginAccount = loginAccount,
|
||||
settings = context.settings
|
||||
)
|
||||
|
||||
if (manageable) {
|
||||
// insert assignees
|
||||
form.assigneeUserNames.foreach { value =>
|
||||
value.split(",").foreach { userName =>
|
||||
registerIssueAssignee(repository.owner, repository.name, issueId, userName)
|
||||
}
|
||||
}
|
||||
// insert labels
|
||||
if (manageable) {
|
||||
form.labelNames.foreach { value =>
|
||||
val labels = getLabels(repository.owner, repository.name)
|
||||
value.split(",").foreach { labelName =>
|
||||
labels.find(_.labelName == labelName).map { label =>
|
||||
registerIssueLabel(repository.owner, repository.name, issueId, label.labelId)
|
||||
}
|
||||
form.labelNames.foreach { value =>
|
||||
val labels = getLabels(repository.owner, repository.name)
|
||||
value.split(",").foreach { labelName =>
|
||||
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")
|
||||
}
|
||||
})
|
||||
|
||||
@@ -609,24 +649,23 @@ trait PullRequestsControllerBase extends ControllerBase {
|
||||
context.loginAccount.map(x => Seq(x.mailAddress) ++ getAccountExtraMailAddresses(x.userName)).getOrElse(Nil)
|
||||
|
||||
val branches =
|
||||
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
|
||||
git =>
|
||||
JGitUtil
|
||||
.getBranches(
|
||||
git = git,
|
||||
defaultBranch = repository.repository.defaultBranch,
|
||||
origin = repository.repository.originUserName.isEmpty
|
||||
)
|
||||
.filter { x =>
|
||||
x.mergeInfo.map(_.ahead).getOrElse(0) > 0 && x.mergeInfo.map(_.behind).getOrElse(0) == 0 &&
|
||||
x.commitTime.getTime > thresholdTime &&
|
||||
mailAddresses.contains(x.committerEmailAddress)
|
||||
}
|
||||
.sortBy { br =>
|
||||
(br.mergeInfo.isEmpty, br.commitTime)
|
||||
}
|
||||
.map(_.name)
|
||||
.reverse
|
||||
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
|
||||
JGitUtil
|
||||
.getBranches(
|
||||
git = git,
|
||||
defaultBranch = repository.repository.defaultBranch,
|
||||
origin = repository.repository.originUserName.isEmpty
|
||||
)
|
||||
.filter { x =>
|
||||
x.mergeInfo.map(_.ahead).getOrElse(0) > 0 && x.mergeInfo.map(_.behind).getOrElse(0) == 0 &&
|
||||
x.commitTime.getTime > thresholdTime &&
|
||||
mailAddresses.contains(x.committerEmailAddress)
|
||||
}
|
||||
.sortBy { br =>
|
||||
(br.mergeInfo.isEmpty, br.commitTime)
|
||||
}
|
||||
.map(_.name)
|
||||
.reverse
|
||||
}
|
||||
|
||||
val targetRepository = (for {
|
||||
@@ -646,10 +685,11 @@ trait PullRequestsControllerBase extends ControllerBase {
|
||||
html.proposals(proposedBranches, targetRepository, repository)
|
||||
})
|
||||
|
||||
private def searchPullRequests(userName: Option[String], repository: RepositoryService.RepositoryInfo) = {
|
||||
val page = IssueSearchCondition.page(request)
|
||||
// retrieve search condition
|
||||
val condition = IssueSearchCondition(request)
|
||||
private def searchPullRequests(
|
||||
repository: RepositoryService.RepositoryInfo,
|
||||
condition: IssueSearchCondition,
|
||||
page: Int
|
||||
) = {
|
||||
// search issues
|
||||
val issues = searchIssue(
|
||||
condition,
|
||||
|
||||
@@ -11,10 +11,10 @@ import gitbucket.core.service.{
|
||||
RepositoryService,
|
||||
RequestCache
|
||||
}
|
||||
import gitbucket.core.util._
|
||||
import gitbucket.core.util.Directory._
|
||||
import gitbucket.core.util.Implicits._
|
||||
import org.scalatra.forms._
|
||||
import gitbucket.core.util.*
|
||||
import gitbucket.core.util.Directory.*
|
||||
import gitbucket.core.util.Implicits.*
|
||||
import org.scalatra.forms.*
|
||||
import gitbucket.core.releases.html
|
||||
import org.apache.commons.io.FileUtils
|
||||
import org.eclipse.jgit.api.Git
|
||||
@@ -33,20 +33,15 @@ class ReleaseController
|
||||
with RequestCache
|
||||
|
||||
trait ReleaseControllerBase extends ControllerBase {
|
||||
self: RepositoryService
|
||||
with AccountService
|
||||
with ReleaseService
|
||||
with ReadableUsersAuthenticator
|
||||
with ReferrerAuthenticator
|
||||
with WritableUsersAuthenticator
|
||||
with ActivityService =>
|
||||
self: RepositoryService & AccountService & ReleaseService & ReadableUsersAuthenticator & ReferrerAuthenticator &
|
||||
WritableUsersAuthenticator & ActivityService =>
|
||||
|
||||
case class ReleaseForm(
|
||||
private case class ReleaseForm(
|
||||
name: String,
|
||||
content: Option[String]
|
||||
)
|
||||
|
||||
val releaseForm = mapping(
|
||||
private val releaseForm = mapping(
|
||||
"name" -> trim(text(required)),
|
||||
"content" -> trim(optional(text()))
|
||||
)(ReleaseForm.apply)
|
||||
@@ -106,42 +101,39 @@ trait ReleaseControllerBase extends ControllerBase {
|
||||
})
|
||||
|
||||
post("/:owner/:repository/releases/*/create", releaseForm)(writableUsersOnly { (form, repository) =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
val tagName = multiParams("splat").head
|
||||
context.withLoginAccount { loginAccount =>
|
||||
val tagName = multiParams("splat").head
|
||||
|
||||
// Insert into RELEASE
|
||||
createRelease(repository.owner, repository.name, form.name, form.content, tagName, loginAccount)
|
||||
// Insert into RELEASE
|
||||
createRelease(repository.owner, repository.name, form.name, form.content, tagName, loginAccount)
|
||||
|
||||
// Insert into RELEASE_ASSET
|
||||
val files = params.toMap.collect {
|
||||
case (name, value) if name.startsWith("file:") =>
|
||||
val Array(_, fileId) = name.split(":")
|
||||
(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)
|
||||
}
|
||||
// Insert into RELEASE_ASSET
|
||||
val files = params.toMap.collect {
|
||||
case (name, value) if name.startsWith("file:") =>
|
||||
val Array(_, fileId) = name.split(":")
|
||||
(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)
|
||||
}
|
||||
|
||||
val releaseInfo = ReleaseInfo(repository.owner, repository.name, loginAccount.userName, form.name, tagName)
|
||||
recordActivity(releaseInfo)
|
||||
val releaseInfo = ReleaseInfo(repository.owner, repository.name, loginAccount.userName, form.name, tagName)
|
||||
recordActivity(releaseInfo)
|
||||
|
||||
redirect(s"/${repository.owner}/${repository.name}/releases/${tagName}")
|
||||
redirect(s"/${repository.owner}/${repository.name}/releases/$tagName")
|
||||
}
|
||||
})
|
||||
|
||||
get("/:owner/:repository/changelog/*...*")(writableUsersOnly { repository =>
|
||||
val Seq(previousTag, currentTag) = multiParams("splat")
|
||||
val previousTagId = repository.tags.collectFirst { case x if x.name == previousTag => x.id }.getOrElse("")
|
||||
|
||||
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
|
||||
.map { commit =>
|
||||
s"- ${commit.shortMessage} ${commit.id}"
|
||||
@@ -171,48 +163,45 @@ trait ReleaseControllerBase extends ControllerBase {
|
||||
})
|
||||
|
||||
post("/:owner/:repository/releases/*/edit", releaseForm)(writableUsersOnly { (form, repository) =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
val tagName = multiParams("splat").head
|
||||
context.withLoginAccount { loginAccount =>
|
||||
val tagName = multiParams("splat").head
|
||||
|
||||
getRelease(repository.owner, repository.name, tagName)
|
||||
.map {
|
||||
release =>
|
||||
// Update RELEASE
|
||||
updateRelease(repository.owner, repository.name, tagName, form.name, form.content)
|
||||
getRelease(repository.owner, repository.name, tagName)
|
||||
.map { release =>
|
||||
// Update RELEASE
|
||||
updateRelease(repository.owner, repository.name, tagName, form.name, form.content)
|
||||
|
||||
// Delete and Insert RELEASE_ASSET
|
||||
val assets = getReleaseAssets(repository.owner, repository.name, tagName)
|
||||
deleteReleaseAssets(repository.owner, repository.name, tagName)
|
||||
// Delete and Insert RELEASE_ASSET
|
||||
val assets = getReleaseAssets(repository.owner, repository.name, tagName)
|
||||
deleteReleaseAssets(repository.owner, repository.name, tagName)
|
||||
|
||||
val files = params.toMap.collect {
|
||||
case (name, value) if name.startsWith("file:") =>
|
||||
val Array(_, fileId) = name.split(":")
|
||||
(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}")
|
||||
val files = params.toMap.collect {
|
||||
case (name, value) if name.startsWith("file:") =>
|
||||
val Array(_, fileId) = name.split(":")
|
||||
(fileId, value)
|
||||
}
|
||||
.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) = {
|
||||
import gitbucket.core.service.ReleaseService._
|
||||
import gitbucket.core.service.ReleaseService.*
|
||||
|
||||
val (offset, limit) = ((page - 1) * ReleaseLimit, ReleaseLimit)
|
||||
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 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
|
||||
}
|
||||
|
||||
@@ -2,26 +2,25 @@ package gitbucket.core.controller
|
||||
|
||||
import java.time.{LocalDateTime, ZoneOffset}
|
||||
import java.util.Date
|
||||
|
||||
import gitbucket.core.settings.html
|
||||
import gitbucket.core.model.{RepositoryWebHook, WebHook}
|
||||
import gitbucket.core.service._
|
||||
import gitbucket.core.service.WebHookService._
|
||||
import gitbucket.core.util._
|
||||
import gitbucket.core.util.JGitUtil._
|
||||
import gitbucket.core.util.SyntaxSugars._
|
||||
import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.util.Directory._
|
||||
import gitbucket.core.service.*
|
||||
import gitbucket.core.service.WebHookService.*
|
||||
import gitbucket.core.util.*
|
||||
import gitbucket.core.util.JGitUtil.*
|
||||
import gitbucket.core.util.SyntaxSugars.*
|
||||
import gitbucket.core.util.Implicits.*
|
||||
import gitbucket.core.util.Directory.*
|
||||
import gitbucket.core.model.WebHookContentType
|
||||
import gitbucket.core.model.activity.RenameRepositoryInfo
|
||||
import org.scalatra.forms._
|
||||
import org.scalatra.forms.*
|
||||
import org.scalatra.i18n.Messages
|
||||
import org.eclipse.jgit.api.Git
|
||||
import org.eclipse.jgit.lib.Constants
|
||||
import org.eclipse.jgit.lib.ObjectId
|
||||
|
||||
import scala.util.Using
|
||||
import org.scalatra.Forbidden
|
||||
import org.scalatra.{Forbidden, Ok}
|
||||
|
||||
class RepositorySettingsController
|
||||
extends RepositorySettingsControllerBase
|
||||
@@ -31,24 +30,18 @@ class RepositorySettingsController
|
||||
with ProtectedBranchService
|
||||
with CommitStatusService
|
||||
with DeployKeyService
|
||||
with CustomFieldsService
|
||||
with ActivityService
|
||||
with OwnerAuthenticator
|
||||
with UsersAuthenticator
|
||||
with RequestCache
|
||||
|
||||
trait RepositorySettingsControllerBase extends ControllerBase {
|
||||
self: RepositoryService
|
||||
with AccountService
|
||||
with WebHookService
|
||||
with ProtectedBranchService
|
||||
with CommitStatusService
|
||||
with DeployKeyService
|
||||
with ActivityService
|
||||
with OwnerAuthenticator
|
||||
with UsersAuthenticator =>
|
||||
self: RepositoryService & AccountService & WebHookService & ProtectedBranchService & CommitStatusService &
|
||||
DeployKeyService & CustomFieldsService & ActivityService & OwnerAuthenticator & UsersAuthenticator =>
|
||||
|
||||
// for repository options
|
||||
case class OptionsForm(
|
||||
private case class OptionsForm(
|
||||
description: Option[String],
|
||||
isPrivate: Boolean,
|
||||
issuesOption: String,
|
||||
@@ -61,7 +54,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
|
||||
safeMode: Boolean
|
||||
)
|
||||
|
||||
val optionsForm = mapping(
|
||||
private val optionsForm = mapping(
|
||||
"description" -> trim(label("Description", optional(text()))),
|
||||
"isPrivate" -> trim(label("Repository Type", boolean())),
|
||||
"issuesOption" -> trim(label("Issues Option", text(required, featureOption))),
|
||||
@@ -79,25 +72,30 @@ trait RepositorySettingsControllerBase extends ControllerBase {
|
||||
}
|
||||
|
||||
// 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))))
|
||||
)(DefaultBranchForm.apply)
|
||||
|
||||
// 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)))),
|
||||
"publicKey" -> trim2(label("Key", text(required))), // TODO duplication check in the repository?
|
||||
"allowWrite" -> trim(label("Key", boolean()))
|
||||
)(DeployKeyForm.apply)
|
||||
|
||||
// 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(
|
||||
"url" -> trim(label("url", text(required, webHook(update)))),
|
||||
"events" -> webhookEvents,
|
||||
@@ -106,21 +104,38 @@ trait RepositorySettingsControllerBase extends ControllerBase {
|
||||
)((url, events, ctype, token) => WebHookForm(url, events, WebHookContentType.valueOf(ctype), token))
|
||||
|
||||
// for rename repository
|
||||
case class RenameRepositoryForm(repositoryName: String)
|
||||
private case class RenameRepositoryForm(repositoryName: String)
|
||||
|
||||
val renameForm = mapping(
|
||||
private val renameForm = mapping(
|
||||
"repositoryName" -> trim(
|
||||
label("New repository name", text(required, maxlength(100), repository, renameRepositoryName))
|
||||
)
|
||||
)(RenameRepositoryForm.apply)
|
||||
|
||||
// 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)))
|
||||
)(TransferOwnerShipForm.apply)
|
||||
|
||||
// for custom field
|
||||
private case class CustomFieldForm(
|
||||
fieldName: String,
|
||||
fieldType: String,
|
||||
constraints: Option[String],
|
||||
enableForIssues: Boolean,
|
||||
enableForPullRequests: Boolean
|
||||
)
|
||||
|
||||
private val customFieldForm = mapping(
|
||||
"fieldName" -> trim(label("Field name", text(required, maxlength(100)))),
|
||||
"fieldType" -> trim(label("Field type", text(required))),
|
||||
"constraints" -> trim(label("Constraints", optional(text()))),
|
||||
"enableForIssues" -> trim(label("Enable for issues", boolean(required))),
|
||||
"enableForPullRequests" -> trim(label("Enable for pull requests", boolean(required))),
|
||||
)(CustomFieldForm.apply)
|
||||
|
||||
/**
|
||||
* Redirect to the Options page.
|
||||
*/
|
||||
@@ -168,7 +183,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
|
||||
/** Update default branch */
|
||||
post("/:owner/:repository/settings/update_default_branch", defaultBranchForm)(ownerOnly { (form, repository) =>
|
||||
if (!repository.branchList.contains(form.defaultBranch)) {
|
||||
redirect(s"/${repository.owner}/${repository.name}/settings/options")
|
||||
redirect(s"/${repository.owner}/${repository.name}/settings/branches")
|
||||
} else {
|
||||
saveRepositoryDefaultBranch(repository.owner, repository.name, form.defaultBranch)
|
||||
// Change repository HEAD
|
||||
@@ -182,13 +197,13 @@ trait RepositorySettingsControllerBase extends ControllerBase {
|
||||
|
||||
/** Branch protection for branch */
|
||||
get("/:owner/:repository/settings/branches/*")(ownerOnly { repository =>
|
||||
import gitbucket.core.api._
|
||||
import gitbucket.core.api.*
|
||||
val branch = params("splat")
|
||||
|
||||
if (!repository.branchList.contains(branch)) {
|
||||
redirect(s"/${repository.owner}/${repository.name}/settings/branches")
|
||||
} else {
|
||||
val protection = ApiBranchProtection(getProtectedBranchInfo(repository.owner, repository.name, branch))
|
||||
val protection = ApiBranchProtectionResponse(getProtectedBranchInfo(repository.owner, repository.name, branch))
|
||||
val lastWeeks = getRecentStatusContexts(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
@@ -238,7 +253,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
|
||||
ctype = WebHookContentType.FORM,
|
||||
token = None
|
||||
)
|
||||
html.edithook(webhook, Set(WebHook.Push), repository, true)
|
||||
html.edithook(webhook, Set(WebHook.Push), repository, create = true)
|
||||
})
|
||||
|
||||
/**
|
||||
@@ -268,93 +283,90 @@ trait RepositorySettingsControllerBase extends ControllerBase {
|
||||
Array(h.getName, h.getValue)
|
||||
}
|
||||
|
||||
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
|
||||
git =>
|
||||
import scala.concurrent.duration._
|
||||
import scala.concurrent._
|
||||
import scala.jdk.CollectionConverters._
|
||||
import scala.util.control.NonFatal
|
||||
import org.apache.http.util.EntityUtils
|
||||
import scala.concurrent.ExecutionContext.Implicits.global
|
||||
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
|
||||
import scala.concurrent.duration.*
|
||||
import scala.concurrent.*
|
||||
import scala.jdk.CollectionConverters.*
|
||||
import scala.util.control.NonFatal
|
||||
import org.apache.http.util.EntityUtils
|
||||
import scala.concurrent.ExecutionContext.Implicits.global
|
||||
|
||||
val url = params("url")
|
||||
val token = Some(params("token"))
|
||||
val ctype = WebHookContentType.valueOf(params("ctype"))
|
||||
val dummyWebHookInfo = RepositoryWebHook(
|
||||
userName = repository.owner,
|
||||
repositoryName = repository.name,
|
||||
url = url,
|
||||
ctype = ctype,
|
||||
token = token
|
||||
val url = params("url")
|
||||
val token = Some(params("token"))
|
||||
val ctype = WebHookContentType.valueOf(params("ctype"))
|
||||
val dummyWebHookInfo = RepositoryWebHook(
|
||||
userName = repository.owner,
|
||||
repositoryName = repository.name,
|
||||
url = url,
|
||||
ctype = ctype,
|
||||
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(
|
||||
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 (webHook, json, reqFuture, resFuture) =
|
||||
callWebHook(WebHook.Push, List(dummyWebHookInfo), dummyPayload, context.settings).head
|
||||
|
||||
val (webHook, json, reqFuture, resFuture) =
|
||||
callWebHook(WebHook.Push, List(dummyWebHookInfo), dummyPayload, context.settings).head
|
||||
val toErrorMap: PartialFunction[Throwable, Map[String, String]] = {
|
||||
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]] = {
|
||||
case e: java.net.UnknownHostException => Map("error" -> ("Unknown host " + e.getMessage))
|
||||
case e: java.lang.IllegalArgumentException => Map("error" -> ("invalid url"))
|
||||
case e: org.apache.http.client.ClientProtocolException => Map("error" -> ("invalid url"))
|
||||
case NonFatal(e) => Map("error" -> (s"${e.getClass} ${e.getMessage}"))
|
||||
}
|
||||
|
||||
contentType = formats("json")
|
||||
org.json4s.jackson.Serialization.write(
|
||||
Map(
|
||||
"url" -> url,
|
||||
"request" -> Await.result(
|
||||
reqFuture
|
||||
.map(
|
||||
req =>
|
||||
Map(
|
||||
"headers" -> _headers(req.getAllHeaders),
|
||||
"payload" -> json
|
||||
)
|
||||
contentType = formats("json")
|
||||
org.json4s.jackson.Serialization.write(
|
||||
Map(
|
||||
"url" -> url,
|
||||
"request" -> Await.result(
|
||||
reqFuture
|
||||
.map(req =>
|
||||
Map(
|
||||
"headers" -> _headers(req.getAllHeaders),
|
||||
"payload" -> json
|
||||
)
|
||||
.recover(toErrorMap),
|
||||
20 seconds
|
||||
),
|
||||
"response" -> Await.result(
|
||||
resFuture
|
||||
.map(
|
||||
res =>
|
||||
Map(
|
||||
"status" -> res.getStatusLine.getStatusCode,
|
||||
"body" -> EntityUtils.toString(res.getEntity()),
|
||||
"headers" -> _headers(res.getAllHeaders())
|
||||
)
|
||||
)
|
||||
.recover(toErrorMap),
|
||||
20 seconds
|
||||
),
|
||||
"response" -> Await.result(
|
||||
resFuture
|
||||
.map(res =>
|
||||
Map(
|
||||
"status" -> res.getStatusLine.getStatusCode,
|
||||
"body" -> EntityUtils.toString(res.getEntity),
|
||||
"headers" -> _headers(res.getAllHeaders)
|
||||
)
|
||||
.recover(toErrorMap),
|
||||
20 seconds
|
||||
)
|
||||
)
|
||||
.recover(toErrorMap),
|
||||
20 seconds
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -362,9 +374,8 @@ trait RepositorySettingsControllerBase extends ControllerBase {
|
||||
* Display the web hook edit page.
|
||||
*/
|
||||
get("/:owner/:repository/settings/hooks/edit")(ownerOnly { repository =>
|
||||
getWebHook(repository.owner, repository.name, params("url")).map {
|
||||
case (webhook, events) =>
|
||||
html.edithook(webhook, events, repository, false)
|
||||
getWebHook(repository.owner, repository.name, params("url")).map { case (webhook, events) =>
|
||||
html.edithook(webhook, events, repository, create = false)
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
|
||||
@@ -388,23 +399,22 @@ trait RepositorySettingsControllerBase extends ControllerBase {
|
||||
* Rename repository.
|
||||
*/
|
||||
post("/:owner/:repository/settings/rename", renameForm)(ownerOnly { (form, repository) =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
if (context.settings.repositoryOperation.rename || loginAccount.isAdmin) {
|
||||
if (repository.name != form.repositoryName) {
|
||||
// Update database and move git repository
|
||||
renameRepository(repository.owner, repository.name, repository.owner, form.repositoryName)
|
||||
// Record activity log
|
||||
val renameInfo = RenameRepositoryInfo(
|
||||
repository.owner,
|
||||
form.repositoryName,
|
||||
loginAccount.userName,
|
||||
repository.name
|
||||
)
|
||||
recordActivity(renameInfo)
|
||||
}
|
||||
redirect(s"/${repository.owner}/${form.repositoryName}")
|
||||
} else Forbidden()
|
||||
context.withLoginAccount { loginAccount =>
|
||||
if (context.settings.basicBehavior.repositoryOperation.rename || loginAccount.isAdmin) {
|
||||
if (repository.name != form.repositoryName) {
|
||||
// Update database and move git repository
|
||||
renameRepository(repository.owner, repository.name, repository.owner, form.repositoryName)
|
||||
// Record activity log
|
||||
val renameInfo = RenameRepositoryInfo(
|
||||
repository.owner,
|
||||
form.repositoryName,
|
||||
loginAccount.userName,
|
||||
repository.name
|
||||
)
|
||||
recordActivity(renameInfo)
|
||||
}
|
||||
redirect(s"/${repository.owner}/${form.repositoryName}")
|
||||
} else Forbidden()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -412,24 +422,23 @@ trait RepositorySettingsControllerBase extends ControllerBase {
|
||||
* Transfer repository ownership.
|
||||
*/
|
||||
post("/:owner/:repository/settings/transfer", transferForm)(ownerOnly { (form, repository) =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
if (context.settings.repositoryOperation.transfer || loginAccount.isAdmin) {
|
||||
// Change repository owner
|
||||
if (repository.owner != form.newOwner) {
|
||||
// Update database and move git repository
|
||||
renameRepository(repository.owner, repository.name, form.newOwner, repository.name)
|
||||
// Record activity log
|
||||
val renameInfo = RenameRepositoryInfo(
|
||||
form.newOwner,
|
||||
repository.name,
|
||||
loginAccount.userName,
|
||||
repository.owner
|
||||
)
|
||||
recordActivity(renameInfo)
|
||||
}
|
||||
redirect(s"/${form.newOwner}/${repository.name}")
|
||||
} else Forbidden()
|
||||
context.withLoginAccount { loginAccount =>
|
||||
if (context.settings.basicBehavior.repositoryOperation.transfer || loginAccount.isAdmin) {
|
||||
// Change repository owner
|
||||
if (repository.owner != form.newOwner) {
|
||||
// Update database and move git repository
|
||||
renameRepository(repository.owner, repository.name, form.newOwner, repository.name)
|
||||
// Record activity log
|
||||
val renameInfo = RenameRepositoryInfo(
|
||||
form.newOwner,
|
||||
repository.name,
|
||||
loginAccount.userName,
|
||||
repository.owner
|
||||
)
|
||||
recordActivity(renameInfo)
|
||||
}
|
||||
redirect(s"/${form.newOwner}/${repository.name}")
|
||||
} else Forbidden()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -438,7 +447,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
|
||||
*/
|
||||
post("/:owner/:repository/settings/delete")(ownerOnly { repository =>
|
||||
context.withLoginAccount { loginAccount =>
|
||||
if (context.settings.repositoryOperation.delete || loginAccount.isAdmin) {
|
||||
if (context.settings.basicBehavior.repositoryOperation.delete || loginAccount.isAdmin) {
|
||||
// Delete the repository and related files
|
||||
deleteRepository(repository.repository)
|
||||
redirect(s"/${repository.owner}")
|
||||
@@ -477,6 +486,60 @@ trait RepositorySettingsControllerBase extends ControllerBase {
|
||||
redirect(s"/${repository.owner}/${repository.name}/settings/deploykey")
|
||||
})
|
||||
|
||||
/** Custom fields for issues and pull requests */
|
||||
get("/:owner/:repository/settings/issues")(ownerOnly { repository =>
|
||||
val customFields = getCustomFields(repository.owner, repository.name)
|
||||
html.issues(customFields, repository)
|
||||
})
|
||||
|
||||
/** New custom field form */
|
||||
get("/:owner/:repository/settings/issues/fields/new")(ownerOnly { repository =>
|
||||
html.issuesfieldform(None, repository)
|
||||
})
|
||||
|
||||
/** Add custom field */
|
||||
ajaxPost("/:owner/:repository/settings/issues/fields/new", customFieldForm)(ownerOnly { (form, repository) =>
|
||||
val fieldId = createCustomField(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
form.fieldName,
|
||||
form.fieldType,
|
||||
if (form.fieldType == "enum") form.constraints else None,
|
||||
form.enableForIssues,
|
||||
form.enableForPullRequests
|
||||
)
|
||||
html.issuesfield(getCustomField(repository.owner, repository.name, fieldId).get)
|
||||
})
|
||||
|
||||
/** Edit custom field form */
|
||||
ajaxGet("/:owner/:repository/settings/issues/fields/:fieldId/edit")(ownerOnly { repository =>
|
||||
getCustomField(repository.owner, repository.name, params("fieldId").toInt).map { customField =>
|
||||
html.issuesfieldform(Some(customField), repository)
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
|
||||
/** Update custom field */
|
||||
ajaxPost("/:owner/:repository/settings/issues/fields/:fieldId/edit", customFieldForm)(ownerOnly {
|
||||
(form, repository) =>
|
||||
updateCustomField(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
params("fieldId").toInt,
|
||||
form.fieldName,
|
||||
form.fieldType,
|
||||
if (form.fieldType == "enum") form.constraints else None,
|
||||
form.enableForIssues,
|
||||
form.enableForPullRequests
|
||||
)
|
||||
html.issuesfield(getCustomField(repository.owner, repository.name, params("fieldId").toInt).get)
|
||||
})
|
||||
|
||||
/** Delete custom field */
|
||||
ajaxPost("/:owner/:repository/settings/issues/fields/:fieldId/delete")(ownerOnly { repository =>
|
||||
deleteCustomField(repository.owner, repository.name, params("fieldId").toInt)
|
||||
Ok()
|
||||
})
|
||||
|
||||
/**
|
||||
* Provides duplication check for web hook url.
|
||||
*/
|
||||
@@ -565,7 +628,7 @@ trait RepositorySettingsControllerBase extends ControllerBase {
|
||||
new Constraint() {
|
||||
override def validate(name: String, value: String, messages: Messages): Option[String] =
|
||||
getAccountByUserName(value) match {
|
||||
case None => Some("User does not exist.")
|
||||
case None => Some("User does not exist.")
|
||||
case Some(x) =>
|
||||
if (x.userName == params("owner")) {
|
||||
Some("This is current repository owner.")
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,20 +1,19 @@
|
||||
package gitbucket.core.controller
|
||||
|
||||
import java.io.FileInputStream
|
||||
|
||||
import gitbucket.core.admin.html
|
||||
import gitbucket.core.plugin.PluginRegistry
|
||||
import gitbucket.core.service.SystemSettingsService._
|
||||
import gitbucket.core.service.SystemSettingsService.*
|
||||
import gitbucket.core.service.{AccountService, RepositoryService}
|
||||
import gitbucket.core.ssh.SshServer
|
||||
import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.util.StringUtil._
|
||||
import gitbucket.core.util.Implicits.*
|
||||
import gitbucket.core.util.StringUtil.*
|
||||
import gitbucket.core.util.{AdminAuthenticator, Mailer}
|
||||
import org.apache.commons.io.IOUtils
|
||||
import org.apache.commons.mail.EmailException
|
||||
import org.json4s.jackson.Serialization
|
||||
import org.scalatra._
|
||||
import org.scalatra.forms._
|
||||
import org.scalatra.*
|
||||
import org.scalatra.forms.*
|
||||
import org.scalatra.i18n.Messages
|
||||
|
||||
import scala.collection.mutable.ListBuffer
|
||||
@@ -30,28 +29,41 @@ case class Table(name: String, columns: Seq[Column])
|
||||
case class Column(name: String, primaryKey: Boolean)
|
||||
|
||||
trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
self: AccountService with RepositoryService with AdminAuthenticator =>
|
||||
self: AccountService & RepositoryService & AdminAuthenticator =>
|
||||
|
||||
private val form = mapping(
|
||||
"baseUrl" -> trim(label("Base URL", optional(text()))),
|
||||
"information" -> trim(label("Information", optional(text()))),
|
||||
"allowAccountRegistration" -> trim(label("Account registration", boolean())),
|
||||
"allowAnonymousAccess" -> trim(label("Anonymous access", boolean())),
|
||||
"isCreateRepoOptionPublic" -> trim(label("Default visibility of new repository", boolean())),
|
||||
"repositoryOperation" -> mapping(
|
||||
"create" -> trim(label("Allow all users to create repository", boolean())),
|
||||
"delete" -> trim(label("Allow all users to delete repository", boolean())),
|
||||
"rename" -> trim(label("Allow all users to rename repository", boolean())),
|
||||
"transfer" -> trim(label("Allow all users to transfer repository", boolean())),
|
||||
"fork" -> trim(label("Allow all users to fork repository", boolean()))
|
||||
)(RepositoryOperation.apply),
|
||||
"gravatar" -> trim(label("Gravatar", boolean())),
|
||||
"notification" -> trim(label("Notification", boolean())),
|
||||
"limitVisibleRepositories" -> trim(label("limitVisibleRepositories", boolean())),
|
||||
"basicBehavior" -> mapping(
|
||||
"allowAccountRegistration" -> trim(label("Account registration", boolean())),
|
||||
"allowResetPassword" -> trim(label("Reset password", boolean())),
|
||||
"allowAnonymousAccess" -> trim(label("Anonymous access", boolean())),
|
||||
"isCreateRepoOptionPublic" -> trim(label("Default visibility of new repository", boolean())),
|
||||
"repositoryOperation" -> mapping(
|
||||
"create" -> trim(label("Allow all users to create repository", boolean())),
|
||||
"delete" -> trim(label("Allow all users to delete repository", boolean())),
|
||||
"rename" -> trim(label("Allow all users to rename repository", boolean())),
|
||||
"transfer" -> trim(label("Allow all users to transfer repository", boolean())),
|
||||
"fork" -> trim(label("Allow all users to fork repository", boolean()))
|
||||
)(RepositoryOperation.apply),
|
||||
"gravatar" -> trim(label("Gravatar", boolean())),
|
||||
"notification" -> trim(label("Notification", boolean())),
|
||||
"limitVisibleRepositories" -> trim(label("limitVisibleRepositories", boolean())),
|
||||
)(BasicBehavior.apply),
|
||||
"ssh" -> mapping(
|
||||
"enabled" -> trim(label("SSH access", boolean())),
|
||||
"host" -> trim(label("SSH host", optional(text()))),
|
||||
"port" -> trim(label("SSH port", optional(number())))
|
||||
"bindAddress" -> mapping(
|
||||
"host" -> trim(label("Bind SSH host", optional(text()))),
|
||||
"port" -> trim(label("Bind SSH port", optional(number()))),
|
||||
)((hostOption, portOption) =>
|
||||
hostOption.map(h => SshAddress(h, portOption.getOrElse(DefaultSshPort), GenericSshUser))
|
||||
),
|
||||
"publicAddress" -> mapping(
|
||||
"host" -> trim(label("Public SSH host", optional(text()))),
|
||||
"port" -> trim(label("Public SSH port", optional(number()))),
|
||||
)((hostOption, portOption) =>
|
||||
hostOption.map(h => SshAddress(h, portOption.getOrElse(PublicSshPort), GenericSshUser))
|
||||
),
|
||||
)(Ssh.apply),
|
||||
"useSMTP" -> trim(label("SMTP", boolean())),
|
||||
"smtp" -> optionalIfNotChecked(
|
||||
@@ -109,15 +121,18 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
"largeTimeout" -> trim(label("Timeout for large file", long(required)))
|
||||
)(Upload.apply),
|
||||
"repositoryViewer" -> mapping(
|
||||
"maxFiles" -> trim(label("Max files", number(required)))
|
||||
)(RepositoryViewerSettings.apply)
|
||||
"maxFiles" -> trim(label("Max files", number(required))),
|
||||
"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 =>
|
||||
Vector(
|
||||
if (settings.ssh.enabled && settings.baseUrl.isEmpty) {
|
||||
Some("baseUrl" -> "Base URL is required if SSH access is enabled.")
|
||||
} else None,
|
||||
if (settings.ssh.enabled && settings.ssh.sshHost.isEmpty) {
|
||||
Some("sshHost" -> "SSH host is required if SSH access is enabled.")
|
||||
if (settings.ssh.enabled && settings.ssh.bindAddress.isEmpty) {
|
||||
Some("ssh.bindAddress.host" -> "SSH bind host is required if SSH access is enabled.")
|
||||
} else None
|
||||
).flatten
|
||||
}
|
||||
@@ -136,11 +151,11 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
"testAddress" -> trim(label("", text(required)))
|
||||
)(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,
|
||||
password: String,
|
||||
fullName: String,
|
||||
@@ -152,7 +167,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
fileId: Option[String]
|
||||
)
|
||||
|
||||
case class EditUserForm(
|
||||
private case class EditUserForm(
|
||||
userName: String,
|
||||
password: Option[String],
|
||||
fullName: String,
|
||||
@@ -166,7 +181,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
isRemoved: Boolean
|
||||
)
|
||||
|
||||
case class NewGroupForm(
|
||||
private case class NewGroupForm(
|
||||
groupName: String,
|
||||
description: Option[String],
|
||||
url: Option[String],
|
||||
@@ -174,7 +189,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
members: String
|
||||
)
|
||||
|
||||
case class EditGroupForm(
|
||||
private case class EditGroupForm(
|
||||
groupName: String,
|
||||
description: Option[String],
|
||||
url: Option[String],
|
||||
@@ -184,7 +199,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
isRemoved: Boolean
|
||||
)
|
||||
|
||||
val newUserForm = mapping(
|
||||
private val newUserForm = mapping(
|
||||
"userName" -> trim(label("Username", text(required, maxlength(100), identifier, uniqueUserName, reservedNames))),
|
||||
"password" -> trim(label("Password", text(required, maxlength(40)))),
|
||||
"fullName" -> trim(label("Full Name", text(required, maxlength(100)))),
|
||||
@@ -198,7 +213,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
"fileId" -> trim(label("File ID", optional(text())))
|
||||
)(NewUserForm.apply)
|
||||
|
||||
val editUserForm = mapping(
|
||||
private val editUserForm = mapping(
|
||||
"userName" -> trim(label("Username", text(required, maxlength(100), identifier))),
|
||||
"password" -> trim(label("Password", optional(text(maxlength(40))))),
|
||||
"fullName" -> trim(label("Full Name", text(required, maxlength(100)))),
|
||||
@@ -214,7 +229,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
"removed" -> trim(label("Disable", boolean(disableByNotYourself("userName"))))
|
||||
)(EditUserForm.apply)
|
||||
|
||||
val newGroupForm = mapping(
|
||||
private val newGroupForm = mapping(
|
||||
"groupName" -> trim(label("Group name", text(required, maxlength(100), identifier, uniqueUserName, reservedNames))),
|
||||
"description" -> trim(label("Group description", optional(text()))),
|
||||
"url" -> trim(label("URL", optional(text(maxlength(200))))),
|
||||
@@ -222,7 +237,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
"members" -> trim(label("Members", text(required, members)))
|
||||
)(NewGroupForm.apply)
|
||||
|
||||
val editGroupForm = mapping(
|
||||
private val editGroupForm = mapping(
|
||||
"groupName" -> trim(label("Group name", text(required, maxlength(100), identifier))),
|
||||
"description" -> trim(label("Group description", optional(text()))),
|
||||
"url" -> trim(label("URL", optional(text(maxlength(200))))),
|
||||
@@ -236,28 +251,27 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
val conn = request2Session(request).conn
|
||||
val meta = conn.getMetaData
|
||||
val tables = ListBuffer[Table]()
|
||||
Using.resource(meta.getTables(null, "%", "%", Array("TABLE", "VIEW"))) {
|
||||
rs =>
|
||||
while (rs.next()) {
|
||||
val tableName = rs.getString("TABLE_NAME")
|
||||
Using.resource(meta.getTables(null, "%", "%", Array("TABLE", "VIEW"))) { rs =>
|
||||
while (rs.next()) {
|
||||
val tableName = rs.getString("TABLE_NAME")
|
||||
|
||||
val pkColumns = ListBuffer[String]()
|
||||
Using.resource(meta.getPrimaryKeys(null, null, tableName)) { rs =>
|
||||
while (rs.next()) {
|
||||
pkColumns += rs.getString("COLUMN_NAME").toUpperCase
|
||||
}
|
||||
val pkColumns = ListBuffer[String]()
|
||||
Using.resource(meta.getPrimaryKeys(null, null, tableName)) { rs =>
|
||||
while (rs.next()) {
|
||||
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)
|
||||
})
|
||||
@@ -270,28 +284,26 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
if (trimmedQuery.nonEmpty) {
|
||||
try {
|
||||
val conn = request2Session(request).conn
|
||||
Using.resource(conn.prepareStatement(query)) {
|
||||
stmt =>
|
||||
if (trimmedQuery.toUpperCase.startsWith("SELECT")) {
|
||||
Using.resource(stmt.executeQuery()) {
|
||||
rs =>
|
||||
val meta = rs.getMetaData
|
||||
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)))
|
||||
Using.resource(conn.prepareStatement(query)) { stmt =>
|
||||
if (trimmedQuery.toUpperCase.startsWith("SELECT")) {
|
||||
Using.resource(stmt.executeQuery()) { rs =>
|
||||
val meta = rs.getMetaData
|
||||
val columns = for (i <- 1 to meta.getColumnCount) yield {
|
||||
meta.getColumnName(i)
|
||||
}
|
||||
} else {
|
||||
val rows = stmt.executeUpdate()
|
||||
Ok(Serialization.write(Map("type" -> "update", "rows" -> rows)))
|
||||
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 rows = stmt.executeUpdate()
|
||||
Ok(Serialization.write(Map("type" -> "update", "rows" -> rows)))
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
case e: Exception =>
|
||||
@@ -308,12 +320,15 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
post("/admin/system", form)(adminOnly { form =>
|
||||
saveSystemSettings(form)
|
||||
|
||||
if (form.sshAddress != context.settings.sshAddress) {
|
||||
if (
|
||||
form.ssh.bindAddress != context.settings.sshBindAddress || form.ssh.publicAddress != context.settings.sshPublicAddress
|
||||
) {
|
||||
SshServer.stop()
|
||||
for {
|
||||
sshAddress <- form.sshAddress
|
||||
bindAddress <- form.ssh.bindAddress
|
||||
publicAddress <- form.ssh.publicAddress.orElse(form.ssh.bindAddress)
|
||||
baseUrl <- form.baseUrl
|
||||
} SshServer.start(sshAddress, baseUrl)
|
||||
} SshServer.start(bindAddress, publicAddress, baseUrl)
|
||||
}
|
||||
|
||||
flash.update("info", "System settings has been updated.")
|
||||
@@ -322,7 +337,12 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
|
||||
post("/admin/system/sendmail", sendMailForm)(adminOnly { form =>
|
||||
try {
|
||||
new Mailer(context.settings.copy(smtp = Some(form.smtp), notification = true)).send(
|
||||
new Mailer(
|
||||
context.settings.copy(
|
||||
smtp = Some(form.smtp),
|
||||
basicBehavior = context.settings.basicBehavior.copy(notification = true)
|
||||
)
|
||||
).send(
|
||||
to = form.testAddress,
|
||||
subject = "Test message from GitBucket",
|
||||
textMsg = "This is a test message from GitBucket.",
|
||||
@@ -343,7 +363,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
})
|
||||
|
||||
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.")
|
||||
redirect("/admin/plugins")
|
||||
})
|
||||
@@ -365,7 +385,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
val includeGroups = params.get("includeGroups").exists(_.toBoolean)
|
||||
val users = getAllUsers(includeRemoved, includeGroups)
|
||||
val members = users.collect {
|
||||
case account if (account.isGroupAccount) =>
|
||||
case account if account.isGroupAccount =>
|
||||
account.userName -> getGroupMembers(account.userName).map(_.userName)
|
||||
}.toMap
|
||||
|
||||
@@ -386,7 +406,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
form.description,
|
||||
form.url
|
||||
)
|
||||
updateImage(form.userName, form.fileId, false)
|
||||
updateImage(form.userName, form.fileId, clearImage = false)
|
||||
updateAccountExtraMailAddresses(form.userName, form.extraMailAddresses.filter(_ != ""))
|
||||
redirect("/admin/users")
|
||||
})
|
||||
@@ -394,49 +414,48 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
get("/admin/users/:userName/_edituser")(adminOnly {
|
||||
val userName = params("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 =>
|
||||
val userName = params("userName")
|
||||
getAccountByUserName(userName, true).map {
|
||||
account =>
|
||||
if (account.isAdmin && (form.isRemoved || !form.isAdmin) && isLastAdministrator(account)) {
|
||||
flash.update("error", "Account can't be turned off because this is last one administrator.")
|
||||
redirect(s"/admin/users/${userName}/_edituser")
|
||||
} else {
|
||||
if (form.isRemoved) {
|
||||
// Remove repositories
|
||||
// getRepositoryNamesOfUser(userName).foreach { repositoryName =>
|
||||
// deleteRepository(userName, repositoryName)
|
||||
// FileUtils.deleteDirectory(getRepositoryDir(userName, repositoryName))
|
||||
// FileUtils.deleteDirectory(getWikiRepositoryDir(userName, repositoryName))
|
||||
// FileUtils.deleteDirectory(getTemporaryDir(userName, repositoryName))
|
||||
// }
|
||||
// Remove from GROUP_MEMBER and COLLABORATOR
|
||||
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")
|
||||
getAccountByUserName(userName, includeRemoved = true).map { account =>
|
||||
if (account.isAdmin && (form.isRemoved || !form.isAdmin) && isLastAdministrator(account)) {
|
||||
flash.update("error", "Account can't be turned off because this is last one administrator.")
|
||||
redirect(s"/admin/users/${userName}/_edituser")
|
||||
} else {
|
||||
if (form.isRemoved) {
|
||||
// Remove repositories
|
||||
// getRepositoryNamesOfUser(userName).foreach { repositoryName =>
|
||||
// deleteRepository(userName, repositoryName)
|
||||
// FileUtils.deleteDirectory(getRepositoryDir(userName, repositoryName))
|
||||
// FileUtils.deleteDirectory(getWikiRepositoryDir(userName, repositoryName))
|
||||
// FileUtils.deleteDirectory(getTemporaryDir(userName, repositoryName))
|
||||
// }
|
||||
// Remove from GROUP_MEMBER and COLLABORATOR
|
||||
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")
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
|
||||
@@ -457,13 +476,13 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
}
|
||||
.toList
|
||||
)
|
||||
updateImage(form.groupName, form.fileId, false)
|
||||
updateImage(form.groupName, form.fileId, clearImage = false)
|
||||
redirect("/admin/users")
|
||||
})
|
||||
|
||||
get("/admin/users/:groupName/_editgroup")(adminOnly {
|
||||
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 =>
|
||||
@@ -477,13 +496,12 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
}
|
||||
.toList
|
||||
|
||||
getAccountByUserName(groupName, true).map {
|
||||
account =>
|
||||
updateGroup(groupName, form.description, form.url, form.isRemoved)
|
||||
getAccountByUserName(groupName, includeRemoved = true).map { account =>
|
||||
updateGroup(groupName, form.description, form.url, form.isRemoved)
|
||||
|
||||
if (form.isRemoved) {
|
||||
// Remove from GROUP_MEMBER
|
||||
updateGroupMembers(form.groupName, Nil)
|
||||
if (form.isRemoved) {
|
||||
// Remove from GROUP_MEMBER
|
||||
updateGroupMembers(form.groupName, Nil)
|
||||
// // Remove repositories
|
||||
// getRepositoryNamesOfUser(form.groupName).foreach { repositoryName =>
|
||||
// deleteRepository(groupName, repositoryName)
|
||||
@@ -491,9 +509,9 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
// FileUtils.deleteDirectory(getWikiRepositoryDir(groupName, repositoryName))
|
||||
// FileUtils.deleteDirectory(getTemporaryDir(groupName, repositoryName))
|
||||
// }
|
||||
} else {
|
||||
// Update GROUP_MEMBER
|
||||
updateGroupMembers(form.groupName, members)
|
||||
} else {
|
||||
// Update GROUP_MEMBER
|
||||
updateGroupMembers(form.groupName, members)
|
||||
// // Update COLLABORATOR for group repositories
|
||||
// getRepositoryNamesOfUser(form.groupName).foreach { repositoryName =>
|
||||
// removeCollaborators(form.groupName, repositoryName)
|
||||
@@ -501,22 +519,22 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
// addCollaborator(form.groupName, repositoryName, userName)
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
updateImage(form.groupName, form.fileId, form.clearImage)
|
||||
redirect("/admin/users")
|
||||
updateImage(form.groupName, form.fileId, form.clearImage)
|
||||
redirect("/admin/users")
|
||||
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
|
||||
get("/admin/data")(adminOnly {
|
||||
import gitbucket.core.util.JDBCUtil._
|
||||
import gitbucket.core.util.JDBCUtil.*
|
||||
val session = request2Session(request)
|
||||
html.data(session.conn.allTableNames())
|
||||
})
|
||||
|
||||
post("/admin/export")(adminOnly {
|
||||
import gitbucket.core.util.JDBCUtil._
|
||||
import gitbucket.core.util.JDBCUtil.*
|
||||
val file = request2Session(request).conn.exportAsSQL(request.getParameterValues("tableNames").toSeq)
|
||||
|
||||
contentType = "application/octet-stream"
|
||||
@@ -531,7 +549,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
})
|
||||
|
||||
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] = {
|
||||
if (value == null) {
|
||||
Nil
|
||||
@@ -544,9 +562,11 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
private def members: Constraint =
|
||||
new Constraint() {
|
||||
override def validate(name: String, value: String, messages: Messages): Option[String] = {
|
||||
if (value.split(",").exists {
|
||||
_.split(":") match { case Array(userName, isManager) => isManager.toBoolean }
|
||||
}) None
|
||||
if (
|
||||
value.split(",").exists {
|
||||
_.split(":") match { case Array(userName, isManager) => isManager.toBoolean }
|
||||
}
|
||||
) None
|
||||
else Some("Must select one manager at least.")
|
||||
}
|
||||
}
|
||||
@@ -557,7 +577,7 @@ trait SystemSettingsControllerBase extends AccountManagementControllerBase {
|
||||
for {
|
||||
userName <- params.get(paramName)
|
||||
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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
package gitbucket.core.controller
|
||||
|
||||
import org.json4s.{JField, JObject, JString}
|
||||
import org.scalatra._
|
||||
import org.scalatra.json._
|
||||
import org.scalatra.forms._
|
||||
import org.scalatra.*
|
||||
import org.scalatra.json.*
|
||||
import org.scalatra.forms.*
|
||||
import org.scalatra.i18n.I18nSupport
|
||||
import org.scalatra.servlet.ServletBase
|
||||
|
||||
/**
|
||||
* 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 = {
|
||||
registerValidate(path, form)
|
||||
@@ -84,9 +84,8 @@ trait ValidationSupport extends FormSupport { self: ServletBase with JacksonJson
|
||||
* Converts errors to JSON.
|
||||
*/
|
||||
private def toJson(errors: Seq[(String, String)]): JObject =
|
||||
JObject(errors.map {
|
||||
case (key, value) =>
|
||||
JField(key, JString(value))
|
||||
JObject(errors.map { case (key, value) =>
|
||||
JField(key, JString(value))
|
||||
}.toList)
|
||||
|
||||
}
|
||||
|
||||
@@ -5,13 +5,13 @@ import gitbucket.core.model.activity.{CreateWikiPageInfo, DeleteWikiInfo, EditWi
|
||||
import gitbucket.core.service.RepositoryService.RepositoryInfo
|
||||
import gitbucket.core.service.WebHookService.WebHookGollumPayload
|
||||
import gitbucket.core.wiki.html
|
||||
import gitbucket.core.service._
|
||||
import gitbucket.core.util._
|
||||
import gitbucket.core.util.StringUtil._
|
||||
import gitbucket.core.util.SyntaxSugars._
|
||||
import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.util.Directory._
|
||||
import org.scalatra.forms._
|
||||
import gitbucket.core.service.*
|
||||
import gitbucket.core.util.*
|
||||
import gitbucket.core.util.StringUtil.*
|
||||
import gitbucket.core.util.SyntaxSugars.*
|
||||
import gitbucket.core.util.Implicits.*
|
||||
import gitbucket.core.util.Directory.*
|
||||
import org.scalatra.forms.*
|
||||
import org.eclipse.jgit.api.Git
|
||||
import org.scalatra.i18n.Messages
|
||||
|
||||
@@ -29,15 +29,10 @@ class WikiController
|
||||
with RequestCache
|
||||
|
||||
trait WikiControllerBase extends ControllerBase {
|
||||
self: WikiService
|
||||
with RepositoryService
|
||||
with AccountService
|
||||
with ActivityService
|
||||
with WebHookService
|
||||
with ReadableUsersAuthenticator
|
||||
with ReferrerAuthenticator =>
|
||||
self: WikiService & RepositoryService & AccountService & ActivityService & WebHookService &
|
||||
ReadableUsersAuthenticator & ReferrerAuthenticator =>
|
||||
|
||||
case class WikiPageEditForm(
|
||||
private case class WikiPageEditForm(
|
||||
pageName: String,
|
||||
content: String,
|
||||
message: Option[String],
|
||||
@@ -45,16 +40,16 @@ trait WikiControllerBase extends ControllerBase {
|
||||
id: String
|
||||
)
|
||||
|
||||
val newForm = mapping(
|
||||
"pageName" -> trim(label("Page name", text(required, maxlength(40), pagename, unique))),
|
||||
private val newForm = mapping(
|
||||
"pageName" -> trim(label("Page name", text(required, maxlength(40), pageName, unique))),
|
||||
"content" -> trim(label("Content", text(required, conflictForNew))),
|
||||
"message" -> trim(label("Message", optional(text()))),
|
||||
"currentPageName" -> trim(label("Current page name", text())),
|
||||
"id" -> trim(label("Latest commit id", text()))
|
||||
)(WikiPageEditForm.apply)
|
||||
|
||||
val editForm = mapping(
|
||||
"pageName" -> trim(label("Page name", text(required, maxlength(40), pagename))),
|
||||
private val editForm = mapping(
|
||||
"pageName" -> trim(label("Page name", text(required, maxlength(40), pageName))),
|
||||
"content" -> trim(label("Content", text(required, conflictForEdit))),
|
||||
"message" -> trim(label("Message", optional(text()))),
|
||||
"currentPageName" -> trim(label("Current page name", text(required))),
|
||||
@@ -62,46 +57,56 @@ trait WikiControllerBase extends ControllerBase {
|
||||
)(WikiPageEditForm.apply)
|
||||
|
||||
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(
|
||||
"Home",
|
||||
page,
|
||||
getWikiPageList(repository.owner, repository.name),
|
||||
getWikiPageList(repository.owner, repository.name, branch),
|
||||
repository,
|
||||
isEditable(repository),
|
||||
getWikiPage(repository.owner, repository.name, "_Sidebar"),
|
||||
getWikiPage(repository.owner, repository.name, "_Footer")
|
||||
getWikiPage(repository.owner, repository.name, "_Sidebar", branch),
|
||||
getWikiPage(repository.owner, repository.name, "_Footer", branch)
|
||||
)
|
||||
} getOrElse redirect(s"/${repository.owner}/${repository.name}/wiki/Home/_edit")
|
||||
})
|
||||
|
||||
get("/:owner/:repository/wiki/:page")(referrersOnly { repository =>
|
||||
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(
|
||||
pageName,
|
||||
page,
|
||||
getWikiPageList(repository.owner, repository.name),
|
||||
getWikiPageList(repository.owner, repository.name, branch),
|
||||
repository,
|
||||
isEditable(repository),
|
||||
getWikiPage(repository.owner, repository.name, "_Sidebar"),
|
||||
getWikiPage(repository.owner, repository.name, "_Footer")
|
||||
getWikiPage(repository.owner, repository.name, "_Sidebar", branch),
|
||||
getWikiPage(repository.owner, repository.name, "_Footer", branch)
|
||||
)
|
||||
} getOrElse redirect(s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(pageName)}/_edit")
|
||||
})
|
||||
|
||||
get("/:owner/:repository/wiki/:page/_history")(referrersOnly { repository =>
|
||||
val pageName = StringUtil.urlDecode(params("page"))
|
||||
val branch = getWikiBranch(repository.owner, repository.name)
|
||||
|
||||
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 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 =>
|
||||
val pageName = StringUtil.urlDecode(params("page"))
|
||||
val Array(from, to) = params("commitId").split("\\.\\.\\.")
|
||||
@@ -111,7 +116,17 @@ trait WikiControllerBase extends ControllerBase {
|
||||
Some(pageName),
|
||||
from,
|
||||
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,
|
||||
isEditable(repository),
|
||||
flash.get("info")
|
||||
@@ -127,7 +142,15 @@ trait WikiControllerBase extends ControllerBase {
|
||||
None,
|
||||
from,
|
||||
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,
|
||||
isEditable(repository),
|
||||
flash.get("info")
|
||||
@@ -136,78 +159,78 @@ trait WikiControllerBase extends ControllerBase {
|
||||
})
|
||||
|
||||
get("/:owner/:repository/wiki/:page/_revert/:commitId")(readableUsersOnly { repository =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
if (isEditable(repository)) {
|
||||
val pageName = StringUtil.urlDecode(params("page"))
|
||||
val Array(from, to) = params("commitId").split("\\.\\.\\.")
|
||||
context.withLoginAccount { loginAccount =>
|
||||
if (isEditable(repository)) {
|
||||
val pageName = StringUtil.urlDecode(params("page"))
|
||||
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))) {
|
||||
redirect(s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(pageName)}")
|
||||
} else {
|
||||
flash.update("info", "This patch was not able to be reversed.")
|
||||
redirect(
|
||||
s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(pageName)}/_compare/${from}...${to}"
|
||||
)
|
||||
}
|
||||
} else Unauthorized()
|
||||
if (revertWikiPage(repository.owner, repository.name, from, to, loginAccount, Some(pageName), branch)) {
|
||||
redirect(s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(pageName)}")
|
||||
} else {
|
||||
flash.update("info", "This patch was not able to be reversed.")
|
||||
redirect(
|
||||
s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(pageName)}/_compare/$from...$to"
|
||||
)
|
||||
}
|
||||
} else Unauthorized()
|
||||
}
|
||||
})
|
||||
|
||||
get("/:owner/:repository/wiki/_revert/:commitId")(readableUsersOnly { repository =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
if (isEditable(repository)) {
|
||||
val Array(from, to) = params("commitId").split("\\.\\.\\.")
|
||||
context.withLoginAccount { loginAccount =>
|
||||
if (isEditable(repository)) {
|
||||
val Array(from, to) = params("commitId").split("\\.\\.\\.")
|
||||
val branch = getWikiBranch(repository.owner, repository.name)
|
||||
|
||||
if (revertWikiPage(repository.owner, repository.name, from, to, loginAccount, None)) {
|
||||
redirect(s"/${repository.owner}/${repository.name}/wiki")
|
||||
} else {
|
||||
flash.update("info", "This patch was not able to be reversed.")
|
||||
redirect(s"/${repository.owner}/${repository.name}/wiki/_compare/${from}...${to}")
|
||||
}
|
||||
} else Unauthorized()
|
||||
if (revertWikiPage(repository.owner, repository.name, from, to, loginAccount, None, branch)) {
|
||||
redirect(s"/${repository.owner}/${repository.name}/wiki")
|
||||
} else {
|
||||
flash.update("info", "This patch was not able to be reversed.")
|
||||
redirect(s"/${repository.owner}/${repository.name}/wiki/_compare/$from...$to")
|
||||
}
|
||||
} else Unauthorized()
|
||||
}
|
||||
})
|
||||
|
||||
get("/:owner/:repository/wiki/:page/_edit")(readableUsersOnly { repository =>
|
||||
if (isEditable(repository)) {
|
||||
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()
|
||||
})
|
||||
|
||||
post("/:owner/:repository/wiki/_edit", editForm)(readableUsersOnly { (form, repository) =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
if (isEditable(repository)) {
|
||||
saveWikiPage(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
form.currentPageName,
|
||||
form.pageName,
|
||||
appendNewLine(convertLineSeparator(form.content, "LF"), "LF"),
|
||||
loginAccount,
|
||||
form.message.getOrElse(""),
|
||||
Some(form.id)
|
||||
).foreach {
|
||||
commitId =>
|
||||
updateLastActivityDate(repository.owner, repository.name)
|
||||
val wikiEditInfo =
|
||||
EditWikiPageInfo(repository.owner, repository.name, loginAccount.userName, form.pageName, commitId)
|
||||
recordActivity(wikiEditInfo)
|
||||
callWebHookOf(repository.owner, repository.name, WebHook.Gollum, context.settings) {
|
||||
getAccountByUserName(repository.owner).map { repositoryUser =>
|
||||
WebHookGollumPayload("edited", form.pageName, commitId, repository, repositoryUser, loginAccount)
|
||||
}
|
||||
}
|
||||
context.withLoginAccount { loginAccount =>
|
||||
if (isEditable(repository)) {
|
||||
saveWikiPage(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
form.currentPageName,
|
||||
form.pageName,
|
||||
appendNewLine(convertLineSeparator(form.content, "LF"), "LF"),
|
||||
loginAccount,
|
||||
form.message.getOrElse(""),
|
||||
Some(form.id)
|
||||
).foreach { commitId =>
|
||||
updateLastActivityDate(repository.owner, repository.name)
|
||||
val wikiEditInfo =
|
||||
EditWikiPageInfo(repository.owner, repository.name, loginAccount.userName, form.pageName, commitId)
|
||||
recordActivity(wikiEditInfo)
|
||||
callWebHookOf(repository.owner, repository.name, WebHook.Gollum, context.settings) {
|
||||
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)}")
|
||||
} else {
|
||||
redirect(s"/${repository.owner}/${repository.name}/wiki")
|
||||
}
|
||||
} else Unauthorized()
|
||||
}
|
||||
if (notReservedPageName(form.pageName)) {
|
||||
redirect(s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(form.pageName)}")
|
||||
} else {
|
||||
redirect(s"/${repository.owner}/${repository.name}/wiki")
|
||||
}
|
||||
} else Unauthorized()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -218,74 +241,73 @@ trait WikiControllerBase extends ControllerBase {
|
||||
})
|
||||
|
||||
post("/:owner/:repository/wiki/_new", newForm)(readableUsersOnly { (form, repository) =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
if (isEditable(repository)) {
|
||||
saveWikiPage(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
form.currentPageName,
|
||||
form.pageName,
|
||||
form.content,
|
||||
loginAccount,
|
||||
form.message.getOrElse(""),
|
||||
None
|
||||
).foreach {
|
||||
commitId =>
|
||||
updateLastActivityDate(repository.owner, repository.name)
|
||||
val createWikiPageInfo =
|
||||
CreateWikiPageInfo(repository.owner, repository.name, loginAccount.userName, form.pageName)
|
||||
recordActivity(createWikiPageInfo)
|
||||
callWebHookOf(repository.owner, repository.name, WebHook.Gollum, context.settings) {
|
||||
getAccountByUserName(repository.owner).map { repositoryUser =>
|
||||
WebHookGollumPayload("created", form.pageName, commitId, repository, repositoryUser, loginAccount)
|
||||
}
|
||||
}
|
||||
context.withLoginAccount { loginAccount =>
|
||||
if (isEditable(repository)) {
|
||||
saveWikiPage(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
form.currentPageName,
|
||||
form.pageName,
|
||||
form.content,
|
||||
loginAccount,
|
||||
form.message.getOrElse(""),
|
||||
None
|
||||
).foreach { commitId =>
|
||||
updateLastActivityDate(repository.owner, repository.name)
|
||||
val createWikiPageInfo =
|
||||
CreateWikiPageInfo(repository.owner, repository.name, loginAccount.userName, form.pageName)
|
||||
recordActivity(createWikiPageInfo)
|
||||
callWebHookOf(repository.owner, repository.name, WebHook.Gollum, context.settings) {
|
||||
getAccountByUserName(repository.owner).map { repositoryUser =>
|
||||
WebHookGollumPayload("created", form.pageName, commitId, repository, repositoryUser, loginAccount)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (notReservedPageName(form.pageName)) {
|
||||
redirect(s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(form.pageName)}")
|
||||
} else {
|
||||
redirect(s"/${repository.owner}/${repository.name}/wiki")
|
||||
}
|
||||
} else Unauthorized()
|
||||
if (notReservedPageName(form.pageName)) {
|
||||
redirect(s"/${repository.owner}/${repository.name}/wiki/${StringUtil.urlEncode(form.pageName)}")
|
||||
} else {
|
||||
redirect(s"/${repository.owner}/${repository.name}/wiki")
|
||||
}
|
||||
} else Unauthorized()
|
||||
}
|
||||
})
|
||||
|
||||
get("/:owner/:repository/wiki/:page/_delete")(readableUsersOnly { repository =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
if (isEditable(repository)) {
|
||||
val pageName = StringUtil.urlDecode(params("page"))
|
||||
deleteWikiPage(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
pageName,
|
||||
loginAccount.fullName,
|
||||
loginAccount.mailAddress,
|
||||
s"Destroyed ${pageName}"
|
||||
)
|
||||
val deleteWikiInfo = DeleteWikiInfo(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
loginAccount.userName,
|
||||
pageName
|
||||
)
|
||||
recordActivity(deleteWikiInfo)
|
||||
updateLastActivityDate(repository.owner, repository.name)
|
||||
context.withLoginAccount { loginAccount =>
|
||||
if (isEditable(repository)) {
|
||||
val pageName = StringUtil.urlDecode(params("page"))
|
||||
deleteWikiPage(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
pageName,
|
||||
loginAccount.fullName,
|
||||
loginAccount.mailAddress,
|
||||
s"Destroyed $pageName"
|
||||
)
|
||||
val deleteWikiInfo = DeleteWikiInfo(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
loginAccount.userName,
|
||||
pageName
|
||||
)
|
||||
recordActivity(deleteWikiInfo)
|
||||
updateLastActivityDate(repository.owner, repository.name)
|
||||
|
||||
redirect(s"/${repository.owner}/${repository.name}/wiki")
|
||||
} else Unauthorized()
|
||||
redirect(s"/${repository.owner}/${repository.name}/wiki")
|
||||
} else Unauthorized()
|
||||
}
|
||||
})
|
||||
|
||||
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 =>
|
||||
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 Left(_) => NotFound()
|
||||
}
|
||||
@@ -295,7 +317,8 @@ trait WikiControllerBase extends ControllerBase {
|
||||
get("/:owner/:repository/wiki/_blob/*")(referrersOnly { repository =>
|
||||
val path = multiParams("splat").head
|
||||
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 =>
|
||||
responseRawFile(git, objectId, path, repository)
|
||||
@@ -309,24 +332,29 @@ trait WikiControllerBase extends ControllerBase {
|
||||
value: String,
|
||||
params: Map[String, Seq[String]],
|
||||
messages: Messages
|
||||
): Option[String] =
|
||||
getWikiPageList(params.value("owner"), params.value("repository"))
|
||||
): Option[String] = {
|
||||
val owner = params.value("owner")
|
||||
val repository = params.value("repository")
|
||||
val branch = getWikiBranch(owner, repository)
|
||||
|
||||
getWikiPageList(owner, repository, branch)
|
||||
.find(_ == value)
|
||||
.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] =
|
||||
if (value.exists("\\/:*?\"<>|".contains(_))) {
|
||||
Some(s"${name} contains invalid character.")
|
||||
Some(s"$name contains invalid character.")
|
||||
} else if (notReservedPageName(value) && (value.startsWith("_") || value.startsWith("-"))) {
|
||||
Some(s"${name} starts with invalid character.")
|
||||
Some(s"$name starts with invalid character.")
|
||||
} else {
|
||||
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() {
|
||||
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 = {
|
||||
repository.repository.options.wikiOption match {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
package gitbucket.core.controller.api
|
||||
import gitbucket.core.api.{ApiObject, ApiRef, CreateARef, JsonFormat, UpdateARef}
|
||||
import gitbucket.core.api.{ApiError, ApiRef, CreateARef, JsonFormat, UpdateARef}
|
||||
import gitbucket.core.controller.ControllerBase
|
||||
import gitbucket.core.service.RepositoryService.RepositoryInfo
|
||||
import gitbucket.core.util.Directory.getRepositoryDir
|
||||
import gitbucket.core.util.ReferrerAuthenticator
|
||||
import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.util.{ReferrerAuthenticator, RepositoryName, WritableUsersAuthenticator}
|
||||
import org.eclipse.jgit.api.Git
|
||||
import org.eclipse.jgit.lib.ObjectId
|
||||
import org.eclipse.jgit.lib.RefUpdate.Result
|
||||
@@ -14,47 +15,38 @@ import scala.jdk.CollectionConverters._
|
||||
import scala.util.Using
|
||||
|
||||
trait ApiGitReferenceControllerBase extends ControllerBase {
|
||||
self: ReferrerAuthenticator =>
|
||||
self: ReferrerAuthenticator & WritableUsersAuthenticator =>
|
||||
|
||||
private val logger = LoggerFactory.getLogger(classOf[ApiGitReferenceControllerBase])
|
||||
|
||||
get("/api/v3/repos/:owner/:repository/git/refs")(referrersOnly { repository =>
|
||||
val result = Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
|
||||
val refs = git
|
||||
.getRepository()
|
||||
.getRefDatabase()
|
||||
.getRefsByPrefix("refs")
|
||||
.asScala
|
||||
|
||||
refs.map(ApiRef.fromRef(RepositoryName(s"${repository.owner}/${repository.name}"), _))
|
||||
}
|
||||
JsonFormat(result)
|
||||
})
|
||||
|
||||
/*
|
||||
* i. Get a reference
|
||||
* https://docs.github.com/en/free-pro-team@latest/rest/reference/git#get-a-reference
|
||||
*/
|
||||
get("/api/v3/repos/:owner/:repository/git/ref/*")(referrersOnly { repository =>
|
||||
getRef()
|
||||
val revstr = multiParams("splat").head
|
||||
getRef(revstr, repository)
|
||||
})
|
||||
|
||||
// Some versions of GHE support this path
|
||||
get("/api/v3/repos/:owner/:repository/git/refs/*")(referrersOnly { repository =>
|
||||
logger.warn("git/refs/ endpoint may not be compatible with GitHub API v3. Consider using git/ref/ endpoint instead")
|
||||
getRef()
|
||||
})
|
||||
|
||||
private def getRef() = {
|
||||
val revstr = multiParams("splat").head
|
||||
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { git =>
|
||||
val ref = git.getRepository().findRef(revstr)
|
||||
|
||||
if (ref != null) {
|
||||
val sha = ref.getObjectId().name()
|
||||
JsonFormat(ApiRef(revstr, ApiObject(sha)))
|
||||
|
||||
} else {
|
||||
val refs = git
|
||||
.getRepository()
|
||||
.getRefDatabase()
|
||||
.getRefsByPrefix("refs/")
|
||||
.asScala
|
||||
|
||||
JsonFormat(refs.map { ref =>
|
||||
val sha = ref.getObjectId().name()
|
||||
ApiRef(revstr, ApiObject(sha))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
getRef(revstr, repository)
|
||||
})
|
||||
|
||||
/*
|
||||
* ii. Get all references
|
||||
@@ -65,23 +57,26 @@ trait ApiGitReferenceControllerBase extends ControllerBase {
|
||||
* iii. 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 { _ =>
|
||||
extractFromJsonBody[CreateARef].map {
|
||||
data =>
|
||||
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { git =>
|
||||
val ref = git.getRepository.findRef(data.ref)
|
||||
if (ref == null) {
|
||||
val update = git.getRepository.updateRef(data.ref)
|
||||
update.setNewObjectId(ObjectId.fromString(data.sha))
|
||||
val result = update.update()
|
||||
result match {
|
||||
case Result.NEW => JsonFormat(ApiRef(update.getName, ApiObject(update.getNewObjectId.getName)))
|
||||
case _ => UnprocessableEntity(result.name())
|
||||
}
|
||||
} else {
|
||||
UnprocessableEntity("Ref already exists.")
|
||||
post("/api/v3/repos/:owner/:repository/git/refs")(writableUsersOnly { repository =>
|
||||
extractFromJsonBody[CreateARef].map { data =>
|
||||
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
|
||||
val ref = git.getRepository.findRef(data.ref)
|
||||
if (ref == null) {
|
||||
val update = git.getRepository.updateRef(data.ref)
|
||||
update.setNewObjectId(ObjectId.fromString(data.sha))
|
||||
val result = update.update()
|
||||
result match {
|
||||
case Result.NEW =>
|
||||
JsonFormat(
|
||||
ApiRef
|
||||
.fromRef(RepositoryName(repository.owner, repository.name), git.getRepository.findRef(data.ref))
|
||||
)
|
||||
case _ => UnprocessableEntity(result.name())
|
||||
}
|
||||
} else {
|
||||
UnprocessableEntity("Ref already exists.")
|
||||
}
|
||||
}
|
||||
} getOrElse BadRequest()
|
||||
})
|
||||
|
||||
@@ -89,26 +84,25 @@ trait ApiGitReferenceControllerBase extends ControllerBase {
|
||||
* iv. Update a reference
|
||||
* https://docs.github.com/en/free-pro-team@latest/rest/reference/git#update-a-reference
|
||||
*/
|
||||
patch("/api/v3/repos/:owner/:repository/git/refs/*")(referrersOnly { _ =>
|
||||
patch("/api/v3/repos/:owner/:repository/git/refs/*")(writableUsersOnly { repository =>
|
||||
val refName = multiParams("splat").mkString("/")
|
||||
extractFromJsonBody[UpdateARef].map {
|
||||
data =>
|
||||
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { git =>
|
||||
val ref = git.getRepository.findRef(refName)
|
||||
if (ref == null) {
|
||||
UnprocessableEntity("Ref does not exist.")
|
||||
} else {
|
||||
val update = git.getRepository.updateRef(ref.getName)
|
||||
update.setNewObjectId(ObjectId.fromString(data.sha))
|
||||
update.setForceUpdate(data.force)
|
||||
val result = update.update()
|
||||
result match {
|
||||
case Result.FORCED | Result.FAST_FORWARD | Result.NO_CHANGE =>
|
||||
JsonFormat(ApiRef(update.getName, ApiObject(update.getNewObjectId.getName)))
|
||||
case _ => UnprocessableEntity(result.name())
|
||||
}
|
||||
extractFromJsonBody[UpdateARef].map { data =>
|
||||
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
|
||||
val ref = git.getRepository.findRef(refName)
|
||||
if (ref == null) {
|
||||
UnprocessableEntity("Ref does not exist.")
|
||||
} else {
|
||||
val update = git.getRepository.updateRef(ref.getName)
|
||||
update.setNewObjectId(ObjectId.fromString(data.sha))
|
||||
update.setForceUpdate(data.force)
|
||||
val result = update.update()
|
||||
result match {
|
||||
case Result.FORCED | Result.FAST_FORWARD | Result.NO_CHANGE =>
|
||||
JsonFormat(ApiRef.fromRef(RepositoryName(repository), git.getRepository.findRef(refName)))
|
||||
case _ => UnprocessableEntity(result.name())
|
||||
}
|
||||
}
|
||||
}
|
||||
} getOrElse BadRequest()
|
||||
})
|
||||
|
||||
@@ -116,7 +110,7 @@ trait ApiGitReferenceControllerBase extends ControllerBase {
|
||||
* v. Delete a reference
|
||||
* https://docs.github.com/en/free-pro-team@latest/rest/reference/git#delete-a-reference
|
||||
*/
|
||||
delete("/api/v3/repos/:owner/:repository/git/refs/*")(referrersOnly { _ =>
|
||||
delete("/api/v3/repos/:owner/:repository/git/refs/*")(writableUsersOnly { _ =>
|
||||
val refName = multiParams("splat").mkString("/")
|
||||
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { git =>
|
||||
val ref = git.getRepository.findRef(refName)
|
||||
@@ -133,4 +127,34 @@ trait ApiGitReferenceControllerBase extends ControllerBase {
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
private def notFound(): ApiError = {
|
||||
response.setStatus(404)
|
||||
ApiError("Not Found")
|
||||
}
|
||||
|
||||
protected def getRef(revstr: String, repository: RepositoryInfo): AnyRef = {
|
||||
logger.debug(s"getRef: path '${revstr}'")
|
||||
|
||||
val name = RepositoryName(repository)
|
||||
val result = JsonFormat(revstr match {
|
||||
case "tags" => repository.tags.map(ApiRef.fromTag(name, _))
|
||||
case x if x.startsWith("tags/") =>
|
||||
val tagName = x.substring("tags/".length)
|
||||
repository.tags.find(_.name == tagName) match {
|
||||
case Some(tagInfo) => ApiRef.fromTag(name, tagInfo)
|
||||
case None => notFound()
|
||||
}
|
||||
case other =>
|
||||
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
|
||||
git.getRepository().findRef(other) match {
|
||||
case null => notFound()
|
||||
case ref => ApiRef.fromRef(name, ref)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
logger.debug(s"json result: $result")
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,13 +7,8 @@ import gitbucket.core.util.{ReadableUsersAuthenticator, ReferrerAuthenticator, R
|
||||
import org.scalatra.ActionResult
|
||||
|
||||
trait ApiIssueCommentControllerBase extends ControllerBase {
|
||||
self: AccountService
|
||||
with IssuesService
|
||||
with RepositoryService
|
||||
with HandleCommentService
|
||||
with MilestonesService
|
||||
with ReadableUsersAuthenticator
|
||||
with ReferrerAuthenticator =>
|
||||
self: AccountService & IssuesService & RepositoryService & HandleCommentService & MilestonesService &
|
||||
ReadableUsersAuthenticator & ReferrerAuthenticator =>
|
||||
/*
|
||||
* i. 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
|
||||
comments = getCommentsForApi(repository.owner, repository.name, issueId)
|
||||
} yield {
|
||||
JsonFormat(comments.map {
|
||||
case (issueComment, user, issue) =>
|
||||
ApiComment(issueComment, RepositoryName(repository), issueId, ApiUser(user), issue.isPullRequest)
|
||||
JsonFormat(comments.map { case (issueComment, user, issue) =>
|
||||
ApiComment(issueComment, RepositoryName(repository), issueId, ApiUser(user), issue.isPullRequest)
|
||||
})
|
||||
}) getOrElse NotFound()
|
||||
})
|
||||
@@ -85,7 +79,7 @@ trait ApiIssueCommentControllerBase extends ControllerBase {
|
||||
* iv. Delete a comment
|
||||
* https://docs.github.com/en/rest/reference/issues#delete-an-issue-comment
|
||||
*/
|
||||
delete("/api/v3/repos/:owner/:repo/issues/comments/:id")(readableUsersOnly { repository =>
|
||||
delete("/api/v3/repos/:owner/:repository/issues/comments/:id")(readableUsersOnly { repository =>
|
||||
val maybeDeleteResponse: Option[Either[ActionResult, Option[Int]]] =
|
||||
for {
|
||||
commentId <- params("id").toIntOpt
|
||||
|
||||
@@ -9,12 +9,8 @@ import gitbucket.core.util.{ReadableUsersAuthenticator, ReferrerAuthenticator, R
|
||||
import gitbucket.core.util.Implicits._
|
||||
|
||||
trait ApiIssueControllerBase extends ControllerBase {
|
||||
self: AccountService
|
||||
with IssuesService
|
||||
with IssueCreationService
|
||||
with MilestonesService
|
||||
with ReadableUsersAuthenticator
|
||||
with ReferrerAuthenticator =>
|
||||
self: AccountService & IssuesService & IssueCreationService & MilestonesService & ReadableUsersAuthenticator &
|
||||
ReferrerAuthenticator =>
|
||||
/*
|
||||
* i. List issues
|
||||
* https://developer.github.com/v3/issues/#list-issues
|
||||
@@ -29,9 +25,9 @@ trait ApiIssueControllerBase extends ControllerBase {
|
||||
val page = IssueSearchCondition.page(request)
|
||||
// TODO: more api spec condition
|
||||
val condition = IssueSearchCondition(request)
|
||||
val baseOwner = getAccountByUserName(repository.owner).get
|
||||
// val baseOwner = getAccountByUserName(repository.owner).get
|
||||
|
||||
val issues: List[(Issue, Account, Option[Account])] =
|
||||
val issues: List[(Issue, Account, List[Account])] =
|
||||
searchIssueByApi(
|
||||
condition = condition,
|
||||
offset = (page - 1) * PullRequestLimit,
|
||||
@@ -39,17 +35,16 @@ trait ApiIssueControllerBase extends ControllerBase {
|
||||
repos = repository.owner -> repository.name
|
||||
)
|
||||
|
||||
JsonFormat(issues.map {
|
||||
case (issue, issueUser, assignedUser) =>
|
||||
ApiIssue(
|
||||
issue = issue,
|
||||
repositoryName = RepositoryName(repository),
|
||||
user = ApiUser(issueUser),
|
||||
assignee = assignedUser.map(ApiUser(_)),
|
||||
labels = getIssueLabels(repository.owner, repository.name, issue.issueId)
|
||||
.map(ApiLabel(_, RepositoryName(repository))),
|
||||
issue.milestoneId.flatMap { getApiMilestone(repository, _) }
|
||||
)
|
||||
JsonFormat(issues.map { case (issue, issueUser, assigneeUsers) =>
|
||||
ApiIssue(
|
||||
issue = issue,
|
||||
repositoryName = RepositoryName(repository),
|
||||
user = ApiUser(issueUser),
|
||||
assignees = assigneeUsers.map(ApiUser(_)),
|
||||
labels = getIssueLabels(repository.owner, repository.name, issue.issueId)
|
||||
.map(ApiLabel(_, RepositoryName(repository))),
|
||||
issue.milestoneId.flatMap { getApiMilestone(repository, _) }
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -61,7 +56,8 @@ trait ApiIssueControllerBase extends ControllerBase {
|
||||
(for {
|
||||
issueId <- params("id").toIntOpt
|
||||
issue <- getIssue(repository.owner, repository.name, issueId.toString)
|
||||
users = getAccountsByUserNames(Set(issue.openedUserName) ++ issue.assignedUserName, Set())
|
||||
assigneeUsers = getIssueAssignees(repository.owner, repository.name, issueId)
|
||||
users = getAccountsByUserNames(Set(issue.openedUserName) ++ assigneeUsers.map(_.assigneeUserName), Set())
|
||||
openedUser <- users.get(issue.openedUserName)
|
||||
} yield {
|
||||
JsonFormat(
|
||||
@@ -69,7 +65,7 @@ trait ApiIssueControllerBase extends ControllerBase {
|
||||
issue,
|
||||
RepositoryName(repository),
|
||||
ApiUser(openedUser),
|
||||
issue.assignedUserName.flatMap(users.get(_)).map(ApiUser(_)),
|
||||
assigneeUsers.flatMap(x => users.get(x.assigneeUserName)).map(ApiUser(_)),
|
||||
getIssueLabels(repository.owner, repository.name, issue.issueId).map(ApiLabel(_, RepositoryName(repository))),
|
||||
issue.milestoneId.flatMap { getApiMilestone(repository, _) }
|
||||
)
|
||||
@@ -92,7 +88,7 @@ trait ApiIssueControllerBase extends ControllerBase {
|
||||
repository,
|
||||
data.title,
|
||||
data.body,
|
||||
data.assignees.headOption,
|
||||
data.assignees,
|
||||
milestone.map(_.milestoneId),
|
||||
None,
|
||||
data.labels,
|
||||
@@ -103,7 +99,9 @@ trait ApiIssueControllerBase extends ControllerBase {
|
||||
issue,
|
||||
RepositoryName(repository),
|
||||
ApiUser(loginAccount),
|
||||
issue.assignedUserName.flatMap(getAccountByUserName(_)).map(ApiUser(_)),
|
||||
getIssueAssignees(repository.owner, repository.name, issue.issueId)
|
||||
.flatMap(x => getAccountByUserName(x.assigneeUserName, false))
|
||||
.map(ApiUser.apply),
|
||||
getIssueLabels(repository.owner, repository.name, issue.issueId)
|
||||
.map(ApiLabel(_, RepositoryName(repository))),
|
||||
issue.milestoneId.flatMap { getApiMilestone(repository, _) }
|
||||
@@ -123,7 +121,7 @@ trait ApiIssueControllerBase extends ControllerBase {
|
||||
*/
|
||||
|
||||
/*
|
||||
* vii. Unlock an issue
|
||||
* https://developer.github.com/v3/issues/#unlock-an-issue
|
||||
*/
|
||||
* vii. Unlock an issue
|
||||
* https://developer.github.com/v3/issues/#unlock-an-issue
|
||||
*/
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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.service._
|
||||
import gitbucket.core.util.Implicits._
|
||||
@@ -7,11 +7,7 @@ import gitbucket.core.util._
|
||||
import org.scalatra.{Created, NoContent, UnprocessableEntity}
|
||||
|
||||
trait ApiIssueLabelControllerBase extends ControllerBase {
|
||||
self: AccountService
|
||||
with IssuesService
|
||||
with LabelsService
|
||||
with ReferrerAuthenticator
|
||||
with WritableUsersAuthenticator =>
|
||||
self: AccountService & IssuesService & LabelsService & ReferrerAuthenticator & WritableUsersAuthenticator =>
|
||||
|
||||
/*
|
||||
* i. List all labels for this repository
|
||||
@@ -69,25 +65,24 @@ trait ApiIssueLabelControllerBase extends ControllerBase {
|
||||
data <- extractFromJsonBody[CreateALabel] if data.isValid
|
||||
} yield {
|
||||
LockUtil.lock(RepositoryName(repository).fullName) {
|
||||
getLabel(repository.owner, repository.name, params("labelName")).map {
|
||||
label =>
|
||||
if (getLabel(repository.owner, repository.name, data.name).isEmpty) {
|
||||
updateLabel(repository.owner, repository.name, label.labelId, data.name, data.color)
|
||||
JsonFormat(
|
||||
ApiLabel(
|
||||
getLabel(repository.owner, repository.name, label.labelId).get,
|
||||
RepositoryName(repository)
|
||||
)
|
||||
getLabel(repository.owner, repository.name, params("labelName")).map { label =>
|
||||
if (getLabel(repository.owner, repository.name, data.name).isEmpty) {
|
||||
updateLabel(repository.owner, repository.name, label.labelId, data.name, data.color)
|
||||
JsonFormat(
|
||||
ApiLabel(
|
||||
getLabel(repository.owner, repository.name, label.labelId).get,
|
||||
RepositoryName(repository)
|
||||
)
|
||||
} else {
|
||||
// TODO ApiError should support errors field to enhance compatibility of GitHub API
|
||||
UnprocessableEntity(
|
||||
ApiError(
|
||||
"Validation Failed",
|
||||
Some("https://developer.github.com/v3/issues/labels/#create-a-label")
|
||||
)
|
||||
)
|
||||
} else {
|
||||
// TODO ApiError should support errors field to enhance compatibility of GitHub API
|
||||
UnprocessableEntity(
|
||||
ApiError(
|
||||
"Validation Failed",
|
||||
Some("https://developer.github.com/v3/issues/labels/#create-a-label")
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
}
|
||||
}) getOrElse NotFound()
|
||||
@@ -121,10 +116,10 @@ trait ApiIssueLabelControllerBase extends ControllerBase {
|
||||
*/
|
||||
post("/api/v3/repos/:owner/:repository/issues/:id/labels")(writableUsersOnly { repository =>
|
||||
JsonFormat(for {
|
||||
data <- extractFromJsonBody[Seq[String]]
|
||||
data <- extractFromJsonBody[AddLabelsToAnIssue]
|
||||
issueId <- params("id").toIntOpt
|
||||
} yield {
|
||||
data.map { labelName =>
|
||||
data.labels.map { labelName =>
|
||||
val label = getLabel(repository.owner, repository.name, labelName).getOrElse(
|
||||
getLabel(
|
||||
repository.owner,
|
||||
@@ -160,11 +155,11 @@ trait ApiIssueLabelControllerBase extends ControllerBase {
|
||||
*/
|
||||
put("/api/v3/repos/:owner/:repository/issues/:id/labels")(writableUsersOnly { repository =>
|
||||
JsonFormat(for {
|
||||
data <- extractFromJsonBody[Seq[String]]
|
||||
data <- extractFromJsonBody[AddLabelsToAnIssue]
|
||||
issueId <- params("id").toIntOpt
|
||||
} yield {
|
||||
deleteAllIssueLabels(repository.owner, repository.name, issueId, true)
|
||||
data.map { labelName =>
|
||||
data.labels.map { labelName =>
|
||||
val label = getLabel(repository.owner, repository.name, labelName).getOrElse(
|
||||
getLabel(
|
||||
repository.owner,
|
||||
@@ -189,7 +184,7 @@ trait ApiIssueLabelControllerBase extends ControllerBase {
|
||||
})
|
||||
|
||||
/*
|
||||
* xi Get labels for every issue in a milestone
|
||||
* https://developer.github.com/v3/issues/labels/#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
|
||||
*/
|
||||
}
|
||||
|
||||
@@ -2,13 +2,12 @@ package gitbucket.core.controller.api
|
||||
import gitbucket.core.api._
|
||||
import gitbucket.core.controller.ControllerBase
|
||||
import gitbucket.core.service.MilestonesService
|
||||
import gitbucket.core.service.RepositoryService.RepositoryInfo
|
||||
import gitbucket.core.util.{ReferrerAuthenticator, WritableUsersAuthenticator}
|
||||
import gitbucket.core.util.Implicits._
|
||||
import org.scalatra.NoContent
|
||||
|
||||
trait ApiIssueMilestoneControllerBase extends ControllerBase {
|
||||
self: MilestonesService with WritableUsersAuthenticator with ReferrerAuthenticator =>
|
||||
self: MilestonesService & WritableUsersAuthenticator & ReferrerAuthenticator =>
|
||||
|
||||
/*
|
||||
* i. List milestones
|
||||
@@ -17,8 +16,10 @@ trait ApiIssueMilestoneControllerBase extends ControllerBase {
|
||||
get("/api/v3/repos/:owner/:repository/milestones")(referrersOnly { repository =>
|
||||
val state = params.getOrElse("state", "all")
|
||||
// TODO "sort", "direction" params should be implemented.
|
||||
val apiMilestones = (for (milestoneWithIssue <- getMilestonesWithIssueCount(repository.owner, repository.name)
|
||||
.sortBy(p => p._1.milestoneId))
|
||||
val apiMilestones = (for (
|
||||
milestoneWithIssue <- getMilestonesWithIssueCount(repository.owner, repository.name)
|
||||
.sortBy(p => p._1.milestoneId)
|
||||
)
|
||||
yield {
|
||||
ApiMilestone(
|
||||
repository.repository,
|
||||
@@ -28,7 +29,7 @@ trait ApiIssueMilestoneControllerBase extends ControllerBase {
|
||||
)
|
||||
}).reverse
|
||||
state match {
|
||||
case "all" => JsonFormat(apiMilestones)
|
||||
case "all" => JsonFormat(apiMilestones)
|
||||
case "open" | "closed" =>
|
||||
JsonFormat(
|
||||
apiMilestones.filter(p => p.state == state)
|
||||
|
||||
@@ -6,7 +6,7 @@ import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.util.{AdminAuthenticator, UsersAuthenticator}
|
||||
|
||||
trait ApiOrganizationControllerBase extends ControllerBase {
|
||||
self: RepositoryService with AccountService with AdminAuthenticator with UsersAuthenticator =>
|
||||
self: RepositoryService & AccountService & AdminAuthenticator & UsersAuthenticator =>
|
||||
|
||||
/*
|
||||
* i. List your organizations
|
||||
@@ -71,6 +71,6 @@ trait ApiOrganizationControllerBase extends ControllerBase {
|
||||
*/
|
||||
|
||||
/*
|
||||
* should implement delete an organization API?
|
||||
*/
|
||||
* should implement delete an organization API?
|
||||
*/
|
||||
}
|
||||
|
||||
@@ -16,14 +16,8 @@ import scala.util.Using
|
||||
import scala.jdk.CollectionConverters._
|
||||
|
||||
trait ApiPullRequestControllerBase extends ControllerBase {
|
||||
self: AccountService
|
||||
with IssuesService
|
||||
with PullRequestService
|
||||
with RepositoryService
|
||||
with MergeService
|
||||
with ReferrerAuthenticator
|
||||
with ReadableUsersAuthenticator
|
||||
with WritableUsersAuthenticator =>
|
||||
self: AccountService & IssuesService & PullRequestService & RepositoryService & MergeService & ReferrerAuthenticator &
|
||||
ReadableUsersAuthenticator & WritableUsersAuthenticator =>
|
||||
|
||||
/*
|
||||
* i. Link Relations
|
||||
@@ -40,7 +34,7 @@ trait ApiPullRequestControllerBase extends ControllerBase {
|
||||
val condition = IssueSearchCondition(request)
|
||||
val baseOwner = getAccountByUserName(repository.owner).get
|
||||
|
||||
val issues: List[(Issue, Account, Int, PullRequest, Repository, Account, Option[Account])] =
|
||||
val issues: List[(Issue, Account, Int, PullRequest, Repository, Account, List[Account])] =
|
||||
searchPullRequestByApi(
|
||||
condition = condition,
|
||||
offset = (page - 1) * PullRequestLimit,
|
||||
@@ -48,19 +42,18 @@ trait ApiPullRequestControllerBase extends ControllerBase {
|
||||
repos = repository.owner -> repository.name
|
||||
)
|
||||
|
||||
JsonFormat(issues.map {
|
||||
case (issue, issueUser, commentCount, pullRequest, headRepo, headOwner, assignee) =>
|
||||
ApiPullRequest(
|
||||
issue = issue,
|
||||
pullRequest = pullRequest,
|
||||
headRepo = ApiRepository(headRepo, ApiUser(headOwner)),
|
||||
baseRepo = ApiRepository(repository, ApiUser(baseOwner)),
|
||||
user = ApiUser(issueUser),
|
||||
labels = getIssueLabels(repository.owner, repository.name, issue.issueId)
|
||||
.map(ApiLabel(_, RepositoryName(repository))),
|
||||
assignee = assignee.map(ApiUser.apply),
|
||||
mergedComment = getMergedComment(repository.owner, repository.name, issue.issueId)
|
||||
)
|
||||
JsonFormat(issues.map { case (issue, issueUser, commentCount, pullRequest, headRepo, headOwner, assignees) =>
|
||||
ApiPullRequest(
|
||||
issue = issue,
|
||||
pullRequest = pullRequest,
|
||||
headRepo = ApiRepository(headRepo, ApiUser(headOwner)),
|
||||
baseRepo = ApiRepository(repository, ApiUser(baseOwner)),
|
||||
user = ApiUser(issueUser),
|
||||
labels = getIssueLabels(repository.owner, repository.name, issue.issueId)
|
||||
.map(ApiLabel(_, RepositoryName(repository))),
|
||||
assignees = assignees.map(ApiUser.apply),
|
||||
mergedComment = getMergedComment(repository.owner, repository.name, issue.issueId)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -89,39 +82,37 @@ trait ApiPullRequestControllerBase extends ControllerBase {
|
||||
case Left(createPullReq) =>
|
||||
val (reqOwner, reqBranch) = parseCompareIdentifier(createPullReq.head, repository.owner)
|
||||
getRepository(reqOwner, repository.name)
|
||||
.flatMap {
|
||||
forkedRepository =>
|
||||
getPullRequestCommitFromTo(repository, forkedRepository, createPullReq.base, reqBranch) match {
|
||||
case (Some(commitIdFrom), Some(commitIdTo)) =>
|
||||
val issueId = insertIssue(
|
||||
owner = repository.owner,
|
||||
repository = repository.name,
|
||||
loginUser = context.loginAccount.get.userName,
|
||||
title = createPullReq.title,
|
||||
content = createPullReq.body,
|
||||
assignedUserName = None,
|
||||
milestoneId = None,
|
||||
priorityId = None,
|
||||
isPullRequest = true
|
||||
)
|
||||
.flatMap { forkedRepository =>
|
||||
getPullRequestCommitFromTo(repository, forkedRepository, createPullReq.base, reqBranch) match {
|
||||
case (Some(commitIdFrom), Some(commitIdTo)) =>
|
||||
val issueId = insertIssue(
|
||||
owner = repository.owner,
|
||||
repository = repository.name,
|
||||
loginUser = context.loginAccount.get.userName,
|
||||
title = createPullReq.title,
|
||||
content = createPullReq.body,
|
||||
milestoneId = None,
|
||||
priorityId = None,
|
||||
isPullRequest = true
|
||||
)
|
||||
|
||||
createPullRequest(
|
||||
originRepository = repository,
|
||||
issueId = issueId,
|
||||
originBranch = createPullReq.base,
|
||||
requestUserName = reqOwner,
|
||||
requestRepositoryName = repository.name,
|
||||
requestBranch = reqBranch,
|
||||
commitIdFrom = commitIdFrom.getName,
|
||||
commitIdTo = commitIdTo.getName,
|
||||
isDraft = createPullReq.draft.getOrElse(false),
|
||||
loginAccount = context.loginAccount.get,
|
||||
settings = context.settings
|
||||
)
|
||||
getApiPullRequest(repository, issueId).map(JsonFormat(_))
|
||||
case _ =>
|
||||
None
|
||||
}
|
||||
createPullRequest(
|
||||
originRepository = repository,
|
||||
issueId = issueId,
|
||||
originBranch = createPullReq.base,
|
||||
requestUserName = reqOwner,
|
||||
requestRepositoryName = repository.name,
|
||||
requestBranch = reqBranch,
|
||||
commitIdFrom = commitIdFrom.getName,
|
||||
commitIdTo = commitIdTo.getName,
|
||||
isDraft = createPullReq.draft.getOrElse(false),
|
||||
loginAccount = context.loginAccount.get,
|
||||
settings = context.settings
|
||||
)
|
||||
getApiPullRequest(repository, issueId).map(JsonFormat(_))
|
||||
case _ =>
|
||||
None
|
||||
}
|
||||
}
|
||||
.getOrElse {
|
||||
NotFound()
|
||||
@@ -129,28 +120,27 @@ trait ApiPullRequestControllerBase extends ControllerBase {
|
||||
case Right(createPullReqAlt) =>
|
||||
val (reqOwner, reqBranch) = parseCompareIdentifier(createPullReqAlt.head, repository.owner)
|
||||
getRepository(reqOwner, repository.name)
|
||||
.flatMap {
|
||||
forkedRepository =>
|
||||
getPullRequestCommitFromTo(repository, forkedRepository, createPullReqAlt.base, reqBranch) match {
|
||||
case (Some(commitIdFrom), Some(commitIdTo)) =>
|
||||
changeIssueToPullRequest(repository.owner, repository.name, createPullReqAlt.issue)
|
||||
createPullRequest(
|
||||
originRepository = repository,
|
||||
issueId = createPullReqAlt.issue,
|
||||
originBranch = createPullReqAlt.base,
|
||||
requestUserName = reqOwner,
|
||||
requestRepositoryName = repository.name,
|
||||
requestBranch = reqBranch,
|
||||
commitIdFrom = commitIdFrom.getName,
|
||||
commitIdTo = commitIdTo.getName,
|
||||
isDraft = false,
|
||||
loginAccount = context.loginAccount.get,
|
||||
settings = context.settings
|
||||
)
|
||||
getApiPullRequest(repository, createPullReqAlt.issue).map(JsonFormat(_))
|
||||
case _ =>
|
||||
None
|
||||
}
|
||||
.flatMap { forkedRepository =>
|
||||
getPullRequestCommitFromTo(repository, forkedRepository, createPullReqAlt.base, reqBranch) match {
|
||||
case (Some(commitIdFrom), Some(commitIdTo)) =>
|
||||
changeIssueToPullRequest(repository.owner, repository.name, createPullReqAlt.issue)
|
||||
createPullRequest(
|
||||
originRepository = repository,
|
||||
issueId = createPullReqAlt.issue,
|
||||
originBranch = createPullReqAlt.base,
|
||||
requestUserName = reqOwner,
|
||||
requestRepositoryName = repository.name,
|
||||
requestBranch = reqBranch,
|
||||
commitIdFrom = commitIdFrom.getName,
|
||||
commitIdTo = commitIdTo.getName,
|
||||
isDraft = false,
|
||||
loginAccount = context.loginAccount.get,
|
||||
settings = context.settings
|
||||
)
|
||||
getApiPullRequest(repository, createPullReqAlt.issue).map(JsonFormat(_))
|
||||
case _ =>
|
||||
None
|
||||
}
|
||||
}
|
||||
.getOrElse {
|
||||
NotFound()
|
||||
@@ -191,26 +181,24 @@ trait ApiPullRequestControllerBase extends ControllerBase {
|
||||
get("/api/v3/repos/:owner/:repository/pulls/:id/commits")(referrersOnly { repository =>
|
||||
val owner = repository.owner
|
||||
val name = repository.name
|
||||
params("id").toIntOpt.flatMap {
|
||||
issueId =>
|
||||
getPullRequest(owner, name, issueId) map {
|
||||
case (issue, pullreq) =>
|
||||
Using.resource(Git.open(getRepositoryDir(owner, name))) { git =>
|
||||
val oldId = git.getRepository.resolve(pullreq.commitIdFrom)
|
||||
val newId = git.getRepository.resolve(pullreq.commitIdTo)
|
||||
val repoFullName = RepositoryName(repository)
|
||||
val commits = git.log
|
||||
.addRange(oldId, newId)
|
||||
.call
|
||||
.iterator
|
||||
.asScala
|
||||
.map { c =>
|
||||
ApiCommitListItem(new CommitInfo(c), repoFullName)
|
||||
}
|
||||
.toList
|
||||
JsonFormat(commits)
|
||||
params("id").toIntOpt.flatMap { issueId =>
|
||||
getPullRequest(owner, name, issueId) map { case (issue, pullreq) =>
|
||||
Using.resource(Git.open(getRepositoryDir(owner, name))) { git =>
|
||||
val oldId = git.getRepository.resolve(pullreq.commitIdFrom)
|
||||
val newId = git.getRepository.resolve(pullreq.commitIdTo)
|
||||
val repoFullName = RepositoryName(repository)
|
||||
val commits = git.log
|
||||
.addRange(oldId, newId)
|
||||
.call
|
||||
.iterator
|
||||
.asScala
|
||||
.map { c =>
|
||||
ApiCommitListItem(new CommitInfo(c), repoFullName)
|
||||
}
|
||||
.toList
|
||||
JsonFormat(commits)
|
||||
}
|
||||
}
|
||||
} getOrElse NotFound()
|
||||
})
|
||||
/*
|
||||
@@ -241,8 +229,8 @@ trait ApiPullRequestControllerBase extends ControllerBase {
|
||||
*/
|
||||
put("/api/v3/repos/:owner/:repository/pulls/:id/merge")(referrersOnly { repository =>
|
||||
(for {
|
||||
//TODO: crash when body is empty
|
||||
//TODO: Implement sha parameter
|
||||
// TODO: crash when body is empty
|
||||
// TODO: Implement sha parameter
|
||||
data <- extractFromJsonBody[MergeAPullRequest]
|
||||
issueId <- params("id").toIntOpt
|
||||
(issue, pullReq) <- getPullRequest(repository.owner, repository.name, issueId)
|
||||
@@ -274,7 +262,7 @@ trait ApiPullRequestControllerBase extends ControllerBase {
|
||||
repository,
|
||||
issueId,
|
||||
context.loginAccount.get,
|
||||
data.commit_message.getOrElse(""), //TODO: Implement commit_title
|
||||
data.commit_message.getOrElse(""), // TODO: Implement commit_title
|
||||
strategy,
|
||||
pullReq.isDraft,
|
||||
context.settings
|
||||
@@ -319,8 +307,8 @@ trait ApiPullRequestControllerBase extends ControllerBase {
|
||||
baseOwner <- users.get(repository.owner)
|
||||
headOwner <- users.get(pullRequest.requestUserName)
|
||||
issueUser <- users.get(issue.openedUserName)
|
||||
assignee = issue.assignedUserName.flatMap { userName =>
|
||||
getAccountByUserName(userName, false)
|
||||
assignees = getIssueAssignees(repository.owner, repository.name, issueId).flatMap { assignedUser =>
|
||||
getAccountByUserName(assignedUser.assigneeUserName, false)
|
||||
}
|
||||
headRepo <- getRepository(pullRequest.requestUserName, pullRequest.requestRepositoryName)
|
||||
} yield {
|
||||
@@ -332,7 +320,7 @@ trait ApiPullRequestControllerBase extends ControllerBase {
|
||||
user = ApiUser(issueUser),
|
||||
labels = getIssueLabels(repository.owner, repository.name, issue.issueId)
|
||||
.map(ApiLabel(_, RepositoryName(repository))),
|
||||
assignee = assignee.map(ApiUser.apply),
|
||||
assignees = assignees.map(ApiUser.apply),
|
||||
mergedComment = getMergedComment(repository.owner, repository.name, issue.issueId)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import org.apache.commons.io.FileUtils
|
||||
import org.scalatra.NoContent
|
||||
|
||||
trait ApiReleaseControllerBase extends ControllerBase {
|
||||
self: AccountService with ReleaseService with ReferrerAuthenticator with WritableUsersAuthenticator =>
|
||||
self: AccountService & ReleaseService & ReferrerAuthenticator & WritableUsersAuthenticator =>
|
||||
|
||||
/**
|
||||
* i. List releases for a repository
|
||||
@@ -119,40 +119,39 @@ trait ApiReleaseControllerBase extends ControllerBase {
|
||||
* ix. Upload a release asset
|
||||
* https://developer.github.com/v3/repos/releases/#upload-a-release-asset
|
||||
*/
|
||||
post("/api/v3/repos/:owner/:repository/releases/:tag/assets")(writableUsersOnly {
|
||||
repository =>
|
||||
val name = params("name")
|
||||
val tag = params("tag")
|
||||
getRelease(repository.owner, repository.name, tag)
|
||||
.map { release =>
|
||||
val fileId = FileUtil.generateFileId
|
||||
val buf = new Array[Byte](request.inputStream.available())
|
||||
request.inputStream.read(buf)
|
||||
FileUtils.writeByteArrayToFile(
|
||||
new File(
|
||||
getReleaseFilesDir(repository.owner, repository.name),
|
||||
FileUtil.checkFilename(tag + "/" + fileId)
|
||||
),
|
||||
buf
|
||||
)
|
||||
createReleaseAsset(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
tag,
|
||||
fileId,
|
||||
name,
|
||||
request.contentLength.getOrElse(0),
|
||||
context.loginAccount.get
|
||||
)
|
||||
getReleaseAsset(repository.owner, repository.name, tag, fileId)
|
||||
.map { asset =>
|
||||
JsonFormat(ApiReleaseAsset(asset, RepositoryName(repository)))
|
||||
}
|
||||
.getOrElse {
|
||||
ApiError("Unknown error")
|
||||
}
|
||||
}
|
||||
.getOrElse(NotFound())
|
||||
post("/api/v3/repos/:owner/:repository/releases/:tag/assets")(writableUsersOnly { repository =>
|
||||
val name = params("name")
|
||||
val tag = params("tag")
|
||||
getRelease(repository.owner, repository.name, tag)
|
||||
.map { release =>
|
||||
val fileId = FileUtil.generateFileId
|
||||
val buf = new Array[Byte](request.inputStream.available())
|
||||
request.inputStream.read(buf)
|
||||
FileUtils.writeByteArrayToFile(
|
||||
new File(
|
||||
getReleaseFilesDir(repository.owner, repository.name),
|
||||
FileUtil.checkFilename(tag + "/" + fileId)
|
||||
),
|
||||
buf
|
||||
)
|
||||
createReleaseAsset(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
tag,
|
||||
fileId,
|
||||
name,
|
||||
request.contentLength.getOrElse(0),
|
||||
context.loginAccount.get
|
||||
)
|
||||
getReleaseAsset(repository.owner, repository.name, tag, fileId)
|
||||
.map { asset =>
|
||||
JsonFormat(ApiReleaseAsset(asset, RepositoryName(repository)))
|
||||
}
|
||||
.getOrElse {
|
||||
ApiError("Unknown error")
|
||||
}
|
||||
}
|
||||
.getOrElse(NotFound())
|
||||
})
|
||||
|
||||
/**
|
||||
@@ -176,7 +175,7 @@ trait ApiReleaseControllerBase extends ControllerBase {
|
||||
*/
|
||||
|
||||
/*
|
||||
* xii. Delete a release asset
|
||||
* https://developer.github.com/v3/repos/releases/#edit-a-release-asset
|
||||
*/
|
||||
* xii. Delete a release asset
|
||||
* https://developer.github.com/v3/repos/releases/#edit-a-release-asset
|
||||
*/
|
||||
}
|
||||
|
||||
@@ -1,26 +1,19 @@
|
||||
package gitbucket.core.controller.api
|
||||
import gitbucket.core.api._
|
||||
import gitbucket.core.api.*
|
||||
import gitbucket.core.controller.ControllerBase
|
||||
import gitbucket.core.service.{AccountService, ProtectedBranchService, RepositoryService}
|
||||
import gitbucket.core.util._
|
||||
import gitbucket.core.util.Directory._
|
||||
import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.util.JGitUtil.getBranches
|
||||
import gitbucket.core.util.*
|
||||
import gitbucket.core.util.Directory.*
|
||||
import gitbucket.core.util.Implicits.*
|
||||
import gitbucket.core.util.JGitUtil.{getBranchesNoMergeInfo, processTree}
|
||||
import org.eclipse.jgit.api.Git
|
||||
import org.scalatra.NoContent
|
||||
|
||||
import scala.util.Using
|
||||
|
||||
trait ApiRepositoryBranchControllerBase extends ControllerBase {
|
||||
self: RepositoryService
|
||||
with AccountService
|
||||
with OwnerAuthenticator
|
||||
with UsersAuthenticator
|
||||
with GroupManagerAuthenticator
|
||||
with ProtectedBranchService
|
||||
with ReferrerAuthenticator
|
||||
with ReadableUsersAuthenticator
|
||||
with WritableUsersAuthenticator =>
|
||||
self: RepositoryService & AccountService & OwnerAuthenticator & UsersAuthenticator & GroupManagerAuthenticator &
|
||||
ProtectedBranchService & ReferrerAuthenticator & ReadableUsersAuthenticator & WritableUsersAuthenticator =>
|
||||
|
||||
/**
|
||||
* i. List branches
|
||||
@@ -30,11 +23,7 @@ trait ApiRepositoryBranchControllerBase extends ControllerBase {
|
||||
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
|
||||
JsonFormat(
|
||||
JGitUtil
|
||||
.getBranches(
|
||||
git = git,
|
||||
defaultBranch = repository.repository.defaultBranch,
|
||||
origin = repository.repository.originUserName.isEmpty
|
||||
)
|
||||
.getBranchesNoMergeInfo(git)
|
||||
.map { br =>
|
||||
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
|
||||
*/
|
||||
get("/api/v3/repos/:owner/:repository/branches/*")(referrersOnly { repository =>
|
||||
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
|
||||
git =>
|
||||
(for {
|
||||
branch <- params.get("splat") if repository.branchList.contains(branch)
|
||||
br <- getBranches(
|
||||
git,
|
||||
repository.repository.defaultBranch,
|
||||
repository.repository.originUserName.isEmpty
|
||||
).find(_.name == branch)
|
||||
} yield {
|
||||
val protection = getProtectedBranchInfo(repository.owner, repository.name, branch)
|
||||
JsonFormat(
|
||||
ApiBranch(branch, ApiBranchCommit(br.commitId), ApiBranchProtection(protection))(RepositoryName(repository))
|
||||
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
|
||||
(for {
|
||||
branch <- params.get("splat") if repository.branchList.contains(branch)
|
||||
br <- getBranchesNoMergeInfo(git).find(_.name == branch)
|
||||
} yield {
|
||||
val protection = getProtectedBranchInfo(repository.owner, repository.name, branch)
|
||||
JsonFormat(
|
||||
ApiBranch(branch, ApiBranchCommit(br.commitId), ApiBranchProtectionResponse(protection))(
|
||||
RepositoryName(repository)
|
||||
)
|
||||
}) getOrElse NotFound()
|
||||
)
|
||||
}) getOrElse NotFound()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -74,7 +60,7 @@ trait ApiRepositoryBranchControllerBase extends ControllerBase {
|
||||
if (repository.branchList.contains(branch)) {
|
||||
val protection = getProtectedBranchInfo(repository.owner, repository.name, branch)
|
||||
JsonFormat(
|
||||
ApiBranchProtection(protection)
|
||||
ApiBranchProtectionResponse(protection)
|
||||
)
|
||||
} else { NotFound() }
|
||||
})
|
||||
@@ -154,7 +140,7 @@ trait ApiRepositoryBranchControllerBase extends ControllerBase {
|
||||
if (repository.branchList.contains(branch)) {
|
||||
val protection = getProtectedBranchInfo(repository.owner, repository.name, branch)
|
||||
JsonFormat(
|
||||
ApiBranchProtection(protection).required_status_checks
|
||||
ApiBranchProtectionResponse(protection).required_status_checks
|
||||
)
|
||||
} else { NotFound() }
|
||||
})
|
||||
@@ -274,31 +260,30 @@ trait ApiRepositoryBranchControllerBase extends ControllerBase {
|
||||
* https://developer.github.com/v3/repos/#enabling-and-disabling-branch-protection
|
||||
*/
|
||||
patch("/api/v3/repos/:owner/:repository/branches/*")(ownerOnly { repository =>
|
||||
import gitbucket.core.api._
|
||||
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) {
|
||||
git =>
|
||||
(for {
|
||||
branch <- params.get("splat") if repository.branchList.contains(branch)
|
||||
protection <- extractFromJsonBody[ApiBranchProtection.EnablingAndDisabling].map(_.protection)
|
||||
br <- getBranches(
|
||||
git,
|
||||
repository.repository.defaultBranch,
|
||||
repository.repository.originUserName.isEmpty
|
||||
).find(_.name == branch)
|
||||
} yield {
|
||||
if (protection.enabled) {
|
||||
enableBranchProtection(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
branch,
|
||||
protection.status.enforcement_level == ApiBranchProtection.Everyone,
|
||||
protection.status.contexts
|
||||
)
|
||||
} else {
|
||||
disableBranchProtection(repository.owner, repository.name, branch)
|
||||
}
|
||||
JsonFormat(ApiBranch(branch, ApiBranchCommit(br.commitId), protection)(RepositoryName(repository)))
|
||||
}) getOrElse NotFound()
|
||||
import gitbucket.core.api.*
|
||||
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
|
||||
(for {
|
||||
branch <- params.get("splat") if repository.branchList.contains(branch)
|
||||
protection <- extractFromJsonBody[ApiBranchProtectionRequest.EnablingAndDisabling].map(_.protection)
|
||||
br <- getBranchesNoMergeInfo(git).find(_.name == branch)
|
||||
} yield {
|
||||
if (protection.enabled) {
|
||||
enableBranchProtection(
|
||||
repository.owner,
|
||||
repository.name,
|
||||
branch,
|
||||
protection.enforce_admins.getOrElse(false),
|
||||
protection.required_status_checks.isDefined,
|
||||
protection.required_status_checks.map(_.contexts).getOrElse(Nil),
|
||||
protection.restrictions.isDefined,
|
||||
protection.restrictions.map(_.users).getOrElse(Nil)
|
||||
)
|
||||
} 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)))
|
||||
}) getOrElse NotFound()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import gitbucket.core.util.{OwnerAuthenticator, ReferrerAuthenticator}
|
||||
import org.scalatra.NoContent
|
||||
|
||||
trait ApiRepositoryCollaboratorControllerBase extends ControllerBase {
|
||||
self: RepositoryService with AccountService with ReferrerAuthenticator with OwnerAuthenticator =>
|
||||
self: RepositoryService & AccountService & ReferrerAuthenticator & OwnerAuthenticator =>
|
||||
|
||||
/*
|
||||
* i. List repository collaborators
|
||||
|
||||
@@ -4,17 +4,24 @@ import gitbucket.core.controller.ControllerBase
|
||||
import gitbucket.core.model.Account
|
||||
import gitbucket.core.service.{AccountService, CommitsService, ProtectedBranchService}
|
||||
import gitbucket.core.util.Directory.getRepositoryDir
|
||||
import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.util.JGitUtil.{CommitInfo, getBranches, getBranchesOfCommit}
|
||||
import gitbucket.core.util.Implicits.*
|
||||
import gitbucket.core.util.JGitUtil.{CommitInfo, getBranchesNoMergeInfo, getBranchesOfCommit}
|
||||
import gitbucket.core.util.{JGitUtil, ReferrerAuthenticator, RepositoryName}
|
||||
import org.eclipse.jgit.api.Git
|
||||
import org.eclipse.jgit.revwalk.RevWalk
|
||||
import org.eclipse.jgit.revwalk.filter.*
|
||||
import org.eclipse.jgit.treewalk.filter.{AndTreeFilter, PathFilterGroup, TreeFilter}
|
||||
|
||||
import scala.jdk.CollectionConverters._
|
||||
import java.time.format.DateTimeFormatter.*
|
||||
import java.time.{LocalDateTime, ZoneOffset}
|
||||
import java.util.Date
|
||||
import scala.collection.mutable.ListBuffer
|
||||
import scala.jdk.CollectionConverters.*
|
||||
import scala.math.min
|
||||
import scala.util.Using
|
||||
|
||||
trait ApiRepositoryCommitControllerBase extends ControllerBase {
|
||||
self: AccountService with CommitsService with ProtectedBranchService with ReferrerAuthenticator =>
|
||||
self: AccountService & CommitsService & ProtectedBranchService & ReferrerAuthenticator =>
|
||||
/*
|
||||
* i. List commits on a repository
|
||||
* https://developer.github.com/v3/repos/commits/#list-commits-on-a-repository
|
||||
@@ -22,28 +29,60 @@ trait ApiRepositoryCommitControllerBase extends ControllerBase {
|
||||
get("/api/v3/repos/:owner/:repository/commits")(referrersOnly { repository =>
|
||||
val owner = repository.owner
|
||||
val name = repository.name
|
||||
// TODO: The following parameters need to be implemented. [:path, :author, :since, :until]
|
||||
val sha = params.getOrElse("sha", "refs/heads/master")
|
||||
Using.resource(Git.open(getRepositoryDir(owner, name))) {
|
||||
git =>
|
||||
val repo = git.getRepository
|
||||
Using.resource(new RevWalk(repo)) {
|
||||
revWalk =>
|
||||
val objectId = repo.resolve(sha)
|
||||
revWalk.markStart(revWalk.parseCommit(objectId))
|
||||
JsonFormat(revWalk.asScala.take(30).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 sha = params.get("sha").filter(_.nonEmpty).getOrElse("HEAD")
|
||||
val page = params.get("page").filter(_.nonEmpty).getOrElse("1").toInt
|
||||
val per_page = min(params.get("per_page").filter(_.nonEmpty).getOrElse("30").toInt, 100)
|
||||
val author = params.get("author").filter(_.nonEmpty)
|
||||
val path = params.get("path").filter(_.nonEmpty)
|
||||
val since = params.get("since").filter(_.nonEmpty)
|
||||
val until = params.get("until").filter(_.nonEmpty)
|
||||
Using.resource(Git.open(getRepositoryDir(owner, name))) { git =>
|
||||
val repo = git.getRepository
|
||||
Using.resource(new RevWalk(repo)) { revWalk =>
|
||||
val objectId = repo.resolve(sha)
|
||||
revWalk.markStart(revWalk.parseCommit(objectId))
|
||||
if (path.nonEmpty) {
|
||||
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
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -56,24 +95,23 @@ trait ApiRepositoryCommitControllerBase extends ControllerBase {
|
||||
val name = repository.name
|
||||
val sha = params("sha")
|
||||
|
||||
Using.resource(Git.open(getRepositoryDir(owner, name))) {
|
||||
git =>
|
||||
val repo = git.getRepository
|
||||
val objectId = repo.resolve(sha)
|
||||
val commitInfo = Using.resource(new RevWalk(repo)) { revWalk =>
|
||||
new CommitInfo(revWalk.parseCommit(objectId))
|
||||
}
|
||||
Using.resource(Git.open(getRepositoryDir(owner, name))) { git =>
|
||||
val repo = git.getRepository
|
||||
val objectId = repo.resolve(sha)
|
||||
val commitInfo = Using.resource(new RevWalk(repo)) { revWalk =>
|
||||
new CommitInfo(revWalk.parseCommit(objectId))
|
||||
}
|
||||
|
||||
JsonFormat(
|
||||
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, sha).size
|
||||
)
|
||||
JsonFormat(
|
||||
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, sha).size
|
||||
)
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -121,7 +159,7 @@ trait ApiRepositoryCommitControllerBase extends ControllerBase {
|
||||
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
|
||||
val apiBranchForCommits = for {
|
||||
branch <- getBranchesOfCommit(git, sha)
|
||||
br <- getBranches(git, branch, repository.repository.originUserName.isEmpty).find(_.name == branch)
|
||||
br <- getBranchesNoMergeInfo(git).find(_.name == branch)
|
||||
} yield {
|
||||
val protection = getProtectedBranchInfo(repository.owner, repository.name, branch)
|
||||
ApiBranchForHeadCommit(branch, ApiBranchCommit(br.commitId), protection.enabled)
|
||||
|
||||
@@ -12,24 +12,23 @@ import org.eclipse.jgit.api.Git
|
||||
import scala.util.Using
|
||||
|
||||
trait ApiRepositoryContentsControllerBase extends ControllerBase {
|
||||
self: ReferrerAuthenticator with WritableUsersAuthenticator with RepositoryCommitFileService =>
|
||||
self: ReferrerAuthenticator & WritableUsersAuthenticator & RepositoryCommitFileService =>
|
||||
|
||||
/**
|
||||
* i. 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 =>
|
||||
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) {
|
||||
git =>
|
||||
val refStr = params.getOrElse("ref", repository.repository.defaultBranch)
|
||||
val files = getFileList(git, refStr, ".", maxFiles = context.settings.repositoryViewer.maxFiles)
|
||||
files // files should be sorted alphabetically.
|
||||
.find { file =>
|
||||
!file.isDirectory && RepositoryService.readmeFiles.contains(file.name.toLowerCase)
|
||||
} match {
|
||||
case Some(x) => getContents(repository = repository, path = x.name, refStr = refStr, ignoreCase = true)
|
||||
case _ => NotFound()
|
||||
}
|
||||
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { git =>
|
||||
val refStr = params.getOrElse("ref", repository.repository.defaultBranch)
|
||||
val files = getFileList(git, refStr, ".", maxFiles = context.settings.repositoryViewer.maxFiles)
|
||||
files // files should be sorted alphabetically.
|
||||
.find { file =>
|
||||
!file.isDirectory && RepositoryService.readmeFiles.contains(file.name.toLowerCase)
|
||||
} match {
|
||||
case Some(x) => getContents(repository = repository, path = x.name, refStr = refStr, ignoreCase = true)
|
||||
case _ => NotFound()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -134,67 +133,66 @@ trait ApiRepositoryContentsControllerBase extends ControllerBase {
|
||||
* requested #2112
|
||||
*/
|
||||
put("/api/v3/repos/:owner/:repository/contents/*")(writableUsersOnly { repository =>
|
||||
context.withLoginAccount {
|
||||
loginAccount =>
|
||||
JsonFormat(for {
|
||||
data <- extractFromJsonBody[CreateAFile]
|
||||
} yield {
|
||||
val branch = data.branch.getOrElse(repository.repository.defaultBranch)
|
||||
val commit = Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
|
||||
val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(branch))
|
||||
revCommit.name
|
||||
}
|
||||
val paths = multiParams("splat").head.split("/")
|
||||
val path = paths.take(paths.size - 1).toList.mkString("/")
|
||||
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) {
|
||||
git =>
|
||||
val fileInfo = getFileInfo(git, commit, path, false)
|
||||
context.withLoginAccount { loginAccount =>
|
||||
JsonFormat(for {
|
||||
data <- extractFromJsonBody[CreateAFile]
|
||||
} yield {
|
||||
val branch = data.branch.getOrElse(repository.repository.defaultBranch)
|
||||
val commit = Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
|
||||
val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(branch))
|
||||
revCommit.name
|
||||
}
|
||||
val fullPath = multiParams("splat").head
|
||||
val paths = fullPath.split("/")
|
||||
val path = paths.take(paths.size - 1).toList.mkString("/")
|
||||
Using.resource(Git.open(getRepositoryDir(params("owner"), params("repository")))) { git =>
|
||||
val fileInfo = getFileInfo(git, commit, fullPath, ignoreCase = false)
|
||||
|
||||
fileInfo match {
|
||||
case Some(f) if !data.sha.contains(f.id.getName) =>
|
||||
ApiError(
|
||||
"The blob SHA is not matched.",
|
||||
Some("https://docs.github.com/en/rest/reference/repos#create-or-update-file-contents")
|
||||
fileInfo match {
|
||||
case Some(f) if !data.sha.contains(f.id.getName) =>
|
||||
ApiError(
|
||||
"The blob SHA is not matched.",
|
||||
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 _ =>
|
||||
val (commitId, blobId) = 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
|
||||
)
|
||||
|
||||
blobId match {
|
||||
case None =>
|
||||
ApiError("Failed to commit a file.", None)
|
||||
case 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)
|
||||
* 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
|
||||
*/
|
||||
* 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-zip
|
||||
*/
|
||||
|
||||
}
|
||||
|
||||
@@ -15,15 +15,9 @@ import scala.concurrent.duration.Duration
|
||||
import scala.util.Using
|
||||
|
||||
trait ApiRepositoryControllerBase extends ControllerBase {
|
||||
self: RepositoryService
|
||||
with RepositoryCreationService
|
||||
with AccountService
|
||||
with OwnerAuthenticator
|
||||
with UsersAuthenticator
|
||||
with GroupManagerAuthenticator
|
||||
with ReferrerAuthenticator
|
||||
with ReadableUsersAuthenticator
|
||||
with WritableUsersAuthenticator =>
|
||||
self: RepositoryService & ApiGitReferenceControllerBase & RepositoryCreationService & AccountService &
|
||||
OwnerAuthenticator & UsersAuthenticator & GroupManagerAuthenticator & ReferrerAuthenticator &
|
||||
ReadableUsersAuthenticator & WritableUsersAuthenticator =>
|
||||
|
||||
/**
|
||||
* i. List your repositories
|
||||
@@ -92,7 +86,8 @@ trait ApiRepositoryControllerBase extends ControllerBase {
|
||||
data.name,
|
||||
data.description,
|
||||
data.`private`,
|
||||
data.auto_init
|
||||
data.auto_init,
|
||||
context.settings.defaultBranch
|
||||
)
|
||||
Await.result(f, Duration.Inf)
|
||||
|
||||
@@ -129,7 +124,8 @@ trait ApiRepositoryControllerBase extends ControllerBase {
|
||||
data.name,
|
||||
data.description,
|
||||
data.`private`,
|
||||
data.auto_init
|
||||
data.auto_init,
|
||||
context.settings.defaultBranch
|
||||
)
|
||||
Await.result(f, Duration.Inf)
|
||||
val repository = Database() withTransaction { session =>
|
||||
@@ -184,9 +180,11 @@ trait ApiRepositoryControllerBase extends ControllerBase {
|
||||
* https://docs.github.com/en/rest/reference/repos#list-repository-tags
|
||||
*/
|
||||
get("/api/v3/repos/:owner/:repository/tags")(referrersOnly { repository =>
|
||||
JsonFormat(
|
||||
repository.tags.map(tagInfo => ApiTag(tagInfo.name, RepositoryName(repository), tagInfo.id))
|
||||
)
|
||||
Using.resource(Git.open(getRepositoryDir(repository.owner, repository.name))) { git =>
|
||||
JsonFormat(
|
||||
repository.tags.map(tagInfo => ApiTag(tagInfo.name, RepositoryName(repository), tagInfo.commitId))
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
/*
|
||||
|
||||
@@ -7,7 +7,7 @@ import gitbucket.core.util.Implicits._
|
||||
import gitbucket.core.util.{JGitUtil, ReferrerAuthenticator, WritableUsersAuthenticator}
|
||||
|
||||
trait ApiRepositoryStatusControllerBase extends ControllerBase {
|
||||
self: AccountService with CommitStatusService with ReferrerAuthenticator with WritableUsersAuthenticator =>
|
||||
self: AccountService & CommitStatusService & ReferrerAuthenticator & WritableUsersAuthenticator =>
|
||||
|
||||
/*
|
||||
* i. Create a status
|
||||
@@ -47,9 +47,8 @@ trait ApiRepositoryStatusControllerBase extends ControllerBase {
|
||||
ref <- params.get("ref")
|
||||
sha <- JGitUtil.getShaByRef(repository.owner, repository.name, ref)
|
||||
} yield {
|
||||
JsonFormat(getCommitStatusesWithCreator(repository.owner, repository.name, sha).map {
|
||||
case (status, creator) =>
|
||||
ApiCommitStatus(status, ApiUser(creator))
|
||||
JsonFormat(getCommitStatusesWithCreator(repository.owner, repository.name, sha).map { case (status, creator) =>
|
||||
ApiCommitStatus(status, ApiUser(creator))
|
||||
})
|
||||
}) getOrElse NotFound()
|
||||
})
|
||||
|
||||
@@ -8,7 +8,7 @@ import gitbucket.core.util.Implicits._
|
||||
import org.scalatra.NoContent
|
||||
|
||||
trait ApiRepositoryWebhookControllerBase extends ControllerBase {
|
||||
self: RepositoryService with WebHookService with ReferrerAuthenticator with WritableUsersAuthenticator =>
|
||||
self: RepositoryService & WebHookService & ReferrerAuthenticator & WritableUsersAuthenticator =>
|
||||
|
||||
/*
|
||||
* i. List repository webhooks
|
||||
@@ -113,8 +113,8 @@ trait ApiRepositoryWebhookControllerBase extends ControllerBase {
|
||||
*/
|
||||
|
||||
/*
|
||||
* vi. Test the push repository webhook
|
||||
* https://docs.github.com/en/rest/reference/repos#test-the-push-repository-webhook
|
||||
*/
|
||||
* vi. Test the push repository webhook
|
||||
* https://docs.github.com/en/rest/reference/repos#test-the-push-repository-webhook
|
||||
*/
|
||||
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import gitbucket.core.util.StringUtil._
|
||||
import org.scalatra.NoContent
|
||||
|
||||
trait ApiUserControllerBase extends ControllerBase {
|
||||
self: RepositoryService with AccountService with AdminAuthenticator with UsersAuthenticator =>
|
||||
self: RepositoryService & AccountService & AdminAuthenticator & UsersAuthenticator =>
|
||||
|
||||
/**
|
||||
* i. Get a single user
|
||||
|
||||
@@ -10,7 +10,7 @@ trait AccessTokenComponent { self: Profile =>
|
||||
val userName = column[String]("USER_NAME")
|
||||
val tokenHash = column[String]("TOKEN_HASH")
|
||||
val note = column[String]("NOTE")
|
||||
def * = (accessTokenId, userName, tokenHash, note).<>(AccessToken.tupled, AccessToken.unapply)
|
||||
def * = (accessTokenId, userName, tokenHash, note).mapTo[AccessToken]
|
||||
}
|
||||
}
|
||||
case class AccessToken(
|
||||
|
||||
@@ -35,7 +35,7 @@ trait AccountComponent { self: Profile =>
|
||||
groupAccount,
|
||||
removed,
|
||||
description.?
|
||||
).<>(Account.tupled, Account.unapply)
|
||||
).mapTo[Account]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ trait AccountExtraMailAddressComponent { self: Profile =>
|
||||
val userName = column[String]("USER_NAME", O PrimaryKey)
|
||||
val extraMailAddress = column[String]("EXTRA_MAIL_ADDRESS", O PrimaryKey)
|
||||
def * =
|
||||
(userName, extraMailAddress).<>(AccountExtraMailAddress.tupled, AccountExtraMailAddress.unapply)
|
||||
(userName, extraMailAddress).mapTo[AccountExtraMailAddress]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ trait AccountFederationComponent { self: Profile =>
|
||||
val issuer = column[String]("ISSUER")
|
||||
val subject = column[String]("SUBJECT")
|
||||
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] =
|
||||
(this.issuer === issuer.bind) && (this.subject === subject.bind)
|
||||
|
||||
@@ -9,7 +9,7 @@ trait AccountPreferenceComponent { self: Profile =>
|
||||
val userName = column[String]("USER_NAME", O PrimaryKey)
|
||||
val highlighterTheme = column[String]("HIGHLIGHTER_THEME")
|
||||
def * =
|
||||
(userName, highlighterTheme).<>(AccountPreference.tupled, AccountPreference.unapply)
|
||||
(userName, highlighterTheme).mapTo[AccountPreference]
|
||||
|
||||
def byPrimaryKey(userName: String): Rep[Boolean] = this.userName === userName.bind
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ trait AccountWebHookComponent extends TemplateComponent { self: Profile =>
|
||||
val url = column[String]("URL")
|
||||
val token = column[Option[String]]("TOKEN")
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ trait AccountWebHookEventComponent extends TemplateComponent { self: Profile =>
|
||||
val url = column[String]("URL")
|
||||
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)
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ trait ActivityComponent extends TemplateComponent { self: Profile =>
|
||||
lazy val Activities = TableQuery[Activities]
|
||||
|
||||
class Activities(tag: Tag) extends Table[Activity](tag, "ACTIVITY") with BasicTemplate {
|
||||
def * = ???
|
||||
def * : slick.lifted.ProvenShape[Activity] = ???
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ package gitbucket.core.model
|
||||
protected[model] trait TemplateComponent { self: Profile =>
|
||||
import profile.api._
|
||||
|
||||
trait BasicTemplate { self: Table[_] =>
|
||||
trait BasicTemplate { self: Table[?] =>
|
||||
val userName = column[String]("USER_NAME")
|
||||
val repositoryName = column[String]("REPOSITORY_NAME")
|
||||
|
||||
@@ -18,7 +18,7 @@ protected[model] trait TemplateComponent { self: Profile =>
|
||||
(this.userName === userName) && (this.repositoryName === repositoryName)
|
||||
}
|
||||
|
||||
trait IssueTemplate extends BasicTemplate { self: Table[_] =>
|
||||
trait IssueTemplate extends BasicTemplate { self: Table[?] =>
|
||||
val issueId = column[Int]("ISSUE_ID")
|
||||
|
||||
def byIssue(owner: String, repository: String, issueId: Int) =
|
||||
@@ -28,7 +28,7 @@ protected[model] trait TemplateComponent { self: Profile =>
|
||||
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 labelName = column[String]("LABEL_NAME")
|
||||
|
||||
@@ -42,7 +42,7 @@ protected[model] trait TemplateComponent { self: Profile =>
|
||||
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 priorityName = column[String]("PRIORITY_NAME")
|
||||
|
||||
@@ -56,7 +56,7 @@ protected[model] trait TemplateComponent { self: Profile =>
|
||||
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")
|
||||
|
||||
def byMilestone(owner: String, repository: String, milestoneId: Int) =
|
||||
@@ -66,7 +66,7 @@ protected[model] trait TemplateComponent { self: Profile =>
|
||||
byRepository(userName, repositoryName) && (this.milestoneId === milestoneId)
|
||||
}
|
||||
|
||||
trait CommitTemplate extends BasicTemplate { self: Table[_] =>
|
||||
trait CommitTemplate extends BasicTemplate { self: Table[?] =>
|
||||
val commitId = column[String]("COMMIT_ID")
|
||||
|
||||
def byCommit(owner: String, repository: String, commitId: String) =
|
||||
@@ -76,7 +76,7 @@ protected[model] trait TemplateComponent { self: Profile =>
|
||||
byRepository(userName, repositoryName) && (this.commitId === commitId)
|
||||
}
|
||||
|
||||
trait BranchTemplate extends BasicTemplate { self: Table[_] =>
|
||||
trait BranchTemplate extends BasicTemplate { self: Table[?] =>
|
||||
val branch = column[String]("BRANCH")
|
||||
def byBranch(owner: String, repository: String, branchName: String) =
|
||||
byRepository(owner, repository) && (branch === branchName.bind)
|
||||
|
||||
@@ -8,7 +8,7 @@ trait CollaboratorComponent extends TemplateComponent { self: Profile =>
|
||||
class Collaborators(tag: Tag) extends Table[Collaborator](tag, "COLLABORATOR") with BasicTemplate {
|
||||
val collaboratorName = column[String]("COLLABORATOR_NAME")
|
||||
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) =
|
||||
byRepository(owner, repository) && (collaboratorName === collaborator.bind)
|
||||
|
||||
@@ -21,7 +21,7 @@ trait IssueCommentComponent extends TemplateComponent { self: Profile =>
|
||||
val updatedDate = column[java.util.Date]("UPDATED_DATE")
|
||||
def * =
|
||||
(userName, repositoryName, issueId, commentId, action, commentedUserName, content, registeredDate, updatedDate)
|
||||
.<>(IssueComment.tupled, IssueComment.unapply)
|
||||
.mapTo[IssueComment]
|
||||
|
||||
def byPrimaryKey(commentId: Int) = this.commentId === commentId.bind
|
||||
}
|
||||
@@ -75,7 +75,7 @@ trait CommitCommentComponent extends TemplateComponent { self: Profile =>
|
||||
originalCommitId,
|
||||
originalOldLine,
|
||||
originalNewLine
|
||||
).<>(CommitComment.tupled, CommitComment.unapply)
|
||||
).mapTo[CommitComment]
|
||||
|
||||
def byPrimaryKey(commentId: Int) = this.commentId === commentId.bind
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ trait CommitStatusComponent extends TemplateComponent { self: Profile =>
|
||||
creator,
|
||||
registeredDate,
|
||||
updatedDate
|
||||
).<>((CommitStatus.apply _).tupled, CommitStatus.unapply)
|
||||
).mapTo[CommitStatus]
|
||||
def byPrimaryKey(id: Int) = commitStatusId === id.bind
|
||||
}
|
||||
}
|
||||
|
||||
377
src/main/scala/gitbucket/core/model/CustomField.scala
Normal file
377
src/main/scala/gitbucket/core/model/CustomField.scala
Normal file
@@ -0,0 +1,377 @@
|
||||
package gitbucket.core.model
|
||||
|
||||
import gitbucket.core.controller.Context
|
||||
import gitbucket.core.service.RepositoryService.RepositoryInfo
|
||||
import gitbucket.core.util.StringUtil
|
||||
import gitbucket.core.view.helpers
|
||||
import org.scalatra.i18n.Messages
|
||||
import play.twirl.api.Html
|
||||
|
||||
trait CustomFieldComponent extends TemplateComponent { self: Profile =>
|
||||
import profile.api._
|
||||
|
||||
lazy val CustomFields = TableQuery[CustomFields]
|
||||
|
||||
class CustomFields(tag: Tag) extends Table[CustomField](tag, "CUSTOM_FIELD") with BasicTemplate {
|
||||
val fieldId = column[Int]("FIELD_ID", O AutoInc)
|
||||
val fieldName = column[String]("FIELD_NAME")
|
||||
val fieldType = column[String]("FIELD_TYPE")
|
||||
val constraints = column[Option[String]]("CONSTRAINTS")
|
||||
val enableForIssues = column[Boolean]("ENABLE_FOR_ISSUES")
|
||||
val enableForPullRequests = column[Boolean]("ENABLE_FOR_PULL_REQUESTS")
|
||||
def * =
|
||||
(userName, repositoryName, fieldId, fieldName, fieldType, constraints, enableForIssues, enableForPullRequests)
|
||||
.mapTo[CustomField]
|
||||
|
||||
def byPrimaryKey(userName: String, repositoryName: String, fieldId: Int) =
|
||||
(this.userName === userName.bind) && (this.repositoryName === repositoryName.bind) && (this.fieldId === fieldId.bind)
|
||||
}
|
||||
}
|
||||
|
||||
case class CustomField(
|
||||
userName: String,
|
||||
repositoryName: String,
|
||||
fieldId: Int = 0,
|
||||
fieldName: String,
|
||||
fieldType: String, // long, double, string, date, or enum
|
||||
constraints: Option[String],
|
||||
enableForIssues: Boolean,
|
||||
enableForPullRequests: Boolean
|
||||
)
|
||||
|
||||
trait CustomFieldBehavior {
|
||||
def createHtml(repository: RepositoryInfo, fieldId: Int, fieldName: String, constraints: Option[String])(implicit
|
||||
context: Context
|
||||
): 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 {
|
||||
def validate(field: CustomField, value: String, messages: Messages): Option[String] = {
|
||||
if (value.isEmpty) None
|
||||
else {
|
||||
CustomFieldBehavior(field.fieldType).flatMap { behavior =>
|
||||
behavior.validate(field.fieldName, field.constraints, value, messages)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def apply(fieldType: String): Option[CustomFieldBehavior] = {
|
||||
fieldType match {
|
||||
case "long" => Some(LongFieldBehavior)
|
||||
case "double" => Some(DoubleFieldBehavior)
|
||||
case "string" => Some(StringFieldBehavior)
|
||||
case "date" => Some(DateFieldBehavior)
|
||||
case "enum" => Some(EnumFieldBehavior)
|
||||
case _ => None
|
||||
}
|
||||
}
|
||||
|
||||
case object LongFieldBehavior extends TextFieldBehavior {
|
||||
override def validate(
|
||||
name: String,
|
||||
constraints: Option[String],
|
||||
value: String,
|
||||
messages: Messages
|
||||
): Option[String] = {
|
||||
try {
|
||||
value.toLong
|
||||
None
|
||||
} catch {
|
||||
case _: NumberFormatException => Some(messages("error.number").format(name))
|
||||
}
|
||||
}
|
||||
}
|
||||
case object DoubleFieldBehavior extends TextFieldBehavior {
|
||||
override def validate(
|
||||
name: String,
|
||||
constraints: Option[String],
|
||||
value: String,
|
||||
messages: Messages
|
||||
): Option[String] = {
|
||||
try {
|
||||
value.toDouble
|
||||
None
|
||||
} catch {
|
||||
case _: NumberFormatException => Some(messages("error.number").format(name))
|
||||
}
|
||||
}
|
||||
}
|
||||
case object StringFieldBehavior extends TextFieldBehavior
|
||||
case object DateFieldBehavior extends TextFieldBehavior {
|
||||
private val pattern = "yyyy-MM-dd"
|
||||
override protected val fieldType: String = "date"
|
||||
|
||||
override def validate(
|
||||
name: String,
|
||||
constraints: Option[String],
|
||||
value: String,
|
||||
messages: Messages
|
||||
): Option[String] = {
|
||||
try {
|
||||
new java.text.SimpleDateFormat(pattern).parse(value)
|
||||
None
|
||||
} catch {
|
||||
case _: java.text.ParseException =>
|
||||
Some(messages("error.datePattern").format(name, pattern))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
protected val fieldType = "text"
|
||||
|
||||
override def createHtml(repository: RepositoryInfo, fieldId: Int, fieldName: String, constraints: Option[String])(
|
||||
implicit context: Context
|
||||
): String = {
|
||||
val sb = new StringBuilder
|
||||
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;"/>"""
|
||||
)
|
||||
sb.append(s"""<script>
|
||||
|$$('#custom-field-$fieldId').focusout(function(){
|
||||
| const $$this = $$(this);
|
||||
| $$.post('${helpers.url(repository)}/issues/customfield_validation/$fieldId',
|
||||
| { value: $$this.val() },
|
||||
| function(data){
|
||||
| if (data != '') {
|
||||
| $$('#custom-field-$fieldId-error').text(data);
|
||||
| } else {
|
||||
| $$('#custom-field-$fieldId-error').text('');
|
||||
| }
|
||||
| }
|
||||
| );
|
||||
|});
|
||||
|</script>
|
||||
|""".stripMargin)
|
||||
sb.toString()
|
||||
}
|
||||
|
||||
override def fieldHtml(
|
||||
repository: RepositoryInfo,
|
||||
issueId: Int,
|
||||
fieldId: Int,
|
||||
fieldName: String,
|
||||
constraints: Option[String],
|
||||
value: String,
|
||||
editable: Boolean
|
||||
)(implicit
|
||||
context: Context
|
||||
): String = {
|
||||
val sb = new StringBuilder
|
||||
if (value.nonEmpty) {
|
||||
sb.append(
|
||||
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) {
|
||||
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;"/>"""
|
||||
)
|
||||
sb.append(s"""<script>
|
||||
|$$('#custom-field-$fieldId-label').click(function(){
|
||||
| const $$this = $$(this);
|
||||
| $$this.hide();
|
||||
| $$this.next().val($$this.text()).show().focus();
|
||||
|});
|
||||
|
|
||||
|$$('#custom-field-$fieldId-editor').focusout(function(){
|
||||
| const $$this = $$(this);
|
||||
| $$.post('${helpers.url(repository)}/issues/customfield_validation/$fieldId',
|
||||
| { value: $$this.val() },
|
||||
| function(data){
|
||||
| if (data != '') {
|
||||
| $$('#custom-field-$fieldId-error').text(data);
|
||||
| } else {
|
||||
| $$('#custom-field-$fieldId-error').text('');
|
||||
| $$.post('${helpers.url(repository)}/issues/$issueId/customfield/$fieldId',
|
||||
| { value: $$this.val() },
|
||||
| function(data){
|
||||
| $$this.hide();
|
||||
| if (data == '') {
|
||||
| $$this.prev().html('<i class="octicon octicon-pencil" style="cursor: pointer;">').show();
|
||||
| } else {
|
||||
| $$this.prev().text(data).show();
|
||||
| }
|
||||
| }
|
||||
| );
|
||||
| }
|
||||
| }
|
||||
| );
|
||||
|});
|
||||
|
|
||||
|// ESC key handling in text field
|
||||
|$$('#custom-field-$fieldId-editor').keyup(function(e){
|
||||
| if (e.keyCode == 27) {
|
||||
| const $$this = $$(this);
|
||||
| $$this.hide();
|
||||
| $$this.prev().show();
|
||||
| }
|
||||
| if (e.keyCode == 13) {
|
||||
| $$('#custom-field-$fieldId-editor').blur();
|
||||
| }
|
||||
|});
|
||||
|</script>
|
||||
|""".stripMargin)
|
||||
}
|
||||
sb.toString()
|
||||
}
|
||||
|
||||
override def validate(
|
||||
name: String,
|
||||
constraints: Option[String],
|
||||
value: String,
|
||||
messages: Messages
|
||||
): Option[String] = None
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ trait DeployKeyComponent extends TemplateComponent { self: Profile =>
|
||||
val publicKey = column[String]("PUBLIC_KEY")
|
||||
val allowWrite = column[Boolean]("ALLOW_WRITE")
|
||||
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) =
|
||||
(this.userName === userName.bind) && (this.repositoryName === repositoryName.bind) && (this.deployKeyId === deployKeyId.bind)
|
||||
|
||||
@@ -11,7 +11,7 @@ trait GpgKeyComponent { self: Profile =>
|
||||
val gpgKeyId = column[Long]("GPG_KEY_ID")
|
||||
val title = column[String]("TITLE")
|
||||
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) =
|
||||
(this.userName === userName.bind) && (this.keyId === keyId.bind)
|
||||
|
||||
@@ -9,7 +9,7 @@ trait GroupMemberComponent { self: Profile =>
|
||||
val groupName = column[String]("GROUP_NAME", O PrimaryKey)
|
||||
val userName = column[String]("USER_NAME", O PrimaryKey)
|
||||
val isManager = column[Boolean]("MANAGER")
|
||||
def * = (groupName, userName, isManager).<>(GroupMember.tupled, GroupMember.unapply)
|
||||
def * = (groupName, userName, isManager).mapTo[GroupMember]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user