Difference between revisions of "Debian package structure/ru"

From Lazarus wiki
Jump to navigationJump to search
Line 81: Line 81:
 
       ├─ bin
 
       ├─ bin
 
       └─ share
 
       └─ share
           ├─ project1      #resources of your package
+
           ├─ project1      #ресурсы для Вашего пакета
           ├─ applications  #shortcut
+
           ├─ applications  #ярлыки
           ├─ pixmaps        #default icon
+
           ├─ pixmaps        #значок по умолчанию
 
           ├─ icons
 
           ├─ icons
           │  └─ hicolor    #icons of various sizes
+
           │  └─ hicolor    #значки различных размеров
 
           ├─ doc
 
           ├─ doc
           │  └─ project1  #information about your package
+
           │  └─ project1  #информация о Вашем пакете
           └─ man            #user manual
+
           └─ man            #руководство пользователя
               └─ man1      #index
+
               └─ man1      #оглавление
  
 
=== DEBIAN directory ===
 
=== DEBIAN directory ===

Revision as of 18:48, 3 September 2021

English (en) русский (ru)

Установки в Debian выполняются файлами с расширением .deb. В этой статье рассматривается, как создать их вручную.

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

Основной раздел

Два типа пакетов

Существует два типа пакетов: пакеты исходных кодов и бинарный пакет. В этой статье будет вестись речь о бинарных пакетах. Бинарные пакеты представляют удобный способ консолидации предварительно скомпилированных бинарных файлов, готовых для предоставлению непосредственно конечному пользователю. Однако дистрибутивы наподобии Debian или Ubuntu не смогут принять бинарные пакеты в свои репозитарии, они требуют Debian-пакеты исходных кодов (source package), которые могут использоваться для сборки бинарных версий в случае необходимости. Пакеты исходных кодов Debian (source package) несколько сложнее собрать и подчиняется ряду технических и юридических правил, прежде чем могут быть приняты в большинстве дистрибутивов Linux.

Подготовка пакетов

В бинарном пакете Debian файлы установки сжимаются с использованием команды dpkg-deb. Вы можете увидеть содержимое сформированных .deb файлов также как и любых других упакованных архивов, нажав правую кнопку мыши на них и открывая их в менеджере архивов (т.е. в обычном архиваторе).

Чтобы сделать .deb файл, Вам следует подготовить структуру папок с соответствующими файлами. Это будет называться промежуточной папкой и выражено в этой статье переменной ${STAGING_DIR}. Вы можете заменить его подходящей папкой или определить эту переменную в скрипте.

Вы можете для примера создать эту промежуточную папку как поддиректорию текущей папки. Простейший скрипт будет таким:

STAGING_DIR=./staging
mkdir ${STAGING_DIR}

Однако, если Вы напишите скрипт, то он может запускаться из другой папки. Поэтому вместо этого Вы можете убедиться в том, что эта переменная содержит подпапку относительно скрипта с помощью нижеследующим кодом:

cd `dirname $0`
STAGING_RELATIVEDIR="./staging"
STAGING_DIR=$(readlink --canonicalize "${STAGING_RELATIVEDIR}")

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

rm -rf "${STAGING_DIR}"
mkdir "${STAGING_DIR}"

Содержимое этой папки раскрывается далее в этой статье

Промежуточная папка. Завершение

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

Папки и файлы в этом архиве предполагаются только для чтения (ReadOnly). Чтобы убедиться в этом Вы можете перед вызовом dpkg-deb сделать нижеследующее:

find "${STAGING_DIR}" -type d -exec chmod 0755 {} \;  #установить атрибуты папок
find "${STAGING_DIR}" -type f -exec chmod 0644 {} \;  #установить атрибуты файлов
find "${STAGING_DIR}/usr/bin" -type f -exec chmod 0755 {} \;  #установить атрибуты для исполняемых файлов

Когда у Вас будут собраны все нужные файлы в промежуточной папке, Вы можете определить установочный размер и добавить его в файл control:

SIZE_IN_KB="$(du -s ${STAGING_DIR} | awk '{print $1;}')"
echo "Installed-Size: ${SIZE_IN_KB}" >> "${STAGING_DIR}/DEBIAN/control"

Создание Deb архива

Как только структура папок будет готова Вы можете создать архив с помощью:

dpkg-deb --root-owner-group --build "${STAGING_DIR}" "${PACKAGE_NAME}.deb"

Или для более старых версий dpkg-deb:

fakeroot dpkg-deb --build "${STAGING_DIR}" "${PACKAGE_NAME}.deb"

${STAGING_DIR} это путь к структуре папок для сжатия. ${PACKAGE_NAME} это имя файла, которое будет использоваться для архива.

Как правило Вы создаете архив под обычным пользователем, а не с root аккаунта. Но установочные файлы должны принадлежать определенному пользователю. Используя флаг --root-owner-group или префикс fakeroot Вы сохраните в архиве информацию о принадлежности файлов root пользователю.

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

rm -rf "${STAGING_DIR}"

Проверка архива

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

lintian "${PACKAGE_NAME}.deb" --info

Здесь приведен список возможных проблем: https://lintian.debian.org/tags.html

В Lazarus Вы по умолчанию получите предупреждения hardening-no-piehardening-no-windnow). Чтобы избежать такие предупреждений добавьте следующие параметры компилятора в параметры проекта:

-Cg
-k-pie
-k-znow

Структура папок

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

промежуточный
  ├─ DEBIAN
  └─ usr
      ├─ bin
      └─ share
          ├─ project1       #ресурсы для Вашего пакета
          ├─ applications   #ярлыки
          ├─ pixmaps        #значок по умолчанию
          ├─ icons
          │   └─ hicolor    #значки различных размеров
          ├─ doc
          │   └─ project1   #информация о Вашем пакете
          └─ man            #руководство пользователя
              └─ man1       #оглавление

