From Fedora Project Wiki

Este é um pequeno tutorial prático sobre como escrever arquivos RPM, mostrando como acelerar a criação de pacotes simples e binários. Assume alguma familiaridade com o uso de pacotes RPM pré-fabricados e com o processo de construção de software FOSS.

Para obter uma informação abrangente sobre como criar arquivos RPM, incluindo dicas mais detalhadas, consulte Como criar um pacote RPM. Se você planeja criar um pacote de RPM para o repositório do Fedora, siga o processo em Como participar do Fedora Package Collection Maintainers, inclusive seguindo as várias orientações do Fedora.

Este tutorial demonstra o empacotamento do projeto "Hello World" do GNU. Enquanto o programa C imprimir 'Olá Mundo' para saída padrão é trivial, a versão GNU contém a maioria dos componentes periféricos usuais associados a um projeto de software FOSS típico, incluindo o ambiente de configuração/compilação/ instalação, documentação, internacionalização, etc.

Ambiente de desenvolvimento

Para construir RPMs, precisamos de um conjunto de ferramentas de desenvolvimento. Esta é uma configuração única, instalada executando esses comandos a partir de uma administração de sistema de conta (root) :

# yum install @development-tools
# yum install fedora-packager

Se você quiser testar o procedimento de compilação em um chroot limpo, você precisará configurar sua conta não privilegiada para ser membro do grupo 'mock':

# usermod -a -G mock <your username>

Esses são os únicos comandos que exigem privilégios root. Todo o trabalho restante deve ser feito a partir de sua conta regular e não privilegiada, ou mesmo de uma conta separada criada apenas para o trabalho de desenvolvimento. Os modernos sistemas baseados em RPM, incluindo o Fedora, são configurados para criar e testar pacotes RPM exclusivamente a partir de uma conta não privilegiada:

$ rpmdev-setuptree

Que basicamente configura uma área de compilação RPM em seu ~/rpmbuild. Este diretório conterá vários subdiretórios, para o código fonte do projeto, os arquivos de configuração RPM e para a fonte resultante e os pacotes binários.

Construindo um "Hello World" RPM

We need the source code of the project we are packaging, often referred to as the 'upstream' source. We will download it from the project's website into the ~/rpmbuild/SOURCE directory. We are getting the compressed tarball archive, which happens to be a preferred distribution form for most FOSS projects.

$ cd ~/rpmbuild/SOURCES
$ wget http://ftp.gnu.org/gnu/hello/hello-2.8.tar.gz

The RPM package is configured by .spec files. We will create a template file hello.spec in the appropriate directory:

$ cd ~/rpmbuild/SPECS
$ rpmdev-newspec hello

Recent versions of Emacs and vi have .spec file editing modes which will also bring up a similar template upon creating a new file. So you can just use the following command for example to use the template automatically.

vi hello.spec

Dentro de um arquivo .spec

The fields in our .spec file need slight editing. Please follow the Fedora rules for these fields. In our case, the file might start as follows:

Name:     hello
Version:  2.8
Release:  1
Summary:  The "Hello World" program from GNU
License:  GPLv3+
URL:      http://ftp.gnu.org/gnu/hello    
Source0:  http://ftp.gnu.org/gnu/hello/hello-2.8.tar.gz

%description
The "Hello World" program, done with all bells and whistles of a proper FOSS 
project, including configuration, build, internationalization, help files, etc.

%changelog
* Thu Jul 07 2011 The Coon of Ty <Ty@coon.org> - 2.8-1
- Initial version of the package

The Version should mirror upstream while Release numbers our work within Fedora.

The first letter of the Summary should be uppercase to avoid rpmlint complaints.

It is your responsibility to check the License status of the software, by inspecting the source files and/or their LICENSE files, and/or by talking to the authors.

The Group tag was historically used to classify the package in accordance to the list in /usr/share/doc/rpm-<version>/GROUPS. It is being phased out so you will not see it added by default. However, it doesn't hurt to add it anyway.

The %changelog should document the work on preparing the RPM, especially if there are security and bug patches included on top of the base upstream source. Changelog data can be displayed by rpm --changelog -q <packagename>, which is very useful for instance to find out if specific bug and security patches were included in the installed software, thanks to diligent Fedora packagers who include this info with the relevant CVE numbers.

