Ссылки на исходный код
Одной из целей дизайна rpm является чистое разделение исходного кода апстрима и модификаций поставщика. Для упаковщика Fedora это означает, что исходные коды, используемые для сборки пакета, должны быть ванильными исходными кодами, доступными от апстрима. Чтобы помочь рецензентам и скриптам QA проверить это, упаковщик должен указать, где рецензент может найти исходный код, использованный для создания rpm.
Наиболее распространённый случай — когда апстрим распространяет исходный код в виде архива tar.gz, tar.bz2 или zip, который мы можем загрузить с веб-сайта апстрима. В этих случаях вы должны использовать полный URL пакета в строке Source:. Например:
Source: https://downloads.sourceforge.net/%{name}/%{name}-%{version}.tar.gz
Source: https://ftp.gnome.org/pub/GNOME/sources/gnome-common/2.12/gnome-common-2.12.0.tar.bz2
|
Наименьший сжатый архив
Если архив исходного кода апстрима доступен в нескольких сжатых форматах, которые наши инструменты могут распаковать, лучше использовать тот, что наименьшего размера. Это обеспечивает наименьший исходный rpm, чтобы экономить место на зеркалах и при загрузке пакетов исходных RPM. |
Использование форджей (размещённый контроль версий)
Любой веб-сайт для публикации программного обеспечения, позволяющий загружать архивы исходного кода через нормализованные URL, которые можно вывести из корневого URL проекта и значений version, commit, tag, scm, extension…, является «форджем», который может поддерживаться макросом %{forgemeta} из redhat-rpm-config. Распространённые примеры форджей — GitLab и GitHub. %{forgemeta} централизует и абстрагирует наши знания об этих форджах, чтобы упаковщикам не приходилось вручную разбираться с особенностями загрузки.
%{forgemeta} упрощает переключение между архивами исходного кода выпуска, тега и коммита. С помощью %{forgemeta} изменения URL-адресов загрузки форджа или рекомендаций распространяются на spec-файлы без ручного рефакторинга.
Когда эти изменения приводят к другому именованию или структуре архива исходного кода, исходный файл необходимо загрузить в систему сборки перед пересборкой существующих spec-файлов. Это главный недостаток использования %{forgemeta}.
Следующие примеры показывают, как использовать макросы Forge в различных ситуациях.
Пример выпуска
# This template shows how to package a commit state using the forgemeta macro.
# That should be the default target use case.
# Other less common use cases are documented in separate templates.
#
# The project url on the forge, for example
# https://gitlab.gnome.org/GNOME/gtk/
%global forgeurl
#
# Packaging a release requires setting Version before calling forgemeta.
# Because most forges follow the git model, and git made no provision for
# release objects, forgemeta will try to guess the customary way to write
# release tags on the selected forge.
# If it guesses wrong use the forge-tag template instead of this one.
Version:
#
# forgemeta converts the supplied rpm variables to variables that can be used
# in the spec file. Most of those can be overriden before or after the
# forgemeta call.
# – use the “-i” flag to display the variables forgemeta reads and sets
# – use the “-v” flag if you want verbose processing
# – remove “-i” and “-v” before commit
%forgemeta
# The following lines use variables computed by forgemeta as default values.
# You can replace them with manual definitions. For example, replace forgeurl
# with the project homepage if it exists separately from the repository URL.
# Only replace the variables when it adds value to the spec file and you
# understand the consequences. Release ordering is controlled by the packager
# with x%{?dist}/0.x%{?dist} number chains.
Name:
Release: 1%{?dist}
Summary:
URL: %{forgeurl}
Source: %{forgesource}
%description
%prep
# forgesetup calls setup with the correct flags for archives downloaded from
# the selected forge. A forgeautosetup autosetup wrapper is also provided. If
# you disagree with the computed setup/autosetup flags, just call
# setup/autosetup directly.
# – use the “-v” flag if you want verbose processing
%forgesetup
#
# After this point the archive extraction is done. forgemeta is no longer used.
%build
%install
%check
%files
%license
%doc
%changelog
Пример тега
# This template shows how to package a tag state using the forgemeta macro.
# For more explanations on forgemeta, read the forgemeta-release template.
#
# The project url on the forge
%global forgeurl
#
# The tag being packaged
%global tag
#
# – use the “-i” flag to display the variables forgemeta reads and sets
# – use the “-v” flag if you want verbose processing
# – remove “-i” and “-v” before commit
%forgemeta
# The following lines use variables computed by forgemeta as default values.
# You can replace them with manual definitions.
# forgemeta will prepend tag information to dist. Release ordering is
# controlled by the packager with x%{?dist}/0.x%{?dist} numbers chains.
Name:
Version:
Release: 1%{?dist}
Summary:
URL: %{forgeurl}
Source: %{forgesource}
%description
%prep
# – an autosetup wrapper, forgeautosetup, is also provided
# – use the “-v” flag if you want verbose processing; remove it before commit
# – call forgesetup/autosetup directly if you do not like the result
%forgesetup
#
# After this point the archive extraction is done. forgemeta is no longer used.
%build
%install
%check
%files
%license
%doc
%changelog
Пример коммита
# This template shows how to package a commit state using the forgemeta macro.
# For more explanations on forgemeta, read the forgemeta-release template.
#
# The project url on the forge
%global forgeurl
#
# The commit being packaged (when using git, a full hash)
%global commit
#
# – use the “-i” flag to display the variables forgemeta reads and sets
# – use the “-v” flag if you want verbose processing
# – remove “-i” and “-v” before commit
%forgemeta
# The following lines use variables computed by forgemeta as default values.
# You can replace them with manual definitions.
# forgemeta will prepend commit information to dist. Release ordering is
# controlled by the packager with x%{?dist}/0.x%{?dist} numbers chains.
Name:
Version:
Release: 1%{?dist}
Summary:
URL: %{forgeurl}
Source: %{forgesource}
%description
%prep
# – an autosetup wrapper, forgeautosetup, is also provided
# – use the “-v” flag if you want verbose processing; remove it before commit
# – call forgesetup/autosetup directly if you do not like the result
%forgesetup
#
# After this point the archive extraction is done. forgemeta is no longer used.
%build
%install
%check
%files
%license
%doc
%changelog
Пример ветки
# This template shows how to package a branch state using the forgemeta macro.
#
# BRANCH STATES ARE NOT REPRODUCIBLE AND SHOULD NEVER BE SHARED WITH OTHERS.
#
# For more explanations on forgemeta, read the forgemeta-release template.
#
# The project url on the forge
%global forgeurl
#
# The branch being packaged
%global branch
#
# – use the “-i” flag to display the variables forgemeta reads and sets
# – use the “-v” flag if you want verbose processing
# – remove “-i” and “-v” before commit
%forgemeta
# The following lines use variables computed by forgemeta as default values.
# You can replace them with manual definitions.
# forgemeta will prepend branch information to dist. Release ordering is
# controlled by the packager with x%{?dist}/0.x%{?dist} number chains.
Name:
Version:
Release: 1%{?dist}
Summary:
URL: %{forgeurl}
Source: %{forgesource}
%description
%prep
# – an autosetup wrapper, forgeautosetup, is also provided
# – use the “-v” flag if you want verbose processing; remove it before commit
# – call forgesetup/autosetup directly if you do not like the result
%forgesetup
#
# After this point the archive extraction is done. forgemeta is no longer used.
%build
%install
%check
%files
%license
%doc
%changelog
Пример нескольких источников
# This template shows how to package multiple source archives using the
# forgemeta macro.
#
# PACKAGING MULTIPLE PROJECT ARCHIVES IN A SINGLE SPEC IS DISCOURAGED. IT OFTEN
# REQUIRES ERROR-INDUCING VERSIONNING DECISIONS. In rpm, versioning is not an
# administrative decoration. Versioning controls the upgrade logic. If upstream
# deemed necessary to release a project through multiple archives, mirror its
# decision using multiple spec files. That will be safer, simpler, and
# ultimately less work.
#
# For more explanations on forgemeta, read the forgemeta-release template.
#
# Start by declaring the characteristics of each source using a number-suffixed
# variable block:
# – no suffix and zero suffix blocks are aliases
# – they are “special” and identify the main source archive
# — they use Version: to identify a release
# – other blocks use a version<number> variable for the same need
# – the syntax is otherwise identical to single archive mode; see the various
# forge templates for examples.
#
# Main archive. In this example we package a full release
%global forgeurl0
Version:
# Second archive.
%global forgeurl1
%global version1
# Third archive. This time a tag. Continue as necessary.
%global forgeurl2
%global tag2
# – use the “-a” flag to process all the source archives in a single pass
# – use “-z <number>” to process only the declaration block suffixed with
# <number>
# — without “-a” of “-z <number>” only the main archive is processed
# – use the “-i” flag to display the variables forgemeta reads and sets
# – use the “-v” flag if you want verbose processing
# – remove “-i” and “-v” before commit
%forgemeta -a
# The following lines use variables computed by forgemeta as default values.
# You can replace them with manual definitions.
# Release ordering is controlled by the packager with x%{?dist}/0.x%{?dist}
# numbers chains.
Name:
Release: 1%{?dist}
Summary:
URL: %{forgeurl0}
# https://github.com/rpm-software-management/rpm/issues/539
Source0: %{forgesource0}
Source1: %{forgesource1}
Source2: %{forgesource2}
%description
%prep
# – use the “-a” flag to process all the source archives in a single pass
# – use “-z <number>” to process only the declaration block suffixed with
# <number>
# — without “-a” of “-z <number>” only the main archive is processed
# – an autosetup wrapper, forgeautosetup, is also provided
# – forgeautosetup does not understand “-a”
# – use the “-v” flag if you want verbose processing; remove it before commit
# – call forgesetup/autosetup directly if you do not like the result
%forgesetup -a
#
# After this point the archive extraction is done. forgemeta is no longer used.
%build
%install
%check
%files
%license
%doc
%changelog
Использование контроля версий
В некоторых случаях вы можете захотеть извлечь исходный код из системы контроля версий апстрима, потому что с момента последнего выпуска было много изменений, и вы думаете, что созданный оттуда архив будет более точно показывать, как пакет соотносится с разработкой апстрима. Вот как можно использовать комментарий, чтобы показать, откуда пришёл исходный код:
# The source for this package was pulled from upstream's vcs. Use the # following commands to generate the tarball: # svn export -r 250 https://www.example.com/svn/foo/trunk foo-20070221 # tar -cJvf foo-20070221.tar.xz foo-20070221 Source: foo-20070221.tar.xz
При извлечении из системы контроля версий, пожалуйста, помните, что нужно использовать Name-version-release, совместимый с рекомендациями по версионированию. В частности, проверьте раздел Сложное версионирование.
Когда апстрим использует запрещённый код
Некоторые пакеты апстрима включают патенты или товарные знаки, которые нам не разрешено поставлять даже в виде исходного кода. В этих случаях вам нужно изменить архив исходного кода, чтобы удалить этот код, ещё до того, как вы загрузите его в систему сборки. Вот пример использования скрипта для документирования того, как вы перешли от архива апстрима к тому, который включён в пакет:
Из spec-файла:
Source: libfoo-1.0-nopatents.tar.gz # libfoo contains patented code that we cannot ship. Therefore we use # this script to remove the patented code before shipping it. # Download the upstream tarball and invoke this script while in the # tarball's directory: # ./generate-tarball.sh 1.0 Source1: generate-tarball.sh
generate-tarball.sh:
#!/bin/sh VERSION=$1 tar -xzvf libfoo-$VERSION.tar.gz rm libfoo-$VERSION/src/patentedcodec.c sed -i -e 's/patentedcodec.c//' libfoo-$VERSION/src/Makefile tar -czvf libfoo-$VERSION-nopatents.tar.gz libfoo-$VERSION
Пакеты Python (pypi)
Поскольку PyPI перешла к хранению файлов в каталогах, которые меняются в зависимости от сохраняемого файла, использовать его в URL Source: довольно неприятно. Вместо этого можно использовать files.pythonhosted.org через макрос %{pypi_source}, за которым следует имя проекта.
Source: %{pypi_source foo}
Подробнее о макросе см. в рекомендациях по Python.
Sourceforge.net
Для пакетов, размещённых на sourceforge, используйте
Source: https://downloads.sourceforge.net/%{name}/%{name}-%{version}.tar.gz
заменив .tar.gz на то, что соответствует распространению апстрима. Обратите внимание, что мы используем downloads.sourceforge.net вместо произвольно выбранного зеркала. Вы можете использовать имя пакета/версию пакета вместо макросов %{name} и %{version}, конечно.
Обратите внимание, что правильный URL — downloads.sourceforge.net, а НЕ download.sourceforge.net.
Службы размещения Git
Если апстрим действительно создаёт архивы, вам следует использовать их, поскольку архивы обеспечивают более простой след для людей, проводящих аудит пакетов.
Веб-службы размещения Git предоставляют механизм создания архивов по запросу — либо из конкретной ревизии коммита, либо из конкретного тега. Если апстрим не создаёт архивы для выпусков, вы можете использовать этот механизм для их создания.
Полный 40-символьный хеш и связанный git-тег можно получить, выполнив следующую команду git:
git ls-remote https://HOSTING-SERVICE/OWNER/%{name}.git
HOSTING-SERVICE: name of the service, i.e. "github.com", "bitbucket.org", "gitlab.com", etc.
OWNER: username for the repository owner
PROJECT: upstream project name (if it's identical to the package name, use %{name} instead)
Вы также можете получить 40-символьный хеш и связанный git-тег через веб-интерфейс HOSTING-SERVICE или клонировав репозиторий и выполнив команду git show-ref.
Как только хеш коммита и git-тег известны, вы можете определить их в своём spec-файле следующим образом:
%global commit 40-CHARACTER-HASH-VALUE
%global gittag GIT-TAG
%global shortcommit %(c=%{commit}; echo ${c:0:7}) [GitHub]
%global shortcommit %(c=%{commit}; echo ${c:0:11}) [Bitbucket]
%global shortcommit %(c=%{commit}; echo ${c:0:7}) [GitLab]
%global shortcommit %(c=%{commit}; echo ${c:0:8}) [Sourcehut]
Ревизия коммита
Для архива исходного кода можно использовать следующий синтаксис:
Source: https://github.com/OWNER/PROJECT/archive/%{commit}/%{name}-%{shortcommit}.tar.gz [GitHub]
Source: https://bitbucket.org/OWNER/PROJECT/get/%{commit}.tar.gz#/%{name}-%{shortcommit}.tar.gz [BitBucket]
Source: https://gitlab.com/OWNER/PROJECT/-/archive/%{commit}/%{name}-%{shortcommit}.tar.gz [GitLab]
Source: https://git.sr.ht/~OWNER/PROJECT/archive/%{shortcommit}.tar.gz#/PROJECT-%{shortcommit}.tar.gz [Sourcehut]
...
%prep
%autosetup -n PROJECT-%{commit} [GitHub]
%autosetup -n OWNER-PROJECT-%{shortcommit} [BitBucket]
%autosetup -n PROJECT-%{commit} [GitLab]
%autosetup -n PROJECT-%{shortcommit} [Sourcehut]
Если выпуск соответствует git-тегу с разумной числовой версией, вы должны использовать эту версию для заполнения тега Version: в spec-файле. Если нет, посмотрите в исходный код, указана ли там версия, и используйте это значение. Если в коде не указана числовая версия, вы можете установить Version в 0 и рассматривать пакет как «предварительный» пакет (и использовать макрос %{shortcommit}). Подробности см. в Предварительные версии.
В качестве альтернативы, если вы используете конкретную ревизию, которая является либо предварительной, либо послерелизной ревизией, вы должны следовать рекомендациям по «снимкам» (snapshots). Они описаны здесь: Снимки. Вы можете подставить %{shortcommit} вместо git-хеша в %{checkout} в этом разделе.
Git-теги
Git-теги представляют определённую точку кода, которую апстрим считает важной, и обычно используются для отметки точек выпуска.
Bitbucket использует идентификатор %{shortcommit} как часть структуры каталогов архива, независимо от того, используете ли вы git-тег или ревизию коммита для его получения. Это показано в примере раздела %prep.
Для архива исходного кода можно использовать следующий синтаксис:
Source: https://github.com/OWNER/PROJECT/archive/%{gittag}/%{name}-%{version}.tar.gz [GitHub]
Source: https://bitbucket.org/OWNER/PROJECT/get/%{gittag}.tar.gz#/%{name}-%{version}.tar.gz [BitBucket]
Source: https://gitlab.com/OWNER/PROJECT/-/archive/%{gittag}/%{name}-%{version}.tar.gz [GitLab]
Source: https://git.sr.ht/~OWNER/PROJECT/archive/%{version}.tar.gz#/PROJECT-%{version}.tar.gz [Sourcehut]
...
%prep
%autosetup -n PROJECT-%{gittag} [GitHub]
%autosetup -n OWNER-PROJECT-%{shortcommit} [BitBucket]
%autosetup -n PROJECT-%{version} [GitLab]
%autosetup -n PROJECT-%{version} [Sourcehut]
Использование %{version}
Использование %{version} в Source: упрощает вам обновление версии пакета, потому что в большинстве случаев вам не нужно редактировать Source: при редактировании spec-файла для нового пакета.
Проблемные URL-адреса
Когда у апстрима есть URL-адреса для загрузки, которые не заканчиваются именем архива, rpm не сможет извлечь имя архива из исходного URL. Одним из обходных путей во многих случаях является создание URL, в котором архив указан во «фрагменте URL»:
Source: https://example.com/foo/1.0/download.cgi#/%{name}-%{version}.tar.gz
Тогда rpm будет использовать %{name}-%{version}.tar.gz в качестве имени архива. Если вы используете spectool -g foo.spec для загрузки архива, он переименует архив за вас.
Иногда это не работает, потому что cgi апстрима пытается разобрать фрагмент или потому что вам нужно войти или заполнить форму для доступа к архиву. В этих случаях вам нужно поместить в тег Source: только имя файла архива. Чтобы было ясно, откуда вы взяли архив, оставьте заметки в комментариях над строкой Source:, чтобы объяснить ситуацию рецензентам и будущим упаковщикам. Например:
# Mysql has a mirror redirector for its downloads # You can get this tarball by following a link from: # https://dev.mysql.com/downloads/mysql/5.1.html Source: mysql-5.1.31.tar.gz
Не делайте Sources условными
При сборке SRPM критически важно, чтобы все источники присутствовали, независимо от платформы, на которой генерируется SRPM. Например, следующий код не работает (так, как вы могли бы ожидать):
%if 0%{?fedora} < 35
Source1: mysource-old.tar.bz2
Patch1: oldpatch.patch
%else
Source1: mysource-ng.tar.bz2
Patch1: ngpatch.patch
%endif
Если вы соберёте этот SRPM на хосте Fedora 34 (rpmbuild -bs mysource.spec), полученный SRPM будет содержать mysource-old.tar.bz2 и oldpatch.patch. Однако если затем вы попытаетесь использовать этот SRPM для сборки под Fedora 35, операция завершится с ошибкой, потому что mysource-ng.tar.bz2 недоступен.
Правильное поведение — всегда включать все источники, которые могут использоваться в сборке, и вместо этого делать условным их использование. Например:
Patch1: oldpatch.patch Patch2: ngpatch.patch ... %prep %autosetup -N ... %if 0%{?fedora} < 35 tar xf %{SOURCE1} %patch 1 -p1 %else tar xf %{SOURCE2} %patch 2 -p1 %endif ```
Want to help? Learn how to contribute to Fedora Docs ›