Movatterモバイル変換


[0]ホーム

URL:


ContentsMenuExpandLight modeDark modeAuto light/dark, in light modeAuto light/dark, in dark modeSkip to content
Python Developer's Guide
Logo
Python Developer's Guide
Back to top

Git bootcamp and cheat sheet

Note

This section provides instructions on common tasks in CPython’sworkflow. It’s designed to assist new contributors who havesome familiarity with Git and GitHub.

If you are new to Git and GitHub, please become comfortable withthese instructions before submitting a pull request. As there are severalways to accomplish these tasks using Git and GitHub, this section reflectsone method suitable for new contributors. Experienced contributors maydesire a different approach.

In this section, we will go over some commonly used Git commands that arerelevant to CPython’s workflow.

Note

Setting up Git aliases for common tasks can be useful to you. You canget more information about that inGit documentation

Forking CPython GitHub repository

You will only need to do this once.

  1. Go tohttps://github.com/python/cpython.

  2. PressFork located near the top right of the page.

  3. Uncheck “Copy themain branch only”.

  4. Press theCreate fork button.

  5. Your forked CPython repository will be created athttps://github.com/<username>/cpython.

Cloning a forked CPython repository

You will only need to do this once per machine. From your command line:

$gitclonegit@github.com:<username>/cpython.git

It is also recommended to configure anupstream remote repository:

$cdcpython$gitremoteaddupstreamhttps://github.com/python/cpython

You can also use SSH-based or HTTPS-based URLs.

Configure the remotes

Configuregit to pullmain from theupstream remote:

$gitconfig--localbranch.main.remoteupstream

Since one should never attempt to push toupstream, configuregit to push always toorigin:

$gitremoteset-url--pushupstreamgit@github.com:<username>/cpython.git

Listing the remote repositories

To list the remote repositories that are configured, along with their URLs:

$gitremote-v

You should have two remote repositories:origin pointing to your forked CPython repository,andupstream pointing to the official CPython repository:

origin  git@github.com:<username>/cpython.git (fetch)origin  git@github.com:<username>/cpython.git (push)upstream        https://github.com/python/cpython (fetch)upstream        git@github.com:<username>/cpython.git (push)

To verify the upstream formain:

$gitconfigbranch.main.remote

It should emitupstream, indicating to track/pull changes formain from theupstream remote.

Once this is verified, update your local clone with the upstream branches:

$gitfetchupstream

Setting up your name and email address

$gitconfig--globaluser.name"Your Name"$gitconfig--globaluser.emailyour.email@example.com

The--global flag sets these parameters globally whilethe--local flag sets them only for the current project.

Enablingautocrlf on Windows

Theautocrlf option will fix automatically any Windows-specific line endings.This should be enabled on Windows, since the public repository has a hook whichwill reject all commits having the wrong line endings:

$gitconfig--globalcore.autocrlfinput

Creating and switching branches

Important

Never commit directly to themain branch.

Create a new branch frommain and switch to it:

$gitswitch-c<branch-name>main

This is equivalent to:

$# create a new branch from main$gitbranch<branch-name>main$# switch to the new branch$gitswitch<branch-name>

To find the branch you are currently on:

$gitbranch

The current branch will have an asterisk next to the branch name. Note, thiswill only list all of your local branches.

To list all the branches, including the remote branches:

$gitbranch-a

To switch to a different branch:

$gitswitch<another-branch-name>

Other releases are just branches in the repository. For example, to workon the 3.12 release from theupstream remote:

$gitswitch-c3.12upstream/3.12

Deleting branches

To delete alocal branch that you no longer need:

$gitswitchmain$gitbranch-D<branch-name>

To delete aremote branch:

$gitpushorigin-d<branch-name>

You may specify more than one branch for deletion.

Renaming branch

The CPython repository’s default branch was renamed frommaster tomain after the Python 3.10b1 release.

If you have a fork on GitHub (as described inForking CPython GitHub repository) that wascreated before the rename, you should visit the GitHub page for your fork torename the branch there. You only have to do this once. GitHub shouldprovide you with a dialog for this. If it doesn’t (or the dialog was alreadydismissed), you can rename the branch in your fork manuallyby followingthese GitHub instructions.

