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