Blame SOURCES/BZ-1429831-yum-copr.patch

085af2
diff -N -up -r a/docs/Makefile b/docs/Makefile
085af2
--- a/docs/Makefile	2017-03-21 14:21:12.326518685 +0100
085af2
+++ b/docs/Makefile	2017-03-21 14:24:34.711624331 +0100
085af2
@@ -5,7 +5,7 @@ DOCS = repoquery package-cleanup repo-rs
085af2
        find-repos-of-install needs-restarting repo-graph repoclosure \
085af2
        repomanage repotrack verifytree yum-config-manager yum-ovl
085af2
 DOCS5 = yum-changelog.conf yum-versionlock.conf yum-fs-snapshot.conf
085af2
-DOCS8 = yum-complete-transaction yumdb
085af2
+DOCS8 = yum-complete-transaction yumdb yum-copr
085af2
 
085af2
 all:
085af2
 	echo "Nothing to do"
085af2
diff -N -up -r a/docs/yum-copr.8 b/docs/yum-copr.8
085af2
--- a/docs/yum-copr.8	1970-01-01 01:00:00.000000000 +0100
085af2
+++ b/docs/yum-copr.8	2017-03-21 14:23:17.436729456 +0100
085af2
@@ -0,0 +1,120 @@
085af2
+.\" Man page generated from reStructuredText.
085af2
+.
085af2
+.TH "YUM-COPR" "8" "July 29, 2014" "0.1.1" "yum-plugin-copr"
085af2
+.SH NAME
085af2
+yum-plugin-copr \- YUM copr Plugin
085af2
+.
085af2
+.nr rst2man-indent-level 0
085af2
+.
085af2
+.de1 rstReportMargin
085af2
+\\$1 \\n[an-margin]
085af2
+level \\n[rst2man-indent-level]
085af2
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
085af2
+-
085af2
+\\n[rst2man-indent0]
085af2
+\\n[rst2man-indent1]
085af2
+\\n[rst2man-indent2]
085af2
+..
085af2
+.de1 INDENT
085af2
+.\" .rstReportMargin pre:
085af2
+. RS \\$1
085af2
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
085af2
+. nr rst2man-indent-level +1
085af2
+.\" .rstReportMargin post:
085af2
+..
085af2
+.de UNINDENT
085af2
+. RE
085af2
+.\" indent \\n[an-margin]
085af2
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
085af2
+.nr rst2man-indent-level -1
085af2
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
085af2
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
085af2
+..
085af2
+.
085af2
+.nr rst2man-indent-level 0
085af2
+.
085af2
+.de1 rstReportMargin
085af2
+\\$1 \\n[an-margin]
085af2
+level \\n[rst2man-indent-level]
085af2
+level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
085af2
+-
085af2
+\\n[rst2man-indent0]
085af2
+\\n[rst2man-indent1]
085af2
+\\n[rst2man-indent2]
085af2
+..
085af2
+.de1 INDENT
085af2
+.\" .rstReportMargin pre:
085af2
+. RS \\$1
085af2
+. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
085af2
+. nr rst2man-indent-level +1
085af2
+.\" .rstReportMargin post:
085af2
+..
085af2
+.de UNINDENT
085af2
+. RE
085af2
+.\" indent \\n[an-margin]
085af2
+.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
085af2
+.nr rst2man-indent-level -1
085af2
+.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
085af2
+.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
085af2
+..
085af2
+.sp
085af2
+Work with Copr & Playground repositories on the local system.
085af2
+.INDENT 0.0
085af2
+.IP \(bu 2
085af2
+The \fBcopr\fP command is used to add or remove Copr repositories to the local system
085af2
+.IP \(bu 2
085af2
+The \fBplayground\fP is used to enable or disable the Playground repository
085af2
+.UNINDENT
085af2
+.SH SYNOPSIS
085af2
+.sp
085af2
+\fByum copr [enable|disable|list|search] <parameters>\fP
085af2
+.sp
085af2
+\fByum playground [enable|disable|upgrade]\fP
085af2
+.SH ARGUMENTS (COPR)
085af2
+.INDENT 0.0
085af2
+.TP
085af2
+.B \fBenable name/project [chroot]\fP
085af2
+Enable the \fBname/project\fP Copr repository with the optional \fBchroot\fP\&.
085af2
+.TP
085af2
+.B \fBdisable name/project\fP
085af2
+Disable the \fBname/project\fP Copr repository.
085af2
+.TP
085af2
+.B \fBlist name\fP
085af2
+List available Copr repositories for a given \fBname\fP\&.
085af2
+.TP
085af2
+.B \fBsearch project\fP
085af2
+Search for a given \fBproject\fP\&.
085af2
+.UNINDENT
085af2
+.SH ARGUMENTS (PLAYGROUND)
085af2
+.INDENT 0.0
085af2
+.TP
085af2
+.B \fBenable\fP
085af2
+Enable the Playground repository.
085af2
+.TP
085af2
+.B \fBdisable\fP
085af2
+Disable the Playground repository.
085af2
+.TP
085af2
+.B \fBupgrade\fP
085af2
+Upgrade the Playground repository settings (same as \fBdisable\fP and then \fBenable\fP).
085af2
+.UNINDENT
085af2
+.SH EXAMPLES
085af2
+.INDENT 0.0
085af2
+.TP
085af2
+.B \fBcopr enable rhscl/perl516 epel\-6\-x86_64\fP
085af2
+Enable the \fBrhscl/perl516\fP Copr repository, using the \fBepel\-6\-x86_64\fP chroot.
085af2
+.TP
085af2
+.B \fBcopr disable rhscl/perl516\fP
085af2
+Disable the \fBrhscl/perl516\fP Copr repository
085af2
+.TP
085af2
+.B \fBcopr list rita\fP
085af2
+List available Copr projects for user \fBrita\fP\&.
085af2
+.TP
085af2
+.B \fBcopr search tests\fP
085af2
+Search for Copr projects named \fBtests\fP\&.
085af2
+.UNINDENT
085af2
+.SH AUTHOR
085af2
+See AUTHORS in the Core DNF Plugins distribution
085af2
+.SH COPYRIGHT
085af2
+2014, Red Hat, Licensed under GPLv2+
085af2
+.\" Generated by docutils manpage writer.
085af2
+.
085af2
diff -N -up -r a/plugins/copr/copr.conf b/plugins/copr/copr.conf
085af2
--- a/plugins/copr/copr.conf	1970-01-01 01:00:00.000000000 +0100
085af2
+++ b/plugins/copr/copr.conf	2017-03-21 14:22:49.094134790 +0100
085af2
@@ -0,0 +1,2 @@
085af2
+[main]
085af2
+enabled=1
085af2
diff -N -up -r a/plugins/copr/copr.py b/plugins/copr/copr.py
085af2
--- a/plugins/copr/copr.py	1970-01-01 01:00:00.000000000 +0100
085af2
+++ b/plugins/copr/copr.py	2017-03-21 14:22:49.095134776 +0100
085af2
@@ -0,0 +1,327 @@
085af2
+# supplies the 'copr' command.
085af2
+#
085af2
+# Copyright (C) 2014  Red Hat, Inc.
085af2
+#
085af2
+# This copyrighted material is made available to anyone wishing to use,
085af2
+# modify, copy, or redistribute it subject to the terms and conditions of
085af2
+# the GNU General Public License v.2, or (at your option) any later version.
085af2
+# This program is distributed in the hope that it will be useful, but WITHOUT
085af2
+# ANY WARRANTY expressed or implied, including the implied warranties of
085af2
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
085af2
+# Public License for more details.  You should have received a copy of the
085af2
+# GNU General Public License along with this program; if not, write to the
085af2
+# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
085af2
+# 02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
085af2
+# source code or documentation are not subject to the GNU General Public
085af2
+# License and may only be used or replicated with the express permission of
085af2
+# Red Hat, Inc.
085af2
+#
085af2
+
085af2
+"""YUM plugin supplying the 'copr' command."""
085af2
+
085af2
+from urlgrabber import grabber
085af2
+
085af2
+import yum
085af2
+import glob
085af2
+import json
085af2
+import os
085af2
+import platform
085af2
+import requests
085af2
+import urllib
085af2
+
085af2
+from yum.i18n import _
085af2
+from yum.plugins import TYPE_INTERACTIVE
085af2
+
085af2
+requires_api_version = '2.5'
085af2
+plugin_type = (TYPE_INTERACTIVE,)
085af2
+
085af2
+yes = set([_('yes'), _('y')])
085af2
+no = set([_('no'), _('n'), ''])
085af2
+
085af2
+YError = yum.Errors.YumBaseError
085af2
+YCliError = yum.Errors.MiscError
085af2
+
085af2
+def config_hook(conduit):
085af2
+    conduit.registerCommand(CoprCommand())
085af2
+    conduit.registerCommand(PlaygroundCommand())
085af2
+
085af2
+class CoprCommand:
085af2
+    """ Copr plugin for DNF """
085af2
+
085af2
+    def getNames(self):
085af2
+        return [self.aliases[0]]
085af2
+
085af2
+    def getUsage(self):
085af2
+        return self.usage
085af2
+
085af2
+    def getSummary(self):
085af2
+        return self.summary[1:]
085af2
+
085af2
+    def doCheck(self, base, basecmd, extcmds):
085af2
+        self.base = base
085af2
+
085af2
+    copr_url = "https://copr.fedoraproject.org"
085af2
+    aliases = ("copr",)
085af2
+    summary = _("Interact with Copr repositories.")
085af2
+    usage = _("""
085af2
+  enable name/project [chroot]
085af2
+  disable name/project
085af2
+  list name
085af2
+  search project
085af2
+
085af2
+  Examples:
085af2
+  copr enable rhscl/perl516 epel-6-x86_64
085af2
+  copr enable ignatenkobrain/ocltoys
085af2
+  copr disable rhscl/perl516
085af2
+  copr list ignatenkobrain
085af2
+  copr search tests
085af2
+    """)
085af2
+
085af2
+    def doCommand(self, base, basecmd, extcmds):
085af2
+        try:
085af2
+            subcommand = extcmds[0]
085af2
+            project_name = extcmds[1]
085af2
+        except (ValueError, IndexError):
085af2
+            base.logger.critical(
085af2
+                _('Error: ') +
085af2
+                _('exactly two additional parameters to '
085af2
+                  'copr command are required'))
085af2
+            # FIXME
085af2
+            # dnf.cli.commands.err_mini_usage(self.cli, self.cli.base.basecmd)
085af2
+            raise YCliError(
085af2
+                _('exactly two additional parameters to '
085af2
+                  'copr command are required'))
085af2
+        try:
085af2
+            chroot = extcmds[2]
085af2
+        except IndexError:
085af2
+            chroot = self._guess_chroot()
085af2
+        repo_filename = "/etc/yum.repos.d/_copr_{}.repo" \
085af2
+                        .format(project_name.replace("/", "-"))
085af2
+        if subcommand == "enable":
085af2
+            self._need_root()
085af2
+            self._ask_user("""
085af2
+You are about to enable a Copr repository. Please note that this
085af2
+repository is not part of the main Fedora distribution, and quality
085af2
+may vary.
085af2
+
085af2
+The Fedora Project does not exercise any power over the contents of
085af2
+this repository beyond the rules outlined in the Copr FAQ at
085af2
+<https://fedorahosted.org/copr/wiki/UserDocs#WhatIcanbuildinCopr>, and
085af2
+packages are not held to any quality or securty level.
085af2
+
085af2
+Please do not file bug reports about these packages in Fedora
085af2
+Bugzilla. In case of problems, contact the owner of this repository.
085af2
+
085af2
+Do you want to continue? [y/N]: """)
085af2
+            self._download_repo(project_name, repo_filename, chroot)
085af2
+            base.logger.info(_("Repository successfully enabled."))
085af2
+        elif subcommand == "disable":
085af2
+            self._need_root()
085af2
+            self._remove_repo(repo_filename)
085af2
+            base.logger.info(_("Repository successfully disabled."))
085af2
+        elif subcommand == "list":
085af2
+            #http://copr.fedoraproject.org/api/coprs/ignatenkobrain/
085af2
+            api_path = "/api/coprs/{}/".format(project_name)
085af2
+
085af2
+            opener = urllib.FancyURLopener({})
085af2
+            res = opener.open(self.copr_url + api_path)
085af2
+            try:
085af2
+                json_parse = json.loads(res.read())
085af2
+            except ValueError:
085af2
+                raise YError(
085af2
+                    _("Can't parse repositories for username '{}'.")
085af2
+                    .format(project_name))
085af2
+            section_text = _("List of {} coprs").format(project_name)
085af2
+            self._print_match_section(section_text)
085af2
+            i = 0
085af2
+            while i < len(json_parse["repos"]):
085af2
+                msg = "{0}/{1} : ".format(project_name,
085af2
+                      json_parse["repos"][i]["name"])
085af2
+                desc = json_parse["repos"][i]["description"]
085af2
+                if not desc:
085af2
+                    desc = _("No description given")
085af2
+                msg = self.base.fmtKeyValFill(unicode(msg), desc)
085af2
+                print(msg)
085af2
+                i += 1
085af2
+        elif subcommand == "search":
085af2
+            #http://copr.fedoraproject.org/api/coprs/search/tests/
085af2
+            api_path = "/api/coprs/search/{}/".format(project_name)
085af2
+
085af2
+            opener = urllib.FancyURLopener({})
085af2
+            res = opener.open(self.copr_url + api_path)
085af2
+            try:
085af2
+                json_parse = json.loads(res.read())
085af2
+            except ValueError:
085af2
+                raise YError(_("Can't parse search for '{}'.").format(project_name))
085af2
+            section_text = _("Matched: {}").format(project_name)
085af2
+            self._print_match_section(section_text)
085af2
+            i = 0
085af2
+            while i < len(json_parse["repos"]):
085af2
+                msg = "{0}/{1} : ".format(json_parse["repos"][i]["username"], json_parse["repos"][i]["coprname"])
085af2
+                desc = json_parse["repos"][i]["description"]
085af2
+                if not desc:
085af2
+                    desc = _("No description given.")
085af2
+                msg = self.base.fmtKeyValFill(unicode(msg), desc)
085af2
+                print(msg)
085af2
+                i += 1
085af2
+        else:
085af2
+            raise YError(
085af2
+                _('Unknown subcommand {}.').format(subcommand))
085af2
+
085af2
+        return 0, [basecmd + ' done']
085af2
+
085af2
+    def _print_match_section(self, text):
085af2
+        formatted = self.base.fmtSection(text)
085af2
+        print(formatted)
085af2
+
085af2
+    def _ask_user(self, question):
085af2
+        if self.base.conf.assumeyes and not self.base.conf.assumeno:
085af2
+            return
085af2
+        elif self.base.conf.assumeno and not self.base.conf.assumeyes:
085af2
+            raise YError(_('Safe and good answer. Exiting.'))
085af2
+
085af2
+        answer = raw_input(question).lower()
085af2
+        answer = _(answer)
085af2
+        while not ((answer in yes) or (answer in no)):
085af2
+            answer = raw_input(question).lower()
085af2
+            answer = _(answer)
085af2
+        if answer in yes:
085af2
+            return
085af2
+        else:
085af2
+            raise YError(_('Safe and good answer. Exiting.'))
085af2
+
085af2
+    @classmethod
085af2
+    def _need_root(cls):
085af2
+        # FIXME this should do dnf itself (BZ#1062889)
085af2
+        if os.geteuid() != 0:
085af2
+            raise YError(
085af2
+                _('This command has to be run under the root user.'))
085af2
+
085af2
+    @classmethod
085af2
+    def _guess_chroot(cls):
085af2
+        """ Guess which choot is equivalent to this machine """
085af2
+        # FIXME Copr should generate non-specific arch repo
085af2
+        dist = platform.linux_distribution()
085af2
+        if "Fedora" in dist:
085af2
+            # x86_64 because repo-file is same for all arch
085af2
+            # ($basearch is used)
085af2
+            if "Rawhide" in dist:
085af2
+                chroot = ("fedora-rawhide-x86_64")
085af2
+            else:
085af2
+                chroot = ("fedora-{}-x86_64".format(dist[1]))
085af2
+        else:
085af2
+            chroot = ("epel-%s-x86_64" % dist[1].split(".", 1)[0])
085af2
+        return chroot
085af2
+
085af2
+    @classmethod
085af2
+    def _download_repo(cls, project_name, repo_filename, chroot=None):
085af2
+        if chroot is None:
085af2
+            chroot = cls._guess_chroot()
085af2
+        #http://copr.fedoraproject.org/coprs/larsks/rcm/repo/epel-7-x86_64/
085af2
+        api_path = "/coprs/{0}/repo/{1}/".format(project_name, chroot)
085af2
+        ug = grabber.URLGrabber()
085af2
+        # FIXME when we are full on python2 urllib.parse
085af2
+        try:
085af2
+            ug.urlgrab(cls.copr_url + api_path, filename=repo_filename)
085af2
+        except grabber.URLGrabError as e:
085af2
+            cls._remove_repo(repo_filename)
085af2
+            raise YError(str(e))
085af2
+
085af2
+    @classmethod
085af2
+    def _remove_repo(cls, repo_filename):
085af2
+        # FIXME is it Copr repo ?
085af2
+        try:
085af2
+            os.remove(repo_filename)
085af2
+        except OSError as e:
085af2
+            raise YError(str(e))
085af2
+
085af2
+    @classmethod
085af2
+    def _get_data(cls, req):
085af2
+        """ Wrapper around response from server
085af2
+
085af2
+        check data and print nice error in case of some error (and return None)
085af2
+        otherwise return json object.
085af2
+        """
085af2
+        try:
085af2
+            output = json.loads(req.text)
085af2
+        except ValueError:
085af2
+            YCliError(_("Unknown response from server."))
085af2
+            return
085af2
+        if req.status_code != 200:
085af2
+            YCliError(_(
085af2
+                "Something went wrong:\n {0}\n".format(output["error"])))
085af2
+            return
085af2
+        return output
085af2
+
085af2
+
085af2
+class PlaygroundCommand(CoprCommand):
085af2
+    """ Playground plugin for DNF """
085af2
+
085af2
+    aliases = ("playground",)
085af2
+    summary = _("Interact with Playground repository.")
085af2
+    usage = " [enable|disable|upgrade]"
085af2
+
085af2
+    def _cmd_enable(self, chroot):
085af2
+        self._need_root()
085af2
+        self._ask_user("""
085af2
+You are about to enable a Playground repository.
085af2
+
085af2
+Do you want to continue? [y/N]: """)
085af2
+        api_url = "{0}/api/playground/list/".format(
085af2
+            self.copr_url)
085af2
+        req = requests.get(api_url)
085af2
+        output = self._get_data(req)
085af2
+        if output["output"] != "ok":
085af2
+            raise YCliError(_("Unknown response from server."))
085af2
+        for repo in output["repos"]:
085af2
+            project_name = "{0}/{1}".format(repo["username"],
085af2
+                repo["coprname"])
085af2
+            repo_filename = "/etc/yum.repos.d/_playground_{}.repo" \
085af2
+                    .format(project_name.replace("/", "-"))
085af2
+            try:
085af2
+                # check if that repo exist? but that will result in twice
085af2
+                # up calls
085af2
+                api_url = "{0}/api/coprs/{1}/detail/{2}/".format(
085af2
+                    self.copr_url, project_name, chroot)
085af2
+                req = requests.get(api_url)
085af2
+                output2 = self._get_data(req)
085af2
+                if output2 and ("output" in output2) and (output2["output"] == "ok"):
085af2
+                    self._download_repo(project_name, repo_filename, chroot)
085af2
+            except YError:
085af2
+                # likely 404 and that repo does not exist
085af2
+                pass
085af2
+
085af2
+    def _cmd_disable(self):
085af2
+        self._need_root()
085af2
+        for repo_filename in glob.glob('/etc/yum.repos.d/_playground_*.repo'):
085af2
+            self._remove_repo(repo_filename)
085af2
+
085af2
+    def doCommand(self, base, basecmd, extcmds):
085af2
+        try:
085af2
+            subcommand = extcmds[0]
085af2
+        except (ValueError, IndexError):
085af2
+            base.logger.critical(
085af2
+                _('Error: ') +
085af2
+                _('exactly one parameter to '
085af2
+                  'playground command are required'))
085af2
+            # FIXME:
085af2
+            # dnf.cli.commands.err_mini_usage(self.cli, self.cli.base.basecmd)
085af2
+            raise YCliError(
085af2
+                _('exactly one parameter to '
085af2
+                  'playground command are required'))
085af2
+        chroot = self._guess_chroot()
085af2
+        if subcommand == "enable":
085af2
+            self._cmd_enable(chroot)
085af2
+            base.logger.info(_("Playground repositories successfully enabled."))
085af2
+        elif subcommand == "disable":
085af2
+            self._cmd_disable()
085af2
+            base.logger.info(_("Playground repositories successfully disabled."))
085af2
+        elif subcommand == "upgrade":
085af2
+            self._cmd_disable()
085af2
+            self._cmd_enable(chroot)
085af2
+            base.logger.info(_("Playground repositories successfully updated."))
085af2
+        else:
085af2
+            raise YError(
085af2
+                _('Unknown subcommand {}.').format(subcommand))
085af2
+
085af2
+        return 0, [basecmd + ' done']