DEBIAN directory

The name of this directory is uppercase. It needs to contain one file called control. Here is an example for a package called project1 at version 2.0.

Section: graphics
Priority: optional
Maintainer: myname <myname@webserver.com>
Homepage: https://www.project1.com
Package: project1
Architecture: amd64
Version: 2.0
Depends: libatk1.0-0 (>= 1.12.4), libc6 (>= 2.2.5), libcairo2 (>= 1.2.4), libgdk-pixbuf2.0-0 (>= 2.22.0), libglib2.0-0 (>= 2.12.0), libgtk2.0-0 (>= 2.24.0), libpango-1.0-0 (>= 1.18.0), libx11-6
Description: This is a test project.
 Long description blah blah blah.

Sample values for Section: comm, database, devel, editors, electronics, fonts, games, graphics, math, web, net, news, science, sound, utils, video.

The Architecture field is the one used to compile the program. To know the current architecture, use the following command:

dpkg --print-architecture

The Depends field contains the list of Linux libraries used. You can get this list with the following commands run in the directory of your binary file:

mkdir debian                 #need a debian directory
touch debian/control         #with one control file in it
dpkg-shlibdeps -O project1   #supposing your binary is called project1

You can then remove the almost empty debian folder if you don't use it.

This will output the dependencies (after the equal sign):

shlibs:Depends=libatk1.0-0 (>= 1.12.4), libc6 (>= 2.2.5), libcairo2 (>= 1.2.4), libgdk-pixbuf2.0-0 (>= 2.22.0), libglib2.0-0 (>= 2.12.0), libgtk2.0-0 (>= 2.24.0), libpango-1.0-0 (>= 1.18.0), libx11-6

To be complete, it should be noted that all these packages are not absolutely necessary, because several packages on this list may already be part of the dependencies - and therefore be part of the installation - of another package listed in this same list (see [1]to cross-check, and eliminate superfluous dependencies).

usr/bin directory

This directory contains the binary file and only this file (for information, avoid underscore in the name of your project - for example, dpkg-deb refuses it - because the package name should follow this regex: ${PackageName}_${Version}_${Arch}.deb, e.g. dpkg-dev_1.19.0.5ubuntu2_all.deb). All resources files need to go in usr/share/project1. To access resources, your program can use a relative path like ../share/project1.

The directory usr/local/bin is invalid in a package[2] because local is used for projects compiled locally and installed using their Makefile.

Resources directory

It will be called usr/share/project1 if the package name is "project1".
You can put here all the data files needed by your program. Note that they will be read-only.

Configuration directory

There are other places to store configuration files. Configuration files should be originally created by the application itself (with default values), if they do not exist when the application starts.

usr/share/applications directory

To add your application to the Linux menu, you need to add a file called project1.desktop containing:

[Desktop Entry]
Name=Project1
Comment=Cool project
Icon=project1
Exec=project1
Terminal=false
Type=Application
Categories=Graphics
GenericName=Project1
Keywords=feature1; feature2; feature3

This file is similar to a shortcut to your program.

The Categories field is similar to the one in the control file. It can be for example: Communication, Database, Development, Editors, Electronics, Fonts, Games, Graphics, Math, Internet, Networking, News, Science, Sound, Utility, Video.

The keywords help search through applications.

Note that you need to provide the icon as a PNG file, either in the directory usr/share/pixmaps or in usr/share/icons/hicolor.

usr/share/pixmaps directory

Will contain the single-size icon of your menu shortcut in PNG format called project1.png. A medium size like 48x48 will be fine.

usr/share/icons/hicolor directory

Will contain the multi-size icon. Here is the directory structure:

icons
 └─ hicolor
     ├─ 8x8
     │   └─ apps
     ├─ 16x16
     │   └─ apps
     ...

There is a subdirectory for each possible size. You can display all the sizes currently defined on your system by writing:

ls /usr/share/icons/hicolor

In each apps folder, put an image with always the same name. If you project is called project1 then it will be called project1.png for most folders. In the scalable and symbolic folders you can put an SVG file.

Documentation directory

It will be called usr/share/doc/project1 if your the package name is "project1".

The folder contains the changelog.gz and copyright files and optionally the README file.

changelog file

The minimum changelog would be:

project1 (1.0) unstable; urgency=low

  * Initial release

 -- myname <myname@webserver.com>  Tue, 19 May 2020 11:06:00 +0100

You can add many lines starting with * to indicate the list of changes in the version. The spaces at the beginning of the line are necessary. Only the line indicating the version starts directly at the beginning of the line.

The latest version must be at the top of the file.

The changelog must be compressed with maximum compression. To do that, supposing you already have the uncompressed changelog file, compress it with the following command:

gzip -9 -n usr/share/doc/project1/changelog

The -9 -n options are necessary for the package to follow the guidelines.

copyright file

If you provide the Deb package yourself, it is not mandatory to use the machine-readable format, however it will prepare you for publishing the package in Debian distributions. See: copyright in Debian package structure.

usr/share/man directory

Contains the user manual that you can view with the man command. It must contain at least project1.1.gz in the man1 subdirectory, which will be the index page of your manual.

The syntax is a bit peculiar. There are some tools to help but you still need to know the syntax.

Here is a sample file:

.TH Project1 1 "19 May 2020" "" Project1
.SH NAME
Project1 - My cool project
.SH SYNOPSIS
.B project1
[PARAMETER]
.SH DESCRIPTION
What my program does.
.PP
More description.

The manual, like the changelog, must be compressed using the following command:

gzip -9 -n usr/share/man/man1/project1.1

The -9 -n options are necessary for the package to follow the guidelines.