fppkg/ru

From Free Pascal wiki
Jump to navigationJump to search

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

Вступление

Fppkg - менеджер пакетов Free Pascal. С помощью этого инструмента вы можете создавать и устанавливать пакеты Free Pascal в своей системе. Вы можете устанавливать пакеты из локальных источников или загружать их из центрального хранилища. Пакеты должны быть сделаны с [помощью] FPMake.

Руководство по началу работы

Light bulb  Примечание: этот раздел действителен только для fppkg от fpc версии 2.5.1 или выше.

Настройка

Когда вы запускаете fppkg в первый раз, он создаст новые файлы конфигурации со значениями по умолчанию. Чтобы проверить, что эти значения в порядке, запустите 'fppkg list' в окне консоли. Вы должны увидеть что-то вроде этого:

 Name                 Installed    Available   
 a52                  2.5.1-1      -           
 aspell               2.5.1-1      -           
 bfd                  2.5.1-1      -           
 lnet                 -            0.6.3-0

Появится список всех установленных пакетов и пакетов, доступных для загрузки. Вы можете увидеть, какая версия каждого пакета доступна и/или установлена.

Если fppkg показывает только доступные пакеты, но не какие-либо установленные пакеты, вы должны адаптировать свою конфигурацию fppkg. Запустите 'fppkg listsettings', чтобы увидеть текущие настройки и расположение файлов конфигурации. Найдите файл конфигурации компилятора и откройте его в текстовом редакторе. Теперь измените настройку 'GlobalPrefix' на место, где установлен fpc. Например:'GlobalPrefix=/usr/lib/fpc' или 'c:\pp'. Сохраните файл и снова запустите 'fppkg list'.

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

Конфигурирование компилятора

Последний шаг - это настройка компилятора Free Pascal таким образом, чтобы он обнаруживал установленные пакеты. По умолчанию пакеты устанавливаются в определенном для пользователя месте, и это местоположение по умолчанию не ищется компилятором. Запустите 'fppkg listsettings', чтобы увидеть, где fppkg устанавливает пользовательские пакеты. Это местоположение указано как 'LocalInstallDir'.

