Handbook:Parts/Working/Portage/ru

Добро пожаловать в Portage
Система Portage — вероятно, самое известное нововведение Gentoo в управлении программным обеспечением. Благодаря высокой гибкости и чрезвычайно богатым возможностям, она зачастую считается лучшим средством управления программным обеспечением из существующих в Linux.

Portage полностью написан на Python и Bash и, следовательно, полностью прозрачен для пользователей, поскольку это скриптовые языки.

Большинство пользователей взаимодействует с Portage с помощью команды. Эта глава не будет дублировать информацию, доступную в emerge man. Для полного обзора опций emerge, пожалуйста, обратитесь к странице man:

Ebuilds
Когда в документации Gentoo говорится о пакетах имеется ввиду программы, которые доступны Gentoo пользователям в дереве Portage. Дерево Portage это коллекция ebuild (сборочных файлов) - файлы содержащие всю информацию, которая нужна Portage для управления программным обеспечением (установка, поиск, запросы, ...). По умолчанию файлы ebuild находятся в.

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

Обновление дерева Portage
Дерево Portage обычно обновляется с помощью, средства быстрой разностной передачи файлов. Обновление выполняется довольно просто, так как в имеется интерфейс для :

Иногда ограничения файрвола ограничивают в доступе к зеркалу. В этом случае обновить дерево Portage с помощью ежедневно генерируемых Gentoo снимков дерева Portage. Утилита автоматически загрузит и установит последний снимок в систему:

An additional advantage of using is that it allows the administrator to only pull in Portage tree snapshots that are signed by the Gentoo release engineering GPG key. More information on this can be found in the Portage features section on Fetching validated Portage tree snapshots.

Поиск программного обеспечения
Есть несколько способов поиска программ в дереве Portage. Один из способов использовать. По умолчанию находит имена пакетов, которые совпадают (полностью или частично) с заданным условием поиска.

Например, чтобы найти все пакеты, содержащие «pdf» в названии:

Для поиска пакетов еще и по тексту описания используйте опцию  (или  ):

Обратите внимание, что вывод команды возвращает много информации. Поля четко обозначены, поэтому мы не будем вдаваться в подробности их значения:

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

Поскольку многие приложения зависят друг от друга, любая попытка установить какой-либо пакет может привести к установке нескольких зависимостей. Не беспокойтесь об этом, Portage учтет и эти зависимости. Чтобы увидеть что Portage будет устанавливать, добавьте опцию. Например:

Во время установки пакета, Portage скачает необходимый исходный код из интернета (если необходимо) и по умолчанию сохранит его в. После этого он распакует, скомпилирует и установить пакет. Для того чтобы Portage только загрузил исходный код без его установки, добавьте опцию  к команде emerge:

Поиск документации для установленных пакетов
Многие пакеты поставляются с собственной документацией. Иногда, USE флаг  определяет будет ли установлена документация из пакета или нет. Чтобы увидеть есть ли USE флаг doc в пакете используйте.

Лучший способ настроить doc USE флаг это настроить его для каждого пакета с помощью, так документация устанавливается только для требуемых пакетов. Для большего количества информации, пожалуйста, прочитайте USE флаги главу.

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

Удаление программы
Для удаления пакета из системы используйте. Это попросит Portage удалить все файлы установленные пакетом из системы. Одним исключением из этого являются файлы конфигурации этого приложения, если они были изменены пользователем. Сохранение конфигурационных файлов позволяет пользователям продолжать работать с пакетом, без необходимости настраивать снова пакет, если он будет установлен снова позже.

Когда удаляется пакет из системы, зависимости от этого пакета, которые установились при установки пакета, все еще остаются в системе. Для того чтобы Portage нашел все зависимости, которые теперь можно удалить, используйте опцию emerge  о которой мы расскажем позже.

Обновление системы
To keep the system in perfect shape (and not to mention install the latest security updates) it is necessary to update the system regularly. Since Portage only checks the ebuilds in the Portage tree, the first thing to do is to update the Portage tree. When the Portage tree is updated, the system can be updated using. In the next example, the  option is also used which will tell Portage to display the list of packages it wants to upgrade and ask for confirmation:

Portage will then search for newer version of the applications that are installed. However, it will only verify the versions for the applications that are explicitly installed (the applications listed in ) - it does not thoroughly check their dependencies. To update the dependencies of those packages as well, add the  option:

Still, this does not mean all packages: some packages on the system are needed during the compile and build process of packages, but once that package is installed, these dependencies are no longer required. Portage calls those build dependencies. To include those in an update cycle, add :

Since security updates also happen in packages that are not explicitly installed on the system (but that are pulled in as dependencies of other programs), it is recommended to run this command once in a while.

If the USE settings of the system have been altered, it is recommended to add  as well. Portage will then verify if the change requires the installation of new packages or recompilation of existing ones:

Метапакеты
Some packages in the Portage tree don't have any real content but are used to install a collection of packages. For instance, the package will install a complete KDE environment on the system by pulling in various KDE-related packages as dependencies.

To remove such a package from your system, running on the package won't have much effect as the dependencies remain on the system.

Portage has the functionality to remove orphaned dependencies as well, but since the availability of software is dynamically dependent it is important to first update the entire system fully, including the new changes applied when changing USE flags. After this one can run to remove the orphaned dependencies. When this is done, it might be necessary to rebuild the applications that were dynamically linked to the now-removed software titles but don't require them anymore, although recently support for this has been added to Portage.

All this is handled with the following three commands:

входит в пакет ; не забудьте установить его:

Лицензии
Beginning with Portage version 2.1.7, it is possible to accept or reject software installation based on its license. All packages in the tree contain a LICENSE entry in their ebuilds. Running will show the package's license.

