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