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