Стандарты пакетов Manjaro

Revision as of 09:42, 10 February 2023 by FuzzyBot (talk | contribs) (Updating to match new version of source page)
Other languages:
English • ‎русский

Представленные PKGBUILD ни при каких обстоятельствах не должны собирать приложения, уже находящиеся в официальных бинарных репозиториях. Исключением из этого строгого правила могут быть только пакеты с включенными дополнительными функциями и/или патчами по сравнению с официальными. В этом случае массив pkgname должен быть другим.

При создании пакетов для Manjaro Linux, придерживайтесь руководства по созданию пакетов, приведенного ниже, особенно если вы собираетесь внести свой вклад в новый пакет для Manjaro Linux. Вам также следует ознакомиться с PKGBUILD и makepkg manpages.

Прототип PKGBUILD

# Maintainer: Иван Иванов <ваша_почта@домен.ru>
pkgname=NAME
pkgver=VERSION
pkgrel=1
pkgdesc=""
arch=()
url=""
license=('GPL')
groups=()
depends=()
makedepends=()
optdepends=()
provides=()
conflicts=()
replaces=()
backup=()
options=()
install=
changelog=
source=($pkgname-$pkgver.tar.gz)
noextract=()
md5sums=() #автозаполнение с помощью updpkgsums

build() {
  cd $pkgname-$pkgver

  ./configure --prefix=/usr
  make
}

package() {
  cd $pkgname-$pkgver

  make DESTDIR="$pkgdir/" install
}

Другие прототипы можно найти в /usr/share/pacman из пакетов pacman и abs.

Этикет упаковки

  • Пакеты никогда не должны устанавливаться в /usr/local
  • Не вводите новые переменные в PKGBUILD в скрипты сборки, если только пакет не может быть собран без этого, так как они могут конфликтовать с переменными, используемыми в самом makepkg. Если новая переменная в самом деле необходима, предварите её имя нижним подчеркиванием (_), напр.
    _customvariable=

    AUR не может определить использование пользовательских переменных и поэтому не может использовать их в подстановках. Чаще всего это можно увидеть в исходном массиве, например.

    http://downloads.sourceforge.net/directxwine/$patchname.$patchver.diff.bz2

    Такая ситуация противоречит эффективной функциональности AUR.

  • Избегайте использования /usr/libexec/ для для всего подряд. Вместо него используйте /usr/lib/${pkgname}/.
  • Поле packager из метафайла пакета может настраиваться создателем пакета путем изменения соответствующей опции в /etc/makepkg.conf файл, или альтернативно переопределить его, создав ~/.makepkg.conf
  • Все важные сообщения должны быть озвучены во время установки с помощью файла .install. Например, например, если пакет требует дополнительной настройки для работы, следует включить указания.
  • Любые необязательные зависимости, которые не нужны для запуска пакета или его общего функционирования, не должны быть включены; вместо этого информация должна быть добавлена в массив optdepends:
    optdepends=('cups: printing support'
                'sane: scanners support'
                'libgphoto2: digital cameras support'
                'alsa-lib: sound support'
                'giflib: GIF images support'
                'libjpeg: JPEG images support'
                'libpng: PNG images support')

    Приведенный выше пример взят для пакета wine в extra. Информация optdepends автоматически выводится при установке/обновлении, поэтому не следует хранить такую информацию в файлах .install.

  • При создании описания пакета для пакета не включайте имя пакета в виде самоссылки. Например, "Nedit is a text editor for X11" может быть упрощен до "A text editor for X11". Также старайтесь, чтобы описание не превышало ~80 символов.
  • Старайтесь, чтобы длина строки в PKGBUILD не превышала ~100 символов.
  • По возможности удаляйте пустые строки из PKGBUILD (provides, replaces и т.д.)
  • Общепринятой практикой является сохранение порядка полей PKGBUILD, как показано выше. Однако это необязательно, поскольку единственным требованием в данном контексте является правильный синтаксис bash.

