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 36 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
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>
6 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>
6 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
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
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  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. // v117 -> v118
  278. NewMigration("Add block on rejected reviews branch protection", addBlockOnRejectedReviews),
  279. // v118 -> v119
  280. NewMigration("Add commit id and stale to reviews", addReviewCommitAndStale),
  281. // v119 -> v120
  282. NewMigration("Fix migrated repositories' git service type", fixMigratedRepositoryServiceType),
  283. // v120 -> v121
  284. NewMigration("Add owner_name on table repository", addOwnerNameOnRepository),
  285. // v121 -> v122
  286. NewMigration("add is_restricted column for users table", addIsRestricted),
  287. // v122 -> v123
  288. NewMigration("Add Require Signed Commits to ProtectedBranch", addRequireSignedCommits),
  289. // v123 -> v124
  290. NewMigration("Add original informations for reactions", addReactionOriginals),
  291. // v124 -> v125
  292. NewMigration("Add columns to user and repository", addUserRepoMissingColumns),
  293. }
  294. // Migrate database to current version
  295. func Migrate(x *xorm.Engine) error {
  296. if err := x.Sync(new(Version)); err != nil {
  297. return fmt.Errorf("sync: %v", err)
  298. }
  299. currentVersion := &Version{ID: 1}
  300. has, err := x.Get(currentVersion)
  301. if err != nil {
  302. return fmt.Errorf("get: %v", err)
  303. } else if !has {
  304. // If the version record does not exist we think
  305. // it is a fresh installation and we can skip all migrations.
  306. currentVersion.ID = 0
  307. currentVersion.Version = int64(minDBVersion + len(migrations))
  308. if _, err = x.InsertOne(currentVersion); err != nil {
  309. return fmt.Errorf("insert: %v", err)
  310. }
  311. }
  312. v := currentVersion.Version
  313. if minDBVersion > v {
  314. log.Fatal(`Gitea no longer supports auto-migration from your previously installed version.
  315. Please try to upgrade to a lower version (>= v0.6.0) first, then upgrade to current version.`)
  316. return nil
  317. }
  318. if int(v-minDBVersion) > len(migrations) {
  319. // User downgraded Gitea.
  320. currentVersion.Version = int64(len(migrations) + minDBVersion)
  321. _, err = x.ID(1).Update(currentVersion)
  322. return err
  323. }
  324. for i, m := range migrations[v-minDBVersion:] {
  325. log.Info("Migration[%d]: %s", v+int64(i), m.Description())
  326. if err = m.Migrate(x); err != nil {
  327. return fmt.Errorf("do migrate: %v", err)
  328. }
  329. currentVersion.Version = v + int64(i) + 1
  330. if _, err = x.ID(1).Update(currentVersion); err != nil {
  331. return err
  332. }
  333. }
  334. return nil
  335. }
  336. func dropTableColumns(sess *xorm.Session, tableName string, columnNames ...string) (err error) {
  337. if tableName == "" || len(columnNames) == 0 {
  338. return nil
  339. }
  340. // TODO: This will not work if there are foreign keys
  341. switch {
  342. case setting.Database.UseSQLite3:
  343. // First drop the indexes on the columns
  344. res, errIndex := sess.Query(fmt.Sprintf("PRAGMA index_list(`%s`)", tableName))
  345. if errIndex != nil {
  346. return errIndex
  347. }
  348. for _, row := range res {
  349. indexName := row["name"]
  350. indexRes, err := sess.Query(fmt.Sprintf("PRAGMA index_info(`%s`)", indexName))
  351. if err != nil {
  352. return err
  353. }
  354. if len(indexRes) != 1 {
  355. continue
  356. }
  357. indexColumn := string(indexRes[0]["name"])
  358. for _, name := range columnNames {
  359. if name == indexColumn {
  360. _, err := sess.Exec(fmt.Sprintf("DROP INDEX `%s`", indexName))
  361. if err != nil {
  362. return err
  363. }
  364. }
  365. }
  366. }
  367. // Here we need to get the columns from the original table
  368. sql := fmt.Sprintf("SELECT sql FROM sqlite_master WHERE tbl_name='%s' and type='table'", tableName)
  369. res, err := sess.Query(sql)
  370. if err != nil {
  371. return err
  372. }
  373. tableSQL := string(res[0]["sql"])
  374. // Separate out the column definitions
  375. tableSQL = tableSQL[strings.Index(tableSQL, "("):]
  376. // Remove the required columnNames
  377. for _, name := range columnNames {
  378. tableSQL = regexp.MustCompile(regexp.QuoteMeta("`"+name+"`")+"[^`,)]*?[,)]").ReplaceAllString(tableSQL, "")
  379. }
  380. // Ensure the query is ended properly
  381. tableSQL = strings.TrimSpace(tableSQL)
  382. if tableSQL[len(tableSQL)-1] != ')' {
  383. if tableSQL[len(tableSQL)-1] == ',' {
  384. tableSQL = tableSQL[:len(tableSQL)-1]
  385. }
  386. tableSQL += ")"
  387. }
  388. // Find all the columns in the table
  389. columns := regexp.MustCompile("`([^`]*)`").FindAllString(tableSQL, -1)
  390. tableSQL = fmt.Sprintf("CREATE TABLE `new_%s_new` ", tableName) + tableSQL
  391. if _, err := sess.Exec(tableSQL); err != nil {
  392. return err
  393. }
  394. // Now restore the data
  395. columnsSeparated := strings.Join(columns, ",")
  396. insertSQL := fmt.Sprintf("INSERT INTO `new_%s_new` (%s) SELECT %s FROM %s", tableName, columnsSeparated, columnsSeparated, tableName)
  397. if _, err := sess.Exec(insertSQL); err != nil {
  398. return err
  399. }
  400. // Now drop the old table
  401. if _, err := sess.Exec(fmt.Sprintf("DROP TABLE `%s`", tableName)); err != nil {
  402. return err
  403. }
  404. // Rename the table
  405. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `new_%s_new` RENAME TO `%s`", tableName, tableName)); err != nil {
  406. return err
  407. }
  408. case setting.Database.UsePostgreSQL:
  409. cols := ""
  410. for _, col := range columnNames {
  411. if cols != "" {
  412. cols += ", "
  413. }
  414. cols += "DROP COLUMN `" + col + "` CASCADE"
  415. }
  416. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  417. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  418. }
  419. case setting.Database.UseMySQL:
  420. // Drop indexes on columns first
  421. sql := fmt.Sprintf("SHOW INDEX FROM %s WHERE column_name IN ('%s')", tableName, strings.Join(columnNames, "','"))
  422. res, err := sess.Query(sql)
  423. if err != nil {
  424. return err
  425. }
  426. for _, index := range res {
  427. indexName := index["column_name"]
  428. if len(indexName) > 0 {
  429. _, err := sess.Exec(fmt.Sprintf("DROP INDEX `%s` ON `%s`", indexName, tableName))
  430. if err != nil {
  431. return err
  432. }
  433. }
  434. }
  435. // Now drop the columns
  436. cols := ""
  437. for _, col := range columnNames {
  438. if cols != "" {
  439. cols += ", "
  440. }
  441. cols += "DROP COLUMN `" + col + "`"
  442. }
  443. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` %s", tableName, cols)); err != nil {
  444. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  445. }
  446. case setting.Database.UseMSSQL:
  447. cols := ""
  448. for _, col := range columnNames {
  449. if cols != "" {
  450. cols += ", "
  451. }
  452. cols += "`" + strings.ToLower(col) + "`"
  453. }
  454. 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'))",
  455. tableName, strings.Replace(cols, "`", "'", -1))
  456. constraints := make([]string, 0)
  457. if err := sess.SQL(sql).Find(&constraints); err != nil {
  458. sess.Rollback()
  459. return fmt.Errorf("Find constraints: %v", err)
  460. }
  461. for _, constraint := range constraints {
  462. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP CONSTRAINT `%s`", tableName, constraint)); err != nil {
  463. sess.Rollback()
  464. return fmt.Errorf("Drop table `%s` constraint `%s`: %v", tableName, constraint, err)
  465. }
  466. }
  467. if _, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` DROP COLUMN %s", tableName, cols)); err != nil {
  468. sess.Rollback()
  469. return fmt.Errorf("Drop table `%s` columns %v: %v", tableName, columnNames, err)
  470. }
  471. return sess.Commit()
  472. default:
  473. log.Fatal("Unrecognized DB")
  474. }
  475. return nil
  476. }
  477. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  478. cfg, err := ini.Load(setting.CustomConf)
  479. if err != nil {
  480. return fmt.Errorf("load custom config: %v", err)
  481. }
  482. cfg.DeleteSection("i18n")
  483. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  484. return fmt.Errorf("save custom config: %v", err)
  485. }
  486. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  487. return nil
  488. }
  489. func trimCommitActionAppURLPrefix(x *xorm.Engine) error {
  490. type PushCommit struct {
  491. Sha1 string
  492. Message string
  493. AuthorEmail string
  494. AuthorName string
  495. }
  496. type PushCommits struct {
  497. Len int
  498. Commits []*PushCommit
  499. CompareURL string `json:"CompareUrl"`
  500. }
  501. type Action struct {
  502. ID int64 `xorm:"pk autoincr"`
  503. Content string `xorm:"TEXT"`
  504. }
  505. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  506. if err != nil {
  507. return fmt.Errorf("select commit actions: %v", err)
  508. }
  509. sess := x.NewSession()
  510. defer sess.Close()
  511. if err = sess.Begin(); err != nil {
  512. return err
  513. }
  514. var pushCommits *PushCommits
  515. for _, action := range results {
  516. actID := com.StrTo(string(action["id"])).MustInt64()
  517. if actID == 0 {
  518. continue
  519. }
  520. pushCommits = new(PushCommits)
  521. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  522. return fmt.Errorf("unmarshal action content[%d]: %v", actID, err)
  523. }
  524. infos := strings.Split(pushCommits.CompareURL, "/")
  525. if len(infos) <= 4 {
  526. continue
  527. }
  528. pushCommits.CompareURL = strings.Join(infos[len(infos)-4:], "/")
  529. p, err := json.Marshal(pushCommits)
  530. if err != nil {
  531. return fmt.Errorf("marshal action content[%d]: %v", actID, err)
  532. }
  533. if _, err = sess.ID(actID).Update(&Action{
  534. Content: string(p),
  535. }); err != nil {
  536. return fmt.Errorf("update action[%d]: %v", actID, err)
  537. }
  538. }
  539. return sess.Commit()
  540. }
  541. func issueToIssueLabel(x *xorm.Engine) error {
  542. type IssueLabel struct {
  543. ID int64 `xorm:"pk autoincr"`
  544. IssueID int64 `xorm:"UNIQUE(s)"`
  545. LabelID int64 `xorm:"UNIQUE(s)"`
  546. }
  547. issueLabels := make([]*IssueLabel, 0, 50)
  548. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  549. if err != nil {
  550. if strings.Contains(err.Error(), "no such column") ||
  551. strings.Contains(err.Error(), "Unknown column") {
  552. return nil
  553. }
  554. return fmt.Errorf("select issues: %v", err)
  555. }
  556. for _, issue := range results {
  557. issueID := com.StrTo(issue["id"]).MustInt64()
  558. // Just in case legacy code can have duplicated IDs for same label.
  559. mark := make(map[int64]bool)
  560. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  561. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  562. if labelID == 0 || mark[labelID] {
  563. continue
  564. }
  565. mark[labelID] = true
  566. issueLabels = append(issueLabels, &IssueLabel{
  567. IssueID: issueID,
  568. LabelID: labelID,
  569. })
  570. }
  571. }
  572. sess := x.NewSession()
  573. defer sess.Close()
  574. if err = sess.Begin(); err != nil {
  575. return err
  576. }
  577. if err = sess.Sync2(new(IssueLabel)); err != nil {
  578. return fmt.Errorf("Sync2: %v", err)
  579. } else if _, err = sess.Insert(issueLabels); err != nil {
  580. return fmt.Errorf("insert issue-labels: %v", err)
  581. }
  582. return sess.Commit()
  583. }
  584. func attachmentRefactor(x *xorm.Engine) error {
  585. type Attachment struct {
  586. ID int64 `xorm:"pk autoincr"`
  587. UUID string `xorm:"uuid INDEX"`
  588. // For rename purpose.
  589. Path string `xorm:"-"`
  590. NewPath string `xorm:"-"`
  591. }
  592. results, err := x.Query("SELECT * FROM `attachment`")
  593. if err != nil {
  594. return fmt.Errorf("select attachments: %v", err)
  595. }
  596. attachments := make([]*Attachment, 0, len(results))
  597. for _, attach := range results {
  598. if !com.IsExist(string(attach["path"])) {
  599. // If the attachment is already missing, there is no point to update it.
  600. continue
  601. }
  602. attachments = append(attachments, &Attachment{
  603. ID: com.StrTo(attach["id"]).MustInt64(),
  604. UUID: gouuid.NewV4().String(),
  605. Path: string(attach["path"]),
  606. })
  607. }
  608. sess := x.NewSession()
  609. defer sess.Close()
  610. if err = sess.Begin(); err != nil {
  611. return err
  612. }
  613. if err = sess.Sync2(new(Attachment)); err != nil {
  614. return fmt.Errorf("Sync2: %v", err)
  615. }
  616. // Note: Roll back for rename can be a dead loop,
  617. // so produces a backup file.
  618. var buf bytes.Buffer
  619. buf.WriteString("# old path -> new path\n")
  620. // Update database first because this is where error happens the most often.
  621. for _, attach := range attachments {
  622. if _, err = sess.ID(attach.ID).Update(attach); err != nil {
  623. return err
  624. }
  625. attach.NewPath = path.Join(setting.AttachmentPath, attach.UUID[0:1], attach.UUID[1:2], attach.UUID)
  626. buf.WriteString(attach.Path)
  627. buf.WriteString("\t")
  628. buf.WriteString(attach.NewPath)
  629. buf.WriteString("\n")
  630. }
  631. // Then rename attachments.
  632. isSucceed := true
  633. defer func() {
  634. if isSucceed {
  635. return
  636. }
  637. dumpPath := path.Join(setting.LogRootPath, "attachment_path.dump")
  638. ioutil.WriteFile(dumpPath, buf.Bytes(), 0666)
  639. log.Info("Failed to rename some attachments, old and new paths are saved into: %s", dumpPath)
  640. }()
  641. for _, attach := range attachments {
  642. if err = os.MkdirAll(path.Dir(attach.NewPath), os.ModePerm); err != nil {
  643. isSucceed = false
  644. return err
  645. }
  646. if err = os.Rename(attach.Path, attach.NewPath); err != nil {
  647. isSucceed = false
  648. return err
  649. }
  650. }
  651. return sess.Commit()
  652. }
  653. func renamePullRequestFields(x *xorm.Engine) (err error) {
  654. type PullRequest struct {
  655. ID int64 `xorm:"pk autoincr"`
  656. PullID int64 `xorm:"INDEX"`
  657. PullIndex int64
  658. HeadBarcnh string
  659. IssueID int64 `xorm:"INDEX"`
  660. Index int64
  661. HeadBranch string
  662. }
  663. if err = x.Sync(new(PullRequest)); err != nil {
  664. return fmt.Errorf("sync: %v", err)
  665. }
  666. results, err := x.Query("SELECT `id`,`pull_id`,`pull_index`,`head_barcnh` FROM `pull_request`")
  667. if err != nil {
  668. if strings.Contains(err.Error(), "no such column") {
  669. return nil
  670. }
  671. return fmt.Errorf("select pull requests: %v", err)
  672. }
  673. sess := x.NewSession()
  674. defer sess.Close()
  675. if err = sess.Begin(); err != nil {
  676. return err
  677. }
  678. var pull *PullRequest
  679. for _, pr := range results {
  680. pull = &PullRequest{
  681. ID: com.StrTo(pr["id"]).MustInt64(),
  682. IssueID: com.StrTo(pr["pull_id"]).MustInt64(),
  683. Index: com.StrTo(pr["pull_index"]).MustInt64(),
  684. HeadBranch: string(pr["head_barcnh"]),
  685. }
  686. if pull.Index == 0 {
  687. continue
  688. }
  689. if _, err = sess.ID(pull.ID).Update(pull); err != nil {
  690. return err
  691. }
  692. }
  693. return sess.Commit()
  694. }
  695. func cleanUpMigrateRepoInfo(x *xorm.Engine) (err error) {
  696. type (
  697. User struct {
  698. ID int64 `xorm:"pk autoincr"`
  699. LowerName string
  700. }
  701. Repository struct {
  702. ID int64 `xorm:"pk autoincr"`
  703. OwnerID int64
  704. LowerName string
  705. }
  706. )
  707. repos := make([]*Repository, 0, 25)
  708. if err = x.Where("is_mirror=?", false).Find(&repos); err != nil {
  709. return fmt.Errorf("select all non-mirror repositories: %v", err)
  710. }
  711. var user *User
  712. for _, repo := range repos {
  713. user = &User{ID: repo.OwnerID}
  714. has, err := x.Get(user)
  715. if err != nil {
  716. return fmt.Errorf("get owner of repository[%d - %d]: %v", repo.ID, repo.OwnerID, err)
  717. } else if !has {
  718. continue
  719. }
  720. configPath := filepath.Join(setting.RepoRootPath, user.LowerName, repo.LowerName+".git/config")
  721. // In case repository file is somehow missing.
  722. if !com.IsFile(configPath) {
  723. continue
  724. }
  725. cfg, err := ini.Load(configPath)
  726. if err != nil {
  727. return fmt.Errorf("open config file: %v", err)
  728. }
  729. cfg.DeleteSection("remote \"origin\"")
  730. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  731. return fmt.Errorf("save config file: %v", err)
  732. }
  733. }
  734. return nil
  735. }
  736. func generateOrgRandsAndSalt(x *xorm.Engine) (err error) {
  737. type User struct {
  738. ID int64 `xorm:"pk autoincr"`
  739. Rands string `xorm:"VARCHAR(10)"`
  740. Salt string `xorm:"VARCHAR(10)"`
  741. }
  742. orgs := make([]*User, 0, 10)
  743. if err = x.Where("type=1").And("rands=''").Find(&orgs); err != nil {
  744. return fmt.Errorf("select all organizations: %v", err)
  745. }
  746. sess := x.NewSession()
  747. defer sess.Close()
  748. if err = sess.Begin(); err != nil {
  749. return err
  750. }
  751. for _, org := range orgs {
  752. if org.Rands, err = generate.GetRandomString(10); err != nil {
  753. return err
  754. }
  755. if org.Salt, err = generate.GetRandomString(10); err != nil {
  756. return err
  757. }
  758. if _, err = sess.ID(org.ID).Update(org); err != nil {
  759. return err
  760. }
  761. }
  762. return sess.Commit()
  763. }
  764. // TAction defines the struct for migrating table action
  765. type TAction struct {
  766. ID int64 `xorm:"pk autoincr"`
  767. CreatedUnix int64
  768. }
  769. // TableName will be invoked by XORM to customrize the table name
  770. func (t *TAction) TableName() string { return "action" }
  771. // TNotice defines the struct for migrating table notice
  772. type TNotice struct {
  773. ID int64 `xorm:"pk autoincr"`
  774. CreatedUnix int64
  775. }
  776. // TableName will be invoked by XORM to customrize the table name
  777. func (t *TNotice) TableName() string { return "notice" }
  778. // TComment defines the struct for migrating table comment
  779. type TComment struct {
  780. ID int64 `xorm:"pk autoincr"`
  781. CreatedUnix int64
  782. }
  783. // TableName will be invoked by XORM to customrize the table name
  784. func (t *TComment) TableName() string { return "comment" }
  785. // TIssue defines the struct for migrating table issue
  786. type TIssue struct {
  787. ID int64 `xorm:"pk autoincr"`
  788. DeadlineUnix int64
  789. CreatedUnix int64
  790. UpdatedUnix int64
  791. }
  792. // TableName will be invoked by XORM to customrize the table name
  793. func (t *TIssue) TableName() string { return "issue" }
  794. // TMilestone defines the struct for migrating table milestone
  795. type TMilestone struct {
  796. ID int64 `xorm:"pk autoincr"`
  797. DeadlineUnix int64
  798. ClosedDateUnix int64
  799. }
  800. // TableName will be invoked by XORM to customrize the table name
  801. func (t *TMilestone) TableName() string { return "milestone" }
  802. // TAttachment defines the struct for migrating table attachment
  803. type TAttachment struct {
  804. ID int64 `xorm:"pk autoincr"`
  805. CreatedUnix int64
  806. }
  807. // TableName will be invoked by XORM to customrize the table name
  808. func (t *TAttachment) TableName() string { return "attachment" }
  809. // TLoginSource defines the struct for migrating table login_source
  810. type TLoginSource struct {
  811. ID int64 `xorm:"pk autoincr"`
  812. CreatedUnix int64
  813. UpdatedUnix int64
  814. }
  815. // TableName will be invoked by XORM to customrize the table name
  816. func (t *TLoginSource) TableName() string { return "login_source" }
  817. // TPull defines the struct for migrating table pull_request
  818. type TPull struct {
  819. ID int64 `xorm:"pk autoincr"`
  820. MergedUnix int64
  821. }
  822. // TableName will be invoked by XORM to customrize the table name
  823. func (t *TPull) TableName() string { return "pull_request" }
  824. // TRelease defines the struct for migrating table release
  825. type TRelease struct {
  826. ID int64 `xorm:"pk autoincr"`
  827. CreatedUnix int64
  828. }
  829. // TableName will be invoked by XORM to customrize the table name
  830. func (t *TRelease) TableName() string { return "release" }
  831. // TRepo defines the struct for migrating table repository
  832. type TRepo 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 *TRepo) TableName() string { return "repository" }
  839. // TMirror defines the struct for migrating table mirror
  840. type TMirror struct {
  841. ID int64 `xorm:"pk autoincr"`
  842. UpdatedUnix int64
  843. NextUpdateUnix int64
  844. }
  845. // TableName will be invoked by XORM to customrize the table name
  846. func (t *TMirror) TableName() string { return "mirror" }
  847. // TPublicKey defines the struct for migrating table public_key
  848. type TPublicKey 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 *TPublicKey) TableName() string { return "public_key" }
  855. // TDeployKey defines the struct for migrating table deploy_key
  856. type TDeployKey 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 *TDeployKey) TableName() string { return "deploy_key" }
  863. // TAccessToken defines the struct for migrating table access_token
  864. type TAccessToken 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 *TAccessToken) TableName() string { return "access_token" }
  871. // TUser defines the struct for migrating table user
  872. type TUser struct {
  873. ID int64 `xorm:"pk autoincr"`
  874. CreatedUnix int64
  875. UpdatedUnix int64
  876. }
  877. // TableName will be invoked by XORM to customrize the table name
  878. func (t *TUser) TableName() string { return "user" }
  879. // TWebhook defines the struct for migrating table webhook
  880. type TWebhook struct {
  881. ID int64 `xorm:"pk autoincr"`
  882. CreatedUnix int64
  883. UpdatedUnix int64
  884. }
  885. // TableName will be invoked by XORM to customrize the table name
  886. func (t *TWebhook) TableName() string { return "webhook" }
  887. func convertDateToUnix(x *xorm.Engine) (err error) {
  888. log.Info("This migration could take up to minutes, please be patient.")
  889. type Bean struct {
  890. ID int64 `xorm:"pk autoincr"`
  891. Created time.Time
  892. Updated time.Time
  893. Merged time.Time
  894. Deadline time.Time
  895. ClosedDate time.Time
  896. NextUpdate time.Time
  897. }
  898. var tables = []struct {
  899. name string
  900. cols []string
  901. bean interface{}
  902. }{
  903. {"action", []string{"created"}, new(TAction)},
  904. {"notice", []string{"created"}, new(TNotice)},
  905. {"comment", []string{"created"}, new(TComment)},
  906. {"issue", []string{"deadline", "created", "updated"}, new(TIssue)},
  907. {"milestone", []string{"deadline", "closed_date"}, new(TMilestone)},
  908. {"attachment", []string{"created"}, new(TAttachment)},
  909. {"login_source", []string{"created", "updated"}, new(TLoginSource)},
  910. {"pull_request", []string{"merged"}, new(TPull)},
  911. {"release", []string{"created"}, new(TRelease)},
  912. {"repository", []string{"created", "updated"}, new(TRepo)},
  913. {"mirror", []string{"updated", "next_update"}, new(TMirror)},
  914. {"public_key", []string{"created", "updated"}, new(TPublicKey)},
  915. {"deploy_key", []string{"created", "updated"}, new(TDeployKey)},
  916. {"access_token", []string{"created", "updated"}, new(TAccessToken)},
  917. {"user", []string{"created", "updated"}, new(TUser)},
  918. {"webhook", []string{"created", "updated"}, new(TWebhook)},
  919. }
  920. for _, table := range tables {
  921. log.Info("Converting table: %s", table.name)
  922. if err = x.Sync2(table.bean); err != nil {
  923. return fmt.Errorf("Sync [table: %s]: %v", table.name, err)
  924. }
  925. offset := 0
  926. for {
  927. beans := make([]*Bean, 0, 100)
  928. if err = x.Table(table.name).Asc("id").Limit(100, offset).Find(&beans); err != nil {
  929. return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
  930. }
  931. log.Trace("Table [%s]: offset: %d, beans: %d", table.name, offset, len(beans))
  932. if len(beans) == 0 {
  933. break
  934. }
  935. offset += 100
  936. baseSQL := "UPDATE `" + table.name + "` SET "
  937. for _, bean := range beans {
  938. valSQLs := make([]string, 0, len(table.cols))
  939. for _, col := range table.cols {
  940. fieldSQL := ""
  941. fieldSQL += col + "_unix = "
  942. switch col {
  943. case "deadline":
  944. if bean.Deadline.IsZero() {
  945. continue
  946. }
  947. fieldSQL += com.ToStr(bean.Deadline.Unix())
  948. case "created":
  949. fieldSQL += com.ToStr(bean.Created.Unix())
  950. case "updated":
  951. fieldSQL += com.ToStr(bean.Updated.Unix())
  952. case "closed_date":
  953. fieldSQL += com.ToStr(bean.ClosedDate.Unix())
  954. case "merged":
  955. fieldSQL += com.ToStr(bean.Merged.Unix())
  956. case "next_update":
  957. fieldSQL += com.ToStr(bean.NextUpdate.Unix())
  958. }
  959. valSQLs = append(valSQLs, fieldSQL)
  960. }
  961. if len(valSQLs) == 0 {
  962. continue
  963. }
  964. if _, err = x.Exec(baseSQL + strings.Join(valSQLs, ",") + " WHERE id = " + com.ToStr(bean.ID)); err != nil {
  965. return fmt.Errorf("update bean [table: %s, id: %d]: %v", table.name, bean.ID, err)
  966. }
  967. }
  968. }
  969. }
  970. return nil
  971. }