Compare commits

..

192 Commits

Author SHA1 Message Date
Unknwon
c9e0b3b987 prepare for 0.5.9 2014-12-13 20:32:30 -05:00
Unknwon
28766479a7 update gopmfile 2014-12-13 20:26:04 -05:00
Unknwon
9ac940d31d update locales 2014-12-13 20:06:50 -05:00
Unknwon
b553ea45ee modes/repo: incorrect SSH clone URL for #742 2014-12-13 16:46:00 -05:00
Unknwon
ac4a10456e api: able to create repo and fix #726
- POST /user/repos
- POST /org/:org/repos
2014-12-12 20:30:32 -05:00
Unknwon
2f3a7e53cb fix #735 2014-12-12 01:29:36 -05:00
Unknwon
42c7bb7529 mirror code clean 2014-12-11 18:55:09 -05:00
无闻
35140f1cc7 Merge pull request #731 from cryptix/dev
increase minimum version for HTTPS to TLS 1.0 (POODLE, fixes #730)
2014-12-11 18:32:49 -05:00
Henry
4f4392b83e increase minimum version vor HTTPS to TLS 1.0 (POODLE, fixes #730) 2014-12-11 11:14:41 +01:00
codeskyblue
db6c0ebf76 fix git clone error when repo has upper case name 2014-12-11 15:57:32 +08:00
Unknwon
cf7ebfbdc8 mirror fix on release JS 2014-12-10 16:41:49 -05:00
Unknwon
bc8721fb6c Finish new UI for release page 2014-12-10 16:37:54 -05:00
Unknwon
01ba771783 fix #703 2014-12-10 07:00:11 -05:00
Unknwon
9ee80e3e54 fix compile error 2014-12-10 05:10:26 -05:00
无闻
b2c6a6920f Merge pull request #727 from Mageti/master
Correction for #723
2014-12-10 05:03:50 -05:00
Mageti
e321469884 remove unused code in BasicAuthDecode 2014-12-10 11:01:17 +01:00
Mageti
b7ebbb4064 Correction for #723
Correction for #723
Bug was : decode failed if the password contains ```:```
2014-12-10 10:51:51 +01:00
Unknwon
9a1fe801e5 fix #711 2014-12-09 02:18:25 -05:00
Unknwon
6f71632e3e new language 2014-12-07 19:27:49 -05:00
无闻
2844674587 Merge pull request #720 from Alukardd/dev
Allow send mail without authentication if SMTP server allow this
2014-12-07 16:05:55 -05:00
fuxiaohei
0daef29053 add label-create ui elements 2014-12-07 21:29:37 +08:00
Alukardd
21081836ba Allow send mail without authentication if SMTP server allow this 2014-12-07 16:07:48 +03:00
无闻
a2f6e1803b Merge pull request #718 from jbcrail/fix-comment-spelling
Fix spelling errors in comments.
2014-12-06 21:01:00 -05:00
Joseph Crail
39c068400e Fix spelling errors in comments. 2014-12-06 20:22:48 -05:00
Unknwon
47e7175b80 upload locales 2014-12-05 18:27:59 -05:00
Unknwon
0b785ad967 work on #672 2014-12-05 18:08:09 -05:00
Unknwon
069486d169 fix #165 2014-12-05 17:54:57 -05:00
无闻
298ebc58c1 Merge pull request #716 from ErebusBat/master
Fix Gravatar images in web view (like commit listing)
2014-12-05 16:20:34 -05:00
无闻
3fd41d138c Merge pull request #712 from Dennis-Smurf/enhancement-issuelink-in-commit
Added issue link rendering in commit messages
2014-12-05 16:15:43 -05:00
Andrew Burns
35b02997f8 Fix Gravatar images in web view (like commit listing)
Related to #700

In the original bug report it was referencing only the sytem avatar images for setup users (like in the header); however the problem also persists with things like commit history.

This commit fixes the `tool.AvatarLink` function so that it also uses the already existing `avatar.HashEmail` function.

I also refactored the `tool.AvatarLink` method some to make the control flow more apparent and adhere better to DRY (there were multiple calls to the `EncodeMd5` function that the `HashEmail` function call replaced, now there is only one.)
2014-12-05 11:02:59 -07:00
Andrew Burns
adc1ac689e HashEmail function should also remove spaces
According to the [Gravatar API](https://en.gravatar.com/site/implement/hash/) whitespace should also be removed from the email, it was not doing this previously.
2014-12-05 10:58:49 -07:00
dennis-smurf
528c075ad6 Added issue link rendering in commit messages 2014-12-05 11:02:52 +01:00
Unknwon
e577f2fff3 fix #706 and other mirror improve 2014-12-04 23:07:51 -05:00
无闻
daf96dfae1 Merge pull request #709 from TonyTsangHK/dev
Display multi-line commit message on commit diff page.
2014-12-04 22:36:54 -05:00
Tony Tsang
d4a1d9f82a Display multi-line commit message on commit diff page. 2014-12-05 10:53:37 +08:00
无闻
f7f4ea1dcf Merge pull request #708 from ErebusBat/master
Use the avatar.HashEmail function instead of hashing email directly.
2014-12-04 18:33:10 -05:00
fuxiaohei
0af3a5b603 add issue list filter ui 2014-12-04 23:22:16 +08:00
Andrew Burns
00cf3e4dab Use the avatar.HashEmail function instead of hashing email directly. Fixes #700 2014-12-03 16:19:35 -07:00
无闻
cb6be94358 Merge pull request #696 from deiwin/update/user-api-to-include-full-name
add full name to found users' list on the UI
2014-12-02 10:27:24 -05:00
Deiwin Sarjas
54ef1cee1d add full name to found users' list 2014-12-02 16:55:52 +02:00
无闻
b9999427a8 Merge pull request #694 from deiwin/update/user-api-to-include-full-name
update user api search results to include the full name
2014-12-02 07:50:05 -05:00
无闻
ddeb076890 Merge pull request #695 from CBiX/dev
fixed code view line height for firefox
2014-12-02 07:47:13 -05:00
Florian Hülsmann
d06d58e461 fixed code view line height for firefox 2014-12-02 11:31:57 +01:00
Deiwin Sarjas
48bb0fadc2 update user api search results to include the full name
Is fully backwards compatible
Fixes #677
2014-12-02 11:44:03 +02:00
无闻
cd627ba16e Merge pull request #690 from Dennis-Smurf/feature-sha1-markdown-pattern
Addded sha1 pattern in markdown for current repository
2014-12-01 11:35:18 -05:00
dennis-smurf
d0a80e432d Addded sha1 pattern in markdown for current repository 2014-12-01 09:30:35 +01:00
Unknwon
9558999698 mirror fix 2014-11-30 18:35:05 -05:00
Unknwon
5338808600 fix #676 2014-11-30 18:29:16 -05:00
Unknwon
82da024a4d fix #687 2014-11-30 10:55:26 -05:00
Unknwon
5c866fc737 Merge branch 'dev' of github.com:gogits/gogs into dev 2014-11-30 02:26:33 -05:00
Unknwon
d75013a0e8 fix #580 2014-11-30 02:26:29 -05:00
无闻
1591a37ad5 Merge pull request #686 from willglynn/cert_stub_exit_code
Cert command stub should return a non-zero exit code
2014-11-30 01:38:35 -05:00
Will Glynn
3e528f34af Cert command stub should return a non-zero exit code 2014-11-29 21:52:59 -06:00
Unknwon
b6437b5a4c safe check 2014-11-28 21:54:49 -05:00
Unknwon
db4951bc61 mirror fix on oauth2 2014-11-28 21:38:35 -05:00
Unknwon
d6132aaa88 fix oauth2 2014-11-28 21:20:13 -05:00
无闻
9adc8e9d3f Merge pull request #683 from jcracknell/admin-repos-cols
Fix swapped issue/star columns in /admin/repos
2014-11-28 15:28:08 -05:00
无闻
be54b4bf26 Merge pull request #682 from jcracknell/user-links
Fix user links
2014-11-28 15:22:56 -05:00
James Cracknell
64d90a761b Fix swapped issue/star columns in /admin/repos 2014-11-28 12:40:02 -07:00
James Cracknell
4d123d0a93 Fix user links 2014-11-28 11:53:00 -07:00
Unknwon
5dd8308686 Merge branch 'dev' of github.com:gogits/gogs into dev 2014-11-27 21:36:20 -05:00
Unknwon
9c2120eb34 fix #675 2014-11-27 21:36:12 -05:00
无闻
4f8d888e66 Merge pull request #674 from jcracknell/pfx-export
Added comments documenting how to export SSL keys from .pfx
2014-11-27 16:56:55 -05:00
James Cracknell
ca09a0b516 Added comments documenting how to export SSL keys from .pfx 2014-11-27 14:42:06 -07:00
Unknwon
a43164877c fix #664 2014-11-25 23:05:43 -05:00
Unknwon
515641d033 fix #659 2014-11-25 22:48:04 -05:00
Unknwon
54d25c13d7 Fix #543 2014-11-24 18:47:59 -05:00
fuxiaohei
23d53561d1 update milestone page design 2014-11-24 23:13:42 +08:00
Unknwon
0cce61de3a Merge branch 'dev' of github.com:gogits/gogs into dev 2014-11-24 09:54:22 -05:00
Unknwon
5b96e3fcc7 fix #660 2014-11-24 09:54:08 -05:00
fuxiaohei
79dae254cf add milestone page design 2014-11-24 22:33:04 +08:00
无闻
5b32cdd960 Merge pull request #657 from chai2010/dev
Fix #656
2014-11-23 22:15:25 -05:00
chai2010
f9ad8d6903 Fix #656 2014-11-24 10:58:39 +08:00
Unknwon
1b66600bd0 Fix #652 2014-11-23 02:33:47 -05:00
Unknwon
dc53270da9 Fix 653 2014-11-22 10:22:53 -05:00
Unknwon
8ea7ba3afa fix #644 2014-11-21 13:10:00 -05:00
Unknwon
ef275ebf62 more on change avatar 2014-11-21 12:51:36 -05:00
Unknwon
22ab4fa1b0 fix #139 2014-11-21 11:08:24 -05:00
Unknwon
55dfe2c978 custom avatar upload 2014-11-21 10:58:08 -05:00
Unknwon
3c3f7c2a56 Fix #643 2014-11-20 18:03:42 -05:00
Unknwon
0c92da7e9c fix invalid user links in admin panels 2014-11-19 21:19:37 -05:00
无闻
8fac41768c Merge pull request #639 from pkgr/pkgr
Make postinstall work for CentOS/RHEL packages as well.
2014-11-19 17:27:53 -05:00
Cyril Rohr
c418b83678 Make postinstall work for CentOS/RHEL packages as well. 2014-11-19 21:43:12 +00:00
无闻
b53f6357fc Merge pull request #638 from pkgr/pkgr
Fix packages generated on packager.io
2014-11-19 15:51:00 -05:00
Cyril Rohr
11ca3dedfb Fix .pkgr.yml 2014-11-19 19:18:44 +00:00
Cyril Rohr
f77680520f Link custom app.ini to /etc/gogs/ 2014-11-19 19:18:44 +00:00
Unknwon
2d8c414f8c Fix #635 2014-11-18 19:05:33 -05:00
Unknwon
ce8d4cc80b #634 2014-11-18 15:13:08 -05:00
Unknwon
37d8d3afe9 more APIs on #12 2014-11-18 11:07:16 -05:00
Unknwon
db0026c507 test drone 2014-11-17 17:47:13 -05:00
Unknwon
51f6148851 test drone 2014-11-17 17:36:51 -05:00
Unknwon
c0549a169a test drone 2014-11-17 17:19:17 -05:00
Unknwon
1e47e2df85 quick fix 2014-11-17 16:29:23 -05:00
Unknwon
5d9ef2bb12 lock gopmfile 2014-11-17 16:25:39 -05:00
无闻
d21d7171b0 Merge pull request #587 from eryx/dev
Fix #266
2014-11-17 16:17:52 -05:00
Unknwon
32dcaefafa fox #620 2014-11-17 14:53:41 -05:00
fuxiaohei
d1a60e3643 add pull-request and labels page design 2014-11-17 23:07:34 +08:00
Unknwon
a0f9197b45 GetFile api 2014-11-16 21:32:26 -05:00
Unknwon
340a4595dd support duoshuo mirror of gravatar 2014-11-16 20:27:04 -05:00
无闻
4c770b87c5 Merge pull request #628 from KylePDavis/use_url_prefix_for_fcgi
Use AppSubUrl as prefix for routes in FCGI mode
2014-11-16 06:59:01 -05:00
Kyle P Davis
47f37e55e9 use AppSubUrl as prefix for routes in FCGI mode 2014-11-16 00:06:09 -05:00
Unknwon
52d66ba6c8 #12, use go-gogs-client 2014-11-14 17:11:30 -05:00
无闻
437dd5272f Merge pull request #626 from skibum55/dev
Add function argument missing
2014-11-14 15:12:30 -05:00
Sean Keery
6bdb8ec4b9 Add function argument missing
Not enough arguments in call to c.AddFunc when I copied and pasted
2014-11-14 10:58:37 -07:00
Unknwon
9dc3c93a6a #12, add/edit hook 2014-11-13 12:57:00 -05:00
Unknwon
9e22840483 fix #622 2014-11-13 05:27:01 -05:00
Unknwon
8eb5120fbd #12, API: list user repos, list repo hooks 2014-11-13 02:32:18 -05:00
Unknwon
8c9338a537 add personal access token panel #12 2014-11-12 06:48:50 -05:00
Unknwon
21b9d5fa1f Fix #618 2014-11-11 16:56:57 -05:00
Unknwon
4f360d8f08 Fix #617 and update Germeny locale 2014-11-11 15:30:11 -05:00
Unknwon
dfa4b38081 work on #616 2014-11-10 06:26:07 -05:00
Unknwon
e0de6cb5ad work on #616 and update locales 2014-11-10 05:30:07 -05:00
Unknwon
ff8578082e update locale files 2014-11-07 17:07:36 -05:00
Unknwon
35977cd34c continue work on #255 2014-11-07 16:44:25 -05:00
Unknwon
abc57b6e43 work on #609 2014-11-07 14:46:13 -05:00
无闻
a01b4baca2 Merge pull request #612 from justinclift/enable_el6_builds
Enable package building on EL6
2014-11-06 23:13:27 -05:00
Justin Clift
fc5985f425 Enable package building on EL6 2014-11-07 03:44:34 +00:00
Unknwon
23eec25274 Fix #605, fix #255, fix #101 2014-11-06 22:06:41 -05:00
Unknwon
4e7eb5be9d Work on #5 fork and fix #608 2014-11-05 23:30:04 -05:00
Unknwon
b375192352 fix tpl error 2014-11-04 12:07:43 -05:00
Unknwon
0c5ba4573a fix session API broken and SQL pretection 2014-11-04 11:37:15 -05:00
fuxiaohei
69a98236bd Merge remote-tracking branch 'origin/dev' into dev 2014-11-04 21:58:47 +08:00
fuxiaohei
b866dc92d7 finish issue list ui draft 2014-11-04 21:58:28 +08:00
Unknwon
78f4f59380 ui fix 2014-11-04 07:59:36 -05:00
Unknwon
743b55b9b0 fix gobuild 2014-11-04 07:56:07 -05:00
无闻
0d5d555521 Merge pull request #604 from omeid/dev
Fix x padding for #repo-content for width < 1170px
2014-11-04 07:55:40 -05:00
omeid
80c6cc6321 Fix x padding for #repo-content for width < 1170px
This pull request fixes the issue when resizing the window smaller than 1170 px, right now there is no padding/margin on sides and it looks broken.
2014-11-04 14:14:23 +11:00
无闻
6588ce52fe Merge pull request #602 from andyleap/fcgi
Add basic FCGI support
2014-11-03 21:04:00 -05:00
Andy Leap
5094e9501c Add basic FCGI support 2014-11-03 20:49:56 -05:00
Unknwon
e9875edcad Update gopmfile 2014-11-02 10:57:29 -05:00
无闻
7e2ea7639e Merge pull request #596 from isotas38/dev
Fix #595
2014-11-02 10:57:04 -05:00
无闻
5b290013a9 Merge pull request #597 from luto/fix-mysql-engine
force the use of InnoDB as db engine for all tables
2014-11-02 10:52:36 -05:00
isotas38
2c28ed8c05 Fix #595 2014-11-02 14:18:37 +09:00
Unknwon
283c81316c locale fix 2014-11-01 21:43:53 -04:00
无闻
beb8a77fc5 Merge pull request #593 from mcheng89/dev
check for smtp AUTH extension
2014-10-31 22:18:15 -04:00
mcheng89
b9881d1e7b check for smtp AUTH extension 2014-10-31 21:52:03 -04:00
无闻
87be4623cf Merge pull request #591 from semlanik/semlanik/589
Fix Issue 589
2014-10-30 22:31:47 -04:00
semlanik
377530ec21 Fix Issue 589 2014-10-30 22:13:52 +03:00
luto
bff1e157d5 force the use of InnoDB as db engine for all tables, fixes #59 2014-10-28 16:40:09 +01:00
Eryx
e84e0ab904 Fix #266 2014-10-28 10:36:47 +08:00
Unknwon
c7f56d7483 Fix #584 2014-10-27 11:18:00 -04:00
Unknwon
83283bca4c Safe work 2014-10-25 07:50:19 -04:00
Unknwon
f1d8746264 Fix fork repo and macaron API broken 2014-10-24 18:43:17 -04:00
无闻
baae94b9cf Merge pull request #581 from compressed/slack_upd
update slack hook to use new format
2014-10-24 17:54:40 -04:00
Christopher Brickley
3794111460 update slack hook to use new format 2014-10-24 08:56:12 -04:00
无闻
d7ea49b9f5 Merge pull request #579 from TonyTsangHK/dev
Fix misuse of issue index for issue id.
2014-10-22 08:44:33 -04:00
Tony Tsang
d87a9cb362 Avoid setting missing label/milestone/assignee ids
Label, milestone, assignee ids are not includes in post request, possible
js or form building bug.
2014-10-22 14:52:49 +08:00
Tony Tsang
93b9a2acc0 Fix misuse of issue index for issue id.
- UpdateAssignee
- UpdateIssueMilestone
2014-10-21 16:27:01 +08:00
无闻
d4a608f64c Merge pull request #577 from eryx/master
Fix #575
2014-10-20 04:44:06 -04:00
Eryx
8209bf74f8 Fix #575 2014-10-20 11:44:11 +08:00
Unknwon
d88ebd9a4b Fix #554 2014-10-19 02:22:38 -04:00
Unknwon
ec8ec58b17 Update gopmfile 2014-10-19 02:13:39 -04:00
Unknwon
a342d58d7e Able to fork repo to individuals 2014-10-19 01:35:24 -04:00
无闻
d7d167ac63 Merge pull request #560 from evolvedlight/master
First cut of fork repo
2014-10-18 23:59:36 -04:00
Unknwon
146c8efee3 Fix API broken 2014-10-18 23:42:43 -04:00
Unknwon
3abc41ccca Fix API broken 2014-10-18 23:26:55 -04:00
fuxiaohei
9e3a1bc11a add nav bar in issue list 2014-10-18 22:52:34 +08:00
fuxiaohei
cb2da7bf2c some ui details fix 2014-10-18 22:15:05 +08:00
Unknwon
1aa12c7452 Fix #572 2014-10-15 16:28:38 -04:00
Unknwon
fa241efa6d Use binding middleware 2014-10-15 11:19:20 -04:00
Unknwon
ecf3eb4307 Fix #570 2014-10-15 07:55:20 -04:00
Unknwon
9ae92459a5 Fix repo css and rel path img in md 2014-10-14 23:44:34 -04:00
无闻
5b3f1efd9f Merge pull request #567 from TonyTsangHK/dev
Fixes #562 & updated zh-HK locale
2014-10-14 14:25:07 -04:00
Tony Tsang
e0f945959e Replace white spaces with tab for format consistency 2014-10-14 17:31:35 +08:00
Tony Tsang
885833892f Updated locale zh-HK 2014-10-14 17:04:45 +08:00
Tony Tsang
91127d9016 Fixes #562 2014-10-14 16:46:25 +08:00
无闻
1a38f0e0d9 Merge pull request #561 from eryx/master
Fix pagination() to get the right total number of pages
2014-10-13 22:47:21 -04:00
Eryx
fb8beaf19a Fix pagination() to get the right total number of pages 2014-10-14 09:54:45 +08:00
Unknwon
4a8a70dde0 Fix gzip 2014-10-13 18:04:07 -04:00
evolvedlight
8d2a6fc484 Merge remote-tracking branch 'upstream/dev'
Conflicts:
	models/repo.go
2014-10-13 20:30:31 +01:00
evolvedlight
29ac3980ff More changes 2014-10-13 20:23:30 +01:00
无闻
89bd994c83 Merge pull request #558 from jacksonpan/master
add +x autoboot.sh
2014-10-13 04:00:46 -04:00
jacksonpan
3e4db7299d add +x autoboot.sh
fix
2014-10-13 15:52:29 +08:00
无闻
80dd548b39 Merge pull request #556 from jacksonpan/master
update the supervisor script and conf
2014-10-13 03:24:59 -04:00
Unknwon
451f328a4c Fix #457 and fix #557 2014-10-13 03:07:47 -04:00
jacksonpan
9e4c2afad7 add auto start script
how to use:
vim /etc/rc.local, then add
cd /home/git/gogs; scripts/autoboot.sh
(goes path you can replace your path)
2014-10-13 14:32:08 +08:00
jacksonpan
2dd4ab65c7 update the supervisor script and conf
now, we auto add the start.sh -> /usr/bin/gogs_start, then supervisor
needn’t the full path, detail please see the commit.
and how to use:
entry gogs root path, then input
scripts/gogs_supervisord.sh restart (add sudo if need)
2014-10-13 14:23:55 +08:00
Unknwon
b93ae452fe Fix #555 2014-10-12 23:22:16 -04:00
Unknwon
c04aea8d9d Fix #540 2014-10-12 02:39:00 -04:00
Unknwon
0d7b9065c6 Fix #540 2014-10-12 02:06:46 -04:00
Unknwon
452ccff81c Mirror fix on add ssh key 2014-10-11 21:04:42 -04:00
Unknwon
fb839ca0fb More debug info 2014-10-11 20:34:48 -04:00
Unknwon
b7b7863364 Work on ssh key issue 2014-10-11 20:06:35 -04:00
Unknwon
3005c4f6db Fix diff css style, hooks \r char 2014-10-11 18:20:07 -04:00
Unknwon
963354c5d7 Add raw, history file button, and other mirror fixes 2014-10-11 18:02:48 -04:00
无闻
17c1bc7383 Merge pull request #549 from m0sth8/fix-timesince
Add omitted lang
2014-10-11 17:36:33 -04:00
Vyacheslav Bakhmutov
5103f16f78 add omitted lang 2014-10-11 13:43:21 +07:00
lunnyxiao
e848b17fab bug fixed for #540 2014-10-11 13:24:36 +08:00
Unknwon
3600498c8f Add push tag action 2014-10-10 21:58:13 -04:00
Unknwon
b2632dec09 Page: Compare 2 commits 2014-10-10 21:40:51 -04:00
evolvedlight
211dc74816 Got the fork count working 2014-10-10 00:21:36 +01:00
evolvedlight
c9e5e38fcf Initial cut of git fork 2014-10-04 18:19:14 +01:00
159 changed files with 10213 additions and 6160 deletions

View File

@@ -14,7 +14,7 @@ watch_dirs = [
watch_exts = [".go", ".ini"]
build_delay = 1500
cmds = [
["go", "install", "-tags", "sqlite cert"],
["go", "install", "-tags", "sqlite cert"],# redis memcache
["go", "build", "-tags", "sqlite cert"],
["./gogs", "web"]
]

11
.gitignore vendored
View File

@@ -8,28 +8,19 @@ data/
*.iml
public/img/avatar/
files/
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.exe~
/gogs
@@ -42,3 +33,5 @@ config.codekit
docker/fig.yml
docker/docker/Dockerfile
docker/docker/init_gogs.sh
gogs.sublime-project
gogs.sublime-workspace

View File

@@ -10,6 +10,7 @@ filesets:
- README_ZH.md
excludes:
- \.git
depth: 5
settings:
build: |
if test "$GOOS" = "windows" -a "$GOARCH" = "386"

View File

@@ -7,20 +7,22 @@ github.com/beego/redigo = commit:856744a0d5
github.com/Unknwon/cae = commit:2e70a1351b
github.com/Unknwon/com = commit:2cbcbc6916
github.com/Unknwon/goconfig = commit:0f8d8dc1c0
github.com/Unknwon/i18n = commit:47baeff8d0
github.com/Unknwon/macaron = commit:4927b78ad9
github.com/Unknwon/i18n = commit:aec5f77857
github.com/Unknwon/macaron = commit:3d307c1232
github.com/codegangsta/cli = commit:7381bc4e62
github.com/go-sql-driver/mysql = commit:8111ee3ec3
github.com/go-xorm/core = commit:750aae0fa5
github.com/go-xorm/xorm = commit:2d8b3135b1
github.com/gogits/gfm = commit:40f747a9c0
github.com/go-xorm/core = commit:3e0fa232ab
github.com/go-xorm/xorm = commit:58d33844ce
github.com/gogits/go-gogs-client = commit:92e76d616a
github.com/gogits/oauth2 = commit:99cbec870a
github.com/lib/pq = commit:b021d0ef20
github.com/macaron-contrib/cache = commit:204d8e5137
github.com/macaron-contrib/captcha = commit:d37d37eeea
github.com/macaron-contrib/csrf = commit:8e980822b0
github.com/macaron-contrib/i18n = commit:2246f45894
github.com/macaron-contrib/session = commit:42ad41e323
github.com/macaron-contrib/binding = commit:0e23661e7d
github.com/macaron-contrib/cache = commit:0bb9e6c9ef
github.com/macaron-contrib/captcha = commit:3567dc48b8
github.com/macaron-contrib/csrf = commit:422b79675c
github.com/macaron-contrib/i18n = commit:184bb832f2
github.com/macaron-contrib/oauth2 = commit:8f394c3629
github.com/macaron-contrib/session = commit:f00d48fd4f
github.com/macaron-contrib/toolbox = commit:57127bcc89
github.com/mattn/go-sqlite3 = commit:a80c27ba33
github.com/nfnt/resize = commit:581d15cb53

View File

@@ -2,9 +2,7 @@ targets:
ubuntu-14.04:
ubuntu-12.04:
debian-7:
build_dependencies:
- mercurial
- bzr
centos-6:
dependencies:
- git
before:

40
LICENSE
View File

@@ -1,27 +1,19 @@
Copyright (c) 2014
All rights reserved.
Copyright (c) 2014 All Gogs Contributors
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -5,7 +5,7 @@ Gogs(Go Git Service) is a painless self-hosted Git Service written in Go.
![Demo](https://gowalker.org/public/gogs_demo.gif)
##### Current version: 0.5.5 Beta
##### Current version: 0.5.8 Beta
### NOTICES
@@ -26,25 +26,29 @@ The goal of this project is to make the easiest, fastest and most painless way t
- See [Trello Board](https://trello.com/b/uxAoeLUl/gogs-go-git-service) to follow the develop team.
- Try it before anything? Do it [online](https://try.gogs.io/Unknown/gogs) or go down to **Installation -> Install from binary** section!
- Having troubles? Get help from [Troubleshooting](http://gogs.io/docs/intro/troubleshooting.md).
- Want to help on localization? Check out [Crowdin](https://crowdin.com/project/gogs)!
## Features
- Activity timeline
- SSH/HTTP(S) protocol support
- SMTP/LDAP/reverse proxy authentication support
- Reverse proxy suburl support
- Register/delete/rename account
- Create/manage/delete organization with team management
- Create/migrate/mirror/delete/watch/rename/transfer public/private repository
- Create/fork/migrate/mirror/delete/watch/rename/transfer public/private repository
- Repository viewer/release/issue tracker
- Repository and Organization level webhooks
- Repository Git hooks
- Add/remove repository collaborators
- Gravatar and cache support
- Mail service(register, issue)
- Administration panel
- Slack webhook integration
- Drone CI integration
- Supports MySQL, PostgreSQL and SQLite3
- Social account login(GitHub, Google, QQ, Weibo)
- Multi-language support(English, Simplified Chinese, Traditional Chinese, Germany, French, Dutch etc.)
- Multi-language support([7 languages](https://crowdin.com/project/gogs))
## System Requirements
@@ -68,13 +72,15 @@ There are 5 ways to install Gogs:
- Router and middleware mechanism of [Macaron](https://github.com/Unknwon/macaron).
- Mail Service, modules design is inspired by [WeTalk](https://github.com/beego/wetalk).
- System Monitor Status is inspired by [GoBlog](https://github.com/fuxiaohei/goblog).
- Usage and modification from [beego](http://beego.me) modules.
- Thanks [lavachen](http://www.lavachen.cn/) and [Rocker](http://weibo.com/rocker1989) for designing Logo.
- Thanks [gobuild.io](http://gobuild.io) for providing binary compile and download service.
- Thanks [Crowdin](https://crowdin.com/project/gogs) for providing open source translation plan.
## Contributors
The [core team](http://gogs.io/team) of this project. See [contributors page](https://github.com/gogits/gogs/graphs/contributors) for full list of contributors.
- The [core team](http://gogs.io/team) of this project.
- See [contributors page](https://github.com/gogits/gogs/graphs/contributors) for full list of contributors.
- See [TRANSLATORS](conf/locale/TRANSLATORS) for full list of translators.
## License

View File

@@ -5,7 +5,7 @@ Gogs(Go Git Service) 是一个基于 Go 语言的自助 Git 服务。
![Demo](https://gowalker.org/public/gogs_demo.gif)
##### 当前版本0.5.5 Beta
##### 当前版本0.5.8 Beta
## 开发目的
@@ -17,25 +17,29 @@ Gogs 的目标是打造一个最简单、最快速和最轻松的方式搭建自
- 您可以到 [Trello Board](https://trello.com/b/uxAoeLUl/gogs-go-git-service) 跟随开发团队的脚步。
- 想要先睹为快?通过 [在线体验](https://try.gogs.io/Unknown/gogs) 或查看 **安装部署 -> 二进制安装** 小节。
- 使用过程中遇到问题?尝试从 [故障排查](http://gogs.io/docs/intro/troubleshooting.md) 页面获取帮助。
- 希望帮助多国语言界面的翻译吗?请立即访问 [Crowdin](https://crowdin.com/project/gogs)
## 功能特性
- 活动时间线
- 支持 SSH/HTTP(S) 协议
- 支持 SMTP/LDAP/反向代理 用户认证
- 注册/删除/重命名 用户
- 创建/管理/删除 组织以及团队管理功能
- 创建/迁移/镜像/删除/关注/重命名/转移 公开/私有 仓库
- 仓库 浏览/发布/工单管理
- 仓库和组织级别 Web 钩子
- 添加/删除 仓库协作者
- Gravatar 以及缓存支持
- 邮件服务注册、Issue
- 支持反向代理子路径
- 支持 注册/删除/重命名 用户
- 支持 创建/管理/删除 组织以及团队管理功能
- 支持 创建/派生/迁移/镜像/删除/关注/重命名/转移 公开/私有 仓库
- 支持仓库 浏览/发布/工单管理
- 支持仓库和组织级别 Web 钩子
- 支持仓库 Git 钩子
- 支持 添加/删除 仓库协作者
- 支持 Gravatar 以及本地缓存
- 支持邮件服务注册、Issue
- 管理员面板
- Slack Web 钩子集成
- Drone CI 持续部署集成
- 支持 MySQL、PostgreSQL 以及 SQLite3 数据库
- 社交帐号登录GitHub、Google、QQ、微博
- 多语言支持(英文、简体中文、繁体中文、德语、法语、荷兰语等等
- 多语言支持([7 种语言]([more](https://crowdin.com/project/gogs))
## 系统要求
@@ -56,16 +60,18 @@ Gogs 的目标是打造一个最简单、最快速和最轻松的方式搭建自
## 特别鸣谢
- [Macaron](https://github.com/Unknwon/macaron) 的路由与中间件机制。
- [beego](http://beego.me) 模块的使用与修改。
- 基于 [Macaron](https://github.com/Unknwon/macaron) 的路由与中间件机制。
- 基于 [WeTalk](https://github.com/beego/wetalk) 修改的邮件服务和模块设计。
- 基于 [GoBlog](https://github.com/fuxiaohei/goblog) 修改的系统监视状态。
- 感谢 [gobuild.io](http://gobuild.io) 提供二进制编译与下载服务。
- 感谢 [lavachen](http://www.lavachen.cn/) 和 [Rocker](http://weibo.com/rocker1989) 设计的 Logo。
- 感谢 [Crowdin](https://crowdin.com/project/gogs) 提供免费的开源项目本地化支持。
## 贡献成员
本项目的 [开发团队](http://gogs.io/team)。您可以通过查看 [贡献者页面](https://github.com/gogits/gogs/graphs/contributors) 获取完整的贡献者列表。
- 本项目的 [开发团队](http://gogs.io/team)。
- 您可以通过查看 [贡献者页面](https://github.com/gogits/gogs/graphs/contributors) 获取完整的贡献者列表。
- 您可以通过查看 [TRANSLATORS](conf/locale/TRANSLATORS) 文件获取完整的翻译人员列表。
## 授权许可

View File

@@ -8,6 +8,7 @@ package cmd
import (
"fmt"
"os"
"time"
"github.com/codegangsta/cli"
@@ -31,4 +32,5 @@ Outputs to 'cert.pem' and 'key.pem' and will overwrite existing files.`,
func runCert(ctx *cli.Context) {
fmt.Println("Command cert not available, please use build tags 'cert' to rebuild.")
os.Exit(1)
}

View File

@@ -58,8 +58,9 @@ func runDump(ctx *cli.Context) {
workDir, _ := setting.WorkDir()
z.AddFile("gogs-repo.zip", path.Join(workDir, "gogs-repo.zip"))
z.AddFile("gogs-db.sql", path.Join(workDir, "gogs-db.sql"))
z.AddFile("custom/conf/app.ini", path.Join(workDir, "custom/conf/app.ini"))
z.AddDir("custom", path.Join(workDir, "custom"))
z.AddDir("log", path.Join(workDir, "log"))
// FIXME: SSH key file.
if err = z.Close(); err != nil {
os.Remove(fileName)
log.Fatalf("Fail to save %s: %v", fileName, err)

View File

@@ -14,6 +14,7 @@ import (
"runtime"
"strings"
"github.com/Unknwon/com"
"github.com/codegangsta/cli"
"github.com/gogits/gogs/models"
@@ -164,10 +165,12 @@ func runFixLocation(ctx *cli.Context) {
// Fix in authorized_keys file.
sshPath := path.Join(models.SshPath, "authorized_keys")
fmt.Printf("Fixing pathes in file: %s\n", sshPath)
if err := rewriteAuthorizedKeys(sshPath, oldPath, execPath); err != nil {
fmt.Println(err)
os.Exit(1)
if com.IsFile(sshPath) {
fmt.Printf("Fixing pathes in file: %s\n", sshPath)
if err := rewriteAuthorizedKeys(sshPath, oldPath, execPath); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
// Fix position in gogs-repositories.

View File

@@ -96,7 +96,7 @@ func runServ(k *cli.Context) {
println("Gogs: you are not the owner of SSH key")
log.GitLogger.Fatal(2, "Invalid owner of SSH key: %d", keyId)
}
println("Gogs: internal error:", err)
println("Gogs: internal error:", err.Error())
log.GitLogger.Fatal(2, "Fail to get user by key ID(%d): %v", keyId, err)
}
@@ -125,7 +125,7 @@ func runServ(k *cli.Context) {
println("Gogs: given repository owner are not registered")
log.GitLogger.Fatal(2, "Unregistered owner: %s", repoUserName)
}
println("Gogs: internal error:", err)
println("Gogs: internal error:", err.Error())
log.GitLogger.Fatal(2, "Fail to get repository owner(%s): %v", repoUserName, err)
}
@@ -134,7 +134,7 @@ func runServ(k *cli.Context) {
case isWrite:
has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.WRITABLE)
if err != nil {
println("Gogs: internal error:", err)
println("Gogs: internal error:", err.Error())
log.GitLogger.Fatal(2, "Fail to check write access:", err)
} else if !has {
println("You have no right to write this repository")
@@ -147,7 +147,7 @@ func runServ(k *cli.Context) {
println("Gogs: given repository does not exist")
log.GitLogger.Fatal(2, "Repository does not exist: %s/%s", repoUser.Name, repoName)
}
println("Gogs: internal error:", err)
println("Gogs: internal error:", err.Error())
log.GitLogger.Fatal(2, "Fail to get repository: %v", err)
}
@@ -157,14 +157,14 @@ func runServ(k *cli.Context) {
has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.READABLE)
if err != nil {
println("Gogs: internal error:", err)
println("Gogs: internal error:", err.Error())
log.GitLogger.Fatal(2, "Fail to check read access:", err)
} else if !has {
println("You have no right to access this repository")
log.GitLogger.Fatal(2, "User %s has no right to read repository %s", user.Name, repoPath)
}
default:
println("Unknown command")
println("Unknown command: " + cmd)
return
}

View File

@@ -5,23 +5,29 @@
package cmd
import (
"crypto/tls"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"net/http/fcgi"
"os"
"path"
"strings"
"github.com/Unknwon/macaron"
"github.com/codegangsta/cli"
"github.com/macaron-contrib/binding"
"github.com/macaron-contrib/cache"
"github.com/macaron-contrib/captcha"
"github.com/macaron-contrib/csrf"
"github.com/macaron-contrib/i18n"
"github.com/macaron-contrib/oauth2"
"github.com/macaron-contrib/session"
"github.com/macaron-contrib/toolbox"
api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/auth/apiv1"
@@ -30,7 +36,6 @@ import (
"github.com/gogits/gogs/modules/git"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/middleware"
"github.com/gogits/gogs/modules/middleware/binding"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/routers"
"github.com/gogits/gogs/routers/admin"
@@ -63,7 +68,7 @@ func checkVersion() {
// Check dependency version.
macaronVer := git.MustParseVersion(strings.Join(strings.Split(macaron.Version(), ".")[:3], "."))
if macaronVer.LessThan(git.MustParseVersion("0.2.0")) {
if macaronVer.LessThan(git.MustParseVersion("0.4.7")) {
log.Fatal(4, "Package macaron version is too old, did you forget to update?(github.com/Unknwon/macaron)")
}
i18nVer := git.MustParseVersion(i18n.Version())
@@ -71,7 +76,7 @@ func checkVersion() {
log.Fatal(4, "Package i18n version is too old, did you forget to update?(github.com/macaron-contrib/i18n)")
}
sessionVer := git.MustParseVersion(session.Version())
if sessionVer.LessThan(git.MustParseVersion("0.0.1")) {
if sessionVer.LessThan(git.MustParseVersion("0.0.5")) {
log.Fatal(4, "Package session version is too old, did you forget to update?(github.com/macaron-contrib/session)")
}
}
@@ -81,15 +86,25 @@ func newMacaron() *macaron.Macaron {
m := macaron.New()
m.Use(macaron.Logger())
m.Use(macaron.Recovery())
if setting.EnableGzip {
m.Use(macaron.Gziper())
}
if setting.Protocol == setting.FCGI {
m.SetURLPrefix(setting.AppSubUrl)
}
m.Use(macaron.Static(
path.Join(setting.StaticRootPath, "public"),
macaron.StaticOptions{
SkipLogging: !setting.DisableRouterLog,
},
))
// if setting.EnableGzip {
// m.Use(macaron.Gzip())
// }
m.Use(macaron.Static(
setting.AvatarUploadPath,
macaron.StaticOptions{
Prefix: "avatars",
SkipLogging: !setting.DisableRouterLog,
},
))
m.Use(macaron.Renderer(macaron.RenderOptions{
Directory: path.Join(setting.StaticRootPath, "templates"),
Funcs: []template.FuncMap{base.TemplateFuncs},
@@ -129,6 +144,13 @@ func newMacaron() *macaron.Macaron {
},
},
}))
// OAuth 2.
if setting.OauthService != nil {
for _, info := range setting.OauthService.OauthInfos {
m.Use(oauth2.NewOAuth2Provider(info.Options, info.AuthUrl, info.TokenUrl))
}
}
m.Use(middleware.Contexter())
return m
}
@@ -144,74 +166,92 @@ func runWeb(*cli.Context) {
ignSignInAndCsrf := middleware.Toggle(&middleware.ToggleOptions{DisableCsrf: true})
reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true})
bind := binding.Bind
bindIgnErr := binding.BindIgnErr
// Routers.
m.Get("/", ignSignIn, routers.Home)
m.Get("/explore", ignSignIn, routers.Explore)
// FIXME: when i'm binding form here???
m.Get("/install", bindIgnErr(auth.InstallForm{}), routers.Install)
m.Post("/install", bindIgnErr(auth.InstallForm{}), routers.InstallPost)
m.Group("", func(r *macaron.Router) {
r.Get("/pulls", user.Pulls)
r.Get("/issues", user.Issues)
m.Group("", func() {
m.Get("/pulls", user.Pulls)
m.Get("/issues", user.Issues)
}, reqSignIn)
// API routers.
m.Group("/api", func(_ *macaron.Router) {
m.Group("/v1", func(r *macaron.Router) {
// API.
// FIXME: custom form error response.
m.Group("/api", func() {
m.Group("/v1", func() {
// Miscellaneous.
r.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown)
r.Post("/markdown/raw", v1.MarkdownRaw)
m.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown)
m.Post("/markdown/raw", v1.MarkdownRaw)
// Users.
m.Group("/users", func(r *macaron.Router) {
r.Get("/search", v1.SearchUsers)
m.Group("/users", func() {
m.Get("/search", v1.SearchUsers)
m.Group("/:username", func() {
m.Get("", v1.GetUserInfo)
m.Group("/tokens", func() {
m.Combo("").Get(v1.ListAccessTokens).Post(bind(v1.CreateAccessTokenForm{}), v1.CreateAccessToken)
}, middleware.ApiReqBasicAuth())
})
})
// Repositories.
m.Group("/repos", func(r *macaron.Router) {
r.Get("/search", v1.SearchRepos)
r.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), v1.Migrate)
m.Combo("/user/repos", middleware.ApiReqToken()).Get(v1.ListMyRepos).Post(bind(api.CreateRepoOption{}), v1.CreateRepo)
m.Post("/org/:org/repos", middleware.ApiReqToken(), bind(api.CreateRepoOption{}), v1.CreateOrgRepo)
m.Group("/repos", func() {
m.Get("/search", v1.SearchRepos)
m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), v1.MigrateRepo)
m.Group("/:username/:reponame", func() {
m.Combo("/hooks").Get(v1.ListRepoHooks).Post(bind(api.CreateHookOption{}), v1.CreateRepoHook)
m.Patch("/hooks/:id:int", bind(api.EditHookOption{}), v1.EditRepoHook)
m.Get("/raw/*", middleware.RepoRef(), v1.GetRepoRawFile)
}, middleware.ApiRepoAssignment(), middleware.ApiReqToken())
})
r.Any("/*", func(ctx *middleware.Context) {
ctx.JSON(404, &base.ApiJsonErr{"Not Found", v1.DOC_URL})
m.Any("/*", func(ctx *middleware.Context) {
ctx.JSON(404, &base.ApiJsonErr{"Not Found", base.DOC_URL})
})
})
})
// User routers.
m.Group("/user", func(r *macaron.Router) {
r.Get("/login", user.SignIn)
r.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
r.Get("/login/:name", user.SocialSignIn)
r.Get("/sign_up", user.SignUp)
r.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
r.Get("/reset_password", user.ResetPasswd)
r.Post("/reset_password", user.ResetPasswdPost)
// User.
m.Group("/user", func() {
m.Get("/login", user.SignIn)
m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
m.Get("/info/:name", user.SocialSignIn)
m.Get("/sign_up", user.SignUp)
m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
m.Get("/reset_password", user.ResetPasswd)
m.Post("/reset_password", user.ResetPasswdPost)
}, reqSignOut)
m.Group("/user/settings", func(r *macaron.Router) {
r.Get("", user.Settings)
r.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
r.Get("/password", user.SettingsPassword)
r.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
r.Get("/ssh", user.SettingsSSHKeys)
r.Post("/ssh", bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
r.Get("/social", user.SettingsSocial)
r.Route("/delete", "GET,POST", user.SettingsDelete)
m.Group("/user/settings", func() {
m.Get("", user.Settings)
m.Post("", bindIgnErr(auth.UpdateProfileForm{}), user.SettingsPost)
m.Post("/avatar", binding.MultipartForm(auth.UploadAvatarForm{}), user.SettingsAvatar)
m.Get("/password", user.SettingsPassword)
m.Post("/password", bindIgnErr(auth.ChangePasswordForm{}), user.SettingsPasswordPost)
m.Get("/ssh", user.SettingsSSHKeys)
m.Post("/ssh", bindIgnErr(auth.AddSSHKeyForm{}), user.SettingsSSHKeysPost)
m.Get("/social", user.SettingsSocial)
m.Combo("/applications").Get(user.SettingsApplications).Post(bindIgnErr(auth.NewAccessTokenForm{}), user.SettingsApplicationsPost)
m.Route("/delete", "GET,POST", user.SettingsDelete)
}, reqSignIn)
m.Group("/user", func(r *macaron.Router) {
m.Group("/user", func() {
// r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
r.Any("/activate", user.Activate)
r.Get("/email2user", user.Email2User)
r.Get("/forget_password", user.ForgotPasswd)
r.Post("/forget_password", user.ForgotPasswdPost)
r.Get("/logout", user.SignOut)
m.Any("/activate", user.Activate)
m.Get("/email2user", user.Email2User)
m.Get("/forget_password", user.ForgotPasswd)
m.Post("/forget_password", user.ForgotPasswdPost)
m.Get("/logout", user.SignOut)
})
// FIXME: Legacy
m.Get("/user/:username", ignSignIn, user.Profile)
// Gravatar service.
avt := avatar.CacheServer("public/img/avatar/", "public/img/avatar_default.jpg")
os.MkdirAll("public/img/avatar/", os.ModePerm)
@@ -219,40 +259,40 @@ func runWeb(*cli.Context) {
adminReq := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true, AdminRequire: true})
m.Group("/admin", func(r *macaron.Router) {
m.Group("/admin", func() {
m.Get("", adminReq, admin.Dashboard)
r.Get("/config", admin.Config)
r.Get("/monitor", admin.Monitor)
m.Get("/config", admin.Config)
m.Get("/monitor", admin.Monitor)
m.Group("/users", func(r *macaron.Router) {
r.Get("", admin.Users)
r.Get("/new", admin.NewUser)
r.Post("/new", bindIgnErr(auth.RegisterForm{}), admin.NewUserPost)
r.Get("/:userid", admin.EditUser)
r.Post("/:userid", bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
r.Post("/:userid/delete", admin.DeleteUser)
m.Group("/users", func() {
m.Get("", admin.Users)
m.Get("/new", admin.NewUser)
m.Post("/new", bindIgnErr(auth.RegisterForm{}), admin.NewUserPost)
m.Get("/:userid", admin.EditUser)
m.Post("/:userid", bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
m.Post("/:userid/delete", admin.DeleteUser)
})
m.Group("/orgs", func(r *macaron.Router) {
r.Get("", admin.Organizations)
m.Group("/orgs", func() {
m.Get("", admin.Organizations)
})
m.Group("/repos", func(r *macaron.Router) {
r.Get("", admin.Repositories)
m.Group("/repos", func() {
m.Get("", admin.Repositories)
})
m.Group("/auths", func(r *macaron.Router) {
r.Get("", admin.Authentications)
r.Get("/new", admin.NewAuthSource)
r.Post("/new", bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
r.Get("/:authid", admin.EditAuthSource)
r.Post("/:authid", bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
r.Post("/:authid/delete", admin.DeleteAuthSource)
m.Group("/auths", func() {
m.Get("", admin.Authentications)
m.Get("/new", admin.NewAuthSource)
m.Post("/new", bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
m.Get("/:authid", admin.EditAuthSource)
m.Post("/:authid", bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
m.Post("/:authid/delete", admin.DeleteAuthSource)
})
m.Group("/notices", func(r *macaron.Router) {
r.Get("", admin.Notices)
r.Get("/:id:int/delete", admin.DeleteNotice)
m.Group("/notices", func() {
m.Get("", admin.Notices)
m.Get("/:id:int/delete", admin.DeleteNotice)
})
}, adminReq)
@@ -264,136 +304,138 @@ func runWeb(*cli.Context) {
reqTrueOwner := middleware.RequireTrueOwner()
// Organization routers.
m.Group("/org", func(r *macaron.Router) {
r.Get("/create", org.Create)
r.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
// Organization.
m.Group("/org", func() {
m.Get("/create", org.Create)
m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
m.Group("/:org", func(r *macaron.Router) {
r.Get("/dashboard", user.Dashboard)
r.Get("/members", org.Members)
r.Get("/members/action/:action", org.MembersAction)
m.Group("/:org", func() {
m.Get("/dashboard", user.Dashboard)
m.Get("/members", org.Members)
m.Get("/members/action/:action", org.MembersAction)
r.Get("/teams", org.Teams)
r.Get("/teams/:team", org.TeamMembers)
r.Get("/teams/:team/repositories", org.TeamRepositories)
r.Get("/teams/:team/action/:action", org.TeamsAction)
r.Get("/teams/:team/action/repo/:action", org.TeamsRepoAction)
m.Get("/teams", org.Teams)
m.Get("/teams/:team", org.TeamMembers)
m.Get("/teams/:team/repositories", org.TeamRepositories)
m.Get("/teams/:team/action/:action", org.TeamsAction)
m.Get("/teams/:team/action/repo/:action", org.TeamsRepoAction)
}, middleware.OrgAssignment(true, true))
m.Group("/:org", func(r *macaron.Router) {
r.Get("/teams/new", org.NewTeam)
r.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
r.Get("/teams/:team/edit", org.EditTeam)
r.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
r.Post("/teams/:team/delete", org.DeleteTeam)
m.Group("/:org", func() {
m.Get("/teams/new", org.NewTeam)
m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
m.Get("/teams/:team/edit", org.EditTeam)
m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
m.Post("/teams/:team/delete", org.DeleteTeam)
m.Group("/settings", func(r *macaron.Router) {
r.Get("", org.Settings)
r.Post("", bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
r.Get("/hooks", org.SettingsHooks)
r.Get("/hooks/new", repo.WebHooksNew)
r.Post("/hooks/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
r.Post("/hooks/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
r.Get("/hooks/:id", repo.WebHooksEdit)
r.Post("/hooks/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
r.Post("/hooks/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
r.Route("/delete", "GET,POST", org.SettingsDelete)
m.Group("/settings", func() {
m.Get("", org.Settings)
m.Post("", bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
m.Get("/hooks", org.SettingsHooks)
m.Get("/hooks/new", repo.WebHooksNew)
m.Post("/hooks/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
m.Post("/hooks/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
m.Get("/hooks/:id", repo.WebHooksEdit)
m.Post("/hooks/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
m.Post("/hooks/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
m.Route("/delete", "GET,POST", org.SettingsDelete)
})
r.Route("/invitations/new", "GET,POST", org.Invitation)
m.Route("/invitations/new", "GET,POST", org.Invitation)
}, middleware.OrgAssignment(true, true, true))
}, reqSignIn)
m.Group("/org", func(r *macaron.Router) {
r.Get("/:org", org.Home)
m.Group("/org", func() {
m.Get("/:org", org.Home)
}, middleware.OrgAssignment(true))
// Repository routers.
m.Group("/repo", func(r *macaron.Router) {
r.Get("/create", repo.Create)
r.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
r.Get("/migrate", repo.Migrate)
r.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
// Repository.
m.Group("/repo", func() {
m.Get("/create", repo.Create)
m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
m.Get("/migrate", repo.Migrate)
m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
m.Get("/fork", repo.Fork)
m.Post("/fork", bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
}, reqSignIn)
m.Group("/:username/:reponame", func(r *macaron.Router) {
r.Get("/settings", repo.Settings)
r.Post("/settings", bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
m.Group("/settings", func(r *macaron.Router) {
r.Route("/collaboration", "GET,POST", repo.SettingsCollaboration)
r.Get("/hooks", repo.Webhooks)
r.Get("/hooks/new", repo.WebHooksNew)
r.Post("/hooks/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
r.Post("/hooks/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
r.Get("/hooks/:id", repo.WebHooksEdit)
r.Post("/hooks/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
r.Post("/hooks/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
m.Group("/:username/:reponame", func() {
m.Get("/settings", repo.Settings)
m.Post("/settings", bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
m.Group("/settings", func() {
m.Route("/collaboration", "GET,POST", repo.SettingsCollaboration)
m.Get("/hooks", repo.Webhooks)
m.Get("/hooks/new", repo.WebHooksNew)
m.Post("/hooks/gogs/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
m.Post("/hooks/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
m.Get("/hooks/:id", repo.WebHooksEdit)
m.Post("/hooks/gogs/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
m.Post("/hooks/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
m.Group("/hooks/git", func(r *macaron.Router) {
r.Get("", repo.GitHooks)
r.Get("/:name", repo.GitHooksEdit)
r.Post("/:name", repo.GitHooksEditPost)
m.Group("/hooks/git", func() {
m.Get("", repo.GitHooks)
m.Get("/:name", repo.GitHooksEdit)
m.Post("/:name", repo.GitHooksEditPost)
}, middleware.GitHookService())
})
}, reqSignIn, middleware.RepoAssignment(true), reqTrueOwner)
m.Group("/:username/:reponame", func(r *macaron.Router) {
r.Get("/action/:action", repo.Action)
m.Group("/:username/:reponame", func() {
m.Get("/action/:action", repo.Action)
m.Group("/issues", func(r *macaron.Router) {
r.Get("/new", repo.CreateIssue)
r.Post("/new", bindIgnErr(auth.CreateIssueForm{}), repo.CreateIssuePost)
r.Post("/:index", bindIgnErr(auth.CreateIssueForm{}), repo.UpdateIssue)
r.Post("/:index/label", repo.UpdateIssueLabel)
r.Post("/:index/milestone", repo.UpdateIssueMilestone)
r.Post("/:index/assignee", repo.UpdateAssignee)
r.Get("/:index/attachment/:id", repo.IssueGetAttachment)
r.Post("/labels/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
r.Post("/labels/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
r.Post("/labels/delete", repo.DeleteLabel)
r.Get("/milestones", repo.Milestones)
r.Get("/milestones/new", repo.NewMilestone)
r.Post("/milestones/new", bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
r.Get("/milestones/:index/edit", repo.UpdateMilestone)
r.Post("/milestones/:index/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.UpdateMilestonePost)
r.Get("/milestones/:index/:action", repo.UpdateMilestone)
m.Group("/issues", func() {
m.Get("/new", repo.CreateIssue)
m.Post("/new", bindIgnErr(auth.CreateIssueForm{}), repo.CreateIssuePost)
m.Post("/:index", bindIgnErr(auth.CreateIssueForm{}), repo.UpdateIssue)
m.Post("/:index/label", repo.UpdateIssueLabel)
m.Post("/:index/milestone", repo.UpdateIssueMilestone)
m.Post("/:index/assignee", repo.UpdateAssignee)
m.Get("/:index/attachment/:id", repo.IssueGetAttachment)
m.Post("/labels/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
m.Post("/labels/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
m.Post("/labels/delete", repo.DeleteLabel)
m.Get("/milestones/new", repo.NewMilestone)
m.Post("/milestones/new", bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
m.Get("/milestones/:index/edit", repo.UpdateMilestone)
m.Post("/milestones/:index/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.UpdateMilestonePost)
m.Get("/milestones/:index/:action", repo.UpdateMilestone)
})
r.Post("/comment/:action", repo.Comment)
r.Get("/releases/new", repo.NewRelease)
r.Get("/releases/edit/:tagname", repo.EditRelease)
m.Post("/comment/:action", repo.Comment)
m.Group("/releases", func() {
m.Get("/new", repo.NewRelease)
m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
m.Get("/edit/:tagname", repo.EditRelease)
m.Post("/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
}, middleware.RepoRef())
}, reqSignIn, middleware.RepoAssignment(true))
m.Group("/:username/:reponame", func(r *macaron.Router) {
r.Post("/releases/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
r.Post("/releases/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
}, reqSignIn, middleware.RepoAssignment(true, true))
m.Group("/:username/:reponame", func() {
m.Get("/releases", middleware.RepoRef(), repo.Releases)
m.Get("/issues", repo.Issues)
m.Get("/issues/:index", repo.ViewIssue)
m.Get("/issues/milestones", repo.Milestones)
m.Get("/pulls", repo.Pulls)
m.Get("/branches", repo.Branches)
m.Get("/archive/*", repo.Download)
m.Get("/issues2/", repo.Issues2)
m.Get("/pulls2/", repo.PullRequest2)
m.Get("/labels2/", repo.Labels2)
m.Get("/milestone2/", repo.Milestones2)
m.Group("/:username/:reponame", func(r *macaron.Router) {
r.Get("/issues", repo.Issues)
r.Get("/issues/:index", repo.ViewIssue)
r.Get("/pulls", repo.Pulls)
r.Get("/branches", repo.Branches)
r.Get("/archive/*", repo.Download)
r.Get("/issues2/", repo.Issues2)
m.Group("", func() {
m.Get("/src/*", repo.Home)
m.Get("/raw/*", repo.SingleDownload)
m.Get("/commits/*", repo.RefCommits)
m.Get("/commit/*", repo.Diff)
}, middleware.RepoRef())
m.Get("/compare/:before([a-z0-9]+)...:after([a-z0-9]+)", repo.CompareDiff)
}, ignSignIn, middleware.RepoAssignment(true))
m.Group("/:username/:reponame", func(r *macaron.Router) {
r.Get("/src/:branchname", repo.Home)
r.Get("/src/:branchname/*", repo.Home)
r.Get("/raw/:branchname/*", repo.SingleDownload)
r.Get("/commits/:branchname", repo.Commits)
r.Get("/commits/:branchname/search", repo.SearchCommits)
r.Get("/commits/:branchname/*", repo.FileHistory)
r.Get("/commit/:branchname", repo.Diff)
r.Get("/commit/:branchname/*", repo.Diff)
r.Get("/releases", repo.Releases)
r.Get("/compare/:before([a-z0-9]+)...:after([a-z0-9]+)", repo.CompareDiff)
}, ignSignIn, middleware.RepoAssignment(true, true))
m.Group("/:username", func(r *macaron.Router) {
r.Get("/:reponame", ignSignIn, middleware.RepoAssignment(true, true, true), repo.Home)
r.Any("/:reponame/*", ignSignInAndCsrf, repo.Http)
m.Group("/:username", func() {
m.Get("/:reponame", ignSignIn, middleware.RepoAssignment(true, true), middleware.RepoRef(), repo.Home)
m.Any("/:reponame/*", ignSignInAndCsrf, repo.Http)
})
// robots.txt
@@ -415,7 +457,10 @@ func runWeb(*cli.Context) {
case setting.HTTP:
err = http.ListenAndServe(listenAddr, m)
case setting.HTTPS:
err = http.ListenAndServeTLS(listenAddr, setting.CertFile, setting.KeyFile, m)
server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS10}, Handler: m}
err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
case setting.FCGI:
err = fcgi.Serve(nil, m)
default:
log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
}

View File

@@ -22,13 +22,20 @@ DISABLE_ROUTER_LOG = false
; Generate steps:
; $ cd path/to/gogs/custom/https
; $ ./gogs cert -ca=true -duration=8760h0m0s -host=myhost.example.com
;
; Or from a .pfx file exported from the Windows certificate store (do
; not forget to export the private key):
; $ openssl pkcs12 -in cert.pfx -out cert.pem -nokeys
; $ openssl pkcs12 -in cert.pfx -out key.pem -nocerts -nodes
CERT_FILE = custom/https/cert.pem
KEY_FILE = custom/https/key.pem
; Upper level of template and static file path
; default is the path where Gogs is executed
STATIC_ROOT_PATH =
; Application level GZIP support
#ENABLE_GZIP = false
ENABLE_GZIP = false
; Landing page for non-logged users, can be "home" or "explore"
LANDING_PAGE = home
[database]
; Either "mysql", "postgres" or "sqlite3", it's your choice
@@ -70,8 +77,7 @@ ENABLE_CACHE_AVATAR = false
ENABLE_NOTIFY_MAIL = false
; More detail: https://github.com/gogits/gogs/issues/165
ENABLE_REVERSE_PROXY_AUTHENTICATION = false
; Repository Git hooks
ENABLE_GIT_HOOKS = false
ENABLE_REVERSE_PROXY_AUTO_REGISTERATION = false
[webhook]
; Cron task interval in minutes
@@ -120,13 +126,10 @@ TOKEN_URL = https://accounts.google.com/o/oauth2/token
ENABLED = false
CLIENT_ID =
CLIENT_SECRET =
SCOPES = all
SCOPES = get_user_info
; QQ 互联
; AUTH_URL = https://graph.qq.com/oauth2.0/authorize
; TOKEN_URL = https://graph.qq.com/oauth2.0/token
; Tencent weibo
AUTH_URL = https://open.t.qq.com/cgi-bin/oauth2/authorize
TOKEN_URL = https://open.t.qq.com/cgi-bin/oauth2/access_token
AUTH_URL = https://graph.qq.com/oauth2.0/authorize
TOKEN_URL = https://graph.qq.com/oauth2.0/token
[oauth.weibo]
ENABLED = false
@@ -165,14 +168,13 @@ ENABLE_SET_COOKIE = true
GC_INTERVAL_TIME = 86400
; Session life time, default is 86400
SESSION_LIFE_TIME = 86400
; session id hash func, Either "sha1", "sha256" or "md5" default is sha1
SESSION_ID_HASHFUNC = sha1
; Session hash key, default is use random string
SESSION_ID_HASHKEY =
[picture]
; The place to picture data, either "server" or "qiniu", default is "server"
SERVICE = server
AVATAR_UPLOAD_PATH = data/avatars
; Chinese users can choose "duoshuo"
GRAVATAR_SOURCE = gravatar
DISABLE_GRAVATAR = false
[attachment]
@@ -256,7 +258,13 @@ CONN =
[git]
MAX_GITDIFF_LINES = 10000
; Arguments for command 'git fsck', e.g.: "--unreachable --tags"
; see more on http://git-scm.com/docs/git-fsck/1.7.5
FSCK_ARGS =
; Arguments for command 'git gc', e.g.: "--aggressive --auto"
; see more on http://git-scm.com/docs/git-gc/1.7.5
GC_ARGS =
[i18n]
LANGS = en-US,zh-CN,zh-HK,de-DE,fr-CA,nl-NL
NAMES = English,简体中文,繁體中文,Deutsch,Français,Nederlands
LANGS = en-US,zh-CN,zh-HK,de-DE,fr-CA,nl-NL,lv-LV
NAMES = English,简体中文,繁體中文,Deutsch,Français,Nederlands,Latviešu

6
conf/locale/TRANSLATORS Normal file
View File

@@ -0,0 +1,6 @@
# This file lists all PUBLIC individuals having contributed content to the translation.
# Order of name is meaningless.
Thomas Fanninger <gogs.thomas@fanninger.at>
Łukasz Jan Niemier <lukasz@niemier.pl>
Lafriks <lafriks@gmail.com>

1296
conf/locale/locale_de-DE.ini Normal file → Executable file

File diff suppressed because it is too large Load Diff

View File

@@ -26,6 +26,7 @@ organization = Organization
mirror = Mirror
new_repo = New Repository
new_migrate = New Migration
new_fork = New Fork Repository
new_org = New Organization
manage_org = Manage Organizations
admin_panel = Admin Panel
@@ -41,7 +42,7 @@ cancel = Cancel
[install]
install = Installation
title = Install Steps For First-time Run
requite_db_desc = Gogs requires MySQL, PostgreSQL or SQLite3, but SQLite3 is usually available in the official binary version.
requite_db_desc = Gogs requires MySQL, PostgreSQL or SQLite3.
db_type = Database Type
host = Host
user = User
@@ -74,7 +75,7 @@ confirm_password = Confirm Password
admin_email = E-mail
install_gogs = Install Gogs
test_git_failed = Fail to test 'git' command: %v
sqlite3_not_available = Your release version does not support SQLite3, please download the official binary version from http://gogs.io/docs/installation/install_from_binary.html, NOT the gobuild version.
sqlite3_not_available = Your release version does not support SQLite3, please download the official binary version from %s, NOT the gobuild version.
invalid_db_setting = Database setting is not correct: %v
invalid_repo_path = Repository root path is invalid: %v
run_user_not_match = Run user isn't the current user: %s -> %s
@@ -159,15 +160,20 @@ user_not_exist = Given user does not exist.
last_org_owner = The user to remove is the last member in owner team. There must be another owner.
invalid_ssh_key = Sorry, we're not able to verify your SSH key: %s
unable_verify_ssh_key = Gogs cannot verify your SSH key, but we assume that is valid, please make sure yourself.
auth_failed = Authentication failed: %v
still_own_repo = Your account still have ownership of repository, you have to delete or transfer them first.
still_has_org = Your account still have membership of organization, you have to left or delete them first.
org_still_own_repo = This organization still have ownership of repository, you have to delete or transfer them first.
still_own_user = This authentication still has used by some users, you should move them and then delete again.
target_branch_not_exist = Target branch does not exist
[user]
change_avatar = Change your avatar at gravatar.com
change_custom_avatar = Change your avatar in settings
join_on = Joined on
repositories = Repositories
activity = Public Activity
@@ -180,6 +186,7 @@ profile = Profile
password = Password
ssh_keys = SSH Keys
social = Social Accounts
applications = Applications
orgs = Organizations
delete = Delete Account
uid = Uid
@@ -190,12 +197,20 @@ full_name = Full Name
website = Website
location = Location
update_profile = Update Profile
update_profile_success = Your profile has been successfully updated.
update_profile_success = Your profile has been updated successfully.
change_username = Username Changed
change_username_desc = Username has been changed, do you want to continue? This will affect all links relate to your account.
continue = Continue
cancel = Cancel
enable_custom_avatar = Enable Custom Avatar
enable_custom_avatar_helper = Enable this to disable fetch from Gravatar
choose_new_avatar = Choose new avatar
update_avatar = Update Avatar Setting
uploaded_avatar_not_a_image = Uploaded file is not a image.
no_custom_avatar_available = No custom avatar available, cannot enable it.
update_avatar_success = Your avatar setting has been updated successfully.
change_password = Change Password
old_password = Current Password
new_password = New Password
@@ -205,7 +220,7 @@ change_password_success = Password is changed successfully. You can now sign in
manage_ssh_keys = Manage SSH Keys
add_key = Add Key
ssh_desc = This is a list of SSH keys associated with your account. Remove any keys that you do not recognize.
ssh_helper = <strong>Need help?</strong> Check out our guide to <a href="https://help.github.com/articles/generating-ssh-keys">generating SSH keys</a> or troubleshoot <a href="https://help.github.com/ssh-issues/">common SSH Problems</a>.
ssh_helper = <strong>Need help?</strong> Check out our guide to <a href="%s">generating SSH keys</a> or troubleshoot <a href="%s">common SSH Problems</a>.
add_new_key = Add SSH Key
key_name = Key Name
key_content = Content
@@ -220,6 +235,16 @@ social_desc = This is a list of associated social accounts. Remove any binding t
unbind = Unbind
unbind_success = Social account has been unbound.
manage_access_token = Manage Personal Access Tokens
generate_new_token = Generate New Token
tokens_desc = Tokens you have generated that can be used to access the Gogs API.
new_token_desc = As for now, every token will have full access to your account.
token_name = Token Name
generate_token = Generate Token
generate_token_succees = New access token has been generated successfully! Make sure to copy your new personal access token now. You won't be able to see it again!
delete_token = Delete
delete_token_success = Personal access token has been deleted successfully! Don't forget to update your applications as well.
delete_account = Delete Your Account
delete_prompt = The operation will delete your account permanently, and <strong>CANNOT</strong> be undone!
confirm_delete_account = Confirm Deletion
@@ -232,6 +257,9 @@ repo_name = Repository Name
repo_name_helper = Great repository names are short, memorable and <strong>unique</strong>.
visibility = Visibility
visiblity_helper = This repository is <span class="label label-red label-radius">Private</span>
fork_repo = Fork Repository
fork_from = Fork From
fork_visiblity_helper = Forked repository cannot change its visiblity
repo_desc = Description
repo_lang = Language
repo_lang_helper = Select a .gitignore file
@@ -252,7 +280,7 @@ migrate_repo = Migrate Repository
copy_link = Copy
click_to_copy = Copy to clipboard
copied = Copied OK
clone_helper = Need help cloning? Visit <a target="_blank" href="http://git-scm.com/book/en/Git-Basics-Getting-a-Git-Repository">Help</a>!
clone_helper = Need help cloning? Visit <a target="_blank" href="%s">Help</a>!
unwatch = Unwatch
watch = Watch
unstar = Unstar
@@ -273,6 +301,9 @@ tags = Tags
issues = Issues
commits = Commits
releases = Releases
file_raw = Raw
file_history = History
file_view_raw = View Raw
commits.commits = Commits
commits.search = Search commits
@@ -301,24 +332,24 @@ settings.new_owner_has_same_repo = New owner already has a repository with same
settings.delete = Delete This Repository
settings.delete_desc = Once you delete a repository, there is no going back. Please be certain.
settings.transfer_notices = <p>- You will lose access if new owner is a individual user.</p><p>- You will remain access if new owner is an organization and you're one of the owners.</p>
settings.update_settings_success = Repository options has been successfully updated.
settings.update_settings_success = Repository options has been updated successfully.
settings.transfer_owner = New Owner
settings.make_transfer = Make Transfer
settings.transfer_succeed = Repository ownership has been successfully transferred.
settings.transfer_succeed = Repository ownership has been transferred successfully.
settings.confirm_delete = Confirm Deletion
settings.add_collaborator = Add New Collaborator
settings.add_collaborator_success = New collaborator has been added.
settings.remove_collaborator_success = Collaborator has been removed.
settings.user_is_org_member = User is organization member who cannot be added as a collaborator.
settings.add_webhook = Add Webhook
settings.hooks_desc = Webhooks allow external services to be notified when certain events happen on Gogs. When the specified events happen, we'll send a POST request to each of the URLs you provide. Learn more in our <a target="_blank" href="http://gogs.io/docs/features/webhook.html">Webhooks Guide</a>.
settings.hooks_desc = Webhooks allow external services to be notified when certain events happen on Gogs. When the specified events happen, we'll send a POST request to each of the URLs you provide. Learn more in our <a target="_blank" href="%s">Webhooks Guide</a>.
settings.githooks_desc = Git Hooks are powered by Git itself, you can edit files of supported hooks in the list below to apply custom operations.
settings.githook_edit_desc = If hook is not active, sample content will be presented. Leave content to be blank will disable this hook.
settings.githook_name = Hook Name
settings.githook_content = Hook Content
settings.update_githook = Update Hook
settings.remove_hook_success = Webhook has been removed.
settings.add_webhook_desc = Well send a <code>POST</code> request to the URL below with details of any subscribed events. You can also specify which data format you'd like to receive (JSON, <code>x-www-form-urlencoded</code>, <em>etc</em>). More information can be found in <a target="_blank" href="http://gogs.io/docs/features/webhook.html">Webhooks Guide</a>.
settings.add_webhook_desc = Well send a <code>POST</code> request to the URL below with details of any subscribed events. You can also specify which data format you'd like to receive (JSON, <code>x-www-form-urlencoded</code>, <em>etc</em>). More information can be found in <a target="_blank" href="%s">Webhooks Guide</a>.
settings.payload_url = Payload URL
settings.content_type = Content Type
settings.secret = Secret
@@ -332,11 +363,44 @@ settings.update_hook_success = Webhook has been updated.
settings.delete_webhook = Delete Webhook
settings.recent_deliveries = Recent Deliveries
settings.hook_type = Hook Type
settings.add_slack_hook_desc = Add <a href="http://slack.com">Slack</a> integration to your repository.
settings.add_slack_hook_desc = Add <a href="%s">Slack</a> integration to your repository.
settings.slack_token = Token
settings.slack_domain = Domain
settings.slack_channel = Channel
diff.browse_source = Browse Source
diff.parent = parent
diff.commit = commit
diff.data_not_available = Diff Data Not Available.
diff.show_diff_stats = Show Diff Stats
diff.stats_desc = <strong> %d changed files</strong> with <strong>%d additions</strong> and <strong>%d deletions</strong>
diff.bin = BIN
diff.view_file = View File
release.releases = Releases
release.new_release = New Release
release.draft = Draft
release.prerelease = Pre-Release
release.stable = Stable
release.edit = edit
release.ahead = <strong>%d</strong> commits to %s since this release
release.source_code = Source Code
release.tag_name = Tag name
release.target = Target
release.tag_helper = Choose an existing tag, or create a new tag on publish.
release.release_title = Release title
release.content_with_md = Content with <a href="%s">Markdown</a>
release.write = Write
release.preview = Preview
release.content_placeholder = Write some content
release.loading = Loading...
release.prerelease_desc = This is a pre-release
release.prerelease_helper = Well point out that this release is identified as non-production ready.
release.publish = Publish Release
release.save_draft = Save Draft
release.edit_release = Edit Release
release.tag_name_already_exist = Release with this tag name has already existed.
[org]
org_name_holder = Organization Name
org_name_helper = Great organization names are short and memorable.
@@ -364,7 +428,7 @@ settings.location = Location
settings.update_settings = Update Settings
settings.change_orgname = Organization Name Changed
settings.change_orgname_desc = Organization name has been changed, do you want to continue? This will affect all links relate to this organization.
settings.update_setting_success = Organization setting has been successfully updated.
settings.update_setting_success = Organization setting has been updated successfully.
settings.delete = Delete Organization
settings.delete_account = Delete This Organization
settings.delete_prompt = The operation will delete this organization permanently, and <strong>CANNOT</strong> be undone!
@@ -402,7 +466,7 @@ teams.delete_team = Delete This Team
teams.add_team_member = Add Team Member
teams.delete_team_title = Team Deletion
teams.delete_team_desc = This team is going to be deleted, do you want to continue? Members of this team may lose access to some repositories.
teams.delete_team_success = Given team has been successfully deleted.
teams.delete_team_success = Given team has been deleted successfully.
teams.read_permission_desc = This team grants <strong>Read</strong> access: members can view and clone the team's repositories.
teams.write_permission_desc = This team grants <strong>Write</strong> access: members can read from and push to the team's repositories.
teams.admin_permission_desc = This team grants <strong>Admin</strong> access: members can read from, push to, and add collaborators to the team's repositories.
@@ -431,7 +495,13 @@ dashboard.operation_name = Operation Name
dashboard.operation_switch = Switch
dashboard.operation_run = Run
dashboard.clean_unbind_oauth = Clean unbound OAuthes
dashboard.clean_unbind_oauth_success = All unbind OAuthes have been deleted successfully.
dashboard.delete_inactivate_accounts = Delete all inactive accounts
dashboard.delete_inactivate_accounts_success = All inactivate accounts have been deleted successfully.
dashboard.delete_repo_archives = Delete all repositories archives
dashboard.delete_repo_archives_success = All repositories archives have been deleted successfully.
dashboard.git_gc_repos = Do garbage collection on repositories
dashboard.git_gc_repos_success = All repositories have done garbage collection successfully.
dashboard.server_uptime = Server Uptime
dashboard.current_goroutine = Current Goroutines
dashboard.current_memory_usage = Current Memory Usage
@@ -473,13 +543,15 @@ users.edit = Edit
users.auth_source = Authorization Source
users.local = Local
users.auth_login_name = Authorization Login Name
users.update_profile_success = Account profile has been successfully updated.
users.update_profile_success = Account profile has been updated successfully.
users.edit_account = Edit Account
users.is_activated = This account is activated
users.is_admin = This account has administrator permissions
users.allow_git_hook = This account has permissions to create Git hooks
users.update_profile = Update Account Profile
users.delete_account = Delete This Account
users.still_own_repo = This account still have ownership of repository, you have to delete or transfer them first.
users.still_has_org = This account still have membership of organization, you have to left or delete them first.
orgs.org_manage_panel = Organization Manage Panel
orgs.name = Name
@@ -517,7 +589,7 @@ auths.enable_auto_register = Enable Auto Registration
auths.tips = Tips
auths.edit = Edit Authorization Setting
auths.activated = This authentication has activated
auths.update_success = Authorization setting has been successfully updated.
auths.update_success = Authorization setting has been updated successfully.
auths.update = Update Authorization Setting
auths.delete = Delete This Authorization
auths.delete_auth_title = Authorization Deletion
@@ -577,8 +649,6 @@ config.gc_interval_time = GC Interval Time
config.session_life_time = Session Life Time
config.https_only = HTTPS Only
config.cookie_life_time = Cookie Life Time
config.session_hash_function = Session ID Hash Function
config.session_hash_key = Session ID Hash Key
config.picture_config = Picture Configuration
config.picture_service = Picture Service
config.disable_gravatar = Disable Gravatar
@@ -601,7 +671,7 @@ notices.type = Type
notices.type_1 = Repository
notices.desc = Description
notices.op = Op.
notices.delete_success = System notice has been successfully deleted.
notices.delete_success = System notice has been deleted successfully.
[action]
create_repo = created repository <a href="%s/%s">%s</a>
@@ -609,6 +679,8 @@ commit_repo = pushed to <a href="%s/%s/src/%s">%s</a> at <a href="%s/%s">%s</a>
create_issue = opened issue <a href="%s/%s/issues/%s">%s#%s</a>
comment_issue = commented on issue <a href="%s/%s/issues/%s">%s#%s</a>
transfer_repo = transfered repository <code>%s</code> to <a href="/%s%s">%s</a>
push_tag = pushed tag <a href="%s/%s/src/%s">%s</a> to <a href="%s/%s">%s</a>
compare_2_commits = View comparison for these 2 commits
[tool]
ago = ago

1234
conf/locale/locale_fr-CA.ini Normal file → Executable file

File diff suppressed because it is too large Load Diff

718
conf/locale/locale_lv-LV.ini Executable file
View File

@@ -0,0 +1,718 @@
app_desc=Viegli uzstādāms Git serviss, kas rakstīts valodā Go
home=Sākums
dashboard=Infopanelis
explore=Izpētīt
help=Palīdzība
sign_in=Pierakstīties
social_sign_in=Sociālā pieteikšanās: 2. solis <small>piesaistīt kontu</small>
sign_out=Izrakstīties
sign_up=Pieteikties
register=Reģistrēties
website=Mājas lapa
version=Versija
page=Lapa
template=Sagatave
language=Valoda
username=Lietotājvārds
email=E-pasts
password=Parole
re_type=Parole atkārtoti
captcha=Pārbaudes kods
repository=Repozitorijs
organization=Organizācija
mirror=Spogulis
new_repo=Jauns repozitorijs
new_migrate=Jauna migrācija
new_fork=Jauns atdalītais repozitorijs
new_org=Jauna organizācija
manage_org=Pārvaldīt organizācijas
admin_panel=Admin panelis
account_settings=Konta iestatījumi
settings=Iestatījumi
news_feed=Jaunumu plūsma
pull_requests=Izmaiņu pieprasījumi
issues=Problēmas
cancel=Atcelt
[install]
install=Instalācija
title=Instalācijas soļi pirmo reizi palaižot
requite_db_desc=Gogs ir nepieciešama MySQL, PostgreSQL vai SQLite3 datu bāze.
db_type=Datu bāzes veids
host=Resursdators
user=Lietotājs
password=Parole
db_name=Datu bāzes nosaukums
db_helper=Nepieciešams izmantot MySQL INNODB dzini ar rakstzīmju kopu utf8_general_ci.
ssl_mode=SSL režīms
path=Ceļš
sqlite_helper=SQLite 3 datu bāzes faila atrašanās vieta.
general_title=Gogs vispārīgie iestatījumi
repo_path=Repozitoriju glabāšanas vieta
repo_path_helper=Visi Git attālinātie repozitoriji tiks glabāti šajā direktorijā.
run_user=Izpildes lietotājs
run_user_helper=Lietotājam ir jābūt rakstīšanas tiesībām repozitorija saknes direktorijai un Gogs jābūt palaistam zem šī lietotāja.
domain=Domēns
domain_helper=Tas ietekmē SSH klonēšanas URL.
app_url=Lietotnes URL
app_url_helper=Tas ietekmē HTTP/HTTPS klonēšanas URL un e-pasta saturā izsūtītās saites.
email_title=E-pasta pakalpojuma iestatījumi (neobligāti)
smtp_host=SMTP resursdators
mailer_user=Sūtītāja e-pasta adrese
mailer_password=Sūtītāja parole
notify_title=Paziņojumu iestatījumi (neobligāti)
register_confirm=Iespējot reģistrēšanās apstiprināšanu
mail_notify=Iespējot e-pasta paziņojumus
admin_title=Admin konta iestatījumi
admin_name=Lietotājvārds
admin_password=Parole
confirm_password=Apstipriniet paroli
admin_email=E-pasts
install_gogs=Instalēt Gogs
test_git_failed=Kļūda pārbaudot 'git' komandu: %v
sqlite3_not_available=Jūsu versija neatbalsta SQLite3, lūdzu lejupielādējiet oficiālo bināro versiju no %s, NEVIS gobuild versiju.
invalid_db_setting=Datu bāzes iestatījums nav pareizs: %v
invalid_repo_path=Repozitorija atrašanās vieta ir nekorekta: %v
run_user_not_match=Izpildes lietotājs nav pašreizējais lietotājs: %s -> %s
save_config_failed=Neizdevās saglabāt konfigurāciju: %v
invalid_admin_setting=Nekorekts admin konta iestatījums: %v
install_success=Laipni lūdzam! Mēs priecājamies, ka Jūs izvēlaties Gogs, patīkamu lietošanu!
[home]
uname_holder=Lietotājvārds vai e-pasts
password_holder=Parole
switch_dashboard_context=Mainīt infopaneļa kontekstu
my_repos=Mani repozitoriji
collaborative_repos=Sadarbības repozitoriji
my_orgs=Manas organizācijas
my_mirrors=Mani spoguļi
[explore]
repos=Repozitoriji
[auth]
create_new_account=Izveidot jaunu kontu
register_hepler_msg=Jau ir konts? Pieraksties tagad!
social_register_hepler_msg=Jau ir konts? Sasaisti tagad!
disable_register_prompt=Atvainojiet, reģistrācija ir atspējota. Lūdzu, sazinieties ar vietnes administratoru.
disable_register_mail=Atvainojiet, reģistrācijas e-pasta apstiprināšana ir atspējota.
remember_me=Atcerēties mani
forgot_password=Aizmirsu paroli
forget_password=Aizmirsi paroli?
sign_up_now=Nepieciešams konts? Reģistrējies tagad.
confirmation_mail_sent_prompt=Jauns apstiprināšanas e-pasts ir nosūtīts uz <b>%s</b>, lūdzu, pārbaudies savu e-pasta kontu tuvāko %d stundu laikā, lai pabeigtu reģistrācijas procesu.
sign_in_email=Atvērt savu e-pasta kontu
active_your_account=Aktivizēt savu kontu
resent_limit_prompt=Atvainojiet, Jūs sūtījāt aktivizācijas e-pastu pārāk bieži. Lūdzu, gaidiet 3 minūtes.
has_unconfirmed_mail=Sveiki %s, Jums ir neapstiprināta e-pasta adrese (<b>%s</b>). Ja neesat saņēmis apstiprināšanas e-pastu vai Jums ir nepieciešams nosūtīt jaunu, lūdzu, nospiediet pogu, kas atrodas zemāk.
resend_mail=Nospiediet šeit, lai vēlreiz nosūtītu aktivizācijas e-pastu
email_not_associate=Šī e-pasta adrese nav saistīta ar Jūsu kontu.
send_reset_mail=Spiediet šeit, lai nosūtītu paroles maiņas vēstuli uz Jūsu e-pastu
reset_password=Atjaunot savu paroli
invalid_code=Atvainojiet, Jūsu apstiprināšanas kodam ir beidzies derīguma termiņš vai arī tas ir nepareizs.
reset_password_helper=Nospiediet šeit, lai atjaunotu paroli
password_too_short=Paroles garums nedrīkst būt mazāks par 6.
[form]
UserName=Lietotājvārds
RepoName=Repozitorija nosaukums
Email=E-pasta adrese
Password=Parole
Retype=Parole atkārtoti
SSHTitle=SSH atslēgas nosaukums
HttpsUrl=HTTPS URL
PayloadUrl=Vērtuma URL
TeamName=Komandas nosaukums
AuthName=Autorizācijas nosaukums
AdminEmail=Admin e-pasta adrese
require_error=` nedrīkst būt tukšs.`
alpha_dash_error=` drīkst saturēt tikai latīņu alfabēta burtus, ciparus vai domuzīmes (-_).`
alpha_dash_dot_error=` drīkst saturēt tikai latīņu alfabēta burtus, ciparus, domuzīmes (-_) vai punktu.`
min_size_error=` jabūt vismaz %s simbolu garumā.`
max_size_error=` jabūt ne mazāk kā %s simbolu garumā.`
email_error=` nav derīga e-pasta adrese.`
url_error=` nav korekts URL.`
unknown_error=Nezināma kļūda:
captcha_incorrect=Pārbaudes kods nesakrīt ar attēlā redzamo.
password_not_match=Parole un atkārtoti ievadītā parole nav vienādas.
username_been_taken=Lietotājvārds ir jau aizņemts.
repo_name_been_taken=Repozitorija vārds ir jau aizņemts.
org_name_been_taken=Organizācijas nosaukums ir jau aizņemts.
team_name_been_taken=Komandas nosaukums ir jau aizņemts.
email_been_used=E-pasta adrese jau tiek izmantota.
ssh_key_been_used=Publiskās atslēgas nosaukums jau tiek izmantos.
illegal_username=Jūsu lietotājvārds satur neatļautas rakstzīmes.
illegal_repo_name=Krātuves nosaukums satur neatļautas rakstzīmes.
illegal_org_name=Organizācijas nosaukums satur neatļautas rakstzīmes.
illegal_team_name=Grupas nosaukums satur neatļautas rakstzīmes.
username_password_incorrect=Lietotājvārds vai parole nav pareiza.
enterred_invalid_repo_name=Lūdzu, pārliecinieties, vai ievadītā repozitorija nosaukums ir pareizs.
enterred_invalid_owner_name=Lūdzu, pārliecinieties, vai ievadītā īpašnieka vārds ir pareizs.
enterred_invalid_password=Lūdzu pārliecinieties, vai Jūsu ievadītā parole ir pareiza.
user_not_exist=Šāds lietotājs neeksistē.
last_org_owner=Nav iespējams noņemt vienīgo komandas īpašnieku. Pirms tam ir nepieciešams norādīt jauno īpašnieku.
invalid_ssh_key=Atvainojiet, nav iespējams pārbaudīt Jūsu SSH atslēgu: %s
unable_verify_ssh_key=Nav iespējams pārbaudīt jūsu SSH atslēgu, bet tiks pieņemts, ka tā ir derīga, lūdzu, pārliecinieties par to pats.
auth_failed=Autentifikācija neizdevās: %v
still_own_repo=Jūsu esat vismaz viena repozitorija īpašnieks, tos sākumā ir nepieciešams izdzēst vai nomainīt to īpašnieku.
still_has_org=Jūsu esat vismaz vienas organizācijas biedrs, sākumā nepieciešams pamest vai izdzēst šo organizāciju.
org_still_own_repo=Šī organizācija ir vismaz viena repozitorija īpašnieks, tos sākumā ir nepieciešams izdzēst vai nomainīt to īpašnieku.
still_own_user=Šo autentifikāciju joprojām izmanto vismaz viens lietotājs, nepieciešams šiem lietotājiem nomainīt autentifikācijas veidu vai tos izdzēst.
target_branch_not_exist=Mērķa atzars neeksistē
[user]
change_avatar=Mainīt savu profila attēlu vietnē gravatar.com
change_custom_avatar=Mainīt savu profila attēlu iestatījumos
join_on=Pievienojās
repositories=Repozitoriji
activity=Publiskā aktivitāte
followers=Sekotāji
starred=Atzīmēti ar zvaigznīti
following=Seko
[settings]
profile=Profils
password=Parole
ssh_keys=SSH atslēgas
social=Sociālie konti
applications=Lietotnes
orgs=Organizācijas
delete=Dzēst kontu
uid=Lietotāja ID
public_profile=Publiskais profils
profile_desc=Jūsu e-pasta adrese ir publiska un tiks izmantota, lai nosūtītju Jums paziņojumus, kas saistīti ar Jūsu kontu vai darbībām veiktām caur šo mājas lapu.
full_name=Pilns vārds
website=Mājas lapa
location=Atrašanās vieta
update_profile=Mainīt profilu
update_profile_success=Jūsu profila dati ir veiksmīgi saglabāti.
change_username=Lietotāja vārds mainīts
change_username_desc=Lietotājvārds tiks mainīts, vai vēlaties turpināt? Tas ietekmēs visas saites, kas attiecas uz Jūsu kontu.
continue=Turpināt
cancel=Atcelt
enable_custom_avatar=Iespējot maināmu profila attēlu
enable_custom_avatar_helper=Iespējojiet šo, lai atslēgtu profilu attēlu ņemšanu no gravatar.com
choose_new_avatar=Izvēlēties jaunu profila attēlu
update_avatar=Saglabāt profila bildi
uploaded_avatar_not_a_image=Augšupielādētais fails nav attēls.
no_custom_avatar_available=Nav iespējams mainīt profila bildi.
update_avatar_success=Jūsu profila bilde tika veiksmīgi saglabāta.
change_password=Mainīt paroli
old_password=Pašreizējā parole
new_password=Jauna parole
password_incorrect=Ievadīta nepareiza pašreizējā parole.
change_password_success=Parole tika veiksmīgi nomainīta. Tagad jūs varat pieraksītites, izmantojot jauno paroli.
manage_ssh_keys=Pārvaldīt SSH atslēgas
add_key=Pievienot atslēgu
ssh_desc=Šis ir saraksts ar Jūsu kontam piesaistītajām SSH atslēgām. Dzēsiet visas, kuras Jūs neatpazīstat.
ssh_helper=<strong>Vajadzīga palīdzība?</strong> Apskatieties pamācību kā <a href="%s">ģenerēt SSH atslēgas</a> vai kā novērst <a href="%s">biežāk sastopamās SSH problēmas</a>.
add_new_key=Pievienot SSH atslēgu
key_name=Atslēgas nosaukums
key_content=Saturs
add_key_success=Pievienota jauna SSH atslēga!
delete_key=Dzēst
add_on=Pievienota
last_used=Pēdējo reizi izmantota
no_activity=Nav nesenas aktivitātes
manage_social=Pārvaldīt piesaistītos sociālos kontus
social_desc=Šeit tiek attēloti visi sociālie konti, kas ir piesaistīti Jūsu kontam. Dzēsiet visus, kurus Jūs neatpazīstat.
unbind=Atsaistīt
unbind_success=Sociālais konts tika atsaistīts.
manage_access_token=Pārvaldīt personīgos piekļuves talonus
generate_new_token=Ģenerēt jaunu talonu
tokens_desc=Talons tika uzģēnerēts, tagad varat to izmantot, lai piekļūtu Gogs API.
new_token_desc=Pašlaik visiem taloniem ir pilna piekļuve Jūsu kontam.
token_name=Talona nosaukums
generate_token=Ģenerēt talonu
generate_token_succees=Jauns piekļuves talons tika veiksmīgi uzģenerēts! Pārliecinieties, ka esat to nokopējis, jo to Jums vairāk nebūs iespēja izdarīt!
delete_token=Dzēst
delete_token_success=Jūsu personīgās piekļuves talons tika veiksmīgi izdzēsts! Neazimistiet veikt nepieciešamos labojumus savās lietojumprogrammās, kas to izmantoja.
delete_account=Dzēst savu kontu
delete_prompt=Šī darbība pilnībā izdzēsīs Jūsu kontu, kā arī tā ir <strong>NEATGRIEZENISKA</strong>!
confirm_delete_account=Apstiprināt dzēšanu
delete_account_title=Konta dzēšana
delete_account_desc=Šis konts tiks neatgriezeniski dzēsts, vai vēlaties turpināt?
[repo]
owner=Īpašnieks
repo_name=Repozitorija nosaukums
repo_name_helper=Labi repzotoriju nosaukumi ir īsi, tādi kurus viegli atcerēties un <strong>unikāli</strong>.
visibility=Redzamība
visiblity_helper=Šis repozitorijs ir <span class="label label-red label-radius">Privāts</span>
fork_repo=Atdalīt repozitoriju
fork_from=Atdalīt no
fork_visiblity_helper=Atdalītam repozitorijam nav iespējams nomainīt tā redzamību
repo_desc=Apraksts
repo_lang=Valoda
repo_lang_helper=Izvēlieties .gitignore failu
license=Licence
license_helper=Izvēlieties licences failu
init_readme=Inicializēt šo repozitoriju ar README.md failu
create_repo=Izveidot repozitoriju
default_branch=Noklusējuma atzars
mirror_interval=Spoguļošanas intervāls (stundās)
goget_meta=Go-Get metadati
goget_meta_helper=Šis repozitorijs saturēs <span class="label label-blue label-radius">Go-Get</span> metadatus
need_auth=Nepieciešama autorizācija
migrate_type=Migrācijas veids
migrate_type_helper=Šis repozitorijs būs <span class="label label-blue label-radius">Spoguļots</span>
migrate_repo=Migrēt repozitoriju
copy_link=Kopēt
click_to_copy=Kopēt uz starpliktuvi
copied=Kopēšana notikusi veiksmīgi
clone_helper=Nepieciešama palīdzība kā veikt klonēšana? Apmeklējiet <a target="_blank" href="%s">Palīdzība</a> lapu!
unwatch=Nevērot
watch=Vērot
unstar=Noņemt zvaigznīti
star=Pievienot zvaigznīti
fork=Atdalīts
no_desc=Nav apraksta
quick_guide=Īsa pamācība
clone_this_repo=Klonēt šo repozitoriju
create_new_repo_command=Izveidot jaunu repozitoriju komandrindā
push_exist_repo=Nosūtīt izmaiņas no komandrindas eksistējošam repozitorijam
branch=Atzars
tree=Koks
branch_and_tags=Atzari un birkas
branches=Atzari
tags=Birkas
issues=Problēmas
commits=Revīzijas
releases=Laidieni
file_raw=Neapstrādāts
file_history=Vēsture
file_view_raw=Rādīt neapstrādātu
commits.commits=Revīzijas
commits.search=Meklēt revīzijas
commits.find=Meklēt
commits.author=Autors
commits.message=Ziņojums
commits.date=Datums
commits.older=Vecāki
commits.newer=Jaunāki
settings=Iestatījumi
settings.options=Opcijas
settings.collaboration=Sadarbība
settings.hooks=Tīmekļa āķi
settings.githooks=Git āķi
settings.deploy_keys=Izvietot atslēgas
settings.basic_settings=Pamatiestatījumi
settings.danger_zone=Bīstamā zona
settings.site=Oficiālā mājas lapa
settings.update_settings=Mainīt iestatījumus
settings.change_reponame=Mainīts repozitorija nosaukums
settings.change_reponame_desc=Repozitorija nosaukums tiks mainīts, vai vēlaties turpināt? Tas ietekmēs visas saites, kas saistītas ar šo repozitoriju.
settings.transfer=Mainīt īpašnieku
settings.transfer_desc=Mainīt šī repozitorija īpašnieku uz citu lietotāju vai organizāciju, kurai Jums ir administratora tiesībs.
settings.new_owner_has_same_repo=Jaunajam īpašniekam jau ir repozitorijs ar šādu nosaukumu.
settings.delete=Dzēst šo repozitoriju
settings.delete_desc=Dzēšot repozitoriju, tā datus vairs nebūs iespējams atgūt. Pirms dzēšanas pārliecinieites vai patiešām vēlaties to darīt.
settings.transfer_notices=<p>- Jūs zaudēsiet piekļuvi repozitorijam, ja jaunais īpašnieks ir individuāls lietotājs.</p><p>- Jūs saglabāsiet piekļuvi repzitorijam, ja jaunais īpašneiks ir organizācija un Jūs esat viens no tās īpašniekiem.</p>
settings.update_settings_success=Repozitorija opcijas ir veiksmīgi saglabātas.
settings.transfer_owner=Jaunais īpašnieks
settings.make_transfer=Mainīt
settings.transfer_succeed=Repozitorija īpašnieks ir veiksmīgi nomainīts.
settings.confirm_delete=Apstiprināt dzēšanu
settings.add_collaborator=Pievienot jaunu līdzstrādnieku
settings.add_collaborator_success=Jauns līdzstrādnieks ir pievienots.
settings.remove_collaborator_success=Līdzstrādnieks tika noņemts.
settings.user_is_org_member=Lietotājs ir organizācijas biedrs, kas nevar tikt pievienots kā līdzstrādnieks.
settings.add_webhook=Pievienot tīmekļa āķi
settings.hooks_desc=Tīmekļa āķi ļauj paziņot ārējiem servisiem par noteiktiem notikomiem, kas notiek Git servisā. Kad iestāsies kāds notikums, katram ārējā servisa URL tiks nosūtīts POST pieprasījums. Lai uzzinātu sīkāk skatieties <a target="_blank" href="%s">Tīmekļa āķu rokasgrāmatā</a>.
settings.githooks_desc=Git āķus apstrādā pats Git. Jūs varat labot atbalsīto āku failus sarakstā zemāk, lai veiktu pielāgotas darbības.
settings.githook_edit_desc=Ja āķis nav aktīvs, tiks attēlots piemērs kā to izmantot. Atstājot āķa saturu tukšu, tas tiks atspējots.
settings.githook_name=Āķa nosaukums
settings.githook_content=Āķa saturs
settings.update_githook=Labot āķi
settings.remove_hook_success=Tīmekļa āķis tika noņemts.
settings.add_webhook_desc=Uz norādīto URL tiks nosūtīts <code>POST</code> pieprasījums ar notikuma datiem. Jūs varat norādīt arī datu formātu, kādā datus vēlaties saņemt (JSON, <code>x-www-form-urlencoded</code> <em>utt.</em>). Detalizētāku informāciju ir iespējams uzzināt <a target="_blank" href="%s">Tīmekļa āķu rokasgrāmatā</a>.
settings.payload_url=Vērtuma URL
settings.content_type=Satura tips
settings.secret=Noslēpums
settings.event_desc=Kādu notikumu rezultātā tiktu izsaukts tīmekļā āķis?
settings.event_push_only=Tikai izmaiņu nosūtīšanas notikumiem.
settings.active=Aktīvs
settings.active_helper=Tiks nosūtīti notikuma dati, kad nostrādās šis āķis.
settings.add_hook_success=Jauns tīmekļa āķis tika veiksmīgi pievienots.
settings.update_webhook=Mainīt tīmekļa āķi
settings.update_hook_success=Tīmekļa āķist tika veiksmīgi saglabāts.
settings.delete_webhook=Dzēst tīmekļa āķi
settings.recent_deliveries=Pēdējās piegādes
settings.hook_type=Āķa veids
settings.add_slack_hook_desc=PIevienot <a href="%s">Slack</a> integrāciju Jūsu repozitorijā.
settings.slack_token=Talons
settings.slack_domain=Domēns
settings.slack_channel=Kanāls
diff.browse_source=Pārlūkot izejas kodu
diff.parent=vecāks
diff.commit=revīzija
diff.data_not_available=Salīdzināšanas dati nav pieejami.
diff.show_diff_stats=Rādīt salīdzināšanas statistiku
diff.stats_desc=<strong>%d mainītis faili</strong> ar <strong>%d papildinājumiem</strong> un <strong>%d dzēšanām</strong>
diff.bin=BIN
diff.view_file=Parādīt failu
release.releases=Releases
release.new_release=New Release
release.draft=Draft
release.prerelease=Pre-Release
release.stable=Stable
release.edit=edit
release.ahead=<strong>%d</strong> commits to %s since this release
release.source_code=Source Code
release.tag_name=Tag name
release.target=Target
release.tag_helper=Choose an existing tag, or create a new tag on publish.
release.release_title=Release title
release.content_with_md=Content with <a href="%s">Markdown</a>
release.write=Write
release.preview=Preview
release.content_placeholder=Write some content
release.loading=Loading...
release.prerelease_desc=This is a pre-release
release.prerelease_helper=Well point out that this release is identified as non-production ready.
release.publish=Publish Release
release.save_draft=Save Draft
release.edit_release=Edit Release
release.tag_name_already_exist=Release with this tag name has already existed.
[org]
org_name_holder=Organizācijas nosaukums
org_name_helper=Labi organizāciju nosaukumi ir īsi un tādi, kurus viegli atcerēties.
org_email_helper=Uz organizācijas e-pastu tiks sūtītas visas notifikācias un apstiprinājumi.
create_org=Izveidot organizāciju
repo_updated=Atjaunināts
people=Personas
invite_someone=Uzaicināt kādu
teams=Komandas
lower_members=dalībnieki
lower_repositories=repozitoriji
create_new_team=Izveidot jaunu komandu
org_desc=Apraksts
team_name=Komandas nosaukums
team_desc=Apraksts
team_name_helper=Šo nosaukumu varēs izmantot, lai pieminētu komandu sarunās.
team_desc_helper=Komandas apraksts
team_permission_desc=Kādām tiesībām šai komandai būtu jābūt?
settings=Iestatījumi
settings.options=Opcijas
settings.full_name=Pilns vārds, uzvārds
settings.website=Mājas lapa
settings.location=Atrašanās vieta
settings.update_settings=Mainīt iestatījumus
settings.change_orgname=Mainīts organizācijas nosaukums
settings.change_orgname_desc=Organizācijas nosaukums tiks mainīts, vai vēlaties turpinat? Tas ietekmēs saites, kas attiecas uz šo organizāciju.
settings.update_setting_success=Organizācijas iestatījumi tika veiksmīgi saglabāti.
settings.delete=Dzēst organizāciju
settings.delete_account=Dzēst šo organizāciju
settings.delete_prompt=Šī darbība pilnībā dzēsīs šo organizāciju, kā arī tā ir <strong>NEATGRIEZENISKA</strong>!
settings.confirm_delete_account=Apstiprināt dzēšanu
settings.delete_org_title=Organizācijas dzēšana
settings.delete_org_desc=Šī organizācija tiks pilnībā izdzēsta, vai vēlaties turpināt?
settings.hooks_desc=Pievienot tīmekļa āķus, kas nostrādās <strong>visiem repozitorijiem</strong> šajā organizācijā.
members.public=Publisks
members.public_helper=padarīt privātu
members.private=Privāts
members.private_helper=padarīt publisku
members.owner=Īpašnieks
members.member=Biedri
members.conceal=Noslēpt
members.remove=Noņemt
members.leave=Atstāt
members.invite_desc=Sāciet rakstīt lietotājvārdu, lai uzaicinātu jaunu biedru organizācijā %s:
members.invite_now=Uzaicināt tagad
teams.join=Pievienoties
teams.leave=Atstāt
teams.read_access=Lasīšanas piekļuve
teams.read_access_helper=Komanda varēs skatīties un klonēt šīs organizācijas repozitorijus.
teams.write_access=Rakstīšanas piekļuve
teams.write_access_helper=Komanda varēs skatīties un klonēt, kā arī nosūtīt izmaiņas šīs organizācijas repozitorijiem.
teams.admin_access=Administratora piekļuve
teams.admin_access_helper=Šī komanda varēs veikt push/pull komandas tās repozitorijiem, kā arī tiem pievienot citus līdzstrādniekus.
teams.no_desc=Komandai nav apraksta
teams.settings=Iestatījumi
teams.owners_permission_desc=Īpašniekiem ir pilna piekļuve <strong>visiem repozitorijiem</strong> un ir organizācijas <strong>administratora tiesības</strong>.
teams.members=Komandas biedri
teams.update_settings=Saglabāt iestatījumus
teams.delete_team=Dzēst komandu
teams.add_team_member=Pievienot komandas biedru
teams.delete_team_title=Komandas dzēšana
teams.delete_team_desc=Komanda tiks dzēsta, vai vēlaties turpināt? Komandas biedri var zaudēt piekļuvi dažiem vai pat visiem repozitorijiem.
teams.delete_team_success=Komanda tika veiksmīgi izdzēsta.
teams.read_permission_desc=Šai komandai ir <strong>lasīšanas</strong> tiesības: dalībnieki var skatīties un klonēt komandas repozitorijus.
teams.write_permission_desc=Šai komandai ir <strong>rakstīšanas</strong> tiesības: dalībnieki var lasīt un nosūtīt izmaiņas repozitorijiem.
teams.admin_permission_desc=Šai komandai ir <strong>administratora</strong> tiesības: dalībnieki var lasīt, rakstīt un pievienot citus dalībniekus komandas repozitorijiem.
teams.repositories=Komandas repozitoriji
teams.add_team_repository=Pievienot komandas repozitoriju
teams.remove_repo=Noņemt
teams.add_nonexistent_repo=Repozitorijs, kuram Jūs mēģinat pievienot neeksistē, sākumā izveidojiet to.
[admin]
dashboard=Infopanelis
users=Lietotāji
organizations=Organizācijas
repositories=Repozitoriji
authentication=Autentifikācijas
config=Konfigurācija
notices=Sistēmas paziņojumi
monitor=Uzraudzība
prev=Iepr.
next=Tālāk
dashboard.statistic=Statistika
dashboard.operations=Darbības
dashboard.system_status=Sistēmas uzraudzības statuss
dashboard.statistic_info=Gogs datu bāze satur <b>%d</b> lietotājus, <b>%d</b> organizācijas, <b>%d</b> publiskās atslēgas, <b>%d</b> repozitorijus, <b>%d</b> vērošanas, <b>%d</b> atzīmētas zvaigznītes, <b>%d</b> darbības, <b>%d</b> piekļuves, <b>%d</b> problēmas, <b>%d</b> komentārus, <b>%d</b> sociālos kontus, <b>%d</b> sekošanas, <b>%d</b> spoguļošanas, <b>%d</b> izlaides, <b>%d</b> login sources, <b>%d</b> tīmekļa āķus, <b>%d</b> starpposmus, <b>%d</b> etiķetes, <b>%d</b> āķu uzdevumus, <b>%d</b> komandas, <b>%d</b> labotus uzdevumus, <b>%d</b> pielikumus.
dashboard.operation_name=Darbības nosaukums
dashboard.operation_switch=Pārslēgt
dashboard.operation_run=Palaist
dashboard.clean_unbind_oauth=Notīrīt nesaistītās OAuth biļetes
dashboard.clean_unbind_oauth_success=Visas nesaistītās OAuth biļetes tika veiksmīgi izdzēstas.
dashboard.delete_inactivate_accounts=Dzēst visus neaktīvos kontus
dashboard.delete_inactivate_accounts_success=Visi neaktīvie kotni tika veiksmīgi izdzēsti.
dashboard.delete_repo_archives=Dzēst visu repozitoriju arhīvus
dashboard.delete_repo_archives_success=Visu repozitoriju arhīvi tika veiksmīgi izdzēsti.
dashboard.git_gc_repos=Veikt repozitoriju datu sakārtošānu (git gc)
dashboard.git_gc_repos_success=Datu sakārtošana visiem repozitorijiem veiksmīgi pabeigta.
dashboard.server_uptime=Servera darbības laiks
dashboard.current_goroutine=Izmantotās Gorutīnas
dashboard.current_memory_usage=Pašreiz izmantotā atmiņa
dashboard.total_memory_allocated=Kopējā piešķirtā atmiņa
dashboard.memory_obtained=Iegūtā atmiņa
dashboard.pointer_lookup_times=Rādītāju meklēšanas reizes
dashboard.memory_allocate_times=Atmiņas piešķiršanas reizes
dashboard.memory_free_times=Atmiņas atbrīvošanas reizes
dashboard.current_heap_usage=Pašreizējā kaudzes izmantošana
dashboard.heap_memory_obtained=Iegūtā kaudzes atmiņa
dashboard.heap_memory_idle=Neizmantotā kaudzes atmiņa
dashboard.heap_memory_in_use=Izmantotā kaudzes atmiņa
dashboard.heap_memory_released=Atbrīvotā kaudzes atmiņa
dashboard.heap_objects=Kaudzes atmiņas objekti
dashboard.bootstrap_stack_usage=Izmantotais sāknēšanas steka lielums
dashboard.stack_memory_obtained=Iegūtā steka atmiņa
dashboard.mspan_structures_usage=Izmantotās MSpan struktūras
dashboard.mspan_structures_obtained=Iegūtās MSpan struktūras
dashboard.mcache_structures_usage=Izmantotās MCache struktūras
dashboard.mcache_structures_obtained=Iegūtās MCache struktūras
dashboard.profiling_bucket_hash_table_obtained=Iegūtā profilēšanas kausa jaucējtabula
dashboard.gc_metadata_obtained=Iegūtie GC metadati
dashboard.other_system_allocation_obtained=Iegūtās citas sistēmas sadales
dashboard.next_gc_recycle=Nākošā GC atkritne
dashboard.last_gc_time=Laiks kopš pēdējās GC
dashboard.total_gc_time=Kopējais GC izpildes laiks
dashboard.total_gc_pause=Kopējais GC izpildes laiks
dashboard.last_gc_pause=Pedējās GC izpildes laiks
dashboard.gc_times=GC reizes
users.user_manage_panel=Lietotāju pārvaldības panelis
users.new_account=Izveidot jaunu kontu
users.name=Vārds
users.activated=Aktivizēts
users.admin=Administrators
users.repos=Repozitoriji
users.created=Izveidots
users.edit=Labot
users.auth_source=Autorizācijas avots
users.local=Iebūvētā
users.auth_login_name=Autorizāciju, pietiekšanās vārds
users.update_profile_success=Konta profils tika veiksmīgi saglabāts.
users.edit_account=Labot kontu
users.is_activated=Konts ir aktivizēts
users.is_admin=Šim kontam ir administratora piekļuves tiesības
users.allow_git_hook=Šim kontam ir tiesības pievienot/labot Git āķus
users.update_profile=Mainīt konta profilu
users.delete_account=Dzēst šo kontu
users.still_own_repo=Šis konts ir vismaz viena repozitorija īpašnieks, tos sākumā ir nepieciešams izdzēst vai nomainīt to īpašnieku.
users.still_has_org=Šis konts ir vismaz vienas organizācijas biedrs, sākumā nepieciešams pamest vai izdzēst šo organizāciju.
orgs.org_manage_panel=Organizāciju pārvaldības panelis
orgs.name=Nosaukums
orgs.teams=Komandas
orgs.members=Dalībnieki
repos.repo_manage_panel=Repozitoriju pārvaldības panelis
repos.owner=Īpašnieks
repos.name=Vārds
repos.private=Privāts
repos.watches=Vērošana
repos.stars=Atzīmētās zvaigznītes
repos.issues=Problēmas
auths.auth_manage_panel=Autorizāciju pārvaldības panelis
auths.new=Pievienot jaunu autorizācijas veidu
auths.name=Nosaukums
auths.type=Veids
auths.enabled=Iespējota
auths.updated=Atjaunināta
auths.auth_type=Autorizācijas veids
auths.auth_name=Autorizācijas nosaukums
auths.domain=Domēns
auths.host=Resursdators
auths.port=Ports
auths.base_dn=Pamata DN
auths.attributes=Meklēšanas atribūti
auths.filter=Meklēšanas filtrs
auths.ms_ad_sa=MS Ad SA
auths.smtp_auth=SMTP autorizācijas veids
auths.smtphost=SMTP resursdators
auths.smtpport=SMTP ports
auths.enable_tls=Iespējot TLS šifrēšanu
auths.enable_auto_register=Iespējot automātisko reģistrāciju
auths.tips=Padomi
auths.edit=Labot autorizācijas iestatījumus
auths.activated=Autentifikācija ir aktivizēta
auths.update_success=Autorizācijas iestatījumi tika veiksmīgi saglabāti.
auths.update=Mainīt autorizācijas iestatījumus
auths.delete=Dzēst šo autorizāciju
auths.delete_auth_title=Autorizācijas dzēšana
auths.delete_auth_desc=Šī autorizācija tiks dzēsta, vai vēlaties turpināt?
config.server_config=Servera konfigurācija
config.app_name=Lietotnes nosaukums
config.app_ver=Lietotnes versija
config.app_url=Lietotnes URL
config.domain=Domēns
config.offline_mode=Bezsaistes režīms
config.disable_router_log=Atspējot maršrutētāja žurnalizēšanu
config.run_user=Izpildes lietotājs
config.run_mode=Izpildes režīms
config.repo_root_path=Repozitoriju glabāšanas vieta
config.static_file_root_path=Statisko failu atrašanās vieta
config.log_file_root_path=Žurnalizēšanas failu glabāšanas vieta
config.script_type=Skripta veids
config.reverse_auth_user=Reversā lietotāja autentifikācija
config.db_config=Datu bāzes konfigurācija
config.db_type=Veids
config.db_host=Resursdators
config.db_name=Nosaukums
config.db_user=Lietotājs
config.db_ssl_mode=SSL režīms
config.db_ssl_mode_helper=(tikai PostgreSQL datu bāzei)
config.db_path=Ceļš
config.db_path_helper=(tikai Sqlite3 datu bāzei)
config.service_config=Pakalpojuma konfigurācija
config.register_email_confirm=E-pasta reģistrēšanas apstiprināšana
config.disable_register=Atspējot jaunu lietotāju reģistrāciju
config.require_sign_in_view=Nepieciešama autorizācija
config.mail_notify=Pasta paziņojumi
config.enable_cache_avatar=Glabāt profila attēlus kešatmiņā
config.active_code_lives=Aktīvā koda ilgums
config.reset_password_code_lives=Paroles atiestatīšanas koda ilgums
config.webhook_config=Tīkla āķu konfigurācija
config.task_interval=Uzdevuma intervāls
config.deliver_timeout=Piegādes noildze
config.mailer_config=Sūtītāja konfigurācija
config.mailer_enabled=Iespējots
config.mailer_name=Nosaukums
config.mailer_host=Resursdators
config.mailer_user=Lietotājs
config.oauth_config=OAuth konfigurācija
config.oauth_enabled=Iespējota
config.cache_config=Kešatmiņas konfigurācija
config.cache_adapter=Kešatmiņas adapteris
config.cache_interval=Kešatmiņas intervāls
config.cache_conn=Kešatmiņas pieslēguma parametri
config.session_config=Sesijas konfigurācja
config.session_provider=Sesijas nodrošinātājs
config.provider_config=Pakalpojumu sniedzēja konfigurācija
config.cookie_name=Sīkdatnes nosaukums
config.enable_set_cookie=Ļaut izmantot sīkdatnes
config.gc_interval_time=GC laika intervāls
config.session_life_time=Sesijas ilgums
config.https_only=Tikai HTTPS
config.cookie_life_time=Sīkdatņu glabāšanas ilgums
config.picture_config=Attēlu konfigurācija
config.picture_service=Lokāli attēli
config.disable_gravatar=Atspējot Gravatar
config.log_config=Žurnalizēšanas konfigurācija
config.log_mode=Žurnalizēšanas veids
monitor.cron=Cron uzdevumi
monitor.name=Nosaukums
monitor.schedule=Grafiks
monitor.next=Nākošās izpildes laiks
monitor.previous=Pēdējās izpildes laiks
monitor.execute_times=Izpilžu skaits
monitor.process=Darbojošies procesi
monitor.desc=Apraksts
monitor.start=Sākuma laiks
monitor.execute_time=Izpildes laiks
notices.system_notice_list=Sistēmas paziņojumi
notices.type=Veids
notices.type_1=Repozitorijs
notices.desc=Apraksts
notices.op=Op.
notices.delete_success=Sistēmas paziņojums tika veiksmīgi izdzēsts.
[action]
create_repo=izveidoja repozitoriju <a href="%s/%s">%s</a>
commit_repo=veica izmaiņu nosūtīšanu atzaram <a href="%s/%s/src/%s">%s</a> repozitorijā <a href="%s/%s">%s</a>
create_issue=reģistrēja problēmu <a href="%s/%s/issues/%s">%s#%s</a>
comment_issue=pievienoja komentāru problēmai <a href="%s/%s/issues/%s">%s#%s</a>
transfer_repo=mainīja repozitorija <code>%s</code> īpašnieku uz <a href="/%s%s">%s</a>
push_tag=pievienoja birku <a href="%s/%s/src/%s">%s</a> repozitorijam <a href="%s/%s">%s</a>
compare_2_commits=Veikt salīdzināšanu starp šīm 2 revīzijām
[tool]
ago=atpakaļ
from_now=no šī brīža
now=tagad
1s=1 sekundi %s
1m=1 minūti %s
1h=1 stundu %s
1d=1 dienu %s
1w=1 nedēļu %s
1mon=1 mēnesi %s
1y=1 gadu %s
seconds=%d sekundes %s
minutes=%d minūtes %s
hours=%d stundas %s
days=%d dienas %s
weeks=%d nedēļas %s
months=%d mēneši %s
years=%d gadi %s
raw_seconds=sekundes
raw_minutes=minūtes

1303
conf/locale/locale_nl-NL.ini Normal file → Executable file

File diff suppressed because it is too large Load Diff

1362
conf/locale/locale_zh-CN.ini Normal file → Executable file

File diff suppressed because it is too large Load Diff

1360
conf/locale/locale_zh-HK.ini Normal file → Executable file

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,12 @@
[unix_http_server]
file=/tmp/supervisor.sock ; path to your socket file
file=log/supervisor.sock ; path to your socket file
[supervisord]
logfile=log/supervisord.log ; supervisord log file
logfile_maxbytes=50MB ; maximum size of logfile before rotation
logfile_backups=10 ; number of backed up logfiles
loglevel=warn ; info, debug, warn, trace
pidfile=/tmp/supervisord.pid ; pidfile location
pidfile=log/supervisord.pid ; pidfile location
nodaemon=false ; run supervisord as a daemon
minfds=1024 ; number of startup file descriptors
minprocs=200 ; number of process descriptors
@@ -17,10 +17,10 @@ childlogdir=log
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
[supervisorctl]
serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL for a unix socket
serverurl=unix://log/supervisor.sock ; use a unix:// URL for a unix socket
[program:gogs]
command = /root/Developer/gopath/src/github.com/gogits/gogs/start.sh ; here must be the real url, not ~ or $GOROOT like
command = gogs_start
autostart = true
stdout_logfile = log/supervisor-gogs-stderr.log
stderr_logfile = log/supervisor-gogs-error.log
stdout_logfile = log/supervisor-gogs-out.log
stderr_logfile = log/supervisor-gogs-err.log

View File

@@ -17,7 +17,7 @@ import (
"github.com/gogits/gogs/modules/setting"
)
const APP_VER = "0.5.5.1010 Beta"
const APP_VER = "0.5.9.1213 Beta"
func init() {
runtime.GOMAXPROCS(runtime.NumCPU())

View File

@@ -58,6 +58,7 @@ type Action struct {
ActUserId int64 // Action user id.
ActUserName string // Action user name.
ActEmail string
ActAvatar string `xorm:"-"`
RepoId int64
RepoUserName string
RepoName string
@@ -153,6 +154,8 @@ func updateIssuesCommit(userId, repoId int64, repoUserName, repoName string, com
if err = UpdateIssue(issue); err != nil {
return err
} else if err = UpdateIssueUserPairsByStatus(issue.Id, issue.IsClosed); err != nil {
return err
}
if err = ChangeMilestoneIssueStats(issue); err != nil {
@@ -181,13 +184,19 @@ func CommitRepoAction(userId, repoUserId int64, userName, actEmail string,
commit = &base.PushCommits{}
}
refName := git.RefEndName(refFullName)
repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName)
// if not the first commit, set the compareUrl
if !strings.HasPrefix(oldCommitId, "0000000") {
commit.CompareUrl = fmt.Sprintf("%s/compare/%s...%s", repoLink, oldCommitId, newCommitId)
}
bs, err := json.Marshal(commit)
if err != nil {
return errors.New("action.CommitRepoAction(json): " + err.Error())
}
refName := git.RefEndName(refFullName)
// Change repository bare status and update last updated time.
repo, err := GetRepositoryByName(repoUserId, repoName)
if err != nil {
@@ -211,7 +220,6 @@ func CommitRepoAction(userId, repoUserId int64, userName, actEmail string,
return errors.New("action.CommitRepoAction(NotifyWatchers): " + err.Error())
}
//qlog.Info("action.CommitRepoAction(end): %d/%s", repoUserId, repoName)
// New push event hook.
if err := repo.GetOwner(); err != nil {
@@ -237,13 +245,6 @@ func CommitRepoAction(userId, repoUserId int64, userName, actEmail string,
return nil
}
repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName)
compareUrl := ""
// if not the first commit, set the compareUrl
if !strings.HasPrefix(oldCommitId, "0000000") {
compareUrl = fmt.Sprintf("%s/compare/%s...%s", repoLink, oldCommitId, newCommitId)
}
pusher_email, pusher_name := "", ""
pusher, err := GetUserByName(userName)
if err == nil {
@@ -293,7 +294,7 @@ func CommitRepoAction(userId, repoUserId int64, userName, actEmail string,
},
Before: oldCommitId,
After: newCommitId,
CompareUrl: compareUrl,
CompareUrl: commit.CompareUrl,
}
for _, w := range ws {
@@ -348,7 +349,7 @@ func NewRepoAction(u *User, repo *Repository) (err error) {
return err
}
// TransferRepoAction adds new action for transfering repository.
// TransferRepoAction adds new action for transferring repository.
func TransferRepoAction(u, newUser *User, repo *Repository) (err error) {
action := &Action{
ActUserId: u.Id,

View File

@@ -6,6 +6,7 @@ package models
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
@@ -15,8 +16,10 @@ import (
"github.com/Unknwon/com"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/git"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/mahonia"
"github.com/gogits/gogs/modules/process"
)
@@ -80,6 +83,8 @@ func ParsePatch(pid int64, maxlines int, cmd *exec.Cmd, reader io.Reader) (*Diff
leftLine, rightLine int
isTooLong bool
// FIXME: use first 30 lines to detect file encoding. Should use cache in the future.
buf bytes.Buffer
)
diff := &Diff{Files: make([]*DiffFile, 0)}
@@ -97,6 +102,11 @@ func ParsePatch(pid int64, maxlines int, cmd *exec.Cmd, reader io.Reader) (*Diff
i = i + 1
// FIXME: use first 30 lines to detect file encoding.
if i <= 30 {
buf.WriteString(line)
}
// Diff data too large, we only show the first about maxlines lines
if i == maxlines {
isTooLong = true
@@ -181,6 +191,21 @@ func ParsePatch(pid int64, maxlines int, cmd *exec.Cmd, reader io.Reader) (*Diff
}
}
// FIXME: use first 30 lines to detect file encoding.
charset, err := base.DetectEncoding(buf.Bytes())
if charset != "utf8" && err == nil {
decoder := mahonia.NewDecoder(charset)
if decoder != nil {
for _, f := range diff.Files {
for _, sec := range f.Sections {
for _, l := range sec.Lines {
l.Content = decoder.ConvertString(l.Content)
}
}
}
}
}
return diff, nil
}

View File

@@ -211,7 +211,10 @@ func GetIssues(uid, rid, pid, mid int64, page int, isClosed bool, labelIds, sort
if len(labelIds) > 0 {
for _, label := range strings.Split(labelIds, ",") {
sess.And("label_ids like '%$" + label + "|%'")
// Prevent SQL inject.
if com.StrTo(label).MustInt() > 0 {
sess.And("label_ids like '%$" + label + "|%'")
}
}
}

View File

@@ -18,6 +18,7 @@ import (
"github.com/gogits/gogs/modules/auth/ldap"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/uuid"
)
type LoginType int
@@ -40,7 +41,7 @@ var LoginTypes = map[LoginType]string{
SMTP: "SMTP",
}
// Ensure structs implmented interface.
// Ensure structs implemented interface.
var (
_ core.Conversion = &LDAPConfig{}
_ core.Conversion = &SMTPConfig{}
@@ -149,7 +150,7 @@ func DelLoginSource(source *LoginSource) error {
// UserSignIn validates user name and password.
func UserSignIn(uname, passwd string) (*User, error) {
var u *User
u := new(User)
if strings.Contains(uname, "@") {
u = &User{Email: uname}
} else {
@@ -225,33 +226,35 @@ func UserSignIn(uname, passwd string) (*User, error) {
}
}
// Query if name/passwd can login against the LDAP direcotry pool
// Query if name/passwd can login against the LDAP directory pool
// Create a local user if success
// Return the same LoginUserPlain semantic
// FIXME: https://github.com/gogits/gogs/issues/672
func LoginUserLdapSource(u *User, name, passwd string, sourceId int64, cfg *LDAPConfig, autoRegister bool) (*User, error) {
mail, logged := cfg.Ldapsource.SearchEntry(name, passwd)
if !logged {
// user not in LDAP, do nothing
// User not in LDAP, do nothing
return nil, ErrUserNotExist
}
if !autoRegister {
return u, nil
}
// fake a local user creation
// Fallback.
if len(mail) == 0 {
mail = uuid.NewV4().String() + "@localhost"
}
u = &User{
LowerName: strings.ToLower(name),
Name: strings.ToLower(name),
Name: name,
LoginType: LDAP,
LoginSource: sourceId,
LoginName: name,
IsActive: true,
Passwd: passwd,
Email: mail,
IsActive: true,
}
err := CreateUser(u)
return u, err
return u, CreateUser(u)
}
type loginAuth struct {
@@ -315,7 +318,7 @@ func SmtpAuth(host string, port int, a smtp.Auth, useTls bool) error {
return ErrUnsupportedLoginType
}
// Query if name/passwd can login against the LDAP direcotry pool
// Query if name/passwd can login against the LDAP directory pool
// Create a local user if success
// Return the same LoginUserPlain semantic
func LoginUserSMTPSource(u *User, name, passwd string, sourceId int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {

View File

@@ -5,6 +5,7 @@
package models
import (
"database/sql"
"fmt"
"os"
"path"
@@ -17,10 +18,16 @@ import (
"github.com/gogits/gogs/modules/setting"
)
var (
x *xorm.Engine
tables []interface{}
// Engine represents a xorm engine or session.
type Engine interface {
Delete(interface{}) (int64, error)
Exec(string, ...interface{}) (sql.Result, error)
Insert(...interface{}) (int64, error)
}
var (
x *xorm.Engine
tables []interface{}
HasEngine bool
DbCfg struct {
@@ -32,7 +39,8 @@ var (
)
func init() {
tables = append(tables, new(User), new(PublicKey), new(Follow), new(Oauth2),
tables = append(tables,
new(User), new(PublicKey), new(Follow), new(Oauth2), new(AccessToken),
new(Repository), new(Watch), new(Star), new(Action), new(Access),
new(Issue), new(Comment), new(Attachment), new(IssueUser), new(Label), new(Milestone),
new(Mirror), new(Release), new(LoginSource), new(Webhook),
@@ -99,7 +107,7 @@ func SetEngine() (err error) {
return fmt.Errorf("models.init(fail to connect to database): %v", err)
}
// WARNNING: for serv command, MUST remove the output to os.stdout,
// WARNING: for serv command, MUST remove the output to os.stdout,
// so use log file to instead print to stdout.
logPath := path.Join(setting.LogRootPath, "xorm.log")
os.MkdirAll(path.Dir(logPath), os.ModePerm)
@@ -122,7 +130,7 @@ func NewEngine() (err error) {
if err = SetEngine(); err != nil {
return err
}
if err = x.Sync2(tables...); err != nil {
if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
return fmt.Errorf("sync database struct error: %v\n", err)
}
return nil

View File

@@ -79,7 +79,7 @@ func UpdateOauth2(oa *Oauth2) error {
return err
}
// GetOauthByUserId returns list of oauthes that are releated to given user.
// GetOauthByUserId returns list of oauthes that are related to given user.
func GetOauthByUserId(uid int64) ([]*Oauth2, error) {
socials := make([]*Oauth2, 0, 5)
err := x.Find(&socials, Oauth2{Uid: uid})

View File

@@ -25,8 +25,8 @@ var (
ErrLastOrgOwner = errors.New("The user to remove is the last member in owner team")
)
// IsOrgOwner returns true if given user is in the owner team.
func (org *User) IsOrgOwner(uid int64) bool {
// IsOwnedBy returns true if given user is in the owner team.
func (org *User) IsOwnedBy(uid int64) bool {
return IsOrganizationOwner(org.Id, uid)
}
@@ -77,6 +77,17 @@ func (org *User) RemoveMember(uid int64) error {
return RemoveOrgUser(org.Id, uid)
}
// IsOrgEmailUsed returns true if the e-mail has been used in organization account.
func IsOrgEmailUsed(email string) (bool, error) {
if len(email) == 0 {
return false, nil
}
return x.Get(&User{
Email: email,
Type: ORGANIZATION,
})
}
// CreateOrganization creates record of a new organization.
func CreateOrganization(org, owner *User) (*User, error) {
if !IsLegalName(org.Name) {
@@ -90,7 +101,7 @@ func CreateOrganization(org, owner *User) (*User, error) {
return nil, ErrUserAlreadyExist
}
isExist, err = IsEmailUsed(org.Email)
isExist, err = IsOrgEmailUsed(org.Email)
if err != nil {
return nil, err
} else if isExist {
@@ -159,6 +170,24 @@ func CreateOrganization(org, owner *User) (*User, error) {
return org, sess.Commit()
}
// GetOrgByName returns organization by given name.
func GetOrgByName(name string) (*User, error) {
if len(name) == 0 {
return nil, ErrOrgNotExist
}
u := &User{
LowerName: strings.ToLower(name),
Type: ORGANIZATION,
}
has, err := x.Get(u)
if err != nil {
return nil, err
} else if !has {
return nil, ErrOrgNotExist
}
return u, nil
}
// CountOrganizations returns number of organizations.
func CountOrganizations() int64 {
count, _ := x.Where("type=1").Count(new(User))
@@ -229,7 +258,7 @@ func IsOrganizationMember(orgId, uid int64) bool {
return has
}
// IsPublicMembership returns ture if given user public his/her membership.
// IsPublicMembership returns true if given user public his/her membership.
func IsPublicMembership(orgId, uid int64) bool {
has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).And("is_public=?", true).Get(new(OrgUser))
return has
@@ -845,23 +874,12 @@ func IsTeamMember(orgId, teamId, uid int64) bool {
// GetTeamMembers returns all members in given team of organization.
func GetTeamMembers(orgId, teamId int64) ([]*User, error) {
tus := make([]*TeamUser, 0, 10)
err := x.Where("org_id=?", orgId).And("team_id=?", teamId).Find(&tus)
if err != nil {
return nil, err
}
us := make([]*User, len(tus))
for i, tu := range tus {
us[i], err = GetUserById(tu.Uid)
if err != nil {
return nil, err
}
}
return us, nil
us := make([]*User, 0, 10)
err := x.Sql("SELECT * FROM `user` JOIN `team_user` ON `team_user`.`team_id` = ? AND `team_user`.`uid` = `user`.`id`", teamId).Find(&us)
return us, err
}
// GetUserTeams returns all teams that user belongs to in given origanization.
// GetUserTeams returns all teams that user belongs to in given organization.
func GetUserTeams(orgId, uid int64) ([]*Team, error) {
tus := make([]*TeamUser, 0, 5)
if err := x.Where("uid=?", uid).And("org_id=?", orgId).Find(&tus); err != nil {

View File

@@ -33,6 +33,7 @@ const (
var (
ErrKeyAlreadyExist = errors.New("Public key already exist")
ErrKeyNotExist = errors.New("Public key does not exist")
ErrKeyUnableVerify = errors.New("Unable to verify public key")
)
var sshOpLocker = sync.Mutex{}
@@ -78,9 +79,9 @@ func init() {
// PublicKey represents a SSH key.
type PublicKey struct {
Id int64
OwnerId int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
Name string `xorm:"UNIQUE(s) NOT NULL"`
Fingerprint string
OwnerId int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
Name string `xorm:"UNIQUE(s) NOT NULL"`
Fingerprint string `xorm:"INDEX NOT NULL"`
Content string `xorm:"TEXT NOT NULL"`
Created time.Time `xorm:"CREATED"`
Updated time.Time
@@ -88,6 +89,11 @@ type PublicKey struct {
HasUsed bool `xorm:"-"`
}
// OmitEmail returns content of public key but without e-mail address.
func (k *PublicKey) OmitEmail() string {
return strings.Join(strings.Split(k.Content, " ")[:2], " ")
}
// GetAuthorizedString generates and returns formatted public key string for authorized_keys file.
func (key *PublicKey) GetAuthorizedString() string {
return fmt.Sprintf(_TPL_PUBLICK_KEY, appPath, key.Id, key.Content)
@@ -107,8 +113,9 @@ var (
// CheckPublicKeyString checks if the given public key string is recognized by SSH.
func CheckPublicKeyString(content string) (bool, error) {
content = strings.TrimRight(content, "\n\r")
if strings.ContainsAny(content, "\n\r") {
return false, errors.New("Only a single line with a single key please")
return false, errors.New("only a single line with a single key please")
}
// write the key to a file…
@@ -126,7 +133,7 @@ func CheckPublicKeyString(content string) (bool, error) {
if err != nil {
return false, errors.New("ssh-keygen -l -f: " + stderr)
} else if len(stdout) < 2 {
return false, errors.New("ssh-keygen returned not enough output to evaluate the key")
return false, errors.New("ssh-keygen returned not enough output to evaluate the key: " + stdout)
}
// The ssh-keygen in Windows does not print key type, so no need go further.
@@ -134,21 +141,22 @@ func CheckPublicKeyString(content string) (bool, error) {
return true, nil
}
fmt.Println(stdout)
sshKeygenOutput := strings.Split(stdout, " ")
if len(sshKeygenOutput) < 4 {
return false, errors.New("Not enough fields returned by ssh-keygen -l -f")
return false, ErrKeyUnableVerify
}
// Check if key type and key size match.
keySize, err := com.StrTo(sshKeygenOutput[0]).Int()
if err != nil {
return false, errors.New("Cannot get key size of the given key")
keySize := com.StrTo(sshKeygenOutput[0]).MustInt()
if keySize == 0 {
return false, errors.New("cannot get key size of the given key")
}
keyType := strings.TrimSpace(sshKeygenOutput[len(sshKeygenOutput)-1])
if minimumKeySize := MinimumKeySize[keyType]; minimumKeySize == 0 {
return false, errors.New("Sorry, unrecognized public key type")
return false, errors.New("sorry, unrecognized public key type")
} else if keySize < minimumKeySize {
return false, fmt.Errorf("The minimum accepted size of a public key %s is %d", keyType, minimumKeySize)
return false, fmt.Errorf("the minimum accepted size of a public key %s is %d", keyType, minimumKeySize)
}
return true, nil
@@ -204,9 +212,12 @@ func AddPublicKey(key *PublicKey) (err error) {
if err != nil {
return errors.New("ssh-keygen -l -f: " + stderr)
} else if len(stdout) < 2 {
return errors.New("Not enough output for calculating fingerprint")
return errors.New("not enough output for calculating fingerprint: " + stdout)
}
key.Fingerprint = strings.Split(stdout, " ")[1]
if has, err := x.Get(&PublicKey{Fingerprint: key.Fingerprint}); err == nil && has {
return ErrKeyAlreadyExist
}
// Save SSH key.
if _, err = x.Insert(key); err != nil {
@@ -234,10 +245,10 @@ func GetPublicKeyById(keyId int64) (*PublicKey, error) {
return key, nil
}
// ListPublicKey returns a list of all public keys that user has.
func ListPublicKey(uid int64) ([]*PublicKey, error) {
// ListPublicKeys returns a list of public keys belongs to given user.
func ListPublicKeys(uid int64) ([]*PublicKey, error) {
keys := make([]*PublicKey, 0, 5)
err := x.Find(&keys, &PublicKey{OwnerId: uid})
err := x.Where("owner_id=?", uid).Find(&keys)
if err != nil {
return nil, err
}

View File

@@ -133,14 +133,15 @@ func NewRepoContext() {
// Repository represents a git repository.
type Repository struct {
Id int64
OwnerId int64 `xorm:"UNIQUE(s)"`
Owner *User `xorm:"-"`
ForkId int64
LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
Name string `xorm:"INDEX NOT NULL"`
Description string
Website string
Id int64
OwnerId int64 `xorm:"UNIQUE(s)"`
Owner *User `xorm:"-"`
LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
Name string `xorm:"INDEX NOT NULL"`
Description string
Website string
DefaultBranch string
NumWatches int
NumStars int
NumForks int
@@ -154,15 +155,20 @@ type Repository struct {
NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
NumOpenMilestones int `xorm:"-"`
NumTags int `xorm:"-"`
IsPrivate bool
IsMirror bool
*Mirror `xorm:"-"`
IsFork bool `xorm:"NOT NULL DEFAULT false"`
IsBare bool
IsGoget bool
DefaultBranch string
Created time.Time `xorm:"CREATED"`
Updated time.Time `xorm:"UPDATED"`
IsPrivate bool
IsBare bool
IsGoget bool
IsMirror bool
*Mirror `xorm:"-"`
IsFork bool `xorm:"NOT NULL DEFAULT false"`
ForkId int64
ForkRepo *Repository `xorm:"-"`
Created time.Time `xorm:"CREATED"`
Updated time.Time `xorm:"UPDATED"`
}
func (repo *Repository) GetOwner() (err error) {
@@ -177,6 +183,33 @@ func (repo *Repository) GetMirror() (err error) {
return err
}
func (repo *Repository) GetForkRepo() (err error) {
if !repo.IsFork {
return nil
}
repo.ForkRepo, err = GetRepositoryById(repo.ForkId)
return err
}
func (repo *Repository) RepoPath() (string, error) {
if err := repo.GetOwner(); err != nil {
return "", err
}
return RepoPath(repo.Owner.Name, repo.Name), nil
}
func (repo *Repository) RepoLink() (string, error) {
if err := repo.GetOwner(); err != nil {
return "", err
}
return setting.AppSubUrl + "/" + repo.Owner.Name + "/" + repo.Name, nil
}
func (repo *Repository) IsOwnedBy(u *User) bool {
return repo.OwnerId == u.Id
}
func (repo *Repository) HasAccess(uname string) bool {
if err := repo.GetOwner(); err != nil {
return false
@@ -208,9 +241,30 @@ func IsRepositoryExist(u *User, repoName string) (bool, error) {
return com.IsDir(RepoPath(u.Name, repoName)), nil
}
// CloneLink represents different types of clone URLs of repository.
type CloneLink struct {
SSH string
HTTPS string
Git string
}
// CloneLink returns clone URLs of repository.
func (repo *Repository) CloneLink() (cl CloneLink, err error) {
if err = repo.GetOwner(); err != nil {
return cl, err
}
if setting.SshPort != 22 {
cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.Domain, setting.SshPort, repo.Owner.LowerName, repo.LowerName)
} else {
cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.Domain, repo.Owner.LowerName, repo.LowerName)
}
cl.HTTPS = fmt.Sprintf("%s%s/%s.git", setting.AppUrl, repo.Owner.LowerName, repo.LowerName)
return cl, nil
}
var (
illegalEquals = []string{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new"}
illegalSuffixs = []string{".git"}
illegalSuffixs = []string{".git", ".keys"}
)
// IsLegalName returns false if name contains illegal characters.
@@ -275,28 +329,6 @@ func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) er
return nil
}
// MirrorUpdate checks and updates mirror repositories.
func MirrorUpdate() {
if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
m := bean.(*Mirror)
if m.NextUpdate.After(time.Now()) {
return nil
}
repoPath := filepath.Join(setting.RepoRootPath, m.RepoName+".git")
if _, stderr, err := process.ExecDir(10*time.Minute,
repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
"git", "remote", "update"); err != nil {
return errors.New("git remote update: " + stderr)
}
m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
return UpdateMirror(m)
}); err != nil {
log.Error(4, "repo.MirrorUpdate: %v", err)
}
}
// MigrateRepository migrates a existing repository from other project hosting.
func MigrateRepository(u *User, name, desc string, private, mirror bool, url string) (*Repository, error) {
repo, err := CreateRepository(u, name, desc, "", "", private, mirror, false)
@@ -663,7 +695,7 @@ func RepoPath(userName, repoName string) string {
func TransferOwnership(u *User, newOwner string, repo *Repository) error {
newUser, err := GetUserByName(newOwner)
if err != nil {
return err
return fmt.Errorf("fail to get new owner(%s): %v", newOwner, err)
}
// Check if new owner has repository with same name.
@@ -800,6 +832,7 @@ func TransferOwnership(u *User, newOwner string, repo *Repository) error {
// ChangeRepositoryName changes all corresponding setting from old repository name to new one.
func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
newRepoName = strings.ToLower(newRepoName)
if !IsLegalName(newRepoName) {
return ErrRepoNameIllegal
}
@@ -845,7 +878,7 @@ func UpdateRepository(repo *Repository) error {
return err
}
// DeleteRepository deletes a repository for a user or orgnaztion.
// DeleteRepository deletes a repository for a user or organization.
func DeleteRepository(uid, repoId int64, userName string) error {
repo := &Repository{Id: repoId, OwnerId: uid}
has, err := x.Get(repo)
@@ -940,6 +973,13 @@ func DeleteRepository(uid, repoId int64, userName string) error {
return err
}
if repo.IsFork {
if _, err = sess.Exec("UPDATE `repository` SET num_forks = num_forks - 1 WHERE id = ?", repo.ForkId); err != nil {
sess.Rollback()
return err
}
}
if _, err = sess.Exec("UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?", uid); err != nil {
sess.Rollback()
return err
@@ -1040,15 +1080,21 @@ func GetCollaboratorNames(repoName string) ([]string, error) {
return names, nil
}
// CollaborativeRepository represents a repository with collaborative information.
type CollaborativeRepository struct {
*Repository
CanPush bool
}
// GetCollaborativeRepos returns a list of repositories that user is collaborator.
func GetCollaborativeRepos(uname string) ([]*Repository, error) {
func GetCollaborativeRepos(uname string) ([]*CollaborativeRepository, error) {
uname = strings.ToLower(uname)
accesses := make([]*Access, 0, 10)
if err := x.Find(&accesses, &Access{UserName: uname}); err != nil {
return nil, err
}
repos := make([]*Repository, 0, 10)
repos := make([]*CollaborativeRepository, 0, 10)
for _, access := range accesses {
infos := strings.Split(access.RepoName, "/")
if infos[0] == uname {
@@ -1065,7 +1111,7 @@ func GetCollaborativeRepos(uname string) ([]*Repository, error) {
return nil, err
}
repo.Owner = u
repos = append(repos, repo)
repos = append(repos, &CollaborativeRepository{repo, access.Mode == WRITABLE})
}
return repos, nil
}
@@ -1091,17 +1137,11 @@ type SearchOption struct {
Keyword string
Uid int64
Limit int
Private bool
}
// SearchRepositoryByName returns given number of repositories whose name contains keyword.
func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
// Prevent SQL inject.
opt.Keyword = strings.TrimSpace(opt.Keyword)
if len(opt.Keyword) == 0 {
return repos, nil
}
opt.Keyword = strings.Split(opt.Keyword, " ")[0]
if len(opt.Keyword) == 0 {
return repos, nil
}
@@ -1114,10 +1154,106 @@ func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
if opt.Uid > 0 {
sess.Where("owner_id=?", opt.Uid)
}
sess.And("lower_name like '%" + opt.Keyword + "%'").Find(&repos)
if !opt.Private {
sess.And("is_private=false")
}
sess.And("lower_name like ?", "%"+opt.Keyword+"%").Find(&repos)
return repos, err
}
// DeleteRepositoryArchives deletes all repositories' archives.
func DeleteRepositoryArchives() error {
return x.Where("id > 0").Iterate(new(Repository),
func(idx int, bean interface{}) error {
repo := bean.(*Repository)
if err := repo.GetOwner(); err != nil {
return err
}
return os.RemoveAll(filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "archives"))
})
}
var (
// Prevent duplicate tasks.
isMirrorUpdating = false
isGitFscking = false
)
// MirrorUpdate checks and updates mirror repositories.
func MirrorUpdate() {
if isMirrorUpdating {
return
}
isMirrorUpdating = true
defer func() { isMirrorUpdating = false }()
if err := x.Iterate(new(Mirror), func(idx int, bean interface{}) error {
m := bean.(*Mirror)
if m.NextUpdate.After(time.Now()) {
return nil
}
repoPath := filepath.Join(setting.RepoRootPath, m.RepoName+".git")
if _, stderr, err := process.ExecDir(10*time.Minute,
repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath),
"git", "remote", "update"); err != nil {
return errors.New("git remote update: " + stderr)
}
m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
return UpdateMirror(m)
}); err != nil {
log.Error(4, "repo.MirrorUpdate: %v", err)
}
}
// GitFsck calls 'git fsck' to check repository health.
func GitFsck() {
if isGitFscking {
return
}
isGitFscking = true
defer func() { isGitFscking = false }()
args := append([]string{"fsck"}, setting.GitFsckArgs...)
if err := x.Where("id > 0").Iterate(new(Repository),
func(idx int, bean interface{}) error {
repo := bean.(*Repository)
if err := repo.GetOwner(); err != nil {
return err
}
repoPath := RepoPath(repo.Owner.Name, repo.Name)
_, _, err := process.ExecDir(-1, repoPath, "Repository health check", "git", args...)
if err != nil {
desc := fmt.Sprintf("Fail to health check repository(%s)", repoPath)
log.Warn(desc)
if err = CreateRepositoryNotice(desc); err != nil {
log.Error(4, "Fail to add notice: %v", err)
}
}
return nil
}); err != nil {
log.Error(4, "repo.Fsck: %v", err)
}
}
func GitGcRepos() error {
args := append([]string{"gc"}, setting.GitGcArgs...)
return x.Where("id > 0").Iterate(new(Repository),
func(idx int, bean interface{}) error {
repo := bean.(*Repository)
if err := repo.GetOwner(); err != nil {
return err
}
_, stderr, err := process.ExecDir(-1, RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection", "git", args...)
if err != nil {
return fmt.Errorf("%v: %v", err, stderr)
}
return nil
})
}
// __ __ __ .__
// / \ / \_____ _/ |_ ____ | |__
// \ \/\/ /\__ \\ __\/ ___\| | \
@@ -1125,39 +1261,43 @@ func SearchRepositoryByName(opt SearchOption) (repos []*Repository, err error) {
// \__/\ / (____ /__| \___ >___| /
// \/ \/ \/ \/
// Watch is connection request for receiving repository notifycation.
// Watch is connection request for receiving repository notification.
type Watch struct {
Id int64
UserId int64 `xorm:"UNIQUE(watch)"`
RepoId int64 `xorm:"UNIQUE(watch)"`
}
// Watch or unwatch repository.
func WatchRepo(uid, repoId int64, watch bool) (err error) {
// IsWatching checks if user has watched given repository.
func IsWatching(uid, repoId int64) bool {
has, _ := x.Get(&Watch{0, uid, repoId})
return has
}
func watchRepoWithEngine(e Engine, uid, repoId int64, watch bool) (err error) {
if watch {
if IsWatching(uid, repoId) {
return nil
}
if _, err = x.Insert(&Watch{RepoId: repoId, UserId: uid}); err != nil {
if _, err = e.Insert(&Watch{RepoId: repoId, UserId: uid}); err != nil {
return err
}
_, err = x.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
_, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?", repoId)
} else {
if !IsWatching(uid, repoId) {
return nil
}
if _, err = x.Delete(&Watch{0, uid, repoId}); err != nil {
if _, err = e.Delete(&Watch{0, uid, repoId}); err != nil {
return err
}
_, err = x.Exec("UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?", repoId)
_, err = e.Exec("UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?", repoId)
}
return err
}
// IsWatching checks if user has watched given repository.
func IsWatching(uid, rid int64) bool {
has, _ := x.Get(&Watch{0, uid, rid})
return has
// Watch or unwatch repository.
func WatchRepo(uid, repoId int64, watch bool) (err error) {
return watchRepoWithEngine(x, uid, repoId, watch)
}
// GetWatchers returns all watchers of given repository.
@@ -1240,6 +1380,157 @@ func IsStaring(uid, repoId int64) bool {
return has
}
func ForkRepository(repoName string, uid int64) {
// ___________ __
// \_ _____/__________| | __
// | __)/ _ \_ __ \ |/ /
// | \( <_> ) | \/ <
// \___ / \____/|__| |__|_ \
// \/ \/
func ForkRepository(u *User, oldRepo *Repository, name, desc string) (*Repository, error) {
isExist, err := IsRepositoryExist(u, name)
if err != nil {
return nil, err
} else if isExist {
return nil, ErrRepoAlreadyExist
}
// In case the old repository is a fork.
if oldRepo.IsFork {
oldRepo, err = GetRepositoryById(oldRepo.ForkId)
if err != nil {
return nil, err
}
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return nil, err
}
repo := &Repository{
OwnerId: u.Id,
Owner: u,
Name: name,
LowerName: strings.ToLower(name),
Description: desc,
IsPrivate: oldRepo.IsPrivate,
IsFork: true,
ForkId: oldRepo.Id,
}
if _, err = sess.Insert(repo); err != nil {
sess.Rollback()
return nil, err
}
var t *Team // Owner team.
mode := WRITABLE
access := &Access{
UserName: u.LowerName,
RepoName: path.Join(u.LowerName, repo.LowerName),
Mode: mode,
}
// Give access to all members in owner team.
if u.IsOrganization() {
t, err = u.GetOwnerTeam()
if err != nil {
sess.Rollback()
return nil, err
}
if err = t.GetMembers(); err != nil {
sess.Rollback()
return nil, err
}
for _, u := range t.Members {
access.Id = 0
access.UserName = u.LowerName
if _, err = sess.Insert(access); err != nil {
sess.Rollback()
return nil, err
}
}
} else {
if _, err = sess.Insert(access); err != nil {
sess.Rollback()
return nil, err
}
}
if _, err = sess.Exec(
"UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?", u.Id); err != nil {
sess.Rollback()
return nil, err
}
// Update owner team info and count.
if u.IsOrganization() {
t.RepoIds += "$" + com.ToStr(repo.Id) + "|"
t.NumRepos++
if _, err = sess.Id(t.Id).AllCols().Update(t); err != nil {
sess.Rollback()
return nil, err
}
}
if u.IsOrganization() {
t, err := u.GetOwnerTeam()
if err != nil {
log.Error(4, "GetOwnerTeam: %v", err)
} else {
if err = t.GetMembers(); err != nil {
log.Error(4, "GetMembers: %v", err)
} else {
for _, u := range t.Members {
if err = watchRepoWithEngine(sess, u.Id, repo.Id, true); err != nil {
log.Error(4, "WatchRepo2: %v", err)
}
}
}
}
} else {
if err = watchRepoWithEngine(sess, u.Id, repo.Id, true); err != nil {
log.Error(4, "WatchRepo3: %v", err)
}
}
if err = NewRepoAction(u, repo); err != nil {
log.Error(4, "NewRepoAction: %v", err)
}
if _, err = sess.Exec(
"UPDATE `repository` SET num_forks = num_forks + 1 WHERE id = ?", oldRepo.Id); err != nil {
sess.Rollback()
return nil, err
}
oldRepoPath, err := oldRepo.RepoPath()
if err != nil {
sess.Rollback()
return nil, fmt.Errorf("fail to get repo path(%s): %v", oldRepo.Name, err)
}
if err = sess.Commit(); err != nil {
return nil, err
}
repoPath := RepoPath(u.Name, repo.Name)
_, stderr, err := process.ExecTimeout(10*time.Minute,
fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
"git", "clone", "--bare", oldRepoPath, repoPath)
if err != nil {
return nil, errors.New("ForkRepository(git clone): " + stderr)
}
_, stderr, err = process.ExecDir(-1,
repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
"git", "update-server-info")
if err != nil {
return nil, errors.New("ForkRepository(git update-server-info): " + stderr)
}
return repo, nil
}

View File

@@ -16,8 +16,6 @@ const (
)
type Slack struct {
Domain string `json:"domain"`
Token string `json:"token"`
Channel string `json:"channel"`
}
@@ -36,14 +34,6 @@ type SlackAttachment struct {
Text string `json:"text"`
}
func GetSlackURL(domain string, token string) string {
return fmt.Sprintf(
"https://%s.slack.com/services/hooks/incoming-webhook?token=%s",
domain,
token,
)
}
func (p SlackPayload) GetJSONPayload() ([]byte, error) {
data, err := json.Marshal(p)
if err != nil {

69
models/token.go Normal file
View File

@@ -0,0 +1,69 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
"errors"
"time"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/uuid"
)
var (
ErrAccessTokenNotExist = errors.New("Access token does not exist")
)
// AccessToken represents a personal access token.
type AccessToken struct {
Id int64
Uid int64
Name string
Sha1 string `xorm:"UNIQUE VARCHAR(40)"`
Created time.Time `xorm:"CREATED"`
Updated time.Time
HasRecentActivity bool `xorm:"-"`
HasUsed bool `xorm:"-"`
}
// NewAccessToken creates new access token.
func NewAccessToken(t *AccessToken) error {
t.Sha1 = base.EncodeSha1(uuid.NewV4().String())
_, err := x.Insert(t)
return err
}
// GetAccessTokenBySha returns access token by given sha1.
func GetAccessTokenBySha(sha string) (*AccessToken, error) {
t := &AccessToken{Sha1: sha}
has, err := x.Get(t)
if err != nil {
return nil, err
} else if !has {
return nil, ErrAccessTokenNotExist
}
return t, nil
}
// ListAccessTokens returns a list of access tokens belongs to given user.
func ListAccessTokens(uid int64) ([]*AccessToken, error) {
tokens := make([]*AccessToken, 0, 5)
err := x.Where("uid=?", uid).Desc("id").Find(&tokens)
if err != nil {
return nil, err
}
for _, t := range tokens {
t.HasUsed = t.Updated.After(t.Created)
t.HasRecentActivity = t.Updated.Add(7 * 24 * time.Hour).After(time.Now())
}
return tokens, nil
}
// DeleteAccessTokenById deletes access token by given ID.
func DeleteAccessTokenById(id int64) error {
_, err := x.Id(id).Delete(new(AccessToken))
return err
}

View File

@@ -106,7 +106,7 @@ func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName
if err = CommitRepoAction(userId, ru.Id, userName, actEmail,
repos.Id, repoUserName, repoName, refName, commit, oldCommitId, newCommitId); err != nil {
log.GitLogger.Fatal(4, "runUpdate.models.CommitRepoAction: %s/%s:%v", repoUserName, repoName, err)
log.GitLogger.Fatal(4, "CommitRepoAction: %s/%s:%v", repoUserName, repoName, err)
}
return err
}
@@ -116,8 +116,8 @@ func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName
return fmt.Errorf("runUpdate GetCommit of newCommitId: %v", err)
}
// Push new branch.
var l *list.List
// if a new branch
if isNew {
l, err = newCommit.CommitsBefore()
if err != nil {
@@ -134,7 +134,7 @@ func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName
return fmt.Errorf("runUpdate.Commit repoId: %v", err)
}
// if commits push
// Push commits.
commits := make([]*base.PushCommit, 0)
var actEmail string
for e := l.Front(); e != nil; e = e.Next() {
@@ -153,9 +153,8 @@ func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName
}
}
//commits = append(commits, []string{lastCommit.Id().String(), lastCommit.Message()})
if err = CommitRepoAction(userId, ru.Id, userName, actEmail,
repos.Id, repoUserName, repoName, refName, &base.PushCommits{l.Len(), commits}, oldCommitId, newCommitId); err != nil {
repos.Id, repoUserName, repoName, refName, &base.PushCommits{l.Len(), commits, ""}, oldCommitId, newCommitId); err != nil {
return fmt.Errorf("runUpdate.models.CommitRepoAction: %s/%s:%v", repoUserName, repoName, err)
}
return nil

View File

@@ -5,18 +5,23 @@
package models
import (
"bytes"
"container/list"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"image"
"image/jpeg"
"os"
"path/filepath"
"strings"
"time"
"github.com/Unknwon/com"
"github.com/nfnt/resize"
"github.com/gogits/gogs/modules/avatar"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/git"
"github.com/gogits/gogs/modules/log"
@@ -45,32 +50,40 @@ var (
// User represents the object of individual and member of organization.
type User struct {
Id int64
LowerName string `xorm:"UNIQUE NOT NULL"`
Name string `xorm:"UNIQUE NOT NULL"`
FullName string
Email string `xorm:"UNIQUE NOT NULL"`
Passwd string `xorm:"NOT NULL"`
LoginType LoginType
LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
LoginName string
Type UserType
Orgs []*User `xorm:"-"`
Repos []*Repository `xorm:"-"`
Id int64
LowerName string `xorm:"UNIQUE NOT NULL"`
Name string `xorm:"UNIQUE NOT NULL"`
FullName string
Email string `xorm:"UNIQUE(s) NOT NULL"`
Passwd string `xorm:"NOT NULL"`
LoginType LoginType
LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
LoginName string
Type UserType `xorm:"UNIQUE(s)"`
Orgs []*User `xorm:"-"`
Repos []*Repository `xorm:"-"`
Location string
Website string
Rands string `xorm:"VARCHAR(10)"`
Salt string `xorm:"VARCHAR(10)"`
Created time.Time `xorm:"CREATED"`
Updated time.Time `xorm:"UPDATED"`
// Permissions.
IsActive bool
IsAdmin bool
AllowGitHook bool
// Avatar.
Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
AvatarEmail string `xorm:"NOT NULL"`
UseCustomAvatar bool
// Counters.
NumFollowers int
NumFollowings int
NumStars int
NumRepos int
Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
AvatarEmail string `xorm:"NOT NULL"`
Location string
Website string
IsActive bool
IsAdmin bool
Rands string `xorm:"VARCHAR(10)"`
Salt string `xorm:"VARCHAR(10)"`
Created time.Time `xorm:"CREATED"`
Updated time.Time `xorm:"UPDATED"`
// For organization.
Description string
@@ -95,12 +108,15 @@ func (u *User) HomeLink() string {
// AvatarLink returns user gravatar link.
func (u *User) AvatarLink() string {
if setting.DisableGravatar {
switch {
case u.UseCustomAvatar:
return setting.AppSubUrl + "/avatars/" + com.ToStr(u.Id)
case setting.DisableGravatar:
return setting.AppSubUrl + "/img/avatar_default.jpg"
} else if setting.Service.EnableCacheAvatar {
case setting.Service.EnableCacheAvatar:
return setting.AppSubUrl + "/avatar/" + u.Avatar
}
return "//1.gravatar.com/avatar/" + u.Avatar
return setting.GravatarSource + u.Avatar
}
// NewGitSig generates and returns the signature of given user.
@@ -125,6 +141,48 @@ func (u *User) ValidtePassword(passwd string) bool {
return u.Passwd == newUser.Passwd
}
// CustomAvatarPath returns user custom avatar file path.
func (u *User) CustomAvatarPath() string {
return filepath.Join(setting.AvatarUploadPath, com.ToStr(u.Id))
}
// UploadAvatar saves custom avatar for user.
// FIXME: split uploads to different subdirs in case we have massive users.
func (u *User) UploadAvatar(data []byte) error {
u.UseCustomAvatar = true
img, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return err
}
m := resize.Resize(200, 200, img, resize.NearestNeighbor)
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.Id(u.Id).AllCols().Update(u); err != nil {
sess.Rollback()
return err
}
os.MkdirAll(setting.AvatarUploadPath, os.ModePerm)
fw, err := os.Create(u.CustomAvatarPath())
if err != nil {
sess.Rollback()
return err
}
defer fw.Close()
if err = jpeg.Encode(fw, m, nil); err != nil {
sess.Rollback()
return err
}
return sess.Commit()
}
// IsOrganization returns true if user is actually a organization.
func (u *User) IsOrganization() bool {
return u.Type == ORGANIZATION
@@ -193,7 +251,7 @@ func IsEmailUsed(email string) (bool, error) {
return x.Get(&User{Email: email})
}
// GetUserSalt returns a user salt token
// GetUserSalt returns a ramdom user salt token.
func GetUserSalt() string {
return base.GetRandomString(10)
}
@@ -219,8 +277,8 @@ func CreateUser(u *User) error {
}
u.LowerName = strings.ToLower(u.Name)
u.Avatar = base.EncodeMd5(u.Email)
u.AvatarEmail = u.Email
u.Avatar = avatar.HashEmail(u.AvatarEmail)
u.Rands = GetUserSalt()
u.Salt = GetUserSalt()
u.EncodePasswd()
@@ -360,6 +418,13 @@ func ChangeUserName(u *User, newUserName string) (err error) {
// UpdateUser updates user's information.
func UpdateUser(u *User) error {
has, err := x.Where("id != ?", u.Id).And("email = ?", u.Email).Get(new(User))
if err != nil {
return err
} else if has {
return ErrEmailAlreadyUsed
}
u.LowerName = strings.ToLower(u.Name)
if len(u.Location) > 255 {
@@ -372,11 +437,16 @@ func UpdateUser(u *User) error {
u.Description = u.Description[:255]
}
_, err := x.Id(u.Id).AllCols().Update(u)
if u.AvatarEmail == "" {
u.AvatarEmail = u.Email
}
u.Avatar = avatar.HashEmail(u.AvatarEmail)
_, err = x.Id(u.Id).AllCols().Update(u)
return err
}
// TODO: need some kind of mechanism to record failure.
// FIXME: need some kind of mechanism to record failure. HINT: system notice
// DeleteUser completely and permanently deletes everything of user.
func DeleteUser(u *User) error {
// Check ownership of repository.
@@ -390,13 +460,13 @@ func DeleteUser(u *User) error {
// Check membership of organization.
count, err = u.GetOrganizationCount()
if err != nil {
return errors.New("modesl.GetRepositories(GetOrganizationCount): " + err.Error())
return errors.New("GetOrganizationCount: " + err.Error())
} else if count > 0 {
return ErrUserHasOrgs
}
// TODO: check issues, other repos' commits
// TODO: roll backable in some point.
// FIXME: check issues, other repos' commits
// FIXME: roll backable in some point.
// Delete all followers.
if _, err = x.Delete(&Follow{FollowId: u.Id}); err != nil {
@@ -473,22 +543,22 @@ func GetUserById(id int64) (*User, error) {
return u, nil
}
// GetUserByName returns the user object by given name if exists.
// GetUserByName returns user by given name.
func GetUserByName(name string) (*User, error) {
if len(name) == 0 {
return nil, ErrUserNotExist
}
user := &User{LowerName: strings.ToLower(name)}
has, err := x.Get(user)
u := &User{LowerName: strings.ToLower(name)}
has, err := x.Get(u)
if err != nil {
return nil, err
} else if !has {
return nil, ErrUserNotExist
}
return user, nil
return u, nil
}
// GetUserEmailsByNames returns a slice of e-mails corresponds to names.
// GetUserEmailsByNames returns a list of e-mails corresponds to names.
func GetUserEmailsByNames(names []string) []string {
mails := make([]string, 0, len(names))
for _, name := range names {
@@ -514,43 +584,40 @@ func GetUserIdsByNames(names []string) []int64 {
return ids
}
// UserCommit represtns a commit with validation of user.
// UserCommit represents a commit with validation of user.
type UserCommit struct {
UserName string
User *User
*git.Commit
}
// ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
func ValidateCommitWithEmail(c *git.Commit) (uname string) {
func ValidateCommitWithEmail(c *git.Commit) *User {
u, err := GetUserByEmail(c.Author.Email)
if err == nil {
uname = u.Name
if err != nil {
return nil
}
return uname
return u
}
// ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
emails := map[string]string{}
emails := map[string]*User{}
newCommits := list.New()
e := oldCommits.Front()
for e != nil {
c := e.Value.(*git.Commit)
uname := ""
var u *User
if v, ok := emails[c.Author.Email]; !ok {
u, err := GetUserByEmail(c.Author.Email)
if err == nil {
uname = u.Name
}
emails[c.Author.Email] = uname
u, _ = GetUserByEmail(c.Author.Email)
emails[c.Author.Email] = u
} else {
uname = v
u = v
}
newCommits.PushBack(UserCommit{
UserName: uname,
Commit: c,
User: u,
Commit: c,
})
e = e.Next()
}
@@ -574,24 +641,17 @@ func GetUserByEmail(email string) (*User, error) {
// SearchUserByName returns given number of users whose name contains keyword.
func SearchUserByName(opt SearchOption) (us []*User, err error) {
// Prevent SQL inject.
opt.Keyword = strings.TrimSpace(opt.Keyword)
if len(opt.Keyword) == 0 {
return us, nil
}
opt.Keyword = strings.Split(opt.Keyword, " ")[0]
if len(opt.Keyword) == 0 {
return us, nil
}
opt.Keyword = strings.ToLower(opt.Keyword)
us = make([]*User, 0, opt.Limit)
err = x.Limit(opt.Limit).Where("type=0").And("lower_name like '%" + opt.Keyword + "%'").Find(&us)
err = x.Limit(opt.Limit).Where("type=0").And("lower_name like ?", "%"+opt.Keyword+"%").Find(&us)
return us, err
}
// Follow is connection request for receiving user notifycation.
// Follow is connection request for receiving user notification.
type Follow struct {
Id int64
UserId int64 `xorm:"unique(follow)"`

View File

@@ -27,6 +27,32 @@ const (
FORM
)
var hookContentTypes = map[string]HookContentType{
"json": JSON,
"form": FORM,
}
// ToHookContentType returns HookContentType by given name.
func ToHookContentType(name string) HookContentType {
return hookContentTypes[name]
}
func (t HookContentType) Name() string {
switch t {
case JSON:
return "json"
case FORM:
return "form"
}
return ""
}
// IsValidHookContentType returns true if given name is a valid hook content type.
func IsValidHookContentType(name string) bool {
_, ok := hookContentTypes[name]
return ok
}
// HookEvent represents events that will delivery hook.
type HookEvent struct {
PushOnly bool `json:"push_only"`
@@ -46,6 +72,8 @@ type Webhook struct {
HookTaskType HookTaskType
Meta string `xorm:"TEXT"` // store hook-specific attributes
OrgId int64
Created time.Time `xorm:"CREATED"`
Updated time.Time `xorm:"UPDATED"`
}
// GetEvent handles conversion from Events to HookEvent.
@@ -71,7 +99,7 @@ func (w *Webhook) UpdateEvent() error {
return err
}
// HasPushEvent returns true if hook enbaled push event.
// HasPushEvent returns true if hook enabled push event.
func (w *Webhook) HasPushEvent() bool {
if w.PushOnly {
return true
@@ -147,12 +175,39 @@ const (
SLACK
)
var hookTaskTypes = map[string]HookTaskType{
"gogs": GOGS,
"slack": SLACK,
}
// ToHookTaskType returns HookTaskType by given name.
func ToHookTaskType(name string) HookTaskType {
return hookTaskTypes[name]
}
func (t HookTaskType) Name() string {
switch t {
case GOGS:
return "gogs"
case SLACK:
return "slack"
}
return ""
}
// IsValidHookTaskType returns true if given name is a valid hook task type.
func IsValidHookTaskType(name string) bool {
_, ok := hookTaskTypes[name]
return ok
}
type HookEventType string
const (
PUSH HookEventType = "push"
)
// FIXME: just use go-gogs-client structs maybe?
type PayloadAuthor struct {
Name string `json:"name"`
Email string `json:"email"`

View File

@@ -6,22 +6,22 @@ package auth
import (
"github.com/Unknwon/macaron"
"github.com/macaron-contrib/i18n"
"github.com/gogits/gogs/modules/middleware/binding"
"github.com/macaron-contrib/binding"
)
type AdminEditUserForm struct {
Email string `form:"email" binding:"Required;Email;MaxSize(50)"`
Passwd string `form:"password"`
Website string `form:"website" binding:"MaxSize(50)"`
Location string `form:"location" binding:"MaxSize(50)"`
Avatar string `form:"avatar" binding:"Required;Email;MaxSize(50)"`
Active bool `form:"active"`
Admin bool `form:"admin"`
LoginType int `form:"login_type"`
Email string `form:"email" binding:"Required;Email;MaxSize(50)"`
Passwd string `form:"password"`
Website string `form:"website" binding:"MaxSize(50)"`
Location string `form:"location" binding:"MaxSize(50)"`
Avatar string `form:"avatar" binding:"Required;Email;MaxSize(50)"`
Active bool `form:"active"`
Admin bool `form:"admin"`
AllowGitHook bool `form:"allow_git_hook"`
LoginType int `form:"login_type"`
}
func (f *AdminEditUserForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *AdminEditUserForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}

View File

@@ -8,31 +8,24 @@ import (
"reflect"
"github.com/Unknwon/macaron"
"github.com/macaron-contrib/i18n"
"github.com/macaron-contrib/binding"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/middleware/binding"
)
type MarkdownForm struct {
Text string `form:"text" binding:"Required"`
Text string `form:"text"`
Mode string `form:"mode"`
Context string `form:"context"`
}
func (f *MarkdownForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validateApiReq(errs, ctx.Data, f, l)
func (f *MarkdownForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validateApiReq(errs, ctx.Data, f)
}
func validateApiReq(errs *binding.Errors, data map[string]interface{}, f interface{}, l i18n.Locale) {
if errs.Count() == 0 {
return
} else if len(errs.Overall) > 0 {
for _, err := range errs.Overall {
log.Error(4, "%s: %v", reflect.TypeOf(f), err)
}
return
func validateApiReq(errs binding.Errors, data map[string]interface{}, f auth.Form) binding.Errors {
if errs.Len() == 0 {
return errs
}
data["HasError"] = true
@@ -54,26 +47,27 @@ func validateApiReq(errs *binding.Errors, data map[string]interface{}, f interfa
continue
}
if err, ok := errs.Fields[field.Name]; ok {
switch err {
case binding.BindingRequireError:
if errs[0].FieldNames[0] == field.Name {
switch errs[0].Classification {
case binding.RequiredError:
data["ErrorMsg"] = fieldName + " cannot be empty"
case binding.BindingAlphaDashError:
case binding.AlphaDashError:
data["ErrorMsg"] = fieldName + " must be valid alpha or numeric or dash(-_) characters"
case binding.BindingAlphaDashDotError:
case binding.AlphaDashDotError:
data["ErrorMsg"] = fieldName + " must be valid alpha or numeric or dash(-_) or dot characters"
case binding.BindingMinSizeError:
case binding.MinSizeError:
data["ErrorMsg"] = fieldName + " must contain at least " + auth.GetMinSize(field) + " characters"
case binding.BindingMaxSizeError:
case binding.MaxSizeError:
data["ErrorMsg"] = fieldName + " must contain at most " + auth.GetMaxSize(field) + " characters"
case binding.BindingEmailError:
case binding.EmailError:
data["ErrorMsg"] = fieldName + " is not a valid e-mail address"
case binding.BindingUrlError:
case binding.UrlError:
data["ErrorMsg"] = fieldName + " is not a valid URL"
default:
data["ErrorMsg"] = "Unknown error: " + err
data["ErrorMsg"] = "Unknown error: " + errs[0].Classification
}
return
return errs
}
}
return errs
}

View File

@@ -9,32 +9,38 @@ import (
"reflect"
"strings"
"github.com/macaron-contrib/i18n"
"github.com/Unknwon/macaron"
"github.com/macaron-contrib/binding"
"github.com/macaron-contrib/session"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/middleware/binding"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/modules/uuid"
)
// SignedInId returns the id of signed in user.
func SignedInId(header http.Header, sess session.Store) int64 {
func SignedInId(req *http.Request, sess session.Store) int64 {
if !models.HasEngine {
return 0
}
if setting.Service.EnableReverseProxyAuth {
webAuthUser := header.Get(setting.ReverseProxyAuthUser)
if len(webAuthUser) > 0 {
u, err := models.GetUserByName(webAuthUser)
if err != nil {
if err != models.ErrUserNotExist {
log.Error(4, "GetUserByName: %v", err)
// API calls need to check access token.
if strings.HasPrefix(req.URL.Path, "/api/") {
auHead := req.Header.Get("Authorization")
if len(auHead) > 0 {
auths := strings.Fields(auHead)
if len(auths) == 2 && auths[0] == "token" {
t, err := models.GetAccessTokenBySha(auths[1])
if err != nil {
if err != models.ErrAccessTokenNotExist {
log.Error(4, "GetAccessTokenBySha: %v", err)
}
return 0
}
return 0
return t.Uid
}
return u.Id
}
}
@@ -55,18 +61,78 @@ func SignedInId(header http.Header, sess session.Store) int64 {
}
// SignedInUser returns the user object of signed user.
func SignedInUser(header http.Header, sess session.Store) *models.User {
uid := SignedInId(header, sess)
// It returns a bool value to indicate whether user uses basic auth or not.
func SignedInUser(req *http.Request, sess session.Store) (*models.User, bool) {
if !models.HasEngine {
return nil, false
}
uid := SignedInId(req, sess)
if uid <= 0 {
return nil
if setting.Service.EnableReverseProxyAuth {
webAuthUser := req.Header.Get(setting.ReverseProxyAuthUser)
if len(webAuthUser) > 0 {
u, err := models.GetUserByName(webAuthUser)
if err != nil {
if err != models.ErrUserNotExist {
log.Error(4, "GetUserByName: %v", err)
return nil, false
}
// Check if enabled auto-registration.
if setting.Service.EnableReverseProxyAutoRegister {
u := &models.User{
Name: webAuthUser,
Email: uuid.NewV4().String() + "@localhost",
Passwd: webAuthUser,
IsActive: true,
}
if err = models.CreateUser(u); err != nil {
// FIXME: should I create a system notice?
log.Error(4, "CreateUser: %v", err)
return nil, false
} else {
return u, false
}
}
}
return u, false
}
}
// Check with basic auth.
baHead := req.Header.Get("Authorization")
if len(baHead) > 0 {
auths := strings.Fields(baHead)
if len(auths) == 2 && auths[0] == "Basic" {
uname, passwd, _ := base.BasicAuthDecode(auths[1])
u, err := models.GetUserByName(uname)
if err != nil {
if err != models.ErrUserNotExist {
log.Error(4, "GetUserByName: %v", err)
}
return nil, false
}
if u.ValidtePassword(passwd) {
return u, true
}
}
}
return nil, false
}
u, err := models.GetUserById(uid)
if err != nil {
log.Error(4, "GetUserById: %v", err)
return nil
return nil, false
}
return u
return u, false
}
type Form interface {
binding.Validator
}
// AssignForm assign form values back to the template data.
@@ -109,14 +175,9 @@ func GetMaxSize(field reflect.StructField) string {
return getSize(field, "MaxSize(")
}
func validate(errs *binding.Errors, data map[string]interface{}, f interface{}, l i18n.Locale) {
if errs.Count() == 0 {
return
} else if len(errs.Overall) > 0 {
for _, err := range errs.Overall {
log.Error(4, "%s: %v", reflect.TypeOf(f), err)
}
return
func validate(errs binding.Errors, data map[string]interface{}, f Form, l macaron.Locale) binding.Errors {
if errs.Len() == 0 {
return errs
}
data["HasError"] = true
@@ -139,28 +200,29 @@ func validate(errs *binding.Errors, data map[string]interface{}, f interface{},
continue
}
if err, ok := errs.Fields[field.Name]; ok {
if errs[0].FieldNames[0] == field.Name {
data["Err_"+field.Name] = true
trName := l.Tr("form." + field.Name)
switch err {
case binding.BindingRequireError:
switch errs[0].Classification {
case binding.RequiredError:
data["ErrorMsg"] = trName + l.Tr("form.require_error")
case binding.BindingAlphaDashError:
case binding.AlphaDashError:
data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_error")
case binding.BindingAlphaDashDotError:
case binding.AlphaDashDotError:
data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_error")
case binding.BindingMinSizeError:
case binding.MinSizeError:
data["ErrorMsg"] = trName + l.Tr("form.min_size_error", GetMinSize(field))
case binding.BindingMaxSizeError:
case binding.MaxSizeError:
data["ErrorMsg"] = trName + l.Tr("form.max_size_error", GetMaxSize(field))
case binding.BindingEmailError:
case binding.EmailError:
data["ErrorMsg"] = trName + l.Tr("form.email_error")
case binding.BindingUrlError:
case binding.UrlError:
data["ErrorMsg"] = trName + l.Tr("form.url_error")
default:
data["ErrorMsg"] = l.Tr("form.unknown_error") + " " + err
data["ErrorMsg"] = l.Tr("form.unknown_error") + " " + errs[0].Classification
}
return
return errs
}
}
return errs
}

View File

@@ -6,9 +6,7 @@ package auth
import (
"github.com/Unknwon/macaron"
"github.com/macaron-contrib/i18n"
"github.com/gogits/gogs/modules/middleware/binding"
"github.com/macaron-contrib/binding"
)
type AuthenticationForm struct {
@@ -31,6 +29,6 @@ type AuthenticationForm struct {
AllowAutoRegister bool `form:"allowautoregister"`
}
func (f *AuthenticationForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *AuthenticationForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}

View File

@@ -20,7 +20,7 @@ type Ldapsource struct {
Port int // port number
UseSSL bool // Use SSL
BaseDN string // Base DN
Attributes string // Attribut to search
Attributes string // Attribute to search
Filter string // Query filter to validate entry
MsAdSAFormat string // in the case of MS AD Simple Authen, the format to use (see: http://msdn.microsoft.com/en-us/library/cc223499.aspx)
Enabled bool // if this source is disabled
@@ -37,7 +37,7 @@ func AddSource(name string, host string, port int, usessl bool, basedn string, a
Authensource = append(Authensource, ldaphost)
}
//LoginUser : try to login an user to LDAP sources, return requested (attribut,true) if ok, ("",false) other wise
//LoginUser : try to login an user to LDAP sources, return requested (attribute,true) if ok, ("",false) other wise
//First match wins
//Returns first attribute if exists
func LoginUser(name, passwd string) (a string, r bool) {

View File

@@ -6,9 +6,7 @@ package auth
import (
"github.com/Unknwon/macaron"
"github.com/macaron-contrib/i18n"
"github.com/gogits/gogs/modules/middleware/binding"
"github.com/macaron-contrib/binding"
)
// ________ .__ __ .__
@@ -23,8 +21,8 @@ type CreateOrgForm struct {
Email string `form:"email" binding:"Required;Email;MaxSize(50)"`
}
func (f *CreateOrgForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *CreateOrgForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type UpdateOrgSettingForm struct {
@@ -37,8 +35,8 @@ type UpdateOrgSettingForm struct {
Avatar string `form:"avatar" binding:"Required;Email;MaxSize(50)"`
}
func (f *UpdateOrgSettingForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *UpdateOrgSettingForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// ___________
@@ -54,6 +52,6 @@ type CreateTeamForm struct {
Permission string `form:"permission"`
}
func (f *CreateTeamForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *CreateTeamForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}

View File

@@ -1,21 +0,0 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package auth
import (
"github.com/Unknwon/macaron"
"github.com/macaron-contrib/i18n"
"github.com/gogits/gogs/modules/middleware/binding"
)
type AddSSHKeyForm struct {
SSHTitle string `form:"title" binding:"Required"`
Content string `form:"content" binding:"Required"`
}
func (f *AddSSHKeyForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
}

View File

@@ -6,9 +6,7 @@ package auth
import (
"github.com/Unknwon/macaron"
"github.com/macaron-contrib/i18n"
"github.com/gogits/gogs/modules/middleware/binding"
"github.com/macaron-contrib/binding"
)
// _______________________________________ _________.______________________ _______________.___.
@@ -23,13 +21,13 @@ type CreateRepoForm struct {
RepoName string `form:"repo_name" binding:"Required;AlphaDashDot;MaxSize(100)"`
Private bool `form:"private"`
Description string `form:"desc" binding:"MaxSize(255)"`
AutoInit bool `form:"auto_init"`
Gitignore string `form:"gitignore"`
License string `form:"license"`
InitReadme bool `form:"init_readme"`
}
func (f *CreateRepoForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *CreateRepoForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type MigrateRepoForm struct {
@@ -43,8 +41,8 @@ type MigrateRepoForm struct {
Description string `form:"desc" binding:"MaxSize(255)"`
}
func (f *MigrateRepoForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *MigrateRepoForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type RepoSettingForm struct {
@@ -57,8 +55,8 @@ type RepoSettingForm struct {
GoGet bool `form:"goget"`
}
func (f *RepoSettingForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *RepoSettingForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// __ __ ___. .__ .__ __
@@ -77,21 +75,20 @@ type NewWebhookForm struct {
Active bool `form:"active"`
}
func (f *NewWebhookForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *NewWebhookForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type NewSlackHookForm struct {
HookTaskType string `form:"hook_type" binding:"Required"`
Domain string `form:"domain" binding:"Required`
Token string `form:"token" binding:"Required"`
PayloadUrl string `form:"payload_url" binding:"Required`
Channel string `form:"channel" binding:"Required"`
PushOnly bool `form:"push_only"`
Active bool `form:"active"`
}
func (f *NewSlackHookForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *NewSlackHookForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// .___
@@ -109,8 +106,8 @@ type CreateIssueForm struct {
Content string `form:"content"`
}
func (f *CreateIssueForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *CreateIssueForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// _____ .__.__ __
@@ -126,8 +123,8 @@ type CreateMilestoneForm struct {
Deadline string `form:"due_date"`
}
func (f *CreateMilestoneForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *CreateMilestoneForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// .____ ___. .__
@@ -142,8 +139,8 @@ type CreateLabelForm struct {
Color string `form:"color" binding:"Required;Size(7)"`
}
func (f *CreateLabelForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *CreateLabelForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// __________ .__
@@ -162,18 +159,17 @@ type NewReleaseForm struct {
Prerelease bool `form:"prerelease"`
}
func (f *NewReleaseForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *NewReleaseForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type EditReleaseForm struct {
Target string `form:"tag_target" binding:"Required"`
Title string `form:"title" binding:"Required"`
Content string `form:"content" binding:"Required"`
Draft string `form:"draft"`
Prerelease bool `form:"prerelease"`
}
func (f *EditReleaseForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *EditReleaseForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}

View File

@@ -5,10 +5,10 @@
package auth
import (
"github.com/Unknwon/macaron"
"github.com/macaron-contrib/i18n"
"mime/multipart"
"github.com/gogits/gogs/modules/middleware/binding"
"github.com/Unknwon/macaron"
"github.com/macaron-contrib/binding"
)
type InstallForm struct {
@@ -34,8 +34,8 @@ type InstallForm struct {
AdminEmail string `form:"admin_email" binding:"Required;Email;MaxSize(50)"`
}
func (f *InstallForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *InstallForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// _____ ____ _________________ ___
@@ -54,8 +54,8 @@ type RegisterForm struct {
LoginName string `form:"loginname"`
}
func (f *RegisterForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *RegisterForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type SignInForm struct {
@@ -64,8 +64,8 @@ type SignInForm struct {
Remember bool `form:"remember"`
}
func (f *SignInForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *SignInForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
// __________________________________________.___ _______ ________ _________
@@ -84,8 +84,17 @@ type UpdateProfileForm struct {
Avatar string `form:"avatar" binding:"Required;Email;MaxSize(50)"`
}
func (f *UpdateProfileForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *UpdateProfileForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type UploadAvatarForm struct {
Enable bool `form:"enable"`
Avatar *multipart.FileHeader `form:"avatar"`
}
func (f *UploadAvatarForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type ChangePasswordForm struct {
@@ -94,6 +103,23 @@ type ChangePasswordForm struct {
Retype string `form:"retype"`
}
func (f *ChangePasswordForm) Validate(ctx *macaron.Context, errs *binding.Errors, l i18n.Locale) {
validate(errs, ctx.Data, f, l)
func (f *ChangePasswordForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type AddSSHKeyForm struct {
SSHTitle string `form:"title" binding:"Required"`
Content string `form:"content" binding:"Required"`
}
func (f *AddSSHKeyForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}
type NewAccessTokenForm struct {
Name string `form:"name" binding:"Required"`
}
func (f *NewAccessTokenForm) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
return validate(errs, ctx.Data, f, ctx.Locale)
}

View File

@@ -33,17 +33,27 @@ import (
"github.com/nfnt/resize"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)
var (
gravatar = "http://www.gravatar.com/avatar"
)
var gravatarSource string
func init() {
gravatarSource = setting.GravatarSource
if !strings.HasPrefix(gravatarSource, "http:") {
gravatarSource = "http:" + gravatarSource
}
}
// hash email to md5 string
// keep this func in order to make this package indenpent
// keep this func in order to make this package independent
func HashEmail(email string) string {
// https://en.gravatar.com/site/implement/hash/
email = strings.TrimSpace(email)
email = strings.ToLower(email)
h := md5.New()
h.Write([]byte(strings.ToLower(email)))
h.Write([]byte(email))
return hex.EncodeToString(h.Sum(nil))
}
@@ -115,13 +125,13 @@ func (this *Avatar) Encode(wr io.Writer, size int) (err error) {
if img, err = decodeImageFile(imgPath); err != nil {
return
}
m := resize.Resize(uint(size), 0, img, resize.Lanczos3)
m := resize.Resize(uint(size), 0, img, resize.NearestNeighbor)
return jpeg.Encode(wr, m, nil)
}
// get image from gravatar.com
func (this *Avatar) Update() {
thunder.Fetch(gravatar+"/"+this.Hash+"?"+this.reqParams,
thunder.Fetch(gravatarSource+this.Hash+"?"+this.reqParams,
this.imagePath)
}
@@ -129,7 +139,7 @@ func (this *Avatar) UpdateTimeout(timeout time.Duration) (err error) {
select {
case <-time.After(timeout):
err = fmt.Errorf("get gravatar image %s timeout", this.Hash)
case err = <-thunder.GoFetch(gravatar+"/"+this.Hash+"?"+this.reqParams,
case err = <-thunder.GoFetch(gravatarSource+this.Hash+"?"+this.reqParams,
this.imagePath):
}
return err

View File

@@ -4,12 +4,14 @@
package base
const DOC_URL = "http://gogs.io/docs"
type (
TplName string
ApiJsonErr struct {
Message string `json:"message"`
DocUrl string `json:"documentation_url"`
DocUrl string `json:"url"`
}
)

View File

@@ -91,11 +91,20 @@ func (options *CustomRender) Link(out *bytes.Buffer, link []byte, title []byte,
options.Renderer.Link(out, link, title, content)
}
func (options *CustomRender) Image(out *bytes.Buffer, link []byte, title []byte, alt []byte) {
if len(link) > 0 && !isLink(link) {
link = []byte(path.Join(strings.Replace(options.urlPrefix, "/src/", "/raw/", 1), string(link)))
}
options.Renderer.Image(out, link, title, alt)
}
var (
MentionPattern = regexp.MustCompile(`@[0-9a-zA-Z_]{1,}`)
commitPattern = regexp.MustCompile(`(\s|^)https?.*commit/[0-9a-zA-Z]+(#+[0-9a-zA-Z-]*)?`)
issueFullPattern = regexp.MustCompile(`(\s|^)https?.*issues/[0-9]+(#+[0-9a-zA-Z-]*)?`)
issueIndexPattern = regexp.MustCompile(`#[0-9]+`)
MentionPattern = regexp.MustCompile(`@[0-9a-zA-Z_]{1,}`)
commitPattern = regexp.MustCompile(`(\s|^)https?.*commit/[0-9a-zA-Z]+(#+[0-9a-zA-Z-]*)?`)
issueFullPattern = regexp.MustCompile(`(\s|^)https?.*issues/[0-9]+(#+[0-9a-zA-Z-]*)?`)
issueIndexPattern = regexp.MustCompile(`#[0-9]+`)
sha1CurrentPattern = regexp.MustCompile(`\b[0-9a-f]{40}\b`)
)
func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte {
@@ -145,7 +154,22 @@ func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte {
rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
` <a href="%s">#%s</a>`, m, ShortSha(string(m[i+7:j])))), -1)
}
ms = issueIndexPattern.FindAll(rawBytes, -1)
rawBytes = RenderIssueIndexPattern(rawBytes, urlPrefix)
rawBytes = RenderSha1CurrentPattern(rawBytes, urlPrefix)
return rawBytes
}
func RenderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
ms := sha1CurrentPattern.FindAll(rawBytes, -1)
for _, m := range ms {
rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
`<a href="%s/commit/%s"><code>%s</code></a>`, urlPrefix, m, ShortSha(string(m)))), -1)
}
return rawBytes
}
func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string) []byte {
ms := issueIndexPattern.FindAll(rawBytes, -1)
for _, m := range ms {
rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
`<a href="%s/issues/%s">%s</a>`, urlPrefix, m[1:], m)), -1)

View File

@@ -5,7 +5,6 @@
package base
import (
"bytes"
"container/list"
"encoding/json"
"errors"
@@ -48,18 +47,23 @@ func ShortSha(sha1 string) string {
return sha1
}
func ToUtf8WithErr(content []byte) (error, string) {
func DetectEncoding(content []byte) (string, error) {
detector := chardet.NewTextDetector()
result, err := detector.DetectBest(content)
return result.Charset, err
}
func ToUtf8WithErr(content []byte) (error, string) {
charset, err := DetectEncoding(content)
if err != nil {
return err, ""
}
if result.Charset == "utf8" {
if charset == "utf8" {
return nil, string(content)
}
decoder := mahonia.NewDecoder(result.Charset)
decoder := mahonia.NewDecoder(charset)
if decoder != nil {
return nil, decoder.ConvertString(string(content))
}
@@ -107,12 +111,11 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{
return a + b
},
"ActionIcon": ActionIcon,
"ActionDesc": ActionDesc,
"DateFormat": DateFormat,
"List": List,
"Mail2Domain": func(mail string) string {
if !strings.Contains(mail, "@") {
return "try.gogits.org"
return "try.gogs.io"
}
suffix := strings.SplitN(mail, "@", 2)[1]
@@ -123,7 +126,17 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{
return domain
},
"SubStr": func(str string, start, length int) string {
return str[start : start+length]
if len(str) == 0 {
return ""
}
end := start + length
if length == -1 {
end = len(str)
}
if len(str) < end {
return str
}
return str[start:end]
},
"DiffTypeToStr": DiffTypeToStr,
"DiffLineTypeToStr": DiffLineTypeToStr,
@@ -133,6 +146,9 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{
"Oauth2Icon": Oauth2Icon,
"Oauth2Name": Oauth2Name,
"ToUtf8": ToUtf8,
"EscapePound": func(str string) string {
return strings.Replace(str, "#", "%23", -1)
},
}
type Actioner interface {
@@ -162,19 +178,6 @@ func ActionIcon(opType int) string {
}
}
// FIXME: Legacy
const (
TPL_CREATE_REPO = `<a href="%s/user/%s">%s</a> created repository <a href="%s">%s</a>`
TPL_COMMIT_REPO = `<a href="%s/user/%s">%s</a> pushed to <a href="%s/src/%s">%s</a> at <a href="%s">%s</a>%s`
TPL_COMMIT_REPO_LI = `<div><img src="%s?s=16" alt="user-avatar"/> <a href="%s/commit/%s" rel="nofollow">%s</a> %s</div>`
TPL_CREATE_ISSUE = `<a href="%s/user/%s">%s</a> opened issue <a href="%s/issues/%s">%s#%s</a>
<div><img src="%s?s=16" alt="user-avatar"/> %s</div>`
TPL_TRANSFER_REPO = `<a href="%s/user/%s">%s</a> transfered repository <code>%s</code> to <a href="%s">%s</a>`
TPL_PUSH_TAG = `<a href="%s/user/%s">%s</a> pushed tag <a href="%s/src/%s" rel="nofollow">%s</a> at <a href="%s">%s</a>`
TPL_COMMENT_ISSUE = `<a href="%s/user/%s">%s</a> commented on issue <a href="%s/issues/%s">%s#%s</a>
<div><img src="%s?s=16" alt="user-avatar"/> %s</div>`
)
type PushCommit struct {
Sha1 string
Message string
@@ -183,8 +186,9 @@ type PushCommit struct {
}
type PushCommits struct {
Len int
Commits []*PushCommit
Len int
Commits []*PushCommit
CompareUrl string
}
func ActionContent2Commits(act Actioner) *PushCommits {
@@ -195,52 +199,6 @@ func ActionContent2Commits(act Actioner) *PushCommits {
return push
}
// FIXME: Legacy
// ActionDesc accepts int that represents action operation type
// and returns the description.
func ActionDesc(act Actioner) string {
actUserName := act.GetActUserName()
email := act.GetActEmail()
repoUserName := act.GetRepoUserName()
repoName := act.GetRepoName()
repoLink := repoUserName + "/" + repoName
branch := act.GetBranch()
content := act.GetContent()
switch act.GetOpType() {
case 1: // Create repository.
return fmt.Sprintf(TPL_CREATE_REPO, setting.AppSubUrl, actUserName, actUserName, repoLink, repoName)
case 5: // Commit repository.
var push *PushCommits
if err := json.Unmarshal([]byte(content), &push); err != nil {
return err.Error()
}
buf := bytes.NewBuffer([]byte("\n"))
for _, commit := range push.Commits {
buf.WriteString(fmt.Sprintf(TPL_COMMIT_REPO_LI, AvatarLink(commit.AuthorEmail), repoLink, commit.Sha1, commit.Sha1[:7], commit.Message) + "\n")
}
if push.Len > 3 {
buf.WriteString(fmt.Sprintf(`<div><a href="{{AppRootSubUrl}}/%s/%s/commits/%s" rel="nofollow">%d other commits >></a></div>`, actUserName, repoName, branch, push.Len))
}
return fmt.Sprintf(TPL_COMMIT_REPO, setting.AppSubUrl, actUserName, actUserName, repoLink, branch, branch, repoLink, repoLink,
buf.String())
case 6: // Create issue.
infos := strings.SplitN(content, "|", 2)
return fmt.Sprintf(TPL_CREATE_ISSUE, setting.AppSubUrl, actUserName, actUserName, repoLink, infos[0], repoLink, infos[0],
AvatarLink(email), infos[1])
case 8: // Transfer repository.
newRepoLink := content + "/" + repoName
return fmt.Sprintf(TPL_TRANSFER_REPO, setting.AppSubUrl, actUserName, actUserName, repoLink, newRepoLink, newRepoLink)
case 9: // Push tag.
return fmt.Sprintf(TPL_PUSH_TAG, setting.AppSubUrl, actUserName, actUserName, repoLink, branch, branch, repoLink, repoLink)
case 10: // Comment issue.
infos := strings.SplitN(content, "|", 2)
return fmt.Sprintf(TPL_COMMENT_ISSUE, setting.AppSubUrl, actUserName, actUserName, repoLink, infos[0], repoLink, infos[0],
AvatarLink(email), infos[1])
default:
return "invalid type"
}
}
func DiffTypeToStr(diffType int) string {
diffTypes := map[int]string{
1: "add", 2: "modify", 3: "del",

View File

@@ -9,6 +9,7 @@ import (
"crypto/md5"
"crypto/rand"
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"fmt"
"hash"
@@ -21,16 +22,38 @@ import (
"github.com/Unknwon/com"
"github.com/Unknwon/i18n"
"github.com/gogits/gogs/modules/avatar"
"github.com/gogits/gogs/modules/setting"
)
// Encode string to md5 hex value
// Encode string to md5 hex value.
func EncodeMd5(str string) string {
m := md5.New()
m.Write([]byte(str))
return hex.EncodeToString(m.Sum(nil))
}
// Encode string to sha1 hex value.
func EncodeSha1(str string) string {
h := sha1.New()
h.Write([]byte(str))
return hex.EncodeToString(h.Sum(nil))
}
func BasicAuthDecode(encoded string) (string, string, error) {
s, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return "", "", err
}
auth := strings.SplitN(string(s), ":", 2)
return auth[0], auth[1], nil
}
func BasicAuthEncode(username, password string) string {
return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
}
// GetRandomString generate random string by specify chars.
func GetRandomString(n int, alphabets ...byte) string {
const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
@@ -148,10 +171,13 @@ func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string
func AvatarLink(email string) string {
if setting.DisableGravatar {
return setting.AppSubUrl + "/img/avatar_default.jpg"
} else if setting.Service.EnableCacheAvatar {
return setting.AppSubUrl + "/avatar/" + EncodeMd5(email)
}
return "//1.gravatar.com/avatar/" + EncodeMd5(email)
gravatarHash := avatar.HashEmail(email)
if setting.Service.EnableCacheAvatar {
return setting.AppSubUrl + "/avatar/" + gravatarHash
}
return setting.GravatarSource + gravatarHash
}
// Seconds-based time units

View File

@@ -7,9 +7,9 @@ Callers may register Funcs to be invoked on a given schedule. Cron will run
them in their own goroutines.
c := cron.New()
c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") })
c.AddFunc("@hourly", func() { fmt.Println("Every hour") })
c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") })
c.AddFunc("Every hour on the half hour","0 30 * * * *", func() { fmt.Println("Every hour on the half hour") })
c.AddFunc("Every hour","@hourly", func() { fmt.Println("Every hour") })
c.AddFunc("Every hour and a half","@every 1h30m", func() { fmt.Println("Every hour thirty") })
c.Start()
..
// Funcs are invoked in their own goroutine, asynchronously.

View File

@@ -16,6 +16,7 @@ var c = New()
func NewCronContext() {
c.AddFunc("Update mirrors", "@every 1h", models.MirrorUpdate)
c.AddFunc("Deliver hooks", fmt.Sprintf("@every %dm", setting.WebhookTaskInterval), models.DeliverHooks)
c.AddFunc("Repository health check", "@every 1h", models.GitFsck)
c.Start()
}

View File

@@ -83,7 +83,7 @@ func (h *Hook) Update() error {
if len(strings.TrimSpace(h.Content)) == 0 {
return os.Remove(h.path)
}
return ioutil.WriteFile(h.path, []byte(h.Content), os.ModePerm)
return ioutil.WriteFile(h.path, []byte(strings.Replace(h.Content, "\r", "", -1)), os.ModePerm)
}
// ListHooks returns a list of Git hooks of given repository.

View File

@@ -5,7 +5,7 @@
package httplib
// NOTE: last sync c07b1d8 on Aug 23, 2014.
// NOTE: last sync 57e62e5 on Oct 29, 2014.
import (
"bytes"
@@ -14,6 +14,7 @@ import (
"encoding/xml"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net"
"net/http"
@@ -252,35 +253,36 @@ func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
} else {
b.url = b.url + "?" + paramBody
}
} else if b.req.Method == "POST" && b.req.Body == nil && len(paramBody) > 0 {
} else if b.req.Method == "POST" && b.req.Body == nil {
if len(b.files) > 0 {
bodyBuf := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuf)
for formname, filename := range b.files {
fileWriter, err := bodyWriter.CreateFormFile(formname, filename)
if err != nil {
return nil, err
pr, pw := io.Pipe()
bodyWriter := multipart.NewWriter(pw)
go func() {
for formname, filename := range b.files {
fileWriter, err := bodyWriter.CreateFormFile(formname, filename)
if err != nil {
log.Fatal(err)
}
fh, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
//iocopy
_, err = io.Copy(fileWriter, fh)
fh.Close()
if err != nil {
log.Fatal(err)
}
}
fh, err := os.Open(filename)
if err != nil {
return nil, err
for k, v := range b.params {
bodyWriter.WriteField(k, v)
}
//iocopy
_, err = io.Copy(fileWriter, fh)
fh.Close()
if err != nil {
return nil, err
}
}
for k, v := range b.params {
bodyWriter.WriteField(k, v)
}
contentType := bodyWriter.FormDataContentType()
bodyWriter.Close()
b.Header("Content-Type", contentType)
b.req.Body = ioutil.NopCloser(bodyBuf)
b.req.ContentLength = int64(bodyBuf.Len())
} else {
bodyWriter.Close()
pw.Close()
}()
b.Header("Content-Type", bodyWriter.FormDataContentType())
b.req.Body = ioutil.NopCloser(pr)
} else if len(paramBody) > 0 {
b.Header("Content-Type", "application/x-www-form-urlencoded")
b.Body(paramBody)
}
@@ -332,7 +334,7 @@ func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
Jar: jar,
}
if b.setting.UserAgent != "" {
if len(b.setting.UserAgent) > 0 && len(b.req.Header.Get("User-Agent")) == 0 {
b.req.Header.Set("User-Agent", b.setting.UserAgent)
}

View File

@@ -57,23 +57,23 @@ func TestSimplePost(t *testing.T) {
}
}
func TestPostFile(t *testing.T) {
v := "smallfish"
req := Post("http://httpbin.org/post")
req.Param("username", v)
req.PostFile("uploadfile", "httplib_test.go")
// func TestPostFile(t *testing.T) {
// v := "smallfish"
// req := Post("http://httpbin.org/post")
// req.Param("username", v)
// req.PostFile("uploadfile", "httplib_test.go")
str, err := req.String()
if err != nil {
t.Fatal(err)
}
t.Log(str)
// str, err := req.String()
// if err != nil {
// t.Fatal(err)
// }
// t.Log(str)
n := strings.Index(str, v)
if n == -1 {
t.Fatal(v + " not found in post")
}
}
// n := strings.Index(str, v)
// if n == -1 {
// t.Fatal(v + " not found in post")
// }
// }
func TestSimplePut(t *testing.T) {
str, err := Put("http://httpbin.org/put").String()
@@ -194,3 +194,13 @@ func TestToFile(t *testing.T) {
t.Fatal(err)
}
}
func TestHeader(t *testing.T) {
req := Get("http://httpbin.org/headers")
req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36")
str, err := req.String()
if err != nil {
t.Fatal(err)
}
t.Log(str)
}

View File

@@ -6,7 +6,7 @@ import (
"github.com/gogits/gogs/modules/asn1-ber"
)
// debbuging type
// debugging type
// - has a Printf method to write the debug output
type debugging bool

View File

@@ -162,7 +162,7 @@ func newLogger(buffer int64) *Logger {
return l
}
// SetLogger sets new logger instanse with given logger adapter and config.
// SetLogger sets new logger instance with given logger adapter and config.
func (l *Logger) SetLogger(adapter string, config string) error {
l.lock.Lock()
defer l.lock.Unlock()

View File

@@ -32,7 +32,7 @@ const (
)
// A Decoder is a function that decodes a character set, one character at a time.
// It works much like utf8.DecodeRune, but has an aditional status return value.
// It works much like utf8.DecodeRune, but has an additional status return value.
type Decoder func(p []byte) (c rune, size int, status Status)
// An Encoder is a function that encodes a character set, one character at a time.

View File

@@ -82,7 +82,7 @@ func sendMail(hostAddressWithPort string, auth smtp.Auth, from string, recipient
return err
}
if auth != nil {
if ok, _ := client.Extension("AUTH"); ok && auth != nil {
if err = client.Auth(auth); err != nil {
return err
}
@@ -127,7 +127,10 @@ func Send(msg *Message) (int, error) {
return 0, fmt.Errorf("empty email body")
}
auth := smtp.PlainAuth("", setting.MailService.User, setting.MailService.Passwd, host[0])
var auth smtp.Auth
if len(setting.MailService.Passwd) > 0 {
auth = smtp.PlainAuth("", setting.MailService.User, setting.MailService.Passwd, host[0])
}
if msg.Massive {
// send mail to multiple emails one by one

View File

@@ -29,6 +29,12 @@ func Toggle(options *ToggleOptions) macaron.Handler {
return
}
// Checking non-logged users landing page.
if !ctx.IsSigned && ctx.Req.RequestURI == "/" && setting.LandingPageUrl != setting.LANDING_PAGE_HOME {
ctx.Redirect(string(setting.LandingPageUrl))
return
}
// Redirect to dashboard if user tries to visit any non-login page.
if options.SignOutRequire && ctx.IsSigned && ctx.Req.RequestURI != "/" {
ctx.Redirect(setting.AppSubUrl + "/")
@@ -67,3 +73,21 @@ func Toggle(options *ToggleOptions) macaron.Handler {
}
}
}
func ApiReqToken() macaron.Handler {
return func(ctx *Context) {
if !ctx.IsSigned {
ctx.Error(403)
return
}
}
}
func ApiReqBasicAuth() macaron.Handler {
return func(ctx *Context) {
if !ctx.IsBasicAuth {
ctx.Error(403)
return
}
}
}

View File

@@ -1,472 +0,0 @@
// Copyright 2013 The Martini Contrib Authors. All rights reserved.
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package binding
import (
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
"regexp"
"strconv"
"strings"
"unicode/utf8"
"github.com/Unknwon/macaron"
"github.com/macaron-contrib/i18n"
)
/*
To the land of Middle-ware Earth:
One func to rule them all,
One func to find them,
One func to bring them all,
And in this package BIND them.
*/
// Bind accepts a copy of an empty struct and populates it with
// values from the request (if deserialization is successful). It
// wraps up the functionality of the Form and Json middleware
// according to the Content-Type of the request, and it guesses
// if no Content-Type is specified. Bind invokes the ErrorHandler
// middleware to bail out if errors occurred. If you want to perform
// your own error handling, use Form or Json middleware directly.
// An interface pointer can be added as a second argument in order
// to map the struct to a specific interface.
func Bind(obj interface{}, ifacePtr ...interface{}) macaron.Handler {
return func(ctx *macaron.Context) {
contentType := ctx.Req.Header.Get("Content-Type")
if strings.Contains(contentType, "form-urlencoded") {
ctx.Invoke(Form(obj, ifacePtr...))
} else if strings.Contains(contentType, "multipart/form-data") {
ctx.Invoke(MultipartForm(obj, ifacePtr...))
} else if strings.Contains(contentType, "json") {
ctx.Invoke(Json(obj, ifacePtr...))
} else {
ctx.Invoke(Json(obj, ifacePtr...))
if getErrors(ctx).Count() > 0 {
ctx.Invoke(Form(obj, ifacePtr...))
}
}
ctx.Invoke(ErrorHandler)
}
}
// BindIgnErr will do the exactly same thing as Bind but without any
// error handling, which user has freedom to deal with them.
// This allows user take advantages of validation.
func BindIgnErr(obj interface{}, ifacePtr ...interface{}) macaron.Handler {
return func(ctx *macaron.Context, req *http.Request) {
contentType := req.Header.Get("Content-Type")
if strings.Contains(contentType, "form-urlencoded") {
ctx.Invoke(Form(obj, ifacePtr...))
} else if strings.Contains(contentType, "multipart/form-data") {
ctx.Invoke(MultipartForm(obj, ifacePtr...))
} else if strings.Contains(contentType, "json") {
ctx.Invoke(Json(obj, ifacePtr...))
} else {
ctx.Invoke(Json(obj, ifacePtr...))
if getErrors(ctx).Count() > 0 {
ctx.Invoke(Form(obj, ifacePtr...))
}
}
}
}
// Form is middleware to deserialize form-urlencoded data from the request.
// It gets data from the form-urlencoded body, if present, or from the
// query string. It uses the http.Request.ParseForm() method
// to perform deserialization, then reflection is used to map each field
// into the struct with the proper type. Structs with primitive slice types
// (bool, float, int, string) can support deserialization of repeated form
// keys, for example: key=val1&key=val2&key=val3
// An interface pointer can be added as a second argument in order
// to map the struct to a specific interface.
func Form(formStruct interface{}, ifacePtr ...interface{}) macaron.Handler {
return func(ctx *macaron.Context) {
ensureNotPointer(formStruct)
formStruct := reflect.New(reflect.TypeOf(formStruct))
errors := newErrors()
parseErr := ctx.Req.ParseForm()
// Format validation of the request body or the URL would add considerable overhead,
// and ParseForm does not complain when URL encoding is off.
// Because an empty request body or url can also mean absence of all needed values,
// it is not in all cases a bad request, so let's return 422.
if parseErr != nil {
errors.Overall[BindingDeserializationError] = parseErr.Error()
}
mapForm(formStruct, ctx.Req.Form, errors)
validateAndMap(formStruct, ctx, errors, ifacePtr...)
}
}
func MultipartForm(formStruct interface{}, ifacePtr ...interface{}) macaron.Handler {
return func(ctx *macaron.Context) {
ensureNotPointer(formStruct)
formStruct := reflect.New(reflect.TypeOf(formStruct))
errors := newErrors()
// Workaround for multipart forms returning nil instead of an error
// when content is not multipart
// https://code.google.com/p/go/issues/detail?id=6334
multipartReader, err := ctx.Req.MultipartReader()
if err != nil {
errors.Overall[BindingDeserializationError] = err.Error()
} else {
form, parseErr := multipartReader.ReadForm(MaxMemory)
if parseErr != nil {
errors.Overall[BindingDeserializationError] = parseErr.Error()
}
ctx.Req.MultipartForm = form
}
mapForm(formStruct, ctx.Req.MultipartForm.Value, errors)
validateAndMap(formStruct, ctx, errors, ifacePtr...)
}
}
// Json is middleware to deserialize a JSON payload from the request
// into the struct that is passed in. The resulting struct is then
// validated, but no error handling is actually performed here.
// An interface pointer can be added as a second argument in order
// to map the struct to a specific interface.
func Json(jsonStruct interface{}, ifacePtr ...interface{}) macaron.Handler {
return func(ctx *macaron.Context) {
ensureNotPointer(jsonStruct)
jsonStruct := reflect.New(reflect.TypeOf(jsonStruct))
errors := newErrors()
if ctx.Req.Body != nil {
defer ctx.Req.Body.Close()
}
if err := json.NewDecoder(ctx.Req.Body).Decode(jsonStruct.Interface()); err != nil && err != io.EOF {
errors.Overall[BindingDeserializationError] = err.Error()
}
validateAndMap(jsonStruct, ctx, errors, ifacePtr...)
}
}
// Validate is middleware to enforce required fields. If the struct
// passed in is a Validator, then the user-defined Validate method
// is executed, and its errors are mapped to the context. This middleware
// performs no error handling: it merely detects them and maps them.
func Validate(obj interface{}) macaron.Handler {
return func(ctx *macaron.Context, l i18n.Locale) {
errors := newErrors()
validateStruct(errors, obj)
if validator, ok := obj.(Validator); ok {
validator.Validate(ctx, errors, l)
}
ctx.Map(*errors)
}
}
var (
alphaDashPattern = regexp.MustCompile("[^\\d\\w-_]")
alphaDashDotPattern = regexp.MustCompile("[^\\d\\w-_\\.]")
emailPattern = regexp.MustCompile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z0-9](?:[\\w-]*[\\w])?")
urlPattern = regexp.MustCompile(`(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?`)
)
func validateStruct(errors *Errors, obj interface{}) {
typ := reflect.TypeOf(obj)
val := reflect.ValueOf(obj)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
val = val.Elem()
}
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
// Allow ignored fields in the struct
if field.Tag.Get("form") == "-" {
continue
}
fieldValue := val.Field(i).Interface()
if field.Type.Kind() == reflect.Struct {
validateStruct(errors, fieldValue)
continue
}
zero := reflect.Zero(field.Type).Interface()
// Match rules.
for _, rule := range strings.Split(field.Tag.Get("binding"), ";") {
if len(rule) == 0 {
continue
}
switch {
case rule == "Required":
if reflect.DeepEqual(zero, fieldValue) {
errors.Fields[field.Name] = BindingRequireError
break
}
case rule == "AlphaDash":
if alphaDashPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
errors.Fields[field.Name] = BindingAlphaDashError
break
}
case rule == "AlphaDashDot":
if alphaDashDotPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
errors.Fields[field.Name] = BindingAlphaDashDotError
break
}
case strings.HasPrefix(rule, "MinSize("):
min, err := strconv.Atoi(rule[8 : len(rule)-1])
if err != nil {
errors.Overall["MinSize"] = err.Error()
break
}
if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) < min {
errors.Fields[field.Name] = BindingMinSizeError
break
}
v := reflect.ValueOf(fieldValue)
if v.Kind() == reflect.Slice && v.Len() < min {
errors.Fields[field.Name] = BindingMinSizeError
break
}
case strings.HasPrefix(rule, "MaxSize("):
max, err := strconv.Atoi(rule[8 : len(rule)-1])
if err != nil {
errors.Overall["MaxSize"] = err.Error()
break
}
if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) > max {
errors.Fields[field.Name] = BindingMaxSizeError
break
}
v := reflect.ValueOf(fieldValue)
if v.Kind() == reflect.Slice && v.Len() > max {
errors.Fields[field.Name] = BindingMinSizeError
break
}
case rule == "Email":
if !emailPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
errors.Fields[field.Name] = BindingEmailError
break
}
case rule == "Url":
str := fmt.Sprintf("%v", fieldValue)
if len(str) == 0 {
continue
} else if !urlPattern.MatchString(str) {
errors.Fields[field.Name] = BindingUrlError
break
}
}
}
}
}
func mapForm(formStruct reflect.Value, form map[string][]string, errors *Errors) {
typ := formStruct.Elem().Type()
for i := 0; i < typ.NumField(); i++ {
typeField := typ.Field(i)
if inputFieldName := typeField.Tag.Get("form"); inputFieldName != "" {
structField := formStruct.Elem().Field(i)
if !structField.CanSet() {
continue
}
inputValue, exists := form[inputFieldName]
if !exists {
continue
}
numElems := len(inputValue)
if structField.Kind() == reflect.Slice && numElems > 0 {
sliceOf := structField.Type().Elem().Kind()
slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
for i := 0; i < numElems; i++ {
setWithProperType(sliceOf, inputValue[i], slice.Index(i), inputFieldName, errors)
}
formStruct.Elem().Field(i).Set(slice)
} else {
setWithProperType(typeField.Type.Kind(), inputValue[0], structField, inputFieldName, errors)
}
}
}
}
// ErrorHandler simply counts the number of errors in the
// context and, if more than 0, writes a 400 Bad Request
// response and a JSON payload describing the errors with
// the "Content-Type" set to "application/json".
// Middleware remaining on the stack will not even see the request
// if, by this point, there are any errors.
// This is a "default" handler, of sorts, and you are
// welcome to use your own instead. The Bind middleware
// invokes this automatically for convenience.
func ErrorHandler(errs Errors, resp http.ResponseWriter) {
if errs.Count() > 0 {
resp.Header().Set("Content-Type", "application/json; charset=utf-8")
if _, ok := errs.Overall[BindingDeserializationError]; ok {
resp.WriteHeader(http.StatusBadRequest)
} else {
resp.WriteHeader(422)
}
errOutput, _ := json.Marshal(errs)
resp.Write(errOutput)
return
}
}
// This sets the value in a struct of an indeterminate type to the
// matching value from the request (via Form middleware) in the
// same type, so that not all deserialized values have to be strings.
// Supported types are string, int, float, and bool.
func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value, nameInTag string, errors *Errors) {
switch valueKind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if val == "" {
val = "0"
}
intVal, err := strconv.ParseInt(val, 10, 64)
if err != nil {
errors.Fields[nameInTag] = BindingIntegerTypeError
} else {
structField.SetInt(intVal)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if val == "" {
val = "0"
}
uintVal, err := strconv.ParseUint(val, 10, 64)
if err != nil {
errors.Fields[nameInTag] = BindingIntegerTypeError
} else {
structField.SetUint(uintVal)
}
case reflect.Bool:
structField.SetBool(val == "on")
case reflect.Float32:
if val == "" {
val = "0.0"
}
floatVal, err := strconv.ParseFloat(val, 32)
if err != nil {
errors.Fields[nameInTag] = BindingFloatTypeError
} else {
structField.SetFloat(floatVal)
}
case reflect.Float64:
if val == "" {
val = "0.0"
}
floatVal, err := strconv.ParseFloat(val, 64)
if err != nil {
errors.Fields[nameInTag] = BindingFloatTypeError
} else {
structField.SetFloat(floatVal)
}
case reflect.String:
structField.SetString(val)
}
}
// Don't pass in pointers to bind to. Can lead to bugs.
func ensureNotPointer(obj interface{}) {
if reflect.TypeOf(obj).Kind() == reflect.Ptr {
panic("Pointers are not accepted as binding models")
}
}
// Performs validation and combines errors from validation
// with errors from deserialization, then maps both the
// resulting struct and the errors to the context.
func validateAndMap(obj reflect.Value, ctx *macaron.Context, errors *Errors, ifacePtr ...interface{}) {
ctx.Invoke(Validate(obj.Interface()))
errors.Combine(getErrors(ctx))
ctx.Map(*errors)
ctx.Map(obj.Elem().Interface())
if len(ifacePtr) > 0 {
ctx.MapTo(obj.Elem().Interface(), ifacePtr[0])
}
}
func newErrors() *Errors {
return &Errors{make(map[string]string), make(map[string]string)}
}
func getErrors(ctx *macaron.Context) Errors {
return ctx.GetVal(reflect.TypeOf(Errors{})).Interface().(Errors)
}
type (
// Implement the Validator interface to define your own input
// validation before the request even gets to your application.
// The Validate method will be executed during the validation phase.
Validator interface {
Validate(*macaron.Context, *Errors, i18n.Locale)
}
)
var (
// Maximum amount of memory to use when parsing a multipart form.
// Set this to whatever value you prefer; default is 10 MB.
MaxMemory = int64(1024 * 1024 * 10)
)
// Errors represents the contract of the response body when the
// binding step fails before getting to the application.
type Errors struct {
Overall map[string]string `json:"overall"`
Fields map[string]string `json:"fields"`
}
// Total errors is the sum of errors with the request overall
// and errors on individual fields.
func (err Errors) Count() int {
return len(err.Overall) + len(err.Fields)
}
func (this *Errors) Combine(other Errors) {
for key, val := range other.Fields {
if _, exists := this.Fields[key]; !exists {
this.Fields[key] = val
}
}
for key, val := range other.Overall {
if _, exists := this.Overall[key]; !exists {
this.Overall[key] = val
}
}
}
const (
BindingRequireError string = "Required"
BindingAlphaDashError string = "AlphaDash"
BindingAlphaDashDotError string = "AlphaDashDot"
BindingMinSizeError string = "MinSize"
BindingMaxSizeError string = "MaxSize"
BindingEmailError string = "Email"
BindingUrlError string = "Url"
BindingDeserializationError string = "DeserializationError"
BindingIntegerTypeError string = "IntegerTypeError"
BindingBooleanTypeError string = "BooleanTypeError"
BindingFloatTypeError string = "FloatTypeError"
)

View File

@@ -34,32 +34,30 @@ type Context struct {
Flash *session.Flash
Session session.Store
User *models.User
IsSigned bool
User *models.User
IsSigned bool
IsBasicAuth bool
Repo struct {
IsOwner bool
IsTrueOwner bool
IsWatching bool
IsBranch bool
IsTag bool
IsCommit bool
IsAdmin bool // Current user is admin level.
HasAccess bool
Repository *models.Repository
Owner *models.User
Commit *git.Commit
Tag *git.Tag
GitRepo *git.Repository
BranchName string
TagName string
CommitId string
RepoLink string
CloneLink struct {
SSH string
HTTPS string
Git string
}
IsOwner bool
IsTrueOwner bool
IsWatching bool
IsBranch bool
IsTag bool
IsCommit bool
IsAdmin bool // Current user is admin level.
HasAccess bool
Repository *models.Repository
Owner *models.User
Commit *git.Commit
Tag *git.Tag
GitRepo *git.Repository
BranchName string
TagName string
TreeName string
CommitId string
RepoLink string
CloneLink models.CloneLink
CommitsCount int
Mirror *models.Mirror
}
@@ -75,12 +73,6 @@ type Context struct {
}
}
// Query querys form parameter.
func (ctx *Context) Query(name string) string {
ctx.Req.ParseForm()
return ctx.Req.Form.Get(name)
}
// HasError returns true if error occurs in form validation.
func (ctx *Context) HasApiError() bool {
hasErr, ok := ctx.Data["HasError"]
@@ -153,7 +145,7 @@ func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interfa
ctx.Resp.Header().Set("Expires", "0")
ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
ctx.Resp.Header().Set("Pragma", "public")
http.ServeContent(ctx.Resp, ctx.Req, name, modtime, r)
http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
}
// Contexter initializes a classic context for a request.
@@ -177,12 +169,16 @@ func Contexter() macaron.Handler {
ctx.Data["PageStartTime"] = time.Now()
// Get user from session if logined.
ctx.User = auth.SignedInUser(ctx.Req.Header, ctx.Session)
ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Req.Request, ctx.Session)
if ctx.User != nil {
ctx.IsSigned = true
ctx.Data["IsSigned"] = ctx.IsSigned
ctx.Data["SignedUser"] = ctx.User
ctx.Data["SignedUserName"] = ctx.User.Name
ctx.Data["IsAdmin"] = ctx.User.IsAdmin
} else {
ctx.Data["SignedUserName"] = ""
}
// If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.

View File

@@ -48,7 +48,7 @@ func OrgAssignment(redirect bool, args ...bool) macaron.Handler {
ctx.Data["Org"] = org
if ctx.IsSigned {
ctx.Org.IsOwner = org.IsOrgOwner(ctx.User.Id)
ctx.Org.IsOwner = org.IsOwnedBy(ctx.User.Id)
if ctx.Org.IsOwner {
ctx.Org.IsMember = true
ctx.Org.IsAdminTeam = true

View File

@@ -13,22 +13,221 @@ import (
"github.com/Unknwon/macaron"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/git"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)
func ApiRepoAssignment() macaron.Handler {
return func(ctx *Context) {
userName := ctx.Params(":username")
repoName := ctx.Params(":reponame")
var (
u *models.User
err error
)
// Collaborators who have write access can be seen as owners.
if ctx.IsSigned {
ctx.Repo.IsOwner, err = models.HasAccess(ctx.User.Name, userName+"/"+repoName, models.WRITABLE)
if err != nil {
ctx.JSON(500, &base.ApiJsonErr{"HasAccess: " + err.Error(), base.DOC_URL})
return
}
ctx.Repo.IsTrueOwner = ctx.User.LowerName == strings.ToLower(userName)
}
if !ctx.Repo.IsTrueOwner {
u, err = models.GetUserByName(userName)
if err != nil {
if err == models.ErrUserNotExist {
ctx.Error(404)
} else {
ctx.JSON(500, &base.ApiJsonErr{"GetUserByName: " + err.Error(), base.DOC_URL})
}
return
}
} else {
u = ctx.User
}
ctx.Repo.Owner = u
// Organization owner team members are true owners as well.
if ctx.IsSigned && ctx.Repo.Owner.IsOrganization() && ctx.Repo.Owner.IsOwnedBy(ctx.User.Id) {
ctx.Repo.IsTrueOwner = true
}
// Get repository.
repo, err := models.GetRepositoryByName(u.Id, repoName)
if err != nil {
if err == models.ErrRepoNotExist {
ctx.Error(404)
return
}
ctx.JSON(500, &base.ApiJsonErr{"GetRepositoryByName: " + err.Error(), base.DOC_URL})
return
} else if err = repo.GetOwner(); err != nil {
ctx.JSON(500, &base.ApiJsonErr{"GetOwner: " + err.Error(), base.DOC_URL})
return
}
// Check if the mirror repository owner(mirror repository doesn't have access).
if ctx.IsSigned && !ctx.Repo.IsOwner {
if repo.OwnerId == ctx.User.Id {
ctx.Repo.IsOwner = true
}
// Check if current user has admin permission to repository.
if u.IsOrganization() {
auth, err := models.GetHighestAuthorize(u.Id, ctx.User.Id, repo.Id, 0)
if err != nil {
ctx.JSON(500, &base.ApiJsonErr{"GetHighestAuthorize: " + err.Error(), base.DOC_URL})
return
}
if auth == models.ORG_ADMIN {
ctx.Repo.IsOwner = true
ctx.Repo.IsAdmin = true
}
}
}
// Check access.
if repo.IsPrivate && !ctx.Repo.IsOwner {
if ctx.User == nil {
ctx.Error(404)
return
}
hasAccess, err := models.HasAccess(ctx.User.Name, ctx.Repo.Owner.Name+"/"+repo.Name, models.READABLE)
if err != nil {
ctx.JSON(500, &base.ApiJsonErr{"HasAccess: " + err.Error(), base.DOC_URL})
return
} else if !hasAccess {
ctx.Error(404)
return
}
}
ctx.Repo.HasAccess = true
ctx.Repo.Repository = repo
}
}
// RepoRef handles repository reference name including those contain `/`.
func RepoRef() macaron.Handler {
return func(ctx *Context) {
var (
refName string
err error
)
// For API calls.
if ctx.Repo.GitRepo == nil {
repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
gitRepo, err := git.OpenRepository(repoPath)
if err != nil {
ctx.Handle(500, "RepoRef Invalid repo "+repoPath, err)
return
}
ctx.Repo.GitRepo = gitRepo
}
// Get default branch.
if len(ctx.Params("*")) == 0 {
refName = ctx.Repo.Repository.DefaultBranch
if !ctx.Repo.GitRepo.IsBranchExist(refName) {
brs, err := ctx.Repo.GitRepo.GetBranches()
if err != nil {
ctx.Handle(500, "GetBranches", err)
return
}
refName = brs[0]
}
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommitOfBranch(refName)
if err != nil {
ctx.Handle(500, "GetCommitOfBranch", err)
return
}
ctx.Repo.CommitId = ctx.Repo.Commit.Id.String()
ctx.Repo.IsBranch = true
} else {
hasMatched := false
parts := strings.Split(ctx.Params("*"), "/")
for i, part := range parts {
refName = strings.TrimPrefix(refName+"/"+part, "/")
if ctx.Repo.GitRepo.IsBranchExist(refName) ||
ctx.Repo.GitRepo.IsTagExist(refName) {
if i < len(parts)-1 {
ctx.Repo.TreeName = strings.Join(parts[i+1:], "/")
}
hasMatched = true
break
}
}
if !hasMatched && len(parts[0]) == 40 {
refName = parts[0]
ctx.Repo.TreeName = strings.Join(parts[1:], "/")
}
if ctx.Repo.GitRepo.IsBranchExist(refName) {
ctx.Repo.IsBranch = true
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommitOfBranch(refName)
if err != nil {
ctx.Handle(500, "GetCommitOfBranch", err)
return
}
ctx.Repo.CommitId = ctx.Repo.Commit.Id.String()
} else if ctx.Repo.GitRepo.IsTagExist(refName) {
ctx.Repo.IsTag = true
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommitOfTag(refName)
if err != nil {
ctx.Handle(500, "GetCommitOfTag", err)
return
}
ctx.Repo.CommitId = ctx.Repo.Commit.Id.String()
} else if len(refName) == 40 {
ctx.Repo.IsCommit = true
ctx.Repo.CommitId = refName
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
if err != nil {
ctx.Handle(404, "GetCommit", nil)
return
}
} else {
ctx.Handle(404, "RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
return
}
}
ctx.Repo.BranchName = refName
ctx.Data["BranchName"] = ctx.Repo.BranchName
ctx.Data["CommitId"] = ctx.Repo.CommitId
ctx.Data["IsBranch"] = ctx.Repo.IsBranch
ctx.Data["IsTag"] = ctx.Repo.IsTag
ctx.Data["IsCommit"] = ctx.Repo.IsCommit
ctx.Repo.CommitsCount, err = ctx.Repo.Commit.CommitsCount()
if err != nil {
ctx.Handle(500, "CommitsCount", err)
return
}
ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
}
}
func RepoAssignment(redirect bool, args ...bool) macaron.Handler {
return func(ctx *Context) {
var (
validBranch bool // To valid brach name.
displayBare bool // To display bare page if it is a bare repo.
)
if len(args) >= 1 {
validBranch = args[0]
}
if len(args) >= 2 {
displayBare = args[1]
displayBare = args[0]
}
var (
@@ -81,7 +280,7 @@ func RepoAssignment(redirect bool, args ...bool) macaron.Handler {
ctx.Repo.Owner = u
// Organization owner team members are true owners as well.
if ctx.IsSigned && ctx.Repo.Owner.IsOrganization() && ctx.Repo.Owner.IsOrgOwner(ctx.User.Id) {
if ctx.IsSigned && ctx.Repo.Owner.IsOrganization() && ctx.Repo.Owner.IsOwnedBy(ctx.User.Id) {
ctx.Repo.IsTrueOwner = true
}
@@ -160,7 +359,11 @@ func RepoAssignment(redirect bool, args ...bool) macaron.Handler {
return
}
ctx.Repo.GitRepo = gitRepo
ctx.Repo.RepoLink = setting.AppSubUrl + "/" + u.Name + "/" + repo.Name
ctx.Repo.RepoLink, err = repo.RepoLink()
if err != nil {
ctx.Handle(500, "RepoLink", err)
return
}
ctx.Data["RepoLink"] = ctx.Repo.RepoLink
tags, err := ctx.Repo.GitRepo.GetTags()
@@ -171,18 +374,23 @@ func RepoAssignment(redirect bool, args ...bool) macaron.Handler {
ctx.Data["Tags"] = tags
ctx.Repo.Repository.NumTags = len(tags)
// Non-fork repository will not return error in this method.
if err = repo.GetForkRepo(); err != nil {
ctx.Handle(500, "GetForkRepo", err)
return
}
ctx.Data["Title"] = u.Name + "/" + repo.Name
ctx.Data["Repository"] = repo
ctx.Data["Owner"] = ctx.Repo.Repository.Owner
ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner
ctx.Data["IsRepositoryTrueOwner"] = ctx.Repo.IsTrueOwner
if setting.SshPort != 22 {
ctx.Repo.CloneLink.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", setting.RunUser, setting.Domain, setting.SshPort, u.LowerName, repo.LowerName)
} else {
ctx.Repo.CloneLink.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.Domain, u.LowerName, repo.LowerName)
ctx.Repo.CloneLink, err = repo.CloneLink()
if err != nil {
ctx.Handle(500, "CloneLink", err)
return
}
ctx.Repo.CloneLink.HTTPS = fmt.Sprintf("%s%s/%s.git", setting.AppUrl, u.LowerName, repo.LowerName)
ctx.Data["CloneLink"] = ctx.Repo.CloneLink
if ctx.Repo.Repository.IsGoget {
@@ -190,76 +398,11 @@ func RepoAssignment(redirect bool, args ...bool) macaron.Handler {
ctx.Data["GoGetImport"] = fmt.Sprintf("%s/%s/%s", setting.Domain, u.LowerName, repo.LowerName)
}
// when repo is bare, not valid branch
if !ctx.Repo.Repository.IsBare && validBranch {
detect:
if len(refName) > 0 {
if gitRepo.IsBranchExist(refName) {
ctx.Repo.IsBranch = true
ctx.Repo.BranchName = refName
ctx.Repo.Commit, err = gitRepo.GetCommitOfBranch(refName)
if err != nil {
ctx.Handle(500, "RepoAssignment invalid branch", err)
return
}
ctx.Repo.CommitId = ctx.Repo.Commit.Id.String()
} else if gitRepo.IsTagExist(refName) {
ctx.Repo.IsTag = true
ctx.Repo.BranchName = refName
ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommitOfTag(refName)
if err != nil {
ctx.Handle(500, "Fail to get tag commit", err)
return
}
ctx.Repo.CommitId = ctx.Repo.Commit.Id.String()
} else if len(refName) == 40 {
ctx.Repo.IsCommit = true
ctx.Repo.CommitId = refName
ctx.Repo.BranchName = refName
ctx.Repo.Commit, err = gitRepo.GetCommit(refName)
if err != nil {
ctx.Handle(404, "RepoAssignment invalid commit", nil)
return
}
} else {
ctx.Handle(404, "RepoAssignment invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
return
}
} else {
if len(refName) == 0 {
if gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) {
refName = ctx.Repo.Repository.DefaultBranch
} else {
brs, err := gitRepo.GetBranches()
if err != nil {
ctx.Handle(500, "GetBranches", err)
return
}
refName = brs[0]
}
}
goto detect
}
ctx.Data["IsBranch"] = ctx.Repo.IsBranch
ctx.Data["IsTag"] = ctx.Repo.IsTag
ctx.Data["IsCommit"] = ctx.Repo.IsCommit
ctx.Repo.CommitsCount, err = ctx.Repo.Commit.CommitsCount()
if err != nil {
ctx.Handle(500, "CommitsCount", err)
return
}
ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
}
// repo is bare and display enable
if ctx.Repo.Repository.IsBare {
log.Debug("Bare repository: %s", ctx.Repo.RepoLink)
// NOTE: to prevent templating error
ctx.Data["BranchName"] = ""
if displayBare {
ctx.HTML(200, "repo/bare")
}
@@ -309,10 +452,10 @@ func RequireTrueOwner() macaron.Handler {
}
}
// GitHookService checks if repsitory Git hooks service has been enabled.
// GitHookService checks if repository Git hooks service has been enabled.
func GitHookService() macaron.Handler {
return func(ctx *Context) {
if !setting.Service.EnableGitHooks {
if !ctx.User.AllowGitHook && !ctx.User.IsAdmin {
ctx.Handle(404, "GitHookService", nil)
return
}

View File

@@ -17,10 +17,11 @@ import (
"github.com/Unknwon/com"
"github.com/Unknwon/goconfig"
"github.com/macaron-contrib/oauth2"
"github.com/macaron-contrib/session"
"github.com/gogits/gogs/modules/log"
// "github.com/gogits/gogs-ng/modules/ssh"
// "github.com/gogits/gogs/modules/ssh"
)
type Scheme string
@@ -28,6 +29,14 @@ type Scheme string
const (
HTTP Scheme = "http"
HTTPS Scheme = "https"
FCGI Scheme = "fcgi"
)
type LandingPage string
const (
LANDING_PAGE_HOME LandingPage = "/"
LANDING_PAGE_EXPLORE LandingPage = "/explore"
)
var (
@@ -47,6 +56,7 @@ var (
CertFile, KeyFile string
StaticRootPath string
EnableGzip bool
LandingPageUrl LandingPage
// Security settings.
InstallLock bool
@@ -65,8 +75,10 @@ var (
ScriptType string
// Picture settings.
PictureService string
DisableGravatar bool
PictureService string
AvatarUploadPath string
GravatarSource string
DisableGravatar bool
// Log settings.
LogRootPath string
@@ -97,6 +109,8 @@ var (
// Git settings.
MaxGitDiffLines int
GitFsckArgs []string
GitGcArgs []string
// I18n settings.
Langs, Names []string
@@ -181,6 +195,9 @@ func NewConfigContext() {
CertFile = Cfg.MustValue("server", "CERT_FILE")
KeyFile = Cfg.MustValue("server", "KEY_FILE")
}
if Cfg.MustValue("server", "PROTOCOL") == "fcgi" {
Protocol = FCGI
}
Domain = Cfg.MustValue("server", "DOMAIN", "localhost")
HttpAddr = Cfg.MustValue("server", "HTTP_ADDR", "0.0.0.0")
HttpPort = Cfg.MustValue("server", "HTTP_PORT", "3000")
@@ -191,6 +208,13 @@ func NewConfigContext() {
LogRootPath = Cfg.MustValue("log", "ROOT_PATH", path.Join(workDir, "log"))
EnableGzip = Cfg.MustBool("server", "ENABLE_GZIP")
switch Cfg.MustValue("server", "LANDING_PAGE", "home") {
case "explore":
LandingPageUrl = LANDING_PAGE_EXPLORE
default:
LandingPageUrl = LANDING_PAGE_HOME
}
InstallLock = Cfg.MustBool("security", "INSTALL_LOCK")
SecretKey = Cfg.MustValue("security", "SECRET_KEY")
LogInRememberDays = Cfg.MustInt("security", "LOGIN_REMEMBER_DAYS")
@@ -236,7 +260,7 @@ func NewConfigContext() {
log.Fatal(4, "Expect user(%s) but current user is: %s", RunUser, curUser)
}
// Determine and create root git reposiroty path.
// Determine and create root git repository path.
homeDir, err := com.HomeDir()
if err != nil {
log.Fatal(4, "Fail to get home directory: %v", err)
@@ -253,11 +277,21 @@ func NewConfigContext() {
}
ScriptType = Cfg.MustValue("repository", "SCRIPT_TYPE", "bash")
PictureService = Cfg.MustValueRange("picture", "SERVICE", "server",
[]string{"server"})
PictureService = Cfg.MustValueRange("picture", "SERVICE", "server", []string{"server"})
AvatarUploadPath = Cfg.MustValue("picture", "AVATAR_UPLOAD_PATH", "data/avatars")
os.MkdirAll(AvatarUploadPath, os.ModePerm)
switch Cfg.MustValue("picture", "GRAVATAR_SOURCE", "gravatar") {
case "duoshuo":
GravatarSource = "http://gravatar.duoshuo.com/avatar/"
default:
GravatarSource = "//1.gravatar.com/avatar/"
}
DisableGravatar = Cfg.MustBool("picture", "DISABLE_GRAVATAR")
MaxGitDiffLines = Cfg.MustInt("git", "MAX_GITDIFF_LINES", 10000)
GitFsckArgs = Cfg.MustValueArray("git", "FSCK_ARGS", " ")
GitGcArgs = Cfg.MustValueArray("git", "GC_ARGS", " ")
Langs = Cfg.MustValueArray("i18n", "LANGS", ",")
Names = Cfg.MustValueArray("i18n", "NAMES", ",")
@@ -266,16 +300,15 @@ func NewConfigContext() {
}
var Service struct {
RegisterEmailConfirm bool
DisableRegistration bool
RequireSignInView bool
EnableCacheAvatar bool
EnableNotifyMail bool
EnableReverseProxyAuth bool
LdapAuth bool
ActiveCodeLives int
ResetPwdCodeLives int
EnableGitHooks bool
RegisterEmailConfirm bool
DisableRegistration bool
RequireSignInView bool
EnableCacheAvatar bool
EnableNotifyMail bool
EnableReverseProxyAuth bool
EnableReverseProxyAutoRegister bool
ActiveCodeLives int
ResetPwdCodeLives int
}
func newService() {
@@ -285,7 +318,7 @@ func newService() {
Service.RequireSignInView = Cfg.MustBool("service", "REQUIRE_SIGNIN_VIEW")
Service.EnableCacheAvatar = Cfg.MustBool("service", "ENABLE_CACHE_AVATAR")
Service.EnableReverseProxyAuth = Cfg.MustBool("service", "ENABLE_REVERSE_PROXY_AUTHENTICATION")
Service.EnableGitHooks = Cfg.MustBool("service", "ENABLE_GIT_HOOKS")
Service.EnableReverseProxyAutoRegister = Cfg.MustBool("service", "ENABLE_REVERSE_PROXY_AUTO_REGISTERATION")
}
var logLevels = map[string]string{
@@ -390,9 +423,6 @@ func newSessionService() {
SessionConfig.EnableSetCookie = Cfg.MustBool("session", "ENABLE_SET_COOKIE", true)
SessionConfig.Gclifetime = Cfg.MustInt64("session", "GC_INTERVAL_TIME", 86400)
SessionConfig.Maxlifetime = Cfg.MustInt64("session", "SESSION_LIFE_TIME", 86400)
SessionConfig.SessionIDHashFunc = Cfg.MustValueRange("session", "SESSION_ID_HASHFUNC",
"sha1", []string{"sha1", "sha256", "md5"})
SessionConfig.SessionIDHashKey = Cfg.MustValue("session", "SESSION_ID_HASHKEY", string(com.RandomCreateBytes(16)))
if SessionProvider == "file" {
os.MkdirAll(path.Dir(SessionConfig.ProviderConfig), os.ModePerm)
@@ -410,9 +440,8 @@ type Mailer struct {
}
type OauthInfo struct {
ClientId, ClientSecret string
Scopes string
AuthUrl, TokenUrl string
oauth2.Options
AuthUrl, TokenUrl string
}
// Oauther represents oauth service.
@@ -479,5 +508,5 @@ func NewServices() {
newRegisterMailService()
newNotifyMailService()
newWebhookService()
// ssh.Listen("2022")
// ssh.Listen("2222")
}

View File

@@ -7,12 +7,12 @@ package social
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
oauth "github.com/gogits/oauth2"
"github.com/macaron-contrib/oauth2"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/log"
@@ -27,16 +27,11 @@ type BasicUserInfo struct {
type SocialConnector interface {
Type() int
SetRedirectUrl(string)
UserInfo(*oauth.Token, *url.URL) (*BasicUserInfo, error)
AuthCodeURL(string) string
Exchange(string) (*oauth.Token, error)
UserInfo(*oauth2.Token, *url.URL) (*BasicUserInfo, error)
}
var (
SocialBaseUrl = "/user/login"
SocialMap = make(map[string]SocialConnector)
SocialMap = make(map[string]SocialConnector)
)
func NewOauthService() {
@@ -44,27 +39,34 @@ func NewOauthService() {
return
}
oauth2.AppSubUrl = setting.AppSubUrl
setting.OauthService = &setting.Oauther{}
setting.OauthService.OauthInfos = make(map[string]*setting.OauthInfo)
socialConfigs := make(map[string]*oauth.Config)
socialConfigs := make(map[string]*oauth2.Options)
allOauthes := []string{"github", "google", "qq", "twitter", "weibo"}
// Load all OAuth config data.
for _, name := range allOauthes {
setting.OauthService.OauthInfos[name] = &setting.OauthInfo{
ClientId: setting.Cfg.MustValue("oauth."+name, "CLIENT_ID"),
ClientSecret: setting.Cfg.MustValue("oauth."+name, "CLIENT_SECRET"),
Scopes: setting.Cfg.MustValue("oauth."+name, "SCOPES"),
AuthUrl: setting.Cfg.MustValue("oauth."+name, "AUTH_URL"),
TokenUrl: setting.Cfg.MustValue("oauth."+name, "TOKEN_URL"),
if !setting.Cfg.MustBool("oauth."+name, "ENABLED") {
continue
}
socialConfigs[name] = &oauth.Config{
ClientId: setting.OauthService.OauthInfos[name].ClientId,
setting.OauthService.OauthInfos[name] = &setting.OauthInfo{
Options: oauth2.Options{
ClientID: setting.Cfg.MustValue("oauth."+name, "CLIENT_ID"),
ClientSecret: setting.Cfg.MustValue("oauth."+name, "CLIENT_SECRET"),
Scopes: setting.Cfg.MustValueArray("oauth."+name, "SCOPES", " "),
PathLogin: "/user/login/oauth2/" + name,
PathCallback: setting.AppSubUrl + "/user/login/" + name,
RedirectURL: setting.AppUrl + "user/login/" + name,
},
AuthUrl: setting.Cfg.MustValue("oauth."+name, "AUTH_URL"),
TokenUrl: setting.Cfg.MustValue("oauth."+name, "TOKEN_URL"),
}
socialConfigs[name] = &oauth2.Options{
ClientID: setting.OauthService.OauthInfos[name].ClientID,
ClientSecret: setting.OauthService.OauthInfos[name].ClientSecret,
RedirectURL: strings.TrimSuffix(setting.AppUrl, "/") + SocialBaseUrl + name,
Scope: setting.OauthService.OauthInfos[name].Scopes,
AuthURL: setting.OauthService.OauthInfos[name].AuthUrl,
TokenURL: setting.OauthService.OauthInfos[name].TokenUrl,
Scopes: setting.OauthService.OauthInfos[name].Scopes,
}
}
enabledOauths := make([]string, 0, 10)
@@ -91,11 +93,11 @@ func NewOauthService() {
}
// Twitter.
if setting.Cfg.MustBool("oauth.twitter", "ENABLED") {
setting.OauthService.Twitter = true
newTwitterOauth(socialConfigs["twitter"])
enabledOauths = append(enabledOauths, "Twitter")
}
// if setting.Cfg.MustBool("oauth.twitter", "ENABLED") {
// setting.OauthService.Twitter = true
// newTwitterOauth(socialConfigs["twitter"])
// enabledOauths = append(enabledOauths, "Twitter")
// }
// Weibo.
if setting.Cfg.MustBool("oauth.weibo", "ENABLED") {
@@ -115,38 +117,25 @@ func NewOauthService() {
// \/ \/ \/
type SocialGithub struct {
Token *oauth.Token
*oauth.Transport
opts *oauth2.Options
}
func newGitHubOauth(opts *oauth2.Options) {
SocialMap["github"] = &SocialGithub{opts}
}
func (s *SocialGithub) Type() int {
return int(models.GITHUB)
}
func newGitHubOauth(config *oauth.Config) {
SocialMap["github"] = &SocialGithub{
Transport: &oauth.Transport{
Config: config,
Transport: http.DefaultTransport,
},
}
}
func (s *SocialGithub) SetRedirectUrl(url string) {
s.Transport.Config.RedirectURL = url
}
func (s *SocialGithub) UserInfo(token *oauth.Token, _ *url.URL) (*BasicUserInfo, error) {
transport := &oauth.Transport{
Token: token,
}
func (s *SocialGithub) UserInfo(token *oauth2.Token, _ *url.URL) (*BasicUserInfo, error) {
transport := s.opts.NewTransportFromToken(token)
var data struct {
Id int `json:"id"`
Name string `json:"login"`
Email string `json:"email"`
}
var err error
r, err := transport.Client().Get(s.Transport.Scope)
r, err := transport.Client().Get("https://api.github.com/user")
if err != nil {
return nil, err
}
@@ -169,38 +158,25 @@ func (s *SocialGithub) UserInfo(token *oauth.Token, _ *url.URL) (*BasicUserInfo,
// \/ /_____/ \/
type SocialGoogle struct {
Token *oauth.Token
*oauth.Transport
opts *oauth2.Options
}
func (s *SocialGoogle) Type() int {
return int(models.GOOGLE)
}
func newGoogleOauth(config *oauth.Config) {
SocialMap["google"] = &SocialGoogle{
Transport: &oauth.Transport{
Config: config,
Transport: http.DefaultTransport,
},
}
func newGoogleOauth(opts *oauth2.Options) {
SocialMap["google"] = &SocialGoogle{opts}
}
func (s *SocialGoogle) SetRedirectUrl(url string) {
s.Transport.Config.RedirectURL = url
}
func (s *SocialGoogle) UserInfo(token *oauth.Token, _ *url.URL) (*BasicUserInfo, error) {
transport := &oauth.Transport{Token: token}
func (s *SocialGoogle) UserInfo(token *oauth2.Token, _ *url.URL) (*BasicUserInfo, error) {
transport := s.opts.NewTransportFromToken(token)
var data struct {
Id string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
var err error
reqUrl := "https://www.googleapis.com/oauth2/v1/userinfo"
r, err := transport.Client().Get(reqUrl)
r, err := transport.Client().Get("https://www.googleapis.com/userinfo/v2/me")
if err != nil {
return nil, err
}
@@ -223,62 +199,35 @@ func (s *SocialGoogle) UserInfo(token *oauth.Token, _ *url.URL) (*BasicUserInfo,
// \__> \__>
type SocialTencent struct {
Token *oauth.Token
*oauth.Transport
reqUrl string
opts *oauth2.Options
}
func newTencentOauth(opts *oauth2.Options) {
SocialMap["qq"] = &SocialTencent{opts}
}
func (s *SocialTencent) Type() int {
return int(models.QQ)
}
func newTencentOauth(config *oauth.Config) {
SocialMap["qq"] = &SocialTencent{
reqUrl: "https://open.t.qq.com/api/user/info",
Transport: &oauth.Transport{
Config: config,
Transport: http.DefaultTransport,
},
}
}
func (s *SocialTencent) SetRedirectUrl(url string) {
s.Transport.Config.RedirectURL = url
}
func (s *SocialTencent) UserInfo(token *oauth.Token, URL *url.URL) (*BasicUserInfo, error) {
var data struct {
Data struct {
Id string `json:"openid"`
Name string `json:"name"`
Email string `json:"email"`
} `json:"data"`
}
var err error
// https://open.t.qq.com/api/user/info?
//oauth_consumer_key=APP_KEY&
//access_token=ACCESSTOKEN&openid=openid
//clientip=CLIENTIP&oauth_version=2.a
//scope=all
var urls = url.Values{
"oauth_consumer_key": {s.Transport.Config.ClientId},
"access_token": {token.AccessToken},
"openid": URL.Query()["openid"],
"oauth_version": {"2.a"},
"scope": {"all"},
}
r, err := http.Get(s.reqUrl + "?" + urls.Encode())
func (s *SocialTencent) UserInfo(token *oauth2.Token, URL *url.URL) (*BasicUserInfo, error) {
r, err := http.Get("https://graph.z.qq.com/moc2/me?access_token=" + url.QueryEscape(token.AccessToken))
if err != nil {
return nil, err
}
defer r.Body.Close()
if err = json.NewDecoder(r.Body).Decode(&data); err != nil {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
vals, err := url.ParseQuery(string(body))
if err != nil {
return nil, err
}
return &BasicUserInfo{
Identity: data.Data.Id,
Name: data.Data.Name,
Email: data.Data.Email,
Identity: vals.Get("openid"),
}, nil
}
@@ -289,54 +238,54 @@ func (s *SocialTencent) UserInfo(token *oauth.Token, URL *url.URL) (*BasicUserIn
// |____| \/\_/ |__||__| |__| \___ >__|
// \/
type SocialTwitter struct {
Token *oauth.Token
*oauth.Transport
}
// type SocialTwitter struct {
// Token *oauth2.Token
// *oauth2.Transport
// }
func (s *SocialTwitter) Type() int {
return int(models.TWITTER)
}
// func (s *SocialTwitter) Type() int {
// return int(models.TWITTER)
// }
func newTwitterOauth(config *oauth.Config) {
SocialMap["twitter"] = &SocialTwitter{
Transport: &oauth.Transport{
Config: config,
Transport: http.DefaultTransport,
},
}
}
// func newTwitterOauth(config *oauth2.Config) {
// SocialMap["twitter"] = &SocialTwitter{
// Transport: &oauth.Transport{
// Config: config,
// Transport: http.DefaultTransport,
// },
// }
// }
func (s *SocialTwitter) SetRedirectUrl(url string) {
s.Transport.Config.RedirectURL = url
}
// func (s *SocialTwitter) SetRedirectUrl(url string) {
// s.Transport.Config.RedirectURL = url
// }
//https://github.com/mrjones/oauth
func (s *SocialTwitter) UserInfo(token *oauth.Token, _ *url.URL) (*BasicUserInfo, error) {
// transport := &oauth.Transport{Token: token}
// var data struct {
// Id string `json:"id"`
// Name string `json:"name"`
// Email string `json:"email"`
// }
// var err error
// //https://github.com/mrjones/oauth
// func (s *SocialTwitter) UserInfo(token *oauth2.Token, _ *url.URL) (*BasicUserInfo, error) {
// // transport := &oauth.Transport{Token: token}
// // var data struct {
// // Id string `json:"id"`
// // Name string `json:"name"`
// // Email string `json:"email"`
// // }
// // var err error
// reqUrl := "https://www.googleapis.com/oauth2/v1/userinfo"
// r, err := transport.Client().Get(reqUrl)
// if err != nil {
// return nil, err
// }
// defer r.Body.Close()
// if err = json.NewDecoder(r.Body).Decode(&data); err != nil {
// return nil, err
// }
// return &BasicUserInfo{
// Identity: data.Id,
// Name: data.Name,
// Email: data.Email,
// }, nil
return nil, nil
}
// // reqUrl := "https://www.googleapis.com/oauth2/v1/userinfo"
// // r, err := transport.Client().Get(reqUrl)
// // if err != nil {
// // return nil, err
// // }
// // defer r.Body.Close()
// // if err = json.NewDecoder(r.Body).Decode(&data); err != nil {
// // return nil, err
// // }
// // return &BasicUserInfo{
// // Identity: data.Id,
// // Name: data.Name,
// // Email: data.Email,
// // }, nil
// return nil, nil
// }
// __ __ ._____.
// / \ / \ ____ |__\_ |__ ____
@@ -346,37 +295,25 @@ func (s *SocialTwitter) UserInfo(token *oauth.Token, _ *url.URL) (*BasicUserInfo
// \/ \/ \/
type SocialWeibo struct {
Token *oauth.Token
*oauth.Transport
opts *oauth2.Options
}
func newWeiboOauth(opts *oauth2.Options) {
SocialMap["weibo"] = &SocialWeibo{opts}
}
func (s *SocialWeibo) Type() int {
return int(models.WEIBO)
}
func newWeiboOauth(config *oauth.Config) {
SocialMap["weibo"] = &SocialWeibo{
Transport: &oauth.Transport{
Config: config,
Transport: http.DefaultTransport,
},
}
}
func (s *SocialWeibo) SetRedirectUrl(url string) {
s.Transport.Config.RedirectURL = url
}
func (s *SocialWeibo) UserInfo(token *oauth.Token, _ *url.URL) (*BasicUserInfo, error) {
transport := &oauth.Transport{Token: token}
func (s *SocialWeibo) UserInfo(token *oauth2.Token, _ *url.URL) (*BasicUserInfo, error) {
transport := s.opts.NewTransportFromToken(token)
var data struct {
Name string `json:"name"`
}
var err error
var urls = url.Values{
"access_token": {token.AccessToken},
"uid": {token.Extra["id_token"]},
"uid": {token.Extra("uid")},
}
reqUrl := "https://api.weibo.com/2/users/show.json"
r, err := transport.Client().Get(reqUrl + "?" + urls.Encode())
@@ -384,11 +321,12 @@ func (s *SocialWeibo) UserInfo(token *oauth.Token, _ *url.URL) (*BasicUserInfo,
return nil, err
}
defer r.Body.Close()
if err = json.NewDecoder(r.Body).Decode(&data); err != nil {
return nil, err
}
return &BasicUserInfo{
Identity: token.Extra["id_token"],
Identity: token.Extra("uid"),
Name: data.Name,
}, nil
}

View File

@@ -13,9 +13,8 @@ import (
"os/exec"
"strings"
"code.google.com/p/go.crypto/ssh"
"github.com/Unknwon/com"
"golang.org/x/crypto/ssh"
"github.com/gogits/gogs/modules/log"
)
@@ -35,8 +34,11 @@ func handleServerConn(keyId string, chans <-chan ssh.NewChannel) {
go func(in <-chan *ssh.Request) {
defer channel.Close()
for req := range in {
ok, payload := false, strings.TrimLeft(string(req.Payload), "\x00")
ok, payload := false, strings.TrimLeft(string(req.Payload), "\x00&")
fmt.Println("Request:", req.Type, req.WantReply, payload)
if req.WantReply {
fmt.Println(req.Reply(true, nil))
}
switch req.Type {
case "env":
args := strings.Split(strings.Replace(payload, "\x00", "", -1), "\v")
@@ -54,7 +56,7 @@ func handleServerConn(keyId string, chans <-chan ssh.NewChannel) {
case "exec":
os.Setenv("SSH_ORIGINAL_COMMAND", strings.TrimLeft(payload, "'("))
log.Info("Payload: %v", strings.TrimLeft(payload, "'("))
cmd := exec.Command("/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs-ng/gogs-ng", "serv", "key-"+keyId)
cmd := exec.Command("/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/gogs", "serv", "key-"+keyId)
cmd.Stdout = channel
cmd.Stdin = channel
cmd.Stderr = channel.Stderr()
@@ -65,7 +67,6 @@ func handleServerConn(keyId string, chans <-chan ssh.NewChannel) {
}
}
fmt.Println("Done:", ok)
req.Reply(ok, nil) // BUG: Git on Mac seems not know this reply and hang?
}
fmt.Println("Done!!!")
}(requests)
@@ -101,7 +102,7 @@ func Listen(port string) {
config := &ssh.ServerConfig{
PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
// keyCache[string(ssh.MarshalAuthorizedKey(key))] = 2
return &ssh.Permissions{Extensions: map[string]string{"key-id": "2"}}, nil
return &ssh.Permissions{Extensions: map[string]string{"key-id": "1"}}, nil
},
}

View File

@@ -2,18 +2,6 @@
set -e
# summary of how this script can be called:
# * <postinst> `configure' <most-recently-configured-version>
# * <old-postinst> `abort-upgrade' <new version>
# * <conflictor's-postinst> `abort-remove' `in-favour' <package>
# <new-version>
# * <postinst> `abort-remove'
# * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
# <failed-install-package> <version> `removing'
# <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package
APP_NAME="gogs"
CLI="${APP_NAME}"
APP_USER=$(${CLI} config:get APP_USER)
@@ -21,28 +9,27 @@ APP_GROUP=$(${CLI} config:get APP_GROUP)
APP_CONFIG="/etc/${APP_NAME}/conf/app.ini"
case "$1" in
abort-upgrade|abort-remove|abort-deconfigure)
exit 0
;;
configure)
configure|*)
mkdir -p $(dirname ${APP_CONFIG})
chown ${APP_USER}.${APP_GROUP} $(dirname ${APP_CONFIG})
[ -f ${APP_CONFIG} ] || ${CLI} run cp conf/app.ini ${APP_CONFIG}
${CLI} config:set USER=${APP_USER}
${CLI} config:set GOGS_CUSTOM="/etc/${APP_NAME}"
PORT=$(${CLI} config:get PORT || echo "6000")
sed -i "s|HTTP_PORT = 3000|HTTP_PORT = ${PORT}|" ${APP_CONFIG}
sed -i "s|RUN_USER = git|RUN_USER = ${APP_USER}|" ${APP_CONFIG}
sed -i "s|RUN_MODE = dev|RUN_MODE = prod|" ${APP_CONFIG}
# setup symlink towards custom conf
mkdir -p /opt/${APP_NAME}/custom/conf
chown -R ${APP_USER}.${APP_GROUP} /opt/${APP_NAME}/custom
ln -f -s ${APP_CONFIG} /opt/${APP_NAME}/custom/conf/app.ini
# scale
${CLI} scale web=1 || true
;;
abort-upgrade|abort-remove|abort-deconfigure)
exit 0
;;
*)
echo "postinst called with unknown argument \`$1'" >&2
exit 1
;;
esac

View File

@@ -303,6 +303,9 @@ var Gogits = {};
// api working
Gogits.getUsers = function (val, $target) {
var notEmpty = function (str) {
return str && str.length > 0;
}
$.ajax({
url: '/api/v1/users/search?q=' + val,
dataType: "json",
@@ -310,7 +313,11 @@ var Gogits = {};
if (json.ok && json.data.length) {
var html = '';
$.each(json.data, function (i, item) {
html += '<li><img src="' + item.avatar + '">' + item.username + '</li>';
html += '<li><img src="' + item.avatar + '">' + item.username;
if (notEmpty(item.full_name)) {
html += ' (' + item.full_name + ')';
}
html += '</li>';
});
$target.toggleShow();
$target.find('ul').html(html);

View File

@@ -95,7 +95,7 @@ img.avatar-100 {
}
#header {
background-color: #428bca;
height: 44px;
height: 45px;
}
#header > .menu-line > li > a {
display: inline-block;
@@ -120,14 +120,14 @@ img.avatar-100 {
height: 44px;
}
#header-nav-user img {
margin: -4px 10px 0 0;
margin: -2px 10px 0 0;
border-radius: 3px;
}
#header-nav-sign-out > a:hover {
color: #ff908b !important;
}
#header-nav-logo {
padding: 6px 1.2em;
padding: 6px 1.2em 6px 0;
}
#header-nav-explore,
#header-nav-help {
@@ -240,6 +240,9 @@ img.avatar-100 {
.text-black {
color: #444444;
}
.text-gold {
color: #a1882b;
}
.table {
width: 100%;
max-width: 100%;
@@ -271,6 +274,10 @@ img.avatar-100 {
.pagination li {
display: inline;
}
.list-unstyled {
padding-left: 0;
list-style: none;
}
.markdown {
background-color: white;
font-size: 16px;
@@ -333,6 +340,30 @@ img.avatar-100 {
padding: 5px 15px;
color: #777;
}
.markdown table {
width: 100%;
overflow: auto;
word-break: normal;
margin: 15px 0;
border-collapse: collapse;
border-spacing: 0;
display: block;
}
.markdown table th {
font-weight: 700;
}
.markdown table th,
.markdown table td {
border: 1px solid #DDD;
padding: 6px 13px !important;
}
.markdown table tr {
background-color: #FFF;
border-top: 1px solid #CCC;
}
.markdown table tr:nth-child(2n) {
background-color: #F8F8F8;
}
.markdown a {
color: #428BCA;
}
@@ -369,29 +400,6 @@ img.avatar-100 {
.markdown h4 {
font-size: 18px;
}
.markdown table {
border-collapse: collapse;
border-spacing: 0;
display: block;
overflow: auto;
width: 100%;
margin: 0 0 9px;
}
.markdown table th {
font-weight: 700;
}
.markdown table th,
.markdown table td {
border: 1px solid #DDD;
padding: 6px 13px;
}
.markdown table tr {
background-color: #FFF;
border-top: 1px solid #CCC;
}
.markdown table tr:nth-child(2n) {
background-color: #f8f8f8;
}
.markdown dl dt {
font-style: italic;
margin-top: 9px;
@@ -712,6 +720,12 @@ ol.linenums {
#dashboard-header > .menu-line > li {
padding: 12px 6px;
}
#dashboard-header > .menu-line > li.drop {
margin-left: -22px;
}
#dashboard-header > .menu-line > li.drop:hover a {
background-color: transparent;
}
#dashboard-header > .menu-line > li.right > a {
font-size: 1.2em;
color: #444444;
@@ -866,6 +880,7 @@ ol.linenums {
}
#dashboard-selection-menu > .drop-down {
top: 56px;
left: 22px;
}
#dashboard-selection-menu li {
white-space: nowrap;
@@ -915,7 +930,7 @@ ol.linenums {
color: #CCC;
}
#dashboard-news .news .avatar {
margin: 0 1.2em;
margin-right: 1.2em;
}
#dashboard-news .news .news-content,
#dashboard-news .news .news-time {
@@ -976,7 +991,6 @@ The register and sign-in page style
background-color: #FFF;
margin-left: -15px;
}
/* repository main */
#repo-wrapper {
padding-bottom: 100px;
}
@@ -1039,9 +1053,9 @@ The register and sign-in page style
}
#repo-header-download-drop {
line-height: 24px;
width: 440px;
width: 460px;
top: 50px;
left: -370px;
left: -390px;
padding: 20px;
box-sizing: border-box;
z-index: 1;
@@ -1053,11 +1067,16 @@ The register and sign-in page style
#repo-header-download-drop input {
font-size: 11px;
}
#repo-header-download-drop #repo-clone-copy {
width: 85px;
text-overflow: clip;
}
#repo-content {
padding: 18px 0;
padding-top: 18px;
padding-bottom: 18px;
}
.repo-wide-wrapper {
padding: 18px 0;
padding: 18px;
position: relative;
}
#repo-clone-url {
@@ -1247,6 +1266,7 @@ The register and sign-in page style
color: #444;
}
#repo-files-table thead .last-commit .text-truncate {
max-width: 440px;
margin-left: .4em;
}
#repo-files-table thead .last-commit .text-truncate,
@@ -1334,31 +1354,54 @@ The register and sign-in page style
#repo-create-cancel {
margin-left: 4em;
}
#release-new-target-branch-list,
#repo-create-owner-list {
top: 30px;
left: 0;
width: auto;
max-width: 300px;
}
#release-new-target-branch-list .octicon,
#repo-create-owner-list .octicon {
margin-right: 12px;
opacity: 0;
}
#release-new-target-branch-list .avatar,
#repo-create-owner-list .avatar {
width: 20px;
height: 20px;
}
#release-new-target-branch-list li,
#repo-create-owner-list li {
white-space: nowrap;
}
#release-new-target-branch-list li.checked .octicon,
#repo-create-owner-list li.checked .octicon {
opacity: 1;
}
#release-new-target-branch-list li a,
#repo-create-owner-list li a {
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
overflow: hidden;
}
#release-new-target-branch-list {
margin-top: -1px;
min-width: 150px;
}
#release-new-title {
margin-top: 10px;
}
#release-new-content {
width: 100%;
}
#release-preview-btn .btn {
border-left: 0;
}
#release-preview.markdown {
margin-top: 5px;
background-color: transparent;
}
.file-name {
margin-left: 1em;
}
@@ -1398,12 +1441,10 @@ The register and sign-in page style
}
.code-view .lines-num span {
font-family: Monaco, Menlo, Consolas, "Courier New", monospace;
line-height: 18px;
padding: 0 8px 0 10px;
line-height: 20px;
padding: 0 10px;
cursor: pointer;
display: block;
margin-top: 2px;
font-size: 12px;
}
.code-view .lines-code > pre {
border: none;
@@ -1411,6 +1452,7 @@ The register and sign-in page style
}
.code-view .lines-code > pre > ol.linenums > li {
padding: 0 10px;
line-height: 20px;
}
.code-view .lines-code > pre > ol.linenums > li.active {
background: #ffffdd;
@@ -1487,6 +1529,204 @@ The register and sign-in page style
font-family: Consolas, Menlo, Monaco, "Lucida Console", monospace;
font-size: 14px;
}
.commit-list .message {
width: 60%;
}
.commit-list .message span {
max-width: 500px;
}
.commit-message {
white-space: pre-wrap;
}
.diff-head-box {
margin-top: 10px;
}
.diff-head-box .panel-body {
padding: 10px 15px 5px 10px;
}
.diff-head-box .author img {
margin-top: -7px;
}
.diff-detail-box {
margin: 15px 0;
line-height: 30px;
}
.diff-detail-box ol {
clear: both;
padding-left: 0;
margin-bottom: 28px;
}
.diff-detail-box ol li {
list-style: none;
padding-bottom: 4px;
margin-bottom: 4px;
border-bottom: 1px dashed #DDD;
padding-left: 6px;
}
.diff-detail-box span.status {
display: inline-block;
width: 12px;
height: 12px;
margin-right: 8px;
vertical-align: middle;
}
.diff-detail-box span.status.modify {
background-color: #f0db88;
}
.diff-detail-box span.status.add {
background-color: #b4e2b4;
}
.diff-detail-box span.status.del {
background-color: #e9aeae;
}
.diff-detail-box span.status.rename {
background-color: #dad8ff;
}
.diff-box .count {
margin-right: 12px;
}
.diff-box .count .bar {
background-color: #e75316;
height: 12px;
width: 40px;
display: inline-block;
margin: 2px 4px 0 4px;
vertical-align: text-top;
}
.diff-box .count .bar .add {
background-color: #77c64a;
height: 12px;
}
.diff-box .file {
color: #888;
}
.diff-box .panel-header {
font-size: 14px;
}
.diff-file-box .file-body.file-code .lines-num {
text-align: right;
color: #999;
background: #fafafa;
width: 1%;
}
.diff-file-box .file-body.file-code .lines-num-old {
border-right: 1px solid #DDD;
}
.diff-file-box .code-diff tbody tr.tag-code td,
.diff-file-box .code-diff tbody tr.tag-code pre {
background-color: #E0E0E0 !important;
border-color: #ADADAD !important;
}
.diff-file-box .code-diff tbody tr.del-code td,
.diff-file-box .code-diff tbody tr.del-code pre {
background-color: #ffe2dd !important;
border-color: #e9aeae !important;
}
.diff-file-box .code-diff tbody tr.add-code td,
.diff-file-box .code-diff tbody tr.add-code pre {
background-color: #d1ffd6 !important;
border-color: #b4e2b4 !important;
}
.diff-file-box .code-diff tbody tr:hover td,
.diff-file-box .code-diff tbody tr:hover pre {
background-color: #FFF8D2 !important;
border-color: #F0DB88 !important;
}
.compare-head-box {
margin-top: 10px;
}
.compare-head-box .compare {
padding: 0 15px 15px 15px;
}
.fork-flag {
display: block;
font-size: 11px;
line-height: 10px;
white-space: nowrap;
margin-left: 44px;
margin-top: -15px;
}
#release h4 {
font-size: 18px;
}
#release h4 small {
font-weight: 400;
line-height: 1;
color: #999;
}
#release #release-head {
margin-top: 0;
margin-bottom: 0;
padding-bottom: 20px;
border-bottom: 1px solid #DDD;
}
#release #release-head .btn {
margin-left: 10px;
}
#release .release-item > div {
padding-top: 20px;
padding-bottom: 20px;
}
#release .release-item .label-green:hover {
background-color: #65ad4e;
}
#release .release-item .release-meta {
position: relative;
float: left;
padding-right: 15px;
}
#release .release-item .tag,
#release .release-item .commit {
display: block;
margin-top: 12px;
line-height: 20px;
}
#release .release-item .release-detail {
margin-top: -1px;
border-left: 1px solid #DDD;
position: relative;
float: left;
padding-left: 15px;
}
#release .release-item .title {
line-height: 25px;
margin-top: 0;
}
#release .release-item p.info {
line-height: 20px;
color: #666;
margin-bottom: 15px;
}
#release .release-item p.info > * {
margin-right: 10px;
}
#release .release-item .author img {
margin-top: -3px;
}
#release .release-item div.desc {
margin-bottom: 25px;
}
#release .release-item div.desc.markdown {
background-color: transparent;
}
#release .release-item .download a {
margin-right: 10px;
}
#release .release-item .dot {
width: 9px;
height: 9px;
background-color: #ccc;
z-index: 999;
position: absolute;
display: block;
left: -6px;
top: 27px;
border-radius: 6px;
border: 1px solid #FFF;
}
#release #release-new-form {
padding-top: 15px;
}
#admin-wrapper,
#setting-wrapper {
padding-bottom: 100px;
@@ -1569,18 +1809,21 @@ The register and sign-in page style
#repo-hooks-panel,
#repo-hooks-history-panel,
#user-social-panel,
#user-applications-panel,
#user-ssh-panel {
margin-bottom: 20px;
}
#repo-hooks-panel .setting-list,
#repo-hooks-history-panel .setting-list,
#user-social-panel .setting-list,
#user-applications-panel .setting-list,
#user-ssh-panel .setting-list {
background-color: #FFF;
}
#repo-hooks-panel .setting-list li,
#repo-hooks-history-panel .setting-list li,
#user-social-panel .setting-list li,
#user-applications-panel .setting-list li,
#user-ssh-panel .setting-list li {
padding: 8px 20px;
border-bottom: 1px solid #eaeaea;
@@ -1588,18 +1831,21 @@ The register and sign-in page style
#repo-hooks-panel .setting-list li.ssh:hover,
#repo-hooks-history-panel .setting-list li.ssh:hover,
#user-social-panel .setting-list li.ssh:hover,
#user-applications-panel .setting-list li.ssh:hover,
#user-ssh-panel .setting-list li.ssh:hover {
background-color: #ffffEE;
}
#repo-hooks-panel .setting-list li i,
#repo-hooks-history-panel .setting-list li i,
#user-social-panel .setting-list li i,
#user-applications-panel .setting-list li i,
#user-ssh-panel .setting-list li i {
padding-right: 5px;
}
#repo-hooks-panel .active-icon,
#repo-hooks-history-panel .active-icon,
#user-social-panel .active-icon,
#user-applications-panel .active-icon,
#user-ssh-panel .active-icon {
width: 10px;
height: 10px;
@@ -1611,43 +1857,60 @@ The register and sign-in page style
#repo-hooks-panel .ssh-content,
#repo-hooks-history-panel .ssh-content,
#user-social-panel .ssh-content,
#user-applications-panel .ssh-content,
#user-ssh-panel .ssh-content {
margin-left: 24px;
}
#repo-hooks-panel .ssh-content .octicon,
#repo-hooks-history-panel .ssh-content .octicon,
#user-social-panel .ssh-content .octicon,
#user-applications-panel .ssh-content .octicon,
#user-ssh-panel .ssh-content .octicon {
margin-right: 4px;
}
#repo-hooks-panel .ssh-content .print,
#repo-hooks-history-panel .ssh-content .print,
#user-social-panel .ssh-content .print,
#user-applications-panel .ssh-content .print,
#user-ssh-panel .ssh-content .print,
#repo-hooks-panel .ssh-content .access,
#repo-hooks-history-panel .ssh-content .access,
#user-social-panel .ssh-content .access,
#user-applications-panel .ssh-content .access,
#user-ssh-panel .ssh-content .access,
#repo-hooks-panel .ssh-content .activity,
#repo-hooks-history-panel .ssh-content .activity,
#user-social-panel .ssh-content .activity,
#user-applications-panel .ssh-content .activity,
#user-ssh-panel .ssh-content .activity {
color: #888;
}
#repo-hooks-panel .ssh-delete-btn,
#repo-hooks-history-panel .ssh-delete-btn,
#user-social-panel .ssh-delete-btn,
#user-ssh-panel .ssh-delete-btn {
#repo-hooks-panel .ssh-content .access,
#repo-hooks-history-panel .ssh-content .access,
#user-social-panel .ssh-content .access,
#user-applications-panel .ssh-content .access,
#user-ssh-panel .ssh-content .access {
max-width: 500px;
}
#repo-hooks-panel .ssh-btn,
#repo-hooks-history-panel .ssh-btn,
#user-social-panel .ssh-btn,
#user-applications-panel .ssh-btn,
#user-ssh-panel .ssh-btn {
margin-top: 6px;
}
#user-ssh-add-form .panel-body {
.form-settings-add .panel-body {
background-color: #FFF;
padding: 30px 0;
}
#user-ssh-add-form .ipt {
.form-settings-add .ipt {
width: 500px;
}
#user-ssh-add-form textarea {
.form-settings-add textarea {
height: 120px;
margin-left: 3px;
}
#user-ssh-add-form .field {
.form-settings-add .field {
margin-bottom: 24px;
}
.pr-main {
@@ -1849,6 +2112,253 @@ textarea#issue-add-content {
height: 120px;
resize: vertical;
}
#issue-list-nav {
border-bottom: 1px solid #DDD;
padding-bottom: 12px;
}
#issue-list-nav li > a {
font-size: 13px;
font-weight: bold;
padding: .2em .8em;
}
#issue-list-nav li.current > a {
background-color: #0079bc;
color: #FAFAFA;
}
#issue-list-nav li.right {
margin-left: 4px;
}
#issue-new > a,
#label-new > a,
#milestone-new > a {
padding: 0 !important;
}
#issue-new > a button,
#label-new > a button,
#milestone-new > a button {
height: 29px;
}
#issue-list-menu {
padding: 16px 0 12px 0;
border-bottom: 1px solid #BBB;
margin-bottom: 12px;
}
#issue-list-menu .mark a {
color: #AAA;
}
#issue-list-menu .mark a:hover {
color: #444;
}
#issue-list-menu .mark.hover a {
color: #222;
font-weight: bold;
}
#issue-list-menu > .left .mark {
margin-right: 12px;
}
#issue-list-menu > .right .mark {
margin-left: 12px;
}
#issue-list .item,
#pull-list .item {
position: relative;
padding-bottom: 12px;
margin-bottom: 12px;
border-bottom: 1px dashed #AAA;
}
#issue-list .item .title > .title-text,
#pull-list .item .title > .title-text {
color: #444;
font-size: 15px;
margin: 0 6px;
}
#issue-list .comment,
#pull-list .comment {
color: #666;
position: absolute;
top: 6px;
right: 0;
}
#issue-list .issue-label a,
#pull-list .issue-label a {
color: #FFF;
}
#issue-list .desc,
#pull-list .desc {
color: #999;
}
#issue-list .desc a,
#pull-list .desc a {
color: #999;
}
#issue-list .desc a:hover,
#pull-list .desc a:hover {
color: #03a2ef;
}
#issue-list-filter .drop > a {
width: 90px;
padding: 0;
margin-left: 12px;
text-align: center;
}
#issue-list-filter .drop-down {
z-index: 999;
width: 236px;
left: -158px;
top: 22px;
padding: 0 12px;
}
#issue-list-filter .drop-down h4 {
line-height: 40px;
border-bottom: 1px solid #CCC;
margin-bottom: 0;
}
#issue-list-filter .drop-down li {
line-height: 30px;
border-bottom: 1px dashed #EEE;
padding-left: 9px;
}
#issue-list-filter .drop-down li:hover {
background-color: #fcffec;
}
#issue-list-filter .drop-down > ul > li > a {
display: block;
}
#issue-list-filter .labels .color {
margin-top: 8px;
display: inline-block;
width: 12px;
height: 12px;
background-color: red;
margin-right: 9px;
margin-left: 9px;
}
#issue-list-filter .labels .name {
vertical-align: top;
display: inline-block;
color: #444;
}
#issue-list-filter .milestones a {
color: #444;
font-weight: bold;
}
#issue-list-pager {
margin: 18px 0 24px 0;
font-size: 14px;
line-height: 24px;
}
#labels-num {
margin-right: 1em;
}
#label-list .right {
margin-left: 1em;
color: #999;
line-height: 30px;
}
#label-list .right i {
margin-right: 3px;
}
#label-list .right:hover {
color: #444444;
}
#label-list .num {
margin-right: 3px;
}
#label-list .issue-num {
margin-right: 4em;
}
#label-list .label:hover {
color: #FFF;
}
#label-list .label i {
margin-right: 6px;
}
#label-list .item {
height: 30px;
padding-bottom: 12px;
margin-bottom: 12px;
border-bottom: 1px dashed #AAA;
}
#label-add-form {
padding: 18px 0;
border-bottom: 1px solid #DDD;
}
#label-add-form .ipt {
font-size: 14px;
}
#label-add-form .ipt[name=name] {
width: 300px;
}
#label-add-form .btn {
height: 33px;
font-size: 14px;
margin-left: 12px;
}
#label-color-drop .ipt {
width: 100px;
}
#label-color-drop .drop-down {
width: 128px;
top: 22px;
left: 50px;
padding: 12px;
line-height: 16px;
}
#label-color-drop .drop-down a.color {
width: 16px;
height: 16px;
display: inline-block;
}
#label-color-drop label {
width: 24px;
height: 24px;
display: inline-block;
margin: 0 1em;
vertical-align: middle;
}
#milestone-list {
padding-top: 6px;
}
#milestone-list .title-text {
font-size: 16px;
}
#milestone-list .desc {
color: #999;
line-height: 30px;
}
#milestone-list .content {
width: 400px;
}
#milestone-list .item {
padding-bottom: 18px;
margin-bottom: 18px;
border-bottom: 1px dashed #AAA;
position: relative;
}
#milestone-list .action {
position: absolute;
top: 0;
right: 0;
}
#milestone-list .status-bar > .bar {
margin: -2px 8px 0 8px;
width: 360px;
background-color: #DDD;
height: 14px;
vertical-align: middle;
}
#milestone-list .status-bar .opening {
background-color: #65ad4e;
width: 40%;
height: 14px;
vertical-align: top;
}
#milestone-list .action-bar {
margin-top: 8px;
}
#milestone-list .action-bar a {
margin-left: 12px;
}
.org-header-alert .alert {
margin-top: 10px;
}
@@ -2085,8 +2595,7 @@ textarea#issue-add-content {
margin-left: 240px;
}
.profile-avatar {
width: 200px;
height: 200px;
width: 100%;
border-radius: 6px;
}
#profile-name {
@@ -2100,7 +2609,6 @@ textarea#issue-add-content {
font-weight: bold;
}
.profile-info {
padding: 0 50px;
font-size: 14px;
}
.profile-info ul {
@@ -2137,3 +2645,6 @@ textarea#issue-add-content {
#profile-header li .current {
border-bottom: 2px solid #D26911;
}
#profile-body {
margin-left: 20px;
}

View File

@@ -4,7 +4,7 @@
}
html {
font-size: 13px;
font-family: Helvetica, "Microsoft Yahei", Menlo, Monaco, Consolas, "Courier New", monospace;
font-family: Helvetica, "Microsoft Yahei", Arial, sans-serif;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
line-height: 24px;
@@ -16,7 +16,7 @@ textarea,
select,
option,
button {
font-family: Helvetica, "Microsoft Yahei", Menlo, Monaco, Consolas, "Courier New", monospace;
font-family: Helvetica, "Microsoft Yahei", Arial, sans-serif;
}
article,
aside,
@@ -151,7 +151,7 @@ code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-family: monospace;
font-size: 1em;
}
.text-left {
@@ -366,6 +366,9 @@ dt {
.grid-4-5 {
width: 80%;
}
.btn {
white-space: nowrap;
}
.btn-small {
font-size: 10.8px;
padding: .4em .9em;
@@ -376,6 +379,7 @@ dt {
}
.btn-large {
font-size: 14.4px;
padding: .4em .9em;
}
.btn-green {
background-color: #65ad4e;
@@ -457,6 +461,9 @@ dt {
box-sizing: content-box;
text-align: center;
}
.btn-comb {
margin-left: -1px;
}
.btn-disabled {
opacity: .6;
cursor: not-allowed;
@@ -713,6 +720,14 @@ ul.menu-radius > li:last-child > a {
border-bottom-left-radius: .3em;
border-bottom-right-radius: .3em;
}
.panel.panel-info {
border-color: #85c5e5;
}
.panel.panel-info > .panel-header {
color: #31708f;
background-color: #d9edf7;
border-color: #85c5e5;
}
.panel.panel-warning {
border-color: #F0C36D;
}
@@ -721,7 +736,7 @@ ul.menu-radius > li:last-child > a {
border-color: #F0C36D;
}
.label {
padding: 2px 6px;
padding: .3em .6em .2em .6em;
color: #ffffff;
}
.label-red {
@@ -867,3 +882,30 @@ table td {
.table-radius tbody tr:last-child > td:last-child {
border-bottom-right-radius: .3em;
}
.pager .page {
padding: .3em .5em .2em .5em;
margin: 0 .3em;
background-color: #cccccc;
color: #444444;
}
.pager .page:hover,
.pager .page.hover {
background-color: #428bca;
color: #ffffff;
}
.pager .prev,
.pager .next {
padding: .4em .6em;
margin: 0 .3em;
background-color: #505050;
color: #fafafa;
}
.pager .prev.invalid,
.pager .next.invalid {
background-color: #eeeeee;
color: #aaaaaa;
cursor: not-allowed;
}
.pager .page-radius {
border-radius: .2em;
}

View File

@@ -2,6 +2,7 @@
// @codekit-prepend "lib/lib.js"
// @codekit-prepend "utils/tabs.js"
// @codekit-prepend "utils/preview.js"
// @codekit-prepend "gogs/issue_label.js"
// @codekit-prepend "lib/jquery.tipsy.js"
var Gogs = {};
@@ -203,6 +204,9 @@ var Gogs = {};
// Search users by keyword.
Gogs.searchUsers = function (val, $target) {
var notEmpty = function (str) {
return str && str.length > 0;
}
$.ajax({
url: Gogs.AppSubUrl + '/api/v1/users/search?q=' + val,
dataType: "json",
@@ -210,7 +214,11 @@ var Gogs = {};
if (json.ok && json.data.length) {
var html = '';
$.each(json.data, function (i, item) {
html += '<li><a><img src="' + item.avatar + '">' + item.username + '</a></li>';
html += '<li><a><img src="' + item.avatar_url + '">' + item.username;
if (notEmpty(item.full_name)) {
html += ' (' + item.full_name + ')';
}
html += '</a></li>';
});
$target.html(html);
$target.toggleShow();
@@ -230,7 +238,7 @@ var Gogs = {};
if (json.ok && json.data.length) {
var html = '';
$.each(json.data, function (i, item) {
html += '<li><a><span class="octicon octicon-repo"></span> ' + item.repolink + '</a></li>';
html += '<li><a><span class="octicon octicon-repo"></span> ' + item.full_name + '</a></li>';
});
$target.html(html);
$target.toggleShow();
@@ -299,6 +307,12 @@ function initCore() {
e.preventDefault();
$.magnificPopup.close();
});
// Plugins.
$('.collapse').hide();
$('.tipsy-tooltip').tipsy({
fade: true
});
}
function initUserSetting() {
@@ -326,9 +340,9 @@ function initUserSetting() {
$profile_form.submit();
});
// Show add SSH key panel.
$('#ssh-add').click(function () {
$('#user-ssh-add-form').removeClass("hide");
// Show panels.
$('.show-form-btn').click(function () {
$($(this).data('target-form')).removeClass("hide");
});
// Confirmation of delete account.
@@ -389,6 +403,16 @@ function initRepo() {
$clone_btn.tipsy({
fade: true
});
// Markdown preview.
$('.markdown-preview').click(function() {
var $this = $(this);
$this.toggleAjax(function (resp) {
$($this.data("preview")).html(resp);
}, function () {
$($this.data("preview")).html("no content");
})
});
}
// when user changes hook type, hide/show proper divs
@@ -409,6 +433,18 @@ function initHookTypeChange() {
});
}
function initRepoRelease() {
$('#release-new-target-branch-list li').click(function() {
if (!$(this).hasClass('checked')) {
$('#repo-branch-current').text($(this).text());
$('#tag-target').val($(this).text());
$(this).parent().find('.checked').removeClass('checked');
$(this).addClass('checked');
}
})
}
function initRepoSetting() {
// Options.
// Confirmation of changing repository name.
@@ -698,6 +734,37 @@ function initProfile() {
});
}
function initTimeSwitch() {
// Time switch.
$(".time-since[title]").on("click", function () {
var $this = $(this);
var title = $this.attr("title");
var text = $this.text();
$this.text(title);
$this.attr("title", text);
});
}
function initDiff() {
$('.diff-detail-box>a').click(function () {
$($(this).data('target')).slideToggle(100);
})
var $counter = $('.diff-counter');
if ($counter.length < 1) {
return;
}
$counter.each(function (i, item) {
var $item = $(item);
var addLine = $item.find('span[data-line].add').data("line");
var delLine = $item.find('span[data-line].del').data("line");
var addPercent = parseFloat(addLine) / (parseFloat(addLine) + parseFloat(delLine)) * 100;
$item.find(".bar .add").css("width", addPercent + "%");
});
}
$(document).ready(function () {
Gogs.AppSubUrl = $('head').data('suburl') || '';
initCore();
@@ -708,8 +775,12 @@ $(document).ready(function () {
initRepoCreate();
}
if ($('#repo-header').length) {
initTimeSwitch();
initRepo();
}
if ($('#release').length) {
initRepoRelease();
}
if ($('#repo-setting').length) {
initRepoSetting();
}
@@ -737,6 +808,10 @@ $(document).ready(function () {
if ($('#user-profile-page').length) {
initProfile();
}
if ($('#diff-page').length) {
initTimeSwitch();
initDiff();
}
$('#dashboard-sidebar-menu').tabs();
$('#pull-issue-preview').markdown_preview(".issue-add-comment");
@@ -770,3 +845,7 @@ function homepage() {
$('#promo-form').attr('action', Gogs.AppSubUrl + '/user/sign_up');
});
}
String.prototype.endsWith = function (suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

View File

@@ -0,0 +1,43 @@
// when dom ready, init issue label events
$(document).ready(function(){
var labelColors = ["#e11d21","#EB6420","#FBCA04","#009800",
"#006B75","#207DE5","#0052cc","#53E917",
"#F6C6C7","#FAD8C7","#FEF2C0","#BFE5BF",
"#BFDADC","#C7DEF8","#BFD4F2","#D4C5F9"];
var colorDropHtml = "";
labelColors.forEach(function(item){
colorDropHtml += '<a class="color" style="background-color:'+item+'" data-color-hex="'+item+'"></a>';
});
// render label color input
var color_input = $('#label-add-color');
var color_label = $('#label-color-drop label');
color_label.css("background-color",labelColors[0]);
color_input.val(labelColors[0]);
// render label color drop
$('#label-color-drop .drop-down')
.html(colorDropHtml)
.on("click","a",function(){
var color = $(this).data("color-hex");
color_label.css("background-color",color);
color_input.val(color);
});
// color drop visible
var form = $('#label-add-form');
$('#label-new-btn').on("click",function(){
if(form.hasClass("hidden")){
form.removeClass("hidden");
}
});
$('#label-cancel-btn').on("click",function(){
form.addClass("hidden");
})
});

File diff suppressed because one or more lines are too long

View File

@@ -110,7 +110,7 @@ clear: both;
}
#header {
background-color: @headerBgColor;
height: 44px;
height: 45px;
> .menu-line {
> li > a {
display: inline-block;
@@ -136,7 +136,7 @@ clear: both;
#header-nav-user {
height: 44px;
img {
margin: -4px 10px 0 0;
margin: -2px 10px 0 0;
border-radius: 3px;
}
}
@@ -144,7 +144,7 @@ clear: both;
color: @headerSignOutColor !important;
}
#header-nav-logo {
padding: 6px 1.2em;
padding: 6px 1.2em 6px 0;
}
#header-nav-explore,
#header-nav-help {
@@ -259,6 +259,9 @@ clear: both;
.text-black {
color: #444444;
}
.text-gold {
color: #a1882b;
}
.table {
width: 100%;
max-width: 100%;
@@ -291,4 +294,8 @@ clear: both;
li {
display: inline;
}
}
.list-unstyled {
padding-left: 0;
list-style: none;
}

View File

@@ -17,6 +17,12 @@
> li {
padding: 12px 6px;
}
> li.drop{
margin-left: -22px;
&:hover a {
background-color: transparent;
}
}
> li.right {
> a {
font-size: 1.2em;
@@ -126,7 +132,7 @@
.repo-contrib-header {
border-top: 1px solid #d6d6d6;
}
.panel-header{
.panel-header {
font-size: 14px;
}
}
@@ -173,6 +179,7 @@
max-width: 300px;
> .drop-down {
top: 56px;
left: 22px;
}
li {
white-space: nowrap;
@@ -221,14 +228,14 @@
border-bottom-right-radius: .3em;
}
#dashboard-news {
padding-bottom: 60px;
padding-bottom: 60px;
.news {
margin-right: 2.4em;
.mega-octicon {
color: #CCC;
}
.avatar {
margin: 0 1.2em;
margin-right: 1.2em;
}
.news-content,
.news-time {

View File

@@ -220,4 +220,286 @@ textarea#issue-add-content {
box-sizing: border-box;
height: 120px;
resize: vertical;
}
// #issue list navigator
#issue-list-nav {
border-bottom: 1px solid #DDD;
padding-bottom: 12px;
li {
> a {
font-size: 13px;
font-weight: bold;
padding: .2em .8em;
}
}
li.current {
> a {
background-color: #0079bc;
color: #FAFAFA;
}
}
li.right {
margin-left: 4px;
}
}
// new issue button
#issue-new,
#label-new,
#milestone-new{
> a {
padding: 0 !important;
button {
height: 29px;
}
}
}
// issue list menu
#issue-list-menu {
padding: 16px 0 12px 0;
border-bottom: 1px solid #BBB;
margin-bottom: 12px;
.mark {
a {
color: #AAA;
&:hover {
color: #444;
}
}
&.hover {
a {
color: #222;
font-weight: bold;
}
}
}
> .left {
.mark {
margin-right: 12px;
}
}
> .right {
.mark {
margin-left: 12px;
}
}
}
// each issue list item
#issue-list,
#pull-list {
.item {
position: relative;
padding-bottom: 12px;
margin-bottom: 12px;
border-bottom: 1px dashed #AAA;
.title > .title-text {
color: #444;
font-size: 15px;
margin: 0 6px;
}
}
.comment {
color: #666;
position: absolute;
top: 6px;
right: 0;
}
.issue-label {
a {
color: #FFF;
}
}
.desc {
color: #999;
a {
color: #999;
&:hover {
color: #03a2ef;
}
}
}
}
// issue list filter
#issue-list-filter{
.drop > a{
width: 90px;
padding: 0;
margin-left: 12px;
text-align: center;
}
.drop-down{
z-index: 999;
width: 236px;
left:-158px; // 260 - 90 - 12
top:22px;
padding: 0 12px;
h4{
line-height: 40px;
border-bottom: 1px solid #CCC;
margin-bottom: 0;
}
li{
line-height: 30px;
border-bottom: 1px dashed #EEE;
padding-left: 9px;
&:hover{
background-color: #fcffec;
}
}
> ul > li > a{
display: block;
}
}
.labels{
.color{
margin-top: 8px;
display: inline-block;
width: 12px;
height: 12px;
background-color: red;
margin-right: 9px;
margin-left: 9px;
}
.name{
vertical-align: top;
display: inline-block;
color: #444;
}
}
.milestones{
a{
color: #444;
font-weight: bold;
}
}
}
// issue list pager
#issue-list-pager {
margin: 18px 0 24px 0;
font-size: 14px;
line-height: 24px;
}
// labels numbers
#labels-num {
margin-right: 1em;
}
// labels list
#label-list {
.right {
margin-left: 1em;
color: #999;
i {
margin-right: 3px;
}
line-height: 30px;
&:hover {
color: #444444;
}
}
.num {
margin-right: 3px;
}
.issue-num {
margin-right: 4em;
}
.label {
&:hover {
color: #FFF;
}
i {
margin-right: 6px;
}
}
.item {
height: 30px;
padding-bottom: 12px;
margin-bottom: 12px;
border-bottom: 1px dashed #AAA;
}
}
// label add form
#label-add-form{
padding: 18px 0;
border-bottom: 1px solid #DDD;
.ipt{
font-size: 14px;
}
.ipt[name=name]{
width: 300px;
}
.btn{
height: 33px;
font-size: 14px;
margin-left: 12px;
}
}
// label color drop
#label-color-drop{
.ipt{
width:100px;
}
.drop-down{
width:128px;
top:22px;
left:50px;
padding: 12px;
line-height: 16px;
a.color{
width: 16px;
height: 16px;
display: inline-block;
}
}
label{
width: 24px;
height: 24px;
display: inline-block;
margin: 0 1em;
vertical-align: middle;
}
}
// milestone items
#milestone-list{
padding-top: 6px;
.title-text{
font-size: 16px;
}
.desc {
color: #999;
line-height: 30px;
}
.content{
width: 400px;
}
.item {
padding-bottom: 18px;
margin-bottom: 18px;
border-bottom: 1px dashed #AAA;
position: relative;
}
.action{
position: absolute;
top: 0;
right: 0;
}
.status-bar {
> .bar {
margin: -2px 8px 0 8px;
width: 360px;
background-color: #DDD;
height: 14px;
vertical-align:middle;
}
.opening{
background-color: #65ad4e;
width: 40%;
height: 14px;
vertical-align: top;
}
}
.action-bar{
margin-top: 8px;
a{
margin-left: 12px;
}
}
}

View File

@@ -59,6 +59,30 @@
color: #777;
}
}
table {
display: block;
width: 100%;
overflow: auto;
word-break: normal;
margin: 15px 0;
border-collapse: collapse;
border-spacing: 0;
display: block;
th {
font-weight: 700;
}
th, td {
border: 1px solid #DDD;
padding: 6px 13px !important;
}
tr {
background-color: #FFF;
border-top: 1px solid #CCC;
&:nth-child(2n) {
background-color: #F8F8F8;
}
}
}
}
.markdown a {
color: #428BCA;
@@ -96,29 +120,6 @@
.markdown h4 {
font-size: 18px
}
.markdown table {
border-collapse: collapse;
border-spacing: 0;
display: block;
overflow: auto;
width: 100%;
margin: 0 0 9px;
}
.markdown table th {
font-weight: 700
}
.markdown table th,
.markdown table td {
border: 1px solid #DDD;
padding: 6px 13px;
}
.markdown table tr {
background-color: #FFF;
border-top: 1px solid #CCC;
}
.markdown table tr:nth-child(2n) {
background-color: #F8F8F8
}
.markdown dl dt {
font-style: italic;
margin-top: 9px;

View File

@@ -1,6 +1,5 @@
.profile-avatar {
width: 200px;
height: 200px;
width: 100%;
border-radius: 6px;
}
#profile-name {
@@ -14,7 +13,7 @@
font-weight: bold;
}
.profile-info {
padding: 0 50px;
// padding: 0 50px;
font-size: 14px;
ul {
padding-bottom: 10px;
@@ -54,4 +53,7 @@
border-bottom: 2px solid #D26911;
}
}
}
#profile-body {
margin-left: 20px;
}

File diff suppressed because it is too large Load Diff

View File

@@ -68,6 +68,7 @@
#repo-hooks-panel,
#repo-hooks-history-panel,
#user-social-panel,
#user-applications-panel,
#user-ssh-panel {
margin-bottom: 20px;
.setting-list {
@@ -97,16 +98,20 @@
margin-right: 4px;
}
.print,
.access,
.activity {
color: #888;
}
.access {
max-width: 500px;
}
}
.ssh-delete-btn {
.ssh-btn {
margin-top: 6px;
}
}
#user-ssh-add-form {
.form-settings-add {
.panel-body {
background-color: #FFF;
padding: 30px 0;

View File

@@ -7,4 +7,5 @@
@import "ui/label";
@import "ui/bread";
@import "ui/alert";
@import "ui/table";
@import "ui/table";
@import "ui/pager";

View File

@@ -1,9 +1,8 @@
@import "var";
// colored buttons
// Button.
.btn {
&:hover {
}
white-space: nowrap;
}
.btn-small {
font-size: 0.9*@baseFontSize;
@@ -15,6 +14,7 @@
}
.btn-large {
font-size: 1.2*@baseFontSize;
padding: .4em .9em;
}
.btn-green {
@@ -102,6 +102,9 @@
box-sizing: content-box;
text-align: center;
}
.btn-comb {
margin-left: -1px;
}
.btn-disabled {
opacity: .6;

View File

@@ -1,7 +1,7 @@
@import "var";
.label {
padding: 2px 6px;
padding: .3em .6em .2em .6em;
color: @labelFontColor;
}

View File

@@ -0,0 +1,28 @@
@import "var";
.pager{
.page{
padding: .3em .5em .2em .5em;
margin: 0 .3em;
background-color: @pagerPageBgColor;
color: @pagerPageColor;
&:hover,&.hover{
background-color: @pagerHoverBgColor;
color: @pagerHoverColor;
}
}
.prev,.next{
padding: .4em .6em;
margin: 0 .3em;
background-color: @pagerDirectionBgColor;
color: @pagerDirectionColor;
&.invalid{
background-color: @pagerInvalidBgColor;
color: @pagerInvalidColor;
cursor: not-allowed;
}
}
.page-radius{
border-radius: .2em;
}
}

View File

@@ -36,6 +36,14 @@
border-bottom-right-radius: .3em;
}
}
&.panel-info {
border-color: #85c5e5;
> .panel-header {
color: #31708f;
background-color: #d9edf7;
border-color: #85c5e5;
}
}
&.panel-warning {
border-color: #F0C36D;
> .panel-header {

View File

@@ -7,7 +7,7 @@
html {
font-size: @baseFontSize+1;
font-family: Helvetica, "Microsoft Yahei", Menlo, Monaco, Consolas, "Courier New", monospace;
font-family: Helvetica, "Microsoft Yahei", Arial, sans-serif;
// make sure min font size
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
@@ -23,7 +23,7 @@ textarea,
select,
option,
button {
font-family: Helvetica, "Microsoft Yahei", Menlo, Monaco, Consolas, "Courier New", monospace;
font-family: Helvetica, "Microsoft Yahei", Arial, sans-serif;
}
// html5 block elements
@@ -193,7 +193,7 @@ code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-family: monospace;
font-size: 1em;
}

View File

@@ -81,3 +81,12 @@
@preBgColor:#444;
@preFontColor:#FFF;
@pagerPageColor:#444;
@pagerPageBgColor:#CCC;
@pagerHoverBgColor:#428BCA;
@pagerHoverColor:#FFF;
@pagerInvalidColor:#AAA;
@pagerInvalidBgColor:#EEE;
@pagerDirectionBgColor:#505050;
@pagerDirectionColor:#FAFAFA;

View File

@@ -116,6 +116,8 @@ type AdminOperation int
const (
CLEAN_UNBIND_OAUTH AdminOperation = iota + 1
CLEAN_INACTIVATE_USER
CLEAN_REPO_ARCHIVES
GIT_GC_REPOS
)
func Dashboard(ctx *middleware.Context) {
@@ -131,11 +133,17 @@ func Dashboard(ctx *middleware.Context) {
switch AdminOperation(op) {
case CLEAN_UNBIND_OAUTH:
success = "All unbind OAuthes have been deleted."
success = ctx.Tr("admin.dashboard.clean_unbind_oauth_success")
err = models.CleanUnbindOauth()
case CLEAN_INACTIVATE_USER:
success = "All inactivate accounts have been deleted."
success = ctx.Tr("admin.dashboard.delete_inactivate_accounts_success")
err = models.DeleteInactivateUsers()
case CLEAN_REPO_ARCHIVES:
success = ctx.Tr("admin.dashboard.delete_repo_archives_success")
err = models.DeleteRepositoryArchives()
case GIT_GC_REPOS:
success = ctx.Tr("admin.dashboard.git_gc_repos_success")
err = models.GitGcRepos()
}
if err != nil {
@@ -148,6 +156,7 @@ func Dashboard(ctx *middleware.Context) {
}
ctx.Data["Stats"] = models.GetStatistic()
// FIXME: update periodically
updateSystemStatus()
ctx.Data["SysStatus"] = sysStatus
ctx.HTML(200, DASHBOARD)

View File

@@ -5,6 +5,7 @@
package admin
import (
"math"
"strings"
"github.com/Unknwon/com"
@@ -30,7 +31,7 @@ func pagination(ctx *middleware.Context, count int64, pageNum int) int {
}
curCount := int64((p-1)*pageNum + pageNum)
if curCount >= count {
p = int(count) / pageNum
p = int(math.Ceil(float64(count) / float64(pageNum)))
} else {
ctx.Data["NextPageNum"] = p + 1
}
@@ -173,7 +174,7 @@ func EditUserPost(ctx *middleware.Context, form auth.AdminEditUserForm) {
return
}
// NOTE: need password length check?
// FIXME: need password length check
if len(form.Passwd) > 0 {
u.Passwd = form.Passwd
u.Salt = models.GetUserSalt()
@@ -190,13 +191,20 @@ func EditUserPost(ctx *middleware.Context, form auth.AdminEditUserForm) {
u.AvatarEmail = form.Avatar
u.IsActive = form.Active
u.IsAdmin = form.Admin
u.AllowGitHook = form.AllowGitHook
ctx.Data["User"] = u
if err := models.UpdateUser(u); err != nil {
ctx.Handle(500, "UpdateUser", err)
if err == models.ErrEmailAlreadyUsed {
ctx.Data["Err_Email"] = true
ctx.RenderWithErr(ctx.Tr("form.email_been_used"), USER_EDIT, &form)
} else {
ctx.Handle(500, "UpdateUser", err)
}
return
}
log.Trace("Account profile updated by admin(%s): %s", ctx.User.Name, u.Name)
ctx.Data["User"] = u
ctx.Flash.Success(ctx.Tr("admin.users.update_profile_success"))
ctx.Redirect(setting.AppSubUrl + "/admin/users/" + ctx.Params(":userid"))
}
@@ -219,6 +227,9 @@ func DeleteUser(ctx *middleware.Context) {
case models.ErrUserOwnRepos:
ctx.Flash.Error(ctx.Tr("admin.users.still_own_repo"))
ctx.Redirect(setting.AppSubUrl + "/admin/users/" + ctx.Params(":userid"))
case models.ErrUserHasOrgs:
ctx.Flash.Error(ctx.Tr("admin.users.still_has_org"))
ctx.Redirect(setting.AppSubUrl + "/admin/users/" + ctx.Params(":userid"))
default:
ctx.Handle(500, "DeleteUser", err)
}

View File

@@ -5,7 +5,6 @@
package v1
import (
"io/ioutil"
"strings"
"github.com/gogits/gogs/modules/auth/apiv1"
@@ -14,12 +13,15 @@ import (
"github.com/gogits/gogs/modules/setting"
)
const DOC_URL = "http://gogs.io/docs"
// Render an arbitrary Markdown document.
func Markdown(ctx *middleware.Context, form apiv1.MarkdownForm) {
if ctx.HasApiError() {
ctx.JSON(422, base.ApiJsonErr{ctx.GetErrMsg(), DOC_URL})
ctx.JSON(422, base.ApiJsonErr{ctx.GetErrMsg(), base.DOC_URL})
return
}
if len(form.Text) == 0 {
ctx.Write([]byte(""))
return
}
@@ -34,9 +36,9 @@ func Markdown(ctx *middleware.Context, form apiv1.MarkdownForm) {
// Render a Markdown document in raw mode.
func MarkdownRaw(ctx *middleware.Context) {
body, err := ioutil.ReadAll(ctx.Req.Body)
body, err := ctx.Req.Body().Bytes()
if err != nil {
ctx.JSON(422, base.ApiJsonErr{err.Error(), DOC_URL})
ctx.JSON(422, base.ApiJsonErr{err.Error(), base.DOC_URL})
return
}
ctx.Write(base.RenderRawMarkdown(body, ""))

265
routers/api/v1/repo.go Normal file
View File

@@ -0,0 +1,265 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package v1
import (
"fmt"
"path"
"strings"
"github.com/Unknwon/com"
api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/middleware"
"github.com/gogits/gogs/modules/setting"
)
// ToApiRepository converts repository to API format.
func ToApiRepository(owner *models.User, repo *models.Repository, permission api.Permission) *api.Repository {
cl, err := repo.CloneLink()
if err != nil {
log.Error(4, "CloneLink: %v", err)
}
return &api.Repository{
Id: repo.Id,
Owner: *ToApiUser(owner),
FullName: owner.Name + "/" + repo.Name,
Private: repo.IsPrivate,
Fork: repo.IsFork,
HtmlUrl: setting.AppUrl + owner.Name + "/" + repo.Name,
CloneUrl: cl.HTTPS,
SshUrl: cl.SSH,
Permissions: permission,
}
}
func SearchRepos(ctx *middleware.Context) {
opt := models.SearchOption{
Keyword: path.Base(ctx.Query("q")),
Uid: com.StrTo(ctx.Query("uid")).MustInt64(),
Limit: com.StrTo(ctx.Query("limit")).MustInt(),
}
if opt.Limit == 0 {
opt.Limit = 10
}
// Check visibility.
if ctx.IsSigned && opt.Uid > 0 {
if ctx.User.Id == opt.Uid {
opt.Private = true
} else {
u, err := models.GetUserById(opt.Uid)
if err != nil {
ctx.JSON(500, map[string]interface{}{
"ok": false,
"error": err.Error(),
})
return
}
if u.IsOrganization() && u.IsOwnedBy(ctx.User.Id) {
opt.Private = true
}
// FIXME: how about collaborators?
}
}
repos, err := models.SearchRepositoryByName(opt)
if err != nil {
ctx.JSON(500, map[string]interface{}{
"ok": false,
"error": err.Error(),
})
return
}
results := make([]*api.Repository, len(repos))
for i := range repos {
if err = repos[i].GetOwner(); err != nil {
ctx.JSON(500, map[string]interface{}{
"ok": false,
"error": err.Error(),
})
return
}
results[i] = &api.Repository{
Id: repos[i].Id,
FullName: path.Join(repos[i].Owner.Name, repos[i].Name),
}
}
ctx.JSON(200, map[string]interface{}{
"ok": true,
"data": results,
})
}
func createRepo(ctx *middleware.Context, owner *models.User, opt api.CreateRepoOption) {
repo, err := models.CreateRepository(owner, opt.Name, opt.Description,
opt.Gitignore, opt.License, opt.Private, false, opt.AutoInit)
if err != nil {
if err == models.ErrRepoAlreadyExist ||
err == models.ErrRepoNameIllegal {
ctx.JSON(422, &base.ApiJsonErr{err.Error(), base.DOC_URL})
} else {
log.Error(4, "CreateRepository: %v", err)
if repo != nil {
if err = models.DeleteRepository(ctx.User.Id, repo.Id, ctx.User.Name); err != nil {
log.Error(4, "DeleteRepository: %v", err)
}
}
ctx.Error(500)
}
return
}
ctx.JSON(200, ToApiRepository(owner, repo, api.Permission{true, true, true}))
}
// POST /user/repos
// https://developer.github.com/v3/repos/#create
func CreateRepo(ctx *middleware.Context, opt api.CreateRepoOption) {
// Shouldn't reach this condition, but just in case.
if ctx.User.IsOrganization() {
ctx.JSON(422, "not allowed creating repository for organization")
return
}
createRepo(ctx, ctx.User, opt)
}
// POST /orgs/:org/repos
// https://developer.github.com/v3/repos/#create
func CreateOrgRepo(ctx *middleware.Context, opt api.CreateRepoOption) {
org, err := models.GetOrgByName(ctx.Params(":org"))
if err != nil {
if err == models.ErrUserNotExist {
ctx.Error(404)
} else {
ctx.Error(500)
}
return
}
if !org.IsOwnedBy(ctx.User.Id) {
ctx.Error(403)
return
}
createRepo(ctx, org, opt)
}
func MigrateRepo(ctx *middleware.Context, form auth.MigrateRepoForm) {
u, err := models.GetUserByName(ctx.Query("username"))
if err != nil {
ctx.JSON(500, map[string]interface{}{
"ok": false,
"error": err.Error(),
})
return
}
if !u.ValidtePassword(ctx.Query("password")) {
ctx.JSON(500, map[string]interface{}{
"ok": false,
"error": "username or password is not correct",
})
return
}
ctxUser := u
// Not equal means current user is an organization.
if form.Uid != u.Id {
org, err := models.GetUserById(form.Uid)
if err != nil {
log.Error(4, "GetUserById: %v", err)
ctx.Error(500)
return
}
ctxUser = org
}
if ctx.HasError() {
ctx.JSON(422, map[string]interface{}{
"ok": false,
"error": ctx.GetErrMsg(),
})
return
}
if ctxUser.IsOrganization() {
// Check ownership of organization.
if !ctxUser.IsOwnedBy(u.Id) {
ctx.JSON(403, map[string]interface{}{
"ok": false,
"error": "given user is not owner of organization",
})
return
}
}
authStr := strings.Replace(fmt.Sprintf("://%s:%s",
form.AuthUserName, form.AuthPasswd), "@", "%40", -1)
url := strings.Replace(form.HttpsUrl, "://", authStr+"@", 1)
repo, err := models.MigrateRepository(ctxUser, form.RepoName, form.Description, form.Private,
form.Mirror, url)
if err == nil {
log.Trace("Repository migrated: %s/%s", ctxUser.Name, form.RepoName)
ctx.JSON(200, map[string]interface{}{
"ok": true,
"data": "/" + ctxUser.Name + "/" + form.RepoName,
})
return
}
if repo != nil {
if errDelete := models.DeleteRepository(ctxUser.Id, repo.Id, ctxUser.Name); errDelete != nil {
log.Error(4, "DeleteRepository: %v", errDelete)
}
}
ctx.JSON(500, map[string]interface{}{
"ok": false,
"error": err.Error(),
})
}
// GET /user/repos
// https://developer.github.com/v3/repos/#list-your-repositories
func ListMyRepos(ctx *middleware.Context) {
ownRepos, err := models.GetRepositories(ctx.User.Id, true)
if err != nil {
ctx.JSON(500, &base.ApiJsonErr{"GetRepositories: " + err.Error(), base.DOC_URL})
return
}
numOwnRepos := len(ownRepos)
collaRepos, err := models.GetCollaborativeRepos(ctx.User.Name)
if err != nil {
ctx.JSON(500, &base.ApiJsonErr{"GetCollaborativeRepos: " + err.Error(), base.DOC_URL})
return
}
repos := make([]*api.Repository, numOwnRepos+len(collaRepos))
for i := range ownRepos {
repos[i] = ToApiRepository(ctx.User, ownRepos[i], api.Permission{true, true, true})
}
for i := range collaRepos {
if err = collaRepos[i].GetOwner(); err != nil {
ctx.JSON(500, &base.ApiJsonErr{"GetOwner: " + err.Error(), base.DOC_URL})
return
}
j := i + numOwnRepos
repos[j] = ToApiRepository(collaRepos[i].Owner, collaRepos[i].Repository, api.Permission{false, collaRepos[i].CanPush, true})
// FIXME: cache result to reduce DB query?
if collaRepos[i].Owner.IsOrganization() && collaRepos[i].Owner.IsOwnedBy(ctx.User.Id) {
repos[j].Permissions.Admin = true
}
}
ctx.JSON(200, &repos)
}

View File

@@ -0,0 +1,32 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package v1
import (
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/git"
"github.com/gogits/gogs/modules/middleware"
"github.com/gogits/gogs/routers/repo"
)
func GetRepoRawFile(ctx *middleware.Context) {
if ctx.Repo.Repository.IsPrivate && !ctx.Repo.HasAccess {
ctx.Error(404)
return
}
blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreeName)
if err != nil {
if err == git.ErrNotExist {
ctx.Error(404)
} else {
ctx.JSON(500, &base.ApiJsonErr{"GetBlobByPath: " + err.Error(), base.DOC_URL})
}
return
}
if err = repo.ServeBlob(ctx, blob); err != nil {
ctx.JSON(500, &base.ApiJsonErr{"ServeBlob: " + err.Error(), base.DOC_URL})
}
}

View File

@@ -0,0 +1,169 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package v1
import (
"encoding/json"
api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/middleware"
)
// GET /repos/:username/:reponame/hooks
// https://developer.github.com/v3/repos/hooks/#list-hooks
func ListRepoHooks(ctx *middleware.Context) {
hooks, err := models.GetWebhooksByRepoId(ctx.Repo.Repository.Id)
if err != nil {
ctx.JSON(500, &base.ApiJsonErr{"GetWebhooksByRepoId: " + err.Error(), base.DOC_URL})
return
}
apiHooks := make([]*api.Hook, len(hooks))
for i := range hooks {
h := &api.Hook{
Id: hooks[i].Id,
Type: hooks[i].HookTaskType.Name(),
Active: hooks[i].IsActive,
Config: make(map[string]string),
}
// Currently, onle have push event.
h.Events = []string{"push"}
h.Config["url"] = hooks[i].Url
h.Config["content_type"] = hooks[i].ContentType.Name()
if hooks[i].HookTaskType == models.SLACK {
s := hooks[i].GetSlackHook()
h.Config["channel"] = s.Channel
}
apiHooks[i] = h
}
ctx.JSON(200, &apiHooks)
}
// POST /repos/:username/:reponame/hooks
// https://developer.github.com/v3/repos/hooks/#create-a-hook
func CreateRepoHook(ctx *middleware.Context, form api.CreateHookOption) {
if !models.IsValidHookTaskType(form.Type) {
ctx.JSON(422, &base.ApiJsonErr{"invalid hook type", base.DOC_URL})
return
}
for _, name := range []string{"url", "content_type"} {
if _, ok := form.Config[name]; !ok {
ctx.JSON(422, &base.ApiJsonErr{"missing config option: " + name, base.DOC_URL})
return
}
}
if !models.IsValidHookContentType(form.Config["content_type"]) {
ctx.JSON(422, &base.ApiJsonErr{"invalid content type", base.DOC_URL})
return
}
w := &models.Webhook{
RepoId: ctx.Repo.Repository.Id,
Url: form.Config["url"],
ContentType: models.ToHookContentType(form.Config["content_type"]),
Secret: form.Config["secret"],
HookEvent: &models.HookEvent{
PushOnly: true, // Only support it now.
},
IsActive: form.Active,
HookTaskType: models.ToHookTaskType(form.Type),
}
if w.HookTaskType == models.SLACK {
channel, ok := form.Config["channel"]
if !ok {
ctx.JSON(422, &base.ApiJsonErr{"missing config option: channel", base.DOC_URL})
return
}
meta, err := json.Marshal(&models.Slack{
Channel: channel,
})
if err != nil {
ctx.JSON(500, &base.ApiJsonErr{"slack: JSON marshal failed: " + err.Error(), base.DOC_URL})
return
}
w.Meta = string(meta)
}
if err := w.UpdateEvent(); err != nil {
ctx.JSON(500, &base.ApiJsonErr{"UpdateEvent: " + err.Error(), base.DOC_URL})
return
} else if err := models.CreateWebhook(w); err != nil {
ctx.JSON(500, &base.ApiJsonErr{"CreateWebhook: " + err.Error(), base.DOC_URL})
return
}
apiHook := &api.Hook{
Id: w.Id,
Type: w.HookTaskType.Name(),
Events: []string{"push"},
Active: w.IsActive,
Config: map[string]string{
"url": w.Url,
"content_type": w.ContentType.Name(),
},
}
if w.HookTaskType == models.SLACK {
s := w.GetSlackHook()
apiHook.Config["channel"] = s.Channel
}
ctx.JSON(201, apiHook)
}
// PATCH /repos/:username/:reponame/hooks/:id
// https://developer.github.com/v3/repos/hooks/#edit-a-hook
func EditRepoHook(ctx *middleware.Context, form api.EditHookOption) {
w, err := models.GetWebhookById(ctx.ParamsInt64(":id"))
if err != nil {
ctx.JSON(500, &base.ApiJsonErr{"GetWebhookById: " + err.Error(), base.DOC_URL})
return
}
if form.Config != nil {
if url, ok := form.Config["url"]; ok {
w.Url = url
}
if ct, ok := form.Config["content_type"]; ok {
if !models.IsValidHookContentType(ct) {
ctx.JSON(422, &base.ApiJsonErr{"invalid content type", base.DOC_URL})
return
}
w.ContentType = models.ToHookContentType(ct)
}
if w.HookTaskType == models.SLACK {
if channel, ok := form.Config["channel"]; ok {
meta, err := json.Marshal(&models.Slack{
Channel: channel,
})
if err != nil {
ctx.JSON(500, &base.ApiJsonErr{"slack: JSON marshal failed: " + err.Error(), base.DOC_URL})
return
}
w.Meta = string(meta)
}
}
}
if form.Active != nil {
w.IsActive = *form.Active
}
// FIXME: edit events
if err := models.UpdateWebhook(w); err != nil {
ctx.JSON(500, &base.ApiJsonErr{"UpdateWebhook: " + err.Error(), base.DOC_URL})
return
}
ctx.JSON(200, map[string]interface{}{
"ok": true,
})
}

View File

@@ -1,137 +0,0 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package v1
import (
"fmt"
"path"
"strings"
"github.com/Unknwon/com"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/middleware"
)
type repo struct {
RepoLink string `json:"repolink"`
}
func SearchRepos(ctx *middleware.Context) {
opt := models.SearchOption{
Keyword: path.Base(ctx.Query("q")),
Uid: com.StrTo(ctx.Query("uid")).MustInt64(),
Limit: com.StrTo(ctx.Query("limit")).MustInt(),
}
if opt.Limit == 0 {
opt.Limit = 10
}
repos, err := models.SearchRepositoryByName(opt)
if err != nil {
ctx.JSON(500, map[string]interface{}{
"ok": false,
"error": err.Error(),
})
return
}
results := make([]*repo, len(repos))
for i := range repos {
if err = repos[i].GetOwner(); err != nil {
ctx.JSON(500, map[string]interface{}{
"ok": false,
"error": err.Error(),
})
return
}
results[i] = &repo{
RepoLink: path.Join(repos[i].Owner.Name, repos[i].Name),
}
}
ctx.Render.JSON(200, map[string]interface{}{
"ok": true,
"data": results,
})
}
func Migrate(ctx *middleware.Context, form auth.MigrateRepoForm) {
u, err := models.GetUserByName(ctx.Query("username"))
if err != nil {
ctx.JSON(500, map[string]interface{}{
"ok": false,
"error": err.Error(),
})
return
}
if !u.ValidtePassword(ctx.Query("password")) {
ctx.JSON(500, map[string]interface{}{
"ok": false,
"error": "username or password is not correct",
})
return
}
ctxUser := u
// Not equal means current user is an organization.
if form.Uid != u.Id {
org, err := models.GetUserById(form.Uid)
if err != nil {
ctx.JSON(500, map[string]interface{}{
"ok": false,
"error": err.Error(),
})
return
}
ctxUser = org
}
if ctx.HasError() {
ctx.JSON(500, map[string]interface{}{
"ok": false,
"error": ctx.GetErrMsg(),
})
return
}
if ctxUser.IsOrganization() {
// Check ownership of organization.
if !ctxUser.IsOrgOwner(u.Id) {
ctx.JSON(403, map[string]interface{}{
"ok": false,
"error": "given user is not owner of organization",
})
return
}
}
authStr := strings.Replace(fmt.Sprintf("://%s:%s",
form.AuthUserName, form.AuthPasswd), "@", "%40", -1)
url := strings.Replace(form.HttpsUrl, "://", authStr+"@", 1)
repo, err := models.MigrateRepository(ctxUser, form.RepoName, form.Description, form.Private,
form.Mirror, url)
if err == nil {
log.Trace("Repository migrated: %s/%s", ctxUser.Name, form.RepoName)
ctx.JSON(200, map[string]interface{}{
"ok": true,
"data": "/" + ctxUser.Name + "/" + form.RepoName,
})
return
}
if repo != nil {
if errDelete := models.DeleteRepository(ctxUser.Id, repo.Id, ctxUser.Name); errDelete != nil {
log.Error(4, "DeleteRepository: %v", errDelete)
}
}
ctx.JSON(500, map[string]interface{}{
"ok": false,
"error": err.Error(),
})
}

72
routers/api/v1/user.go Normal file
View File

@@ -0,0 +1,72 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package v1
import (
"github.com/Unknwon/com"
api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/middleware"
"github.com/gogits/gogs/modules/setting"
)
// ToApiUser converts user to API format.
func ToApiUser(u *models.User) *api.User {
return &api.User{
Id: u.Id,
UserName: u.Name,
AvatarUrl: string(setting.Protocol) + u.AvatarLink(),
}
}
func SearchUsers(ctx *middleware.Context) {
opt := models.SearchOption{
Keyword: ctx.Query("q"),
Limit: com.StrTo(ctx.Query("limit")).MustInt(),
}
if opt.Limit == 0 {
opt.Limit = 10
}
us, err := models.SearchUserByName(opt)
if err != nil {
ctx.JSON(500, map[string]interface{}{
"ok": false,
"error": err.Error(),
})
return
}
results := make([]*api.User, len(us))
for i := range us {
results[i] = &api.User{
UserName: us[i].Name,
AvatarUrl: us[i].AvatarLink(),
FullName: us[i].FullName,
}
}
ctx.Render.JSON(200, map[string]interface{}{
"ok": true,
"data": results,
})
}
// GET /users/:username
func GetUserInfo(ctx *middleware.Context) {
u, err := models.GetUserByName(ctx.Params(":username"))
if err != nil {
if err == models.ErrUserNotExist {
ctx.Error(404)
} else {
ctx.JSON(500, &base.ApiJsonErr{"GetUserByName: " + err.Error(), base.DOC_URL})
}
return
}
ctx.JSON(200, &api.User{u.Id, u.Name, u.FullName, u.Email, u.AvatarLink()})
}

View File

@@ -0,0 +1,45 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package v1
import (
api "github.com/gogits/go-gogs-client"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/middleware"
)
// GET /users/:username/tokens
func ListAccessTokens(ctx *middleware.Context) {
tokens, err := models.ListAccessTokens(ctx.User.Id)
if err != nil {
ctx.JSON(500, &base.ApiJsonErr{"ListAccessTokens: " + err.Error(), base.DOC_URL})
return
}
apiTokens := make([]*api.AccessToken, len(tokens))
for i := range tokens {
apiTokens[i] = &api.AccessToken{tokens[i].Name, tokens[i].Sha1}
}
ctx.JSON(200, &apiTokens)
}
type CreateAccessTokenForm struct {
Name string `json:"name" binding:"Required"`
}
// POST /users/:username/tokens
func CreateAccessToken(ctx *middleware.Context, form CreateAccessTokenForm) {
t := &models.AccessToken{
Uid: ctx.User.Id,
Name: form.Name,
}
if err := models.NewAccessToken(t); err != nil {
ctx.JSON(500, &base.ApiJsonErr{"NewAccessToken: " + err.Error(), base.DOC_URL})
return
}
ctx.JSON(201, &api.AccessToken{t.Name, t.Sha1})
}

View File

@@ -1,49 +0,0 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package v1
import (
"github.com/Unknwon/com"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/middleware"
)
type user struct {
UserName string `json:"username"`
AvatarLink string `json:"avatar"`
}
func SearchUsers(ctx *middleware.Context) {
opt := models.SearchOption{
Keyword: ctx.Query("q"),
Limit: com.StrTo(ctx.Query("limit")).MustInt(),
}
if opt.Limit == 0 {
opt.Limit = 10
}
us, err := models.SearchUserByName(opt)
if err != nil {
ctx.JSON(500, map[string]interface{}{
"ok": false,
"error": err.Error(),
})
return
}
results := make([]*user, len(us))
for i := range us {
results[i] = &user{
UserName: us[i].Name,
AvatarLink: us[i].AvatarLink(),
}
}
ctx.Render.JSON(200, map[string]interface{}{
"ok": true,
"data": results,
})
}

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