Именование пакетов

  • Имена пакетов должны состоять только из буквенно-цифровых символов; все буквы должны быть строчными.
  • Имена пакетов НЕ должны иметь суффикс с номером версии основного выпуска upstream (например, нам не нужен libfoo2, если upstream называет его libfoo v2.3.4) в случае, если ожидается, что библиотека и ее зависимости будут использовать самую последнюю версию библиотеки с каждым соответствующим выпуском upstream. Однако не для всех программ или зависимостей можно ожидать подобное. В прошлом это было верно для наборов инструментов виджетов, таких как GTK и Qt. Программное обеспечение, зависящее от таких наборов инструментов, как правило не может быть тривиально перенесено на новую основную версию. Поэтому в случаях, когда программы не могут тривиально продолжать развиваться вместе со своими зависимостями, имена пакетов должны содержать суффикс основной версии (например, gtk2, gtk3, qt4, qt5). Для случаев, когда большинство зависимостей могут продолжать распространяться вместе с новейшим релизом, но некоторые не могут (например, закрытый исходный код, требующий libpng12 или аналогичный), устаревшая версия пакета может называться libfoo1, а текущая версия - просто libfoo.
  • Версии пакетов должны быть такими же, как версия, выпущенная автором. Версии могут включать буквы, если это необходимо (например, версия nmap - 2.54BETA32). Теги версий не должны включать дефисы!. Только буквы, цифры и точки.
  • Релизы пакетов - это специфические для Manjaro Linux пакеты. Они позволяют пользователям различать более новые и более старые сборки пакетов. Когда новая версия пакета выпускается впервые, счетчик релизов начинается с 1. Затем, по мере внесения исправлений и оптимизаций, пакет будет перевыпущен для публики Manjaro Linux и номер релиза будет увеличиваться. Когда выходит новая версия, счетчик релизов обнуляется до 1. Теги релизов пакетов следуют тем же ограничениям именования, что и теги версий.

Directories

  • Configuration files should be placed in the /etc directory. If there is more than one configuration file, it is customary to use a subdirectory in order to keep the /etc area as clean as possible. Use /etc/{pkgname}/ where {pkgname} is the name of the package (or a suitable alternative, eg, apache uses /etc/httpd/).
  • Файлы пакетов должны следовать этим общим рекомендациям по каталогам:
/etc System-essential configuration files
/usr/bin Binaries
/usr/lib Libraries
/usr/include Header files
/usr/lib/{pkg} Modules, plugins, etc.
/usr/share/doc/{pkg} Application documentation
/usr/share/info GNU Info system files
/usr/share/man Manpages
/usr/share/{pkg} Application data
/var/lib/{pkg} Persistent application storage
/etc/{pkg} Configuration files for {pkg}
/opt/{pkg} Large self-contained packages such as Java, etc.
  • Пакеты не должны содержать ни одного из следующих каталогов:
    • /dev
    • /home
    • /srv
    • /media
    • /mnt
    • /proc
    • /root
    • /selinux
    • /sys
    • /tmp
    • /var/tmp
    • /run

Makepkg duties

When makepkg is used to build a package, it does the following automatically:

  1. Checks if package dependencies and makedepends are installed
  2. Downloads source files from servers
  3. Checks the integrity of source files
  4. Unpacks source files
  5. Does any necessary patching

