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