jenkins-bot has submitted this change. ( 
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/987146 )

Change subject: [bugfix] Check for 'from' option first
......................................................................

[bugfix] Check for 'from' option first

- import pydot first, use exception for dependency warning
- make args method a staticmethod and renamit it to setup_args
- remove ap parametr from CategoryGraphBot which isn't used
- use vars() function to access to args.__dict__
- fix usage of args attribute within CategoryGraphBot
- add main() function
- pass local_args to ap.parse_known_args
- pass rest of ap.parse_known_args to suggest_help as unknown_parameters
- call suggest_help() first
- use contextlib.suppress to ignore FileNotFoundError

Bug: T354162
Change-Id: Ic8694814ed54825ae9999cdb4610387e6a2e94c4
---
M scripts/category_graph.py
1 file changed, 63 insertions(+), 21 deletions(-)

Approvals:
  Enag2000: Looks good to me, but someone else must approve
  Xqt: Looks good to me, approved
  jenkins-bot: Verified




diff --git a/scripts/category_graph.py b/scripts/category_graph.py
index c50a1dc..9be4863 100755
--- a/scripts/category_graph.py
+++ b/scripts/category_graph.py
@@ -6,7 +6,7 @@

 Usage:

-    pwb.py graph [-style STYLE] [-depth DEPTH] [-from FROM] [-to TO]
+    pwb.py category_graph [-style STYLE] [-depth DEPTH] [-from FROM] [-to TO]

 actions:

@@ -37,7 +37,7 @@
 .. versionadded:: 8.0
 """
 #
-# (C) Pywikibot team, 2022-2023
+# (C) Pywikibot team, 2022-2024
 #
 # Distributed under the terms of the MIT license.
 #
@@ -45,8 +45,8 @@

 import argparse
 import glob
-import sys
 from collections import defaultdict
+from contextlib import suppress
 from pathlib import Path

 import pywikibot
@@ -54,10 +54,17 @@
 from pywikibot.bot import SingleSiteBot, suggest_help


+try:
+    import pydot
+except ImportError as e:
+    pydot = e
+
+
 class CategoryGraphBot(SingleSiteBot):
     """Bot to create graph of the category structure."""

-    def args(self, ap):
+    @staticmethod
+    def setup_args(ap):
         """Declares arguments."""
         ap.add_argument('-from', nargs='?', default=argparse.SUPPRESS)
         ap.add_argument('-to', nargs='?', default='')
@@ -65,11 +72,11 @@
         ap.add_argument('-depth', nargs='?', default=2)
         ap.add_argument('-downsize', nargs='?', default=4)

-    def __init__(self, ap, args: argparse.Namespace) -> None:
+    def __init__(self, args: argparse.Namespace) -> None:
         """Initializer."""
         super().__init__()
         self.args = args
-        cat_title = args.__dict__.get('from')
+        cat_title = vars(args)['from']
         if not cat_title:
             cat_title = 'Main topic classifications'
         if cat_title == '?':
@@ -106,7 +113,7 @@
             the tree (for recursion), opposite of depth.
         """
         title = cat.title(with_ns=False)
-        size = float(args.downsize) ** level
+        size = float(self.args.downsize) ** level
         subcats = sorted(cat.subcategories())

         def node():
@@ -202,11 +209,26 @@
             o.write(self.dot.create('dot', 'svg', encoding='utf-8'))


-if __name__ == '__main__':
+def main(*args: str) -> None:
+    """
+    Process command line arguments and invoke bot.
+
+    If args is an empty list, sys.argv is used.
+
+    :param args: command line arguments
+    """
     ap = argparse.ArgumentParser(add_help=False)
-    CategoryGraphBot.args(None, ap)
+    CategoryGraphBot.setup_args(ap)
     local_args = pywikibot.handle_args()
-    args, rest = ap.parse_known_args()
+    args, rest = ap.parse_known_args(local_args)
+
+    if suggest_help(
+        missing_action='from' not in args,
+        unknown_parameters=rest,
+        missing_dependencies=(['pydot'] if isinstance(pydot, ImportError)
+                              else [])
+    ):
+        return

     file_path = args.to
     # If file exists, ask user if ok to overwrite. Otherwise, make
@@ -216,16 +238,15 @@
                                     'n', automatic_quit=False)
         if not choice:
             pywikibot.info('Exiting...')
-            sys.exit(1)
+            return
     else:
-        try:
-            dir_path = Path(file_path)
+        dir_path = Path(file_path)
+        with suppress(FileNotFoundError):
             dir_path.parent.mkdir(parents=True, exist_ok=True)
-        # Except ValueError in the event that the directory is top level
-        # and does not contain any slashes.
-        except FileNotFoundError:
-            pass
-    if not suggest_help(missing_action='from' not in args):
-        import pydot
-        bot = CategoryGraphBot(ap, args)
-        bot.run()
+
+    bot = CategoryGraphBot(args)
+    bot.run()
+
+
+if __name__ == '__main__':
+    main()

--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/987146
To unsubscribe, or for help writing mail filters, visit 
https://gerrit.wikimedia.org/r/settings

Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: Ic8694814ed54825ae9999cdb4610387e6a2e94c4
Gerrit-Change-Number: 987146
Gerrit-PatchSet: 7
Gerrit-Owner: Xqt <[email protected]>
Gerrit-Reviewer: D3r1ck01 <[email protected]>
Gerrit-Reviewer: Enag2000 <[email protected]>
Gerrit-Reviewer: Xqt <[email protected]>
Gerrit-Reviewer: jenkins-bot
Gerrit-CC: Mpaa <[email protected]>
Gerrit-MessageType: merged
_______________________________________________
Pywikibot-commits mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to