Chapter 5. Основы

Table of Contents

5.1. Работа по созданию пакета
5.1.1. Пакет debhelper
5.2. Historical perspective of Debian packaging practices
5.3. Future perspective on Debian packaging practices
5.4. Имя пакета и версия
5.5. Родной пакет Debian
5.6. debian/rules
5.6.1. dh
5.6.2. Простой сценарий debian/rules
5.6.3. Настроенный файл debian/rules
5.6.4. Переменные debian/rules
5.6.5. Повторяемая сборка
5.7. debian/control
5.7.1. Split of a Debian binary package
5.7.1.1. debmake -b
5.7.1.2. Сценарии и примеры разделения пакета
5.7.1.3. Имя пакета библиотеки
5.7.2. Переменные подстановки
5.7.3. Безопасная binNMU-загрузка
5.8. debian/changelog
5.9. debian/copyright
5.10. debian/patches/*
5.10.1. dpkg-source -x
5.10.2. dquilt и dpkg-source
5.11. debian/upstream/signing-key.asc
5.12. debian/watch и критерии Debian по определению свободного ПО (DFSG)
5.13. Other debian/* Files
5.14. Настройка пакета Debian
5.15. Запись в систему управления версиями (стандарт)
5.16. Запись в систему управления версиями (альтернатива)
5.17. Сборка пакета без постороннего содержимого
5.17.1. Исправление с помощью debian/rules clean
5.17.2. Исправление с помощью систем управления версиями
5.17.3. Исправление с помощью extend-diff-ignore
5.17.4. Исправление с помощью tar-ignore
5.18. Системы сборки основой ветки
5.18.1. Autotools
5.18.2. CMake
5.18.3. Meson
5.18.4. Python distutils
5.19. Отладочная информация
5.19.1. New -dbgsym package (Stretch 9.0 and after)
5.20. Пакет библиотеки
5.20.1. Библиотека символов
5.20.2. Смена библиотек
5.21. debconf
5.22. Multiarch
5.22.1. Путь мультиархитектурной библиотеки
5.22.2. Путь мультархитектурных заголовочных файлов
5.22.3. Мультиархиектурный путь к файлу *.pc
5.23. Усиление безопасности компилятора
5.24. Непрерывная интеграция
5.25. Other new requirements
5.26. Предзагрузка
5.27. Bug reports

A broad overview is presented here for the basic rules of Debian packaging focusing on the non-native Debian package in the “3.0 (quilt)” format.

[Note] Note

Для ясности в дайльнейшем были умышленно опущены некоторые детали. Ознакомьтесь со страницами руководства dpkg-source(1), dpkg-buildpackage(1), dpkg(1), dpkg-deb(1), deb(5) и др.

Пакет Debian с исходным кодом является набором входных файлов, используемых для сборки двоичного пакета Debian, и не представляет собой только один файл.

The Debian binary package is a special archive file which holds a set of installable binary data with its associated information.

Один пакет Debian с исходным кодом может использоваться для создания нескольких двоичных пакетов Debian, определяемых в файле debian/control.

Неродной пакет Debian в формате «3.0 (quilt)» является наиболее обычным форматом пакетов Debian с исходным кодом.

[Note] Note

Сущесвтует множество обёрточных сценариев. Используйте их для упрощения вашей работы, но обязательно разберитесь с основами их внутреннего устройства.

The Debian packaging workflow to create a Debian binary package involves generating several specifically named files (see Section 5.4, “Имя пакета и версия”) as defined in the “Debian Policy Manual”.

The oversimplified method for the Debian packaging workflow can be summarized in 10 steps as follows.

  1. Загружается tar-архив основной ветки разработки в виде файла пакет-версия.tar.gz.
  2. Этот архив распаковывается, создаётся множество файлов в каталоге пакет-версия/.
  3. Архив основной ветки разработки копируется (или создаётся символьная ссылка на него) в файл со специальным именем имяпакета_версия.orig.tar.gz.

    • символ, разделяющий пакет и версию, заменяется с - (дефиса) на _ (подчёркивание)
    • к расширению добавляется .orig.
  4. К исходному коду основной ветки разработки в каталог пакет-версия/debian/ добавляются файлы спецификации пакета Debian.

    • Обязательные файлы спецификации в каталоге debian/*:

      debian/rules
      Исполняемый сценарий для сборки пакета Debian (см. Section 5.6, “debian/rules”)
      debian/control
      The package configuration file containing the source package name, the source build dependencies, the binary package name, the binary dependencies, etc. (see Section 5.7, “debian/control”)
      debian/changelog
      Файл с историей пакета Debian, определяющий в первой строке версию пакета из основной ветки разработки и номер редакции Debian (см. Section 5.8, “debian/changelog”)
      debian/copyright
      Информация об авторских правах и лицензии (см. Section 5.9, “debian/copyright”)
    • Необязательные файлы спецификации в каталоге debian/* (see Section 5.13, “Other debian/* Files”):
    • Команда debmake, запущенная в каталоге пакет-версия/, создаёт изначальный набор шаблонных файлов настройки.

      • Обязательные файлы спецификации создаются даже при использовании опции -x0.
      • Команда debmake не перезаписывает какие-либо существующией файлы настройки.
    • Эти файлы должны быть отредактированы вручную с целью доведения их до совершенства в соответствии с «Руководством по политике Debian» и «Справочником разработчика Debian».
  5. The dpkg-buildpackage command (usually from its wrapper debuild or sbuild) is invoked in the package-version/ directory to make the Debian source and binary packages by invoking the debian/rules script.

    • Текущий каталог устанавливается следующим образом: $(CURDIR)=/путь/до/пакет-версия/
    • Создание пакета Debian с исходным кодом в формате «3.0 (quilt)» с помощью dpkg-source(1)

      • пакет_версия.orig.tar.gz (копия или символьная ссылка на пакет-версия.tar.gz)
      • пакет_версия-редакция.debian.tar.xz (tar-архив каталога пакет-версия/debian/*)
      • пакет_версия-редакция.dsc
    • Сборка исходного кода с помощью «debian/rules build» в $(DESTDIR)

      • DESTDIR=debian/binarypackage/ (один двоичный пакет)
      • DESTDIR=debian/tmp/ (несколько двоичных пакетов)
    • Создание двоичного пакета Debian с помощью dpkg-deb(1), dpkg-genbuildinfo(1) и dpkg-genchanges(1).

      • двоичныйпакет_версия-редакция_архитектура.deb
      • … (Могут существовать несколько файлов с двоичными пакетами Debian.)
      • пакет_версия-редакция_архитектура.changes
      • package_version-revision_arch.buildinfo
  6. Проверка качества пакета Debian с помощью команды lintian. (рекомендуется)

  7. Test the goodness of the generated Debian binary package manually by installing it and running its programs.
  8. After confirming the goodness, prepare files for the normal source-only upload to the Debian archive.
  9. Sign the package_version-revision.dsc and 'package_version-revision’_*source.changes* files with the debsign command using your private GPG key.
  10. Upload the set of the Debian source package files with the dput command to the Debian archive.

Test building and confirming of the binary package goodness as above is the moral obligation as a diligent Debian developer but there is no physical barrier for people to skip such operations at this moment for the source-only upload.

Under some exceptional situation such as NEW uploads, uploads to the Debian archive may need to include Debian binary package files. For such situation, sign package_version-revision_arch.changes instead of 'package_version-revision’_*source.changes* in the step 9, and upload the set of the Debian source and binary package files in the step 10.

Теперь замените каждую часть имени файла.

  • часть пакет на имя пакета Debian с исходным кодом
  • часть двоичныйпакет на имя двоичного пакета Debian
  • часть версия на версию основной ветки разработки
  • часть редакция на номер редации Debian
  • часть архитектура на архитектуру пакета

See also Source-only uploads.

[Tip] Tip

Использется множество различных стратегий по управлению заплатами и использованию систем управления версиями. Вам не следует использовать все из них.

[Tip] Tip

There is very extensive documentation in Chapter 6. Best Packaging Practices in the “Debian Developer’s Reference”. Please read it.

Although a Debian package can be made by writing a debian/rules script without using the debhelper package, it is impractical to do so. There are too many modern “Policy” required features to be addressed, such as application of the proper file permissions, use of the proper architecture dependent library installation path, insertion of the installation hook scripts, generation of the debug symbol package, generation of package dependency information, generation of the package information files, application of the proper timestamp for reproducible build, etc.

Debhelper package provides a set of useful scripts in order to simplify Debian’s packaging workflow and reduce the burden of package maintainers. When properly used, they will help packagers handle and implement “Policy” required features automatically.

Процедура создания пакета Debian в современном стиле может быть организована в виде набора простых модульных действий:

  • using the dh command to invoke many utility scripts automatically from the debhelper package, and
  • настройка их поведения с помощью декларативных файлов настройки в каталоге debian/.

You should almost always use debhelper as your package’s build dependency. This document also assumes that you are using a fairly contemporary version of debhelper to handle packaging works in the following contents.

Let me oversimplify historical perspective of Debian packaging practices.

Debian was started in 1990s when upstream packages were available from public FTP sites such as Sunsite. In those early days, Debian packaging used dpkg-source currently known as "Format: 1.0":

  • Upstream released packages in tar.gz format. They were obtained from some FTP sites.
  • Debian applied "one big patch" as its source distribution and made its binary distribution form it.
  • Many different approaches were adopted by different Debian developers to manage topic patches with custom scripts within the "one big patch". — Chaos!

In order to address issues of old dpkg-source "Format: 1.0", new dpkg-source "Format: 3.0 (quilt)" was invented around 2008:

  • Upstream released packages in tar.gz/tar.bz2/tar.xz format optionally with signature files. They were obtained from some HTTP sites.
  • Most Debian developers adopted patch queue mechanism of "Format: 3.0 (quilt)" to manage topic patches and made Debian packages while keeping files outside of debian/ directory untouched.
  • VCS, especially git, became popular and most Debian developers and started to record this packaging practice in gbp-buildpackage(1) style.
  • The gbp-buildpackage(1) workflow records the exact same content of the upstream tarball to VCS for source files outside of debian/ directory (= patch-unapplied).

The use of Git repositories to distribute upstream packages with signed tags (supported feature since 2011) became very popular.

  • The tarball centric gbp-buildpackage(1) workflow to record changes to VCS was cumbersome for some Debian developers and dgit(1) was invented in 2013.
  • The Git centric dgit-maint-debrebase(7) and dgit-maint-merge(7) workflows to record changes to VCS are gaining popularity among these Debian developers.
  • Source files recorded to VCS by dgit-maint-debrebase(7) and git-maint-merge(7) are modified upstream source files (= patch-applied).
  • Uploaded source packages by dgit-maint-debrebase(7) and git-maint-merge(7) workflows still use dpkg-source "Format: 3.0 (quilt)".

Debian also enforced the source-only upload when developing Debian/11 Bullseye (released in 2021).

In this tutorial, mostly simple tarball based dpkg-source "Format: 3.0 (quilt)" examples are presented as an introductory purpose.

Please assess these VCS usage approaches by yourself later to decide which one to deploy as your preferred one.

Please also read Notes on Debian by Russ Allbery which have best practices such as Using Git for Debian Packaging.

Please look around to understand how Debian packaging practices are evolving and follow the current general trends if possible.

You can also search entire Debian source code by yourself, too.

Если исходный код основной ветки разработки поставляется в виде архива hello-0.9.12.tar.gz, можно использовать hello в качестве имени пакета с исходным кодом основной ветки разработки, а 0.9.12 — в качестве версии основной ветки.

Утилита debmake предназначена для создания шаблонных файлов в помощью сопровождающему пакета. Строчки с комментариями начинаются с символа # и содержат обучающий текст. Вам следует удалить или отредактировать строки с комментариями до выполнения загрузки пакета в архив Debian.

The license extraction and assignment process involves a lot of heuristics; it may fail in some cases. It is highly recommended to use other tools such as licensecheck from the devscripts package in conjunction with debmake.

There are some limitations for what characters may be used as a part of the Debian package. The most notable limitation is the prohibition of uppercase letters in the package name. Here is a summary as a set of regular expressions:

  • Имя пакета основной ветки разработки (-p): [-+.a-z0-9]{2,}
  • Имя двоичного пакета (-b): [-+.a-z0-9]{2,}
  • Версия основной ветки разработки (-u): [0-9][-+.:~a-z0-9A-Z]*
  • Редакция Debian (-r): [0-9][+.~a-z0-9A-Z]*

See the exact definition in Chapter 5 - Control files and their fields in the “Debian Policy Manual”.

debmake предполагает относительно простые случаи создания пакетов. Поэтому все программы, относящиеся е интерпретатору, считаются «Architecture: all». Тем не менее, это не всегда так.

Вам следует соответствующим образом изменить имя пакета и версию основной ветки разработки для создания пакета Debian.

Для того, чтобы информация об имени пакета и номере версии эффективно обрабатывались такими популярными инструментами как команда aptitude, рекомендуется, чтобы длина имени пакета была равна 30 символам или была меньше; а общая длина версии и редакции была равна 14 символам или меньше. [11]

Для того, чтобы не возникали конфликты, видимое пользователю имя двоичного пакета не следует выбирать из числа распространённых слов.

If upstream does not use a normal versioning scheme such as 2.30.32 but uses some kind of date such as 11Apr29, a random codename string, or a VCS hash value as part of the version, make sure to remove them from the upstream version. Such information can be recorded in the debian/changelog file. If you need to invent a version string, use the YYYYMMDD format such as 20110429 as upstream version. This ensures that the dpkg command interprets later versions correctly as upgrades. If you need to ensure a smooth transition to a normal version scheme such as 0.1 in the future, use the 0~YYMMDD format such as 0~110429 as upstream version, instead.

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

$ dpkg --compare-versions ver1 op ver2

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

  • Строки сравниваются в порядке с начала до конца.
  • Буквы больше чисел.
  • Числа сравниваются как целые числа.
  • Буквы сравниваются в порядке таблицы кодов ASCII.

Также имеются специальные правила для символов точки (.), плюса (+) и тильды (~). Они показаны ниже.

0.0 < 0.5 < 0.10 < 0.99 < 1 < 1.0~rc1 < 1.0 < 1.0+b1 < 1.0+nmu1 < 1.1 < 2.0

Один сложный случай возникает тогда, когда разработчики основной ветки выпускают hello-0.9.12-ReleaseCandidate-99.tar.gz как предварительный выпуск для hello-0.9.12.tar.gz. Вам следует гарантировать, что обновление пакета Debian будет происходить правильно, переименовав для этого архив с исходным кодом основной ветки в hello-0.9.12~rc99.tar.gz.

Неродной пакет Debian в формате «3.0 (quilt)» является самым обычным форматом пакетов Debian с исходным кодом. Файл debian/source/format должен содержать строку «3.0 (quilt)», что описывается в dpkg-source(1). Описанные выше процедуры создания пакетов и примеры используют этот формат.

A native Debian package is the rare Debian binary package format. It may be used only when the package is useful and valuable only for Debian. Thus, its use is generally discouraged.

[Caution] Caution

A native Debian package is often accidentally built when its upstream tarball is not accessible from the dpkg-buildpackage command with its correct name package_version.orig.tar.gz . This is a typical newbie mistake caused by making a symlink name with “-” instead of the correct one with “_”.

A native Debian package has no separation between the upstream code and the Debian changes and consists only of the following:

  • пакет_версия.tar.gz (копия или символьная ссылка на пакет-версия.tar.gz с файлами debian/*.)
  • пакет_версия.dsc

If you need to create a native Debian package, create it in the “3.0 (native)” format using dpkg-source(1).

[Tip] Tip

Some people promote packaging even programs that have been written only for Debian in the non-native package format. The required tarball without debian/* files needs to be manually generated in advance before the standard workflow in Section 5.1, “Работа по созданию пакета”. [12] They claim that the use of non-native package format eases communication with the downstream distributions.

[Tip] Tip

При использовании формата родных пкетов нужды заранее создавать tar-архив нет. Родной пакет может быть создан в том случае, если файл debian/source/format содержит строку «3.0 (native)», в файле debian/changelog указана версия без редакции Debian (1.0 вместо 1.0-1), а также в дереве исходного кода вызывается команда «dpkg-source -b .». Тогда создаётся tar-архив, содержащий исходный код.

Сценарий debian/rules представляет собой исполняемый сценарий для сборки пакета Debian.

The dh command from the debhelper package with help from its associated packages functions as the wrapper to the typical upstream build systems and offers us uniform access to them by supporting all the Debian policy stipulated targets of the debian/rules file.

  • dh clean : вычищет файлы в дереве исходного кода.
  • dh build : сборка дерева исходного кода
  • dh build-arch : сборка зависящих от архитектуры пакетов из дерева исходного кода
  • dh build-indep : сборка независящих от архитектуры пакетов из дерева исходного кода
  • dh install : установка двоичных файлов в $(DESTDIR)
  • dh install-arch : установка двоичных файлов в $(DESTDIR) для зависящих от архитектуры пакетов
  • dh install-indep : установка двоичных файлов в $(DESTDIR) для независящих от архитектуры пакетов
  • dh binary : создание файла deb
  • dh binary-arch : создание файла deb для зависящих от архитектуры пакетов
  • dh binary-indep : создание файла deb для независящих от архитектуры пакетов
[Note] Note

Для пакетов, использующих debhelper и имеющих «compat >= 9», команда dh экспортирует флаги компилятора (CFLAGS, CXXFLAGS, FFLAGS, CPPFLAGS и LDFLAGS) со значениями, возвращаемыми командой dpkg-buildflags в том случае, если они не были установлены ранее. (Команда dh вызывает функцию set_buildflags, определённую в модуле Debian::Debhelper::Dh_Lib.)

Благодаря абстракциям команды dh [13] соответствующий политике Debian файл debian/rules, поддерживающий все требуемые цели, можно написать так же просто как [14]:

Простой файл debian/rules

#!/usr/bin/make -f
#export DH_VERBOSE = 1

%:
        dh $@

По сути, эта команда dh работает как планировщик для вызовов всех требуемых команд dh_* в нужный момент.

[Tip] Tip

Установка «export DH_VERBOSE = 1» приводит к тому, что в выводе отражаются все команды, изменяющие файлы в сборочной системе. Кроме того, для некоторых систем сборки это включает режим создания более подробных журналов.

Гибкая настройка сценария debian/rules осуществляется путём добавления соответствующих целей override_dh_* и их правил.

Всякий раз как требуется выполнить какую-то специальную операцию для определённой команды dh_foo, вызываемой командой dh, всякое автоматическое выполнение её может быть отменено путём добавления Makefile-цели override_dh_foo в файл debian/rules.

The build process may be customized via the upstream provided interface such as arguments to the standard source build system commands, such as:

  • configure,
  • Makefile,
  • setup.py или
  • Build.PL.

If this is the case, you should add the override_dh_auto_build target and executing the “dh_auto_build -- arguments” command. This ensures passing arguments to the such build system after the default parameters that dh_auto_build usually passes.

[Tip] Tip

Please try not to execute the above build system commands directly if they are supported by the dh_auto_build command.

The debmake command creates the initial template file taking advantage of the above simple debian/rules file example while adding some extra customizations for package hardening, etc. You need to know how underlying build systems work under the hood (see Section 5.18, “Системы сборки основой ветки”) to address their irregularities using package customization.

Некоторые определения переменных, которые могут оказаться полезными для debian/rules, можно найти в файлах в каталоге /usr/share/dpkg/. В частности:

pkg-info.mk
DEB_SOURCE, DEB_VERSION, DEB_VERSION_EPOCH_UPSTREAM, DEB_VERSION_UPSTREAM_REVISION, DEB_VERSION_UPSTREAM, and DEB_DISTRIBUTION variables. These are useful for backport support etc..
vendor.mk
DEB_VENDOR and DEB_PARENT_VENDOR variables; and dpkg_vendor_derives_from macro. These are useful for vendor support (Debian, Ubuntu, …).
architecture.mk
Set DEB_HOST_* and DEB_BUILD_* variables. An alternative method of retrieving those variables is to invoke dpkg-architecture directly and query the value of a single variable. With explicit invocation of dpkg-architecture to retrieve necessary variables, there is no need to include architecture.mk in debian/rules, which would import all architecture-related variables.
buildflags.mk
Установите флаги сборки CFLAGS, CPPFLAGS, CXXFLAGS, OBJCFLAGS, OBJCXXFLAGS, GCJFLAGS, FFLAGS, FCFLAGS и LDFLAGS.

If you wish to use some of these useful variables in debian/rules, copy relevant code to debian/rules or write a simpler alternative in it. Please keep debian/rules simple.

Например, можно добавить дополнительную опцию в CONFIGURE_FLAGS для архитектур linux-any, добавляя следующее в файл debian/rules:

DEB_HOST_ARCH_OS ?= $(shell dpkg-architecture -qDEB_HOST_ARCH_OS)
 ...
ifeq ($(DEB_HOST_ARCH_OS),linux)
CONFIGURE_FLAGS += --enable-wayland
endif
[Tip] Tip

It was useful to include buildflags.mk in debian/rules to set the build flags such as CPPFLAGS, CFLAGS, LDFLAGS, etc. properly while honoring DEB_CFLAGS_MAINT_APPEND, DEB_BUILD_MAINT_OPTIONS, etc. for the debhelper “compat <= 8”. Now you should use the debhelper “compat >= 9”, should not include buildflags.mk without specific reasons, and should let the dh command set these build flags.

См. Section 5.22, “Multiarch”, dpkg-architecture(1) и dpkg-buildflags(1).

Here are some recommendations to attain a reproducible build result.

Управляющий файл имя-исходного-кода_версия-исходного-кода_архитектура.buildinfo, создаваемый dpkg-genbuildinfo(1), содержит информацию о сборочном окружении. См. deb-buildinfo(5)

The debian/control file consists of blocks of meta data separated by a blank line. Each block of meta data defines the following in this order:

  • метаданных пакета Debian с исходным кодом
  • метаданные двоичных пакетов Debian

See Chapter 5 - Control files and their fields of the “Debian Policy Manual” for the definition of each meta data.

[Note] Note

The debmake command sets the debian/control file with “Build-Depends: debhelper-compat (= 13)” to set the debhelper compatibility level.

[Tip] Tip

If an existing package has lower than debhelper compatibility level 9, probably it’s time to update its packaging.

For well behaving build systems, the split of a Debian binary package into small ones can be realized as follows.

  • Создайте записи с определениями метаданных двоичных пакетах в файле debian/control для всех двоичных пакетов.
  • Укажите все пути к файлам (относительно каталга debian/tmp) в соответствующих файлах debian/двоичныйпакет.install.

С примерами можно ознакомиться в настоящем руководстве:

The debmake command with the -b option provides an intuitive and flexible method to create the initial template debian/control file defining the split of the Debian binary packages with following stanzas:

  • Package:
  • Architecture:
  • Multi-Arch:
  • Depends:
  • Pre-Depends:

The debmake command also sets an appropriate set of substvars used in each pertinent dependency stanza.

Ниже приводится цитата соответствующей части страницы руководства debmake.

-b "двоичныйпакет[:тип],…", --binaryspec "двоичныйпакет[:тип],…"

set the binary package specs by a comma separated list of binarypackage:type pairs, e.g., in the full form “foo:bin,foo-doc:doc,libfoo1:lib,libfoo-dev:dev” or in the short form, “-doc,libfoo1,libfoo-dev”.

Here, binarypackage is the binary package name, and the optional type is chosen from the following type values:

  • bin: скомпилированный двоичный пакет с исполняемыми файлами формата ELF на языке C/C++ (any, foreign) (по умолчанию, псевдоним: "", то есть пустая-строка)
  • data: пакет с данными (шрифты, графика, …) (all, foreign) (псевдоним: da)
  • dev: пакет с библиотекой разработки (any, same) (псевдоним: de)
  • doc: пакет документации (all, foreign) (псевдоним: do)
  • lib: пакет с библиотекой (any, same) (псевдоним: l)
  • perl: пакет со сценарием на языке Perl (all, foreign) (псевдоним: pl)
  • python3: Python (version 3) script package (all, foreign) (alias: py3)
  • ruby: пакет со сценарием на языке Ruby (all, foreign) (псевдоним: rb)
  • nodejs: Node.js based JavaScript package (all, foreign) (alias: js)
  • script: пакет со сценарием командной оболочки (all, foreign) (псевдоним: sh)

Пары значений в скобках, такие как (any, foreign), представляют собой значения служебных строк Architecture и Multi-Arch, устанавливаемые в файле debian/control.

Во многих случаях команда debmake довольно хорошо предсказывает значение поля тип, исходя из значения поля двоичныйпакет. Если тип не очевиден, то значением поля тип становится bin. Например, исходя из libfoo значением поля тип становится lib, а исходя из font-bar значением поля тип становится data, …

Если содержимое дерева исходного кода не совпадает с настройками поля тип, то команда debmake выводит предупреждение.

Ниже приводится несколько типичных сценариев разделения мультиархитектурного пакета для следующих примеров исходного кода основной ветки разработки, в которых используется команда debmake:

  • исходный код библиотеки libfoo-1.0.tar.gz
  • исходный код утилиты bar-1.0.tar.gz, написанный на компилируемом языке
  • исходный код утилиты baz-1.0.tar.gz, написанный на интерпретируемом языке
двоичныйпакет тип Architecture: Multi-Arch: Содержимое пакета

lib foo1

lib *

any

same

разделяемая бибиотека, возможна совместная установка

lib foo -dev

dev *

any

same

заголовочные файлы разделяемой библиотеки и проч., возможна совместная установка

lib foo -tools

bin *

any

foreign

программы с поддержкой времени исполнения, совместная установка невозможна

lib foo -doc

doc *

all

foreign

файлы документации разделяемой библиотеки

bar

bin *

any

foreign

скомпилированный файлы программы, совместная устанвка невозможна

bar -doc

doc *

all

foreign

файлы документации программы

baz

script

all

foreign

файлы интерпретируемой программы

Let’s consider that the upstream source tarball of the libfoo library is updated from libfoo-7.0.tar.gz to libfoo-8.0.tar.gz with a new SONAME major version which affects other packages.

Двоичный пакет библиотеки следует переименовать с libfoo7 в libfoo8, чтобы после загрузки пакета, созданного из на осно, в unstable все зависимые пакеты остались в рабочем состоянии.

[Warning] Warning

If the binary library package isn’t renamed, many dependent packages in the unstable suite become broken just after the library upload even if a binNMU upload is requested. The binNMU may not happen immediately after the upload due to several reasons.

Пакет -dev должен соответствовать следующим правилам именования:

[Tip] Tip

If the data encoding scheme changes (e.g., latin1 to utf-8), the same care as the API change needs to be taken.

См. Section 5.20, “Пакет библиотеки”.

Кроме того, файл debian/control определяет зависимости пакета, в которых может исопльзоваться механизм подстановки переменных (substvar), который освобождает сопровождающих пакета от рутинной работы по отслеживанию большинства простых зависимостей пакета. См. deb-substvars(5).

The debmake command supports the following substvars:

  • ${misc:Depends} для всех двоичных пакетов
  • ${misc:Pre-Depends} для всех мультиархитектурных пакетов
  • ${shlibs:Depends} для всех двоичных пакетов с исполняемыми файлами и пакетов библиотек
  • ${python:Depends} для всех пакетов с кодом на языке Python
  • ${python3:Depends} для всех пакетов с кодом на языке Python3
  • ${perl:Depends} для всех пакетов с кодом на языке Perl
  • ${ruby:Depends} для всех пакетов с кодом на языке Ruby

Для разделяемых библиотек необходимые библиотеки обнаруживаются с помощью просто команды «objdump -p /путь/к/программе | grep NEEDED» и обрабатываются переменной подстановки shlib.

For Python and other interpreters, required modules found simply looking for lines with “import”, “use”, “require”, etc., are covered by the corresponding substvars.

Для остальных программ, не использующих собственные переменные подстановки, зависимости обрабатываются переменной misc.

Для программ командной оболочки POSIX нет простого способа определения зависимостей, поэтому их зависимости не обрабатываются никакой переменной.

Для библиотек и модулей, требующихся через механизм динамической загрузки, включая механизм GObject-интроспекция, нет простого способа определения зависимостей, поэтому их зависимости не обрабатываются никакой переменной.

A binNMU is a binary-only non-maintainer upload performed for library transitions etc. In a binNMU upload, only the “Architecture: any” packages are rebuilt with a suffixed version number (e.g. version 2.3.4-3 will become 2.3.4-3+b1). The “Architecture: all” packages are not built.

The dependency defined in the debian/control file among binary packages from the same source package should be safe for the binNMU. This needs attention if there are both “Architecture: any” and “Architecture: all” packages involved in it.

  • Architecture: any” package: depends on “Architecture: anyfoo package

    • Depends: foo (= ${binary:Version})
  • Architecture: any” package: depends on “Architecture: allbar package

    • Depends: bar (= ${source:Version})
  • Architecture: all” package: depends on “Architecture: anybaz package

    • Depends: baz (>= ${source:Version}), baz (<< ${source:Version}.0~)

The debian/changelog file records the Debian package history and defines the upstream package version and the Debian revision in its first line. The changes need to be documented in the specific, formal, and concise style.

  • Even if you are uploading your package by yourself, you must document all non-trivial user-visible changes such as:

    • the security related bug fixes.
    • the user interface changes.
  • If you are asking your sponsor to upload it, you should document changes more comprehensively, including all packaging related ones, to help reviewing your package.

    • The sponsor shouldn’t second guess your thought behind your package.
    • The sponsor’s time is more valuable than yours.

Команда debmake создаёт изначальный шаблонный файл с версией основной ветки и редакцией Debian. С целью предотвращения случайной загрузки в архив Debian выбирается выпуск UNRELEASED.

The debchange command (alias dch) is commonly used to edit this.

[Tip] Tip

You can edit the debian/changelog file manually with any text editor as long as you follow the formatting convention used by the debchange command.

[Tip] Tip

Строка с датой, используемая в файле debian/changelog, может быть создана вручную с помощью команды «LC_ALL=C date -R».

Этот файл устанавливается командой dh_installchangelogs в каталог /usr/share/doc/двоичныйпакет под именем changelog.Debian.gz.

Журнал изменений основной ветки устанавливается в каталог /usr/share/doc/двоичныйпакет под именем changelog.gz.

The upstream changelog is automatically found by the dh_installchangelogs using the case insensitive match of its file name to changelog, changes, changelog.txt, changes.txt, history, history.txt, or changelog.md and searched in the ./ doc/ or docs/ directories.

After finishing your packaging and verifying its quality, please execute the “dch -r” command and save the finalized debian/changelog file with the distribution normally set to unstable. [15] If you are packaging for backports, security updates, LTS, etc., please use the appropriate distribution names instead.

Debian takes the copyright and license matters very seriously. The “Debian Policy Manual” enforces having a summary of them in the debian/copyright file in the package.

You should format it as a machine-readable debian/copyright file (DEP-5).

[Caution] Caution

Файл debian/copyright должен быть отсортирован таким образом, что наиболее общие шаблоны файлов были размещены в начале списка. См. Section 6.4, “debmake -k”.

Команда debmake создаёт изначальный совместимый с DEP-5 шаблонный файл, сканируя все дерево исходного кода. Она использует специальную внутреннюю команду для проверки и классификации лицензий. [16]

Если команде debmake не была передана опция -P, то команда пропускает создаваемые автоматически файлы под разрешительными лицензиями.

[Note] Note

Если при проверке лицензионной информации вы обнаружите какие-либо проблемы, то отправьте сообщение об ошибке в пакете debmake с проблемной частью текста, содержащего информацию об авторском праве и лицензии.

[Note] Note

The debmake command focuses on bunching up same copyright and license claims in detail to create template for debian/copyright. In order to do this within reasonable time, it only picks the first section which looks like copyright and license claims. So its license assignment may not be optimal. Please also use other tools such as licensecheck.

[Tip] Tip

You are highly encouraged to check the license status with the licensecheck(1) command and, as needed, with your manual code review.

Заплаты -p1 в каталоге debian/patches/ применяются в последовательности, определяемой в файле debian/patches/series, к дереву исходного кода основной ветки до запуска процесса сборки.

[Note] Note

В родных пакетах Debian (см. Section 5.5, “Родной пакет Debian”) эти файлы не используются.

Имеется несколько способов подготовки серии заплат -p1.

  • Команда diff

    • См. Section 4.9.1, “Создание заплаты с помощью diff -u”
    • Примитивный, но универсальный метод

      • Заплаты могут поступать из других дистрибутивов, из сообщений в списках рассылки или выборки заплат из git-репозитория основной ветки разработки с помощью команды «git format-patches»
    • Отсутствие каталога .pc/
    • Неизменённое дерево исходного кода основной ветки
    • Обновите файл debian/patches/series вручную
  • Команда dquilt

    • См. Section 3.4, “quilt”
    • Простой и удобный метод
    • Правильное создание данных в каталоге .pc/
    • Изменённое дерево исходного кода основной ветки
  • Команда «dpkg-source --commit»

  • Автоматическое создание заплат с помощью dpkg-buildpackage

  • The gbp pq command

    • Простая работа в стиле git с помощью пакета git-buildpackage
    • Отсутствие каталога .pc/
    • Modified upstream source tree in the throw-away branch (patch-queue/master)
    • Неизменённый исходный код основной ветки в Debian-ветке (master)
  • The git-dpm command

    • Более продуманный подход в стиле git с помощью пакета git-dpm
    • Отсутствие каталога .pc/
    • Изменённый исходный код основной ветки в ветке patched (patched/чтоугодно)
    • Неизменённый исходный код основной ветки в Debian-ветке (master/чтоугодно)

Wherever these patches come from, it is a good idea to tag them with a DEP-3 compatible header.

[Tip] Tip

The dgit package offers an alternative git integration tool with the Debian package archive.

До появления опции --commit у команды dpkg-source в версии 1.16.1 для работы с заплатами -p1 из каталога debian/patches/ требовалась команда quilt (или её обёртка dquilt).

The patches should apply cleanly when using the dpkg-source command. Thus you can’t just copy the patches to the new packaging of the new upstream release if there are patch offsets, etc.

The dquilt command (see Section 3.4, “quilt”) is more forgiving. You can normalize the patches by the dquilt command.

 $ while dquilt push; do dquilt refresh ; done
 $ dquilt pop -a

There is one advantage of using the dpkg-source command over the dquilt command. While the dquilt command cannot handle modified binary files automatically, the dpkg-source command detects modified binary files and lists them in the debian/source/include-binaries file to include them in the Debian tarball.

Some packages are signed by a GPG key.

Например, пакет GNU hello можно загрузить через HTTP по адресу https://ftp.gnu.org/gnu/hello/. Там содержится несколько файлов:

  • hello-версия.tar.gz (исходный код основной ветки)
  • hello-версия.tar.gz.sig (отделённая подпись)

Выберем самую последнюю версию.

$ wget https://ftp.gnu.org/gnu/hello/hello-2.9.tar.gz
 ...
$ wget https://ftp.gnu.org/gnu/hello/hello-2.9.tar.gz.sig
 ...
$ gpg --verify hello-2.9.tar.gz.sig
gpg: Signature made Thu 10 Oct 2013 08:49:23 AM JST using DSA key ID 80EE4A00
gpg: Can't check signature: public key not found

If you know the public GPG key of the upstream maintainer from the mailing list, use it as the debian/upstream/signing-key.asc file. Otherwise, use the hkp keyserver and check it via your web of trust.

$ gpg --keyserver hkp://keys.gnupg.net --recv-key 80EE4A00
gpg: requesting key 80EE4A00 from hkp server keys.gnupg.net
gpg: key 80EE4A00: public key "Reuben Thomas <rrt@sc3d.org>" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg:               imported: 1
$ gpg --verify hello-2.9.tar.gz.sig
gpg: Signature made Thu 10 Oct 2013 08:49:23 AM JST using DSA key ID 80EE4A00
gpg: Good signature from "Reuben Thomas <rrt@sc3d.org>"
  ...
Primary key fingerprint: 9297 8852 A62F A5E2 85B2  A174 6808 9F73 80EE 4A00
[Tip] Tip

Если ваше сетевое окружение блокирует доступ к HKP-порту 11371, используйте «hkp://keyserver.ubuntu.com:80».

After confirming the key ID 80EE4A00 is a trustworthy one, download its public key into the debian/upstream/signing-key.asc file.

$ gpg --armor --export 80EE4A00 >debian/upstream/signing-key.asc

Затем настройте файл debian/watch соответствующим образом.

version=4
pgpsigurlmangle=s/$/.sig/  https://ftp.gnu.org/gnu/hello/ hello-(\d[\d.]*)\.tar\.(?:gz|bz2|xz)

Теперь команда uscan будет выполнять проверку подлинности пакета с помощью его GPG-подписи.

Debian очень серьёзно относится к вопросу свободы ПО и руководствуется в этом DFSG.

Несоответствующие DFSG компоненты в tar-архиве исходного кода основной ветки можно легко удалить в том случае, когда для обновления пакета Debian используется команда uscan.

  • Укажите список файлов для удаления в строке Files-Excluded файла debian/copyright.
  • Укажите URL для загрузки tar-архива основной ветки в файле debian/watch.
  • Запустите команду uscan для загрузки нового tar-архива основной ветки.

    • Либо используйте команду «gbp import-orig --uscan --pristine-tar».
  • Получившийся tar-архив будет иметь версию с дополнительным суффиком +dfsg.

В каталог debian/ можно добавить дополнительные файлы настройки. Большинство из них используются для управления командами dh_*, предоставляемыми пакетом debhelper, но также имеются дополнительные файлы для команд dpkg-source, lintian и gbp.

[Tip] Tip

Наиболее свежий список доступных команд dh_* см. в debhelper(7).

Файлы debian/двоичныйпакет.* предоставляют очень мощные средства для выбора путей установки файлов. С помощью этих файлов можно создать пакет даже из исходный кода основной ветки, неиспользующего какую-либо систему сборки. Пример см. в Section 8.2, “Без Makefile (командная оболочка, интерфейс командной оболочки)”.

The "-x[1234]" superscript notation that appears in the following list indicates the minimum value for the debmake -x option that will generate the associated template file. See Section 6.6, “debmake -x” or debmake(1) for details.

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

двоичныйпакет.bug-control -x3
устанавливается как usr/share/bug/двоичныйпакет/control в двоичныйпакет. См. Section 5.27, “Bug reports”.
двоичныйпакет.bug-presubj -x3
устанавливается как usr/share/bug/двоичныйпакет/presubj в binarypackage. См. Section 5.27, “Bug reports”.
двоичныйпакет.bug-script -x3
устанавливается как usr/share/bug/двоичныйпакет или usr/share/bug/двоичныйпакет/script в двоичныйпакет. См. Section 5.27, “Bug reports”.
двоичныйпакет.bash-completion

Список устанавливаемых автодополнений bash.

The bash-completion package is required for both build and user environments.

См. dh_bash-completion(1).

clean -x2

List files that should be removed but are not cleaned by the dh_auto_clean command.

См. dh_auto_clean(1) и dh_clean(1).

compat -x3

Previously, this set the debhelper compatibility level.

Now, use Build-Depends: debhelper-compat (= 13) in debian/control to specify the compatibility level.

См. «COMPATIBILITY LEVELS» в debhelper(8).

двоичныйпакет.conffile

No need for this file now since all files in the etc/ directory are conffiles for recent “compat >= 3”.

If the program you’re packaging requires every user to modify the configuration files in the /etc directory, there are two popular ways to arrange for them not to be conffiles, keeping the dpkg command happy and quiet.

  • Создайте символьную ссылку в каталоге /etc, указывающую на файл в каталоге /var, создаваемый сценариями сопровождающего.
  • Создайте файл с помощью сценариев сопровождающего в каталоге /etc.

См. dh_installdeb(1).

двоичныйпакет.config
Это config-сценарий debconf, используемый для того, чтобы задавать пользователю любые необходимые для настройки пакета вопросы. См. Section 5.21, “debconf”.
двоичныйпакет.cron.hourly -x3

Устанавливается в файл etc/cron/hourly/двоичныйпакет в двоичныйпакет.

См. dh_installcron(1) и cron(8).

двоичныйпакет.cron.daily -x3

Устанавливается в файл etc/cron/daily/двоичныйпакет в двоичныйпакет.

См. dh_installcron(1) и cron(8).

двоичныйпакет.cron.weekly -x3

Устанавливается в файл etc/cron/weekly/двоичныйпакет в двоичныйпакет.

См. dh_installcron(1) и cron(8).

двоичныйпакет.cron.monthly -x3

Устанавливается в файл etc/cron/monthly/двоичныйпакет в двоичныйпакет.

См. dh_installcron(1) и cron(8).

двоичныйпакет.cron.d -x3

Устанавливается в файл etc/cron.d/двоичныйпакет в двоичныйпакет.

См. dh_installcron(1), cron(8) и crontab(5).

двоичныйпакет.default -x3

Если такой файл существует, то он устанавливается в etc/default/двоичныйпакет в двоичныйпакет.

См. dh_installinit(1).

двоичныйпакет.dirs -x3

Содержит список каталогов, которые должны быть созданы в двоичныйпакет.

См. dh_installdirs(1).

Это это не требуется, поскольку все команды dh_install* автоматически создают необходимые каталоги. Используйте этот файл только в том случае, если у вас возникают какие-либо затруднения.

двоичыйпакет.doc-base -x2

Устанавливается как управляющий файл doc-base в двоичныйпакет.

См. dh_installdocs(1) и Руководство Debian по doc-base, предоставляемое пакетом doc-base.

двоичныйпакет.docs -x2

Создержит список файлов документации для их установки в двоичныйпакет.

См. dh_installdocs(1).

двоичныйпакет.emacsen-compat -x3

Устанавливается в usr/lib/emacsen-common/packages/compat/двоичныйпакет в binarypackage.

См. dh_installemacsen(1).

двоичныйпакет.emacsen-install -x3

Устанавливается в usr/lib/emacsen-common/packages/install/двоичныйпакет в двоичныйпакет.

См. dh_installemacsen(1).

двоичныйпакет.emacsen-remove -x3

Устанавливается в usr/lib/emacsen-common/packages/remove/двоичныйпакет в двоичныйпакет.

См. dh_installemacsen(1).

двоичныйпакет.emacsen-startup -x3

Устанавливается в usr/lib/emacsen-common/packages/startup/двоичныйпакет в двоичныйпакет.

См. dh_installemacsen(1).

двоичныйпакет.examples -x2

Содержит список файлов или каталогов с примерами для их установки в usr/share/doc/двоичныйпакет/examples/ в двоичныйпакет.

См. dh_installexamples(1).

gbp.conf

Если этот файл существует, то он используется как файл настройки для команды gbp.

См. gbp.conf(5), gbp(1) и git-buildpackage(1).

двоичныйпакет.info -x2

Содержит список info-файлов для их установки в двоичныйпакет.

См. dh_installinfo(1).

двоичныйпакет.init -x3

Устанавливается в etc/init.d/двоичныйнакет в двоичныйпакет.

См. dh_installinit(1).

двоичныйпакет.install -x2

Содержит список файлов, которые должны быть установлены, но не устанавливаются командой dh_auto_install.

См. dh_install(1) и dh_auto_install(1).

license-examples/* -x4

These are copyright file examples generated by the debmake command. Use these as the reference for making the copyright file.

Обязательно удалите эти файлы.

двоичныйпакет.links -x2

List pairs of source and destination files to be symlinked. Each pair should be put on its own line, with the source and destination separated by whitespace.

См. dh_link(1).

двоичныйпакет.lintian-overrides -x3

Устанавливается в usr/share/lintian/overrides/двоичныйпакет в каталоге сборки пакета. Этот файл используется для блокировки ошибочных диагностических процедур lintian.

См. dh_lintian(1), lintian(1) и Руководство пользователя Lintian.

manpage.* -x3

Команда debmake создаёт шаблонные файы страниц руководства. Переименуйте эти файлы соответствующим образом и обновите их содержимое.

Политика Debian требует, чтобы у каждой программы, утилиты и функции была связанная с ними страница руководства, входящая в состав того же пакета. Страницы руководства пишутся в формате nroff(1).

If you are new to making a manpage, use manpage.asciidoc or manpage.1 as the starting point.

двоичныйпакет.manpages -x2

Содержит список страниц руководства для их установки.

См. dh_installman(1).

двоичныйпакет.menu (устарел, более не устанавливается)

Технический комитет в #741573 решил «В Debian следует соответствующим образом использовать файлы .desktop".

Файл меню Debian устанавливается в usr/share/menu/двоичныйпакет в двоичныйпакет.

Информацию о формате см. в menufile(5). См. dh_installmenu(1).

NEWS

Устанавливается в usr/share/doc/двоичныйпакет/NEWS.Debian.

См. dh_installchangelogs(1).

patches/*

Набор файлов заплат -p1, которые применяются к исходному коде основной ветки до запуска процесса сборки исходного кода.

См. dpkg-source(1), Section 3.4, “quilt” и Section 4.9, “Шаг 3 (альтернативный): изменение исходного кода основной ветки разработки”.

Команда debmake не создаёт файлы заплат.

patches/series -x1
Последовательность применения файлов заплат patches/*.
двоичныйпакет.preinst -x2 , двоичныйпакет.postinst -x2 , двоичныйпакет.prerm -x2 , двоичныйпакет.postrm -x2

Указанные сценарии сопровождаюшего устанавливаются в каталог DEBIAN.

В самих этих сценариях токен #DEBHELPER# заменяется на фрагменты кода, создаваемые другими командами debhelper.

See dh_installdeb(1) and Chapter 6 - Package maintainer scripts and installation procedure in the “Debian Policy Manual”.

See also debconf-devel(7) and 3.9.1 Prompting in maintainer scripts in the “Debian Policy Manual”.

README.Debian -x1

Устанавливается в первый двоичный пакет, указанный в файле debian/control как usr/share/doc/двоичныйпакет/README.Debian.

См. dh_installdocs(1).

Этот файл содержит специальную информацию о пакете Debian.

двоичныйпакет.service -x3

Если этот файл существует, то он устанавливается в lib/systemd/system/двоичныйпакет.service в binarypackage.

См. dh_systemd_enable(1), dh_systemd_start(1) и dh_installinit(1).

source/format -x1

Формат пакета Debian.

  • Используйте «3.0 (quilt)» для создания неродных пакетов (рекомендуется)
  • Используйте «3.0 (native)» для создания родного пакета

См. «SOURCE PACKAGE FORMATS» в dpkg-source(1).

source/lintian-overrides или source.lintian-overrides -x3

Эти файлы не устанавливаются, но загружаются командой lintian и предоставляют отмены проверок для пакета с исходным кодом.

См. dh_lintian(1) и lintian(1).

source/local-options -x1

The dpkg-source command uses this content as its options. Notable options are:

  • unapply-patches
  • abort-on-upstream-changes
  • auto-commit
  • single-debian-patch

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

См. «FILE FORMATS» в dpkg-source(1).

source/local-patch-header

Свободная текстовая форма, размещаемая в верхней части автоматически созданной заплаты.

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

+ См. «FILE FORMATS» в dpkg-source(1).

двоичныйпакет.symbols -x2

Файлы символов. Если эти файлы существуют, то они будут переданы для обработки и установки команде dpkg-gensymbols.

См. dh_makeshlibs(1) и Section 5.20.1, “Библиотека символов”..

двоичныйпакет.templates
Это файл шаблонов для debconf. Он используется для вывода вопросов, необходимых для настройки пакета. См. Section 5.21, “debconf”.
tests/control
This is the RFC822-style test meta data file defined in DEP-8. See autopkgtest(1) and Section 5.24, “Непрерывная интеграция”.
TODO

Устанавливается в первый двоичный пакет, указанный в файле debian/control как usr/share/doc/двоичныйпакет/TODO.Debian.

См. dh_installdocs(1).

двоичныйпакет.tmpfile -x3

Если этот файл существует, то он устанавливается в usr/lib/tmpfiles.d/двоичныйпакет.conf в двоичныйпакет.

См. dh_systemd_enable(1), dh_systemd_start(1) и dh_installinit(1).

двоичныйпакет.upstart -x3

Если этот файл существует, то он устанавливается в etc/init/package.conf в каталог сборки пакета. (устарел)

См. dh_installinit(1) и Section 8.1, “Выборочное применение шаблонов”.

watch -x1

The control file for the uscan command to download the latest upstream version.

Этот управляющий файл можно настроить так, чтобы выполнялась проверка подлинности tar-архива с помощью его GPG-подписи (см. Section 5.11, “debian/upstream/signing-key.asc”).

См. Section 5.12, “debian/watch и критерии Debian по определению свободного ПО (DFSG)” и uscan(1).

Here are a few reminders for the above list.

  • For a single binary package, the binarypackage. part of the filename in the list may be removed.
  • For a multi binary package, a configuration file missing the binarypackage. part of the filename is applied to the first binary package listed in the debian/control.
  • Если создаётся много двоичных пакетов, то их настройки можно указать отдельно, добавив их имя к их файлам настройки, например, таким как пакет-1.install, пакет-2.install и т. д.
  • Некоторые шаблонные файлы настроек могут не быть созданы командой debmake. В таких случаях вам следует создать их с помощью редактора.
  • Unusual configuration template files generated by the debmake command with an extra .ex suffix need to be activated by removing that suffix.
  • Неиспользуемые шаблонные файлы настроек, созданные командой debmake, следует удалить.
  • Копируйте шаблонные файлы настроек по необходимости в файлы с соответствующими именами двоичных пакетов.

Кратко резюмируем настройку пакета Debian.

All customization data for the Debian package resides in the debian/ directory. A simple example is given in Section 4.7, “Шаг 3: изменение шаблонных файлов”. Normally, this customization involves a combination of the following:

When these are not sufficient to make a good Debian package, modifications to the upstream source recorded as the -p1 patches in the debian/patches/ directory is deployed. These patches are applied in the sequence defined in the debian/patches/series file before building the package (see Section 5.10, “debian/patches/*”). Simple examples are given in Section 4.9, “Шаг 3 (альтернативный): изменение исходного кода основной ветки разработки”.

You should address the root cause of the Debian packaging problem by the least invasive way. The generated package shall be more robust for future upgrades in this way.

[Note] Note

Send the patch addressing the root cause to the upstream maintainer if it is useful to the upstream.

Typically, Git is used as the VCS to record the Debian packaging activity with the following branches.

  • ветка master

    • Записывает дерево исходного кода, используемое для пакета Debian.
    • Часть, относящаяся к дереву исходного кода основной ветки разработки, записывается в неизменённом виде.
    • Изменения основной ветки, производимые в пакете Debian, записываются в каталог debian/patches/ в виде -p1 заплат.
  • ветка upstream

    • Record the upstream source tree untarred from the released upstream tarball.
[Tip] Tip

It’s a good idea to add to the .gitignore file the listing .pc.

[Tip] Tip

Add unapply-patches and abort-on-upstream-changes lines to the debian/source/local-options file to keep the upstream portion unmodified.

[Tip] Tip

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

Можно не сохранять заплаты -p1 для всех изменений основной ветки, свою работу над пакетом Debian можно хранить в следующих ветках.

  • ветка master

    • Записывает дерево исходного кода, используемое для пакета Debian.
    • Исходный код основной ветки сохраняется вместе с изменениями, внесёнными в ходе подготовки пакета Debian.
  • ветка upstream

    • Record the upstream source tree untarred from the released upstream tarball.

Adding a few extra files in the debian/ directory enables you to do this.

 $ tar -xvzf <package-version>.tar.gz
 $ ln -sf <package_version>.orig.tar.gz
 $ cd <package-version>/
 ... hack...hack...
 $ echo "single-debian-patch" >> debian/source/local-options
 $ cat >debian/source/local-patch-header <<END
 This patch contains all the Debian-specific changes mixed
 together. To review them separately, please inspect the VCS
 history at https://git.debian.org/?=collab-maint/foo.git.

Let the dpkg-source command invoked by the Debian package build process (dpkg-buildpackage, debuild, …) generate the -p1 patch file debian/patches/debian-changes automatically.

[Tip] Tip

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

[Tip] Tip

Файлы debian/source/local-options и debian/source/local-patch-header следует сохранять в системе управления версиями. Они не входят в пакет Debian с исходным кодом.

There are a few cases which cause the inclusion of undesirable contents in the generated Debian source package.

  • Дерево исходного кода основной ветки может быть размещено в системе управления версиями. При пересборке пакета из дерева исходного кода создаваемый пакет Debian с исходным кодом содержит постороннее содержимое, источником которого является система управления содержимым.
  • Дерево исходного кода основной ветки может содержать автоматически создаваемые файлы. При пересборке пакета из дерева исходного кода создаваемый пакет Debian с исходным кодом содержит постороннее содержимое, источником которого являются автоматически создаваемые файлы.

Обычно в Section 3.5, “devscripts” для команды dpkg-source устанавливаются опции -i и -I, что позволяет этого избежать. Опция -i предназначена для неродных пакетов, а опция -I — для родных пакетов. См. dpkg-source(1) и вывод команды «dpkg-source --help».

There are several methods to avoid inclusion of undesirable contents.

This is for a non-native package.

Проблема посторонних изменений может быть исправлена путём игнорирования изменений, внесённых в часто дерева исходного кода, путём добавления в файл debian/source/options строки «extend-diff-ignore=…».

Для того, чтобы исключить файлы config.sub, config.guess и Makefile, добавьте следующее:

# Don't store changes on autogenerated files
extend-diff-ignore = "(^|/)(config\.sub|config\.guess|Makefile)$"
[Note] Note

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

[Tip] Tip

Если используется файл debian/source/local-options, то можно скрыть эти настройки из создаваемого пакета с исходным кодом. Это может быть полезно в том случае, когда локальные нестандартные файлы системы управления версиями вмешиваются в процесс создания вашего пакета.

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

Three typical build systems are described here. The situation of other build systems are very similar to these since debhelper(7) the does most of the work and helps you build a Debian package.

[Tip] Tip

Before attempting to make a Debian package, you should become familiar with the upstream build system of the upstream source code and try to build it.

The Debian package is built with the debugging information but packaged into the binary package after stripping the debugging information as required by Chapter 10 - Files of the “Debian Policy Manual”.

См.

Packaging library software requires you to perform much more work than usual. Here are some reminders for packaging library software:

Before packaging shared library software, see:

Для получения исторических сведений обратитесь к следующей документации:

The symbols support in dpkg introduced in Debian lenny (5.0, May 2009) helps us to manage the backward ABI compatibility of the library package with the same package name. The DEBIAN/symbols file in the binary package provides the minimal version associated with each symbol.

An oversimplified method for the library packaging is as follows.

  • Распакуйте старый файл DEBIAN/symbols ближайшего предыдущего двоичного пакета с помощью команды «dpkg-deb -e».

    • Либо можно использовать команду mc для распаковки файла DEBIAN/symbols.
  • Скопируйте его в файл debian/двоичныйпакет.symbols.

    • Если это первый пакет, то используйте пустой файл.
  • Соберите двоичный пакет.

    • If the dpkg-gensymbols command warns about some new symbols:

      • Распакуйте обновлённый файл DEBIAN/symbols с помощью команды «dpkg-deb -e».
      • Удалите номер редакции версии Debian, например, -1, из файла.
      • Скопируйте его в файл debian/двоичныйпакет.symbols.
      • Повторно соберите двоичный пакет.
    • If the dpkg-gensymbols command does not warn about new symbols:

      • Работа с библиотекой завершена.

Подробные сведения можно получить, обратившись к следующей справочной информации:

Также следует ознакомиться со следующей документацией:

[Tip] Tip

For C++ libraries and other cases where the tracking of symbols is problematic, follow 8.6.4 The shlibs system of the “Debian Policy Manual”, instead. Please make sure to erase the empty debian/binarypackage.symbols file generated by the debmake command. For this case, the DEBIAN/shlibs file is used.

Пакет debconf позволяет нам настраивать пакеты в ходе их установки двуями основными способами:

  • неинтерактивно из предпосевных настроек программы установки Debian.
  • интерактивно из меню-ориентированного интерфейса (dialog, gnome, kde, …)

    • установка пакета: вызывается командой dpkg
    • установленный пакет: вызывается командой dpkg-reconfigure

Всё взаимодействие с пользователем в ходе установки пакета должны обрабатыватся системой debconf с помощью следующих файлов.

  • debian/binarypackage.config

    • Этот config-сценарий debconf используется для того, чтобы задавать любые вопросы, необходимые для настройки пакета.
  • debian/двоичныйпакет.template

    • Этот templates-файл debconf используется для того, чтобы задавать любые вопросы, наобходимые для настройки пакета.
  • сценарии настройка пакета

    • debian/двоичныйпакет.preinst
    • debian/двоичныйпакет.prerm
    • debian/двоичныйпакет.postinst
    • debian/двоичныйпакет.postrm

See dh_installdebconf(1), debconf(7), debconf-devel(7) and 3.9.1 Prompting in maintainer scripts in the “Debian Policy Manual”.

Multiarch support for cross-architecture installation of binary packages (particularly i386 and amd64, but also other combinations) in the dpkg and apt packages introduced in Debian wheezy (7.0, May 2013), demands that we pay extra attention to packaging.

Вам следует подробно изнакомиться со следующей справочной документацией:

Мультиархитектурность включается с помощью значения <тройки> вида i386-linux-gnu или x86_64-linux-gnu в пути установки разделяемых библиотек вида /usr/lib/<тройка>/ и т. д.

  • Значение <тройки>, внутренне необходимое для сценариев debhelper, устанавливается самими сценариями неявно. Сопровождающему не нужно об этом беспокоиться.
  • The <triplet> value used in override_dh_* target scripts must be explicitly set in the debian/rules file by the maintainer. The <triplet> value is stored in the $(DEB_HOST_MULTIARCH) variable in the following debian/rules snippet example:

    DEB_HOST_MULTIARCH = $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
    ...
    override_dh_install:
            mkdir -p package1/lib/$(DEB_HOST_MULTIARCH)
            cp -dR tmp/lib/. package1/lib/$(DEB_HOST_MULTIARCH)

См.:

Debian policy requires following Filesystem Hierarchy Standard. Its /usr/lib : Libraries for programming and packages states "/usr/lib includes object files, libraries, and internal binaries that are not intended to be executed directly by users or shell scripts."

Debian policy makes an exception to the Filesystem Hierarchy Standard to use /usr/lib/<triplet>/ instead of /usr/lib<qual>/ (e.g., /lib32/ and /lib64/) to support a multiarch library.


Для пакетов на основе Autotools, в которых используется пакет debhelper с (compat>=9), установка этого пути выполняется автоматически с помощью команды dh_auto_configure.

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

  • If “./configure” is used in the override_dh_auto_configure target in debian/rules, make sure to replace it with “dh_auto_configure --” while re-targeting the install path from /usr/lib/ to /usr/lib/$(DEB_HOST_MULTIARCH)/.
  • Замените все пути с /usr/lib/ на /usr/lib/*/ в файлах debian/foo.install.

