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 29 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
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
8 years ago
8 years ago
9 years ago
9 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  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. "bufio"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/process"
  19. "code.gitea.io/gitea/modules/setting"
  20. api "code.gitea.io/gitea/modules/structs"
  21. "code.gitea.io/gitea/modules/sync"
  22. "code.gitea.io/gitea/modules/timeutil"
  23. "github.com/unknwon/com"
  24. )
  25. var pullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  26. // PullRequestType defines pull request type
  27. type PullRequestType int
  28. // Enumerate all the pull request types
  29. const (
  30. PullRequestGitea PullRequestType = iota
  31. PullRequestGit
  32. )
  33. // PullRequestStatus defines pull request status
  34. type PullRequestStatus int
  35. // Enumerate all the pull request status
  36. const (
  37. PullRequestStatusConflict PullRequestStatus = iota
  38. PullRequestStatusChecking
  39. PullRequestStatusMergeable
  40. PullRequestStatusManuallyMerged
  41. )
  42. // PullRequest represents relation between pull request and repositories.
  43. type PullRequest struct {
  44. ID int64 `xorm:"pk autoincr"`
  45. Type PullRequestType
  46. Status PullRequestStatus
  47. ConflictedFiles []string `xorm:"TEXT JSON"`
  48. IssueID int64 `xorm:"INDEX"`
  49. Issue *Issue `xorm:"-"`
  50. Index int64
  51. HeadRepoID int64 `xorm:"INDEX"`
  52. HeadRepo *Repository `xorm:"-"`
  53. BaseRepoID int64 `xorm:"INDEX"`
  54. BaseRepo *Repository `xorm:"-"`
  55. HeadBranch string
  56. BaseBranch string
  57. ProtectedBranch *ProtectedBranch `xorm:"-"`
  58. MergeBase string `xorm:"VARCHAR(40)"`
  59. HasMerged bool `xorm:"INDEX"`
  60. MergedCommitID string `xorm:"VARCHAR(40)"`
  61. MergerID int64 `xorm:"INDEX"`
  62. Merger *User `xorm:"-"`
  63. MergedUnix timeutil.TimeStamp `xorm:"updated INDEX"`
  64. }
  65. // MustHeadUserName returns the HeadRepo's username if failed return blank
  66. func (pr *PullRequest) MustHeadUserName() string {
  67. if err := pr.LoadHeadRepo(); err != nil {
  68. log.Error("LoadHeadRepo: %v", err)
  69. return ""
  70. }
  71. return pr.HeadRepo.MustOwnerName()
  72. }
  73. // Note: don't try to get Issue because will end up recursive querying.
  74. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  75. if pr.HasMerged && pr.Merger == nil {
  76. pr.Merger, err = getUserByID(e, pr.MergerID)
  77. if IsErrUserNotExist(err) {
  78. pr.MergerID = -1
  79. pr.Merger = NewGhostUser()
  80. } else if err != nil {
  81. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  82. }
  83. }
  84. return nil
  85. }
  86. // LoadAttributes loads pull request attributes from database
  87. func (pr *PullRequest) LoadAttributes() error {
  88. return pr.loadAttributes(x)
  89. }
  90. // LoadBaseRepo loads pull request base repository from database
  91. func (pr *PullRequest) LoadBaseRepo() error {
  92. if pr.BaseRepo == nil {
  93. if pr.HeadRepoID == pr.BaseRepoID && pr.HeadRepo != nil {
  94. pr.BaseRepo = pr.HeadRepo
  95. return nil
  96. }
  97. var repo Repository
  98. if has, err := x.ID(pr.BaseRepoID).Get(&repo); err != nil {
  99. return err
  100. } else if !has {
  101. return ErrRepoNotExist{ID: pr.BaseRepoID}
  102. }
  103. pr.BaseRepo = &repo
  104. }
  105. return nil
  106. }
  107. // LoadHeadRepo loads pull request head repository from database
  108. func (pr *PullRequest) LoadHeadRepo() error {
  109. if pr.HeadRepo == nil {
  110. if pr.HeadRepoID == pr.BaseRepoID && pr.BaseRepo != nil {
  111. pr.HeadRepo = pr.BaseRepo
  112. return nil
  113. }
  114. var repo Repository
  115. if has, err := x.ID(pr.HeadRepoID).Get(&repo); err != nil {
  116. return err
  117. } else if !has {
  118. return ErrRepoNotExist{ID: pr.BaseRepoID}
  119. }
  120. pr.HeadRepo = &repo
  121. }
  122. return nil
  123. }
  124. // LoadIssue loads issue information from database
  125. func (pr *PullRequest) LoadIssue() (err error) {
  126. return pr.loadIssue(x)
  127. }
  128. func (pr *PullRequest) loadIssue(e Engine) (err error) {
  129. if pr.Issue != nil {
  130. return nil
  131. }
  132. pr.Issue, err = getIssueByID(e, pr.IssueID)
  133. if err == nil {
  134. pr.Issue.PullRequest = pr
  135. }
  136. return err
  137. }
  138. // LoadProtectedBranch loads the protected branch of the base branch
  139. func (pr *PullRequest) LoadProtectedBranch() (err error) {
  140. if pr.BaseRepo == nil {
  141. if pr.BaseRepoID == 0 {
  142. return nil
  143. }
  144. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  145. if err != nil {
  146. return
  147. }
  148. }
  149. pr.ProtectedBranch, err = GetProtectedBranchBy(pr.BaseRepo.ID, pr.BaseBranch)
  150. return
  151. }
  152. // GetDefaultMergeMessage returns default message used when merging pull request
  153. func (pr *PullRequest) GetDefaultMergeMessage() string {
  154. if pr.HeadRepo == nil {
  155. var err error
  156. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  157. if err != nil {
  158. log.Error("GetRepositoryById[%d]: %v", pr.HeadRepoID, err)
  159. return ""
  160. }
  161. }
  162. return fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.MustHeadUserName(), pr.HeadRepo.Name, pr.BaseBranch)
  163. }
  164. // GetDefaultSquashMessage returns default message used when squash and merging pull request
  165. func (pr *PullRequest) GetDefaultSquashMessage() string {
  166. if err := pr.LoadIssue(); err != nil {
  167. log.Error("LoadIssue: %v", err)
  168. return ""
  169. }
  170. return fmt.Sprintf("%s (#%d)", pr.Issue.Title, pr.Issue.Index)
  171. }
  172. // GetGitRefName returns git ref for hidden pull request branch
  173. func (pr *PullRequest) GetGitRefName() string {
  174. return fmt.Sprintf("refs/pull/%d/head", pr.Index)
  175. }
  176. // APIFormat assumes following fields have been assigned with valid values:
  177. // Required - Issue
  178. // Optional - Merger
  179. func (pr *PullRequest) APIFormat() *api.PullRequest {
  180. return pr.apiFormat(x)
  181. }
  182. func (pr *PullRequest) apiFormat(e Engine) *api.PullRequest {
  183. var (
  184. baseBranch *git.Branch
  185. headBranch *git.Branch
  186. baseCommit *git.Commit
  187. headCommit *git.Commit
  188. err error
  189. )
  190. if err = pr.Issue.loadRepo(e); err != nil {
  191. log.Error("loadRepo[%d]: %v", pr.ID, err)
  192. return nil
  193. }
  194. apiIssue := pr.Issue.apiFormat(e)
  195. if pr.BaseRepo == nil {
  196. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  197. if err != nil {
  198. log.Error("GetRepositoryById[%d]: %v", pr.ID, err)
  199. return nil
  200. }
  201. }
  202. if pr.HeadRepo == nil {
  203. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  204. if err != nil {
  205. log.Error("GetRepositoryById[%d]: %v", pr.ID, err)
  206. return nil
  207. }
  208. }
  209. if err = pr.Issue.loadRepo(e); err != nil {
  210. log.Error("pr.Issue.loadRepo[%d]: %v", pr.ID, err)
  211. return nil
  212. }
  213. apiPullRequest := &api.PullRequest{
  214. ID: pr.ID,
  215. URL: pr.Issue.HTMLURL(),
  216. Index: pr.Index,
  217. Poster: apiIssue.Poster,
  218. Title: apiIssue.Title,
  219. Body: apiIssue.Body,
  220. Labels: apiIssue.Labels,
  221. Milestone: apiIssue.Milestone,
  222. Assignee: apiIssue.Assignee,
  223. Assignees: apiIssue.Assignees,
  224. State: apiIssue.State,
  225. Comments: apiIssue.Comments,
  226. HTMLURL: pr.Issue.HTMLURL(),
  227. DiffURL: pr.Issue.DiffURL(),
  228. PatchURL: pr.Issue.PatchURL(),
  229. HasMerged: pr.HasMerged,
  230. MergeBase: pr.MergeBase,
  231. Deadline: apiIssue.Deadline,
  232. Created: pr.Issue.CreatedUnix.AsTimePtr(),
  233. Updated: pr.Issue.UpdatedUnix.AsTimePtr(),
  234. }
  235. baseBranch, err = pr.BaseRepo.GetBranch(pr.BaseBranch)
  236. if err != nil {
  237. if git.IsErrBranchNotExist(err) {
  238. apiPullRequest.Base = nil
  239. } else {
  240. log.Error("GetBranch[%s]: %v", pr.BaseBranch, err)
  241. return nil
  242. }
  243. } else {
  244. apiBaseBranchInfo := &api.PRBranchInfo{
  245. Name: pr.BaseBranch,
  246. Ref: pr.BaseBranch,
  247. RepoID: pr.BaseRepoID,
  248. Repository: pr.BaseRepo.innerAPIFormat(e, AccessModeNone, false),
  249. }
  250. baseCommit, err = baseBranch.GetCommit()
  251. if err != nil {
  252. if git.IsErrNotExist(err) {
  253. apiBaseBranchInfo.Sha = ""
  254. } else {
  255. log.Error("GetCommit[%s]: %v", baseBranch.Name, err)
  256. return nil
  257. }
  258. } else {
  259. apiBaseBranchInfo.Sha = baseCommit.ID.String()
  260. }
  261. apiPullRequest.Base = apiBaseBranchInfo
  262. }
  263. headBranch, err = pr.HeadRepo.GetBranch(pr.HeadBranch)
  264. if err != nil {
  265. if git.IsErrBranchNotExist(err) {
  266. apiPullRequest.Head = nil
  267. } else {
  268. log.Error("GetBranch[%s]: %v", pr.HeadBranch, err)
  269. return nil
  270. }
  271. } else {
  272. apiHeadBranchInfo := &api.PRBranchInfo{
  273. Name: pr.HeadBranch,
  274. Ref: pr.HeadBranch,
  275. RepoID: pr.HeadRepoID,
  276. Repository: pr.HeadRepo.innerAPIFormat(e, AccessModeNone, false),
  277. }
  278. headCommit, err = headBranch.GetCommit()
  279. if err != nil {
  280. if git.IsErrNotExist(err) {
  281. apiHeadBranchInfo.Sha = ""
  282. } else {
  283. log.Error("GetCommit[%s]: %v", headBranch.Name, err)
  284. return nil
  285. }
  286. } else {
  287. apiHeadBranchInfo.Sha = headCommit.ID.String()
  288. }
  289. apiPullRequest.Head = apiHeadBranchInfo
  290. }
  291. if pr.Status != PullRequestStatusChecking {
  292. mergeable := pr.Status != PullRequestStatusConflict && !pr.IsWorkInProgress()
  293. apiPullRequest.Mergeable = mergeable
  294. }
  295. if pr.HasMerged {
  296. apiPullRequest.Merged = pr.MergedUnix.AsTimePtr()
  297. apiPullRequest.MergedCommitID = &pr.MergedCommitID
  298. apiPullRequest.MergedBy = pr.Merger.APIFormat()
  299. }
  300. return apiPullRequest
  301. }
  302. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  303. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  304. if err != nil && !IsErrRepoNotExist(err) {
  305. return fmt.Errorf("getRepositoryByID(head): %v", err)
  306. }
  307. return nil
  308. }
  309. // GetHeadRepo loads the head repository
  310. func (pr *PullRequest) GetHeadRepo() error {
  311. return pr.getHeadRepo(x)
  312. }
  313. // GetBaseRepo loads the target repository
  314. func (pr *PullRequest) GetBaseRepo() (err error) {
  315. if pr.BaseRepo != nil {
  316. return nil
  317. }
  318. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  319. if err != nil {
  320. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  321. }
  322. return nil
  323. }
  324. // IsChecking returns true if this pull request is still checking conflict.
  325. func (pr *PullRequest) IsChecking() bool {
  326. return pr.Status == PullRequestStatusChecking
  327. }
  328. // CanAutoMerge returns true if this pull request can be merged automatically.
  329. func (pr *PullRequest) CanAutoMerge() bool {
  330. return pr.Status == PullRequestStatusMergeable
  331. }
  332. // GetLastCommitStatus returns the last commit status for this pull request.
  333. func (pr *PullRequest) GetLastCommitStatus() (status *CommitStatus, err error) {
  334. if err = pr.GetHeadRepo(); err != nil {
  335. return nil, err
  336. }
  337. if pr.HeadRepo == nil {
  338. return nil, ErrPullRequestHeadRepoMissing{pr.ID, pr.HeadRepoID}
  339. }
  340. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  341. if err != nil {
  342. return nil, err
  343. }
  344. defer headGitRepo.Close()
  345. lastCommitID, err := headGitRepo.GetBranchCommitID(pr.HeadBranch)
  346. if err != nil {
  347. return nil, err
  348. }
  349. err = pr.LoadBaseRepo()
  350. if err != nil {
  351. return nil, err
  352. }
  353. statusList, err := GetLatestCommitStatus(pr.BaseRepo, lastCommitID, 0)
  354. if err != nil {
  355. return nil, err
  356. }
  357. return CalcCommitStatus(statusList), nil
  358. }
  359. // MergeStyle represents the approach to merge commits into base branch.
  360. type MergeStyle string
  361. const (
  362. // MergeStyleMerge create merge commit
  363. MergeStyleMerge MergeStyle = "merge"
  364. // MergeStyleRebase rebase before merging
  365. MergeStyleRebase MergeStyle = "rebase"
  366. // MergeStyleRebaseMerge rebase before merging with merge commit (--no-ff)
  367. MergeStyleRebaseMerge MergeStyle = "rebase-merge"
  368. // MergeStyleSquash squash commits into single commit before merging
  369. MergeStyleSquash MergeStyle = "squash"
  370. )
  371. // CheckUserAllowedToMerge checks whether the user is allowed to merge
  372. func (pr *PullRequest) CheckUserAllowedToMerge(doer *User) (err error) {
  373. if doer == nil {
  374. return ErrNotAllowedToMerge{
  375. "Not signed in",
  376. }
  377. }
  378. if pr.BaseRepo == nil {
  379. if err = pr.GetBaseRepo(); err != nil {
  380. return fmt.Errorf("GetBaseRepo: %v", err)
  381. }
  382. }
  383. if protected, err := pr.BaseRepo.IsProtectedBranchForMerging(pr, pr.BaseBranch, doer); err != nil {
  384. return fmt.Errorf("IsProtectedBranch: %v", err)
  385. } else if protected {
  386. return ErrNotAllowedToMerge{
  387. "The branch is protected",
  388. }
  389. }
  390. return nil
  391. }
  392. // SetMerged sets a pull request to merged and closes the corresponding issue
  393. func (pr *PullRequest) SetMerged() (err error) {
  394. if pr.HasMerged {
  395. return fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  396. }
  397. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  398. return fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  399. }
  400. pr.HasMerged = true
  401. sess := x.NewSession()
  402. defer sess.Close()
  403. if err = sess.Begin(); err != nil {
  404. return err
  405. }
  406. if err = pr.loadIssue(sess); err != nil {
  407. return err
  408. }
  409. if err = pr.Issue.loadRepo(sess); err != nil {
  410. return err
  411. }
  412. if err = pr.Issue.Repo.getOwner(sess); err != nil {
  413. return err
  414. }
  415. if err = pr.Issue.changeStatus(sess, pr.Merger, true); err != nil {
  416. return fmt.Errorf("Issue.changeStatus: %v", err)
  417. }
  418. if _, err = sess.ID(pr.ID).Cols("has_merged, status, merged_commit_id, merger_id, merged_unix").Update(pr); err != nil {
  419. return fmt.Errorf("update pull request: %v", err)
  420. }
  421. if err = sess.Commit(); err != nil {
  422. return fmt.Errorf("Commit: %v", err)
  423. }
  424. return nil
  425. }
  426. // manuallyMerged checks if a pull request got manually merged
  427. // When a pull request got manually merged mark the pull request as merged
  428. func (pr *PullRequest) manuallyMerged() bool {
  429. commit, err := pr.getMergeCommit()
  430. if err != nil {
  431. log.Error("PullRequest[%d].getMergeCommit: %v", pr.ID, err)
  432. return false
  433. }
  434. if commit != nil {
  435. pr.MergedCommitID = commit.ID.String()
  436. pr.MergedUnix = timeutil.TimeStamp(commit.Author.When.Unix())
  437. pr.Status = PullRequestStatusManuallyMerged
  438. merger, _ := GetUserByEmail(commit.Author.Email)
  439. // When the commit author is unknown set the BaseRepo owner as merger
  440. if merger == nil {
  441. if pr.BaseRepo.Owner == nil {
  442. if err = pr.BaseRepo.getOwner(x); err != nil {
  443. log.Error("BaseRepo.getOwner[%d]: %v", pr.ID, err)
  444. return false
  445. }
  446. }
  447. merger = pr.BaseRepo.Owner
  448. }
  449. pr.Merger = merger
  450. pr.MergerID = merger.ID
  451. if err = pr.SetMerged(); err != nil {
  452. log.Error("PullRequest[%d].setMerged : %v", pr.ID, err)
  453. return false
  454. }
  455. log.Info("manuallyMerged[%d]: Marked as manually merged into %s/%s by commit id: %s", pr.ID, pr.BaseRepo.Name, pr.BaseBranch, commit.ID.String())
  456. return true
  457. }
  458. return false
  459. }
  460. // getMergeCommit checks if a pull request got merged
  461. // Returns the git.Commit of the pull request if merged
  462. func (pr *PullRequest) getMergeCommit() (*git.Commit, error) {
  463. if pr.BaseRepo == nil {
  464. var err error
  465. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  466. if err != nil {
  467. return nil, fmt.Errorf("GetRepositoryByID: %v", err)
  468. }
  469. }
  470. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  471. defer os.Remove(indexTmpPath)
  472. headFile := pr.GetGitRefName()
  473. // Check if a pull request is merged into BaseBranch
  474. _, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git merge-base --is-ancestor): %d", pr.BaseRepo.ID),
  475. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  476. git.GitExecutable, "merge-base", "--is-ancestor", headFile, pr.BaseBranch)
  477. if err != nil {
  478. // Errors are signaled by a non-zero status that is not 1
  479. if strings.Contains(err.Error(), "exit status 1") {
  480. return nil, nil
  481. }
  482. return nil, fmt.Errorf("git merge-base --is-ancestor: %v %v", stderr, err)
  483. }
  484. commitIDBytes, err := ioutil.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
  485. if err != nil {
  486. return nil, fmt.Errorf("ReadFile(%s): %v", headFile, err)
  487. }
  488. commitID := string(commitIDBytes)
  489. if len(commitID) < 40 {
  490. return nil, fmt.Errorf(`ReadFile(%s): invalid commit-ID "%s"`, headFile, commitID)
  491. }
  492. cmd := commitID[:40] + ".." + pr.BaseBranch
  493. // Get the commit from BaseBranch where the pull request got merged
  494. mergeCommit, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git rev-list --ancestry-path --merges --reverse): %d", pr.BaseRepo.ID),
  495. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  496. git.GitExecutable, "rev-list", "--ancestry-path", "--merges", "--reverse", cmd)
  497. if err != nil {
  498. return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v %v", stderr, err)
  499. } else if len(mergeCommit) < 40 {
  500. // PR was fast-forwarded, so just use last commit of PR
  501. mergeCommit = commitID[:40]
  502. }
  503. gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  504. if err != nil {
  505. return nil, fmt.Errorf("OpenRepository: %v", err)
  506. }
  507. defer gitRepo.Close()
  508. commit, err := gitRepo.GetCommit(mergeCommit[:40])
  509. if err != nil {
  510. return nil, fmt.Errorf("GetCommit: %v", err)
  511. }
  512. return commit, nil
  513. }
  514. // patchConflicts is a list of conflict description from Git.
  515. var patchConflicts = []string{
  516. "patch does not apply",
  517. "already exists in working directory",
  518. "unrecognized input",
  519. "error:",
  520. }
  521. // testPatch checks if patch can be merged to base repository without conflict.
  522. func (pr *PullRequest) testPatch(e Engine) (err error) {
  523. if pr.BaseRepo == nil {
  524. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  525. if err != nil {
  526. return fmt.Errorf("GetRepositoryByID: %v", err)
  527. }
  528. }
  529. patchPath, err := pr.BaseRepo.patchPath(e, pr.Index)
  530. if err != nil {
  531. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  532. }
  533. // Fast fail if patch does not exist, this assumes data is corrupted.
  534. if !com.IsFile(patchPath) {
  535. log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID)
  536. return nil
  537. }
  538. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  539. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  540. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  541. pr.Status = PullRequestStatusChecking
  542. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  543. defer os.Remove(indexTmpPath)
  544. var stderr string
  545. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git read-tree): %d", pr.BaseRepo.ID),
  546. []string{"GIT_DIR=" + pr.BaseRepo.RepoPath(), "GIT_INDEX_FILE=" + indexTmpPath},
  547. git.GitExecutable, "read-tree", pr.BaseBranch)
  548. if err != nil {
  549. return fmt.Errorf("git read-tree --index-output=%s %s: %v - %s", indexTmpPath, pr.BaseBranch, err, stderr)
  550. }
  551. prUnit, err := pr.BaseRepo.getUnit(e, UnitTypePullRequests)
  552. if err != nil {
  553. return err
  554. }
  555. prConfig := prUnit.PullRequestsConfig()
  556. args := []string{"apply", "--check", "--cached"}
  557. if prConfig.IgnoreWhitespaceConflicts {
  558. args = append(args, "--ignore-whitespace")
  559. }
  560. args = append(args, patchPath)
  561. pr.ConflictedFiles = []string{}
  562. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  563. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  564. git.GitExecutable, args...)
  565. if err != nil {
  566. for i := range patchConflicts {
  567. if strings.Contains(stderr, patchConflicts[i]) {
  568. log.Trace("PullRequest[%d].testPatch (apply): has conflict: %s", pr.ID, stderr)
  569. const prefix = "error: patch failed:"
  570. pr.Status = PullRequestStatusConflict
  571. pr.ConflictedFiles = make([]string, 0, 5)
  572. scanner := bufio.NewScanner(strings.NewReader(stderr))
  573. for scanner.Scan() {
  574. line := scanner.Text()
  575. if strings.HasPrefix(line, prefix) {
  576. var found bool
  577. var filepath = strings.TrimSpace(strings.Split(line[len(prefix):], ":")[0])
  578. for _, f := range pr.ConflictedFiles {
  579. if f == filepath {
  580. found = true
  581. break
  582. }
  583. }
  584. if !found {
  585. pr.ConflictedFiles = append(pr.ConflictedFiles, filepath)
  586. }
  587. }
  588. // only list 10 conflicted files
  589. if len(pr.ConflictedFiles) >= 10 {
  590. break
  591. }
  592. }
  593. if len(pr.ConflictedFiles) > 0 {
  594. log.Trace("Found %d files conflicted: %v", len(pr.ConflictedFiles), pr.ConflictedFiles)
  595. }
  596. return nil
  597. }
  598. }
  599. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  600. }
  601. return nil
  602. }
  603. // NewPullRequest creates new pull request with labels for repository.
  604. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  605. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  606. i := 0
  607. for {
  608. if err = newPullRequestAttempt(repo, pull, labelIDs, uuids, pr, patch); err == nil {
  609. return nil
  610. }
  611. if !IsErrNewIssueInsert(err) {
  612. return err
  613. }
  614. if i++; i == issueMaxDupIndexAttempts {
  615. break
  616. }
  617. log.Error("NewPullRequest: error attempting to insert the new issue; will retry. Original error: %v", err)
  618. }
  619. return fmt.Errorf("NewPullRequest: too many errors attempting to insert the new issue. Last error was: %v", err)
  620. }
  621. func newPullRequestAttempt(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  622. sess := x.NewSession()
  623. defer sess.Close()
  624. if err = sess.Begin(); err != nil {
  625. return err
  626. }
  627. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  628. Repo: repo,
  629. Issue: pull,
  630. LabelIDs: labelIDs,
  631. Attachments: uuids,
  632. IsPull: true,
  633. }); err != nil {
  634. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  635. return err
  636. }
  637. return fmt.Errorf("newIssue: %v", err)
  638. }
  639. pr.Index = pull.Index
  640. pr.BaseRepo = repo
  641. pr.Status = PullRequestStatusChecking
  642. if len(patch) > 0 {
  643. if err = repo.savePatch(sess, pr.Index, patch); err != nil {
  644. return fmt.Errorf("SavePatch: %v", err)
  645. }
  646. if err = pr.testPatch(sess); err != nil {
  647. return fmt.Errorf("testPatch: %v", err)
  648. }
  649. }
  650. // No conflict appears after test means mergeable.
  651. if pr.Status == PullRequestStatusChecking {
  652. pr.Status = PullRequestStatusMergeable
  653. }
  654. pr.IssueID = pull.ID
  655. if _, err = sess.Insert(pr); err != nil {
  656. return fmt.Errorf("insert pull repo: %v", err)
  657. }
  658. if err = sess.Commit(); err != nil {
  659. return fmt.Errorf("Commit: %v", err)
  660. }
  661. return nil
  662. }
  663. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  664. // by given head/base and repo/branch.
  665. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  666. pr := new(PullRequest)
  667. has, err := x.
  668. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  669. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  670. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  671. Get(pr)
  672. if err != nil {
  673. return nil, err
  674. } else if !has {
  675. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  676. }
  677. return pr, nil
  678. }
  679. // GetLatestPullRequestByHeadInfo returns the latest pull request (regardless of its status)
  680. // by given head information (repo and branch).
  681. func GetLatestPullRequestByHeadInfo(repoID int64, branch string) (*PullRequest, error) {
  682. pr := new(PullRequest)
  683. has, err := x.
  684. Where("head_repo_id = ? AND head_branch = ?", repoID, branch).
  685. OrderBy("id DESC").
  686. Get(pr)
  687. if !has {
  688. return nil, err
  689. }
  690. return pr, err
  691. }
  692. // GetPullRequestByIndex returns a pull request by the given index
  693. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  694. pr := &PullRequest{
  695. BaseRepoID: repoID,
  696. Index: index,
  697. }
  698. has, err := x.Get(pr)
  699. if err != nil {
  700. return nil, err
  701. } else if !has {
  702. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  703. }
  704. if err = pr.LoadAttributes(); err != nil {
  705. return nil, err
  706. }
  707. if err = pr.LoadIssue(); err != nil {
  708. return nil, err
  709. }
  710. return pr, nil
  711. }
  712. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  713. pr := new(PullRequest)
  714. has, err := e.ID(id).Get(pr)
  715. if err != nil {
  716. return nil, err
  717. } else if !has {
  718. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  719. }
  720. return pr, pr.loadAttributes(e)
  721. }
  722. // GetPullRequestByID returns a pull request by given ID.
  723. func GetPullRequestByID(id int64) (*PullRequest, error) {
  724. return getPullRequestByID(x, id)
  725. }
  726. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  727. pr := &PullRequest{
  728. IssueID: issueID,
  729. }
  730. has, err := e.Get(pr)
  731. if err != nil {
  732. return nil, err
  733. } else if !has {
  734. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  735. }
  736. return pr, pr.loadAttributes(e)
  737. }
  738. // GetPullRequestByIssueID returns pull request by given issue ID.
  739. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  740. return getPullRequestByIssueID(x, issueID)
  741. }
  742. // Update updates all fields of pull request.
  743. func (pr *PullRequest) Update() error {
  744. _, err := x.ID(pr.ID).AllCols().Update(pr)
  745. return err
  746. }
  747. // UpdateCols updates specific fields of pull request.
  748. func (pr *PullRequest) UpdateCols(cols ...string) error {
  749. _, err := x.ID(pr.ID).Cols(cols...).Update(pr)
  750. return err
  751. }
  752. // UpdatePatch generates and saves a new patch.
  753. func (pr *PullRequest) UpdatePatch() (err error) {
  754. if err = pr.GetHeadRepo(); err != nil {
  755. return fmt.Errorf("GetHeadRepo: %v", err)
  756. } else if pr.HeadRepo == nil {
  757. log.Trace("PullRequest[%d].UpdatePatch: ignored corrupted data", pr.ID)
  758. return nil
  759. }
  760. if err = pr.GetBaseRepo(); err != nil {
  761. return fmt.Errorf("GetBaseRepo: %v", err)
  762. }
  763. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  764. if err != nil {
  765. return fmt.Errorf("OpenRepository: %v", err)
  766. }
  767. defer headGitRepo.Close()
  768. // Add a temporary remote.
  769. tmpRemote := com.ToStr(time.Now().UnixNano())
  770. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  771. return fmt.Errorf("AddRemote: %v", err)
  772. }
  773. defer func() {
  774. if err := headGitRepo.RemoveRemote(tmpRemote); err != nil {
  775. log.Error("UpdatePatch: RemoveRemote: %s", err)
  776. }
  777. }()
  778. pr.MergeBase, _, err = headGitRepo.GetMergeBase(tmpRemote, pr.BaseBranch, pr.HeadBranch)
  779. if err != nil {
  780. return fmt.Errorf("GetMergeBase: %v", err)
  781. } else if err = pr.Update(); err != nil {
  782. return fmt.Errorf("Update: %v", err)
  783. }
  784. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  785. if err != nil {
  786. return fmt.Errorf("GetPatch: %v", err)
  787. }
  788. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  789. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  790. }
  791. return nil
  792. }
  793. // PushToBaseRepo pushes commits from branches of head repository to
  794. // corresponding branches of base repository.
  795. // FIXME: Only push branches that are actually updates?
  796. func (pr *PullRequest) PushToBaseRepo() (err error) {
  797. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo '%s'", pr.BaseRepoID, pr.GetGitRefName())
  798. headRepoPath := pr.HeadRepo.RepoPath()
  799. headGitRepo, err := git.OpenRepository(headRepoPath)
  800. if err != nil {
  801. return fmt.Errorf("OpenRepository: %v", err)
  802. }
  803. defer headGitRepo.Close()
  804. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  805. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  806. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  807. }
  808. // Make sure to remove the remote even if the push fails
  809. defer func() {
  810. if err := headGitRepo.RemoveRemote(tmpRemoteName); err != nil {
  811. log.Error("PushToBaseRepo: RemoveRemote: %s", err)
  812. }
  813. }()
  814. headFile := pr.GetGitRefName()
  815. // Remove head in case there is a conflict.
  816. file := path.Join(pr.BaseRepo.RepoPath(), headFile)
  817. _ = os.Remove(file)
  818. if err = git.Push(headRepoPath, git.PushOptions{
  819. Remote: tmpRemoteName,
  820. Branch: fmt.Sprintf("%s:%s", pr.HeadBranch, headFile),
  821. Force: true,
  822. }); err != nil {
  823. return fmt.Errorf("Push: %v", err)
  824. }
  825. return nil
  826. }
  827. // AddToTaskQueue adds itself to pull request test task queue.
  828. func (pr *PullRequest) AddToTaskQueue() {
  829. go pullRequestQueue.AddFunc(pr.ID, func() {
  830. pr.Status = PullRequestStatusChecking
  831. if err := pr.UpdateCols("status"); err != nil {
  832. log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  833. }
  834. })
  835. }
  836. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  837. // and set to be either conflict or mergeable.
  838. func (pr *PullRequest) checkAndUpdateStatus() {
  839. // Status is not changed to conflict means mergeable.
  840. if pr.Status == PullRequestStatusChecking {
  841. pr.Status = PullRequestStatusMergeable
  842. }
  843. // Make sure there is no waiting test to process before leaving the checking status.
  844. if !pullRequestQueue.Exist(pr.ID) {
  845. if err := pr.UpdateCols("status, conflicted_files"); err != nil {
  846. log.Error("Update[%d]: %v", pr.ID, err)
  847. }
  848. }
  849. }
  850. // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title
  851. func (pr *PullRequest) IsWorkInProgress() bool {
  852. if err := pr.LoadIssue(); err != nil {
  853. log.Error("LoadIssue: %v", err)
  854. return false
  855. }
  856. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  857. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  858. return true
  859. }
  860. }
  861. return false
  862. }
  863. // IsFilesConflicted determines if the Pull Request has changes conflicting with the target branch.
  864. func (pr *PullRequest) IsFilesConflicted() bool {
  865. return len(pr.ConflictedFiles) > 0
  866. }
  867. // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress.
  868. // It returns an empty string when none were found
  869. func (pr *PullRequest) GetWorkInProgressPrefix() string {
  870. if err := pr.LoadIssue(); err != nil {
  871. log.Error("LoadIssue: %v", err)
  872. return ""
  873. }
  874. for _, prefix := range setting.Repository.PullRequest.WorkInProgressPrefixes {
  875. if strings.HasPrefix(strings.ToUpper(pr.Issue.Title), prefix) {
  876. return pr.Issue.Title[0:len(prefix)]
  877. }
  878. }
  879. return ""
  880. }