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

1010 lines
31 KiB

9 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
Pull request review/approval and comment on code (#3748) * Initial ui components for pull request review * Add Review Add IssueComment types Signed-off-by: Jonas Franz <info@jonasfranz.software> (cherry picked from commit 2b4daab) Signed-off-by: Jonas Franz <info@jonasfranz.software> * Replace ReviewComment with Content Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add load functions Add ReviewID to findComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add create review comment implementation Add migration for review Other small changes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Simplified create and find functions for review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved "Pending" to first position Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add GetCurrentReview to simplify fetching current review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Preview for listing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Move new comment form to its own file Signed-off-by: Jonas Franz <info@jonasfranz.software> * Implement Review form Show Review comments on comment stream Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for single comments Showing buttons in context Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add pending tag to pending review comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add unit tests for Review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fetch all review ids at once Add unit tests Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improved comment rendering in "Files" view by adding Comments to DiffLine Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for invalidating comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Switched back to code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved review migration from v64 to v65 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Rebuild css Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improve translations Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests by updating fixtures and updating outdated test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Comments will be shown at the right place now Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for deleting CodeComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems caused by files in subdirectories Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for showing code comments of reviews in conversation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for "Show/Hide outdated" Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for new webhooks Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update comparison Signed-off-by: Jonas Franz <info@jonasfranz.software> * Resolve conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Minor UI improvements * update code.gitea.io/git * Fix ui bug reported by @lunny causing wrong position of add button Add functionality to "Cancel" button Add scale effects to add button Hide "Cancel" button for existing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Prepare solving conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show add button only if no comments already exist for the line Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing vendor files Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if reviewer is nil Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show forms only to users who are logged in Signed-off-by: Jonas Franz <info@jonasfranz.software> * Revert "Show forms only to users who are logged in" This reverts commit c083682 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Save patch in comment Render patch for code comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add link to comment in code Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add reply form to comment list Show forms only to signed in users Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add 'Reply' as translatable Add CODE_COMMENT_LINES setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems introduced by checking for singed in user Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add v70 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update generated stylesheet Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix preview Beginn with new review comment patch system Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add new algo to generate diff for line range Remove old algo used for cutting big diffs (it was very buggy) * Add documentation and example for CutDiffAroundLine * Fix example of CutDiffAroundLine * Fix some comment UI rendering bugs * Add code comment edit mode * Send notifications / actions to users until review gets published Fix diff generation bug Fix wrong hashtag * Fix vet errors * Send notifications also for single comments * Fix some notification bugs, fix link * Fix: add comment icon is only shown on code lines * Add lint comment * Add unit tests for git diff * Add more error messages * Regenerated css Signed-off-by: Jonas Franz <info@jonasfranz.software> * fmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Regenerated CSS with latest less version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by updating comment type to new ID Signed-off-by: Jonas Franz <info@jonasfranz.software> * Introducing CodeComments as type for map[string]map[int64][]*Comment Other minor code improvements Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix data-tab issues Signed-off-by: Jonas Franz <info@jonasfranz.software> * Remove unnecessary change Signed-off-by: Jonas Franz <info@jonasfranz.software> * refactored checkForInvalidation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Append comments instead of setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * Use HeadRepo instead of BaseRepo Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update migration Signed-off-by: Jonas Franz <info@jonasfranz.de> * Regenerated CSS Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add copyright Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update index.css Signed-off-by: Jonas Franz <info@jonasfranz.software>
6 years ago
Pull request review/approval and comment on code (#3748) * Initial ui components for pull request review * Add Review Add IssueComment types Signed-off-by: Jonas Franz <info@jonasfranz.software> (cherry picked from commit 2b4daab) Signed-off-by: Jonas Franz <info@jonasfranz.software> * Replace ReviewComment with Content Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add load functions Add ReviewID to findComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add create review comment implementation Add migration for review Other small changes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Simplified create and find functions for review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved "Pending" to first position Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add GetCurrentReview to simplify fetching current review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Preview for listing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Move new comment form to its own file Signed-off-by: Jonas Franz <info@jonasfranz.software> * Implement Review form Show Review comments on comment stream Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for single comments Showing buttons in context Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add pending tag to pending review comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add unit tests for Review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fetch all review ids at once Add unit tests Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improved comment rendering in "Files" view by adding Comments to DiffLine Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for invalidating comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Switched back to code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved review migration from v64 to v65 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Rebuild css Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improve translations Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests by updating fixtures and updating outdated test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Comments will be shown at the right place now Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for deleting CodeComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems caused by files in subdirectories Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for showing code comments of reviews in conversation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for "Show/Hide outdated" Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for new webhooks Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update comparison Signed-off-by: Jonas Franz <info@jonasfranz.software> * Resolve conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Minor UI improvements * update code.gitea.io/git * Fix ui bug reported by @lunny causing wrong position of add button Add functionality to "Cancel" button Add scale effects to add button Hide "Cancel" button for existing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Prepare solving conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show add button only if no comments already exist for the line Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing vendor files Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if reviewer is nil Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show forms only to users who are logged in Signed-off-by: Jonas Franz <info@jonasfranz.software> * Revert "Show forms only to users who are logged in" This reverts commit c083682 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Save patch in comment Render patch for code comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add link to comment in code Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add reply form to comment list Show forms only to signed in users Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add 'Reply' as translatable Add CODE_COMMENT_LINES setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems introduced by checking for singed in user Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add v70 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update generated stylesheet Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix preview Beginn with new review comment patch system Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add new algo to generate diff for line range Remove old algo used for cutting big diffs (it was very buggy) * Add documentation and example for CutDiffAroundLine * Fix example of CutDiffAroundLine * Fix some comment UI rendering bugs * Add code comment edit mode * Send notifications / actions to users until review gets published Fix diff generation bug Fix wrong hashtag * Fix vet errors * Send notifications also for single comments * Fix some notification bugs, fix link * Fix: add comment icon is only shown on code lines * Add lint comment * Add unit tests for git diff * Add more error messages * Regenerated css Signed-off-by: Jonas Franz <info@jonasfranz.software> * fmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Regenerated CSS with latest less version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by updating comment type to new ID Signed-off-by: Jonas Franz <info@jonasfranz.software> * Introducing CodeComments as type for map[string]map[int64][]*Comment Other minor code improvements Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix data-tab issues Signed-off-by: Jonas Franz <info@jonasfranz.software> * Remove unnecessary change Signed-off-by: Jonas Franz <info@jonasfranz.software> * refactored checkForInvalidation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Append comments instead of setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * Use HeadRepo instead of BaseRepo Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update migration Signed-off-by: Jonas Franz <info@jonasfranz.de> * Regenerated CSS Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add copyright Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update index.css Signed-off-by: Jonas Franz <info@jonasfranz.software>
6 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
5 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
9 years ago
9 years ago
9 years ago
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 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 migrations
  6. import (
  7. "bytes"
  8. "encoding/json"
  9. "fmt"
  10. "io/ioutil"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "regexp"
  15. "strings"
  16. "time"
  17. "github.com/Unknwon/com"
  18. "github.com/go-xorm/xorm"
  19. gouuid "github.com/satori/go.uuid"
  20. ini "gopkg.in/ini.v1"
  21. "code.gitea.io/gitea/modules/generate"
  22. "code.gitea.io/gitea/modules/log"
  23. "code.gitea.io/gitea/modules/setting"
  24. )
  25. const minDBVersion = 4
  26. // Migration describes on migration from lower version to high version
  27. type Migration interface {
  28. Description() string
  29. Migrate(*xorm.Engine) error
  30. }
  31. type migration struct {
  32. description string
  33. migrate func(*xorm.Engine) error
  34. }
  35. // NewMigration creates a new migration
  36. func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
  37. return &migration{desc, fn}
  38. }
  39. // Description returns the migration's description
  40. func (m *migration) Description() string {
  41. return m.description
  42. }
  43. // Migrate executes the migration
  44. func (m *migration) Migrate(x *xorm.Engine) error {
  45. return m.migrate(x)
  46. }
  47. // Version describes the version table. Should have only one row with id==1
  48. type Version struct {
  49. ID int64 `xorm:"pk autoincr"`
  50. Version int64
  51. }
  52. func emptyMigration(x *xorm.Engine) error {
  53. return nil
  54. }
  55. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  56. // If you want to "retire" a migration, remove it from the top of the list and
  57. // update minDBVersion accordingly
  58. var migrations = []Migration{
  59. // v0 -> v4: before 0.6.0 -> 0.7.33
  60. NewMigration("fix locale file load panic", fixLocaleFileLoadPanic), // V4 -> V5:v0.6.0
  61. NewMigration("trim action compare URL prefix", trimCommitActionAppURLPrefix), // V5 -> V6:v0.6.3
  62. NewMigration("generate issue-label from issue", issueToIssueLabel), // V6 -> V7:v0.6.4
  63. NewMigration("refactor attachment table", attachmentRefactor), // V7 -> V8:v0.6.4
  64. NewMigration("rename pull request fields", renamePullRequestFields), // V8 -> V9:v0.6.16
  65. NewMigration("clean up migrate repo info", cleanUpMigrateRepoInfo), // V9 -> V10:v0.6.20
  66. NewMigration("generate rands and salt for organizations", generateOrgRandsAndSalt), // V10 -> V11:v0.8.5
  67. NewMigration("convert date to unix timestamp", convertDateToUnix), // V11 -> V12:v0.9.2
  68. NewMigration("convert LDAP UseSSL option to SecurityProtocol", ldapUseSSLToSecurityProtocol), // V12 -> V13:v0.9.37
  69. // v13 -> v14:v0.9.87
  70. NewMigration("set comment updated with created", setCommentUpdatedWithCreated),
  71. // v14 -> v15
  72. NewMigration("create user column diff view style", createUserColumnDiffViewStyle),
  73. // v15 -> v16
  74. NewMigration("create user column allow create organization", createAllowCreateOrganizationColumn),
  75. // V16 -> v17
  76. NewMigration("create repo unit table and add units for all repos", addUnitsToTables),
  77. // v17 -> v18
  78. NewMigration("set protect branches updated with created", setProtectedBranchUpdatedWithCreated),
  79. // v18 -> v19
  80. NewMigration("add external login user", addExternalLoginUser),
  81. // v19 -> v20
  82. NewMigration("generate and migrate Git hooks", generateAndMigrateGitHooks),
  83. // v20 -> v21
  84. NewMigration("use new avatar path name for security reason", useNewNameAvatars),
  85. // v21 -> v22
  86. NewMigration("rewrite authorized_keys file via new format", useNewPublickeyFormat),
  87. // v22 -> v23
  88. NewMigration("generate and migrate wiki Git hooks", generateAndMigrateWikiGitHooks),
  89. // v23 -> v24
  90. NewMigration("add user openid table", addUserOpenID),
  91. // v24 -> v25
  92. NewMigration("change the key_id and primary_key_id type", changeGPGKeysColumns),
  93. // v25 -> v26
  94. NewMigration("add show field in user openid table", addUserOpenIDShow),
  95. // v26 -> v27
  96. NewMigration("generate and migrate repo and wiki Git hooks", generateAndMigrateGitHookChains),
  97. // v27 -> v28
  98. NewMigration("change mirror interval from hours to time.Duration", convertIntervalToDuration),
  99. // v28 -> v29
  100. NewMigration("add field for repo size", addRepoSize),
  101. // v29 -> v30
  102. NewMigration("add commit status table", addCommitStatus),
  103. // v30 -> 31
  104. NewMigration("add primary key to external login user", addExternalLoginUserPK),
  105. // v31 -> 32
  106. NewMigration("add field for login source synchronization", addLoginSourceSyncEnabledColumn),
  107. // v32 -> v33
  108. NewMigration("add units for team", addUnitsToRepoTeam),
  109. // v33 -> v34
  110. NewMigration("remove columns from action", removeActionColumns),
  111. // v34 -> v35
  112. NewMigration("give all units to owner teams", giveAllUnitsToOwnerTeams),
  113. // v35 -> v36
  114. NewMigration("adds comment to an action", addCommentIDToAction),
  115. // v36 -> v37
  116. NewMigration("regenerate git hooks", regenerateGitHooks36),
  117. // v37 -> v38
  118. NewMigration("unescape user full names", unescapeUserFullNames),
  119. // v38 -> v39
  120. NewMigration("remove commits and settings unit types", removeCommitsUnitType),
  121. // v39 -> v40
  122. NewMigration("add tags to releases and sync existing repositories", releaseAddColumnIsTagAndSyncTags),
  123. // v40 -> v41
  124. NewMigration("fix protected branch can push value to false", fixProtectedBranchCanPushValue),
  125. // v41 -> v42
  126. NewMigration("remove duplicate unit types", removeDuplicateUnitTypes),
  127. // v42 -> v43
  128. NewMigration("empty step", emptyMigration),
  129. // v43 -> v44
  130. NewMigration("empty step", emptyMigration),
  131. // v44 -> v45
  132. NewMigration("empty step", emptyMigration),
  133. // v45 -> v46
  134. NewMigration("remove index column from repo_unit table", removeIndexColumnFromRepoUnitTable),
  135. // v46 -> v47
  136. NewMigration("remove organization watch repositories", removeOrganizationWatchRepo),
  137. // v47 -> v48
  138. NewMigration("add deleted branches", addDeletedBranch),
  139. // v48 -> v49
  140. NewMigration("add repo indexer status", addRepoIndexerStatus),
  141. // v49 -> v50
  142. NewMigration("adds time tracking and stopwatches", addTimetracking),
  143. // v50 -> v51
  144. NewMigration("migrate protected branch struct", migrateProtectedBranchStruct),
  145. // v51 -> v52
  146. NewMigration("add default value to user prohibit_login", addDefaultValueToUserProhibitLogin),
  147. // v52 -> v53
  148. NewMigration("add lfs lock table", addLFSLock),
  149. // v53 -> v54
  150. NewMigration("add reactions", addReactions),
  151. // v54 -> v55
  152. NewMigration("add pull request options", addPullRequestOptions),
  153. // v55 -> v56
  154. NewMigration("add writable deploy keys", addModeToDeploKeys),
  155. // v56 -> v57
  156. NewMigration("remove is_owner, num_teams columns from org_user", removeIsOwnerColumnFromOrgUser),
  157. // v57 -> v58
  158. NewMigration("add closed_unix column for issues", addIssueClosedTime),
  159. // v58 -> v59
  160. NewMigration("add label descriptions", addLabelsDescriptions),
  161. // v59 -> v60
  162. NewMigration("add merge whitelist for protected branches", addProtectedBranchMergeWhitelist),
  163. // v60 -> v61
  164. NewMigration("add is_fsck_enabled column for repos", addFsckEnabledToRepo),
  165. // v61 -> v62
  166. NewMigration("add size column for attachments", addSizeToAttachment),
  167. // v62 -> v63
  168. NewMigration("add last used passcode column for TOTP", addLastUsedPasscodeTOTP),
  169. // v63 -> v64
  170. NewMigration("add language column for user setting", addLanguageSetting),
  171. // v64 -> v65
  172. NewMigration("add multiple assignees", addMultipleAssignees),
  173. // v65 -> v66
  174. NewMigration("add u2f", addU2FReg),
  175. // v66 -> v67
  176. NewMigration("add login source id column for public_key table", addLoginSourceIDToPublicKeyTable),
  177. // v67 -> v68
  178. NewMigration("remove stale watches", removeStaleWatches),
  179. // v68 -> V69
  180. NewMigration("Reformat and remove incorrect topics", reformatAndRemoveIncorrectTopics),
  181. // v69 -> v70
  182. NewMigration("move team units to team_unit table", moveTeamUnitsToTeamUnitTable),
  183. // v70 -> v71
  184. NewMigration("add issue_dependencies", addIssueDependencies),
  185. // v71 -> v72
  186. NewMigration("protect each scratch token", addScratchHash),
  187. // v72 -> v73
  188. NewMigration("add review", addReview),
  189. // v73 -> v74
  190. NewMigration("add must_change_password column for users table", addMustChangePassword),
  191. // v74 -> v75
  192. NewMigration("add approval whitelists to protected branches", addApprovalWhitelistsToProtectedBranches),
  193. // v75 -> v76
  194. NewMigration("clear nonused data which not deleted when user was deleted", clearNonusedData),
  195. // v76 -> v77
  196. NewMigration("add pull request rebase with merge commit", addPullRequestRebaseWithMerge),
  197. // v77 -> v78
  198. NewMigration("add theme to users", addUserDefaultTheme),
  199. // v78 -> v79
  200. NewMigration("rename repo is_bare to repo is_empty", renameRepoIsBareToIsEmpty),
  201. // v79 -> v80
  202. NewMigration("add can close issues via commit in any branch", addCanCloseIssuesViaCommitInAnyBranch),
  203. // v80 -> v81
  204. NewMigration("add is locked to issues", addIsLockedToIssues),
  205. // v81 -> v82
  206. NewMigration("update U2F counter type", changeU2FCounterType),
  207. // v82 -> v83
  208. NewMigration("hot fix for wrong release sha1 on release table", fixReleaseSha1OnReleaseTable),
  209. // v83 -> v84
  210. NewMigration("add uploader id for table attachment", addUploaderIDForAttachment),
  211. // v84 -> v85
  212. NewMigration("add table to store original imported gpg keys", addGPGKeyImport),
  213. // v85 -> v86
  214. NewMigration("hash application token", hashAppToken),
  215. // v86 -> v87
  216. NewMigration("add http method to webhook", addHTTPMethodToWebhook),
  217. // v87 -> v88
  218. NewMigration("add avatar field to repository", addAvatarFieldToRepository),
  219. // v88 -> v89
  220. NewMigration("add commit status context field to commit_status", addCommitStatusContext),
  221. }
  222. // Migrate database to current version
  223. func Migrate(x *xorm.Engine) error {
  224. if err := x.Sync(new(Version)); err != nil {
  225. return fmt.Errorf("sync: %v", err)
  226. }
  227. currentVersion := &Version{ID: 1}
  228. has, err := x.Get(currentVersion)
  229. if err != nil {
  230. return fmt.Errorf("get: %v", err)
  231. } else if !has {
  232. // If the version record does not exist we think
  233. // it is a fresh installation and we can skip all migrations.
  234. currentVersion.ID = 0
  235. currentVersion.Version = int64(minDBVersion + len(migrations))
  236. if _, err = x.InsertOne(currentVersion); err != nil {
  237. return fmt.Errorf("insert: %v", err)
  238. }
  239. }
  240. v := currentVersion.Version
  241. if minDBVersion > v {
  242. log.Fatal(`Gitea no longer supports auto-migration from your previously installed version.
  243. Please try to upgrade to a lower version (>= v0.6.0) first, then upgrade to current version.`)
  244. return nil
  245. }
  246. if int(v-minDBVersion) > len(migrations) {
  247. // User downgraded Gitea.
  248. currentVersion.Version = int64(len(migrations) + minDBVersion)
  249. _, err = x.ID(1).Update(currentVersion)
  250. return err
  251. }
  252. for i, m := range migrations[v-minDBVersion:] {
  253. log.Info("Migration[%d]: %s", v+int64(i), m.Description())
  254. if err = m.Migrate(x); err != nil {
  255. return fmt.Errorf("do migrate: %v", err)
  256. }
  257. currentVersion.Version = v + int64(i) + 1
  258. if _, err = x.ID(1).Update(currentVersion); err != nil {
  259. return err
  260. }
  261. }
  262. return nil
  263. }
  264. func dropTableColumns(sess *xorm.Session, tableName string, columnNames ...string) (err error) {
  265. if tableName == "" || len(columnNames) == 0 {
  266. return nil
  267. }
  268. // TODO: This will not work if there are foreign keys
  269. switch {
  270. case setting.UseSQLite3:
  271. // First drop the indexes on the columns
  272. res, errIndex := sess.Query(fmt.Sprintf("PRAGMA index_list(`%s`)", tableName))
  273. if errIndex != nil {
  274. return errIndex
  275. }
  276. for _, row := range res {
  277. indexName := row["name"]
  278. indexRes, err := sess.Query(fmt.Sprintf("PRAGMA index_info(`%s`)", indexName))
  279. if err != nil {
  280. return err
  281. }
  282. if len(indexRes) != 1 {
  283. continue
  284. }
  285. indexColumn := string(indexRes[0]["name"])
  286. for _, name := range columnNames {
  287. if name == indexColumn {
  288. _, err := sess.Exec(fmt.Sprintf("DROP INDEX `%s`", indexName))
  289. if err != nil {
  290. return err
  291. }
  292. }
  293. }
  294. }
  295. // Here we need to get the columns from the original table
  296. sql := fmt.Sprintf("SELECT sql FROM sqlite_master WHERE tbl_name='%s' and type='table'", tableName)
  297. res, err := sess.Query(sql)
  298. if err != nil {
  299. return err
  300. }
  301. tableSQL := string(res[0]["sql"])
  302. tableSQL = tableSQL[strings.Index(tableSQL, "("):]
  303. for _, name := range columnNames {
  304. tableSQL = regexp.MustCompile(regexp.QuoteMeta("`"+name+"`")+"[^`,)]*[,)]").ReplaceAllString(tableSQL, "")
  305. }
  306. columns := regexp.MustCompile("`([^`]*)`").FindAllString(tableSQL, -1)
  307. tableSQL = fmt.Sprintf("CREATE TABLE `new_%s_new` ", tableName) + tableSQL
  308. if _, err := sess.Exec(tableSQL); err != nil {
  309. return err
  310. }
  311. // Now restore the data
  312. columnsSeparated := strings.Join(columns, ",")
  313. insertSQL := fmt.Sprintf("INSERT INTO `new_%s_new` (%s) SELECT %s FROM %s", tableName, columnsSeparated, columnsSeparated, tableName)
  314. if _, err := sess.Exec(insertSQL); err != nil {
  315. return err
  316. }
  317. // Now drop the old table
  318. if _, err := sess.Exec(fmt.Sprintf("DROP TABLE `%s`", tableName)); err != nil {
  319. return err
  320. }
  321. // Rename the table
  322. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `new_%s_new` RENAME TO `%s`", tableName, tableName)); err != nil {
  323. return err
  324. }
  325. case setting.UsePostgreSQL:
  326. cols := ""
  327. for _, col := range columnNames {
  328. if cols != "" {
  329. cols += ", "
  330. }
  331. cols += "DROP COLUMN `" + col + "` CASCADE"
  332. }
  333. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  334. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  335. }
  336. case setting.UseMySQL, setting.UseTiDB:
  337. // Drop indexes on columns first
  338. sql := fmt.Sprintf("SHOW INDEX FROM %s WHERE column_name IN ('%s')", tableName, strings.Join(columnNames, "','"))
  339. res, err := sess.Query(sql)
  340. if err != nil {
  341. return err
  342. }
  343. for _, index := range res {
  344. indexName := index["column_name"]
  345. _, err := sess.Exec(fmt.Sprintf("DROP INDEX `%s` ON `%s`", indexName, tableName))
  346. if err != nil {
  347. return err
  348. }
  349. }
  350. // Now drop the columns
  351. cols := ""
  352. for _, col := range columnNames {
  353. if cols != "" {
  354. cols += ", "
  355. }
  356. cols += "DROP COLUMN `" + col + "`"
  357. }
  358. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  359. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  360. }
  361. case setting.UseMSSQL:
  362. cols := ""
  363. for _, col := range columnNames {
  364. if cols != "" {
  365. cols += ", "
  366. }
  367. cols += "`" + strings.ToLower(col) + "`"
  368. }
  369. sql := fmt.Sprintf("SELECT Name FROM SYS.DEFAULT_CONSTRAINTS WHERE PARENT_OBJECT_ID = OBJECT_ID('%[1]s') AND PARENT_COLUMN_ID IN (SELECT column_id FROM sys.columns WHERE lower(NAME) IN (%[2]s) AND object_id = OBJECT_ID('%[1]s'))",
  370. tableName, strings.Replace(cols, "`", "'", -1))
  371. constraints := make([]string, 0)
  372. if err := sess.SQL(sql).Find(&constraints); err != nil {
  373. sess.Rollback()
  374. return fmt.Errorf("Find constraints: %v", err)
  375. }
  376. for _, constraint := range constraints {
  377. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP CONSTRAINT `%s`", tableName, constraint)); err != nil {
  378. sess.Rollback()
  379. return fmt.Errorf("Drop table `%s` constraint `%s`: %v", tableName, constraint, err)
  380. }
  381. }
  382. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP COLUMN %s", tableName, cols)); err != nil {
  383. sess.Rollback()
  384. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  385. }
  386. return sess.Commit()
  387. default:
  388. log.Fatal("Unrecognized DB")
  389. }
  390. return nil
  391. }
  392. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  393. cfg, err := ini.Load(setting.CustomConf)
  394. if err != nil {
  395. return fmt.Errorf("load custom config: %v", err)
  396. }
  397. cfg.DeleteSection("i18n")
  398. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  399. return fmt.Errorf("save custom config: %v", err)
  400. }
  401. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  402. return nil
  403. }
  404. func trimCommitActionAppURLPrefix(x *xorm.Engine) error {
  405. type PushCommit struct {
  406. Sha1 string
  407. Message string
  408. AuthorEmail string
  409. AuthorName string
  410. }
  411. type PushCommits struct {
  412. Len int
  413. Commits []*PushCommit
  414. CompareURL string `json:"CompareUrl"`
  415. }
  416. type Action struct {
  417. ID int64 `xorm:"pk autoincr"`
  418. Content string `xorm:"TEXT"`
  419. }
  420. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  421. if err != nil {
  422. return fmt.Errorf("select commit actions: %v", err)
  423. }
  424. sess := x.NewSession()
  425. defer sess.Close()
  426. if err = sess.Begin(); err != nil {
  427. return err
  428. }
  429. var pushCommits *PushCommits
  430. for _, action := range results {
  431. actID := com.StrTo(string(action["id"])).MustInt64()
  432. if actID == 0 {
  433. continue
  434. }
  435. pushCommits = new(PushCommits)
  436. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  437. return fmt.Errorf("unmarshal action content[%d]: %v", actID, err)
  438. }
  439. infos := strings.Split(pushCommits.CompareURL, "/")
  440. if len(infos) <= 4 {
  441. continue
  442. }
  443. pushCommits.CompareURL = strings.Join(infos[len(infos)-4:], "/")
  444. p, err := json.Marshal(pushCommits)
  445. if err != nil {
  446. return fmt.Errorf("marshal action content[%d]: %v", actID, err)
  447. }
  448. if _, err = sess.ID(actID).Update(&Action{
  449. Content: string(p),
  450. }); err != nil {
  451. return fmt.Errorf("update action[%d]: %v", actID, err)
  452. }
  453. }
  454. return sess.Commit()
  455. }
  456. func issueToIssueLabel(x *xorm.Engine) error {
  457. type IssueLabel struct {
  458. ID int64 `xorm:"pk autoincr"`
  459. IssueID int64 `xorm:"UNIQUE(s)"`
  460. LabelID int64 `xorm:"UNIQUE(s)"`
  461. }
  462. issueLabels := make([]*IssueLabel, 0, 50)
  463. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  464. if err != nil {
  465. if strings.Contains(err.Error(), "no such column") ||
  466. strings.Contains(err.Error(), "Unknown column") {
  467. return nil
  468. }
  469. return fmt.Errorf("select issues: %v", err)
  470. }
  471. for _, issue := range results {
  472. issueID := com.StrTo(issue["id"]).MustInt64()
  473. // Just in case legacy code can have duplicated IDs for same label.
  474. mark := make(map[int64]bool)
  475. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  476. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  477. if labelID == 0 || mark[labelID] {
  478. continue
  479. }
  480. mark[labelID] = true
  481. issueLabels = append(issueLabels, &IssueLabel{
  482. IssueID: issueID,
  483. LabelID: labelID,
  484. })
  485. }
  486. }
  487. sess := x.NewSession()
  488. defer sess.Close()
  489. if err = sess.Begin(); err != nil {
  490. return err
  491. }
  492. if err = sess.Sync2(new(IssueLabel)); err != nil {
  493. return fmt.Errorf("Sync2: %v", err)
  494. } else if _, err = sess.Insert(issueLabels); err != nil {
  495. return fmt.Errorf("insert issue-labels: %v", err)
  496. }
  497. return sess.Commit()
  498. }
  499. func attachmentRefactor(x *xorm.Engine) error {
  500. type Attachment struct {
  501. ID int64 `xorm:"pk autoincr"`
  502. UUID string `xorm:"uuid INDEX"`
  503. // For rename purpose.
  504. Path string `xorm:"-"`
  505. NewPath string `xorm:"-"`
  506. }
  507. results, err := x.Query("SELECT * FROM `attachment`")
  508. if err != nil {
  509. return fmt.Errorf("select attachments: %v", err)
  510. }
  511. attachments := make([]*Attachment, 0, len(results))
  512. for _, attach := range results {
  513. if !com.IsExist(string(attach["path"])) {
  514. // If the attachment is already missing, there is no point to update it.
  515. continue
  516. }
  517. attachments = append(attachments, &Attachment{
  518. ID: com.StrTo(attach["id"]).MustInt64(),
  519. UUID: gouuid.NewV4().String(),
  520. Path: string(attach["path"]),
  521. })
  522. }
  523. sess := x.NewSession()
  524. defer sess.Close()
  525. if err = sess.Begin(); err != nil {
  526. return err
  527. }
  528. if err = sess.Sync2(new(Attachment)); err != nil {
  529. return fmt.Errorf("Sync2: %v", err)
  530. }
  531. // Note: Roll back for rename can be a dead loop,
  532. // so produces a backup file.
  533. var buf bytes.Buffer
  534. buf.WriteString("# old path -> new path\n")
  535. // Update database first because this is where error happens the most often.
  536. for _, attach := range attachments {
  537. if _, err = sess.ID(attach.ID).Update(attach); err != nil {
  538. return err
  539. }
  540. attach.NewPath = path.Join(setting.AttachmentPath, attach.UUID[0:1], attach.UUID[1:2], attach.UUID)
  541. buf.WriteString(attach.Path)
  542. buf.WriteString("\t")
  543. buf.WriteString(attach.NewPath)
  544. buf.WriteString("\n")
  545. }
  546. // Then rename attachments.
  547. isSucceed := true
  548. defer func() {
  549. if isSucceed {
  550. return
  551. }
  552. dumpPath := path.Join(setting.LogRootPath, "attachment_path.dump")
  553. ioutil.WriteFile(dumpPath, buf.Bytes(), 0666)
  554. log.Info("Failed to rename some attachments, old and new paths are saved into: %s", dumpPath)
  555. }()
  556. for _, attach := range attachments {
  557. if err = os.MkdirAll(path.Dir(attach.NewPath), os.ModePerm); err != nil {
  558. isSucceed = false
  559. return err
  560. }
  561. if err = os.Rename(attach.Path, attach.NewPath); err != nil {
  562. isSucceed = false
  563. return err
  564. }
  565. }
  566. return sess.Commit()
  567. }
  568. func renamePullRequestFields(x *xorm.Engine) (err error) {
  569. type PullRequest struct {
  570. ID int64 `xorm:"pk autoincr"`
  571. PullID int64 `xorm:"INDEX"`
  572. PullIndex int64
  573. HeadBarcnh string
  574. IssueID int64 `xorm:"INDEX"`
  575. Index int64
  576. HeadBranch string
  577. }
  578. if err = x.Sync(new(PullRequest)); err != nil {
  579. return fmt.Errorf("sync: %v", err)
  580. }
  581. results, err := x.Query("SELECT `id`,`pull_id`,`pull_index`,`head_barcnh` FROM `pull_request`")
  582. if err != nil {
  583. if strings.Contains(err.Error(), "no such column") {
  584. return nil
  585. }
  586. return fmt.Errorf("select pull requests: %v", err)
  587. }
  588. sess := x.NewSession()
  589. defer sess.Close()
  590. if err = sess.Begin(); err != nil {
  591. return err
  592. }
  593. var pull *PullRequest
  594. for _, pr := range results {
  595. pull = &PullRequest{
  596. ID: com.StrTo(pr["id"]).MustInt64(),
  597. IssueID: com.StrTo(pr["pull_id"]).MustInt64(),
  598. Index: com.StrTo(pr["pull_index"]).MustInt64(),
  599. HeadBranch: string(pr["head_barcnh"]),
  600. }
  601. if pull.Index == 0 {
  602. continue
  603. }
  604. if _, err = sess.ID(pull.ID).Update(pull); err != nil {
  605. return err
  606. }
  607. }
  608. return sess.Commit()
  609. }
  610. func cleanUpMigrateRepoInfo(x *xorm.Engine) (err error) {
  611. type (
  612. User struct {
  613. ID int64 `xorm:"pk autoincr"`
  614. LowerName string
  615. }
  616. Repository struct {
  617. ID int64 `xorm:"pk autoincr"`
  618. OwnerID int64
  619. LowerName string
  620. }
  621. )
  622. repos := make([]*Repository, 0, 25)
  623. if err = x.Where("is_mirror=?", false).Find(&repos); err != nil {
  624. return fmt.Errorf("select all non-mirror repositories: %v", err)
  625. }
  626. var user *User
  627. for _, repo := range repos {
  628. user = &User{ID: repo.OwnerID}
  629. has, err := x.Get(user)
  630. if err != nil {
  631. return fmt.Errorf("get owner of repository[%d - %d]: %v", repo.ID, repo.OwnerID, err)
  632. } else if !has {
  633. continue
  634. }
  635. configPath := filepath.Join(setting.RepoRootPath, user.LowerName, repo.LowerName+".git/config")
  636. // In case repository file is somehow missing.
  637. if !com.IsFile(configPath) {
  638. continue
  639. }
  640. cfg, err := ini.Load(configPath)
  641. if err != nil {
  642. return fmt.Errorf("open config file: %v", err)
  643. }
  644. cfg.DeleteSection("remote \"origin\"")
  645. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  646. return fmt.Errorf("save config file: %v", err)
  647. }
  648. }
  649. return nil
  650. }
  651. func generateOrgRandsAndSalt(x *xorm.Engine) (err error) {
  652. type User struct {
  653. ID int64 `xorm:"pk autoincr"`
  654. Rands string `xorm:"VARCHAR(10)"`
  655. Salt string `xorm:"VARCHAR(10)"`
  656. }
  657. orgs := make([]*User, 0, 10)
  658. if err = x.Where("type=1").And("rands=''").Find(&orgs); err != nil {
  659. return fmt.Errorf("select all organizations: %v", err)
  660. }
  661. sess := x.NewSession()
  662. defer sess.Close()
  663. if err = sess.Begin(); err != nil {
  664. return err
  665. }
  666. for _, org := range orgs {
  667. if org.Rands, err = generate.GetRandomString(10); err != nil {
  668. return err
  669. }
  670. if org.Salt, err = generate.GetRandomString(10); err != nil {
  671. return err
  672. }
  673. if _, err = sess.ID(org.ID).Update(org); err != nil {
  674. return err
  675. }
  676. }
  677. return sess.Commit()
  678. }
  679. // TAction defines the struct for migrating table action
  680. type TAction struct {
  681. ID int64 `xorm:"pk autoincr"`
  682. CreatedUnix int64
  683. }
  684. // TableName will be invoked by XORM to customrize the table name
  685. func (t *TAction) TableName() string { return "action" }
  686. // TNotice defines the struct for migrating table notice
  687. type TNotice struct {
  688. ID int64 `xorm:"pk autoincr"`
  689. CreatedUnix int64
  690. }
  691. // TableName will be invoked by XORM to customrize the table name
  692. func (t *TNotice) TableName() string { return "notice" }
  693. // TComment defines the struct for migrating table comment
  694. type TComment struct {
  695. ID int64 `xorm:"pk autoincr"`
  696. CreatedUnix int64
  697. }
  698. // TableName will be invoked by XORM to customrize the table name
  699. func (t *TComment) TableName() string { return "comment" }
  700. // TIssue defines the struct for migrating table issue
  701. type TIssue struct {
  702. ID int64 `xorm:"pk autoincr"`
  703. DeadlineUnix int64
  704. CreatedUnix int64
  705. UpdatedUnix int64
  706. }
  707. // TableName will be invoked by XORM to customrize the table name
  708. func (t *TIssue) TableName() string { return "issue" }
  709. // TMilestone defines the struct for migrating table milestone
  710. type TMilestone struct {
  711. ID int64 `xorm:"pk autoincr"`
  712. DeadlineUnix int64
  713. ClosedDateUnix int64
  714. }
  715. // TableName will be invoked by XORM to customrize the table name
  716. func (t *TMilestone) TableName() string { return "milestone" }
  717. // TAttachment defines the struct for migrating table attachment
  718. type TAttachment struct {
  719. ID int64 `xorm:"pk autoincr"`
  720. CreatedUnix int64
  721. }
  722. // TableName will be invoked by XORM to customrize the table name
  723. func (t *TAttachment) TableName() string { return "attachment" }
  724. // TLoginSource defines the struct for migrating table login_source
  725. type TLoginSource struct {
  726. ID int64 `xorm:"pk autoincr"`
  727. CreatedUnix int64
  728. UpdatedUnix int64
  729. }
  730. // TableName will be invoked by XORM to customrize the table name
  731. func (t *TLoginSource) TableName() string { return "login_source" }
  732. // TPull defines the struct for migrating table pull_request
  733. type TPull struct {
  734. ID int64 `xorm:"pk autoincr"`
  735. MergedUnix int64
  736. }
  737. // TableName will be invoked by XORM to customrize the table name
  738. func (t *TPull) TableName() string { return "pull_request" }
  739. // TRelease defines the struct for migrating table release
  740. type TRelease struct {
  741. ID int64 `xorm:"pk autoincr"`
  742. CreatedUnix int64
  743. }
  744. // TableName will be invoked by XORM to customrize the table name
  745. func (t *TRelease) TableName() string { return "release" }
  746. // TRepo defines the struct for migrating table repository
  747. type TRepo struct {
  748. ID int64 `xorm:"pk autoincr"`
  749. CreatedUnix int64
  750. UpdatedUnix int64
  751. }
  752. // TableName will be invoked by XORM to customrize the table name
  753. func (t *TRepo) TableName() string { return "repository" }
  754. // TMirror defines the struct for migrating table mirror
  755. type TMirror struct {
  756. ID int64 `xorm:"pk autoincr"`
  757. UpdatedUnix int64
  758. NextUpdateUnix int64
  759. }
  760. // TableName will be invoked by XORM to customrize the table name
  761. func (t *TMirror) TableName() string { return "mirror" }
  762. // TPublicKey defines the struct for migrating table public_key
  763. type TPublicKey struct {
  764. ID int64 `xorm:"pk autoincr"`
  765. CreatedUnix int64
  766. UpdatedUnix int64
  767. }
  768. // TableName will be invoked by XORM to customrize the table name
  769. func (t *TPublicKey) TableName() string { return "public_key" }
  770. // TDeployKey defines the struct for migrating table deploy_key
  771. type TDeployKey struct {
  772. ID int64 `xorm:"pk autoincr"`
  773. CreatedUnix int64
  774. UpdatedUnix int64
  775. }
  776. // TableName will be invoked by XORM to customrize the table name
  777. func (t *TDeployKey) TableName() string { return "deploy_key" }
  778. // TAccessToken defines the struct for migrating table access_token
  779. type TAccessToken struct {
  780. ID int64 `xorm:"pk autoincr"`
  781. CreatedUnix int64
  782. UpdatedUnix int64
  783. }
  784. // TableName will be invoked by XORM to customrize the table name
  785. func (t *TAccessToken) TableName() string { return "access_token" }
  786. // TUser defines the struct for migrating table user
  787. type TUser struct {
  788. ID int64 `xorm:"pk autoincr"`
  789. CreatedUnix int64
  790. UpdatedUnix int64
  791. }
  792. // TableName will be invoked by XORM to customrize the table name
  793. func (t *TUser) TableName() string { return "user" }
  794. // TWebhook defines the struct for migrating table webhook
  795. type TWebhook struct {
  796. ID int64 `xorm:"pk autoincr"`
  797. CreatedUnix int64
  798. UpdatedUnix int64
  799. }
  800. // TableName will be invoked by XORM to customrize the table name
  801. func (t *TWebhook) TableName() string { return "webhook" }
  802. func convertDateToUnix(x *xorm.Engine) (err error) {
  803. log.Info("This migration could take up to minutes, please be patient.")
  804. type Bean struct {
  805. ID int64 `xorm:"pk autoincr"`
  806. Created time.Time
  807. Updated time.Time
  808. Merged time.Time
  809. Deadline time.Time
  810. ClosedDate time.Time
  811. NextUpdate time.Time
  812. }
  813. var tables = []struct {
  814. name string
  815. cols []string
  816. bean interface{}
  817. }{
  818. {"action", []string{"created"}, new(TAction)},
  819. {"notice", []string{"created"}, new(TNotice)},
  820. {"comment", []string{"created"}, new(TComment)},
  821. {"issue", []string{"deadline", "created", "updated"}, new(TIssue)},
  822. {"milestone", []string{"deadline", "closed_date"}, new(TMilestone)},
  823. {"attachment", []string{"created"}, new(TAttachment)},
  824. {"login_source", []string{"created", "updated"}, new(TLoginSource)},
  825. {"pull_request", []string{"merged"}, new(TPull)},
  826. {"release", []string{"created"}, new(TRelease)},
  827. {"repository", []string{"created", "updated"}, new(TRepo)},
  828. {"mirror", []string{"updated", "next_update"}, new(TMirror)},
  829. {"public_key", []string{"created", "updated"}, new(TPublicKey)},
  830. {"deploy_key", []string{"created", "updated"}, new(TDeployKey)},
  831. {"access_token", []string{"created", "updated"}, new(TAccessToken)},
  832. {"user", []string{"created", "updated"}, new(TUser)},
  833. {"webhook", []string{"created", "updated"}, new(TWebhook)},
  834. }
  835. for _, table := range tables {
  836. log.Info("Converting table: %s", table.name)
  837. if err = x.Sync2(table.bean); err != nil {
  838. return fmt.Errorf("Sync [table: %s]: %v", table.name, err)
  839. }
  840. offset := 0
  841. for {
  842. beans := make([]*Bean, 0, 100)
  843. if err = x.Table(table.name).Asc("id").Limit(100, offset).Find(&beans); err != nil {
  844. return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
  845. }
  846. log.Trace("Table [%s]: offset: %d, beans: %d", table.name, offset, len(beans))
  847. if len(beans) == 0 {
  848. break
  849. }
  850. offset += 100
  851. baseSQL := "UPDATE `" + table.name + "` SET "
  852. for _, bean := range beans {
  853. valSQLs := make([]string, 0, len(table.cols))
  854. for _, col := range table.cols {
  855. fieldSQL := ""
  856. fieldSQL += col + "_unix = "
  857. switch col {
  858. case "deadline":
  859. if bean.Deadline.IsZero() {
  860. continue
  861. }
  862. fieldSQL += com.ToStr(bean.Deadline.Unix())
  863. case "created":
  864. fieldSQL += com.ToStr(bean.Created.Unix())
  865. case "updated":
  866. fieldSQL += com.ToStr(bean.Updated.Unix())
  867. case "closed_date":
  868. fieldSQL += com.ToStr(bean.ClosedDate.Unix())
  869. case "merged":
  870. fieldSQL += com.ToStr(bean.Merged.Unix())
  871. case "next_update":
  872. fieldSQL += com.ToStr(bean.NextUpdate.Unix())
  873. }
  874. valSQLs = append(valSQLs, fieldSQL)
  875. }
  876. if len(valSQLs) == 0 {
  877. continue
  878. }
  879. if _, err = x.Exec(baseSQL + strings.Join(valSQLs, ",") + " WHERE id = " + com.ToStr(bean.ID)); err != nil {
  880. return fmt.Errorf("update bean [table: %s, id: %d]: %v", table.name, bean.ID, err)
  881. }
  882. }
  883. }
  884. }
  885. return nil
  886. }