You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

894 lines
26 KiB

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>
6 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 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>
3 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>
6 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>
6 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>
6 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
5 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
5 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
5 years ago
Template Repositories (#8768) * Start work on templates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Continue work Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix IsTemplate vs IsGenerated Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tabs vs spaces * Tabs vs Spaces * Add templates to API & start adding tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix integration tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove unused User Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move template tests to existing repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Minor re-check updates and cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix optionalbool Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test fixes and icon change Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add new user and repo for tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests (finally) Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update meta repo with env variables Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move generation to create page Combine with repo create template Modify API search to prioritize owner for repo Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests and coverage Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix swagger and JS lint Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix API searching for own private repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Change wording Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix repo search test. User had a private repo that didn't show up Signed-off-by: jolheiser <john.olheiser@gmail.com> * Another search test fix Signed-off-by: jolheiser <john.olheiser@gmail.com> * Clarify git content Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Feedback updates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add topics WIP Signed-off-by: jolheiser <john.olheiser@gmail.com> * Finish adding topics Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update locale Signed-off-by: jolheiser <john.olheiser@gmail.com>
4 years ago
Template Repositories (#8768) * Start work on templates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Continue work Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix IsTemplate vs IsGenerated Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tabs vs spaces * Tabs vs Spaces * Add templates to API & start adding tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix integration tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove unused User Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move template tests to existing repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Minor re-check updates and cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix optionalbool Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test fixes and icon change Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add new user and repo for tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests (finally) Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update meta repo with env variables Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move generation to create page Combine with repo create template Modify API search to prioritize owner for repo Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests and coverage Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix swagger and JS lint Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix API searching for own private repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Change wording Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix repo search test. User had a private repo that didn't show up Signed-off-by: jolheiser <john.olheiser@gmail.com> * Another search test fix Signed-off-by: jolheiser <john.olheiser@gmail.com> * Clarify git content Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Feedback updates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add topics WIP Signed-off-by: jolheiser <john.olheiser@gmail.com> * Finish adding topics Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update locale Signed-off-by: jolheiser <john.olheiser@gmail.com>
4 years ago
10 years ago
8 years ago
Template Repositories (#8768) * Start work on templates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Continue work Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix IsTemplate vs IsGenerated Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tabs vs spaces * Tabs vs Spaces * Add templates to API & start adding tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix integration tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove unused User Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move template tests to existing repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Minor re-check updates and cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix optionalbool Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test fixes and icon change Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add new user and repo for tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests (finally) Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update meta repo with env variables Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move generation to create page Combine with repo create template Modify API search to prioritize owner for repo Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests and coverage Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix swagger and JS lint Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix API searching for own private repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Change wording Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix repo search test. User had a private repo that didn't show up Signed-off-by: jolheiser <john.olheiser@gmail.com> * Another search test fix Signed-off-by: jolheiser <john.olheiser@gmail.com> * Clarify git content Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Feedback updates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add topics WIP Signed-off-by: jolheiser <john.olheiser@gmail.com> * Finish adding topics Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update locale Signed-off-by: jolheiser <john.olheiser@gmail.com>
4 years ago
10 years ago
10 years ago
8 years ago
10 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
5 years ago
9 years ago
9 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package context
  6. import (
  7. "fmt"
  8. "io/ioutil"
  9. "net/url"
  10. "path"
  11. "strings"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/cache"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/markup/markdown"
  17. "code.gitea.io/gitea/modules/setting"
  18. api "code.gitea.io/gitea/modules/structs"
  19. "gitea.com/macaron/macaron"
  20. "github.com/editorconfig/editorconfig-core-go/v2"
  21. "github.com/unknwon/com"
  22. )
  23. // IssueTemplateDirCandidates issue templates directory
  24. var IssueTemplateDirCandidates = []string{
  25. "ISSUE_TEMPLATE",
  26. "issue_template",
  27. ".gitea/ISSUE_TEMPLATE",
  28. ".gitea/issue_template",
  29. ".github/ISSUE_TEMPLATE",
  30. ".github/issue_template",
  31. ".gitlab/ISSUE_TEMPLATE",
  32. ".gitlab/issue_template",
  33. }
  34. // PullRequest contains informations to make a pull request
  35. type PullRequest struct {
  36. BaseRepo *models.Repository
  37. Allowed bool
  38. SameRepo bool
  39. HeadInfo string // [<user>:]<branch>
  40. }
  41. // Repository contains information to operate a repository
  42. type Repository struct {
  43. models.Permission
  44. IsWatching bool
  45. IsViewBranch bool
  46. IsViewTag bool
  47. IsViewCommit bool
  48. Repository *models.Repository
  49. Owner *models.User
  50. Commit *git.Commit
  51. Tag *git.Tag
  52. GitRepo *git.Repository
  53. BranchName string
  54. TagName string
  55. TreePath string
  56. CommitID string
  57. RepoLink string
  58. CloneLink models.CloneLink
  59. CommitsCount int64
  60. Mirror *models.Mirror
  61. PullRequest *PullRequest
  62. }
  63. // CanEnableEditor returns true if repository is editable and user has proper access level.
  64. func (r *Repository) CanEnableEditor() bool {
  65. return r.Permission.CanWrite(models.UnitTypeCode) && r.Repository.CanEnableEditor() && r.IsViewBranch && !r.Repository.IsArchived
  66. }
  67. // CanCreateBranch returns true if repository is editable and user has proper access level.
  68. func (r *Repository) CanCreateBranch() bool {
  69. return r.Permission.CanWrite(models.UnitTypeCode) && r.Repository.CanCreateBranch()
  70. }
  71. // RepoMustNotBeArchived checks if a repo is archived
  72. func RepoMustNotBeArchived() macaron.Handler {
  73. return func(ctx *Context) {
  74. if ctx.Repo.Repository.IsArchived {
  75. ctx.NotFound("IsArchived", fmt.Errorf(ctx.Tr("repo.archive.title")))
  76. }
  77. }
  78. }
  79. // CanCommitToBranchResults represents the results of CanCommitToBranch
  80. type CanCommitToBranchResults struct {
  81. CanCommitToBranch bool
  82. EditorEnabled bool
  83. UserCanPush bool
  84. RequireSigned bool
  85. WillSign bool
  86. SigningKey string
  87. WontSignReason string
  88. }
  89. // CanCommitToBranch returns true if repository is editable and user has proper access level
  90. // and branch is not protected for push
  91. func (r *Repository) CanCommitToBranch(doer *models.User) (CanCommitToBranchResults, error) {
  92. protectedBranch, err := models.GetProtectedBranchBy(r.Repository.ID, r.BranchName)
  93. if err != nil {
  94. return CanCommitToBranchResults{}, err
  95. }
  96. userCanPush := true
  97. requireSigned := false
  98. if protectedBranch != nil {
  99. userCanPush = protectedBranch.CanUserPush(doer.ID)
  100. requireSigned = protectedBranch.RequireSignedCommits
  101. }
  102. sign, keyID, _, err := r.Repository.SignCRUDAction(doer, r.Repository.RepoPath(), git.BranchPrefix+r.BranchName)
  103. canCommit := r.CanEnableEditor() && userCanPush
  104. if requireSigned {
  105. canCommit = canCommit && sign
  106. }
  107. wontSignReason := ""
  108. if err != nil {
  109. if models.IsErrWontSign(err) {
  110. wontSignReason = string(err.(*models.ErrWontSign).Reason)
  111. err = nil
  112. } else {
  113. wontSignReason = "error"
  114. }
  115. }
  116. return CanCommitToBranchResults{
  117. CanCommitToBranch: canCommit,
  118. EditorEnabled: r.CanEnableEditor(),
  119. UserCanPush: userCanPush,
  120. RequireSigned: requireSigned,
  121. WillSign: sign,
  122. SigningKey: keyID,
  123. WontSignReason: wontSignReason,
  124. }, err
  125. }
  126. // CanUseTimetracker returns whether or not a user can use the timetracker.
  127. func (r *Repository) CanUseTimetracker(issue *models.Issue, user *models.User) bool {
  128. // Checking for following:
  129. // 1. Is timetracker enabled
  130. // 2. Is the user a contributor, admin, poster or assignee and do the repository policies require this?
  131. isAssigned, _ := models.IsUserAssignedToIssue(issue, user)
  132. return r.Repository.IsTimetrackerEnabled() && (!r.Repository.AllowOnlyContributorsToTrackTime() ||
  133. r.Permission.CanWriteIssuesOrPulls(issue.IsPull) || issue.IsPoster(user.ID) || isAssigned)
  134. }
  135. // CanCreateIssueDependencies returns whether or not a user can create dependencies.
  136. func (r *Repository) CanCreateIssueDependencies(user *models.User, isPull bool) bool {
  137. return r.Repository.IsDependenciesEnabled() && r.Permission.CanWriteIssuesOrPulls(isPull)
  138. }
  139. // GetCommitsCount returns cached commit count for current view
  140. func (r *Repository) GetCommitsCount() (int64, error) {
  141. var contextName string
  142. if r.IsViewBranch {
  143. contextName = r.BranchName
  144. } else if r.IsViewTag {
  145. contextName = r.TagName
  146. } else {
  147. contextName = r.CommitID
  148. }
  149. return cache.GetInt64(r.Repository.GetCommitsCountCacheKey(contextName, r.IsViewBranch || r.IsViewTag), func() (int64, error) {
  150. return r.Commit.CommitsCount()
  151. })
  152. }
  153. // BranchNameSubURL sub-URL for the BranchName field
  154. func (r *Repository) BranchNameSubURL() string {
  155. switch {
  156. case r.IsViewBranch:
  157. return "branch/" + r.BranchName
  158. case r.IsViewTag:
  159. return "tag/" + r.BranchName
  160. case r.IsViewCommit:
  161. return "commit/" + r.BranchName
  162. }
  163. log.Error("Unknown view type for repo: %v", r)
  164. return ""
  165. }
  166. // FileExists returns true if a file exists in the given repo branch
  167. func (r *Repository) FileExists(path string, branch string) (bool, error) {
  168. if branch == "" {
  169. branch = r.Repository.DefaultBranch
  170. }
  171. commit, err := r.GitRepo.GetBranchCommit(branch)
  172. if err != nil {
  173. return false, err
  174. }
  175. if _, err := commit.GetTreeEntryByPath(path); err != nil {
  176. return false, err
  177. }
  178. return true, nil
  179. }
  180. // GetEditorconfig returns the .editorconfig definition if found in the
  181. // HEAD of the default repo branch.
  182. func (r *Repository) GetEditorconfig() (*editorconfig.Editorconfig, error) {
  183. if r.GitRepo == nil {
  184. return nil, nil
  185. }
  186. commit, err := r.GitRepo.GetBranchCommit(r.Repository.DefaultBranch)
  187. if err != nil {
  188. return nil, err
  189. }
  190. treeEntry, err := commit.GetTreeEntryByPath(".editorconfig")
  191. if err != nil {
  192. return nil, err
  193. }
  194. if treeEntry.Blob().Size() >= setting.UI.MaxDisplayFileSize {
  195. return nil, git.ErrNotExist{ID: "", RelPath: ".editorconfig"}
  196. }
  197. reader, err := treeEntry.Blob().DataAsync()
  198. if err != nil {
  199. return nil, err
  200. }
  201. defer reader.Close()
  202. data, err := ioutil.ReadAll(reader)
  203. if err != nil {
  204. return nil, err
  205. }
  206. return editorconfig.ParseBytes(data)
  207. }
  208. // RetrieveBaseRepo retrieves base repository
  209. func RetrieveBaseRepo(ctx *Context, repo *models.Repository) {
  210. // Non-fork repository will not return error in this method.
  211. if err := repo.GetBaseRepo(); err != nil {
  212. if models.IsErrRepoNotExist(err) {
  213. repo.IsFork = false
  214. repo.ForkID = 0
  215. return
  216. }
  217. ctx.ServerError("GetBaseRepo", err)
  218. return
  219. } else if err = repo.BaseRepo.GetOwner(); err != nil {
  220. ctx.ServerError("BaseRepo.GetOwner", err)
  221. return
  222. }
  223. }
  224. // RetrieveTemplateRepo retrieves template repository used to generate this repository
  225. func RetrieveTemplateRepo(ctx *Context, repo *models.Repository) {
  226. // Non-generated repository will not return error in this method.
  227. if err := repo.GetTemplateRepo(); err != nil {
  228. if models.IsErrRepoNotExist(err) {
  229. repo.TemplateID = 0
  230. return
  231. }
  232. ctx.ServerError("GetTemplateRepo", err)
  233. return
  234. } else if err = repo.TemplateRepo.GetOwner(); err != nil {
  235. ctx.ServerError("TemplateRepo.GetOwner", err)
  236. return
  237. }
  238. perm, err := models.GetUserRepoPermission(repo.TemplateRepo, ctx.User)
  239. if err != nil {
  240. ctx.ServerError("GetUserRepoPermission", err)
  241. return
  242. }
  243. if !perm.CanRead(models.UnitTypeCode) {
  244. repo.TemplateID = 0
  245. }
  246. }
  247. // ComposeGoGetImport returns go-get-import meta content.
  248. func ComposeGoGetImport(owner, repo string) string {
  249. /// setting.AppUrl is guaranteed to be parse as url
  250. appURL, _ := url.Parse(setting.AppURL)
  251. return path.Join(appURL.Host, setting.AppSubURL, url.PathEscape(owner), url.PathEscape(repo))
  252. }
  253. // EarlyResponseForGoGetMeta responses appropriate go-get meta with status 200
  254. // if user does not have actual access to the requested repository,
  255. // or the owner or repository does not exist at all.
  256. // This is particular a workaround for "go get" command which does not respect
  257. // .netrc file.
  258. func EarlyResponseForGoGetMeta(ctx *Context) {
  259. username := ctx.Params(":username")
  260. reponame := strings.TrimSuffix(ctx.Params(":reponame"), ".git")
  261. if username == "" || reponame == "" {
  262. ctx.PlainText(400, []byte("invalid repository path"))
  263. return
  264. }
  265. ctx.PlainText(200, []byte(com.Expand(`<meta name="go-import" content="{GoGetImport} git {CloneLink}">`,
  266. map[string]string{
  267. "GoGetImport": ComposeGoGetImport(username, reponame),
  268. "CloneLink": models.ComposeHTTPSCloneURL(username, reponame),
  269. })))
  270. }
  271. // RedirectToRepo redirect to a differently-named repository
  272. func RedirectToRepo(ctx *Context, redirectRepoID int64) {
  273. ownerName := ctx.Params(":username")
  274. previousRepoName := ctx.Params(":reponame")
  275. repo, err := models.GetRepositoryByID(redirectRepoID)
  276. if err != nil {
  277. ctx.ServerError("GetRepositoryByID", err)
  278. return
  279. }
  280. redirectPath := strings.Replace(
  281. ctx.Req.URL.Path,
  282. fmt.Sprintf("%s/%s", ownerName, previousRepoName),
  283. repo.FullName(),
  284. 1,
  285. )
  286. if ctx.Req.URL.RawQuery != "" {
  287. redirectPath += "?" + ctx.Req.URL.RawQuery
  288. }
  289. ctx.Redirect(path.Join(setting.AppSubURL, redirectPath))
  290. }
  291. func repoAssignment(ctx *Context, repo *models.Repository) {
  292. var err error
  293. if err = repo.GetOwner(); err != nil {
  294. ctx.ServerError("GetOwner", err)
  295. return
  296. }
  297. ctx.Repo.Permission, err = models.GetUserRepoPermission(repo, ctx.User)
  298. if err != nil {
  299. ctx.ServerError("GetUserRepoPermission", err)
  300. return
  301. }
  302. // Check access.
  303. if ctx.Repo.Permission.AccessMode == models.AccessModeNone {
  304. if ctx.Query("go-get") == "1" {
  305. EarlyResponseForGoGetMeta(ctx)
  306. return
  307. }
  308. ctx.NotFound("no access right", nil)
  309. return
  310. }
  311. ctx.Data["HasAccess"] = true
  312. ctx.Data["Permission"] = &ctx.Repo.Permission
  313. if repo.IsMirror {
  314. var err error
  315. ctx.Repo.Mirror, err = models.GetMirrorByRepoID(repo.ID)
  316. if err != nil {
  317. ctx.ServerError("GetMirror", err)
  318. return
  319. }
  320. ctx.Data["MirrorEnablePrune"] = ctx.Repo.Mirror.EnablePrune
  321. ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval
  322. ctx.Data["Mirror"] = ctx.Repo.Mirror
  323. }
  324. ctx.Repo.Repository = repo
  325. ctx.Data["RepoName"] = ctx.Repo.Repository.Name
  326. ctx.Data["IsEmptyRepo"] = ctx.Repo.Repository.IsEmpty
  327. }
  328. // RepoIDAssignment returns a macaron handler which assigns the repo to the context.
  329. func RepoIDAssignment() macaron.Handler {
  330. return func(ctx *Context) {
  331. repoID := ctx.ParamsInt64(":repoid")
  332. // Get repository.
  333. repo, err := models.GetRepositoryByID(repoID)
  334. if err != nil {
  335. if models.IsErrRepoNotExist(err) {
  336. ctx.NotFound("GetRepositoryByID", nil)
  337. } else {
  338. ctx.ServerError("GetRepositoryByID", err)
  339. }
  340. return
  341. }
  342. repoAssignment(ctx, repo)
  343. }
  344. }
  345. // RepoAssignment returns a macaron to handle repository assignment
  346. func RepoAssignment() macaron.Handler {
  347. return func(ctx *Context) {
  348. var (
  349. owner *models.User
  350. err error
  351. )
  352. userName := ctx.Params(":username")
  353. repoName := ctx.Params(":reponame")
  354. // Check if the user is the same as the repository owner
  355. if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
  356. owner = ctx.User
  357. } else {
  358. owner, err = models.GetUserByName(userName)
  359. if err != nil {
  360. if models.IsErrUserNotExist(err) {
  361. if ctx.Query("go-get") == "1" {
  362. EarlyResponseForGoGetMeta(ctx)
  363. return
  364. }
  365. ctx.NotFound("GetUserByName", nil)
  366. } else {
  367. ctx.ServerError("GetUserByName", err)
  368. }
  369. return
  370. }
  371. }
  372. ctx.Repo.Owner = owner
  373. ctx.Data["Username"] = ctx.Repo.Owner.Name
  374. // Get repository.
  375. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  376. if err != nil {
  377. if models.IsErrRepoNotExist(err) {
  378. redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
  379. if err == nil {
  380. RedirectToRepo(ctx, redirectRepoID)
  381. } else if models.IsErrRepoRedirectNotExist(err) {
  382. if ctx.Query("go-get") == "1" {
  383. EarlyResponseForGoGetMeta(ctx)
  384. return
  385. }
  386. ctx.NotFound("GetRepositoryByName", nil)
  387. } else {
  388. ctx.ServerError("LookupRepoRedirect", err)
  389. }
  390. } else {
  391. ctx.ServerError("GetRepositoryByName", err)
  392. }
  393. return
  394. }
  395. repo.Owner = owner
  396. repoAssignment(ctx, repo)
  397. if ctx.Written() {
  398. return
  399. }
  400. ctx.Repo.RepoLink = repo.Link()
  401. ctx.Data["RepoLink"] = ctx.Repo.RepoLink
  402. ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
  403. unit, err := ctx.Repo.Repository.GetUnit(models.UnitTypeExternalTracker)
  404. if err == nil {
  405. ctx.Data["RepoExternalIssuesLink"] = unit.ExternalTrackerConfig().ExternalTrackerURL
  406. }
  407. ctx.Data["NumReleases"], err = models.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{
  408. IncludeDrafts: false,
  409. IncludeTags: true,
  410. })
  411. if err != nil {
  412. ctx.ServerError("GetReleaseCountByRepoID", err)
  413. return
  414. }
  415. ctx.Data["Title"] = owner.Name + "/" + repo.Name
  416. ctx.Data["Repository"] = repo
  417. ctx.Data["Owner"] = ctx.Repo.Repository.Owner
  418. ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner()
  419. ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin()
  420. ctx.Data["RepoOwnerIsOrganization"] = repo.Owner.IsOrganization()
  421. ctx.Data["CanWriteCode"] = ctx.Repo.CanWrite(models.UnitTypeCode)
  422. ctx.Data["CanWriteIssues"] = ctx.Repo.CanWrite(models.UnitTypeIssues)
  423. ctx.Data["CanWritePulls"] = ctx.Repo.CanWrite(models.UnitTypePullRequests)
  424. if ctx.Data["CanSignedUserFork"], err = ctx.Repo.Repository.CanUserFork(ctx.User); err != nil {
  425. ctx.ServerError("CanUserFork", err)
  426. return
  427. }
  428. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  429. ctx.Data["ExposeAnonSSH"] = setting.SSH.ExposeAnonymous
  430. ctx.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit
  431. ctx.Data["RepoSearchEnabled"] = setting.Indexer.RepoIndexerEnabled
  432. ctx.Data["CloneLink"] = repo.CloneLink()
  433. ctx.Data["WikiCloneLink"] = repo.WikiCloneLink()
  434. if ctx.IsSigned {
  435. ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.ID, repo.ID)
  436. ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.ID, repo.ID)
  437. }
  438. if repo.IsFork {
  439. RetrieveBaseRepo(ctx, repo)
  440. if ctx.Written() {
  441. return
  442. }
  443. }
  444. if repo.IsGenerated() {
  445. RetrieveTemplateRepo(ctx, repo)
  446. if ctx.Written() {
  447. return
  448. }
  449. }
  450. // Disable everything when the repo is being created
  451. if ctx.Repo.Repository.IsBeingCreated() {
  452. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  453. return
  454. }
  455. gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName))
  456. if err != nil {
  457. ctx.ServerError("RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err)
  458. return
  459. }
  460. ctx.Repo.GitRepo = gitRepo
  461. // We opened it, we should close it
  462. defer func() {
  463. // If it's been set to nil then assume someone else has closed it.
  464. if ctx.Repo.GitRepo != nil {
  465. ctx.Repo.GitRepo.Close()
  466. }
  467. }()
  468. // Stop at this point when the repo is empty.
  469. if ctx.Repo.Repository.IsEmpty {
  470. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  471. ctx.Next()
  472. return
  473. }
  474. tags, err := ctx.Repo.GitRepo.GetTags()
  475. if err != nil {
  476. ctx.ServerError("GetTags", err)
  477. return
  478. }
  479. ctx.Data["Tags"] = tags
  480. brs, err := ctx.Repo.GitRepo.GetBranches()
  481. if err != nil {
  482. ctx.ServerError("GetBranches", err)
  483. return
  484. }
  485. ctx.Data["Branches"] = brs
  486. ctx.Data["BranchesCount"] = len(brs)
  487. ctx.Data["TagName"] = ctx.Repo.TagName
  488. // If not branch selected, try default one.
  489. // If default branch doesn't exists, fall back to some other branch.
  490. if len(ctx.Repo.BranchName) == 0 {
  491. if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) {
  492. ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch
  493. } else if len(brs) > 0 {
  494. ctx.Repo.BranchName = brs[0]
  495. }
  496. }
  497. ctx.Data["BranchName"] = ctx.Repo.BranchName
  498. ctx.Data["CommitID"] = ctx.Repo.CommitID
  499. // People who have push access or have forked repository can propose a new pull request.
  500. canPush := ctx.Repo.CanWrite(models.UnitTypeCode) || (ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID))
  501. canCompare := false
  502. // Pull request is allowed if this is a fork repository
  503. // and base repository accepts pull requests.
  504. if repo.BaseRepo != nil && repo.BaseRepo.AllowsPulls() {
  505. canCompare = true
  506. ctx.Data["BaseRepo"] = repo.BaseRepo
  507. ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo
  508. ctx.Repo.PullRequest.Allowed = canPush
  509. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName
  510. } else if repo.AllowsPulls() {
  511. // Or, this is repository accepts pull requests between branches.
  512. canCompare = true
  513. ctx.Data["BaseRepo"] = repo
  514. ctx.Repo.PullRequest.BaseRepo = repo
  515. ctx.Repo.PullRequest.Allowed = canPush
  516. ctx.Repo.PullRequest.SameRepo = true
  517. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName
  518. }
  519. ctx.Data["CanCompareOrPull"] = canCompare
  520. ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest
  521. if ctx.Query("go-get") == "1" {
  522. ctx.Data["GoGetImport"] = ComposeGoGetImport(owner.Name, repo.Name)
  523. prefix := setting.AppURL + path.Join(owner.Name, repo.Name, "src", "branch", ctx.Repo.BranchName)
  524. ctx.Data["GoDocDirectory"] = prefix + "{/dir}"
  525. ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}"
  526. }
  527. ctx.Next()
  528. }
  529. }
  530. // RepoRefType type of repo reference
  531. type RepoRefType int
  532. const (
  533. // RepoRefLegacy unknown type, make educated guess and redirect.
  534. // for backward compatibility with previous URL scheme
  535. RepoRefLegacy RepoRefType = iota
  536. // RepoRefAny is for usage where educated guess is needed
  537. // but redirect can not be made
  538. RepoRefAny
  539. // RepoRefBranch branch
  540. RepoRefBranch
  541. // RepoRefTag tag
  542. RepoRefTag
  543. // RepoRefCommit commit
  544. RepoRefCommit
  545. // RepoRefBlob blob
  546. RepoRefBlob
  547. )
  548. // RepoRef handles repository reference names when the ref name is not
  549. // explicitly given
  550. func RepoRef() macaron.Handler {
  551. // since no ref name is explicitly specified, ok to just use branch
  552. return RepoRefByType(RepoRefBranch)
  553. }
  554. // RefTypeIncludesBranches returns true if ref type can be a branch
  555. func (rt RepoRefType) RefTypeIncludesBranches() bool {
  556. if rt == RepoRefLegacy || rt == RepoRefAny || rt == RepoRefBranch {
  557. return true
  558. }
  559. return false
  560. }
  561. // RefTypeIncludesTags returns true if ref type can be a tag
  562. func (rt RepoRefType) RefTypeIncludesTags() bool {
  563. if rt == RepoRefLegacy || rt == RepoRefAny || rt == RepoRefTag {
  564. return true
  565. }
  566. return false
  567. }
  568. func getRefNameFromPath(ctx *Context, path string, isExist func(string) bool) string {
  569. refName := ""
  570. parts := strings.Split(path, "/")
  571. for i, part := range parts {
  572. refName = strings.TrimPrefix(refName+"/"+part, "/")
  573. if isExist(refName) {
  574. ctx.Repo.TreePath = strings.Join(parts[i+1:], "/")
  575. return refName
  576. }
  577. }
  578. return ""
  579. }
  580. func getRefName(ctx *Context, pathType RepoRefType) string {
  581. path := ctx.Params("*")
  582. switch pathType {
  583. case RepoRefLegacy, RepoRefAny:
  584. if refName := getRefName(ctx, RepoRefBranch); len(refName) > 0 {
  585. return refName
  586. }
  587. if refName := getRefName(ctx, RepoRefTag); len(refName) > 0 {
  588. return refName
  589. }
  590. if refName := getRefName(ctx, RepoRefCommit); len(refName) > 0 {
  591. return refName
  592. }
  593. if refName := getRefName(ctx, RepoRefBlob); len(refName) > 0 {
  594. return refName
  595. }
  596. ctx.Repo.TreePath = path
  597. return ctx.Repo.Repository.DefaultBranch
  598. case RepoRefBranch:
  599. return getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsBranchExist)
  600. case RepoRefTag:
  601. return getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsTagExist)
  602. case RepoRefCommit:
  603. parts := strings.Split(path, "/")
  604. if len(parts) > 0 && len(parts[0]) == 40 {
  605. ctx.Repo.TreePath = strings.Join(parts[1:], "/")
  606. return parts[0]
  607. }
  608. case RepoRefBlob:
  609. _, err := ctx.Repo.GitRepo.GetBlob(path)
  610. if err != nil {
  611. return ""
  612. }
  613. return path
  614. default:
  615. log.Error("Unrecognized path type: %v", path)
  616. }
  617. return ""
  618. }
  619. // RepoRefByType handles repository reference name for a specific type
  620. // of repository reference
  621. func RepoRefByType(refType RepoRefType) macaron.Handler {
  622. return func(ctx *Context) {
  623. // Empty repository does not have reference information.
  624. if ctx.Repo.Repository.IsEmpty {
  625. return
  626. }
  627. var (
  628. refName string
  629. err error
  630. )
  631. // For API calls.
  632. if ctx.Repo.GitRepo == nil {
  633. repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  634. ctx.Repo.GitRepo, err = git.OpenRepository(repoPath)
  635. if err != nil {
  636. ctx.ServerError("RepoRef Invalid repo "+repoPath, err)
  637. return
  638. }
  639. // We opened it, we should close it
  640. defer func() {
  641. // If it's been set to nil then assume someone else has closed it.
  642. if ctx.Repo.GitRepo != nil {
  643. ctx.Repo.GitRepo.Close()
  644. }
  645. }()
  646. }
  647. // Get default branch.
  648. if len(ctx.Params("*")) == 0 {
  649. refName = ctx.Repo.Repository.DefaultBranch
  650. ctx.Repo.BranchName = refName
  651. if !ctx.Repo.GitRepo.IsBranchExist(refName) {
  652. brs, err := ctx.Repo.GitRepo.GetBranches()
  653. if err != nil {
  654. ctx.ServerError("GetBranches", err)
  655. return
  656. } else if len(brs) == 0 {
  657. err = fmt.Errorf("No branches in non-empty repository %s",
  658. ctx.Repo.GitRepo.Path)
  659. ctx.ServerError("GetBranches", err)
  660. return
  661. }
  662. refName = brs[0]
  663. }
  664. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  665. if err != nil {
  666. ctx.ServerError("GetBranchCommit", err)
  667. return
  668. }
  669. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  670. ctx.Repo.IsViewBranch = true
  671. } else {
  672. refName = getRefName(ctx, refType)
  673. ctx.Repo.BranchName = refName
  674. if refType.RefTypeIncludesBranches() && ctx.Repo.GitRepo.IsBranchExist(refName) {
  675. ctx.Repo.IsViewBranch = true
  676. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  677. if err != nil {
  678. ctx.ServerError("GetBranchCommit", err)
  679. return
  680. }
  681. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  682. } else if refType.RefTypeIncludesTags() && ctx.Repo.GitRepo.IsTagExist(refName) {
  683. ctx.Repo.IsViewTag = true
  684. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
  685. if err != nil {
  686. ctx.ServerError("GetTagCommit", err)
  687. return
  688. }
  689. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  690. } else if len(refName) == 40 {
  691. ctx.Repo.IsViewCommit = true
  692. ctx.Repo.CommitID = refName
  693. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
  694. if err != nil {
  695. ctx.NotFound("GetCommit", nil)
  696. return
  697. }
  698. } else {
  699. ctx.NotFound("RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
  700. return
  701. }
  702. if refType == RepoRefLegacy {
  703. // redirect from old URL scheme to new URL scheme
  704. ctx.Redirect(path.Join(
  705. setting.AppSubURL,
  706. strings.TrimSuffix(ctx.Req.URL.Path, ctx.Params("*")),
  707. ctx.Repo.BranchNameSubURL(),
  708. ctx.Repo.TreePath))
  709. return
  710. }
  711. }
  712. ctx.Data["BranchName"] = ctx.Repo.BranchName
  713. ctx.Data["BranchNameSubURL"] = ctx.Repo.BranchNameSubURL()
  714. ctx.Data["CommitID"] = ctx.Repo.CommitID
  715. ctx.Data["TreePath"] = ctx.Repo.TreePath
  716. ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch
  717. ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag
  718. ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit
  719. ctx.Data["CanCreateBranch"] = ctx.Repo.CanCreateBranch()
  720. ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
  721. if err != nil {
  722. ctx.ServerError("GetCommitsCount", err)
  723. return
  724. }
  725. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  726. ctx.Next()
  727. }
  728. }
  729. // GitHookService checks if repository Git hooks service has been enabled.
  730. func GitHookService() macaron.Handler {
  731. return func(ctx *Context) {
  732. if !ctx.User.CanEditGitHook() {
  733. ctx.NotFound("GitHookService", nil)
  734. return
  735. }
  736. }
  737. }
  738. // UnitTypes returns a macaron middleware to set unit types to context variables.
  739. func UnitTypes() macaron.Handler {
  740. return func(ctx *Context) {
  741. ctx.Data["UnitTypeCode"] = models.UnitTypeCode
  742. ctx.Data["UnitTypeIssues"] = models.UnitTypeIssues
  743. ctx.Data["UnitTypePullRequests"] = models.UnitTypePullRequests
  744. ctx.Data["UnitTypeReleases"] = models.UnitTypeReleases
  745. ctx.Data["UnitTypeWiki"] = models.UnitTypeWiki
  746. ctx.Data["UnitTypeExternalWiki"] = models.UnitTypeExternalWiki
  747. ctx.Data["UnitTypeExternalTracker"] = models.UnitTypeExternalTracker
  748. ctx.Data["UnitTypeProjects"] = models.UnitTypeProjects
  749. }
  750. }
  751. // IssueTemplatesFromDefaultBranch checks for issue templates in the repo's default branch
  752. func (ctx *Context) IssueTemplatesFromDefaultBranch() []api.IssueTemplate {
  753. var issueTemplates []api.IssueTemplate
  754. if ctx.Repo.Commit == nil {
  755. var err error
  756. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  757. if err != nil {
  758. return issueTemplates
  759. }
  760. }
  761. for _, dirName := range IssueTemplateDirCandidates {
  762. tree, err := ctx.Repo.Commit.SubTree(dirName)
  763. if err != nil {
  764. continue
  765. }
  766. entries, err := tree.ListEntries()
  767. if err != nil {
  768. return issueTemplates
  769. }
  770. for _, entry := range entries {
  771. if strings.HasSuffix(entry.Name(), ".md") {
  772. if entry.Blob().Size() >= setting.UI.MaxDisplayFileSize {
  773. log.Debug("Issue template is too large: %s", entry.Name())
  774. continue
  775. }
  776. r, err := entry.Blob().DataAsync()
  777. if err != nil {
  778. log.Debug("DataAsync: %v", err)
  779. continue
  780. }
  781. defer r.Close()
  782. data, err := ioutil.ReadAll(r)
  783. if err != nil {
  784. log.Debug("ReadAll: %v", err)
  785. continue
  786. }
  787. var it api.IssueTemplate
  788. content, err := markdown.ExtractMetadata(string(data), &it)
  789. if err != nil {
  790. log.Debug("ExtractMetadata: %v", err)
  791. continue
  792. }
  793. it.Content = content
  794. it.FileName = entry.Name()
  795. if it.Valid() {
  796. issueTemplates = append(issueTemplates, it)
  797. }
  798. }
  799. }
  800. if len(issueTemplates) > 0 {
  801. return issueTemplates
  802. }
  803. }
  804. return issueTemplates
  805. }