Jelajahi Sumber

switch from OptionParser to ArgumentParser, move argument parsing to helpers, raise minimum python version to 3.2

Helmut Pozimski 6 tahun lalu
induk
melakukan
4611b019ca
3 mengubah file dengan 105 tambahan dan 122 penghapusan
  1. 1 1
      README.md
  2. 63 0
      lib_stov/helpers.py
  3. 41 121
      stov

+ 1 - 1
README.md

@@ -10,7 +10,7 @@ see ./stov --help
 
 stov depends on the following software to be installed:
 
-* Python 3.0 or higher
+* Python 3.2 or higher
 * youtube-dl (get it from http://rg3.github.com/youtube-dl/ if you don't have it yet, it is needed to download videos and retrieve information about them from youtube)
 * lxml module for python
 

+ 63 - 0
lib_stov/helpers.py

@@ -22,6 +22,7 @@ import gettext
 import os
 import sys
 import signal
+import argparse
 
 
 def initialize_gettext():
@@ -68,3 +69,65 @@ def setup_sighandler():
     """
     signal.signal(signal.SIGTERM, sighandler)
     signal.signal(signal.SIGINT, sighandler)
+
+
+def parse_arguments():
+    """
+    Uses the argument parser to parse command line arguments and return them
+
+    :return: parsed arguments
+    :rtype: argparser.ArgumentParser
+    """
+    parser = argparse.ArgumentParser(conflict_handler="resolve")
+    parser.add_argument("-h", "--help", action="store_true", dest="help",
+                        help=_("show this help message and exit"))
+    parser.add_argument("-a", "--add", dest="add", action="store_true",
+                        help=_("Add a new subscription (requires either \
+                        --search, --channel or --playlist)"))
+    parser.add_argument("-p", "--playlist", dest="playlist",
+                        help=_("Add a new Playlist subscription (requires "
+                               "add)"))
+    parser.add_argument("-l", "--lssubs", action="store_true", dest="list",
+                        help=_("List the currently available subscriptions"))
+    parser.add_argument("-r", "--remove", type=int, dest="deleteid",
+                        help=_("remove a subscription"))
+    parser.add_argument("-u", "--update", action="store_true", dest="update",
+                        help=_(
+                            "update the information about the available "
+                            "videos"))
+    parser.add_argument("-d", "--download", action="store_true",
+                        dest="download", help=_("download all available "
+                                                "videos which haven't already"
+                                                " been downloaded"))
+    parser.add_argument("-s", "--search", dest="searchparameter",
+                        help=_("optionally add a search string to a new "
+                               "channel subscription or create a new search"
+                               " subscription (requires --add)"))
+    parser.add_argument("-l", "--lsvids", type=int, dest="subscriptionid",
+                        help=_("Print all videos from a subscription"))
+    parser.add_argument("-c", "--catchup", dest="catchup",
+                        help=_("Mark all videos from one channel as read \
+                        (requires subscription-id as argument)"))
+    parser.add_argument("-c", "--channel", dest="channel",
+                        help=_("specify a channel for a new subscription "
+                               "(requires --add)"))
+    parser.add_argument("-l", "--license", dest="license", action="store_true",
+                        help=_("show the license of the program"))
+    parser.add_argument("-v", "--version", dest="version", action="store_true",
+                        help=_("show the current running version number"))
+    parser.add_argument("-q", "--quiet", dest="quiet", action="store_true",
+                        help=_("Suppress all output"))
+    parser.add_argument("-v", "--verbose", dest="verbose", action="store_true",
+                        help=_("Be verbose and print also diagnostic "
+                               "messages"))
+    parser.add_argument("-c", "--clean-database", dest="cleanup",
+                        action="store_true",
+                        help=_("Clean the database of entries "
+                               "no longer listed in the current API response"))
+    parser.add_argument("-e", "--enable", type=int, dest="enableid",
+                        help=_("enables the subscription with the "
+                               "provided ID"))
+    parser.add_argument("--disable", type=int, dest="disableid",
+                        help=_("disables the subscription with the "
+                               "provided ID"))
+    return parser

+ 41 - 121
stov

@@ -32,7 +32,6 @@ import subprocess
 import socket
 from email.mime.multipart import MIMEMultipart
 from email.mime.text import MIMEText
-from optparse import OptionParser
 
 from lib_stov import subscription
 from lib_stov import configuration
@@ -43,87 +42,8 @@ from lib_stov import helpers
 
 helpers.initialize_gettext()
 helpers.setup_sighandler()
-
-# Overwrite the default OptionParser class so error messages
-# can be localized
-
-
-class MyOptionParser(OptionParser):
-    """Custom class overriding the OptionParser class."""
-    def error(self, parser_msg):
-        if "invalid integer" in parser_msg:
-            print(_("option %s requires an integer value")
-                  % parser_msg.split()[1], file=sys.stderr)
-            self.exit()
-        elif "an argument" in parser_msg:
-            print(_("option %s requires an argument") % parser_msg.split()[0],
-                  file=sys.stderr)
-            self.exit()
-        elif "no such" in parser_msg:
-            print(_("invalid option %s") % parser_msg.split()[3],
-                  file=sys.stderr)
-            self.exit()
-        else:
-            print(parser_msg, file=sys.stderr)
-            self.exit()
-
-PARSER = MyOptionParser(usage=_("Usage: %prog [options]"), prog="stov",
-                        add_help_option=True, conflict_handler="resolve")
-
-PARSER.add_option("-h", "--help", action="store_true", dest="help",
-                  help=_("show this help message and exit"))
-PARSER.add_option("-a", "--add", dest="add", action="store_true",
-                  help=_("Add a new subscription (requires either \
-                  --search, --channel or --playlist)"))
-PARSER.add_option("-p", "--playlist", dest="playlist",
-                  help=_("Add a new Playlist subscription (requires add)"))
-PARSER.add_option("-l", "--lssubs", action="store_true", dest="list",
-                  help=_("List the currently available subscriptions"))
-PARSER.add_option("-r", "--remove", type="int", dest="deleteid",
-                  help=_("remove a subscription"))
-PARSER.add_option("-u", "--update", action="store_true", dest="update",
-                  help=_("update the information about the available videos"))
-PARSER.add_option("-d", "--download", action="store_true", dest="download",
-                  help=_("download all available videos which haven't already "
-                         "been downloaded"))
-PARSER.add_option("-s", "--search", dest="searchparameter",
-                  help=_("optionally add a search string to a new channel "
-                         "subscription or create a new search subscription "
-                         "(requires --add)"))
-PARSER.add_option("-l", "--lsvids", type="int", dest="subscriptionid",
-                  help=_("Print all videos from a subscription"))
-PARSER.add_option("-c", "--catchup", dest="catchup",
-                  help=_("Mark all videos from one channel as read \
-                  (requires subscription-id as argument)"))
-PARSER.add_option("-c", "--channel", dest="channel",
-                  help=_("specify a channel for a new subscription "
-                         "(requires --add)"))
-PARSER.add_option("-l", "--license", dest="license", action="store_true",
-                  help=_("show the license of the program"))
-PARSER.add_option("-v", "--version", dest="version", action="store_true",
-                  help=_("show the current running version number"))
-PARSER.add_option("-q", "--quiet", dest="quiet", action="store_true",
-                  help=_("Suppress all output"))
-PARSER.add_option("-v", "--verbose", dest="verbose", action="store_true",
-                  help=_("Be verbose and print also diagnostical messages"))
-PARSER.add_option("-c", "--clean-database", dest="cleanup",
-                  action="store_true", help=_("Clean the database of entries "
-                                              "no longer listed in the current"
-                                              " API response"))
-PARSER.add_option("-e", "--enable", type="int", dest="enableid",
-                  help=_("enables the subscription with the provided ID"))
-PARSER.add_option("--disable", type="int", dest="disableid",
-                  help=_("disables the subscription with the provided ID"))
-(OPTIONS, ARGUMENTS) = PARSER.parse_args()
-
-# Check if stov is run directly from command line since it shouldn't be
-# loaded as a module
-
-if __name__ != "__main__":
-    print("This file should not be imported as a module"
-          "please run it directly from command line")
-    sys.exit(1)
-
+PARSER = helpers.parse_arguments()
+ARGUMENTS = PARSER.parse_args()
 
 # Create the lock file which is used to determine if another instance is
 # already running by chance, the program shouldn't be run in this case since
@@ -168,7 +88,7 @@ if not os.access(os.environ['HOME'] + "/.stov", os.F_OK & os.W_OK):
     print(_("This seems to be the first time you run the programm, do "
             "you want to run the interactive assistant? (yes/no)"))
     CONF = configuration.Conf()
-    LOGGER = CONF.configure_logging(OPTIONS.verbose, OPTIONS.quiet)
+    LOGGER = CONF.configure_logging(ARGUMENTS.verbose, ARGUMENTS.quiet)
     TEMP_INPUT = input()
     if TEMP_INPUT == "yes":
         CONF.assist()
@@ -192,7 +112,7 @@ if not os.access(os.environ['HOME'] + "/.stov", os.F_OK & os.W_OK):
             LOGGER.error(error)
 else:
     CONF = configuration.Conf()
-    LOGGER = CONF.configure_logging(OPTIONS.verbose, OPTIONS.quiet)
+    LOGGER = CONF.configure_logging(ARGUMENTS.verbose, ARGUMENTS.quiet)
     if os.access(str(os.environ['HOME']) + "/.stov/stov.config", os.F_OK):
         LOGGER.debug(_("Migrating configuration from plain text to json."))
         CONF.migrate_config()
@@ -289,30 +209,30 @@ if CONF.values["youtube-dl"] == "":
 # Variable to save the text that is later sent as e-mail
 MAIL_CONTENT = []
 
-"""Check which options are given on the command line and
+"""Check which ARGUMENTS are given on the command line and
 run the corresponding code
 
 """
-if OPTIONS.add is True:
-    if OPTIONS.channel is not None and OPTIONS.searchparameter is None:
+if ARGUMENTS.add is True:
+    if ARGUMENTS.channel is not None and ARGUMENTS.searchparameter is None:
         NEW_SUBSCRIPTION = subscription.Sub(subscription_type="user",
-                                            name=OPTIONS.channel, conf=CONF)
-    elif OPTIONS.channel is not None and OPTIONS.searchparameter is not None:
+                                            name=ARGUMENTS.channel, conf=CONF)
+    elif ARGUMENTS.channel is not None and ARGUMENTS.searchparameter is not None:
         NEW_SUBSCRIPTION = subscription.Sub(subscription_type="user",
-                                            name=OPTIONS.channel,
-                                            search=OPTIONS.searchparameter,
+                                            name=ARGUMENTS.channel,
+                                            search=ARGUMENTS.searchparameter,
                                             conf=CONF)
-    elif OPTIONS.channel is None and OPTIONS.searchparameter is not None:
+    elif ARGUMENTS.channel is None and ARGUMENTS.searchparameter is not None:
         NEW_SUBSCRIPTION = subscription.Sub(subscription_type="search",
                                             name=_("Search_"),
-                                            search=OPTIONS.searchparameter,
+                                            search=ARGUMENTS.searchparameter,
                                             conf=CONF)
-    elif OPTIONS.playlist is not None:
-        if OPTIONS.searchparameter is not None:
+    elif ARGUMENTS.playlist is not None:
+        if ARGUMENTS.searchparameter is not None:
             LOGGER.error(_("Playlists do not support searching, the search "
                            "option will be ignored!"))
         NEW_SUBSCRIPTION = subscription.Sub(subscription_type="playlist",
-                                            name=OPTIONS.playlist,
+                                            name=ARGUMENTS.playlist,
                                             conf=CONF)
     else:
         LOGGER.error(_("None or invalid subscription type given, please check "
@@ -348,7 +268,7 @@ if OPTIONS.add is True:
                                    "database."), video.title)
     LOGGER.info(_("New subscription ") + NEW_SUBSCRIPTION.get_title() +
                 _(" successfully added"))
-elif OPTIONS.list is True:
+elif ARGUMENTS.list is True:
     LIST_OF_SUBSCRIPTIONS = DB.get_subscriptions(CONF)
     SUB_STATE = None
     if len(LIST_OF_SUBSCRIPTIONS) != 0:
