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 25 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
10 years ago
10 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  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/git"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/setting"
  13. api "code.gitea.io/gitea/modules/structs"
  14. "code.gitea.io/gitea/modules/timeutil"
  15. )
  16. // PullRequestType defines pull request type
  17. type PullRequestType int
  18. // Enumerate all the pull request types
  19. const (
  20. PullRequestGitea PullRequestType = iota
  21. PullRequestGit
  22. )
  23. // PullRequestStatus defines pull request status
  24. type PullRequestStatus int
  25. // Enumerate all the pull request status
  26. const (
  27. PullRequestStatusConflict PullRequestStatus = iota
  28. PullRequestStatusChecking
  29. PullRequestStatusMergeable
  30. PullRequestStatusManuallyMerged
  31. )
  32. // PullRequest represents relation between pull request and repositories.
  33. type PullRequest struct {
  34. ID int64 `xorm:"pk autoincr"`
  35. Type PullRequestType
  36. Status PullRequestStatus
  37. ConflictedFiles []string `xorm:"TEXT JSON"`
  38. IssueID int64 `xorm:"INDEX"`
  39. Issue *Issue `xorm:"-"`
  40. Index int64
  41. HeadRepoID int64 `xorm:"INDEX"`
  42. HeadRepo *Repository `xorm:"-"`
  43. BaseRepoID int64 `xorm:"INDEX"`
  44. BaseRepo *Repository `xorm:"-"`
  45. HeadBranch string
  46. BaseBranch string
  47. ProtectedBranch *ProtectedBranch `xorm:"-"`
  48. MergeBase string `xorm:"VARCHAR(40)"`
  49. HasMerged bool `xorm:"INDEX"`
  50. MergedCommitID string `xorm:"VARCHAR(40)"`
  51. MergerID int64 `xorm:"INDEX"`
  52. Merger *User `xorm:"-"`
  53. MergedUnix timeutil.TimeStamp `xorm:"updated INDEX"`
  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. log.Error("LoadHeadRepo: %v", err)
  59. return ""
  60. }
  61. return pr.HeadRepo.MustOwnerName()
  62. }
  63. // Note: don't try to get Issue because will end up recursive querying.
  64. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  65. if pr.HasMerged && pr.Merger == nil {
  66. pr.Merger, err = getUserByID(e, pr.MergerID)
  67. if IsErrUserNotExist(err) {
  68. pr.MergerID = -1
  69. pr.Merger = NewGhostUser()
  70. } else if err != nil {
  71. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  72. }
  73. }
  74. return nil
  75. }
  76. // LoadAttributes loads pull request attributes from database
  77. func (pr *PullRequest) LoadAttributes() error {
  78. return pr.loadAttributes(x)
  79. }
  80. // LoadBaseRepo loads pull request base repository from database
  81. func (pr *PullRequest) LoadBaseRepo() error {
  82. if pr.BaseRepo == nil {
  83. if pr.HeadRepoID == pr.BaseRepoID && pr.HeadRepo != nil {
  84. pr.BaseRepo = pr.HeadRepo
  85. return nil
  86. }
  87. var repo Repository
  88. if has, err := x.ID(pr.BaseRepoID).Get(&repo); err != nil {
  89. return err
  90. } else if !has {
  91. return ErrRepoNotExist{ID: pr.BaseRepoID}
  92. }
  93. pr.BaseRepo = &repo
  94. }
  95. return nil
  96. }
  97. // LoadHeadRepo loads pull request head repository from database
  98. func (pr *PullRequest) LoadHeadRepo() error {
  99. if pr.HeadRepo == nil {
  100. if pr.HeadRepoID == pr.BaseRepoID && pr.BaseRepo != nil {
  101. pr.HeadRepo = pr.BaseRepo
  102. return nil
  103. }
  104. var repo Repository
  105. if has, err := x.ID(pr.HeadRepoID).Get(&repo); err != nil {
  106. return err
  107. } else if !has {
  108. return ErrRepoNotExist{ID: pr.BaseRepoID}
  109. }
  110. pr.HeadRepo = &repo
  111. }
  112. return nil
  113. }
  114. // LoadIssue loads issue information from database
  115. func (pr *PullRequest) LoadIssue() (err error) {
  116. return pr.loadIssue(x)
  117. }
  118. func (pr *PullRequest) loadIssue(e Engine) (err error) {
  119. if pr.Issue != nil {
  120. return nil
  121. }
  122. pr.Issue, err = getIssueByID(e, pr.IssueID)
  123. if err == nil {
  124. pr.Issue.PullRequest = pr
  125. }
  126. return err
  127. }
  128. // LoadProtectedBranch loads the protected branch of the base branch
  129. func (pr *PullRequest) LoadProtectedBranch() (err error) {
  130. return pr.loadProtectedBranch(x)
  131. }
  132. func (pr *PullRequest) loadProtectedBranch(e Engine) (err error) {
  133. if pr.BaseRepo == nil {
  134. if pr.BaseRepoID == 0 {
  135. return nil
  136. }
  137. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  138. if err != nil {
  139. return
  140. }
  141. }
  142. pr.ProtectedBranch, err = getProtectedBranchBy(e, pr.BaseRepo.ID, pr.BaseBranch)
  143. return
  144. }
  145. // GetDefaultMergeMessage returns default message used when merging pull request
  146. func (pr *PullRequest) GetDefaultMergeMessage() string {
  147. if pr.HeadRepo == nil {
  148. var err error
  149. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  150. if err != nil {
  151. log.Error("GetRepositoryById[%d]: %v", pr.HeadRepoID, err)
  152. return ""
  153. }
  154. }
  155. return fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.MustHeadUserName(), pr.HeadRepo.Name, pr.BaseBranch)
  156. }
  157. // GetCommitMessages returns the commit messages between head and merge base (if there is one)
  158. func (pr *PullRequest) GetCommitMessages() string {
  159. if err := pr.LoadIssue(); err != nil {
  160. log.Error("Cannot load issue %d for PR id %d: Error: %v", pr.IssueID, pr.ID, err)
  161. return ""
  162. }
  163. if err := pr.Issue.LoadPoster(); err != nil {
  164. log.Error("Cannot load poster %d for pr id %d, index %d Error: %v", pr.Issue.PosterID, pr.ID, pr.Index, err)
  165. return ""
  166. }
  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. gitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  176. if err != nil {
  177. log.Error("Unable to open head repository: Error: %v", err)
  178. return ""
  179. }
  180. defer gitRepo.Close()
  181. headCommit, err := gitRepo.GetBranchCommit(pr.HeadBranch)
  182. if err != nil {
  183. log.Error("Unable to get head commit: %s Error: %v", pr.HeadBranch, err)
  184. return ""
  185. }
  186. mergeBase, err := gitRepo.GetCommit(pr.MergeBase)
  187. if err != nil {
  188. log.Error("Unable to get merge base commit: %s Error: %v", pr.MergeBase, err)
  189. return ""
  190. }
  191. limit := setting.Repository.PullRequest.DefaultMergeMessageCommitsLimit
  192. list, err := gitRepo.CommitsBetweenLimit(headCommit, mergeBase, limit, 0)
  193. if err != nil {
  194. log.Error("Unable to get commits between: %s %s Error: %v", pr.HeadBranch, pr.MergeBase, err)
  195. return ""
  196. }
  197. maxSize := setting.Repository.PullRequest.DefaultMergeMessageSize
  198. posterSig := pr.Issue.Poster.NewGitSig().String()
  199. authorsMap := map[string]bool{}
  200. authors := make([]string, 0, list.Len())
  201. stringBuilder := strings.Builder{}
  202. element := list.Front()
  203. for element != nil {
  204. commit := element.Value.(*git.Commit)
  205. if maxSize < 0 || stringBuilder.Len() < maxSize {
  206. toWrite := []byte(commit.CommitMessage)
  207. if len(toWrite) > maxSize-stringBuilder.Len() && maxSize > -1 {
  208. toWrite = append(toWrite[:maxSize-stringBuilder.Len()], "..."...)
  209. }
  210. if _, err := stringBuilder.Write(toWrite); err != nil {
  211. log.Error("Unable to write commit message Error: %v", err)
  212. return ""
  213. }
  214. if _, err := stringBuilder.WriteRune('\n'); err != nil {
  215. log.Error("Unable to write commit message Error: %v", err)
  216. return ""
  217. }
  218. }
  219. authorString := commit.Author.String()
  220. if !authorsMap[authorString] && authorString != posterSig {
  221. authors = append(authors, authorString)
  222. authorsMap[authorString] = true
  223. }
  224. element = element.Next()
  225. }
  226. // Consider collecting the remaining authors
  227. if limit >= 0 && setting.Repository.PullRequest.DefaultMergeMessageAllAuthors {
  228. skip := limit
  229. limit = 30
  230. for {
  231. list, err := gitRepo.CommitsBetweenLimit(headCommit, mergeBase, limit, skip)
  232. if err != nil {
  233. log.Error("Unable to get commits between: %s %s Error: %v", pr.HeadBranch, pr.MergeBase, err)
  234. return ""
  235. }
  236. if list.Len() == 0 {
  237. break
  238. }
  239. element := list.Front()
  240. for element != nil {
  241. commit := element.Value.(*git.Commit)
  242. authorString := commit.Author.String()
  243. if !authorsMap[authorString] && authorString != posterSig {
  244. authors = append(authors, authorString)
  245. authorsMap[authorString] = true
  246. }
  247. element = element.Next()
  248. }
  249. }
  250. }
  251. if len(authors) > 0 {
  252. if _, err := stringBuilder.WriteRune('\n'); err != nil {
  253. log.Error("Unable to write to string builder Error: %v", err)
  254. return ""
  255. }
  256. }
  257. for _, author := range authors {
  258. if _, err := stringBuilder.Write([]byte("Co-authored-by: ")); err != nil {
  259. log.Error("Unable to write to string builder Error: %v", err)
  260. return ""
  261. }
  262. if _, err := stringBuilder.Write([]byte(author)); err != nil {
  263. log.Error("Unable to write to string builder Error: %v", err)
  264. return ""
  265. }
  266. if _, err := stringBuilder.WriteRune('\n'); err != nil {
  267. log.Error("Unable to write to string builder Error: %v", err)
  268. return ""
  269. }
  270. }
  271. return stringBuilder.String()
  272. }
  273. // GetApprovers returns the approvers of the pull request
  274. func (pr *PullRequest) GetApprovers() string {
  275. stringBuilder := strings.Builder{}
  276. if err := pr.getReviewedByLines(&stringBuilder); err != nil {
  277. log.Error("Unable to getReviewedByLines: Error: %v", err)
  278. return ""
  279. }
  280. return stringBuilder.String()
  281. }
  282. func (pr *PullRequest) getReviewedByLines(writer io.Writer) error {
  283. maxReviewers := setting.Repository.PullRequest.DefaultMergeMessageMaxApprovers
  284. if maxReviewers == 0 {
  285. return nil
  286. }
  287. sess := x.NewSession()
  288. defer sess.Close()
  289. if err := sess.Begin(); err != nil {
  290. return err
  291. }
  292. // Note: This doesn't page as we only expect a very limited number of reviews
  293. reviews, err := findReviews(sess, FindReviewOptions{
  294. Type: ReviewTypeApprove,
  295. IssueID: pr.IssueID,
  296. OfficialOnly: setting.Repository.PullRequest.DefaultMergeMessageOfficialApproversOnly,
  297. })
  298. if err != nil {
  299. log.Error("Unable to FindReviews for PR ID %d: %v", pr.ID, err)
  300. return err
  301. }
  302. reviewersWritten := 0
  303. for _, review := range reviews {
  304. if maxReviewers > 0 && reviewersWritten > maxReviewers {
  305. break
  306. }
  307. if err := review.loadReviewer(sess); err != nil && !IsErrUserNotExist(err) {
  308. log.Error("Unable to LoadReviewer[%d] for PR ID %d : %v", review.ReviewerID, pr.ID, err)
  309. return err
  310. } else if review.Reviewer == nil {
  311. continue
  312. }
  313. if _, err := writer.Write([]byte("Reviewed-by: ")); err != nil {
  314. return err
  315. }
  316. if _, err := writer.Write([]byte(review.Reviewer.NewGitSig().String())); err != nil {
  317. return err
  318. }
  319. if _, err := writer.Write([]byte{'\n'}); err != nil {
  320. return err
  321. }
  322. reviewersWritten++
  323. }
  324. return sess.Commit()
  325. }
  326. // GetDefaultSquashMessage returns default message used when squash and merging pull request
  327. func (pr *PullRequest) GetDefaultSquashMessage() string {
  328. if err := pr.LoadIssue(); err != nil {
  329. log.Error("LoadIssue: %v", err)
  330. return ""
  331. }
  332. return fmt.Sprintf("%s (#%d)", pr.Issue.Title, pr.Issue.Index)
  333. }
  334. // GetGitRefName returns git ref for hidden pull request branch
  335. func (pr *PullRequest) GetGitRefName() string {
  336. return fmt.Sprintf("refs/pull/%d/head", pr.Index)
  337. }
  338. // APIFormat assumes following fields have been assigned with valid values:
  339. // Required - Issue
  340. // Optional - Merger
  341. func (pr *PullRequest) APIFormat() *api.PullRequest {
  342. return pr.apiFormat(x)
  343. }
  344. func (pr *PullRequest) apiFormat(e Engine) *api.PullRequest {
  345. var (
  346. baseBranch *git.Branch
  347. headBranch *git.Branch
  348. baseCommit *git.Commit
  349. headCommit *git.Commit
  350. err error
  351. )
  352. if err = pr.Issue.loadRepo(e); err != nil {
  353. log.Error("loadRepo[%d]: %v", pr.ID, err)
  354. return nil
  355. }
  356. apiIssue := pr.Issue.apiFormat(e)
  357. if pr.BaseRepo == nil {
  358. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  359. if err != nil {
  360. log.Error("GetRepositoryById[%d]: %v", pr.ID, err)
  361. return nil
  362. }
  363. }
  364. if pr.HeadRepo == nil {
  365. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  366. if err != nil {
  367. log.Error("GetRepositoryById[%d]: %v", pr.ID, err)
  368. return nil
  369. }
  370. }
  371. if err = pr.Issue.loadRepo(e); err != nil {
  372. log.Error("pr.Issue.loadRepo[%d]: %v", pr.ID, err)
  373. return nil
  374. }
  375. apiPullRequest := &api.PullRequest{
  376. ID: pr.ID,
  377. URL: pr.Issue.HTMLURL(),
  378. Index: pr.Index,
  379. Poster: apiIssue.Poster,
  380. Title: apiIssue.Title,
  381. Body: apiIssue.Body,
  382. Labels: apiIssue.Labels,
  383. Milestone: apiIssue.Milestone,
  384. Assignee: apiIssue.Assignee,
  385. Assignees: apiIssue.Assignees,
  386. State: apiIssue.State,
  387. Comments: apiIssue.Comments,
  388. HTMLURL: pr.Issue.HTMLURL(),
  389. DiffURL: pr.Issue.DiffURL(),
  390. PatchURL: pr.Issue.PatchURL(),
  391. HasMerged: pr.HasMerged,
  392. MergeBase: pr.MergeBase,
  393. Deadline: apiIssue.Deadline,
  394. Created: pr.Issue.CreatedUnix.AsTimePtr(),
  395. Updated: pr.Issue.UpdatedUnix.AsTimePtr(),
  396. }
  397. baseBranch, err = pr.BaseRepo.GetBranch(pr.BaseBranch)
  398. if err != nil {
  399. if git.IsErrBranchNotExist(err) {
  400. apiPullRequest.Base = nil
  401. } else {
  402. log.Error("GetBranch[%s]: %v", pr.BaseBranch, err)
  403. return nil
  404. }
  405. } else {
  406. apiBaseBranchInfo := &api.PRBranchInfo{
  407. Name: pr.BaseBranch,
  408. Ref: pr.BaseBranch,
  409. RepoID: pr.BaseRepoID,
  410. Repository: pr.BaseRepo.innerAPIFormat(e, AccessModeNone, false),
  411. }
  412. baseCommit, err = baseBranch.GetCommit()
  413. if err != nil {
  414. if git.IsErrNotExist(err) {
  415. apiBaseBranchInfo.Sha = ""
  416. } else {
  417. log.Error("GetCommit[%s]: %v", baseBranch.Name, err)
  418. return nil
  419. }
  420. } else {
  421. apiBaseBranchInfo.Sha = baseCommit.ID.String()
  422. }
  423. apiPullRequest.Base = apiBaseBranchInfo
  424. }
  425. headBranch, err = pr.HeadRepo.GetBranch(pr.HeadBranch)
  426. if err != nil {
  427. if git.IsErrBranchNotExist(err) {
  428. apiPullRequest.Head = nil
  429. } else {
  430. log.Error("GetBranch[%s]: %v", pr.HeadBranch, err)
  431. return nil
  432. }
  433. } else {
  434. apiHeadBranchInfo := &api.PRBranchInfo{
  435. Name: pr.HeadBranch,
  436. Ref: pr.HeadBranch,
  437. RepoID: pr.HeadRepoID,
  438. Repository: pr.HeadRepo.innerAPIFormat(e, AccessModeNone, false),
  439. }
  440. headCommit, err = headBranch.GetCommit()
  441. if err != nil {
  442. if git.IsErrNotExist(err) {
  443. apiHeadBranchInfo.Sha = ""
  444. } else {
  445. log.Error("GetCommit[%s]: %v", headBranch.Name, err)
  446. return nil
  447. }
  448. } else {
  449. apiHeadBranchInfo.Sha = headCommit.ID.String()
  450. }
  451. apiPullRequest.Head = apiHeadBranchInfo
  452. }
  453. if pr.Status != PullRequestStatusChecking {
  454. mergeable := pr.Status != PullRequestStatusConflict && !pr.IsWorkInProgress()
  455. apiPullRequest.Mergeable = mergeable
  456. }
  457. if pr.HasMerged {
  458. apiPullRequest.Merged = pr.MergedUnix.AsTimePtr()
  459. apiPullRequest.MergedCommitID = &pr.MergedCommitID
  460. apiPullRequest.MergedBy = pr.Merger.APIFormat()
  461. }
  462. return apiPullRequest
  463. }
  464. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  465. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  466. if err != nil && !IsErrRepoNotExist(err) {
  467. return fmt.Errorf("getRepositoryByID(head): %v", err)
  468. }
  469. return nil
  470. }
  471. // GetHeadRepo loads the head repository
  472. func (pr *PullRequest) GetHeadRepo() error {
  473. return pr.getHeadRepo(x)
  474. }
  475. // GetBaseRepo loads the target repository
  476. func (pr *PullRequest) GetBaseRepo() (err error) {
  477. if pr.BaseRepo != nil {
  478. return nil
  479. }
  480. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  481. if err != nil {
  482. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  483. }
  484. return nil
  485. }
  486. // IsChecking returns true if this pull request is still checking conflict.
  487. func (pr *PullRequest) IsChecking() bool {
  488. return pr.Status == PullRequestStatusChecking
  489. }
  490. // CanAutoMerge returns true if this pull request can be merged automatically.
  491. func (pr *PullRequest) CanAutoMerge() bool {
  492. return pr.Status == PullRequestStatusMergeable
  493. }
  494. // GetLastCommitStatus returns the last commit status for this pull request.
  495. func (pr *PullRequest) GetLastCommitStatus() (status *CommitStatus, err error) {
  496. if err = pr.GetHeadRepo(); err != nil {
  497. return nil, err
  498. }
  499. if pr.HeadRepo == nil {
  500. return nil, ErrPullRequestHeadRepoMissing{pr.ID, pr.HeadRepoID}
  501. }
  502. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  503. if err != nil {
  504. return nil, err
  505. }
  506. defer headGitRepo.Close()
  507. lastCommitID, err := headGitRepo.GetBranchCommitID(pr.HeadBranch)
  508. if err != nil {
  509. return nil, err
  510. }
  511. err = pr.LoadBaseRepo()
  512. if err != nil {
  513. return nil, err
  514. }
  515. statusList, err := GetLatestCommitStatus(pr.BaseRepo, lastCommitID, 0)
  516. if err != nil {
  517. return nil, err
  518. }
  519. return CalcCommitStatus(statusList), nil
  520. }
  521. // MergeStyle represents the approach to merge commits into base branch.
  522. type MergeStyle string
  523. const (
  524. // MergeStyleMerge create merge commit
  525. MergeStyleMerge MergeStyle = "merge"
  526. // MergeStyleRebase rebase before merging
  527. MergeStyleRebase MergeStyle = "rebase"
  528. // MergeStyleRebaseMerge rebase before merging with merge commit (--no-ff)
  529. MergeStyleRebaseMerge MergeStyle = "rebase-merge"
  530. // MergeStyleSquash squash commits into single commit before merging
  531. MergeStyleSquash MergeStyle = "squash"
  532. )
  533. // CheckUserAllowedToMerge checks whether the user is allowed to merge
  534. func (pr *PullRequest) CheckUserAllowedToMerge(doer *User) (err error) {
  535. if doer == nil {
  536. return ErrNotAllowedToMerge{
  537. "Not signed in",
  538. }
  539. }
  540. if pr.BaseRepo == nil {
  541. if err = pr.GetBaseRepo(); err != nil {
  542. return fmt.Errorf("GetBaseRepo: %v", err)
  543. }
  544. }
  545. if protected, err := pr.BaseRepo.IsProtectedBranchForMerging(pr, pr.BaseBranch, doer); err != nil {
  546. return fmt.Errorf("IsProtectedBranch: %v", err)
  547. } else if protected {
  548. return ErrNotAllowedToMerge{
  549. "The branch is protected",
  550. }
  551. }
  552. return nil
  553. }
  554. // SetMerged sets a pull request to merged and closes the corresponding issue
  555. func (pr *PullRequest) SetMerged() (err error) {
  556. if pr.HasMerged {
  557. return fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  558. }
  559. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  560. return fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  561. }
  562. pr.HasMerged = true
  563. sess := x.NewSession()
  564. defer sess.Close()
  565. if err = sess.Begin(); err != nil {
  566. return err
  567. }
  568. if err = pr.loadIssue(sess); err != nil {
  569. return err
  570. }
  571. if err = pr.Issue.loadRepo(sess); err != nil {
  572. return err
  573. }
  574. if err = pr.Issue.Repo.getOwner(sess); err != nil {
  575. return err
  576. }
  577. if _, err = pr.Issue.changeStatus(sess, pr.Merger, true); err != nil {
  578. return fmt.Errorf("Issue.changeStatus: %v", err)
  579. }
  580. if _, err = sess.ID(pr.ID).Cols("has_merged, status, merged_commit_id, merger_id, merged_unix").Update(pr); err != nil {
  581. return fmt.Errorf("update pull request: %v", err)
  582. }
  583. if err = sess.Commit(); err != nil {
  584. return fmt.Errorf("Commit: %v", err)
  585. }
  586. return nil
  587. }
  588. // NewPullRequest creates new pull request with labels for repository.
  589. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
  590. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  591. i := 0
  592. for {
  593. if err = newPullRequestAttempt(repo, pull, labelIDs, uuids, pr); err == nil {
  594. return nil
  595. }
  596. if !IsErrNewIssueInsert(err) {
  597. return err
  598. }
  599. if i++; i == issueMaxDupIndexAttempts {
  600. break
  601. }
  602. log.Error("NewPullRequest: error attempting to insert the new issue; will retry. Original error: %v", err)
  603. }
  604. return fmt.Errorf("NewPullRequest: too many errors attempting to insert the new issue. Last error was: %v", err)
  605. }
  606. func newPullRequestAttempt(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) {
  607. sess := x.NewSession()
  608. defer sess.Close()
  609. if err = sess.Begin(); err != nil {
  610. return err
  611. }
  612. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  613. Repo: repo,
  614. Issue: pull,
  615. LabelIDs: labelIDs,
  616. Attachments: uuids,
  617. IsPull: true,
  618. }); err != nil {
  619. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  620. return err
  621. }
  622. return fmt.Errorf("newIssue: %v", err)
  623. }
  624. pr.Index = pull.Index
  625. pr.BaseRepo = repo
  626. pr.IssueID = pull.ID
  627. if _, err = sess.Insert(pr); err != nil {
  628. return fmt.Errorf("insert pull repo: %v", err)
  629. }
  630. if err = sess.Commit(); err != nil {
  631. return fmt.Errorf("Commit: %v", err)
  632. }
  633. return nil
  634. }
  635. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  636. // by given head/base and repo/branch.
  637. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  638. pr := new(PullRequest)
  639. has, err := x.
  640. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  641. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  642. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  643. Get(pr)
  644. if err != nil {
  645. return nil, err
  646. } else if !has {
  647. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  648. }
  649. return pr, nil
  650. }
  651. // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
  652. // by given head information (repo and branch).
  653. func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
  654. pr := new(PullRequest)
  655. has, err := x.
  656. Where("head_repo_id = ? AND head_branch = ?", repoID, branch).
  657. OrderBy("id DESC").
  658. Get(pr)
  659. if !has {
  660. return nil, err
  661. }
  662. return pr, err
  663. }
  664. // GetPullRequestByIndex returns a pull request by the given index
  665. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  666. pr := &PullRequest{
  667. BaseRepoID: repoID,
  668. Index: index,
  669. }
  670. has, err := x.Get(pr)
  671. if err != nil {
  672. return nil, err
  673. } else if !has {
  674. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  675. }
  676. if err = pr.LoadAttributes(); err != nil {
  677. return nil, err
  678. }
  679. if err = pr.LoadIssue(); err != nil {
  680. return nil, err
  681. }
  682. return pr, nil
  683. }
  684. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  685. pr := new(PullRequest)
  686. has, err := e.ID(id).Get(pr)
  687. if err != nil {
  688. return nil, err
  689. } else if !has {
  690. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  691. }
  692. return pr, pr.loadAttributes(e)
  693. }
  694. // GetPullRequestByID returns a pull request by given ID.
  695. func GetPullRequestByID(id int64) (*PullRequest, error) {
  696. return getPullRequestByID(x, id)
  697. }
  698. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  699. pr := &PullRequest{
  700. IssueID: issueID,
  701. }
  702. has, err := e.Get(pr)
  703. if err != nil {
  704. return nil, err
  705. } else if !has {
  706. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  707. }
  708. return pr, pr.loadAttributes(e)
  709. }
  710. // GetPullRequestByIssueID returns pull request by given issue ID.
  711. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  712. return getPullRequestByIssueID(x, issueID)
  713. }
  714. // Update updates all fields of pull request.
  715. func (pr *PullRequest) Update() error {
  716. _, err := x.ID(pr.ID).AllCols().Update(pr)
  717. return err
  718. }
  719. // UpdateCols updates specific fields of pull request.
  720. func (pr *PullRequest) UpdateCols(cols ...string) error {
  721. _, err := x.ID(pr.ID).Cols(cols...).Update(pr)
  722. return err
  723. }
  724. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  725. func (pr *PullRequest) IsWorkInProgress() bool {
  726. if err := pr.LoadIssue(); err != nil {
  727. log.Error("LoadIssue: %v", err)
  728. return false
  729. }
  730. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  731. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  732. return true
  733. }
  734. }
  735. return false
  736. }
  737. // IsFilesConflicted determines if the Pull Request has changes conflicting with the target branch.
  738. func (pr *PullRequest) IsFilesConflicted() bool {
  739. return len(pr.ConflictedFiles) > 0
  740. }
  741. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  742. // It returns an empty string when none were found
  743. func (pr *PullRequest) GetWorkInProgressPrefix() string {
  744. if err := pr.LoadIssue(); err != nil {
  745. log.Error("LoadIssue: %v", err)
  746. return ""
  747. }
  748. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  749. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  750. return pr.Issue.Title[0:len(prefix)]
  751. }
  752. }
  753. return ""
  754. }
  755. // IsHeadEqualWithBranch returns if the commits of branchName are available in pull request head
  756. func (pr *PullRequest) IsHeadEqualWithBranch(branchName string) (bool, error) {
  757. var err error
  758. if err = pr.GetBaseRepo(); err != nil {
  759. return false, err
  760. }
  761. baseGitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  762. if err != nil {
  763. return false, err
  764. }
  765. baseCommit, err := baseGitRepo.GetBranchCommit(branchName)
  766. if err != nil {
  767. return false, err
  768. }
  769. if err = pr.GetHeadRepo(); err != nil {
  770. return false, err
  771. }
  772. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  773. if err != nil {
  774. return false, err
  775. }
  776. headCommit, err := headGitRepo.GetBranchCommit(pr.HeadBranch)
  777. if err != nil {
  778. return false, err
  779. }
  780. return baseCommit.HasPreviousCommit(headCommit.ID)
  781. }