Blame SOURCES/0001-groups-manager-Re-introduce-yum-groups-manager-funct.patch

fce868
From 40f08d7a22907e6292c314462c01de94584c0854 Mon Sep 17 00:00:00 2001
fce868
From: Marek Blaha <mblaha@redhat.com>
fce868
Date: Tue, 27 Oct 2020 15:46:03 +0100
fce868
Subject: [PATCH 1/2] [groups-manager] Re-introduce yum-groups-manager
fce868
 functionality (RhBug:1826016)
fce868
fce868
Implements 'dnf groups-manager' command with features:
fce868
- read, merge, print and write groups metadata files
fce868
- edit group attributes name (with translated variants),
fce868
  description (with translated variants), uservisible, displayorder
fce868
- add packgages to group
fce868
- remove packages from group
fce868
fce868
= changelog =
fce868
msg:           Re-introduce yum-groups-manager functionality
fce868
type:          enhancement
fce868
resolves:      https://bugzilla.redhat.com/show_bug.cgi?id=1826016
fce868
---
fce868
 dnf-plugins-core.spec     |  22 ++-
fce868
 doc/CMakeLists.txt        |   2 +
fce868
 doc/conf.py               |   2 +
fce868
 doc/groups-manager.rst    |  94 ++++++++++++
fce868
 doc/index.rst             |   1 +
fce868
 libexec/dnf-utils.in      |   1 +
fce868
 plugins/CMakeLists.txt    |   1 +
fce868
 plugins/groups_manager.py | 314 ++++++++++++++++++++++++++++++++++++++
fce868
 8 files changed, 432 insertions(+), 5 deletions(-)
fce868
 create mode 100644 doc/groups-manager.rst
fce868
 create mode 100644 plugins/groups_manager.py
fce868
fce868
diff --git a/dnf-plugins-core.spec b/dnf-plugins-core.spec
fce868
index d13a996..42d0884 100644
fce868
--- a/dnf-plugins-core.spec
fce868
+++ b/dnf-plugins-core.spec
fce868
@@ -58,6 +58,7 @@ Provides:       dnf-command(debug-dump)
fce868
 Provides:       dnf-command(debug-restore)
fce868
 Provides:       dnf-command(debuginfo-install)
fce868
 Provides:       dnf-command(download)
fce868
+Provides:       dnf-command(groups-manager)
fce868
 Provides:       dnf-command(repoclosure)
fce868
 Provides:       dnf-command(repograph)
fce868
 Provides:       dnf-command(repomanage)
fce868
@@ -73,6 +74,7 @@ Provides:       dnf-plugin-debuginfo-install = %{version}-%{release}
fce868
 Provides:       dnf-plugin-download = %{version}-%{release}
fce868
 Provides:       dnf-plugin-generate_completion_cache = %{version}-%{release}
fce868
 Provides:       dnf-plugin-needs_restarting = %{version}-%{release}
fce868
+Provides:       dnf-plugin-groups-manager = %{version}-%{release}
fce868
 Provides:       dnf-plugin-repoclosure = %{version}-%{release}
fce868
 Provides:       dnf-plugin-repodiff = %{version}-%{release}
fce868
 Provides:       dnf-plugin-repograph = %{version}-%{release}
fce868
@@ -87,7 +89,7 @@ Conflicts:      dnf-plugins-extras-common-data < %{dnf_plugins_extra}
fce868
 
fce868
 %description
fce868
 Core Plugins for DNF. This package enhances DNF with builddep, config-manager,
fce868
-copr, debug, debuginfo-install, download, needs-restarting, repoclosure,
fce868
+copr, debug, debuginfo-install, download, needs-restarting, groups-manager, repoclosure,
fce868
 repograph, repomanage, reposync, changelog and repodiff commands. Additionally
fce868
 provides generate_completion_cache passive plugin.
fce868
 
fce868
@@ -129,7 +131,8 @@ Conflicts:      python-%{name} < %{version}-%{release}
fce868
 %description -n python2-%{name}
fce868
 Core Plugins for DNF, Python 2 interface. This package enhances DNF with builddep,
fce868
 config-manager, copr, degug, debuginfo-install, download, needs-restarting,
fce868
-repoclosure, repograph, repomanage, reposync, changelog and repodiff commands.
fce868
+groups-manager, repoclosure, repograph, repomanage, reposync, changelog
fce868
+and repodiff commands.
fce868
 Additionally provides generate_completion_cache passive plugin.
fce868
 %endif
fce868
 
