---
title: "Enviando código"
version: 5.2
locale: pt-br
source: https://docs.djangoproject.com/pt-br/5.2/internals/contributing/committing-code/
canonical: https://djangodocs.dev/pt-br/5.2/internals/contributing/committing-code/
---
# Enviando código

This section is addressed to the mergers and to anyone interested in knowing
how code gets committed into Django. If you’re a community member who wants to
contribute code to Django, look at [Trabalhando com Git e GitHub](/pt-br/5.2/internals/contributing/writing-code/working-with-git/) instead.

## Manipulando pull requests

Como o Django é hospeado no GitbHub, os patches são provisionados na forma de pull requests.

When committing a pull request, make sure each individual commit matches the
commit guidelines described below. Contributors are expected to provide the
best pull requests possible. In practice mergers - who will likely be more
familiar with the commit guidelines - may decide to bring a commit up to
standard themselves.

You may want to have Jenkins or GitHub actions test the pull request with one
of the pull request builders that doesn’t run automatically, such as Oracle or
Selenium. See the [CI wiki page](https://code.djangoproject.com/wiki/CI) for instructions.

If you find yourself checking out pull requests locally more often, this git
alias will be helpful:

```ini
[alias]
    pr = !sh -c \"git fetch upstream pull/${1}/head:pr/${1} && git checkout pr/${1}\"
```

Add it to your `~/.gitconfig`, and set `upstream` to be `django/django`.
Then you can run `git pr ####` to checkout the corresponding pull request.

A partir deste momento, você pode trabalhar no código. Utilize `git rebase -i` e `git commit --amend` para garantir que os commits tenham o nível de qualidade desejado. Quando você estiver pronto:

```console
$ # Pull in the latest changes from main.
$ git checkout main
$ git pull upstream main
$ # Rebase the pull request on main.
$ git checkout pr/####
$ git rebase main
$ git checkout main
$ # Merge the work as "fast-forward" to main to avoid a merge commit.
$ # (in practice, you can omit "--ff-only" since you just rebased)
$ git merge --ff-only pr/XXXX
$ # If you're not sure if you did things correctly, check that only the
$ # changes you expect will be pushed to upstream.
$ git push --dry-run upstream main
$ # Push!
$ git push upstream main
$ # Delete the pull request branch.
$ git branch -d pr/xxxx
```

*Windows*

```doscon
...\> REM Pull in the latest changes from main.
...\> git checkout main
...\> git pull upstream main
...\> REM Rebase the pull request on main.
...\> git checkout pr/####
...\> git rebase main
...\> git checkout main
...\> REM Merge the work as "fast-forward" to main to avoid a merge commit.
...\> REM (in practice, you can omit "--ff-only" since you just rebased)
...\> git merge --ff-only pr/XXXX
...\> REM If you're not sure if you did things correctly, check that only the
...\> REM changes you expect will be pushed to upstream.
...\> git push --dry-run upstream main
...\> REM Push!
...\> git push upstream main
...\> REM Delete the pull request branch.
...\> git branch -d pr/xxxx
```

Force push to the branch after rebasing on main but before merging and pushing
to upstream. This allows the commit hashes on main and the branch to match
which automatically closes the pull request.

If a pull request doesn’t need to be merged as multiple commits, you can use
GitHub’s “Squash and merge” button on the website. Edit the commit message as
needed to conform to [the guidelines](#committing-guidelines) and remove
the pull request number that’s automatically appended to the message’s first
line.

Quando estiver reescrevendo o histórico de commits de um pull request, o objetivo é fazer com que o histórico de commits do Django seja o mais útil possível:

- Se um patch possui retornos e avanços nos commits, então reescreva esses em um só. Por exemplo, se um commit adiciona mais código e um segundo commit faz ajustes em problemas de estilo introduzidos pelo primeiro commit, esses commits devem ser unificados antes de se fazer um merge.
- Separe as mudanças em diferentes commits por grupos lógicos: se você faz uma limpeza de estilo ao mesmo tempo em que você faz outras mudanças em um arquivo, a separação dessas mudanças em dois commits diferentes fará a revisão do histórico de alterações mais simples.
- Cuidado com merges de branches do upstream dentro de pull requests.
- Testes devem passar e a documentação deve ser gerada depois de cada commit. Nem os testes, nem a documentação devem emitir avisos.
- Patchs triviais e pequenos costumam ser melhor realizados em um único commit. Trabalhos médios ou maiores podem ser quebrados em múltiplos commits se isso fizer sentido.

Practicality beats purity, so it is up to each merger to decide how much
history mangling to do for a pull request. The main points are engaging the
community, getting work done, and having a usable commit history.

## Regras de commit

Adicionalmente, por favor siga as regras a seguir quando estiver commitando código para o repositório do Django no git:

- Nunca altere o histórico publicado dos “branches” do  `django/django` através de um “push” forçado. Se for absolutamente necessário (por razões de segurança), primeiro discuta a situação com o time.
- For any medium-to-big changes, where “medium-to-big” is according to
  your judgment, please bring things up on the [Django Forum](https://forum.djangoproject.com/) before making
  the change.

  If you bring something up and nobody responds, please don’t take that
  to mean your idea is great and should be implemented immediately because
  nobody contested it. Everyone doesn’t always have a lot of time to read
  discussions immediately, so you may have to wait a couple of days before
  getting a response.
- Escreva os commits com mensagens detalhadas e utilizando o passado como tempo verbal, não o presente.

  - Bom: “Corrigido bug de Unicode na API de RSS.”
  - Ruim: “Corrige bug de Unicode na API de RSS.”
  - Ruim: “Corrigindo bug de Unicode na API de RSS.”

  The commit message should be in lines of 72 chars maximum. There should be
  a subject line, separated by a blank line and then paragraphs of 72 char
  lines. The limits are soft. For the subject line, shorter is better. In the
  body of the commit message more detail is better than less:

  ```
  Fixed #18307 -- Added git workflow guidelines.

  Refactored the Django's documentation to remove mentions of SVN
  specific tasks. Added guidelines of how to use Git, GitHub, and
  how to use pull request together with Trac instead.
  ```

  Credit the contributors in the commit message: “Thanks A for the report and B
  for review.” Use git’s [Co-Authored-By](https://docs.github.com/en/pull-requests/committing-changes-to-your-project/creating-and-editing-commits/creating-a-commit-with-multiple-authors) as appropriate.
- Para commits em uma branch, coloque antes da mensagem de commit o nome da branch. Por exemplo: “\[1.4.x\] Fixed #xxxxx – Adicionado suporte para leitura de mentes.”
- Limit commits to the most granular change that makes sense. This means,
  use frequent small commits rather than infrequent large commits. For
  example, if implementing feature X requires a small change to library Y,
  first commit the change to library Y, then commit feature X in a separate
  commit. This goes a *long way* in helping everyone follow your changes.
- Separate bug fixes from feature changes. Bugfixes may need to be backported
  to the stable branch, according to [Versões suportadas](/pt-br/5.2/internals/release-process/#supported-versions-policy).
- Se o seu commit fecha um ticket no rastreador de tickets do Django, comece a sua mensagem de commit com o texto “Fixed #xxxxx”, onde “xxxxx” é o número do ticket que o seu commit corrige. Exemplo: “Corrigido #123 – Adicionada a funcionalidade whizbang.”.
  Nós configuramos o Trac de modo que qualquer mensagem de commit nesse formato irá automaticamente fechar o ticket referenciado e colocar um comentário nele com a mensagem completa do commit.

  Para os curiosos, nós estamos utilizando um [Trac plugin](https://github.com/trac-hacks/trac-github) para isso.

> **Note**
>
> Note that the Trac integration doesn’t know anything about pull requests.
> So if you try to close a pull request with the phrase “closes #400” in your
> commit message, GitHub will close the pull request, but the Trac plugin
> will not close the same numbered ticket in Trac.

- Se o seu commit faz referência a um ticket no rastreador de tickets do Django mas *não* fecha o ticket, inclua a frase  “Refs #xxxxx”, onde “xxxxx” é o número do ticket que o seu commit faz menção. Isso irá automaticamente postar um comentário na página do respectivo ticket.
- Escreva mensagens de commit para backports usando esse formato:

  ```
  [<Django version>] Fixed <ticket> -- <description>

  Backport of <revision> from <branch>.
  ```

  Por exemplo:

  ```
  [1.3.x] Fixed #17028 -- Changed diveintopython.org -> diveintopython.net.

  Backport of 80c0cbf1c97047daed2c5b41b296bbc56fe1d7e3 from main.
  ```

  There’s a [script on the wiki](https://code.djangoproject.com/wiki/MergerTips#AutomatingBackports) to
  automate this.

  If the commit fixes a regression, include this in the commit message:

  ```
  Regression in 6ecccad711b52f9273b1acb07a57d3f806e93928.
  ```

  (use the commit hash where the regression was introduced).

## Revertendo commits

Ninguém é perfeito; erros serão comitados.

But try very hard to ensure that mistakes don’t happen. Just because we have a
reversion policy doesn’t relax your responsibility to aim for the highest
quality possible. Really: double-check your work, or have it checked by
another merger **before** you commit it in the first place!

Quando um commit indevido é descoberto, por favor siga as instruções abaixo:

- Se possível, deixe que o autor original reverta o seu próprio commit.
- Não faça o revert das mudanças de outro autor sem a permissão do autor original.
- Utilize o git revert – isso irá fazer um commit reverso, mas o commit original ainda será parte do histórico de commits.
- If the original author can’t be reached (within a reasonable amount
  of time – a day or so) and the problem is severe – crashing bug,
  major test failures, etc. – then ask for objections on the [Django Forum](https://forum.djangoproject.com/)
  then revert if there are none.
- Se o problema é pequeno (uma funcionalidade congelada, por exemplo) aguarde.
- If there’s a disagreement between the merger and the reverter-to-be then try
  to work it out on the [Django Forum](https://forum.djangoproject.com/) . If an agreement can’t be reached then
  it should be put to a vote.
- Se o commit introduziu uma vulnerabilidade de segurança confirmada, aberta então o commit deve ser revertido imediatamente sem permissão de ninguém.
- O mantenedor da branch de releases pode voltar commits nessa branch sem permissão caso o commit tenha quebrado a branch de releases.
- If you mistakenly push a topic branch to `django/django`, delete it.
  For instance, if you did: `git push upstream feature_antigravity`,
  do a reverse push: `git push upstream :feature_antigravity`.
