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.

repo.go 19 kB

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
11 years ago
11 years ago
11 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
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
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 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 context
  6. import (
  7. "fmt"
  8. "io/ioutil"
  9. "path"
  10. "strings"
  11. "code.gitea.io/git"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/setting"
  14. "github.com/Unknwon/com"
  15. "gopkg.in/editorconfig/editorconfig-core-go.v1"
  16. "gopkg.in/macaron.v1"
  17. )
  18. // PullRequest contains informations to make a pull request
  19. type PullRequest struct {
  20. BaseRepo *models.Repository
  21. Allowed bool
  22. SameRepo bool
  23. HeadInfo string // [<user>:]<branch>
  24. }
  25. // Repository contains information to operate a repository
  26. type Repository struct {
  27. AccessMode models.AccessMode
  28. IsWatching bool
  29. IsViewBranch bool
  30. IsViewTag bool
  31. IsViewCommit bool
  32. Repository *models.Repository
  33. Owner *models.User
  34. Commit *git.Commit
  35. Tag *git.Tag
  36. GitRepo *git.Repository
  37. BranchName string
  38. TagName string
  39. TreePath string
  40. CommitID string
  41. RepoLink string
  42. CloneLink models.CloneLink
  43. CommitsCount int64
  44. Mirror *models.Mirror
  45. PullRequest *PullRequest
  46. }
  47. // IsOwner returns true if current user is the owner of repository.
  48. func (r *Repository) IsOwner() bool {
  49. return r.AccessMode >= models.AccessModeOwner
  50. }
  51. // IsAdmin returns true if current user has admin or higher access of repository.
  52. func (r *Repository) IsAdmin() bool {
  53. return r.AccessMode >= models.AccessModeAdmin
  54. }
  55. // IsWriter returns true if current user has write or higher access of repository.
  56. func (r *Repository) IsWriter() bool {
  57. return r.AccessMode >= models.AccessModeWrite
  58. }
  59. // HasAccess returns true if the current user has at least read access for this repository
  60. func (r *Repository) HasAccess() bool {
  61. return r.AccessMode >= models.AccessModeRead
  62. }
  63. // CanEnableEditor returns true if repository is editable and user has proper access level.
  64. func (r *Repository) CanEnableEditor() bool {
  65. return r.Repository.CanEnableEditor() && r.IsViewBranch && r.IsWriter()
  66. }
  67. // CanCreateBranch returns true if repository is editable and user has proper access level.
  68. func (r *Repository) CanCreateBranch() bool {
  69. return r.Repository.CanCreateBranch() && r.IsWriter()
  70. }
  71. // CanCommitToBranch returns true if repository is editable and user has proper access level
  72. // and branch is not protected
  73. func (r *Repository) CanCommitToBranch(doer *models.User) (bool, error) {
  74. protectedBranch, err := r.Repository.IsProtectedBranch(r.BranchName, doer)
  75. if err != nil {
  76. return false, err
  77. }
  78. return r.CanEnableEditor() && !protectedBranch, nil
  79. }
  80. // CanUseTimetracker returns whether or not a user can use the timetracker.
  81. func (r *Repository) CanUseTimetracker(issue *models.Issue, user *models.User) bool {
  82. // Checking for following:
  83. // 1. Is timetracker enabled
  84. // 2. Is the user a contributor, admin, poster or assignee and do the repository policies require this?
  85. return r.Repository.IsTimetrackerEnabled() && (!r.Repository.AllowOnlyContributorsToTrackTime() ||
  86. r.IsWriter() || issue.IsPoster(user.ID) || issue.AssigneeID == user.ID)
  87. }
  88. // GetEditorconfig returns the .editorconfig definition if found in the
  89. // HEAD of the default repo branch.
  90. func (r *Repository) GetEditorconfig() (*editorconfig.Editorconfig, error) {
  91. commit, err := r.GitRepo.GetBranchCommit(r.Repository.DefaultBranch)
  92. if err != nil {
  93. return nil, err
  94. }
  95. treeEntry, err := commit.GetTreeEntryByPath(".editorconfig")
  96. if err != nil {
  97. return nil, err
  98. }
  99. reader, err := treeEntry.Blob().Data()
  100. if err != nil {
  101. return nil, err
  102. }
  103. data, err := ioutil.ReadAll(reader)
  104. if err != nil {
  105. return nil, err
  106. }
  107. return editorconfig.ParseBytes(data)
  108. }
  109. // RetrieveBaseRepo retrieves base repository
  110. func RetrieveBaseRepo(ctx *Context, repo *models.Repository) {
  111. // Non-fork repository will not return error in this method.
  112. if err := repo.GetBaseRepo(); err != nil {
  113. if models.IsErrRepoNotExist(err) {
  114. repo.IsFork = false
  115. repo.ForkID = 0
  116. return
  117. }
  118. ctx.Handle(500, "GetBaseRepo", err)
  119. return
  120. } else if err = repo.BaseRepo.GetOwner(); err != nil {
  121. ctx.Handle(500, "BaseRepo.GetOwner", err)
  122. return
  123. }
  124. }
  125. // ComposeGoGetImport returns go-get-import meta content.
  126. func ComposeGoGetImport(owner, repo string) string {
  127. return path.Join(setting.Domain, setting.AppSubURL, owner, repo)
  128. }
  129. // EarlyResponseForGoGetMeta responses appropriate go-get meta with status 200
  130. // if user does not have actual access to the requested repository,
  131. // or the owner or repository does not exist at all.
  132. // This is particular a workaround for "go get" command which does not respect
  133. // .netrc file.
  134. func EarlyResponseForGoGetMeta(ctx *Context) {
  135. username := ctx.Params(":username")
  136. reponame := ctx.Params(":reponame")
  137. ctx.PlainText(200, []byte(com.Expand(`<meta name="go-import" content="{GoGetImport} git {CloneLink}">`,
  138. map[string]string{
  139. "GoGetImport": ComposeGoGetImport(username, strings.TrimSuffix(reponame, ".git")),
  140. "CloneLink": models.ComposeHTTPSCloneURL(username, reponame),
  141. })))
  142. }
  143. // RedirectToRepo redirect to a differently-named repository
  144. func RedirectToRepo(ctx *Context, redirectRepoID int64) {
  145. ownerName := ctx.Params(":username")
  146. previousRepoName := ctx.Params(":reponame")
  147. repo, err := models.GetRepositoryByID(redirectRepoID)
  148. if err != nil {
  149. ctx.Handle(500, "GetRepositoryByID", err)
  150. return
  151. }
  152. redirectPath := strings.Replace(
  153. ctx.Req.URL.Path,
  154. fmt.Sprintf("%s/%s", ownerName, previousRepoName),
  155. fmt.Sprintf("%s/%s", ownerName, repo.Name),
  156. 1,
  157. )
  158. ctx.Redirect(redirectPath)
  159. }
  160. func repoAssignment(ctx *Context, repo *models.Repository) {
  161. // Admin has super access.
  162. if ctx.IsSigned && ctx.User.IsAdmin {
  163. ctx.Repo.AccessMode = models.AccessModeOwner
  164. } else {
  165. var userID int64
  166. if ctx.User != nil {
  167. userID = ctx.User.ID
  168. }
  169. mode, err := models.AccessLevel(userID, repo)
  170. if err != nil {
  171. ctx.Handle(500, "AccessLevel", err)
  172. return
  173. }
  174. ctx.Repo.AccessMode = mode
  175. }
  176. // Check access.
  177. if ctx.Repo.AccessMode == models.AccessModeNone {
  178. if ctx.Query("go-get") == "1" {
  179. EarlyResponseForGoGetMeta(ctx)
  180. return
  181. }
  182. ctx.Handle(404, "no access right", nil)
  183. return
  184. }
  185. ctx.Data["HasAccess"] = true
  186. if repo.IsMirror {
  187. var err error
  188. ctx.Repo.Mirror, err = models.GetMirrorByRepoID(repo.ID)
  189. if err != nil {
  190. ctx.Handle(500, "GetMirror", err)
  191. return
  192. }
  193. ctx.Data["MirrorEnablePrune"] = ctx.Repo.Mirror.EnablePrune
  194. ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval
  195. ctx.Data["Mirror"] = ctx.Repo.Mirror
  196. }
  197. ctx.Repo.Repository = repo
  198. ctx.Data["RepoName"] = ctx.Repo.Repository.Name
  199. ctx.Data["IsBareRepo"] = ctx.Repo.Repository.IsBare
  200. }
  201. // RepoIDAssignment returns a macaron handler which assigns the repo to the context.
  202. func RepoIDAssignment() macaron.Handler {
  203. return func(ctx *Context) {
  204. repoID := ctx.ParamsInt64(":repoid")
  205. // Get repository.
  206. repo, err := models.GetRepositoryByID(repoID)
  207. if err != nil {
  208. if models.IsErrRepoNotExist(err) {
  209. ctx.Handle(404, "GetRepositoryByID", nil)
  210. } else {
  211. ctx.Handle(500, "GetRepositoryByID", err)
  212. }
  213. return
  214. }
  215. if err = repo.GetOwner(); err != nil {
  216. ctx.Handle(500, "GetOwner", err)
  217. return
  218. }
  219. repoAssignment(ctx, repo)
  220. }
  221. }
  222. // RepoAssignment returns a macaron to handle repository assignment
  223. func RepoAssignment() macaron.Handler {
  224. return func(ctx *Context) {
  225. var (
  226. owner *models.User
  227. err error
  228. )
  229. userName := ctx.Params(":username")
  230. repoName := ctx.Params(":reponame")
  231. // Check if the user is the same as the repository owner
  232. if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
  233. owner = ctx.User
  234. } else {
  235. owner, err = models.GetUserByName(userName)
  236. if err != nil {
  237. if models.IsErrUserNotExist(err) {
  238. if ctx.Query("go-get") == "1" {
  239. EarlyResponseForGoGetMeta(ctx)
  240. return
  241. }
  242. ctx.Handle(404, "GetUserByName", nil)
  243. } else {
  244. ctx.Handle(500, "GetUserByName", err)
  245. }
  246. return
  247. }
  248. }
  249. ctx.Repo.Owner = owner
  250. ctx.Data["Username"] = ctx.Repo.Owner.Name
  251. // Get repository.
  252. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  253. if err != nil {
  254. if models.IsErrRepoNotExist(err) {
  255. redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
  256. if err == nil {
  257. RedirectToRepo(ctx, redirectRepoID)
  258. } else if models.IsErrRepoRedirectNotExist(err) {
  259. if ctx.Query("go-get") == "1" {
  260. EarlyResponseForGoGetMeta(ctx)
  261. return
  262. }
  263. ctx.Handle(404, "GetRepositoryByName", nil)
  264. } else {
  265. ctx.Handle(500, "LookupRepoRedirect", err)
  266. }
  267. } else {
  268. ctx.Handle(500, "GetRepositoryByName", err)
  269. }
  270. return
  271. }
  272. repo.Owner = owner
  273. repoAssignment(ctx, repo)
  274. if ctx.Written() {
  275. return
  276. }
  277. gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName))
  278. if err != nil {
  279. ctx.Handle(500, "RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err)
  280. return
  281. }
  282. ctx.Repo.GitRepo = gitRepo
  283. ctx.Repo.RepoLink = repo.Link()
  284. ctx.Data["RepoLink"] = ctx.Repo.RepoLink
  285. ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
  286. tags, err := ctx.Repo.GitRepo.GetTags()
  287. if err != nil {
  288. ctx.Handle(500, "GetTags", err)
  289. return
  290. }
  291. ctx.Data["Tags"] = tags
  292. count, err := models.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{
  293. IncludeDrafts: false,
  294. IncludeTags: true,
  295. })
  296. if err != nil {
  297. ctx.Handle(500, "GetReleaseCountByRepoID", err)
  298. return
  299. }
  300. ctx.Repo.Repository.NumReleases = int(count)
  301. ctx.Data["Title"] = owner.Name + "/" + repo.Name
  302. ctx.Data["Repository"] = repo
  303. ctx.Data["Owner"] = ctx.Repo.Repository.Owner
  304. ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner()
  305. ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin()
  306. ctx.Data["IsRepositoryWriter"] = ctx.Repo.IsWriter()
  307. if ctx.Data["CanSignedUserFork"], err = ctx.Repo.Repository.CanUserFork(ctx.User); err != nil {
  308. ctx.Handle(500, "CanUserFork", err)
  309. return
  310. }
  311. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  312. ctx.Data["ExposeAnonSSH"] = setting.SSH.ExposeAnonymous
  313. ctx.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit
  314. ctx.Data["CloneLink"] = repo.CloneLink()
  315. ctx.Data["WikiCloneLink"] = repo.WikiCloneLink()
  316. if ctx.IsSigned {
  317. ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.ID, repo.ID)
  318. ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.ID, repo.ID)
  319. }
  320. // repo is bare and display enable
  321. if ctx.Repo.Repository.IsBare {
  322. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  323. return
  324. }
  325. ctx.Data["TagName"] = ctx.Repo.TagName
  326. brs, err := ctx.Repo.GitRepo.GetBranches()
  327. if err != nil {
  328. ctx.Handle(500, "GetBranches", err)
  329. return
  330. }
  331. ctx.Data["Branches"] = brs
  332. ctx.Data["BrancheCount"] = len(brs)
  333. // If not branch selected, try default one.
  334. // If default branch doesn't exists, fall back to some other branch.
  335. if len(ctx.Repo.BranchName) == 0 {
  336. if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) {
  337. ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch
  338. } else if len(brs) > 0 {
  339. ctx.Repo.BranchName = brs[0]
  340. }
  341. }
  342. ctx.Data["BranchName"] = ctx.Repo.BranchName
  343. ctx.Data["CommitID"] = ctx.Repo.CommitID
  344. if repo.IsFork {
  345. RetrieveBaseRepo(ctx, repo)
  346. if ctx.Written() {
  347. return
  348. }
  349. }
  350. // People who have push access or have forked repository can propose a new pull request.
  351. if ctx.Repo.IsWriter() || (ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID)) {
  352. // Pull request is allowed if this is a fork repository
  353. // and base repository accepts pull requests.
  354. if repo.BaseRepo != nil && repo.BaseRepo.AllowsPulls() {
  355. ctx.Data["BaseRepo"] = repo.BaseRepo
  356. ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo
  357. ctx.Repo.PullRequest.Allowed = true
  358. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName
  359. } else {
  360. // Or, this is repository accepts pull requests between branches.
  361. if repo.AllowsPulls() {
  362. ctx.Data["BaseRepo"] = repo
  363. ctx.Repo.PullRequest.BaseRepo = repo
  364. ctx.Repo.PullRequest.Allowed = true
  365. ctx.Repo.PullRequest.SameRepo = true
  366. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName
  367. }
  368. }
  369. // Reset repo units as otherwise user specific units wont be loaded later
  370. ctx.Repo.Repository.Units = nil
  371. }
  372. ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest
  373. if ctx.Query("go-get") == "1" {
  374. ctx.Data["GoGetImport"] = ComposeGoGetImport(owner.Name, repo.Name)
  375. prefix := setting.AppURL + path.Join(owner.Name, repo.Name, "src", ctx.Repo.BranchName)
  376. ctx.Data["GoDocDirectory"] = prefix + "{/dir}"
  377. ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}"
  378. }
  379. }
  380. }
  381. // RepoRef handles repository reference name including those contain `/`.
  382. func RepoRef() macaron.Handler {
  383. return func(ctx *Context) {
  384. // Empty repository does not have reference information.
  385. if ctx.Repo.Repository.IsBare {
  386. return
  387. }
  388. var (
  389. refName string
  390. err error
  391. )
  392. // For API calls.
  393. if ctx.Repo.GitRepo == nil {
  394. repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  395. ctx.Repo.GitRepo, err = git.OpenRepository(repoPath)
  396. if err != nil {
  397. ctx.Handle(500, "RepoRef Invalid repo "+repoPath, err)
  398. return
  399. }
  400. }
  401. // Get default branch.
  402. if len(ctx.Params("*")) == 0 {
  403. refName = ctx.Repo.Repository.DefaultBranch
  404. if !ctx.Repo.GitRepo.IsBranchExist(refName) {
  405. brs, err := ctx.Repo.GitRepo.GetBranches()
  406. if err != nil {
  407. ctx.Handle(500, "GetBranches", err)
  408. return
  409. } else if len(brs) == 0 {
  410. err = fmt.Errorf("No branches in non-bare repository %s",
  411. ctx.Repo.GitRepo.Path)
  412. ctx.Handle(500, "GetBranches", err)
  413. return
  414. }
  415. refName = brs[0]
  416. }
  417. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  418. if err != nil {
  419. ctx.Handle(500, "GetBranchCommit", err)
  420. return
  421. }
  422. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  423. ctx.Repo.IsViewBranch = true
  424. } else {
  425. hasMatched := false
  426. parts := strings.Split(ctx.Params("*"), "/")
  427. for i, part := range parts {
  428. refName = strings.TrimPrefix(refName+"/"+part, "/")
  429. if ctx.Repo.GitRepo.IsBranchExist(refName) ||
  430. ctx.Repo.GitRepo.IsTagExist(refName) {
  431. if i < len(parts)-1 {
  432. ctx.Repo.TreePath = strings.Join(parts[i+1:], "/")
  433. }
  434. hasMatched = true
  435. break
  436. }
  437. }
  438. if !hasMatched && len(parts[0]) == 40 {
  439. refName = parts[0]
  440. ctx.Repo.TreePath = strings.Join(parts[1:], "/")
  441. }
  442. if ctx.Repo.GitRepo.IsBranchExist(refName) {
  443. ctx.Repo.IsViewBranch = true
  444. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  445. if err != nil {
  446. ctx.Handle(500, "GetBranchCommit", err)
  447. return
  448. }
  449. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  450. } else if ctx.Repo.GitRepo.IsTagExist(refName) {
  451. ctx.Repo.IsViewTag = true
  452. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
  453. if err != nil {
  454. ctx.Handle(500, "GetTagCommit", err)
  455. return
  456. }
  457. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  458. } else if len(refName) == 40 {
  459. ctx.Repo.IsViewCommit = true
  460. ctx.Repo.CommitID = refName
  461. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
  462. if err != nil {
  463. ctx.Handle(404, "GetCommit", nil)
  464. return
  465. }
  466. } else {
  467. ctx.Handle(404, "RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
  468. return
  469. }
  470. }
  471. ctx.Repo.BranchName = refName
  472. ctx.Data["BranchName"] = ctx.Repo.BranchName
  473. ctx.Data["CommitID"] = ctx.Repo.CommitID
  474. ctx.Data["TreePath"] = ctx.Repo.TreePath
  475. ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch
  476. ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag
  477. ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit
  478. ctx.Data["CanCreateBranch"] = ctx.Repo.CanCreateBranch()
  479. ctx.Repo.CommitsCount, err = ctx.Repo.Commit.CommitsCount()
  480. if err != nil {
  481. ctx.Handle(500, "CommitsCount", err)
  482. return
  483. }
  484. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  485. }
  486. }
  487. // RequireRepoAdmin returns a macaron middleware for requiring repository admin permission
  488. func RequireRepoAdmin() macaron.Handler {
  489. return func(ctx *Context) {
  490. if !ctx.IsSigned || (!ctx.Repo.IsAdmin() && !ctx.User.IsAdmin) {
  491. ctx.Handle(404, ctx.Req.RequestURI, nil)
  492. return
  493. }
  494. }
  495. }
  496. // RequireRepoWriter returns a macaron middleware for requiring repository write permission
  497. func RequireRepoWriter() macaron.Handler {
  498. return func(ctx *Context) {
  499. if !ctx.IsSigned || (!ctx.Repo.IsWriter() && !ctx.User.IsAdmin) {
  500. ctx.Handle(404, ctx.Req.RequestURI, nil)
  501. return
  502. }
  503. }
  504. }
  505. // LoadRepoUnits loads repsitory's units, it should be called after repository and user loaded
  506. func LoadRepoUnits() macaron.Handler {
  507. return func(ctx *Context) {
  508. var isAdmin bool
  509. if ctx.User != nil && ctx.User.IsAdmin {
  510. isAdmin = true
  511. }
  512. var userID int64
  513. if ctx.User != nil {
  514. userID = ctx.User.ID
  515. }
  516. err := ctx.Repo.Repository.LoadUnitsByUserID(userID, isAdmin)
  517. if err != nil {
  518. ctx.Handle(500, "LoadUnitsByUserID", err)
  519. return
  520. }
  521. }
  522. }
  523. // CheckUnit will check whether unit type is enabled
  524. func CheckUnit(unitType models.UnitType) macaron.Handler {
  525. return func(ctx *Context) {
  526. if !ctx.Repo.Repository.UnitEnabled(unitType) {
  527. ctx.Handle(404, "CheckUnit", fmt.Errorf("%s: %v", ctx.Tr("units.error.unit_not_allowed"), unitType))
  528. }
  529. }
  530. }
  531. // CheckAnyUnit will check whether any of the unit types are enabled
  532. func CheckAnyUnit(unitTypes ...models.UnitType) macaron.Handler {
  533. return func(ctx *Context) {
  534. if !ctx.Repo.Repository.AnyUnitEnabled(unitTypes...) {
  535. ctx.Handle(404, "CheckAnyUnit", fmt.Errorf("%s: %v", ctx.Tr("units.error.unit_not_allowed"), unitTypes))
  536. }
  537. }
  538. }
  539. // GitHookService checks if repository Git hooks service has been enabled.
  540. func GitHookService() macaron.Handler {
  541. return func(ctx *Context) {
  542. if !ctx.User.CanEditGitHook() {
  543. ctx.Handle(404, "GitHookService", nil)
  544. return
  545. }
  546. }
  547. }
  548. // UnitTypes returns a macaron middleware to set unit types to context variables.
  549. func UnitTypes() macaron.Handler {
  550. return func(ctx *Context) {
  551. ctx.Data["UnitTypeCode"] = models.UnitTypeCode
  552. ctx.Data["UnitTypeIssues"] = models.UnitTypeIssues
  553. ctx.Data["UnitTypePullRequests"] = models.UnitTypePullRequests
  554. ctx.Data["UnitTypeReleases"] = models.UnitTypeReleases
  555. ctx.Data["UnitTypeWiki"] = models.UnitTypeWiki
  556. ctx.Data["UnitTypeExternalWiki"] = models.UnitTypeExternalWiki
  557. ctx.Data["UnitTypeExternalTracker"] = models.UnitTypeExternalTracker
  558. }
  559. }