fce868
@@ -163,7 +166,8 @@ Conflicts:      python-%{name} < %{version}-%{release}
fce868
 %description -n python3-%{name}
fce868
 Core Plugins for DNF, Python 3 interface. This package enhances DNF with builddep,
fce868
 config-manager, copr, debug, debuginfo-install, download, needs-restarting,
fce868
-repoclosure, repograph, repomanage, reposync, changelog and repodiff commands.
fce868
+groups-manager, repoclosure, repograph, repomanage, reposync, changelog
fce868
+and repodiff commands.
fce868
 Additionally provides generate_completion_cache passive plugin.
fce868
 %endif
fce868
 
fce868
@@ -190,8 +194,8 @@ Summary:        Yum-utils CLI compatibility layer
fce868
 %description -n %{yum_utils_subpackage_name}
fce868
 As a Yum-utils CLI compatibility layer, supplies in CLI shims for
fce868
 debuginfo-install, repograph, package-cleanup, repoclosure, repomanage,
fce868
-repoquery, reposync, repotrack, repodiff, builddep, config-manager, debug
fce868
-and download that use new implementations using DNF.
fce868
+repoquery, reposync, repotrack, repodiff, builddep, config-manager, debug,
fce868
+download and yum-groups-manager that use new implementations using DNF.
fce868
 %endif
fce868
 
fce868
 %if 0%{?rhel} == 0 && %{with python2}
fce868
@@ -458,6 +462,7 @@ ln -sf %{_libexecdir}/dnf-utils %{buildroot}%{_bindir}/yum-builddep
fce868
 ln -sf %{_libexecdir}/dnf-utils %{buildroot}%{_bindir}/yum-config-manager
fce868
 ln -sf %{_libexecdir}/dnf-utils %{buildroot}%{_bindir}/yum-debug-dump
fce868
 ln -sf %{_libexecdir}/dnf-utils %{buildroot}%{_bindir}/yum-debug-restore
fce868
+ln -sf %{_libexecdir}/dnf-utils %{buildroot}%{_bindir}/yum-groups-manager
fce868
 ln -sf %{_libexecdir}/dnf-utils %{buildroot}%{_bindir}/yumdownloader
fce868
 # These commands don't have a dedicated man page, so let's just point them
fce868
 # to the utils page which contains their descriptions.
fce868
@@ -483,6 +488,7 @@ PYTHONPATH=./plugins nosetests-%{python3_version} -s tests/
fce868
 %{_mandir}/man8/dnf-debuginfo-install.*
fce868
 %{_mandir}/man8/dnf-download.*
fce868
 %{_mandir}/man8/dnf-generate_completion_cache.*
fce868
+%{_mandir}/man8/dnf-groups-manager.*
fce868
 %{_mandir}/man8/dnf-needs-restarting.*
fce868
 %{_mandir}/man8/dnf-repoclosure.*
fce868
 %{_mandir}/man8/dnf-repodiff.*
fce868
@@ -513,6 +519,7 @@ PYTHONPATH=./plugins nosetests-%{python3_version} -s tests/
fce868
 %{python2_sitelib}/dnf-plugins/debuginfo-install.*
fce868
 %{python2_sitelib}/dnf-plugins/download.*
fce868
 %{python2_sitelib}/dnf-plugins/generate_completion_cache.*
fce868
+%{python2_sitelib}/dnf-plugins/groups_manager.*
fce868
 %{python2_sitelib}/dnf-plugins/needs_restarting.*
fce868
 %{python2_sitelib}/dnf-plugins/repoclosure.*
fce868
 %{python2_sitelib}/dnf-plugins/repodiff.*
fce868
@@ -538,6 +545,7 @@ PYTHONPATH=./plugins nosetests-%{python3_version} -s tests/
fce868
 %{python3_sitelib}/dnf-plugins/debuginfo-install.py
fce868
 %{python3_sitelib}/dnf-plugins/download.py
fce868
 %{python3_sitelib}/dnf-plugins/generate_completion_cache.py
fce868
+%{python3_sitelib}/dnf-plugins/groups_manager.py
fce868
 %{python3_sitelib}/dnf-plugins/needs_restarting.py
fce868
 %{python3_sitelib}/dnf-plugins/repoclosure.py
fce868
 %{python3_sitelib}/dnf-plugins/repodiff.py
fce868
@@ -552,6 +560,7 @@ PYTHONPATH=./plugins nosetests-%{python3_version} -s tests/
fce868
 %{python3_sitelib}/dnf-plugins/__pycache__/debuginfo-install.*
fce868
 %{python3_sitelib}/dnf-plugins/__pycache__/download.*
fce868
 %{python3_sitelib}/dnf-plugins/__pycache__/generate_completion_cache.*
fce868
+%{python3_sitelib}/dnf-plugins/__pycache__/groups_manager.*
fce868
 %{python3_sitelib}/dnf-plugins/__pycache__/needs_restarting.*
fce868
 %{python3_sitelib}/dnf-plugins/__pycache__/repoclosure.*
fce868
 %{python3_sitelib}/dnf-plugins/__pycache__/repodiff.*
fce868
@@ -579,6 +588,7 @@ PYTHONPATH=./plugins nosetests-%{python3_version} -s tests/
fce868
 %{_bindir}/yum-config-manager
fce868
 %{_bindir}/yum-debug-dump
fce868
 %{_bindir}/yum-debug-restore
fce868
+%{_bindir}/yum-groups-manager
fce868
 %{_bindir}/yumdownloader
fce868
 %{_mandir}/man1/debuginfo-install.*
fce868
 %{_mandir}/man1/needs-restarting.*
fce868
@@ -591,6 +601,7 @@ PYTHONPATH=./plugins nosetests-%{python3_version} -s tests/
fce868
 %{_mandir}/man1/yum-config-manager.*
fce868
 %{_mandir}/man1/yum-debug-dump.*
fce868
 %{_mandir}/man1/yum-debug-restore.*
fce868
+%{_mandir}/man1/yum-groups-manager.*
fce868
 %{_mandir}/man1/yumdownloader.*
fce868
 %{_mandir}/man1/package-cleanup.*
fce868
 %{_mandir}/man1/dnf-utils.*
fce868
@@ -612,6 +623,7 @@ PYTHONPATH=./plugins nosetests-%{python3_version} -s tests/
fce868
 %exclude %{_mandir}/man1/yum-config-manager.*
fce868
 %exclude %{_mandir}/man1/yum-debug-dump.*
fce868
 %exclude %{_mandir}/man1/yum-debug-restore.*
fce868
+%exclude %{_mandir}/man1/yum-groups-manager.*
fce868
 %exclude %{_mandir}/man1/yumdownloader.*
fce868
 %exclude %{_mandir}/man1/package-cleanup.*
fce868
 %exclude %{_mandir}/man1/dnf-utils.*
fce868
diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt
fce868
index dd97eb2..3fb665d 100644
fce868
--- a/doc/CMakeLists.txt
fce868
+++ b/doc/CMakeLists.txt
fce868
@@ -26,6 +26,7 @@ INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/dnf-builddep.8
fce868
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-debuginfo-install.8
fce868
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-download.8
fce868
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-generate_completion_cache.8
fce868
+    ${CMAKE_CURRENT_BINARY_DIR}/dnf-groups-manager.8
fce868
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-leaves.8
fce868
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-needs-restarting.8
fce868
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-repoclosure.8
fce868
@@ -61,6 +62,7 @@ INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/debuginfo-install.1
fce868
     ${CMAKE_CURRENT_BINARY_DIR}/yum-config-manager.1
fce868
     ${CMAKE_CURRENT_BINARY_DIR}/yum-debug-dump.1
fce868
     ${CMAKE_CURRENT_BINARY_DIR}/yum-debug-restore.1
fce868
+    ${CMAKE_CURRENT_BINARY_DIR}/yum-groups-manager.1
fce868
     ${CMAKE_CURRENT_BINARY_DIR}/yumdownloader.1
fce868
     ${CMAKE_CURRENT_BINARY_DIR}/package-cleanup.1
