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