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