Теперь добавьте эту строку в ваш файл конфигурации компилятора Free Pascal fpc.cfg:

 -Fu<LocalInstallDir>/units/$fpctarget/*

Замените <LocalInstallDir> значением параметра 'LocalInstallDir', как показано в 'fppkg list'. Например:

Linux: (/etc/fpc.cfg or ~/.fpc.cfg)

-Fu~/.fppkg/lib/fpc/$fpcversion/units/$fpctarget/*

Windows: (fpc.cfg)

-Fuc:\users\username\AppData\Local\FreePascal\fppkg\units\$fpctarget\*

Теперь вы можете использовать модули из установленных пакетов во всех ваших программах. Если вы разместите строку в нижней части fpc.cfg, вы уверены, что компилятор предпочтет (локально) установленные пакеты выше глобально установленных. Таким образом, вы можете устанавливать новые версии пакетов локально (специально для одного пользователя), не изменяя глобальные настройки.

Установка пакета

Установить пакет так же просто, как 'fppkg install [packagename]'. Это загрузит, скомпилирует и установит пакет. Если ошибки не появляются, используйте 'fppkg list', чтобы проверить, правильно ли установлен пакет. По умолчанию пакет устанавливается только для текущего пользователя. Если вы хотите принудительно сделать общесистемную установку, используйте параметр '-g'. Обратите внимание, что в этом случае вам необходимо иметь соответствующие права.

Аргументы командной строки

Вывод fppkg -h

использование: fppkg [опции] <действие> <пакет>
Опции:
  -c --config        Устанавливать конфигурацию компилятора для использования
  -h --help          Эта справка
  -v --verbose       Показывать больше информации 
  -d --debug         Показывать отладочную информацию
  -g --global        Принудительная установка в глобальный (общесистемный) каталог
  -f --force         Принудительная установка также, если пакет уже установлен
  -r --recovery      Режим восстановления, всегда использовать внутренний fpmkunit
  -b --broken        Не останавливаться на поврежденных пакетах
  -l --showlocation  Показывать, установлены ли пакеты глобально или локально
  -o --options=value Передать дополнительные параметры компилятору
  -n                 Не читать файлы конфигурации по умолчанию
  -p --prefix=value  Указать префикс
  -s --skipbroken    Пропустить пересборку зависимых пакетов после установки
  --compiler=value   Указать исполняемый компилятором
  --cpu=value        Указать целевой процессор для компиляции
  --os=value         Указать целевую операционную систему для компиляции

Действия:
  update            Обновить список пакетов
  list              Список доступных и установленных пакетов
  build             Сборка пакета
  compile           Скомпилировать пакет
  install           Установить пакет
  clean             Очистить пакет
  archive           Создать архив пакета
  download          Скачать пакет
  convertmk         Конвертировать Makefile.fpc в fpmake.pp
  fixbroken         Перекомпилировать все (поврежденные) пакеты с измененными зависимостями
  listsettings      Показать значения для всех настроек fppkg

Все действия описаны ниже.

Параметр пакета может означать следующее:

  • Packagename: Имя пакета в том виде, в котором оно указано в используемом хранилище. Все доступные имена пакетов перечислены в 'fppkg list'.
  • Zipfile: Полное имя zip-файла (включая расширение .zip), содержащего пакет.
  • Current directory: Когда нет параметра пакета, fppkg ищет файл с именем 'fpmake.pp' в текущем каталоге, и, если он найден, использует пакет, определенный этим файлом. В этом случае скомпилированные файлы не размещаются в другом месте (см. настройка 'BuildDir'), но находятся в каталоге 'units' в текущем каталоге.

Действия

Update

Обновляет список пакетов

List

[Выводит] список доступных и установленных пакетов

Build

Сборка пакетов

Install

Установка пакетов

Download

Загрузка пакетов

Convertmk

Конвертация Makefile.fpc в fpmake.pp

Конфигурация

Общая конфигурация

При запуске fppkg считывает свои настройки из fppkg.cfg. Если он не может найти его, он попытается создать его с некоторыми значениями по умолчанию. В этом файле конфигурации указывается местоположение локального репозитория. Обычно он [находится] в домашнем каталоге пользователя. Также возможно добавить пользовательские параметры, которые всегда передаются при вызове fpmake. Это может быть использовано [с помощью] fpmake-addins. Для всех других опций см. глобальный файл конфигурации.

Besides the global configuration file, there is also a file which is specific for a compiler version. You can add as much of these files as you want, using different compiler versions or compiler options. A common use is for cross-compiling. You can specify which configuration file to use on the fppkg command line with the '-c' option. The location of these configuration files is set in fppkg.cfg. when no configuration file is specified, the file called 'default' is used. (This can be set in fppkg.cfg)

Most important settings in these configuration files are the locations of where the packages have to be installed. Fppkg supports two different locations for installed packages. One 'global' location, which normally can be used by all users of the computer. And a 'local' location which in most cases is in a user's home-directory. These locations can be set with the 'localprefix' and 'globalprefix' settings. If you want that fppkg detects which packages are installed by fpc itself, the 'globalprefix' has to be set to match the prefix of your fpc-installation. It is common to use the location of the local repository (set in fppkg.cfg) as setting for the localprefix. For a better explanation of all options see the compiler configuration files.

The 'fppkg listsettings' command will show the values for all settings and the names of the used configuration files. From settings that allow macros the value as it is set by the user and the value when all macros are evaluated are both shown.

Глобальный файл конфигурации

The global configuration file contains general information for fppkg, like the repository to download from and where to place the temporary files. A typical global configuration file looks like this: (linux)

[Defaults]
ConfigVersion=4
LocalRepository={UserDir}.fppkg/
BuildDir={LocalRepository}build/
ArchivesDir={LocalRepository}archives/
CompilerConfigDir={LocalRepository}config/
RemoteMirrors=http://www.freepascal.org/repository/mirrors.xml
RemoteRepository=auto
CompilerConfig=default
FPMakeCompilerConfig=default
Downloader=lnet

When fppkg is started it first tries to load fppkg.cfg from a user-specific location. If a user-specific version can not be found fppkg searches for a system-wide fppkg.cfg. See the table for the exact location of these files. If both files do not exist a configuration file is created. When the current user is a superuser, a system-wide configuration file is made, else a user-specific one. When creating the configuration file fppkg tries some reasonable defaults for all settings. When you set the location of the fpc-installation in the enviroment-option FPCDIR, fppkg will use this location in the generated configuration files.

When you want to know for sure which configuration files fppkg uses, use the 'listsettings' action. It will list which configuration files are used plus the values for all settings.

Location of configuration files on different OS'es
OS User-specific configuration file System-wide configuration file
Unix/Linux ~/.config/fppkg.cfg /etc/fppkg.cfg
Windows %localsettings%\FreePascal\fppkg\fppkg.cfg

The following settings are available:

LocalRepository
The location where local repository information is stored. Supports macros.
BuildDir
The location where packages are build when a package is supplied. When the package in the current directory is used, this setting is ignored. Supports macros.
ArchivesDir
Place where packages downloaded from a remote repository are stored. Supports macros.
CompilerConfigDir
Place where the compiler-configuration files can be found. Supports macros.
RemoteMirrors
The URL to a file which contains all mirrors for a remote repository.
RemoteRepository
Contains the repository which has to be used. Selecting 'auto' will result in a random repository selected from the mirror list.
Compilerconfig
The filename of the compiler-configuration file which has to be used by default.
FPMakeCompilerconfig
The filename of the compiler-configuration file which has to be used by default for compiling the fpmake.pp files.
Downloader
Select the download-mechanism. lnet is the default.
FPMakeOptions
Specifies options which have to be added to each call to fpmake. Use this if you have fpmake-addons installed that need some specific settings. An example is the lazmkunit-addin, which needs the lazarusdir setting. (FPMakeOptions=--lazarusdir=/path/to/lazarus)
ConfigVersion
The version number of the used configuration-file format. Is used internally to check if the configuration file is in the format fppkg expects. Do not change.

Configuration for use with Lazarus

Some packages use the lazmkunit to integrate with Lazarus. When these packages are installed they need to know where Lazarus is installed. Add the following line with the path to your lazarus installation to fppkg.cfg:

FPMakeOptions=--lazarusdir=/path/to/lazarus

Compiler configuration files

A compiler configuration file contains all information necessary to select which fpc-compiler to use. A typical compiler-configuration file looks like this:

[Defaults]
ConfigVersion=4
GlobalPrefix=/usr/local/lib/fpc
LocalPrefix={LocalRepository}
Compiler=/usr/local/bin/fpc
OS=linux
CPU=i386
Version=2.5.1

The following settings are available:

GlobalPrefix
The prefix which has to be used when installing global packages. Normally this is the prefix of where fpc is installed, so that the packages which are installed by fpc are recognised. Supports macros.
LocalPrefix
Supports macros.
GlobalInstallDir
This is the location where the global packages are installed. The default value is {GlobalPrefix}lib/fpc/{compilerversion}/ on unices, and {globalprefix} on other operating systems. Supports macros.
LocalInstallDir
This is the location where the user-specifig (local) packages are installed. Add this path to the search path of the compiler if you want to use one of the packages installed into this location. The default value is {LocalPrefix}lib/fpc/{compilerversion}/ on unices, and {LocalPrefix} on other operating systems. Supports macros.
Compiler
The executable name of the compiler which has to be used.
OS
The target OS.
CPU
The target CPU-family.
Version
The version of the used compiler.
ConfigVersion
The version number of the used configuration-file format. Is used internally to check if the configuration file is in the format fppkg expects.

Using macros in the configuration files

To make life easier you can use macros within the configuration-files. Macro's are between accolades '{}' and they are substituted on by some dynamic values. The following macros are available:

AppConfigDir
Returns the location where fppkg stores it's user-specific configuration files. In fact it calls GetAppConfigDir with Global=false.
UserDir
Returns the location of the user's home-directory. (GetUserDir)
LocalRepository
The value of LocalRepository in the global configuration file
CompilerVersion
The version of the compiler as set in the compile configuration file, or the version detected from the compiler executable. This macro is not available in the global configuration file.

Upgrade

After upgrading the compiler your old fppkg directory is outdated.

  • If you use only one compiler version remove your ~/.fppkg/config/default directory and do fppkg update.
  • If you use multiple compiler versions copy the ~/.fppkg/config/default to ~/.fppkg/config/3.1.1 and then use fppkg -c 3.1.1.