Как сделать коммит pycharm
Перейти к содержимому

Как сделать коммит pycharm

  • автор:

Edit Git project history

Git allows you to edit your project history. This is useful when you’re working on a feature branch and want to clean it up and make it look the way you want before you share it with others. For example, you can edit commit messages, squash together smaller commits related to the same functionality, or split a commit that contains unrelated changes into separate commits, add changes to a previous commit, and so on.

Avoid modifying the history for a remote branch with multiple contributors unless absolutely necessary, for example, if you accidentally pushed some sensitive data.

Pushing modifications that rewrite a branch history to the remote repository will be rejected to prevent data loss, so you will have to force push your changes.

You cannot modify the history for protected branches where push —force is not allowed (configure protected branches in the Version Control | Git page of the IDE settings Control+Alt+S . Note that if a branch is marked as protected on GitHub, PyCharm will automatically mark it as protected when you check it out.

Also, you cannot perform actions that modify a branch history for commits that are not contained in the branch currently checked out.

Edit a commit message

If the only thing you need to change is a commit message, you can edit it before you push this commit.

  1. Right-click the commit whose message you want to edit in the Log tab of the Git tool window Alt+9 and select Edit Commit Message from the context menu, or press F2 .
  2. In the dialog that opens, enter a new commit message and click OK .

Amend the previous commit

Sometimes you may commit too early and forget to add some files, or notice an error in the last commit that you want to fix without creating a separate commit.

You can do this by using the Amend commit option that appends staged changes to the previous commit. As a result, you end up with a single commit instead of two different ones.

  1. In the Commit tool window Alt+0 , select the modified files containing the changes you want to add to the previous commit.
  2. Select the Amend checkbox so that the Commit button changes to Amend Commit and click it.

Amend any earlier commit

If you need to add changes to any earlier commit instead of committing them separately, you can do this by using the fixup or the squash action. Both commands append staged changes to the selected commit, but handle commit messages differently:

  • squash adds the new commit message to the original commit
  • fixup discards the new commit message, leaving only the message from the original commit

Both commands require a rebase because they change the commit hashes.

  1. In the Commit tool window Alt+0 , select the modified files containing the changes you want to append to an earlier commit.
  2. In the Log tab of the Git tool window Alt+9 , right-click the commit that you want to modify with your local changes and select Fixup or Squash Into from the context menu.
  3. Modify the commit message if you’ve chosen to squash changes.
  4. Click the arrow on the Commit button and choose Commit and Rebase .

Squash commits

If you need to meld any two commits related to the same functionality, you can squash them into one for the sake of cleaner branch history.

  1. In the Log tab of the Git tool window Alt+9 select the commits that you want to combine into one and choose Squash Commits from the context menu.
  2. In the dialog that opens, edit the commit message (by default, it contains the messages from both commits) and click OK .
  3. Push Control+Shift+K the changes to the remote branch.

Drop a commit

You can discard a pushed commit in the current branch without creating an additional commit that reverts the changes.

  • Select a commit you want to discard in the Log view and choose Drop Commit from the context menu.

Edit project history by performing interactive rebase

With Git integration in PyCharm, you can edit project history for the sake of making it linear and meaningful by performing interactive rebase . This allows you to clean up the history of commits by altering individual commits, changing their order, squashing commits into one, skipping commits that contain extraneous changes, and so on before you integrate changes from your feature branch to another branch.

Edit the history of the current branch

PyCharm allows you to edit the commits history in the current branch before you apply the changes to a different branch.

  1. Open the Git tool window Alt+9 and switch to the Log tab.
  2. Filter the log so that it only displays commits from the current branch: Filter log by branch
  3. Select the oldest commit in the series of commits that you want to edit, right-click it and choose Interactively Rebase from Here . The Interactive Rebase dialog will be displayed containing the list of all commits in the current branch that were made after the selected commit: Interactive Rebase dialogIf the Interactively Rebase from Here option is disabled, this may be due to one of the following reasons:
    • the selected commit has several parents
    • the selected commit is not in the current branch
    • the selected commit is pushed to a protected branch

To identify the reason, hover over the action in the context menu and look for the message in the status bar:

Status bar message

  • You can perform the following changes to the branch history:
    • Change the order in which commits should be applied: use the and buttons to move commits up and down the list.
    • Pick a commit : this is the default state for all commits. If you need to undo an action you’ve already taken on a commit, click Pick so that this commit is applied as is.
    • Edit : click Stop to Edit so that when you start the rebase, you stop at this commit to be able to edit it. When rebase is stopped at a commit, a notification pops up in the bottom-right corner of the PyCharm window letting you continue or abort the rebase: the rebase status notificationYou can modify this commit using the context actions (such as Revert , Undo , Amend , and so on before continuing the rebase. If you don’t perform any actions, this commit will be applied as is. If you’ve closed the notification, from the main menu choose Git | Continue rebase to resume it.
    • Reword the commit message : click Reword or double-click a commit and edit the text in the mini-editor that opens.
    • Combine two commits into one : select the commit you want to meld into the previous one and click Squash or the arrow next to the Squash button and then Fixup . If you click Squash , by default the messages from the two commits will be combined, so if you don’t modify the resulting commit message this action will be reflected in the branch history. If you click Fixup , the commit message of the fixup commit will be discarded, so this change will be invisible in the branch history. In both cases, you will be able to edit the commit message in the mini editor that opens when you apply one of these actions.
    • Ignore a commit : click Drop so that the changes from the selected commit are not applied.
    • Undo all changes : click Reset to discard all actions you’ve applied to the commits.

    As a result, the Rebasing Commits dialog shows a graph illustrating all actions you’ve applied to commits in your branch, so that you can review them before starting the rebase:

    Interactive Rebase graph

  • Click Start Rebasing .
  • Edit a branch history and integrate it into another branch

    PyCharm allows you to rebase a branch on top of another branch and edit the source branch history before you apply the changes.

    1. From the main menu select Git | Rebase : Git rebase dialog
    2. Click Modify options and choose —interactive .
    3. From the list, select the target branch onto which you want to rebase the current branch: Choose target branch in the Git rebase dialog
    4. If you need to rebase the source branch starting from a particular commit instead of rebasing the entire branch, click Modify options and choose —onto . In the source branch field, enter the hash of the commit starting from which you want to apply the current branch to the new base: Specify commit hash with --ontoTo copy a commit hash, select it in the Log , right-click it and choose Copy Revision Number .
    5. If the branch you want to rebase is not currently checked out, click Modify options , click Select another branch to rebase , and choose a branch from the list that appears: Choose the branch you want to rebasePyCharm will check out this branch before starting the rebase operation.
    6. If you want to rebase all commits reachable in the branch, click Modify options and choose —root (for more information on this option, refer to git-rebase).
    7. If you need to keep empty commits, which are commits that do not change anything from their parent, click Modify options and choose —keep-empty (for more information on this option, refer to git-rebase).
    8. Click Rebase . The Interactive Rebase dialog will be displayed containing the list of all commits in the current branch that were made after the selected commit. Interactive Rebase dialog
    9. You can perform the following changes to the branch history:
      • Change the order in which commits should be applied: use the and buttons to move commits up and down the list.
      • Pick a commit : this is the default state for all commits. If you need to undo an action you’ve already taken on a commit, click Pick so that this commit is applied as is.
      • Edit : click Stop to Edit so that when you start the rebase, you stop at this commit to be able to edit it. When rebase is stopped at a commit, a notification pops up in the bottom-right corner of the PyCharm window letting you continue or abort the rebase: the rebase status notificationYou can modify this commit using the context actions (such as Revert , Undo , Amend , and so on before continuing the rebase. If you don’t perform any actions, this commit will be applied as is. If you’ve closed the notification, from the main menu choose Git | Continue rebase to resume it.
      • Reword the commit message : click Reword or double-click a commit and edit the text in the mini-editor that opens.
      • Combine two commits into one : select the commit you want to meld into the previous one and click Squash or the arrow next to the Squash button and then Fixup . If you click Squash , by default the messages from the two commits will be combined, so if you don’t modify the resulting commit message this action will be reflected in the branch history. If you click Fixup , the commit message of the fixup commit will be discarded, so this change will be invisible in the branch history. In both cases, you will be able to edit the commit message in the mini editor that opens when you apply one of these actions.
      • Ignore a commit : click Drop so that the changes from the selected commit are not applied.
      • Undo all changes : click Reset to discard all actions you’ve applied to the commits.

    As a result, the Rebasing Commits dialog shows a graph illustrating all actions you’ve applied to commits in your branch, so that you can review them before starting the rebase:

    Interactive Rebase graph

  • Click Start Rebasing .
  • Set up a Git repository

    When you clone an existing Git repository or put an existing project under Git version control, PyCharm automatically detects if Git is installed on your computer. If the IDE can’t locate a Git executable, it suggests downloading it.

    PyCharm supports Git from the Windows Subsystem for Linux 2 (WSL2), which is available in Windows 10 version 2004.

    If Git is not installed on Windows, PyCharm searches for Git in WSL and uses it from there. Also, PyCharm automatically switches to Git from WSL for projects that are opened when you use the \\wsl$ path.

    If you need to manually configure PyCharm to use Git from WSL, go to the Version Control | Git page of the IDE settings Control+Alt+S , click the Browse icon in the Path to Git executable field, and select Git from WSL via the \wsl$ path, for example, \\wsl$\debian\usr\bin\git .

    Check out a project from a remote host (git clone)

    PyCharm allows you to check out (in Git terms, clone ) an existing repository and create a new project based on the data you’ve downloaded.

    Getting a project from GitHub

    1. To start cloning a Git repository, do one of the following:
      • If the version control integration is already enabled, go to Git | Clone .
      • If the version control integration is not enabled yet, go to VCS | Get from Version Control . Alternatively, go to File | New | Project from Version Control .
      • If no project is currently open, click Get from VCS on the Welcome screen.
    2. In the Get from Version Control dialog, specify the URL of the remote repository you want to clone or select one of the VCS hosting services on the left. If you are already logged in to the selected hosting service, completion will suggest the list of available repositories that you can clone.
    3. Click Clone . If you want to create a project based on the sources you have cloned, click Yes in the confirmation dialog. Git root mapping will be automatically set to the project root directory. If your project contains submodules, they will also be cloned and automatically registered as project roots.
    4. In the Trust and Open Project »? project security dialog, select the way you want to open the project: Trust Project or Preview in Safe Mode .

    Put an existing project under Git version control

    You can create a local Git repository based on the existing project sources.

    Associate the entire project with a single Git repository

    Notification prompting to select how to treat configuration files

    1. Open the project that you want to put under Git.
    2. Press Alt+` to open the VCS Operations Popup and select Enable Version Control Integration . Alternatively, go to VCS | Enable Version Control Integration .
    3. Choose Git as the version control system and click OK . The entire project will then be associated with a single Git directory, so there is no need to add each file to the Git directory individually.
    4. After VCS integration is enabled, PyCharm will ask you whether you want to share project settings files via VCS. You can choose Always Add to synchronize project settings with other repository users who work with PyCharm.

    If there is no Enable Version Control Integration option available in the VCS Operations Popup , it means that Git version control is already enabled for the project.

    Associate different directories within the project with different Git repositories

    1. Open the project that you want to put under Git.
    2. In the main menu, go to VCS | Create Git Repository .
    3. In the dialog that opens, specify the directory where a new Git repository will be created. Git does not support external paths, so if you choose a directory that is outside your project root, make sure that the folder where the repository is going to be created also contains the project root.
    4. If you are creating multiple Git repositories inside the project structure, repeat the previous steps for each directory.

    After you have initialized a Git repository for your project, you need to add project files to the repository.

    Add files to the local repository

    1. In the Commit tool window Alt+0 , expand the Unversioned Files node.
    2. Select the files you want to add to Git or the entire changelist and press Control+Alt+A or choose Add to VCS from the context menu. You can also add files to your local Git repository from the Project tool window: select the files you want to add, and press Control+Alt+A or choose Git | Add from the context menu.

    When Git integration is enabled in your project, PyCharm suggests adding each newly created file under Git, even if it was added from outside PyCharm. You can change this behavior in the Version Control | Confirmation page of the IDE settings Control+Alt+S . If you want certain files to always remain unversioned, you can ignore them.

    If you attempt to add a file that’s on the .gitignore list, PyCharm will suggest force-adding it. Clicking Cancel in the confirmation dialog only cancels force-adding ignored files – all other files will be added to the Git repository.

    Exclude files from version control (ignore)

    Sometimes you may need to leave certain files unversioned. These can be VCS administration files, artifacts of utilities, backup copies, and so on. You can ignore files through PyCharm, and the IDE will not suggest adding them to Git and will highlight them as ignored.

    You can only ignore unversioned files, that is, files that you see in the Unversioned Files changelist. If a file is added to Git but not committed, you can right-click it in the Changes view and choose Rollback .

    Git lets you list ignored file patterns in two kinds of configuration files:

    • .git/info/exclude file. Patterns listed in this file only apply to the local copy of the repository. This file is created automatically when you initialize or check out a Git repository.
    • One or more .gitignore files in the VCS root directory and its subdirectories. These files are checked into the repository so that the ignore patterns in them are available to the entire team. Therefore, it is the most common place to store the ignored file patterns. If there is no .gitignore file in the VCS root directory, you can right-click anywhere in the Project tool window, choose New | File , and type .gitignore in the New File dialog. To create a .gitignore file in Windows Explorer, create a file named .gitignore. and Windows will rename it automatically to .gitignore .

    Add files to .gitignore or .git/info/exclude

    1. Decide what kind of Git configuration file you are going to use to ignore files. If in doubt, use .gitignore .
    2. Locate the unversioned file or folder you want to ignore in the Changes view or in the Project tool window. File colors in these views help you identify the status of the file.
    3. Right-click the selection and choose Git | Add to .gitignore or Git | Add to .git/info/exclude . File colors in these views help you identify the status of the file.

    If you need to exclude files by a certain pattern or type, you can edit the .gitignore or .git/info/exclude file directly. See .gitignore patterns format.

    If you want ignored files to be also displayed in the Changes view, click on the toolbar and select Show Ignored Files .

    Add a remote repository

    If you created a Git repository based on local sources, you need to add a remote repository to be able to collaborate on your Git project, as well as to eliminate the risks of storing your whole codebase locally. You push changes to a remote repository when you need to share your work and pull data from it to integrate changes made by other contributors into your local repository version.

    If you have cloned a remote Git repository, for example, from GitHub, the remote is configured automatically, and you do not have to specify it when you want to sync with it. The default name Git gives to the remote you’ve cloned from is origin .

    Define a remote

    1. Create an empty repository on any Git hosting, such as Bitbucket or GitHub. You can create a repository on GitHub without leaving PyCharm: see Share a project on GitHub.
    2. Invoke the Push dialog when you are ready to push your commits by selecting Git | Push from the main menu, or press Control+Shift+K .
    3. If you haven’t added any remotes so far, the Define remote link will appear instead of a remote name. Click it to add a remote.
    4. In the dialog that opens, specify the remote name and the URL where it will be hosted, and click OK .

    Add a second remote

    In some cases, you also need to add a second remote repository. This may be useful, for example, if you have cloned a repository that you do not have write access to and are going to push changes to your own fork of the original project. Another common scenario is that you have cloned your own repository, which is somebody else’s project fork, and you need to synchronize with the original project and fetch changes from it.

    1. In the main menu, go to Git | Manage Remotes . The Git Remotes dialog will open.
    2. Click the Add button on the toolbar or press Alt+Insert .
    3. In the dialog that opens, specify the remote name and URL and click OK .
    • To edit a remote (for example, to change the name of the original project that you have cloned), right-click the remote branch in the Branches pane of the Git Log tool window and select Edit Remote from the context menu. You can also edit a remote from the Push Dialog by clicking its name.
    • To remove a repository that is no longer valid, right-click it in the Branches pane of the Git Log tool window, and select Remove Remote from the context menu.

    Learn more from this video:

    Commit and push changes to Git repository

    After you’ve added new files to the Git repository, or modified files that are already under Git version control, and you are happy with their current state, you can share the results of your work. This involves committing them locally to record the snapshot of your repository to the project history, and then pushing them to the remote repository so that they become available to others.

    Set your Git username

    Git needs to know your username to associate commits with an identity. If you have not set your username, PyCharm will prompt you to specify it when you first attempt to commit changes.

    • Open the Terminal and execute one of the following commands:
      • To set a name for every Git repository on your machine, use $ git config —global user.name «John Smith»
      • To set a name for a single repository, use $ git config user.name «John Smith»

      Commit changes locally

      1. Open the vertical Commit tool window Alt+0 located on the left: Commit tool window
      2. As your changes are ready to be committed, select the corresponding files or an entire changelist. If you press Control+K , the entire active changelist will be selected. You can also select files under the Unversioned Files node — PyCharm will stage and commit these files in one step.
      3. If you want to append local changes to the latest commit instead of creating a separate commit, select the Amend option.
      4. Enter the commit message. You can click to choose from the list of recent commit messages. You can also edit the commit message later before you’ve pushed the commit. You can customize commit message rules on the Version Control | Commit page of the IDE settings Control+Alt+S . There is also a quick-fix and the Reformat action that wrap a long line or reformat the message. You can also define a commit template that will be used as the default commit message. Specify the boilerplate text you want to use in a .txt file and execute the following command in the terminal to add it to your Git config: git config —local commit.template
      5. If you need to perform commit checks, upload files to a server after the commit, or commit with advanced options, click in the bottom-right corner: advanced commit options popupThe following options are available:
        • Author : if you are committing changes made by another person, you can specify the author of these changes.
        • Sign-off commit : select if you want to sign off your commit to certify that the changes you are about to check in have been made by you, or that you take the responsibility for the code you’re committing. When this option is enabled, the following line is automatically added at the end of the commit message: Signed off by:
        • In the Commit Checks area, select the actions you want PyCharm to perform while committing the selected files to the local repository. The following options are available:
          • Reformat code : perform code formatting according to the Project Code Style settings.
          • Rearrange code : rearrange your code according to the arrangement rules preferences.
          • Optimize imports : remove redundant import statements.
          • Analyze code : analyze modified files while committing them. Click Choose profile to select an inspection profile from which the IDE will run inspections.
          • Check TODO () : Review the TODO items matching the specified filter. Click Configure to choose an existing TODO filter, or open the TODO settings page and define a new filter to be applied.
          • Cleanup : batch-apply quick-fixes from code cleanup inspections. Click Choose profile to select a profile from which the IDE will run inspections.
          • Run Tests : run tests as commit checks. Click Choose configuration near Run Tests and select which configuration you want to run.
          • Update copyright : add or update a copyright notice according to the selected copyright profile — scope combination.
        • In the After Commit area, you can select the server access configuration or a server group to use for uploading the committed files to a local or remote host, a mounted disk, or a directory. For more information, refer to Deploy. The following options are available:
          • Run tool : select the external tool that you want PyCharm to launch after the selected changes have been committed. You can select a tool from the list, or click the Browse button and configure an external tool in the External Tools dialog that opens.
          • Upload files to : select the server access configuration or a server group to use for uploading the committed files to a local or remote host, a mounted disk, or a directory.
            • To suppress uploading, choose None .
            • To add a server configuration to the list, click and fill in the required fields in the Add Server dialog that opens.

      The list is only available if the FTP/SFTP/WebDAV Connectivity plugin is enabled.

      Commit part of a file

      Sometimes when you make changes that are related to a specific task, you also apply other unrelated code modifications that affect the same file. Including all such changes into one commit may not be a good option, since it would be more difficult to review, revert, cherry-pick them, and so on.

      PyCharm lets you commit such changes separately in one of the following ways:

      • select modified code chunks and lines that you want to include in a commit right in the Commit Changes dialog and leave other changes pending so that you can commit them later.
      • put different code chunks into different changelists on the fly, when you edit code, and then commit these changelists separately. You can also create a new changelist and make it active, then all changes that you make after that will fall into that changelist, while any modifications you made before that will stay where they are.

      Select chunks and specific lines you want to commit

      1. Open the Commit tool window Alt+0 .
      2. To display the differences between the repository version and the local version of the selected file, in the Commit tool window Alt+0 , select Show Diff from the context menu or press Control+D .
      3. Select the checkbox next to each chunk of modified or newly added code that you want to commit, and leave other changes unselected: PyCharm: Partial commit dialogYou can also select Move to Another Changelist from the context menu of a modified chunk to split changes between different changelists that you can commit separately. To assign a custom shortcut for this action, look for the Move Lines to Another Changelist action under Version Control Systems on the Keymap page of the IDE settings Control+Alt+S .
      4. If you want to commit only a specific line from a chunk, right-click the line you want to include and select Split Chunks and Include Selected Lines into Commit . PyCharm: An option to include current line in commit in the context menuAlternatively, hover over the gutter and select or clear the checkbox next to the line you want to include in the commit or exclude from it.
      5. Click Commit . Unselected changes will stay in the current changelist, so that you can commit them separately.

      Put changes into different changelists

      Partial commit changelists

      1. When you make a change to a file in the editor, click the corresponding change marker in the gutter. If there are no change markers in the gutter, make sure the Highlight modified lines in the gutter option is enabled on the Editor | General page of the IDE settings Control+Alt+S .
      2. In the toolbar that appears, select the target changelist for the modified code chunk (or create a new changelist):
      3. Commit each changelist separately.

      Use the Git staging area to commit changes

      If you are more used to the concept of staging changes for commit instead of using changelists where modified files are staged automatically, press Control+Alt+S to open the IDE settings and select Version Control | Git , then select the Enable staging area checkbox.

      The Commit tool window will now look as follows:

      Git staging area

      Using the staging area allows you to easily commit changes to the same file separately (including overlapping changes), and see which changes are already staged without switching focus from the editor.

      When you switch from using changelists to Git staging area, all existing changelists are saved. You can switch between the two modes without losing your changes.

      Stage changes for commit

      1. Do one of the following:
        • To stage an entire file, in the Commit tool window Alt+0 , select this file and click on the right next to it or press Control+Alt+A . Stage from the Commit tool window
        • To stage a specific chunk inside a file, in the editor click the change marker in the gutter next to the modified chunk and click Stage . Stage change from the editorStaged changes (including changes staged from outside PyCharm) are marked with a border-shaped change marker in the editor: Gutter marker for staged changes
        • To stage granular changes like a single line instead of a code chunk, or even one of several changes to a single line, in the Commit tool window Alt+0 , select the file containing the change and choose Compare HEAD, Staged and Local Versions from the context menu. This will open a three-way Diff Viewer where the left pane shows the repository version, the right pane shows the local version, and the central pane is a fully-functional editor where you can make the changes you want to stage. Stage changes interactively
      2. When ready, commit the changes as described in Commit changes locally.

      Push changes to a remote repository

      Before pushing your changes, sync with the remote and make sure your local copy of the repository is up to date to avoid conflicts.

      PyCharm allows you to upload changes from any branch to its tracked branch or to any other remote branch.

      1. Do one of the following:
        • To push changes from the current branch press Control+Shift+K or choose Git | Push from the main menu.
        • To push changes from any local branch that has a remote, select this branch in the Branches popup and choose Push from the list of actions.

      The Push Commits dialog opens showing all Git repositories (for multi-repository projects) and listing all commits made in the current branch in each repository since the last push.

      If you have a project that uses multiple repositories that are not controlled synchronously, only the current repository is selected by default (for more information about enabling synchronous repositories control, refer to Version Control Settings: Git).

      You can press Control+Q for the selected commit to display extra info, such as the commit author, time, hash and the commit message.

      Update your working copy if push is rejected

      If push is rejected because your working copy is outdated, PyCharm displays the Push Rejected dialog, provided that the Auto-update if push of the current branch was rejected option in the Git settings page of the Settings dialog is not selected. Do the following:

      1. If your project uses several Git repositories, specify which of them you want to update. If you want to update all repositories, no matter whether push was rejected for them or not, select the Update all repositories option. If this option is cleared, only the affected repositories will be updated.
      2. If you want PyCharm to apply the update procedure silently the next time push is rejected using the update method you choose in this dialog, select the Remember the update method choice and silently update in the future option. After you leave this dialog, the Auto-update if push of the current branch was rejected checkbox in the Git settings page of the Settings dialog will be selected, and the applied update method will become the default one. To change the update strategy, deselect this option to invoke the Push Rejected dialog the next time push of the current branch is rejected, apply a different update procedure, and select the Remember the update method choice option once again.
      3. Select the update method (rebase or merge) by clicking the Rebase or Merge button respectively.

      When do I need to use force push?

      When you run push , Git will refuse to complete the operation if the remote repository has changes that you are missing and that you are going to overwrite with your local copy of the repository. Normally, you need to perform pull to synchronize with the remote before you update it with your changes.

      The —force push command disables this check and lets you overwrite the remote repository, thus erasing its history and causing data loss. Under the hood, when you choose to force push, PyCharm performs the push —force-with-lease operation which is a safer option that helps you ensure you do not overwrite someone else’s commits (refer to git push for more details on the push options).

      A possible situation when you may still need to perform —force push is when you rebase a pushed branch and then want to push it to the remote server. In this case, when you try to push, Git will reject your changes because the remote ref is not an ancestor of the local ref. If you perform pull in this situation, you will end up with two copies of the branch which you then need to merge.

      Apply changes from one Git branch to another

      In Git, there are several ways to integrate changes from one branch into another:

      • Merge branches
      • Rebase branches
      • Cherry-pick separate commits
      • Apply separate changes from a commit
      • Apply specific file to a branch

      Merge branches

      feature branch diagram

      Suppose you have created a feature branch to work on a specific task, and want to integrate the results of your work into the main code base after you have completed and tested your feature:

      Merging your branch into master is the most common way to do this.

      feature branch diverged from master

      It is very common that while you are working in your feature branch, your teammates continue to commit their work to master:

      When you run merge , the changes from your feature branch are integrated into the HEAD of the target branch:

      merge result

      Git creates a new commit (M) that is referred to as a merge commit that results from combining the changes from your feature branch and master from the point where the two branches diverged.

      Merge branches

      The Merge dialog

      1. In the Branches popup (main menu Git | Branches ) or in the Branches pane of the Git tool window, select the target branch that you want to integrate the changes to, and choose Checkout from the context menu to switch to that branch.
      2. Do one of the following:
        • If you do not need to specify options for the merge, select the branch that you want to merge into the current branch and choose Merge into Current from the submenu.
        • If you need to specify merge options, from the main menu choose VCS Git | Merge Changes to open the Merge dialog: Select the branch that you want to merge into the current branch, click Modify options and choose from the following:
          • —no-ff : a merge commit will be created in all cases, even if the merge could be resolved as a fast-forward.
          • —ff-only : the merge will be resolved only if it is possible to fast-forward.
          • —squash : a single commit with all pulled changes will be created on top of the current branch.
          • -m : you will be able to edit the message for the merge commit.
          • —no-commit : a merge will be performed, but a merge commit will not be created so that you can inspect the result of the merge before committing.

      If your working tree is clean (which means you have no uncommitted changes), and no conflicts occur between your feature branch and the target branch, Git will merge the two branches, and the merge commit will appear in the Log tab of the Git tool window Alt+9 :

      merge commit

      If conflicts occur between your branch and the target branch, you will be prompted to resolve them (refer to Resolve conflicts). If there are unresolved conflicts left after a merge, the Merge Conflicts node will appear in the corresponding changelist in the Changes view with a link to resolve them.

      If you have local changes that will be overwritten by merge, PyCharm will suggest performing Smart merge . If you select this option, PyCharm will stash uncommitted changes, perform merge, and then unstash the changes.

      You can cancel an unfinished merge operation by selecting the Abort action from the Git Branches popup.

      Rebase branches (git-rebase)

      When you rebase a branch onto another branch, you apply the commits from the first branch on top of the HEAD commit in the second branch.

      feature branch

      Suppose you have created a feature branch to work on a specific task and make several commits to that branch:

      feature branch diverged from master

      While you develop in your branch, your teammates continue to commit their work to master:

      rebase operation result

      When you perform the rebase operation you integrate changes you have done in your feature branch to the master branch by applying your commits on top of the current HEAD commit in master :

      Rebase a branch on top of another branch

      1. From the main menu select Git | Rebase : Git rebase dialog
      2. From the list, select the target branch onto which you want to rebase the current branch: Choose target branch in the Git rebase dialog
      3. If you need to rebase the source branch starting from a particular commit instead of rebasing the entire branch, click Modify options and choose —onto . In the source branch field, enter the hash of the commit starting from which you want to apply the current branch to the new base: Specify commit hash with --ontoTo copy a commit hash, select it in the Log , right-click it and choose Copy Revision Number .
      4. If the branch you want to rebase is not currently checked out, click Modify options , click Select another branch to rebase , and choose a branch from the list that appears: Choose the branch you want to rebasePyCharm will check out this branch before starting the rebase operation.
      5. If you want to rebase all commits reachable in the branch, click Modify options and choose —root (for more information on this option, refer to git-rebase).
      6. If you need to keep empty commits, which are commits that do not change anything from their parent, click Modify options and choose —keep-empty (for more information on this option, refer to git-rebase).
      7. If you want to preserve merge commits during the rebase for the sake of keeping them in the branch history, click Modify options and choose —preserve-merges (this option is unavailable for interactive rebase).
      8. Click Rebase .

      You can cancel an unfinished rebase operation or resume an interrupted rebase by selecting the Abort or Continue actions respectively from the top of the Git Branches popup.

      If you do not need to specify options for the rebase, you can initiate a rebase without invoking the rebase dialog. In the Branches popup or in the Branches pane of the Git tool window select a branch and choose one of the following actions:

      • Pull into Current Using Rebase (for remote branches) to fetch changes from the selected branch and rebase the current branch on top of these changes.
      • Checkout and Rebase onto Current (for both remote and local branches) to check out the selected branch and rebase it on top of the branch that is currently checked out. If the remote branch doesn’t exist locally, PyCharm will silently create a tracked local branch, checkout into it and rebase.
      • Rebase Current onto Selected (for both remote and local branches) to rebase the branch that is currently checked out on top of the selected.

      For more information about skipping or squashing commit during a rebase, refer to Edit project history by performing interactive rebase.

      Watch this video to get a better view on how rebase operation can be performed:

      Cherry-pick separate commits

      Sometimes you only need to apply a single commit to a different branch instead of rebasing or merging an entire branch. This may be useful, for example, if you are working in a feature branch and want to integrate a hotfix from master that was committed after the two branches have diverged. Or you may want to backport a fix to a previous release branch. You can do so by using the Cherry-pick action.

      Cherry pick operation status

      The status of a cherry-pick operation is displayed in the status bar. You can always abort an ongoing cherry-pick by selecting Abort Cherry-Pick in the Git Branches popup.

      Apply a commit to another branch

      1. In the Branches popup (main menu Git | Branches ), select the target branch that you want to integrate the changes to and choose Checkout from the popup menu to switch to that branch.
      2. Open the Git tool window Alt+9 and switch to the Log tab.
      3. Locate the commit containing the changes you want to cherry-pick. You can filter commits by branch, user or date. You can also click on the toolbar and select Highlight | Non-Picked Commits option to grey out the commits that have already been applied to the current branch. If you know the commit hash, or are looking for a tagged commit, you can also use the Go to Hash / Branch / Tag action (press Control+F in the Log tab of the Git tool window Alt+9 , or click on the toolbar).
      4. Select the required commit. Use the information in the Commit Details area to make sure these are the changes you want to transfer to another branch.
      5. Click Cherry-pick on the toolbar. PyCharm will apply and commit changes to the target branch.
      6. If the cherry-pick failed with conflicts, the selected changes will appear in the Changes area that you can see in the Changes view. You can review these changes and commit them later if necessary. If you want PyCharm to create changelists automatically in case of cherry-pick fail, switch on the corresponding setting in Settings | Version Control | Changelists .
      7. Push the changes to the target branch.

      The following video will help you see how cherry-pick works:

      Apply separate changes

      Imagine you’ve made some changes to a file that you want to apply to a different branch, but these changes were committed together with other modified files. PyCharm lets you apply separate changes instead of cherry-picking an entire commit.

      1. In the Branches popup (main menu Git | Branches ), select the target branch that you want to integrate the changes to and choose Checkout from the popup menu to switch to that branch.
      2. Open the Git tool window Alt+9 and switch to the Log tab.
      3. Locate the commit that contains the changes that you want to apply. You can filter commits by branch, user or date. You can also click on the toolbar and select Highlight | Non-Picked Commits option to grey out the commits that have already been applied to the current branch. If you know the commit hash, or are looking for a tagged commit, you can also use the Go to Hash / Branch / Tag action (press Control+F in the Log tab of the Git tool window Alt+9 , or click on the toolbar).
      4. In the Commit details pane on the right, select the files containing the changes you want to apply to the target branch and select Cherry-Pick Selected Changes from the context menu.
      5. In the dialog that opens, select an existing changelist or enter the name for a new changelist and click OK .
      6. Commit the changes and then push them to the target branch.

      Apply separate files

      In addition to applying separate changes to a single file, you can copy an entire file’s contents to a different branch. This may be useful, for example, if the file you want to apply doesn’t exist in the target branch, or if changes to it were made within several commits.

      1. Switch to the branch to which the changes will be applied.
      2. In the Branches popup (main menu Git | Branches ) or in the Branches pane of the Git tool window, select the branch that contains the file you want to apply and choose Show Diff with Working Tree from the context menu. The Changes tool window that opens shows a list of all files that are different in the selected branch compared with the branch that is currently checked out:
        • Files that exist in the selected branch and are missing in the current branch are marked with grey.
        • Files that exist in the current branch but are missing in the selected branch are marked with green.
        • Files that contain differences between the selected and the current branch are marked with blue.

      You can click the Swap Branches link to change which branch is considered as a base against which you are comparing the other branch.

      You can also apply a file to another branch from the Project view: select the folder containing the file you want to copy, and choose Git | Compare with Branch | from the context menu, then click the Get icon on the toolbar.

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *