Глава 4. Простой пример

Содержание

4.1. Общая картина
4.2. Что такое debmake?
4.3. Что такое debuild?
4.4. Шаг 1: получение исходного кода основной ветки разработки
4.5. Шаг 2: создание шаблонных файлов с помощью debmake
4.6. Шаг 3: изменение шаблонных файлов
4.7. Шаг 4: сборка пакета с помощью debuild
4.8. Шаг 3 (альтернативный): изменение исходного кода основной ветки разработки
4.8.1. Создание заплаты с помощью diff -u
4.8.2. Создание заплаты с помощью dquilt
4.8.3. Создание заплаты с помощью dpkg-source --commit

Есть старая латинская поговорка: «Longum iter est per praecepta, breve et efficax per exempla» («Долог путь поучений, короток и успешен путь примеров»).

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

Допустим, имя tar-архива из основной ветки разработки будет debhello-0.0.tar.gz.

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

 $ tar -xzmf debhello-0.0.tar.gz
 $ cd debhello-0.0
 $ make
 $ make install

Debian packaging requires changing this “make install” process to install files to the target system image location instead of the normal location under /usr/local.

[Примечание] Примечание

Examples of creating a Debian package from other complicated build systems are described in Глава 8, Дополнительные примеры.

Общая картина сборки простого неродного пакета Debian из tar-архива основной ветки разработки debhello-0.0.tar.gz может быть представлена следующим образом:

  • The maintainer obtains the upstream tarball debhello-0.0.tar.gz and untars its contents to the debhello-0.0 directory.
  • The debmake command debianizes the upstream source tree by adding template files only in the debian directory.

    • Создаётся символьная ссылка debhello_0.0.orig.tar.gz, указывающая на файл debhello-0.0.tar.gz.
    • Сопровождающий настраивает шаблонные файлы.
  • Команда debuild собирает двоичный пакет из подготовленного дерева исходного кода.

    • Создаётся файл debhello-0.0-1.debian.tar.xz, содержащий каталог debian.

Общая картина сборки пакета. 

 $ tar -xzmf debhello-0.0.tar.gz
 $ cd debhello-0.0
 $ debmake
   ... manual customization
 $ debuild
   ...

[Подсказка] Подсказка

The debuild command in this and following examples may be substituted by equivalent commands such as the pdebuild command.

[Подсказка] Подсказка

If the upstream tarball in the .tar.xz format is available, use it instead of the one in the .tar.gz and .tar.bz2 formats. The xz compression format offers the better compression than the gzip and bzip2 compressions.

Команда debmake является вспомогательным сценарием для создания и изменения пакетов Debian.

  • Она всегда устанавливает большую часть очевидных опций в разумные значения.
  • Она создаёт tar-архив основной ветки разработки и необходимую символьную ссылку в случае их отсутствия.
  • Она не переписывает существующие файлы настройки в каталоге debian/.
  • Она поддерживает мультиархитектурные пакеты.
  • It creates good template files such as the debian/copyright file compliant with DEP-5.

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

[Примечание] Примечание

Команда debmake не является единственным способом создания пакета Debian. Множество пакетов создаются при помощи одного только текстового редактора по образу и подобию других сходных пакетов.

Ниже приводтся обзор команд, похожих на команду debuild.

[Примечание] Примечание

Подробную информацию см. в dpkg-buildpackage(1).

Получим исходный код основной ветки разработки.

Скачаем файл debhello-0.0.tar.gz

 $ wget http://www.example.org/download/debhello-0.0.tar.gz
 ...
 $ tar -xzmf debhello-0.0.tar.gz
 $ tree
.
├── debhello-0.0
│   ├── LICENSE
│   ├── Makefile
│   └── src
│       └── hello.c
└── debhello-0.0.tar.gz

2 directories, 4 files

В нём содерижится исходный код на языке C, hello.c, довольно простой.

hello.c

 $ cat debhello-0.0/src/hello.c
#include <stdio.h>
int
main()
{
        printf("Hello, world!\n");
        return 0;
}