After renaming the branch in your fork, you need to update any local clonesas well. This only has to be done once per clone:

$gitbranch-mmastermain$gitfetchorigin$gitbranch-uorigin/mainmain$gitremoteset-headorigin-a

(GitHub also provides these instructions after you rename the branch.)

If you do not have a fork on GitHub, but rather a direct clone of the mainrepo created before the branch rename, you still have to update your localclones. This still only has to be done once per clone. In that case, you canrename your local branch as follows:

$gitbranch-mmastermain$gitfetchupstream$gitbranch-uupstream/mainmain

Staging and committing files

  1. To show the current changes:

    $gitstatus
  2. To stage the files to be included in your commit:

    $gitadd-p# to review and add changes to existing files$gitadd<filename1><filename2># to add new files
  3. To commit the files that have been staged (done in step 2):

    gitcommit-m"This is the commit message."

Reverting changes

To revert changes to a file that has not been committed yet:

$gitcheckout<filename>

If the change has been committed, and now you want to reset it to whateverthe origin is at:

$gitreset--hardHEAD

Stashing changes

To stash away changes that are not ready to be committed yet:

$gitstash

To re-apply the last stashed change:

$gitstashpop

Comparing changes

View all non-commited changes:

$gitdiff

Compare to themain branch:

$gitdiffmain

Exclude generated files from diff using anattrpathspec (note thesingle quotes):

$gitdiffmain':(attr:!generated)'

Exclude generated files from diff by default:

$gitconfigdiff.generated.binarytrue

Thegeneratedattribute isdefined in.gitattributes, found in the repository root.

Pushing changes

Once your changes are ready for a review or a pull request, you will need to pushthem to the remote repository.

$gitswitch<branch-name>$gitpushorigin<branch-name>

Creating a pull request

  1. Go tohttps://github.com/python/cpython.

  2. Press theNew pull request button.

  3. Click thecompareacrossforks link.

  4. Select the base repository:python/cpython and base branch:main.

  5. Select the head repository:<username>/cpython and head branch: the branchcontaining your changes.

  6. Press theCreate pull request button.

You should include the issue number in the title of the PR,in the formatgh-NNNNN:<PRTitle>.

Linking to issues and pull requests

