@node Contribuindo
@chapter Contribuindo

This project is a cooperative effort, and we need your help to make it grow!
Please get in touch with us on @email{guix-devel@@gnu.org} and @code{#guix}
on the Libera Chat IRC network.  We welcome ideas, bug reports, patches, and
anything that may be helpful to the project.  We particularly welcome help
on packaging (@pxref{Diretrizes de empacotamento}).

@cindex código de conduta, de contribuidores
@cindex acordo de contribuição
Queremos oferecer um ambiente acolhedor, amigável e sem assédio, para que
todos possam contribuir com o melhor de suas habilidades. Para este fim,
nosso projeto usa um ``Acordo de contribuição``, que foi adaptado de
@url{https://contributor-covenant.org/}. Você pode encontrar uma versão
local no arquivo @file{CODE-OF-CONDUCT} na árvore de fontes.

Os contribuidores não são obrigados a usar seu nome legal em patches e
comunicação on-line; eles podem usar qualquer nome ou pseudônimo de sua
escolha.

@menu
* Compilando do git::        A mais recente e melhor.
* Executando guix antes dele ser instalado::  Truques de hacker.
* A configuração perfeita::  As ferramentas certas.
* Diretrizes de empacotamento::  Crescendo a distribuição.
* Estilo de código::        Limpeza do contribuidor.
* Enviando patches::         Compartilhe seu trabalho.
* Tracking Bugs and Patches::  Keeping it all organized.
* Commit Access::            Pushing to the official repository.
* Updating the Guix Package::  Updating the Guix package definition.
* Writing Documentation::    Improving documentation in GNU Guix.
* Traduzindo o Guix::        Make Guix speak your native language.
@end menu

@node Compilando do git
@section Compilando do git

Se você quiser hackear o próprio Guix, é recomendado usar a versão mais
recente do repositório Git:

@example
git clone https://git.savannah.gnu.org/git/guix.git
@end example

@cindex authentication, of a Guix checkout
How do you ensure that you obtained a genuine copy of the repository? To do
that, run @command{guix git authenticate}, passing it the commit and OpenPGP
fingerprint of the @dfn{channel introduction} (@pxref{Invoking guix git authenticate}):

@c ===========================================================================
@c
@c This file was generated with po4a. Translate the source file.
@c
@c ===========================================================================

@c The commit and fingerprint below must match those of the channel
@c introduction in '%default-channels'.
@example
git fetch origin keyring:keyring
guix git authenticate 9edb3f66fd807b096b48283debdcddccfea34bad \
  "BBB0 2DDF 2CEA F6A8 0D1D  E643 A2A0 6DF2 A33A 54FA"
@end example

@noindent
This command completes with exit code zero on success; it prints an error
message and exits with a non-zero code otherwise.

As you can see, there is a chicken-and-egg problem: you first need to have
Guix installed.  Typically you would install Guix System (@pxref{Instalação do sistema}) or Guix on top of another distro (@pxref{Instalação de binários}); in either case, you would verify the OpenPGP signature on
the installation medium.  This ``bootstraps'' the trust chain.

A maneira mais fácil de configurar um ambiente de desenvolvimento para o
Guix é, obviamente, usando o Guix! O comando a seguir inicia um novo shell
no qual todas as dependências e variáveis de ambiente apropriadas são
configuradas para hackear o Guix:

@example
guix shell -D guix --pure
@end example

@xref{Invoking guix shell}, for more information on that command.

If you are unable to use Guix when building Guix from a checkout, the
following are the required packages in addition to those mentioned in the
installation instructions (@pxref{Requisitos}).

@itemize
@item @url{https://gnu.org/software/autoconf/, GNU Autoconf};
@item @url{https://gnu.org/software/automake/, GNU Automake};
@item @url{https://gnu.org/software/gettext/, GNU Gettext};
@item @url{https://gnu.org/software/texinfo/, GNU Texinfo};
@item @url{https://www.graphviz.org/, Graphviz};
@item @url{https://www.gnu.org/software/help2man/, GNU Help2man (optional)}.
@end itemize

On Guix, extra dependencies can be added by instead running @command{guix
shell}:

@example
guix shell -D guix help2man git strace --pure
@end example

From there you can generate the build system infrastructure using Autoconf
and Automake:

@example
./bootstrap
@end example

If you get an error like this one:

@example
configure.ac:46: error: possibly undefined macro: PKG_CHECK_MODULES
@end example

@noindent
provavelmente significa que o Autoconf não conseguiu encontrar o
@file{pkg.m4}, que é fornecido pelo pkg-config. Certifique-se de que
@file{pkg.m4} esteja disponível. O mesmo vale para o conjunto de macros
@file{guile.m4} fornecido pelo Guile. Por exemplo, se você instalou o
Automake em @file{/usr/local}, ele não procuraria arquivos @file{.m4} em
@file{/usr/share}. Nesse caso, você tem que invocar o seguinte comando:

@example
export ACLOCAL_PATH=/usr/share/aclocal
@end example

@xref{Macro Search Path,,, automake, The GNU Automake Manual}, para mais
informações.

Then, run:

@example
./configure --localstatedir=/var
@end example

@noindent
... where @file{/var} is the normal @code{localstatedir} value (@pxref{O armazém}, for information about this).  Note that you will probably not run
@command{make install} at the end (you don't have to)  but it's still
important to pass the right @code{localstatedir}.

Finally, you can build Guix and, if you feel so inclined, run the tests
(@pxref{Executando a suíte de testes}):

@example
make
make check
@end example

@noindent
If anything fails, take a look at installation instructions
(@pxref{Instalação}) or send a message to the @email{guix-devel@@gnu.org,
mailing list}.

From there on, you can authenticate all the commits included in your
checkout by running:

@example
make authenticate
@end example

The first run takes a couple of minutes, but subsequent runs are faster.

Or, when your configuration for your local Git repository doesn't match the
default one, you can provide the reference for the @code{keyring} branch
through the variable @code{GUIX_GIT_KEYRING}.  The following example assumes
that you have a Git remote called @samp{myremote} pointing to the official
repository:

@example
make authenticate GUIX_GIT_KEYRING=myremote/keyring
@end example

@quotation Nota
You are advised to run @command{make authenticate} after every @command{git
pull} invocation.  This ensures you keep receiving valid changes to the
repository.
@end quotation

After updating the repository, @command{make} might fail with an error
similar to the following example:

@example
error: failed to load 'gnu/packages/dunst.scm':
ice-9/eval.scm:293:34: In procedure abi-check: #<record-type <origin>>: record ABI mismatch; recompilation needed
@end example

This means that one of the record types that Guix defines (in this example,
the @code{origin} record) has changed, and all of guix needs to be
recompiled to take that change into account.  To do so, run @command{make
clean-go} followed by @command{make}.

@node Executando guix antes dele ser instalado
@section Executando guix antes dele ser instalado

Para manter um ambiente de trabalho saudável, você achará útil testar as
alterações feitas na árvore local de fontes sem realmente instalá-las. Para
que você possa distinguir entre o seu chapéude ''usuário final'' e sua
fantasia ''misturada''.

To that end, all the command-line tools can be used even if you have not run
@code{make install}.  To do that, you first need to have an environment with
all the dependencies available (@pxref{Compilando do git}), and then simply
prefix each command with @command{./pre-inst-env} (the @file{pre-inst-env}
script lives in the top build tree of Guix; it is generated by running
@command{./bootstrap} followed by @command{./configure}).  As an example,
here is how you would build the @code{hello} package as defined in your
working tree (this assumes @command{guix-daemon} is already running on your
system; it's OK if it's a different version):

@example
$ ./pre-inst-env guix build hello
@end example

@noindent
Similarly, an example for a Guile session using the Guix modules:

@example
$ ./pre-inst-env guile -c '(use-modules (guix utils)) (pk (%current-system))'

;;; ("x86_64-linux")
@end example

@noindent
@cindex REPL
@cindex read-eval-print loop
@dots{} and for a REPL (@pxref{Using Guix Interactively}):

@example
$ ./pre-inst-env guile
scheme@@(guile-user)> ,use(guix)
scheme@@(guile-user)> ,use(gnu)
scheme@@(guile-user)> (define snakes
                       (fold-packages
                         (lambda (package lst)
                           (if (string-prefix? "python"
                                               (package-name package))
                               (cons package lst)
                               lst))
                         '()))
scheme@@(guile-user)> (length snakes)
$1 = 361
@end example

If you are hacking on the daemon and its supporting code or if
@command{guix-daemon} is not already running on your system, you can launch
it straight from the build tree@footnote{The @option{-E} flag to
@command{sudo} guarantees that @code{GUILE_LOAD_PATH} is correctly set such
that @command{guix-daemon} and the tools it uses can find the Guile modules
they need.}:

@example
$ sudo -E ./pre-inst-env guix-daemon --build-users-group=guixbuild
@end example

O script @command{pre-inst-env} configura todas as variáveis de ambiente
necessárias para prover suporte a isso, incluindo @env{PATH} e
@env{GUILE_LOAD_PATH}.

Observe que @command{./pre-inst-env guix pull} @emph{não} atualiza a área de
fontes local; ele simplesmente atualiza o link simbólico
@file{~/.config/guix/current} (@pxref{Invocando guix pull}). Execute
@command{git pull} em vez disso, se você quiser atualizar sua árvore de
fontes local.

Sometimes, especially if you have recently updated your repository, running
@command{./pre-inst-env} will print a message similar to the following
example:

@example
;;; note: source file /home/user/projects/guix/guix/progress.scm
;;;       newer than compiled /home/user/projects/guix/guix/progress.go
@end example

This is only a note and you can safely ignore it.  You can get rid of the
message by running @command{make -j4}.  Until you do, Guile will run
slightly slower because it will interpret the code instead of using prepared
Guile object (@file{.go}) files.

You can run @command{make} automatically as you work using
@command{watchexec} from the @code{watchexec} package.  For example, to
build again each time you update a package file, run @samp{watchexec -w
gnu/packages -- make -j4}.

@node A configuração perfeita
@section A configuração perfeita

The Perfect Setup to hack on Guix is basically the perfect setup used for
Guile hacking (@pxref{Using Guile in Emacs,,, guile, Guile Reference
Manual}).  First, you need more than an editor, you need
@url{https://www.gnu.org/software/emacs, Emacs}, empowered by the wonderful
@url{https://nongnu.org/geiser/, Geiser}.  To set that up, run:

@example
guix install emacs guile emacs-geiser emacs-geiser-guile
@end example

O Geiser permite um desenvolvimento interativo e incremental de dentro do
Emacs: compilação e avaliação de código de dentro dos buffers, acesso à
documentação on-line (docstrings), completação sensível ao contexto,
@kbd{M-.} para pular para uma definição de objeto, um REPL para tentar seu
código e muito mais (@pxref{Introdução ,,, geiser, Manual de usuário do
Geiser}). Para um desenvolvimento prático do Guix, certifique-se de aumentar
o caminho de carregamento do Guile para que ele encontre os arquivos de
origem do seu checkout:

@lisp
;; @r{Presumindo que o checkout do Guix está em ~/src/guix.}
(with-eval-after-load 'geiser-guile
  (add-to-list 'geiser-guile-load-path "~/src/guix"))
@end lisp

To actually edit the code, Emacs already has a neat Scheme mode.  But in
addition to that, you must not miss
@url{https://www.emacswiki.org/emacs/ParEdit, Paredit}.  It provides
facilities to directly operate on the syntax tree, such as raising an
s-expression or wrapping it, swallowing or rejecting the following
s-expression, etc.

@cindex trechos de código
@cindex modelos
@cindex reduzindo boilerplate
We also provide templates for common git commit messages and package
definitions in the @file{etc/snippets} directory.  These templates can be
used to expand short trigger strings to interactive text snippets. If you
use @url{https://joaotavora.github.io/yasnippet/, YASnippet}, you may want
to add the @file{etc/snippets/yas} snippets directory to the
@var{yas-snippet-dirs} variable.  If you use
@url{https://github.com/minad/tempel/, Tempel}, you may want to add the
@file{etc/snippets/tempel/*} path to the @var{tempel-path} variable in
Emacs.

@lisp
;; @r{Assuming the Guix checkout is in ~/src/guix.}
;; @r{Yasnippet configuration}
(with-eval-after-load 'yasnippet
  (add-to-list 'yas-snippet-dirs "~/src/guix/etc/snippets/yas"))
;; @r{Tempel configuration}
(with-eval-after-load 'tempel
   ;; Ensure tempel-path is a list -- it may also be a string.
   (unless (listp 'tempel-path)
     (setq tempel-path (list tempel-path)))
   (add-to-list 'tempel-path "~/src/guix/etc/snippets/tempel/*"))
@end lisp

Os trechos de mensagens de commit dependem de @url{https://magit.vc/, Magit}
para exibir arquivos "staged". Ao editar uma mensagem de commit, digite
@code{add} seguido por @kbd{TAB} para inserir um modelo de mensagem de
commit para adicionar um pacote; digite @code{update} seguido por @kbd{TAB}
para inserir um modelo para atualizar um pacote; digite @code{https} seguido
por @kbd{TAB} para inserir um modelo para alterar a URI da página inicial de
um pacote para HTTPS.

O trecho principal para @code{scheme-mode} é acionado digitando
@code{package ...} seguido de @kbd{TAB}. Esse trecho também insere a string
de acionamento @code{origin...}, que pode ser expandida ainda mais. O trecho
@code{origin}, por sua vez, pode inserir outras strings acionadoras que
terminam em @code{...}, que também podem ser expandidas.

@cindex insert or update copyright
@cindex @code{M-x guix-copyright}
@cindex @code{M-x copyright-update}
We additionally provide insertion and automatic update of a copyright in
@file{etc/copyright.el}.  You may want to set your full name, mail, and load
a file.

@lisp
(setq user-full-name "Alice Doe")
(setq user-mail-address "alice@@mail.org")
;; @r{Assuming the Guix checkout is in ~/src/guix.}
(load-file "~/src/guix/etc/copyright.el")
@end lisp

To insert a copyright at the current line invoke @code{M-x guix-copyright}.

To update a copyright you need to specify a @code{copyright-names-regexp}.

@lisp
(setq copyright-names-regexp
      (format "%s <%s>" user-full-name user-mail-address))
@end lisp

You can check if your copyright is up to date by evaluating @code{M-x
copyright-update}.  If you want to do it automatically after each buffer
save then add @code{(add-hook 'after-save-hook 'copyright-update)} in Emacs.

@node Diretrizes de empacotamento
@section Diretrizes de empacotamento

@cindex pacotes, criação
A distribuição do GNU é incipiente e pode muito bem não ter alguns dos seus
pacotes favoritos. Esta seção descreve como você pode ajudar a fazer a
distribuição crescer.

Pacotes de software livre geralmente são distribuídos na forma de
@dfn{tarballs de código-fonte} -- geralmente arquivos @file{tar.gz} que
contêm todos os arquivos fonte. Adicionar um pacote à distribuição significa
essencialmente duas coisas: adicionar uma @dfn{receita} que descreve como
criar o pacote, incluindo uma lista de outros pacotes necessários para
compilá-lo e adicionar @dfn{metadados de pacote} junto com essa receita,
como uma descrição e informações de licenciamento.

No Guix, todas essas informações estão incorporadas em @dfn{configurações de
pacote}. As definições de pacote fornecem uma visão de alto nível do
pacote. Elas são escritas usando a sintaxe da linguagem de programação
Scheme; de fato, para cada pacote, definimos uma variável vinculada à
definição do pacote e exportamos essa variável de um módulo (@pxref{Módulos de pacote}). No entanto, o conhecimento profundo de Scheme @emph{não} é um
pré-requisito para a criação de pacotes. Para mais informações sobre
definições de pacotes, @pxref{Definindo pacotes}.

Quando uma definição de pacote está em vigor, armazenada em um arquivo na
árvore de fontes do Guix, ela pode ser testada usando o comando
@command{guix build} (@pxref{Invocando guix build}). Por exemplo, supondo
que o novo pacote seja chamado @code{gnew}, você pode executar este comando
na árvore de construção do Guix (@pxref{Executando guix antes dele ser instalado}):

@example
./pre-inst-env guix build gnew --keep-failed
@end example

O uso de @code{--keep-failed} facilita a depuração de falhas de compilação,
pois fornece acesso à árvore de compilação com falha. Outra opção útil da
linha de comando ao depurar é @code{--log-file}, para acessar o log de
compilação.

Se o pacote for desconhecido para o comando @command{guix}, pode ser que o
arquivo fonte contenha um erro de sintaxe ou não tenha uma cláusula
@code{define-public} para exportar a variável do pacote. Para descobrir
isso, você pode carregar o módulo do Guile para obter mais informações sobre
o erro real:

@example
./pre-inst-env guile -c '(use-modules (gnu packages gnew))'
@end example

Once your package builds correctly, please send us a patch
(@pxref{Enviando patches}).  Well, if you need help, we will be happy to
help you too.  Once the patch is committed in the Guix repository, the new
package automatically gets built on the supported platforms by
@url{https://@value{SUBSTITUTE-SERVER-1}, our continuous integration
system}.

@cindex substituidor
Users can obtain the new package definition simply by running @command{guix
pull} (@pxref{Invocando guix pull}).  When @code{@value{SUBSTITUTE-SERVER-1}}
is done building the package, installing the package automatically downloads
binaries from there (@pxref{Substitutos}).  The only place where human
intervention is needed is to review and apply the patch.


@menu
* Liberdade de software::    O que pode ir na distribuição.
* Nomeando um pacote::       Que há em um nome?
* Números de versão::      Quando o nome não é suficiente.
* Sinopses e descrições::  Ajudando usuários a localizar o pacote certo.
* Snippets versus Phases::   Whether to use a snippet, or a build phase.
* Emacs Packages::           Your Elisp fix.
* Módulos Python::          Um toque de comédia britânica.
* Módulos Perl::            Pequenas pérolas.
* Pacotes Java::             Parada para o café.
* Rust Crates::              Beware of oxidation.
* Elm Packages::             Trees of browser code
* Fontes::                   Vício em fontes.
@end menu

@node Liberdade de software
@subsection Liberdade de software

@c Adapted from http://www.gnu.org/philosophy/philosophy.html.
@cindex software livre
The GNU operating system has been developed so that users can have freedom
in their computing.  GNU is @dfn{free software}, meaning that users have the
@url{https://www.gnu.org/philosophy/free-sw.html,four essential freedoms}:
to run the program, to study and change the program in source code form, to
redistribute exact copies, and to distribute modified versions.  Packages
found in the GNU distribution provide only software that conveys these four
freedoms.

In addition, the GNU distribution follow the
@url{https://www.gnu.org/distros/free-system-distribution-guidelines.html,free
software distribution guidelines}.  Among other things, these guidelines
reject non-free firmware, recommendations of non-free software, and discuss
ways to deal with trademarks and patents.

Algumas fontes de pacotes upstream livres de outra forma contêm um
subconjunto pequeno e opcional que viola as diretrizes acima, por exemplo,
porque esse subconjunto é ele próprio um código não livre. Quando isso
acontece, os itens incorretos são removidos com patches ou trechos de código
apropriados no formato @code{origin} do pacote (@pxref{Definindo pacotes}). Dessa forma, o @code{guix build --source} retorna a fonte
``lançada'' em vez da fonte upstream não modificada.


@node Nomeando um pacote
@subsection Nomeando um pacote

@cindex nome de pacote
A package actually has two names associated with it.  First, there is the
name of the @emph{Scheme variable}, the one following @code{define-public}.
By this name, the package can be made known in the Scheme code, for instance
as input to another package.  Second, there is the string in the @code{name}
field of a package definition.  This name is used by package management
commands such as @command{guix package} and @command{guix build}.

Ambos são geralmente iguais e correspondem à conversão em minúscula do nome
do projeto escolhido a montante, com os sublinhados substituídos por
hífenes. Por exemplo, o GNUnet está disponível como @code{gnunet} e SDL_net
como @code{sdl-net}.

A noteworthy exception to this rule is when the project name is only a
single character, or if an older maintained project with the same name
already exists---regardless of whether it has already been packaged for
Guix.  Use common sense to make such names unambiguous and meaningful.  For
example, Guix's package for the shell called ``s'' upstream is
@code{s-shell} and @emph{not} @code{s}.  Feel free to ask your fellow
hackers for inspiration.

Não adicionamos prefixos @code{lib} para pacotes de bibliotecas, a menos que
eles já façam parte do nome oficial do projeto. Mas @pxref{Módulos Python} e
@ref{Módulos Perl} para regras especiais relativas a módulos para as
linguagens Python e Perl.

Nomes de pacote de fontes são lidados de forma diferente. @xref{Fontes}.


@node Números de versão
@subsection Números de versão

@cindex versão de pacote
Geralmente, empacotamos apenas a versão mais recente de um determinado
projeto de software livre. Mas, às vezes, por exemplo, para versões
incompatíveis de bibliotecas, são necessárias duas (ou mais) versões do
mesmo pacote. Isso requer nomes de variáveis Scheme diferentes. Usamos o
nome como definido em @ref{Nomeando um pacote} para a versão mais recente;
as versões anteriores usam o mesmo nome, com o sufixo @code{-} e o menor
prefixo do número da versão que pode distinguir as duas versões.

O nome dentro da definição do pacote é o mesmo para todas as versões de um
pacote e não contém nenhum número de versão.

Por exemplo, as versões 2.24.20 e 3.9.12 do GTK podem ser empacotados da
seguinte forma:

@lisp
(define-public gtk+
  (package
    (name "gtk+")
    (version "3.9.12")
    ...))
(define-public gtk+-2
  (package
    (name "gtk+")
    (version "2.24.20")
    ...))
@end lisp
Se também quiséssemos GTK 3.8.2, este seria empacotado como
@lisp
(define-public gtk+-3.8
  (package
    (name "gtk+")
    (version "3.8.2")
    ...))
@end lisp

@c See <https://lists.gnu.org/archive/html/guix-devel/2016-01/msg00425.html>,
@c for a discussion of what follows.
@cindex número de versão, para snapshots de VCS
Ocasionalmente, empacotamos snapshots do sistema de controle de versão (VCS)
do upstream em vez de lançamentos formais. Isso deve permanecer excepcional,
porque cabe aos desenvolvedores upstream esclarecer qual é a versão
estável. No entanto, às vezes é necessário. Então, o que devemos colocar no
campo @code{version}?

Claramente, precisamos tornar o identificador de commit do snapshot VCS
visível na string de versão, mas também precisamos garantir que a string de
versão esteja aumentando monotonicamente para que o @command{pacote guix
--upgrade} possa determinar qual versão é mais recente. Como os
identificadores de commit, principalmente com o Git, não estão aumentando
monotonicamente, adicionamos um número de revisão que aumentamos cada vez
que atualizamos para um snapshot mais recente. A sequência da versão
resultante é assim:

@example
2.0.11-3.cabba9e
  ^    ^    ^
  |    |    `-- ID do commit do upstream
  |    |
  |    `--- revisão do pacote do Guix
  |
versão mais recente do upstream
@end example

It is a good idea to strip commit identifiers in the @code{version} field
to, say, 7 digits.  It avoids an aesthetic annoyance (assuming aesthetics
have a role to play here) as well as problems related to OS limits such as
the maximum shebang length (127 bytes for the Linux kernel).  There are
helper functions for doing this for packages using @code{git-fetch} or
@code{hg-fetch} (see below).  It is best to use the full commit identifiers
in @code{origin}s, though, to avoid ambiguities.  A typical package
definition may look like this:


@lisp
(define meu-pacote
  (let ((commit "c3f29bc928d5900971f65965feaae59e1272a3f7")
        (revision "1"))          ;revisão do pacote do Guix
    (package
      (version (git-version "0.9" revision commit))
      (source (origin
                (method git-fetch)
                (uri (git-reference
                      (url "git://example.org/meu-pacote.git")
                      (commit commit)))
                (sha256 (base32 "1mbikn@dots{}"))
                (file-name (git-file-name name version))))
      ;; @dots{}
      )))
@end lisp

@deffn {Scheme Procedure} git-version @var{VERSION} @var{REVISION} @var{COMMIT}
Return the version string for packages using @code{git-fetch}.

@lisp
(git-version "0.2.3" "0" "93818c936ee7e2f1ba1b315578bde363a7d43d05")
@result{} "0.2.3-0.93818c9"
@end lisp
@end deffn

@deffn {Scheme Procedure} hg-version @var{VERSION} @var{REVISION} @var{CHANGESET}
Return the version string for packages using @code{hg-fetch}.  It works in
the same way as @code{git-version}.
@end deffn

@node Sinopses e descrições
@subsection Sinopses e descrições

@cindex descrição do pacote
@cindex sinopse do pacote
Como vimos anteriormente, cada pacote no GNU@tie{}Guix inclui uma sinopse e
uma descrição (@pxref{Definindo pacotes}). Sinopses e descrições são
importantes: são o que o @command{guix package --search} pesquisa e uma
informação crucial para ajudar os usuários a determinar se um determinado
pacote atende às suas necessidades. Consequentemente, os empacotadores devem
prestar atenção ao que entra neles.

As sinopses devem começar com uma letra maiúscula e não devem terminar com
um ponto. Elas não devem começar com ``a'' ou ``the'', que geralmente não
traz nada; por exemplo, prefira ``Tool-frobbing tool'' em vez de ``A tool
that frobs files''. A sinopse deve dizer o que é o pacote -- por exemplo,
``Core GNU utilities (file, text, shell)'' -- ou para que é usado -- por
exemplo, a sinopse do GNU@tie{}grep é ``Print lines matching a pattern''.

Lembre-se de que a sinopse deve ser significativa para um público muito
amplo. Por exemplo, ``Manipulate alignments in the SAM format'' pode fazer
sentido para um pesquisador experiente em bioinformática, mas pode ser
bastante inútil ou até enganoso para um público não especializado. É uma boa
ideia apresentar uma sinopse que dê uma ideia do domínio do aplicativo do
pacote. Neste exemplo, isso pode fornecer algo como ``Manipulate nucleotide
sequence alignments'', o que, esperançosamente, dá ao usuário uma melhor
ideia de se é isso que eles estão procurando.

Descrições devem levar entre cinco e dez linhas. Use sentenças completas e
evite usar acrônimos sem primeiro apresentá-los. Por favor, evite frases de
marketing como ``inovação mundial'', ``força industrial'' e ``próxima
geração'', e evite superlativos como ``a mais avançada'' -- eles não ajudam
o usuário procurando por um pacote e podem atém parece suspeito. Em vez
idsso, tente se ater aos fatos, mencionando casos de uso e recursos.

@cindex Marcação Texinfo, em descrições de pacote
Descriptions can include Texinfo markup, which is useful to introduce
ornaments such as @code{@@code} or @code{@@dfn}, bullet lists, or hyperlinks
(@pxref{Overview,,, texinfo, GNU Texinfo}).  However you should be careful
when using some characters for example @samp{@@} and curly braces which are
the basic special characters in Texinfo (@pxref{Special Characters,,,
texinfo, GNU Texinfo}).  User interfaces such as @command{guix show} take
care of rendering it appropriately.

Synopses and descriptions are translated by volunteers
@uref{https://translate.fedoraproject.org/projects/guix/packages, at
Weblate} so that as many users as possible can read them in their native
language.  User interfaces search them and display them in the language
specified by the current locale.

Para permitir que @command{xgettext} extrai-as com strings traduzíveis, as
sinopses e descrições @emph{devem ser strings literais}. Isso significa que
você não pode usar @code{string-append} ou @code{format} para construir
essas strings:

@lisp
(package
  ;; @dots{}
  (synopsis "Isso é traduzível")
  (description (string-append "Isso " "*não*" " é traduzível.")))
@end lisp

Tradução é muito trabalhoso, então, como empacotador, por favor, tenha ainda
mais atenção às suas sinopses e descrições, pois cada alteração pode
implicar em trabalho adicional para tradutores. Para ajudá-loas, é possível
tornar recomendações ou instruções visíveis inserindo comentários especiais
como esse (@pxref{xgettext Invocation,,, gettext, GNU Gettext}):

@lisp
;; TRANSLATORS: "X11 resize-and-rotate" should not be translated.
(description "ARandR is designed to provide a simple visual front end
for the X11 resize-and-rotate (RandR) extension. @dots{}")
@end lisp

@node Snippets versus Phases
@subsection Snippets versus Phases

@cindex snippets, when to use
The boundary between using an origin snippet versus a build phase to modify
the sources of a package can be elusive.  Origin snippets are typically used
to remove unwanted files such as bundled libraries, nonfree sources, or to
apply simple substitutions.  The source derived from an origin should
produce a source that can be used to build the package on any system that
the upstream package supports (i.e., act as the corresponding source).  In
particular, origin snippets must not embed store items in the sources; such
patching should rather be done using build phases.  Refer to the
@code{origin} record documentation for more information (@pxref{Referência do origin}).

@node Emacs Packages
@subsection Emacs Packages

@cindex emacs, packaging
@cindex elisp, packaging
Emacs packages should preferably use the Emacs build system
(@pxref{emacs-build-system}), for uniformity and the benefits provided by
its build phases, such as the auto-generation of the autoloads file and the
byte compilation of the sources.  Because there is no standardized way to
run a test suite for Emacs packages, tests are disabled by default.  When a
test suite is available, it should be enabled by setting the @code{#:tests?}
argument to @code{#true}.  By default, the command to run the test is
@command{make check}, but any command can be specified via the
@code{#:test-command} argument.  The @code{#:test-command} argument expects
a list containing a command and its arguments, to be invoked during the
@code{check} phase.

The Elisp dependencies of Emacs packages are typically provided as
@code{propagated-inputs} when required at run time.  As for other packages,
build or test dependencies should be specified as @code{native-inputs}.

Emacs packages sometimes depend on resources directories that should be
installed along the Elisp files.  The @code{#:include} argument can be used
for that purpose, by specifying a list of regexps to match.  The best
practice when using the @code{#:include} argument is to extend rather than
override its default value (accessible via the @code{%default-include}
variable).  As an example, a yasnippet extension package typically include a
@file{snippets} directory, which could be copied to the installation
directory using:

@lisp
#:include (cons "^snippets/" %default-include)
@end lisp

When encountering problems, it is wise to check for the presence of the
@code{Package-Requires} extension header in the package main source file,
and whether any dependencies and their versions listed therein are
satisfied.

@node Módulos Python
@subsection Módulos Python

@cindex python
Atualmente empacotamos Python 2 e Python 3, sob os nomes de variável Scheme
@code{python-2} e @code{python} conforme explicado em @ref{Números de versão}.  Para evitar confusão e conflitos de nomes com outras linguagens de
programação, parece desejável que o nome de um pacote para um módulo Python
contenha a palavra @code{python}.

Some modules are compatible with only one version of Python, others with
both.  If the package Foo is compiled with Python 3, we name it
@code{python-foo}.  If it is compiled with Python 2, we name it
@code{python2-foo}.  Packages should be added when they are necessary; we
don't add Python 2 variants of the package unless we are going to use them.

Se um projeto já contém a palavra @code{python}, nós a descartamos; por
exemplo, o módulo python-dateutil é empacotado sob os nomes
@code{python-dateutil} e @code{python2-dateutil}. Se o nome do projeto
começa com @code{py} (p.ex., @code{pytz}), nós o mantemos e o prefixamos
conforme descrito acima.

@quotation Nota
Currently there are two different build systems for Python packages in Guix:
@var{python-build-system} and @var{pyproject-build-system}.  For the longest
time, Python packages were built from an informally specified
@file{setup.py} file.  That worked amazingly well, considering Python's
success, but was difficult to build tooling around.  As a result, a host of
alternative build systems emerged and the community eventually settled on a
@url{https://peps.python.org/pep-0517/, formal standard} for specifying
build requirements.  @var{pyproject-build-system} is Guix's implementation
of this standard.  It is considered ``experimental'' in that it does not yet
support all the various PEP-517 @emph{build backends}, but you are
encouraged to try it for new Python packages and report any problems.  It
will eventually be deprecated and merged into @var{python-build-system}.
@end quotation

@subsubsection Especificando dependências
@cindex entradas, para pacotes Python

Dependency information for Python packages is usually available in the
package source tree, with varying degrees of accuracy: in the
@file{pyproject.toml} file, the @file{setup.py} file, in
@file{requirements.txt}, or in @file{tox.ini} (the latter mostly for test
dependencies).

Sua missão, ao escrever uma receita para um pacote Python, é mapear essas
dependências para o tipo apropriado de ``entrada'' (@pxref{Referência do package, inputs}). Apesar do importador do @code{pypi} normalmente fazer um
bom trabalho (@pxref{Invocando guix import}), você pode se interessar em
verificar a lista de verificação a seguir para determinar qual dependência
vai onde.

@itemize

@item
We currently package Python with @code{setuptools} and @code{pip} installed
per default.  This is about to change, and users are encouraged to use
@code{python-toolchain} if they want a build environment for Python.

@command{guix lint} will warn if @code{setuptools} or @code{pip} are added
as native-inputs because they are generally not necessary.

@item
Dependências de Python necessárias em tempo de execução vão em
@code{propagated-inputs}. Elas geralmente são definidas com a palavra-chave
@code{install_requires} em @file{setup.py} ou no arquivo
@file{requirements.txt}.

@item
Python packages required only at build time---e.g., those listed under
@code{build-system.requires} in @file{pyproject.toml} or with the
@code{setup_requires} keyword in @file{setup.py}---or dependencies only for
testing---e.g., those in @code{tests_require} or @file{tox.ini}---go into
@code{native-inputs}.  The rationale is that (1) they do not need to be
propagated because they are not needed at run time, and (2) in a
cross-compilation context, it's the ``native'' input that we'd want.

Exemplos são os frameworks de teste @code{pytest}, @code{mock} e
@code{nose}. É claro, se qualquer um desses pacotes também for necessário em
tempo de compilação, ele precisa ir para @code{propagated-inputs}.

@item
Qualquer coisa que não encaixar nas categorias anteriores vai para
@code{inputs}. Por exemplo, programas ou bibliotecas C necessárias para
compilar pacotes Python contendo extensões C.

@item
Se um pacote Python tem dependências opcionais (@code{extras_require}), fica
a seu critério adicioná-las ou não, com base na sua proporção de
utilidade/sobrecarga (@pxref{Enviando patches, @command{guix size}}).

@end itemize


@node Módulos Perl
@subsection Módulos Perl

@cindex perl
Os programas Perl próprios são nomeados como qualquer outro pacote, usando o
nome upstream em letras minúsculas. Para pacotes Perl que contêm uma única
classe, usamos o nome da classe em letras minúsculas, substituímos todas as
ocorrências de @code{::} por traços e precede o prefixo
@code{perl-}. Portanto, a classe @code{XML::Parser} se torna
@code{perl-xml-parser}. Módulos contendo várias classes mantêm seu nome
upstream em minúsculas e também são precedidos por @code{perl-}. Esses
módulos tendem a ter a palavra @code{perl} em algum lugar do nome, que é
descartada em favor do prefixo. Por exemplo, @code{libwww-perl} se torna
@code{perl-libwww}.


@node Pacotes Java
@subsection Pacotes Java

@cindex java
Os programas Java próprios são nomeados como qualquer outro pacote, usando o
nome do upstream em letras minúsculas.

Para evitar confusão e conflitos de nomes com outras linguagens de
programação, é desejável que o nome de um pacote para um pacote Java seja
prefixado com @code{java-}. Se um projeto já contém a palavra @code{java},
descartamos isso; por exemplo, o pacote @code{ngsjava} é empacotado com o
nome @code{java-ngs}.

Para pacotes Java que contêm uma única classe ou uma pequena hierarquia de
classes, usamos o nome da classe em letras minúsculas, substitua todas as
ocorrências de @code{.} por traços e acrescente o prefixo
@code{java-}. Assim, a classe @code{apache.commons.cli} se torna o pacote
@code{java-apache-commons-cli}.


@node Rust Crates
@subsection Rust Crates

@cindex rust
Rust programs standing for themselves are named as any other package, using
the lowercase upstream name.

To prevent namespace collisions we prefix all other Rust packages with the
@code{rust-} prefix.  The name should be changed to lowercase as appropriate
and dashes should remain in place.

In the rust ecosystem it is common for multiple incompatible versions of a
package to be used at any given time, so all package definitions should have
a versioned suffix.  The versioned suffix is the left-most non-zero digit
(and any leading zeros, of course).  This follows the ``caret'' version
scheme intended by Cargo.  Examples@: @code{rust-clap-2},
@code{rust-rand-0.6}.

Because of the difficulty in reusing rust packages as pre-compiled inputs
for other packages the Cargo build system (@pxref{Sistemas de compilação,
@code{cargo-build-system}}) presents the @code{#:cargo-inputs} and
@code{cargo-development-inputs} keywords as build system arguments.  It
would be helpful to think of these as similar to @code{propagated-inputs}
and @code{native-inputs}.  Rust @code{dependencies} and
@code{build-dependencies} should go in @code{#:cargo-inputs}, and
@code{dev-dependencies} should go in @code{#:cargo-development-inputs}.  If
a Rust package links to other libraries then the standard placement in
@code{inputs} and the like should be used.

Care should be taken to ensure the correct version of dependencies are used;
to this end we try to refrain from skipping the tests or using
@code{#:skip-build?} when possible.  Of course this is not always possible,
as the package may be developed for a different Operating System, depend on
features from the Nightly Rust compiler, or the test suite may have
atrophied since it was released.


@node Elm Packages
@subsection Elm Packages

@cindex Elm
Elm applications can be named like other software: their names need not
mention Elm.

Packages in the Elm sense (see @code{elm-build-system} under @ref{Sistemas de compilação}) are required use names of the format
@var{author}@code{/}@var{project}, where both the @var{author} and the
@var{project} may contain hyphens internally, and the @var{author} sometimes
contains uppercase letters.

To form the Guix package name from the upstream name, we follow a convention
similar to Python packages (@pxref{Módulos Python}), adding an @code{elm-}
prefix unless the name would already begin with @code{elm-}.

In many cases we can reconstruct an Elm package's upstream name
heuristically, but, since conversion to a Guix-style name involves a loss of
information, this is not always possible.  Care should be taken to add the
@code{'upstream-name} property when necessary so that @samp{guix import elm}
will work correctly (@pxref{Invocando guix import}). The most notable
scenarios when explicitly specifying the upstream name is necessary are:

@enumerate
@item
When the @var{author} is @code{elm} and the @var{project} contains one or
more hyphens, as with @code{elm/virtual-dom}; and

@item
When the @var{author} contains hyphens or uppercase letters, as with
@code{Elm-Canvas/raster-shapes}---unless the @var{author} is
@code{elm-explorations}, which is handled as a special case, so packages
like @code{elm-explorations/markdown} do @emph{not} need to use the
@code{'upstream-name} property.
@end enumerate

The module @code{(guix build-system elm)} provides the following utilities
for working with names and related conventions:

@deffn {Scheme procedure} elm-package-origin @var{elm-name} @var{version} @
  @var{hash} Returns a Git origin using the repository naming and tagging
regime required for a published Elm package with the upstream name
@var{elm-name} at version @var{version} with sha256 checksum @var{hash}.

For example:
@lisp
(package
  (name "elm-html")
  (version "1.0.0")
  (source
   (elm-package-origin
    "elm/html"
    version
    (base32 "15k1679ja57vvlpinpv06znmrxy09lbhzfkzdc89i01qa8c4gb4a")))
  ...)
@end lisp
@end deffn

@deffn {Scheme procedure} elm->package-name @var{elm-name}
Returns the Guix-style package name for an Elm package with upstream name
@var{elm-name}.

Note that there is more than one possible @var{elm-name} for which
@code{elm->package-name} will produce a given result.
@end deffn

@deffn {Scheme procedure} guix-package->elm-name @var{package}
Given an Elm @var{package}, returns the possibly-inferred upstream name, or
@code{#f} the upstream name is not specified via the @code{'upstream-name}
property and can not be inferred by @code{infer-elm-package-name}.
@end deffn

@deffn {Scheme procedure} infer-elm-package-name @var{guix-name}
Given the @var{guix-name} of an Elm package, returns the inferred upstream
name, or @code{#f} if the upstream name can't be inferred.  If the result is
not @code{#f}, supplying it to @code{elm->package-name} would produce
@var{guix-name}.
@end deffn

@node Fontes
@subsection Fontes

@cindex fontes
Para fontes que geralmente não são instaladas por um usuário para fins de
digitação ou que são distribuídas como parte de um pacote de software maior,
contamos com as regras gerais de empacotamento de software; por exemplo,
isso se aplica às fontes entregues como parte do sistema X.Org ou às fontes
que fazem parte do TeX Live.

Para facilitar a busca de fontes por um usuário, os nomes de outros pacotes
contendo apenas fontes são compilados da seguinte maneira, independentemente
do nome do pacote upstream.

O nome de um pacote que contém apenas uma família de fontes começa com
@code{font-}; é seguido pelo nome da fundição e um traço @code{-} se a
fundição for conhecida e o nome da família da fonte, em que os espaços são
substituídos por hífenes (e, como sempre, todas as letras maiúsculas são
transformadas em minúsculas). Por exemplo, a família de fontes Gentium da
SIL é empacotada com o nome @code{font-sil-gentium}.

Para um pacote que contém várias famílias de fontes, o nome da coleção é
usado no lugar do nome da família de fontes. Por exemplo, as fontes
Liberation consistem em três famílias, Liberation Sans, Liberation Serif e
Liberation Mono. Eles podem ser empacotados separadamente com os nomes
@code{font-liberation-sans} e assim por diante; mas como eles são
distribuídos juntos com um nome comum, preferimos agrupá-los como
@code{font-liberation}.

No caso de vários formatos da mesma família ou coleção de fontes serem
empacotados separadamente, um formato abreviado do formato, precedido por um
traço, é adicionado ao nome do pacote. Usamos @code{-ttf} para fontes
TrueType, @code{-otf} para fontes OpenType e @code{-type1} para fontes
PostScript Type 1.


@node Estilo de código
@section Estilo de código

Em geral, nosso código segue os Padrões de Codificação GNU (@pxref{Top ,,,
standards, GNU Coding Standards}). No entanto, eles não dizem muito sobre
Scheme, então aqui estão algumas regras adicionais.

@menu
* Paradigma de programação::  Como compor seus elementos.
* Módulos::                 Onde armazenar seu código?
* Tipos de dados e correspondência de padrão::  Implementação de 
                                                    estruturas de dados.
* Formatação de código::  Convenções de escrita.
@end menu

@node Paradigma de programação
@subsection Paradigma de programação

O código Scheme no Guix é escrito em um estilo puramente funcional. Uma
exceção é o código que envolve entrada/saída e procedimentos que implementam
conceitos de baixo nível, como o procedimento @code{memoize}.

@node Módulos
@subsection Módulos

Os módulos de Guile que devem ser usados no lado do compilador devem residir
no espaço de nomes @code{(guix build @dots{})}. Eles não devem fazer
referência a outros módulos Guix ou GNU. No entanto, é aceitável que um
módulo no lado do ``hospedeiro'' use um módulo do lado do compilador.

Módulos que lidam com o sistema GNU mais amplo devem estar no espaço de nome
@code{(gnu @dots{})} em vez de @code{(guix @dots{})}.

@node Tipos de dados e correspondência de padrão
@subsection Tipos de dados e correspondência de padrão

A tendência no Lisp clássico é usar listas para representar tudo e, em
seguida, pesquisá-las ``à mão'' usando @code{car}, @code{cdr}, @code{cadr} e
co. Existem vários problemas com esse estilo, notadamente o fato de que é
difícil de ler, propenso a erros e um obstáculo para os relatórios de erros
de tipos adequados.

Guix code should define appropriate data types (for instance, using
@code{define-record-type*}) rather than abuse lists.  In addition, it should
use pattern matching, via Guile’s @code{(ice-9 match)} module, especially
when matching lists (@pxref{Pattern Matching,,, guile, GNU Guile Reference
Manual}).

@node Formatação de código
@subsection Formatação de código

@cindex formatação de código
@cindex estilo de codificação
When writing Scheme code, we follow common wisdom among Scheme programmers.
In general, we follow the
@url{https://mumble.net/~campbell/scheme/style.txt, Riastradh's Lisp Style
Rules}.  This document happens to describe the conventions mostly used in
Guile’s code too.  It is very thoughtful and well written, so please do read
it.

Alguns formulários especiais introduzidos no Guix, como a macro
@code{substitute*}, possuem regras especiais de recuo. Estes são definidos
no arquivo @file{.dir-locals.el}, que o Emacs usa automaticamente. Observe
também que o Emacs-Guix fornece o modo @code{guix-devel-mode} que recua e
destaca o código Guix corretamente (@pxref{Development ,,, emacs-guix, O
manual de referência do Emacs-Guix}).

@cindex recuo, de código
@cindex formatação, de código
Se você não usa o Emacs, por favor, certifique-se que o seu editor conhece
estas regras. Para recuar automaticamente uma definição de pacote, você
também pode executar:

@example
./pre-inst-env guix style @var{package}
@end example

@noindent
@xref{Invoking guix style}, for more information.

@cindex Vim, edição de código Scheme
Se você estiver editando código com o Vim, recomendamos que execute
@code{:set autoindent} para que seu código seja automaticamente recuado na
medida em que você digita. Além disso, o
@uref{https://www.vim.org/scripts/script.php?script_id=3998,
@code{paredit.vim}} pode ajudá-lo a lidar com todos esses parênteses.

Nós exigimos que todos os procedimentos de nível superior carreguem uma
docstring. Porém, este requisito pode ser relaxado para procedimentos
privados simples no espaço de nomes @code{(guix build @dots{})}.

Os procedimentos não devem ter mais de quatro parâmetros posicionais. Use os
parâmetros de palavra-chave para procedimentos que levam mais de quatro
parâmetros.


@node Enviando patches
@section Enviando patches

Development is done using the Git distributed version control system.  Thus,
access to the repository is not strictly necessary.  We welcome
contributions in the form of patches as produced by @code{git format-patch}
sent to the @email{guix-patches@@gnu.org} mailing list (@pxref{Submitting patches to a project,,, git, Git User Manual}).  Contributors are encouraged
to take a moment to set some Git repository options (@pxref{Configurando o Git}) first, which can improve the readability of patches.  Seasoned Guix
developers may also want to look at the section on commit access
(@pxref{Commit Access}).

This mailing list is backed by a Debbugs instance, which allows us to keep
track of submissions (@pxref{Tracking Bugs and Patches}).  Each message sent
to that mailing list gets a new tracking number assigned; people can then
follow up on the submission by sending email to
@code{@var{ISSUE_NUMBER}@@debbugs.gnu.org}, where @var{ISSUE_NUMBER} is the
tracking number (@pxref{Enviando uma série de patches}).

Por favor, escreva os logs de commit no formato de ChangeLog (@pxref{Change Logs ,,, standards, GNU Coding Standards}); você pode verificar o histórico
de commit para exemplos.

Antes de enviar um patch que adicione ou modifique uma definição de pacote,
execute esta lista de verificação:

@enumerate
@item
Se os autores do software empacotado fornecerem uma assinatura criptográfica
para o tarball de lançamento, faça um esforço para verificar a autenticidade
do arquivo. Para um arquivo de assinatura GPG separado, isso seria feito com
o comando @code{gpg --verify}.

@item
Reserve algum tempo para fornecer uma sinopse e descrição adequadas para o
pacote. @xref{Sinopses e descrições}, para algumas diretrizes.

@item
Execute @code{guix lint @var{pacote}}, sendo @var{pacote} o nome do pacote
novo ou modificado e corrija quaisquer erros que forem relatados
(@pxref{Invocando guix lint}).

@item
Run @code{guix style @var{package}} to format the new package definition
according to the project's conventions (@pxref{Invoking guix style}).

@item
Certifique-se de que o pacote compila em sua plataforma, usando @code{guix
build @var{pacote}}.

@item
We recommend you also try building the package on other supported
platforms.  As you may not have access to actual hardware platforms, we
recommend using the @code{qemu-binfmt-service-type} to emulate them.  In
order to enable it, add the @code{virtualization} service module and the
following service to the list of services in your @code{operating-system}
configuration:

@lisp
(service qemu-binfmt-service-type
 (qemu-binfmt-configuration
   (platforms (lookup-qemu-platforms "arm" "aarch64"))))
@end lisp

Então, reconfigure seu sistema.

You can then build packages for different platforms by specifying the
@code{--system} option.  For example, to build the "hello" package for the
armhf or aarch64 architectures, you would run the following commands,
respectively:
@example
guix build --system=armhf-linux --rounds=2 hello
guix build --system=aarch64-linux --rounds=2 hello
@end example

@item
@cindex incorporando
Verifique se o pacote não usa cópias de software já disponíveis como pacotes
separados.

Às vezes, os pacotes incluem cópias do código-fonte de suas dependências
como uma conveniência para os usuários. No entanto, como uma distribuição,
queremos garantir que esses pacotes acabem usando a cópia que já temos na
distribuição, se houver. Isso melhora o uso de recursos (a dependência é
criada e armazenada apenas uma vez) e permite que a distribuição faça
alterações transversais, como aplicar atualizações de segurança para um
determinado pacote de software em um único local e fazê-las afetar todo o
sistema -- algo que cópias incluídas impedem.

@item
Take a look at the profile reported by @command{guix size} (@pxref{Invocando guix size}).  This will allow you to notice references to other packages
unwillingly retained.  It may also help determine whether to split the
package (@pxref{Pacotes com múltiplas saídas}), and which optional
dependencies should be used.  In particular, avoid adding @code{texlive} as
a dependency: because of its extreme size, use the @code{texlive-tiny}
package or @code{texlive-union} procedure instead.

@item
For important changes, check that dependent packages (if applicable) are not
affected by the change; @code{guix refresh --list-dependent @var{package}}
will help you do that (@pxref{Invocando guix refresh}).

@c See <https://lists.gnu.org/archive/html/guix-devel/2016-10/msg00933.html>.
@cindex estratégia de ramificação
@cindex estratégia de agendamento de recompilação
Dependendo do número de pacotes dependentes e, portanto, da quantidade de
recompilação induzida, os commits vão para diferentes ramos, ao longo das
seguintes linhas:

@table @asis
@item 300 pacotes dependentes ou menos
Ramo @code{master} (alterações não disruptivas).

@item between 300 and 1,800 dependent packages
@code{staging} branch (non-disruptive changes).  This branch is intended to
be merged in @code{master} every 6 weeks or so.  Topical changes (e.g., an
update of the GNOME stack) can instead go to a specific branch (say,
@code{gnome-updates}).  This branch is not expected to be buildable or
usable until late in its development process.

@item more than 1,800 dependent packages
@code{core-updates} branch (may include major and potentially disruptive
changes).  This branch is intended to be merged in @code{master} every 6
months or so.  This branch is not expected to be buildable or usable until
late in its development process.
@end table

All these branches are @uref{https://@value{SUBSTITUTE-SERVER-1}, tracked by
our build farm} and merged into @code{master} once everything has been
successfully built.  This allows us to fix issues before they hit users, and
to reduce the window during which pre-built binaries are not available.

@c TODO: It would be good with badges on the website that tracks these
@c branches.  Or maybe even a status page.
When we decide to start building the @code{staging} or @code{core-updates}
branches, they will be forked and renamed with the suffix @code{-frozen}, at
which time only bug fixes may be pushed to the frozen branches.  The
@code{core-updates} and @code{staging} branches will remain open to accept
patches for the next cycle.  Please ask on the mailing list or IRC if unsure
where to place a patch.

@item
@cindex determinismo, de processos de compilação
@cindex compilações reproduzíveis, verificação
Verifique se o processo de compilação do pacote é determinístico. Isso
normalmente significa verificar se uma compilação independente do pacote
produz o mesmo resultado que você obteve, bit por bit.

Uma maneira simples de fazer isso é compilar o mesmo pacote várias vezes
seguidas em sua máquina (@pxref{Invocando guix build}):

@example
guix build --rounds=2 meu-pacote
@end example

Isso é suficiente para capturar uma classe de problemas comuns de
não-determinismo, como registros de data e hora ou saída gerada
aleatoriamente no resultado da compilação.

Another option is to use @command{guix challenge} (@pxref{Invocando guix challenge}).  You may run it once the package has been committed and built
by @code{@value{SUBSTITUTE-SERVER-1}} to check whether it obtains the same
result as you did.  Better yet: Find another machine that can build it and
run @command{guix publish}.  Since the remote build machine is likely
different from yours, this can catch non-determinism issues related to the
hardware---e.g., use of different instruction set extensions---or to the
operating system kernel---e.g., reliance on @code{uname} or @file{/proc}
files.

@item
Ao escrever documentação, por favor, use palavras de gênero neutras ao se
referir a pessoas, como @uref{https://en.wikipedia.org/wiki/Singular_they,
singular ``they''@comma{} ``their'' @comma{} ``them''}, e assim por diante.

@item
Verifique se o seu patch contém apenas um conjunto de alterações
relacionadas. Agrupar mudanças não relacionadas juntas torna a revisão mais
difícil e lenta.

Exemplos de alterações não relacionadas incluem a adição de vários pacotes
ou uma atualização de pacote juntamente com correções para esse pacote.

@item
Please follow our code formatting rules, possibly running @command{guix
style} script to do that automatically for you (@pxref{Formatação de código}).

@item
Quando possível, use espelhos no URL fonte (@pxref{Invocando guix download}). Use URLs confiáveis, não os gerados. Por exemplo, os arquivos do
GitHub não são necessariamente idênticos de uma geração para a seguinte,
portanto, nesse caso, geralmente é melhor clonar o repositório. Não use o
campo @command{name} no URL: não é muito útil e se o nome mudar, o URL
provavelmente estará errado.

@item
Check if Guix builds (@pxref{Compilando do git}) and address the warnings,
especially those about use of undefined symbols.

@item
Make sure your changes do not break Guix and simulate a @code{guix pull}
with:
@example
guix pull --url=/path/to/your/checkout --profile=/tmp/guix.master
@end example

@end enumerate

When posting a patch to the mailing list, use @samp{[PATCH] @dots{}} as a
subject, if your patch is to be applied on a branch other than
@code{master}, say @code{core-updates}, specify it in the subject like
@samp{[PATCH core-updates] @dots{}}.

You may use your email client or the @command{git send-email} command
(@pxref{Enviando uma série de patches}).  We prefer to get patches in plain text
messages, either inline or as MIME attachments.  You are advised to pay
attention if your email client changes anything like line breaks or
indentation which could potentially break the patches.

Expect some delay when you submit your very first patch to
@email{guix-patches@@gnu.org}. You have to wait until you get an
acknowledgement with the assigned tracking number. Future acknowledgements
should not be delayed.

When a bug is resolved, please close the thread by sending an email to
@email{@var{ISSUE_NUMBER}-done@@debbugs.gnu.org}.

@node Configurando o Git
@subsection Configurando o Git
@cindex Configuração do git
@cindex @code{git format-patch}
@cindex @code{git send-email}

If you have not done so already, you may wish to set a name and email that
will be associated with your commits (@pxref{telling git your name, ,
Telling Git your name, git, Git User Manual}).  If you wish to use a
different name or email just for commits in this repository, you can use
@command{git config --local}, or edit @file{.git/config} in the repository
instead of @file{~/.gitconfig}.

We provide some default settings in @file{etc/git/gitconfig} which modify
how patches are generated, making them easier to read and apply.  These
settings can be applied by manually copying them to @file{.git/config} in
your checkout, or by telling Git to include the whole file:

@example
git config --local include.path ../etc/git/gitconfig
@end example

From then on, any changes to @file{etc/git/gitconfig} would automatically
take effect.

Since the first patch in a series must be sent separately (@pxref{Enviando uma série de patches}), it can also be helpful to tell @command{git format-patch} to
handle the e-mail threading instead of @command{git send-email}:

@example
git config --local format.thread shallow
git config --local sendemail.thread no
@end example

@node Enviando uma série de patches
@subsection Enviando uma série de patches
@cindex série de patches
@cindex @code{git send-email}
@cindex @code{git format-patch}

@unnumberedsubsubsec Single Patches
@anchor{Single Patches}
The @command{git send-email} command is the best way to send both single
patches and patch series (@pxref{Multiple Patches}) to the Guix mailing
list.  Sending patches as email attachments may make them difficult to
review in some mail clients, and @command{git diff} does not store commit
metadata.

@quotation Nota
The @command{git send-email} command is provided by the @code{send-email}
output of the @code{git} package, i.e. @code{git:send-email}.
@end quotation

The following command will create a patch email from the latest commit, open
it in your @var{EDITOR} or @var{VISUAL} for editing, and send it to the Guix
mailing list to be reviewed and merged:

@example
$ git send-email -1 -a --base=auto --to=guix-patches@@gnu.org
@end example

@quotation Tip
To add a prefix to the subject of your patch, you may use the
@option{--subject-prefix} option.  The Guix project uses this to specify
that the patch is intended for a branch or repository other than the
@code{master} branch of @url{https://git.savannah.gnu.org/cgit/guix.git}.

@example
git send-email -1 -a --base=auto \
    --subject-prefix='PATCH core-updates' \
    --to=guix-patches@@gnu.org
@end example
@end quotation

The patch email contains a three-dash separator line after the commit
message.  You may ``annotate'' the patch with explanatory text by adding it
under this line.  If you do not wish to annotate the email, you may drop the
@option{-a} flag (which is short for @option{--annotate}).

The @option{--base=auto} flag automatically adds a note at the bottom of the
patch of the commit it was based on, making it easier for maintainers to
rebase and merge your patch.

If you need to send a revised patch, don't resend it like this or send a
``fix'' patch to be applied on top of the last one; instead, use
@command{git commit -a} or @url{https://git-rebase.io, @command{git rebase}}
to modify the commit, and use the
@email{@var{ISSUE_NUMBER}@@debbugs.gnu.org} address and the @option{-v} flag
with @command{git send-email}.

@example
$ git commit -a
$ git send-email -1 -a --base=auto -v @var{REVISION} \
      --to=@var{ISSUE_NUMBER}@@debbugs.gnu.org
@end example

You can find out @var{ISSUE_NUMBER} either by searching on the mumi
interface at @url{issues.guix.gnu.org} for the name of your patch or reading
the acknowledgement email sent automatically by Debbugs in reply to incoming
bugs and patches, which contains the bug number.

@unnumberedsubsubsec Notifying Teams
@anchor{Notifying Teams}
@cindex teams
The @file{etc/teams.scm} script may be used to notify all those who may be
interested in your patch of its existence (@pxref{Teams}).  Use
@command{etc/teams.scm list-teams} to display all the teams, decide which
team(s) your patch relates to, and use @command{etc/teams.scm cc} to output
various @command{git send-email} flags which will notify the appropriate
team members, or use @command{etc/teams.scm cc-members} to detect the
appropriate teams automatically.

@unnumberedsubsubsec Multiple Patches
@anchor{Multiple Patches}
@cindex cover letter
While @command{git send-email} alone will suffice for a single patch, an
unfortunate flaw in Debbugs means you need to be more careful when sending
multiple patches: if you send them all to the @email{guix-patches@@gnu.org}
address, a new issue will be created for each patch!

When sending a series of patches, it's best to send a Git ``cover letter''
first, to give reviewers an overview of the patch series.  We can create a
directory called @file{outgoing} containing both our patch series and a
cover letter called @file{0000-cover-letter.patch} with @command{git
format-patch}.

@example
$ git format-patch -@var{NUMBER_COMMITS} -o outgoing \
      --cover-letter --base=auto
@end example

We can now send @emph{just} the cover letter to the
@email{guix-patches@@gnu.org} address, which will create an issue that we
can send the rest of the patches to.

@example
$ git send-email outgoing/0000-cover-letter.patch -a \
      --to=guix-patches@@debbugs.gnu.org \
      $(etc/teams.scm cc-members ...)
$ rm outgoing/0000-cover-letter.patch # we don't want to resend it!
@end example

Ensure you edit the email to add an appropriate subject line and blurb
before sending it.  Note the automatically generated shortlog and diffstat
below the blurb.

Once the Debbugs mailer has replied to your cover letter email, you can send
the actual patches to the newly-created issue address.

@example
$ git send-email outgoing/*.patch \
      --to=@var{ISSUE_NUMBER}@@debbugs.gnu.org \
      $(etc/teams.scm cc-members ...)
$ rm -rf outgoing # we don't need these anymore
@end example

Thankfully, this @command{git format-patch} dance is not necessary to send
an amended patch series, since an issue already exists for the patchset.

@example
$ git send-email -@var{NUMBER_COMMITS} \
      -v@var{REVISION} --base=auto \
      --to @var{ISSUE_NUMBER}@@debbugs.gnu.org
@end example

If need be, you may use @option{--cover-letter -a} to send another cover
letter, e.g. for explaining what's changed since the last revision, and
these changes are necessary.

@node Teams
@subsection Teams
@cindex teams

There are several teams mentoring different parts of the Guix source code.
To list all those teams, you can run from a Guix checkout:

@example
$ ./etc/teams.scm list-teams
id: mentors
name: Mentors
description: A group of mentors who chaperone contributions by newcomers.
members:
+ Christopher Baines <mail@@cbaines.net>
+ Ricardo Wurmus <rekado@@elephly.net>
+ Mathieu Othacehe <othacehe@@gnu.org>
+ jgart <jgart@@dismail.de>
+ Ludovic Courtès <ludo@@gnu.org>
@dots{}
@end example

You can run the following command to have the @code{Mentors} team put in CC
of a patch series:

@example
$ git send-email --to @var{ISSUE_NUMBER}@@debbugs.gnu.org $(./etc/teams.scm cc mentors) *.patch
@end example

The appropriate team or teams can also be inferred from the modified files.
For instance, if you want to send the two latest commits of the current Git
repository to review, you can run:

@example
$ guix shell -D guix
[env]$ git send-email --to @var{ISSUE_NUMBER}@@debbugs.gnu.org $(./etc/teams.scm cc-members HEAD~2 HEAD) *.patch
@end example

@node Tracking Bugs and Patches
@section Tracking Bugs and Patches

This section describes how the Guix project tracks its bug reports and patch
submissions.

@menu
* The Issue Tracker::        The official bug and patch tracker.
* Debbugs User Interfaces::  Ways to interact with Debbugs.
* Debbugs Usertags::         Tag reports with custom labels.
@end menu

@node The Issue Tracker
@subsection The Issue Tracker

@cindex bug reports, tracking
@cindex patch submissions, tracking
@cindex issue tracking
@cindex Debbugs, issue tracking system
Bug reports and patch submissions are currently tracked using the Debbugs
instance at @uref{https://bugs.gnu.org}.  Bug reports are filed against the
@code{guix} ``package'' (in Debbugs parlance), by sending email to
@email{bug-guix@@gnu.org}, while patch submissions are filed against the
@code{guix-patches} package by sending email to
@email{guix-patches@@gnu.org} (@pxref{Enviando patches}).

@node Debbugs User Interfaces
@subsection Debbugs User Interfaces

A web interface (actually @emph{two} web interfaces!) are available to
browse issues:

@itemize
@item
@url{https://issues.guix.gnu.org} provides a pleasant interface@footnote{The
web interface at @url{https://issues.guix.gnu.org} is powered by Mumi, a
nice piece of software written in Guile, and you can help! See
@url{https://git.elephly.net/gitweb.cgi?p=software/mumi.git}.} to browse bug
reports and patches, and to participate in discussions;
@item
@url{https://bugs.gnu.org/guix} lists bug reports;
@item
@url{https://bugs.gnu.org/guix-patches} lists patch submissions.
@end itemize

To view discussions related to issue number @var{n}, go to
@indicateurl{https://issues.guix.gnu.org/@var{n}} or
@indicateurl{https://bugs.gnu.org/@var{n}}.

If you use Emacs, you may find it more convenient to interact with issues
using @file{debbugs.el}, which you can install with:

@example
guix install emacs-debbugs
@end example

For example, to list all open issues on @code{guix-patches}, hit:

@example
@kbd{C-u} @kbd{M-x} debbugs-gnu @kbd{RET} @kbd{RET} guix-patches @kbd{RET} n y
@end example

@xref{Top,,, debbugs-ug, Debbugs User Guide}, for more information on this
nifty tool!

@node Debbugs Usertags
@subsection Debbugs Usertags

@cindex usertags, for debbugs
@cindex Debbugs usertags
Debbugs provides a feature called @dfn{usertags} that allows any user to tag
any bug with an arbitrary label.  Bugs can be searched by usertag, so this
is a handy way to organize bugs@footnote{The list of usertags is public
information, and anyone can modify any user's list of usertags, so keep that
in mind if you choose to use this feature.}.

For example, to view all the bug reports (or patches, in the case of
@code{guix-patches}) tagged with the usertag @code{powerpc64le-linux} for
the user @code{guix}, open a URL like the following in a web browser:
@url{https://debbugs.gnu.org/cgi-bin/pkgreport.cgi?tag=powerpc64le-linux;users=guix}.

For more information on how to use usertags, please refer to the
documentation for Debbugs or the documentation for whatever tool you use to
interact with Debbugs.

In Guix, we are experimenting with usertags to keep track of
architecture-specific issues.  To facilitate collaboration, all our usertags
are associated with the single user @code{guix}.  The following usertags
currently exist for that user:

@table @code

@item powerpc64le-linux
The purpose of this usertag is to make it easy to find the issues that
matter most for the @code{powerpc64le-linux} system type.  Please assign
this usertag to bugs or patches that affect @code{powerpc64le-linux} but not
other system types.  In addition, you may use it to identify issues that for
some reason are particularly important for the @code{powerpc64le-linux}
system type, even if the issue affects other system types, too.

@item reproducibility
For issues related to reproducibility.  For example, it would be appropriate
to assign this usertag to a bug report for a package that fails to build
reproducibly.

@end table

If you're a committer and you want to add a usertag, just start using it
with the @code{guix} user.  If the usertag proves useful to you, consider
updating this section of the manual so that others will know what your
usertag means.

@node Commit Access
@section Commit Access

@cindex commit access, for developers
Everyone can contribute to Guix without having commit access
(@pxref{Enviando patches}).  However, for frequent contributors, having
write access to the repository can be convenient.  As a rule of thumb, a
contributor should have accumulated fifty (50) reviewed commits to be
considered as a committer and have sustained their activity in the project
for at least 6 months.  This ensures enough interactions with the
contributor, which is essential for mentoring and assessing whether they are
ready to become a committer.  Commit access should not be thought of as a
``badge of honor'' but rather as a responsibility a contributor is willing
to take to help the project.

The following sections explain how to get commit access, how to be ready to
push commits, and the policies and community expectations for commits pushed
upstream.

@subsection Applying for Commit Access

When you deem it necessary, consider applying for commit access by following
these steps:

@enumerate
@item
Find three committers who would vouch for you.  You can view the list of
committers at
@url{https://savannah.gnu.org/project/memberlist.php?group=guix}.  Each of
them should email a statement to @email{guix-maintainers@@gnu.org} (a
private alias for the collective of maintainers), signed with their OpenPGP
key.

Committers are expected to have had some interactions with you as a
contributor and to be able to judge whether you are sufficiently familiar
with the project's practices.  It is @emph{not} a judgment on the value of
your work, so a refusal should rather be interpreted as ``let's try again
later''.

@item
Send @email{guix-maintainers@@gnu.org} a message stating your intent,
listing the three committers who support your application, signed with the
OpenPGP key you will use to sign commits, and giving its fingerprint (see
below).  See @uref{https://emailselfdefense.fsf.org/en/}, for an
introduction to public-key cryptography with GnuPG.

@c See <https://sha-mbles.github.io/>.
Set up GnuPG such that it never uses the SHA1 hash algorithm for digital
signatures, which is known to be unsafe since 2019, for instance by adding
the following line to @file{~/.gnupg/gpg.conf} (@pxref{GPG Esoteric Options,,, gnupg, The GNU Privacy Guard Manual}):

@example
digest-algo sha512
@end example

@item
Maintainers ultimately decide whether to grant you commit access, usually
following your referrals' recommendation.

@item
@cindex OpenPGP, signed commits
If and once you've been given access, please send a message to
@email{guix-devel@@gnu.org} to say so, again signed with the OpenPGP key you
will use to sign commits (do that before pushing your first commit).  That
way, everyone can notice and ensure you control that OpenPGP key.

@quotation Importante
Before you can push for the first time, maintainers must:

@enumerate
@item
add your OpenPGP key to the @code{keyring} branch;
@item
add your OpenPGP fingerprint to the @file{.guix-authorizations} file of the
branch(es) you will commit to.
@end enumerate
@end quotation

@item
Make sure to read the rest of this section and... profit!
@end enumerate

@quotation Nota
Maintainers are happy to give commit access to people who have been
contributing for some time and have a track record---don't be shy and don't
underestimate your work!

However, note that the project is working towards a more automated patch
review and merging system, which, as a consequence, may lead us to have
fewer people with commit access to the main repository.  Stay tuned!
@end quotation

All commits that are pushed to the central repository on Savannah must be
signed with an OpenPGP key, and the public key should be uploaded to your
user account on Savannah and to public key servers, such as
@code{keys.openpgp.org}.  To configure Git to automatically sign commits,
run:

@example
git config commit.gpgsign true

# Substitute the fingerprint of your public PGP key.
git config user.signingkey CABBA6EA1DC0FF33
@end example

To check that commits are signed with correct key, use:

@example
make authenticate
@end example

You can prevent yourself from accidentally pushing unsigned or signed with
the wrong key commits to Savannah by using the pre-push Git hook located at
@file{etc/git/pre-push}:

@example
cp etc/git/pre-push .git/hooks/pre-push
@end example

It additionally calls @code{make check-channel-news} to be sure
@file{news.scm} file is correct.

@subsection Commit Policy

If you get commit access, please make sure to follow the policy below
(discussions of the policy can take place on @email{guix-devel@@gnu.org}).

Non-trivial patches should always be posted to @email{guix-patches@@gnu.org}
(trivial patches include fixing typos, etc.).  This mailing list fills the
patch-tracking database (@pxref{Tracking Bugs and Patches}).

For patches that just add a new package, and a simple one, it's OK to
commit, if you're confident (which means you successfully built it in a
chroot setup, and have done a reasonable copyright and license auditing).
Likewise for package upgrades, except upgrades that trigger a lot of
rebuilds (for example, upgrading GnuTLS or GLib).  We have a mailing list
for commit notifications (@email{guix-commits@@gnu.org}), so people can
notice.  Before pushing your changes, make sure to run @code{git pull
--rebase}.

When pushing a commit on behalf of somebody else, please add a
@code{Signed-off-by} line at the end of the commit log message---e.g., with
@command{git am --signoff}.  This improves tracking of who did what.

When adding channel news entries (@pxref{Canais, Writing Channel News}),
make sure they are well-formed by running the following command right before
pushing:

@example
make check-channel-news
@end example

For anything else, please post to @email{guix-patches@@gnu.org} and leave
time for a review, without committing anything (@pxref{Enviando patches}).  If you didn’t receive any reply after two weeks, and if you're
confident, it's OK to commit.

That last part is subject to being adjusted, allowing individuals to commit
directly on non-controversial changes on parts they’re familiar with.

@subsection Addressing Issues

Peer review (@pxref{Enviando patches}) and tools such as @command{guix
lint} (@pxref{Invocando guix lint}) and the test suite (@pxref{Executando a suíte de testes}) should catch issues before they are pushed.  Yet, commits that
``break'' functionality might occasionally go through.  When that happens,
there are two priorities: mitigating the impact, and understanding what
happened to reduce the chance of similar incidents in the future.  The
responsibility for both these things primarily lies with those involved, but
like everything this is a group effort.

Some issues can directly affect all users---for instance because they make
@command{guix pull} fail or break core functionality, because they break
major packages (at build time or run time), or because they introduce known
security vulnerabilities.

@cindex reverting commits
The people involved in authoring, reviewing, and pushing such commit(s)
should be at the forefront to mitigate their impact in a timely fashion: by
pushing a followup commit to fix it (if possible), or by reverting it to
leave time to come up with a proper fix, and by communicating with other
developers about the problem.

If these persons are unavailable to address the issue in time, other
committers are entitled to revert the commit(s), explaining in the commit
log and on the mailing list what the problem was, with the goal of leaving
time to the original committer, reviewer(s), and author(s)  to propose a way
forward.

Once the problem has been dealt with, it is the responsibility of those
involved to make sure the situation is understood.  If you are working to
understand what happened, focus on gathering information and avoid assigning
any blame.  Do ask those involved to describe what happened, do not ask them
to explain the situation---this would implicitly blame them, which is
unhelpful.  Accountability comes from a consensus about the problem,
learning from it and improving processes so that it's less likely to
reoccur.

@subsection Commit Revocation

In order to reduce the possibility of mistakes, committers will have their
Savannah account removed from the Guix Savannah project and their key
removed from @file{.guix-authorizations} after 12 months of inactivity; they
can ask to regain commit access by emailing the maintainers, without going
through the vouching process.

Maintainers@footnote{See @uref{https://guix.gnu.org/en/about} for the
current list of maintainers.  You can email them privately at
@email{guix-maintainers@@gnu.org}.} may also revoke an individual's commit
rights, as a last resort, if cooperation with the rest of the community has
caused too much friction---even within the bounds of the project's code of
conduct (@pxref{Contribuindo}).  They would only do so after public or
private discussion with the individual and a clear notice.  Examples of
behavior that hinders cooperation and could lead to such a decision include:

@itemize
@item repeated violation of the commit policy stated above;
@item repeated failure to take peer criticism into account;
@item breaching trust through a series of grave incidents.
@end itemize

When maintainers resort to such a decision, they notify developers on
@email{guix-devel@@gnu.org}; inquiries may be sent to
@email{guix-maintainers@@gnu.org}.  Depending on the situation, the
individual may still be welcome to contribute.

@subsection Helping Out

One last thing: the project keeps moving forward because committers not only
push their own awesome changes, but also offer some of their time
@emph{reviewing} and pushing other people's changes.  As a committer, you're
welcome to use your expertise and commit rights to help other contributors,
too!

@node Updating the Guix Package
@section Updating the Guix Package

@cindex update-guix-package, updating the guix package
It is sometimes desirable to update the @code{guix} package itself (the
package defined in @code{(gnu packages package-management)}), for example to
make new daemon features available for use by the @code{guix-service-type}
service type.  In order to simplify this task, the following command can be
used:

@example
make update-guix-package
@end example

The @code{update-guix-package} make target will use the last known
@emph{commit} corresponding to @code{HEAD} in your Guix checkout, compute
the hash of the Guix sources corresponding to that commit and update the
@code{commit}, @code{revision} and hash of the @code{guix} package
definition.

To validate that the updated @code{guix} package hashes are correct and that
it can be built successfully, the following command can be run from the
directory of your Guix checkout:

@example
./pre-inst-env guix build guix
@end example

To guard against accidentally updating the @code{guix} package to a commit
that others can't refer to, a check is made that the commit used has already
been pushed to the Savannah-hosted Guix git repository.

This check can be disabled, @emph{at your own peril}, by setting the
@code{GUIX_ALLOW_ME_TO_USE_PRIVATE_COMMIT} environment variable.  When this
variable is set, the updated package source is also added to the store.
This is used as part of the release process of Guix.

@cindex documentation
@node Writing Documentation
@section Writing Documentation

Guix is documented using the Texinfo system.  If you are not yet familiar
with it, we accept contributions for documentation in most formats.  That
includes plain text, Markdown, Org, etc.

Documentation contributions can be sent to @email{guix-patches@@gnu.org}.
Prepend @samp{[DOCUMENTATION]} to the subject.

When you need to make more than a simple addition to the documentation, we
prefer that you send a proper patch as opposed to sending an email as
described above.  @xref{Enviando patches} for more information on how to
send your patches.

To modify the documentation, you need to edit @file{doc/guix.texi} and
@file{doc/contributing.texi} (which contains this documentation section), or
@file{doc/guix-cookbook.texi} for the cookbook.  If you compiled the Guix
repository before, you will have many more @file{.texi} files that are
translations of these documents.  Do not modify them, the translation is
managed through @uref{https://translate.fedoraproject.org/projects/guix,
Weblate}.  @xref{Traduzindo o Guix} for more information.

To render documentation, you must first make sure that you ran
@command{./configure} in your source tree (@pxref{Executando guix antes dele ser instalado}).  After that you can run one of the following commands:

@itemize
@item @samp{make doc/guix.info} to compile the Info manual.
      You can check it with @command{info doc/guix.info}.
@item @samp{make doc/guix.html} to compile the HTML version.
      You can point your browser to the relevant file in the @file{doc/guix.html}
directory.
@item @samp{make doc/guix-cookbook.info} for the cookbook Info manual.
@item @samp{make doc/guix-cookbook.html} for the cookbook HTML version.
@end itemize

@cindex tradução
@cindex l10n
@cindex i18n
@cindex native language support
@node Traduzindo o Guix
@section Traduzindo o Guix

Writing code and packages is not the only way to provide a meaningful
contribution to Guix.  Translating to a language you speak is another
example of a valuable contribution you can make.  This section is designed
to describe the translation process.  It gives you advice on how you can get
involved, what can be translated, what mistakes you should avoid and what we
can do to help you!

Guix is a big project that has multiple components that can be translated.
We coordinate the translation effort on a
@uref{https://translate.fedoraproject.org/projects/guix/,Weblate instance}
hosted by our friends at Fedora.  You will need an account to submit
translations.

Some of the software packaged in Guix also contain translations.  We do not
host a translation platform for them.  If you want to translate a package
provided by Guix, you should contact their developers or find the
information on their website.  As an example, you can find the homepage of
the @code{hello} package by typing @code{guix show hello}.  On the
``homepage'' line, you will see @url{https://www.gnu.org/software/hello/} as
the homepage.

Many GNU and non-GNU packages can be translated on the
@uref{https://translationproject.org,Translation Project}.  Some projects
with multiple components have their own platform.  For instance, GNOME has
its own platform, @uref{https://l10n.gnome.org/,Damned Lies}.

Guix has five components hosted on Weblate.

@itemize
@item @code{guix} contains all the strings from the Guix software (the
      guided system installer, the package manager, etc), excluding packages.
@item @code{packages} contains the synopsis (single-sentence description
      of a package) and description (longer description) of packages in Guix.
@item @code{website} contains the official Guix website, except for
      blog posts and multimedia content.
@item @code{documentation-manual} corresponds to this manual.
@item @code{documentation-cookbook} is the component for the cookbook.
@end itemize

@subsubheading General Directions

Once you get an account, you should be able to select a component from
@uref{https://translate.fedoraproject.org/projects/guix/,the guix project},
and select a language.  If your language does not appear in the list, go to
the bottom and click on the ``Start new translation'' button.  Select the
language you want to translate to from the list, to start your new
translation.

Like lots of other free software packages, Guix uses
@uref{https://www.gnu.org/software/gettext,GNU Gettext} for its
translations, with which translatable strings are extracted from the source
code to so-called PO files.

Even though PO files are text files, changes should not be made with a text
editor but with PO editing software.  Weblate integrates PO editing
functionality.  Alternatively, translators can use any of various
free-software tools for filling in translations, of which
@uref{https://poedit.net/,Poedit} is one example, and (after logging in)
@uref{https://docs.weblate.org/en/latest/user/files.html,upload} the changed
file.  There is also a special
@uref{https://www.emacswiki.org/emacs/PoMode,PO editing mode} for users of
GNU Emacs.  Over time translators find out what software they are happy with
and what features they need.

On Weblate, you will find various links to the editor, that will show
various subsets (or all) of the strings.  Have a look around and at the
@uref{https://docs.weblate.org/en/latest/,documentation} to familiarize
yourself with the platform.

@subsubheading Translation Components

In this section, we provide more detailed guidance on the translation
process, as well as details on what you should or should not do.  When in
doubt, please contact us, we will be happy to help!

@table @asis
@item guix
Guix is written in the Guile programming language, and some strings contain
special formatting that is interpreted by Guile.  These special formatting
should be highlighted by Weblate.  They start with @code{~} followed by one
or more characters.

When printing the string, Guile replaces the special formatting symbols with
actual values.  For instance, the string @samp{ambiguous package
specification `~a'} would be substituted to contain said package
specification instead of @code{~a}.  To properly translate this string, you
must keep the formatting code in your translation, although you can place it
where it makes sense in your language.  For instance, the French translation
says @samp{spécification du paquet « ~a » ambiguë} because the adjective
needs to be placed in the end of the sentence.

If there are multiple formatting symbols, make sure to respect the order.
Guile does not know in which order you intended the string to be read, so it
will substitute the symbols in the same order as the English sentence.

As an example, you cannot translate @samp{package '~a' has been superseded
by '~a'} by @samp{'~a' superseeds package '~a'}, because the meaning would
be reversed.  If @var{foo} is superseded by @var{bar}, the translation would
read @samp{'foo' superseeds package 'bar'}.  To work around this problem, it
is possible to use more advanced formatting to select a given piece of data,
instead of following the default English order.  @xref{Formatted Output,,,
guile, GNU Guile Reference Manual}, for more information on formatting in
Guile.

@item pacotes

Package descriptions occasionally contain Texinfo markup (@pxref{Sinopses e descrições}).  Texinfo markup looks like @samp{@@code@{rm -rf@}},
@samp{@@emph@{important@}}, etc.  When translating, please leave markup as
is.

The characters after ``@@'' form the name of the markup, and the text
between ``@{'' and ``@}'' is its content.  In general, you should not
translate the content of markup like @code{@@code}, as it contains literal
code that do not change with language.  You can translate the content of
formatting markup such as @code{@@emph}, @code{@@i}, @code{@@itemize},
@code{@@item}.  However, do not translate the name of the markup, or it will
not be recognized.  Do not translate the word after @code{@@end}, it is the
name of the markup that is closed at this position (e.g.@: @code{@@itemize
... @@end itemize}).

@item documentation-manual and documentation-cookbook

The first step to ensure a successful translation of the manual is to find
and translate the following strings @emph{first}:

@itemize
@item @code{version.texi}: Translate this string as @code{version-xx.texi},
      where @code{xx} is your language code (the one shown in the URL on weblate).
@item @code{contributing.texi}: Translate this string as
      @code{contributing.xx.texi}, where @code{xx} is the same language code.
@item @code{Top}: Do not translate this string, it is important for Texinfo.
      If you translate it, the document will be empty (missing a Top node).
Please look for it, and register @code{Top} as its translation.
@end itemize

Translating these strings first ensure we can include your translation in
the guix repository without breaking the make process or the @command{guix
pull} machinery.

The manual and the cookbook both use Texinfo.  As for @code{packages},
please keep Texinfo markup as is.  There are more possible markup types in
the manual than in the package descriptions.  In general, do not translate
the content of @code{@@code}, @code{@@file}, @code{@@var}, @code{@@value},
etc.  You should translate the content of formatting markup such as
@code{@@emph}, @code{@@i}, etc.

The manual contains sections that can be referred to by name by
@code{@@ref}, @code{@@xref} and @code{@@pxref}.  We have a mechanism in
place so you do not have to translate their content.  If you keep the
English title, we will automatically replace it with your translation of
that title.  This ensures that Texinfo will always be able to find the
node. If you decide to change the translation of the title, the references
will automatically be updated and you will not have to update them all
yourself.

When translating references from the cookbook to the manual, you need to
replace the name of the manual and the name of the section.  For instance,
to translate @code{@@pxref@{Defining Packages,,, guix, GNU Guix Reference
Manual@}}, you would replace @code{Defining Packages} with the title of that
section in the translated manual @emph{only} if that title is translated.
If the title is not translated in your language yet, do not translate it
here, or the link will be broken.  Replace @code{guix} with @code{guix.xx}
where @code{xx} is your language code.  @code{GNU Guix Reference Manual} is
the text of the link.  You can translate it however you wish.

@item website

The website pages are written using SXML, an s-expression version of HTML,
the basic language of the web.  We have a process to extract translatable
strings from the source, and replace complex s-expressions with a more
familiar XML markup, where each markup is numbered.  Translators can
arbitrarily change the ordering, as in the following example.

@example
#. TRANSLATORS: Defining Packages is a section name
#. in the English (en) manual.
#: apps/base/templates/about.scm:64
msgid "Packages are <1>defined<1.1>en</1.1><1.2>Defining-Packages.html</1.2></1> as native <2>Guile</2> modules."
msgstr "Pakete werden als reine <2>Guile</2>-Module <1>definiert<1.1>de</1.1><1.2>Pakete-definieren.html</1.2></1>."
@end example

Note that you need to include the same markups.  You cannot skip any.
@end table

In case you make a mistake, the component might fail to build properly with
your language, or even make guix pull fail.  To prevent that, we have a
process in place to check the content of the files before pushing to our
repository.  We will not be able to update the translation for your language
in Guix, so we will notify you (through weblate and/or by email) so you get
a chance to fix the issue.

@subsubheading Outside of Weblate

Currently, some parts of Guix cannot be translated on Weblate, help wanted!

@itemize
@item @command{guix pull} news can be translated in @file{news.scm}, but is not
      available from Weblate.  If you want to provide a translation, you can
prepare a patch as described above, or simply send us your translation with
the name of the news entry you translated and your language. @xref{Writing Channel News}, for more information about channel news.
@item Guix blog posts cannot currently be translated.
@item The installer script (for foreign distributions) is entirely in English.
@item Some of the libraries Guix uses cannot be translated or are translated
      outside of the Guix project.  Guile itself is not internationalized.
@item Other manuals linked from this manual or the cookbook might not be
      translated.
@end itemize

@subsubheading Conditions for Inclusion

There are no conditions for adding new translations of the @code{guix} and
@code{guix-packages} components, other than they need at least one
translated string.  New languages will be added to Guix as soon as
possible.  The files may be removed if they fall out of sync and have no
more translated strings.

Given that the web site is dedicated to new users, we want its translation
to be as complete as possible before we include it in the language menu.
For a new language to be included, it needs to reach at least 80%
completion.  When a language is included, it may be removed in the future if
it stays out of sync and falls below 60% completion.

The manual and cookbook are automatically added in the default compilation
target.  Every time we synchronize translations, developers need to
recompile all the translated manuals and cookbooks.  This is useless for
what is essentially the English manual or cookbook.  Therefore, we will only
include a new language when it reaches 10% completion in the component.
When a language is included, it may be removed in the future if it stays out
of sync and falls below 5% completion.

@subsubheading Translation Infrastructure

Weblate is backed by a git repository from which it discovers new strings to
translate and pushes new and updated translations.  Normally, it would be
enough to give it commit access to our repositories.  However, we decided to
use a separate repository for two reasons.  First, we would have to give
Weblate commit access and authorize its signing key, but we do not trust it
in the same way we trust guix developers, especially since we do not manage
the instance ourselves.  Second, if translators mess something up, it can
break the generation of the website and/or guix pull for all our users,
independently of their language.

For these reasons, we use a dedicated repository to host translations, and
we synchronize it with our guix and artworks repositories after checking no
issue was introduced in the translation.

Developers can download the latest PO files from weblate in the Guix
repository by running the @command{make download-po} command.  It will
automatically download the latest files from weblate, reformat them to a
canonical form, and check they do not contain issues.  The manual needs to
be built again to check for additional issues that might crash Texinfo.

Before pushing new translation files, developers should add them to the make
machinery so the translations are actually available.  The process differs
for the various components.

@itemize
@item New po files for the @code{guix} and @code{packages} components must
      be registered by adding the new language to @file{po/guix/LINGUAS} or
@file{po/packages/LINGUAS}.
@item New po files for the @code{documentation-manual} component must be
      registered by adding the file name to @code{DOC_PO_FILES} in
@file{po/doc/local.mk}, the generated @file{%D%/guix.xx.texi} manual to
@code{info_TEXINFOS} in @file{doc/local.mk} and the generated
@file{%D%/guix.xx.texi} and @file{%D%/contributing.xx.texi} to
@code{TRANSLATED_INFO} also in @file{doc/local.mk}.
@item New po files for the @code{documentation-cookbook} component must be
      registered by adding the file name to @code{DOC_COOKBOOK_PO_FILES} in
@file{po/doc/local.mk}, the generated @file{%D%/guix-cookbook.xx.texi}
manual to @code{info_TEXINFOS} in @file{doc/local.mk} and the generated
@file{%D%/guix-cookbook.xx.texi} to @code{TRANSLATED_INFO} also in
@file{doc/local.mk}.
@item New po files for the @code{website} component must be added to the
      @code{guix-artwork} repository, in @file{website/po/}.
@file{website/po/LINGUAS} and @file{website/po/ietf-tags.scm} must be
updated accordingly (see @file{website/i18n-howto.txt} for more information
on the process).
@end itemize
