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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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. AllowManualMerge: form.PullsAllowManualMerge,
  286. AutodetectManualMerge: form.EnableAutodetectManualMerge,
  287. },
  288. })
  289. } else if !models.UnitTypePullRequests.UnitGlobalDisabled() {
  290. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypePullRequests)
  291. }
  292. if err := models.UpdateRepositoryUnits(repo, units, deleteUnitTypes); err != nil {
  293. ctx.ServerError("UpdateRepositoryUnits", err)
  294. return
  295. }
  296. log.Trace("Repository advanced settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  297. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  298. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  299. case "signing":
  300. changed := false
  301. trustModel := models.ToTrustModel(form.TrustModel)
  302. if trustModel != repo.TrustModel {
  303. repo.TrustModel = trustModel
  304. changed = true
  305. }
  306. if changed {
  307. if err := models.UpdateRepository(repo, false); err != nil {
  308. ctx.ServerError("UpdateRepository", err)
  309. return
  310. }
  311. }
  312. log.Trace("Repository signing settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  313. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  314. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  315. case "admin":
  316. if !ctx.User.IsAdmin {
  317. ctx.Error(403)
  318. return
  319. }
  320. if repo.IsFsckEnabled != form.EnableHealthCheck {
  321. repo.IsFsckEnabled = form.EnableHealthCheck
  322. }
  323. if repo.CloseIssuesViaCommitInAnyBranch != form.EnableCloseIssuesViaCommitInAnyBranch {
  324. repo.CloseIssuesViaCommitInAnyBranch = form.EnableCloseIssuesViaCommitInAnyBranch
  325. }
  326. if err := models.UpdateRepository(repo, false); err != nil {
  327. ctx.ServerError("UpdateRepository", err)
  328. return
  329. }
  330. log.Trace("Repository admin settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  331. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  332. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  333. case "convert":
  334. if !ctx.Repo.IsOwner() {
  335. ctx.Error(404)
  336. return
  337. }
  338. if repo.Name != form.RepoName {
  339. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  340. return
  341. }
  342. if !repo.IsMirror {
  343. ctx.Error(404)
  344. return
  345. }
  346. repo.IsMirror = false
  347. if _, err := repository.CleanUpMigrateInfo(repo); err != nil {
  348. ctx.ServerError("CleanUpMigrateInfo", err)
  349. return
  350. } else if err = models.DeleteMirrorByRepoID(ctx.Repo.Repository.ID); err != nil {
  351. ctx.ServerError("DeleteMirrorByRepoID", err)
  352. return
  353. }
  354. log.Trace("Repository converted from mirror to regular: %s", repo.FullName())
  355. ctx.Flash.Success(ctx.Tr("repo.settings.convert_succeed"))
  356. ctx.Redirect(repo.Link())
  357. case "convert_fork":
  358. if !ctx.Repo.IsOwner() {
  359. ctx.Error(404)
  360. return
  361. }
  362. if err := repo.GetOwner(); err != nil {
  363. ctx.ServerError("Convert Fork", err)
  364. return
  365. }
  366. if repo.Name != form.RepoName {
  367. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  368. return
  369. }
  370. if !repo.IsFork {
  371. ctx.Error(404)
  372. return
  373. }
  374. if !ctx.Repo.Owner.CanCreateRepo() {
  375. ctx.Flash.Error(ctx.Tr("repo.form.reach_limit_of_creation", ctx.User.MaxCreationLimit()))
  376. ctx.Redirect(repo.Link() + "/settings")
  377. return
  378. }
  379. repo.IsFork = false
  380. repo.ForkID = 0
  381. if err := models.UpdateRepository(repo, false); err != nil {
  382. log.Error("Unable to update repository %-v whilst converting from fork", repo)
  383. ctx.ServerError("Convert Fork", err)
  384. return
  385. }
  386. log.Trace("Repository converted from fork to regular: %s", repo.FullName())
  387. ctx.Flash.Success(ctx.Tr("repo.settings.convert_fork_succeed"))
  388. ctx.Redirect(repo.Link())
  389. case "transfer":
  390. if !ctx.Repo.IsOwner() {
  391. ctx.Error(404)
  392. return
  393. }
  394. if repo.Name != form.RepoName {
  395. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  396. return
  397. }
  398. newOwner, err := models.GetUserByName(ctx.Query("new_owner_name"))
  399. if err != nil {
  400. if models.IsErrUserNotExist(err) {
  401. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_owner_name"), tplSettingsOptions, nil)
  402. return
  403. }
  404. ctx.ServerError("IsUserExist", err)
  405. return
  406. }
  407. if newOwner.Type == models.UserTypeOrganization {
  408. if !ctx.User.IsAdmin && newOwner.Visibility == structs.VisibleTypePrivate && !newOwner.HasMemberWithUserID(ctx.User.ID) {
  409. // The user shouldn't know about this organization
  410. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_owner_name"), tplSettingsOptions, nil)
  411. return
  412. }
  413. }
  414. // Close the GitRepo if open
  415. if ctx.Repo.GitRepo != nil {
  416. ctx.Repo.GitRepo.Close()
  417. ctx.Repo.GitRepo = nil
  418. }
  419. if err := repo_service.StartRepositoryTransfer(ctx.User, newOwner, repo, nil); err != nil {
  420. if models.IsErrRepoAlreadyExist(err) {
  421. ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplSettingsOptions, nil)
  422. } else if models.IsErrRepoTransferInProgress(err) {
  423. ctx.RenderWithErr(ctx.Tr("repo.settings.transfer_in_progress"), tplSettingsOptions, nil)
  424. } else {
  425. ctx.ServerError("TransferOwnership", err)
  426. }
  427. return
  428. }
  429. log.Trace("Repository transfer process was started: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newOwner)
  430. ctx.Flash.Success(ctx.Tr("repo.settings.transfer_started", newOwner.DisplayName()))
  431. ctx.Redirect(setting.AppSubURL + "/" + ctx.Repo.Owner.Name + "/" + repo.Name + "/settings")
  432. case "cancel_transfer":
  433. if !ctx.Repo.IsOwner() {
  434. ctx.Error(404)
  435. return
  436. }
  437. repoTransfer, err := models.GetPendingRepositoryTransfer(ctx.Repo.Repository)
  438. if err != nil {
  439. if models.IsErrNoPendingTransfer(err) {
  440. ctx.Flash.Error("repo.settings.transfer_abort_invalid")
  441. ctx.Redirect(setting.AppSubURL + "/" + ctx.User.Name + "/" + repo.Name + "/settings")
  442. } else {
  443. ctx.ServerError("GetPendingRepositoryTransfer", err)
  444. }
  445. return
  446. }
  447. if err := repoTransfer.LoadAttributes(); err != nil {
  448. ctx.ServerError("LoadRecipient", err)
  449. return
  450. }
  451. if err := models.CancelRepositoryTransfer(ctx.Repo.Repository); err != nil {
  452. ctx.ServerError("CancelRepositoryTransfer", err)
  453. return
  454. }
  455. log.Trace("Repository transfer process was cancelled: %s/%s ", ctx.Repo.Owner.Name, repo.Name)
  456. ctx.Flash.Success(ctx.Tr("repo.settings.transfer_abort_success", repoTransfer.Recipient.Name))
  457. ctx.Redirect(setting.AppSubURL + "/" + ctx.Repo.Owner.Name + "/" + repo.Name + "/settings")
  458. case "delete":
  459. if !ctx.Repo.IsOwner() {
  460. ctx.Error(404)
  461. return
  462. }
  463. if repo.Name != form.RepoName {
  464. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  465. return
  466. }
  467. if err := repo_service.DeleteRepository(ctx.User, ctx.Repo.Repository); err != nil {
  468. ctx.ServerError("DeleteRepository", err)
  469. return
  470. }
  471. log.Trace("Repository deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  472. ctx.Flash.Success(ctx.Tr("repo.settings.deletion_success"))
  473. ctx.Redirect(ctx.Repo.Owner.DashboardLink())
  474. case "delete-wiki":
  475. if !ctx.Repo.IsOwner() {
  476. ctx.Error(404)
  477. return
  478. }
  479. if repo.Name != form.RepoName {
  480. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  481. return
  482. }
  483. err := repo.DeleteWiki()
  484. if err != nil {
  485. log.Error("Delete Wiki: %v", err.Error())
  486. }
  487. log.Trace("Repository wiki deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  488. ctx.Flash.Success(ctx.Tr("repo.settings.wiki_deletion_success"))
  489. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  490. case "archive":
  491. if !ctx.Repo.IsOwner() {
  492. ctx.Error(403)
  493. return
  494. }
  495. if repo.IsMirror {
  496. ctx.Flash.Error(ctx.Tr("repo.settings.archive.error_ismirror"))
  497. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  498. return
  499. }
  500. if err := repo.SetArchiveRepoState(true); err != nil {
  501. log.Error("Tried to archive a repo: %s", err)
  502. ctx.Flash.Error(ctx.Tr("repo.settings.archive.error"))
  503. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  504. return
  505. }
  506. ctx.Flash.Success(ctx.Tr("repo.settings.archive.success"))
  507. log.Trace("Repository was archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  508. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  509. case "unarchive":
  510. if !ctx.Repo.IsOwner() {
  511. ctx.Error(403)
  512. return
  513. }
  514. if err := repo.SetArchiveRepoState(false); err != nil {
  515. log.Error("Tried to unarchive a repo: %s", err)
  516. ctx.Flash.Error(ctx.Tr("repo.settings.unarchive.error"))
  517. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  518. return
  519. }
  520. ctx.Flash.Success(ctx.Tr("repo.settings.unarchive.success"))
  521. log.Trace("Repository was un-archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  522. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  523. default:
  524. ctx.NotFound("", nil)
  525. }
  526. }
  527. // Collaboration render a repository's collaboration page
  528. func Collaboration(ctx *context.Context) {
  529. ctx.Data["Title"] = ctx.Tr("repo.settings")
  530. ctx.Data["PageIsSettingsCollaboration"] = true
  531. users, err := ctx.Repo.Repository.GetCollaborators(models.ListOptions{})
  532. if err != nil {
  533. ctx.ServerError("GetCollaborators", err)
  534. return
  535. }
  536. ctx.Data["Collaborators"] = users
  537. teams, err := ctx.Repo.Repository.GetRepoTeams()
  538. if err != nil {
  539. ctx.ServerError("GetRepoTeams", err)
  540. return
  541. }
  542. ctx.Data["Teams"] = teams
  543. ctx.Data["Repo"] = ctx.Repo.Repository
  544. ctx.Data["OrgID"] = ctx.Repo.Repository.OwnerID
  545. ctx.Data["OrgName"] = ctx.Repo.Repository.OwnerName
  546. ctx.Data["Org"] = ctx.Repo.Repository.Owner
  547. ctx.Data["Units"] = models.Units
  548. ctx.HTML(200, tplCollaboration)
  549. }
  550. // CollaborationPost response for actions for a collaboration of a repository
  551. func CollaborationPost(ctx *context.Context) {
  552. name := utils.RemoveUsernameParameterSuffix(strings.ToLower(ctx.Query("collaborator")))
  553. if len(name) == 0 || ctx.Repo.Owner.LowerName == name {
  554. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  555. return
  556. }
  557. u, err := models.GetUserByName(name)
  558. if err != nil {
  559. if models.IsErrUserNotExist(err) {
  560. ctx.Flash.Error(ctx.Tr("form.user_not_exist"))
  561. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  562. } else {
  563. ctx.ServerError("GetUserByName", err)
  564. }
  565. return
  566. }
  567. if !u.IsActive {
  568. ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_inactive_user"))
  569. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  570. return
  571. }
  572. // Organization is not allowed to be added as a collaborator.
  573. if u.IsOrganization() {
  574. ctx.Flash.Error(ctx.Tr("repo.settings.org_not_allowed_to_be_collaborator"))
  575. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  576. return
  577. }
  578. if got, err := ctx.Repo.Repository.IsCollaborator(u.ID); err == nil && got {
  579. ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_duplicate"))
  580. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  581. return
  582. }
  583. if err = ctx.Repo.Repository.AddCollaborator(u); err != nil {
  584. ctx.ServerError("AddCollaborator", err)
  585. return
  586. }
  587. if setting.Service.EnableNotifyMail {
  588. mailer.SendCollaboratorMail(u, ctx.User, ctx.Repo.Repository)
  589. }
  590. ctx.Flash.Success(ctx.Tr("repo.settings.add_collaborator_success"))
  591. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  592. }
  593. // ChangeCollaborationAccessMode response for changing access of a collaboration
  594. func ChangeCollaborationAccessMode(ctx *context.Context) {
  595. if err := ctx.Repo.Repository.ChangeCollaborationAccessMode(
  596. ctx.QueryInt64("uid"),
  597. models.AccessMode(ctx.QueryInt("mode"))); err != nil {
  598. log.Error("ChangeCollaborationAccessMode: %v", err)
  599. }
  600. }
  601. // DeleteCollaboration delete a collaboration for a repository
  602. func DeleteCollaboration(ctx *context.Context) {
  603. if err := ctx.Repo.Repository.DeleteCollaboration(ctx.QueryInt64("id")); err != nil {
  604. ctx.Flash.Error("DeleteCollaboration: " + err.Error())
  605. } else {
  606. ctx.Flash.Success(ctx.Tr("repo.settings.remove_collaborator_success"))
  607. }
  608. ctx.JSON(200, map[string]interface{}{
  609. "redirect": ctx.Repo.RepoLink + "/settings/collaboration",
  610. })
  611. }
  612. // AddTeamPost response for adding a team to a repository
  613. func AddTeamPost(ctx *context.Context) {
  614. if !ctx.Repo.Owner.RepoAdminChangeTeamAccess && !ctx.Repo.IsOwner() {
  615. ctx.Flash.Error(ctx.Tr("repo.settings.change_team_access_not_allowed"))
  616. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  617. return
  618. }
  619. name := utils.RemoveUsernameParameterSuffix(strings.ToLower(ctx.Query("team")))
  620. if len(name) == 0 {
  621. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  622. return
  623. }
  624. team, err := ctx.Repo.Owner.GetTeam(name)
  625. if err != nil {
  626. if models.IsErrTeamNotExist(err) {
  627. ctx.Flash.Error(ctx.Tr("form.team_not_exist"))
  628. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  629. } else {
  630. ctx.ServerError("GetTeam", err)
  631. }
  632. return
  633. }
  634. if team.OrgID != ctx.Repo.Repository.OwnerID {
  635. ctx.Flash.Error(ctx.Tr("repo.settings.team_not_in_organization"))
  636. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  637. return
  638. }
  639. if models.HasTeamRepo(ctx.Repo.Repository.OwnerID, team.ID, ctx.Repo.Repository.ID) {
  640. ctx.Flash.Error(ctx.Tr("repo.settings.add_team_duplicate"))
  641. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  642. return
  643. }
  644. if err = team.AddRepository(ctx.Repo.Repository); err != nil {
  645. ctx.ServerError("team.AddRepository", err)
  646. return
  647. }
  648. ctx.Flash.Success(ctx.Tr("repo.settings.add_team_success"))
  649. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  650. }
  651. // DeleteTeam response for deleting a team from a repository
  652. func DeleteTeam(ctx *context.Context) {
  653. if !ctx.Repo.Owner.RepoAdminChangeTeamAccess && !ctx.Repo.IsOwner() {
  654. ctx.Flash.Error(ctx.Tr("repo.settings.change_team_access_not_allowed"))
  655. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  656. return
  657. }
  658. team, err := models.GetTeamByID(ctx.QueryInt64("id"))
  659. if err != nil {
  660. ctx.ServerError("GetTeamByID", err)
  661. return
  662. }
  663. if err = team.RemoveRepository(ctx.Repo.Repository.ID); err != nil {
  664. ctx.ServerError("team.RemoveRepositorys", err)
  665. return
  666. }
  667. ctx.Flash.Success(ctx.Tr("repo.settings.remove_team_success"))
  668. ctx.JSON(200, map[string]interface{}{
  669. "redirect": ctx.Repo.RepoLink + "/settings/collaboration",
  670. })
  671. }
  672. // parseOwnerAndRepo get repos by owner
  673. func parseOwnerAndRepo(ctx *context.Context) (*models.User, *models.Repository) {
  674. owner, err := models.GetUserByName(ctx.Params(":username"))
  675. if err != nil {
  676. if models.IsErrUserNotExist(err) {
  677. ctx.NotFound("GetUserByName", err)
  678. } else {
  679. ctx.ServerError("GetUserByName", err)
  680. }
  681. return nil, nil
  682. }
  683. repo, err := models.GetRepositoryByName(owner.ID, ctx.Params(":reponame"))
  684. if err != nil {
  685. if models.IsErrRepoNotExist(err) {
  686. ctx.NotFound("GetRepositoryByName", err)
  687. } else {
  688. ctx.ServerError("GetRepositoryByName", err)
  689. }
  690. return nil, nil
  691. }
  692. return owner, repo
  693. }
  694. // GitHooks hooks of a repository
  695. func GitHooks(ctx *context.Context) {
  696. ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
  697. ctx.Data["PageIsSettingsGitHooks"] = true
  698. hooks, err := ctx.Repo.GitRepo.Hooks()
  699. if err != nil {
  700. ctx.ServerError("Hooks", err)
  701. return
  702. }
  703. ctx.Data["Hooks"] = hooks
  704. ctx.HTML(200, tplGithooks)
  705. }
  706. // GitHooksEdit render for editing a hook of repository page
  707. func GitHooksEdit(ctx *context.Context) {
  708. ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
  709. ctx.Data["PageIsSettingsGitHooks"] = true
  710. name := ctx.Params(":name")
  711. hook, err := ctx.Repo.GitRepo.GetHook(name)
  712. if err != nil {
  713. if err == git.ErrNotValidHook {
  714. ctx.NotFound("GetHook", err)
  715. } else {
  716. ctx.ServerError("GetHook", err)
  717. }
  718. return
  719. }
  720. ctx.Data["Hook"] = hook
  721. ctx.HTML(200, tplGithookEdit)
  722. }
  723. // GitHooksEditPost response for editing a git hook of a repository
  724. func GitHooksEditPost(ctx *context.Context) {
  725. name := ctx.Params(":name")
  726. hook, err := ctx.Repo.GitRepo.GetHook(name)
  727. if err != nil {
  728. if err == git.ErrNotValidHook {
  729. ctx.NotFound("GetHook", err)
  730. } else {
  731. ctx.ServerError("GetHook", err)
  732. }
  733. return
  734. }
  735. hook.Content = ctx.Query("content")
  736. if err = hook.Update(); err != nil {
  737. ctx.ServerError("hook.Update", err)
  738. return
  739. }
  740. ctx.Redirect(ctx.Repo.RepoLink + "/settings/hooks/git")
  741. }
  742. // DeployKeys render the deploy keys list of a repository page
  743. func DeployKeys(ctx *context.Context) {
  744. ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
  745. ctx.Data["PageIsSettingsKeys"] = true
  746. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  747. keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID, models.ListOptions{})
  748. if err != nil {
  749. ctx.ServerError("ListDeployKeys", err)
  750. return
  751. }
  752. ctx.Data["Deploykeys"] = keys
  753. ctx.HTML(200, tplDeployKeys)
  754. }
  755. // DeployKeysPost response for adding a deploy key of a repository
  756. func DeployKeysPost(ctx *context.Context) {
  757. form := web.GetForm(ctx).(*auth.AddKeyForm)
  758. ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
  759. ctx.Data["PageIsSettingsKeys"] = true
  760. keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID, models.ListOptions{})
  761. if err != nil {
  762. ctx.ServerError("ListDeployKeys", err)
  763. return
  764. }
  765. ctx.Data["Deploykeys"] = keys
  766. if ctx.HasError() {
  767. ctx.HTML(200, tplDeployKeys)
  768. return
  769. }
  770. content, err := models.CheckPublicKeyString(form.Content)
  771. if err != nil {
  772. if models.IsErrSSHDisabled(err) {
  773. ctx.Flash.Info(ctx.Tr("settings.ssh_disabled"))
  774. } else if models.IsErrKeyUnableVerify(err) {
  775. ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key"))
  776. } else {
  777. ctx.Data["HasError"] = true
  778. ctx.Data["Err_Content"] = true
  779. ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error()))
  780. }
  781. ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
  782. return
  783. }
  784. key, err := models.AddDeployKey(ctx.Repo.Repository.ID, form.Title, content, !form.IsWritable)
  785. if err != nil {
  786. ctx.Data["HasError"] = true
  787. switch {
  788. case models.IsErrDeployKeyAlreadyExist(err):
  789. ctx.Data["Err_Content"] = true
  790. ctx.RenderWithErr(ctx.Tr("repo.settings.key_been_used"), tplDeployKeys, &form)
  791. case models.IsErrKeyAlreadyExist(err):
  792. ctx.Data["Err_Content"] = true
  793. ctx.RenderWithErr(ctx.Tr("settings.ssh_key_been_used"), tplDeployKeys, &form)
  794. case models.IsErrKeyNameAlreadyUsed(err):
  795. ctx.Data["Err_Title"] = true
  796. ctx.RenderWithErr(ctx.Tr("repo.settings.key_name_used"), tplDeployKeys, &form)
  797. case models.IsErrDeployKeyNameAlreadyUsed(err):
  798. ctx.Data["Err_Title"] = true
  799. ctx.RenderWithErr(ctx.Tr("repo.settings.key_name_used"), tplDeployKeys, &form)
  800. default:
  801. ctx.ServerError("AddDeployKey", err)
  802. }
  803. return
  804. }
  805. log.Trace("Deploy key added: %d", ctx.Repo.Repository.ID)
  806. ctx.Flash.Success(ctx.Tr("repo.settings.add_key_success", key.Name))
  807. ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
  808. }
  809. // DeleteDeployKey response for deleting a deploy key
  810. func DeleteDeployKey(ctx *context.Context) {
  811. if err := models.DeleteDeployKey(ctx.User, ctx.QueryInt64("id")); err != nil {
  812. ctx.Flash.Error("DeleteDeployKey: " + err.Error())
  813. } else {
  814. ctx.Flash.Success(ctx.Tr("repo.settings.deploy_key_deletion_success"))
  815. }
  816. ctx.JSON(200, map[string]interface{}{
  817. "redirect": ctx.Repo.RepoLink + "/settings/keys",
  818. })
  819. }
  820. func init() {
  821. var err error
  822. validFormAddress, err = xurls.StrictMatchingScheme(`(https?)|(git)://`)
  823. if err != nil {
  824. panic(err)
  825. }
  826. }
  827. // UpdateAvatarSetting update repo's avatar
  828. func UpdateAvatarSetting(ctx *context.Context, form auth.AvatarForm) error {
  829. ctxRepo := ctx.Repo.Repository
  830. if form.Avatar == nil {
  831. // No avatar is uploaded and we not removing it here.
  832. // No random avatar generated here.
  833. // Just exit, no action.
  834. if ctxRepo.CustomAvatarRelativePath() == "" {
  835. log.Trace("No avatar was uploaded for repo: %d. Default icon will appear instead.", ctxRepo.ID)
  836. }
  837. return nil
  838. }
  839. r, err := form.Avatar.Open()
  840. if err != nil {
  841. return fmt.Errorf("Avatar.Open: %v", err)
  842. }
  843. defer r.Close()
  844. if form.Avatar.Size > setting.Avatar.MaxFileSize {
  845. return errors.New(ctx.Tr("settings.uploaded_avatar_is_too_big"))
  846. }
  847. data, err := ioutil.ReadAll(r)
  848. if err != nil {
  849. return fmt.Errorf("ioutil.ReadAll: %v", err)
  850. }
  851. if !base.IsImageFile(data) {
  852. return errors.New(ctx.Tr("settings.uploaded_avatar_not_a_image"))
  853. }
  854. if err = ctxRepo.UploadAvatar(data); err != nil {
  855. return fmt.Errorf("UploadAvatar: %v", err)
  856. }
  857. return nil
  858. }
  859. // SettingsAvatar save new POSTed repository avatar
  860. func SettingsAvatar(ctx *context.Context) {
  861. form := web.GetForm(ctx).(*auth.AvatarForm)
  862. form.Source = auth.AvatarLocal
  863. if err := UpdateAvatarSetting(ctx, *form); err != nil {
  864. ctx.Flash.Error(err.Error())
  865. } else {
  866. ctx.Flash.Success(ctx.Tr("repo.settings.update_avatar_success"))
  867. }
  868. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  869. }
  870. // SettingsDeleteAvatar delete repository avatar
  871. func SettingsDeleteAvatar(ctx *context.Context) {
  872. if err := ctx.Repo.Repository.DeleteAvatar(); err != nil {
  873. ctx.Flash.Error(fmt.Sprintf("DeleteAvatar: %v", err))
  874. }
  875. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  876. }