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 26 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
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>
6 years ago
10 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
8 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
8 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
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
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
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  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/auth"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/context"
  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/timeutil"
  23. "code.gitea.io/gitea/modules/validation"
  24. "code.gitea.io/gitea/routers/utils"
  25. "code.gitea.io/gitea/services/mailer"
  26. mirror_service "code.gitea.io/gitea/services/mirror"
  27. repo_service "code.gitea.io/gitea/services/repository"
  28. "github.com/unknwon/com"
  29. "mvdan.cc/xurls/v2"
  30. )
  31. const (
  32. tplSettingsOptions base.TplName = "repo/settings/options"
  33. tplCollaboration base.TplName = "repo/settings/collaboration"
  34. tplBranches base.TplName = "repo/settings/branches"
  35. tplGithooks base.TplName = "repo/settings/githooks"
  36. tplGithookEdit base.TplName = "repo/settings/githook_edit"
  37. tplDeployKeys base.TplName = "repo/settings/deploy_keys"
  38. tplProtectedBranch base.TplName = "repo/settings/protected_branch"
  39. )
  40. var validFormAddress *regexp.Regexp
  41. // Settings show a repository's settings page
  42. func Settings(ctx *context.Context) {
  43. ctx.Data["Title"] = ctx.Tr("repo.settings")
  44. ctx.Data["PageIsSettingsOptions"] = true
  45. ctx.Data["ForcePrivate"] = setting.Repository.ForcePrivate
  46. ctx.HTML(200, tplSettingsOptions)
  47. }
  48. // SettingsPost response for changes of a repository
  49. func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
  50. ctx.Data["Title"] = ctx.Tr("repo.settings")
  51. ctx.Data["PageIsSettingsOptions"] = true
  52. repo := ctx.Repo.Repository
  53. switch ctx.Query("action") {
  54. case "update":
  55. if ctx.HasError() {
  56. ctx.HTML(200, tplSettingsOptions)
  57. return
  58. }
  59. newRepoName := form.RepoName
  60. // Check if repository name has been changed.
  61. if repo.LowerName != strings.ToLower(newRepoName) {
  62. // Close the GitRepo if open
  63. if ctx.Repo.GitRepo != nil {
  64. ctx.Repo.GitRepo.Close()
  65. ctx.Repo.GitRepo = nil
  66. }
  67. if err := repo_service.ChangeRepositoryName(ctx.Repo.Owner, repo, newRepoName); err != nil {
  68. ctx.Data["Err_RepoName"] = true
  69. switch {
  70. case models.IsErrRepoAlreadyExist(err):
  71. ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tplSettingsOptions, &form)
  72. case models.IsErrNameReserved(err):
  73. ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tplSettingsOptions, &form)
  74. case models.IsErrNamePatternNotAllowed(err):
  75. ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSettingsOptions, &form)
  76. default:
  77. ctx.ServerError("ChangeRepositoryName", err)
  78. }
  79. return
  80. }
  81. log.Trace("Repository name changed: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newRepoName)
  82. }
  83. // In case it's just a case change.
  84. repo.Name = newRepoName
  85. repo.LowerName = strings.ToLower(newRepoName)
  86. repo.Description = form.Description
  87. repo.Website = form.Website
  88. repo.IsTemplate = form.Template
  89. // Visibility of forked repository is forced sync with base repository.
  90. if repo.IsFork {
  91. form.Private = repo.BaseRepo.IsPrivate
  92. }
  93. visibilityChanged := repo.IsPrivate != form.Private
  94. // when ForcePrivate enabled, you could change public repo to private, but only admin users can change private to public
  95. if visibilityChanged && setting.Repository.ForcePrivate && !form.Private && !ctx.User.IsAdmin {
  96. ctx.ServerError("Force Private enabled", errors.New("cannot change private repository to public"))
  97. return
  98. }
  99. repo.IsPrivate = form.Private
  100. if err := models.UpdateRepository(repo, visibilityChanged); err != nil {
  101. ctx.ServerError("UpdateRepository", err)
  102. return
  103. }
  104. log.Trace("Repository basic settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  105. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  106. ctx.Redirect(repo.Link() + "/settings")
  107. case "mirror":
  108. if !repo.IsMirror {
  109. ctx.NotFound("", nil)
  110. return
  111. }
  112. // This section doesn't require repo_name/RepoName to be set in the form, don't show it
  113. // as an error on the UI for this action
  114. ctx.Data["Err_RepoName"] = nil
  115. interval, err := time.ParseDuration(form.Interval)
  116. if err != nil || (interval != 0 && interval < setting.Mirror.MinInterval) {
  117. ctx.Data["Err_Interval"] = true
  118. ctx.RenderWithErr(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
  119. } else {
  120. ctx.Repo.Mirror.EnablePrune = form.EnablePrune
  121. ctx.Repo.Mirror.Interval = interval
  122. if interval != 0 {
  123. ctx.Repo.Mirror.NextUpdateUnix = timeutil.TimeStampNow().AddDuration(interval)
  124. } else {
  125. ctx.Repo.Mirror.NextUpdateUnix = 0
  126. }
  127. if err := models.UpdateMirror(ctx.Repo.Mirror); err != nil {
  128. ctx.Data["Err_Interval"] = true
  129. ctx.RenderWithErr(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
  130. return
  131. }
  132. }
  133. // Validate the form.MirrorAddress
  134. u, err := url.Parse(form.MirrorAddress)
  135. if err != nil {
  136. ctx.Data["Err_MirrorAddress"] = true
  137. ctx.RenderWithErr(ctx.Tr("repo.mirror_address_url_invalid"), tplSettingsOptions, &form)
  138. return
  139. }
  140. if u.Opaque != "" || !(u.Scheme == "http" || u.Scheme == "https" || u.Scheme == "git") {
  141. ctx.Data["Err_MirrorAddress"] = true
  142. ctx.RenderWithErr(ctx.Tr("repo.mirror_address_protocol_invalid"), tplSettingsOptions, &form)
  143. return
  144. }
  145. if form.MirrorUsername != "" || form.MirrorPassword != "" {
  146. u.User = url.UserPassword(form.MirrorUsername, form.MirrorPassword)
  147. }
  148. // Now use xurls
  149. address := validFormAddress.FindString(form.MirrorAddress)
  150. if address != form.MirrorAddress && form.MirrorAddress != "" {
  151. ctx.Data["Err_MirrorAddress"] = true
  152. ctx.RenderWithErr(ctx.Tr("repo.mirror_address_url_invalid"), tplSettingsOptions, &form)
  153. return
  154. }
  155. if u.EscapedPath() == "" || u.Host == "" || !u.IsAbs() {
  156. ctx.Data["Err_MirrorAddress"] = true
  157. ctx.RenderWithErr(ctx.Tr("repo.mirror_address_url_invalid"), tplSettingsOptions, &form)
  158. return
  159. }
  160. address = u.String()
  161. if err := mirror_service.SaveAddress(ctx.Repo.Mirror, address); err != nil {
  162. ctx.ServerError("SaveAddress", err)
  163. return
  164. }
  165. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  166. ctx.Redirect(repo.Link() + "/settings")
  167. case "mirror-sync":
  168. if !repo.IsMirror {
  169. ctx.NotFound("", nil)
  170. return
  171. }
  172. mirror_service.StartToMirror(repo.ID)
  173. ctx.Flash.Info(ctx.Tr("repo.settings.mirror_sync_in_progress"))
  174. ctx.Redirect(repo.Link() + "/settings")
  175. case "advanced":
  176. var units []models.RepoUnit
  177. // This section doesn't require repo_name/RepoName to be set in the form, don't show it
  178. // as an error on the UI for this action
  179. ctx.Data["Err_RepoName"] = nil
  180. for _, tp := range models.MustRepoUnits {
  181. units = append(units, models.RepoUnit{
  182. RepoID: repo.ID,
  183. Type: tp,
  184. Config: new(models.UnitConfig),
  185. })
  186. }
  187. if form.EnableWiki {
  188. if form.EnableExternalWiki {
  189. if !validation.IsValidExternalURL(form.ExternalWikiURL) {
  190. ctx.Flash.Error(ctx.Tr("repo.settings.external_wiki_url_error"))
  191. ctx.Redirect(repo.Link() + "/settings")
  192. return
  193. }
  194. units = append(units, models.RepoUnit{
  195. RepoID: repo.ID,
  196. Type: models.UnitTypeExternalWiki,
  197. Config: &models.ExternalWikiConfig{
  198. ExternalWikiURL: form.ExternalWikiURL,
  199. },
  200. })
  201. } else {
  202. units = append(units, models.RepoUnit{
  203. RepoID: repo.ID,
  204. Type: models.UnitTypeWiki,
  205. Config: new(models.UnitConfig),
  206. })
  207. }
  208. }
  209. if form.EnableIssues {
  210. if form.EnableExternalTracker {
  211. if !validation.IsValidExternalURL(form.ExternalTrackerURL) {
  212. ctx.Flash.Error(ctx.Tr("repo.settings.external_tracker_url_error"))
  213. ctx.Redirect(repo.Link() + "/settings")
  214. return
  215. }
  216. if len(form.TrackerURLFormat) != 0 && !validation.IsValidExternalTrackerURLFormat(form.TrackerURLFormat) {
  217. ctx.Flash.Error(ctx.Tr("repo.settings.tracker_url_format_error"))
  218. ctx.Redirect(repo.Link() + "/settings")
  219. return
  220. }
  221. units = append(units, models.RepoUnit{
  222. RepoID: repo.ID,
  223. Type: models.UnitTypeExternalTracker,
  224. Config: &models.ExternalTrackerConfig{
  225. ExternalTrackerURL: form.ExternalTrackerURL,
  226. ExternalTrackerFormat: form.TrackerURLFormat,
  227. ExternalTrackerStyle: form.TrackerIssueStyle,
  228. },
  229. })
  230. } else {
  231. units = append(units, models.RepoUnit{
  232. RepoID: repo.ID,
  233. Type: models.UnitTypeIssues,
  234. Config: &models.IssuesConfig{
  235. EnableTimetracker: form.EnableTimetracker,
  236. AllowOnlyContributorsToTrackTime: form.AllowOnlyContributorsToTrackTime,
  237. EnableDependencies: form.EnableIssueDependencies,
  238. },
  239. })
  240. }
  241. }
  242. if form.EnablePulls {
  243. units = append(units, models.RepoUnit{
  244. RepoID: repo.ID,
  245. Type: models.UnitTypePullRequests,
  246. Config: &models.PullRequestsConfig{
  247. IgnoreWhitespaceConflicts: form.PullsIgnoreWhitespace,
  248. AllowMerge: form.PullsAllowMerge,
  249. AllowRebase: form.PullsAllowRebase,
  250. AllowRebaseMerge: form.PullsAllowRebaseMerge,
  251. AllowSquash: form.PullsAllowSquash,
  252. },
  253. })
  254. }
  255. if err := models.UpdateRepositoryUnits(repo, units); err != nil {
  256. ctx.ServerError("UpdateRepositoryUnits", err)
  257. return
  258. }
  259. log.Trace("Repository advanced settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  260. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  261. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  262. case "admin":
  263. if !ctx.User.IsAdmin {
  264. ctx.Error(403)
  265. return
  266. }
  267. if repo.IsFsckEnabled != form.EnableHealthCheck {
  268. repo.IsFsckEnabled = form.EnableHealthCheck
  269. }
  270. if repo.CloseIssuesViaCommitInAnyBranch != form.EnableCloseIssuesViaCommitInAnyBranch {
  271. repo.CloseIssuesViaCommitInAnyBranch = form.EnableCloseIssuesViaCommitInAnyBranch
  272. }
  273. if err := models.UpdateRepository(repo, false); err != nil {
  274. ctx.ServerError("UpdateRepository", err)
  275. return
  276. }
  277. log.Trace("Repository admin settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  278. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  279. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  280. case "convert":
  281. if !ctx.Repo.IsOwner() {
  282. ctx.Error(404)
  283. return
  284. }
  285. if repo.Name != form.RepoName {
  286. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  287. return
  288. }
  289. if !repo.IsMirror {
  290. ctx.Error(404)
  291. return
  292. }
  293. repo.IsMirror = false
  294. if _, err := repository.CleanUpMigrateInfo(repo); err != nil {
  295. ctx.ServerError("CleanUpMigrateInfo", err)
  296. return
  297. } else if err = models.DeleteMirrorByRepoID(ctx.Repo.Repository.ID); err != nil {
  298. ctx.ServerError("DeleteMirrorByRepoID", err)
  299. return
  300. }
  301. log.Trace("Repository converted from mirror to regular: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  302. ctx.Flash.Success(ctx.Tr("repo.settings.convert_succeed"))
  303. ctx.Redirect(setting.AppSubURL + "/" + ctx.Repo.Owner.Name + "/" + repo.Name)
  304. case "transfer":
  305. if !ctx.Repo.IsOwner() {
  306. ctx.Error(404)
  307. return
  308. }
  309. if repo.Name != form.RepoName {
  310. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  311. return
  312. }
  313. newOwner := ctx.Query("new_owner_name")
  314. isExist, err := models.IsUserExist(0, newOwner)
  315. if err != nil {
  316. ctx.ServerError("IsUserExist", err)
  317. return
  318. } else if !isExist {
  319. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_owner_name"), tplSettingsOptions, nil)
  320. return
  321. }
  322. // Close the GitRepo if open
  323. if ctx.Repo.GitRepo != nil {
  324. ctx.Repo.GitRepo.Close()
  325. ctx.Repo.GitRepo = nil
  326. }
  327. if err = repo_service.TransferOwnership(ctx.User, newOwner, repo); err != nil {
  328. if models.IsErrRepoAlreadyExist(err) {
  329. ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplSettingsOptions, nil)
  330. } else {
  331. ctx.ServerError("TransferOwnership", err)
  332. }
  333. return
  334. }
  335. log.Trace("Repository transferred: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newOwner)
  336. ctx.Flash.Success(ctx.Tr("repo.settings.transfer_succeed"))
  337. ctx.Redirect(setting.AppSubURL + "/" + newOwner + "/" + repo.Name)
  338. case "delete":
  339. if !ctx.Repo.IsOwner() {
  340. ctx.Error(404)
  341. return
  342. }
  343. if repo.Name != form.RepoName {
  344. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  345. return
  346. }
  347. if err := repo_service.DeleteRepository(ctx.User, ctx.Repo.Repository); err != nil {
  348. ctx.ServerError("DeleteRepository", err)
  349. return
  350. }
  351. log.Trace("Repository deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  352. ctx.Flash.Success(ctx.Tr("repo.settings.deletion_success"))
  353. ctx.Redirect(ctx.Repo.Owner.DashboardLink())
  354. case "delete-wiki":
  355. if !ctx.Repo.IsOwner() {
  356. ctx.Error(404)
  357. return
  358. }
  359. if repo.Name != form.RepoName {
  360. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  361. return
  362. }
  363. err := repo.DeleteWiki()
  364. if err != nil {
  365. log.Error("Delete Wiki: %v", err.Error())
  366. }
  367. log.Trace("Repository wiki deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  368. ctx.Flash.Success(ctx.Tr("repo.settings.wiki_deletion_success"))
  369. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  370. case "archive":
  371. if !ctx.Repo.IsOwner() {
  372. ctx.Error(403)
  373. return
  374. }
  375. if repo.IsMirror {
  376. ctx.Flash.Error(ctx.Tr("repo.settings.archive.error_ismirror"))
  377. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  378. return
  379. }
  380. if err := repo.SetArchiveRepoState(true); err != nil {
  381. log.Error("Tried to archive a repo: %s", err)
  382. ctx.Flash.Error(ctx.Tr("repo.settings.archive.error"))
  383. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  384. return
  385. }
  386. ctx.Flash.Success(ctx.Tr("repo.settings.archive.success"))
  387. log.Trace("Repository was archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  388. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  389. case "unarchive":
  390. if !ctx.Repo.IsOwner() {
  391. ctx.Error(403)
  392. return
  393. }
  394. if err := repo.SetArchiveRepoState(false); err != nil {
  395. log.Error("Tried to unarchive a repo: %s", err)
  396. ctx.Flash.Error(ctx.Tr("repo.settings.unarchive.error"))
  397. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  398. return
  399. }
  400. ctx.Flash.Success(ctx.Tr("repo.settings.unarchive.success"))
  401. log.Trace("Repository was un-archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  402. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  403. default:
  404. ctx.NotFound("", nil)
  405. }
  406. }
  407. // Collaboration render a repository's collaboration page
  408. func Collaboration(ctx *context.Context) {
  409. ctx.Data["Title"] = ctx.Tr("repo.settings")
  410. ctx.Data["PageIsSettingsCollaboration"] = true
  411. users, err := ctx.Repo.Repository.GetCollaborators()
  412. if err != nil {
  413. ctx.ServerError("GetCollaborators", err)
  414. return
  415. }
  416. ctx.Data["Collaborators"] = users
  417. teams, err := ctx.Repo.Repository.GetRepoTeams()
  418. if err != nil {
  419. ctx.ServerError("GetRepoTeams", err)
  420. return
  421. }
  422. ctx.Data["Teams"] = teams
  423. ctx.Data["Repo"] = ctx.Repo.Repository
  424. ctx.Data["OrgID"] = ctx.Repo.Repository.OwnerID
  425. ctx.Data["OrgName"] = ctx.Repo.Repository.OwnerName
  426. ctx.Data["Org"] = ctx.Repo.Repository.Owner
  427. ctx.Data["Units"] = models.Units
  428. ctx.HTML(200, tplCollaboration)
  429. }
  430. // CollaborationPost response for actions for a collaboration of a repository
  431. func CollaborationPost(ctx *context.Context) {
  432. name := utils.RemoveUsernameParameterSuffix(strings.ToLower(ctx.Query("collaborator")))
  433. if len(name) == 0 || ctx.Repo.Owner.LowerName == name {
  434. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  435. return
  436. }
  437. u, err := models.GetUserByName(name)
  438. if err != nil {
  439. if models.IsErrUserNotExist(err) {
  440. ctx.Flash.Error(ctx.Tr("form.user_not_exist"))
  441. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  442. } else {
  443. ctx.ServerError("GetUserByName", err)
  444. }
  445. return
  446. }
  447. if !u.IsActive {
  448. ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_inactive_user"))
  449. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  450. return
  451. }
  452. // Organization is not allowed to be added as a collaborator.
  453. if u.IsOrganization() {
  454. ctx.Flash.Error(ctx.Tr("repo.settings.org_not_allowed_to_be_collaborator"))
  455. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  456. return
  457. }
  458. if got, err := ctx.Repo.Repository.IsCollaborator(u.ID); err == nil && got {
  459. ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_duplicate"))
  460. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  461. return
  462. }
  463. if err = ctx.Repo.Repository.AddCollaborator(u); err != nil {
  464. ctx.ServerError("AddCollaborator", err)
  465. return
  466. }
  467. if setting.Service.EnableNotifyMail {
  468. mailer.SendCollaboratorMail(u, ctx.User, ctx.Repo.Repository)
  469. }
  470. ctx.Flash.Success(ctx.Tr("repo.settings.add_collaborator_success"))
  471. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  472. }
  473. // ChangeCollaborationAccessMode response for changing access of a collaboration
  474. func ChangeCollaborationAccessMode(ctx *context.Context) {
  475. if err := ctx.Repo.Repository.ChangeCollaborationAccessMode(
  476. ctx.QueryInt64("uid"),
  477. models.AccessMode(ctx.QueryInt("mode"))); err != nil {
  478. log.Error("ChangeCollaborationAccessMode: %v", err)
  479. }
  480. }
  481. // DeleteCollaboration delete a collaboration for a repository
  482. func DeleteCollaboration(ctx *context.Context) {
  483. if err := ctx.Repo.Repository.DeleteCollaboration(ctx.QueryInt64("id")); err != nil {
  484. ctx.Flash.Error("DeleteCollaboration: " + err.Error())
  485. } else {
  486. ctx.Flash.Success(ctx.Tr("repo.settings.remove_collaborator_success"))
  487. }
  488. ctx.JSON(200, map[string]interface{}{
  489. "redirect": ctx.Repo.RepoLink + "/settings/collaboration",
  490. })
  491. }
  492. // AddTeamPost response for adding a team to a repository
  493. func AddTeamPost(ctx *context.Context) {
  494. if !ctx.Repo.Owner.RepoAdminChangeTeamAccess && !ctx.Repo.IsOwner() {
  495. ctx.Flash.Error(ctx.Tr("repo.settings.change_team_access_not_allowed"))
  496. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  497. return
  498. }
  499. name := utils.RemoveUsernameParameterSuffix(strings.ToLower(ctx.Query("team")))
  500. if len(name) == 0 || ctx.Repo.Owner.LowerName == name {
  501. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  502. return
  503. }
  504. team, err := ctx.Repo.Owner.GetTeam(name)
  505. if err != nil {
  506. if models.IsErrTeamNotExist(err) {
  507. ctx.Flash.Error(ctx.Tr("form.team_not_exist"))
  508. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  509. } else {
  510. ctx.ServerError("GetTeam", err)
  511. }
  512. return
  513. }
  514. if team.OrgID != ctx.Repo.Repository.OwnerID {
  515. ctx.Flash.Error(ctx.Tr("repo.settings.team_not_in_organization"))
  516. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  517. return
  518. }
  519. if models.HasTeamRepo(ctx.Repo.Repository.OwnerID, team.ID, ctx.Repo.Repository.ID) {
  520. ctx.Flash.Error(ctx.Tr("repo.settings.add_team_duplicate"))
  521. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  522. return
  523. }
  524. if err = team.AddRepository(ctx.Repo.Repository); err != nil {
  525. ctx.ServerError("team.AddRepository", err)
  526. return
  527. }
  528. ctx.Flash.Success(ctx.Tr("repo.settings.add_team_success"))
  529. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  530. }
  531. // DeleteTeam response for deleting a team from a repository
  532. func DeleteTeam(ctx *context.Context) {
  533. if !ctx.Repo.Owner.RepoAdminChangeTeamAccess && !ctx.Repo.IsOwner() {
  534. ctx.Flash.Error(ctx.Tr("repo.settings.change_team_access_not_allowed"))
  535. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  536. return
  537. }
  538. team, err := models.GetTeamByID(ctx.QueryInt64("id"))
  539. if err != nil {
  540. ctx.ServerError("GetTeamByID", err)
  541. return
  542. }
  543. if err = team.RemoveRepository(ctx.Repo.Repository.ID); err != nil {
  544. ctx.ServerError("team.RemoveRepositorys", err)
  545. return
  546. }
  547. ctx.Flash.Success(ctx.Tr("repo.settings.remove_team_success"))
  548. ctx.JSON(200, map[string]interface{}{
  549. "redirect": ctx.Repo.RepoLink + "/settings/collaboration",
  550. })
  551. }
  552. // parseOwnerAndRepo get repos by owner
  553. func parseOwnerAndRepo(ctx *context.Context) (*models.User, *models.Repository) {
  554. owner, err := models.GetUserByName(ctx.Params(":username"))
  555. if err != nil {
  556. if models.IsErrUserNotExist(err) {
  557. ctx.NotFound("GetUserByName", err)
  558. } else {
  559. ctx.ServerError("GetUserByName", err)
  560. }
  561. return nil, nil
  562. }
  563. repo, err := models.GetRepositoryByName(owner.ID, ctx.Params(":reponame"))
  564. if err != nil {
  565. if models.IsErrRepoNotExist(err) {
  566. ctx.NotFound("GetRepositoryByName", err)
  567. } else {
  568. ctx.ServerError("GetRepositoryByName", err)
  569. }
  570. return nil, nil
  571. }
  572. return owner, repo
  573. }
  574. // GitHooks hooks of a repository
  575. func GitHooks(ctx *context.Context) {
  576. ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
  577. ctx.Data["PageIsSettingsGitHooks"] = true
  578. hooks, err := ctx.Repo.GitRepo.Hooks()
  579. if err != nil {
  580. ctx.ServerError("Hooks", err)
  581. return
  582. }
  583. ctx.Data["Hooks"] = hooks
  584. ctx.HTML(200, tplGithooks)
  585. }
  586. // GitHooksEdit render for editing a hook of repository page
  587. func GitHooksEdit(ctx *context.Context) {
  588. ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
  589. ctx.Data["PageIsSettingsGitHooks"] = true
  590. ctx.Data["RequireSimpleMDE"] = true
  591. name := ctx.Params(":name")
  592. hook, err := ctx.Repo.GitRepo.GetHook(name)
  593. if err != nil {
  594. if err == git.ErrNotValidHook {
  595. ctx.NotFound("GetHook", err)
  596. } else {
  597. ctx.ServerError("GetHook", err)
  598. }
  599. return
  600. }
  601. ctx.Data["Hook"] = hook
  602. ctx.HTML(200, tplGithookEdit)
  603. }
  604. // GitHooksEditPost response for editing a git hook of a repository
  605. func GitHooksEditPost(ctx *context.Context) {
  606. name := ctx.Params(":name")
  607. hook, err := ctx.Repo.GitRepo.GetHook(name)
  608. if err != nil {
  609. if err == git.ErrNotValidHook {
  610. ctx.NotFound("GetHook", err)
  611. } else {
  612. ctx.ServerError("GetHook", err)
  613. }
  614. return
  615. }
  616. hook.Content = ctx.Query("content")
  617. if err = hook.Update(); err != nil {
  618. ctx.ServerError("hook.Update", err)
  619. return
  620. }
  621. ctx.Redirect(ctx.Repo.RepoLink + "/settings/hooks/git")
  622. }
  623. // DeployKeys render the deploy keys list of a repository page
  624. func DeployKeys(ctx *context.Context) {
  625. ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
  626. ctx.Data["PageIsSettingsKeys"] = true
  627. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  628. keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID)
  629. if err != nil {
  630. ctx.ServerError("ListDeployKeys", err)
  631. return
  632. }
  633. ctx.Data["Deploykeys"] = keys
  634. ctx.HTML(200, tplDeployKeys)
  635. }
  636. // DeployKeysPost response for adding a deploy key of a repository
  637. func DeployKeysPost(ctx *context.Context, form auth.AddKeyForm) {
  638. ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
  639. ctx.Data["PageIsSettingsKeys"] = true
  640. keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID)
  641. if err != nil {
  642. ctx.ServerError("ListDeployKeys", err)
  643. return
  644. }
  645. ctx.Data["Deploykeys"] = keys
  646. if ctx.HasError() {
  647. ctx.HTML(200, tplDeployKeys)
  648. return
  649. }
  650. content, err := models.CheckPublicKeyString(form.Content)
  651. if err != nil {
  652. if models.IsErrSSHDisabled(err) {
  653. ctx.Flash.Info(ctx.Tr("settings.ssh_disabled"))
  654. } else if models.IsErrKeyUnableVerify(err) {
  655. ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key"))
  656. } else {
  657. ctx.Data["HasError"] = true
  658. ctx.Data["Err_Content"] = true
  659. ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error()))
  660. }
  661. ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
  662. return
  663. }
  664. key, err := models.AddDeployKey(ctx.Repo.Repository.ID, form.Title, content, !form.IsWritable)
  665. if err != nil {
  666. ctx.Data["HasError"] = true
  667. switch {
  668. case models.IsErrDeployKeyAlreadyExist(err):
  669. ctx.Data["Err_Content"] = true
  670. ctx.RenderWithErr(ctx.Tr("repo.settings.key_been_used"), tplDeployKeys, &form)
  671. case models.IsErrKeyAlreadyExist(err):
  672. ctx.Data["Err_Content"] = true
  673. ctx.RenderWithErr(ctx.Tr("settings.ssh_key_been_used"), tplDeployKeys, &form)
  674. case models.IsErrKeyNameAlreadyUsed(err):
  675. ctx.Data["Err_Title"] = true
  676. ctx.RenderWithErr(ctx.Tr("repo.settings.key_name_used"), tplDeployKeys, &form)
  677. default:
  678. ctx.ServerError("AddDeployKey", err)
  679. }
  680. return
  681. }
  682. log.Trace("Deploy key added: %d", ctx.Repo.Repository.ID)
  683. ctx.Flash.Success(ctx.Tr("repo.settings.add_key_success", key.Name))
  684. ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
  685. }
  686. // DeleteDeployKey response for deleting a deploy key
  687. func DeleteDeployKey(ctx *context.Context) {
  688. if err := models.DeleteDeployKey(ctx.User, ctx.QueryInt64("id")); err != nil {
  689. ctx.Flash.Error("DeleteDeployKey: " + err.Error())
  690. } else {
  691. ctx.Flash.Success(ctx.Tr("repo.settings.deploy_key_deletion_success"))
  692. }
  693. ctx.JSON(200, map[string]interface{}{
  694. "redirect": ctx.Repo.RepoLink + "/settings/keys",
  695. })
  696. }
  697. func init() {
  698. var err error
  699. validFormAddress, err = xurls.StrictMatchingScheme(`(https?)|(git)://`)
  700. if err != nil {
  701. panic(err)
  702. }
  703. }
  704. // UpdateAvatarSetting update repo's avatar
  705. func UpdateAvatarSetting(ctx *context.Context, form auth.AvatarForm) error {
  706. ctxRepo := ctx.Repo.Repository
  707. if form.Avatar == nil {
  708. // No avatar is uploaded and we not removing it here.
  709. // No random avatar generated here.
  710. // Just exit, no action.
  711. if !com.IsFile(ctxRepo.CustomAvatarPath()) {
  712. log.Trace("No avatar was uploaded for repo: %d. Default icon will appear instead.", ctxRepo.ID)
  713. }
  714. return nil
  715. }
  716. r, err := form.Avatar.Open()
  717. if err != nil {
  718. return fmt.Errorf("Avatar.Open: %v", err)
  719. }
  720. defer r.Close()
  721. if form.Avatar.Size > setting.AvatarMaxFileSize {
  722. return errors.New(ctx.Tr("settings.uploaded_avatar_is_too_big"))
  723. }
  724. data, err := ioutil.ReadAll(r)
  725. if err != nil {
  726. return fmt.Errorf("ioutil.ReadAll: %v", err)
  727. }
  728. if !base.IsImageFile(data) {
  729. return errors.New(ctx.Tr("settings.uploaded_avatar_not_a_image"))
  730. }
  731. if err = ctxRepo.UploadAvatar(data); err != nil {
  732. return fmt.Errorf("UploadAvatar: %v", err)
  733. }
  734. return nil
  735. }
  736. // SettingsAvatar save new POSTed repository avatar
  737. func SettingsAvatar(ctx *context.Context, form auth.AvatarForm) {
  738. form.Source = auth.AvatarLocal
  739. if err := UpdateAvatarSetting(ctx, form); err != nil {
  740. ctx.Flash.Error(err.Error())
  741. } else {
  742. ctx.Flash.Success(ctx.Tr("repo.settings.update_avatar_success"))
  743. }
  744. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  745. }
  746. // SettingsDeleteAvatar delete repository avatar
  747. func SettingsDeleteAvatar(ctx *context.Context) {
  748. if err := ctx.Repo.Repository.DeleteAvatar(); err != nil {
  749. ctx.Flash.Error(fmt.Sprintf("DeleteAvatar: %v", err))
  750. }
  751. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  752. }