Contribuindo para o Sphinx¶
Existem muitas maneiras de contribuir para o Sphinx, seja enviando relatórios de erros ou solicitações de recursos, escrevendo nova documentação ou enviando patches para comportamento novo ou corrigido. Este guia serve para ilustrar como você pode começar com isso.
Get help¶
A comunidade do Sphinx mantém uma série de listas de discussão e canais de IRC.
- Stack Overflow com a tag python-sphinx
Perguntas e respostas sobre o uso e o desenvolvimento.
- sphinx-users <sphinx-users@googlegroups.com>
Lista de discussão para suporte a usuário(a).
- sphinx-dev <sphinx-dev@googlegroups.com>
Lista de discussão para discussões relacionadas a desenvolvimento.
- #sphinx-doc on irc.libera.chat
Canal IRC para perguntas desenvolvimento e suporte a usuário(a).
Relatórios de bugs e solicitação de recursos¶
Se você encontrou um problema no Sphinx
ou tem uma ideia para um novo recurso, envie-o para o issue tracker no GitHub ou discuta-o na lista de discussão sphinx-dev.
Para relatórios de bugs, inclua a saída produzida durante o processo de construção e também o arquivo de log criado pelo Sphinx após encontrar uma exceção não tratada. A localização deste arquivo deve ser mostrada no final da mensagem de erro.
Incluindo or informando um link para os arquivos fonte envolvidos podem ajudar na correção da ocorrência. Se possível, tente criar e postar um projeto restrito para reproduzir e exibir o erro.
Contribute code¶
O código-fonte do Sphinx é gerenciado usando Git e está hospedado no GitHub. A maneira recomendada para novos contribuidores enviarem código para o Sphinx é fazer o fork deste repositório e enviar uma pull request após fazer commit das alterações em seu fork. A pull request precisará então ser aprovada por um dos desenvolvedores principais antes de ser incorporada ao repositório principal.
Primeiros passos¶
Antes de iniciar um patch, recomendamos verificar se há problemas em aberto ou abrir um novo problema para iniciar uma discussão sobre uma ideia de recurso ou um bug. Se você se sentir desconfortável ou incerto sobre um problema ou suas alterações, sinta-se à vontade para enviar um e-mail para a lista de discussão sphinx-dev.
Passos básicos necessários para iniciar no desenvolvimento no Sphinx.
Crie uma conta no GitHub.
Faça um fork do repositório principal do Sphinx (sphinx-doc/sphinx) usando a interface do GitHub.
Clone o repositório fork para seu computador.
git clone https://github.com/USERNAME/sphinx cd sphinx
Faça o checkout para o branch apropriado.
O
Sphinx
adota o Versionamento Semântico 2.0.0 (refs: https://semver.org/lang/pt-BR/ ).Para alterações que preservam a compatibilidade retroativa da API e dos recursos, elas devem ser incluídas na próxima versão MENOR, use a ramificação
A.x
:git checkout A.x
Para alterações substanciais incompatíveis ou outras que devem aguardar até a próxima liberação MAJOR, use o branch
master
.Para um lançamento urgente, um novo branch PATCH deve ser ramificado a partir da tag de lançamento mais recente (veja Processo de lançamento do Sphinx para detalhes).
Configure um ambiente virtual.
This is not necessary for unit testing, thanks to
tox
, but it is necessary if you wish to runsphinx-build
locally or run unit tests without the help oftox
:virtualenv ~/.venv . ~/.venv/bin/activate pip install -e .
Create a new working branch. Choose any name you like.
git checkout -b feature-xyz
Hack, trabalhe, trabalhe, escreva.
Write your code along with tests that shows that the bug was fixed or that the feature works as expected.
Add a bullet point to
CHANGES.rst
if the fix or feature is not trivial (small doc updates, typo fixes), then commit:git commit -m '#42: Add useful new feature that does this.'
GitHub recognizes certain phrases that can be used to automatically update the issue tracker. For example:
git commit -m 'Closes #42: Fix invalid markup in docstring of Foo.bar.'
pode fechar requerimento #42.
Push changes in the branch to your forked repository on GitHub:
git push origin feature-xyz
Envie um pull request de seu branch para o respectivo branch (
master
ouA.x
).Aguarde até que um desenvolvedor do núcleo revise suas modificações.
Coding style¶
Please follow these guidelines when writing code for Sphinx:
Try to use the same code style as used in the rest of the project.
For non-trivial changes, please update the
CHANGES.rst
file. If your changes alter existing behavior, please document this.Novas funcionalidades devem ser documentadas. Incluir exemplos e usos onde apropriado. Se possível, incluir um exemplo do que é exibido na geração de saída.
Ao adicionar uma nova variável de configuração, certifique-se de documentá-la e atualizar
sphinx/cmd/quickstart.py
se ela for importante o suficiente.Adicionar unidades de teste apropriadas.
Style and type checks can be run as follows:
ruff .
mypy sphinx/
Unit tests¶
Sphinx is tested using pytest for Python code and Karma for JavaScript.
To run Python unit tests, we recommend using tox
, which provides a number
of targets and allows testing against multiple different Python environments:
Para listar todos os alvos possíveis:
tox -av
To run unit tests for a specific Python version, such as Python 3.10:
tox -e py310
To run unit tests for a specific Python version and turn on deprecation warnings so they’re shown in the test output:
PYTHONWARNINGS=error tox -e py310
Arguments to
pytest
can be passed viatox
, e.g., in order to run a particular test:tox -e py310 tests/test_module.py::test_new_feature
You can also test by installing dependencies in your local environment:
pip install .[test]
To run JavaScript tests, use npm
:
npm install
npm run test
Dica
karma
requires a Firefox binary to use as a test browser.
For Unix-based systems, you can specify the path to the Firefox binary using:
FIREFOX_BIN="/Applications/Firefox.app/Contents/MacOS/firefox" npm test
Novos testes unitários devem ser incluídos no diretório tests
onde necessário:
Para corrigir bugs, primeiro adicionar um teste que falha seu suas modificações e passe após suas modificações.
Os testes que precisam de uma execução
sphinx-build
devem ser integrados em um dos módulos de teste existentes, se possível. Novos testes que para@with_app
e depoisbuild_all
para algumas asserções não são bons desde o conjunto de testes não deve demorar mais de um minuto para ser executado.
Adicionado na versão 1.8: O Sphinx
também executa testes de JavaScript.
Adicionado na versão 1.6: sphinx.testing
is added as a experimental.
Alterado na versão 1.5.2: Sphinx was switched from nose to pytest.
Por fazer
The below belongs in the developer guide
Utility functions and pytest fixtures for testing are provided in
sphinx.testing
. If you are a developer of Sphinx extensions, you can write
unit tests by using pytest. At this time, sphinx.testing
will help your
test implementation.
How to use pytest fixtures that are provided by sphinx.testing
? You can
require 'sphinx.testing.fixtures'
in your test modules or conftest.py
files like this:
pytest_plugins = 'sphinx.testing.fixtures'
If you want to know more detailed usage, please refer to tests/conftest.py
and other test_*.py
files under the tests
directory.
Contribute documentation¶
Contributing to documentation involves modifying the source files found in the
doc/
folder. To get started, you should first follow Primeiros passos,
and then take the steps below to work with the documentation.
The following sections describe how to get started with contributing documentation, as well as key aspects of a few different tools that we use.
Por fazer
Add a more extensive documentation contribution guide.
Build the documentation¶
To build the documentation, run the following command:
sphinx-build -M html ./doc ./build/sphinx -W --keep-going
This will parse the Sphinx documentation’s source files and generate HTML for
you to preview in build/sphinx/html
.
You can also build a live version of the documentation that you can preview in the browser. It will detect changes and reload the page any time you make edits. To do so, run the following command:
sphinx-autobuild ./doc ./build/sphinx/
Traduções¶
As partes das mensagens no Sphinx que vão para as construções são traduzidas em vários locais. As traduções são mantidas como arquivos gettext .po
traduzidos do modelo mestre sphinx/locale/sphinx.pot
.
Sphinx uses Babel to extract messages
and maintain the catalog files. The utils
directory contains a helper
script, babel_runner.py
.
Use
python babel_runner.py extract
to update the.pot
template.Use
python babel_runner.py update
to update all existing language catalogs insphinx/locale/*/LC_MESSAGES
with the current messages in the template file.Use
python babel_runner.py compile
to compile the.po
files to binary.mo
files and.js
files.
When an updated .po
file is submitted, run
python babel_runner.py compile
to commit both the source and the compiled
catalogs.
Quando uma nova localidade é enviada, adicione um novo diretório com o identificador de idioma ISO 639-1 e coloque sphinx.po
nele. Não se esqueça de atualizar os valores possíveis para language
em doc/usage/configuration.rst
.
The Sphinx core messages can also be translated on Transifex. There tx
client tool,
which is provided by the transifex_client
Python package, can be used to
pull translations in .po
format from Transifex. To do this, go to
sphinx/locale
and then run tx pull -f -l LANG
where LANG
is an
existing language identifier. It is good practice to run
python babel_runner.py update
afterwards to make sure the .po
file has the
canonical Babel formatting.
Debugging tips¶
Apague o cache de construção antes de construir documentos, caso tenha feito modificações no código, usar o comando
make clean
ou usar a opçãosphinx-build -E
.Use a opção
sphinx-build -P
para executarpd
em exceções.Usar
node.pformat()
enode.asdom().toxml()
para gerar representação impressa da estrutura do documento.Definir a variável de configuração
keep_warnings
paraTrue
assim os avisos serão exibidos na saída gerada.Configurar a variável
nitpicky
paraTrue
assim Sphinx irá respeitar referências sem alvos conhecidos.Set the debugging options in the Docutils configuration file.
JavaScript stemming algorithms in
sphinx/search/non-minified-js/*.js
are generated using snowball by cloning the repository, executingmake dist_libstemmer_js
and then unpacking the tarball which is generated indist
directory.Minified files in
sphinx/search/minified-js/*.js
are generated from non-minified ones usinguglifyjs
(installed via npm), with-m
option to enable mangling.