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

638 lines
18 KiB

Improve listing performance by using go-git (#6478) * Use go-git for tree reading and commit info lookup. Signed-off-by: Filip Navara <navara@emclient.com> * Use TreeEntry.IsRegular() instead of ObjectType that was removed. Signed-off-by: Filip Navara <navara@emclient.com> * Use the treePath to optimize commit info search. Signed-off-by: Filip Navara <navara@emclient.com> * Extract the latest commit at treePath along with the other commits. Signed-off-by: Filip Navara <navara@emclient.com> * Fix listing commit info for a directory that was created in one commit and never modified after. Signed-off-by: Filip Navara <navara@emclient.com> * Avoid nearly all external 'git' invocations when doing directory listing (.editorconfig code path is still hit). Signed-off-by: Filip Navara <navara@emclient.com> * Use go-git for reading blobs. Signed-off-by: Filip Navara <navara@emclient.com> * Make SHA1 type alias for plumbing.Hash in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Make Signature type alias for object.Signature in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Fix GetCommitsInfo for repository with only one commit. Signed-off-by: Filip Navara <navara@emclient.com> * Fix PGP signature verification. Signed-off-by: Filip Navara <navara@emclient.com> * Fix issues with walking commit graph across merges. Signed-off-by: Filip Navara <navara@emclient.com> * Fix typo in condition. Signed-off-by: Filip Navara <navara@emclient.com> * Speed up loading branch list by keeping the repository reference (and thus all the loaded packfile indexes). Signed-off-by: Filip Navara <navara@emclient.com> * Fix lising submodules. Signed-off-by: Filip Navara <navara@emclient.com> * Fix build Signed-off-by: Filip Navara <navara@emclient.com> * Add back commit cache because of name-rev Signed-off-by: Filip Navara <navara@emclient.com> * Fix tests Signed-off-by: Filip Navara <navara@emclient.com> * Fix code style * Fix spelling * Address PR feedback Signed-off-by: Filip Navara <navara@emclient.com> * Update vendor module list Signed-off-by: Filip Navara <navara@emclient.com> * Fix getting trees by commit id Signed-off-by: Filip Navara <navara@emclient.com> * Fix remaining unit test failures * Fix GetTreeBySHA * Avoid running `git name-rev` if not necessary Signed-off-by: Filip Navara <navara@emclient.com> * Move Branch code to git module * Clean up GPG signature verification and fix it for tagged commits * Address PR feedback (import formatting, copyright headers) * Make blob lookup by SHA working * Update tests to use public API * Allow getting content from any type of object through the blob interface * Change test to actually expect the object content that is in the GIT repository * Change one more test to actually expect the object content that is in the GIT repository * Add comments
5 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
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>
4 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>
4 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>
4 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>
4 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>
4 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>
4 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>
4 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>
4 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>
4 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>
4 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>
4 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>
4 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>
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
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
5 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>
4 years ago
  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. // PullRequest represents relation between pull request and repositories.
  32. type PullRequest struct {
  33. ID int64 `xorm:"pk autoincr"`
  34. Type PullRequestType
  35. Status PullRequestStatus
  36. ConflictedFiles []string `xorm:"TEXT JSON"`
  37. CommitsAhead int
  38. CommitsBehind int
  39. IssueID int64 `xorm:"INDEX"`
  40. Issue *Issue `xorm:"-"`
  41. Index int64
  42. HeadRepoID int64 `xorm:"INDEX"`
  43. HeadRepo *Repository `xorm:"-"`
  44. BaseRepoID int64 `xorm:"INDEX"`
  45. BaseRepo *Repository `xorm:"-"`
  46. HeadBranch string
  47. BaseBranch string
  48. ProtectedBranch *ProtectedBranch `xorm:"-"`
  49. MergeBase string `xorm:"VARCHAR(40)"`
  50. HasMerged bool `xorm:"INDEX"`
  51. MergedCommitID string `xorm:"VARCHAR(40)"`
  52. MergerID int64 `xorm:"INDEX"`
  53. Merger *User `xorm:"-"`
  54. MergedUnix timeutil.TimeStamp `xorm:"updated INDEX"`
  55. isHeadRepoLoaded bool `xorm:"-"`
  56. }
  57. // MustHeadUserName returns the HeadRepo's username if failed return blank
  58. func (pr *PullRequest) MustHeadUserName() string {
  59. if err := pr.LoadHeadRepo(); err != nil {
  60. if !IsErrRepoNotExist(err) {
  61. log.Error("LoadHeadRepo: %v", err)
  62. } else {
  63. log.Warn("LoadHeadRepo %d but repository does not exist: %v", pr.HeadRepoID, err)
  64. }
  65. return ""
  66. }
  67. if pr.HeadRepo == nil {
  68. return ""
  69. }
  70. return pr.HeadRepo.OwnerName
  71. }
  72. // Note: don't try to get Issue because will end up recursive querying.
  73. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  74. if pr.HasMerged && pr.Merger == nil {
  75. pr.Merger, err = getUserByID(e, pr.MergerID)
  76. if IsErrUserNotExist(err) {
  77. pr.MergerID = -1
  78. pr.Merger = NewGhostUser()
  79. } else if err != nil {
  80. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  81. }
  82. }
  83. return nil
  84. }
  85. // LoadAttributes loads pull request attributes from database
  86. func (pr *PullRequest) LoadAttributes() error {
  87. return pr.loadAttributes(x)
  88. }
  89. func (pr *PullRequest) loadHeadRepo(e Engine) (err error) {
  90. if !pr.isHeadRepoLoaded && pr.HeadRepo == nil && pr.HeadRepoID > 0 {
  91. if pr.HeadRepoID == pr.BaseRepoID {
  92. if pr.BaseRepo != nil {
  93. pr.HeadRepo = pr.BaseRepo
  94. return nil
  95. } else if pr.Issue != nil && pr.Issue.Repo != nil {
  96. pr.HeadRepo = pr.Issue.Repo
  97. return nil
  98. }
  99. }
  100. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  101. if err != nil && !IsErrRepoNotExist(err) { // Head repo maybe deleted, but it should still work
  102. return fmt.Errorf("getRepositoryByID(head): %v", err)
  103. }
  104. pr.isHeadRepoLoaded = true
  105. }
  106. return nil
  107. }
  108. // LoadHeadRepo loads the head repository
  109. func (pr *PullRequest) LoadHeadRepo() error {
  110. return pr.loadHeadRepo(x)
  111. }
  112. // LoadBaseRepo loads the target repository
  113. func (pr *PullRequest) LoadBaseRepo() error {
  114. return pr.loadBaseRepo(x)
  115. }
  116. func (pr *PullRequest) loadBaseRepo(e Engine) (err error) {
  117. if pr.BaseRepo != nil {
  118. return nil
  119. }
  120. if pr.HeadRepoID == pr.BaseRepoID && pr.HeadRepo != nil {
  121. pr.BaseRepo = pr.HeadRepo
  122. return nil
  123. }
  124. if pr.Issue != nil && pr.Issue.Repo != nil {
  125. pr.BaseRepo = pr.Issue.Repo
  126. return nil
  127. }
  128. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  129. if err != nil {
  130. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  131. }
  132. return nil
  133. }
  134. // LoadIssue loads issue information from database
  135. func (pr *PullRequest) LoadIssue() (err error) {
  136. return pr.loadIssue(x)
  137. }
  138. func (pr *PullRequest) loadIssue(e Engine) (err error) {
  139. if pr.Issue != nil {
  140. return nil
  141. }
  142. pr.Issue, err = getIssueByID(e, pr.IssueID)
  143. if err == nil {
  144. pr.Issue.PullRequest = pr
  145. }
  146. return err
  147. }
  148. // LoadProtectedBranch loads the protected branch of the base branch
  149. func (pr *PullRequest) LoadProtectedBranch() (err error) {
  150. return pr.loadProtectedBranch(x)
  151. }
  152. func (pr *PullRequest) loadProtectedBranch(e Engine) (err error) {
  153. if pr.ProtectedBranch == nil {
  154. if pr.BaseRepo == nil {
  155. if pr.BaseRepoID == 0 {
  156. return nil
  157. }
  158. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  159. if err != nil {
  160. return
  161. }
  162. }
  163. pr.ProtectedBranch, err = getProtectedBranchBy(e, pr.BaseRepo.ID, pr.BaseBranch)
  164. }
  165. return
  166. }
  167. // GetDefaultMergeMessage returns default message used when merging pull request
  168. func (pr *PullRequest) GetDefaultMergeMessage() string {
  169. if pr.HeadRepo == nil {
  170. var err error
  171. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  172. if err != nil {
  173. log.Error("GetRepositoryById[%d]: %v", pr.HeadRepoID, err)
  174. return ""
  175. }
  176. }
  177. if err := pr.LoadIssue(); err != nil {
  178. log.Error("Cannot load issue %d for PR id %d: Error: %v", pr.IssueID, pr.ID, err)
  179. return ""
  180. }
  181. if pr.BaseRepoID == pr.HeadRepoID {
  182. return fmt.Sprintf("Merge pull request '%s' (#%d) from %s into %s", pr.Issue.Title, pr.Issue.Index, pr.HeadBranch, pr.BaseBranch)
  183. }
  184. 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)
  185. }
  186. // ReviewCount represents a count of Reviews
  187. type ReviewCount struct {
  188. IssueID int64
  189. Type ReviewType
  190. Count int64
  191. }
  192. // GetApprovalCounts returns the approval counts by type
  193. // FIXME: Only returns official counts due to double counting of non-official counts
  194. func (pr *PullRequest) GetApprovalCounts() ([]*ReviewCount, error) {
  195. return pr.getApprovalCounts(x)
  196. }
  197. func (pr *PullRequest) getApprovalCounts(e Engine) ([]*ReviewCount, error) {
  198. rCounts := make([]*ReviewCount, 0, 6)
  199. sess := e.Where("issue_id = ?", pr.IssueID)
  200. return rCounts, sess.Select("issue_id, type, count(id) as `count`").Where("official = ?", true).GroupBy("issue_id, type").Table("review").Find(&rCounts)
  201. }
  202. // GetApprovers returns the approvers of the pull request
  203. func (pr *PullRequest) GetApprovers() string {
  204. stringBuilder := strings.Builder{}
  205. if err := pr.getReviewedByLines(&stringBuilder); err != nil {
  206. log.Error("Unable to getReviewedByLines: Error: %v", err)
  207. return ""
  208. }
  209. return stringBuilder.String()
  210. }
  211. func (pr *PullRequest) getReviewedByLines(writer io.Writer) error {
  212. maxReviewers := setting.Repository.PullRequest.DefaultMergeMessageMaxApprovers
  213. if maxReviewers == 0 {
  214. return nil
  215. }
  216. sess := x.NewSession()
  217. defer sess.Close()
  218. if err := sess.Begin(); err != nil {
  219. return err
  220. }
  221. // Note: This doesn't page as we only expect a very limited number of reviews
  222. reviews, err := findReviews(sess, FindReviewOptions{
  223. Type: ReviewTypeApprove,
  224. IssueID: pr.IssueID,
  225. OfficialOnly: setting.Repository.PullRequest.DefaultMergeMessageOfficialApproversOnly,
  226. })
  227. if err != nil {
  228. log.Error("Unable to FindReviews for PR ID %d: %v", pr.ID, err)
  229. return err
  230. }
  231. reviewersWritten := 0
  232. for _, review := range reviews {
  233. if maxReviewers > 0 && reviewersWritten > maxReviewers {
  234. break
  235. }
  236. if err := review.loadReviewer(sess); err != nil && !IsErrUserNotExist(err) {
  237. log.Error("Unable to LoadReviewer[%d] for PR ID %d : %v", review.ReviewerID, pr.ID, err)
  238. return err
  239. } else if review.Reviewer == nil {
  240. continue
  241. }
  242. if _, err := writer.Write([]byte("Reviewed-by: ")); err != nil {
  243. return err
  244. }
  245. if _, err := writer.Write([]byte(review.Reviewer.NewGitSig().String())); err != nil {
  246. return err
  247. }
  248. if _, err := writer.Write([]byte{'\n'}); err != nil {
  249. return err
  250. }
  251. reviewersWritten++
  252. }
  253. return sess.Commit()
  254. }
  255. // GetDefaultSquashMessage returns default message used when squash and merging pull request
  256. func (pr *PullRequest) GetDefaultSquashMessage() string {
  257. if err := pr.LoadIssue(); err != nil {
  258. log.Error("LoadIssue: %v", err)
  259. return ""
  260. }
  261. if err := pr.LoadBaseRepo(); err != nil {
  262. log.Error("LoadBaseRepo: %v", err)
  263. return ""
  264. }
  265. if pr.BaseRepo.UnitEnabled(UnitTypeExternalTracker) {
  266. return fmt.Sprintf("%s (!%d)", pr.Issue.Title, pr.Issue.Index)
  267. }
  268. return fmt.Sprintf("%s (#%d)", pr.Issue.Title, pr.Issue.Index)
  269. }
  270. // GetGitRefName returns git ref for hidden pull request branch
  271. func (pr *PullRequest) GetGitRefName() string {
  272. return fmt.Sprintf("refs/pull/%d/head", pr.Index)
  273. }
  274. // IsChecking returns true if this pull request is still checking conflict.
  275. func (pr *PullRequest) IsChecking() bool {
  276. return pr.Status == PullRequestStatusChecking
  277. }
  278. // CanAutoMerge returns true if this pull request can be merged automatically.
  279. func (pr *PullRequest) CanAutoMerge() bool {
  280. return pr.Status == PullRequestStatusMergeable
  281. }
  282. // MergeStyle represents the approach to merge commits into base branch.
  283. type MergeStyle string
  284. const (
  285. // MergeStyleMerge create merge commit
  286. MergeStyleMerge MergeStyle = "merge"
  287. // MergeStyleRebase rebase before merging
  288. MergeStyleRebase MergeStyle = "rebase"
  289. // MergeStyleRebaseMerge rebase before merging with merge commit (--no-ff)
  290. MergeStyleRebaseMerge MergeStyle = "rebase-merge"
  291. // MergeStyleSquash squash commits into single commit before merging
  292. MergeStyleSquash MergeStyle = "squash"
  293. )
  294. // SetMerged sets a pull request to merged and closes the corresponding issue
  295. func (pr *PullRequest) SetMerged() (bool, error) {
  296. if pr.HasMerged {
  297. return false, fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  298. }
  299. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  300. return false, fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  301. }
  302. pr.HasMerged = true
  303. sess := x.NewSession()
  304. defer sess.Close()
  305. if err := sess.Begin(); err != nil {
  306. return false, err
  307. }
  308. if _, err := sess.Exec("UPDATE `issue` SET `repo_id` = `repo_id` WHERE `id` = ?", pr.IssueID); err != nil {
  309. return false, err
  310. }
  311. if _, err := sess.Exec("UPDATE `pull_request` SET `issue_id` = `issue_id` WHERE `id` = ?", pr.ID); err != nil {
  312. return false, err
  313. }
  314. pr.Issue = nil
  315. if err := pr.loadIssue(sess); err != nil {
  316. return false, err
  317. }
  318. if tmpPr, err := getPullRequestByID(sess, pr.ID); err != nil {
  319. return false, err
  320. } else if tmpPr.HasMerged {
  321. if pr.Issue.IsClosed {
  322. return false, nil
  323. }
  324. return false, fmt.Errorf("PullRequest[%d] already merged but it's associated issue [%d] is not closed", pr.Index, pr.IssueID)
  325. } else if pr.Issue.IsClosed {
  326. return false, fmt.Errorf("PullRequest[%d] already closed", pr.Index)
  327. }
  328. if err := pr.Issue.loadRepo(sess); err != nil {
  329. return false, err
  330. }
  331. if err := pr.Issue.Repo.getOwner(sess); err != nil {
  332. return false, err
  333. }
  334. if _, err := pr.Issue.changeStatus(sess, pr.Merger, true, true); err != nil {
  335. return false, fmt.Errorf("Issue.changeStatus: %v", err)
  336. }
  337. if _, err := sess.Where("id = ?", pr.ID).Cols("has_merged, status, merged_commit_id, merger_id, merged_unix").Update(pr); err != nil {
  338. return false, fmt.Errorf("Failed to update pr[%d]: %v", pr.ID, err)
  339. }
  340. if err := sess.Commit(); err != nil {
  341. return false, fmt.Errorf("Commit: %v", err)
  342. }
  343. return true, nil
  344. }
  345. // NewPullRequest creates new pull request with labels for repository.
  346. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
  347. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  348. i := 0
  349. for {
  350. if err = newPullRequestAttempt(repo, pull, labelIDs, uuids, pr); err == nil {
  351. return nil
  352. }
  353. if !IsErrNewIssueInsert(err) {
  354. return err
  355. }
  356. if i++; i == issueMaxDupIndexAttempts {
  357. break
  358. }
  359. log.Error("NewPullRequest: error attempting to insert the new issue; will retry. Original error: %v", err)
  360. }
  361. return fmt.Errorf("NewPullRequest: too many errors attempting to insert the new issue. Last error was: %v", err)
  362. }
  363. func newPullRequestAttempt(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
  364. sess := x.NewSession()
  365. defer sess.Close()
  366. if err = sess.Begin(); err != nil {
  367. return err
  368. }
  369. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  370. Repo: repo,
  371. Issue: pull,
  372. LabelIDs: labelIDs,
  373. Attachments: uuids,
  374. IsPull: true,
  375. }); err != nil {
  376. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  377. return err
  378. }
  379. return fmt.Errorf("newIssue: %v", err)
  380. }
  381. pr.Index = pull.Index
  382. pr.BaseRepo = repo
  383. pr.IssueID = pull.ID
  384. if _, err = sess.Insert(pr); err != nil {
  385. return fmt.Errorf("insert pull repo: %v", err)
  386. }
  387. if err = sess.Commit(); err != nil {
  388. return fmt.Errorf("Commit: %v", err)
  389. }
  390. return nil
  391. }
  392. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  393. // by given head/base and repo/branch.
  394. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  395. pr := new(PullRequest)
  396. has, err := x.
  397. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  398. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  399. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  400. Get(pr)
  401. if err != nil {
  402. return nil, err
  403. } else if !has {
  404. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  405. }
  406. return pr, nil
  407. }
  408. // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
  409. // by given head information (repo and branch).
  410. func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
  411. pr := new(PullRequest)
  412. has, err := x.
  413. Where("head_repo_id = ? AND head_branch = ?", repoID, branch).
  414. OrderBy("id DESC").
  415. Get(pr)
  416. if !has {
  417. return nil, err
  418. }
  419. return pr, err
  420. }
  421. // GetPullRequestByIndex returns a pull request by the given index
  422. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  423. pr := &PullRequest{
  424. BaseRepoID: repoID,
  425. Index: index,
  426. }
  427. has, err := x.Get(pr)
  428. if err != nil {
  429. return nil, err
  430. } else if !has {
  431. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  432. }
  433. if err = pr.LoadAttributes(); err != nil {
  434. return nil, err
  435. }
  436. if err = pr.LoadIssue(); err != nil {
  437. return nil, err
  438. }
  439. return pr, nil
  440. }
  441. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  442. pr := new(PullRequest)
  443. has, err := e.ID(id).Get(pr)
  444. if err != nil {
  445. return nil, err
  446. } else if !has {
  447. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  448. }
  449. return pr, pr.loadAttributes(e)
  450. }
  451. // GetPullRequestByID returns a pull request by given ID.
  452. func GetPullRequestByID(id int64) (*PullRequest, error) {
  453. return getPullRequestByID(x, id)
  454. }
  455. // GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID.
  456. func GetPullRequestByIssueIDWithNoAttributes(issueID int64) (*PullRequest, error) {
  457. var pr PullRequest
  458. has, err := x.Where("issue_id = ?", issueID).Get(&pr)
  459. if err != nil {
  460. return nil, err
  461. }
  462. if !has {
  463. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  464. }
  465. return &pr, nil
  466. }
  467. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  468. pr := &PullRequest{
  469. IssueID: issueID,
  470. }
  471. has, err := e.Get(pr)
  472. if err != nil {
  473. return nil, err
  474. } else if !has {
  475. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  476. }
  477. return pr, pr.loadAttributes(e)
  478. }
  479. // GetPullRequestByIssueID returns pull request by given issue ID.
  480. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  481. return getPullRequestByIssueID(x, issueID)
  482. }
  483. // Update updates all fields of pull request.
  484. func (pr *PullRequest) Update() error {
  485. _, err := x.ID(pr.ID).AllCols().Update(pr)
  486. return err
  487. }
  488. // UpdateCols updates specific fields of pull request.
  489. func (pr *PullRequest) UpdateCols(cols ...string) error {
  490. _, err := x.ID(pr.ID).Cols(cols...).Update(pr)
  491. return err
  492. }
  493. // UpdateColsIfNotMerged updates specific fields of a pull request if it has not been merged
  494. func (pr *PullRequest) UpdateColsIfNotMerged(cols ...string) error {
  495. _, err := x.Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr)
  496. return err
  497. }
  498. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  499. func (pr *PullRequest) IsWorkInProgress() bool {
  500. if err := pr.LoadIssue(); err != nil {
  501. log.Error("LoadIssue: %v", err)
  502. return false
  503. }
  504. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  505. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  506. return true
  507. }
  508. }
  509. return false
  510. }
  511. // IsFilesConflicted determines if the Pull Request has changes conflicting with the target branch.
  512. func (pr *PullRequest) IsFilesConflicted() bool {
  513. return len(pr.ConflictedFiles) > 0
  514. }
  515. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  516. // It returns an empty string when none were found
  517. func (pr *PullRequest) GetWorkInProgressPrefix() string {
  518. if err := pr.LoadIssue(); err != nil {
  519. log.Error("LoadIssue: %v", err)
  520. return ""
  521. }
  522. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  523. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  524. return pr.Issue.Title[0:len(prefix)]
  525. }
  526. }
  527. return ""
  528. }
  529. // UpdateCommitDivergence update Divergence of a pull request
  530. func (pr *PullRequest) UpdateCommitDivergence(ahead, behind int) error {
  531. return pr.updateCommitDivergence(x, ahead, behind)
  532. }
  533. func (pr *PullRequest) updateCommitDivergence(e Engine, ahead, behind int) error {
  534. if pr.ID == 0 {
  535. return fmt.Errorf("pull ID is 0")
  536. }
  537. pr.CommitsAhead = ahead
  538. pr.CommitsBehind = behind
  539. _, err := e.ID(pr.ID).Cols("commits_ahead", "commits_behind").Update(pr)
  540. return err
  541. }
  542. // IsSameRepo returns true if base repo and head repo is the same
  543. func (pr *PullRequest) IsSameRepo() bool {
  544. return pr.BaseRepoID == pr.HeadRepoID
  545. }