From ecb7f20025662812f45e16ab65f1e69ba3105c2a Mon Sep 17 00:00:00 2001
From: Anton Medvedev <amedvede@redhat.com>
Date: Mar 17 2023 15:23:48 +0000
Subject: [PATCH 1/3] feat: add new unretire command


Signed-off-by: Anton Medvedev <amedvede@redhat.com>

---

diff --git a/fedpkg/cli.py b/fedpkg/cli.py
index 57659af..a5af7a4 100644
--- a/fedpkg/cli.py
+++ b/fedpkg/cli.py
@@ -18,6 +18,7 @@ import itertools
 import json
 import os
 import re
+import requests
 import shutil
 import textwrap
 from datetime import datetime
@@ -471,8 +472,8 @@ class fedpkgClient(cliClient):
         request_branch_parser.add_argument(
             '--no-auto-module', default=False, action='store_true',
             help='If requesting an rpm arbitrary branch, do not '
-            'also request a new matching module.  See '
-            'https://pagure.io/fedrepo_req/issue/129'
+                 'also request a new matching module.  See '
+                 'https://pagure.io/fedrepo_req/issue/129'
         )
         request_branch_parser.add_argument(
             '--all-releases', default=False, action='store_true',
@@ -549,8 +550,8 @@ class fedpkgClient(cliClient):
     def register_set_distgit_token(self):
         help_msg = \
             'Updates the fedpkg.distgit API token in ~/.config/rpkg/{0}.conf file.\n\n\
-            Tokens are of length 64 and contain only uppercase and numerical values.'\
-            .format(self.name)
+            Tokens are of length 64 and contain only uppercase and numerical values.' \
+                .format(self.name)
         distgit_section = '{0}.distgit'.format(self.name)
         distgit_api_base_url = config_get_safely(self.config, distgit_section, "apibaseurl")
 
@@ -568,8 +569,8 @@ class fedpkgClient(cliClient):
     def register_set_pagure_token(self):
         help_msg = \
             'Updates the fedpkg.pagure API token in ~/.config/rpkg/{0}.conf file.\n\n\
-            Tokens are of length 64 and contain only uppercase and numerical values.'\
-            .format(self.name)
+            Tokens are of length 64 and contain only uppercase and numerical values.' \
+                .format(self.name)
         pagure_section = '{0}.pagure'.format(self.name)
         pagure_url = config_get_safely(self.config, pagure_section, 'url')
 
@@ -755,6 +756,67 @@ class fedpkgClient(cliClient):
             description=description)
         disable_monitoring_parser.set_defaults(command=self.do_disable_monitoring)
 
+    def _get_fedora_branches(self):
+        def extract_number(s):
+            return -int(''.join(filter(str.isdigit, s)))
+
+        bodhi_endpoint = "https://bodhi.fedoraproject.org/releases/"
+        response = requests.get(url=bodhi_endpoint)
+        count_of_version_on_bodhi = response.json()["total"]
+
+        params = {"rows_per_page": count_of_version_on_bodhi}
+        response = requests.get(url=bodhi_endpoint, params=params)
+
+        branches = response.json()["releases"]
+        branches = [branch["branch"] for branch in branches]
+
+        pattern = re.compile('f\d{2}$')
+
+        filtered_branches = list(set(filter(pattern.match, branches)))
+        sorted_branches = sorted(filtered_branches, key=extract_number)
+        fedora_branches = sorted_branches.insert(0, "rawhide")
+        return fedora_branches
+
+    def register_unretire(self):
+        """
+
+        """
+        help_msg = "Request to unretire the package"
+
+        description = textwrap.dedent("""
+            Some text
+        """)
+
+        request_unretire_parcer = self.subparsers.add_parser(
+            "unretire",
+            formatted_class=argparse.RawDescriptionHelpFormatter,
+            help=help_msg,
+            description=description
+        )
+        request_unretire_parcer.add_argument(
+            "name",
+            help="Repository name to unretire."
+        )
+        request_unretire_parcer.add_argument(
+            "--namespace",
+            required=False,
+            choices=self.get_distgit_namespaces(),
+            help="Namespace of repository."
+        )
+        request_unretire_parcer.add_argument(
+            "--branches",
+            default="rawhide",
+            choices=self._get_fedora_branches(),
+            nargs="+",
+            required=True,
+            help="Branches requester would like to unretire."
+        )
+        request_unretire_parcer.add_argument(
+            "--review_bugilla_url",
+            help="Bugzilla url with review request on package requester would like to unretire."
+        )
+        request_unretire_parcer.set_defaults(command=self.unretire)
+
     # Target functions go here
     def _format_update_clog(self, clog):
         ''' Format clog for the update template. '''
