Сборка пакетов/Соглашение по стилю RPM-пакетов/Макросы RPM
| Эта статья содержит фрагменты на иностранном языке. Вы можете помочь переведя её до конца. (cм. руководство по переводу) |
| 3. Макросы RPM | ||
|---|---|---|
Содержание
- 1 Макросы RPM
- 1.1 %_docdir
- 1.2 %_infodir
- 1.3 %_lib
- 1.4 %_libdir
- 1.5 %_libexecdir
- 1.6 %_mandir
- 1.7 %fillup_and_insserv
- 1.8 %fillup_only
- 1.9 %find_lang
- 1.10 %insserv_cleanup
- 1.11 %insserv_force_if_yast
- 1.12 %install_info
- 1.13 %install_info_delete
- 1.14 %perl_archlib
- 1.15 %perl_make_install
- 1.16 %perl_process_packlist
- 1.17 %perl_sitearch
- 1.18 %perl_sitelib
- 1.19 %perl_vendorarch
- 1.20 %perl_vendorlib
- 1.21 %perl_version
- 1.22 %py_incdir
- 1.23 %py_libdir
- 1.24 %py_requires
- 1.25 %py_sitedir
- 1.26 %py_ver
- 1.27 %remove_and_set
- 1.28 %restart_on_update
- 1.29 %run_ldconfig (deprecated)
- 1.30 %run_permissions
- 1.31 %sles_version
- 1.32 %stop_on_removal
- 1.33 %suse_update_config
- 1.34 %suse_update_desktop_file
- 1.35 %suse_version
- 1.36 %tcl_version
- 1.37 %ul_version
- 1.38 %verify_permissions
- 1.39 %suse_version
- 1.40 %fdupes
Макросы RPM
Эта секция описывает предопределенные RPM макросы, которые используются в SUSE пакетах. Некоторые из них являются универсальными, другие же подходят только для SUSE. Информацию о других универсальных макросах можно найти в: Maximum RPM
. Некоторую информацию о RPM на русском можно найти здесь: RPM-HOWTO
и Red Hat RPM Guide
. Специфичные для Java макросы описаны на странице Java/Packaging/RPM_Macros.
Все предопределенные макросы с соответсвующими пояснениями вы можете найти в файле: /usr/lib/rpm/macros.
Одно из важнейших отличий между RPM макросами и обычнми командами Linux, это способ записи опций и параметров. RPM предоставляет только простейшую поддержку для обработки опций. Другое ограничение: все опции должны быть определены до параметров, и это делает непростым использование пар: опций и параметров(значений). К примеру, команда Linux top используется со следующим синтаксисом:
top [-bcisS] [-d delay] [-n iterations] [-p pid] [, pid ...]
Использованные пары -d delay, -n iterations, -p pid как и прочие - необязательны. Пары могут быть пропущены или идти в другой последовательности, но порядок при котором значение следует сразу за опцией - обязателен, он позволяет сразу понять какой параметр соответствует данной опции.
Примеры Linux команд:
top -n 20 -p 10345 top -d 1 -p 10345
В приведенном выше примере команда знает, что 20 это число повторов, 1 задержка, а 10345 это pid(номер процесса).
Но чтобы соответствовать ограничениям RPM, синтаксис вызова команды должен выглядить следующим образом:
%top [-bcisSdnp] [delay] [iterations] [pid] [,pid ...]
Все используемые опции должны быть перечислены отдельно и до перечисления значений(параметров). Это означает, что вызов RPM макросов, аналогичных приведенным выше командам, мог бы выглядеть следующим образом:
Примеры использования возможного RPM макроса:
%top -n -p 5 10345 %top -d -p 1 460
%_docdir
Этот макрос по умолчанию указывает на каталог для документации, /usr/share/doc/packages. Он может быть изменен с помощью тега Docdir. Обычно он используется в секции %install, если этого недостаточно используйте тег %doc в секции %files. Тег %doc не нужно использовать вместе с %_docdir в секции %files. Это делается автоматически для этого каталога.
Этот пример взят из пакета aeolus:
%install
[...]
mkdir -p $RPM_BUILD_ROOT%{_docdir}/%{name}
cp .aeolusrc $RPM_BUILD_ROOT%{_docdir}/%{name}/aeolusrc
cp -R stops-* $RPM_BUILD_ROOT%{_docdir}/%{name}
[...]
%files
[...]
%{_docdir}/%{name}
%_infodir
Этот макрос по умолчанию указывает на каталог для info документации, /usr/share/info. Он часто используется c ./configure --infodir=%_infodir, в макросе %install_info, а также в списке файлов(%files). Как и тег %_docdir, тег %_infodir не нужно успользовать вместе с %doc в секции %files. Это делается автоматически для этого каталога.
%_lib
Этот макрос по умолчанию имеет значение lib, либо lib64. Второй вариант используется в ОС с 64-битной архитектурой, которые позволяют выпольнять приложения обоих типов(32- и 64-битные приложения) одновременно, т.е. в биархитектурной системе. На таких системах некоторые библиотеки должны существовать в двух вариантах. Поэтому 64-битные библиотеки устанавливаются в директорию lib64, а 32-битные в lib директорию.
Он используется когда макроса %_libdir недостаточно, к примеру, когда библиотеки устанавливаются в директорию /usr/X11R6/lib. Его часто используют в выражения вроде ./configure –libdir=/usr/X11R6/%_lib, или в секции %files.
%_libdir
Этот макрос по умолчанию имеет значение /usr/lib64 в биархитектурных системах, и /usr/lib во всех остальных случаях. Его назначение похоже на %_lib, но используется он гораздо чаще, потому что обычно библиотеки устанавливаются в /usr/lib. Опять-таки, его часто используют в выражениях вроде ./configure –libdir=%_libdir, или в секции %files.
%_libexecdir
В отличие от %_libdir, этот макрос всегда разворачивается в пусть /usr/lib.
%_mandir
Этот макрос по умолчанию указывает на директорию с руководствами(man): /usr/share/man. Он часто используется в выражениях вроде ./configure --mandir=%_mandir, а так же в секции %files (пример: %_mandir/man5/*).
Как и в случае с %_docdir и %_infodir, тег %doc не должен использоваться вместе с %_mandir в разделе %files. Это делается автоматически для этого каталога.
%fillup_and_insserv
Этот макрос можно использовать для установки(заполнения) файлов системной конфигурации(/etc/sysconfig/*) и скриптов инициализации системы.
Синтаксис:
%fillup_and_insserv [-finyY] [sysconfig_filename] [init_script_name] ...
Макрос %fillup_and_insserv сочетает в себе две функции. Во-первых, создает(заполняет) файлы конфигурации в директории /etc/sysconfig, во-вторых, добавляет/активирует(insserv) сервисы инициализации системы(runlevels). Утилита fillup предполагает, что шаблон конфигурационного файла находится в /var/adm/fillup-templates/[sysconfig_filename][.][%name].
Этот макрос используется в %post секции пакета, который устанавливает скрипты инициализации системы, и хочет активировать их по умолчанию. Подробности в SUSE_Package_Conventions/Init_Scripts#spc_is_installation Section 7.8, “Installation”. Незабудьте обьявить используемые утилиты в теге PreReq, для этого есть макросы %insserv_prereq и %fillup_prereq.
Опции:
-
-fпропустить обработку файлов конфигурации(fillup). -
-iпропустить обработку сервисов инициализации системы(insserv). -
-nиспользовать параметрsysconfig_filename(см. ниже). -
-yпо умолчанию сервис активирован(если пакет устанавливается впервые, а не обновляется). Опция игнорируется если в скрипте инициализации определено значение опцииX-UnitedLinux-Default-Enabled. -
-Yпринудительная активация сервиса. Это означает что после обновления/установки сервис будет активирован, не обращает внимание на свое состояние перед обновлением.
Параметры:
-
sysconfig_filenameиспользуется с опцией-nи определяет куда будет сохранен конфигурационный файл, его имя(и соответственно имя шаблона) т.е.:/etc/sysconfig/sysconfig_filename.
Макрос ищет шаблон конфигурационного файла либо в /var/adm/fillup-templates/sysconfig.sysconfig_filename.%name, либо в /var/adm/fillup-templates/sysconfig.sysconfig_filename. Если несколько пакетов используют один конфигурационный файл, то нужно использовать более длинный(первый) вариант имени шаблона. По умолчанию (если не используется опция -n), шаблон конфигурационного файла должен находится в /var/adm/fillup-templates/sysconfig.%name, а сам файл в /etc/sysconfig/%name.
-
init_script_nameопределяет имя скрипта инициализации, который будет обработан утилитой insserv. Параметр должен быть определен, если не используется опция-i.
Примеры:
- Пример взят из пакета
mailman, также показана соответствующая частьPreReq:
PreReq: ... %insserv_prereq %fillup_prereq ...
%post
%{fillup_and_insserv mailman}
В данном случае конфигурационный файл /etc/sysconfig/mailman заполняется из шаблона /var/adm/fillup-templates/sysconfig.mailman.
- Пример взят из пакета
hwinfo, также показана соответствующая частьPreReq:
PreReq: ... %insserv_prereq ...
%post
[...]
%{fillup_and_insserv -f -y hwscan}
Здесь запускается утилита insserv для файла /etc/init.d/hwscan и активирует этот сервис по умолчанию. В теге PreReq содержатся определения необходимые для insserv, но не для fillup, т.к. это часть макроса пропущенна опцией -f.
- Пример взят из пакета
openssh:
%{fillup_and_insserv -n -y ssh sshd}
Здесь конфигурационный файл вставляется в /etc/sysconfig/ssh. Шаблон берется из /var/adm/fillup-templates/sysconfig.ssh.openssh, либо из /var/adm/fillup-templates/sysconfig.ssh(рекомендуется первый вариант). Утилита insserv вставляет сервис в /etc/init.d/sshd, и активирует его если пакет устанавливается впервые.
- Пример взят из пакета
openldap2:
%{fillup_and_insserv -n openldap ldap slurpd}
Здесь конфигурационный файл вставляется в /etc/sysconfig/openldap. Шаблон берется либо из /var/adm/fillup-templates/sysconfig.openldap.openldap2(рекомендуется), либо из /var/adm/fillup-templates/sysconfig.openldap.
%fillup_only
Этот макрос можно использовать для установки файлов системной конфигурации.
Синтаксис:
%fillup_only [-adns] [sysconfig_filename] [suffix] [sysconfig_subdir]
Макрос %fillup_only вставляет(заполняет) значения переменных из шаблона /var/adm/fillup-templates/sysconfig.sysconfig_filename[-suffix] в конфигурационный файл /etc/sysconfig/sysconfig_filename. Основная функциональность этого макроса похожа на функциональность %fillup_and_insserv -i, но помимо этого, он также модифицирует конфигурационные файлы в поддиректориях /etc/sysconfig.
Обычно этот макрос используется в секции %post.
Незабудьте обьявить в теге PreReq, что вы используете данную утилиту, для этого есть макрос %fillup_prereq.
Опции:
-
-aиспользовать имя пакета как суффикс имени конфигурационного шаблона. -
-dиспользовать параметрsysconf_subdir(см. ниже). -
-nиспользовать параметрsysconfig_filename(см. ниже). -
-sиспользовать параметрsuffix(см. ниже).
Параметры:
-
sysconfig_subdirиспользуется с опцией-d, определяет имя поддиректории в/etc/sysconfig, куда будут сохранятся конфигурационные файлы. -
sysconfig_filenameиспользуется с опцией-nи определяет куда будет сохранен конфигурационный файл, его имя(и соответственно имя шаблона).
Опция -n - необязательная, по умолчанию вместо нее используется имя пакета, т.е. шаблон /var/adm/fillup-templates/sysconfig.%name используется для заполнения конфигурационного файла /etc/sysconfig/%name.
-
sysconfig_template_filename_suffixиспользуется с опцией-s, добавляет суффикс к имени шаблона.
Примеры:'
- Пример взят из пакета
tetex, также показана соответствующая частьPreReq:
PreReq: %fillup_prereq ...
%post
%{fillup_only}
Здесь конфигурационный файл /etc/sysconfig/tetex заполняется из шаблона /var/adm/fillup-templates/sysconfig.tetex.
- Пример взят из пакета
man:
%{fillup_only -an cron}
Здесь конфигурационный файл /etc/sysconfig/cron заполняется из шаблона /var/adm/fillup-templates/sysconfig.cron-man.
- Пример взят из пакета
dhcp:
%{fillup_only -ans syslog dhcpd}
Здесь конфигурационный файл /etc/sysconfig/syslog заполняется из шаблона /var/adm/fillup-templates/sysconfig.syslog-dhcpd.
- Пример взят из пакета
samba:
%fillup_only -nsd dhcp samba-client network
Здесь конфигурационный файл /etc/sysconfig/network/dhcp заполняется из шаблона /var/adm/fillup-templates/sysconfig.dhcp-samba-client.
%find_lang
Этот макрос помогает отметить файлы зависящие от локали(locale), используется вместе с соответствующим тегом %lang в секции %files
Синтаксис
%find_langname[имя_списка_файлов]
Макрос %find_lang ищет файлы name.mo в директориях /usr/share/locale и locale/*/LC_MESSAGES. Он также просматривает директории gnome/help/name и kde*/share/doc/HTML/*/name в поисках локализованной(переведенной) документации. Затем он создает список файлов (имя_списка_файлов), в котором файлы(пути к файлам) отмечены соответствующими тегами %lang(locale) и %doc. Такие списки могут быть переданы макросу %files(с помощью опции -f). Примеры см. ниже.
Используйте этот макрос только в том случае, если определен тег BuildRoot, иначе поиск будет осуществлен по всей системе(/).
Пример использования
%install
# installation
%find_lang %{name}
%files -f %{name}.lang
Настройки
- --without-gnome
- не искать файлы справки GNOME.
- --without-kde
- не искать файлы справки KDE.
- --with-qt
- найти файлы переводов Qt.
- --with-man
- найти локализованные man-страниц.
- --all-name
- найти все файлы совпадающие с именем пакета/домена.
- --without-mo
- не искать файлы локали.
Параметры
-
name - определяет имя
.moфайлов и имена поддиреткторий, где хранится локализованная документация GNOME и KDE. Он также используется для задания имени файла в котором будет сохранен список файлов, если параметрfilelistне указан.
-
имя_списка_файлов - определяет имя файла содержащего сгенерированный список файлов. Если не определено, используется
name.lang.
Этот пример взят из пакета pan:
%install
make -i DESTDIR=$RPM_BUILD_ROOT install
%find_lang %{name} # создать специальный файл со списком файлов для обработки
%files -f %{name}.lang # использовать созданный выше файл
%defattr(-,root,root) # перечисление остальных файлов пакета
%doc README ChangeLog AUTHORS TODO COPYING CREDITS
%attr(755,root,root) %{prefix}/bin/pan
[...]
%insserv_cleanup
Этот макрос используется для удаления скриптов инициализации системы(insserv) после удалении соответствующих пакетов. Каждый пакет, который устанавливает сервисы инициализации системы, должен использовать данный макрос в секции %postun.
Данный пример взят из пакета openldap2:
%postun %restart_on_update ldap slurpd %insserv_cleanup
%insserv_force_if_yast
Этот макрос просто вызывает утилиту insserv, если пакет устанавливается не с помощью YaST. Если же используется YaST, то вызвается insserv -f. Это помогает избежать ошибок типа "out-of-sequence" при установке пакетов.
Макрос используется в секции %post пакета, который устанавливает скрипт инициализации системы, и хочет активировать его по умолчанию.
It is also used if the init script existed prior to SL 8.0 when the START variables were used. See SUSE_Package_Conventions/Init_Scripts#spc_is_installation Section�7.8, “Installation” for more details. Do not forget to mention the used utilities in the PreReq tag. There are the macros %insserv_prereq and %fillup_prereq for this purpose.
Данный пример взят из подпакета nscd пакета glibc (также показана соответствующая часть тега PreReq):
%package -n nscd
[...]
PreReq: %insserv_prereq
%post -n nscd
%{insserv_force_if_yast nscd}
%install_info
Этот макрос добавляет файлы документации(info) в каталог документации(обновляет его).
Синтаксис:
%install_info install_info_options
Макрос %install_info запускает программу install-info с некоторыми дополнительными проверками. Допустимы любые опции утилиты install-info. Дополнительная информация - man install-info.
Каждый пакет предоставляющий страницы документации(info) должен вызывать этот макрос в секции %post. Также не забудьте указать в теге PreReq все используемые в пакете утилиты, в частности, для данного макроса используйте специальный макрос %install_info_prereq
Примеры:'
- Пример взят из пакета
zsh, также показана соответствующая часть тегаPreReq:
PreReq: %install_info_prereq [...] %post %install_info --info-dir=%_infodir %_infodir/%name.info.gz
- Пример взят из пакета
rplay, содержащего несколько страниц документации. Также показана соответствующая часть тегаPreReq:
PreReq: %install_info_prereq
[...]
%post
%install_info --info-dir=%{_infodir} %{_infodir}/%{name}.info.gz
%install_info --info-dir=%{_infodir} %{_infodir}/RPLAY.info.gz
%install_info --info-dir=%{_infodir} %{_infodir}/RPTP.info.gz
%install_info --info-dir=%{_infodir} %{_infodir}/librplay.info.gz
%install_info_delete
This macro removes dir entries for info files.
Synopsis:
%install_info_delete install_info_options
The macro %install_info_delete is a complement to the macro %install_info. It runs sbin/install-info --quiet –delete with some additional tests. It accepts any option from the install-info utility. See man install-info for more details.
Each package providing info pages should call this macro in %postun script. Do not forget to mention all the utilities used in the PreReq tag. The macro %install_info_prereq is intended for this purpose.
Examples:
- This example is taken from the package
zsh(also shows the relatedPreReqtag):
PreReq: %install_info_prereq
[...]
%post
%install_info_delete --info-dir=%{_infodir} %{_infodir}/%{name}.info.gz
- This example is taken from the package
rplay(a package with multiple info pages). The example also shows the relatedPreReqtag):
PreReq: %install_info_prereq
[...]
%postun
%install_info_delete --info-dir=%{_infodir} %{_infodir}/%{name}.info.gz
%install_info_delete --info-dir=%{_infodir} %{_infodir}/RPLAY.info.gz
%install_info_delete --info-dir=%{_infodir} %{_infodir}/RPTP.info.gz
%install_info_delete --info-dir=%{_infodir} %{_infodir}/librplay.info.gz
%perl_archlib
This macro is substituted by the path where architecture-specific parts of Perl are installed, for example, /usr/lib/perl5/5.8.5/i586-linux-thread-multi.
It is normally only used by the perl package itself and by the macro %perl_process_packlist. See below.
%perl_make_install
This macro does the make install call correctly on various products. Before SL 9.0, the normal way to invoke it was:
make PREFIX=$RPM_BUILD_ROOT/%_prefix \ INSTALLMAN1DIR=$RPM_BUILD_ROOT/%_mandir/man1 \ INSTALLMAN3DIR=$RPM_BUILD_ROOT/%_mandir/man3 \ install
For 9.0 and later versions:
make DESTDIR=$RPM_BUILD_ROOT install_vendor
With the macro %perl_make_install, this is done correctly according to the version.
This example comes from the package perl-URI:
%install %perl_make_install
%perl_process_packlist
This macro prepares some files, related to perl modules, for the final package. It does the following actions:
- Removes
$RPM_BUILD_ROOTfrom%perl_archlib/perllocal.podand renames the file to a package-specific file. See below for more details. - Searches for the installed
.packlistfiles and removes$RPM_BUILD_ROOTfrom them.
Each package including a perl module should call this macro in the section %install.
The file %perl_archlib/perllocal.pod must be renamed because it contains information about additional installed perl modules and evidently cannot be installed at the same place from multiple packages. Therefore, it is renamed and a special SuSEconfig module, /sbin/conf.d/SuSEconfig.perl, adds this information to the system %perl_archlib/perllocal.pod after the package is installed.
This example is taken from the package perl_URI:
%install
%perl_make_install
%perl_process_packlist
%files
[...]
/var/adm/perl-modules/%{name}
%perl_sitearch
This macro is substituted by the path where architecture-specific parts of Perl modules are installed by a local administrator (/usr/lib/perl5/site_perl/5.8.5/i586-linux-thread-multi). The packages distributed within SUSE Linux use the path defined by %perl_vendorarch instead. See below.
%perl_sitelib
This macro is substituted by the path where architecture-independent parts of Perl modules are installed by a local administrator (/usr/lib/perl5/site_perl/5.8.5). The packages distributed within SUSE Linux use the path defined by %perl_vendorlib instead (see below).
%perl_vendorarch
This macro is substituted by the path where architecture-specific parts of Perl modules are installed by a Linux vendor (/usr/lib/perl5/vendor_perl/5.8.5/i586-linux-thread-multi). The macro is typically used in the file list. This example comes from the package perl-URI:
%files
[...]
%{perl_vendorarch}/auto/URI
This path has been used since SL 9.0. Until then, the Perl modules were installed below /usr/lib/perl5/site_perl using the macro %perl_sitearch. The directory site_perl is now intended for modules installed by a local administrator (see above at %perl_sitearch).
%perl_vendorlib
This macro substitutes for the path where architecture-independent parts of Perl modules are installed by a Linux vendor (/usr/lib/perl5/vendor_perl/5.8.5). The macro is typically used in the file list. This example comes from the package perl-URI:
%files
[...]
%{perl_vendorlib}/URI.pm
%{perl_vendorlib}/URI
This path has been used since SL 9.0. Until then, the Perl modules were installed below /usr/lib/perl5/site_perl using the macro %perl_sitearch. The directory site_perl is now intended for modules installed by a local administrator (see above at %perl_sitelib).
%perl_version
This macro is substituted by the version of Perl used for building the package, such as 5.8.5. It is used in packages providing a perl module to define the dependency on Perl.
It is typically used the following way. This example is taken from the package perl-URI:
Requires: perl = %{perl_version}
%py_incdir
This macro substituted by the path where Python header files are installed, such as /usr/include/python2.3. See SUSE_Package_Conventions/Specific_Packages#spc_sp_python_modules Section 10.4, “Python Modules” for an example.
%py_libdir
This macro is substituted by the path where Python modules are installed, such as /usr/lib/python2.3. See SUSE_Package_Conventions/Specific_Packages#spc_sp_python_modules Section 10.4, “Python Modules” for an example.
%py_requires
This macro is substituted by PreReq and BuildRequires tags. This defines dependency on the same python major version as is used during build. See SUSE_Package_Conventions/Specific_Packages#spc_sp_python_modules Section 10.4, “Python Modules” for an example.
%py_sitedir
This macro is substituted by the path where all extra Python modules all installed, such as /usr/lib/python2.3/site-packages. See Section 10.4, “Python Modules” for an example.
%py_ver
This macro is substituted by the Python major version, such as 2.3. See SUSE_Package_Conventions/Specific_Packages#spc_sp_python_modules Section 10.4, “Python Modules” for an example.
%remove_and_set
This macro is used to remove obsolete sysconfig variables.
Synopsis:
%remove_and_set [-ny] [sysconfig_filename] variable...
The macro %remove_and_set removes variables from /etc/rc.config and /etc/sysconfig/sysconfig_filename and sets them in the actual environment for further handling. If a variable is not found, it is set to "no" by default or it is set to “yes” if the option -y is used.
Options:
-
-ndefines that the parametersysconfig_filenameis used (see below). -
-ysets the default value to“yes”.
Parameters:
-
sysconfig_filenamecreates a pair with the option-nand defines the syconfig filename. The package name (%name) is used as the sysconfig filename otherwise. -
variabledefines the name of a variable to remove. Multiple variables can be defined.
Examples:
- This example is taken from the package
postfix:
%{fillup_and_insserv -y postfix}
if [ -f etc/sysconfig/mail ]; then
. etc/sysconfig/mail
if [ -n "$NULLCLIENT" ]; then
RCTMP=etc/sysconfig/postfix.$$
sed "s/^POSTFIX_NULLCLIENT.*/POSTFIX_NULLCLIENT=\"$ \"/" \
etc/sysconfig/postfix > $RCTMP
mv $RCTMP etc/sysconfig/postfix
fi
fi
%{remove_and_set -n mail NULLCLIENT}
This code sets the variable POSTFIX_NULLCLIENT from etc/sysconfig/postfix to the value of the obsolete variable NULLCLIENT from etc/sysconfig/mail. Then the obsolete variable is removed.
- This example is taken from the package
autofs:
%post
%{fillup_and_insserv autofs}
# needed for update from 7.3 and before
%{remove_and_set USE_NIS_FOR_AUTOFS USE_NISPLUS_FOR_AUTOFS}
if [ $USE_NIS_FOR_AUTOFS == "yes" ] ; then
if `grep "^automount:" etc/nsswitch.conf | \
grep -vqw nis` ; then
sed "s/^automount:.*/& nis/" < etc/nsswitch.conf \
>etc/nsswitch.conf.new
mv etc/nsswitch.conf.new etc/nsswitch.conf
fi
fi
if [ $USE_NISPLUS_FOR_AUTOFS == "yes" ] ; then
if `grep "^automount:" etc/nsswitch.conf | \
grep -vqw nisplus` ; then
sed "s/^automount:.*/& nisplus/" < etc/nsswitch.conf \
> etc/nsswitch.conf
mv etc/nsswitch.conf.new etc/nsswitch.conf
fi
fi
The obsolete variables USE_NIS_FOR_AUTOFS, USE_NISPLUS_FOR_AUTOFS are removed from /etc/rc_config and /etc/sysconfig/autofs and the removed values are used to modify an actual configuration.
The detected values cannot be used in the previous example because the macro %remove_and_set is able to set only values “yes” or “no” in the environment.
%restart_on_update
This macro restarts a service after an update.
Synopsis:
%restart_on_update service...
The macro %restart_on_update runs /etc/init.d/service try-restart if not running under YaST in the instsys mode. Multiple services can be defined.
This macro is usually used in the %postun script of packages providing a service. However, it cannot be used if it cannot be guaranteed that the service will work after an update.
Examples:
- This example is taken from the package
rsync:
%postun %restart_on_update rsyncd %insserv_cleanup
- This example is taken from the package
samba(restarts two services):
%postun %restart_on_update nmb smb %insserv_cleanup
%run_ldconfig (deprecated)
This macro runs ldconfig if not running from YaST. YaST runs ldconfig itself after all selected packages are installed.
It was used in both %post and %postun scripts of packages providing a library. The macro is deprecated and should not be used anymore. Instead, /sbin/ldconfig should be called directly both scripts, even from YaST, to keep from breaking other %post scripts. It could be done the following way:
%post -p /sbin/ldconfig %postun -p /sbin/ldconfig
If ldconfig is not the only command, the -p option is not usable. For example, the %post script could look like:
%post /sbin/ldconfig [...]
%run_permissions
This script fixes permissions of problematic files to follow a system security setting. It requires the package permissions to be installed.
It should be called in the %post script of packages installing a file that has secure permissions defined in /etc/permissions.{easy,secure} or in /etc/permissions.d/%name.{easy,secure}. Do not forget to mention the package permissions in the PreReq tag.
It is usually used together with the macro %verify_permissions.
This example is taken from the package xtetris (also shows the related PreReq tag):
PreReq: permissions [...] %post %run_permissions
%sles_version
This macro expands to the version of SLES where the package is built. It is ”7” for SLES7, ”8” for SLES8, etc. It is ”0” when not building on SLES.
See also %suse_version and %ul_version.
This example is taken from the package pam-modules:
%install
[...]
# On UL or SLES, we have other defaults
%if %sles_version >= 8
cp $RPM_SOURCE_DIR/pam_pwcheck.conf.sles \
$RPM_BUILD_ROOT/etc/security/pam_pwcheck.conf
%endif
%stop_on_removal
Данный макрос останавливает сервис, при удаления соответствующего пакета.
Синтаксис:
%stop_on_removal service...
The macro %stop_on_removal runs /etc/init.d/service stop if not running from YaST in the instsys mode. Multiple services can be defined.
Каждый пакет, который устанавливает системные сервисы, которые могут быть остановлены, должен использовать данный макрос в секции %preun.
Примеры:
- Пример взят из пакета
rsync:
%preun %stop_on_removal rsyncd
- Пример взят из пакета
samba(останавливает два сервиса):
%preun %stop_on_removal smb nmb
%suse_update_config
This macro updates some auto-stuff related files.
Usage:
%suse_update_config [-fcl] [dir ...]
This macro takes the following actions for the current directory and all directories given as parameters:
-
config.guessandconfig.subare overwritten by their most current versions from/usr/share/automake*/. -
depcompandmissingare added if not present in the processed directory but present in/usr/share/automake*/. -
ltconfigandltmain.share patched to accept bothlinux-gnuandlinux. -
/libis replaced by/%_libin some occurrences in bothltconfigandltmain.sh.
This macro should be called in all packages using the problematic files. However, it is not needed when autoreconf or aclocal, libtoolize, automake, and autoconf is used, because they are able to update the needed things.
This macro should be tested for existence when used in the section %prep. This allows running this section on other distributions where the macro is not available. See the examples below.
Options:
-
-c— do not updateconfig.guess,config.sub,depcompandmissing -
-f— force, ignore time stamps -
-l— do not updateltconfigandltmain.sh
Parameters:
-
dirdefines an additional directory where the files should be updated. Multiple directories can be defined.
Examples:
- This example is taken from the package
libunicode:
%prep
%setup
%patch1
%{?suse_update_config:%{suse_update_config -f}}
%build
CFLAGS="$RPM_OPT_FLAGS" \
./configure --prefix=%{prefix} \
--libdir=%{prefix}/%_lib \
--sysconfdir=%{sysconfdir}
make
- This example is taken from the package
xosview(updates files in both./and./configdirectories):
%prep
%setup -q
%patch1 -p0 -b ".serial"
[...]
%{?suse_update_config:%{suse_update_config -f config}}
%build
%ifarch ppc
export SYSTEM=powerpc-suse-linux
%else
export SYSTEM=%{_target_cpu}-suse-linux
%endif
(cd config/; autoconf; cp configure ../)
./configure $SYSTEM \
--with-x \
--enable-auto-depend \
--enable-linux-syscalls \
--prefix=/usr/X11R6 \
--disable-linux-memstat
make clean
%suse_update_desktop_file
Этот макрос обновляет/устанавливает/создает .desktop файлы.
Синтаксис:
%suse_update_desktop_file -c filename name comment exec icon [category]...
%suse_update_desktop_file [-inru] [-D docpath] [-N name] [-G genericname] filename [category]...
Макрос %suse_update_desktop_file обновляет перевод, добавляет категории (для сортировки меню), и делает некоторые проверки правильности .desktop файла. Для макроса требуется пакет update-desktop-files
Каждый пакет, содержащий .desktop файлы, должен вызывать этот макрос для всех .desktop файлов(используются без расширения .desktop), в секции %install после того, как они будут установлены в директорию /usr/share/applications или директорию /etc/xdg/autostart. Незабудьте добавить update-desktop-files в тег SUSE_Package_Conventions#spc_ps_buildrequires_tag BuildRequires. Это уже вложено в следущие мета-пакеты:
-
gnome2-devel-packages -
gtk2-devel-packages -
kde3-devel-packages -
qt3-devel-packages -
yast2-core-devel-packages -
yast2-devel-packages
Опции:
-
-cfilenamenamecommentexecicon[category] — Создает новый .desktop файл инициализированный параметрамиfilename,name,comment,exec,iconиcategory, следующим способом:
[Desktop Entry] Name=name GenericName=comment Type=Application Exec=exec Icon=icon Categories=category;....
затем устанавливает его в $RPM_BUILD_ROOT/usr/share/applications/filename.desktop.
-
-i— Ищет шаблон .desktop файла в директориях$RPM_SOURCE_DIRи/usr/share/update-desktop-files/templates, затем устанавливает их в$RPM_BUILD_ROOT/usr/share/applications/filename.desktop. -
-n— Не обновлять перевод. Используется если параметрыName=иGenericName=содержат строки не подлежащие переводу. -
-r— Замещает записьCategories=в .desktop файле соответствующим параметром. По умолчанию(т.е. без опции-r) параметр category не замещает, а добавляется в записьCategories=. -
-u— Добавляет строкуX-SuSE-Unimportant=trueв .desktop файл (файл не отображется в категориях меню, но доступен при поиске по меню). -
-Ddocpath— Sets the .desktop file DocPath entry. -
-Nname— Устанавливает значение параметраName=.desktop файла. -
-Ggenericname— Устанавливает значение параметраGenericName=.desktop файла.
Параметры:
-
filenameустанавливает имя .desktop файла(без расширения.desktop, т.е.: filename.desktop). -
categoryиспольлзуется для добавления/модификации записиCategories=в .desktop файле. Эта запись используется для сортировки содержимого в меню(подменю).
Примеры:
- Этот пример взят из пакета
kvim(также показана соответствующая часть тегаBuildRequiresи секции%files):
BuildRequires: ... update-desktop-files ... %install [...] %suse_update_desktop_file KVim TextEditor %files [...] /opt/kde3/share/applnk/*/*.desktop
Этот код обновляет перевод в уже установленном файле /opt/kde3/share/applnk/Editors/KVim.desktop. Так как оригинальный .desktop файл не содержит запись Categories=, то данная запись инициализируется следующим образом: Categories=TextEditor;.
- Этот пример взят из пакета
crack-atack(также показана соответствующие части теговBuildRequires,Sourceи секции%files):
BuildRequires: ... update-desktop-files ... Source1: %name.desktop Source2: %name-xtreme.desktop [...] %install [...] %suse_update_desktop_file -i %name Game ArcadeGame %suse_update_desktop_file -i %name-xtreme Game ArcadeGame %files [...] /usr/share/applications/%name.desktop /usr/share/applications/%name-xtreme.desktop
Этот код находит два шаблона в директории $RPM_SOURCE_DIR и устанавливает их в /usr/share/applications.
See the section %files for the final path. It also updates translations. As the templates do not contain the line Categories=, it is initialized to Categories=Game;ArcadeGame;.
- Этот пример взят из пакета
koffice:
%install [...] %suse_update_desktop_file kugar Office Viewer %suse_update_desktop_file karbon -r Graphics VectorGraphics %suse_update_desktop_file kivio Office FlowChart %suse_update_desktop_file kpresenter Office Presentation %suse_update_desktop_file kchart Office FlowChart %suse_update_desktop_file kspread Office Spreadsheet %suse_update_desktop_file KThesaurus -u Office %suse_update_desktop_file kformula -u Office %suse_update_desktop_file kword Office WordProcessor %suse_update_desktop_file koshell -u Office Core-Office
Этот код обновляет переводы в уже установленных .desktop файлах. Также, к примеру, файл Kthesaurus.desktop отмечен как неважный(опция -u), а в файле karbon.dekstop запись Categories= заменена на Categories=VectorGraphics;.
- Этот пример взят из пакета
qbrew:
%suse_update_desktop_file -c qbrew QBrew \ "A homebrewer's recipe calculator" \ qbrew "" Science
Этот код создает .desktop файл:
[Desktop Entry] Name=QBrew GenericName=A homebrewer's recipe calculator Type=Application Exec=qbrew Icon= Categories=Science;
Которые будет установлен в /usr/share/applications/qbrew.desktop.
%suse_version
This macro expands to the version of SUSE Linux the package is built in. It is ”800” for SUSE Linux 8.0, ”810” for 8.1, etc.
See also %sles_version and %ul_version.
And Build_Service/cross_distribution_package_how_to#Detect_a_distribution_flavor_for_special_code
This example it taken from the package binutils:
%prep
[...]
# experimental stuff not for the older distributions
%if 0%{?suse_version} > 820
%patch6
%endif
%tcl_version
This macro expands to the version of Tcl used on the product where the package is built. It is "8.3" for tcl-8.3, “8.4” for tcl-8.4, etc.
This example is taken from the package vkeybd:
%build
make PREFIX=%{_prefix} \
TCL_VERSION=%{tcl_version} \
XLIB="-L/usr/X11R6/lib64 -L/usr/X11R6/lib -lX11" \
USE_LADCCA=1
%ul_version
This macro expands to a version of United Linux where the package is built. It is “1” for UL 1.0 and “0” when not building on UL.
See also %sles_version and %suse_version.
This example is taken from the package installation-images:
%build [...] %ifarch %ix86 themes="SuSE Home" %else themes=SuSE %endif %if %ul_version > 0 themes=UnitedLinux %else %if %sles_version > 0 themes="SuSE-SLES" %endif
%verify_permissions
This macro helps to verify permissions of files if they depend on the system security setting.
Usage:
%verify_permissions [-f filelist] [-e file] ...
Each package, including files that have different permissions defined in /etc/permissions or /etc/permissions.easy than in /etc/permissions.secure, should call this macro in the %verifyscript section.
It is usually used together with the macro SUSE_Package_Conventions/RPM_Macros#spc_rm_run_permissions %run_permissions. The problematic files are usually marked as %verify(not mode) in the package filelist (see examples below).
Options:
-
-ffilelist — Defines a file with a list of files to check. -
-efile — defines a file to check.
Both options can be repeated.
Examples:
- This example is taken from the package
xtetris(also shows the part with%run_permissions):
PreReq: permissions [...] %post %run_permissions %verifyscript %verify_permissions -e /usr/X11R6/bin/xtetris %files %defattr(-, root, root) %verify(not mode) %attr(0755,games,games) /usr/X11R6/bin/xtetris
- This example is taken from the package
cron:
%verifyscript %verify_permissions -e /etc/crontab -e /usr/bin/crontab [...] %files [...] %verify(not mode) %config(noreplace) /etc/crontab [...] %verify(not mode) %attr (4750,root,trusted) /usr/bin/crontab
- This example is taken from the package
gnome-games:
%verifyscript
%verify_permissions -f %prefix/share/gnome-games/sgidlist
[...]
%files -f %files -f %{name}.lang
%defattr(-,root,root)
%doc AUTHORS COPYING ChangeLog NEWS README
%defattr (0755, games, games)
%verify(not mode) %{prefix}/bin/glines
%verify(not mode) %{prefix}/bin/gnibbles
%verify(not mode) %{prefix}/bin/gnobots2
[...]
%verify(not mode) %{prefix}/bin/same-gnome
%defattr (-, root, root)
%{prefix}/bin/blackjack
%suse_version
Этот макрос заменяется на версию SUSE Linux/openSUSE среды в которой собирается пакет. Например, "1000" для SUSE Linux 10.0, "1020" для openSUSE 10.2 и так далее.
Он может быть использована для проверки используемой версии
..
%if 0%{?suse_version} > 1100
BuildRequires: new-package-introduced-in-11.0
%endif
..
Или, чтобы проверить, что пакет был собран для OpenSUSE
..
%if 0%{?suse_version}
BuildRequires: libqt4-devel
%else
BuildRequires: qt4-devel
%endif
...
%fdupes
Этот макрос используется для создания жестких ссылок к дублируемым файлам в $RPM_BUILD_ROOT. Он позволяет уменьшить размер требуемый для установки, а в некоторых случаях и размер самого пакета. Будьте внимательны, чтобы дублируемые таким образом файлы не оказались в разных подпакетах, потому что неизвестно как поведет себя утилита rpm в данном случае. В случае сомнений, вы можете использовать %fdupes -s, это создает символические ссылки, которые с легкостью обрабатываются rpm.
Вы также можете комбинировать их слудующим образом:
..
%if 0%{?suse_version} > 1020
BuildRequires: fdupes
%endif
..
%install
..
%if 0%{?suse_version} > 1020
# create symlinks for man pages
%fdupes -s $RPM_BUILD_ROOT/%_mandir
# create hardlinks for the rest
%fdupes $RPM_BUILD_ROOT
%endif
There is a RPMLint check that will give an error for the package if its wasting a considerable amount of space.
| 2. Группы RPM | 4. Структура файловой системы |