You can link to issues and pull requests usinggh-NNNNN (this form ispreferred over#NNNNN). If the reference appears in a list, the linkwill be expanded to show the status and title of the issue/PR.

When you create a PR that includesgh-NNNNN in the title,bedeverewill automatically add a link to the issue in the first message.

In addition, pull requests supportspecial keywords that can be used tolink to an issue and automatically close it when the PR is merged.However, issues often require multiple PRs before they can be closed (forexample, backports to other branches), so this features is only useful ifyou know for sure that a single PR is enough to address and close the issue.

Updating your CPython fork

Scenario:

  • You forked the CPython repository some time ago.

  • Time passes.

  • There have been new commits made in the upstream CPython repository.

  • Your forked CPython repository is no longer up to date.

  • You now want to update your forked CPython repository to be the same asthe upstream CPython repository.

Please do not try to solve this by creating a pull request frompython:main to<username>:main as the authors of the pull requests willget notified unnecessarily.

Solution:

$gitswitchmain$gitpullupstreammain$gitpushoriginmain

Note

For the above commands to work, please follow the instructions foundin theGet the source code section.

Another scenario:

  • You createdsome-branch some time ago.

  • Time passes.

  • You made some commits tosome-branch.

  • Meanwhile, there are recent changes from the upstream CPython repository.

  • You want to incorporate the recent changes from the upstream CPythonrepository intosome-branch.

Solution:

$gitswitchsome-branch$gitfetchupstream$gitmergeupstream/main$gitpushoriginsome-branch

You may see error messages like “CONFLICT” and “Automatic merge failed;” whenyou rungitmergeupstream/main.

When it happens, you need to resolve conflict. See these articles about resolving conflicts:

Applying a patch to Git

Scenario:

  • A patch exists but there is no pull request for it.

Solution:

  1. Download the patch locally.

  2. Apply the patch:

    $gitapply/path/to/patch.diff

    If there are errors, update to a revision from when the patch wascreated and then try thegitapply again:

    $gitcheckout$(gitrev-list-n1--before="yyyy-mm-dd hh:mm:ss"main)$gitapply/path/to/patch.diff

    If the patch still won’t apply, then a patch tool will not be able toapply the patch and it will need to be re-implemented manually.

  3. If the apply was successful, create a new branch and switch to it.

  4. Stage and commit the changes.

  5. If the patch was applied to an old revision, it needs to be updated andmerge conflicts need to be resolved:

    $gitrebasemain$gitmergetool

    For very old changes,gitmerge--no-ff may be easier than a rebase,with regards to resolving conflicts.

  6. Push the changes and open a pull request.

Checking out others’ pull requests

Scenario:

  • A contributor made a pull request to CPython.

  • Before merging it, you want to be able to test their changes locally.

If you’ve gotGitHub CLI orhub installed, you can do:

$ghco<pr_number># GitHub CLI$hubprcheckout<pr_number># hub

Both of these tools will configure a remote URL for the branch, so you cangitpush if the pull request author checked “Allow edits from maintainers”when creating the pull request.

If you don’t have GitHub CLI or hub installed, you can set up a git alias:

$gitconfig--globalalias.pr'!sh -c "git fetch upstream pull/${1}/head:pr_${1} && git checkout pr_${1}" -'
git config --global alias.pr"!sh -c 'git fetch upstream pull/${1}/head:pr_${1} && git checkout pr_${1}' -"

The alias only needs to be done once. After the alias is set up, you can get alocal copy of a pull request as follows:

$gitpr<pr_number>

Accepting and merging a pull request

Pull requests can be accepted and merged by a Python Core Developer.You can read more about what to look for before accepting a changehere.

All pull requests have required checks that need to pass before a changecan be merged. See“Keeping CI green” for somesimple things you can do to help the checks turn green.

At any point, a core developer can schedule an automatic merge of the changeby clicking the grayEnable auto-merge (squash) button. You will findit at the bottom of the pull request page. The auto-merge will onlyhappen if all the required checks pass, but the PR does not need to have beenapproved for a successful auto-merge to take place.

If all required checks are already finished on a PR you’re reviewing,in place of the grayEnable auto-merge button you will find a greenSquash and merge button.

In either case, adjust and clean up the commit message.

✅ Here’s an example of agood commit message:

gh-12345: Improve the spam module (GH-777)* Add method A to the spam module* Update the documentation of the spam module

❌ Here’s an example of abad commit message:

gh-12345: Improve the spam module (#777)* Improve the spam module* merge from main* adjust code based on review comment* rebased

The bad example contains bullet points that are a direct effect of thePR life cycle, while being irrelevant to the final change.

Note

How to Write a Git Commit Messageis a nice article describing how to write a good commit message.

Finally, press theConfirm squash and merge button.

Cancelling an automatic merge

If you notice a problem with a pull request that was accepted and whereauto-merge was enabled, you can still cancel the workflow before GitHubautomatically merges the change.

Press the grayDisable auto-merge button on the bottom of thepull request page to disable automatic merging entirely. This is therecommended approach.

To pause automatic merging, apply the “DO-NOT-MERGE” label to the PR orsubmit a review requesting changes. The latter will put an “awaitingchanges” label on the PR, which pauses the auto-merge similarly to“DO-NOT-MERGE”. After the author submits a fix and re-requests review, you canresume the auto-merge process either by submitting an approving review or bydismissing your previous review that requested changes.

Note that pushing new changes after the auto-merge flow was enableddoesNOT stop it.

Backporting merged changes

A pull request may need to be backported into one of the maintenance branchesafter it has been accepted and merged intomain. It is usually indicatedby the labelneedsbackporttoX.Y on the pull request itself.

Use the utility scriptcherry_picker.pyto backport the commit.

The commit hash for backporting is the squashed commit that was merged tothemain branch. On the merged pull request, scroll to the bottom of thepage. Find the event that says something like:

<core_developer> merged commit <commit_sha1> into python:main <sometime> ago.

By following the link to<commit_sha1>, you will get the full commit hash.

Alternatively, the commit hash can also be obtained by the following Gitcommands:

$gitfetchupstream$gitrev-parse":/gh-12345"

The above commands will print out the hash of the commit containing"gh-12345" as part of the commit message.

When formatting the commit message for a backport commit: leave the originalone as is and delete the number of the backport pull request.

✅ Example of good backport commit message:

 gh-12345: Improve the spam module (GH-777) * Add method A to the spam module * Update the documentation of the spam module (cherry picked from commit 62adc55)

❌ Example of bad backport commit message:

 gh-12345: Improve the spam module (GH-777) (#888) * Add method A to the spam module * Update the documentation of the spam module

Editing a pull request prior to merging

When a pull request submitter has enabled theAllow edits from maintainersoption, Python Core Developers may decide to make any remaining edits neededprior to merging themselves, rather than asking the submitter to do them. Thiscan be particularly appropriate when the remaining changes are bookkeepingitems like updatingMisc/ACKS.

To edit an open pull request that targetsmain:

  1. In the pull request page, under the description, there is some informationabout the contributor’s forked CPython repository and branch name that will be useful later:

<contributor> wants to merge 1 commit into python:main from <contributor>:<branch_name>
  1. Fetch the pull request, using thegit pr alias:

    $gitpr<pr_number>

    This will checkout the contributor’s branch at<pr_number>.

  2. Make and commit your changes on the branch. For example, merge in changesmade tomain since the PR was submitted (any merge commits will beremoved by the laterSquashandMerge when accepting the change):

    $gitfetchupstream$gitmergeupstream/main$gitadd<filename>$gitcommit-m"<message>"
  3. Push the changes back to the contributor’s PR branch:

    $gitpushgit@github.com:<contributor>/cpython<pr_number>:<branch_name>
  4. Optionally,delete the PR branch.

GitHub CLI

GitHub CLI is a command-lineinterface that allows you to create, update, and check GitHubissues and pull requests.

You can install GitHub CLIby following these instructions. After installing,you need to authenticate:

$ghauthlogin

Examples of useful commands:

  • Create a PR:

    $ghprcreate
  • Check out another PR:

    $ghco<pr-id>
  • Setssh as the Git protocol:

    $ghconfigsetgit_protocolssh
  • Set the browser:

    $ghconfigsetbrowser<browser-path>

Git worktree

With Git worktrees, you can have multiple isolated working treesassociated with a single repository (the.git directory).This allows you to work simultaneously on different versionbranches, eliminating the need for multiple independent clonesthat need to be maintained and updated separately.In addition, it reduces cloning overhead and saves disk space.

Setting up Git worktree

With an existing CPython clone (seeCloning a forked CPython repository), rename thecpython directory tomain and move it into a newcpythondirectory, so we have a structure like:

cpython└── main (.git is here)

Next, create worktrees for the other branches:

$cdcpython/main$gitworktreeadd-b3.11../3.11upstream/3.11$gitworktreeadd-b3.12../3.12upstream/3.12

This gives a structure like this, with the code for each branch checked out inits own directory:

cpython├── 3.11├── 3.12└── main

Using Git worktree

List your worktrees, for example:

$gitworktreelist/Users/my-name/cpython/main  b3d24c40df [main]/Users/my-name/cpython/3.11  da1736b06a [3.11]/Users/my-name/cpython/3.12  cf29a2f25e [3.12]

Change into a directory to work from that branch. For example:

$cd../3.12$gitswitch-cmy-3.12-bugfix-branch# create new branch$# make changes, test them, commit$gitpushoriginmy-3.12-bugfix-branch$# create PR$gitswitch3.12# switch back to the 3.12 branch...
On this page

[8]ページ先頭

©2009-2025 Movatter.jp