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

1008 lines
29 KiB

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