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.

migrations.go 28 kB

10 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)
8 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>
8 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>
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>
7 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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. "strings"
  15. "time"
  16. "github.com/Unknwon/com"
  17. "github.com/go-xorm/xorm"
  18. gouuid "github.com/satori/go.uuid"
  19. ini "gopkg.in/ini.v1"
  20. "code.gitea.io/gitea/modules/generate"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/setting"
  23. )
  24. const minDBVersion = 4
  25. // Migration describes on migration from lower version to high version
  26. type Migration interface {
  27. Description() string
  28. Migrate(*xorm.Engine) error
  29. }
  30. type migration struct {
  31. description string
  32. migrate func(*xorm.Engine) error
  33. }
  34. // NewMigration creates a new migration
  35. func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
  36. return &migration{desc, fn}
  37. }
  38. // Description returns the migration's description
  39. func (m *migration) Description() string {
  40. return m.description
  41. }
  42. // Migrate executes the migration
  43. func (m *migration) Migrate(x *xorm.Engine) error {
  44. return m.migrate(x)
  45. }
  46. // Version describes the version table. Should have only one row with id==1
  47. type Version struct {
  48. ID int64 `xorm:"pk autoincr"`
  49. Version int64
  50. }
  51. func emptyMigration(x *xorm.Engine) error {
  52. return nil
  53. }
  54. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  55. // If you want to "retire" a migration, remove it from the top of the list and
  56. // update minDBVersion accordingly
  57. var migrations = []Migration{
  58. // v0 -> v4: before 0.6.0 -> 0.7.33
  59. NewMigration("fix locale file load panic", fixLocaleFileLoadPanic), // V4 -> V5:v0.6.0
  60. NewMigration("trim action compare URL prefix", trimCommitActionAppURLPrefix), // V5 -> V6:v0.6.3
  61. NewMigration("generate issue-label from issue", issueToIssueLabel), // V6 -> V7:v0.6.4
  62. NewMigration("refactor attachment table", attachmentRefactor), // V7 -> V8:v0.6.4
  63. NewMigration("rename pull request fields", renamePullRequestFields), // V8 -> V9:v0.6.16
  64. NewMigration("clean up migrate repo info", cleanUpMigrateRepoInfo), // V9 -> V10:v0.6.20
  65. NewMigration("generate rands and salt for organizations", generateOrgRandsAndSalt), // V10 -> V11:v0.8.5
  66. NewMigration("convert date to unix timestamp", convertDateToUnix), // V11 -> V12:v0.9.2
  67. NewMigration("convert LDAP UseSSL option to SecurityProtocol", ldapUseSSLToSecurityProtocol), // V12 -> V13:v0.9.37
  68. // v13 -> v14:v0.9.87
  69. NewMigration("set comment updated with created", setCommentUpdatedWithCreated),
  70. // v14 -> v15
  71. NewMigration("create user column diff view style", createUserColumnDiffViewStyle),
  72. // v15 -> v16
  73. NewMigration("create user column allow create organization", createAllowCreateOrganizationColumn),
  74. // V16 -> v17
  75. NewMigration("create repo unit table and add units for all repos", addUnitsToTables),
  76. // v17 -> v18
  77. NewMigration("set protect branches updated with created", setProtectedBranchUpdatedWithCreated),
  78. // v18 -> v19
  79. NewMigration("add external login user", addExternalLoginUser),
  80. // v19 -> v20
  81. NewMigration("generate and migrate Git hooks", generateAndMigrateGitHooks),
  82. // v20 -> v21
  83. NewMigration("use new avatar path name for security reason", useNewNameAvatars),
  84. // v21 -> v22
  85. NewMigration("rewrite authorized_keys file via new format", useNewPublickeyFormat),
  86. // v22 -> v23
  87. NewMigration("generate and migrate wiki Git hooks", generateAndMigrateWikiGitHooks),
  88. // v23 -> v24
  89. NewMigration("add user openid table", addUserOpenID),
  90. // v24 -> v25
  91. NewMigration("change the key_id and primary_key_id type", changeGPGKeysColumns),
  92. // v25 -> v26
  93. NewMigration("add show field in user openid table", addUserOpenIDShow),
  94. // v26 -> v27
  95. NewMigration("generate and migrate repo and wiki Git hooks", generateAndMigrateGitHookChains),
  96. // v27 -> v28
  97. NewMigration("change mirror interval from hours to time.Duration", convertIntervalToDuration),
  98. // v28 -> v29
  99. NewMigration("add field for repo size", addRepoSize),
  100. // v29 -> v30
  101. NewMigration("add commit status table", addCommitStatus),
  102. // v30 -> 31
  103. NewMigration("add primary key to external login user", addExternalLoginUserPK),
  104. // v31 -> 32
  105. NewMigration("add field for login source synchronization", addLoginSourceSyncEnabledColumn),
  106. // v32 -> v33
  107. NewMigration("add units for team", addUnitsToRepoTeam),
  108. // v33 -> v34
  109. NewMigration("remove columns from action", removeActionColumns),
  110. // v34 -> v35
  111. NewMigration("give all units to owner teams", giveAllUnitsToOwnerTeams),
  112. // v35 -> v36
  113. NewMigration("adds comment to an action", addCommentIDToAction),
  114. // v36 -> v37
  115. NewMigration("regenerate git hooks", regenerateGitHooks36),
  116. // v37 -> v38
  117. NewMigration("unescape user full names", unescapeUserFullNames),
  118. // v38 -> v39
  119. NewMigration("remove commits and settings unit types", removeCommitsUnitType),
  120. // v39 -> v40
  121. NewMigration("add tags to releases and sync existing repositories", releaseAddColumnIsTagAndSyncTags),
  122. // v40 -> v41
  123. NewMigration("fix protected branch can push value to false", fixProtectedBranchCanPushValue),
  124. // v41 -> v42
  125. NewMigration("remove duplicate unit types", removeDuplicateUnitTypes),
  126. // v42 -> v43
  127. NewMigration("empty step", emptyMigration),
  128. // v43 -> v44
  129. NewMigration("empty step", emptyMigration),
  130. // v44 -> v45
  131. NewMigration("empty step", emptyMigration),
  132. // v45 -> v46
  133. NewMigration("remove index column from repo_unit table", removeIndexColumnFromRepoUnitTable),
  134. // v46 -> v47
  135. NewMigration("remove organization watch repositories", removeOrganizationWatchRepo),
  136. // v47 -> v48
  137. NewMigration("add deleted branches", addDeletedBranch),
  138. // v48 -> v49
  139. NewMigration("add repo indexer status", addRepoIndexerStatus),
  140. // v49 -> v50
  141. NewMigration("adds time tracking and stopwatches", addTimetracking),
  142. // v50 -> v51
  143. NewMigration("migrate protected branch struct", migrateProtectedBranchStruct),
  144. // v51 -> v52
  145. NewMigration("add default value to user prohibit_login", addDefaultValueToUserProhibitLogin),
  146. // v52 -> v53
  147. NewMigration("add lfs lock table", addLFSLock),
  148. // v53 -> v54
  149. NewMigration("add reactions", addReactions),
  150. // v54 -> v55
  151. NewMigration("add pull request options", addPullRequestOptions),
  152. // v55 -> v56
  153. NewMigration("add writable deploy keys", addModeToDeploKeys),
  154. // v56 -> v57
  155. NewMigration("remove is_owner, num_teams columns from org_user", removeIsOwnerColumnFromOrgUser),
  156. // v57 -> v58
  157. NewMigration("add closed_unix column for issues", addIssueClosedTime),
  158. // v58 -> v59
  159. NewMigration("add label descriptions", addLabelsDescriptions),
  160. // v59 -> v60
  161. NewMigration("add merge whitelist for protected branches", addProtectedBranchMergeWhitelist),
  162. // v60 -> v61
  163. NewMigration("add is_fsck_enabled column for repos", addFsckEnabledToRepo),
  164. // v61 -> v62
  165. NewMigration("add size column for attachments", addSizeToAttachment),
  166. // v62 -> v63
  167. NewMigration("add last used passcode column for TOTP", addLastUsedPasscodeTOTP),
  168. // v63 -> v64
  169. NewMigration("add language column for user setting", addLanguageSetting),
  170. // v64 -> v65
  171. NewMigration("add multiple assignees", addMultipleAssignees),
  172. // v65 -> v66
  173. NewMigration("add u2f", addU2FReg),
  174. // v66 -> v67
  175. NewMigration("add login source id column for public_key table", addLoginSourceIDToPublicKeyTable),
  176. // v67 -> v68
  177. NewMigration("remove stale watches", removeStaleWatches),
  178. // v68 -> V69
  179. NewMigration("Reformat and remove incorrect topics", reformatAndRemoveIncorrectTopics),
  180. // v69 -> v70
  181. NewMigration("move team units to team_unit table", moveTeamUnitsToTeamUnitTable),
  182. // v70 -> v71
  183. NewMigration("add issue_dependencies", addIssueDependencies),
  184. // v71 -> v72
  185. NewMigration("protect each scratch token", addScratchHash),
  186. // v72 -> v73
  187. NewMigration("add review", addReview),
  188. // v73 -> v74
  189. NewMigration("add must_change_password column for users table", addMustChangePassword),
  190. // v74 -> v75
  191. NewMigration("add approval whitelists to protected branches", addApprovalWhitelistsToProtectedBranches),
  192. // v75 -> v76
  193. NewMigration("clear nonused data which not deleted when user was deleted", clearNonusedData),
  194. // v76 -> v77
  195. NewMigration("add pull request rebase with merge commit", addPullRequestRebaseWithMerge),
  196. // v77 -> v78
  197. NewMigration("add theme to users", addUserDefaultTheme),
  198. // v78 -> v79
  199. NewMigration("rename repo is_bare to repo is_empty", renameRepoIsBareToIsEmpty),
  200. // v79 -> v80
  201. NewMigration("add can close issues via commit in any branch", addCanCloseIssuesViaCommitInAnyBranch),
  202. // v80 -> v81
  203. NewMigration("add is locked to issues", addIsLockedToIssues),
  204. // v81 -> v82
  205. NewMigration("update U2F counter type", changeU2FCounterType),
  206. // v82 -> v83
  207. NewMigration("hot fix for wrong release sha1 on release table", fixReleaseSha1OnReleaseTable),
  208. // v83 -> v84
  209. NewMigration("add uploader id for table attachment", addUploaderIDForAttachment),
  210. // v84 -> v85
  211. NewMigration("add table to store original imported gpg keys", addGPGKeyImport),
  212. }
  213. // Migrate database to current version
  214. func Migrate(x *xorm.Engine) error {
  215. if err := x.Sync(new(Version)); err != nil {
  216. return fmt.Errorf("sync: %v", err)
  217. }
  218. currentVersion := &Version{ID: 1}
  219. has, err := x.Get(currentVersion)
  220. if err != nil {
  221. return fmt.Errorf("get: %v", err)
  222. } else if !has {
  223. // If the version record does not exist we think
  224. // it is a fresh installation and we can skip all migrations.
  225. currentVersion.ID = 0
  226. currentVersion.Version = int64(minDBVersion + len(migrations))
  227. if _, err = x.InsertOne(currentVersion); err != nil {
  228. return fmt.Errorf("insert: %v", err)
  229. }
  230. }
  231. v := currentVersion.Version
  232. if minDBVersion > v {
  233. log.Fatal(`Gitea no longer supports auto-migration from your previously installed version.
  234. Please try to upgrade to a lower version (>= v0.6.0) first, then upgrade to current version.`)
  235. return nil
  236. }
  237. if int(v-minDBVersion) > len(migrations) {
  238. // User downgraded Gitea.
  239. currentVersion.Version = int64(len(migrations) + minDBVersion)
  240. _, err = x.ID(1).Update(currentVersion)
  241. return err
  242. }
  243. for i, m := range migrations[v-minDBVersion:] {
  244. log.Info("Migration: %s", m.Description())
  245. if err = m.Migrate(x); err != nil {
  246. return fmt.Errorf("do migrate: %v", err)
  247. }
  248. currentVersion.Version = v + int64(i) + 1
  249. if _, err = x.ID(1).Update(currentVersion); err != nil {
  250. return err
  251. }
  252. }
  253. return nil
  254. }
  255. func dropTableColumns(sess *xorm.Session, tableName string, columnNames ...string) (err error) {
  256. if tableName == "" || len(columnNames) == 0 {
  257. return nil
  258. }
  259. switch {
  260. case setting.UseSQLite3:
  261. log.Warn("Unable to drop columns in SQLite")
  262. case setting.UseMySQL, setting.UseTiDB, setting.UsePostgreSQL:
  263. cols := ""
  264. for _, col := range columnNames {
  265. if cols != "" {
  266. cols += ", "
  267. }
  268. cols += "DROP COLUMN `" + col + "`"
  269. }
  270. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  271. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  272. }
  273. case setting.UseMSSQL:
  274. cols := ""
  275. for _, col := range columnNames {
  276. if cols != "" {
  277. cols += ", "
  278. }
  279. cols += "`" + strings.ToLower(col) + "`"
  280. }
  281. 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'))",
  282. tableName, strings.Replace(cols, "`", "'", -1))
  283. constraints := make([]string, 0)
  284. if err := sess.SQL(sql).Find(&constraints); err != nil {
  285. sess.Rollback()
  286. return fmt.Errorf("Find constraints: %v", err)
  287. }
  288. for _, constraint := range constraints {
  289. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP CONSTRAINT `%s`", tableName, constraint)); err != nil {
  290. sess.Rollback()
  291. return fmt.Errorf("Drop table `%s` constraint `%s`: %v", tableName, constraint, err)
  292. }
  293. }
  294. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP COLUMN %s", tableName, cols)); err != nil {
  295. sess.Rollback()
  296. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  297. }
  298. return sess.Commit()
  299. default:
  300. log.Fatal("Unrecognized DB")
  301. }
  302. return nil
  303. }
  304. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  305. cfg, err := ini.Load(setting.CustomConf)
  306. if err != nil {
  307. return fmt.Errorf("load custom config: %v", err)
  308. }
  309. cfg.DeleteSection("i18n")
  310. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  311. return fmt.Errorf("save custom config: %v", err)
  312. }
  313. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  314. return nil
  315. }
  316. func trimCommitActionAppURLPrefix(x *xorm.Engine) error {
  317. type PushCommit struct {
  318. Sha1 string
  319. Message string
  320. AuthorEmail string
  321. AuthorName string
  322. }
  323. type PushCommits struct {
  324. Len int
  325. Commits []*PushCommit
  326. CompareURL string `json:"CompareUrl"`
  327. }
  328. type Action struct {
  329. ID int64 `xorm:"pk autoincr"`
  330. Content string `xorm:"TEXT"`
  331. }
  332. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  333. if err != nil {
  334. return fmt.Errorf("select commit actions: %v", err)
  335. }
  336. sess := x.NewSession()
  337. defer sess.Close()
  338. if err = sess.Begin(); err != nil {
  339. return err
  340. }
  341. var pushCommits *PushCommits
  342. for _, action := range results {
  343. actID := com.StrTo(string(action["id"])).MustInt64()
  344. if actID == 0 {
  345. continue
  346. }
  347. pushCommits = new(PushCommits)
  348. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  349. return fmt.Errorf("unmarshal action content[%d]: %v", actID, err)
  350. }
  351. infos := strings.Split(pushCommits.CompareURL, "/")
  352. if len(infos) <= 4 {
  353. continue
  354. }
  355. pushCommits.CompareURL = strings.Join(infos[len(infos)-4:], "/")
  356. p, err := json.Marshal(pushCommits)
  357. if err != nil {
  358. return fmt.Errorf("marshal action content[%d]: %v", actID, err)
  359. }
  360. if _, err = sess.Id(actID).Update(&Action{
  361. Content: string(p),
  362. }); err != nil {
  363. return fmt.Errorf("update action[%d]: %v", actID, err)
  364. }
  365. }
  366. return sess.Commit()
  367. }
  368. func issueToIssueLabel(x *xorm.Engine) error {
  369. type IssueLabel struct {
  370. ID int64 `xorm:"pk autoincr"`
  371. IssueID int64 `xorm:"UNIQUE(s)"`
  372. LabelID int64 `xorm:"UNIQUE(s)"`
  373. }
  374. issueLabels := make([]*IssueLabel, 0, 50)
  375. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  376. if err != nil {
  377. if strings.Contains(err.Error(), "no such column") ||
  378. strings.Contains(err.Error(), "Unknown column") {
  379. return nil
  380. }
  381. return fmt.Errorf("select issues: %v", err)
  382. }
  383. for _, issue := range results {
  384. issueID := com.StrTo(issue["id"]).MustInt64()
  385. // Just in case legacy code can have duplicated IDs for same label.
  386. mark := make(map[int64]bool)
  387. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  388. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  389. if labelID == 0 || mark[labelID] {
  390. continue
  391. }
  392. mark[labelID] = true
  393. issueLabels = append(issueLabels, &IssueLabel{
  394. IssueID: issueID,
  395. LabelID: labelID,
  396. })
  397. }
  398. }
  399. sess := x.NewSession()
  400. defer sess.Close()
  401. if err = sess.Begin(); err != nil {
  402. return err
  403. }
  404. if err = sess.Sync2(new(IssueLabel)); err != nil {
  405. return fmt.Errorf("Sync2: %v", err)
  406. } else if _, err = sess.Insert(issueLabels); err != nil {
  407. return fmt.Errorf("insert issue-labels: %v", err)
  408. }
  409. return sess.Commit()
  410. }
  411. func attachmentRefactor(x *xorm.Engine) error {
  412. type Attachment struct {
  413. ID int64 `xorm:"pk autoincr"`
  414. UUID string `xorm:"uuid INDEX"`
  415. // For rename purpose.
  416. Path string `xorm:"-"`
  417. NewPath string `xorm:"-"`
  418. }
  419. results, err := x.Query("SELECT * FROM `attachment`")
  420. if err != nil {
  421. return fmt.Errorf("select attachments: %v", err)
  422. }
  423. attachments := make([]*Attachment, 0, len(results))
  424. for _, attach := range results {
  425. if !com.IsExist(string(attach["path"])) {
  426. // If the attachment is already missing, there is no point to update it.
  427. continue
  428. }
  429. attachments = append(attachments, &Attachment{
  430. ID: com.StrTo(attach["id"]).MustInt64(),
  431. UUID: gouuid.NewV4().String(),
  432. Path: string(attach["path"]),
  433. })
  434. }
  435. sess := x.NewSession()
  436. defer sess.Close()
  437. if err = sess.Begin(); err != nil {
  438. return err
  439. }
  440. if err = sess.Sync2(new(Attachment)); err != nil {
  441. return fmt.Errorf("Sync2: %v", err)
  442. }
  443. // Note: Roll back for rename can be a dead loop,
  444. // so produces a backup file.
  445. var buf bytes.Buffer
  446. buf.WriteString("# old path -> new path\n")
  447. // Update database first because this is where error happens the most often.
  448. for _, attach := range attachments {
  449. if _, err = sess.Id(attach.ID).Update(attach); err != nil {
  450. return err
  451. }
  452. attach.NewPath = path.Join(setting.AttachmentPath, attach.UUID[0:1], attach.UUID[1:2], attach.UUID)
  453. buf.WriteString(attach.Path)
  454. buf.WriteString("\t")
  455. buf.WriteString(attach.NewPath)
  456. buf.WriteString("\n")
  457. }
  458. // Then rename attachments.
  459. isSucceed := true
  460. defer func() {
  461. if isSucceed {
  462. return
  463. }
  464. dumpPath := path.Join(setting.LogRootPath, "attachment_path.dump")
  465. ioutil.WriteFile(dumpPath, buf.Bytes(), 0666)
  466. log.Info("Failed to rename some attachments, old and new paths are saved into: %s", dumpPath)
  467. }()
  468. for _, attach := range attachments {
  469. if err = os.MkdirAll(path.Dir(attach.NewPath), os.ModePerm); err != nil {
  470. isSucceed = false
  471. return err
  472. }
  473. if err = os.Rename(attach.Path, attach.NewPath); err != nil {
  474. isSucceed = false
  475. return err
  476. }
  477. }
  478. return sess.Commit()
  479. }
  480. func renamePullRequestFields(x *xorm.Engine) (err error) {
  481. type PullRequest struct {
  482. ID int64 `xorm:"pk autoincr"`
  483. PullID int64 `xorm:"INDEX"`
  484. PullIndex int64
  485. HeadBarcnh string
  486. IssueID int64 `xorm:"INDEX"`
  487. Index int64
  488. HeadBranch string
  489. }
  490. if err = x.Sync(new(PullRequest)); err != nil {
  491. return fmt.Errorf("sync: %v", err)
  492. }
  493. results, err := x.Query("SELECT `id`,`pull_id`,`pull_index`,`head_barcnh` FROM `pull_request`")
  494. if err != nil {
  495. if strings.Contains(err.Error(), "no such column") {
  496. return nil
  497. }
  498. return fmt.Errorf("select pull requests: %v", err)
  499. }
  500. sess := x.NewSession()
  501. defer sess.Close()
  502. if err = sess.Begin(); err != nil {
  503. return err
  504. }
  505. var pull *PullRequest
  506. for _, pr := range results {
  507. pull = &PullRequest{
  508. ID: com.StrTo(pr["id"]).MustInt64(),
  509. IssueID: com.StrTo(pr["pull_id"]).MustInt64(),
  510. Index: com.StrTo(pr["pull_index"]).MustInt64(),
  511. HeadBranch: string(pr["head_barcnh"]),
  512. }
  513. if pull.Index == 0 {
  514. continue
  515. }
  516. if _, err = sess.Id(pull.ID).Update(pull); err != nil {
  517. return err
  518. }
  519. }
  520. return sess.Commit()
  521. }
  522. func cleanUpMigrateRepoInfo(x *xorm.Engine) (err error) {
  523. type (
  524. User struct {
  525. ID int64 `xorm:"pk autoincr"`
  526. LowerName string
  527. }
  528. Repository struct {
  529. ID int64 `xorm:"pk autoincr"`
  530. OwnerID int64
  531. LowerName string
  532. }
  533. )
  534. repos := make([]*Repository, 0, 25)
  535. if err = x.Where("is_mirror=?", false).Find(&repos); err != nil {
  536. return fmt.Errorf("select all non-mirror repositories: %v", err)
  537. }
  538. var user *User
  539. for _, repo := range repos {
  540. user = &User{ID: repo.OwnerID}
  541. has, err := x.Get(user)
  542. if err != nil {
  543. return fmt.Errorf("get owner of repository[%d - %d]: %v", repo.ID, repo.OwnerID, err)
  544. } else if !has {
  545. continue
  546. }
  547. configPath := filepath.Join(setting.RepoRootPath, user.LowerName, repo.LowerName+".git/config")
  548. // In case repository file is somehow missing.
  549. if !com.IsFile(configPath) {
  550. continue
  551. }
  552. cfg, err := ini.Load(configPath)
  553. if err != nil {
  554. return fmt.Errorf("open config file: %v", err)
  555. }
  556. cfg.DeleteSection("remote \"origin\"")
  557. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  558. return fmt.Errorf("save config file: %v", err)
  559. }
  560. }
  561. return nil
  562. }
  563. func generateOrgRandsAndSalt(x *xorm.Engine) (err error) {
  564. type User struct {
  565. ID int64 `xorm:"pk autoincr"`
  566. Rands string `xorm:"VARCHAR(10)"`
  567. Salt string `xorm:"VARCHAR(10)"`
  568. }
  569. orgs := make([]*User, 0, 10)
  570. if err = x.Where("type=1").And("rands=''").Find(&orgs); err != nil {
  571. return fmt.Errorf("select all organizations: %v", err)
  572. }
  573. sess := x.NewSession()
  574. defer sess.Close()
  575. if err = sess.Begin(); err != nil {
  576. return err
  577. }
  578. for _, org := range orgs {
  579. if org.Rands, err = generate.GetRandomString(10); err != nil {
  580. return err
  581. }
  582. if org.Salt, err = generate.GetRandomString(10); err != nil {
  583. return err
  584. }
  585. if _, err = sess.Id(org.ID).Update(org); err != nil {
  586. return err
  587. }
  588. }
  589. return sess.Commit()
  590. }
  591. // TAction defines the struct for migrating table action
  592. type TAction struct {
  593. ID int64 `xorm:"pk autoincr"`
  594. CreatedUnix int64
  595. }
  596. // TableName will be invoked by XORM to customrize the table name
  597. func (t *TAction) TableName() string { return "action" }
  598. // TNotice defines the struct for migrating table notice
  599. type TNotice struct {
  600. ID int64 `xorm:"pk autoincr"`
  601. CreatedUnix int64
  602. }
  603. // TableName will be invoked by XORM to customrize the table name
  604. func (t *TNotice) TableName() string { return "notice" }
  605. // TComment defines the struct for migrating table comment
  606. type TComment struct {
  607. ID int64 `xorm:"pk autoincr"`
  608. CreatedUnix int64
  609. }
  610. // TableName will be invoked by XORM to customrize the table name
  611. func (t *TComment) TableName() string { return "comment" }
  612. // TIssue defines the struct for migrating table issue
  613. type TIssue struct {
  614. ID int64 `xorm:"pk autoincr"`
  615. DeadlineUnix int64
  616. CreatedUnix int64
  617. UpdatedUnix int64
  618. }
  619. // TableName will be invoked by XORM to customrize the table name
  620. func (t *TIssue) TableName() string { return "issue" }
  621. // TMilestone defines the struct for migrating table milestone
  622. type TMilestone struct {
  623. ID int64 `xorm:"pk autoincr"`
  624. DeadlineUnix int64
  625. ClosedDateUnix int64
  626. }
  627. // TableName will be invoked by XORM to customrize the table name
  628. func (t *TMilestone) TableName() string { return "milestone" }
  629. // TAttachment defines the struct for migrating table attachment
  630. type TAttachment struct {
  631. ID int64 `xorm:"pk autoincr"`
  632. CreatedUnix int64
  633. }
  634. // TableName will be invoked by XORM to customrize the table name
  635. func (t *TAttachment) TableName() string { return "attachment" }
  636. // TLoginSource defines the struct for migrating table login_source
  637. type TLoginSource struct {
  638. ID int64 `xorm:"pk autoincr"`
  639. CreatedUnix int64
  640. UpdatedUnix int64
  641. }
  642. // TableName will be invoked by XORM to customrize the table name
  643. func (t *TLoginSource) TableName() string { return "login_source" }
  644. // TPull defines the struct for migrating table pull_request
  645. type TPull struct {
  646. ID int64 `xorm:"pk autoincr"`
  647. MergedUnix int64
  648. }
  649. // TableName will be invoked by XORM to customrize the table name
  650. func (t *TPull) TableName() string { return "pull_request" }
  651. // TRelease defines the struct for migrating table release
  652. type TRelease struct {
  653. ID int64 `xorm:"pk autoincr"`
  654. CreatedUnix int64
  655. }
  656. // TableName will be invoked by XORM to customrize the table name
  657. func (t *TRelease) TableName() string { return "release" }
  658. // TRepo defines the struct for migrating table repository
  659. type TRepo struct {
  660. ID int64 `xorm:"pk autoincr"`
  661. CreatedUnix int64
  662. UpdatedUnix int64
  663. }
  664. // TableName will be invoked by XORM to customrize the table name
  665. func (t *TRepo) TableName() string { return "repository" }
  666. // TMirror defines the struct for migrating table mirror
  667. type TMirror struct {
  668. ID int64 `xorm:"pk autoincr"`
  669. UpdatedUnix int64
  670. NextUpdateUnix int64
  671. }
  672. // TableName will be invoked by XORM to customrize the table name
  673. func (t *TMirror) TableName() string { return "mirror" }
  674. // TPublicKey defines the struct for migrating table public_key
  675. type TPublicKey struct {
  676. ID int64 `xorm:"pk autoincr"`
  677. CreatedUnix int64
  678. UpdatedUnix int64
  679. }
  680. // TableName will be invoked by XORM to customrize the table name
  681. func (t *TPublicKey) TableName() string { return "public_key" }
  682. // TDeployKey defines the struct for migrating table deploy_key
  683. type TDeployKey struct {
  684. ID int64 `xorm:"pk autoincr"`
  685. CreatedUnix int64
  686. UpdatedUnix int64
  687. }
  688. // TableName will be invoked by XORM to customrize the table name
  689. func (t *TDeployKey) TableName() string { return "deploy_key" }
  690. // TAccessToken defines the struct for migrating table access_token
  691. type TAccessToken struct {
  692. ID int64 `xorm:"pk autoincr"`
  693. CreatedUnix int64
  694. UpdatedUnix int64
  695. }
  696. // TableName will be invoked by XORM to customrize the table name
  697. func (t *TAccessToken) TableName() string { return "access_token" }
  698. // TUser defines the struct for migrating table user
  699. type TUser struct {
  700. ID int64 `xorm:"pk autoincr"`
  701. CreatedUnix int64
  702. UpdatedUnix int64
  703. }
  704. // TableName will be invoked by XORM to customrize the table name
  705. func (t *TUser) TableName() string { return "user" }
  706. // TWebhook defines the struct for migrating table webhook
  707. type TWebhook struct {
  708. ID int64 `xorm:"pk autoincr"`
  709. CreatedUnix int64
  710. UpdatedUnix int64
  711. }
  712. // TableName will be invoked by XORM to customrize the table name
  713. func (t *TWebhook) TableName() string { return "webhook" }
  714. func convertDateToUnix(x *xorm.Engine) (err error) {
  715. log.Info("This migration could take up to minutes, please be patient.")
  716. type Bean struct {
  717. ID int64 `xorm:"pk autoincr"`
  718. Created time.Time
  719. Updated time.Time
  720. Merged time.Time
  721. Deadline time.Time
  722. ClosedDate time.Time
  723. NextUpdate time.Time
  724. }
  725. var tables = []struct {
  726. name string
  727. cols []string
  728. bean interface{}
  729. }{
  730. {"action", []string{"created"}, new(TAction)},
  731. {"notice", []string{"created"}, new(TNotice)},
  732. {"comment", []string{"created"}, new(TComment)},
  733. {"issue", []string{"deadline", "created", "updated"}, new(TIssue)},
  734. {"milestone", []string{"deadline", "closed_date"}, new(TMilestone)},
  735. {"attachment", []string{"created"}, new(TAttachment)},
  736. {"login_source", []string{"created", "updated"}, new(TLoginSource)},
  737. {"pull_request", []string{"merged"}, new(TPull)},
  738. {"release", []string{"created"}, new(TRelease)},
  739. {"repository", []string{"created", "updated"}, new(TRepo)},
  740. {"mirror", []string{"updated", "next_update"}, new(TMirror)},
  741. {"public_key", []string{"created", "updated"}, new(TPublicKey)},
  742. {"deploy_key", []string{"created", "updated"}, new(TDeployKey)},
  743. {"access_token", []string{"created", "updated"}, new(TAccessToken)},
  744. {"user", []string{"created", "updated"}, new(TUser)},
  745. {"webhook", []string{"created", "updated"}, new(TWebhook)},
  746. }
  747. for _, table := range tables {
  748. log.Info("Converting table: %s", table.name)
  749. if err = x.Sync2(table.bean); err != nil {
  750. return fmt.Errorf("Sync [table: %s]: %v", table.name, err)
  751. }
  752. offset := 0
  753. for {
  754. beans := make([]*Bean, 0, 100)
  755. if err = x.Table(table.name).Asc("id").Limit(100, offset).Find(&beans); err != nil {
  756. return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
  757. }
  758. log.Trace("Table [%s]: offset: %d, beans: %d", table.name, offset, len(beans))
  759. if len(beans) == 0 {
  760. break
  761. }
  762. offset += 100
  763. baseSQL := "UPDATE `" + table.name + "` SET "
  764. for _, bean := range beans {
  765. valSQLs := make([]string, 0, len(table.cols))
  766. for _, col := range table.cols {
  767. fieldSQL := ""
  768. fieldSQL += col + "_unix = "
  769. switch col {
  770. case "deadline":
  771. if bean.Deadline.IsZero() {
  772. continue
  773. }
  774. fieldSQL += com.ToStr(bean.Deadline.Unix())
  775. case "created":
  776. fieldSQL += com.ToStr(bean.Created.Unix())
  777. case "updated":
  778. fieldSQL += com.ToStr(bean.Updated.Unix())
  779. case "closed_date":
  780. fieldSQL += com.ToStr(bean.ClosedDate.Unix())
  781. case "merged":
  782. fieldSQL += com.ToStr(bean.Merged.Unix())
  783. case "next_update":
  784. fieldSQL += com.ToStr(bean.NextUpdate.Unix())
  785. }
  786. valSQLs = append(valSQLs, fieldSQL)
  787. }
  788. if len(valSQLs) == 0 {
  789. continue
  790. }
  791. if _, err = x.Exec(baseSQL + strings.Join(valSQLs, ",") + " WHERE id = " + com.ToStr(bean.ID)); err != nil {
  792. return fmt.Errorf("update bean [table: %s, id: %d]: %v", table.name, bean.ID, err)
  793. }
  794. }
  795. }
  796. }
  797. return nil
  798. }