Chapter 7. Полезные советы

Table of Contents

7.1. debdiff
7.2. dget
7.3. debc
7.4. piuparts
7.5. debsign
7.6. dput
7.7. bts
7.8. git-buildpackage
7.8.1. gbp import-dscs --debsnap
7.8.2. git-репозиторий основной ветки
7.9. dgit
7.9.1. Snapshot upstream tarball (alternative git deborig approach)
7.10. chroot
7.11. Новая редакция Debian
7.12. Новый выпуск основной ветки
7.12.1. uupdate + tarball
7.12.2. uscan
7.12.3. gbp
7.12.4. gbp + uscan
7.13. Формат исходного кода 3.0
7.14. CDBS
7.15. Сборка с использованием кодировки UTF-8
7.16. Преобразование в кодировку UTF-8
7.17. Загрузите orig.tar.gz
7.18. Пропущенные загрузки
7.19. Продвинутые темы работы над пакетом
7.20. Другие дистрибутивы
7.21. Отладка

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] 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-dsc: импортировать предыдущий пакет Debian с исходным кодом в git-репозиторий.
  • gbp import-orig: импортировать новый tar-архив основной ветки в git-репозиторий.

    • The --pristine-tar option for the git import-orig command enables storing the upstream tarball in the same git repository.
    • The --uscan option as the last argument of the gbp import-orig command enables downloading and committing the new upstream tarball into the git repository.
  • gbp dch: создание записи журнала изменений Debian из сообщений о коммитах.
  • gbp buildpackage: сборка двоичного пакета Debian из git-репозитория.

    • The sbuild package can be used as its clean chroot build backend either by configuration or adding --git-builder='sbuild -A -s --source-only-changes -v -d unstable'
  • gbp pull: безопасно обновить ветки debian, upstream и pristine-tar из удалённого репозитория.
  • Команды gbp pq, git-dpm или quilt (или её псевдоним dquilt) используются для работы с заплатами quilt.

    • The dquilt command is the simplest to learn and requires you to commit the resulting files manually with the git command to the master branch.
    • The “gbp pq” command provides the equivalent functionality of patch set management without using dquilt and eases including upstream git repository changes by cherry-picking.
    • The “git dpm” command provides more enhanced functionality than that of the ‘gbp pq’' command.

Package history management with the git-buildpackage package is becoming the standard practice for most Debian maintainers.

См.:

[Tip] Tip

Расслабьтесь. Вам не нужно использовать все обёртки и инструменты. Используйте только те, которые подходят под ваши нужды.

Для пакета Debian с исходным кодом с именем <source-package>, сохранённого в архиве snapshot.debian.org начальный git-репозиторий со всей историей версий Debian можно получить следующим образом.

$ gbp import-dscs --debsnap --pristine-tar '<source-package>'

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:

  • dgit-maint-merge(7) — for dpkg-source "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.
  • dgit-maint-debrebase(7) — for dpkg-source "Format: 3.0 (quilt)" package with its changes flowing mostly one way from the upstream Git repository to the Debian Git repository.
  • dgit-maint-gbp(7) — for dpkg-source "Format: 3.0 (quilt)" package with its Debian Git repository which is kept usable also for people using gbp-buildpackage(1).
  • dgit-maint-native(7) — for dpkg-source "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).

  • dgit push-source — for uploading source-only package (normal)
  • dgit push — for uploading binary package

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]

Ниже приводится краткий обзор доступных команд для сборки пакетов. Существует множество способов сделать одно и то же.

  • dpkg-buildpackage = ядро инструмента для сборки пакета
  • debuild = dpkg-buildpackage + lintian (сборка с очищенными переменными окружения)
  • schroot = core of the Debian chroot environment tool
  • sbuild = schroot + dpkg-buildpackage (build in the chroot)
  • gbp = manage the Debian source under git
  • gbp buildpackage = sbuild + dpkg-buildpackage + gbp (if configured with sbuild)

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

    • path: /srv/chroot/unstable-amd64-sbuild
  • The package build command for the unstable distribution chroot

    • sbuild
    • gbp buildpackage
  • The command to update the unstable chroot

    • sudo sbuild-update -udcar u
  • The command to login to the unstable chroot filesystem to modify it

    • sudo sbuild-shell u

Here, single "u" is predefined short alias for "unstable".

