Table of Contents
Here are some notable tips about Debian packaging.
Debian now enforces the source-only upload when developing packages. So
there may be 2 different *
.changes files:
Можно сравнивать содержимое файлов в двух пакетах Debian с исходным кодом с помощью команды debdiff.
$ debdiff old-package.dsc new-package.dsc
Также можно сравнивать списки файлов в двух наборах двоичных пакетов Debian с помощью команды debdiff.
$ debdiff old-package.changes new-package.changes
Это полезно для определения изменений в пакетах с исходным кодом и для проверки на предмет нечаянных изменений, привнесённых при обновлении двоичных пакетов, таких как непреднамеренное ошибочное размещение или удаление файлов.
Можно скачать набор файлв для пакета Debian с исходным кодом с помощью команды dget.
$ dget https://www.example.org/path/to/package_version-rev.dsc
Созданные пакеты следуется установить с помощью команды debc для их локальной проверки.
$ debc package_version-rev_arch.changes
Созданные пакеты следует установить с помощью команды piuparts для их автоматической проверки.
$ sudo piuparts package_version-rev_arch.changes
Note | |
---|---|
This is a very slow process with remote APT package repository access. |
После завершения тестирования пакета можно его подписать с помощью команды debsign.
For uploading source-only package (normal):
$ debsign package_version-rev_source.changes
For uploading binary package:
$ debsign package_version-rev_arch.changes
After signing the package with the debsign command, you can upload the set of files for the Debian source and binary packages with the dput command.
For uploading source-only package (normal):
$ dput package_version-rev_source.changes
For uploading binary package:
$ dput package_version-rev_arch.changes
После загрузки пакета вы начнёте получать сообщения об ошибках. Соответствующая работа с ошибками является важным обязательством сопровождающего, что описано в разделе 5.8. Работа с ошибками «Справочника разработчика Debian».
The bts command is a handy tool to manage bugs on the Debian Bug Tracking System.
$ bts severity 123123 wishlist , tags -1 pending
Пакет git-buildpackage предлагает множество команд для автоматизации деятельности по работе над пакетом с помощью репозитория git.
gbp import-orig: импортировать новый tar-архив основной ветки в git-репозиторий.
gbp buildpackage: сборка двоичного пакета Debian из git-репозитория.
--git-builder='sbuild -A -s --source-only-changes -v -d
unstable'
Команды gbp pq, git-dpm или quilt (или её псевдоним dquilt) используются для работы с заплатами quilt.
Package history management with the git-buildpackage package is becoming the standard practice for most Debian maintainers.
См.:
Tip | |
---|---|
Расслабьтесь. Вам не нужно использовать все обёртки и инструменты. Используйте только те, которые подходят под ваши нужды. |
Для пакета Debian с исходным кодом с именем <source-package>, сохранённого в архиве snapshot.debian.org начальный git-репозиторий со всей историей версий Debian можно получить следующим образом.
$ gbp import-dscs --debsnap --pristine-tar '<source-package>'
For Debian packaging with the git-buildpackage package, the upstream branch on the remote repository origin is normally used to track the content of the released upstream tarball.
git-репозиторий основной ветки также может отслеживаться, его удалённый репозиторий следует назвать upstream, а не origin как по умолчанию. Теперь вы легко сможете избирательно применять наиболее свежие изменения основной ветки к редакции Debian с помощью команды gitk и используя команду gbp-pq.
Tip | |
---|---|
The “gbp import-orig --upstream-vcs-tag” command can create a nice packaging history by making a merge commit into the upstream branch from the specified tag on the upstream git repository. |
Caution | |
---|---|
Содержимое выпущенного разработчиками основной ветки tar-архива может не совпадать в точности с соответствующим содержимым git-репозитория основной ветки. Оно может содержать созданные автоматически файлы, либо какие-то файлы могут отсутствовать. (Autotools, distutils, …) |
The new dgit package offers commands to automate packaging activities using the git repository as an alternative to still popular gbp-buildpackage. Please read their guide:
Format: 3.0 (quilt)
" package with its changes flowing
both ways between the upstream Git repository and the Debian Git repository
which are tightly coupled.
Format: 3.0 (quilt)
" package with its changes flowing
mostly one way from the upstream Git repository to the Debian Git
repository.
Format: 3.0 (quilt)
" package with its Debian Git
repository which is kept usable also for people using gbp-buildpackage(1).
Format: 3.0 (native)
" package in the Debian Git
repository.
The dgit(1) command can push the easy-to-trace change history to the https://browse.dgit.debian.org/ site and can upload Debian package to the Debian repository properly without using dput(1).
If you already use main
and upstream
branches in the Debian packaging repository
(salsa.debian.org
), you can use your local
upstream-vcs-main
branch to track the
main
branch of the upstream-vcs
repository as:
$ git fetch upstream-vcs main:upstream-vcs-main
Cherry picking bug fix commits from latest upstream commits are intuitive
operation with dgit-maint-merge(7) and
dgit-maint-debrebase(7). Just
right-click those commits interactively on the
upstream-vcs-main
branch of the gitk(1) GUI dialog.
For quasi-native Debian binary package
scheme situation described in Section 6.2, “Snapshot upstream tarball (-d, -t)” can be addressed
using alternative git deborig
approach adopting the
dgit-maint-merge(7) scheme when
debian/changelog
contains the non-native version number
with revision like 0.16-1
.
$ cd /path/to/upstream-git $ git rm -rf debian $ git tag -s upstream/0.16 $ git reset --hard HEAD^ $ git deborig $ sbuild
Here, for source format 3.0 (quilt)
, removal of files
under debian/
directory in the upstream tarball is
non-essential operation to quiet false positive warning from lintian.
For -1
revision, this use of
git-deborig
(1) as above is how this
debmake-doc
package generates the upstream tarball.
For -2
, -3
, … revisions, you need to
fetch and use the uploaded upstream tarball instead. For this,
origtargz
(1) may be handy.
The chroot for a clean package build environment can be created and managed using the tools described in Chapter 3, Настройка инструментов. [20]
Ниже приводится краткий обзор доступных команд для сборки пакетов. Существует множество способов сделать одно и то же.
A clean unstable distribution chroot environment can be used as follows.
The chroot filesystem creation command for the unstable distribution
The master chroot filesystem path for the unstable distribution chroot filesystem
The package build command for the unstable distribution chroot
The command to update the unstable chroot
The command to login to the unstable chroot filesystem to modify it
Here, single "u" is predefined short alias for "unstable".
Произвольное окружение выпуска выпуск может быть использовано следующим образом.
Команда создания файловой системы chroot-окружения для выпуска выпуск
Главный путь файловой системы chroot-окружения для chroot-окружения выпуска выпуск
Команда сборки пакета для chroot-окружения выпуска выпуск
Команда для обновления chroot-окружения выпуск
The command to login to the master chroot (source:dist) of the dist distribution environment to modify it persistently
Tip | |
---|---|
For building new experimental packages or for debugging buggy packages without using slow network access, this “sudo sbuild-shell dist” command can be used to pre-loaded some packages. Make sure to retain the backup of the original minimal chroot since changes are persistent and interfere with the normal test package building with the minimal chroot. |
Tip | |
---|---|
If your old chroot filesystem is missing packages such as libeatmydata1, ccache, and lintian, you may want to install these with the “sudo sbuild-shell dist” command. |
Tip | |
---|---|
When the orig.tar.gz file needs to be uploaded for a Debian revision other than 0 or 1 (e.g., for a security upload), add the -sa option to the end of dpkg-buildpackage, debuild, and sbuild commands. For the “gbp buildpackage” command, temporarily modify the builder setting of ~/.gbp.conf. |
Note | |
---|---|
Описание в этом разделе слишком кратко, чтобы оно оказалось полезным для большинства будущих сопровождающих. Это — намеренный выбор автора. Настоятельно рекомендуется поискать и прочесть всю соответствующую документация, связанную с используемыми командами. |
Note | |
---|---|
When an essential package becomes a non-essential one (e.g., adduser), you need to remove it manually from the existing chroot environment for its use by piuparts. |
Let’s assume that a bug report #bug_number was filed against your package, and it describes a problem that you can solve by editing the buggy file in the upstream source. Here’s what you need to do to create a new Debian revision of the package with the bugname.patch file recording the fix.
Новая редакция Debian с помощью команды dquilt.
$ dquilt push -a $ dquilt new bugname.patch $ dquilt add buggy $ vim buggy ... $ dquilt refresh $ dquilt header -e $ dquilt pop -a $ dch -i
Alternatively if the package is managed in the git repository using the git-buildpackage command with its default configuration:
Новая редакция Debian с помощью команды gbp-pq.
$ git checkout master $ gbp pq import $ vim buggy $ git add buggy $ git commit $ git tag pq/<newrev> $ gbp pq export $ gbp pq drop $ git add debian/patches/* $ dch -i $ git commit -a -m "Closes: #<bug_number>"
Проверьте, что вы лаконично описали изменения, исправляющие ошибку, и закрыли сообщение об ошибке, добавив «Closes: #<номер_ошибки>» в файл debian/changelog.
Tip | |
---|---|
Когда вы экспериментируете, то используйте запись debian/changelog со строкой версии вида 1.0.1-1~rc1. Затем сведите такие записи журнала изменений в одну запись для официального пакета. |
Если пакет foo создан в одном из современных форматов «3.0 (native)» или «3.0 (quilt)», то работа над пакетом с новым выпуском основной ветки будет представлять собой по сути перемещение старого каталога debian/ в новый исходный код. Это можно сделать, запустив команду «tar -xvzf /путь/к/foo_стараяверсия.debian.tar.gz» в каталоге с распакованным новым исходным кодом. [21] Конечно, вам придётся сделать некоторую рутинную работу.
Для такой ситуации существует несколько инструментов. После обновления до нового выпуска основной ветки с помощью этих инструментов убедитесь, что вы лаконично описали изменения в новом выпуске основной ветки, исправляющие известные ошибки, и закрыли эти сообщения об ошибках, добавив «Closes: #номер_ошибки» в файл debian/changelog.
You can automatically update to the new upstream source with the uupdate command from the devscripts package. It requires having the old Debian source package and the new upstream tarball.
$ wget https://example.org/foo/foo-newversion.tar.gz $ cd foo-oldversion $ uupdate -v newversion ../foo-newversion.tar.gz ... $ cd ../foo-newversion $ while dquilt push; do dquilt refresh; done $ dch
You can automatically update to the new upstream source with the uscan command from the devscripts package. It requires having the old Debian source package and the debian/watch file in it.
$ cd foo-oldversion $ uscan ... $ while dquilt push; do dquilt refresh; done $ dch
You can automatically update to the new upstream source with the “gbp import-orig --pristine-tar” command from the git-buildpackage package. It requires having the old Debian source in the git repository and the new upstream tarball.
$ ln -sf foo-newversion.tar.gz foo_newversion.orig.tar.gz $ cd foo-vcs $ git checkout master $ gbp pq import $ git checkout master $ gbp import-orig --pristine-tar ../foo_newversion.orig.tar.gz ... $ gbp pq rebase $ git checkout master $ gbp pq export $ gbp pq drop $ git add debian/patches $ dch -v <newversion> $ git commit -a -m "Refresh patches"
Tip | |
---|---|
If upstream uses a git repository, please also use the --upstream-vcs-tag option for the gbp import-orig command. |
You can automatically update to the new upstream source with the “gbp import-orig --pristine-tar --uscan” command from the git-buildpackage package. It requires having the old Debian source in the git repository and the debian/watch file in it.
$ cd foo-vcs $ git checkout master $ gbp pq import $ git checkout master $ gbp import-orig --pristine-tar --uscan ... $ gbp pq rebase $ git checkout master $ gbp pq export $ gbp pq drop $ git add debian/patches $ dch -v <newversion> $ git commit -a -m "Refresh patches"
Tip | |
---|---|
If upstream uses a git repository, please also use the --upstream-vcs-tag option for the gbp import-orig command. |
Обновление стиля пакета не является требуемой деятельностью до обновления пакета. Тем не менее, такое обновление позволяет использовать все возможности современной системы debhelper и формат исходного кода 3.0.
Вам следует просмотреть DEP — Предложения по улучшению Debian и использовать принятые (ACCEPTED) предложения.
Информацию о статусе поддержки новых форматов исходного кода Debian в наборе инструментальных средств Debian см. в ProjectsDebSrc3.0.
Общая система сборки Debian (CDBS) является обёрткой над пакетом debhelper. CDBS построена на основе механизма включения Makefile и настраивается с помощью установки переменных настройки DEB_* в файле debian/rules.
До добавления команды dh в пакет debhelper (начиная с версии 7) CDBS являлась единственным подходом к созданию простого и ясного файла debian/rules.
For many simple packages, the dh command alone allows us to make a simple and clean debian/rules file now. It is desirable to keep the build system simple and clean by not using the superfluous CDBS.
Note | |
---|---|
Neither “the CDBS magically does the job for me with less typing” nor “I don’t understand the new dh syntax” can be an excuse to keep using the CDBS system. |
For some complicated packages such as GNOME related ones, the CDBS is leveraged to automate their uniform packaging by the current maintainers with justification. If this is the case, please do not bother converting from the CDBS to the dh syntax.
Note | |
---|---|
Если вы работаете вместе с командой сопровождающих, то следуйте установленным традициям и практикам этой команды. |
При переходе с использования системы CDBS на синтаксис dh в качестве справочника используйте следующую документацию:
Локалью по умолчанию в сборочном окружении является C.
Некоторые программы, такие как функци read из Python3, изменяют своё поведение в зависимости от текущей локали.
Adding the following code to the debian/rules file ensures building the program under the C.UTF-8 locale.
LC_ALL := C.UTF-8 export LC_ALL
Если документация основной ветки разработки закодирована с помощью устаревших кодировок, то лучше будет преобразовать её в UTF-8.
Используйте команду iconv из пакета libc-bin для преобразования кодировки в обычных текстовых файлах.
$ iconv -f latin1 -t utf8 foo_in.txt > foo_out.txt
Используйте w3m(1) для преобразования HTML-файлов в обычные текстовые файлы в кодировке UTF-8. При выполнении преобразования убедитесь, что у вас используется локаль UTF-8.
$ LC_ALL=C.UTF-8 w3m -o display_charset=UTF-8 \ -cols 70 -dump -no-graph -T text/html \ < foo_in.html > foo_out.txt
Запустите эти сценарии в цели override_dh_* файла debian/rules.
При первой загрузке пакета в архив вам следует включить в загрузку также и архив с оригинальным исходным кодом, orig.tar.gz.
Если номер редакции Debian вашего пакета не является 1 или 0, то это происходит по умолчанию. В противном случае, вам следует передать опцию -sa команде dpkg-buildpackage.
Tip | |
---|---|
С другой стороны использование опции -sd приведёт к тому, что архив с оригинальным исходным кодом, orig.tar.gz, будет включён в загрузку. |
Tip | |
---|---|
Security uploads require including the orig.tar.gz file. |
Если вы создаёте несколько записей в файле debian/changelog и пропускаете загрузки, то вам следует создать соответствующий файл *_.changes, включающий все изменения с последней загрузки. Это можно сделать, передав dpkg-buildpackage опцию -v с указанием последней загруженной версии, например, 1.2.
Полезные советы по приведённым ниже вопросам можно найти в странице руководства debhelper(7):
сборка нескольких двоичных пакетов в нескольких разных условиях сборки
excluding some packages for the bootstrapping process (see also BuildProfileSpec)
Полезные советы по приведённым ниже вопросам можно найти в странице руководства dpkg-source(1):
naming convention for multiple upstream source tarballs
запись изменений Debian в пакет исходного кода основной ветки
Несмотря на то, что в tar-архиве основной ветки имеется вся информация для сборки пакета Debian, не всегда легко понять, какую комбинацию опций следует использовать.
Also, the upstream package may be more focused on feature enhancements and may be less eager about backward compatibilities etc., which are an important aspect of Debian packaging practice.
The leveraging of information from other distributions is an option to address the above issues.
If the other distribution of interest is a Debian derivative one, it is trivial to reuse it.
If the other distribution of interest is an RPM based distribution, see Repackage src.rpm.
Скачивание и открытие файла src.rpm может быть выполнено с помощью команды rget. (Разместите сценарий rget в одном из каталогов, указанных в вашей переменной PATH.)
Сценарий rget.
#!/bin/sh FCSRPM=$(basename $1) mkdir ${FCSRPM}; cd ${FCSRPM}/ wget $1 rpm2cpio ${FCSRPM} | cpio -dium
Во многих tar-архивах основной ветки содержится файл SPEC, который имеет имя packagename.spec или packagename.spec.in и используется системой RPM. Также он может использоваться в качестве основы для пакета Debian.
Когда вы сталкиваетесь с проблемами сборки или дампом памяти созданных двоичных программ, вам необходимо разрешить их самостоятельно. Это называется отладкой.
Это слишком обширная тема, чтобы обсуждать её в настоящем руководстве. Поэтому позвольте просто привести несколько ссылок и полезных советов по использованию типичных инструментов отладки.
Обновите файл «/etc/security/limits.conf» так, чтобы он включал в себя следующее:
* soft core unlimited
gdb — отладчик GNU
strace — трассировка системных вызовов и сигналов
ltrace - трассировка библиотечных вызовов
«perl -d:Trace script.pl» — трассировка сценария на языке Perl
lsof — вывод списка файлов, открытых процессами
Tip | |
---|---|
The script command records console outputs. |
Tip | |
---|---|
The screen and tmux commands used with the ssh command offer secure and robust remote connection terminals. |
Tip | |
---|---|
A Python- and Shell-like REPL (=READ + EVAL + PRINT + LOOP) environment for Perl is offered by the reply command from the libreply-perl (new) package and the re.pl command from the libdevel-repl-perl (old) package. |
Tip | |
---|---|
The rlwrap and rlfe commands add input line editing capability with history support to any interactive commands. E.g. “rlwrap dash -i”' . |
[20] The sbuild style chroot organization is deployed here. See https://wiki.debian.org/sbuild . Be careful since many HOWTOs use different chroot setups.
[21] If a package foo is packaged in the old 1.0 format, this can be done by running the “zcat /path/to/foo_oldversion.diff.gz|patch -p1” command in the new extracted source, instead.
[22] Можно разделить файл большой.diff на несколько небольших инкрементальных заплат с помощью команды splitdiff.