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

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)
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>
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
6 years ago
Template Repositories (#8768) * Start work on templates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Continue work Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix IsTemplate vs IsGenerated Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tabs vs spaces * Tabs vs Spaces * Add templates to API & start adding tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix integration tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove unused User Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move template tests to existing repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Minor re-check updates and cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix optionalbool Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test fixes and icon change Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add new user and repo for tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests (finally) Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update meta repo with env variables Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move generation to create page Combine with repo create template Modify API search to prioritize owner for repo Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests and coverage Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix swagger and JS lint Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix API searching for own private repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Change wording Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix repo search test. User had a private repo that didn't show up Signed-off-by: jolheiser <john.olheiser@gmail.com> * Another search test fix Signed-off-by: jolheiser <john.olheiser@gmail.com> * Clarify git content Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Feedback updates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add topics WIP Signed-off-by: jolheiser <john.olheiser@gmail.com> * Finish adding topics Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update locale Signed-off-by: jolheiser <john.olheiser@gmail.com>
5 years ago
Change target branch for pull request (#6488) * Adds functionality to change target branch of created pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use const instead of var in JavaScript additions Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Check if branches are equal and if PR already exists before changing target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Make sure to check all commits Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Print error messages for user as error flash message Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Disallow changing target branch of closed or merged pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Resolve conflicts after merge of upstream/master Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Change order of branch select fields Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes duplicate check Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use ctx.Tr for translations Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Recompile JS Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use correct translation namespace Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove redundant if condition Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves most change branch logic into pull service Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Completes comment Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Add Ref to ChangesPayload for logging changed target branches instead of creating a new struct Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Revert changes to go.mod Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Directly use createComment method Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return 404 if pull request is not found. Move written check up Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove variable declaration Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return client errors on change pull request target errors Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return error in commit.HasPreviousCommit Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds blank line Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Test patch before persisting new target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update patch before testing (not working) Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes patch calls when changeing pull request target Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes unneeded check for base name Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves ChangeTargetBranch completely to pull service. Update patch status. Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Set webhook mode after errors were validated Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update PR in one transaction Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Move logic for check if head is equal with branch to pull model Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds missing comment and simplify return Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adjust CreateComment method call Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com>
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
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
9 years ago
9 years ago
9 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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. "code.gitea.io/gitea/modules/generate"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/setting"
  20. gouuid "github.com/satori/go.uuid"
  21. "github.com/unknwon/com"
  22. ini "gopkg.in/ini.v1"
  23. "xorm.io/xorm"
  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. // v89 -> v90
  222. NewMigration("add original author/url migration info to issues, comments, and repo ", addOriginalMigrationInfo),
  223. // v90 -> v91
  224. NewMigration("change length of some repository columns", changeSomeColumnsLengthOfRepo),
  225. // v91 -> v92
  226. NewMigration("add index on owner_id of repository and type, review_id of comment", addIndexOnRepositoryAndComment),
  227. // v92 -> v93
  228. NewMigration("remove orphaned repository index statuses", removeLingeringIndexStatus),
  229. // v93 -> v94
  230. NewMigration("add email notification enabled preference to user", addEmailNotificationEnabledToUser),
  231. // v94 -> v95
  232. NewMigration("add enable_status_check, status_check_contexts to protected_branch", addStatusCheckColumnsForProtectedBranches),
  233. // v95 -> v96
  234. NewMigration("add table columns for cross referencing issues", addCrossReferenceColumns),
  235. // v96 -> v97
  236. NewMigration("delete orphaned attachments", deleteOrphanedAttachments),
  237. // v97 -> v98
  238. NewMigration("add repo_admin_change_team_access to user", addRepoAdminChangeTeamAccessColumnForUser),
  239. // v98 -> v99
  240. NewMigration("add original author name and id on migrated release", addOriginalAuthorOnMigratedReleases),
  241. // v99 -> v100
  242. NewMigration("add task table and status column for repository table", addTaskTable),
  243. // v100 -> v101
  244. NewMigration("update migration repositories' service type", updateMigrationServiceTypes),
  245. // v101 -> v102
  246. NewMigration("change length of some external login users columns", changeSomeColumnsLengthOfExternalLoginUser),
  247. // v102 -> v103
  248. NewMigration("update migration repositories' service type", dropColumnHeadUserNameOnPullRequest),
  249. // v103 -> v104
  250. NewMigration("Add WhitelistDeployKeys to protected branch", addWhitelistDeployKeysToBranches),
  251. // v104 -> v105
  252. NewMigration("remove unnecessary columns from label", removeLabelUneededCols),
  253. // v105 -> v106
  254. NewMigration("add includes_all_repositories to teams", addTeamIncludesAllRepositories),
  255. // v106 -> v107
  256. NewMigration("add column `mode` to table watch", addModeColumnToWatch),
  257. // v107 -> v108
  258. NewMigration("Add template options to repository", addTemplateToRepo),
  259. // v108 -> v109
  260. NewMigration("Add comment_id on table notification", addCommentIDOnNotification),
  261. // v109 -> v110
  262. NewMigration("add can_create_org_repo to team", addCanCreateOrgRepoColumnForTeam),
  263. // v110 -> v111
  264. NewMigration("change review content type to text", changeReviewContentToText),
  265. // v111 -> v112
  266. NewMigration("update branch protection for can push and whitelist enable", addBranchProtectionCanPushAndEnableWhitelist),
  267. // v112 -> v113
  268. NewMigration("remove release attachments which repository deleted", removeAttachmentMissedRepo),
  269. // v113 -> v114
  270. NewMigration("new feature: change target branch of pull requests", featureChangeTargetBranch),
  271. // v114 -> v115
  272. NewMigration("Remove authentication credentials from stored URL", sanitizeOriginalURL),
  273. // v115 -> v116
  274. NewMigration("add user_id prefix to existing user avatar name", renameExistingUserAvatarName),
  275. // v116 -> v117
  276. NewMigration("Extend TrackedTimes", extendTrackedTimes),
  277. }
  278. // Migrate database to current version
  279. func Migrate(x *xorm.Engine) error {
  280. if err := x.Sync(new(Version)); err != nil {
  281. return fmt.Errorf("sync: %v", err)
  282. }
  283. currentVersion := &Version{ID: 1}
  284. has, err := x.Get(currentVersion)
  285. if err != nil {
  286. return fmt.Errorf("get: %v", err)
  287. } else if !has {
  288. // If the version record does not exist we think
  289. // it is a fresh installation and we can skip all migrations.
  290. currentVersion.ID = 0
  291. currentVersion.Version = int64(minDBVersion + len(migrations))
  292. if _, err = x.InsertOne(currentVersion); err != nil {
  293. return fmt.Errorf("insert: %v", err)
  294. }
  295. }
  296. v := currentVersion.Version
  297. if minDBVersion > v {
  298. log.Fatal(`Gitea no longer supports auto-migration from your previously installed version.
  299. Please try to upgrade to a lower version (>= v0.6.0) first, then upgrade to current version.`)
  300. return nil
  301. }
  302. if int(v-minDBVersion) > len(migrations) {
  303. // User downgraded Gitea.
  304. currentVersion.Version = int64(len(migrations) + minDBVersion)
  305. _, err = x.ID(1).Update(currentVersion)
  306. return err
  307. }
  308. for i, m := range migrations[v-minDBVersion:] {
  309. log.Info("Migration[%d]: %s", v+int64(i), m.Description())
  310. if err = m.Migrate(x); err != nil {
  311. return fmt.Errorf("do migrate: %v", err)
  312. }
  313. currentVersion.Version = v + int64(i) + 1
  314. if _, err = x.ID(1).Update(currentVersion); err != nil {
  315. return err
  316. }
  317. }
  318. return nil
  319. }
  320. func dropTableColumns(sess *xorm.Session, tableName string, columnNames ...string) (err error) {
  321. if tableName == "" || len(columnNames) == 0 {
  322. return nil
  323. }
  324. // TODO: This will not work if there are foreign keys
  325. switch {
  326. case setting.Database.UseSQLite3:
  327. // First drop the indexes on the columns
  328. res, errIndex := sess.Query(fmt.Sprintf("PRAGMA index_list(`%s`)", tableName))
  329. if errIndex != nil {
  330. return errIndex
  331. }
  332. for _, row := range res {
  333. indexName := row["name"]
  334. indexRes, err := sess.Query(fmt.Sprintf("PRAGMA index_info(`%s`)", indexName))
  335. if err != nil {
  336. return err
  337. }
  338. if len(indexRes) != 1 {
  339. continue
  340. }
  341. indexColumn := string(indexRes[0]["name"])
  342. for _, name := range columnNames {
  343. if name == indexColumn {
  344. _, err := sess.Exec(fmt.Sprintf("DROP INDEX `%s`", indexName))
  345. if err != nil {
  346. return err
  347. }
  348. }
  349. }
  350. }
  351. // Here we need to get the columns from the original table
  352. sql := fmt.Sprintf("SELECT sql FROM sqlite_master WHERE tbl_name='%s' and type='table'", tableName)
  353. res, err := sess.Query(sql)
  354. if err != nil {
  355. return err
  356. }
  357. tableSQL := string(res[0]["sql"])
  358. // Separate out the column definitions
  359. tableSQL = tableSQL[strings.Index(tableSQL, "("):]
  360. // Remove the required columnNames
  361. for _, name := range columnNames {
  362. tableSQL = regexp.MustCompile(regexp.QuoteMeta("`"+name+"`")+"[^`,)]*?[,)]").ReplaceAllString(tableSQL, "")
  363. }
  364. // Ensure the query is ended properly
  365. tableSQL = strings.TrimSpace(tableSQL)
  366. if tableSQL[len(tableSQL)-1] != ')' {
  367. if tableSQL[len(tableSQL)-1] == ',' {
  368. tableSQL = tableSQL[:len(tableSQL)-1]
  369. }
  370. tableSQL += ")"
  371. }
  372. // Find all the columns in the table
  373. columns := regexp.MustCompile("`([^`]*)`").FindAllString(tableSQL, -1)
  374. tableSQL = fmt.Sprintf("CREATE TABLE `new_%s_new` ", tableName) + tableSQL
  375. if _, err := sess.Exec(tableSQL); err != nil {
  376. return err
  377. }
  378. // Now restore the data
  379. columnsSeparated := strings.Join(columns, ",")
  380. insertSQL := fmt.Sprintf("INSERT INTO `new_%s_new` (%s) SELECT %s FROM %s", tableName, columnsSeparated, columnsSeparated, tableName)
  381. if _, err := sess.Exec(insertSQL); err != nil {
  382. return err
  383. }
  384. // Now drop the old table
  385. if _, err := sess.Exec(fmt.Sprintf("DROP TABLE `%s`", tableName)); err != nil {
  386. return err
  387. }
  388. // Rename the table
  389. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `new_%s_new` RENAME TO `%s`", tableName, tableName)); err != nil {
  390. return err
  391. }
  392. case setting.Database.UsePostgreSQL:
  393. cols := ""
  394. for _, col := range columnNames {
  395. if cols != "" {
  396. cols += ", "
  397. }
  398. cols += "DROP COLUMN `" + col + "` CASCADE"
  399. }
  400. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  401. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  402. }
  403. case setting.Database.UseMySQL:
  404. // Drop indexes on columns first
  405. sql := fmt.Sprintf("SHOW INDEX FROM %s WHERE column_name IN ('%s')", tableName, strings.Join(columnNames, "','"))
  406. res, err := sess.Query(sql)
  407. if err != nil {
  408. return err
  409. }
  410. for _, index := range res {
  411. indexName := index["column_name"]
  412. if len(indexName) > 0 {
  413. _, err := sess.Exec(fmt.Sprintf("DROP INDEX `%s` ON `%s`", indexName, tableName))
  414. if err != nil {
  415. return err
  416. }
  417. }
  418. }
  419. // Now drop the columns
  420. cols := ""
  421. for _, col := range columnNames {
  422. if cols != "" {
  423. cols += ", "
  424. }
  425. cols += "DROP COLUMN `" + col + "`"
  426. }
  427. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  428. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  429. }
  430. case setting.Database.UseMSSQL:
  431. cols := ""
  432. for _, col := range columnNames {
  433. if cols != "" {
  434. cols += ", "
  435. }
  436. cols += "`" + strings.ToLower(col) + "`"
  437. }
  438. 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'))",
  439. tableName, strings.Replace(cols, "`", "'", -1))
  440. constraints := make([]string, 0)
  441. if err := sess.SQL(sql).Find(&constraints); err != nil {
  442. sess.Rollback()
  443. return fmt.Errorf("Find constraints: %v", err)
  444. }
  445. for _, constraint := range constraints {
  446. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP CONSTRAINT `%s`", tableName, constraint)); err != nil {
  447. sess.Rollback()
  448. return fmt.Errorf("Drop table `%s` constraint `%s`: %v", tableName, constraint, err)
  449. }
  450. }
  451. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP COLUMN %s", tableName, cols)); err != nil {
  452. sess.Rollback()
  453. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  454. }
  455. return sess.Commit()
  456. default:
  457. log.Fatal("Unrecognized DB")
  458. }
  459. return nil
  460. }
  461. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  462. cfg, err := ini.Load(setting.CustomConf)
  463. if err != nil {
  464. return fmt.Errorf("load custom config: %v", err)
  465. }
  466. cfg.DeleteSection("i18n")
  467. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  468. return fmt.Errorf("save custom config: %v", err)
  469. }
  470. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  471. return nil
  472. }
  473. func trimCommitActionAppURLPrefix(x *xorm.Engine) error {
  474. type PushCommit struct {
  475. Sha1 string
  476. Message string
  477. AuthorEmail string
  478. AuthorName string
  479. }
  480. type PushCommits struct {
  481. Len int
  482. Commits []*PushCommit
  483. CompareURL string `json:"CompareUrl"`
  484. }
  485. type Action struct {
  486. ID int64 `xorm:"pk autoincr"`
  487. Content string `xorm:"TEXT"`
  488. }
  489. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  490. if err != nil {
  491. return fmt.Errorf("select commit actions: %v", err)
  492. }
  493. sess := x.NewSession()
  494. defer sess.Close()
  495. if err = sess.Begin(); err != nil {
  496. return err
  497. }
  498. var pushCommits *PushCommits
  499. for _, action := range results {
  500. actID := com.StrTo(string(action["id"])).MustInt64()
  501. if actID == 0 {
  502. continue
  503. }
  504. pushCommits = new(PushCommits)
  505. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  506. return fmt.Errorf("unmarshal action content[%d]: %v", actID, err)
  507. }
  508. infos := strings.Split(pushCommits.CompareURL, "/")
  509. if len(infos) <= 4 {
  510. continue
  511. }
  512. pushCommits.CompareURL = strings.Join(infos[len(infos)-4:], "/")
  513. p, err := json.Marshal(pushCommits)
  514. if err != nil {
  515. return fmt.Errorf("marshal action content[%d]: %v", actID, err)
  516. }
  517. if _, err = sess.ID(actID).Update(&Action{
  518. Content: string(p),
  519. }); err != nil {
  520. return fmt.Errorf("update action[%d]: %v", actID, err)
  521. }
  522. }
  523. return sess.Commit()
  524. }
  525. func issueToIssueLabel(x *xorm.Engine) error {
  526. type IssueLabel struct {
  527. ID int64 `xorm:"pk autoincr"`
  528. IssueID int64 `xorm:"UNIQUE(s)"`
  529. LabelID int64 `xorm:"UNIQUE(s)"`
  530. }
  531. issueLabels := make([]*IssueLabel, 0, 50)
  532. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  533. if err != nil {
  534. if strings.Contains(err.Error(), "no such column") ||
  535. strings.Contains(err.Error(), "Unknown column") {
  536. return nil
  537. }
  538. return fmt.Errorf("select issues: %v", err)
  539. }
  540. for _, issue := range results {
  541. issueID := com.StrTo(issue["id"]).MustInt64()
  542. // Just in case legacy code can have duplicated IDs for same label.
  543. mark := make(map[int64]bool)
  544. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  545. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  546. if labelID == 0 || mark[labelID] {
  547. continue
  548. }
  549. mark[labelID] = true
  550. issueLabels = append(issueLabels, &IssueLabel{
  551. IssueID: issueID,
  552. LabelID: labelID,
  553. })
  554. }
  555. }
  556. sess := x.NewSession()
  557. defer sess.Close()
  558. if err = sess.Begin(); err != nil {
  559. return err
  560. }
  561. if err = sess.Sync2(new(IssueLabel)); err != nil {
  562. return fmt.Errorf("Sync2: %v", err)
  563. } else if _, err = sess.Insert(issueLabels); err != nil {
  564. return fmt.Errorf("insert issue-labels: %v", err)
  565. }
  566. return sess.Commit()
  567. }
  568. func attachmentRefactor(x *xorm.Engine) error {
  569. type Attachment struct {
  570. ID int64 `xorm:"pk autoincr"`
  571. UUID string `xorm:"uuid INDEX"`
  572. // For rename purpose.
  573. Path string `xorm:"-"`
  574. NewPath string `xorm:"-"`
  575. }
  576. results, err := x.Query("SELECT * FROM `attachment`")
  577. if err != nil {
  578. return fmt.Errorf("select attachments: %v", err)
  579. }
  580. attachments := make([]*Attachment, 0, len(results))
  581. for _, attach := range results {
  582. if !com.IsExist(string(attach["path"])) {
  583. // If the attachment is already missing, there is no point to update it.
  584. continue
  585. }
  586. attachments = append(attachments, &Attachment{
  587. ID: com.StrTo(attach["id"]).MustInt64(),
  588. UUID: gouuid.NewV4().String(),
  589. Path: string(attach["path"]),
  590. })
  591. }
  592. sess := x.NewSession()
  593. defer sess.Close()
  594. if err = sess.Begin(); err != nil {
  595. return err
  596. }
  597. if err = sess.Sync2(new(Attachment)); err != nil {
  598. return fmt.Errorf("Sync2: %v", err)
  599. }
  600. // Note: Roll back for rename can be a dead loop,
  601. // so produces a backup file.
  602. var buf bytes.Buffer
  603. buf.WriteString("# old path -> new path\n")
  604. // Update database first because this is where error happens the most often.
  605. for _, attach := range attachments {
  606. if _, err = sess.ID(attach.ID).Update(attach); err != nil {
  607. return err
  608. }
  609. attach.NewPath = path.Join(setting.AttachmentPath, attach.UUID[0:1], attach.UUID[1:2], attach.UUID)
  610. buf.WriteString(attach.Path)
  611. buf.WriteString("\t")
  612. buf.WriteString(attach.NewPath)
  613. buf.WriteString("\n")
  614. }
  615. // Then rename attachments.
  616. isSucceed := true
  617. defer func() {
  618. if isSucceed {
  619. return
  620. }
  621. dumpPath := path.Join(setting.LogRootPath, "attachment_path.dump")
  622. ioutil.WriteFile(dumpPath, buf.Bytes(), 0666)
  623. log.Info("Failed to rename some attachments, old and new paths are saved into: %s", dumpPath)
  624. }()
  625. for _, attach := range attachments {
  626. if err = os.MkdirAll(path.Dir(attach.NewPath), os.ModePerm); err != nil {
  627. isSucceed = false
  628. return err
  629. }
  630. if err = os.Rename(attach.Path, attach.NewPath); err != nil {
  631. isSucceed = false
  632. return err
  633. }
  634. }
  635. return sess.Commit()
  636. }
  637. func renamePullRequestFields(x *xorm.Engine) (err error) {
  638. type PullRequest struct {
  639. ID int64 `xorm:"pk autoincr"`
  640. PullID int64 `xorm:"INDEX"`
  641. PullIndex int64
  642. HeadBarcnh string
  643. IssueID int64 `xorm:"INDEX"`
  644. Index int64
  645. HeadBranch string
  646. }
  647. if err = x.Sync(new(PullRequest)); err != nil {
  648. return fmt.Errorf("sync: %v", err)
  649. }
  650. results, err := x.Query("SELECT `id`,`pull_id`,`pull_index`,`head_barcnh` FROM `pull_request`")
  651. if err != nil {
  652. if strings.Contains(err.Error(), "no such column") {
  653. return nil
  654. }
  655. return fmt.Errorf("select pull requests: %v", err)
  656. }
  657. sess := x.NewSession()
  658. defer sess.Close()
  659. if err = sess.Begin(); err != nil {
  660. return err
  661. }
  662. var pull *PullRequest
  663. for _, pr := range results {
  664. pull = &PullRequest{
  665. ID: com.StrTo(pr["id"]).MustInt64(),
  666. IssueID: com.StrTo(pr["pull_id"]).MustInt64(),
  667. Index: com.StrTo(pr["pull_index"]).MustInt64(),
  668. HeadBranch: string(pr["head_barcnh"]),
  669. }
  670. if pull.Index == 0 {
  671. continue
  672. }
  673. if _, err = sess.ID(pull.ID).Update(pull); err != nil {
  674. return err
  675. }
  676. }
  677. return sess.Commit()
  678. }
  679. func cleanUpMigrateRepoInfo(x *xorm.Engine) (err error) {
  680. type (
  681. User struct {
  682. ID int64 `xorm:"pk autoincr"`
  683. LowerName string
  684. }
  685. Repository struct {
  686. ID int64 `xorm:"pk autoincr"`
  687. OwnerID int64
  688. LowerName string
  689. }
  690. )
  691. repos := make([]*Repository, 0, 25)
  692. if err = x.Where("is_mirror=?", false).Find(&repos); err != nil {
  693. return fmt.Errorf("select all non-mirror repositories: %v", err)
  694. }
  695. var user *User
  696. for _, repo := range repos {
  697. user = &User{ID: repo.OwnerID}
  698. has, err := x.Get(user)
  699. if err != nil {
  700. return fmt.Errorf("get owner of repository[%d - %d]: %v", repo.ID, repo.OwnerID, err)
  701. } else if !has {
  702. continue
  703. }
  704. configPath := filepath.Join(setting.RepoRootPath, user.LowerName, repo.LowerName+".git/config")
  705. // In case repository file is somehow missing.
  706. if !com.IsFile(configPath) {
  707. continue
  708. }
  709. cfg, err := ini.Load(configPath)
  710. if err != nil {
  711. return fmt.Errorf("open config file: %v", err)
  712. }
  713. cfg.DeleteSection("remote \"origin\"")
  714. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  715. return fmt.Errorf("save config file: %v", err)
  716. }
  717. }
  718. return nil
  719. }
  720. func generateOrgRandsAndSalt(x *xorm.Engine) (err error) {
  721. type User struct {
  722. ID int64 `xorm:"pk autoincr"`
  723. Rands string `xorm:"VARCHAR(10)"`
  724. Salt string `xorm:"VARCHAR(10)"`
  725. }
  726. orgs := make([]*User, 0, 10)
  727. if err = x.Where("type=1").And("rands=''").Find(&orgs); err != nil {
  728. return fmt.Errorf("select all organizations: %v", err)
  729. }
  730. sess := x.NewSession()
  731. defer sess.Close()
  732. if err = sess.Begin(); err != nil {
  733. return err
  734. }
  735. for _, org := range orgs {
  736. if org.Rands, err = generate.GetRandomString(10); err != nil {
  737. return err
  738. }
  739. if org.Salt, err = generate.GetRandomString(10); err != nil {
  740. return err
  741. }
  742. if _, err = sess.ID(org.ID).Update(org); err != nil {
  743. return err
  744. }
  745. }
  746. return sess.Commit()
  747. }
  748. // TAction defines the struct for migrating table action
  749. type TAction struct {
  750. ID int64 `xorm:"pk autoincr"`
  751. CreatedUnix int64
  752. }
  753. // TableName will be invoked by XORM to customrize the table name
  754. func (t *TAction) TableName() string { return "action" }
  755. // TNotice defines the struct for migrating table notice
  756. type TNotice struct {
  757. ID int64 `xorm:"pk autoincr"`
  758. CreatedUnix int64
  759. }
  760. // TableName will be invoked by XORM to customrize the table name
  761. func (t *TNotice) TableName() string { return "notice" }
  762. // TComment defines the struct for migrating table comment
  763. type TComment struct {
  764. ID int64 `xorm:"pk autoincr"`
  765. CreatedUnix int64
  766. }
  767. // TableName will be invoked by XORM to customrize the table name
  768. func (t *TComment) TableName() string { return "comment" }
  769. // TIssue defines the struct for migrating table issue
  770. type TIssue struct {
  771. ID int64 `xorm:"pk autoincr"`
  772. DeadlineUnix int64
  773. CreatedUnix int64
  774. UpdatedUnix int64
  775. }
  776. // TableName will be invoked by XORM to customrize the table name
  777. func (t *TIssue) TableName() string { return "issue" }
  778. // TMilestone defines the struct for migrating table milestone
  779. type TMilestone struct {
  780. ID int64 `xorm:"pk autoincr"`
  781. DeadlineUnix int64
  782. ClosedDateUnix int64
  783. }
  784. // TableName will be invoked by XORM to customrize the table name
  785. func (t *TMilestone) TableName() string { return "milestone" }
  786. // TAttachment defines the struct for migrating table attachment
  787. type TAttachment struct {
  788. ID int64 `xorm:"pk autoincr"`
  789. CreatedUnix int64
  790. }
  791. // TableName will be invoked by XORM to customrize the table name
  792. func (t *TAttachment) TableName() string { return "attachment" }
  793. // TLoginSource defines the struct for migrating table login_source
  794. type TLoginSource struct {
  795. ID int64 `xorm:"pk autoincr"`
  796. CreatedUnix int64
  797. UpdatedUnix int64
  798. }
  799. // TableName will be invoked by XORM to customrize the table name
  800. func (t *TLoginSource) TableName() string { return "login_source" }
  801. // TPull defines the struct for migrating table pull_request
  802. type TPull struct {
  803. ID int64 `xorm:"pk autoincr"`
  804. MergedUnix int64
  805. }
  806. // TableName will be invoked by XORM to customrize the table name
  807. func (t *TPull) TableName() string { return "pull_request" }
  808. // TRelease defines the struct for migrating table release
  809. type TRelease struct {
  810. ID int64 `xorm:"pk autoincr"`
  811. CreatedUnix int64
  812. }
  813. // TableName will be invoked by XORM to customrize the table name
  814. func (t *TRelease) TableName() string { return "release" }
  815. // TRepo defines the struct for migrating table repository
  816. type TRepo struct {
  817. ID int64 `xorm:"pk autoincr"`
  818. CreatedUnix int64
  819. UpdatedUnix int64
  820. }
  821. // TableName will be invoked by XORM to customrize the table name
  822. func (t *TRepo) TableName() string { return "repository" }
  823. // TMirror defines the struct for migrating table mirror
  824. type TMirror struct {
  825. ID int64 `xorm:"pk autoincr"`
  826. UpdatedUnix int64
  827. NextUpdateUnix int64
  828. }
  829. // TableName will be invoked by XORM to customrize the table name
  830. func (t *TMirror) TableName() string { return "mirror" }
  831. // TPublicKey defines the struct for migrating table public_key
  832. type TPublicKey struct {
  833. ID int64 `xorm:"pk autoincr"`
  834. CreatedUnix int64
  835. UpdatedUnix int64
  836. }
  837. // TableName will be invoked by XORM to customrize the table name
  838. func (t *TPublicKey) TableName() string { return "public_key" }
  839. // TDeployKey defines the struct for migrating table deploy_key
  840. type TDeployKey struct {
  841. ID int64 `xorm:"pk autoincr"`
  842. CreatedUnix int64
  843. UpdatedUnix int64
  844. }
  845. // TableName will be invoked by XORM to customrize the table name
  846. func (t *TDeployKey) TableName() string { return "deploy_key" }
  847. // TAccessToken defines the struct for migrating table access_token
  848. type TAccessToken struct {
  849. ID int64 `xorm:"pk autoincr"`
  850. CreatedUnix int64
  851. UpdatedUnix int64
  852. }
  853. // TableName will be invoked by XORM to customrize the table name
  854. func (t *TAccessToken) TableName() string { return "access_token" }
  855. // TUser defines the struct for migrating table user
  856. type TUser struct {
  857. ID int64 `xorm:"pk autoincr"`
  858. CreatedUnix int64
  859. UpdatedUnix int64
  860. }
  861. // TableName will be invoked by XORM to customrize the table name
  862. func (t *TUser) TableName() string { return "user" }
  863. // TWebhook defines the struct for migrating table webhook
  864. type TWebhook struct {
  865. ID int64 `xorm:"pk autoincr"`
  866. CreatedUnix int64
  867. UpdatedUnix int64
  868. }
  869. // TableName will be invoked by XORM to customrize the table name
  870. func (t *TWebhook) TableName() string { return "webhook" }
  871. func convertDateToUnix(x *xorm.Engine) (err error) {
  872. log.Info("This migration could take up to minutes, please be patient.")
  873. type Bean struct {
  874. ID int64 `xorm:"pk autoincr"`
  875. Created time.Time
  876. Updated time.Time
  877. Merged time.Time
  878. Deadline time.Time
  879. ClosedDate time.Time
  880. NextUpdate time.Time
  881. }
  882. var tables = []struct {
  883. name string
  884. cols []string
  885. bean interface{}
  886. }{
  887. {"action", []string{"created"}, new(TAction)},
  888. {"notice", []string{"created"}, new(TNotice)},
  889. {"comment", []string{"created"}, new(TComment)},
  890. {"issue", []string{"deadline", "created", "updated"}, new(TIssue)},
  891. {"milestone", []string{"deadline", "closed_date"}, new(TMilestone)},
  892. {"attachment", []string{"created"}, new(TAttachment)},
  893. {"login_source", []string{"created", "updated"}, new(TLoginSource)},
  894. {"pull_request", []string{"merged"}, new(TPull)},
  895. {"release", []string{"created"}, new(TRelease)},
  896. {"repository", []string{"created", "updated"}, new(TRepo)},
  897. {"mirror", []string{"updated", "next_update"}, new(TMirror)},
  898. {"public_key", []string{"created", "updated"}, new(TPublicKey)},
  899. {"deploy_key", []string{"created", "updated"}, new(TDeployKey)},
  900. {"access_token", []string{"created", "updated"}, new(TAccessToken)},
  901. {"user", []string{"created", "updated"}, new(TUser)},
  902. {"webhook", []string{"created", "updated"}, new(TWebhook)},
  903. }
  904. for _, table := range tables {
  905. log.Info("Converting table: %s", table.name)
  906. if err = x.Sync2(table.bean); err != nil {
  907. return fmt.Errorf("Sync [table: %s]: %v", table.name, err)
  908. }
  909. offset := 0
  910. for {
  911. beans := make([]*Bean, 0, 100)
  912. if err = x.Table(table.name).Asc("id").Limit(100, offset).Find(&beans); err != nil {
  913. return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
  914. }
  915. log.Trace("Table [%s]: offset: %d, beans: %d", table.name, offset, len(beans))
  916. if len(beans) == 0 {
  917. break
  918. }
  919. offset += 100
  920. baseSQL := "UPDATE `" + table.name + "` SET "
  921. for _, bean := range beans {
  922. valSQLs := make([]string, 0, len(table.cols))
  923. for _, col := range table.cols {
  924. fieldSQL := ""
  925. fieldSQL += col + "_unix = "
  926. switch col {
  927. case "deadline":
  928. if bean.Deadline.IsZero() {
  929. continue
  930. }
  931. fieldSQL += com.ToStr(bean.Deadline.Unix())
  932. case "created":
  933. fieldSQL += com.ToStr(bean.Created.Unix())
  934. case "updated":
  935. fieldSQL += com.ToStr(bean.Updated.Unix())
  936. case "closed_date":
  937. fieldSQL += com.ToStr(bean.ClosedDate.Unix())
  938. case "merged":
  939. fieldSQL += com.ToStr(bean.Merged.Unix())
  940. case "next_update":
  941. fieldSQL += com.ToStr(bean.NextUpdate.Unix())
  942. }
  943. valSQLs = append(valSQLs, fieldSQL)
  944. }
  945. if len(valSQLs) == 0 {
  946. continue
  947. }
  948. if _, err = x.Exec(baseSQL + strings.Join(valSQLs, ",") + " WHERE id = " + com.ToStr(bean.ID)); err != nil {
  949. return fmt.Errorf("update bean [table: %s, id: %d]: %v", table.name, bean.ID, err)
  950. }
  951. }
  952. }
  953. }
  954. return nil
  955. }