Произвольное окружение выпуска выпуск может быть использовано следующим образом.

  • Команда создания файловой системы chroot-окружения для выпуска выпуск

  • Главный путь файловой системы chroot-окружения для chroot-окружения выпуска выпуск

    • path: /srv/chroot/dist-amd64-sbuild
  • Команда сборки пакета для chroot-окружения выпуска выпуск

    • sbuild -d dist
    • gbp buildpackage --git-dist=выпуск
  • Команда для обновления chroot-окружения выпуск

    • sudo sbuild-update -udcar dist
  • The command to login to the master chroot (source:dist) of the dist distribution environment to modify it persistently

    • sudo sbuild-shell dist
[Tip] 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] 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] 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

Описание в этом разделе слишком кратко, чтобы оно оказалось полезным для большинства будущих сопровождающих. Это — намеренный выбор автора. Настоятельно рекомендуется поискать и прочесть всю соответствующую документация, связанную с используемыми командами.

[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] 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.

Обновление стиля пакета не является требуемой деятельностью до обновления пакета. Тем не менее, такое обновление позволяет использовать все возможности современной системы 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] 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] 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.

  • dpkg-buildpackage -sa
  • debuild -sa
  • *sbuild
  • При использовании gbp buildpackage отредактируйте файл ~/.gbp.conf.
[Tip] Tip

С другой стороны использование опции -sd приведёт к тому, что архив с оригинальным исходным кодом, orig.tar.gz, будет включён в загрузку.

[Tip] Tip

Security uploads require including the orig.tar.gz file.

Если вы создаёте несколько записей в файле debian/changelog и пропускаете загрузки, то вам следует создать соответствующий файл *_.changes, включающий все изменения с последней загрузки. Это можно сделать, передав dpkg-buildpackage опцию -v с указанием последней загруженной версии, например, 1.2.

  • dpkg-buildpackage -v1.2
  • debuild -v1.2
  • sbuild --debbuildopts -v1.2
  • При использовании gbp buildpackage отредактируйте файл ~/.gbp.conf.

Полезные советы по приведённым ниже вопросам можно найти в странице руководства debhelper(7):

Полезные советы по приведённым ниже вопросам можно найти в странице руководства dpkg-source(1):

  • naming convention for multiple upstream source tarballs

    • имяпакета_версия.orig.tar.gz
    • имяпакета_версия.orig-имякомпонента.tar.gz
  • запись изменений Debian в пакет исходного кода основной ветки

    • dpkg-source --commit

Несмотря на то, что в 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.

Когда вы сталкиваетесь с проблемами сборки или дампом памяти созданных двоичных программ, вам необходимо разрешить их самостоятельно. Это называется отладкой.

Это слишком обширная тема, чтобы обсуждать её в настоящем руководстве. Поэтому позвольте просто привести несколько ссылок и полезных советов по использованию типичных инструментов отладки.

  • дамп памяти

    • man core
    • Обновите файл «/etc/security/limits.conf» так, чтобы он включал в себя следующее:

      * soft core unlimited
    • «ulimit -c unlimited» в ~/.bashrc
    • «ulimit -a» для проверки
    • Нажмите Ctrl-\ или «kill -ABRT PID» для того, чтобы создать файл с дампом памяти
  • gdb — отладчик GNU

    • info gdb
    • «Отладка с помощью GDB» в /usr/share/doc/gdb-doc/html/gdb/index.html
  • strace — трассировка системных вызовов и сигналов

    • Используйте сценарий strace-graph из каталога /usr/share/doc/strace/examples/, чтобы иметь удобную визуализацию в виде дерева
    • man strace
  • ltrace - трассировка библиотечных вызовов

    • «man ltrace»
  • «sh -n script.sh» — проверка синтаксиса сценариев командной оболочки
  • «sh -x script.sh» — трассировка сценария командной оболочки
  • «python -m py_compile script.py» — проверка синтаксиса сценария на языке Python
  • «python -mtrace --trace script.py» — трассировка сценария на языке Python
  • «perl -I ../libpath -c script.pl» — проверка синтаксиса сценария на языке Perl
  • «perl -d:Trace script.pl» — трассировка сценария на языке Perl

    • Install the libterm-readline-gnu-perl package or its equivalent to add input line editing capability with history support.
  • lsof — вывод списка файлов, открытых процессами

    • man lsof
[Tip] Tip

The script command records console outputs.

[Tip] Tip

The screen and tmux commands used with the ssh command offer secure and robust remote connection terminals.

[Tip] 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] 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.