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 20 kB

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