You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

setting.go 32 kB

Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
Add configurable Trust Models (#11712) * Add configurable Trust Models Gitea's default signature verification model differs from GitHub. GitHub uses signatures to verify that the committer is who they say they are - meaning that when GitHub makes a signed commit it must be the committer. The GitHub model prevents re-publishing of commits after revocation of a key and prevents re-signing of other people's commits to create a completely trusted repository signed by one key or a set of trusted keys. The default behaviour of Gitea in contrast is to always display the avatar and information related to a signature. This allows signatures to be decoupled from the committer. That being said, allowing arbitary users to present other peoples commits as theirs is not necessarily desired therefore we have a trust model whereby signatures from collaborators are marked trusted, signatures matching the commit line are marked untrusted and signatures that match a user in the db but not the committer line are marked unmatched. The problem with this model is that this conflicts with Github therefore we need to provide an option to allow users to choose the Github model should they wish to. Signed-off-by: Andrew Thornton <art27@cantab.net> * Adjust locale strings Signed-off-by: Andrew Thornton <art27@cantab.net> * as per @6543 Co-authored-by: 6543 <6543@obermui.de> * Update models/gpg_key.go * Add migration for repository Signed-off-by: Andrew Thornton <art27@cantab.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
4 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
Adopt repositories (#12920) * Don't automatically delete repository files if they are present Prior to this PR Gitea would delete any repository files if they are present during creation or migration. This can in certain circumstances lead to data-loss and is slightly unpleasant. This PR provides a mechanism for Gitea to adopt repositories on creation and otherwise requires an explicit flag for deletion. PushCreate is slightly different - the create will cause adoption if that is allowed otherwise it will delete the data if that is allowed. Signed-off-by: Andrew Thornton <art27@cantab.net> * Update swagger Signed-off-by: Andrew Thornton <art27@cantab.net> * Fix tests and migrate overwrite Signed-off-by: Andrew Thornton <art27@cantab.net> * as per @lunny Only offer to adopt or overwrite if the user can do that. Allow the site administrator to adopt or overwrite in all circumstances Signed-off-by: Andrew Thornton <art27@cantab.net> * Use setting.Repository.DefaultBranch for the default branch Signed-off-by: Andrew Thornton <art27@cantab.net> * Always set setting.Repository.DefaultBranch Signed-off-by: Andrew Thornton <art27@cantab.net> * update swagger Signed-off-by: Andrew Thornton <art27@cantab.net> * update templates Signed-off-by: Andrew Thornton <art27@cantab.net> * ensure repo closed Signed-off-by: Andrew Thornton <art27@cantab.net> * Rewrite of adoption as per @6543 and @lunny Signed-off-by: Andrew Thornton <art27@cantab.net> * Apply suggestions from code review * update swagger Signed-off-by: Andrew Thornton <art27@cantab.net> * missing not Signed-off-by: Andrew Thornton <art27@cantab.net> * add modals and flash reporting Signed-off-by: Andrew Thornton <art27@cantab.net> * Make the unadopted page searchable Signed-off-by: Andrew Thornton <art27@cantab.net> * Add API Signed-off-by: Andrew Thornton <art27@cantab.net> * Fix swagger Signed-off-by: Andrew Thornton <art27@cantab.net> * fix swagger Signed-off-by: Andrew Thornton <art27@cantab.net> * Handle empty and non-master branched repositories Signed-off-by: Andrew Thornton <art27@cantab.net> * placate lint Signed-off-by: Andrew Thornton <art27@cantab.net> * remove commented out code Signed-off-by: Andrew Thornton <art27@cantab.net> Co-authored-by: techknowlogick <techknowlogick@gitea.io>
4 years ago
Template Repositories (#8768) * Start work on templates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Continue work Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix IsTemplate vs IsGenerated Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tabs vs spaces * Tabs vs Spaces * Add templates to API & start adding tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix integration tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove unused User Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move template tests to existing repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Minor re-check updates and cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix optionalbool Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test fixes and icon change Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add new user and repo for tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests (finally) Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update meta repo with env variables Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move generation to create page Combine with repo create template Modify API search to prioritize owner for repo Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests and coverage Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix swagger and JS lint Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix API searching for own private repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Change wording Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix repo search test. User had a private repo that didn't show up Signed-off-by: jolheiser <john.olheiser@gmail.com> * Another search test fix Signed-off-by: jolheiser <john.olheiser@gmail.com> * Clarify git content Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Feedback updates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add topics WIP Signed-off-by: jolheiser <john.olheiser@gmail.com> * Finish adding topics Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update locale Signed-off-by: jolheiser <john.olheiser@gmail.com>
5 years ago
9 years ago
9 years ago
Add configurable Trust Models (#11712) * Add configurable Trust Models Gitea's default signature verification model differs from GitHub. GitHub uses signatures to verify that the committer is who they say they are - meaning that when GitHub makes a signed commit it must be the committer. The GitHub model prevents re-publishing of commits after revocation of a key and prevents re-signing of other people's commits to create a completely trusted repository signed by one key or a set of trusted keys. The default behaviour of Gitea in contrast is to always display the avatar and information related to a signature. This allows signatures to be decoupled from the committer. That being said, allowing arbitary users to present other peoples commits as theirs is not necessarily desired therefore we have a trust model whereby signatures from collaborators are marked trusted, signatures matching the commit line are marked untrusted and signatures that match a user in the db but not the committer line are marked unmatched. The problem with this model is that this conflicts with Github therefore we need to provide an option to allow users to choose the Github model should they wish to. Signed-off-by: Andrew Thornton <art27@cantab.net> * Adjust locale strings Signed-off-by: Andrew Thornton <art27@cantab.net> * as per @6543 Co-authored-by: 6543 <6543@obermui.de> * Update models/gpg_key.go * Add migration for repository Signed-off-by: Andrew Thornton <art27@cantab.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
4 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
9 years ago
9 years ago
9 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package repo
  6. import (
  7. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "net/url"
  11. "regexp"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/base"
  16. "code.gitea.io/gitea/modules/context"
  17. auth "code.gitea.io/gitea/modules/forms"
  18. "code.gitea.io/gitea/modules/git"
  19. "code.gitea.io/gitea/modules/log"
  20. "code.gitea.io/gitea/modules/repository"
  21. "code.gitea.io/gitea/modules/setting"
  22. "code.gitea.io/gitea/modules/structs"
  23. "code.gitea.io/gitea/modules/timeutil"
  24. "code.gitea.io/gitea/modules/validation"
  25. "code.gitea.io/gitea/modules/web"
  26. "code.gitea.io/gitea/routers/utils"
  27. "code.gitea.io/gitea/services/mailer"
  28. mirror_service "code.gitea.io/gitea/services/mirror"
  29. repo_service "code.gitea.io/gitea/services/repository"
  30. "mvdan.cc/xurls/v2"
  31. )
  32. const (
  33. tplSettingsOptions base.TplName = "repo/settings/options"
  34. tplCollaboration base.TplName = "repo/settings/collaboration"
  35. tplBranches base.TplName = "repo/settings/branches"
  36. tplGithooks base.TplName = "repo/settings/githooks"
  37. tplGithookEdit base.TplName = "repo/settings/githook_edit"
  38. tplDeployKeys base.TplName = "repo/settings/deploy_keys"
  39. tplProtectedBranch base.TplName = "repo/settings/protected_branch"
  40. )
  41. var validFormAddress *regexp.Regexp
  42. // Settings show a repository's settings page
  43. func Settings(ctx *context.Context) {
  44. ctx.Data["Title"] = ctx.Tr("repo.settings")
  45. ctx.Data["PageIsSettingsOptions"] = true
  46. ctx.Data["ForcePrivate"] = setting.Repository.ForcePrivate
  47. signing, _ := models.SigningKey(ctx.Repo.Repository.RepoPath())
  48. ctx.Data["SigningKeyAvailable"] = len(signing) > 0
  49. ctx.Data["SigningSettings"] = setting.Repository.Signing
  50. ctx.HTML(200, tplSettingsOptions)
  51. }
  52. // SettingsPost response for changes of a repository
  53. func SettingsPost(ctx *context.Context) {
  54. form := web.GetForm(ctx).(*auth.RepoSettingForm)
  55. ctx.Data["Title"] = ctx.Tr("repo.settings")
  56. ctx.Data["PageIsSettingsOptions"] = true
  57. repo := ctx.Repo.Repository
  58. switch ctx.Query("action") {
  59. case "update":
  60. if ctx.HasError() {
  61. ctx.HTML(200, tplSettingsOptions)
  62. return
  63. }
  64. newRepoName := form.RepoName
  65. // Check if repository name has been changed.
  66. if repo.LowerName != strings.ToLower(newRepoName) {
  67. // Close the GitRepo if open
  68. if ctx.Repo.GitRepo != nil {
  69. ctx.Repo.GitRepo.Close()
  70. ctx.Repo.GitRepo = nil
  71. }
  72. if err := repo_service.ChangeRepositoryName(ctx.User, repo, newRepoName); err != nil {
  73. ctx.Data["Err_RepoName"] = true
  74. switch {
  75. case models.IsErrRepoAlreadyExist(err):
  76. ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tplSettingsOptions, &form)
  77. case models.IsErrNameReserved(err):
  78. ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tplSettingsOptions, &form)
  79. case models.IsErrRepoFilesAlreadyExist(err):
  80. ctx.Data["Err_RepoName"] = true
  81. switch {
  82. case ctx.IsUserSiteAdmin() || (setting.Repository.AllowAdoptionOfUnadoptedRepositories && setting.Repository.AllowDeleteOfUnadoptedRepositories):
  83. ctx.RenderWithErr(ctx.Tr("form.repository_files_already_exist.adopt_or_delete"), tplSettingsOptions, form)
  84. case setting.Repository.AllowAdoptionOfUnadoptedRepositories:
  85. ctx.RenderWithErr(ctx.Tr("form.repository_files_already_exist.adopt"), tplSettingsOptions, form)
  86. case setting.Repository.AllowDeleteOfUnadoptedRepositories:
  87. ctx.RenderWithErr(ctx.Tr("form.repository_files_already_exist.delete"), tplSettingsOptions, form)
  88. default:
  89. ctx.RenderWithErr(ctx.Tr("form.repository_files_already_exist"), tplSettingsOptions, form)
  90. }
  91. case models.IsErrNamePatternNotAllowed(err):
  92. ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSettingsOptions, &form)
  93. default:
  94. ctx.ServerError("ChangeRepositoryName", err)
  95. }
  96. return
  97. }
  98. log.Trace("Repository name changed: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newRepoName)
  99. }
  100. // In case it's just a case change.
  101. repo.Name = newRepoName
  102. repo.LowerName = strings.ToLower(newRepoName)
  103. repo.Description = form.Description
  104. repo.Website = form.Website
  105. repo.IsTemplate = form.Template
  106. // Visibility of forked repository is forced sync with base repository.
  107. if repo.IsFork {
  108. form.Private = repo.BaseRepo.IsPrivate || repo.BaseRepo.Owner.Visibility == structs.VisibleTypePrivate
  109. }
  110. visibilityChanged := repo.IsPrivate != form.Private
  111. // when ForcePrivate enabled, you could change public repo to private, but only admin users can change private to public
  112. if visibilityChanged && setting.Repository.ForcePrivate && !form.Private && !ctx.User.IsAdmin {
  113. ctx.ServerError("Force Private enabled", errors.New("cannot change private repository to public"))
  114. return
  115. }
  116. repo.IsPrivate = form.Private
  117. if err := models.UpdateRepository(repo, visibilityChanged); err != nil {
  118. ctx.ServerError("UpdateRepository", err)
  119. return
  120. }
  121. log.Trace("Repository basic settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  122. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  123. ctx.Redirect(repo.Link() + "/settings")
  124. case "mirror":
  125. if !repo.IsMirror {
  126. ctx.NotFound("", nil)
  127. return
  128. }
  129. // This section doesn't require repo_name/RepoName to be set in the form, don't show it
  130. // as an error on the UI for this action
  131. ctx.Data["Err_RepoName"] = nil
  132. interval, err := time.ParseDuration(form.Interval)
  133. if err != nil || (interval != 0 && interval < setting.Mirror.MinInterval) {
  134. ctx.Data["Err_Interval"] = true
  135. ctx.RenderWithErr(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
  136. } else {
  137. ctx.Repo.Mirror.EnablePrune = form.EnablePrune
  138. ctx.Repo.Mirror.Interval = interval
  139. if interval != 0 {
  140. ctx.Repo.Mirror.NextUpdateUnix = timeutil.TimeStampNow().AddDuration(interval)
  141. } else {
  142. ctx.Repo.Mirror.NextUpdateUnix = 0
  143. }
  144. if err := models.UpdateMirror(ctx.Repo.Mirror); err != nil {
  145. ctx.Data["Err_Interval"] = true
  146. ctx.RenderWithErr(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
  147. return
  148. }
  149. }
  150. // Validate the form.MirrorAddress
  151. u, err := url.Parse(form.MirrorAddress)
  152. if err != nil {
  153. ctx.Data["Err_MirrorAddress"] = true
  154. ctx.RenderWithErr(ctx.Tr("repo.mirror_address_url_invalid"), tplSettingsOptions, &form)
  155. return
  156. }
  157. if u.Opaque != "" || !(u.Scheme == "http" || u.Scheme == "https" || u.Scheme == "git") {
  158. ctx.Data["Err_MirrorAddress"] = true
  159. ctx.RenderWithErr(ctx.Tr("repo.mirror_address_protocol_invalid"), tplSettingsOptions, &form)
  160. return
  161. }
  162. if form.MirrorUsername != "" || form.MirrorPassword != "" {
  163. u.User = url.UserPassword(form.MirrorUsername, form.MirrorPassword)
  164. }
  165. // Now use xurls
  166. address := validFormAddress.FindString(form.MirrorAddress)
  167. if address != form.MirrorAddress && form.MirrorAddress != "" {
  168. ctx.Data["Err_MirrorAddress"] = true
  169. ctx.RenderWithErr(ctx.Tr("repo.mirror_address_url_invalid"), tplSettingsOptions, &form)
  170. return
  171. }
  172. if u.EscapedPath() == "" || u.Host == "" || !u.IsAbs() {
  173. ctx.Data["Err_MirrorAddress"] = true
  174. ctx.RenderWithErr(ctx.Tr("repo.mirror_address_url_invalid"), tplSettingsOptions, &form)
  175. return
  176. }
  177. address = u.String()
  178. if err := mirror_service.UpdateAddress(ctx.Repo.Mirror, address); err != nil {
  179. ctx.ServerError("UpdateAddress", err)
  180. return
  181. }
  182. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  183. ctx.Redirect(repo.Link() + "/settings")
  184. case "mirror-sync":
  185. if !repo.IsMirror {
  186. ctx.NotFound("", nil)
  187. return
  188. }
  189. mirror_service.StartToMirror(repo.ID)
  190. ctx.Flash.Info(ctx.Tr("repo.settings.mirror_sync_in_progress"))
  191. ctx.Redirect(repo.Link() + "/settings")
  192. case "advanced":
  193. var units []models.RepoUnit
  194. var deleteUnitTypes []models.UnitType
  195. // This section doesn't require repo_name/RepoName to be set in the form, don't show it
  196. // as an error on the UI for this action
  197. ctx.Data["Err_RepoName"] = nil
  198. if form.EnableWiki && form.EnableExternalWiki && !models.UnitTypeExternalWiki.UnitGlobalDisabled() {
  199. if !validation.IsValidExternalURL(form.ExternalWikiURL) {
  200. ctx.Flash.Error(ctx.Tr("repo.settings.external_wiki_url_error"))
  201. ctx.Redirect(repo.Link() + "/settings")
  202. return
  203. }
  204. units = append(units, models.RepoUnit{
  205. RepoID: repo.ID,
  206. Type: models.UnitTypeExternalWiki,
  207. Config: &models.ExternalWikiConfig{
  208. ExternalWikiURL: form.ExternalWikiURL,
  209. },
  210. })
  211. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeWiki)
  212. } else if form.EnableWiki && !form.EnableExternalWiki && !models.UnitTypeWiki.UnitGlobalDisabled() {
  213. units = append(units, models.RepoUnit{
  214. RepoID: repo.ID,
  215. Type: models.UnitTypeWiki,
  216. Config: new(models.UnitConfig),
  217. })
  218. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeExternalWiki)
  219. } else {
  220. if !models.UnitTypeExternalWiki.UnitGlobalDisabled() {
  221. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeExternalWiki)
  222. }
  223. if !models.UnitTypeWiki.UnitGlobalDisabled() {
  224. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeWiki)
  225. }
  226. }
  227. if form.EnableIssues && form.EnableExternalTracker && !models.UnitTypeExternalTracker.UnitGlobalDisabled() {
  228. if !validation.IsValidExternalURL(form.ExternalTrackerURL) {
  229. ctx.Flash.Error(ctx.Tr("repo.settings.external_tracker_url_error"))
  230. ctx.Redirect(repo.Link() + "/settings")
  231. return
  232. }
  233. if len(form.TrackerURLFormat) != 0 && !validation.IsValidExternalTrackerURLFormat(form.TrackerURLFormat) {
  234. ctx.Flash.Error(ctx.Tr("repo.settings.tracker_url_format_error"))
  235. ctx.Redirect(repo.Link() + "/settings")
  236. return
  237. }
  238. units = append(units, models.RepoUnit{
  239. RepoID: repo.ID,
  240. Type: models.UnitTypeExternalTracker,
  241. Config: &models.ExternalTrackerConfig{
  242. ExternalTrackerURL: form.ExternalTrackerURL,
  243. ExternalTrackerFormat: form.TrackerURLFormat,
  244. ExternalTrackerStyle: form.TrackerIssueStyle,
  245. },
  246. })
  247. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeIssues)
  248. } else if form.EnableIssues && !form.EnableExternalTracker && !models.UnitTypeIssues.UnitGlobalDisabled() {
  249. units = append(units, models.RepoUnit{
  250. RepoID: repo.ID,
  251. Type: models.UnitTypeIssues,
  252. Config: &models.IssuesConfig{
  253. EnableTimetracker: form.EnableTimetracker,
  254. AllowOnlyContributorsToTrackTime: form.AllowOnlyContributorsToTrackTime,
  255. EnableDependencies: form.EnableIssueDependencies,
  256. },
  257. })
  258. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeExternalTracker)
  259. } else {
  260. if !models.UnitTypeExternalTracker.UnitGlobalDisabled() {
  261. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeExternalTracker)
  262. }
  263. if !models.UnitTypeIssues.UnitGlobalDisabled() {
  264. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeIssues)
  265. }
  266. }
  267. if form.EnableProjects && !models.UnitTypeProjects.UnitGlobalDisabled() {
  268. units = append(units, models.RepoUnit{
  269. RepoID: repo.ID,
  270. Type: models.UnitTypeProjects,
  271. })
  272. } else if !models.UnitTypeProjects.UnitGlobalDisabled() {
  273. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeProjects)
  274. }
  275. if form.EnablePulls && !models.UnitTypePullRequests.UnitGlobalDisabled() {
  276. units = append(units, models.RepoUnit{
  277. RepoID: repo.ID,
  278. Type: models.UnitTypePullRequests,
  279. Config: &models.PullRequestsConfig{
  280. IgnoreWhitespaceConflicts: form.PullsIgnoreWhitespace,
  281. AllowMerge: form.PullsAllowMerge,
  282. AllowRebase: form.PullsAllowRebase,
  283. AllowRebaseMerge: form.PullsAllowRebaseMerge,
  284. AllowSquash: form.PullsAllowSquash,
  285. },
  286. })
  287. } else if !models.UnitTypePullRequests.UnitGlobalDisabled() {
  288. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypePullRequests)
  289. }
  290. if err := models.UpdateRepositoryUnits(repo, units, deleteUnitTypes); err != nil {
  291. ctx.ServerError("UpdateRepositoryUnits", err)
  292. return
  293. }
  294. log.Trace("Repository advanced settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  295. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  296. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  297. case "signing":
  298. changed := false
  299. trustModel := models.ToTrustModel(form.TrustModel)
  300. if trustModel != repo.TrustModel {
  301. repo.TrustModel = trustModel
  302. changed = true
  303. }
  304. if changed {
  305. if err := models.UpdateRepository(repo, false); err != nil {
  306. ctx.ServerError("UpdateRepository", err)
  307. return
  308. }
  309. }
  310. log.Trace("Repository signing settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  311. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  312. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  313. case "admin":
  314. if !ctx.User.IsAdmin {
  315. ctx.Error(403)
  316. return
  317. }
  318. if repo.IsFsckEnabled != form.EnableHealthCheck {
  319. repo.IsFsckEnabled = form.EnableHealthCheck
  320. }
  321. if repo.CloseIssuesViaCommitInAnyBranch != form.EnableCloseIssuesViaCommitInAnyBranch {
  322. repo.CloseIssuesViaCommitInAnyBranch = form.EnableCloseIssuesViaCommitInAnyBranch
  323. }
  324. if err := models.UpdateRepository(repo, false); err != nil {
  325. ctx.ServerError("UpdateRepository", err)
  326. return
  327. }
  328. log.Trace("Repository admin settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  329. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  330. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  331. case "convert":
  332. if !ctx.Repo.IsOwner() {
  333. ctx.Error(404)
  334. return
  335. }
  336. if repo.Name != form.RepoName {
  337. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  338. return
  339. }
  340. if !repo.IsMirror {
  341. ctx.Error(404)
  342. return
  343. }
  344. repo.IsMirror = false
  345. if _, err := repository.CleanUpMigrateInfo(repo); err != nil {
  346. ctx.ServerError("CleanUpMigrateInfo", err)
  347. return
  348. } else if err = models.DeleteMirrorByRepoID(ctx.Repo.Repository.ID); err != nil {
  349. ctx.ServerError("DeleteMirrorByRepoID", err)
  350. return
  351. }
  352. log.Trace("Repository converted from mirror to regular: %s", repo.FullName())
  353. ctx.Flash.Success(ctx.Tr("repo.settings.convert_succeed"))
  354. ctx.Redirect(repo.Link())
  355. case "convert_fork":
  356. if !ctx.Repo.IsOwner() {
  357. ctx.Error(404)
  358. return
  359. }
  360. if err := repo.GetOwner(); err != nil {
  361. ctx.ServerError("Convert Fork", err)
  362. return
  363. }
  364. if repo.Name != form.RepoName {
  365. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  366. return
  367. }
  368. if !repo.IsFork {
  369. ctx.Error(404)
  370. return
  371. }
  372. if !ctx.Repo.Owner.CanCreateRepo() {
  373. ctx.Flash.Error(ctx.Tr("repo.form.reach_limit_of_creation", ctx.User.MaxCreationLimit()))
  374. ctx.Redirect(repo.Link() + "/settings")
  375. return
  376. }
  377. repo.IsFork = false
  378. repo.ForkID = 0
  379. if err := models.UpdateRepository(repo, false); err != nil {
  380. log.Error("Unable to update repository %-v whilst converting from fork", repo)
  381. ctx.ServerError("Convert Fork", err)
  382. return
  383. }
  384. log.Trace("Repository converted from fork to regular: %s", repo.FullName())
  385. ctx.Flash.Success(ctx.Tr("repo.settings.convert_fork_succeed"))
  386. ctx.Redirect(repo.Link())
  387. case "transfer":
  388. if !ctx.Repo.IsOwner() {
  389. ctx.Error(404)
  390. return
  391. }
  392. if repo.Name != form.RepoName {
  393. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  394. return
  395. }
  396. newOwner, err := models.GetUserByName(ctx.Query("new_owner_name"))
  397. if err != nil {
  398. if models.IsErrUserNotExist(err) {
  399. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_owner_name"), tplSettingsOptions, nil)
  400. return
  401. }
  402. ctx.ServerError("IsUserExist", err)
  403. return
  404. }
  405. if newOwner.Type == models.UserTypeOrganization {
  406. if !ctx.User.IsAdmin && newOwner.Visibility == structs.VisibleTypePrivate && !newOwner.HasMemberWithUserID(ctx.User.ID) {
  407. // The user shouldn't know about this organization
  408. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_owner_name"), tplSettingsOptions, nil)
  409. return
  410. }
  411. }
  412. // Close the GitRepo if open
  413. if ctx.Repo.GitRepo != nil {
  414. ctx.Repo.GitRepo.Close()
  415. ctx.Repo.GitRepo = nil
  416. }
  417. if err := repo_service.StartRepositoryTransfer(ctx.User, newOwner, repo, nil); err != nil {
  418. if models.IsErrRepoAlreadyExist(err) {
  419. ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplSettingsOptions, nil)
  420. } else if models.IsErrRepoTransferInProgress(err) {
  421. ctx.RenderWithErr(ctx.Tr("repo.settings.transfer_in_progress"), tplSettingsOptions, nil)
  422. } else {
  423. ctx.ServerError("TransferOwnership", err)
  424. }
  425. return
  426. }
  427. log.Trace("Repository transfer process was started: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newOwner)
  428. ctx.Flash.Success(ctx.Tr("repo.settings.transfer_started", newOwner.DisplayName()))
  429. ctx.Redirect(setting.AppSubURL + "/" + ctx.Repo.Owner.Name + "/" + repo.Name + "/settings")
  430. case "cancel_transfer":
  431. if !ctx.Repo.IsOwner() {
  432. ctx.Error(404)
  433. return
  434. }
  435. repoTransfer, err := models.GetPendingRepositoryTransfer(ctx.Repo.Repository)
  436. if err != nil {
  437. if models.IsErrNoPendingTransfer(err) {
  438. ctx.Flash.Error("repo.settings.transfer_abort_invalid")
  439. ctx.Redirect(setting.AppSubURL + "/" + ctx.User.Name + "/" + repo.Name + "/settings")
  440. } else {
  441. ctx.ServerError("GetPendingRepositoryTransfer", err)
  442. }
  443. return
  444. }
  445. if err := repoTransfer.LoadAttributes(); err != nil {
  446. ctx.ServerError("LoadRecipient", err)
  447. return
  448. }
  449. if err := models.CancelRepositoryTransfer(ctx.Repo.Repository); err != nil {
  450. ctx.ServerError("CancelRepositoryTransfer", err)
  451. return
  452. }
  453. log.Trace("Repository transfer process was cancelled: %s/%s ", ctx.Repo.Owner.Name, repo.Name)
  454. ctx.Flash.Success(ctx.Tr("repo.settings.transfer_abort_success", repoTransfer.Recipient.Name))
  455. ctx.Redirect(setting.AppSubURL + "/" + ctx.Repo.Owner.Name + "/" + repo.Name + "/settings")
  456. case "delete":
  457. if !ctx.Repo.IsOwner() {
  458. ctx.Error(404)
  459. return
  460. }
  461. if repo.Name != form.RepoName {
  462. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  463. return
  464. }
  465. if err := repo_service.DeleteRepository(ctx.User, ctx.Repo.Repository); err != nil {
  466. ctx.ServerError("DeleteRepository", err)
  467. return
  468. }
  469. log.Trace("Repository deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  470. ctx.Flash.Success(ctx.Tr("repo.settings.deletion_success"))
  471. ctx.Redirect(ctx.Repo.Owner.DashboardLink())
  472. case "delete-wiki":
  473. if !ctx.Repo.IsOwner() {
  474. ctx.Error(404)
  475. return
  476. }
  477. if repo.Name != form.RepoName {
  478. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  479. return
  480. }
  481. err := repo.DeleteWiki()
  482. if err != nil {
  483. log.Error("Delete Wiki: %v", err.Error())
  484. }
  485. log.Trace("Repository wiki deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  486. ctx.Flash.Success(ctx.Tr("repo.settings.wiki_deletion_success"))
  487. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  488. case "archive":
  489. if !ctx.Repo.IsOwner() {
  490. ctx.Error(403)
  491. return
  492. }
  493. if repo.IsMirror {
  494. ctx.Flash.Error(ctx.Tr("repo.settings.archive.error_ismirror"))
  495. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  496. return
  497. }
  498. if err := repo.SetArchiveRepoState(true); err != nil {
  499. log.Error("Tried to archive a repo: %s", err)
  500. ctx.Flash.Error(ctx.Tr("repo.settings.archive.error"))
  501. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  502. return
  503. }
  504. ctx.Flash.Success(ctx.Tr("repo.settings.archive.success"))
  505. log.Trace("Repository was archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  506. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  507. case "unarchive":
  508. if !ctx.Repo.IsOwner() {
  509. ctx.Error(403)
  510. return
  511. }
  512. if err := repo.SetArchiveRepoState(false); err != nil {
  513. log.Error("Tried to unarchive a repo: %s", err)
  514. ctx.Flash.Error(ctx.Tr("repo.settings.unarchive.error"))
  515. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  516. return
  517. }
  518. ctx.Flash.Success(ctx.Tr("repo.settings.unarchive.success"))
  519. log.Trace("Repository was un-archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  520. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  521. default:
  522. ctx.NotFound("", nil)
  523. }
  524. }
  525. // Collaboration render a repository's collaboration page
  526. func Collaboration(ctx *context.Context) {
  527. ctx.Data["Title"] = ctx.Tr("repo.settings")
  528. ctx.Data["PageIsSettingsCollaboration"] = true
  529. users, err := ctx.Repo.Repository.GetCollaborators(models.ListOptions{})
  530. if err != nil {
  531. ctx.ServerError("GetCollaborators", err)
  532. return
  533. }
  534. ctx.Data["Collaborators"] = users
  535. teams, err := ctx.Repo.Repository.GetRepoTeams()
  536. if err != nil {
  537. ctx.ServerError("GetRepoTeams", err)
  538. return
  539. }
  540. ctx.Data["Teams"] = teams
  541. ctx.Data["Repo"] = ctx.Repo.Repository
  542. ctx.Data["OrgID"] = ctx.Repo.Repository.OwnerID
  543. ctx.Data["OrgName"] = ctx.Repo.Repository.OwnerName
  544. ctx.Data["Org"] = ctx.Repo.Repository.Owner
  545. ctx.Data["Units"] = models.Units
  546. ctx.HTML(200, tplCollaboration)
  547. }
  548. // CollaborationPost response for actions for a collaboration of a repository
  549. func CollaborationPost(ctx *context.Context) {
  550. name := utils.RemoveUsernameParameterSuffix(strings.ToLower(ctx.Query("collaborator")))
  551. if len(name) == 0 || ctx.Repo.Owner.LowerName == name {
  552. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  553. return
  554. }
  555. u, err := models.GetUserByName(name)
  556. if err != nil {
  557. if models.IsErrUserNotExist(err) {
  558. ctx.Flash.Error(ctx.Tr("form.user_not_exist"))
  559. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  560. } else {
  561. ctx.ServerError("GetUserByName", err)
  562. }
  563. return
  564. }
  565. if !u.IsActive {
  566. ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_inactive_user"))
  567. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  568. return
  569. }
  570. // Organization is not allowed to be added as a collaborator.
  571. if u.IsOrganization() {
  572. ctx.Flash.Error(ctx.Tr("repo.settings.org_not_allowed_to_be_collaborator"))
  573. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  574. return
  575. }
  576. if got, err := ctx.Repo.Repository.IsCollaborator(u.ID); err == nil && got {
  577. ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_duplicate"))
  578. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  579. return
  580. }
  581. if err = ctx.Repo.Repository.AddCollaborator(u); err != nil {
  582. ctx.ServerError("AddCollaborator", err)
  583. return
  584. }
  585. if setting.Service.EnableNotifyMail {
  586. mailer.SendCollaboratorMail(u, ctx.User, ctx.Repo.Repository)
  587. }
  588. ctx.Flash.Success(ctx.Tr("repo.settings.add_collaborator_success"))
  589. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  590. }
  591. // ChangeCollaborationAccessMode response for changing access of a collaboration
  592. func ChangeCollaborationAccessMode(ctx *context.Context) {
  593. if err := ctx.Repo.Repository.ChangeCollaborationAccessMode(
  594. ctx.QueryInt64("uid"),
  595. models.AccessMode(ctx.QueryInt("mode"))); err != nil {
  596. log.Error("ChangeCollaborationAccessMode: %v", err)
  597. }
  598. }
  599. // DeleteCollaboration delete a collaboration for a repository
  600. func DeleteCollaboration(ctx *context.Context) {
  601. if err := ctx.Repo.Repository.DeleteCollaboration(ctx.QueryInt64("id")); err != nil {
  602. ctx.Flash.Error("DeleteCollaboration: " + err.Error())
  603. } else {
  604. ctx.Flash.Success(ctx.Tr("repo.settings.remove_collaborator_success"))
  605. }
  606. ctx.JSON(200, map[string]interface{}{
  607. "redirect": ctx.Repo.RepoLink + "/settings/collaboration",
  608. })
  609. }
  610. // AddTeamPost response for adding a team to a repository
  611. func AddTeamPost(ctx *context.Context) {
  612. if !ctx.Repo.Owner.RepoAdminChangeTeamAccess && !ctx.Repo.IsOwner() {
  613. ctx.Flash.Error(ctx.Tr("repo.settings.change_team_access_not_allowed"))
  614. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  615. return
  616. }
  617. name := utils.RemoveUsernameParameterSuffix(strings.ToLower(ctx.Query("team")))
  618. if len(name) == 0 {
  619. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  620. return
  621. }
  622. team, err := ctx.Repo.Owner.GetTeam(name)
  623. if err != nil {
  624. if models.IsErrTeamNotExist(err) {
  625. ctx.Flash.Error(ctx.Tr("form.team_not_exist"))
  626. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  627. } else {
  628. ctx.ServerError("GetTeam", err)
  629. }
  630. return
  631. }
  632. if team.OrgID != ctx.Repo.Repository.OwnerID {
  633. ctx.Flash.Error(ctx.Tr("repo.settings.team_not_in_organization"))
  634. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  635. return
  636. }
  637. if models.HasTeamRepo(ctx.Repo.Repository.OwnerID, team.ID, ctx.Repo.Repository.ID) {
  638. ctx.Flash.Error(ctx.Tr("repo.settings.add_team_duplicate"))
  639. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  640. return
  641. }
  642. if err = team.AddRepository(ctx.Repo.Repository); err != nil {
  643. ctx.ServerError("team.AddRepository", err)
  644. return
  645. }
  646. ctx.Flash.Success(ctx.Tr("repo.settings.add_team_success"))
  647. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  648. }
  649. // DeleteTeam response for deleting a team from a repository
  650. func DeleteTeam(ctx *context.Context) {
  651. if !ctx.Repo.Owner.RepoAdminChangeTeamAccess && !ctx.Repo.IsOwner() {
  652. ctx.Flash.Error(ctx.Tr("repo.settings.change_team_access_not_allowed"))
  653. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  654. return
  655. }
  656. team, err := models.GetTeamByID(ctx.QueryInt64("id"))
  657. if err != nil {
  658. ctx.ServerError("GetTeamByID", err)
  659. return
  660. }
  661. if err = team.RemoveRepository(ctx.Repo.Repository.ID); err != nil {
  662. ctx.ServerError("team.RemoveRepositorys", err)
  663. return
  664. }
  665. ctx.Flash.Success(ctx.Tr("repo.settings.remove_team_success"))
  666. ctx.JSON(200, map[string]interface{}{
  667. "redirect": ctx.Repo.RepoLink + "/settings/collaboration",
  668. })
  669. }
  670. // parseOwnerAndRepo get repos by owner
  671. func parseOwnerAndRepo(ctx *context.Context) (*models.User, *models.Repository) {
  672. owner, err := models.GetUserByName(ctx.Params(":username"))
  673. if err != nil {
  674. if models.IsErrUserNotExist(err) {
  675. ctx.NotFound("GetUserByName", err)
  676. } else {
  677. ctx.ServerError("GetUserByName", err)
  678. }
  679. return nil, nil
  680. }
  681. repo, err := models.GetRepositoryByName(owner.ID, ctx.Params(":reponame"))
  682. if err != nil {
  683. if models.IsErrRepoNotExist(err) {
  684. ctx.NotFound("GetRepositoryByName", err)
  685. } else {
  686. ctx.ServerError("GetRepositoryByName", err)
  687. }
  688. return nil, nil
  689. }
  690. return owner, repo
  691. }
  692. // GitHooks hooks of a repository
  693. func GitHooks(ctx *context.Context) {
  694. ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
  695. ctx.Data["PageIsSettingsGitHooks"] = true
  696. hooks, err := ctx.Repo.GitRepo.Hooks()
  697. if err != nil {
  698. ctx.ServerError("Hooks", err)
  699. return
  700. }
  701. ctx.Data["Hooks"] = hooks
  702. ctx.HTML(200, tplGithooks)
  703. }
  704. // GitHooksEdit render for editing a hook of repository page
  705. func GitHooksEdit(ctx *context.Context) {
  706. ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
  707. ctx.Data["PageIsSettingsGitHooks"] = true
  708. name := ctx.Params(":name")
  709. hook, err := ctx.Repo.GitRepo.GetHook(name)
  710. if err != nil {
  711. if err == git.ErrNotValidHook {
  712. ctx.NotFound("GetHook", err)
  713. } else {
  714. ctx.ServerError("GetHook", err)
  715. }
  716. return
  717. }
  718. ctx.Data["Hook"] = hook
  719. ctx.HTML(200, tplGithookEdit)
  720. }
  721. // GitHooksEditPost response for editing a git hook of a repository
  722. func GitHooksEditPost(ctx *context.Context) {
  723. name := ctx.Params(":name")
  724. hook, err := ctx.Repo.GitRepo.GetHook(name)
  725. if err != nil {
  726. if err == git.ErrNotValidHook {
  727. ctx.NotFound("GetHook", err)
  728. } else {
  729. ctx.ServerError("GetHook", err)
  730. }
  731. return
  732. }
  733. hook.Content = ctx.Query("content")
  734. if err = hook.Update(); err != nil {
  735. ctx.ServerError("hook.Update", err)
  736. return
  737. }
  738. ctx.Redirect(ctx.Repo.RepoLink + "/settings/hooks/git")
  739. }
  740. // DeployKeys render the deploy keys list of a repository page
  741. func DeployKeys(ctx *context.Context) {
  742. ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
  743. ctx.Data["PageIsSettingsKeys"] = true
  744. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  745. keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID, models.ListOptions{})
  746. if err != nil {
  747. ctx.ServerError("ListDeployKeys", err)
  748. return
  749. }
  750. ctx.Data["Deploykeys"] = keys
  751. ctx.HTML(200, tplDeployKeys)
  752. }
  753. // DeployKeysPost response for adding a deploy key of a repository
  754. func DeployKeysPost(ctx *context.Context) {
  755. form := web.GetForm(ctx).(*auth.AddKeyForm)
  756. ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
  757. ctx.Data["PageIsSettingsKeys"] = true
  758. keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID, models.ListOptions{})
  759. if err != nil {
  760. ctx.ServerError("ListDeployKeys", err)
  761. return
  762. }
  763. ctx.Data["Deploykeys"] = keys
  764. if ctx.HasError() {
  765. ctx.HTML(200, tplDeployKeys)
  766. return
  767. }
  768. content, err := models.CheckPublicKeyString(form.Content)
  769. if err != nil {
  770. if models.IsErrSSHDisabled(err) {
  771. ctx.Flash.Info(ctx.Tr("settings.ssh_disabled"))
  772. } else if models.IsErrKeyUnableVerify(err) {
  773. ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key"))
  774. } else {
  775. ctx.Data["HasError"] = true
  776. ctx.Data["Err_Content"] = true
  777. ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error()))
  778. }
  779. ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
  780. return
  781. }
  782. key, err := models.AddDeployKey(ctx.Repo.Repository.ID, form.Title, content, !form.IsWritable)
  783. if err != nil {
  784. ctx.Data["HasError"] = true
  785. switch {
  786. case models.IsErrDeployKeyAlreadyExist(err):
  787. ctx.Data["Err_Content"] = true
  788. ctx.RenderWithErr(ctx.Tr("repo.settings.key_been_used"), tplDeployKeys, &form)
  789. case models.IsErrKeyAlreadyExist(err):
  790. ctx.Data["Err_Content"] = true
  791. ctx.RenderWithErr(ctx.Tr("settings.ssh_key_been_used"), tplDeployKeys, &form)
  792. case models.IsErrKeyNameAlreadyUsed(err):
  793. ctx.Data["Err_Title"] = true
  794. ctx.RenderWithErr(ctx.Tr("repo.settings.key_name_used"), tplDeployKeys, &form)
  795. case models.IsErrDeployKeyNameAlreadyUsed(err):
  796. ctx.Data["Err_Title"] = true
  797. ctx.RenderWithErr(ctx.Tr("repo.settings.key_name_used"), tplDeployKeys, &form)
  798. default:
  799. ctx.ServerError("AddDeployKey", err)
  800. }
  801. return
  802. }
  803. log.Trace("Deploy key added: %d", ctx.Repo.Repository.ID)
  804. ctx.Flash.Success(ctx.Tr("repo.settings.add_key_success", key.Name))
  805. ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
  806. }
  807. // DeleteDeployKey response for deleting a deploy key
  808. func DeleteDeployKey(ctx *context.Context) {
  809. if err := models.DeleteDeployKey(ctx.User, ctx.QueryInt64("id")); err != nil {
  810. ctx.Flash.Error("DeleteDeployKey: " + err.Error())
  811. } else {
  812. ctx.Flash.Success(ctx.Tr("repo.settings.deploy_key_deletion_success"))
  813. }
  814. ctx.JSON(200, map[string]interface{}{
  815. "redirect": ctx.Repo.RepoLink + "/settings/keys",
  816. })
  817. }
  818. func init() {
  819. var err error
  820. validFormAddress, err = xurls.StrictMatchingScheme(`(https?)|(git)://`)
  821. if err != nil {
  822. panic(err)
  823. }
  824. }
  825. // UpdateAvatarSetting update repo's avatar
  826. func UpdateAvatarSetting(ctx *context.Context, form auth.AvatarForm) error {
  827. ctxRepo := ctx.Repo.Repository
  828. if form.Avatar == nil {
  829. // No avatar is uploaded and we not removing it here.
  830. // No random avatar generated here.
  831. // Just exit, no action.
  832. if ctxRepo.CustomAvatarRelativePath() == "" {
  833. log.Trace("No avatar was uploaded for repo: %d. Default icon will appear instead.", ctxRepo.ID)
  834. }
  835. return nil
  836. }
  837. r, err := form.Avatar.Open()
  838. if err != nil {
  839. return fmt.Errorf("Avatar.Open: %v", err)
  840. }
  841. defer r.Close()
  842. if form.Avatar.Size > setting.Avatar.MaxFileSize {
  843. return errors.New(ctx.Tr("settings.uploaded_avatar_is_too_big"))
  844. }
  845. data, err := ioutil.ReadAll(r)
  846. if err != nil {
  847. return fmt.Errorf("ioutil.ReadAll: %v", err)
  848. }
  849. if !base.IsImageFile(data) {
  850. return errors.New(ctx.Tr("settings.uploaded_avatar_not_a_image"))
  851. }
  852. if err = ctxRepo.UploadAvatar(data); err != nil {
  853. return fmt.Errorf("UploadAvatar: %v", err)
  854. }
  855. return nil
  856. }
  857. // SettingsAvatar save new POSTed repository avatar
  858. func SettingsAvatar(ctx *context.Context) {
  859. form := web.GetForm(ctx).(*auth.AvatarForm)
  860. form.Source = auth.AvatarLocal
  861. if err := UpdateAvatarSetting(ctx, *form); err != nil {
  862. ctx.Flash.Error(err.Error())
  863. } else {
  864. ctx.Flash.Success(ctx.Tr("repo.settings.update_avatar_success"))
  865. }
  866. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  867. }
  868. // SettingsDeleteAvatar delete repository avatar
  869. func SettingsDeleteAvatar(ctx *context.Context) {
  870. if err := ctx.Repo.Repository.DeleteAvatar(); err != nil {
  871. ctx.Flash.Error(fmt.Sprintf("DeleteAvatar: %v", err))
  872. }
  873. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  874. }