Introduction to Git rebase and force-push - GitLab Docs

文章推薦指數: 80 %
投票人數:10人

Introduction to Git rebase and force-push, methods to resolve merge conflicts through the command line. Docs What'snew? Getfreetrial GitLabDocs LearnGitLabwithtutorials Chooseasubscription GitLabSaaSsubscriptions Self-managedsubscriptions GitLabDedicatedsubscriptions Quarterlyreconciliation Storageusagequota CI/CDminutesquota Freeuserlimit ActivateEnterpriseEdition FeaturesavailabletoStarterandBronzesubscribers InstallGitLab Requirements PostgreSQLextensions Installationmethods Linuxpackages(Omnibus) Architecture Omnibuspackagesandimages Packageinformation Packagedefaults Packagelicensing Packagesignatures PostgreSQLversions Installation Deprecationpolicy SupportedOSes Manualinstallation InstallJiHuEdition Configure ActionCable Backups Configurationoptions Customenvironmentvariables Database GitLabMattermost Grafana Highavailabilityroles Logs NGINX GitalyCluster Prometheus Puma RaspberryPi Redis SMTP SSL DNS Imagescaling Memory-constrainedenvironments Releaseprocess Maintain Troubleshoot Cloud-nativeGitLab InstallwithaHelmchart Install Installprerequisites Cloudclusterpreparation AzureKubernetesService AmazonEKS GoogleKubernetesEngine OpenShiftOrigin OracleContainerEngineforKubernetes DeploytheHelmchart Deploymentoptions Upgrade Releasenotes6.0 Releasenotes5.0 Releasenotes4.0 Releasenotes3.0 Releasenotes2.0 Releasenotes1.0 BackupandRestore Backup Restore MigratefromOmnibus MigratefromtheLinuxpackage MigratetotheLinuxpackage MigratebetweenHelmversions MigratetoMinIO Versionmappings Configure Globals GitLabsub-charts Gitalychart GitLabExporterchart GitLabGrafanachart GitLabPageschart GitLabRunnerchart GitLabShellchart KASchart Migrationschart Praefectchart Sidekiqchart Toolboxchart Webservicechart Miniochart Nginxchart Registrychart Advanced CustomDockerimages Externaldatabase ExternalGitaly ExternalGitLabPages ExternalMattermost ExternalNginx Externalobjectstorage ExternalRedis FIPS-compliantimages Geo InternalTLSbetweenservices Persistentvolumes RedHatUBI-basedimages Troubleshoot InstallwithGitLabOperator Install Backupandrestore UpgradeGitLab SupportforGitoverSSH UpgradetheOperator Securitycontextconstraints Docker Fromsource InstallunderarelativeURL Troubleshooting Cloudprovidersguides Azure GoogleCloudPlatform(GCP) AmazonWebServices(AWS) EKSbestpractices GitLabSREforAWS GitLabCloudNativeHybridonAWSEKS ManualinstallonAWS OfflineGitLab OfflineGitLabinstallation ReferenceArchitectures Upto1,000users Upto2,000users Upto3,000users Upto5,000users Upto10,000users Upto25,000users Upto50,000users Stepsafterinstalling UpgradeGitLab Plananupgrade UpgradeOmnibusinstance ConverttoOmnibus ConverttoEnterpriseEdition Packagesignatures GitLab15changes GitLab14changes GitLab13changes GitLab12changes GitLab11changes GitLab10changes Downgrade Upgradesourceinstance Patchversions ChangefromCommunityEditiontoEnterpriseEdition Zero-downtimeupgradesformulti-nodeinstances Upgradeswithdowntimeformulti-nodeinstances ChangefromEnterpriseEditiontoCommunityEdition Releasesandmaintenance Deprecationsbyversion Removalsbyversion What'snew InstallGitLabRunner Linux Linuxmanualinstall FreeBSD macOS Windows Docker Helmchart GitLabagent Operator Bleedingedgereleases ConfigureGitLabRunner Advancedconfig Autoscaleconfig AutoscaleonAWSEC2 AutoscaleonAWSFargate Commands Featureflags macOSsetup RunnerOperatoronOpenShift Runningbehindaproxy Ratelimitedrequests Self-signedcertificates Systemservices Speedupjobexecution TroubleshootGitLabRunner Integrateapplications Akismet ArkoseProtect Datadog Elasticsearch Elasticsearchtroubleshooting Gitpod Jiraintegrations ConfiguretheJiraintegration GitLabforJiraapp JiraDVCSconnector JiraDevelopmentPanel CreateJiraServeruser CreateJiraCloudAPItoken Jiraintegrationissuemanagement Krokidiagrams Mailgun PlantUML Projectintegrationmanagement Projectintegrations Asana BambooCI Discord Emailsonpush GitHub GoogleChat Harbor Irker Jenkins Mattermostnotifications Mattermostslashcommands MicrosoftTeams MockCI Pipelinestatusemails PivotalTracker Prometheus Pumble ServiceNow Slacknotifications Slackslashcommands Slashcommands Slackapplication UnifyCircuit WebexTeams Webhooks Webhookevents Externalissuetracker Bugzilla Customissuetracker IBMEngineeringWorkflowManagement Redmine YouTrack ZenTao Gmailactionsbuttons reCAPTCHA Securitypartners Sourcegraph Trello VisualStudioCodeextension AdministerGitLab Getstarted Configureyourinstallation Authenticationandauthorization AliCloud AtlassianCrowd(deprecated) Atlassian Auth0 Authentiq AWSCognito Azure BitbucketCloud CAS(deprecated) DingTalk Facebook GenericOAuth2 GitHub GitLab.com Google JWT Kerberos LDAP LDAPsynchronization LDAP(GoogleSecure) LDAPtroubleshooting OAuthserviceprovider OmniAuth OpenIDConnectOmniAuth OpenIDConnectidentity Salesforce SAML Smartcard Twitter Vault CI/CD ConfigurationandAdminArea AdminAreasettings Accountandlimitsettings Appearance Authentication Batchedbackgroundmigrations CI/CD Applicationcacheinterval Custominstance-levelprojecttemplates DeprecatedAPIratelimits Difflimits Email Externalauthorization Externalpipelinevalidation Enablefeatureswithfeatureflags AvailableGitLabfeatureflags FederatedLearningofCohorts(FLoC) Geosites Gitabuseratelimit GitLFSadministration GitLabPages GitLabPagesforsourceinstallations HealthCheck Incidentmanagementratelimits Instancetemplaterepository Jobartifacts Joblogs Labels Logsystem Parselogswithjq TracelogsbasedoncorrelationID MaintenanceMode Mergerequestapprovals PackageRegistryratelimits Pollingintervalmultiplier Protectedpaths Pusheventactivitieslimit RatelimitsonRepositoryfilesAPI RatelimitsonGitLFS Ratelimitsonissuecreation Ratelimitsonrawendpoints Ratelimitsonnotecreation RatelimitsonUsersAPI Ratelimitsonpipelinecreation Replybyemail Repositorychecks Sign-inandhelppagetext Sign-inrestrictions Sign-uprestrictions Spamcheck SystemHooks Third-partyoffers Timezone Uploads UserCohorts Visibilityandaccesscontrols Consul Environmentvariables Filehooks Gitprotocolv2 Incomingemail Instancelimits InstanceReview PostgreSQL Replicationandfailover Standalonepackageddatabase PgBouncer DatabaseLoadBalancing Externaldatabaseservice Moveinstances Loadbalancer NFS Postfix Redis ConfigurethebundledRedisforreplication ConfigureyourownRedisforreplication StandaloneRedisconfiguration Troubleshooting Sidekiq MultipleSidekiqprocesses Sidekiqroutingrules SidekiqMemoryKiller Sidekiqhealthcheck Sidekiqjobmigration Sidekiqjobsizelimits TroubleshootingSidekiq S/MIMEsigning Repositorystorage Repositorystoragetypes GitalyandGitalyCluster ConfigureGitaly ConfigureGitalyCluster Monitoring Recoveryoptions Troubleshooting Gitalyreference Gitalytimeouts Objectstorage Mergerequestdiffsstorage Staticobjectsexternalstorage Geo SettingupGeo Databasereplication ExternalPostgreSQLinstances Configuration UsingaGeosite Configuresecondaryproxying Location-awarepublicURL UpgradingGeosites Version-specificupgrades Usingobjectstorage UsingDockerRegistry Geoformultipleservers Geosecurityreview Location-awareGitremoteURLs TuningGeo DisableGeo RemovingaGeosite Supporteddatatypes Frequentlyaskedquestions Troubleshooting Validationtests GeoGlossary Disasterrecovery(Geo) Plannedfailover Bringprimaryback Automaticbackgroundverification AgentserverforKubernetes Serverhooks Terraformstate Packages ContainerRegistry DependencyProxy Webterminals Wikis InvalidateMarkdowncache Issueclosingpattern Snippets Hosttheproductdocumentation Maintainyourinstallation Housekeeping FastSSHkeylookup Filesystembenchmarking Railsconsole UseSSHcertificates Enableencryptedconfiguration Raketasks Backupandrestore BackupGitLab RestoreGitLab Cleanup Generalmaintenance Geotasks GitHubimport SMTP SPDXlicenselistimport Importrepositories Inactiveprojectdeletion Moverepositories Integritycheck LDAPmaintenance Listrepositories Migratesnippets Praefecttasks Projectimportandexport Read-onlystate Repositorystorage RestartGitLab SamplePrometheusdata Uploadsmigration Uploadssanitization Usermanagement Webhooksadministration X509signatures Secureyourinstallation LimitsonSSHkeys Ratelimits Webhooks Informationexclusivity ManagetheCRIMEvulnerability Enforcetwo-factorauthentication(2FA) Useremailconfirmation Runners Proxyingassets CI/CDvariables Tokenoverview Compliancefeatures Respondtosecurityincidents Administerusers Resetuserpassword Unlockauser Reviewabusereports Unknownsign-ins,emailnotification Userfileuploads Passwordstorage Credentialsinventory Custompasswordlengthlimits Generatedpasswordsandintegratedauthentication Globalusersettings Moderateusers Auditorusers Configurethelibravatarservice Broadcastmessages EmailfromGitLab UseGitLab Setupyourorganization Namespaces Members Groups Managegroups Groupaccessandpermissions Customgroup-levelprojecttemplates Groupaccesstokens Groupimport/export Migratinggroups SAMLGroupSync SAMLSSOforGitLab.comgroups SCIMprovisioning ExamplegroupSAMLandSCIMconfigurations Subgroups Moveapersonalprojecttoagroup Useraccountoptions Activesessions Permissionsandroles Personalaccesstokens Profilepreferences Notificationemails Two-factorauthentication Reportabuse Deleteaccount SSHkeys GitLab.comsettings Organizeworkwithprojects Manageprojects Projectvisibility Projectsettings Projectaccesstokens Shareprojects Reservedprojectandgroupnames Search AdvancedSearch AdvancedSearchsyntax Badges Codeintelligence Compliance LicenseCompliance Compliancereport Descriptiontemplates Deploykeys Deploytokens Filefinder GitLabPages Createfromscratch CreateusingaCI/CDtemplate Createusingaforkedsampleproject Createusingaprojecttemplate Defaultdomains,URLs,andbaseurls CustomdomainsandSSL/TLScertificates DNSconcepts SSL/TLSconcepts Let'sEncryptintegration Accesscontrol Redirects ExploringGitLabPages Migratingprojects BitbucketCloud BitbucketServer ClearCase CVS FogBugz GitHub GitLab.com Gitea Jira PerforceHelix Phabricator Repobymanifestfile RepobyURL SVN TFVC Projectimport/export Project/Groupimport/exportratelimits Projectimportachivesizelimits Planandtrackwork Epics Manageepics Linkedepics Epicboards Issues Manageissues Awardemoji Confidentialissues Crosslinkingissues CSVexport CSVimport Designmanagement Duedates Issueboards Multipleassignees Linkedissues ServiceDesk Sortingandorderingissuelists Weight Zoommeetingsinissues Labels Commentsandthreads Customerrelations(CRM) Iterations Milestones Burndownandburnupcharts Requirements Roadmaps Planninghierarchies Tasks Timetracking Wikis Groupwikis Keyboardshortcuts Quickactions Autocompletecharacters Markdown AsciiDoc CSVfiles To-DoList UsingGit Getstarted Terminology InstallingGit CommandlineGit Featurebranchworkflow Featurebranchdevelopment GitLabFlow Addfiletorepository Bisect Cherry-pickacommit Featurebranching Fileediting Gitadd Gitlog Gitstash Mergeconflicts Partialclone Rebase,force-push,mergeconflicts Rollbackcommits Subtree Tags TroubleshootingGit UndowithGit Unstage Usefulcommands Pushoptions Buildyourapplication Repositories Codeowners Snippets Branches Defaultbranch Forkingworkflow Gitattributes GitLFS Jupyternotebookfiles Lockedfiles FileBlame FileHistory Mirroring Bidirectionalmirroring Pullmirroring Pushmirroring Protectedbranches Protectedtags Pushrules Reducerepositorysize SignedCommits SigningcommitsandtagswithX.509 Syntaxhighlighting WebEditor WebIDE Managinglargerepositories Mergerequests Getstarted Approvals Approvalrules Approvalsettings Changes Cherrypickchanges Collaborateacrossforks Commitmessagetemplates Confidentialmergerequests Createmergerequests Draftmergerequests ExportmergerequeststoCSV Externalstatuschecks Mergemethods Squashandmerge Mergerequestdependencies Mergerequestwidgets Mergewhenpipelinesucceeds Mergeconflicts Revertingchanges Reviewingandmanagingmergerequests Suggestions Versions Workflows CI/CD Getstarted CI/CDconcepts MigratefromCircleCI MigratefromJenkins EnableordisableCI/CD Pipelines Scheduledpipelines Triggerapipeline Customizepipelineconfiguration Pipelinearchitectures Pipelineefficiency Pipelineresourcegroups Directedacyclicgraph(DAG) Multi-projectpipelines Parent-childpipelines Mergerequestpipelines Mergedresultspipelines Mergetrains Jobs Choosewhenjobsrun CI/CDjobtoken Accessaterminalforarunningjob Formatscriptsandjoblogs Gitsubmodules Variables Predefinedvariables Wherevariablescanbeused Cacheandartifacts Jobartifacts Pipelineartifacts .gitlab-ci.yml .gitlab-ci.ymlreference OptimizeyourYAMLfiles Validatesyntax PipelineEditor Artifactsreports Includeexamples Workflowexamples Docker RunCI/CDjobsinDockercontainers UseDockertobuildDockerimages UsekanikotobuildDockerimages Services MySQLservice PostgreSQLservice Redisservice GitLabasaservice AutoDevOps Requirements Stages Customize UpgradePostgreSQL UpgradeAutoDeploydependencies DeploytoGKE DeploytoECS DeploytoEC2 Troubleshooting Testing Accessibilitytesting Browserperformancetesting Codequality Failfasttesting Loadperformancetesting Metricsreports Testcases Testcoveragevisualization Unittestreports Unittestreportexamples SSHkeys Externalsecrets Connecttocloudservices AuthenticatingwithHashiCorpVault ConfigureOpenIDConnectinAWS ConfigureOpenIDConnectwithGoogleCloud ChatOps Externalrepositoryintegrations BitbucketCloud GitHub CI/CDexamples DeploymentwithDpl End-to-endtesting NPMwithsemantic-release PHPwithPHPunitandatoum PHPwithNPMandSCP PHPwithLaravelandEnvoy TroubleshootingCI/CD Runners RunnerSaaS Linux macOS VMinstances Codesigning Windows Thescopeofrunners Registerarunner Examples Runnerexecutors Custom libvirt LXD Docker DockerMachine Kubernetes Shell Supportedshells SSH Parallels VirtualBox Configurerunners Scaleafleetofrunners Bestpracticesforlargerepositories Packages&Registries PackageRegistry Composer Conan Debian GoProxy Helm Maven npm NuGet PyPI Rubygems Generic Storeallpackagesinoneproject Monorepoworkflows ReducePackageRegistrystorage ContainerRegistry ReduceContainerRegistrystorage ReduceContainerRegistrydatatransfers InfrastructureRegistry Terraformmoduleregistry DependencyProxy ReduceDependencyProxystorage Secureyourapplication Getstarted SecurityConfiguration ContainerScanning DependencyScanning DependencyScanningAnalyzers DependencyList StaticApplicationSecurityTesting Customizerulesets SASTAnalyzers InfrastructureasCode(IaC)Scanning SecretDetection Post-processingandrevocation DynamicApplicationSecurityTesting(DAST) DASTbrowser-basedcrawler Vulnerabilitychecks DASTAPI DASTTroubleshooting RunDASToffline APIFuzzing HTTPArchiveformat Coverage-guidedfuzztesting SecurityDashboard OfflineEnvironments VulnerabilityReport Viewvulnerabilitiesinapipeline Generatetestvulnerabilities VulnerabilityPage Vulnerabilityseveritylevels CVEIDrequests Policies Scanexecutionpolicies Scanresultpolicies Securityscannerintegration SecureandProtectTerminology Deployandreleaseyourapplication Environmentsanddeployments EnvironmentsDashboard Protectedenvironments Deploymentsafety Deploymentapprovals Rolloutanapplicationincrementally DeploytoAWS DeploytoAmazonECS Releases ReleaseCI/CDexamples ReleaseCLItool Releasefields ReviewApps Featureflags Monitorapplicationperformance ErrorTracking Tracing Productanalytics Incidentmanagement Alerts Escalationpolicies Pagingandnotifications Incidents Linkedresources Integrations Statuspage On-callschedules Metricsdashboard Customdashboards GitLab-definedmetricsdashboards DashboardYAMLproperties Dashboardsettings Paneltypesfordashboards Unitformatsreference Usingvariables Templatesforcustomdashboards Templatingvariablesfordashboards EmbeddingmetricsinGrafana EmbeddingmetricsinMarkdown Metricslibrary MonitoringAWSresources HAProxy Kubernetes NGINX NGINXIngress NGINXIngressVTS Setupalertsformetrics Monitorrunnerperformance Manageyourinfrastructure InfrastructureasCode Terraformstate Terraformintegrationinmergerequests TroubleshootTerraform CreateKubernetesclusters AmazonEKS GoogleGKE Civo ConnectKubernetesclusters GitOpsworkflow ManageKubernetessecrets Trackclusterresources GitLabCI/CDworkflow Manageclusterapplications InstalltheagentforKubernetes WorkwiththeagentforKubernetes Operationalcontainerscanning TroubleshoottheagentforKubernetes MigratetotheagentforKubernetes Runbooks AnalyzeGitLabusage CI/CDanalytics Codereviewanalytics Contributionanalytics DevOpsadoptionbyinstance DevOpsadoptionbygroup Insightsforprojects Insightsforgroups Issueanalyticsforprojects Issueanalyticsforgroups Mergerequestanalytics Productivityanalytics Repositoryanalytics Repositoryanalyticsforgroups Usagetrends Valuestreamanalyticsforprojects Valuestreamanalyticsforgroups Instance-levelanalytics Auditevents Auditeventstreaming Auditreports Metrics ConfigureGitLab ConfigureGrafana GitHubimports GitLabexporter GitLabPrometheusmetrics Selfmonitoringproject IPallowlistendpoints Nodeexporter PGBouncerexporter PostgreSQLserverexporter Prometheus Performancebar Performancemonitoring Redisexporter Registryexporter Usagestatistics Webexporter UsetheAPI RESTAPIresources .gitignore(templates) .gitlab-ci.yml(templates) Accessrequests AgentforKubernetes AlertManagement Appearance(application) Applications Auditevents Avatar Awardemoji Badges(project) Badges(group) Branches Broadcastmessages Commits Composer Conan ContainerRegistry Customattributes Dashboardannotations Debian Debiangroupdistributions Debianprojectdistributions Dependencies DependencyProxy Deploykeys Deploytokens Deployments Discussions Dockerfile(templates) DORA4metrics Environments Epics Errortracking Events Experiments Externalstatuschecks Featureflags Featureflaguserlists Freezeperiods Geonodes GitLabPages GoProxy Groupaccesstokens Groupactivityanalytics GroupImport/Export Grouprelationsexport Grouprepositorystoragemoves Groups Helm Import Instance-levelCI/CDvariables Integrations Invitations Issueboards(project) Issueboards(group) Issues Issues(epic) Issuesstatistics Iterations(project) Iterations(group) Jobs Jobartifacts Keys Labels(project) Labels(group) License Licenses(templates) Linkedepics Links(issue) Links(epic) Managedlicenses Markdown Maven Members Mergerequestapprovals Mergerequestcontextcommits Mergerequests Mergetrains Metadata Migrations(bulkimports) Milestones(project) Milestones(group) Namespaces Notes(comments) Notificationsettings npm NuGet Packages Pagesdomains Personalaccesstokens Pipelinesschedules Pipelinetriggers Pipelines Planlimits Projectaccesstokens Projectaliases Projectimport/export Projectrelationsexport Projectremotemirrors Projectrepositorystoragemoves Projectstatistics Projecttemplates Projectvulnerabilities Projects Protectedbranches Project-levelprotectedenvironments Group-levelprotectedenvironments Protectedtags PyPI Releases Groupreleases Releaselinks Repositories Repositoryfiles Repositorysubmodules Resourcegroup Resourceiterationevents Resourcelabelevents Resourcemilestoneevents Resourcestateevents Resourceweightevents Rubygems Runners SCIM Search Settings(application) Sidekiqmetrics Sidekiqqueues Snippetrepositorystoragemoves Snippets Snippets(project) Statistics(application) Suggestions Systemhooks Tags To-Dolists Topics ServiceData Users User-starredmetricsdashboards Variables(project) Variables(group) Version VisualReviewdiscussions Vulnerabilities Vulnerabilityexport VulnerabilityFindings Wikis(group) Wikis(project) OpenAPI GraphQL GetstartedusingGraphQL GraphQLreference Createauditreport(example) Identifyissueboards(example) Queryusers(example) Usecustomemojis(example) Removeditems Lint.gitlab-ci.yml GitLabasanOAuth2provider ContributetoGitLabdevelopment ContributetoGitLab Architecture Documentation Styleguide CreatingaGraphQLexamplepage RESTfulAPIstyleguide Recommendedwordlist Topictypes Process Testing Sitearchitecture Folderstructure Globalnavigation Documentingproductversions Deploymentprocess Documentationreviewapps Redirects DevelopmentRaketasks MassinsertRailsmodels Developmentprocesses Changelogentries ChatOpsonGitLab.com Codereviewguidelines Communityroles Dangerbot Deprecationguidelines FIPScompliance Experiments Implementingexperiments Testingexperiments Experimentcodereviews Experimentrollouts FeatureflagsforGitLabdevelopment Controllingfeatureflags Documentingfeatureflags FeatureflagsAPI Framework-DeclarativePolicy Issuesworkflow Mergerequestconcepts Mergerequestworkflow Securepartneronboardingprocess Testingstandardsandstyles Flakytests Frontendtestingstandardsandstyleguidelines Reviewapps Smoketests Testingbestpractices Testinglevels TestingRailsmigrations TestingRaketasks Testing(contract) Writingconsumertests Writingprovidertests Testing(endtoend) Beginner'sguidetowritingend-to-endtests Bestpracticeswhenwritingend-to-endtests Dynamicelementvalidation FlowsinGitLabQA PageobjectsinGitLabQA ResourceclassinGitLabQA Styleguideforwritingend-to-endtests Testingwithfeatureflags Troubleshooting TranslateGitLab Externalization Translation Proofreading Merging Developmentstyleguides Frontendstyleguides APIstyleguide Gostandardsandstyleguidelines GraphQLAPIstyleguide Guidelinesforshellcommands HTMLstyleguide JavaScriptstyleguide Newlinesstyleguide Pythondevelopmentguidelines Rubystyleguide SCSSstyleguide Shellscriptingstandardsandstyleguidelines Vuestyleguide Featuredevelopment Approvalrulesdevelopment AuditEventdevelopment AutoDevOpsdevelopment Built-inprojecttemplates CI/CDdevelopment Documentingkeywords ContributetotheCI/CDschema CI/CDtemplatedevelopment PipelineWizard Codeintelligence CodeSandboxdevelopmentenvironment Create-SourceCodebackend Gitalytouchpoints SourceCodeRESTendpoints Databasedevelopment Avoidingdowntimeinmigrations Backgroundmigrations Casestudy-filteringbylabel Casestudy-namespacesstoragestatistics CImirroredtables DatabaseLabandPostgres.ai Databasereviewguidelines Databasecheck-migrationsjob Deleteexistingmigrations Layoutandaccesspatterns Migrationsstyleguide Paginationguidelines Paginationperformanceguidelines Keysetpagination Post-deploymentmigrations QuerycommentswithMarginalia QueryRecorder SQLguidelines Swappingtables Tablepartitioning TroubleshootingandDebuggingDatabase UnderstandingEXPLAINplans Multipledatabases LooseForeignKeys DesignandUI Developerguidetologging Distributedtracing Frontenddevelopment Accessibility Architecture Axios ContentEditor Darkmode Dependencies Designanti-patterns Designpatterns Developmentprocess Eventtracking Emojis FrontendFAQ GraphQL HAML IconsandSVGillustrations Keyboardshortcuts Logging Mergerequestwidgetextensions Performance Principles Registryarchitecture Security Sourceeditor Tooling Troubleshooting ViewComponent Vuex Vue Vue3migration Widgets Geodevelopment Geoframework Geoproxying GitLFS Gitobjectdeduplication Gitalydevelopment GitLabFlavoredMarkdown(GLFM)developerdocumentation GitLabFlavoredMarkdown(GLFM)specificationguide GitLabgroupmigration GraphQLdevelopment GraphQLauthorization GraphQLBatchLoader GraphQLpagination GraphQLPro Import/Export Integrations InternalAPI InternalallowedAPI Internalusers Issuable-likeRailsmodelsutilities Issuetypes Jenkinsinlocalenvironments Jiradevelopmentenvironment Kubernetesintegration Observabilityforstagegroups Dashboards Stagegroupdashboard Errorbudgetdetail Packagedevelopment Packagesettings Packagestructure Supportnewformats Debianrepository Permissions ProductQualifiedLead(PQL)guide Real-timefeatures ServicePingguide Metricslifecycle ImplementServicePing Metricsinstrumentation Metricsdictionaryguide Metricsdictionary MetricsPerformanceIndicator Reviewguidelines Troubleshooting Sidekiqdevelopment Compatibilityacrossupdates Jobidempotencyandjobdeduplication Limitedcapacityworker Logging Workerattributes Snowplow ImplementSnowplow SnowplowInfrastructure Schemas Eventdictionaryguide Eventdictionary Reviewguidelines Troubleshooting SpamprotectionandCAPTCHA Modelandservices RESTAPIspamprotection GraphQLAPIspamprotection WebUIspamprotection Exploratorytesting Uploads Addingnewuploads ValueStreamAnalytics Verifystagedevelopment Wikis Workitemsandworkitemtypes Workhorse AddingnewfeaturestoWorkhorse Configuration FeaturesthatrelyonWorkhorse Websocketchannelsupport Prometheusmetrics Workspace GitLabDevelopmentKit GitLabDesignSystem GitLabprojectpipelines ContributetoOmnibusGitLab Getstarted Buildlocally BuildOmnibusGitLabpackage Buildall-in-oneDockerimage InformationforGitLabteammembers Setupadevelopmentenvironment CIvariables Changepackagebehavior ChangeYAMLconfigoptions Adddeprecationmessages Addnewgitlab-ctlcommands Addnewservices Addnewsoftwaredefinitions Createpatches Addorremoveconfigurationoptions ManagePostgreSQLversions Omnibusmirror VersionformatforthepackagesandDockerimages Pipelines Workwithpublic_attributes.json UpgradeChef Handlevulnerabilities Handlebrokenmasterpipelines DeprecateandremovesupportforanOS ContributetoGitLabPages ContributetoGitLabRunner ReviewGitLabRunner AddnewWindowsversionsupportforDockerexecutor ContributetoGitLabHelmCharts ArchitectureofCloudnativeGitLabHelmcharts BackupandRestore Goals Architecture DesignDecisions ResourceUsage Environmentsetup Styleguide Versioningandrelease Helpuslearnaboutyourcurrentexperiencewiththedocumentation.Takethesurvey. × Gitrebase Beforerebasing Regularrebase RebasefromtheGitLabUIInteractiverebaseForce-pushIntroductiontoGitrebaseandforce-push Thisguidehelpsyoutogetstartedwithrebasing,force-pushing,andfixing mergeconflictslocally.Beforedivingintothisdocument,makesureyouarefamiliarwithusing Gitthroughthecommandline.Gitrebase Rebasingisaverycommonoperationin Git,andhastheseoptions: Regularrebase. Interactiverebase.Beforerebasing caution gitrebaserewritesthecommithistory.Itcanbeharmfultodoitin sharedbranches.Itcancausecomplexandhardtoresolve mergeconflicts.In thesecases,insteadofrebasingyourbranchagainstthedefaultbranch, considerpullingitinstead(gitpulloriginmaster).Ithasasimilar effectwithoutcompromisingtheworkofyourcontributors.It’ssafertobackupyourbranchbeforerebasingtomakesureyoudon’tlose anychanges.Forexample,considerafeaturebranch calledmy-feature-branch: Openyourfeaturebranchintheterminal: gitcheckoutmy-feature-branch Checkoutanewbranchfromit: gitcheckout-bmy-feature-branch-backup Gobacktoyouroriginalbranch: gitcheckoutmy-feature-branch Nowyoucansafelyrebaseit.Ifanythinggoeswrong,youcanrecoveryour changesbyresettingmy-feature-branchagainstmy-feature-branch-backup: Makesureyou’reinthecorrectbranch(my-feature-branch): gitcheckoutmy-feature-branch Resetitagainstmy-feature-branch-backup: gitreset--hardmy-feature-branch-backup Ifyouaddedchangestomy-feature-branchaftercreatingthebackupbranch, youlosethemwhenresetting.Regularrebase Witharegularrebaseyoucanupdateyourfeaturebranchwiththedefault branch(oranyotherbranch). ThisstepisimportantforGit-baseddevelopmentstrategies.Youcan ensureyournewchangesdon’tbreakany existingchangesaddedtothetargetbranchafteryoucreatedyourfeature branch.Forexample,toupdateyourbranchmy-feature-branchwithyour defaultbranch(here,usingmain): Fetchthelatestchangesfrommain: gitfetchoriginmain Checkoutyourfeaturebranch: gitcheckoutmy-feature-branch Rebaseitagainstmain: gitrebaseorigin/main Force-pushtoyourbranch.Whenyourebase: Gitimportsallthecommitssubmittedtomainafterthe momentyoucreatedyourfeaturebranchuntilthepresentmoment.Gitputsthecommitsyouhaveinyourfeaturebranchontopofall thecommitsimportedfrommain:Youcanreplacemainwithanyotherbranchyouwanttorebaseagainst,for example,release-10-3.Youcanalsoreplaceoriginwithotherremote repositories,forexample,upstream.Tocheckwhatremotesyouhavelinkedtoyourlocal repository,youcanrungitremote-v.Iftherearemergeconflicts,Gitpromptsyoutofix thembeforecontinuingtherebase.Tolearnmore,checkGit’sdocumentationonrebasing andrebasingstrategies.RebasefromtheGitLabUI Youcanrebaseyourfeaturebranchdirectlyfromthemergerequestthrougha quickaction, ifalloftheseconditionsaremet: Nomergeconflictsexistforyourfeaturebranch.YouhavetheDeveloperroleforthesourceproject.Thisrolegrantsyou permissiontopushtothesourcebranchforthesourceproject.Ifthemergerequestisinafork,theforkmustallowcommits frommembersoftheupstreamproject.TorebasefromtheUI: Gotoyourmergerequest.Type/rebaseinacomment.SelectComment.GitLabschedulesarebaseofthefeaturebranchagainstthedefaultbranchand executesitassoonaspossible.Theuserperformingtherebaseactionisconsidered auserthataddedcommitstothemergerequest.Whenthemergerequestapprovalssetting Preventapprovalsbyuserswhoaddcommits isenabled,theusercan’talsoapprovethemergerequest.Interactiverebase Youcanuseinteractiverebasetomodifycommits.Forexample,amendacommit message,squash(joinmultiplecommitsintoone),edit,ordelete commits.Usearebaseforchangingpastcommitmessages, andorganizingthecommithistoryofyourbranchtokeepitclean. noteKeepingthedefaultbranchcommithistorycleandoesn’trequireyouto manuallysquashallyourcommitsbeforemergingeverymergerequest. WithSquashandMerge, GitLabdoesitautomatically.Whenyouwanttochangeanythinginrecentcommits,useinteractive rebasebypassingtheflag--interactive(or-i)totherebasecommand.Forexample,ifyouwanttoeditthelastthreecommitsinyourbranch (HEAD~3),run:gitrebase-iHEAD~3 Gitopensthelastthreecommitsinyourterminaltexteditoranddescribes alltheinteractiverebaseoptionsyoucanuse.Thedefaultoptionispick, whichmaintainsthecommitunchanged.Replacethekeywordpickaccordingto theoperationyouwanttoperformineachcommit.Todoso,edit thecommitsinyourterminal’stexteditor.Forexample,withVimasthetexteditorin amacOS’sZshshell,youcansquashorfixup(combine)allthreecommits: Pressi onyourkeyboardtoswitchtoVim’seditingmode.Useyourkeyboardarrowstoeditthesecondcommitkeyword frompicktosquashorfixup(orsorf).Dothesametothethirdcommit. Thefirstcommitshouldbeleftunchanged(pick)aswewanttosquash thesecondandthirdintothefirst.PressEscapetoleavetheeditingmode.Type:wqto“write”(save)and“quit”.Whensquashing,Gitoutputsthecommitmessagesoyouhaveachancetoeditit: Alllinesstartingwith#areignoredandnotincludedinthecommit message.Everythingelseisincluded.Toleaveitasitis,type:wq.Toeditthecommitmessage:switchtothe editingmode,editthecommitmessage,andsaveitasyoujustdid.Ifyouhaven’tpushedyourcommitstotheremotebranchbeforerebasing, pushyourchangesnormally.Ifyouhadpushedthesecommitsalready, force-pushinstead.Thestepsforeditingthroughthecommandlinecanbeslightly differentdependingonyouroperatingsystemandtheshellyou’reusing.SeeNumerousundopossibilitiesinGit foradeeperlookintointeractiverebase.Force-push Whenyouperformmorecomplexoperations,forexample,squashcommits,resetor rebaseyourbranch,youmustforceanupdatetotheremotebranch. Theseoperationsimplyrewritingthecommithistoryofthebranch. Toforceanupdate,passtheflag--forceor-ftothepushcommand.For example:gitpush--forceoriginmy-feature-branch Forcinganupdateisnotrecommendedwhenyou’reworkingonshared branches.Alternatively,youcanpasstheflag--force-with-lease instead,asitissafer.Thisflagpreservesanynewcommitsaddedtotheremote branchbyotherpeople:gitpush--force-with-leaseoriginmy-feature-branch Ifthebranchyouwanttoforce-pushisprotected, youcan’tforcepushtoitunlessyoueither: Unprotectit. Allowforcepush toit.Thenyoucanforcepushandprotectitagain. Help&feedback DocsEditthispage tofixanerrororaddanimprovementinamergerequest. Createanissue tosuggestanimprovementtothispage. Showandpostcomments toreviewandgivefeedbackaboutthispage. ProductCreateanissue ifthere'ssomethingyoudon'tlikeaboutthisfeature. Proposefunctionality bysubmittingafeaturerequest. JoinFirstLook tohelpshapenewfeatures. FeatureavailabilityandproducttrialsViewpricing toseeallGitLabtiersandfeatures,ortoupgrade. TryGitLabforfree withaccesstoallfeaturesfor30days. GetHelp Ifyoudidn'tfindwhatyouwerelookingfor, searchthedocs. Ifyouwanthelpwithsomethingspecificandcouldusecommunitysupport, postontheGitLabforum. Forproblemssettinguporusingthisfeature(dependingonyourGitLab subscription). Requestsupport



請為這篇文章評分?