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