All files installed simultaneously as the multiarch package to the same file path should have exactly the same file content. You must be careful with differences generated by the data byte order and by the compression algorithm.

[Note] Note

The --libexecdir option of the ./configure command specifies the default path to install executable programs run by other programs rather than by users. Its Autotools default is /usr/libexec/ but its Debian non-multi-arch default is /usr/lib/. If such executables are a part of a "Multi-arch: foreign" package, a path such as /usr/lib/ or /usr/lib/packagename may be more desirable than /usr/lib/<triplet>/, which dh_auto_configure uses. The GNU Coding Standards: 7.2.5 Variables for Installation Directories has a description for libexecdir as "The definition of libexecdir is the same for all packages, so you should install your data in a subdirectory thereof. Most packages install their data under $(libexecdir)/package-name/ …". (It is always a good idea to follow GNU unless it conflicts with the Debian policy.)

Файлы разделяемых библиотек, расположенные в каталогах по умолчанию, /usr/lib/ и /usr/lib/<тройка>/, загружаются автоматически.

For shared library files in another path, the GCC option -l must be set by the pkg-config command to make them load properly.

The compiler hardening support spreading for Debian jessie (8.0, TBA) demands that we pay extra attention to the packaging.

Вам следует подробно изнакомиться со следующей справочной документацией:

Команда debmake добавляет шаблонные комментарии в файл debian/rules, требующиеся для DEB_BUILD_MAINT_OPTIONS, DEB_CFLAGS_MAINT_APPEND и DEB_LDFLAGS_MAINT_APPEND (см. Chapter 4, Простой пример и dpkg-buildflags(1)).

DEP-8 defines the debian/tests/control file as the RFC822-style test metadata file for continuous integration (CI) of the Debian package.

It is used after building the binary packages from the source package containing this debian/tests/control file. When the autopkgtest command is run, the generated binary packages are installed and tested in the virtual environment according to this file.

See documents in the /usr/share/doc/autopkgtest/ directory and 4. autopkgtest: Automatic testing for packages of the “Ubuntu Packaging Guide”.

[Note] Note

Testing of the binary packages during their building time can be accomodated by dh_auto_test.

Кроме того, в Debian существует ещё несколько других инструментов непрерывной интеграции.

  • The debci package: CI platform on top of the autopkgtest package
  • Пакет jenkins: платформа непрерывной интеграции общего назначения

Debian packaging practices are moving target. Please keep your eyes on DEP - Debian Enhancement Proposals.

Debian cares about supporting new ports or flavours. The new ports or flavours require bootstrapping operation for the cross-build of the initial minimal native-building system. In order to avoid build-dependency loops during bootstrapping, the build-dependency needs to be reduced using the profile builds feature.