By default, Portage permits all licenses, except End User License Agreements (EULAs) that require reading and signing an acceptance agreement.

The variable that controls permitted licenses is called ACCEPT_LICENSE, which can be set in. In the next example, this default value is shown:

With this configuration, packages that require interaction during installation to approve their EULA will not be installable. Packages without an EULA will be installable.

It is possible to set ACCEPT_LICENSE globally in, or to specify it on a per-package basis in.

For example, to allow the license for, add the following to :

This permits installation of truecrypt versions that have the license, but not versions with the  license.

License groups defined in ACCEPT_LICENSE are prefixed with an sign. A commonly requested setting is to only allow the installation of free software and documentation. To accomplish this, remove all currently accepted licenses (using ) and then only allow the licenses in the FREE group as follows:

In this case, "free" is mostly defined by the FSF and OSI. Any package whose license does not meet these requirements will not be installable on the system.

Терминология
As stated before, Portage is extremely powerful and supports many features that other software management tools lack. To understand this, we explain a few aspects of Portage without going into too much detail.

With Portage different versions of a single package can coexist on a system. While other distributions tend to name their package to those versions (like freetype and freetype2) Portage uses a technology called SLOTs. An ebuild declares a certain SLOT for its version. Ebuilds with different SLOTs can coexist on the same system. For instance, the freetype package has ebuilds with SLOT="1" and SLOT="2".

There are also packages that provide the same functionality but are implemented differently. For instance, metalogd, sysklogd and syslog-ng are all system loggers. Applications that rely on the availability of "a system logger" cannot depend on, for instance, metalogd, as the other system loggers are as good a choice as any. Portage allows for virtuals: each system logger is listed as an "exclusive" dependency of the logging service in the logger virtual package of the virtual category, so that applications can depend on the package. When installed, the package will pull in the first logging package mentioned in the package, unless a logging package was already installed (in which case the virtual is satisfied).

Software in the Portage tree can reside in different branches. By default the system only accepts packages that Gentoo deems stable. Most new software titles, when committed, are added to the testing branch, meaning more testing needs to be done before it is marked as stable. Although the ebuilds for those software are in the Portage tree, Portage will not update them before they are placed in the stable branch.

Some softwares are only available for a few architectures. Or the software doesn't work on the other architectures, or it needs more testing, or the developer that committed the software to the Portage tree is unable to verify if the package works on different architectures.

Each Gentoo installation also adheres to a certain profile which contains, amongst other information, the list of packages that are required for a system to function normally.

Заблокированные пакеты
Ebuilds contain specific fields that inform Portage about its dependencies. There are two possible dependencies: build dependencies, declared in the DEPEND variable and run-time dependencies, likewise declared in RDEPEND. When one of these dependencies explicitly marks a package or virtual as being not compatible, it triggers a blockage.

While recent versions of Portage are smart enough to work around minor blockages without user intervention, occasionally such blockages need to be resolved manually.

To fix a blockage, users can choose to not install the package or unmerge the conflicting package first. In the given example, one can opt not to install postfix or to remove ssmtp first.

Sometimes there are also blocking packages with specific atoms, such as. In this case, updating to a more recent version of the blocking package could remove the block.

It is also possible that two packages that are yet to be installed are blocking each other. In this rare case, try to find out why both would need to be installed. In most cases it is sufficient to do with one of the packages alone. If not, please file a bug on Gentoo's bugtracking system.

Замаскированные пакеты
When trying to install a package that isn't available for the system, this masking error occurs. Users should try installing a different application that is available for the system or wait until the package is marked as available. There is always a reason why a package is masked:

Необходимо изменить USE флаг
The error message might also be displayed as follows, if  isn't set:

Such warning or error occurs when a package is requested for installation which not only depends on another package, but also requires that that package is built with a particular USE flag (or set of USE flags). In the given example, the package app-text/feelings needs to be built with USE="test", but this USE flag is not set on the system.

To resolve this, either add the requested USE flag to the global USE flags in, or set it for the specific package in.

Отсутствующие зависимости
The application to install depends on another package that is not available for the system. Please check Bugzilla if the issue is known and if not, please report it. Unless the system is configured to mix branches, this should not occur and is therefore a bug.

Неоднозначное имя ebuild
The application that is selected for installation has a name that corresponds with more than one package. Supply the category name as well to resolve this. Portage will inform the user about possible matches to choose from.

Циклические зависимости
Two (or more) packages to install depend on each other and can therefore not be installed. This is most likely a bug in one of the packages in the Portage tree. Please re-sync after a while and try again. It might also be beneficial to check Bugzilla to see if the issue is known and if not, report it.

Ошибка загрузки
Portage was unable to download the sources for the given application and will try to continue installing the other applications (if applicable). This failure can be due to a mirror that has not synchronized correctly or because the ebuild points to an incorrect location. The server where the sources reside can also be down for some reason.

Retry after one hour to see if the issue still persists.

Защита системного профиля
The user has asked to remove a package that is part of the system's core packages. It is listed in the profile as required and should therefore not be removed from the system.

Ошибка проверки подписи
This is a sign that something is wrong with the Portage tree - often, it is because a developer may have made a mistake when committing a package to the tree.

When the digest verification fails, do not try to re-digest the package personally. Running will not fix the problem; it will almost certainly make it worse!

Instead, wait an hour or two for the tree to settle down. It's likely that the error was noticed right away, but it can take a little time for the fix to trickle down the Portage tree. Check Bugzilla and see if anyone has reported the problem yet or ask around on (IRC). If not, go ahead and file a bug for the broken package.

Once the bug has been fixed, re-sync the Portage tree to pick up the fixed digest.