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

pull.go 19 kB

Improve listing performance by using go-git (#6478) * Use go-git for tree reading and commit info lookup. Signed-off-by: Filip Navara <navara@emclient.com> * Use TreeEntry.IsRegular() instead of ObjectType that was removed. Signed-off-by: Filip Navara <navara@emclient.com> * Use the treePath to optimize commit info search. Signed-off-by: Filip Navara <navara@emclient.com> * Extract the latest commit at treePath along with the other commits. Signed-off-by: Filip Navara <navara@emclient.com> * Fix listing commit info for a directory that was created in one commit and never modified after. Signed-off-by: Filip Navara <navara@emclient.com> * Avoid nearly all external 'git' invocations when doing directory listing (.editorconfig code path is still hit). Signed-off-by: Filip Navara <navara@emclient.com> * Use go-git for reading blobs. Signed-off-by: Filip Navara <navara@emclient.com> * Make SHA1 type alias for plumbing.Hash in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Make Signature type alias for object.Signature in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Fix GetCommitsInfo for repository with only one commit. Signed-off-by: Filip Navara <navara@emclient.com> * Fix PGP signature verification. Signed-off-by: Filip Navara <navara@emclient.com> * Fix issues with walking commit graph across merges. Signed-off-by: Filip Navara <navara@emclient.com> * Fix typo in condition. Signed-off-by: Filip Navara <navara@emclient.com> * Speed up loading branch list by keeping the repository reference (and thus all the loaded packfile indexes). Signed-off-by: Filip Navara <navara@emclient.com> * Fix lising submodules. Signed-off-by: Filip Navara <navara@emclient.com> * Fix build Signed-off-by: Filip Navara <navara@emclient.com> * Add back commit cache because of name-rev Signed-off-by: Filip Navara <navara@emclient.com> * Fix tests Signed-off-by: Filip Navara <navara@emclient.com> * Fix code style * Fix spelling * Address PR feedback Signed-off-by: Filip Navara <navara@emclient.com> * Update vendor module list Signed-off-by: Filip Navara <navara@emclient.com> * Fix getting trees by commit id Signed-off-by: Filip Navara <navara@emclient.com> * Fix remaining unit test failures * Fix GetTreeBySHA * Avoid running `git name-rev` if not necessary Signed-off-by: Filip Navara <navara@emclient.com> * Move Branch code to git module * Clean up GPG signature verification and fix it for tagged commits * Address PR feedback (import formatting, copyright headers) * Make blob lookup by SHA working * Update tests to use public API * Allow getting content from any type of object through the blob interface * Change test to actually expect the object content that is in the GIT repository * Change one more test to actually expect the object content that is in the GIT repository * Add comments
6 years ago
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
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
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
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
9 years ago
9 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Change target branch for pull request (#6488) * Adds functionality to change target branch of created pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use const instead of var in JavaScript additions Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Check if branches are equal and if PR already exists before changing target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Make sure to check all commits Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Print error messages for user as error flash message Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Disallow changing target branch of closed or merged pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Resolve conflicts after merge of upstream/master Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Change order of branch select fields Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes duplicate check Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use ctx.Tr for translations Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Recompile JS Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use correct translation namespace Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove redundant if condition Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves most change branch logic into pull service Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Completes comment Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Add Ref to ChangesPayload for logging changed target branches instead of creating a new struct Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Revert changes to go.mod Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Directly use createComment method Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return 404 if pull request is not found. Move written check up Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove variable declaration Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return client errors on change pull request target errors Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return error in commit.HasPreviousCommit Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds blank line Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Test patch before persisting new target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update patch before testing (not working) Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes patch calls when changeing pull request target Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes unneeded check for base name Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves ChangeTargetBranch completely to pull service. Update patch status. Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Set webhook mode after errors were validated Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update PR in one transaction Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Move logic for check if head is equal with branch to pull model Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds missing comment and simplify return Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adjust CreateComment method call Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com>
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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. "strings"
  9. "code.gitea.io/gitea/modules/git"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. api "code.gitea.io/gitea/modules/structs"
  13. "code.gitea.io/gitea/modules/timeutil"
  14. )
  15. // PullRequestType defines pull request type
  16. type PullRequestType int
  17. // Enumerate all the pull request types
  18. const (
  19. PullRequestGitea PullRequestType = iota
  20. PullRequestGit
  21. )
  22. // PullRequestStatus defines pull request status
  23. type PullRequestStatus int
  24. // Enumerate all the pull request status
  25. const (
  26. PullRequestStatusConflict PullRequestStatus = iota
  27. PullRequestStatusChecking
  28. PullRequestStatusMergeable
  29. PullRequestStatusManuallyMerged
  30. )
  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. }
  54. // MustHeadUserName returns the HeadRepo's username if failed return blank
  55. func (pr *PullRequest) MustHeadUserName() string {
  56. if err := pr.LoadHeadRepo(); err != nil {
  57. log.Error("LoadHeadRepo: %v", err)
  58. return ""
  59. }
  60. return pr.HeadRepo.MustOwnerName()
  61. }
  62. // Note: don't try to get Issue because will end up recursive querying.
  63. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  64. if pr.HasMerged && pr.Merger == nil {
  65. pr.Merger, err = getUserByID(e, pr.MergerID)
  66. if IsErrUserNotExist(err) {
  67. pr.MergerID = -1
  68. pr.Merger = NewGhostUser()
  69. } else if err != nil {
  70. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  71. }
  72. }
  73. return nil
  74. }
  75. // LoadAttributes loads pull request attributes from database
  76. func (pr *PullRequest) LoadAttributes() error {
  77. return pr.loadAttributes(x)
  78. }
  79. // LoadBaseRepo loads pull request base repository from database
  80. func (pr *PullRequest) LoadBaseRepo() error {
  81. if pr.BaseRepo == nil {
  82. if pr.HeadRepoID == pr.BaseRepoID && pr.HeadRepo != nil {
  83. pr.BaseRepo = pr.HeadRepo
  84. return nil
  85. }
  86. var repo Repository
  87. if has, err := x.ID(pr.BaseRepoID).Get(&repo); err != nil {
  88. return err
  89. } else if !has {
  90. return ErrRepoNotExist{ID: pr.BaseRepoID}
  91. }
  92. pr.BaseRepo = &repo
  93. }
  94. return nil
  95. }
  96. // LoadHeadRepo loads pull request head repository from database
  97. func (pr *PullRequest) LoadHeadRepo() error {
  98. if pr.HeadRepo == nil {
  99. if pr.HeadRepoID == pr.BaseRepoID && pr.BaseRepo != nil {
  100. pr.HeadRepo = pr.BaseRepo
  101. return nil
  102. }
  103. var repo Repository
  104. if has, err := x.ID(pr.HeadRepoID).Get(&repo); err != nil {
  105. return err
  106. } else if !has {
  107. return ErrRepoNotExist{ID: pr.BaseRepoID}
  108. }
  109. pr.HeadRepo = &repo
  110. }
  111. return nil
  112. }
  113. // LoadIssue loads issue information from database
  114. func (pr *PullRequest) LoadIssue() (err error) {
  115. return pr.loadIssue(x)
  116. }
  117. func (pr *PullRequest) loadIssue(e Engine) (err error) {
  118. if pr.Issue != nil {
  119. return nil
  120. }
  121. pr.Issue, err = getIssueByID(e, pr.IssueID)
  122. if err == nil {
  123. pr.Issue.PullRequest = pr
  124. }
  125. return err
  126. }
  127. // LoadProtectedBranch loads the protected branch of the base branch
  128. func (pr *PullRequest) LoadProtectedBranch() (err error) {
  129. return pr.loadProtectedBranch(x)
  130. }
  131. func (pr *PullRequest) loadProtectedBranch(e Engine) (err error) {
  132. if pr.BaseRepo == nil {
  133. if pr.BaseRepoID == 0 {
  134. return nil
  135. }
  136. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  137. if err != nil {
  138. return
  139. }
  140. }
  141. pr.ProtectedBranch, err = getProtectedBranchBy(e, pr.BaseRepo.ID, pr.BaseBranch)
  142. return
  143. }
  144. // GetDefaultMergeMessage returns default message used when merging pull request
  145. func (pr *PullRequest) GetDefaultMergeMessage() string {
  146. if pr.HeadRepo == nil {
  147. var err error
  148. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  149. if err != nil {
  150. log.Error("GetRepositoryById[%d]: %v", pr.HeadRepoID, err)
  151. return ""
  152. }
  153. }
  154. return fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.MustHeadUserName(), pr.HeadRepo.Name, pr.BaseBranch)
  155. }
  156. // GetDefaultSquashMessage returns default message used when squash and merging pull request
  157. func (pr *PullRequest) GetDefaultSquashMessage() string {
  158. if err := pr.LoadIssue(); err != nil {
  159. log.Error("LoadIssue: %v", err)
  160. return ""
  161. }
  162. return fmt.Sprintf("%s (#%d)", pr.Issue.Title, pr.Issue.Index)
  163. }
  164. // GetGitRefName returns git ref for hidden pull request branch
  165. func (pr *PullRequest) GetGitRefName() string {
  166. return fmt.Sprintf("refs/pull/%d/head", pr.Index)
  167. }
  168. // APIFormat assumes following fields have been assigned with valid values:
  169. // Required - Issue
  170. // Optional - Merger
  171. func (pr *PullRequest) APIFormat() *api.PullRequest {
  172. return pr.apiFormat(x)
  173. }
  174. func (pr *PullRequest) apiFormat(e Engine) *api.PullRequest {
  175. var (
  176. baseBranch *git.Branch
  177. headBranch *git.Branch
  178. baseCommit *git.Commit
  179. headCommit *git.Commit
  180. err error
  181. )
  182. if err = pr.Issue.loadRepo(e); err != nil {
  183. log.Error("loadRepo[%d]: %v", pr.ID, err)
  184. return nil
  185. }
  186. apiIssue := pr.Issue.apiFormat(e)
  187. if pr.BaseRepo == nil {
  188. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  189. if err != nil {
  190. log.Error("GetRepositoryById[%d]: %v", pr.ID, err)
  191. return nil
  192. }
  193. }
  194. if pr.HeadRepo == nil {
  195. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  196. if err != nil {
  197. log.Error("GetRepositoryById[%d]: %v", pr.ID, err)
  198. return nil
  199. }
  200. }
  201. if err = pr.Issue.loadRepo(e); err != nil {
  202. log.Error("pr.Issue.loadRepo[%d]: %v", pr.ID, err)
  203. return nil
  204. }
  205. apiPullRequest := &api.PullRequest{
  206. ID: pr.ID,
  207. URL: pr.Issue.HTMLURL(),
  208. Index: pr.Index,
  209. Poster: apiIssue.Poster,
  210. Title: apiIssue.Title,
  211. Body: apiIssue.Body,
  212. Labels: apiIssue.Labels,
  213. Milestone: apiIssue.Milestone,
  214. Assignee: apiIssue.Assignee,
  215. Assignees: apiIssue.Assignees,
  216. State: apiIssue.State,
  217. Comments: apiIssue.Comments,
  218. HTMLURL: pr.Issue.HTMLURL(),
  219. DiffURL: pr.Issue.DiffURL(),
  220. PatchURL: pr.Issue.PatchURL(),
  221. HasMerged: pr.HasMerged,
  222. MergeBase: pr.MergeBase,
  223. Deadline: apiIssue.Deadline,
  224. Created: pr.Issue.CreatedUnix.AsTimePtr(),
  225. Updated: pr.Issue.UpdatedUnix.AsTimePtr(),
  226. }
  227. baseBranch, err = pr.BaseRepo.GetBranch(pr.BaseBranch)
  228. if err != nil {
  229. if git.IsErrBranchNotExist(err) {
  230. apiPullRequest.Base = nil
  231. } else {
  232. log.Error("GetBranch[%s]: %v", pr.BaseBranch, err)
  233. return nil
  234. }
  235. } else {
  236. apiBaseBranchInfo := &api.PRBranchInfo{
  237. Name: pr.BaseBranch,
  238. Ref: pr.BaseBranch,
  239. RepoID: pr.BaseRepoID,
  240. Repository: pr.BaseRepo.innerAPIFormat(e, AccessModeNone, false),
  241. }
  242. baseCommit, err = baseBranch.GetCommit()
  243. if err != nil {
  244. if git.IsErrNotExist(err) {
  245. apiBaseBranchInfo.Sha = ""
  246. } else {
  247. log.Error("GetCommit[%s]: %v", baseBranch.Name, err)
  248. return nil
  249. }
  250. } else {
  251. apiBaseBranchInfo.Sha = baseCommit.ID.String()
  252. }
  253. apiPullRequest.Base = apiBaseBranchInfo
  254. }
  255. headBranch, err = pr.HeadRepo.GetBranch(pr.HeadBranch)
  256. if err != nil {
  257. if git.IsErrBranchNotExist(err) {
  258. apiPullRequest.Head = nil
  259. } else {
  260. log.Error("GetBranch[%s]: %v", pr.HeadBranch, err)
  261. return nil
  262. }
  263. } else {
  264. apiHeadBranchInfo := &api.PRBranchInfo{
  265. Name: pr.HeadBranch,
  266. Ref: pr.HeadBranch,
  267. RepoID: pr.HeadRepoID,
  268. Repository: pr.HeadRepo.innerAPIFormat(e, AccessModeNone, false),
  269. }
  270. headCommit, err = headBranch.GetCommit()
  271. if err != nil {
  272. if git.IsErrNotExist(err) {
  273. apiHeadBranchInfo.Sha = ""
  274. } else {
  275. log.Error("GetCommit[%s]: %v", headBranch.Name, err)
  276. return nil
  277. }
  278. } else {
  279. apiHeadBranchInfo.Sha = headCommit.ID.String()
  280. }
  281. apiPullRequest.Head = apiHeadBranchInfo
  282. }
  283. if pr.Status != PullRequestStatusChecking {
  284. mergeable := pr.Status != PullRequestStatusConflict && !pr.IsWorkInProgress()
  285. apiPullRequest.Mergeable = mergeable
  286. }
  287. if pr.HasMerged {
  288. apiPullRequest.Merged = pr.MergedUnix.AsTimePtr()
  289. apiPullRequest.MergedCommitID = &pr.MergedCommitID
  290. apiPullRequest.MergedBy = pr.Merger.APIFormat()
  291. }
  292. return apiPullRequest
  293. }
  294. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  295. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  296. if err != nil && !IsErrRepoNotExist(err) {
  297. return fmt.Errorf("getRepositoryByID(head): %v", err)
  298. }
  299. return nil
  300. }
  301. // GetHeadRepo loads the head repository
  302. func (pr *PullRequest) GetHeadRepo() error {
  303. return pr.getHeadRepo(x)
  304. }
  305. // GetBaseRepo loads the target repository
  306. func (pr *PullRequest) GetBaseRepo() (err error) {
  307. if pr.BaseRepo != nil {
  308. return nil
  309. }
  310. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  311. if err != nil {
  312. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  313. }
  314. return nil
  315. }
  316. // IsChecking returns true if this pull request is still checking conflict.
  317. func (pr *PullRequest) IsChecking() bool {
  318. return pr.Status == PullRequestStatusChecking
  319. }
  320. // CanAutoMerge returns true if this pull request can be merged automatically.
  321. func (pr *PullRequest) CanAutoMerge() bool {
  322. return pr.Status == PullRequestStatusMergeable
  323. }
  324. // GetLastCommitStatus returns the last commit status for this pull request.
  325. func (pr *PullRequest) GetLastCommitStatus() (status *CommitStatus, err error) {
  326. if err = pr.GetHeadRepo(); err != nil {
  327. return nil, err
  328. }
  329. if pr.HeadRepo == nil {
  330. return nil, ErrPullRequestHeadRepoMissing{pr.ID, pr.HeadRepoID}
  331. }
  332. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  333. if err != nil {
  334. return nil, err
  335. }
  336. defer headGitRepo.Close()
  337. lastCommitID, err := headGitRepo.GetBranchCommitID(pr.HeadBranch)
  338. if err != nil {
  339. return nil, err
  340. }
  341. err = pr.LoadBaseRepo()
  342. if err != nil {
  343. return nil, err
  344. }
  345. statusList, err := GetLatestCommitStatus(pr.BaseRepo, lastCommitID, 0)
  346. if err != nil {
  347. return nil, err
  348. }
  349. return CalcCommitStatus(statusList), nil
  350. }
  351. // MergeStyle represents the approach to merge commits into base branch.
  352. type MergeStyle string
  353. const (
  354. // MergeStyleMerge create merge commit
  355. MergeStyleMerge MergeStyle = "merge"
  356. // MergeStyleRebase rebase before merging
  357. MergeStyleRebase MergeStyle = "rebase"
  358. // MergeStyleRebaseMerge rebase before merging with merge commit (--no-ff)
  359. MergeStyleRebaseMerge MergeStyle = "rebase-merge"
  360. // MergeStyleSquash squash commits into single commit before merging
  361. MergeStyleSquash MergeStyle = "squash"
  362. )
  363. // CheckUserAllowedToMerge checks whether the user is allowed to merge
  364. func (pr *PullRequest) CheckUserAllowedToMerge(doer *User) (err error) {
  365. if doer == nil {
  366. return ErrNotAllowedToMerge{
  367. "Not signed in",
  368. }
  369. }
  370. if pr.BaseRepo == nil {
  371. if err = pr.GetBaseRepo(); err != nil {
  372. return fmt.Errorf("GetBaseRepo: %v", err)
  373. }
  374. }
  375. if protected, err := pr.BaseRepo.IsProtectedBranchForMerging(pr, pr.BaseBranch, doer); err != nil {
  376. return fmt.Errorf("IsProtectedBranch: %v", err)
  377. } else if protected {
  378. return ErrNotAllowedToMerge{
  379. "The branch is protected",
  380. }
  381. }
  382. return nil
  383. }
  384. // SetMerged sets a pull request to merged and closes the corresponding issue
  385. func (pr *PullRequest) SetMerged() (err error) {
  386. if pr.HasMerged {
  387. return fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  388. }
  389. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  390. return fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  391. }
  392. pr.HasMerged = true
  393. sess := x.NewSession()
  394. defer sess.Close()
  395. if err = sess.Begin(); err != nil {
  396. return err
  397. }
  398. if err = pr.loadIssue(sess); err != nil {
  399. return err
  400. }
  401. if err = pr.Issue.loadRepo(sess); err != nil {
  402. return err
  403. }
  404. if err = pr.Issue.Repo.getOwner(sess); err != nil {
  405. return err
  406. }
  407. if _, err = pr.Issue.changeStatus(sess, pr.Merger, true); err != nil {
  408. return fmt.Errorf("Issue.changeStatus: %v", err)
  409. }
  410. if _, err = sess.ID(pr.ID).Cols("has_merged, status, merged_commit_id, merger_id, merged_unix").Update(pr); err != nil {
  411. return fmt.Errorf("update pull request: %v", err)
  412. }
  413. if err = sess.Commit(); err != nil {
  414. return fmt.Errorf("Commit: %v", err)
  415. }
  416. return nil
  417. }
  418. // NewPullRequest creates new pull request with labels for repository.
  419. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
  420. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  421. i := 0
  422. for {
  423. if err = newPullRequestAttempt(repo, pull, labelIDs, uuids, pr); err == nil {
  424. return nil
  425. }
  426. if !IsErrNewIssueInsert(err) {
  427. return err
  428. }
  429. if i++; i == issueMaxDupIndexAttempts {
  430. break
  431. }
  432. log.Error("NewPullRequest: error attempting to insert the new issue; will retry. Original error: %v", err)
  433. }
  434. return fmt.Errorf("NewPullRequest: too many errors attempting to insert the new issue. Last error was: %v", err)
  435. }
  436. func newPullRequestAttempt(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
  437. sess := x.NewSession()
  438. defer sess.Close()
  439. if err = sess.Begin(); err != nil {
  440. return err
  441. }
  442. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  443. Repo: repo,
  444. Issue: pull,
  445. LabelIDs: labelIDs,
  446. Attachments: uuids,
  447. IsPull: true,
  448. }); err != nil {
  449. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  450. return err
  451. }
  452. return fmt.Errorf("newIssue: %v", err)
  453. }
  454. pr.Index = pull.Index
  455. pr.BaseRepo = repo
  456. pr.IssueID = pull.ID
  457. if _, err = sess.Insert(pr); err != nil {
  458. return fmt.Errorf("insert pull repo: %v", err)
  459. }
  460. if err = sess.Commit(); err != nil {
  461. return fmt.Errorf("Commit: %v", err)
  462. }
  463. return nil
  464. }
  465. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  466. // by given head/base and repo/branch.
  467. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  468. pr := new(PullRequest)
  469. has, err := x.
  470. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  471. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  472. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  473. Get(pr)
  474. if err != nil {
  475. return nil, err
  476. } else if !has {
  477. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  478. }
  479. return pr, nil
  480. }
  481. // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
  482. // by given head information (repo and branch).
  483. func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
  484. pr := new(PullRequest)
  485. has, err := x.
  486. Where("head_repo_id = ? AND head_branch = ?", repoID, branch).
  487. OrderBy("id DESC").
  488. Get(pr)
  489. if !has {
  490. return nil, err
  491. }
  492. return pr, err
  493. }
  494. // GetPullRequestByIndex returns a pull request by the given index
  495. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  496. pr := &PullRequest{
  497. BaseRepoID: repoID,
  498. Index: index,
  499. }
  500. has, err := x.Get(pr)
  501. if err != nil {
  502. return nil, err
  503. } else if !has {
  504. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  505. }
  506. if err = pr.LoadAttributes(); err != nil {
  507. return nil, err
  508. }
  509. if err = pr.LoadIssue(); err != nil {
  510. return nil, err
  511. }
  512. return pr, nil
  513. }
  514. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  515. pr := new(PullRequest)
  516. has, err := e.ID(id).Get(pr)
  517. if err != nil {
  518. return nil, err
  519. } else if !has {
  520. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  521. }
  522. return pr, pr.loadAttributes(e)
  523. }
  524. // GetPullRequestByID returns a pull request by given ID.
  525. func GetPullRequestByID(id int64) (*PullRequest, error) {
  526. return getPullRequestByID(x, id)
  527. }
  528. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  529. pr := &PullRequest{
  530. IssueID: issueID,
  531. }
  532. has, err := e.Get(pr)
  533. if err != nil {
  534. return nil, err
  535. } else if !has {
  536. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  537. }
  538. return pr, pr.loadAttributes(e)
  539. }
  540. // GetPullRequestByIssueID returns pull request by given issue ID.
  541. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  542. return getPullRequestByIssueID(x, issueID)
  543. }
  544. // Update updates all fields of pull request.
  545. func (pr *PullRequest) Update() error {
  546. _, err := x.ID(pr.ID).AllCols().Update(pr)
  547. return err
  548. }
  549. // UpdateCols updates specific fields of pull request.
  550. func (pr *PullRequest) UpdateCols(cols ...string) error {
  551. _, err := x.ID(pr.ID).Cols(cols...).Update(pr)
  552. return err
  553. }
  554. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  555. func (pr *PullRequest) IsWorkInProgress() bool {
  556. if err := pr.LoadIssue(); err != nil {
  557. log.Error("LoadIssue: %v", err)
  558. return false
  559. }
  560. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  561. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  562. return true
  563. }
  564. }
  565. return false
  566. }
  567. // IsFilesConflicted determines if the Pull Request has changes conflicting with the target branch.
  568. func (pr *PullRequest) IsFilesConflicted() bool {
  569. return len(pr.ConflictedFiles) > 0
  570. }
  571. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  572. // It returns an empty string when none were found
  573. func (pr *PullRequest) GetWorkInProgressPrefix() string {
  574. if err := pr.LoadIssue(); err != nil {
  575. log.Error("LoadIssue: %v", err)
  576. return ""
  577. }
  578. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  579. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  580. return pr.Issue.Title[0:len(prefix)]
  581. }
  582. }
  583. return ""
  584. }
  585. // IsHeadEqualWithBranch returns if the commits of branchName are available in pull request head
  586. func (pr *PullRequest) IsHeadEqualWithBranch(branchName string) (bool, error) {
  587. var err error
  588. if err = pr.GetBaseRepo(); err != nil {
  589. return false, err
  590. }
  591. baseGitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  592. if err != nil {
  593. return false, err
  594. }
  595. baseCommit, err := baseGitRepo.GetBranchCommit(branchName)
  596. if err != nil {
  597. return false, err
  598. }
  599. if err = pr.GetHeadRepo(); err != nil {
  600. return false, err
  601. }
  602. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  603. if err != nil {
  604. return false, err
  605. }
  606. headCommit, err := headGitRepo.GetBranchCommit(pr.HeadBranch)
  607. if err != nil {
  608. return false, err
  609. }
  610. return baseCommit.HasPreviousCommit(headCommit.ID)
  611. }