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

pull.go 25 kB

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