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.

684 lines
20 KiB

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
5 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
8 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
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
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
9 years ago
9 years ago
9 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. "strings"
  9. "time"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/auth"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/context"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/util"
  18. "code.gitea.io/gitea/modules/validation"
  19. "code.gitea.io/gitea/routers/utils"
  20. )
  21. const (
  22. tplSettingsOptions base.TplName = "repo/settings/options"
  23. tplCollaboration base.TplName = "repo/settings/collaboration"
  24. tplBranches base.TplName = "repo/settings/branches"
  25. tplGithooks base.TplName = "repo/settings/githooks"
  26. tplGithookEdit base.TplName = "repo/settings/githook_edit"
  27. tplDeployKeys base.TplName = "repo/settings/deploy_keys"
  28. tplProtectedBranch base.TplName = "repo/settings/protected_branch"
  29. )
  30. // Settings show a repository's settings page
  31. func Settings(ctx *context.Context) {
  32. ctx.Data["Title"] = ctx.Tr("repo.settings")
  33. ctx.Data["PageIsSettingsOptions"] = true
  34. ctx.Data["ForcePrivate"] = setting.Repository.ForcePrivate
  35. ctx.HTML(200, tplSettingsOptions)
  36. }
  37. // SettingsPost response for changes of a repository
  38. func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
  39. ctx.Data["Title"] = ctx.Tr("repo.settings")
  40. ctx.Data["PageIsSettingsOptions"] = true
  41. repo := ctx.Repo.Repository
  42. switch ctx.Query("action") {
  43. case "update":
  44. if ctx.HasError() {
  45. ctx.HTML(200, tplSettingsOptions)
  46. return
  47. }
  48. isNameChanged := false
  49. oldRepoName := repo.Name
  50. newRepoName := form.RepoName
  51. // Check if repository name has been changed.
  52. if repo.LowerName != strings.ToLower(newRepoName) {
  53. isNameChanged = true
  54. if err := models.ChangeRepositoryName(ctx.Repo.Owner, repo.Name, newRepoName); err != nil {
  55. ctx.Data["Err_RepoName"] = true
  56. switch {
  57. case models.IsErrRepoAlreadyExist(err):
  58. ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tplSettingsOptions, &form)
  59. case models.IsErrNameReserved(err):
  60. ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tplSettingsOptions, &form)
  61. case models.IsErrNamePatternNotAllowed(err):
  62. ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSettingsOptions, &form)
  63. default:
  64. ctx.ServerError("ChangeRepositoryName", err)
  65. }
  66. return
  67. }
  68. err := models.NewRepoRedirect(ctx.Repo.Owner.ID, repo.ID, repo.Name, newRepoName)
  69. if err != nil {
  70. ctx.ServerError("NewRepoRedirect", err)
  71. return
  72. }
  73. log.Trace("Repository name changed: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newRepoName)
  74. }
  75. // In case it's just a case change.
  76. repo.Name = newRepoName
  77. repo.LowerName = strings.ToLower(newRepoName)
  78. repo.Description = form.Description
  79. repo.Website = form.Website
  80. // Visibility of forked repository is forced sync with base repository.
  81. if repo.IsFork {
  82. form.Private = repo.BaseRepo.IsPrivate
  83. }
  84. visibilityChanged := repo.IsPrivate != form.Private
  85. // when ForcePrivate enabled, you could change public repo to private, but could not change private to public
  86. if visibilityChanged && setting.Repository.ForcePrivate && !form.Private {
  87. ctx.ServerError("Force Private enabled", errors.New("cannot change private repository to public"))
  88. return
  89. }
  90. repo.IsPrivate = form.Private
  91. if err := models.UpdateRepository(repo, visibilityChanged); err != nil {
  92. ctx.ServerError("UpdateRepository", err)
  93. return
  94. }
  95. log.Trace("Repository basic settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  96. if isNameChanged {
  97. if err := models.RenameRepoAction(ctx.User, oldRepoName, repo); err != nil {
  98. log.Error("RenameRepoAction: %v", err)
  99. }
  100. }
  101. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  102. ctx.Redirect(repo.Link() + "/settings")
  103. case "mirror":
  104. if !repo.IsMirror {
  105. ctx.NotFound("", nil)
  106. return
  107. }
  108. // This section doesn't require repo_name/RepoName to be set in the form, don't show it
  109. // as an error on the UI for this action
  110. ctx.Data["Err_RepoName"] = nil
  111. interval, err := time.ParseDuration(form.Interval)
  112. if err != nil || (interval != 0 && interval < setting.Mirror.MinInterval) {
  113. ctx.Data["Err_Interval"] = true
  114. ctx.RenderWithErr(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
  115. } else {
  116. ctx.Repo.Mirror.EnablePrune = form.EnablePrune
  117. ctx.Repo.Mirror.Interval = interval
  118. if interval != 0 {
  119. ctx.Repo.Mirror.NextUpdateUnix = util.TimeStampNow().AddDuration(interval)
  120. } else {
  121. ctx.Repo.Mirror.NextUpdateUnix = 0
  122. }
  123. if err := models.UpdateMirror(ctx.Repo.Mirror); err != nil {
  124. ctx.Data["Err_Interval"] = true
  125. ctx.RenderWithErr(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
  126. return
  127. }
  128. }
  129. if err := ctx.Repo.Mirror.SaveAddress(form.MirrorAddress); err != nil {
  130. ctx.ServerError("SaveAddress", err)
  131. return
  132. }
  133. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  134. ctx.Redirect(repo.Link() + "/settings")
  135. case "mirror-sync":
  136. if !repo.IsMirror {
  137. ctx.NotFound("", nil)
  138. return
  139. }
  140. go models.MirrorQueue.Add(repo.ID)
  141. ctx.Flash.Info(ctx.Tr("repo.settings.mirror_sync_in_progress"))
  142. ctx.Redirect(repo.Link() + "/settings")
  143. case "advanced":
  144. var units []models.RepoUnit
  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. for _, tp := range models.MustRepoUnits {
  149. units = append(units, models.RepoUnit{
  150. RepoID: repo.ID,
  151. Type: tp,
  152. Config: new(models.UnitConfig),
  153. })
  154. }
  155. if form.EnableWiki {
  156. if form.EnableExternalWiki {
  157. if !validation.IsValidExternalURL(form.ExternalWikiURL) {
  158. ctx.Flash.Error(ctx.Tr("repo.settings.external_wiki_url_error"))
  159. ctx.Redirect(repo.Link() + "/settings")
  160. return
  161. }
  162. units = append(units, models.RepoUnit{
  163. RepoID: repo.ID,
  164. Type: models.UnitTypeExternalWiki,
  165. Config: &models.ExternalWikiConfig{
  166. ExternalWikiURL: form.ExternalWikiURL,
  167. },
  168. })
  169. } else {
  170. units = append(units, models.RepoUnit{
  171. RepoID: repo.ID,
  172. Type: models.UnitTypeWiki,
  173. Config: new(models.UnitConfig),
  174. })
  175. }
  176. }
  177. if form.EnableIssues {
  178. if form.EnableExternalTracker {
  179. if !validation.IsValidExternalURL(form.ExternalTrackerURL) {
  180. ctx.Flash.Error(ctx.Tr("repo.settings.external_tracker_url_error"))
  181. ctx.Redirect(repo.Link() + "/settings")
  182. return
  183. }
  184. if len(form.TrackerURLFormat) != 0 && !validation.IsValidExternalURL(form.TrackerURLFormat) {
  185. ctx.Flash.Error(ctx.Tr("repo.settings.tracker_url_format_error"))
  186. ctx.Redirect(repo.Link() + "/settings")
  187. return
  188. }
  189. units = append(units, models.RepoUnit{
  190. RepoID: repo.ID,
  191. Type: models.UnitTypeExternalTracker,
  192. Config: &models.ExternalTrackerConfig{
  193. ExternalTrackerURL: form.ExternalTrackerURL,
  194. ExternalTrackerFormat: form.TrackerURLFormat,
  195. ExternalTrackerStyle: form.TrackerIssueStyle,
  196. },
  197. })
  198. } else {
  199. units = append(units, models.RepoUnit{
  200. RepoID: repo.ID,
  201. Type: models.UnitTypeIssues,
  202. Config: &models.IssuesConfig{
  203. EnableTimetracker: form.EnableTimetracker,
  204. AllowOnlyContributorsToTrackTime: form.AllowOnlyContributorsToTrackTime,
  205. EnableDependencies: form.EnableIssueDependencies,
  206. },
  207. })
  208. }
  209. }
  210. if form.EnablePulls {
  211. units = append(units, models.RepoUnit{
  212. RepoID: repo.ID,
  213. Type: models.UnitTypePullRequests,
  214. Config: &models.PullRequestsConfig{
  215. IgnoreWhitespaceConflicts: form.PullsIgnoreWhitespace,
  216. AllowMerge: form.PullsAllowMerge,
  217. AllowRebase: form.PullsAllowRebase,
  218. AllowRebaseMerge: form.PullsAllowRebaseMerge,
  219. AllowSquash: form.PullsAllowSquash,
  220. },
  221. })
  222. }
  223. if err := models.UpdateRepositoryUnits(repo, units); err != nil {
  224. ctx.ServerError("UpdateRepositoryUnits", err)
  225. return
  226. }
  227. log.Trace("Repository advanced settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  228. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  229. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  230. case "admin":
  231. if !ctx.User.IsAdmin {
  232. ctx.Error(403)
  233. return
  234. }
  235. if repo.IsFsckEnabled != form.EnableHealthCheck {
  236. repo.IsFsckEnabled = form.EnableHealthCheck
  237. }
  238. if repo.CloseIssuesViaCommitInAnyBranch != form.EnableCloseIssuesViaCommitInAnyBranch {
  239. repo.CloseIssuesViaCommitInAnyBranch = form.EnableCloseIssuesViaCommitInAnyBranch
  240. }
  241. if err := models.UpdateRepository(repo, false); err != nil {
  242. ctx.ServerError("UpdateRepository", err)
  243. return
  244. }
  245. log.Trace("Repository admin settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  246. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  247. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  248. case "convert":
  249. if !ctx.Repo.IsOwner() {
  250. ctx.Error(404)
  251. return
  252. }
  253. if repo.Name != form.RepoName {
  254. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  255. return
  256. }
  257. if !repo.IsMirror {
  258. ctx.Error(404)
  259. return
  260. }
  261. repo.IsMirror = false
  262. if _, err := models.CleanUpMigrateInfo(repo); err != nil {
  263. ctx.ServerError("CleanUpMigrateInfo", err)
  264. return
  265. } else if err = models.DeleteMirrorByRepoID(ctx.Repo.Repository.ID); err != nil {
  266. ctx.ServerError("DeleteMirrorByRepoID", err)
  267. return
  268. }
  269. log.Trace("Repository converted from mirror to regular: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  270. ctx.Flash.Success(ctx.Tr("repo.settings.convert_succeed"))
  271. ctx.Redirect(setting.AppSubURL + "/" + ctx.Repo.Owner.Name + "/" + repo.Name)
  272. case "transfer":
  273. if !ctx.Repo.IsOwner() {
  274. ctx.Error(404)
  275. return
  276. }
  277. if repo.Name != form.RepoName {
  278. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  279. return
  280. }
  281. newOwner := ctx.Query("new_owner_name")
  282. isExist, err := models.IsUserExist(0, newOwner)
  283. if err != nil {
  284. ctx.ServerError("IsUserExist", err)
  285. return
  286. } else if !isExist {
  287. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_owner_name"), tplSettingsOptions, nil)
  288. return
  289. }
  290. oldOwnerID := ctx.Repo.Owner.ID
  291. if err = models.TransferOwnership(ctx.User, newOwner, repo); err != nil {
  292. if models.IsErrRepoAlreadyExist(err) {
  293. ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplSettingsOptions, nil)
  294. } else {
  295. ctx.ServerError("TransferOwnership", err)
  296. }
  297. return
  298. }
  299. err = models.NewRepoRedirect(oldOwnerID, repo.ID, repo.Name, repo.Name)
  300. if err != nil {
  301. ctx.ServerError("NewRepoRedirect", err)
  302. return
  303. }
  304. log.Trace("Repository transferred: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newOwner)
  305. ctx.Flash.Success(ctx.Tr("repo.settings.transfer_succeed"))
  306. ctx.Redirect(setting.AppSubURL + "/" + newOwner + "/" + repo.Name)
  307. case "delete":
  308. if !ctx.Repo.IsOwner() {
  309. ctx.Error(404)
  310. return
  311. }
  312. if repo.Name != form.RepoName {
  313. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  314. return
  315. }
  316. if err := models.DeleteRepository(ctx.User, ctx.Repo.Owner.ID, repo.ID); err != nil {
  317. ctx.ServerError("DeleteRepository", err)
  318. return
  319. }
  320. log.Trace("Repository deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  321. ctx.Flash.Success(ctx.Tr("repo.settings.deletion_success"))
  322. ctx.Redirect(ctx.Repo.Owner.DashboardLink())
  323. case "delete-wiki":
  324. if !ctx.Repo.IsOwner() {
  325. ctx.Error(404)
  326. return
  327. }
  328. if repo.Name != form.RepoName {
  329. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  330. return
  331. }
  332. repo.DeleteWiki()
  333. log.Trace("Repository wiki deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  334. ctx.Flash.Success(ctx.Tr("repo.settings.wiki_deletion_success"))
  335. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  336. case "archive":
  337. if !ctx.Repo.IsOwner() {
  338. ctx.Error(403)
  339. return
  340. }
  341. if repo.IsMirror {
  342. ctx.Flash.Error(ctx.Tr("repo.settings.archive.error_ismirror"))
  343. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  344. return
  345. }
  346. if err := repo.SetArchiveRepoState(true); err != nil {
  347. log.Error("Tried to archive a repo: %s", err)
  348. ctx.Flash.Error(ctx.Tr("repo.settings.archive.error"))
  349. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  350. return
  351. }
  352. ctx.Flash.Success(ctx.Tr("repo.settings.archive.success"))
  353. log.Trace("Repository was archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  354. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  355. case "unarchive":
  356. if !ctx.Repo.IsOwner() {
  357. ctx.Error(403)
  358. return
  359. }
  360. if err := repo.SetArchiveRepoState(false); err != nil {
  361. log.Error("Tried to unarchive a repo: %s", err)
  362. ctx.Flash.Error(ctx.Tr("repo.settings.unarchive.error"))
  363. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  364. return
  365. }
  366. ctx.Flash.Success(ctx.Tr("repo.settings.unarchive.success"))
  367. log.Trace("Repository was un-archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  368. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  369. default:
  370. ctx.NotFound("", nil)
  371. }
  372. }
  373. // Collaboration render a repository's collaboration page
  374. func Collaboration(ctx *context.Context) {
  375. ctx.Data["Title"] = ctx.Tr("repo.settings")
  376. ctx.Data["PageIsSettingsCollaboration"] = true
  377. users, err := ctx.Repo.Repository.GetCollaborators()
  378. if err != nil {
  379. ctx.ServerError("GetCollaborators", err)
  380. return
  381. }
  382. ctx.Data["Collaborators"] = users
  383. ctx.HTML(200, tplCollaboration)
  384. }
  385. // CollaborationPost response for actions for a collaboration of a repository
  386. func CollaborationPost(ctx *context.Context) {
  387. name := utils.RemoveUsernameParameterSuffix(strings.ToLower(ctx.Query("collaborator")))
  388. if len(name) == 0 || ctx.Repo.Owner.LowerName == name {
  389. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  390. return
  391. }
  392. u, err := models.GetUserByName(name)
  393. if err != nil {
  394. if models.IsErrUserNotExist(err) {
  395. ctx.Flash.Error(ctx.Tr("form.user_not_exist"))
  396. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  397. } else {
  398. ctx.ServerError("GetUserByName", err)
  399. }
  400. return
  401. }
  402. if !u.IsActive {
  403. ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_inactive_user"))
  404. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  405. return
  406. }
  407. // Organization is not allowed to be added as a collaborator.
  408. if u.IsOrganization() {
  409. ctx.Flash.Error(ctx.Tr("repo.settings.org_not_allowed_to_be_collaborator"))
  410. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  411. return
  412. }
  413. if got, err := ctx.Repo.Repository.IsCollaborator(u.ID); err == nil && got {
  414. ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_duplicate"))
  415. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  416. return
  417. }
  418. if err = ctx.Repo.Repository.AddCollaborator(u); err != nil {
  419. ctx.ServerError("AddCollaborator", err)
  420. return
  421. }
  422. if setting.Service.EnableNotifyMail {
  423. models.SendCollaboratorMail(u, ctx.User, ctx.Repo.Repository)
  424. }
  425. ctx.Flash.Success(ctx.Tr("repo.settings.add_collaborator_success"))
  426. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  427. }
  428. // ChangeCollaborationAccessMode response for changing access of a collaboration
  429. func ChangeCollaborationAccessMode(ctx *context.Context) {
  430. if err := ctx.Repo.Repository.ChangeCollaborationAccessMode(
  431. ctx.QueryInt64("uid"),
  432. models.AccessMode(ctx.QueryInt("mode"))); err != nil {
  433. log.Error("ChangeCollaborationAccessMode: %v", err)
  434. }
  435. }
  436. // DeleteCollaboration delete a collaboration for a repository
  437. func DeleteCollaboration(ctx *context.Context) {
  438. if err := ctx.Repo.Repository.DeleteCollaboration(ctx.QueryInt64("id")); err != nil {
  439. ctx.Flash.Error("DeleteCollaboration: " + err.Error())
  440. } else {
  441. ctx.Flash.Success(ctx.Tr("repo.settings.remove_collaborator_success"))
  442. }
  443. ctx.JSON(200, map[string]interface{}{
  444. "redirect": ctx.Repo.RepoLink + "/settings/collaboration",
  445. })
  446. }
  447. // parseOwnerAndRepo get repos by owner
  448. func parseOwnerAndRepo(ctx *context.Context) (*models.User, *models.Repository) {
  449. owner, err := models.GetUserByName(ctx.Params(":username"))
  450. if err != nil {
  451. if models.IsErrUserNotExist(err) {
  452. ctx.NotFound("GetUserByName", err)
  453. } else {
  454. ctx.ServerError("GetUserByName", err)
  455. }
  456. return nil, nil
  457. }
  458. repo, err := models.GetRepositoryByName(owner.ID, ctx.Params(":reponame"))
  459. if err != nil {
  460. if models.IsErrRepoNotExist(err) {
  461. ctx.NotFound("GetRepositoryByName", err)
  462. } else {
  463. ctx.ServerError("GetRepositoryByName", err)
  464. }
  465. return nil, nil
  466. }
  467. return owner, repo
  468. }
  469. // GitHooks hooks of a repository
  470. func GitHooks(ctx *context.Context) {
  471. ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
  472. ctx.Data["PageIsSettingsGitHooks"] = true
  473. hooks, err := ctx.Repo.GitRepo.Hooks()
  474. if err != nil {
  475. ctx.ServerError("Hooks", err)
  476. return
  477. }
  478. ctx.Data["Hooks"] = hooks
  479. ctx.HTML(200, tplGithooks)
  480. }
  481. // GitHooksEdit render for editing a hook of repository page
  482. func GitHooksEdit(ctx *context.Context) {
  483. ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
  484. ctx.Data["PageIsSettingsGitHooks"] = true
  485. name := ctx.Params(":name")
  486. hook, err := ctx.Repo.GitRepo.GetHook(name)
  487. if err != nil {
  488. if err == git.ErrNotValidHook {
  489. ctx.NotFound("GetHook", err)
  490. } else {
  491. ctx.ServerError("GetHook", err)
  492. }
  493. return
  494. }
  495. ctx.Data["Hook"] = hook
  496. ctx.HTML(200, tplGithookEdit)
  497. }
  498. // GitHooksEditPost response for editing a git hook of a repository
  499. func GitHooksEditPost(ctx *context.Context) {
  500. name := ctx.Params(":name")
  501. hook, err := ctx.Repo.GitRepo.GetHook(name)
  502. if err != nil {
  503. if err == git.ErrNotValidHook {
  504. ctx.NotFound("GetHook", err)
  505. } else {
  506. ctx.ServerError("GetHook", err)
  507. }
  508. return
  509. }
  510. hook.Content = ctx.Query("content")
  511. if err = hook.Update(); err != nil {
  512. ctx.ServerError("hook.Update", err)
  513. return
  514. }
  515. ctx.Redirect(ctx.Repo.RepoLink + "/settings/hooks/git")
  516. }
  517. // DeployKeys render the deploy keys list of a repository page
  518. func DeployKeys(ctx *context.Context) {
  519. ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
  520. ctx.Data["PageIsSettingsKeys"] = true
  521. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  522. keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID)
  523. if err != nil {
  524. ctx.ServerError("ListDeployKeys", err)
  525. return
  526. }
  527. ctx.Data["Deploykeys"] = keys
  528. ctx.HTML(200, tplDeployKeys)
  529. }
  530. // DeployKeysPost response for adding a deploy key of a repository
  531. func DeployKeysPost(ctx *context.Context, form auth.AddKeyForm) {
  532. ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
  533. ctx.Data["PageIsSettingsKeys"] = true
  534. keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID)
  535. if err != nil {
  536. ctx.ServerError("ListDeployKeys", err)
  537. return
  538. }
  539. ctx.Data["Deploykeys"] = keys
  540. if ctx.HasError() {
  541. ctx.HTML(200, tplDeployKeys)
  542. return
  543. }
  544. content, err := models.CheckPublicKeyString(form.Content)
  545. if err != nil {
  546. if models.IsErrSSHDisabled(err) {
  547. ctx.Flash.Info(ctx.Tr("settings.ssh_disabled"))
  548. } else if models.IsErrKeyUnableVerify(err) {
  549. ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key"))
  550. } else {
  551. ctx.Data["HasError"] = true
  552. ctx.Data["Err_Content"] = true
  553. ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error()))
  554. }
  555. ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
  556. return
  557. }
  558. key, err := models.AddDeployKey(ctx.Repo.Repository.ID, form.Title, content, !form.IsWritable)
  559. if err != nil {
  560. ctx.Data["HasError"] = true
  561. switch {
  562. case models.IsErrDeployKeyAlreadyExist(err):
  563. ctx.Data["Err_Content"] = true
  564. ctx.RenderWithErr(ctx.Tr("repo.settings.key_been_used"), tplDeployKeys, &form)
  565. case models.IsErrKeyAlreadyExist(err):
  566. ctx.Data["Err_Content"] = true
  567. ctx.RenderWithErr(ctx.Tr("settings.ssh_key_been_used"), tplDeployKeys, &form)
  568. case models.IsErrKeyNameAlreadyUsed(err):
  569. ctx.Data["Err_Title"] = true
  570. ctx.RenderWithErr(ctx.Tr("repo.settings.key_name_used"), tplDeployKeys, &form)
  571. default:
  572. ctx.ServerError("AddDeployKey", err)
  573. }
  574. return
  575. }
  576. log.Trace("Deploy key added: %d", ctx.Repo.Repository.ID)
  577. ctx.Flash.Success(ctx.Tr("repo.settings.add_key_success", key.Name))
  578. ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
  579. }
  580. // DeleteDeployKey response for deleting a deploy key
  581. func DeleteDeployKey(ctx *context.Context) {
  582. if err := models.DeleteDeployKey(ctx.User, ctx.QueryInt64("id")); err != nil {
  583. ctx.Flash.Error("DeleteDeployKey: " + err.Error())
  584. } else {
  585. ctx.Flash.Success(ctx.Tr("repo.settings.deploy_key_deletion_success"))
  586. }
  587. ctx.JSON(200, map[string]interface{}{
  588. "redirect": ctx.Repo.RepoLink + "/settings/keys",
  589. })
  590. }