@@ -1234,10 +1296,10 @@ class fedpkgClient(cliClient):
 
             # check whether the requested branch was already created
             if b not in get_pagure_branches(
-                logger=logger,
-                url=get_dist_git_url(anongiturl),
-                namespace=ns,
-                repo_name=repo_name
+                    logger=logger,
+                    url=get_dist_git_url(anongiturl),
+                    namespace=ns,
+                    repo_name=repo_name
             ):
                 print(new_pagure_issue(
                     logger, pagure_url, pagure_token, ticket_title, ticket_body,
@@ -1249,11 +1311,11 @@ class fedpkgClient(cliClient):
             # For non-standard rpm branch requests, also request a matching new
             # module repo with a matching branch.
             auto_module = (
-                ns == 'rpms'
-                and not re.match(RELEASE_BRANCH_REGEX, b)
-                and not playground_match  # Dont run auto_module on epel-playground requests
-                and not next_match        # Dont run auto_module on epel-next requests
-                and not no_auto_module
+                    ns == 'rpms'
+                    and not re.match(RELEASE_BRANCH_REGEX, b)
+                    and not playground_match  # Dont run auto_module on epel-playground requests
+                    and not next_match  # Dont run auto_module on epel-next requests
+                    and not no_auto_module
             )
             if auto_module:
                 summary = ('Automatically requested module for '
@@ -1577,3 +1639,9 @@ class fedpkgClient(cliClient):
             namespace=self.cmd.ns,
             cli_name=self.name,
         )
+
+    def unretire(self):
+        """
+
+        """
+        pass

From abeee7f80608c5d07aa612a193fb98875f5bca6b Mon Sep 17 00:00:00 2001
From: amedvede <amedvede@redhat.com>
Date: May 25 2023 14:43:42 +0000
Subject: [PATCH 2/3] feat: getting necessary data for ticket and creating a ticket


Signed-off-by: amedvede <amedvede@redhat.com>

---

diff --git a/fedpkg/cli.py b/fedpkg/cli.py
index a5af7a4..7468cc2 100644
--- a/fedpkg/cli.py
+++ b/fedpkg/cli.py
@@ -131,6 +131,7 @@ class fedpkgClient(cliClient):
         self.register_override()
         self.register_set_distgit_token()
         self.register_set_pagure_token()
+        self.register_unretire()
         self.register_do_disable_monitoring()
 
     def setup_completers(self):
@@ -756,7 +757,8 @@ class fedpkgClient(cliClient):
             description=description)
         disable_monitoring_parser.set_defaults(command=self.do_disable_monitoring)
 
-    def _get_fedora_branches(self):
+    @staticmethod
+    def _get_fedora_branches():
         def extract_number(s):
             return -int(''.join(filter(str.isdigit, s)))
 
@@ -779,43 +781,21 @@ class fedpkgClient(cliClient):
 
     def register_unretire(self):
         """
-
+        Register the unretire target.
         """
-        help_msg = "Request to unretire the package"
+        help_msg = "Request to unretire the package/module"
 
         description = textwrap.dedent("""
-            Some text
+            Creates a well-structured releng ticket to be automatically processed by toddler plugin.
         """)
 
-        request_unretire_parcer = self.subparsers.add_parser(
+        request_unretire_parser = self.subparsers.add_parser(
             "unretire",
             formatted_class=argparse.RawDescriptionHelpFormatter,
             help=help_msg,
             description=description
         )
-        request_unretire_parcer.add_argument(
-            "name",
-            help="Repository name to unretire."
-        )
-        request_unretire_parcer.add_argument(
-            "--namespace",
-            required=False,
-            choices=self.get_distgit_namespaces(),
-            help="Namespace of repository."
-        )
-        request_unretire_parcer.add_argument(
-            "--branches",
-            default="rawhide",
-            choices=self._get_fedora_branches(),
-            nargs="+",
-            required=True,
-            help="Branches requester would like to unretire."
-        )
-        request_unretire_parcer.add_argument(
-            "--review_bugilla_url",
-            help="Bugzilla url with review request on package requester would like to unretire."
-        )
-        request_unretire_parcer.set_defaults(command=self.unretire)
+        request_unretire_parser.set_defaults(command=self.unretire)
 
     # Target functions go here
     def _format_update_clog(self, clog):
@@ -1642,6 +1622,37 @@ class fedpkgClient(cliClient):
 
     def unretire(self):
         """
-
+        Create pagure ticket with unretire request after check.
         """
+        # TODO get info for ticket
+        pkg_name = self.cmd.repo_name
+        pkg_type = self.cmd.ns
+        branches = ["rawhide"]
+        all_existing_branches = self._get_fedora_branches()
+
+        while True:
+            response = input("Write the name of the branch to add it to unretire "
+                             "request or no to continue. like (f38/no): ")
+
+            if response.lower() in all_existing_branches:
+                print(f"You successfully add new branch '{response.lower()}'")
+                branches.append(response.lower())
+                continue
+            elif response.lower() in ["no", "n"]:
+                print(f'Alright, those branches will be part of request: '
+                      f'{" ".join(map(str, branches))}')
+                break
+            else:
+                print("Invalid response, please try again.")
+
+        # TODO create a ticket
+        issue_title = "Unretire " + pkg_name
+        issue_body = "{name:<name-of-the-package>,type:<rpm/test/flatpack/module>, " \
+                     "branches:<branches_for_unretirement>,review_bugzilla:<RHBZ>}"
+        pagure_section = '{0}.pagure'.format(self.name)
+        pagure_url = config_get_safely(self.config, pagure_section, 'url')
+        pagure_token = config_get_safely(self.config, pagure_section, 'token')
+        print(new_pagure_issue(
+            self.log, pagure_url, pagure_token, issue_title, issue_body, self.name
+        ))
         pass

From df18472c1a55109d8db125005a15f3a14ff73750 Mon Sep 17 00:00:00 2001
From: amedvede <amedvede@redhat.com>
Date: May 29 2023 10:03:13 +0000
Subject: [PATCH 3/3] feat: add prompt for getting bz ticket id


---

diff --git a/fedpkg/cli.py b/fedpkg/cli.py
index 7468cc2..0505b3d 100644
--- a/fedpkg/cli.py
+++ b/fedpkg/cli.py
@@ -1633,9 +1633,8 @@ class fedpkgClient(cliClient):
         while True:
             response = input("Write the name of the branch to add it to unretire "
                              "request or no to continue. like (f38/no): ")
-
             if response.lower() in all_existing_branches:
-                print(f"You successfully add new branch '{response.lower()}'")
+                print(f"You successfully added new branch '{response.lower()}'")
                 branches.append(response.lower())
                 continue
             elif response.lower() in ["no", "n"]:
@@ -1645,14 +1644,30 @@ class fedpkgClient(cliClient):
             else:
                 print("Invalid response, please try again.")
 
+        while True:
+            response = input("Provide the bugzilla ticket id: ")
+            if re.match(r'^[0-9]{7}$', response):
+                print(f"You successfully added review bugzilla url.")
+                review_bugzilla_url = "https://bugzilla.redhat.com/show_bug.cgi?id=" + response
+                break
+            else:
+                print("Invalid response, please try again.")
+
+        branches_for_unretirement = ",".join(map(str, branches))
+
         # TODO create a ticket
-        issue_title = "Unretire " + pkg_name
-        issue_body = "{name:<name-of-the-package>,type:<rpm/test/flatpack/module>, " \
-                     "branches:<branches_for_unretirement>,review_bugzilla:<RHBZ>}"
+        ticket_body = {
+            "name": pkg_name,
+            "type": pkg_type,
+            "branches": branches_for_unretirement,
+            "review_bugzilla": review_bugzilla_url,
+        }
+        ticket_body = json.dumps(ticket_body, indent=True)
+        ticket_body = '```\n{0}\n```'.format(ticket_body)
+        ticket_title = "Unretire " + pkg_name
         pagure_section = '{0}.pagure'.format(self.name)
         pagure_url = config_get_safely(self.config, pagure_section, 'url')
         pagure_token = config_get_safely(self.config, pagure_section, 'token')
         print(new_pagure_issue(
-            self.log, pagure_url, pagure_token, issue_title, issue_body, self.name
+            self.log, pagure_url, pagure_token, ticket_title, ticket_body, self.name
         ))
-        pass

