You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

882 lines
27 KiB

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