fce868
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-utils.1
fce868
diff --git a/doc/conf.py b/doc/conf.py
fce868
index d760ef3..645185a 100644
fce868
--- a/doc/conf.py
fce868
+++ b/doc/conf.py
fce868
@@ -251,6 +251,7 @@ man_pages = [
fce868
     ('download', 'dnf-download', u'DNF download Plugin', AUTHORS, 8),
fce868
     ('generate_completion_cache', 'dnf-generate_completion_cache',
fce868
         u'DNF generate_completion_cache Plugin', AUTHORS, 8),
fce868
+    ('groups-manager', 'dnf-groups-manager', u'DNF groups-manager Plugin', AUTHORS, 8),
fce868
     ('leaves', 'dnf-leaves', u'DNF leaves Plugin', AUTHORS, 8),
fce868
     ('local', 'dnf-local', u'DNF local Plugin', AUTHORS, 8),
fce868
     ('needs_restarting', 'dnf-needs-restarting', u'DNF needs_restarting Plugin', AUTHORS, 8),
fce868
@@ -268,6 +269,7 @@ man_pages = [
fce868
     ('copr', 'yum-copr', u'redirecting to DNF copr Plugin', AUTHORS, 8),
fce868
     ('debuginfo-install', 'debuginfo-install', u'redirecting to DNF debuginfo-install Plugin',
fce868
      AUTHORS, 1),
fce868
+    ('groups-manager', 'yum-groups-manager', u'redirecting to DNF groups-manager Plugin', AUTHORS, 1),
fce868
     ('needs_restarting', 'needs-restarting', u'redirecting to DNF needs-restarting Plugin',
fce868
      AUTHORS, 1),
fce868
     ('repoclosure', 'repoclosure', u'redirecting to DNF repoclosure Plugin', AUTHORS, 1),
fce868
diff --git a/doc/groups-manager.rst b/doc/groups-manager.rst
fce868
new file mode 100644
fce868
index 0000000..f8f76a1
fce868
--- /dev/null
fce868
+++ b/doc/groups-manager.rst
fce868
@@ -0,0 +1,94 @@
fce868
+..
fce868
+  Copyright (C) 2020  Red Hat, Inc.
fce868
+
fce868
+  This copyrighted material is made available to anyone wishing to use,
fce868
+  modify, copy, or redistribute it subject to the terms and conditions of
fce868
+  the GNU General Public License v.2, or (at your option) any later version.
fce868
+  This program is distributed in the hope that it will be useful, but WITHOUT
fce868
+  ANY WARRANTY expressed or implied, including the implied warranties of
fce868
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
fce868
+  Public License for more details.  You should have received a copy of the
fce868
+  GNU General Public License along with this program; if not, write to the
fce868
+  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
fce868
+  02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
fce868
+  source code or documentation are not subject to the GNU General Public
fce868
+  License and may only be used or replicated with the express permission of
fce868
+  Red Hat, Inc.
fce868
+
fce868
+=========================
fce868
+DNF groups-manager Plugin
fce868
+=========================
fce868
+
fce868
+Create and edit groups repository metadata files.
fce868
+
fce868
+--------
fce868
+Synopsis
fce868
+--------
fce868
+
fce868
+``dnf groups-manager [options] [package-name-spec [package-name-spec ...]]``
fce868
+
fce868
+-----------
fce868
+Description
fce868
+-----------
fce868
+groups-manager plugin is used to create or edit a group metadata file for a repository. This is often much easier than writing/editing the XML by hand. The groups-manager can load an entire file of groups metadata and either create a new group or edit an existing group and then write all of the groups metadata back out.
fce868
+
fce868
+---------
fce868
+Arguments
fce868
+---------
fce868
+
fce868
+``<package-name-spec>``
fce868
+    Package to add to a group or remove from a group.
fce868
+
fce868
+-------
fce868
+Options
fce868
+-------
fce868
+
fce868
+All general DNF options are accepted, see `Options` in :manpage:`dnf(8)` for details.
fce868
+
fce868
+``--load=<path_to_comps.xml>``
fce868
+    Load the groups metadata information from the specified file before performing any operations. Metadata from all files are merged together if the option is specified multiple times.
fce868
+
fce868
+``--save=<path_to_comps.xml>``
fce868
+    Save the result to this file. You can specify the name of a file you are loading from as the data will only be saved when all the operations have been performed. This option can also be specified multiple times.
fce868
+
fce868
+``--merge=<path_to_comps.xml>``
fce868
+    This is the same as loading and saving a file, however the "merge" file is loaded before any others and saved last.
fce868
+
fce868
+``--print``
fce868
+    Also print the result to stdout.
fce868
+
fce868
+``--id=<id>``
fce868
+    The id to lookup/use for the group. If you don't specify an ``<id>``, but do specify a name that doesn't refer to an existing group, then an id for the group is generated based on the name.
fce868
+
fce868
+``-n <name>, --name=<name>``
fce868
+    The name to lookup/use for the group. If you specify an existing group id, then the group with that id will have it's name changed to this value.
fce868
+
fce868
+``--description=<description>``
fce868
+    The description to use for the group.
fce868
+
fce868
+``--display-order=<display_order>``
fce868
+    Change the integer which controls the order groups are presented in, for example in ``dnf grouplist``.
fce868
+
fce868
+``--translated-name=<lang:text>``
fce868
+    A translation of the group name in the given language. The syntax is ``lang:text``. Eg. ``en:my-group-name-in-english``
fce868
+
fce868
+``--translated-description=<lang:text>``
fce868
+    A translation of the group description in the given language. The syntax is ``lang:text``. Eg. ``en:my-group-description-in-english``.
fce868
+
fce868
+``--user-visible``
fce868
+    Make the group visible in ``dnf grouplist`` (this is the default).
fce868
+
fce868
+``--not-user-visible``
fce868
+    Make the group not visible in ``dnf grouplist``.
fce868
+
fce868
+``--mandatory``
fce868
+    Store the package names specified within the mandatory section of the specified group, the default is to use the default section.
fce868
+
fce868
+``--optional``
fce868
+    Store the package names specified within the optional section of the specified group, the default is to use the default section.
fce868
+
fce868
+``--remove``
fce868
+    Instead of adding packages remove them. Note that the packages are removed from all sections (default, mandatory and optional).
fce868
+
fce868
+``--dependencies``
fce868
+    Also include the names of the direct dependencies for each package specified.
fce868
diff --git a/doc/index.rst b/doc/index.rst
fce868
index 91bb36e..7213253 100644
fce868
--- a/doc/index.rst
fce868
+++ b/doc/index.rst
fce868
@@ -33,6 +33,7 @@ This documents core plugins of DNF:
fce868
    debuginfo-install
fce868
    download
fce868
    generate_completion_cache
fce868
+   groups-manager
fce868
    leaves
fce868
    local
fce868
    migrate
fce868
diff --git a/libexec/dnf-utils.in b/libexec/dnf-utils.in
fce868
index 667ce13..af1e893 100644
fce868
--- a/libexec/dnf-utils.in
fce868
+++ b/libexec/dnf-utils.in
fce868
@@ -37,6 +37,7 @@ MAPPING = {'debuginfo-install': ['debuginfo-install'],
fce868
            'yum-config-manager': ['config-manager'],
fce868
            'yum-debug-dump': ['debug-dump'],
fce868
            'yum-debug-restore': ['debug-restore'],
fce868
+           'yum-groups-manager': ['groups-manager'],
fce868
            'yumdownloader': ['download']
fce868
            }
fce868
 
fce868
diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt
fce868
index 7465e53..f66d3df 100644
fce868
--- a/plugins/CMakeLists.txt
fce868
+++ b/plugins/CMakeLists.txt
fce868
@@ -6,6 +6,7 @@ INSTALL (FILES config_manager.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
fce868
 INSTALL (FILES copr.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
fce868
 INSTALL (FILES download.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
fce868
 INSTALL (FILES generate_completion_cache.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
fce868
+INSTALL (FILES groups_manager.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
fce868
 INSTALL (FILES leaves.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
fce868
 if (${WITHOUT_LOCAL} STREQUAL "0")
fce868
 INSTALL (FILES local.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
fce868
diff --git a/plugins/groups_manager.py b/plugins/groups_manager.py
fce868
new file mode 100644
fce868
index 0000000..382df37
fce868
--- /dev/null
fce868
+++ b/plugins/groups_manager.py
fce868
@@ -0,0 +1,314 @@
fce868
+# groups_manager.py
fce868
+# DNF plugin for managing comps groups metadata files
fce868
+#
fce868
+# Copyright (C) 2020 Red Hat, Inc.
fce868
+#
fce868
+# This copyrighted material is made available to anyone wishing to use,
fce868
+# modify, copy, or redistribute it subject to the terms and conditions of
fce868
+# the GNU General Public License v.2, or (at your option) any later version.
fce868
+# This program is distributed in the hope that it will be useful, but WITHOUT
fce868
+# ANY WARRANTY expressed or implied, including the implied warranties of
fce868
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
fce868
+# Public License for more details.  You should have received a copy of the
fce868
+# GNU General Public License along with this program; if not, write to the
fce868
+# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
fce868
+# 02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
fce868
+# source code or documentation are not subject to the GNU General Public
fce868
+# License and may only be used or replicated with the express permission of
fce868
+# Red Hat, Inc.
fce868
+#
fce868
+
fce868
+from __future__ import absolute_import
fce868
+from __future__ import unicode_literals
fce868
+
fce868
+import argparse
fce868
+import gzip
fce868
+import libcomps
fce868
+import os
fce868
+import re
fce868
+import shutil
fce868
+import tempfile
fce868
+
fce868
+from dnfpluginscore import _, logger
fce868
+import dnf
fce868
+import dnf.cli
fce868
+
fce868
+
fce868
+RE_GROUP_ID_VALID = '-a-z0-9_.:'
fce868
+RE_GROUP_ID = re.compile(r'^[{}]+$'.format(RE_GROUP_ID_VALID))
fce868
+RE_LANG = re.compile(r'^[-a-zA-Z0-9_.@]+$')
fce868
+COMPS_XML_OPTIONS = {
fce868
+    'default_explicit': True,
fce868
+    'uservisible_explicit': True,
fce868
+    'empty_groups': True}
fce868
+
fce868
+
fce868
+def group_id_type(value):
fce868
+    '''group id validator'''
fce868
+    if not RE_GROUP_ID.match(value):
fce868
+        raise argparse.ArgumentTypeError(_('Invalid group id'))
fce868
+    return value
fce868
+
fce868
+
fce868
+def translation_type(value):
fce868
+    '''translated texts validator'''
fce868
+    data = value.split(':', 2)
fce868
+    if len(data) != 2:
fce868
+        raise argparse.ArgumentTypeError(
fce868
+            _("Invalid translated data, should be in form 'lang:text'"))
fce868
+    lang, text = data
fce868
+    if not RE_LANG.match(lang):
fce868
+        raise argparse.ArgumentTypeError(_('Invalid/empty language for translated data'))
fce868
+    return lang, text
fce868
+
fce868
+
fce868
+def text_to_id(text):
fce868
+    '''generate group id based on its name'''
fce868
+    group_id = text.lower()
fce868
+    group_id = re.sub('[^{}]'.format(RE_GROUP_ID_VALID), '', group_id)
fce868
+    if not group_id:
fce868
+        raise dnf.cli.CliError(
fce868
+            _("Can't generate group id from '{}'. Please specify group id using --id.").format(
fce868
+                text))
fce868
+    return group_id
fce868
+
fce868
+
fce868
+@dnf.plugin.register_command
fce868
+class GroupsManagerCommand(dnf.cli.Command):
fce868
+    aliases = ('groups-manager',)
fce868
+    summary = _('create and edit groups metadata file')
fce868
+
fce868
+    def __init__(self, cli):
fce868
+        super(GroupsManagerCommand, self).__init__(cli)
fce868
+        self.comps = libcomps.Comps()
fce868
+
fce868
+    @staticmethod
fce868
+    def set_argparser(parser):
fce868
+        # input / output options
fce868
+        parser.add_argument('--load', action='append', default=[],
fce868
+                            metavar='COMPS.XML',
fce868
+                            help=_('load groups metadata from file'))
fce868
+        parser.add_argument('--save', action='append', default=[],
fce868
+                            metavar='COMPS.XML',
fce868
+                            help=_('save groups metadata to file'))
fce868
+        parser.add_argument('--merge', metavar='COMPS.XML',
fce868
+                            help=_('load and save groups metadata to file'))
fce868
+        parser.add_argument('--print', action='store_true', default=False,
fce868
+                            help=_('print the result metadata to stdout'))
fce868
+        # group options
fce868
+        parser.add_argument('--id', type=group_id_type,
fce868
+                            help=_('group id'))
fce868
+        parser.add_argument('-n', '--name', help=_('group name'))
fce868
+        parser.add_argument('--description',
fce868
+                            help=_('group description'))
fce868
+        parser.add_argument('--display-order', type=int,
fce868
+                            help=_('group display order'))
fce868
+        parser.add_argument('--translated-name', action='append', default=[],
fce868
+                            metavar='LANG:TEXT', type=translation_type,
fce868
+                            help=_('translated name for the group'))
fce868
+        parser.add_argument('--translated-description', action='append', default=[],
fce868
+                            metavar='LANG:TEXT', type=translation_type,
fce868
+                            help=_('translated description for the group'))
fce868
+        visible = parser.add_mutually_exclusive_group()
fce868
+        visible.add_argument('--user-visible', dest='user_visible', action='store_true',
fce868
+                             default=None,
fce868
+                             help=_('make the group user visible (default)'))
fce868
+        visible.add_argument('--not-user-visible', dest='user_visible', action='store_false',
fce868
+                             default=None,
fce868
+                             help=_('make the group user invisible'))
fce868
+
fce868
+        # package list options
fce868
+        section = parser.add_mutually_exclusive_group()
fce868
+        section.add_argument('--mandatory', action='store_true',
fce868
+                             help=_('add packages to the mandatory section'))
fce868
+        section.add_argument('--optional', action='store_true',
fce868
+                             help=_('add packages to the optional section'))
fce868
+        section.add_argument('--remove', action='store_true', default=False,
fce868
+                             help=_('remove packages from the group instead of adding them'))
fce868
+        parser.add_argument('--dependencies', action='store_true',
fce868
+                            help=_('include also direct dependencies for packages'))
fce868
+
fce868
+        parser.add_argument("packages", nargs='*', metavar='PACKAGE',
fce868
+                            help=_('package specification'))
fce868
+
fce868
+    def configure(self):
fce868
+        demands = self.cli.demands
fce868
+
fce868
+        if self.opts.packages:
fce868
+            demands.sack_activation = True
fce868
+            demands.available_repos = True
fce868
+            demands.load_system_repo = False
fce868
+
fce868
+        # handle --merge option (shortcut to --load and --save the same file)
fce868
+        if self.opts.merge:
fce868
+            self.opts.load.insert(0, self.opts.merge)
fce868
+            self.opts.save.append(self.opts.merge)
fce868
+
fce868
+        # check that group is specified when editing is attempted
fce868
+        if (self.opts.description
fce868
+                or self.opts.display_order
fce868
+                or self.opts.translated_name
fce868
+                or self.opts.translated_description
fce868
+                or self.opts.user_visible is not None
fce868
+                or self.opts.packages):
fce868
+            if not self.opts.id and not self.opts.name:
fce868
+                raise dnf.cli.CliError(
fce868
+                    _("Can't edit group without specifying it (use --id or --name)"))
fce868
+
fce868
+    def load_input_files(self):
fce868
+        """
fce868
+        Loads all input xml files.
fce868
+        Returns True if at least one file was successfuly loaded
fce868
+        """
fce868
+        for file_name in self.opts.load:
fce868
+            file_comps = libcomps.Comps()
fce868
+            try:
fce868
+                if file_name.endswith('.gz'):
fce868
+                    # libcomps does not support gzipped files - decompress to temporary
fce868
+                    # location
fce868
+                    with gzip.open(file_name) as gz_file:
fce868
+                        temp_file = tempfile.NamedTemporaryFile(delete=False)
fce868
+                        try:
fce868
+                            shutil.copyfileobj(gz_file, temp_file)
fce868
+                            # close temp_file to ensure the content is flushed to disk
fce868
+                            temp_file.close()
fce868
+                            file_comps.fromxml_f(temp_file.name)
fce868
+                        finally:
fce868
+                            os.unlink(temp_file.name)
fce868
+                else:
fce868
+                    file_comps.fromxml_f(file_name)
fce868
+            except (IOError, OSError, libcomps.ParserError) as err:
fce868
+                # gzip module raises OSError on reading from malformed gz file
fce868
+                # get_last_errors() output often contains duplicit lines, remove them
fce868
+                seen = set()
fce868
+                for error in file_comps.get_last_errors():
fce868
+                    if error in seen:
fce868
+                        continue
fce868
+                    logger.error(error.strip())
fce868
+                    seen.add(error)
fce868
+                raise dnf.exceptions.Error(
fce868
+                    _("Can't load file \"{}\": {}").format(file_name, err))
fce868
+            else:
fce868
+                self.comps += file_comps
fce868
+
fce868
+    def save_output_files(self):
fce868
+        for file_name in self.opts.save:
fce868
+            try:
fce868
+                # xml_f returns a list of errors / log entries
fce868
+                errors = self.comps.xml_f(file_name, xml_options=COMPS_XML_OPTIONS)
fce868
+            except libcomps.XMLGenError as err:
fce868
+                errors = [err]
fce868
+            if errors:
fce868
+                # xml_f() method could return more than one error. In this case
fce868
+                # raise the latest of them and log the others.
fce868
+                for err in errors[:-1]:
fce868
+                    logger.error(err.strip())
fce868
+                raise dnf.exceptions.Error(_("Can't save file \"{}\": {}").format(
fce868
+                    file_name, errors[-1].strip()))
fce868
+
fce868
+
fce868
+    def find_group(self, group_id, name):
fce868
+        '''
fce868
+        Try to find group according to command line parameters - first by id
fce868
+        then by name.
fce868
+        '''
fce868
+        group = None
fce868
+        if group_id:
fce868
+            for grp in self.comps.groups:
fce868
+                if grp.id == group_id:
fce868
+                    group = grp
fce868
+                    break
fce868
+        if group is None and name:
fce868
+            for grp in self.comps.groups:
fce868
+                if grp.name == name:
fce868
+                    group = grp
fce868
+                    break
fce868
+        return group
fce868
+
fce868
+    def edit_group(self, group):
fce868
+        '''
fce868
+        Set attributes and package lists for selected group
fce868
+        '''
fce868
+        def langlist_to_strdict(lst):
fce868
+            str_dict = libcomps.StrDict()
fce868
+            for lang, text in lst:
fce868
+                str_dict[lang] = text
fce868
+            return str_dict
fce868
+
fce868
+        # set group attributes
fce868
+        if self.opts.name:
fce868
+            group.name = self.opts.name
fce868
+        if self.opts.description:
fce868
+            group.desc = self.opts.description
fce868
+        if self.opts.display_order:
fce868
+            group.display_order = self.opts.display_order
fce868
+        if self.opts.user_visible is not None:
fce868
+            group.uservisible = self.opts.user_visible
fce868
+        if self.opts.translated_name:
fce868
+            group.name_by_lang = langlist_to_strdict(self.opts.translated_name)
fce868
+        if self.opts.translated_description:
fce868
+            group.desc_by_lang = langlist_to_strdict(self.opts.translated_description)
fce868
+
fce868
+        # edit packages list
fce868
+        if self.opts.packages:
fce868
+            # find packages according to specifications from command line
fce868
+            packages = set()
fce868
+            for pkg_spec in self.opts.packages:
fce868
+                q = self.base.sack.query().filterm(name__glob=pkg_spec).latest()
fce868
+                if not q:
fce868
+                    logger.warning(_("No match for argument: {}").format(pkg_spec))
fce868
+                    continue
fce868
+                packages.update(q)
fce868
+            if self.opts.dependencies:
fce868
+                # add packages that provide requirements
fce868
+                requirements = set()
fce868
+                for pkg in packages:
fce868
+                    requirements.update(pkg.requires)
fce868
+                packages.update(self.base.sack.query().filterm(provides=requirements))
fce868
+
fce868
+            pkg_names = {pkg.name for pkg in packages}
fce868
+
fce868
+            if self.opts.remove:
fce868
+                for pkg_name in pkg_names:
fce868
+                    for pkg in group.packages_match(name=pkg_name,
fce868
+                                                    type=libcomps.PACKAGE_TYPE_UNKNOWN):
fce868
+                        group.packages.remove(pkg)
fce868
+            else:
fce868
+                if self.opts.mandatory:
fce868
+                    pkg_type = libcomps.PACKAGE_TYPE_MANDATORY
fce868
+                elif self.opts.optional:
fce868
+                    pkg_type = libcomps.PACKAGE_TYPE_OPTIONAL
fce868
+                else:
fce868
+                    pkg_type = libcomps.PACKAGE_TYPE_DEFAULT
fce868
+                for pkg_name in sorted(pkg_names):
fce868
+                    if not group.packages_match(name=pkg_name, type=pkg_type):
fce868
+                        group.packages.append(libcomps.Package(name=pkg_name, type=pkg_type))
fce868
+
fce868
+    def run(self):
fce868
+        self.load_input_files()
fce868
+
fce868
+        if self.opts.id or self.opts.name:
fce868
+            # we are adding / editing a group
fce868
+            group = self.find_group(group_id=self.opts.id, name=self.opts.name)
fce868
+            if group is None:
fce868
+                # create a new group
fce868
+                if self.opts.remove:
fce868
+                    raise dnf.exceptions.Error(_("Can't remove packages from non-existent group"))
fce868
+                group = libcomps.Group()
fce868
+                if self.opts.id:
fce868
+                    group.id = self.opts.id
fce868
+                    group.name = self.opts.id
fce868
+                elif self.opts.name:
fce868
+                    group_id = text_to_id(self.opts.name)
fce868
+                    if self.find_group(group_id=group_id, name=None):
fce868
+                        raise dnf.cli.CliError(
fce868
+                            _("Group id '{}' generated from '{}' is duplicit. "
fce868
+                              "Please specify group id using --id.").format(
fce868
+                                  group_id, self.opts.name))
fce868
+                    group.id = group_id
fce868
+                self.comps.groups.append(group)
fce868
+            self.edit_group(group)
fce868
+
fce868
+        self.save_output_files()
fce868
+        if self.opts.print or (not self.opts.save):
fce868
+            print(self.comps.xml_str(xml_options=COMPS_XML_OPTIONS))
fce868
-- 
fce868
2.26.2
fce868