Итак, Makefile поддерживает Стандартам написания кода GNU и Стандарту иерархии файловой системы. А именно:

  • сборку двоичных файлов с учётом значений $(CPPFLAGS), $(CFLAGS), $(LDFLAGS) и т. д.
  • install files with $(DESTDIR) defined to the target system image
  • install files with $(prefix) defined, which can be overridden to be /usr

Makefile

 $ cat debhello-0.0/Makefile
prefix = /usr/local

all: src/hello

src/hello: src/hello.c
        @echo "CFLAGS=$(CFLAGS)" | \
                fold -s -w 70 | \
                sed -e 's/^/# /'
        $(CC) $(CPPFLAGS) $(CFLAGS) $(LDCFLAGS) -o $@ $^

install: src/hello
        install -D src/hello \
                $(DESTDIR)$(prefix)/bin/hello

clean:
        -rm -f src/hello

distclean: clean

uninstall:
        -rm -f $(DESTDIR)$(prefix)/bin/hello

.PHONY: all install clean distclean uninstall

[Примечание] Примечание

The echo of the $(CFLAGS) variable is used to verify the proper setting of the build flag in the following example.

[Подсказка] Подсказка

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

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

 $ cd debhello-0.0
 $ debmake
I: set parameters
I: sanity check of parameters
I: pkg="debhello", ver="0.0", rev="1"
I: *** start packaging in "debhello-0.0". ***
I: provide debhello_0.0.orig.tar.gz for non-native Debian package
I: pwd = "/path/to"
I: $ ln -sf debhello-0.0.tar.gz debhello_0.0.orig.tar.gz
I: pwd = "/path/to/debhello-0.0"
I: parse binary package settings:
I: binary package=debhello Type=bin / Arch=any M-A=foreign
I: analyze the source tree
I: build_type = make
I: scan source for copyright+license text and file extensions
I: 100 %, ext = c
I: check_all_licenses
I: ..
I: check_all_licenses completed for 2 files.
I: bunch_all_licenses
I: format_all_licenses
I: make debian/* template files
I: single binary package
I: debmake -x "1" ...
I: creating => debian/control
I: creating => debian/copyright
I: substituting => /usr/share/debmake/extra0/rules
I: creating => debian/rules
I: substituting => /usr/share/debmake/extra0/changelog
I: creating => debian/changelog
I: substituting => /usr/share/debmake/extra1/compat
I: creating => debian/compat
I: substituting => /usr/share/debmake/extra1/watch
I: creating => debian/watch
I: substituting => /usr/share/debmake/extra1/README.Debian
I: creating => debian/README.Debian
I: substituting => /usr/share/debmake/extra1source/local-options
I: creating => debian/source/local-options
I: substituting => /usr/share/debmake/extra1source/format
I: creating => debian/source/format
I: substituting => /usr/share/debmake/extra1patches/series
I: creating => debian/patches/series
I: run "debmake -x2" to get more template files
I: $ wrap-and-sort

The debmake command generates all these template files based on command line options. Since no options are specified, the debmake command chooses reasonable default values for you:

  • Имя пакета с исходным кодом: debhello
  • Версия основной ветки разработки: 0.0
  • Имя двоичного пакета: debhello
  • Номер редакции Debian: 1
  • Тип пакета: bin (пакет с дволичными исполняемыми файлами формата ELF)
  • Опция -x: -x1 (используется по умолчанию для случая с одним двоичным пакетом)

Проверим созданные шаблонные файлы.

Дерево исходного кода после простого выполнения debmake

 $ cd ..
 $ tree
.
├── debhello-0.0
│   ├── LICENSE
│   ├── Makefile
│   ├── debian
│   │   ├── README.Debian
│   │   ├── changelog
│   │   ├── compat
│   │   ├── control
│   │   ├── copyright
│   │   ├── patches
│   │   │   └── series
│   │   ├── rules
│   │   ├── source
│   │   │   ├── format
│   │   │   └── local-options
│   │   └── watch
│   └── src
│       └── hello.c
├── debhello-0.0.tar.gz
└── debhello_0.0.orig.tar.gz -> debhello-0.0.tar.gz

5 directories, 15 files

Файл debian/rules является сборочным сценарием, предоставляемым сопровождающим пакета. Ниже приводится его шаблонный файл, созданный с помощью команды debmake.

debian/rules (шаблонный файл): 

 $ cat debhello-0.0/debian/rules
#!/usr/bin/make -f
# You must remove unused comment lines for the released package.
#export DH_VERBOSE = 1
#export DEB_BUILD_MAINT_OPTIONS = hardening=+all
#export DEB_CFLAGS_MAINT_APPEND  = -Wall -pedantic
#export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed

%:
        dh $@

#override_dh_auto_install:
#       dh_auto_install -- prefix=/usr

#override_dh_install:
#       dh_install --list-missing -X.pyc -X.pyo

По сути, это стандартный файл debian/rules с командой dh. (Для удобства его настройки в нём содержится несколько закомментированных строк.)

Файл debian/control предоставляет основные метаданные пакета Debian. Ниже приводится шаблонный файл, созданный командой debmake.

debian/control (шаблонный файл): 

 $ cat debhello-0.0/debian/control
Source: debhello
Section: unknown
Priority: optional
Maintainer: "Firstname Lastname" <email.address@example.org>
Build-Depends: debhelper (>=11~)
Standards-Version: 4.1.4
Homepage: <insert the upstream URL, if relevant>

Package: debhello
Architecture: any
Multi-Arch: foreign
Depends: ${misc:Depends}, ${shlibs:Depends}
Description: auto-generated package by debmake
 This Debian binary package was auto-generated by the
 debmake(1) command provided by the debmake package.

[Предупреждение] Предупреждение

If you leave “Section: unknown” in the template debian/control file unchanged, the lintian error may cause the build to fail.

Поскольку это пакет с двоичными исполняемыми файлами в формате ELF, команда debmake устанавливает «Architecture: any» и «Multi-Arch: foreign». Кроме того, она устанавливает требуемые параметры переменных подстановки следующим образом: «Depends: ${shlibs:Depends}, ${misc:Depends}». Это объясняется в Глава 5, Основы.

[Примечание] Примечание

Заметьте, что этот файл debian/control использует стиль оформления RFC-822, описываемый в 5.2 Управляющие файлы пакета с исходным кодом — debian/control в «Руководстве по политике Debian». Использование пустой строки и начального пробела важно и имеет особый смысл.

Файл debian/copyright предоставляет данные об авторском праве на пакет Debian. Ниже приводтся шаблонный файл, созданный командой debmake.

debian/copyright (шаблонный файл): 

 $ cat debhello-0.0/debian/copyright
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: debhello
Source: <url://example.com>
#
# Please double check copyright with the licensecheck(1) command.

Files:     Makefile
           src/hello.c
Copyright: __NO_COPYRIGHT_NOR_LICENSE__
License:   __NO_COPYRIGHT_NOR_LICENSE__

#----------------------------------------------------------------------------...
# Files marked as NO_LICENSE_TEXT_FOUND may be covered by the following
# license/copyright files.

#----------------------------------------------------------------------------...
# License file: LICENSE
 License:
 .
 All files in this archive are licensed under the MIT License as below.
 .
 Copyright 2015 Osamu Aoki <osamu@debian.org>
 .
 Permission is hereby granted, free of charge, to any person obtaining a
 copy of this software and associated documentation files (the "Software"),
 to deal in the Software without restriction, including without limitation
 the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following conditions:
 .
 The above copyright notice and this permission notice shall be included
 in all copies or substantial portions of the Software.
 .
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

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

Для того, чтобы установить файлы в качестве части системных файлов, текущее значение $(prefix), /usr/local, в Makefile должно быть заменено на /usr. Это можно сделать в файле debian/rules с помощью цели override_dh_auto_install, передав значение «prefix=/usr».

debian/rules (версия сопровождающего): 

 $ vim debhello-0.0/debian/rules
 ... hack, hack, hack, ...
 $ cat debhello-0.0/debian/rules
#!/usr/bin/make -f
export DH_VERBOSE = 1
export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export DEB_CFLAGS_MAINT_APPEND  = -Wall -pedantic
export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed

%:
        dh $@

override_dh_auto_install:
        dh_auto_install -- prefix=/usr

Exporting the DH_VERBOSE environment variable in the debian/rules file as above forces the debhelper tool to make a fine grained build report.

Exporting DEB_BUILD_MAINT_OPTION as above sets the hardening options as described in the “FEATURE AREAS/ENVIRONMENT” in dpkg-buildflags(1). [8]

Exporting DEB_CFLAGS_MAINT_APPEND as above forces the C compiler to emit all the warnings.

Exporting DEB_LDFLAGS_MAINT_APPEND as above forces the linker to link only when the library is actually needed. [9]

The dh_auto_install command for the Makefile based build system essentially runs “$(MAKE) install DESTDIR=debian/debhello”. The creation of this override_dh_auto_install target changes its behavior to “$(MAKE) install DESTDIR=debian/debhello prefix=/usr”.

Here are the maintainer versions of the debian/control and debian/copyright files.

debian/control (версия сопровождающего): 

 $ vim debhello-0.0/debian/control
 ... hack, hack, hack, ...
 $ cat debhello-0.0/debian/control
Source: debhello
Section: devel
Priority: optional
Maintainer: Osamu Aoki <osamu@debian.org>
Build-Depends: debhelper (>=11~)
Standards-Version: 4.1.3
Homepage: https://salsa.debian.org/debian/debmake-doc

Package: debhello
Architecture: any
Multi-Arch: foreign
Depends: ${misc:Depends}, ${shlibs:Depends}
Description: example package in the debmake-doc package
 This is an example package to demonstrate Debian packaging using
 the debmake command.
 .
 The generated Debian package uses the dh command offered by the
 debhelper package and the dpkg source format `3.0 (quilt)'.

debian/copyright (версия сопровождающего): 

 $ vim debhello-0.0/debian/copyright
 ... hack, hack, hack, ...
 $ cat debhello-0.0/debian/copyright
Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: debhello
Source: http://anonscm.debian.org/cgit/collab-maint/debmake-doc.git/tree/base...

Files:     *
Copyright: 2015 Osamu Aoki <osamu@debian.org>
License:   MIT
 Permission is hereby granted, free of charge, to any person obtaining a
 copy of this software and associated documentation files (the "Software"),
 to deal in the Software without restriction, including without limitation
 the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following conditions:
 .
 The above copyright notice and this permission notice shall be included
 in all copies or substantial portions of the Software.
 .
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

В каталоге debian/ имеются и другие шаблонные файлы. Их также следует обновить.

Шаблонные файлы в debian/. (v=0.0): 

 $ tree debhello-0.0/debian
debhello-0.0/debian
├── README.Debian
├── changelog
├── compat
├── control
├── copyright
├── patches
│   └── series
├── rules
├── source
│   ├── format
│   └── local-options
└── watch

2 directories, 10 files

[Подсказка] Подсказка

Configuration files used by the dh_* commands from the debhelper package usually treat # as the start of a comment line.

В данном дереве исходного кода вы можете создать неродной пакет Debian с помощью команды debuild или эквивалентных ей команд (см. Раздел 4.3, «Что такое debuild?»). Вывод команды очень подробен, выполняемые действия объясняются в нём следующим образом.

 $ cd debhello-0.0
 $ debuild
 dpkg-buildpackage -rfakeroot -us -uc -ui -i
 ...
 fakeroot debian/rules clean
dh clean
 ...
 debian/rules build
dh build
   dh_update_autotools_config
   dh_autoreconf
   dh_auto_configure
   dh_auto_build
        make -j4 "INSTALL=install --strip-program=true"
make[1]: Entering directory '/path/to/debhello-0.0'
# CFLAGS=-g -O2 -fdebug-prefix-map=/build/debmake-doc-1.11=.
# -fstack-protector-strong -Wformat -Werror=format-security
cc -Wdate-time -D_FORTIFY_SOURCE=2 -g -O2 -fdebug-prefix-map=/build/debmake-d...
 ...
 fakeroot debian/rules binary
dh binary
 ...
Now running lintian debhello_0.0-1_amd64.changes ...
 ...
W: debhello: binary-without-manpage usr/bin/hello
Finished running lintian.

 ...

You can verify that CFLAGS is updated properly with -Wall and -pedantic by the DEB_CFLAGS_MAINT_APPEND variable.

The manpage should be added to the package as reported by the lintian package, as shown in later examples (see Глава 8, Дополнительные примеры). Let’s move on for now.

Проверим результат сборки.

Файлы debhello версии 0.0, созданные с помощью команды debuild

 $ cd ..
 $ tree -FL 1
.
├── debhello-0.0/
├── debhello-0.0.tar.gz
├── debhello-dbgsym_0.0-1_amd64.deb
├── debhello_0.0-1.debian.tar.xz
├── debhello_0.0-1.dsc
├── debhello_0.0-1_amd64.build
├── debhello_0.0-1_amd64.buildinfo
├── debhello_0.0-1_amd64.changes
├── debhello_0.0-1_amd64.deb
└── debhello_0.0.orig.tar.gz -> debhello-0.0.tar.gz

1 directory, 9 files

Вы видите все созданные файлы.

  • debhello_0.0.orig.tar.gz представляет собой символьную ссылку на tar-архив основной ветки разработки.
  • debhello_0.0-1.debian.tar.xz содержит файлы, созданные сопровождающим.
  • debhello_0.0-1.dsc представляет собой файл с метаданными для пакета Debian с исходным кодом.
  • debhello_0.0-1_amd64.deb — двоичный пакет Debian.
  • The debhello-dbgsym_0.0-1_amd64.deb is the Debian debug symbol binary package. See Раздел 5.17.1, «New -dbgsym package (Stretch 9.0 and after)».
  • The debhello_0.0-1_amd64.build file is the build log file.
  • The debhello_0.0-1_amd64.buildinfo file is the meta data file generated by dpkg-genbuildinfo(1).
  • debhello_0.0-1_amd64.changes — файл с метаданными для двоичного пакета Debian.

debhello_0.0-1.debian.tar.xz содержит изменения Debian, внесённые в исходный код основной ветки разработки. Содержимое этого файла приведено ниже.

Содержимое архива debhello_0.0-1.debian.tar.xz

 $ tar -tzf debhello-0.0.tar.gz
debhello-0.0/
debhello-0.0/Makefile
debhello-0.0/src/
debhello-0.0/src/hello.c
debhello-0.0/LICENSE
 $ tar --xz -tf debhello_0.0-1.debian.tar.xz
debian/
debian/README.Debian
debian/changelog
debian/compat
debian/control
debian/copyright
debian/patches/
debian/patches/series
debian/rules
debian/source/
debian/source/format
debian/watch

The debhello_0.0-1_amd64.deb contains the binary files to be installed to the target system.

The debhello-debsym_0.0-1_amd64.deb contains the debug symbol files to be installed to the target system..

The binary package contents of all binary packages: 

 $ dpkg -c debhello-dbgsym_0.0-1_amd64.deb
drwxr-xr-x root/root ...  ./
drwxr-xr-x root/root ...  ./usr/
drwxr-xr-x root/root ...  ./usr/lib/
drwxr-xr-x root/root ...  ./usr/lib/debug/
drwxr-xr-x root/root ...  ./usr/lib/debug/.build-id/
drwxr-xr-x root/root ...  ./usr/lib/debug/.build-id/ce/
-rw-r--r-- root/root ...  ./usr/lib/debug/.build-id/ce/88708a35cc4e7d0f0b67bc...
drwxr-xr-x root/root ...  ./usr/share/
drwxr-xr-x root/root ...  ./usr/share/doc/
lrwxrwxrwx root/root ...  ./usr/share/doc/debhello-dbgsym -> debhello
 $ dpkg -c debhello_0.0-1_amd64.deb
drwxr-xr-x root/root ...  ./
drwxr-xr-x root/root ...  ./usr/
drwxr-xr-x root/root ...  ./usr/bin/
-rwxr-xr-x root/root ...  ./usr/bin/hello
drwxr-xr-x root/root ...  ./usr/share/
drwxr-xr-x root/root ...  ./usr/share/doc/
drwxr-xr-x root/root ...  ./usr/share/doc/debhello/
-rw-r--r-- root/root ...  ./usr/share/doc/debhello/README.Debian
-rw-r--r-- root/root ...  ./usr/share/doc/debhello/changelog.Debian.gz
-rw-r--r-- root/root ...  ./usr/share/doc/debhello/copyright

The generated dependency list of all binary packages.

The generated dependency list of all binary packages (v=0.0): 

 $ dpkg -f debhello-dbgsym_0.0-1_amd64.deb pre-depends depends recommends con...
Depends: debhello (= 0.0-1)
 $ dpkg -f debhello_0.0-1_amd64.deb pre-depends depends recommends conflicts ...
Depends: libc6 (>= 2.2.5)

[Внимание] Внимание

Many more details need to be addressed before uploading the package to the Debian archive.

[Примечание] Примечание

Если вы пропустили ручную настройку автоматически созданных командой debmake файлов настройки, то у созданного двоичного пакета может отсутствовать понятное другим описание пакета, а также пакет может несоответствовать некоторым требованиям политики. Такой сырой пакет вполне хорошо работает, если передать его команде dpkg, и может оказаться вполне достаточным для его локального развёртывания.

В примере выше при создании пакета Debian исходный код основной ветки разработки не был изменён.

Альтернативный подход состоит в том, что сопровождающий изменяет исходный код основной ветки, меняя файл Makefile так, чтобы значением $(prefix) было /usr.

Фактически процесс создания пакета в этом случае совпадает с тем, что описан выше в Раздел 4.6, «Шаг 3: изменение шаблонных файлов» за исключением двух моментов:

This alternative approach to Debian packaging using a series of patch files may be less robust for future upstream changes but more flexible coping with the difficult upstream source. (See Раздел 7.13, «Формат исходного кода 3.0».)

[Примечание] Примечание

Для этого конкретного случая приведённый выше Раздел 4.6, «Шаг 3: изменение шаблонных файлов», использующий файл debian/rules, является более подходящим. Тем не менее, продолжим работу с текущим подходом с целью обучения.

Ниже приводится пример создания 000-prefix-usr.patch с помощью команды diff.

 $ cp -a debhello-0.0 debhello-0.0.orig
 $ vim debhello-0.0/Makefile
 ... hack, hack, hack, ...
 $ diff -Nru debhello-0.0.orig debhello-0.0 >000-prefix-usr.patch
 $ cat 000-prefix-usr.patch
diff -Nru debhello-0.0.orig/Makefile debhello-0.0/Makefile
--- debhello-0.0.orig/Makefile  2018-08-09 13:57:15.925952917 +0000
+++ debhello-0.0/Makefile       2018-08-09 13:57:16.009952918 +0000
@@ -1,4 +1,4 @@
-prefix = /usr/local
+prefix = /usr

 all: src/hello

 $ rm -rf debhello-0.0
 $ mv -f debhello-0.0.orig debhello-0.0

Заметьте, что дерево исходного кода основной ветки разработки восстанавливается к изначальному состоянию, а файл заплаты доступен как 000-prefix-usr.patch.

Этот 000-prefix-usr.patch редактируется так, чтобы он соответствовал DEP-3, а также перемещается в соответствующий каталог, как это указано ниже.

 $ cd debhello-0.0
 $ echo '000-prefix-usr.patch' >debian/patches/series
 $ vim ../000-prefix-usr.patch
 ... hack, hack, hack, ...
 $ mv -f ../000-prefix-usr.patch debian/patches/000-prefix-usr.patch
 $ cat debian/patches/000-prefix-usr.patch
From: Osamu Aoki <osamu@debian.org>
Description: set prefix=/usr patch
diff -Nru debhello-0.0.orig/Makefile debhello-0.0/Makefile
--- debhello-0.0.orig/Makefile
+++ debhello-0.0/Makefile
@@ -1,4 +1,4 @@
-prefix = /usr/local
+prefix = /usr

 all: src/hello

Ниже приводится пример создания 000-prefix-usr.patch с помощью команды dquilt, которая является простой обёрткой для программы quilt. Синтаксис и функции команды dquilt совпадают с синтаксисом и функциями команды quilt(1) за тем лишь исключением, что заплата сохраняется в каталог debian/patches/.

 $ cd debhello-0.0
 $ dquilt new 000-prefix-usr.patch
Patch debian/patches/000-prefix-usr.patch is now on top
 $ dquilt add Makefile
File Makefile added to patch debian/patches/000-prefix-usr.patch
 ... hack, hack, hack, ...
 $ head -1 Makefile
prefix = /usr
 $ dquilt refresh
Refreshed patch debian/patches/000-prefix-usr.patch
 $ dquilt header -e --dep3
 ... edit the DEP-3 patch header with editor
 $ tree -a
.
├── .pc
│   ├── .quilt_patches
│   ├── .quilt_series
│   ├── .version
│   ├── 000-prefix-usr.patch
│   │   ├── .timestamp
│   │   └── Makefile
│   └── applied-patches
├── LICENSE
├── Makefile
├── debian
│   ├── README.Debian
│   ├── changelog
│   ├── compat
│   ├── control
│   ├── copyright
│   ├── patches
│   │   ├── 000-prefix-usr.patch
│   │   └── series
│   ├── rules
│   ├── source
│   │   ├── format
│   │   └── local-options
│   └── watch
└── src
    └── hello.c

6 directories, 20 files
 $ cat debian/patches/series
000-prefix-usr.patch
 $ cat debian/patches/000-prefix-usr.patch
Description: set prefix=/usr patch
Author: Osamu Aoki <osamu@debian.org>
Index: debhello-0.0/Makefile
===================================================================
--- debhello-0.0.orig/Makefile
+++ debhello-0.0/Makefile
@@ -1,4 +1,4 @@
-prefix = /usr/local
+prefix = /usr

 all: src/hello

Here, Makefile in the upstream source tree doesn’t need to be restored to the original state. The dpkg-source command invoked by the Debian packaging procedure in Раздел 4.7, «Шаг 4: сборка пакета с помощью debuild», understands the patch application state recorded by the dquilt program in the .pc/ directory. As long as all the changes are committed by the dquilt command, the Debian source package can be built from the modified source tree.

[Примечание] Примечание

If the .pc/ directory is missing, the dpkg-source command assumes that no patch was applied. That’s why the more primitive patch generation methods like in Раздел 4.8.1, «Создание заплаты с помощью diff -u» without generating the .pc/ directory require the upstream source tree to be restored.

Ниже приводится пример создания 000-prefix-usr.patch с помощью команды «dpkg-source --commit».

Отредактируем исходный код основной ветки разработки.

 $ cd debhello-0.0
 $ vim Makefile
 ... hack, hack, hack, ...
 $ head -n1 Makefile
prefix = /usr

Сохраним изменения в файл заплаты.

 $ dpkg-source --commit . 000-prefix-usr.patch
... editor to edit the DEP-3 patch header
...

Посмотрим результат.

 $ cat debian/patches/series
000-prefix-usr.patch
 $ cat debian/patches/000-prefix-usr.patch
Description: set prefix=/usr patch
Author: Osamu Aoki <osamu@debian.org>
Index: debhello-0.0/Makefile

--- debhello-0.0.orig/Makefile
+++ debhello-0.0/Makefile
@@ -1,4 +1,4 @@
-prefix = /usr/local
+prefix = /usr

 all: src/hello

 $ tree -a
.
├── .pc
│   ├── .quilt_patches
│   ├── .quilt_series
│   ├── .version
│   ├── 000-prefix-usr.patch
│   │   ├── .timestamp
│   │   └── Makefile
│   └── applied-patches
├── LICENSE
├── Makefile
├── debian
│   ├── README.Debian
│   ├── changelog
│   ├── compat
│   ├── control
│   ├── copyright
│   ├── patches
│   │   ├── 000-prefix-usr.patch
│   │   └── series
│   ├── rules
│   ├── source
│   │   ├── format
│   │   └── local-options
│   └── watch
└── src
    └── hello.c

6 directories, 20 files

Итак, команда dpkg-source выполняет в точности то же, что и было выполнено командой dquilt в Раздел 4.8.2, «Создание заплаты с помощью dquilt».



[8] This is a cliché to force a read-only relocation link for the hardening and to prevent the lintian warning “W: debhello: hardening-no-relro usr/bin/hello”. This is not really needed for this example but should be harmless. The lintian tool seems to produce a false positive warning for this case which has no linked library.

[9] This is a cliché to prevent overlinking for the complex library dependency case such as Gnome programs. This is not really needed for this simple example but should be harmless.