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