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.

pull.go 19 kB

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
[Enhancement] Allow admin to merge pr with protected file changes (#12078) * [Enhancement] Allow admin to merge pr with protected file changes As tilte, show protected message in diff page and merge box. Signed-off-by: a1012112796 <1012112796@qq.com> * remove unused ver * Update options/locale/locale_en-US.ini Co-authored-by: Cirno the Strongest <1447794+CirnoT@users.noreply.github.com> * Add TrN * Apply suggestions from code review * fix lint * Update options/locale/locale_en-US.ini Co-authored-by: zeripath <art27@cantab.net> * Apply suggestions from code review * move pr proteced files check to TestPatch * Call TestPatch when protected branches settings changed * Apply review suggestion @CirnoT * move to service @lunny * slightly restructure routers/private/hook.go Adds a lot of comments and simplifies the logic Signed-off-by: Andrew Thornton <art27@cantab.net> * placate lint Signed-off-by: Andrew Thornton <art27@cantab.net> * skip duplicate protected files check * fix check logic * slight refactor of TestPatch Signed-off-by: Andrew Thornton <art27@cantab.net> * When checking for protected files changes in TestPatch use the temporary repository Signed-off-by: Andrew Thornton <art27@cantab.net> * fix introduced issue with hook Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove the check on PR index being greater than 0 as it unnecessary Signed-off-by: Andrew Thornton <art27@cantab.net> Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: Cirno the Strongest <1447794+CirnoT@users.noreply.github.com> Co-authored-by: zeripath <art27@cantab.net> Co-authored-by: techknowlogick <techknowlogick@gitea.io>
4 years ago
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
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
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
9 years ago
9 years ago
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
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
Change target branch for pull request (#6488) * Adds functionality to change target branch of created pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use const instead of var in JavaScript additions Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Check if branches are equal and if PR already exists before changing target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Make sure to check all commits Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Print error messages for user as error flash message Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Disallow changing target branch of closed or merged pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Resolve conflicts after merge of upstream/master Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Change order of branch select fields Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes duplicate check Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use ctx.Tr for translations Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Recompile JS Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use correct translation namespace Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove redundant if condition Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves most change branch logic into pull service Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Completes comment Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Add Ref to ChangesPayload for logging changed target branches instead of creating a new struct Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Revert changes to go.mod Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Directly use createComment method Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return 404 if pull request is not found. Move written check up Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove variable declaration Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return client errors on change pull request target errors Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return error in commit.HasPreviousCommit Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds blank line Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Test patch before persisting new target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update patch before testing (not working) Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes patch calls when changeing pull request target Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes unneeded check for base name Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves ChangeTargetBranch completely to pull service. Update patch status. Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Set webhook mode after errors were validated Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update PR in one transaction Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Move logic for check if head is equal with branch to pull model Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds missing comment and simplify return Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adjust CreateComment method call Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com>
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 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 models
  6. import (
  7. "fmt"
  8. "io"
  9. "strings"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/modules/timeutil"
  13. "code.gitea.io/gitea/modules/util"
  14. )
  15. // PullRequestType defines pull request type
  16. type PullRequestType int
  17. // Enumerate all the pull request types
  18. const (
  19. PullRequestGitea PullRequestType = iota
  20. PullRequestGit
  21. )
  22. // PullRequestStatus defines pull request status
  23. type PullRequestStatus int
  24. // Enumerate all the pull request status
  25. const (
  26. PullRequestStatusConflict PullRequestStatus = iota
  27. PullRequestStatusChecking
  28. PullRequestStatusMergeable
  29. PullRequestStatusManuallyMerged
  30. PullRequestStatusError
  31. )
  32. // PullRequest represents relation between pull request and repositories.
  33. type PullRequest struct {
  34. ID int64 `xorm:"pk autoincr"`
  35. Type PullRequestType
  36. Status PullRequestStatus
  37. ConflictedFiles []string `xorm:"TEXT JSON"`
  38. CommitsAhead int
  39. CommitsBehind int
  40. ChangedProtectedFiles []string `xorm:"TEXT JSON"`
  41. IssueID int64 `xorm:"INDEX"`
  42. Issue *Issue `xorm:"-"`
  43. Index int64
  44. HeadRepoID int64 `xorm:"INDEX"`
  45. HeadRepo *Repository `xorm:"-"`
  46. BaseRepoID int64 `xorm:"INDEX"`
  47. BaseRepo *Repository `xorm:"-"`
  48. HeadBranch string
  49. BaseBranch string
  50. ProtectedBranch *ProtectedBranch `xorm:"-"`
  51. MergeBase string `xorm:"VARCHAR(40)"`
  52. HasMerged bool `xorm:"INDEX"`
  53. MergedCommitID string `xorm:"VARCHAR(40)"`
  54. MergerID int64 `xorm:"INDEX"`
  55. Merger *User `xorm:"-"`
  56. MergedUnix timeutil.TimeStamp `xorm:"updated INDEX"`
  57. isHeadRepoLoaded bool `xorm:"-"`
  58. }
  59. // MustHeadUserName returns the HeadRepo's username if failed return blank
  60. func (pr *PullRequest) MustHeadUserName() string {
  61. if err := pr.LoadHeadRepo(); err != nil {
  62. if !IsErrRepoNotExist(err) {
  63. log.Error("LoadHeadRepo: %v", err)
  64. } else {
  65. log.Warn("LoadHeadRepo %d but repository does not exist: %v", pr.HeadRepoID, err)
  66. }
  67. return ""
  68. }
  69. if pr.HeadRepo == nil {
  70. return ""
  71. }
  72. return pr.HeadRepo.OwnerName
  73. }
  74. // Note: don't try to get Issue because will end up recursive querying.
  75. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  76. if pr.HasMerged && pr.Merger == nil {
  77. pr.Merger, err = getUserByID(e, pr.MergerID)
  78. if IsErrUserNotExist(err) {
  79. pr.MergerID = -1
  80. pr.Merger = NewGhostUser()
  81. } else if err != nil {
  82. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  83. }
  84. }
  85. return nil
  86. }
  87. // LoadAttributes loads pull request attributes from database
  88. func (pr *PullRequest) LoadAttributes() error {
  89. return pr.loadAttributes(x)
  90. }
  91. func (pr *PullRequest) loadHeadRepo(e Engine) (err error) {
  92. if !pr.isHeadRepoLoaded && pr.HeadRepo == nil && pr.HeadRepoID > 0 {
  93. if pr.HeadRepoID == pr.BaseRepoID {
  94. if pr.BaseRepo != nil {
  95. pr.HeadRepo = pr.BaseRepo
  96. return nil
  97. } else if pr.Issue != nil && pr.Issue.Repo != nil {
  98. pr.HeadRepo = pr.Issue.Repo
  99. return nil
  100. }
  101. }
  102. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  103. if err != nil && !IsErrRepoNotExist(err) { // Head repo maybe deleted, but it should still work
  104. return fmt.Errorf("getRepositoryByID(head): %v", err)
  105. }
  106. pr.isHeadRepoLoaded = true
  107. }
  108. return nil
  109. }
  110. // LoadHeadRepo loads the head repository
  111. func (pr *PullRequest) LoadHeadRepo() error {
  112. return pr.loadHeadRepo(x)
  113. }
  114. // LoadBaseRepo loads the target repository
  115. func (pr *PullRequest) LoadBaseRepo() error {
  116. return pr.loadBaseRepo(x)
  117. }
  118. func (pr *PullRequest) loadBaseRepo(e Engine) (err error) {
  119. if pr.BaseRepo != nil {
  120. return nil
  121. }
  122. if pr.HeadRepoID == pr.BaseRepoID && pr.HeadRepo != nil {
  123. pr.BaseRepo = pr.HeadRepo
  124. return nil
  125. }
  126. if pr.Issue != nil && pr.Issue.Repo != nil {
  127. pr.BaseRepo = pr.Issue.Repo
  128. return nil
  129. }
  130. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  131. if err != nil {
  132. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  133. }
  134. return nil
  135. }
  136. // LoadIssue loads issue information from database
  137. func (pr *PullRequest) LoadIssue() (err error) {
  138. return pr.loadIssue(x)
  139. }
  140. func (pr *PullRequest) loadIssue(e Engine) (err error) {
  141. if pr.Issue != nil {
  142. return nil
  143. }
  144. pr.Issue, err = getIssueByID(e, pr.IssueID)
  145. if err == nil {
  146. pr.Issue.PullRequest = pr
  147. }
  148. return err
  149. }
  150. // LoadProtectedBranch loads the protected branch of the base branch
  151. func (pr *PullRequest) LoadProtectedBranch() (err error) {
  152. return pr.loadProtectedBranch(x)
  153. }
  154. func (pr *PullRequest) loadProtectedBranch(e Engine) (err error) {
  155. if pr.ProtectedBranch == nil {
  156. if pr.BaseRepo == nil {
  157. if pr.BaseRepoID == 0 {
  158. return nil
  159. }
  160. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  161. if err != nil {
  162. return
  163. }
  164. }
  165. pr.ProtectedBranch, err = getProtectedBranchBy(e, pr.BaseRepo.ID, pr.BaseBranch)
  166. }
  167. return
  168. }
  169. // GetDefaultMergeMessage returns default message used when merging pull request
  170. func (pr *PullRequest) GetDefaultMergeMessage() string {
  171. if pr.HeadRepo == nil {
  172. var err error
  173. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  174. if err != nil {
  175. log.Error("GetRepositoryById[%d]: %v", pr.HeadRepoID, err)
  176. return ""
  177. }
  178. }
  179. if err := pr.LoadIssue(); err != nil {
  180. log.Error("Cannot load issue %d for PR id %d: Error: %v", pr.IssueID, pr.ID, err)
  181. return ""
  182. }
  183. if pr.BaseRepoID == pr.HeadRepoID {
  184. return fmt.Sprintf("Merge pull request '%s' (#%d) from %s into %s", pr.Issue.Title, pr.Issue.Index, pr.HeadBranch, pr.BaseBranch)
  185. }
  186. return fmt.Sprintf("Merge pull request '%s' (#%d) from %s:%s into %s", pr.Issue.Title, pr.Issue.Index, pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseBranch)
  187. }
  188. // ReviewCount represents a count of Reviews
  189. type ReviewCount struct {
  190. IssueID int64
  191. Type ReviewType
  192. Count int64
  193. }
  194. // GetApprovalCounts returns the approval counts by type
  195. // FIXME: Only returns official counts due to double counting of non-official counts
  196. func (pr *PullRequest) GetApprovalCounts() ([]*ReviewCount, error) {
  197. return pr.getApprovalCounts(x)
  198. }
  199. func (pr *PullRequest) getApprovalCounts(e Engine) ([]*ReviewCount, error) {
  200. rCounts := make([]*ReviewCount, 0, 6)
  201. sess := e.Where("issue_id = ?", pr.IssueID)
  202. return rCounts, sess.Select("issue_id, type, count(id) as `count`").Where("official = ? AND dismissed = ?", true, false).GroupBy("issue_id, type").Table("review").Find(&rCounts)
  203. }
  204. // GetApprovers returns the approvers of the pull request
  205. func (pr *PullRequest) GetApprovers() string {
  206. stringBuilder := strings.Builder{}
  207. if err := pr.getReviewedByLines(&stringBuilder); err != nil {
  208. log.Error("Unable to getReviewedByLines: Error: %v", err)
  209. return ""
  210. }
  211. return stringBuilder.String()
  212. }
  213. func (pr *PullRequest) getReviewedByLines(writer io.Writer) error {
  214. maxReviewers := setting.Repository.PullRequest.DefaultMergeMessageMaxApprovers
  215. if maxReviewers == 0 {
  216. return nil
  217. }
  218. sess := x.NewSession()
  219. defer sess.Close()
  220. if err := sess.Begin(); err != nil {
  221. return err
  222. }
  223. // Note: This doesn't page as we only expect a very limited number of reviews
  224. reviews, err := findReviews(sess, FindReviewOptions{
  225. Type: ReviewTypeApprove,
  226. IssueID: pr.IssueID,
  227. OfficialOnly: setting.Repository.PullRequest.DefaultMergeMessageOfficialApproversOnly,
  228. })
  229. if err != nil {
  230. log.Error("Unable to FindReviews for PR ID %d: %v", pr.ID, err)
  231. return err
  232. }
  233. reviewersWritten := 0
  234. for _, review := range reviews {
  235. if maxReviewers > 0 && reviewersWritten > maxReviewers {
  236. break
  237. }
  238. if err := review.loadReviewer(sess); err != nil && !IsErrUserNotExist(err) {
  239. log.Error("Unable to LoadReviewer[%d] for PR ID %d : %v", review.ReviewerID, pr.ID, err)
  240. return err
  241. } else if review.Reviewer == nil {
  242. continue
  243. }
  244. if _, err := writer.Write([]byte("Reviewed-by: ")); err != nil {
  245. return err
  246. }
  247. if _, err := writer.Write([]byte(review.Reviewer.NewGitSig().String())); err != nil {
  248. return err
  249. }
  250. if _, err := writer.Write([]byte{'\n'}); err != nil {
  251. return err
  252. }
  253. reviewersWritten++
  254. }
  255. return sess.Commit()
  256. }
  257. // GetDefaultSquashMessage returns default message used when squash and merging pull request
  258. func (pr *PullRequest) GetDefaultSquashMessage() string {
  259. if err := pr.LoadIssue(); err != nil {
  260. log.Error("LoadIssue: %v", err)
  261. return ""
  262. }
  263. if err := pr.LoadBaseRepo(); err != nil {
  264. log.Error("LoadBaseRepo: %v", err)
  265. return ""
  266. }
  267. if pr.BaseRepo.UnitEnabled(UnitTypeExternalTracker) {
  268. return fmt.Sprintf("%s (!%d)", pr.Issue.Title, pr.Issue.Index)
  269. }
  270. return fmt.Sprintf("%s (#%d)", pr.Issue.Title, pr.Issue.Index)
  271. }
  272. // GetGitRefName returns git ref for hidden pull request branch
  273. func (pr *PullRequest) GetGitRefName() string {
  274. return fmt.Sprintf("refs/pull/%d/head", pr.Index)
  275. }
  276. // IsChecking returns true if this pull request is still checking conflict.
  277. func (pr *PullRequest) IsChecking() bool {
  278. return pr.Status == PullRequestStatusChecking
  279. }
  280. // CanAutoMerge returns true if this pull request can be merged automatically.
  281. func (pr *PullRequest) CanAutoMerge() bool {
  282. return pr.Status == PullRequestStatusMergeable
  283. }
  284. // MergeStyle represents the approach to merge commits into base branch.
  285. type MergeStyle string
  286. const (
  287. // MergeStyleMerge create merge commit
  288. MergeStyleMerge MergeStyle = "merge"
  289. // MergeStyleRebase rebase before merging
  290. MergeStyleRebase MergeStyle = "rebase"
  291. // MergeStyleRebaseMerge rebase before merging with merge commit (--no-ff)
  292. MergeStyleRebaseMerge MergeStyle = "rebase-merge"
  293. // MergeStyleSquash squash commits into single commit before merging
  294. MergeStyleSquash MergeStyle = "squash"
  295. )
  296. // SetMerged sets a pull request to merged and closes the corresponding issue
  297. func (pr *PullRequest) SetMerged() (bool, error) {
  298. if pr.HasMerged {
  299. return false, fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  300. }
  301. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  302. return false, fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  303. }
  304. pr.HasMerged = true
  305. sess := x.NewSession()
  306. defer sess.Close()
  307. if err := sess.Begin(); err != nil {
  308. return false, err
  309. }
  310. if _, err := sess.Exec("UPDATE `issue` SET `repo_id` = `repo_id` WHERE `id` = ?", pr.IssueID); err != nil {
  311. return false, err
  312. }
  313. if _, err := sess.Exec("UPDATE `pull_request` SET `issue_id` = `issue_id` WHERE `id` = ?", pr.ID); err != nil {
  314. return false, err
  315. }
  316. pr.Issue = nil
  317. if err := pr.loadIssue(sess); err != nil {
  318. return false, err
  319. }
  320. if tmpPr, err := getPullRequestByID(sess, pr.ID); err != nil {
  321. return false, err
  322. } else if tmpPr.HasMerged {
  323. if pr.Issue.IsClosed {
  324. return false, nil
  325. }
  326. return false, fmt.Errorf("PullRequest[%d] already merged but it's associated issue [%d] is not closed", pr.Index, pr.IssueID)
  327. } else if pr.Issue.IsClosed {
  328. return false, fmt.Errorf("PullRequest[%d] already closed", pr.Index)
  329. }
  330. if err := pr.Issue.loadRepo(sess); err != nil {
  331. return false, err
  332. }
  333. if err := pr.Issue.Repo.getOwner(sess); err != nil {
  334. return false, err
  335. }
  336. if _, err := pr.Issue.changeStatus(sess, pr.Merger, true, true); err != nil {
  337. return false, fmt.Errorf("Issue.changeStatus: %v", err)
  338. }
  339. if _, err := sess.Where("id = ?", pr.ID).Cols("has_merged, status, merged_commit_id, merger_id, merged_unix").Update(pr); err != nil {
  340. return false, fmt.Errorf("Failed to update pr[%d]: %v", pr.ID, err)
  341. }
  342. if err := sess.Commit(); err != nil {
  343. return false, fmt.Errorf("Commit: %v", err)
  344. }
  345. return true, nil
  346. }
  347. // NewPullRequest creates new pull request with labels for repository.
  348. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
  349. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  350. i := 0
  351. for {
  352. if err = newPullRequestAttempt(repo, pull, labelIDs, uuids, pr); err == nil {
  353. return nil
  354. }
  355. if !IsErrNewIssueInsert(err) {
  356. return err
  357. }
  358. if i++; i == issueMaxDupIndexAttempts {
  359. break
  360. }
  361. log.Error("NewPullRequest: error attempting to insert the new issue; will retry. Original error: %v", err)
  362. }
  363. return fmt.Errorf("NewPullRequest: too many errors attempting to insert the new issue. Last error was: %v", err)
  364. }
  365. func newPullRequestAttempt(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
  366. sess := x.NewSession()
  367. defer sess.Close()
  368. if err = sess.Begin(); err != nil {
  369. return err
  370. }
  371. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  372. Repo: repo,
  373. Issue: pull,
  374. LabelIDs: labelIDs,
  375. Attachments: uuids,
  376. IsPull: true,
  377. }); err != nil {
  378. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  379. return err
  380. }
  381. return fmt.Errorf("newIssue: %v", err)
  382. }
  383. pr.Index = pull.Index
  384. pr.BaseRepo = repo
  385. pr.IssueID = pull.ID
  386. if _, err = sess.Insert(pr); err != nil {
  387. return fmt.Errorf("insert pull repo: %v", err)
  388. }
  389. if err = sess.Commit(); err != nil {
  390. return fmt.Errorf("Commit: %v", err)
  391. }
  392. return nil
  393. }
  394. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  395. // by given head/base and repo/branch.
  396. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  397. pr := new(PullRequest)
  398. has, err := x.
  399. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  400. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  401. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  402. Get(pr)
  403. if err != nil {
  404. return nil, err
  405. } else if !has {
  406. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  407. }
  408. return pr, nil
  409. }
  410. // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
  411. // by given head information (repo and branch).
  412. func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
  413. pr := new(PullRequest)
  414. has, err := x.
  415. Where("head_repo_id = ? AND head_branch = ?", repoID, branch).
  416. OrderBy("id DESC").
  417. Get(pr)
  418. if !has {
  419. return nil, err
  420. }
  421. return pr, err
  422. }
  423. // GetPullRequestByIndex returns a pull request by the given index
  424. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  425. pr := &PullRequest{
  426. BaseRepoID: repoID,
  427. Index: index,
  428. }
  429. has, err := x.Get(pr)
  430. if err != nil {
  431. return nil, err
  432. } else if !has {
  433. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  434. }
  435. if err = pr.LoadAttributes(); err != nil {
  436. return nil, err
  437. }
  438. if err = pr.LoadIssue(); err != nil {
  439. return nil, err
  440. }
  441. return pr, nil
  442. }
  443. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  444. pr := new(PullRequest)
  445. has, err := e.ID(id).Get(pr)
  446. if err != nil {
  447. return nil, err
  448. } else if !has {
  449. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  450. }
  451. return pr, pr.loadAttributes(e)
  452. }
  453. // GetPullRequestByID returns a pull request by given ID.
  454. func GetPullRequestByID(id int64) (*PullRequest, error) {
  455. return getPullRequestByID(x, id)
  456. }
  457. // GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID.
  458. func GetPullRequestByIssueIDWithNoAttributes(issueID int64) (*PullRequest, error) {
  459. var pr PullRequest
  460. has, err := x.Where("issue_id = ?", issueID).Get(&pr)
  461. if err != nil {
  462. return nil, err
  463. }
  464. if !has {
  465. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  466. }
  467. return &pr, nil
  468. }
  469. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  470. pr := &PullRequest{
  471. IssueID: issueID,
  472. }
  473. has, err := e.Get(pr)
  474. if err != nil {
  475. return nil, err
  476. } else if !has {
  477. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  478. }
  479. return pr, pr.loadAttributes(e)
  480. }
  481. // GetPullRequestByIssueID returns pull request by given issue ID.
  482. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  483. return getPullRequestByIssueID(x, issueID)
  484. }
  485. // Update updates all fields of pull request.
  486. func (pr *PullRequest) Update() error {
  487. _, err := x.ID(pr.ID).AllCols().Update(pr)
  488. return err
  489. }
  490. // UpdateCols updates specific fields of pull request.
  491. func (pr *PullRequest) UpdateCols(cols ...string) error {
  492. _, err := x.ID(pr.ID).Cols(cols...).Update(pr)
  493. return err
  494. }
  495. // UpdateColsIfNotMerged updates specific fields of a pull request if it has not been merged
  496. func (pr *PullRequest) UpdateColsIfNotMerged(cols ...string) error {
  497. _, err := x.Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr)
  498. return err
  499. }
  500. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  501. func (pr *PullRequest) IsWorkInProgress() bool {
  502. if err := pr.LoadIssue(); err != nil {
  503. log.Error("LoadIssue: %v", err)
  504. return false
  505. }
  506. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  507. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  508. return true
  509. }
  510. }
  511. return false
  512. }
  513. // IsFilesConflicted determines if the Pull Request has changes conflicting with the target branch.
  514. func (pr *PullRequest) IsFilesConflicted() bool {
  515. return len(pr.ConflictedFiles) > 0
  516. }
  517. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  518. // It returns an empty string when none were found
  519. func (pr *PullRequest) GetWorkInProgressPrefix() string {
  520. if err := pr.LoadIssue(); err != nil {
  521. log.Error("LoadIssue: %v", err)
  522. return ""
  523. }
  524. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  525. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  526. return pr.Issue.Title[0:len(prefix)]
  527. }
  528. }
  529. return ""
  530. }
  531. // UpdateCommitDivergence update Divergence of a pull request
  532. func (pr *PullRequest) UpdateCommitDivergence(ahead, behind int) error {
  533. return pr.updateCommitDivergence(x, ahead, behind)
  534. }
  535. func (pr *PullRequest) updateCommitDivergence(e Engine, ahead, behind int) error {
  536. if pr.ID == 0 {
  537. return fmt.Errorf("pull ID is 0")
  538. }
  539. pr.CommitsAhead = ahead
  540. pr.CommitsBehind = behind
  541. _, err := e.ID(pr.ID).Cols("commits_ahead", "commits_behind").Update(pr)
  542. return err
  543. }
  544. // IsSameRepo returns true if base repo and head repo is the same
  545. func (pr *PullRequest) IsSameRepo() bool {
  546. return pr.BaseRepoID == pr.HeadRepoID
  547. }
  548. // GetBaseBranchHTMLURL returns the HTML URL of the base branch
  549. func (pr *PullRequest) GetBaseBranchHTMLURL() string {
  550. if err := pr.LoadBaseRepo(); err != nil {
  551. log.Error("LoadBaseRepo: %v", err)
  552. return ""
  553. }
  554. if pr.BaseRepo == nil {
  555. return ""
  556. }
  557. return pr.BaseRepo.HTMLURL() + "/src/branch/" + util.PathEscapeSegments(pr.BaseBranch)
  558. }
  559. // GetHeadBranchHTMLURL returns the HTML URL of the head branch
  560. func (pr *PullRequest) GetHeadBranchHTMLURL() string {
  561. if err := pr.LoadHeadRepo(); err != nil {
  562. log.Error("LoadHeadRepo: %v", err)
  563. return ""
  564. }
  565. if pr.HeadRepo == nil {
  566. return ""
  567. }
  568. return pr.HeadRepo.HTMLURL() + "/src/branch/" + util.PathEscapeSegments(pr.HeadBranch)
  569. }