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

repo.go 23 kB

Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
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
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
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
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>
5 years ago
11 years ago
9 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>
5 years ago
11 years ago
11 years ago
9 years ago
11 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
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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/setting"
  17. "gitea.com/macaron/macaron"
  18. "github.com/editorconfig/editorconfig-core-go/v2"
  19. "github.com/unknwon/com"
  20. )
  21. // PullRequest contains informations to make a pull request
  22. type PullRequest struct {
  23. BaseRepo *models.Repository
  24. Allowed bool
  25. SameRepo bool
  26. HeadInfo string // [<user>:]<branch>
  27. }
  28. // Repository contains information to operate a repository
  29. type Repository struct {
  30. models.Permission
  31. IsWatching bool
  32. IsViewBranch bool
  33. IsViewTag bool
  34. IsViewCommit bool
  35. Repository *models.Repository
  36. Owner *models.User
  37. Commit *git.Commit
  38. Tag *git.Tag
  39. GitRepo *git.Repository
  40. BranchName string
  41. TagName string
  42. TreePath string
  43. CommitID string
  44. RepoLink string
  45. CloneLink models.CloneLink
  46. CommitsCount int64
  47. Mirror *models.Mirror
  48. PullRequest *PullRequest
  49. }
  50. // CanEnableEditor returns true if repository is editable and user has proper access level.
  51. func (r *Repository) CanEnableEditor() bool {
  52. return r.Permission.CanWrite(models.UnitTypeCode) && r.Repository.CanEnableEditor() && r.IsViewBranch && !r.Repository.IsArchived
  53. }
  54. // CanCreateBranch returns true if repository is editable and user has proper access level.
  55. func (r *Repository) CanCreateBranch() bool {
  56. return r.Permission.CanWrite(models.UnitTypeCode) && r.Repository.CanCreateBranch()
  57. }
  58. // RepoMustNotBeArchived checks if a repo is archived
  59. func RepoMustNotBeArchived() macaron.Handler {
  60. return func(ctx *Context) {
  61. if ctx.Repo.Repository.IsArchived {
  62. ctx.NotFound("IsArchived", fmt.Errorf(ctx.Tr("repo.archive.title")))
  63. }
  64. }
  65. }
  66. // CanCommitToBranch returns true if repository is editable and user has proper access level
  67. // and branch is not protected for push
  68. func (r *Repository) CanCommitToBranch(doer *models.User) (bool, error) {
  69. protectedBranch, err := r.Repository.IsProtectedBranchForPush(r.BranchName, doer)
  70. if err != nil {
  71. return false, err
  72. }
  73. return r.CanEnableEditor() && !protectedBranch, nil
  74. }
  75. // CanUseTimetracker returns whether or not a user can use the timetracker.
  76. func (r *Repository) CanUseTimetracker(issue *models.Issue, user *models.User) bool {
  77. // Checking for following:
  78. // 1. Is timetracker enabled
  79. // 2. Is the user a contributor, admin, poster or assignee and do the repository policies require this?
  80. isAssigned, _ := models.IsUserAssignedToIssue(issue, user)
  81. return r.Repository.IsTimetrackerEnabled() && (!r.Repository.AllowOnlyContributorsToTrackTime() ||
  82. r.Permission.CanWrite(models.UnitTypeIssues) || issue.IsPoster(user.ID) || isAssigned)
  83. }
  84. // CanCreateIssueDependencies returns whether or not a user can create dependencies.
  85. func (r *Repository) CanCreateIssueDependencies(user *models.User) bool {
  86. return r.Permission.CanWrite(models.UnitTypeIssues) && r.Repository.IsDependenciesEnabled()
  87. }
  88. // GetCommitsCount returns cached commit count for current view
  89. func (r *Repository) GetCommitsCount() (int64, error) {
  90. var contextName string
  91. if r.IsViewBranch {
  92. contextName = r.BranchName
  93. } else if r.IsViewTag {
  94. contextName = r.TagName
  95. } else {
  96. contextName = r.CommitID
  97. }
  98. return cache.GetInt64(r.Repository.GetCommitsCountCacheKey(contextName, r.IsViewBranch || r.IsViewTag), func() (int64, error) {
  99. return r.Commit.CommitsCount()
  100. })
  101. }
  102. // BranchNameSubURL sub-URL for the BranchName field
  103. func (r *Repository) BranchNameSubURL() string {
  104. switch {
  105. case r.IsViewBranch:
  106. return "branch/" + r.BranchName
  107. case r.IsViewTag:
  108. return "tag/" + r.BranchName
  109. case r.IsViewCommit:
  110. return "commit/" + r.BranchName
  111. }
  112. log.Error("Unknown view type for repo: %v", r)
  113. return ""
  114. }
  115. // FileExists returns true if a file exists in the given repo branch
  116. func (r *Repository) FileExists(path string, branch string) (bool, error) {
  117. if branch == "" {
  118. branch = r.Repository.DefaultBranch
  119. }
  120. commit, err := r.GitRepo.GetBranchCommit(branch)
  121. if err != nil {
  122. return false, err
  123. }
  124. if _, err := commit.GetTreeEntryByPath(path); err != nil {
  125. return false, err
  126. }
  127. return true, nil
  128. }
  129. // GetEditorconfig returns the .editorconfig definition if found in the
  130. // HEAD of the default repo branch.
  131. func (r *Repository) GetEditorconfig() (*editorconfig.Editorconfig, error) {
  132. if r.GitRepo == nil {
  133. return nil, nil
  134. }
  135. commit, err := r.GitRepo.GetBranchCommit(r.Repository.DefaultBranch)
  136. if err != nil {
  137. return nil, err
  138. }
  139. treeEntry, err := commit.GetTreeEntryByPath(".editorconfig")
  140. if err != nil {
  141. return nil, err
  142. }
  143. if treeEntry.Blob().Size() >= setting.UI.MaxDisplayFileSize {
  144. return nil, git.ErrNotExist{ID: "", RelPath: ".editorconfig"}
  145. }
  146. reader, err := treeEntry.Blob().DataAsync()
  147. if err != nil {
  148. return nil, err
  149. }
  150. defer reader.Close()
  151. data, err := ioutil.ReadAll(reader)
  152. if err != nil {
  153. return nil, err
  154. }
  155. return editorconfig.ParseBytes(data)
  156. }
  157. // RetrieveBaseRepo retrieves base repository
  158. func RetrieveBaseRepo(ctx *Context, repo *models.Repository) {
  159. // Non-fork repository will not return error in this method.
  160. if err := repo.GetBaseRepo(); err != nil {
  161. if models.IsErrRepoNotExist(err) {
  162. repo.IsFork = false
  163. repo.ForkID = 0
  164. return
  165. }
  166. ctx.ServerError("GetBaseRepo", err)
  167. return
  168. } else if err = repo.BaseRepo.GetOwner(); err != nil {
  169. ctx.ServerError("BaseRepo.GetOwner", err)
  170. return
  171. }
  172. }
  173. // RetrieveTemplateRepo retrieves template repository used to generate this repository
  174. func RetrieveTemplateRepo(ctx *Context, repo *models.Repository) {
  175. // Non-generated repository will not return error in this method.
  176. if err := repo.GetTemplateRepo(); err != nil {
  177. if models.IsErrRepoNotExist(err) {
  178. repo.TemplateID = 0
  179. return
  180. }
  181. ctx.ServerError("GetTemplateRepo", err)
  182. return
  183. } else if err = repo.TemplateRepo.GetOwner(); err != nil {
  184. ctx.ServerError("TemplateRepo.GetOwner", err)
  185. return
  186. }
  187. if !repo.TemplateRepo.CheckUnitUser(ctx.User.ID, ctx.User.IsAdmin, models.UnitTypeCode) {
  188. repo.TemplateID = 0
  189. }
  190. }
  191. // ComposeGoGetImport returns go-get-import meta content.
  192. func ComposeGoGetImport(owner, repo string) string {
  193. /// setting.AppUrl is guaranteed to be parse as url
  194. appURL, _ := url.Parse(setting.AppURL)
  195. return path.Join(appURL.Host, setting.AppSubURL, url.PathEscape(owner), url.PathEscape(repo))
  196. }
  197. // EarlyResponseForGoGetMeta responses appropriate go-get meta with status 200
  198. // if user does not have actual access to the requested repository,
  199. // or the owner or repository does not exist at all.
  200. // This is particular a workaround for "go get" command which does not respect
  201. // .netrc file.
  202. func EarlyResponseForGoGetMeta(ctx *Context) {
  203. username := ctx.Params(":username")
  204. reponame := strings.TrimSuffix(ctx.Params(":reponame"), ".git")
  205. if username == "" || reponame == "" {
  206. ctx.PlainText(400, []byte("invalid repository path"))
  207. return
  208. }
  209. ctx.PlainText(200, []byte(com.Expand(`<meta name="go-import" content="{GoGetImport} git {CloneLink}">`,
  210. map[string]string{
  211. "GoGetImport": ComposeGoGetImport(username, reponame),
  212. "CloneLink": models.ComposeHTTPSCloneURL(username, reponame),
  213. })))
  214. }
  215. // RedirectToRepo redirect to a differently-named repository
  216. func RedirectToRepo(ctx *Context, redirectRepoID int64) {
  217. ownerName := ctx.Params(":username")
  218. previousRepoName := ctx.Params(":reponame")
  219. repo, err := models.GetRepositoryByID(redirectRepoID)
  220. if err != nil {
  221. ctx.ServerError("GetRepositoryByID", err)
  222. return
  223. }
  224. redirectPath := strings.Replace(
  225. ctx.Req.URL.Path,
  226. fmt.Sprintf("%s/%s", ownerName, previousRepoName),
  227. fmt.Sprintf("%s/%s", repo.MustOwnerName(), repo.Name),
  228. 1,
  229. )
  230. if ctx.Req.URL.RawQuery != "" {
  231. redirectPath += "?" + ctx.Req.URL.RawQuery
  232. }
  233. ctx.Redirect(path.Join(setting.AppSubURL, redirectPath))
  234. }
  235. func repoAssignment(ctx *Context, repo *models.Repository) {
  236. var err error
  237. if err = repo.GetOwner(); err != nil {
  238. ctx.ServerError("GetOwner", err)
  239. return
  240. }
  241. ctx.Repo.Permission, err = models.GetUserRepoPermission(repo, ctx.User)
  242. if err != nil {
  243. ctx.ServerError("GetUserRepoPermission", err)
  244. return
  245. }
  246. // Check access.
  247. if ctx.Repo.Permission.AccessMode == models.AccessModeNone {
  248. if ctx.Query("go-get") == "1" {
  249. EarlyResponseForGoGetMeta(ctx)
  250. return
  251. }
  252. ctx.NotFound("no access right", nil)
  253. return
  254. }
  255. ctx.Data["HasAccess"] = true
  256. ctx.Data["Permission"] = &ctx.Repo.Permission
  257. if repo.IsMirror {
  258. var err error
  259. ctx.Repo.Mirror, err = models.GetMirrorByRepoID(repo.ID)
  260. if err != nil {
  261. ctx.ServerError("GetMirror", err)
  262. return
  263. }
  264. ctx.Data["MirrorEnablePrune"] = ctx.Repo.Mirror.EnablePrune
  265. ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval
  266. ctx.Data["Mirror"] = ctx.Repo.Mirror
  267. }
  268. ctx.Repo.Repository = repo
  269. ctx.Data["RepoName"] = ctx.Repo.Repository.Name
  270. ctx.Data["IsEmptyRepo"] = ctx.Repo.Repository.IsEmpty
  271. }
  272. // RepoIDAssignment returns a macaron handler which assigns the repo to the context.
  273. func RepoIDAssignment() macaron.Handler {
  274. return func(ctx *Context) {
  275. repoID := ctx.ParamsInt64(":repoid")
  276. // Get repository.
  277. repo, err := models.GetRepositoryByID(repoID)
  278. if err != nil {
  279. if models.IsErrRepoNotExist(err) {
  280. ctx.NotFound("GetRepositoryByID", nil)
  281. } else {
  282. ctx.ServerError("GetRepositoryByID", err)
  283. }
  284. return
  285. }
  286. repoAssignment(ctx, repo)
  287. }
  288. }
  289. // RepoAssignment returns a macaron to handle repository assignment
  290. func RepoAssignment() macaron.Handler {
  291. return func(ctx *Context) {
  292. var (
  293. owner *models.User
  294. err error
  295. )
  296. userName := ctx.Params(":username")
  297. repoName := ctx.Params(":reponame")
  298. // Check if the user is the same as the repository owner
  299. if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
  300. owner = ctx.User
  301. } else {
  302. owner, err = models.GetUserByName(userName)
  303. if err != nil {
  304. if models.IsErrUserNotExist(err) {
  305. if ctx.Query("go-get") == "1" {
  306. EarlyResponseForGoGetMeta(ctx)
  307. return
  308. }
  309. ctx.NotFound("GetUserByName", nil)
  310. } else {
  311. ctx.ServerError("GetUserByName", err)
  312. }
  313. return
  314. }
  315. }
  316. ctx.Repo.Owner = owner
  317. ctx.Data["Username"] = ctx.Repo.Owner.Name
  318. // Get repository.
  319. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  320. if err != nil {
  321. if models.IsErrRepoNotExist(err) {
  322. redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
  323. if err == nil {
  324. RedirectToRepo(ctx, redirectRepoID)
  325. } else if models.IsErrRepoRedirectNotExist(err) {
  326. if ctx.Query("go-get") == "1" {
  327. EarlyResponseForGoGetMeta(ctx)
  328. return
  329. }
  330. ctx.NotFound("GetRepositoryByName", nil)
  331. } else {
  332. ctx.ServerError("LookupRepoRedirect", err)
  333. }
  334. } else {
  335. ctx.ServerError("GetRepositoryByName", err)
  336. }
  337. return
  338. }
  339. repo.Owner = owner
  340. repoAssignment(ctx, repo)
  341. if ctx.Written() {
  342. return
  343. }
  344. ctx.Repo.RepoLink = repo.Link()
  345. ctx.Data["RepoLink"] = ctx.Repo.RepoLink
  346. ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
  347. unit, err := ctx.Repo.Repository.GetUnit(models.UnitTypeExternalTracker)
  348. if err == nil {
  349. ctx.Data["RepoExternalIssuesLink"] = unit.ExternalTrackerConfig().ExternalTrackerURL
  350. }
  351. count, err := models.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{
  352. IncludeDrafts: false,
  353. IncludeTags: true,
  354. })
  355. if err != nil {
  356. ctx.ServerError("GetReleaseCountByRepoID", err)
  357. return
  358. }
  359. ctx.Repo.Repository.NumReleases = int(count)
  360. ctx.Data["Title"] = owner.Name + "/" + repo.Name
  361. ctx.Data["Repository"] = repo
  362. ctx.Data["Owner"] = ctx.Repo.Repository.Owner
  363. ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner()
  364. ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin()
  365. ctx.Data["RepoOwnerIsOrganization"] = repo.Owner.IsOrganization()
  366. ctx.Data["CanWriteCode"] = ctx.Repo.CanWrite(models.UnitTypeCode)
  367. ctx.Data["CanWriteIssues"] = ctx.Repo.CanWrite(models.UnitTypeIssues)
  368. ctx.Data["CanWritePulls"] = ctx.Repo.CanWrite(models.UnitTypePullRequests)
  369. if ctx.Data["CanSignedUserFork"], err = ctx.Repo.Repository.CanUserFork(ctx.User); err != nil {
  370. ctx.ServerError("CanUserFork", err)
  371. return
  372. }
  373. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  374. ctx.Data["ExposeAnonSSH"] = setting.SSH.ExposeAnonymous
  375. ctx.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit
  376. ctx.Data["RepoSearchEnabled"] = setting.Indexer.RepoIndexerEnabled
  377. ctx.Data["CloneLink"] = repo.CloneLink()
  378. ctx.Data["WikiCloneLink"] = repo.WikiCloneLink()
  379. if ctx.IsSigned {
  380. ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.ID, repo.ID)
  381. ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.ID, repo.ID)
  382. }
  383. if repo.IsFork {
  384. RetrieveBaseRepo(ctx, repo)
  385. if ctx.Written() {
  386. return
  387. }
  388. }
  389. if repo.IsGenerated() {
  390. RetrieveTemplateRepo(ctx, repo)
  391. if ctx.Written() {
  392. return
  393. }
  394. }
  395. // Disable everything when the repo is being created
  396. if ctx.Repo.Repository.IsBeingCreated() {
  397. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  398. return
  399. }
  400. gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName))
  401. if err != nil {
  402. ctx.ServerError("RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err)
  403. return
  404. }
  405. ctx.Repo.GitRepo = gitRepo
  406. // We opened it, we should close it
  407. defer func() {
  408. // If it's been set to nil then assume someone else has closed it.
  409. if ctx.Repo.GitRepo != nil {
  410. ctx.Repo.GitRepo.Close()
  411. }
  412. }()
  413. // Stop at this point when the repo is empty.
  414. if ctx.Repo.Repository.IsEmpty {
  415. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  416. ctx.Next()
  417. return
  418. }
  419. tags, err := ctx.Repo.GitRepo.GetTags()
  420. if err != nil {
  421. ctx.ServerError("GetTags", err)
  422. return
  423. }
  424. ctx.Data["Tags"] = tags
  425. brs, err := ctx.Repo.GitRepo.GetBranches()
  426. if err != nil {
  427. ctx.ServerError("GetBranches", err)
  428. return
  429. }
  430. ctx.Data["Branches"] = brs
  431. ctx.Data["BranchesCount"] = len(brs)
  432. ctx.Data["TagName"] = ctx.Repo.TagName
  433. // If not branch selected, try default one.
  434. // If default branch doesn't exists, fall back to some other branch.
  435. if len(ctx.Repo.BranchName) == 0 {
  436. if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) {
  437. ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch
  438. } else if len(brs) > 0 {
  439. ctx.Repo.BranchName = brs[0]
  440. }
  441. }
  442. ctx.Data["BranchName"] = ctx.Repo.BranchName
  443. ctx.Data["CommitID"] = ctx.Repo.CommitID
  444. // People who have push access or have forked repository can propose a new pull request.
  445. if ctx.Repo.CanWrite(models.UnitTypeCode) || (ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID)) {
  446. // Pull request is allowed if this is a fork repository
  447. // and base repository accepts pull requests.
  448. if repo.BaseRepo != nil && repo.BaseRepo.AllowsPulls() {
  449. ctx.Data["BaseRepo"] = repo.BaseRepo
  450. ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo
  451. ctx.Repo.PullRequest.Allowed = true
  452. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName
  453. } else if repo.AllowsPulls() {
  454. // Or, this is repository accepts pull requests between branches.
  455. ctx.Data["BaseRepo"] = repo
  456. ctx.Repo.PullRequest.BaseRepo = repo
  457. ctx.Repo.PullRequest.Allowed = true
  458. ctx.Repo.PullRequest.SameRepo = true
  459. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName
  460. }
  461. }
  462. ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest
  463. if ctx.Query("go-get") == "1" {
  464. ctx.Data["GoGetImport"] = ComposeGoGetImport(owner.Name, repo.Name)
  465. prefix := setting.AppURL + path.Join(owner.Name, repo.Name, "src", "branch", ctx.Repo.BranchName)
  466. ctx.Data["GoDocDirectory"] = prefix + "{/dir}"
  467. ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}"
  468. }
  469. ctx.Next()
  470. }
  471. }
  472. // RepoRefType type of repo reference
  473. type RepoRefType int
  474. const (
  475. // RepoRefLegacy unknown type, make educated guess and redirect.
  476. // for backward compatibility with previous URL scheme
  477. RepoRefLegacy RepoRefType = iota
  478. // RepoRefAny is for usage where educated guess is needed
  479. // but redirect can not be made
  480. RepoRefAny
  481. // RepoRefBranch branch
  482. RepoRefBranch
  483. // RepoRefTag tag
  484. RepoRefTag
  485. // RepoRefCommit commit
  486. RepoRefCommit
  487. // RepoRefBlob blob
  488. RepoRefBlob
  489. )
  490. // RepoRef handles repository reference names when the ref name is not
  491. // explicitly given
  492. func RepoRef() macaron.Handler {
  493. // since no ref name is explicitly specified, ok to just use branch
  494. return RepoRefByType(RepoRefBranch)
  495. }
  496. // RefTypeIncludesBranches returns true if ref type can be a branch
  497. func (rt RepoRefType) RefTypeIncludesBranches() bool {
  498. if rt == RepoRefLegacy || rt == RepoRefAny || rt == RepoRefBranch {
  499. return true
  500. }
  501. return false
  502. }
  503. // RefTypeIncludesTags returns true if ref type can be a tag
  504. func (rt RepoRefType) RefTypeIncludesTags() bool {
  505. if rt == RepoRefLegacy || rt == RepoRefAny || rt == RepoRefTag {
  506. return true
  507. }
  508. return false
  509. }
  510. func getRefNameFromPath(ctx *Context, path string, isExist func(string) bool) string {
  511. refName := ""
  512. parts := strings.Split(path, "/")
  513. for i, part := range parts {
  514. refName = strings.TrimPrefix(refName+"/"+part, "/")
  515. if isExist(refName) {
  516. ctx.Repo.TreePath = strings.Join(parts[i+1:], "/")
  517. return refName
  518. }
  519. }
  520. return ""
  521. }
  522. func getRefName(ctx *Context, pathType RepoRefType) string {
  523. path := ctx.Params("*")
  524. switch pathType {
  525. case RepoRefLegacy, RepoRefAny:
  526. if refName := getRefName(ctx, RepoRefBranch); len(refName) > 0 {
  527. return refName
  528. }
  529. if refName := getRefName(ctx, RepoRefTag); len(refName) > 0 {
  530. return refName
  531. }
  532. if refName := getRefName(ctx, RepoRefCommit); len(refName) > 0 {
  533. return refName
  534. }
  535. if refName := getRefName(ctx, RepoRefBlob); len(refName) > 0 {
  536. return refName
  537. }
  538. ctx.Repo.TreePath = path
  539. return ctx.Repo.Repository.DefaultBranch
  540. case RepoRefBranch:
  541. return getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsBranchExist)
  542. case RepoRefTag:
  543. return getRefNameFromPath(ctx, path, ctx.Repo.GitRepo.IsTagExist)
  544. case RepoRefCommit:
  545. parts := strings.Split(path, "/")
  546. if len(parts) > 0 && len(parts[0]) == 40 {
  547. ctx.Repo.TreePath = strings.Join(parts[1:], "/")
  548. return parts[0]
  549. }
  550. case RepoRefBlob:
  551. _, err := ctx.Repo.GitRepo.GetBlob(path)
  552. if err != nil {
  553. return ""
  554. }
  555. return path
  556. default:
  557. log.Error("Unrecognized path type: %v", path)
  558. }
  559. return ""
  560. }
  561. // RepoRefByType handles repository reference name for a specific type
  562. // of repository reference
  563. func RepoRefByType(refType RepoRefType) macaron.Handler {
  564. return func(ctx *Context) {
  565. // Empty repository does not have reference information.
  566. if ctx.Repo.Repository.IsEmpty {
  567. return
  568. }
  569. var (
  570. refName string
  571. err error
  572. )
  573. // For API calls.
  574. if ctx.Repo.GitRepo == nil {
  575. repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  576. ctx.Repo.GitRepo, err = git.OpenRepository(repoPath)
  577. if err != nil {
  578. ctx.ServerError("RepoRef Invalid repo "+repoPath, err)
  579. return
  580. }
  581. // We opened it, we should close it
  582. defer func() {
  583. // If it's been set to nil then assume someone else has closed it.
  584. if ctx.Repo.GitRepo != nil {
  585. ctx.Repo.GitRepo.Close()
  586. }
  587. }()
  588. }
  589. // Get default branch.
  590. if len(ctx.Params("*")) == 0 {
  591. refName = ctx.Repo.Repository.DefaultBranch
  592. ctx.Repo.BranchName = refName
  593. if !ctx.Repo.GitRepo.IsBranchExist(refName) {
  594. brs, err := ctx.Repo.GitRepo.GetBranches()
  595. if err != nil {
  596. ctx.ServerError("GetBranches", err)
  597. return
  598. } else if len(brs) == 0 {
  599. err = fmt.Errorf("No branches in non-empty repository %s",
  600. ctx.Repo.GitRepo.Path)
  601. ctx.ServerError("GetBranches", err)
  602. return
  603. }
  604. refName = brs[0]
  605. }
  606. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  607. if err != nil {
  608. ctx.ServerError("GetBranchCommit", err)
  609. return
  610. }
  611. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  612. ctx.Repo.IsViewBranch = true
  613. } else {
  614. refName = getRefName(ctx, refType)
  615. ctx.Repo.BranchName = refName
  616. if refType.RefTypeIncludesBranches() && ctx.Repo.GitRepo.IsBranchExist(refName) {
  617. ctx.Repo.IsViewBranch = true
  618. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  619. if err != nil {
  620. ctx.ServerError("GetBranchCommit", err)
  621. return
  622. }
  623. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  624. } else if refType.RefTypeIncludesTags() && ctx.Repo.GitRepo.IsTagExist(refName) {
  625. ctx.Repo.IsViewTag = true
  626. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
  627. if err != nil {
  628. ctx.ServerError("GetTagCommit", err)
  629. return
  630. }
  631. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  632. } else if len(refName) == 40 {
  633. ctx.Repo.IsViewCommit = true
  634. ctx.Repo.CommitID = refName
  635. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
  636. if err != nil {
  637. ctx.NotFound("GetCommit", nil)
  638. return
  639. }
  640. } else {
  641. ctx.NotFound("RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
  642. return
  643. }
  644. if refType == RepoRefLegacy {
  645. // redirect from old URL scheme to new URL scheme
  646. ctx.Redirect(path.Join(
  647. setting.AppSubURL,
  648. strings.TrimSuffix(ctx.Req.URL.Path, ctx.Params("*")),
  649. ctx.Repo.BranchNameSubURL(),
  650. ctx.Repo.TreePath))
  651. return
  652. }
  653. }
  654. ctx.Data["BranchName"] = ctx.Repo.BranchName
  655. ctx.Data["BranchNameSubURL"] = ctx.Repo.BranchNameSubURL()
  656. ctx.Data["CommitID"] = ctx.Repo.CommitID
  657. ctx.Data["TreePath"] = ctx.Repo.TreePath
  658. ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch
  659. ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag
  660. ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit
  661. ctx.Data["CanCreateBranch"] = ctx.Repo.CanCreateBranch()
  662. ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
  663. if err != nil {
  664. ctx.ServerError("GetCommitsCount", err)
  665. return
  666. }
  667. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  668. ctx.Next()
  669. }
  670. }
  671. // GitHookService checks if repository Git hooks service has been enabled.
  672. func GitHookService() macaron.Handler {
  673. return func(ctx *Context) {
  674. if !ctx.User.CanEditGitHook() {
  675. ctx.NotFound("GitHookService", nil)
  676. return
  677. }
  678. }
  679. }
  680. // UnitTypes returns a macaron middleware to set unit types to context variables.
  681. func UnitTypes() macaron.Handler {
  682. return func(ctx *Context) {
  683. ctx.Data["UnitTypeCode"] = models.UnitTypeCode
  684. ctx.Data["UnitTypeIssues"] = models.UnitTypeIssues
  685. ctx.Data["UnitTypePullRequests"] = models.UnitTypePullRequests
  686. ctx.Data["UnitTypeReleases"] = models.UnitTypeReleases
  687. ctx.Data["UnitTypeWiki"] = models.UnitTypeWiki
  688. ctx.Data["UnitTypeExternalWiki"] = models.UnitTypeExternalWiki
  689. ctx.Data["UnitTypeExternalTracker"] = models.UnitTypeExternalTracker
  690. }
  691. }