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.

issue.go 72 kB

11 years ago
11 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
10 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
10 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
9 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
9 years ago
9 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
9 years ago
9 years ago
9 years ago
Improve listing performance by using go-git (#6478) * Use go-git for tree reading and commit info lookup. Signed-off-by: Filip Navara <navara@emclient.com> * Use TreeEntry.IsRegular() instead of ObjectType that was removed. Signed-off-by: Filip Navara <navara@emclient.com> * Use the treePath to optimize commit info search. Signed-off-by: Filip Navara <navara@emclient.com> * Extract the latest commit at treePath along with the other commits. Signed-off-by: Filip Navara <navara@emclient.com> * Fix listing commit info for a directory that was created in one commit and never modified after. Signed-off-by: Filip Navara <navara@emclient.com> * Avoid nearly all external 'git' invocations when doing directory listing (.editorconfig code path is still hit). Signed-off-by: Filip Navara <navara@emclient.com> * Use go-git for reading blobs. Signed-off-by: Filip Navara <navara@emclient.com> * Make SHA1 type alias for plumbing.Hash in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Make Signature type alias for object.Signature in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Fix GetCommitsInfo for repository with only one commit. Signed-off-by: Filip Navara <navara@emclient.com> * Fix PGP signature verification. Signed-off-by: Filip Navara <navara@emclient.com> * Fix issues with walking commit graph across merges. Signed-off-by: Filip Navara <navara@emclient.com> * Fix typo in condition. Signed-off-by: Filip Navara <navara@emclient.com> * Speed up loading branch list by keeping the repository reference (and thus all the loaded packfile indexes). Signed-off-by: Filip Navara <navara@emclient.com> * Fix lising submodules. Signed-off-by: Filip Navara <navara@emclient.com> * Fix build Signed-off-by: Filip Navara <navara@emclient.com> * Add back commit cache because of name-rev Signed-off-by: Filip Navara <navara@emclient.com> * Fix tests Signed-off-by: Filip Navara <navara@emclient.com> * Fix code style * Fix spelling * Address PR feedback Signed-off-by: Filip Navara <navara@emclient.com> * Update vendor module list Signed-off-by: Filip Navara <navara@emclient.com> * Fix getting trees by commit id Signed-off-by: Filip Navara <navara@emclient.com> * Fix remaining unit test failures * Fix GetTreeBySHA * Avoid running `git name-rev` if not necessary Signed-off-by: Filip Navara <navara@emclient.com> * Move Branch code to git module * Clean up GPG signature verification and fix it for tagged commits * Address PR feedback (import formatting, copyright headers) * Make blob lookup by SHA working * Update tests to use public API * Allow getting content from any type of object through the blob interface * Change test to actually expect the object content that is in the GIT repository * Change one more test to actually expect the object content that is in the GIT repository * Add comments
6 years ago
Improve listing performance by using go-git (#6478) * Use go-git for tree reading and commit info lookup. Signed-off-by: Filip Navara <navara@emclient.com> * Use TreeEntry.IsRegular() instead of ObjectType that was removed. Signed-off-by: Filip Navara <navara@emclient.com> * Use the treePath to optimize commit info search. Signed-off-by: Filip Navara <navara@emclient.com> * Extract the latest commit at treePath along with the other commits. Signed-off-by: Filip Navara <navara@emclient.com> * Fix listing commit info for a directory that was created in one commit and never modified after. Signed-off-by: Filip Navara <navara@emclient.com> * Avoid nearly all external 'git' invocations when doing directory listing (.editorconfig code path is still hit). Signed-off-by: Filip Navara <navara@emclient.com> * Use go-git for reading blobs. Signed-off-by: Filip Navara <navara@emclient.com> * Make SHA1 type alias for plumbing.Hash in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Make Signature type alias for object.Signature in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Fix GetCommitsInfo for repository with only one commit. Signed-off-by: Filip Navara <navara@emclient.com> * Fix PGP signature verification. Signed-off-by: Filip Navara <navara@emclient.com> * Fix issues with walking commit graph across merges. Signed-off-by: Filip Navara <navara@emclient.com> * Fix typo in condition. Signed-off-by: Filip Navara <navara@emclient.com> * Speed up loading branch list by keeping the repository reference (and thus all the loaded packfile indexes). Signed-off-by: Filip Navara <navara@emclient.com> * Fix lising submodules. Signed-off-by: Filip Navara <navara@emclient.com> * Fix build Signed-off-by: Filip Navara <navara@emclient.com> * Add back commit cache because of name-rev Signed-off-by: Filip Navara <navara@emclient.com> * Fix tests Signed-off-by: Filip Navara <navara@emclient.com> * Fix code style * Fix spelling * Address PR feedback Signed-off-by: Filip Navara <navara@emclient.com> * Update vendor module list Signed-off-by: Filip Navara <navara@emclient.com> * Fix getting trees by commit id Signed-off-by: Filip Navara <navara@emclient.com> * Fix remaining unit test failures * Fix GetTreeBySHA * Avoid running `git name-rev` if not necessary Signed-off-by: Filip Navara <navara@emclient.com> * Move Branch code to git module * Clean up GPG signature verification and fix it for tagged commits * Address PR feedback (import formatting, copyright headers) * Make blob lookup by SHA working * Update tests to use public API * Allow getting content from any type of object through the blob interface * Change test to actually expect the object content that is in the GIT repository * Change one more test to actually expect the object content that is in the GIT repository * Add comments
6 years ago
9 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
8 years ago
9 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
Add a storage layer for attachments (#11387) * Add a storage layer for attachments * Fix some bug * fix test * Fix copyright head and lint * Fix bug * Add setting for minio and flags for migrate-storage * Add documents * fix lint * Add test for minio store type on attachments * fix test * fix test * Apply suggestions from code review Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> * Add warning when storage migrated successfully * Fix drone * fix test * rebase * Fix test * display the error on console * Move minio test to amd64 since minio docker don't support arm64 * refactor the codes * add trace * Fix test * remove log on xorm * Fi download bug * Add a storage layer for attachments * Add setting for minio and flags for migrate-storage * fix lint * Add test for minio store type on attachments * Apply suggestions from code review Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> * Fix drone * fix test * Fix test * display the error on console * Move minio test to amd64 since minio docker don't support arm64 * refactor the codes * add trace * Fix test * Add URL function to serve attachments directly from S3/Minio * Add ability to enable/disable redirection in attachment configuration * Fix typo * Add a storage layer for attachments * Add setting for minio and flags for migrate-storage * fix lint * Add test for minio store type on attachments * Apply suggestions from code review Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> * Fix drone * fix test * Fix test * display the error on console * Move minio test to amd64 since minio docker don't support arm64 * don't change unrelated files * Fix lint * Fix build * update go.mod and go.sum * Use github.com/minio/minio-go/v6 * Remove unused function * Upgrade minio to v7 and some other improvements * fix lint * Fix go mod Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Tyler <tystuyfzand@gmail.com>
4 years ago
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
8 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
Change target branch for pull request (#6488) * Adds functionality to change target branch of created pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use const instead of var in JavaScript additions Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Check if branches are equal and if PR already exists before changing target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Make sure to check all commits Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Print error messages for user as error flash message Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Disallow changing target branch of closed or merged pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Resolve conflicts after merge of upstream/master Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Change order of branch select fields Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes duplicate check Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use ctx.Tr for translations Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Recompile JS Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use correct translation namespace Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove redundant if condition Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves most change branch logic into pull service Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Completes comment Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Add Ref to ChangesPayload for logging changed target branches instead of creating a new struct Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Revert changes to go.mod Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Directly use createComment method Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return 404 if pull request is not found. Move written check up Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove variable declaration Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return client errors on change pull request target errors Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return error in commit.HasPreviousCommit Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds blank line Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Test patch before persisting new target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update patch before testing (not working) Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes patch calls when changeing pull request target Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes unneeded check for base name Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves ChangeTargetBranch completely to pull service. Update patch status. Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Set webhook mode after errors were validated Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update PR in one transaction Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Move logic for check if head is equal with branch to pull model Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds missing comment and simplify return Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adjust CreateComment method call Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com>
5 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 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>
7 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>
7 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>
7 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>
7 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>
7 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
8 years ago
Support unicode emojis and remove emojify.js (#11032) * Support unicode emojis and remove emojify.js This PR replaces all use of emojify.js and adds unicode emoji support to various areas of gitea. This works in a few ways: First it adds emoji parsing support into gitea itself. This allows us to * Render emojis from valid alias (:smile:) * Detect unicode emojis and let us put them in their own class with proper aria-labels and styling * Easily allow for custom "emoji" * Support all emoji rendering and features without javascript * Uses plain unicode and lets the system render in appropriate emoji font * Doesn't leave us relying on external sources for updates/fixes/features That same list of emoji is also used to create a json file which replaces the part of emojify.js that populates the emoji search tribute. This file is about 35KB with GZIP turned on and I've set it to load after the page renders to not hinder page load time (and this removes loading emojify.js also) For custom "emoji" it uses a pretty simple scheme of just looking for /emojis/img/name.png where name is something a user has put in the "allowed reactions" setting we already have. The gitea reaction that was previously hard coded into a forked copy of emojify.js is included and works as a custom reaction under this method. The emoji data sourced here is from https://github.com/github/gemoji which is the gem library Github uses for their emoji rendering (and a data source for other sites). So we should be able to easily render any emoji and :alias: that Github can, removing any errors from migrated content. They also update it as well, so we can sync when there are new unicode emoji lists released. I've included a slimmed down and slightly modified forked copy of https://github.com/knq/emoji to make up our own emoji module. The code is pretty straight forward and again allows us to have a lot of flexibility in what happens. I had seen a few comments about performance in some of the other threads if we render this ourselves, but there doesn't seem to be any issue here. In a test it can parse, convert, and render 1,000 emojis inside of a large markdown table in about 100ms on my laptop (which is many more emojis than will ever be in any normal issue). This also prevents any flickering and other weirdness from using javascript to render some things while using go for others. Not included here are image fall back URLS. I don't really think they are necessary for anything new being written in 2020. However, managing the emoji ourselves would allow us to add these as a feature later on if it seems necessary. Fixes: https://github.com/go-gitea/gitea/issues/9182 Fixes: https://github.com/go-gitea/gitea/issues/8974 Fixes: https://github.com/go-gitea/gitea/issues/8953 Fixes: https://github.com/go-gitea/gitea/issues/6628 Fixes: https://github.com/go-gitea/gitea/issues/5130 * add new shared function emojiHTML * don't increase emoji size in issue title * Update templates/repo/issue/view_content/add_reaction.tmpl Co-Authored-By: 6543 <6543@obermui.de> * Support for emoji rendering in various templates * Render code and review comments as they should be * Better way to handle mail subjects * insert unicode from tribute selection * Add template helper for plain text when needed * Use existing replace function I forgot about * Don't include emoji greater than Unicode Version 12 Only include emoji and aliases in JSON * Update build/generate-emoji.go * Tweak regex slightly to really match everything including random invisible characters. Run tests for every emoji we have * final updates * code review * code review * hard code gitea custom emoji to match previous behavior * Update .eslintrc Co-Authored-By: silverwind <me@silverwind.io> * disable preempt Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Pull request review/approval and comment on code (#3748) * Initial ui components for pull request review * Add Review Add IssueComment types Signed-off-by: Jonas Franz <info@jonasfranz.software> (cherry picked from commit 2b4daab) Signed-off-by: Jonas Franz <info@jonasfranz.software> * Replace ReviewComment with Content Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add load functions Add ReviewID to findComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add create review comment implementation Add migration for review Other small changes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Simplified create and find functions for review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved "Pending" to first position Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add GetCurrentReview to simplify fetching current review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Preview for listing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Move new comment form to its own file Signed-off-by: Jonas Franz <info@jonasfranz.software> * Implement Review form Show Review comments on comment stream Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for single comments Showing buttons in context Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add pending tag to pending review comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add unit tests for Review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fetch all review ids at once Add unit tests Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improved comment rendering in "Files" view by adding Comments to DiffLine Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for invalidating comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Switched back to code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved review migration from v64 to v65 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Rebuild css Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improve translations Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests by updating fixtures and updating outdated test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Comments will be shown at the right place now Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for deleting CodeComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems caused by files in subdirectories Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for showing code comments of reviews in conversation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for "Show/Hide outdated" Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for new webhooks Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update comparison Signed-off-by: Jonas Franz <info@jonasfranz.software> * Resolve conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Minor UI improvements * update code.gitea.io/git * Fix ui bug reported by @lunny causing wrong position of add button Add functionality to "Cancel" button Add scale effects to add button Hide "Cancel" button for existing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Prepare solving conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show add button only if no comments already exist for the line Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing vendor files Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if reviewer is nil Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show forms only to users who are logged in Signed-off-by: Jonas Franz <info@jonasfranz.software> * Revert "Show forms only to users who are logged in" This reverts commit c083682 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Save patch in comment Render patch for code comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add link to comment in code Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add reply form to comment list Show forms only to signed in users Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add 'Reply' as translatable Add CODE_COMMENT_LINES setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems introduced by checking for singed in user Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add v70 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update generated stylesheet Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix preview Beginn with new review comment patch system Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add new algo to generate diff for line range Remove old algo used for cutting big diffs (it was very buggy) * Add documentation and example for CutDiffAroundLine * Fix example of CutDiffAroundLine * Fix some comment UI rendering bugs * Add code comment edit mode * Send notifications / actions to users until review gets published Fix diff generation bug Fix wrong hashtag * Fix vet errors * Send notifications also for single comments * Fix some notification bugs, fix link * Fix: add comment icon is only shown on code lines * Add lint comment * Add unit tests for git diff * Add more error messages * Regenerated css Signed-off-by: Jonas Franz <info@jonasfranz.software> * fmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Regenerated CSS with latest less version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by updating comment type to new ID Signed-off-by: Jonas Franz <info@jonasfranz.software> * Introducing CodeComments as type for map[string]map[int64][]*Comment Other minor code improvements Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix data-tab issues Signed-off-by: Jonas Franz <info@jonasfranz.software> * Remove unnecessary change Signed-off-by: Jonas Franz <info@jonasfranz.software> * refactored checkForInvalidation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Append comments instead of setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * Use HeadRepo instead of BaseRepo Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update migration Signed-off-by: Jonas Franz <info@jonasfranz.de> * Regenerated CSS Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add copyright Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update index.css Signed-off-by: Jonas Franz <info@jonasfranz.software>
6 years ago
Pull request review/approval and comment on code (#3748) * Initial ui components for pull request review * Add Review Add IssueComment types Signed-off-by: Jonas Franz <info@jonasfranz.software> (cherry picked from commit 2b4daab) Signed-off-by: Jonas Franz <info@jonasfranz.software> * Replace ReviewComment with Content Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add load functions Add ReviewID to findComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add create review comment implementation Add migration for review Other small changes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Simplified create and find functions for review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved "Pending" to first position Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add GetCurrentReview to simplify fetching current review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Preview for listing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Move new comment form to its own file Signed-off-by: Jonas Franz <info@jonasfranz.software> * Implement Review form Show Review comments on comment stream Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for single comments Showing buttons in context Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add pending tag to pending review comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add unit tests for Review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fetch all review ids at once Add unit tests Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improved comment rendering in "Files" view by adding Comments to DiffLine Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for invalidating comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Switched back to code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved review migration from v64 to v65 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Rebuild css Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improve translations Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests by updating fixtures and updating outdated test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Comments will be shown at the right place now Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for deleting CodeComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems caused by files in subdirectories Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for showing code comments of reviews in conversation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for "Show/Hide outdated" Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for new webhooks Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update comparison Signed-off-by: Jonas Franz <info@jonasfranz.software> * Resolve conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Minor UI improvements * update code.gitea.io/git * Fix ui bug reported by @lunny causing wrong position of add button Add functionality to "Cancel" button Add scale effects to add button Hide "Cancel" button for existing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Prepare solving conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show add button only if no comments already exist for the line Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing vendor files Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if reviewer is nil Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show forms only to users who are logged in Signed-off-by: Jonas Franz <info@jonasfranz.software> * Revert "Show forms only to users who are logged in" This reverts commit c083682 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Save patch in comment Render patch for code comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add link to comment in code Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add reply form to comment list Show forms only to signed in users Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add 'Reply' as translatable Add CODE_COMMENT_LINES setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems introduced by checking for singed in user Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add v70 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update generated stylesheet Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix preview Beginn with new review comment patch system Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add new algo to generate diff for line range Remove old algo used for cutting big diffs (it was very buggy) * Add documentation and example for CutDiffAroundLine * Fix example of CutDiffAroundLine * Fix some comment UI rendering bugs * Add code comment edit mode * Send notifications / actions to users until review gets published Fix diff generation bug Fix wrong hashtag * Fix vet errors * Send notifications also for single comments * Fix some notification bugs, fix link * Fix: add comment icon is only shown on code lines * Add lint comment * Add unit tests for git diff * Add more error messages * Regenerated css Signed-off-by: Jonas Franz <info@jonasfranz.software> * fmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Regenerated CSS with latest less version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by updating comment type to new ID Signed-off-by: Jonas Franz <info@jonasfranz.software> * Introducing CodeComments as type for map[string]map[int64][]*Comment Other minor code improvements Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix data-tab issues Signed-off-by: Jonas Franz <info@jonasfranz.software> * Remove unnecessary change Signed-off-by: Jonas Franz <info@jonasfranz.software> * refactored checkForInvalidation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Append comments instead of setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * Use HeadRepo instead of BaseRepo Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update migration Signed-off-by: Jonas Franz <info@jonasfranz.de> * Regenerated CSS Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add copyright Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update index.css Signed-off-by: Jonas Franz <info@jonasfranz.software>
6 years ago
Pull request review/approval and comment on code (#3748) * Initial ui components for pull request review * Add Review Add IssueComment types Signed-off-by: Jonas Franz <info@jonasfranz.software> (cherry picked from commit 2b4daab) Signed-off-by: Jonas Franz <info@jonasfranz.software> * Replace ReviewComment with Content Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add load functions Add ReviewID to findComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add create review comment implementation Add migration for review Other small changes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Simplified create and find functions for review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved "Pending" to first position Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add GetCurrentReview to simplify fetching current review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Preview for listing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Move new comment form to its own file Signed-off-by: Jonas Franz <info@jonasfranz.software> * Implement Review form Show Review comments on comment stream Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for single comments Showing buttons in context Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add pending tag to pending review comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add unit tests for Review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fetch all review ids at once Add unit tests Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improved comment rendering in "Files" view by adding Comments to DiffLine Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for invalidating comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Switched back to code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved review migration from v64 to v65 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Rebuild css Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improve translations Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests by updating fixtures and updating outdated test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Comments will be shown at the right place now Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for deleting CodeComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems caused by files in subdirectories Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for showing code comments of reviews in conversation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for "Show/Hide outdated" Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for new webhooks Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update comparison Signed-off-by: Jonas Franz <info@jonasfranz.software> * Resolve conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Minor UI improvements * update code.gitea.io/git * Fix ui bug reported by @lunny causing wrong position of add button Add functionality to "Cancel" button Add scale effects to add button Hide "Cancel" button for existing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Prepare solving conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show add button only if no comments already exist for the line Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing vendor files Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if reviewer is nil Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show forms only to users who are logged in Signed-off-by: Jonas Franz <info@jonasfranz.software> * Revert "Show forms only to users who are logged in" This reverts commit c083682 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Save patch in comment Render patch for code comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add link to comment in code Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add reply form to comment list Show forms only to signed in users Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add 'Reply' as translatable Add CODE_COMMENT_LINES setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems introduced by checking for singed in user Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add v70 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update generated stylesheet Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix preview Beginn with new review comment patch system Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add new algo to generate diff for line range Remove old algo used for cutting big diffs (it was very buggy) * Add documentation and example for CutDiffAroundLine * Fix example of CutDiffAroundLine * Fix some comment UI rendering bugs * Add code comment edit mode * Send notifications / actions to users until review gets published Fix diff generation bug Fix wrong hashtag * Fix vet errors * Send notifications also for single comments * Fix some notification bugs, fix link * Fix: add comment icon is only shown on code lines * Add lint comment * Add unit tests for git diff * Add more error messages * Regenerated css Signed-off-by: Jonas Franz <info@jonasfranz.software> * fmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Regenerated CSS with latest less version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by updating comment type to new ID Signed-off-by: Jonas Franz <info@jonasfranz.software> * Introducing CodeComments as type for map[string]map[int64][]*Comment Other minor code improvements Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix data-tab issues Signed-off-by: Jonas Franz <info@jonasfranz.software> * Remove unnecessary change Signed-off-by: Jonas Franz <info@jonasfranz.software> * refactored checkForInvalidation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Append comments instead of setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * Use HeadRepo instead of BaseRepo Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update migration Signed-off-by: Jonas Franz <info@jonasfranz.de> * Regenerated CSS Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add copyright Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update index.css Signed-off-by: Jonas Franz <info@jonasfranz.software>
6 years ago
Change target branch for pull request (#6488) * Adds functionality to change target branch of created pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use const instead of var in JavaScript additions Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Check if branches are equal and if PR already exists before changing target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Make sure to check all commits Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Print error messages for user as error flash message Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Disallow changing target branch of closed or merged pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Resolve conflicts after merge of upstream/master Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Change order of branch select fields Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes duplicate check Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use ctx.Tr for translations Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Recompile JS Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use correct translation namespace Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove redundant if condition Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves most change branch logic into pull service Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Completes comment Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Add Ref to ChangesPayload for logging changed target branches instead of creating a new struct Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Revert changes to go.mod Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Directly use createComment method Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return 404 if pull request is not found. Move written check up Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove variable declaration Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return client errors on change pull request target errors Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return error in commit.HasPreviousCommit Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds blank line Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Test patch before persisting new target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update patch before testing (not working) Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes patch calls when changeing pull request target Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes unneeded check for base name Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves ChangeTargetBranch completely to pull service. Update patch status. Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Set webhook mode after errors were validated Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update PR in one transaction Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Move logic for check if head is equal with branch to pull model Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds missing comment and simplify return Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adjust CreateComment method call Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com>
5 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
[Enhancement] Allow admin to merge pr with protected file changes (#12078) * [Enhancement] Allow admin to merge pr with protected file changes As tilte, show protected message in diff page and merge box. Signed-off-by: a1012112796 <1012112796@qq.com> * remove unused ver * Update options/locale/locale_en-US.ini Co-authored-by: Cirno the Strongest <1447794+CirnoT@users.noreply.github.com> * Add TrN * Apply suggestions from code review * fix lint * Update options/locale/locale_en-US.ini Co-authored-by: zeripath <art27@cantab.net> * Apply suggestions from code review * move pr proteced files check to TestPatch * Call TestPatch when protected branches settings changed * Apply review suggestion @CirnoT * move to service @lunny * slightly restructure routers/private/hook.go Adds a lot of comments and simplifies the logic Signed-off-by: Andrew Thornton <art27@cantab.net> * placate lint Signed-off-by: Andrew Thornton <art27@cantab.net> * skip duplicate protected files check * fix check logic * slight refactor of TestPatch Signed-off-by: Andrew Thornton <art27@cantab.net> * When checking for protected files changes in TestPatch use the temporary repository Signed-off-by: Andrew Thornton <art27@cantab.net> * fix introduced issue with hook Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove the check on PR index being greater than 0 as it unnecessary Signed-off-by: Andrew Thornton <art27@cantab.net> Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: Cirno the Strongest <1447794+CirnoT@users.noreply.github.com> Co-authored-by: zeripath <art27@cantab.net> Co-authored-by: techknowlogick <techknowlogick@gitea.io>
4 years ago
Add configurable Trust Models (#11712) * Add configurable Trust Models Gitea's default signature verification model differs from GitHub. GitHub uses signatures to verify that the committer is who they say they are - meaning that when GitHub makes a signed commit it must be the committer. The GitHub model prevents re-publishing of commits after revocation of a key and prevents re-signing of other people's commits to create a completely trusted repository signed by one key or a set of trusted keys. The default behaviour of Gitea in contrast is to always display the avatar and information related to a signature. This allows signatures to be decoupled from the committer. That being said, allowing arbitary users to present other peoples commits as theirs is not necessarily desired therefore we have a trust model whereby signatures from collaborators are marked trusted, signatures matching the commit line are marked untrusted and signatures that match a user in the db but not the committer line are marked unmatched. The problem with this model is that this conflicts with Github therefore we need to provide an option to allow users to choose the Github model should they wish to. Signed-off-by: Andrew Thornton <art27@cantab.net> * Adjust locale strings Signed-off-by: Andrew Thornton <art27@cantab.net> * as per @6543 Co-authored-by: 6543 <6543@obermui.de> * Update models/gpg_key.go * Add migration for repository Signed-off-by: Andrew Thornton <art27@cantab.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
4 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>
7 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>
7 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>
7 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
Add a storage layer for attachments (#11387) * Add a storage layer for attachments * Fix some bug * fix test * Fix copyright head and lint * Fix bug * Add setting for minio and flags for migrate-storage * Add documents * fix lint * Add test for minio store type on attachments * fix test * fix test * Apply suggestions from code review Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> * Add warning when storage migrated successfully * Fix drone * fix test * rebase * Fix test * display the error on console * Move minio test to amd64 since minio docker don't support arm64 * refactor the codes * add trace * Fix test * remove log on xorm * Fi download bug * Add a storage layer for attachments * Add setting for minio and flags for migrate-storage * fix lint * Add test for minio store type on attachments * Apply suggestions from code review Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> * Fix drone * fix test * Fix test * display the error on console * Move minio test to amd64 since minio docker don't support arm64 * refactor the codes * add trace * Fix test * Add URL function to serve attachments directly from S3/Minio * Add ability to enable/disable redirection in attachment configuration * Fix typo * Add a storage layer for attachments * Add setting for minio and flags for migrate-storage * fix lint * Add test for minio store type on attachments * Apply suggestions from code review Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> * Fix drone * fix test * Fix test * display the error on console * Move minio test to amd64 since minio docker don't support arm64 * don't change unrelated files * Fix lint * Fix build * update go.mod and go.sum * Use github.com/minio/minio-go/v6 * Remove unused function * Upgrade minio to v7 and some other improvements * fix lint * Fix go mod Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Tyler <tystuyfzand@gmail.com>
4 years ago
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
8 years ago
9 years ago
9 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Pull request review/approval and comment on code (#3748) * Initial ui components for pull request review * Add Review Add IssueComment types Signed-off-by: Jonas Franz <info@jonasfranz.software> (cherry picked from commit 2b4daab) Signed-off-by: Jonas Franz <info@jonasfranz.software> * Replace ReviewComment with Content Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add load functions Add ReviewID to findComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add create review comment implementation Add migration for review Other small changes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Simplified create and find functions for review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved "Pending" to first position Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add GetCurrentReview to simplify fetching current review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Preview for listing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Move new comment form to its own file Signed-off-by: Jonas Franz <info@jonasfranz.software> * Implement Review form Show Review comments on comment stream Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for single comments Showing buttons in context Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add pending tag to pending review comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add unit tests for Review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fetch all review ids at once Add unit tests Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improved comment rendering in "Files" view by adding Comments to DiffLine Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for invalidating comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Switched back to code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved review migration from v64 to v65 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Rebuild css Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improve translations Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests by updating fixtures and updating outdated test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Comments will be shown at the right place now Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for deleting CodeComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems caused by files in subdirectories Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for showing code comments of reviews in conversation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for "Show/Hide outdated" Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for new webhooks Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update comparison Signed-off-by: Jonas Franz <info@jonasfranz.software> * Resolve conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Minor UI improvements * update code.gitea.io/git * Fix ui bug reported by @lunny causing wrong position of add button Add functionality to "Cancel" button Add scale effects to add button Hide "Cancel" button for existing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Prepare solving conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show add button only if no comments already exist for the line Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing vendor files Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if reviewer is nil Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show forms only to users who are logged in Signed-off-by: Jonas Franz <info@jonasfranz.software> * Revert "Show forms only to users who are logged in" This reverts commit c083682 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Save patch in comment Render patch for code comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add link to comment in code Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add reply form to comment list Show forms only to signed in users Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add 'Reply' as translatable Add CODE_COMMENT_LINES setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems introduced by checking for singed in user Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add v70 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update generated stylesheet Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix preview Beginn with new review comment patch system Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add new algo to generate diff for line range Remove old algo used for cutting big diffs (it was very buggy) * Add documentation and example for CutDiffAroundLine * Fix example of CutDiffAroundLine * Fix some comment UI rendering bugs * Add code comment edit mode * Send notifications / actions to users until review gets published Fix diff generation bug Fix wrong hashtag * Fix vet errors * Send notifications also for single comments * Fix some notification bugs, fix link * Fix: add comment icon is only shown on code lines * Add lint comment * Add unit tests for git diff * Add more error messages * Regenerated css Signed-off-by: Jonas Franz <info@jonasfranz.software> * fmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Regenerated CSS with latest less version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by updating comment type to new ID Signed-off-by: Jonas Franz <info@jonasfranz.software> * Introducing CodeComments as type for map[string]map[int64][]*Comment Other minor code improvements Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix data-tab issues Signed-off-by: Jonas Franz <info@jonasfranz.software> * Remove unnecessary change Signed-off-by: Jonas Franz <info@jonasfranz.software> * refactored checkForInvalidation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Append comments instead of setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * Use HeadRepo instead of BaseRepo Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update migration Signed-off-by: Jonas Franz <info@jonasfranz.de> * Regenerated CSS Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add copyright Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update index.css Signed-off-by: Jonas Franz <info@jonasfranz.software>
6 years ago
Pull request review/approval and comment on code (#3748) * Initial ui components for pull request review * Add Review Add IssueComment types Signed-off-by: Jonas Franz <info@jonasfranz.software> (cherry picked from commit 2b4daab) Signed-off-by: Jonas Franz <info@jonasfranz.software> * Replace ReviewComment with Content Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add load functions Add ReviewID to findComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add create review comment implementation Add migration for review Other small changes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Simplified create and find functions for review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved "Pending" to first position Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add GetCurrentReview to simplify fetching current review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Preview for listing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Move new comment form to its own file Signed-off-by: Jonas Franz <info@jonasfranz.software> * Implement Review form Show Review comments on comment stream Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for single comments Showing buttons in context Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add pending tag to pending review comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add unit tests for Review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fetch all review ids at once Add unit tests Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improved comment rendering in "Files" view by adding Comments to DiffLine Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for invalidating comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Switched back to code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved review migration from v64 to v65 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Rebuild css Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improve translations Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests by updating fixtures and updating outdated test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Comments will be shown at the right place now Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for deleting CodeComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems caused by files in subdirectories Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for showing code comments of reviews in conversation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for "Show/Hide outdated" Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for new webhooks Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update comparison Signed-off-by: Jonas Franz <info@jonasfranz.software> * Resolve conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Minor UI improvements * update code.gitea.io/git * Fix ui bug reported by @lunny causing wrong position of add button Add functionality to "Cancel" button Add scale effects to add button Hide "Cancel" button for existing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Prepare solving conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show add button only if no comments already exist for the line Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing vendor files Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if reviewer is nil Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show forms only to users who are logged in Signed-off-by: Jonas Franz <info@jonasfranz.software> * Revert "Show forms only to users who are logged in" This reverts commit c083682 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Save patch in comment Render patch for code comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add link to comment in code Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add reply form to comment list Show forms only to signed in users Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add 'Reply' as translatable Add CODE_COMMENT_LINES setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems introduced by checking for singed in user Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add v70 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update generated stylesheet Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix preview Beginn with new review comment patch system Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add new algo to generate diff for line range Remove old algo used for cutting big diffs (it was very buggy) * Add documentation and example for CutDiffAroundLine * Fix example of CutDiffAroundLine * Fix some comment UI rendering bugs * Add code comment edit mode * Send notifications / actions to users until review gets published Fix diff generation bug Fix wrong hashtag * Fix vet errors * Send notifications also for single comments * Fix some notification bugs, fix link * Fix: add comment icon is only shown on code lines * Add lint comment * Add unit tests for git diff * Add more error messages * Regenerated css Signed-off-by: Jonas Franz <info@jonasfranz.software> * fmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Regenerated CSS with latest less version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by updating comment type to new ID Signed-off-by: Jonas Franz <info@jonasfranz.software> * Introducing CodeComments as type for map[string]map[int64][]*Comment Other minor code improvements Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix data-tab issues Signed-off-by: Jonas Franz <info@jonasfranz.software> * Remove unnecessary change Signed-off-by: Jonas Franz <info@jonasfranz.software> * refactored checkForInvalidation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Append comments instead of setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * Use HeadRepo instead of BaseRepo Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update migration Signed-off-by: Jonas Franz <info@jonasfranz.de> * Regenerated CSS Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add copyright Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update index.css Signed-off-by: Jonas Franz <info@jonasfranz.software>
6 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package repo
  6. import (
  7. "bytes"
  8. "errors"
  9. "fmt"
  10. "io/ioutil"
  11. "net/http"
  12. "path"
  13. "strconv"
  14. "strings"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/context"
  18. "code.gitea.io/gitea/modules/convert"
  19. auth "code.gitea.io/gitea/modules/forms"
  20. "code.gitea.io/gitea/modules/git"
  21. issue_indexer "code.gitea.io/gitea/modules/indexer/issues"
  22. "code.gitea.io/gitea/modules/log"
  23. "code.gitea.io/gitea/modules/markup"
  24. "code.gitea.io/gitea/modules/markup/markdown"
  25. "code.gitea.io/gitea/modules/setting"
  26. api "code.gitea.io/gitea/modules/structs"
  27. "code.gitea.io/gitea/modules/upload"
  28. "code.gitea.io/gitea/modules/util"
  29. "code.gitea.io/gitea/modules/web"
  30. comment_service "code.gitea.io/gitea/services/comments"
  31. issue_service "code.gitea.io/gitea/services/issue"
  32. pull_service "code.gitea.io/gitea/services/pull"
  33. "github.com/unknwon/com"
  34. )
  35. const (
  36. tplAttachment base.TplName = "repo/issue/view_content/attachments"
  37. tplIssues base.TplName = "repo/issue/list"
  38. tplIssueNew base.TplName = "repo/issue/new"
  39. tplIssueChoose base.TplName = "repo/issue/choose"
  40. tplIssueView base.TplName = "repo/issue/view"
  41. tplReactions base.TplName = "repo/issue/view_content/reactions"
  42. issueTemplateKey = "IssueTemplate"
  43. issueTemplateTitleKey = "IssueTemplateTitle"
  44. )
  45. var (
  46. // ErrTooManyFiles upload too many files
  47. ErrTooManyFiles = errors.New("Maximum number of files to upload exceeded")
  48. // IssueTemplateCandidates issue templates
  49. IssueTemplateCandidates = []string{
  50. "ISSUE_TEMPLATE.md",
  51. "issue_template.md",
  52. ".gitea/ISSUE_TEMPLATE.md",
  53. ".gitea/issue_template.md",
  54. ".github/ISSUE_TEMPLATE.md",
  55. ".github/issue_template.md",
  56. }
  57. )
  58. // MustAllowUserComment checks to make sure if an issue is locked.
  59. // If locked and user has permissions to write to the repository,
  60. // then the comment is allowed, else it is blocked
  61. func MustAllowUserComment(ctx *context.Context) {
  62. issue := GetActionIssue(ctx)
  63. if ctx.Written() {
  64. return
  65. }
  66. if issue.IsLocked && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) && !ctx.User.IsAdmin {
  67. ctx.Flash.Error(ctx.Tr("repo.issues.comment_on_locked"))
  68. ctx.Redirect(issue.HTMLURL())
  69. return
  70. }
  71. }
  72. // MustEnableIssues check if repository enable internal issues
  73. func MustEnableIssues(ctx *context.Context) {
  74. if !ctx.Repo.CanRead(models.UnitTypeIssues) &&
  75. !ctx.Repo.CanRead(models.UnitTypeExternalTracker) {
  76. ctx.NotFound("MustEnableIssues", nil)
  77. return
  78. }
  79. unit, err := ctx.Repo.Repository.GetUnit(models.UnitTypeExternalTracker)
  80. if err == nil {
  81. ctx.Redirect(unit.ExternalTrackerConfig().ExternalTrackerURL)
  82. return
  83. }
  84. }
  85. // MustAllowPulls check if repository enable pull requests and user have right to do that
  86. func MustAllowPulls(ctx *context.Context) {
  87. if !ctx.Repo.Repository.CanEnablePulls() || !ctx.Repo.CanRead(models.UnitTypePullRequests) {
  88. ctx.NotFound("MustAllowPulls", nil)
  89. return
  90. }
  91. // User can send pull request if owns a forked repository.
  92. if ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID) {
  93. ctx.Repo.PullRequest.Allowed = true
  94. ctx.Repo.PullRequest.HeadInfo = ctx.User.Name + ":" + ctx.Repo.BranchName
  95. }
  96. }
  97. func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption util.OptionalBool) {
  98. var err error
  99. viewType := ctx.Query("type")
  100. sortType := ctx.Query("sort")
  101. types := []string{"all", "your_repositories", "assigned", "created_by", "mentioned", "review_requested"}
  102. if !util.IsStringInSlice(viewType, types, true) {
  103. viewType = "all"
  104. }
  105. var (
  106. assigneeID = ctx.QueryInt64("assignee")
  107. posterID int64
  108. mentionedID int64
  109. reviewRequestedID int64
  110. forceEmpty bool
  111. )
  112. if ctx.IsSigned {
  113. switch viewType {
  114. case "created_by":
  115. posterID = ctx.User.ID
  116. case "mentioned":
  117. mentionedID = ctx.User.ID
  118. case "assigned":
  119. assigneeID = ctx.User.ID
  120. case "review_requested":
  121. reviewRequestedID = ctx.User.ID
  122. }
  123. }
  124. repo := ctx.Repo.Repository
  125. var labelIDs []int64
  126. selectLabels := ctx.Query("labels")
  127. if len(selectLabels) > 0 && selectLabels != "0" {
  128. labelIDs, err = base.StringsToInt64s(strings.Split(selectLabels, ","))
  129. if err != nil {
  130. ctx.ServerError("StringsToInt64s", err)
  131. return
  132. }
  133. }
  134. keyword := strings.Trim(ctx.Query("q"), " ")
  135. if bytes.Contains([]byte(keyword), []byte{0x00}) {
  136. keyword = ""
  137. }
  138. var issueIDs []int64
  139. if len(keyword) > 0 {
  140. issueIDs, err = issue_indexer.SearchIssuesByKeyword([]int64{repo.ID}, keyword)
  141. if err != nil {
  142. ctx.ServerError("issueIndexer.Search", err)
  143. return
  144. }
  145. if len(issueIDs) == 0 {
  146. forceEmpty = true
  147. }
  148. }
  149. var issueStats *models.IssueStats
  150. if forceEmpty {
  151. issueStats = &models.IssueStats{}
  152. } else {
  153. issueStats, err = models.GetIssueStats(&models.IssueStatsOptions{
  154. RepoID: repo.ID,
  155. Labels: selectLabels,
  156. MilestoneID: milestoneID,
  157. AssigneeID: assigneeID,
  158. MentionedID: mentionedID,
  159. PosterID: posterID,
  160. ReviewRequestedID: reviewRequestedID,
  161. IsPull: isPullOption,
  162. IssueIDs: issueIDs,
  163. })
  164. if err != nil {
  165. ctx.ServerError("GetIssueStats", err)
  166. return
  167. }
  168. }
  169. isShowClosed := ctx.Query("state") == "closed"
  170. // if open issues are zero and close don't, use closed as default
  171. if len(ctx.Query("state")) == 0 && issueStats.OpenCount == 0 && issueStats.ClosedCount != 0 {
  172. isShowClosed = true
  173. }
  174. page := ctx.QueryInt("page")
  175. if page <= 1 {
  176. page = 1
  177. }
  178. var total int
  179. if !isShowClosed {
  180. total = int(issueStats.OpenCount)
  181. } else {
  182. total = int(issueStats.ClosedCount)
  183. }
  184. pager := context.NewPagination(total, setting.UI.IssuePagingNum, page, 5)
  185. var mileIDs []int64
  186. if milestoneID > 0 {
  187. mileIDs = []int64{milestoneID}
  188. }
  189. var issues []*models.Issue
  190. if forceEmpty {
  191. issues = []*models.Issue{}
  192. } else {
  193. issues, err = models.Issues(&models.IssuesOptions{
  194. ListOptions: models.ListOptions{
  195. Page: pager.Paginater.Current(),
  196. PageSize: setting.UI.IssuePagingNum,
  197. },
  198. RepoIDs: []int64{repo.ID},
  199. AssigneeID: assigneeID,
  200. PosterID: posterID,
  201. MentionedID: mentionedID,
  202. ReviewRequestedID: reviewRequestedID,
  203. MilestoneIDs: mileIDs,
  204. ProjectID: projectID,
  205. IsClosed: util.OptionalBoolOf(isShowClosed),
  206. IsPull: isPullOption,
  207. LabelIDs: labelIDs,
  208. SortType: sortType,
  209. IssueIDs: issueIDs,
  210. })
  211. if err != nil {
  212. ctx.ServerError("Issues", err)
  213. return
  214. }
  215. }
  216. approvalCounts, err := models.IssueList(issues).GetApprovalCounts()
  217. if err != nil {
  218. ctx.ServerError("ApprovalCounts", err)
  219. return
  220. }
  221. var commitStatus = make(map[int64]*models.CommitStatus, len(issues))
  222. // Get posters.
  223. for i := range issues {
  224. // Check read status
  225. if !ctx.IsSigned {
  226. issues[i].IsRead = true
  227. } else if err = issues[i].GetIsRead(ctx.User.ID); err != nil {
  228. ctx.ServerError("GetIsRead", err)
  229. return
  230. }
  231. if issues[i].IsPull {
  232. if err := issues[i].LoadPullRequest(); err != nil {
  233. ctx.ServerError("LoadPullRequest", err)
  234. return
  235. }
  236. var statuses, _ = pull_service.GetLastCommitStatus(issues[i].PullRequest)
  237. commitStatus[issues[i].PullRequest.ID] = models.CalcCommitStatus(statuses)
  238. }
  239. }
  240. ctx.Data["Issues"] = issues
  241. ctx.Data["CommitStatus"] = commitStatus
  242. // Get assignees.
  243. ctx.Data["Assignees"], err = repo.GetAssignees()
  244. if err != nil {
  245. ctx.ServerError("GetAssignees", err)
  246. return
  247. }
  248. handleTeamMentions(ctx)
  249. if ctx.Written() {
  250. return
  251. }
  252. labels, err := models.GetLabelsByRepoID(repo.ID, "", models.ListOptions{})
  253. if err != nil {
  254. ctx.ServerError("GetLabelsByRepoID", err)
  255. return
  256. }
  257. if repo.Owner.IsOrganization() {
  258. orgLabels, err := models.GetLabelsByOrgID(repo.Owner.ID, ctx.Query("sort"), models.ListOptions{})
  259. if err != nil {
  260. ctx.ServerError("GetLabelsByOrgID", err)
  261. return
  262. }
  263. ctx.Data["OrgLabels"] = orgLabels
  264. labels = append(labels, orgLabels...)
  265. }
  266. for _, l := range labels {
  267. l.LoadSelectedLabelsAfterClick(labelIDs)
  268. }
  269. ctx.Data["Labels"] = labels
  270. ctx.Data["NumLabels"] = len(labels)
  271. if ctx.QueryInt64("assignee") == 0 {
  272. assigneeID = 0 // Reset ID to prevent unexpected selection of assignee.
  273. }
  274. ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] =
  275. issue_service.GetRefEndNamesAndURLs(issues, ctx.Repo.RepoLink)
  276. ctx.Data["ApprovalCounts"] = func(issueID int64, typ string) int64 {
  277. counts, ok := approvalCounts[issueID]
  278. if !ok || len(counts) == 0 {
  279. return 0
  280. }
  281. reviewTyp := models.ReviewTypeApprove
  282. if typ == "reject" {
  283. reviewTyp = models.ReviewTypeReject
  284. } else if typ == "waiting" {
  285. reviewTyp = models.ReviewTypeRequest
  286. }
  287. for _, count := range counts {
  288. if count.Type == reviewTyp {
  289. return count.Count
  290. }
  291. }
  292. return 0
  293. }
  294. ctx.Data["IssueStats"] = issueStats
  295. ctx.Data["SelLabelIDs"] = labelIDs
  296. ctx.Data["SelectLabels"] = selectLabels
  297. ctx.Data["ViewType"] = viewType
  298. ctx.Data["SortType"] = sortType
  299. ctx.Data["MilestoneID"] = milestoneID
  300. ctx.Data["AssigneeID"] = assigneeID
  301. ctx.Data["IsShowClosed"] = isShowClosed
  302. ctx.Data["Keyword"] = keyword
  303. if isShowClosed {
  304. ctx.Data["State"] = "closed"
  305. } else {
  306. ctx.Data["State"] = "open"
  307. }
  308. pager.AddParam(ctx, "q", "Keyword")
  309. pager.AddParam(ctx, "type", "ViewType")
  310. pager.AddParam(ctx, "sort", "SortType")
  311. pager.AddParam(ctx, "state", "State")
  312. pager.AddParam(ctx, "labels", "SelectLabels")
  313. pager.AddParam(ctx, "milestone", "MilestoneID")
  314. pager.AddParam(ctx, "assignee", "AssigneeID")
  315. ctx.Data["Page"] = pager
  316. }
  317. // Issues render issues page
  318. func Issues(ctx *context.Context) {
  319. isPullList := ctx.Params(":type") == "pulls"
  320. if isPullList {
  321. MustAllowPulls(ctx)
  322. if ctx.Written() {
  323. return
  324. }
  325. ctx.Data["Title"] = ctx.Tr("repo.pulls")
  326. ctx.Data["PageIsPullList"] = true
  327. } else {
  328. MustEnableIssues(ctx)
  329. if ctx.Written() {
  330. return
  331. }
  332. ctx.Data["Title"] = ctx.Tr("repo.issues")
  333. ctx.Data["PageIsIssueList"] = true
  334. ctx.Data["NewIssueChooseTemplate"] = len(ctx.IssueTemplatesFromDefaultBranch()) > 0
  335. }
  336. issues(ctx, ctx.QueryInt64("milestone"), ctx.QueryInt64("project"), util.OptionalBoolOf(isPullList))
  337. var err error
  338. // Get milestones
  339. ctx.Data["Milestones"], err = models.GetMilestones(models.GetMilestonesOption{
  340. RepoID: ctx.Repo.Repository.ID,
  341. State: api.StateType(ctx.Query("state")),
  342. })
  343. if err != nil {
  344. ctx.ServerError("GetAllRepoMilestones", err)
  345. return
  346. }
  347. ctx.Data["CanWriteIssuesOrPulls"] = ctx.Repo.CanWriteIssuesOrPulls(isPullList)
  348. ctx.HTML(200, tplIssues)
  349. }
  350. // RetrieveRepoMilestonesAndAssignees find all the milestones and assignees of a repository
  351. func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *models.Repository) {
  352. var err error
  353. ctx.Data["OpenMilestones"], err = models.GetMilestones(models.GetMilestonesOption{
  354. RepoID: repo.ID,
  355. State: api.StateOpen,
  356. })
  357. if err != nil {
  358. ctx.ServerError("GetMilestones", err)
  359. return
  360. }
  361. ctx.Data["ClosedMilestones"], err = models.GetMilestones(models.GetMilestonesOption{
  362. RepoID: repo.ID,
  363. State: api.StateClosed,
  364. })
  365. if err != nil {
  366. ctx.ServerError("GetMilestones", err)
  367. return
  368. }
  369. ctx.Data["Assignees"], err = repo.GetAssignees()
  370. if err != nil {
  371. ctx.ServerError("GetAssignees", err)
  372. return
  373. }
  374. handleTeamMentions(ctx)
  375. if ctx.Written() {
  376. return
  377. }
  378. }
  379. func retrieveProjects(ctx *context.Context, repo *models.Repository) {
  380. var err error
  381. ctx.Data["OpenProjects"], _, err = models.GetProjects(models.ProjectSearchOptions{
  382. RepoID: repo.ID,
  383. Page: -1,
  384. IsClosed: util.OptionalBoolFalse,
  385. Type: models.ProjectTypeRepository,
  386. })
  387. if err != nil {
  388. ctx.ServerError("GetProjects", err)
  389. return
  390. }
  391. ctx.Data["ClosedProjects"], _, err = models.GetProjects(models.ProjectSearchOptions{
  392. RepoID: repo.ID,
  393. Page: -1,
  394. IsClosed: util.OptionalBoolTrue,
  395. Type: models.ProjectTypeRepository,
  396. })
  397. if err != nil {
  398. ctx.ServerError("GetProjects", err)
  399. return
  400. }
  401. }
  402. // repoReviewerSelection items to bee shown
  403. type repoReviewerSelection struct {
  404. IsTeam bool
  405. Team *models.Team
  406. User *models.User
  407. Review *models.Review
  408. CanChange bool
  409. Checked bool
  410. ItemID int64
  411. }
  412. // RetrieveRepoReviewers find all reviewers of a repository
  413. func RetrieveRepoReviewers(ctx *context.Context, repo *models.Repository, issue *models.Issue, canChooseReviewer bool) {
  414. ctx.Data["CanChooseReviewer"] = canChooseReviewer
  415. originalAuthorReviews, err := models.GetReviewersFromOriginalAuthorsByIssueID(issue.ID)
  416. if err != nil {
  417. ctx.ServerError("GetReviewersFromOriginalAuthorsByIssueID", err)
  418. return
  419. }
  420. ctx.Data["OriginalReviews"] = originalAuthorReviews
  421. reviews, err := models.GetReviewersByIssueID(issue.ID)
  422. if err != nil {
  423. ctx.ServerError("GetReviewersByIssueID", err)
  424. return
  425. }
  426. if len(reviews) == 0 && !canChooseReviewer {
  427. return
  428. }
  429. var (
  430. pullReviews []*repoReviewerSelection
  431. reviewersResult []*repoReviewerSelection
  432. teamReviewersResult []*repoReviewerSelection
  433. teamReviewers []*models.Team
  434. reviewers []*models.User
  435. )
  436. if canChooseReviewer {
  437. posterID := issue.PosterID
  438. if issue.OriginalAuthorID > 0 {
  439. posterID = 0
  440. }
  441. reviewers, err = repo.GetReviewers(ctx.User.ID, posterID)
  442. if err != nil {
  443. ctx.ServerError("GetReviewers", err)
  444. return
  445. }
  446. teamReviewers, err = repo.GetReviewerTeams()
  447. if err != nil {
  448. ctx.ServerError("GetReviewerTeams", err)
  449. return
  450. }
  451. if len(reviewers) > 0 {
  452. reviewersResult = make([]*repoReviewerSelection, 0, len(reviewers))
  453. }
  454. if len(teamReviewers) > 0 {
  455. teamReviewersResult = make([]*repoReviewerSelection, 0, len(teamReviewers))
  456. }
  457. }
  458. pullReviews = make([]*repoReviewerSelection, 0, len(reviews))
  459. for _, review := range reviews {
  460. tmp := &repoReviewerSelection{
  461. Checked: review.Type == models.ReviewTypeRequest,
  462. Review: review,
  463. ItemID: review.ReviewerID,
  464. }
  465. if review.ReviewerTeamID > 0 {
  466. tmp.IsTeam = true
  467. tmp.ItemID = -review.ReviewerTeamID
  468. }
  469. if ctx.Repo.IsAdmin() {
  470. // Admin can dismiss or re-request any review requests
  471. tmp.CanChange = true
  472. } else if ctx.User != nil && ctx.User.ID == review.ReviewerID && review.Type == models.ReviewTypeRequest {
  473. // A user can refuse review requests
  474. tmp.CanChange = true
  475. } else if (canChooseReviewer || (ctx.User != nil && ctx.User.ID == issue.PosterID)) && review.Type != models.ReviewTypeRequest &&
  476. ctx.User.ID != review.ReviewerID {
  477. // The poster of the PR, a manager, or official reviewers can re-request review from other reviewers
  478. tmp.CanChange = true
  479. }
  480. pullReviews = append(pullReviews, tmp)
  481. if canChooseReviewer {
  482. if tmp.IsTeam {
  483. teamReviewersResult = append(teamReviewersResult, tmp)
  484. } else {
  485. reviewersResult = append(reviewersResult, tmp)
  486. }
  487. }
  488. }
  489. if len(pullReviews) > 0 {
  490. // Drop all non-existing users and teams from the reviews
  491. currentPullReviewers := make([]*repoReviewerSelection, 0, len(pullReviews))
  492. for _, item := range pullReviews {
  493. if item.Review.ReviewerID > 0 {
  494. if err = item.Review.LoadReviewer(); err != nil {
  495. if models.IsErrUserNotExist(err) {
  496. continue
  497. }
  498. ctx.ServerError("LoadReviewer", err)
  499. return
  500. }
  501. item.User = item.Review.Reviewer
  502. } else if item.Review.ReviewerTeamID > 0 {
  503. if err = item.Review.LoadReviewerTeam(); err != nil {
  504. if models.IsErrTeamNotExist(err) {
  505. continue
  506. }
  507. ctx.ServerError("LoadReviewerTeam", err)
  508. return
  509. }
  510. item.Team = item.Review.ReviewerTeam
  511. } else {
  512. continue
  513. }
  514. currentPullReviewers = append(currentPullReviewers, item)
  515. }
  516. ctx.Data["PullReviewers"] = currentPullReviewers
  517. }
  518. if canChooseReviewer && reviewersResult != nil {
  519. preadded := len(reviewersResult)
  520. for _, reviewer := range reviewers {
  521. found := false
  522. reviewAddLoop:
  523. for _, tmp := range reviewersResult[:preadded] {
  524. if tmp.ItemID == reviewer.ID {
  525. tmp.User = reviewer
  526. found = true
  527. break reviewAddLoop
  528. }
  529. }
  530. if found {
  531. continue
  532. }
  533. reviewersResult = append(reviewersResult, &repoReviewerSelection{
  534. IsTeam: false,
  535. CanChange: true,
  536. User: reviewer,
  537. ItemID: reviewer.ID,
  538. })
  539. }
  540. ctx.Data["Reviewers"] = reviewersResult
  541. }
  542. if canChooseReviewer && teamReviewersResult != nil {
  543. preadded := len(teamReviewersResult)
  544. for _, team := range teamReviewers {
  545. found := false
  546. teamReviewAddLoop:
  547. for _, tmp := range teamReviewersResult[:preadded] {
  548. if tmp.ItemID == -team.ID {
  549. tmp.Team = team
  550. found = true
  551. break teamReviewAddLoop
  552. }
  553. }
  554. if found {
  555. continue
  556. }
  557. teamReviewersResult = append(teamReviewersResult, &repoReviewerSelection{
  558. IsTeam: true,
  559. CanChange: true,
  560. Team: team,
  561. ItemID: -team.ID,
  562. })
  563. }
  564. ctx.Data["TeamReviewers"] = teamReviewersResult
  565. }
  566. }
  567. // RetrieveRepoMetas find all the meta information of a repository
  568. func RetrieveRepoMetas(ctx *context.Context, repo *models.Repository, isPull bool) []*models.Label {
  569. if !ctx.Repo.CanWriteIssuesOrPulls(isPull) {
  570. return nil
  571. }
  572. labels, err := models.GetLabelsByRepoID(repo.ID, "", models.ListOptions{})
  573. if err != nil {
  574. ctx.ServerError("GetLabelsByRepoID", err)
  575. return nil
  576. }
  577. ctx.Data["Labels"] = labels
  578. if repo.Owner.IsOrganization() {
  579. orgLabels, err := models.GetLabelsByOrgID(repo.Owner.ID, ctx.Query("sort"), models.ListOptions{})
  580. if err != nil {
  581. return nil
  582. }
  583. ctx.Data["OrgLabels"] = orgLabels
  584. labels = append(labels, orgLabels...)
  585. }
  586. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  587. if ctx.Written() {
  588. return nil
  589. }
  590. retrieveProjects(ctx, repo)
  591. if ctx.Written() {
  592. return nil
  593. }
  594. brs, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  595. if err != nil {
  596. ctx.ServerError("GetBranches", err)
  597. return nil
  598. }
  599. ctx.Data["Branches"] = brs
  600. // Contains true if the user can create issue dependencies
  601. ctx.Data["CanCreateIssueDependencies"] = ctx.Repo.CanCreateIssueDependencies(ctx.User, isPull)
  602. return labels
  603. }
  604. func getFileContentFromDefaultBranch(ctx *context.Context, filename string) (string, bool) {
  605. var bytes []byte
  606. if ctx.Repo.Commit == nil {
  607. var err error
  608. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  609. if err != nil {
  610. return "", false
  611. }
  612. }
  613. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(filename)
  614. if err != nil {
  615. return "", false
  616. }
  617. if entry.Blob().Size() >= setting.UI.MaxDisplayFileSize {
  618. return "", false
  619. }
  620. r, err := entry.Blob().DataAsync()
  621. if err != nil {
  622. return "", false
  623. }
  624. defer r.Close()
  625. bytes, err = ioutil.ReadAll(r)
  626. if err != nil {
  627. return "", false
  628. }
  629. return string(bytes), true
  630. }
  631. func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleDirs []string, possibleFiles []string) {
  632. templateCandidates := make([]string, 0, len(possibleFiles))
  633. if ctx.Query("template") != "" {
  634. for _, dirName := range possibleDirs {
  635. templateCandidates = append(templateCandidates, path.Join(dirName, ctx.Query("template")))
  636. }
  637. }
  638. templateCandidates = append(templateCandidates, possibleFiles...) // Append files to the end because they should be fallback
  639. for _, filename := range templateCandidates {
  640. templateContent, found := getFileContentFromDefaultBranch(ctx, filename)
  641. if found {
  642. var meta api.IssueTemplate
  643. templateBody, err := markdown.ExtractMetadata(templateContent, &meta)
  644. if err != nil {
  645. log.Debug("could not extract metadata from %s [%s]: %v", filename, ctx.Repo.Repository.FullName(), err)
  646. ctx.Data[ctxDataKey] = templateContent
  647. return
  648. }
  649. ctx.Data[issueTemplateTitleKey] = meta.Title
  650. ctx.Data[ctxDataKey] = templateBody
  651. labelIDs := make([]string, 0, len(meta.Labels))
  652. if repoLabels, err := models.GetLabelsByRepoID(ctx.Repo.Repository.ID, "", models.ListOptions{}); err == nil {
  653. ctx.Data["Labels"] = repoLabels
  654. if ctx.Repo.Owner.IsOrganization() {
  655. if orgLabels, err := models.GetLabelsByOrgID(ctx.Repo.Owner.ID, ctx.Query("sort"), models.ListOptions{}); err == nil {
  656. ctx.Data["OrgLabels"] = orgLabels
  657. repoLabels = append(repoLabels, orgLabels...)
  658. }
  659. }
  660. for _, metaLabel := range meta.Labels {
  661. for _, repoLabel := range repoLabels {
  662. if strings.EqualFold(repoLabel.Name, metaLabel) {
  663. repoLabel.IsChecked = true
  664. labelIDs = append(labelIDs, fmt.Sprintf("%d", repoLabel.ID))
  665. break
  666. }
  667. }
  668. }
  669. }
  670. ctx.Data["HasSelectedLabel"] = len(labelIDs) > 0
  671. ctx.Data["label_ids"] = strings.Join(labelIDs, ",")
  672. return
  673. }
  674. }
  675. }
  676. // NewIssue render creating issue page
  677. func NewIssue(ctx *context.Context) {
  678. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  679. ctx.Data["PageIsIssueList"] = true
  680. ctx.Data["NewIssueChooseTemplate"] = len(ctx.IssueTemplatesFromDefaultBranch()) > 0
  681. ctx.Data["RequireHighlightJS"] = true
  682. ctx.Data["RequireSimpleMDE"] = true
  683. ctx.Data["RequireTribute"] = true
  684. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  685. title := ctx.Query("title")
  686. ctx.Data["TitleQuery"] = title
  687. body := ctx.Query("body")
  688. ctx.Data["BodyQuery"] = body
  689. ctx.Data["IsProjectsEnabled"] = ctx.Repo.CanRead(models.UnitTypeProjects)
  690. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  691. upload.AddUploadContext(ctx, "comment")
  692. milestoneID := ctx.QueryInt64("milestone")
  693. if milestoneID > 0 {
  694. milestone, err := models.GetMilestoneByID(milestoneID)
  695. if err != nil {
  696. log.Error("GetMilestoneByID: %d: %v", milestoneID, err)
  697. } else {
  698. ctx.Data["milestone_id"] = milestoneID
  699. ctx.Data["Milestone"] = milestone
  700. }
  701. }
  702. projectID := ctx.QueryInt64("project")
  703. if projectID > 0 {
  704. project, err := models.GetProjectByID(projectID)
  705. if err != nil {
  706. log.Error("GetProjectByID: %d: %v", projectID, err)
  707. } else if project.RepoID != ctx.Repo.Repository.ID {
  708. log.Error("GetProjectByID: %d: %v", projectID, fmt.Errorf("project[%d] not in repo [%d]", project.ID, ctx.Repo.Repository.ID))
  709. } else {
  710. ctx.Data["project_id"] = projectID
  711. ctx.Data["Project"] = project
  712. }
  713. }
  714. RetrieveRepoMetas(ctx, ctx.Repo.Repository, false)
  715. setTemplateIfExists(ctx, issueTemplateKey, context.IssueTemplateDirCandidates, IssueTemplateCandidates)
  716. if ctx.Written() {
  717. return
  718. }
  719. ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWrite(models.UnitTypeIssues)
  720. ctx.HTML(200, tplIssueNew)
  721. }
  722. // NewIssueChooseTemplate render creating issue from template page
  723. func NewIssueChooseTemplate(ctx *context.Context) {
  724. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  725. ctx.Data["PageIsIssueList"] = true
  726. ctx.Data["milestone"] = ctx.QueryInt64("milestone")
  727. issueTemplates := ctx.IssueTemplatesFromDefaultBranch()
  728. ctx.Data["NewIssueChooseTemplate"] = len(issueTemplates) > 0
  729. ctx.Data["IssueTemplates"] = issueTemplates
  730. ctx.HTML(200, tplIssueChoose)
  731. }
  732. // ValidateRepoMetas check and returns repository's meta informations
  733. func ValidateRepoMetas(ctx *context.Context, form auth.CreateIssueForm, isPull bool) ([]int64, []int64, int64, int64) {
  734. var (
  735. repo = ctx.Repo.Repository
  736. err error
  737. )
  738. labels := RetrieveRepoMetas(ctx, ctx.Repo.Repository, isPull)
  739. if ctx.Written() {
  740. return nil, nil, 0, 0
  741. }
  742. var labelIDs []int64
  743. hasSelected := false
  744. // Check labels.
  745. if len(form.LabelIDs) > 0 {
  746. labelIDs, err = base.StringsToInt64s(strings.Split(form.LabelIDs, ","))
  747. if err != nil {
  748. return nil, nil, 0, 0
  749. }
  750. labelIDMark := base.Int64sToMap(labelIDs)
  751. for i := range labels {
  752. if labelIDMark[labels[i].ID] {
  753. labels[i].IsChecked = true
  754. hasSelected = true
  755. }
  756. }
  757. }
  758. ctx.Data["Labels"] = labels
  759. ctx.Data["HasSelectedLabel"] = hasSelected
  760. ctx.Data["label_ids"] = form.LabelIDs
  761. // Check milestone.
  762. milestoneID := form.MilestoneID
  763. if milestoneID > 0 {
  764. ctx.Data["Milestone"], err = repo.GetMilestoneByID(milestoneID)
  765. if err != nil {
  766. ctx.ServerError("GetMilestoneByID", err)
  767. return nil, nil, 0, 0
  768. }
  769. ctx.Data["milestone_id"] = milestoneID
  770. }
  771. if form.ProjectID > 0 {
  772. p, err := models.GetProjectByID(form.ProjectID)
  773. if err != nil {
  774. ctx.ServerError("GetProjectByID", err)
  775. return nil, nil, 0, 0
  776. }
  777. if p.RepoID != ctx.Repo.Repository.ID {
  778. ctx.NotFound("", nil)
  779. return nil, nil, 0, 0
  780. }
  781. ctx.Data["Project"] = p
  782. ctx.Data["project_id"] = form.ProjectID
  783. }
  784. // Check assignees
  785. var assigneeIDs []int64
  786. if len(form.AssigneeIDs) > 0 {
  787. assigneeIDs, err = base.StringsToInt64s(strings.Split(form.AssigneeIDs, ","))
  788. if err != nil {
  789. return nil, nil, 0, 0
  790. }
  791. // Check if the passed assignees actually exists and is assignable
  792. for _, aID := range assigneeIDs {
  793. assignee, err := models.GetUserByID(aID)
  794. if err != nil {
  795. ctx.ServerError("GetUserByID", err)
  796. return nil, nil, 0, 0
  797. }
  798. valid, err := models.CanBeAssigned(assignee, repo, isPull)
  799. if err != nil {
  800. ctx.ServerError("CanBeAssigned", err)
  801. return nil, nil, 0, 0
  802. }
  803. if !valid {
  804. ctx.ServerError("canBeAssigned", models.ErrUserDoesNotHaveAccessToRepo{UserID: aID, RepoName: repo.Name})
  805. return nil, nil, 0, 0
  806. }
  807. }
  808. }
  809. // Keep the old assignee id thingy for compatibility reasons
  810. if form.AssigneeID > 0 {
  811. assigneeIDs = append(assigneeIDs, form.AssigneeID)
  812. }
  813. return labelIDs, assigneeIDs, milestoneID, form.ProjectID
  814. }
  815. // NewIssuePost response for creating new issue
  816. func NewIssuePost(ctx *context.Context) {
  817. form := web.GetForm(ctx).(*auth.CreateIssueForm)
  818. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  819. ctx.Data["PageIsIssueList"] = true
  820. ctx.Data["NewIssueChooseTemplate"] = len(ctx.IssueTemplatesFromDefaultBranch()) > 0
  821. ctx.Data["RequireHighlightJS"] = true
  822. ctx.Data["RequireSimpleMDE"] = true
  823. ctx.Data["ReadOnly"] = false
  824. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  825. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  826. upload.AddUploadContext(ctx, "comment")
  827. var (
  828. repo = ctx.Repo.Repository
  829. attachments []string
  830. )
  831. labelIDs, assigneeIDs, milestoneID, projectID := ValidateRepoMetas(ctx, *form, false)
  832. if ctx.Written() {
  833. return
  834. }
  835. if setting.Attachment.Enabled {
  836. attachments = form.Files
  837. }
  838. if ctx.HasError() {
  839. ctx.HTML(200, tplIssueNew)
  840. return
  841. }
  842. if util.IsEmptyString(form.Title) {
  843. ctx.RenderWithErr(ctx.Tr("repo.issues.new.title_empty"), tplIssueNew, form)
  844. return
  845. }
  846. issue := &models.Issue{
  847. RepoID: repo.ID,
  848. Title: form.Title,
  849. PosterID: ctx.User.ID,
  850. Poster: ctx.User,
  851. MilestoneID: milestoneID,
  852. Content: form.Content,
  853. Ref: form.Ref,
  854. }
  855. if err := issue_service.NewIssue(repo, issue, labelIDs, attachments, assigneeIDs); err != nil {
  856. if models.IsErrUserDoesNotHaveAccessToRepo(err) {
  857. ctx.Error(400, "UserDoesNotHaveAccessToRepo", err.Error())
  858. return
  859. }
  860. ctx.ServerError("NewIssue", err)
  861. return
  862. }
  863. if projectID > 0 {
  864. if err := models.ChangeProjectAssign(issue, ctx.User, projectID); err != nil {
  865. ctx.ServerError("ChangeProjectAssign", err)
  866. return
  867. }
  868. }
  869. log.Trace("Issue created: %d/%d", repo.ID, issue.ID)
  870. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + fmt.Sprint(issue.Index))
  871. }
  872. // commentTag returns the CommentTag for a comment in/with the given repo, poster and issue
  873. func commentTag(repo *models.Repository, poster *models.User, issue *models.Issue) (models.CommentTag, error) {
  874. perm, err := models.GetUserRepoPermission(repo, poster)
  875. if err != nil {
  876. return models.CommentTagNone, err
  877. }
  878. if perm.IsOwner() {
  879. if !poster.IsAdmin {
  880. return models.CommentTagOwner, nil
  881. }
  882. ok, err := models.IsUserRealRepoAdmin(repo, poster)
  883. if err != nil {
  884. return models.CommentTagNone, err
  885. }
  886. if ok {
  887. return models.CommentTagOwner, nil
  888. }
  889. if ok, err = repo.IsCollaborator(poster.ID); ok && err == nil {
  890. return models.CommentTagWriter, nil
  891. }
  892. return models.CommentTagNone, err
  893. }
  894. if perm.CanWrite(models.UnitTypeCode) {
  895. return models.CommentTagWriter, nil
  896. }
  897. return models.CommentTagNone, nil
  898. }
  899. func getBranchData(ctx *context.Context, issue *models.Issue) {
  900. ctx.Data["BaseBranch"] = nil
  901. ctx.Data["HeadBranch"] = nil
  902. ctx.Data["HeadUserName"] = nil
  903. ctx.Data["BaseName"] = ctx.Repo.Repository.OwnerName
  904. if issue.IsPull {
  905. pull := issue.PullRequest
  906. ctx.Data["BaseBranch"] = pull.BaseBranch
  907. ctx.Data["HeadBranch"] = pull.HeadBranch
  908. ctx.Data["HeadUserName"] = pull.MustHeadUserName()
  909. }
  910. }
  911. // ViewIssue render issue view page
  912. func ViewIssue(ctx *context.Context) {
  913. if ctx.Params(":type") == "issues" {
  914. // If issue was requested we check if repo has external tracker and redirect
  915. extIssueUnit, err := ctx.Repo.Repository.GetUnit(models.UnitTypeExternalTracker)
  916. if err == nil && extIssueUnit != nil {
  917. if extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == markup.IssueNameStyleNumeric || extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == "" {
  918. metas := ctx.Repo.Repository.ComposeMetas()
  919. metas["index"] = ctx.Params(":index")
  920. ctx.Redirect(com.Expand(extIssueUnit.ExternalTrackerConfig().ExternalTrackerFormat, metas))
  921. return
  922. }
  923. } else if err != nil && !models.IsErrUnitTypeNotExist(err) {
  924. ctx.ServerError("GetUnit", err)
  925. return
  926. }
  927. }
  928. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  929. if err != nil {
  930. if models.IsErrIssueNotExist(err) {
  931. ctx.NotFound("GetIssueByIndex", err)
  932. } else {
  933. ctx.ServerError("GetIssueByIndex", err)
  934. }
  935. return
  936. }
  937. // Make sure type and URL matches.
  938. if ctx.Params(":type") == "issues" && issue.IsPull {
  939. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(issue.Index))
  940. return
  941. } else if ctx.Params(":type") == "pulls" && !issue.IsPull {
  942. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + fmt.Sprint(issue.Index))
  943. return
  944. }
  945. if issue.IsPull {
  946. MustAllowPulls(ctx)
  947. if ctx.Written() {
  948. return
  949. }
  950. ctx.Data["PageIsPullList"] = true
  951. ctx.Data["PageIsPullConversation"] = true
  952. } else {
  953. MustEnableIssues(ctx)
  954. if ctx.Written() {
  955. return
  956. }
  957. ctx.Data["PageIsIssueList"] = true
  958. ctx.Data["NewIssueChooseTemplate"] = len(ctx.IssueTemplatesFromDefaultBranch()) > 0
  959. }
  960. if issue.IsPull && !ctx.Repo.CanRead(models.UnitTypeIssues) {
  961. ctx.Data["IssueType"] = "pulls"
  962. } else if !issue.IsPull && !ctx.Repo.CanRead(models.UnitTypePullRequests) {
  963. ctx.Data["IssueType"] = "issues"
  964. } else {
  965. ctx.Data["IssueType"] = "all"
  966. }
  967. ctx.Data["RequireHighlightJS"] = true
  968. ctx.Data["RequireTribute"] = true
  969. ctx.Data["RequireSimpleMDE"] = true
  970. ctx.Data["IsProjectsEnabled"] = ctx.Repo.CanRead(models.UnitTypeProjects)
  971. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  972. upload.AddUploadContext(ctx, "comment")
  973. if err = issue.LoadAttributes(); err != nil {
  974. ctx.ServerError("LoadAttributes", err)
  975. return
  976. }
  977. if err = filterXRefComments(ctx, issue); err != nil {
  978. ctx.ServerError("filterXRefComments", err)
  979. return
  980. }
  981. ctx.Data["Title"] = fmt.Sprintf("#%d - %s", issue.Index, issue.Title)
  982. iw := new(models.IssueWatch)
  983. if ctx.User != nil {
  984. iw.UserID = ctx.User.ID
  985. iw.IssueID = issue.ID
  986. iw.IsWatching, err = models.CheckIssueWatch(ctx.User, issue)
  987. if err != nil {
  988. ctx.ServerError("CheckIssueWatch", err)
  989. return
  990. }
  991. }
  992. ctx.Data["IssueWatch"] = iw
  993. issue.RenderedContent = string(markdown.Render([]byte(issue.Content), ctx.Repo.RepoLink,
  994. ctx.Repo.Repository.ComposeMetas()))
  995. repo := ctx.Repo.Repository
  996. // Get more information if it's a pull request.
  997. if issue.IsPull {
  998. if issue.PullRequest.HasMerged {
  999. ctx.Data["DisableStatusChange"] = issue.PullRequest.HasMerged
  1000. PrepareMergedViewPullInfo(ctx, issue)
  1001. } else {
  1002. PrepareViewPullInfo(ctx, issue)
  1003. ctx.Data["DisableStatusChange"] = ctx.Data["IsPullRequestBroken"] == true && issue.IsClosed
  1004. }
  1005. if ctx.Written() {
  1006. return
  1007. }
  1008. }
  1009. // Metas.
  1010. // Check labels.
  1011. labelIDMark := make(map[int64]bool)
  1012. for i := range issue.Labels {
  1013. labelIDMark[issue.Labels[i].ID] = true
  1014. }
  1015. labels, err := models.GetLabelsByRepoID(repo.ID, "", models.ListOptions{})
  1016. if err != nil {
  1017. ctx.ServerError("GetLabelsByRepoID", err)
  1018. return
  1019. }
  1020. ctx.Data["Labels"] = labels
  1021. if repo.Owner.IsOrganization() {
  1022. orgLabels, err := models.GetLabelsByOrgID(repo.Owner.ID, ctx.Query("sort"), models.ListOptions{})
  1023. if err != nil {
  1024. ctx.ServerError("GetLabelsByOrgID", err)
  1025. return
  1026. }
  1027. ctx.Data["OrgLabels"] = orgLabels
  1028. labels = append(labels, orgLabels...)
  1029. }
  1030. hasSelected := false
  1031. for i := range labels {
  1032. if labelIDMark[labels[i].ID] {
  1033. labels[i].IsChecked = true
  1034. hasSelected = true
  1035. }
  1036. }
  1037. ctx.Data["HasSelectedLabel"] = hasSelected
  1038. // Check milestone and assignee.
  1039. if ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) {
  1040. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  1041. retrieveProjects(ctx, repo)
  1042. if ctx.Written() {
  1043. return
  1044. }
  1045. }
  1046. if issue.IsPull {
  1047. canChooseReviewer := ctx.Repo.CanWrite(models.UnitTypePullRequests)
  1048. if !canChooseReviewer && ctx.User != nil && ctx.IsSigned {
  1049. canChooseReviewer, err = models.IsOfficialReviewer(issue, ctx.User)
  1050. if err != nil {
  1051. ctx.ServerError("IsOfficialReviewer", err)
  1052. return
  1053. }
  1054. }
  1055. RetrieveRepoReviewers(ctx, repo, issue, canChooseReviewer)
  1056. if ctx.Written() {
  1057. return
  1058. }
  1059. }
  1060. if ctx.IsSigned {
  1061. // Update issue-user.
  1062. if err = issue.ReadBy(ctx.User.ID); err != nil {
  1063. ctx.ServerError("ReadBy", err)
  1064. return
  1065. }
  1066. }
  1067. var (
  1068. tag models.CommentTag
  1069. ok bool
  1070. marked = make(map[int64]models.CommentTag)
  1071. comment *models.Comment
  1072. participants = make([]*models.User, 1, 10)
  1073. )
  1074. if ctx.Repo.Repository.IsTimetrackerEnabled() {
  1075. if ctx.IsSigned {
  1076. // Deal with the stopwatch
  1077. ctx.Data["IsStopwatchRunning"] = models.StopwatchExists(ctx.User.ID, issue.ID)
  1078. if !ctx.Data["IsStopwatchRunning"].(bool) {
  1079. var exists bool
  1080. var sw *models.Stopwatch
  1081. if exists, sw, err = models.HasUserStopwatch(ctx.User.ID); err != nil {
  1082. ctx.ServerError("HasUserStopwatch", err)
  1083. return
  1084. }
  1085. ctx.Data["HasUserStopwatch"] = exists
  1086. if exists {
  1087. // Add warning if the user has already a stopwatch
  1088. var otherIssue *models.Issue
  1089. if otherIssue, err = models.GetIssueByID(sw.IssueID); err != nil {
  1090. ctx.ServerError("GetIssueByID", err)
  1091. return
  1092. }
  1093. if err = otherIssue.LoadRepo(); err != nil {
  1094. ctx.ServerError("LoadRepo", err)
  1095. return
  1096. }
  1097. // Add link to the issue of the already running stopwatch
  1098. ctx.Data["OtherStopwatchURL"] = otherIssue.HTMLURL()
  1099. }
  1100. }
  1101. ctx.Data["CanUseTimetracker"] = ctx.Repo.CanUseTimetracker(issue, ctx.User)
  1102. } else {
  1103. ctx.Data["CanUseTimetracker"] = false
  1104. }
  1105. if ctx.Data["WorkingUsers"], err = models.TotalTimes(models.FindTrackedTimesOptions{IssueID: issue.ID}); err != nil {
  1106. ctx.ServerError("TotalTimes", err)
  1107. return
  1108. }
  1109. }
  1110. // Check if the user can use the dependencies
  1111. ctx.Data["CanCreateIssueDependencies"] = ctx.Repo.CanCreateIssueDependencies(ctx.User, issue.IsPull)
  1112. // check if dependencies can be created across repositories
  1113. ctx.Data["AllowCrossRepositoryDependencies"] = setting.Service.AllowCrossRepositoryDependencies
  1114. if issue.ShowTag, err = commentTag(repo, issue.Poster, issue); err != nil {
  1115. ctx.ServerError("commentTag", err)
  1116. return
  1117. }
  1118. marked[issue.PosterID] = issue.ShowTag
  1119. // Render comments and and fetch participants.
  1120. participants[0] = issue.Poster
  1121. for _, comment = range issue.Comments {
  1122. comment.Issue = issue
  1123. if err := comment.LoadPoster(); err != nil {
  1124. ctx.ServerError("LoadPoster", err)
  1125. return
  1126. }
  1127. if comment.Type == models.CommentTypeComment {
  1128. if err := comment.LoadAttachments(); err != nil {
  1129. ctx.ServerError("LoadAttachments", err)
  1130. return
  1131. }
  1132. comment.RenderedContent = string(markdown.Render([]byte(comment.Content), ctx.Repo.RepoLink,
  1133. ctx.Repo.Repository.ComposeMetas()))
  1134. // Check tag.
  1135. tag, ok = marked[comment.PosterID]
  1136. if ok {
  1137. comment.ShowTag = tag
  1138. continue
  1139. }
  1140. comment.ShowTag, err = commentTag(repo, comment.Poster, issue)
  1141. if err != nil {
  1142. ctx.ServerError("commentTag", err)
  1143. return
  1144. }
  1145. marked[comment.PosterID] = comment.ShowTag
  1146. participants = addParticipant(comment.Poster, participants)
  1147. } else if comment.Type == models.CommentTypeLabel {
  1148. if err = comment.LoadLabel(); err != nil {
  1149. ctx.ServerError("LoadLabel", err)
  1150. return
  1151. }
  1152. } else if comment.Type == models.CommentTypeMilestone {
  1153. if err = comment.LoadMilestone(); err != nil {
  1154. ctx.ServerError("LoadMilestone", err)
  1155. return
  1156. }
  1157. ghostMilestone := &models.Milestone{
  1158. ID: -1,
  1159. Name: ctx.Tr("repo.issues.deleted_milestone"),
  1160. }
  1161. if comment.OldMilestoneID > 0 && comment.OldMilestone == nil {
  1162. comment.OldMilestone = ghostMilestone
  1163. }
  1164. if comment.MilestoneID > 0 && comment.Milestone == nil {
  1165. comment.Milestone = ghostMilestone
  1166. }
  1167. } else if comment.Type == models.CommentTypeProject {
  1168. if err = comment.LoadProject(); err != nil {
  1169. ctx.ServerError("LoadProject", err)
  1170. return
  1171. }
  1172. ghostProject := &models.Project{
  1173. ID: -1,
  1174. Title: ctx.Tr("repo.issues.deleted_project"),
  1175. }
  1176. if comment.OldProjectID > 0 && comment.OldProject == nil {
  1177. comment.OldProject = ghostProject
  1178. }
  1179. if comment.ProjectID > 0 && comment.Project == nil {
  1180. comment.Project = ghostProject
  1181. }
  1182. } else if comment.Type == models.CommentTypeAssignees || comment.Type == models.CommentTypeReviewRequest {
  1183. if err = comment.LoadAssigneeUserAndTeam(); err != nil {
  1184. ctx.ServerError("LoadAssigneeUserAndTeam", err)
  1185. return
  1186. }
  1187. } else if comment.Type == models.CommentTypeRemoveDependency || comment.Type == models.CommentTypeAddDependency {
  1188. if err = comment.LoadDepIssueDetails(); err != nil {
  1189. if !models.IsErrIssueNotExist(err) {
  1190. ctx.ServerError("LoadDepIssueDetails", err)
  1191. return
  1192. }
  1193. }
  1194. } else if comment.Type == models.CommentTypeCode || comment.Type == models.CommentTypeReview || comment.Type == models.CommentTypeDismissReview {
  1195. comment.RenderedContent = string(markdown.Render([]byte(comment.Content), ctx.Repo.RepoLink,
  1196. ctx.Repo.Repository.ComposeMetas()))
  1197. if err = comment.LoadReview(); err != nil && !models.IsErrReviewNotExist(err) {
  1198. ctx.ServerError("LoadReview", err)
  1199. return
  1200. }
  1201. participants = addParticipant(comment.Poster, participants)
  1202. if comment.Review == nil {
  1203. continue
  1204. }
  1205. if err = comment.Review.LoadAttributes(); err != nil {
  1206. if !models.IsErrUserNotExist(err) {
  1207. ctx.ServerError("Review.LoadAttributes", err)
  1208. return
  1209. }
  1210. comment.Review.Reviewer = models.NewGhostUser()
  1211. }
  1212. if err = comment.Review.LoadCodeComments(); err != nil {
  1213. ctx.ServerError("Review.LoadCodeComments", err)
  1214. return
  1215. }
  1216. for _, codeComments := range comment.Review.CodeComments {
  1217. for _, lineComments := range codeComments {
  1218. for _, c := range lineComments {
  1219. // Check tag.
  1220. tag, ok = marked[c.PosterID]
  1221. if ok {
  1222. c.ShowTag = tag
  1223. continue
  1224. }
  1225. c.ShowTag, err = commentTag(repo, c.Poster, issue)
  1226. if err != nil {
  1227. ctx.ServerError("commentTag", err)
  1228. return
  1229. }
  1230. marked[c.PosterID] = c.ShowTag
  1231. participants = addParticipant(c.Poster, participants)
  1232. }
  1233. }
  1234. }
  1235. if err = comment.LoadResolveDoer(); err != nil {
  1236. ctx.ServerError("LoadResolveDoer", err)
  1237. return
  1238. }
  1239. } else if comment.Type == models.CommentTypePullPush {
  1240. participants = addParticipant(comment.Poster, participants)
  1241. if err = comment.LoadPushCommits(); err != nil {
  1242. ctx.ServerError("LoadPushCommits", err)
  1243. return
  1244. }
  1245. } else if comment.Type == models.CommentTypeAddTimeManual ||
  1246. comment.Type == models.CommentTypeStopTracking {
  1247. // drop error since times could be pruned from DB..
  1248. _ = comment.LoadTime()
  1249. }
  1250. }
  1251. // Combine multiple label assignments into a single comment
  1252. combineLabelComments(issue)
  1253. getBranchData(ctx, issue)
  1254. if issue.IsPull {
  1255. pull := issue.PullRequest
  1256. pull.Issue = issue
  1257. canDelete := false
  1258. ctx.Data["AllowMerge"] = false
  1259. if ctx.IsSigned {
  1260. if err := pull.LoadHeadRepo(); err != nil {
  1261. log.Error("LoadHeadRepo: %v", err)
  1262. } else if pull.HeadRepo != nil && pull.HeadBranch != pull.HeadRepo.DefaultBranch {
  1263. perm, err := models.GetUserRepoPermission(pull.HeadRepo, ctx.User)
  1264. if err != nil {
  1265. ctx.ServerError("GetUserRepoPermission", err)
  1266. return
  1267. }
  1268. if perm.CanWrite(models.UnitTypeCode) {
  1269. // Check if branch is not protected
  1270. if protected, err := pull.HeadRepo.IsProtectedBranch(pull.HeadBranch, ctx.User); err != nil {
  1271. log.Error("IsProtectedBranch: %v", err)
  1272. } else if !protected {
  1273. canDelete = true
  1274. ctx.Data["DeleteBranchLink"] = ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(issue.Index) + "/cleanup"
  1275. }
  1276. }
  1277. }
  1278. if err := pull.LoadBaseRepo(); err != nil {
  1279. log.Error("LoadBaseRepo: %v", err)
  1280. }
  1281. perm, err := models.GetUserRepoPermission(pull.BaseRepo, ctx.User)
  1282. if err != nil {
  1283. ctx.ServerError("GetUserRepoPermission", err)
  1284. return
  1285. }
  1286. ctx.Data["AllowMerge"], err = pull_service.IsUserAllowedToMerge(pull, perm, ctx.User)
  1287. if err != nil {
  1288. ctx.ServerError("IsUserAllowedToMerge", err)
  1289. return
  1290. }
  1291. if ctx.Data["CanMarkConversation"], err = models.CanMarkConversation(issue, ctx.User); err != nil {
  1292. ctx.ServerError("CanMarkConversation", err)
  1293. return
  1294. }
  1295. }
  1296. prUnit, err := repo.GetUnit(models.UnitTypePullRequests)
  1297. if err != nil {
  1298. ctx.ServerError("GetUnit", err)
  1299. return
  1300. }
  1301. prConfig := prUnit.PullRequestsConfig()
  1302. // Check correct values and select default
  1303. if ms, ok := ctx.Data["MergeStyle"].(models.MergeStyle); !ok ||
  1304. !prConfig.IsMergeStyleAllowed(ms) {
  1305. if prConfig.AllowMerge {
  1306. ctx.Data["MergeStyle"] = models.MergeStyleMerge
  1307. } else if prConfig.AllowRebase {
  1308. ctx.Data["MergeStyle"] = models.MergeStyleRebase
  1309. } else if prConfig.AllowRebaseMerge {
  1310. ctx.Data["MergeStyle"] = models.MergeStyleRebaseMerge
  1311. } else if prConfig.AllowSquash {
  1312. ctx.Data["MergeStyle"] = models.MergeStyleSquash
  1313. } else if prConfig.AllowManualMerge {
  1314. ctx.Data["MergeStyle"] = models.MergeStyleManuallyMerged
  1315. } else {
  1316. ctx.Data["MergeStyle"] = ""
  1317. }
  1318. }
  1319. if err = pull.LoadProtectedBranch(); err != nil {
  1320. ctx.ServerError("LoadProtectedBranch", err)
  1321. return
  1322. }
  1323. if pull.ProtectedBranch != nil {
  1324. cnt := pull.ProtectedBranch.GetGrantedApprovalsCount(pull)
  1325. ctx.Data["IsBlockedByApprovals"] = !pull.ProtectedBranch.HasEnoughApprovals(pull)
  1326. ctx.Data["IsBlockedByRejection"] = pull.ProtectedBranch.MergeBlockedByRejectedReview(pull)
  1327. ctx.Data["IsBlockedByOfficialReviewRequests"] = pull.ProtectedBranch.MergeBlockedByOfficialReviewRequests(pull)
  1328. ctx.Data["IsBlockedByOutdatedBranch"] = pull.ProtectedBranch.MergeBlockedByOutdatedBranch(pull)
  1329. ctx.Data["GrantedApprovals"] = cnt
  1330. ctx.Data["RequireSigned"] = pull.ProtectedBranch.RequireSignedCommits
  1331. ctx.Data["ChangedProtectedFiles"] = pull.ChangedProtectedFiles
  1332. ctx.Data["IsBlockedByChangedProtectedFiles"] = len(pull.ChangedProtectedFiles) != 0
  1333. ctx.Data["ChangedProtectedFilesNum"] = len(pull.ChangedProtectedFiles)
  1334. }
  1335. ctx.Data["WillSign"] = false
  1336. if ctx.User != nil {
  1337. sign, key, _, err := pull.SignMerge(ctx.User, pull.BaseRepo.RepoPath(), pull.BaseBranch, pull.GetGitRefName())
  1338. ctx.Data["WillSign"] = sign
  1339. ctx.Data["SigningKey"] = key
  1340. if err != nil {
  1341. if models.IsErrWontSign(err) {
  1342. ctx.Data["WontSignReason"] = err.(*models.ErrWontSign).Reason
  1343. } else {
  1344. ctx.Data["WontSignReason"] = "error"
  1345. log.Error("Error whilst checking if could sign pr %d in repo %s. Error: %v", pull.ID, pull.BaseRepo.FullName(), err)
  1346. }
  1347. }
  1348. } else {
  1349. ctx.Data["WontSignReason"] = "not_signed_in"
  1350. }
  1351. ctx.Data["IsPullBranchDeletable"] = canDelete &&
  1352. pull.HeadRepo != nil &&
  1353. git.IsBranchExist(pull.HeadRepo.RepoPath(), pull.HeadBranch) &&
  1354. (!pull.HasMerged || ctx.Data["HeadBranchCommitID"] == ctx.Data["PullHeadCommitID"])
  1355. stillCanManualMerge := func() bool {
  1356. if pull.HasMerged || issue.IsClosed || !ctx.IsSigned {
  1357. return false
  1358. }
  1359. if pull.CanAutoMerge() || pull.IsWorkInProgress() || pull.IsChecking() {
  1360. return false
  1361. }
  1362. if (ctx.User.IsAdmin || ctx.Repo.IsAdmin()) && prConfig.AllowManualMerge {
  1363. return true
  1364. }
  1365. return false
  1366. }
  1367. ctx.Data["StillCanManualMerge"] = stillCanManualMerge()
  1368. }
  1369. // Get Dependencies
  1370. ctx.Data["BlockedByDependencies"], err = issue.BlockedByDependencies()
  1371. if err != nil {
  1372. ctx.ServerError("BlockedByDependencies", err)
  1373. return
  1374. }
  1375. ctx.Data["BlockingDependencies"], err = issue.BlockingDependencies()
  1376. if err != nil {
  1377. ctx.ServerError("BlockingDependencies", err)
  1378. return
  1379. }
  1380. ctx.Data["Participants"] = participants
  1381. ctx.Data["NumParticipants"] = len(participants)
  1382. ctx.Data["Issue"] = issue
  1383. ctx.Data["ReadOnly"] = false
  1384. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login?redirect_to=" + ctx.Data["Link"].(string)
  1385. ctx.Data["IsIssuePoster"] = ctx.IsSigned && issue.IsPoster(ctx.User.ID)
  1386. ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)
  1387. ctx.Data["HasProjectsWritePermission"] = ctx.Repo.CanWrite(models.UnitTypeProjects)
  1388. ctx.Data["IsRepoAdmin"] = ctx.IsSigned && (ctx.Repo.IsAdmin() || ctx.User.IsAdmin)
  1389. ctx.Data["LockReasons"] = setting.Repository.Issue.LockReasons
  1390. ctx.Data["RefEndName"] = git.RefEndName(issue.Ref)
  1391. ctx.HTML(200, tplIssueView)
  1392. }
  1393. // GetActionIssue will return the issue which is used in the context.
  1394. func GetActionIssue(ctx *context.Context) *models.Issue {
  1395. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  1396. if err != nil {
  1397. ctx.NotFoundOrServerError("GetIssueByIndex", models.IsErrIssueNotExist, err)
  1398. return nil
  1399. }
  1400. issue.Repo = ctx.Repo.Repository
  1401. checkIssueRights(ctx, issue)
  1402. if ctx.Written() {
  1403. return nil
  1404. }
  1405. if err = issue.LoadAttributes(); err != nil {
  1406. ctx.ServerError("LoadAttributes", nil)
  1407. return nil
  1408. }
  1409. return issue
  1410. }
  1411. func checkIssueRights(ctx *context.Context, issue *models.Issue) {
  1412. if issue.IsPull && !ctx.Repo.CanRead(models.UnitTypePullRequests) ||
  1413. !issue.IsPull && !ctx.Repo.CanRead(models.UnitTypeIssues) {
  1414. ctx.NotFound("IssueOrPullRequestUnitNotAllowed", nil)
  1415. }
  1416. }
  1417. func getActionIssues(ctx *context.Context) []*models.Issue {
  1418. commaSeparatedIssueIDs := ctx.Query("issue_ids")
  1419. if len(commaSeparatedIssueIDs) == 0 {
  1420. return nil
  1421. }
  1422. issueIDs := make([]int64, 0, 10)
  1423. for _, stringIssueID := range strings.Split(commaSeparatedIssueIDs, ",") {
  1424. issueID, err := strconv.ParseInt(stringIssueID, 10, 64)
  1425. if err != nil {
  1426. ctx.ServerError("ParseInt", err)
  1427. return nil
  1428. }
  1429. issueIDs = append(issueIDs, issueID)
  1430. }
  1431. issues, err := models.GetIssuesByIDs(issueIDs)
  1432. if err != nil {
  1433. ctx.ServerError("GetIssuesByIDs", err)
  1434. return nil
  1435. }
  1436. // Check access rights for all issues
  1437. issueUnitEnabled := ctx.Repo.CanRead(models.UnitTypeIssues)
  1438. prUnitEnabled := ctx.Repo.CanRead(models.UnitTypePullRequests)
  1439. for _, issue := range issues {
  1440. if issue.IsPull && !prUnitEnabled || !issue.IsPull && !issueUnitEnabled {
  1441. ctx.NotFound("IssueOrPullRequestUnitNotAllowed", nil)
  1442. return nil
  1443. }
  1444. if err = issue.LoadAttributes(); err != nil {
  1445. ctx.ServerError("LoadAttributes", err)
  1446. return nil
  1447. }
  1448. }
  1449. return issues
  1450. }
  1451. // UpdateIssueTitle change issue's title
  1452. func UpdateIssueTitle(ctx *context.Context) {
  1453. issue := GetActionIssue(ctx)
  1454. if ctx.Written() {
  1455. return
  1456. }
  1457. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
  1458. ctx.Error(403)
  1459. return
  1460. }
  1461. title := ctx.QueryTrim("title")
  1462. if len(title) == 0 {
  1463. ctx.Error(204)
  1464. return
  1465. }
  1466. if err := issue_service.ChangeTitle(issue, ctx.User, title); err != nil {
  1467. ctx.ServerError("ChangeTitle", err)
  1468. return
  1469. }
  1470. ctx.JSON(200, map[string]interface{}{
  1471. "title": issue.Title,
  1472. })
  1473. }
  1474. // UpdateIssueRef change issue's ref (branch)
  1475. func UpdateIssueRef(ctx *context.Context) {
  1476. issue := GetActionIssue(ctx)
  1477. if ctx.Written() {
  1478. return
  1479. }
  1480. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) || issue.IsPull {
  1481. ctx.Error(403)
  1482. return
  1483. }
  1484. ref := ctx.QueryTrim("ref")
  1485. if err := issue_service.ChangeIssueRef(issue, ctx.User, ref); err != nil {
  1486. ctx.ServerError("ChangeRef", err)
  1487. return
  1488. }
  1489. ctx.JSON(200, map[string]interface{}{
  1490. "ref": ref,
  1491. })
  1492. }
  1493. // UpdateIssueContent change issue's content
  1494. func UpdateIssueContent(ctx *context.Context) {
  1495. issue := GetActionIssue(ctx)
  1496. if ctx.Written() {
  1497. return
  1498. }
  1499. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
  1500. ctx.Error(403)
  1501. return
  1502. }
  1503. content := ctx.Query("content")
  1504. if err := issue_service.ChangeContent(issue, ctx.User, content); err != nil {
  1505. ctx.ServerError("ChangeContent", err)
  1506. return
  1507. }
  1508. files := ctx.QueryStrings("files[]")
  1509. if err := updateAttachments(issue, files); err != nil {
  1510. ctx.ServerError("UpdateAttachments", err)
  1511. }
  1512. ctx.JSON(200, map[string]interface{}{
  1513. "content": string(markdown.Render([]byte(issue.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  1514. "attachments": attachmentsHTML(ctx, issue.Attachments, issue.Content),
  1515. })
  1516. }
  1517. // UpdateIssueMilestone change issue's milestone
  1518. func UpdateIssueMilestone(ctx *context.Context) {
  1519. issues := getActionIssues(ctx)
  1520. if ctx.Written() {
  1521. return
  1522. }
  1523. milestoneID := ctx.QueryInt64("id")
  1524. for _, issue := range issues {
  1525. oldMilestoneID := issue.MilestoneID
  1526. if oldMilestoneID == milestoneID {
  1527. continue
  1528. }
  1529. issue.MilestoneID = milestoneID
  1530. if err := issue_service.ChangeMilestoneAssign(issue, ctx.User, oldMilestoneID); err != nil {
  1531. ctx.ServerError("ChangeMilestoneAssign", err)
  1532. return
  1533. }
  1534. }
  1535. ctx.JSON(200, map[string]interface{}{
  1536. "ok": true,
  1537. })
  1538. }
  1539. // UpdateIssueAssignee change issue's or pull's assignee
  1540. func UpdateIssueAssignee(ctx *context.Context) {
  1541. issues := getActionIssues(ctx)
  1542. if ctx.Written() {
  1543. return
  1544. }
  1545. assigneeID := ctx.QueryInt64("id")
  1546. action := ctx.Query("action")
  1547. for _, issue := range issues {
  1548. switch action {
  1549. case "clear":
  1550. if err := issue_service.DeleteNotPassedAssignee(issue, ctx.User, []*models.User{}); err != nil {
  1551. ctx.ServerError("ClearAssignees", err)
  1552. return
  1553. }
  1554. default:
  1555. assignee, err := models.GetUserByID(assigneeID)
  1556. if err != nil {
  1557. ctx.ServerError("GetUserByID", err)
  1558. return
  1559. }
  1560. valid, err := models.CanBeAssigned(assignee, issue.Repo, issue.IsPull)
  1561. if err != nil {
  1562. ctx.ServerError("canBeAssigned", err)
  1563. return
  1564. }
  1565. if !valid {
  1566. ctx.ServerError("canBeAssigned", models.ErrUserDoesNotHaveAccessToRepo{UserID: assigneeID, RepoName: issue.Repo.Name})
  1567. return
  1568. }
  1569. _, _, err = issue_service.ToggleAssignee(issue, ctx.User, assigneeID)
  1570. if err != nil {
  1571. ctx.ServerError("ToggleAssignee", err)
  1572. return
  1573. }
  1574. }
  1575. }
  1576. ctx.JSON(200, map[string]interface{}{
  1577. "ok": true,
  1578. })
  1579. }
  1580. // UpdatePullReviewRequest add or remove review request
  1581. func UpdatePullReviewRequest(ctx *context.Context) {
  1582. issues := getActionIssues(ctx)
  1583. if ctx.Written() {
  1584. return
  1585. }
  1586. reviewID := ctx.QueryInt64("id")
  1587. action := ctx.Query("action")
  1588. // TODO: Not support 'clear' now
  1589. if action != "attach" && action != "detach" {
  1590. ctx.Status(403)
  1591. return
  1592. }
  1593. for _, issue := range issues {
  1594. if err := issue.LoadRepo(); err != nil {
  1595. ctx.ServerError("issue.LoadRepo", err)
  1596. return
  1597. }
  1598. if !issue.IsPull {
  1599. log.Warn(
  1600. "UpdatePullReviewRequest: refusing to add review request for non-PR issue %-v#%d",
  1601. issue.Repo, issue.Index,
  1602. )
  1603. ctx.Status(403)
  1604. return
  1605. }
  1606. if reviewID < 0 {
  1607. // negative reviewIDs represent team requests
  1608. if err := issue.Repo.GetOwner(); err != nil {
  1609. ctx.ServerError("issue.Repo.GetOwner", err)
  1610. return
  1611. }
  1612. if !issue.Repo.Owner.IsOrganization() {
  1613. log.Warn(
  1614. "UpdatePullReviewRequest: refusing to add team review request for %s#%d owned by non organization UID[%d]",
  1615. issue.Repo.FullName(), issue.Index, issue.Repo.ID,
  1616. )
  1617. ctx.Status(403)
  1618. return
  1619. }
  1620. team, err := models.GetTeamByID(-reviewID)
  1621. if err != nil {
  1622. ctx.ServerError("models.GetTeamByID", err)
  1623. return
  1624. }
  1625. if team.OrgID != issue.Repo.OwnerID {
  1626. log.Warn(
  1627. "UpdatePullReviewRequest: refusing to add team review request for UID[%d] team %s to %s#%d owned by UID[%d]",
  1628. team.OrgID, team.Name, issue.Repo.FullName(), issue.Index, issue.Repo.ID)
  1629. ctx.Status(403)
  1630. return
  1631. }
  1632. err = issue_service.IsValidTeamReviewRequest(team, ctx.User, action == "attach", issue)
  1633. if err != nil {
  1634. if models.IsErrNotValidReviewRequest(err) {
  1635. log.Warn(
  1636. "UpdatePullReviewRequest: refusing to add invalid team review request for UID[%d] team %s to %s#%d owned by UID[%d]: Error: %v",
  1637. team.OrgID, team.Name, issue.Repo.FullName(), issue.Index, issue.Repo.ID,
  1638. err,
  1639. )
  1640. ctx.Status(403)
  1641. return
  1642. }
  1643. ctx.ServerError("IsValidTeamReviewRequest", err)
  1644. return
  1645. }
  1646. _, err = issue_service.TeamReviewRequest(issue, ctx.User, team, action == "attach")
  1647. if err != nil {
  1648. ctx.ServerError("TeamReviewRequest", err)
  1649. return
  1650. }
  1651. continue
  1652. }
  1653. reviewer, err := models.GetUserByID(reviewID)
  1654. if err != nil {
  1655. if models.IsErrUserNotExist(err) {
  1656. log.Warn(
  1657. "UpdatePullReviewRequest: requested reviewer [%d] for %-v to %-v#%d is not exist: Error: %v",
  1658. reviewID, issue.Repo, issue.Index,
  1659. err,
  1660. )
  1661. ctx.Status(403)
  1662. return
  1663. }
  1664. ctx.ServerError("GetUserByID", err)
  1665. return
  1666. }
  1667. err = issue_service.IsValidReviewRequest(reviewer, ctx.User, action == "attach", issue, nil)
  1668. if err != nil {
  1669. if models.IsErrNotValidReviewRequest(err) {
  1670. log.Warn(
  1671. "UpdatePullReviewRequest: refusing to add invalid review request for %-v to %-v#%d: Error: %v",
  1672. reviewer, issue.Repo, issue.Index,
  1673. err,
  1674. )
  1675. ctx.Status(403)
  1676. return
  1677. }
  1678. ctx.ServerError("isValidReviewRequest", err)
  1679. return
  1680. }
  1681. _, err = issue_service.ReviewRequest(issue, ctx.User, reviewer, action == "attach")
  1682. if err != nil {
  1683. ctx.ServerError("ReviewRequest", err)
  1684. return
  1685. }
  1686. }
  1687. ctx.JSON(200, map[string]interface{}{
  1688. "ok": true,
  1689. })
  1690. }
  1691. // UpdateIssueStatus change issue's status
  1692. func UpdateIssueStatus(ctx *context.Context) {
  1693. issues := getActionIssues(ctx)
  1694. if ctx.Written() {
  1695. return
  1696. }
  1697. var isClosed bool
  1698. switch action := ctx.Query("action"); action {
  1699. case "open":
  1700. isClosed = false
  1701. case "close":
  1702. isClosed = true
  1703. default:
  1704. log.Warn("Unrecognized action: %s", action)
  1705. }
  1706. if _, err := models.IssueList(issues).LoadRepositories(); err != nil {
  1707. ctx.ServerError("LoadRepositories", err)
  1708. return
  1709. }
  1710. for _, issue := range issues {
  1711. if issue.IsClosed != isClosed {
  1712. if err := issue_service.ChangeStatus(issue, ctx.User, isClosed); err != nil {
  1713. if models.IsErrDependenciesLeft(err) {
  1714. ctx.JSON(http.StatusPreconditionFailed, map[string]interface{}{
  1715. "error": "cannot close this issue because it still has open dependencies",
  1716. })
  1717. return
  1718. }
  1719. ctx.ServerError("ChangeStatus", err)
  1720. return
  1721. }
  1722. }
  1723. }
  1724. ctx.JSON(200, map[string]interface{}{
  1725. "ok": true,
  1726. })
  1727. }
  1728. // NewComment create a comment for issue
  1729. func NewComment(ctx *context.Context) {
  1730. form := web.GetForm(ctx).(*auth.CreateCommentForm)
  1731. issue := GetActionIssue(ctx)
  1732. if ctx.Written() {
  1733. return
  1734. }
  1735. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanReadIssuesOrPulls(issue.IsPull)) {
  1736. if log.IsTrace() {
  1737. if ctx.IsSigned {
  1738. issueType := "issues"
  1739. if issue.IsPull {
  1740. issueType = "pulls"
  1741. }
  1742. log.Trace("Permission Denied: User %-v not the Poster (ID: %d) and cannot read %s in Repo %-v.\n"+
  1743. "User in Repo has Permissions: %-+v",
  1744. ctx.User,
  1745. log.NewColoredIDValue(issue.PosterID),
  1746. issueType,
  1747. ctx.Repo.Repository,
  1748. ctx.Repo.Permission)
  1749. } else {
  1750. log.Trace("Permission Denied: Not logged in")
  1751. }
  1752. }
  1753. ctx.Error(403)
  1754. return
  1755. }
  1756. if issue.IsLocked && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) && !ctx.User.IsAdmin {
  1757. ctx.Flash.Error(ctx.Tr("repo.issues.comment_on_locked"))
  1758. ctx.Redirect(issue.HTMLURL(), http.StatusSeeOther)
  1759. return
  1760. }
  1761. var attachments []string
  1762. if setting.Attachment.Enabled {
  1763. attachments = form.Files
  1764. }
  1765. if ctx.HasError() {
  1766. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  1767. ctx.Redirect(issue.HTMLURL())
  1768. return
  1769. }
  1770. var comment *models.Comment
  1771. defer func() {
  1772. // Check if issue admin/poster changes the status of issue.
  1773. if (ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))) &&
  1774. (form.Status == "reopen" || form.Status == "close") &&
  1775. !(issue.IsPull && issue.PullRequest.HasMerged) {
  1776. // Duplication and conflict check should apply to reopen pull request.
  1777. var pr *models.PullRequest
  1778. if form.Status == "reopen" && issue.IsPull {
  1779. pull := issue.PullRequest
  1780. var err error
  1781. pr, err = models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch)
  1782. if err != nil {
  1783. if !models.IsErrPullRequestNotExist(err) {
  1784. ctx.ServerError("GetUnmergedPullRequest", err)
  1785. return
  1786. }
  1787. }
  1788. // Regenerate patch and test conflict.
  1789. if pr == nil {
  1790. pull_service.AddToTaskQueue(issue.PullRequest)
  1791. }
  1792. }
  1793. if pr != nil {
  1794. ctx.Flash.Info(ctx.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index))
  1795. } else {
  1796. isClosed := form.Status == "close"
  1797. if err := issue_service.ChangeStatus(issue, ctx.User, isClosed); err != nil {
  1798. log.Error("ChangeStatus: %v", err)
  1799. if models.IsErrDependenciesLeft(err) {
  1800. if issue.IsPull {
  1801. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked"))
  1802. ctx.Redirect(fmt.Sprintf("%s/pulls/%d", ctx.Repo.RepoLink, issue.Index), http.StatusSeeOther)
  1803. } else {
  1804. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.issue_close_blocked"))
  1805. ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index), http.StatusSeeOther)
  1806. }
  1807. return
  1808. }
  1809. } else {
  1810. if err := stopTimerIfAvailable(ctx.User, issue); err != nil {
  1811. ctx.ServerError("CreateOrStopIssueStopwatch", err)
  1812. return
  1813. }
  1814. log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed)
  1815. }
  1816. }
  1817. }
  1818. // Redirect to comment hashtag if there is any actual content.
  1819. typeName := "issues"
  1820. if issue.IsPull {
  1821. typeName = "pulls"
  1822. }
  1823. if comment != nil {
  1824. ctx.Redirect(fmt.Sprintf("%s/%s/%d#%s", ctx.Repo.RepoLink, typeName, issue.Index, comment.HashTag()))
  1825. } else {
  1826. ctx.Redirect(fmt.Sprintf("%s/%s/%d", ctx.Repo.RepoLink, typeName, issue.Index))
  1827. }
  1828. }()
  1829. // Fix #321: Allow empty comments, as long as we have attachments.
  1830. if len(form.Content) == 0 && len(attachments) == 0 {
  1831. return
  1832. }
  1833. comment, err := comment_service.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, form.Content, attachments)
  1834. if err != nil {
  1835. ctx.ServerError("CreateIssueComment", err)
  1836. return
  1837. }
  1838. log.Trace("Comment created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID)
  1839. }
  1840. // UpdateCommentContent change comment of issue's content
  1841. func UpdateCommentContent(ctx *context.Context) {
  1842. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1843. if err != nil {
  1844. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1845. return
  1846. }
  1847. if err := comment.LoadIssue(); err != nil {
  1848. ctx.NotFoundOrServerError("LoadIssue", models.IsErrIssueNotExist, err)
  1849. return
  1850. }
  1851. if comment.Type == models.CommentTypeComment {
  1852. if err := comment.LoadAttachments(); err != nil {
  1853. ctx.ServerError("LoadAttachments", err)
  1854. return
  1855. }
  1856. }
  1857. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull)) {
  1858. ctx.Error(403)
  1859. return
  1860. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  1861. ctx.Error(204)
  1862. return
  1863. }
  1864. oldContent := comment.Content
  1865. comment.Content = ctx.Query("content")
  1866. if len(comment.Content) == 0 {
  1867. ctx.JSON(200, map[string]interface{}{
  1868. "content": "",
  1869. })
  1870. return
  1871. }
  1872. if err = comment_service.UpdateComment(comment, ctx.User, oldContent); err != nil {
  1873. ctx.ServerError("UpdateComment", err)
  1874. return
  1875. }
  1876. files := ctx.QueryStrings("files[]")
  1877. if err := updateAttachments(comment, files); err != nil {
  1878. ctx.ServerError("UpdateAttachments", err)
  1879. }
  1880. ctx.JSON(200, map[string]interface{}{
  1881. "content": string(markdown.Render([]byte(comment.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  1882. "attachments": attachmentsHTML(ctx, comment.Attachments, comment.Content),
  1883. })
  1884. }
  1885. // DeleteComment delete comment of issue
  1886. func DeleteComment(ctx *context.Context) {
  1887. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1888. if err != nil {
  1889. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1890. return
  1891. }
  1892. if err := comment.LoadIssue(); err != nil {
  1893. ctx.NotFoundOrServerError("LoadIssue", models.IsErrIssueNotExist, err)
  1894. return
  1895. }
  1896. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull)) {
  1897. ctx.Error(403)
  1898. return
  1899. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  1900. ctx.Error(204)
  1901. return
  1902. }
  1903. if err = comment_service.DeleteComment(ctx.User, comment); err != nil {
  1904. ctx.ServerError("DeleteCommentByID", err)
  1905. return
  1906. }
  1907. ctx.Status(200)
  1908. }
  1909. // ChangeIssueReaction create a reaction for issue
  1910. func ChangeIssueReaction(ctx *context.Context) {
  1911. form := web.GetForm(ctx).(*auth.ReactionForm)
  1912. issue := GetActionIssue(ctx)
  1913. if ctx.Written() {
  1914. return
  1915. }
  1916. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanReadIssuesOrPulls(issue.IsPull)) {
  1917. if log.IsTrace() {
  1918. if ctx.IsSigned {
  1919. issueType := "issues"
  1920. if issue.IsPull {
  1921. issueType = "pulls"
  1922. }
  1923. log.Trace("Permission Denied: User %-v not the Poster (ID: %d) and cannot read %s in Repo %-v.\n"+
  1924. "User in Repo has Permissions: %-+v",
  1925. ctx.User,
  1926. log.NewColoredIDValue(issue.PosterID),
  1927. issueType,
  1928. ctx.Repo.Repository,
  1929. ctx.Repo.Permission)
  1930. } else {
  1931. log.Trace("Permission Denied: Not logged in")
  1932. }
  1933. }
  1934. ctx.Error(403)
  1935. return
  1936. }
  1937. if ctx.HasError() {
  1938. ctx.ServerError("ChangeIssueReaction", errors.New(ctx.GetErrMsg()))
  1939. return
  1940. }
  1941. switch ctx.Params(":action") {
  1942. case "react":
  1943. reaction, err := models.CreateIssueReaction(ctx.User, issue, form.Content)
  1944. if err != nil {
  1945. if models.IsErrForbiddenIssueReaction(err) {
  1946. ctx.ServerError("ChangeIssueReaction", err)
  1947. return
  1948. }
  1949. log.Info("CreateIssueReaction: %s", err)
  1950. break
  1951. }
  1952. // Reload new reactions
  1953. issue.Reactions = nil
  1954. if err = issue.LoadAttributes(); err != nil {
  1955. log.Info("issue.LoadAttributes: %s", err)
  1956. break
  1957. }
  1958. log.Trace("Reaction for issue created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, reaction.ID)
  1959. case "unreact":
  1960. if err := models.DeleteIssueReaction(ctx.User, issue, form.Content); err != nil {
  1961. ctx.ServerError("DeleteIssueReaction", err)
  1962. return
  1963. }
  1964. // Reload new reactions
  1965. issue.Reactions = nil
  1966. if err := issue.LoadAttributes(); err != nil {
  1967. log.Info("issue.LoadAttributes: %s", err)
  1968. break
  1969. }
  1970. log.Trace("Reaction for issue removed: %d/%d", ctx.Repo.Repository.ID, issue.ID)
  1971. default:
  1972. ctx.NotFound(fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  1973. return
  1974. }
  1975. if len(issue.Reactions) == 0 {
  1976. ctx.JSON(200, map[string]interface{}{
  1977. "empty": true,
  1978. "html": "",
  1979. })
  1980. return
  1981. }
  1982. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  1983. "ctx": ctx.Data,
  1984. "ActionURL": fmt.Sprintf("%s/issues/%d/reactions", ctx.Repo.RepoLink, issue.Index),
  1985. "Reactions": issue.Reactions.GroupByType(),
  1986. })
  1987. if err != nil {
  1988. ctx.ServerError("ChangeIssueReaction.HTMLString", err)
  1989. return
  1990. }
  1991. ctx.JSON(200, map[string]interface{}{
  1992. "html": html,
  1993. })
  1994. }
  1995. // ChangeCommentReaction create a reaction for comment
  1996. func ChangeCommentReaction(ctx *context.Context) {
  1997. form := web.GetForm(ctx).(*auth.ReactionForm)
  1998. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1999. if err != nil {
  2000. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  2001. return
  2002. }
  2003. if err := comment.LoadIssue(); err != nil {
  2004. ctx.NotFoundOrServerError("LoadIssue", models.IsErrIssueNotExist, err)
  2005. return
  2006. }
  2007. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanReadIssuesOrPulls(comment.Issue.IsPull)) {
  2008. if log.IsTrace() {
  2009. if ctx.IsSigned {
  2010. issueType := "issues"
  2011. if comment.Issue.IsPull {
  2012. issueType = "pulls"
  2013. }
  2014. log.Trace("Permission Denied: User %-v not the Poster (ID: %d) and cannot read %s in Repo %-v.\n"+
  2015. "User in Repo has Permissions: %-+v",
  2016. ctx.User,
  2017. log.NewColoredIDValue(comment.Issue.PosterID),
  2018. issueType,
  2019. ctx.Repo.Repository,
  2020. ctx.Repo.Permission)
  2021. } else {
  2022. log.Trace("Permission Denied: Not logged in")
  2023. }
  2024. }
  2025. ctx.Error(403)
  2026. return
  2027. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  2028. ctx.Error(204)
  2029. return
  2030. }
  2031. switch ctx.Params(":action") {
  2032. case "react":
  2033. reaction, err := models.CreateCommentReaction(ctx.User, comment.Issue, comment, form.Content)
  2034. if err != nil {
  2035. if models.IsErrForbiddenIssueReaction(err) {
  2036. ctx.ServerError("ChangeIssueReaction", err)
  2037. return
  2038. }
  2039. log.Info("CreateCommentReaction: %s", err)
  2040. break
  2041. }
  2042. // Reload new reactions
  2043. comment.Reactions = nil
  2044. if err = comment.LoadReactions(ctx.Repo.Repository); err != nil {
  2045. log.Info("comment.LoadReactions: %s", err)
  2046. break
  2047. }
  2048. log.Trace("Reaction for comment created: %d/%d/%d/%d", ctx.Repo.Repository.ID, comment.Issue.ID, comment.ID, reaction.ID)
  2049. case "unreact":
  2050. if err := models.DeleteCommentReaction(ctx.User, comment.Issue, comment, form.Content); err != nil {
  2051. ctx.ServerError("DeleteCommentReaction", err)
  2052. return
  2053. }
  2054. // Reload new reactions
  2055. comment.Reactions = nil
  2056. if err = comment.LoadReactions(ctx.Repo.Repository); err != nil {
  2057. log.Info("comment.LoadReactions: %s", err)
  2058. break
  2059. }
  2060. log.Trace("Reaction for comment removed: %d/%d/%d", ctx.Repo.Repository.ID, comment.Issue.ID, comment.ID)
  2061. default:
  2062. ctx.NotFound(fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  2063. return
  2064. }
  2065. if len(comment.Reactions) == 0 {
  2066. ctx.JSON(200, map[string]interface{}{
  2067. "empty": true,
  2068. "html": "",
  2069. })
  2070. return
  2071. }
  2072. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  2073. "ctx": ctx.Data,
  2074. "ActionURL": fmt.Sprintf("%s/comments/%d/reactions", ctx.Repo.RepoLink, comment.ID),
  2075. "Reactions": comment.Reactions.GroupByType(),
  2076. })
  2077. if err != nil {
  2078. ctx.ServerError("ChangeCommentReaction.HTMLString", err)
  2079. return
  2080. }
  2081. ctx.JSON(200, map[string]interface{}{
  2082. "html": html,
  2083. })
  2084. }
  2085. func addParticipant(poster *models.User, participants []*models.User) []*models.User {
  2086. for _, part := range participants {
  2087. if poster.ID == part.ID {
  2088. return participants
  2089. }
  2090. }
  2091. return append(participants, poster)
  2092. }
  2093. func filterXRefComments(ctx *context.Context, issue *models.Issue) error {
  2094. // Remove comments that the user has no permissions to see
  2095. for i := 0; i < len(issue.Comments); {
  2096. c := issue.Comments[i]
  2097. if models.CommentTypeIsRef(c.Type) && c.RefRepoID != issue.RepoID && c.RefRepoID != 0 {
  2098. var err error
  2099. // Set RefRepo for description in template
  2100. c.RefRepo, err = models.GetRepositoryByID(c.RefRepoID)
  2101. if err != nil {
  2102. return err
  2103. }
  2104. perm, err := models.GetUserRepoPermission(c.RefRepo, ctx.User)
  2105. if err != nil {
  2106. return err
  2107. }
  2108. if !perm.CanReadIssuesOrPulls(c.RefIsPull) {
  2109. issue.Comments = append(issue.Comments[:i], issue.Comments[i+1:]...)
  2110. continue
  2111. }
  2112. }
  2113. i++
  2114. }
  2115. return nil
  2116. }
  2117. // GetIssueAttachments returns attachments for the issue
  2118. func GetIssueAttachments(ctx *context.Context) {
  2119. issue := GetActionIssue(ctx)
  2120. var attachments = make([]*api.Attachment, len(issue.Attachments))
  2121. for i := 0; i < len(issue.Attachments); i++ {
  2122. attachments[i] = convert.ToReleaseAttachment(issue.Attachments[i])
  2123. }
  2124. ctx.JSON(200, attachments)
  2125. }
  2126. // GetCommentAttachments returns attachments for the comment
  2127. func GetCommentAttachments(ctx *context.Context) {
  2128. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  2129. if err != nil {
  2130. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  2131. return
  2132. }
  2133. var attachments = make([]*api.Attachment, 0)
  2134. if comment.Type == models.CommentTypeComment {
  2135. if err := comment.LoadAttachments(); err != nil {
  2136. ctx.ServerError("LoadAttachments", err)
  2137. return
  2138. }
  2139. for i := 0; i < len(comment.Attachments); i++ {
  2140. attachments = append(attachments, convert.ToReleaseAttachment(comment.Attachments[i]))
  2141. }
  2142. }
  2143. ctx.JSON(200, attachments)
  2144. }
  2145. func updateAttachments(item interface{}, files []string) error {
  2146. var attachments []*models.Attachment
  2147. switch content := item.(type) {
  2148. case *models.Issue:
  2149. attachments = content.Attachments
  2150. case *models.Comment:
  2151. attachments = content.Attachments
  2152. default:
  2153. return fmt.Errorf("Unknown Type: %T", content)
  2154. }
  2155. for i := 0; i < len(attachments); i++ {
  2156. if util.IsStringInSlice(attachments[i].UUID, files) {
  2157. continue
  2158. }
  2159. if err := models.DeleteAttachment(attachments[i], true); err != nil {
  2160. return err
  2161. }
  2162. }
  2163. var err error
  2164. if len(files) > 0 {
  2165. switch content := item.(type) {
  2166. case *models.Issue:
  2167. err = content.UpdateAttachments(files)
  2168. case *models.Comment:
  2169. err = content.UpdateAttachments(files)
  2170. default:
  2171. return fmt.Errorf("Unknown Type: %T", content)
  2172. }
  2173. if err != nil {
  2174. return err
  2175. }
  2176. }
  2177. switch content := item.(type) {
  2178. case *models.Issue:
  2179. content.Attachments, err = models.GetAttachmentsByIssueID(content.ID)
  2180. case *models.Comment:
  2181. content.Attachments, err = models.GetAttachmentsByCommentID(content.ID)
  2182. default:
  2183. return fmt.Errorf("Unknown Type: %T", content)
  2184. }
  2185. return err
  2186. }
  2187. func attachmentsHTML(ctx *context.Context, attachments []*models.Attachment, content string) string {
  2188. attachHTML, err := ctx.HTMLString(string(tplAttachment), map[string]interface{}{
  2189. "ctx": ctx.Data,
  2190. "Attachments": attachments,
  2191. "Content": content,
  2192. })
  2193. if err != nil {
  2194. ctx.ServerError("attachmentsHTML.HTMLString", err)
  2195. return ""
  2196. }
  2197. return attachHTML
  2198. }
  2199. func combineLabelComments(issue *models.Issue) {
  2200. for i := 0; i < len(issue.Comments); i++ {
  2201. var (
  2202. prev *models.Comment
  2203. cur = issue.Comments[i]
  2204. )
  2205. if i > 0 {
  2206. prev = issue.Comments[i-1]
  2207. }
  2208. if i == 0 || cur.Type != models.CommentTypeLabel ||
  2209. (prev != nil && prev.PosterID != cur.PosterID) ||
  2210. (prev != nil && cur.CreatedUnix-prev.CreatedUnix >= 60) {
  2211. if cur.Type == models.CommentTypeLabel && cur.Label != nil {
  2212. if cur.Content != "1" {
  2213. cur.RemovedLabels = append(cur.RemovedLabels, cur.Label)
  2214. } else {
  2215. cur.AddedLabels = append(cur.AddedLabels, cur.Label)
  2216. }
  2217. }
  2218. continue
  2219. }
  2220. if cur.Label != nil {
  2221. if cur.Content != "1" {
  2222. prev.RemovedLabels = append(prev.RemovedLabels, cur.Label)
  2223. } else {
  2224. prev.AddedLabels = append(prev.AddedLabels, cur.Label)
  2225. }
  2226. }
  2227. prev.CreatedUnix = cur.CreatedUnix
  2228. issue.Comments = append(issue.Comments[:i], issue.Comments[i+1:]...)
  2229. i--
  2230. }
  2231. }
  2232. // get all teams that current user can mention
  2233. func handleTeamMentions(ctx *context.Context) {
  2234. if ctx.User == nil || !ctx.Repo.Owner.IsOrganization() {
  2235. return
  2236. }
  2237. isAdmin := false
  2238. var err error
  2239. // Admin has super access.
  2240. if ctx.User.IsAdmin {
  2241. isAdmin = true
  2242. } else {
  2243. isAdmin, err = ctx.Repo.Owner.IsOwnedBy(ctx.User.ID)
  2244. if err != nil {
  2245. ctx.ServerError("IsOwnedBy", err)
  2246. return
  2247. }
  2248. }
  2249. if isAdmin {
  2250. if err := ctx.Repo.Owner.GetTeams(&models.SearchTeamOptions{}); err != nil {
  2251. ctx.ServerError("GetTeams", err)
  2252. return
  2253. }
  2254. } else {
  2255. ctx.Repo.Owner.Teams, err = ctx.Repo.Owner.GetUserTeams(ctx.User.ID)
  2256. if err != nil {
  2257. ctx.ServerError("GetUserTeams", err)
  2258. return
  2259. }
  2260. }
  2261. ctx.Data["MentionableTeams"] = ctx.Repo.Owner.Teams
  2262. ctx.Data["MentionableTeamsOrg"] = ctx.Repo.Owner.Name
  2263. ctx.Data["MentionableTeamsOrgAvatar"] = ctx.Repo.Owner.RelAvatarLink()
  2264. }