Builds the software and installs it in a fake root

  • Strips symbols from binaries
  • Strips debugging symbols from libraries
  • Compresses manual and, or info pages
  • Generates the package meta file which is included with each package
  • Compresses the fake root into the package file
  • Stores the package file in the configured destination directory (cwd by default)
  • Architectures

    The arch array should contain 'i686' and/or 'x86_64' depending on which architectures it can be built on. You can also use 'any' for architecture independent packages.

    Licenses

    The license array is being implemented in the official repos, and it should be used in your packages as well. Use it as follows:

    • A licenses package has been created in [core] that stores common licenses in /usr/share/licenses/common ie. /usr/share/licenses/common/GPL. If a package is licensed under one of these licenses, the licenses variable will be set to the directory name e.g. license=('GPL')
    • If the appropriate license is not included in the official licenses package, several things must be done:
      1. The license file(s) should be included in /usr/share/licenses/$pkgname/ e.g. /usr/share/licenses/dibfoo/LICENSE. One good way to do this is by using:
        install -D -m644 LICENSE "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
      2. If the source tarball does NOT contain the license details and the license is only displayed on a website for example, then copy the license to a file and include it. Remember to call it something appropriate too.
      3. Add 'custom' to the licenses array. Optionally, you can replace 'custom' with 'custom:"name of license"'.
    • Once a licenses is used in two or more packages in an official repo, including [community], it becomes common
    • The MIT, BSD, zlib/libpng and Python licenses are special cases and cannot be included in the 'common' licenses pkg. For the sake of the license variable, it is treated like a common license (license=('BSD'), license=('MIT'), license=('ZLIB') or license=('Python')) but for the sake of the filesystem, it is a custom license, because each one has its own copyright line. Each MIT, BSD, zlib/libpng or Python licensed package should have its unique license stored in /usr/share/licenses/$pkgname/.
    • Some packages may not be covered by a single license. In these cases multiple entries may be made in the license array e.g. license=("GPL" "custom:some commercial license"). For the majority of packages these licenses apply in different cases, as opposed to applying at the same time. When pacman gets the ability to filter on licenses (so you can say, "I only want GPL and BSD licensed software") dual (or more) licenses will be treated by pacman using OR, rather than AND logic, thus pacman will consider the above example as GPL licensed software, regardless of the other licenses listed.
    • The (L)GPL has many versions and permutations of those versions. For (L)GPL software, the convention is:
      • (L)GPL - (L)GPLv2 or any later version
      • (L)GPL2 - (L)GPL2 only
      • (L)GPL3 - (L)GPL3 or any later version

    Submitting packages to the AUR

    Note the following before submitting any packages to the AUR:

    1. The submitted PKGBUILDs MUST NOT build applications already in any of the official binary repositories under any circumstances. Exception to this strict rule may only be packages having extra features enabled and/or patches in compare to the official ones. In such an occasion the pkgname array should be different to express that difference. eg. A GNU screen PKGBUILD submitted containing the sidebar patch, could be named screen-sidebar etc. Additionally the provides=('screen') PKGBUILD array should be used in order to avoid conflicts with the official package.
    2. To ensure the security of pkgs submitted to the AUR please ensure that you have correctly filled the md5sum field. The md5sum's can be generated using the updpkgsums command.
    3. Please add a comment line to the top of the PKGBUILD file that follows this format. Remember to disguise your email to protect against spam:
    # Maintainer: Your Name <address at domain dot com>

    If you are assuming the role of maintainer for an existing PKGBUILD, add your name to the top as described above and change the title of the previous Maintainer(s) to Contributor:

    # Maintainer: Your Name <address at domain dot com>
    # Contributor: Previous Name <address at domain dot com>
  • Verify the package dependencies (eg, run ldd on dynamic executables, check tools required by scripts, etc).
  • The TU team strongly recommend the use of the namcap utility, written by Jason Chu (jason@archlinux.org), to analyze the sanity of packages. namcap will warn you about bad permissions, missing dependencies, un-needed dependencies, and other common mistakes. You can install the namcap package with pacman.

    Remember namcap can be used to check both pkg.tar.gz files and PKGBUILDs

  • Dependencies are the most common packaging error. Namcap can help detect them, but it is not always correct. Verify dependencies by looking at source documentation and the program website.
  • Do not use replaces in a PKGBUILD unless the package is to be renamed, for example when Ethereal became Wireshark. If the package is an alternate version of an already existing package, use conflicts (and provides if that package is required by others). The main difference is: after syncing (-Sy) pacman immediately wants to replace an installed, 'offending' package upon encountering a package with the matching replaces anywhere in its repositories; conflicts on the other hand is only evaluated when actually installing the package, which is usually the desired behavior because it is less invasive.
  • All files uploaded to the AUR should be contained in a compressed tar file containing a directory with the PKGBUILD and additional build files (patches, install, ...) in it.
    foo/PKGBUILD
    foo/foo.install
    foo/foo_bar.diff
    foo/foo.rc.conf

    The archive name should contain the name of the package e.g. foo.tar.gz.

  • One can easily build a tarball containing all the required files by using makepkg --source. This makes a tarball named $pkgname-$pkgver-$pkgrel.src.tar.gz, which can then be uploaded to the AUR.

    The tarball should not contain the binary tarball created by makepkg, nor should it contain the filelist