[Tip] Tip

Если сборка базового пакета foo зависит от пакета bar, имеющего глубокую цепочку сборочных зависимостей, но bar используется только в цели test в foo, вы можете пометить bar меткой <!nocheck> в поле Build-depends пакета foo, что позволит избежать циклов при сборке.

Поведение команды reportbug, используемой для отправки отчётов об ошибке в двоичномпакете, может быть настроено с помощью файлов в каталоге usr/share/bug/двоичныйпакет/.

Команда dh_bugfiles устанавливает эти файлы из шаблонных файлов в каталоге debian/.

  • debian/двоичныйпакет.bug-controlusr/share/bug/двоичныйпакет/control

    • Этот файл содержит некоторые указания, такие как перенаправления отчёта об ошибке другому пакету.
  • debian/двоичныйпакет.bug-presubjusr/share/bug/двоичныйпакет/presubj

    • Этот файл отображается пользователю с помощью команды reportbug.
  • debian/двоичныйпакет.bug-scriptusr/share/bug/двоичныйпакет или usr/share/bug/двоичныйпакет/script

    • Команда reportbug запускает этот сценарий для создания шаблонного файла для отчёта об ошибке.

См. dh_bugfiles(1) и Возможности reportbug для разработчиков

[Tip] Tip

If you always remind the bug reporter of something or ask them about their situation, use these files to automate it.



