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