@@ -362,9 +282,9 @@ elif OPTIONS.list is True:
                         " (%s)" % SUB_STATE)
     else:
         LOGGER.info(_("No subscriptions added yet, add one!"))
-elif OPTIONS.deleteid is not None:
+elif ARGUMENTS.deleteid is not None:
     try:
-        DELETE_ID = int(OPTIONS.deleteid)
+        DELETE_ID = int(ARGUMENTS.deleteid)
     except ValueError:
         LOGGER.error(_("Invalid option, please use the ID of the subscription "
                        "you want to delete as parameter for the remove "
@@ -380,7 +300,7 @@ elif OPTIONS.deleteid is not None:
             sys.exit(1)
         else:
             LOGGER.info(_("Subscription deleted successfully!"))
-elif OPTIONS.update is True:
+elif ARGUMENTS.update is True:
     SUBSCRIPTIONS_LIST = DB.get_subscriptions(CONF)
     for element in SUBSCRIPTIONS_LIST:
         VIDEOS = DB.get_videos(element.get_id(), CONF)
@@ -404,7 +324,7 @@ elif OPTIONS.update is True:
                         LOGGER.debug(_("Video %s successfully inserted into "
                                        "database."), video.title)
 
-elif OPTIONS.download is True:
+elif ARGUMENTS.download is True:
     SUBSCRIPTIONS_LIST = DB.get_subscriptions(CONF)
     LOGGER.debug(_("Trying to determine the itag value for youtube-dl from"
                    " your quality and codec settings."))
@@ -502,9 +422,9 @@ elif OPTIONS.download is True:
                            "about new videos, please check the notify "
                            "parameter in your configuration."))
 
-elif OPTIONS.subscriptionid is not None:
+elif ARGUMENTS.subscriptionid is not None:
     try:
-        DATA = DB.get_subscription(OPTIONS.subscriptionid)
+        DATA = DB.get_subscription(ARGUMENTS.subscriptionid)
     except stov_exceptions.DBWriteAccessFailedException as error:
         LOGGER.error(error)
         sys.exit(1)
@@ -525,16 +445,16 @@ elif OPTIONS.subscriptionid is not None:
         else:
             LOGGER.error(_("Invalid subscription, please check the list and "
                            "try again."))
-elif OPTIONS.catchup is not None:
+elif ARGUMENTS.catchup is not None:
     try:
-        SUB_DATA = DB.get_subscription_title(OPTIONS.catchup)
+        SUB_DATA = DB.get_subscription_title(ARGUMENTS.catchup)
     except stov_exceptions.DBWriteAccessFailedException as error:
         LOGGER.error(error)
         sys.exit(1)
     else:
         if SUB_DATA != []:
             try:
-                DB.mark_video_downloaded(OPTIONS.catchup)
+                DB.mark_video_downloaded(ARGUMENTS.catchup)
             except stov_exceptions.DBWriteAccessFailedException as error:
                 LOGGER.error(error)
         else:
@@ -542,7 +462,7 @@ elif OPTIONS.catchup is not None:
                            "please check if the ID given is correct."))
 
 
-elif OPTIONS.cleanup is True:
+elif ARGUMENTS.cleanup is True:
     SUBSCRIPTION_LIST = DB.get_subscriptions(CONF)
     for element in SUBSCRIPTION_LIST:
         VIDEOS = DB.get_videos(element.get_id(), CONF)
@@ -560,42 +480,42 @@ elif OPTIONS.cleanup is True:
     except stov_exceptions.DBWriteAccessFailedException as error:
         LOGGER.error(error)
         sys.exit(1)
-elif OPTIONS.enableid is not None:
-    SUBSCRIPTION_STATE = DB.get_subscription(OPTIONS.enableid)
+elif ARGUMENTS.enableid is not None:
+    SUBSCRIPTION_STATE = DB.get_subscription(ARGUMENTS.enableid)
     try:
         if int(SUBSCRIPTION_STATE[0][6]) == 0:
             LOGGER.error(_("The subscription ID %s is already enabled."),
-                         OPTIONS.enableid)
+                         ARGUMENTS.enableid)
         elif int(SUBSCRIPTION_STATE[0][6]) == 1:
             try:
-                DB.change_subscription_state(OPTIONS.enableid, 0)
+                DB.change_subscription_state(ARGUMENTS.enableid, 0)
             except stov_exceptions.DBWriteAccessFailedException as error:
                 LOGGER.error(error)
                 sys.exit(1)
             else:
-                LOGGER.info(_("Enabled subscription ID %s."), OPTIONS.enableid)
+                LOGGER.info(_("Enabled subscription ID %s."), ARGUMENTS.enableid)
     except IndexError:
         LOGGER.error(_("Could not find the subscription with ID %s, "
-                       "please check and try again."), OPTIONS.enableid)
-elif OPTIONS.disableid is not None:
-    SUBSCRIPTION_STATE = DB.get_subscription(OPTIONS.disableid)
+                       "please check and try again."), ARGUMENTS.enableid)
+elif ARGUMENTS.disableid is not None:
+    SUBSCRIPTION_STATE = DB.get_subscription(ARGUMENTS.disableid)
     try:
         if int(SUBSCRIPTION_STATE[0][6]) == 1:
             LOGGER.error(_("Subscription ID %s is already disabled."),
-                         OPTIONS.disableid)
+                         ARGUMENTS.disableid)
         elif int(SUBSCRIPTION_STATE[0][6]) == 0:
             try:
-                DB.change_subscription_state(OPTIONS.disableid, 1)
+                DB.change_subscription_state(ARGUMENTS.disableid, 1)
             except stov_exceptions.DBWriteAccessFailedException as error:
                 LOGGER.error(error)
                 sys.exit(1)
             else:
                 LOGGER.info(_("Disabled subscription ID %s."),
-                            OPTIONS.disableid)
+                            ARGUMENTS.disableid)
     except IndexError:
         LOGGER.error(_("Could not find the subscription with ID %s, please"
-                       " check and try again."), OPTIONS.disableid)
-elif OPTIONS.license is True:
+                       " check and try again."), ARGUMENTS.disableid)
+elif ARGUMENTS.license is True:
     LOGGER.info("""
     stov is free software: you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
@@ -608,7 +528,7 @@ elif OPTIONS.license is True:
 
     You should have received a copy of the GNU General Public License
     along with stov.  If not, see <http://www.gnu.org/licenses/>.""")
-elif OPTIONS.version is True:
+elif ARGUMENTS.version is True:
     LOGGER.info("1.0wip")
 else:
     PARSER.print_help()