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
4 years ago
4 years ago
4 years ago
4 years ago
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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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. )
  14. // PullRequestType defines pull request type
  15. type PullRequestType int
  16. // Enumerate all the pull request types
  17. const (
  18. PullRequestGitea PullRequestType = iota
  19. PullRequestGit
  20. )
  21. // PullRequestStatus defines pull request status
  22. type PullRequestStatus int
  23. // Enumerate all the pull request status
  24. const (
  25. PullRequestStatusConflict PullRequestStatus = iota
  26. PullRequestStatusChecking
  27. PullRequestStatusMergeable
  28. PullRequestStatusManuallyMerged
  29. PullRequestStatusError
  30. )
  31. const (
  32. PullRequestAmountZero int = 0
  33. PullRequestAmountOne int = 100
  34. PullRequestAmountTwo int = 200
  35. PullRequestAmountMax int = 300
  36. )
  37. // PullRequest represents relation between pull request and repositories.
  38. type PullRequest struct {
  39. ID int64 `xorm:"pk autoincr"`
  40. Type PullRequestType
  41. Status PullRequestStatus
  42. ConflictedFiles []string `xorm:"TEXT JSON"`
  43. CommitsAhead int
  44. CommitsBehind int
  45. IssueID int64 `xorm:"INDEX"`
  46. Issue *Issue `xorm:"-"`
  47. Index int64
  48. HeadRepoID int64 `xorm:"INDEX"`
  49. HeadRepo *Repository `xorm:"-"`
  50. BaseRepoID int64 `xorm:"INDEX"`
  51. BaseRepo *Repository `xorm:"-"`
  52. HeadBranch string
  53. BaseBranch string
  54. ProtectedBranch *ProtectedBranch `xorm:"-"`
  55. MergeBase string `xorm:"VARCHAR(40)"`
  56. HasMerged bool `xorm:"INDEX"`
  57. MergedCommitID string `xorm:"VARCHAR(40)"`
  58. MergerID int64 `xorm:"INDEX"`
  59. Merger *User `xorm:"-"`
  60. MergedUnix timeutil.TimeStamp `xorm:"updated INDEX"`
  61. isHeadRepoLoaded bool `xorm:"-"`
  62. //block_chain
  63. IsTransformed bool `xorm:"INDEX NOT NULL DEFAULT false"`
  64. Amount int `xorm:"INDEX NOT NULL DEFAULT 0"`
  65. }
  66. // MustHeadUserName returns the HeadRepo's username if failed return blank
  67. func (pr *PullRequest) MustHeadUserName() string {
  68. if err := pr.LoadHeadRepo(); err != nil {
  69. if !IsErrRepoNotExist(err) {
  70. log.Error("LoadHeadRepo: %v", err)
  71. } else {
  72. log.Warn("LoadHeadRepo %d but repository does not exist: %v", pr.HeadRepoID, err)
  73. }
  74. return ""
  75. }
  76. if pr.HeadRepo == nil {
  77. return ""
  78. }
  79. return pr.HeadRepo.OwnerName
  80. }
  81. // Note: don't try to get Issue because will end up recursive querying.
  82. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  83. if pr.HasMerged && pr.Merger == nil {
  84. pr.Merger, err = getUserByID(e, pr.MergerID)
  85. if IsErrUserNotExist(err) {
  86. pr.MergerID = -1
  87. pr.Merger = NewGhostUser()
  88. } else if err != nil {
  89. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  90. }
  91. }
  92. return nil
  93. }
  94. // LoadAttributes loads pull request attributes from database
  95. func (pr *PullRequest) LoadAttributes() error {
  96. return pr.loadAttributes(x)
  97. }
  98. func (pr *PullRequest) loadHeadRepo(e Engine) (err error) {
  99. if !pr.isHeadRepoLoaded && pr.HeadRepo == nil && pr.HeadRepoID > 0 {
  100. if pr.HeadRepoID == pr.BaseRepoID {
  101. if pr.BaseRepo != nil {
  102. pr.HeadRepo = pr.BaseRepo
  103. return nil
  104. } else if pr.Issue != nil && pr.Issue.Repo != nil {
  105. pr.HeadRepo = pr.Issue.Repo
  106. return nil
  107. }
  108. }
  109. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  110. if err != nil && !IsErrRepoNotExist(err) { // Head repo maybe deleted, but it should still work
  111. return fmt.Errorf("getRepositoryByID(head): %v", err)
  112. }
  113. pr.isHeadRepoLoaded = true
  114. }
  115. return nil
  116. }
  117. // LoadHeadRepo loads the head repository
  118. func (pr *PullRequest) LoadHeadRepo() error {
  119. return pr.loadHeadRepo(x)
  120. }
  121. // LoadBaseRepo loads the target repository
  122. func (pr *PullRequest) LoadBaseRepo() error {
  123. return pr.loadBaseRepo(x)
  124. }
  125. func (pr *PullRequest) loadBaseRepo(e Engine) (err error) {
  126. if pr.BaseRepo != nil {
  127. return nil
  128. }
  129. if pr.HeadRepoID == pr.BaseRepoID && pr.HeadRepo != nil {
  130. pr.BaseRepo = pr.HeadRepo
  131. return nil
  132. }
  133. if pr.Issue != nil && pr.Issue.Repo != nil {
  134. pr.BaseRepo = pr.Issue.Repo
  135. return nil
  136. }
  137. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  138. if err != nil {
  139. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  140. }
  141. return nil
  142. }
  143. // LoadIssue loads issue information from database
  144. func (pr *PullRequest) LoadIssue() (err error) {
  145. return pr.loadIssue(x)
  146. }
  147. func (pr *PullRequest) loadIssue(e Engine) (err error) {
  148. if pr.Issue != nil {
  149. return nil
  150. }
  151. pr.Issue, err = getIssueByID(e, pr.IssueID)
  152. if err == nil {
  153. pr.Issue.PullRequest = pr
  154. }
  155. return err
  156. }
  157. // LoadProtectedBranch loads the protected branch of the base branch
  158. func (pr *PullRequest) LoadProtectedBranch() (err error) {
  159. return pr.loadProtectedBranch(x)
  160. }
  161. func (pr *PullRequest) loadProtectedBranch(e Engine) (err error) {
  162. if pr.ProtectedBranch == nil {
  163. if pr.BaseRepo == nil {
  164. if pr.BaseRepoID == 0 {
  165. return nil
  166. }
  167. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  168. if err != nil {
  169. return
  170. }
  171. }
  172. pr.ProtectedBranch, err = getProtectedBranchBy(e, pr.BaseRepo.ID, pr.BaseBranch)
  173. }
  174. return
  175. }
  176. // GetDefaultMergeMessage returns default message used when merging pull request
  177. func (pr *PullRequest) GetDefaultMergeMessage() string {
  178. if pr.HeadRepo == nil {
  179. var err error
  180. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  181. if err != nil {
  182. log.Error("GetRepositoryById[%d]: %v", pr.HeadRepoID, err)
  183. return ""
  184. }
  185. }
  186. if err := pr.LoadIssue(); err != nil {
  187. log.Error("Cannot load issue %d for PR id %d: Error: %v", pr.IssueID, pr.ID, err)
  188. return ""
  189. }
  190. if pr.BaseRepoID == pr.HeadRepoID {
  191. return fmt.Sprintf("Merge pull request '%s' (#%d) from %s into %s", pr.Issue.Title, pr.Issue.Index, pr.HeadBranch, pr.BaseBranch)
  192. }
  193. 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)
  194. }
  195. // ReviewCount represents a count of Reviews
  196. type ReviewCount struct {
  197. IssueID int64
  198. Type ReviewType
  199. Count int64
  200. }
  201. // GetApprovalCounts returns the approval counts by type
  202. // FIXME: Only returns official counts due to double counting of non-official counts
  203. func (pr *PullRequest) GetApprovalCounts() ([]*ReviewCount, error) {
  204. return pr.getApprovalCounts(x)
  205. }
  206. func (pr *PullRequest) getApprovalCounts(e Engine) ([]*ReviewCount, error) {
  207. rCounts := make([]*ReviewCount, 0, 6)
  208. sess := e.Where("issue_id = ?", pr.IssueID)
  209. return rCounts, sess.Select("issue_id, type, count(id) as `count`").Where("official = ?", true).GroupBy("issue_id, type").Table("review").Find(&rCounts)
  210. }
  211. // GetApprovers returns the approvers of the pull request
  212. func (pr *PullRequest) GetApprovers() string {
  213. stringBuilder := strings.Builder{}
  214. if err := pr.getReviewedByLines(&stringBuilder); err != nil {
  215. log.Error("Unable to getReviewedByLines: Error: %v", err)
  216. return ""
  217. }
  218. return stringBuilder.String()
  219. }
  220. func (pr *PullRequest) getReviewedByLines(writer io.Writer) error {
  221. maxReviewers := setting.Repository.PullRequest.DefaultMergeMessageMaxApprovers
  222. if maxReviewers == 0 {
  223. return nil
  224. }
  225. sess := x.NewSession()
  226. defer sess.Close()
  227. if err := sess.Begin(); err != nil {
  228. return err
  229. }
  230. // Note: This doesn't page as we only expect a very limited number of reviews
  231. reviews, err := findReviews(sess, FindReviewOptions{
  232. Type: ReviewTypeApprove,
  233. IssueID: pr.IssueID,
  234. OfficialOnly: setting.Repository.PullRequest.DefaultMergeMessageOfficialApproversOnly,
  235. })
  236. if err != nil {
  237. log.Error("Unable to FindReviews for PR ID %d: %v", pr.ID, err)
  238. return err
  239. }
  240. reviewersWritten := 0
  241. for _, review := range reviews {
  242. if maxReviewers > 0 && reviewersWritten > maxReviewers {
  243. break
  244. }
  245. if err := review.loadReviewer(sess); err != nil && !IsErrUserNotExist(err) {
  246. log.Error("Unable to LoadReviewer[%d] for PR ID %d : %v", review.ReviewerID, pr.ID, err)
  247. return err
  248. } else if review.Reviewer == nil {
  249. continue
  250. }
  251. if _, err := writer.Write([]byte("Reviewed-by: ")); err != nil {
  252. return err
  253. }
  254. if _, err := writer.Write([]byte(review.Reviewer.NewGitSig().String())); err != nil {
  255. return err
  256. }
  257. if _, err := writer.Write([]byte{'\n'}); err != nil {
  258. return err
  259. }
  260. reviewersWritten++
  261. }
  262. return sess.Commit()
  263. }
  264. // GetDefaultSquashMessage returns default message used when squash and merging pull request
  265. func (pr *PullRequest) GetDefaultSquashMessage() string {
  266. if err := pr.LoadIssue(); err != nil {
  267. log.Error("LoadIssue: %v", err)
  268. return ""
  269. }
  270. if err := pr.LoadBaseRepo(); err != nil {
  271. log.Error("LoadBaseRepo: %v", err)
  272. return ""
  273. }
  274. if pr.BaseRepo.UnitEnabled(UnitTypeExternalTracker) {
  275. return fmt.Sprintf("%s (!%d)", pr.Issue.Title, pr.Issue.Index)
  276. }
  277. return fmt.Sprintf("%s (#%d)", pr.Issue.Title, pr.Issue.Index)
  278. }
  279. // GetGitRefName returns git ref for hidden pull request branch
  280. func (pr *PullRequest) GetGitRefName() string {
  281. return fmt.Sprintf("refs/pull/%d/head", pr.Index)
  282. }
  283. // IsChecking returns true if this pull request is still checking conflict.
  284. func (pr *PullRequest) IsChecking() bool {
  285. return pr.Status == PullRequestStatusChecking
  286. }
  287. // CanAutoMerge returns true if this pull request can be merged automatically.
  288. func (pr *PullRequest) CanAutoMerge() bool {
  289. return pr.Status == PullRequestStatusMergeable
  290. }
  291. // MergeStyle represents the approach to merge commits into base branch.
  292. type MergeStyle string
  293. const (
  294. // MergeStyleMerge create merge commit
  295. MergeStyleMerge MergeStyle = "merge"
  296. // MergeStyleRebase rebase before merging
  297. MergeStyleRebase MergeStyle = "rebase"
  298. // MergeStyleRebaseMerge rebase before merging with merge commit (--no-ff)
  299. MergeStyleRebaseMerge MergeStyle = "rebase-merge"
  300. // MergeStyleSquash squash commits into single commit before merging
  301. MergeStyleSquash MergeStyle = "squash"
  302. )
  303. // SetMerged sets a pull request to merged and closes the corresponding issue
  304. func (pr *PullRequest) SetMerged() (bool, error) {
  305. if pr.HasMerged {
  306. return false, fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  307. }
  308. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  309. return false, fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  310. }
  311. pr.HasMerged = true
  312. sess := x.NewSession()
  313. defer sess.Close()
  314. if err := sess.Begin(); err != nil {
  315. return false, err
  316. }
  317. if _, err := sess.Exec("UPDATE `issue` SET `repo_id` = `repo_id` WHERE `id` = ?", pr.IssueID); err != nil {
  318. return false, err
  319. }
  320. if _, err := sess.Exec("UPDATE `pull_request` SET `issue_id` = `issue_id` WHERE `id` = ?", pr.ID); err != nil {
  321. return false, err
  322. }
  323. pr.Issue = nil
  324. if err := pr.loadIssue(sess); err != nil {
  325. return false, err
  326. }
  327. if tmpPr, err := getPullRequestByID(sess, pr.ID); err != nil {
  328. return false, err
  329. } else if tmpPr.HasMerged {
  330. if pr.Issue.IsClosed {
  331. return false, nil
  332. }
  333. return false, fmt.Errorf("PullRequest[%d] already merged but it's associated issue [%d] is not closed", pr.Index, pr.IssueID)
  334. } else if pr.Issue.IsClosed {
  335. return false, fmt.Errorf("PullRequest[%d] already closed", pr.Index)
  336. }
  337. if err := pr.Issue.loadRepo(sess); err != nil {
  338. return false, err
  339. }
  340. if err := pr.Issue.Repo.getOwner(sess); err != nil {
  341. return false, err
  342. }
  343. if _, err := pr.Issue.changeStatus(sess, pr.Merger, true, true); err != nil {
  344. return false, fmt.Errorf("Issue.changeStatus: %v", err)
  345. }
  346. if _, err := sess.Where("id = ?", pr.ID).Cols("has_merged, status, merged_commit_id, merger_id, merged_unix, amount").Update(pr); err != nil {
  347. return false, fmt.Errorf("Failed to update pr[%d]: %v", pr.ID, err)
  348. }
  349. if err := sess.Commit(); err != nil {
  350. return false, fmt.Errorf("Commit: %v", err)
  351. }
  352. return true, nil
  353. }
  354. // NewPullRequest creates new pull request with labels for repository.
  355. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
  356. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  357. i := 0
  358. for {
  359. if err = newPullRequestAttempt(repo, pull, labelIDs, uuids, pr); err == nil {
  360. return nil
  361. }
  362. if !IsErrNewIssueInsert(err) {
  363. return err
  364. }
  365. if i++; i == issueMaxDupIndexAttempts {
  366. break
  367. }
  368. log.Error("NewPullRequest: error attempting to insert the new issue; will retry. Original error: %v", err)
  369. }
  370. return fmt.Errorf("NewPullRequest: too many errors attempting to insert the new issue. Last error was: %v", err)
  371. }
  372. func newPullRequestAttempt(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
  373. sess := x.NewSession()
  374. defer sess.Close()
  375. if err = sess.Begin(); err != nil {
  376. return err
  377. }
  378. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  379. Repo: repo,
  380. Issue: pull,
  381. LabelIDs: labelIDs,
  382. Attachments: uuids,
  383. IsPull: true,
  384. }); err != nil {
  385. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  386. return err
  387. }
  388. return fmt.Errorf("newIssue: %v", err)
  389. }
  390. pr.Index = pull.Index
  391. pr.BaseRepo = repo
  392. pr.IssueID = pull.ID
  393. if _, err = sess.Insert(pr); err != nil {
  394. return fmt.Errorf("insert pull repo: %v", err)
  395. }
  396. if err = sess.Commit(); err != nil {
  397. return fmt.Errorf("Commit: %v", err)
  398. }
  399. return nil
  400. }
  401. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  402. // by given head/base and repo/branch.
  403. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  404. pr := new(PullRequest)
  405. has, err := x.
  406. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  407. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  408. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  409. Get(pr)
  410. if err != nil {
  411. return nil, err
  412. } else if !has {
  413. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  414. }
  415. return pr, nil
  416. }
  417. // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
  418. // by given head information (repo and branch).
  419. func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
  420. pr := new(PullRequest)
  421. has, err := x.
  422. Where("head_repo_id = ? AND head_branch = ?", repoID, branch).
  423. OrderBy("id DESC").
  424. Get(pr)
  425. if !has {
  426. return nil, err
  427. }
  428. return pr, err
  429. }
  430. // GetPullRequestByIndex returns a pull request by the given index
  431. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  432. pr := &PullRequest{
  433. BaseRepoID: repoID,
  434. Index: index,
  435. }
  436. has, err := x.Get(pr)
  437. if err != nil {
  438. return nil, err
  439. } else if !has {
  440. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  441. }
  442. if err = pr.LoadAttributes(); err != nil {
  443. return nil, err
  444. }
  445. if err = pr.LoadIssue(); err != nil {
  446. return nil, err
  447. }
  448. return pr, nil
  449. }
  450. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  451. pr := new(PullRequest)
  452. has, err := e.ID(id).Get(pr)
  453. if err != nil {
  454. return nil, err
  455. } else if !has {
  456. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  457. }
  458. return pr, pr.loadAttributes(e)
  459. }
  460. // GetPullRequestByID returns a pull request by given ID.
  461. func GetPullRequestByID(id int64) (*PullRequest, error) {
  462. return getPullRequestByID(x, id)
  463. }
  464. // GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID.
  465. func GetPullRequestByIssueIDWithNoAttributes(issueID int64) (*PullRequest, error) {
  466. var pr PullRequest
  467. has, err := x.Where("issue_id = ?", issueID).Get(&pr)
  468. if err != nil {
  469. return nil, err
  470. }
  471. if !has {
  472. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  473. }
  474. return &pr, nil
  475. }
  476. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  477. pr := &PullRequest{
  478. IssueID: issueID,
  479. }
  480. has, err := e.Get(pr)
  481. if err != nil {
  482. return nil, err
  483. } else if !has {
  484. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  485. }
  486. return pr, pr.loadAttributes(e)
  487. }
  488. // GetPullRequestByIssueID returns pull request by given issue ID.
  489. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  490. return getPullRequestByIssueID(x, issueID)
  491. }
  492. // Update updates all fields of pull request.
  493. func (pr *PullRequest) Update() error {
  494. _, err := x.ID(pr.ID).AllCols().Update(pr)
  495. return err
  496. }
  497. // UpdateCols updates specific fields of pull request.
  498. func (pr *PullRequest) UpdateCols(cols ...string) error {
  499. _, err := x.ID(pr.ID).Cols(cols...).Update(pr)
  500. return err
  501. }
  502. // UpdateColsIfNotMerged updates specific fields of a pull request if it has not been merged
  503. func (pr *PullRequest) UpdateColsIfNotMerged(cols ...string) error {
  504. _, err := x.Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr)
  505. return err
  506. }
  507. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  508. func (pr *PullRequest) IsWorkInProgress() bool {
  509. if err := pr.LoadIssue(); err != nil {
  510. log.Error("LoadIssue: %v", err)
  511. return false
  512. }
  513. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  514. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  515. return true
  516. }
  517. }
  518. return false
  519. }
  520. // IsFilesConflicted determines if the Pull Request has changes conflicting with the target branch.
  521. func (pr *PullRequest) IsFilesConflicted() bool {
  522. return len(pr.ConflictedFiles) > 0
  523. }
  524. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  525. // It returns an empty string when none were found
  526. func (pr *PullRequest) GetWorkInProgressPrefix() string {
  527. if err := pr.LoadIssue(); err != nil {
  528. log.Error("LoadIssue: %v", err)
  529. return ""
  530. }
  531. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  532. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  533. return pr.Issue.Title[0:len(prefix)]
  534. }
  535. }
  536. return ""
  537. }
  538. // UpdateCommitDivergence update Divergence of a pull request
  539. func (pr *PullRequest) UpdateCommitDivergence(ahead, behind int) error {
  540. return pr.updateCommitDivergence(x, ahead, behind)
  541. }
  542. func (pr *PullRequest) updateCommitDivergence(e Engine, ahead, behind int) error {
  543. if pr.ID == 0 {
  544. return fmt.Errorf("pull ID is 0")
  545. }
  546. pr.CommitsAhead = ahead
  547. pr.CommitsBehind = behind
  548. _, err := e.ID(pr.ID).Cols("commits_ahead", "commits_behind").Update(pr)
  549. return err
  550. }
  551. // IsSameRepo returns true if base repo and head repo is the same
  552. func (pr *PullRequest) IsSameRepo() bool {
  553. return pr.BaseRepoID == pr.HeadRepoID
  554. }