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

setting.go 20 kB

10 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
8 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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/git"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/auth"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/context"
  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(4, "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. interval, err := time.ParseDuration(form.Interval)
  109. if err != nil || (interval != 0 && interval < setting.Mirror.MinInterval) {
  110. ctx.RenderWithErr(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
  111. } else {
  112. ctx.Repo.Mirror.EnablePrune = form.EnablePrune
  113. ctx.Repo.Mirror.Interval = interval
  114. if interval != 0 {
  115. ctx.Repo.Mirror.NextUpdateUnix = util.TimeStampNow().AddDuration(interval)
  116. } else {
  117. ctx.Repo.Mirror.NextUpdateUnix = 0
  118. }
  119. if err := models.UpdateMirror(ctx.Repo.Mirror); err != nil {
  120. ctx.RenderWithErr(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
  121. return
  122. }
  123. }
  124. if err := ctx.Repo.Mirror.SaveAddress(form.MirrorAddress); err != nil {
  125. ctx.ServerError("SaveAddress", err)
  126. return
  127. }
  128. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  129. ctx.Redirect(repo.Link() + "/settings")
  130. case "mirror-sync":
  131. if !repo.IsMirror {
  132. ctx.NotFound("", nil)
  133. return
  134. }
  135. go models.MirrorQueue.Add(repo.ID)
  136. ctx.Flash.Info(ctx.Tr("repo.settings.mirror_sync_in_progress"))
  137. ctx.Redirect(repo.Link() + "/settings")
  138. case "advanced":
  139. var units []models.RepoUnit
  140. for _, tp := range models.MustRepoUnits {
  141. units = append(units, models.RepoUnit{
  142. RepoID: repo.ID,
  143. Type: tp,
  144. Config: new(models.UnitConfig),
  145. })
  146. }
  147. if form.EnableWiki {
  148. if form.EnableExternalWiki {
  149. if !validation.IsValidExternalURL(form.ExternalWikiURL) {
  150. ctx.Flash.Error(ctx.Tr("repo.settings.external_wiki_url_error"))
  151. ctx.Redirect(repo.Link() + "/settings")
  152. return
  153. }
  154. units = append(units, models.RepoUnit{
  155. RepoID: repo.ID,
  156. Type: models.UnitTypeExternalWiki,
  157. Config: &models.ExternalWikiConfig{
  158. ExternalWikiURL: form.ExternalWikiURL,
  159. },
  160. })
  161. } else {
  162. units = append(units, models.RepoUnit{
  163. RepoID: repo.ID,
  164. Type: models.UnitTypeWiki,
  165. Config: new(models.UnitConfig),
  166. })
  167. }
  168. }
  169. if form.EnableIssues {
  170. if form.EnableExternalTracker {
  171. if !validation.IsValidExternalURL(form.ExternalTrackerURL) {
  172. ctx.Flash.Error(ctx.Tr("repo.settings.external_tracker_url_error"))
  173. ctx.Redirect(repo.Link() + "/settings")
  174. return
  175. }
  176. if len(form.TrackerURLFormat) != 0 && !validation.IsValidExternalURL(form.TrackerURLFormat) {
  177. ctx.Flash.Error(ctx.Tr("repo.settings.tracker_url_format_error"))
  178. ctx.Redirect(repo.Link() + "/settings")
  179. return
  180. }
  181. units = append(units, models.RepoUnit{
  182. RepoID: repo.ID,
  183. Type: models.UnitTypeExternalTracker,
  184. Config: &models.ExternalTrackerConfig{
  185. ExternalTrackerURL: form.ExternalTrackerURL,
  186. ExternalTrackerFormat: form.TrackerURLFormat,
  187. ExternalTrackerStyle: form.TrackerIssueStyle,
  188. },
  189. })
  190. } else {
  191. units = append(units, models.RepoUnit{
  192. RepoID: repo.ID,
  193. Type: models.UnitTypeIssues,
  194. Config: &models.IssuesConfig{
  195. EnableTimetracker: form.EnableTimetracker,
  196. AllowOnlyContributorsToTrackTime: form.AllowOnlyContributorsToTrackTime,
  197. EnableDependencies: form.EnableIssueDependencies,
  198. },
  199. })
  200. }
  201. }
  202. if form.EnablePulls {
  203. units = append(units, models.RepoUnit{
  204. RepoID: repo.ID,
  205. Type: models.UnitTypePullRequests,
  206. Config: &models.PullRequestsConfig{
  207. IgnoreWhitespaceConflicts: form.PullsIgnoreWhitespace,
  208. AllowMerge: form.PullsAllowMerge,
  209. AllowRebase: form.PullsAllowRebase,
  210. AllowRebaseMerge: form.PullsAllowRebaseMerge,
  211. AllowSquash: form.PullsAllowSquash,
  212. },
  213. })
  214. }
  215. if err := models.UpdateRepositoryUnits(repo, units); err != nil {
  216. ctx.ServerError("UpdateRepositoryUnits", err)
  217. return
  218. }
  219. log.Trace("Repository advanced settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  220. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  221. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  222. case "admin":
  223. if !ctx.User.IsAdmin {
  224. ctx.Error(403)
  225. return
  226. }
  227. if repo.IsFsckEnabled != form.EnableHealthCheck {
  228. repo.IsFsckEnabled = form.EnableHealthCheck
  229. }
  230. if repo.CloseIssuesViaCommitInAnyBranch != form.EnableCloseIssuesViaCommitInAnyBranch {
  231. repo.CloseIssuesViaCommitInAnyBranch = form.EnableCloseIssuesViaCommitInAnyBranch
  232. }
  233. if err := models.UpdateRepository(repo, false); err != nil {
  234. ctx.ServerError("UpdateRepository", err)
  235. return
  236. }
  237. log.Trace("Repository admin settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  238. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  239. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  240. case "convert":
  241. if !ctx.Repo.IsOwner() {
  242. ctx.Error(404)
  243. return
  244. }
  245. if repo.Name != form.RepoName {
  246. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  247. return
  248. }
  249. if !repo.IsMirror {
  250. ctx.Error(404)
  251. return
  252. }
  253. repo.IsMirror = false
  254. if _, err := models.CleanUpMigrateInfo(repo); err != nil {
  255. ctx.ServerError("CleanUpMigrateInfo", err)
  256. return
  257. } else if err = models.DeleteMirrorByRepoID(ctx.Repo.Repository.ID); err != nil {
  258. ctx.ServerError("DeleteMirrorByRepoID", err)
  259. return
  260. }
  261. log.Trace("Repository converted from mirror to regular: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  262. ctx.Flash.Success(ctx.Tr("repo.settings.convert_succeed"))
  263. ctx.Redirect(setting.AppSubURL + "/" + ctx.Repo.Owner.Name + "/" + repo.Name)
  264. case "transfer":
  265. if !ctx.Repo.IsOwner() {
  266. ctx.Error(404)
  267. return
  268. }
  269. if repo.Name != form.RepoName {
  270. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  271. return
  272. }
  273. newOwner := ctx.Query("new_owner_name")
  274. isExist, err := models.IsUserExist(0, newOwner)
  275. if err != nil {
  276. ctx.ServerError("IsUserExist", err)
  277. return
  278. } else if !isExist {
  279. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_owner_name"), tplSettingsOptions, nil)
  280. return
  281. }
  282. oldOwnerID := ctx.Repo.Owner.ID
  283. if err = models.TransferOwnership(ctx.User, newOwner, repo); err != nil {
  284. if models.IsErrRepoAlreadyExist(err) {
  285. ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplSettingsOptions, nil)
  286. } else {
  287. ctx.ServerError("TransferOwnership", err)
  288. }
  289. return
  290. }
  291. err = models.NewRepoRedirect(oldOwnerID, repo.ID, repo.Name, repo.Name)
  292. if err != nil {
  293. ctx.ServerError("NewRepoRedirect", err)
  294. return
  295. }
  296. log.Trace("Repository transferred: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newOwner)
  297. ctx.Flash.Success(ctx.Tr("repo.settings.transfer_succeed"))
  298. ctx.Redirect(setting.AppSubURL + "/" + newOwner + "/" + repo.Name)
  299. case "delete":
  300. if !ctx.Repo.IsOwner() {
  301. ctx.Error(404)
  302. return
  303. }
  304. if repo.Name != form.RepoName {
  305. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  306. return
  307. }
  308. if err := models.DeleteRepository(ctx.User, ctx.Repo.Owner.ID, repo.ID); err != nil {
  309. ctx.ServerError("DeleteRepository", err)
  310. return
  311. }
  312. log.Trace("Repository deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  313. ctx.Flash.Success(ctx.Tr("repo.settings.deletion_success"))
  314. ctx.Redirect(ctx.Repo.Owner.DashboardLink())
  315. case "delete-wiki":
  316. if !ctx.Repo.IsOwner() {
  317. ctx.Error(404)
  318. return
  319. }
  320. if repo.Name != form.RepoName {
  321. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  322. return
  323. }
  324. repo.DeleteWiki()
  325. log.Trace("Repository wiki deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  326. ctx.Flash.Success(ctx.Tr("repo.settings.wiki_deletion_success"))
  327. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  328. case "archive":
  329. if !ctx.Repo.IsOwner() {
  330. ctx.Error(403)
  331. return
  332. }
  333. if repo.IsMirror {
  334. ctx.Flash.Error(ctx.Tr("repo.settings.archive.error_ismirror"))
  335. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  336. return
  337. }
  338. if err := repo.SetArchiveRepoState(true); err != nil {
  339. log.Error(4, "Tried to archive a repo: %s", err)
  340. ctx.Flash.Error(ctx.Tr("repo.settings.archive.error"))
  341. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  342. return
  343. }
  344. ctx.Flash.Success(ctx.Tr("repo.settings.archive.success"))
  345. log.Trace("Repository was archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  346. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  347. case "unarchive":
  348. if !ctx.Repo.IsOwner() {
  349. ctx.Error(403)
  350. return
  351. }
  352. if err := repo.SetArchiveRepoState(false); err != nil {
  353. log.Error(4, "Tried to unarchive a repo: %s", err)
  354. ctx.Flash.Error(ctx.Tr("repo.settings.unarchive.error"))
  355. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  356. return
  357. }
  358. ctx.Flash.Success(ctx.Tr("repo.settings.unarchive.success"))
  359. log.Trace("Repository was un-archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  360. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  361. default:
  362. ctx.NotFound("", nil)
  363. }
  364. }
  365. // Collaboration render a repository's collaboration page
  366. func Collaboration(ctx *context.Context) {
  367. ctx.Data["Title"] = ctx.Tr("repo.settings")
  368. ctx.Data["PageIsSettingsCollaboration"] = true
  369. users, err := ctx.Repo.Repository.GetCollaborators()
  370. if err != nil {
  371. ctx.ServerError("GetCollaborators", err)
  372. return
  373. }
  374. ctx.Data["Collaborators"] = users
  375. ctx.HTML(200, tplCollaboration)
  376. }
  377. // CollaborationPost response for actions for a collaboration of a repository
  378. func CollaborationPost(ctx *context.Context) {
  379. name := utils.RemoveUsernameParameterSuffix(strings.ToLower(ctx.Query("collaborator")))
  380. if len(name) == 0 || ctx.Repo.Owner.LowerName == name {
  381. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  382. return
  383. }
  384. u, err := models.GetUserByName(name)
  385. if err != nil {
  386. if models.IsErrUserNotExist(err) {
  387. ctx.Flash.Error(ctx.Tr("form.user_not_exist"))
  388. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  389. } else {
  390. ctx.ServerError("GetUserByName", err)
  391. }
  392. return
  393. }
  394. if !u.IsActive {
  395. ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_inactive_user"))
  396. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  397. return
  398. }
  399. // Organization is not allowed to be added as a collaborator.
  400. if u.IsOrganization() {
  401. ctx.Flash.Error(ctx.Tr("repo.settings.org_not_allowed_to_be_collaborator"))
  402. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  403. return
  404. }
  405. if got, err := ctx.Repo.Repository.IsCollaborator(u.ID); err == nil && got {
  406. ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_duplicate"))
  407. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  408. return
  409. }
  410. if err = ctx.Repo.Repository.AddCollaborator(u); err != nil {
  411. ctx.ServerError("AddCollaborator", err)
  412. return
  413. }
  414. if setting.Service.EnableNotifyMail {
  415. models.SendCollaboratorMail(u, ctx.User, ctx.Repo.Repository)
  416. }
  417. ctx.Flash.Success(ctx.Tr("repo.settings.add_collaborator_success"))
  418. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  419. }
  420. // ChangeCollaborationAccessMode response for changing access of a collaboration
  421. func ChangeCollaborationAccessMode(ctx *context.Context) {
  422. if err := ctx.Repo.Repository.ChangeCollaborationAccessMode(
  423. ctx.QueryInt64("uid"),
  424. models.AccessMode(ctx.QueryInt("mode"))); err != nil {
  425. log.Error(4, "ChangeCollaborationAccessMode: %v", err)
  426. }
  427. }
  428. // DeleteCollaboration delete a collaboration for a repository
  429. func DeleteCollaboration(ctx *context.Context) {
  430. if err := ctx.Repo.Repository.DeleteCollaboration(ctx.QueryInt64("id")); err != nil {
  431. ctx.Flash.Error("DeleteCollaboration: " + err.Error())
  432. } else {
  433. ctx.Flash.Success(ctx.Tr("repo.settings.remove_collaborator_success"))
  434. }
  435. ctx.JSON(200, map[string]interface{}{
  436. "redirect": ctx.Repo.RepoLink + "/settings/collaboration",
  437. })
  438. }
  439. // parseOwnerAndRepo get repos by owner
  440. func parseOwnerAndRepo(ctx *context.Context) (*models.User, *models.Repository) {
  441. owner, err := models.GetUserByName(ctx.Params(":username"))
  442. if err != nil {
  443. if models.IsErrUserNotExist(err) {
  444. ctx.NotFound("GetUserByName", err)
  445. } else {
  446. ctx.ServerError("GetUserByName", err)
  447. }
  448. return nil, nil
  449. }
  450. repo, err := models.GetRepositoryByName(owner.ID, ctx.Params(":reponame"))
  451. if err != nil {
  452. if models.IsErrRepoNotExist(err) {
  453. ctx.NotFound("GetRepositoryByName", err)
  454. } else {
  455. ctx.ServerError("GetRepositoryByName", err)
  456. }
  457. return nil, nil
  458. }
  459. return owner, repo
  460. }
  461. // GitHooks hooks of a repository
  462. func GitHooks(ctx *context.Context) {
  463. ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
  464. ctx.Data["PageIsSettingsGitHooks"] = true
  465. hooks, err := ctx.Repo.GitRepo.Hooks()
  466. if err != nil {
  467. ctx.ServerError("Hooks", err)
  468. return
  469. }
  470. ctx.Data["Hooks"] = hooks
  471. ctx.HTML(200, tplGithooks)
  472. }
  473. // GitHooksEdit render for editing a hook of repository page
  474. func GitHooksEdit(ctx *context.Context) {
  475. ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
  476. ctx.Data["PageIsSettingsGitHooks"] = true
  477. name := ctx.Params(":name")
  478. hook, err := ctx.Repo.GitRepo.GetHook(name)
  479. if err != nil {
  480. if err == git.ErrNotValidHook {
  481. ctx.NotFound("GetHook", err)
  482. } else {
  483. ctx.ServerError("GetHook", err)
  484. }
  485. return
  486. }
  487. ctx.Data["Hook"] = hook
  488. ctx.HTML(200, tplGithookEdit)
  489. }
  490. // GitHooksEditPost response for editing a git hook of a repository
  491. func GitHooksEditPost(ctx *context.Context) {
  492. name := ctx.Params(":name")
  493. hook, err := ctx.Repo.GitRepo.GetHook(name)
  494. if err != nil {
  495. if err == git.ErrNotValidHook {
  496. ctx.NotFound("GetHook", err)
  497. } else {
  498. ctx.ServerError("GetHook", err)
  499. }
  500. return
  501. }
  502. hook.Content = ctx.Query("content")
  503. if err = hook.Update(); err != nil {
  504. ctx.ServerError("hook.Update", err)
  505. return
  506. }
  507. ctx.Redirect(ctx.Repo.RepoLink + "/settings/hooks/git")
  508. }
  509. // DeployKeys render the deploy keys list of a repository page
  510. func DeployKeys(ctx *context.Context) {
  511. ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
  512. ctx.Data["PageIsSettingsKeys"] = true
  513. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  514. keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID)
  515. if err != nil {
  516. ctx.ServerError("ListDeployKeys", err)
  517. return
  518. }
  519. ctx.Data["Deploykeys"] = keys
  520. ctx.HTML(200, tplDeployKeys)
  521. }
  522. // DeployKeysPost response for adding a deploy key of a repository
  523. func DeployKeysPost(ctx *context.Context, form auth.AddKeyForm) {
  524. ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
  525. ctx.Data["PageIsSettingsKeys"] = true
  526. keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID)
  527. if err != nil {
  528. ctx.ServerError("ListDeployKeys", err)
  529. return
  530. }
  531. ctx.Data["Deploykeys"] = keys
  532. if ctx.HasError() {
  533. ctx.HTML(200, tplDeployKeys)
  534. return
  535. }
  536. content, err := models.CheckPublicKeyString(form.Content)
  537. if err != nil {
  538. if models.IsErrSSHDisabled(err) {
  539. ctx.Flash.Info(ctx.Tr("settings.ssh_disabled"))
  540. } else if models.IsErrKeyUnableVerify(err) {
  541. ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key"))
  542. } else {
  543. ctx.Data["HasError"] = true
  544. ctx.Data["Err_Content"] = true
  545. ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error()))
  546. }
  547. ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
  548. return
  549. }
  550. key, err := models.AddDeployKey(ctx.Repo.Repository.ID, form.Title, content, !form.IsWritable)
  551. if err != nil {
  552. ctx.Data["HasError"] = true
  553. switch {
  554. case models.IsErrDeployKeyAlreadyExist(err):
  555. ctx.Data["Err_Content"] = true
  556. ctx.RenderWithErr(ctx.Tr("repo.settings.key_been_used"), tplDeployKeys, &form)
  557. case models.IsErrKeyAlreadyExist(err):
  558. ctx.Data["Err_Content"] = true
  559. ctx.RenderWithErr(ctx.Tr("settings.ssh_key_been_used"), tplDeployKeys, &form)
  560. case models.IsErrKeyNameAlreadyUsed(err):
  561. ctx.Data["Err_Title"] = true
  562. ctx.RenderWithErr(ctx.Tr("repo.settings.key_name_used"), tplDeployKeys, &form)
  563. default:
  564. ctx.ServerError("AddDeployKey", err)
  565. }
  566. return
  567. }
  568. log.Trace("Deploy key added: %d", ctx.Repo.Repository.ID)
  569. ctx.Flash.Success(ctx.Tr("repo.settings.add_key_success", key.Name))
  570. ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
  571. }
  572. // DeleteDeployKey response for deleting a deploy key
  573. func DeleteDeployKey(ctx *context.Context) {
  574. if err := models.DeleteDeployKey(ctx.User, ctx.QueryInt64("id")); err != nil {
  575. ctx.Flash.Error("DeleteDeployKey: " + err.Error())
  576. } else {
  577. ctx.Flash.Success(ctx.Tr("repo.settings.deploy_key_deletion_success"))
  578. }
  579. ctx.JSON(200, map[string]interface{}{
  580. "redirect": ctx.Repo.RepoLink + "/settings/keys",
  581. })
  582. }