[11] Для более чем 90% пакетов длина имени пакета равна 24 символам или меньше этого числа; длина версии основной ветки равна 10 символам или меньше, а длина номера редакции Debian равна 3 символам или меньше.

[12] Use of the “debmake -t …” command or “git deborig -f HEAD” can help this workflow. See Section 6.2, “Snapshot upstream tarball (-d, -t)” and dgit-maint-merge(7).

[13] This simplicity is available since version 7 of the debhelper package. This guide assumes the use of debhelper version 13 or newer.

[14] Команда debmake создаёт несколько более сложный файл debian/rules. Тем не менее, это базовая часть.

[15] If you are using the vim editor, make sure to save this with the “:wq” command.

[16] Ранее для выполнения такой внутренней проверки использовалась команда licensecheck из пакета devscripts. Теперь же команда licensecheck предоставляется в виде отдельного пакета licensecheck и содержит множество улучшений.

[17] Этот документ был написан до появления файла symbols.

[18] The strong preference is to use the SONAME versioned -dev package names over the single -dev package name in Chapter 6. Development (-DEV) packages, which does not seem to be shared by the former ftp-master (Steve Langasek). This document was written before the introduction of the multiarch system and the symbols file.

[19] This path is compliant with the FHS. Filesystem Hierarchy Standard: /usr/lib : Libraries for programming and packages states "Applications may use a single subdirectory under /usr/lib. If an application uses a subdirectory, all architecture-dependent data exclusively used by the application must be placed within that subdirectory."