The changelog entry should include the version string to avoid rpmlint complaints.

Multi-line sections like %changelog or %description start on a line under the directive, and end with an empty line.

Lines which aren't needed (e.g. BuildRequires and Requires) can be commented out with a hash ('#') for now.

Many lines in the template don't need to be changed at all in many cases, at least for the initial attempt.

Construindo o pacote

We are ready for the first run to build source, binary and debugging packages:

$ rpmbuild -ba hello.spec

It will complain and list the unpackaged files, i.e. the files that would be installed in the system that weren't declared as belonging to the package. We need to declare them in the %files section. Do not hardcode names like /usr/bin/, but use macros, like %{_bindir}/hello instead. The manual pages should be declared in the %doc subsection: %doc %{_mandir}/man1/hello.1.gz.

This is an iterative process: after editing the .spec file, rerun rpmbuild.

Since our program uses translations and internationalization, we are seeing a lot of undeclared i18 files. The recommended method to declare them is:

  • find the filenames in the %install step: %find_lang %{name}
  • add the required build dependencies: BuildRequires: gettext
  • use the found filenames %files -f %{name}.lang

If the program uses GNU info files, you need to make sure the installation and uninstallation of the package does not interfere with other software on the system, by using this boilerplate:

  • delete the 'dir' file in %install: rm -f %{buildroot}/%{_infodir}/dir
  • Requires(post): info and Requires(preun): info
  • add those steps:
%post
/sbin/install-info %{_infodir}/%{name}.info %{_infodir}/dir || :

%preun
if [ $1 = 0 ] ; then
/sbin/install-info --delete %{_infodir}/%{name}.info %{_infodir}/dir || :
fi

Um arquivo hello.spec completo

Aqui está uma versão inicial do hello.spec:

Name:           hello
Version:        2.8
Release:        1%{?dist}
Summary:        The "Hello World" program from GNU

License:        GPLv3+
URL:            http://ftp.gnu.org/gnu/%{name}
Source0:        http://ftp.gnu.org/gnu/%{name}/%{name}-%{version}.tar.gz

BuildRequires: gettext
      
Requires(post): info
Requires(preun): info

%description 
The "Hello World" program, done with all bells and whistles of a proper FOSS 
project, including configuration, build, internationalization, help files, etc.

%prep
%autosetup

%build
%configure
make %{?_smp_mflags}

%install
%make_install
%find_lang %{name}
rm -f %{buildroot}/%{_infodir}/dir

%post
/sbin/install-info %{_infodir}/%{name}.info %{_infodir}/dir || :

%preun
if [ $1 = 0 ] ; then
/sbin/install-info --delete %{_infodir}/%{name}.info %{_infodir}/dir || :
fi

%files -f %{name}.lang
%doc AUTHORS ChangeLog COPYING NEWS README THANKS TODO
%{_mandir}/man1/hello.1.gz
%{_infodir}/%{name}.info.gz
%{_bindir}/hello

%changelog
* Tue Sep 06 2011 The Coon of Ty <Ty@coon.org> 2.8-1
- Initial version of the package

With this spec file, you should be able to successfully complete the build process, and create the source and binary RPM packages.

Next you should check them for conformance with RPM design rules, by running rpmlint on the spec file and all RPMs:

$ rpmlint hello.spec ../SRPMS/hello* ../RPMS/*/hello*

Se não houverem alertas ou erros, obtivemos sucesso. Do contrário, use rpmlint -i ou rpmlint -I <error_code> para ver uma descrição mais detalhada do diagnóstico do rpmlint

Osmock builds

To check that the package build will succeed in the Fedora restricted build environment, check it with mock. The default mock configuration builds the package against Rawhide - the Fedora development branch.

$ mock --verbose ../SRPMS/hello-2.8-1.fc20.src.rpm

Referências

History

Przemek Klosowski wrote this tutorial when he worked through Christoph Wickert's IRC session on building RPMs using Rahul Sundaram suggestion of GNU "Hello World" as a test case. After he wrote up his experience, he found out about the excellent and extensive How to create an RPM package page on this wiki, as well as the Christian Lyder Jacobsen's website. However, Christian isn't planning to update his site, and it seemed that a 5-minute 'fast food' alternative to the more extensive article might suit some people. More in-depth information on using and building RPM packages is available from other sources.