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