Back-End

3 nov, 2010

Criando documentação elegante com Sphinx

Publicidade

O Sphinx é uma ferramenta que permite criar documentação para qualquer finalidade, utilizando uma linguagem de marcação (reStructuredText) e alguns scripts Python para gerar saída em formatos como HTML, LaTeX e PDF. 

A maioria dos programadores tem uma certa resistência em criar documentação

Na maioria das vezes, a documentação é parte essencial de projetos e o uso de uma linguagem de marcação pode tornar a escrita muito mais confortável, rápida e menos trabalhosa do que usar um editor WYSIWYG. Como a documentação é feita utilizando uma linguagem de marcação, facilita a utilização de controle de versão e dividir as seções entre diversos colaboradores, tornando a tarefa de criação de documentação ainda mais rápida, evitando problemas de acesso e gravação quando se trabalha em um único arquivo.

O Sphinx é muito prático e objetivo, faz com que os programadores tenham interesse e vontade em escrever documentações.

Muitas distribuições GNU/Linux já possuem o pacote do python-sphinx pronto, bastando um apt-get install python-sphinx (para Debian e Ubuntu) ou yum install python-sphinx (como Fedora/Red Hat/CentOS). Em outras distribuições e sistemas operacionais como Mac ou Windows, é necessário ter o Python instalado, pode-se utilizar o comando easy_install -U Sphinx para instalar o pacote e suas dependências (como Jinja) para ter o Sphinx e suas dependências instaladas.

Uma vez instalado, basta iniciar a criação de seu projeto de documentação com o utilitário sphinx-quickstart, a saída será como no exemplo abaixo:

anderson@yoda:~/tmp$ sphinx-quickstart 
Welcome to the Sphinx quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Enter the root path for documentation.
> Root path for the documentation [.]:

You have two options for placing the build directory for Sphinx output.

Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/N) [n]: y

Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.
> Name prefix for templates and static dir [_]:

The project name will occur in several places in the built documentation.
> Project name: Teste Sphinx
> Author name(s): Christiano Anderson

Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1. If you don't need this dual structure,
just set both to the same value.
> Project version: 1.0
> Project release [1.0]:

The file name suffix for source files. Commonly, this is either ".txt"
or ".rst". Only files with this suffix are considered documents.
> Source file suffix [.rst]:

One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.
> Name of your master document (without suffix) [index]:

Please indicate if you want to use one of the following Sphinx extensions:
> autodoc: automatically insert docstrings from modules (y/N) [n]:
> doctest: automatically test code snippets in doctest blocks (y/N) [n]:
> intersphinx: link between Sphinx documentation of different projects (y/N) [n]:
> todo: write "todo" entries that can be shown or hidden on build (y/N) [n]:
> coverage: checks for documentation coverage (y/N) [n]:
> pngmath: include math, rendered as PNG images (y/N) [n]:
> jsmath: include math, rendered in the browser by JSMath (y/N) [n]:
> ifconfig: conditional inclusion of content based on config values (y/N) [n]:

A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.
> Create Makefile? (Y/n) [y]:
> Create Windows command file? (Y/n) [y]: n

Finished: An initial directory structure has been created.

You should now populate your master file ./source/index.rst and create other documentation
source files. Use the Makefile to build the docs, like so:
make builder
where "builder" is one of the supported builders, e.g. html, latex or linkcheck

Depois de ter respondido as perguntas acima, um diretório com um Makefile e os subdiretórios build e source serão criados. No source, você vai trabalhar na criação do documento, enquanto que no build, ficará sua documentação depois de gerada.

Dentro do build, terá um arquivo conf.py, que agrega todos os parâmetros de configuração.  As opções estão comentadas, com um breve resumo de cada parâmetro, mas recomendo alterar a linha “language” para pt_BR se estiver criando sua documentação em português. Ficará desse jeito:

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = 'pt_BR'

Depois de configurado, basta criar seus documentos, são arquivos .rst com a formatação bem semelhante de wiki. Um exemplo de documento (arquivo intro.rst):

Título
======

A linguagem de marcação é semelhante a muitos wikis.

Subtítulo
---------

Você também pode usar **negrito**, *itálico*.

Uma lista enumerada ficaria assim:

#. Primeira linha
#. Segunda linha
#. Terceira linha

.. hint::
Aqui você pode colocar uma dica

Depois basta referenciar seus arquivos dentro do index.rst, não sendo necessário colocar a extensão .rst. Exemplo:

.. Teste Sphinx documentation master file, created by
sphinx-quickstart on Sun Oct 24 18:19:06 2010.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.

Welcome to Teste Sphinx's documentation!
========================================

Contents:

.. toctree::
:maxdepth: 2

intro

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

Para gerar a saída em PDF, basta digitar make latex no diretório principal da documentação. Depois basta entrar no diretório build/latex e digitar make all-pdf para que o PDF seja gerado, como no exemplo abaixo (a página do nosso exemplo de documento):

Dicas aos usuários de Debian/Ubuntu (e provavelmente outras distribuições): instale o pacote texlive-full para que o suporte a geração de PDF funcione.

Além da tela acima, o pacote gera automaticamente o índice, índice de imagens, índice de tabelas e demais facilidades utilizadas em documentação. A qualidade do documento fica realmente muito profissional, excelente para documentar projetos de software, criar material para treinamentos, apresentações e outras necessidades com toda a agilidade de trabalhar diretamente com linguagem de marcação. Para saber mais, visite os links abaixo: 

Veja todas as marcações disponíveis em reStructuredText quickstart.

Visite também o site do projeto: Python Sphinx