Move functional sections to functions in main()

To make main() function less complicated functional sections are moved
to dedicated functions

Related Task: [https://fs.golderweb.de/index.php?do=details&task_id=82 FS#82]
This commit is contained in:
2016-08-27 15:18:17 +02:00
parent 460d2db183
commit 3540cc2a7d

151
red.py
View File

@@ -34,23 +34,17 @@ from pywikibot import pagegenerators
import jogobot import jogobot
def main(*args): # noqa (temp) def active(task_slug):
""" """
Process command line arguments and invoke bot. Checks up if bot with given task_slug is active via jogobot.framework
If args is an empty list, sys.argv is used. @param task_slug Task slug to check
@type task_slug str
@param args: command line arguments @return True if active, otherwise False
@type args: list of unicode @rtype bool
""" """
# Process global arguments to determine desired site
local_args = pywikibot.handle_args(args)
# Get the jogobot-task_slug (basename of current file without ending)
task_slug = os.path.basename(__file__)[:-len(".py")]
# Before run, we need to check wether we are currently active or not
try: try:
# Will throw Exception if disabled/blocked # Will throw Exception if disabled/blocked
# jogobot.is_active( task_slug ) # jogobot.is_active( task_slug )
@@ -60,14 +54,35 @@ def main(*args): # noqa (temp)
(type, value, traceback) = sys.exc_info() (type, value, traceback) = sys.exc_info()
jogobot.output( "\03{lightpurple} %s (%s)" % (value, type ), jogobot.output( "\03{lightpurple} %s (%s)" % (value, type ),
"CRITICAL" ) "CRITICAL" )
return False
except jogobot.jogobot.Disabled: except jogobot.jogobot.Disabled:
(type, value, traceback) = sys.exc_info() (type, value, traceback) = sys.exc_info()
jogobot.output( "\03{red} %s (%s)" % (value, type ), jogobot.output( "\03{red} %s (%s)" % (value, type ),
"ERROR" ) "ERROR" )
return False
# Bot/Task is active # Bot/Task is active
else: else:
return True
def parse_local_args( local_args ):
"""
Parses local cmd args which are not parsed by pywikibot
@param local_args Local args returned by pywikibot.handle_args(args)
@type iterable
@returns The following tuple
@return 1 Slug of given subtask (Arg "-task")
@rtype str
@return 2 GenFactory with parsed pagegenerator args
@rtype pagegenerators.GeneratorFactory
@return 3 Additional args for subtasks
@rtype dict
@rtype tuple
"""
# This factory is responsible for processing command line arguments # This factory is responsible for processing command line arguments
# that are also used by other scripts and that determine on which pages # that are also used by other scripts and that determine on which pages
@@ -102,7 +117,39 @@ def main(*args): # noqa (temp)
else: else:
genFactory.handleArg(arg) genFactory.handleArg(arg)
# After parsing args we can select bot to run # Return Tuple
return ( subtask, genFactory, kwargs )
def prepare_bot( task_slug, subtask, genFactory, subtask_args ):
"""
Handles importing subtask Bot class and prepares specific args
Throws exception if bot not exists
@param task_slug Task slug, needed for logging
@type task_slug str
@param subtask Slug of given subtask
@type subtask str
@param genFactory GenFactory with parsed pagegenerator args
@type genFactory pagegenerators.GeneratorFactory
@param subtask_args Additional args for subtasks
@type subtask_args dict\
@returns The following tuple
@return 1 Subtask slug (replaced None for default)
@rtype str
@return 2 Botclass of given subtask (Arg "-task")
@rtype Class
@return 3 GenFactory with parsed pagegenerator args
@rtype pagegenerators.GeneratorFactory
@return 4 Additional args for subtasks
@rtype dict
@rtype tuple
"""
# kwargs are passed to selected bot as **kwargs
kwargs = dict()
if not subtask or subtask == "discparser": if not subtask or subtask == "discparser":
# Default case: discparser # Default case: discparser
subtask = "discparser" subtask = "discparser"
@@ -110,12 +157,37 @@ def main(*args): # noqa (temp)
# Import related bot # Import related bot
from bots.reddiscparser import DiscussionParserBot as Bot from bots.reddiscparser import DiscussionParserBot as Bot
# # Subtask error
else: else:
jogobot.output( ( jogobot.output( (
"\03{{red}} Given subtask \"{subtask} \"" + "\03{{red}} Given subtask \"{subtask} \"" +
"is not existing!" ).format( subtask=subtask ), "ERROR" ) "is not existing!" ).format( subtask=subtask ), "ERROR" )
raise Exception
return ( subtask, Bot, genFactory, kwargs )
def init_bot( task_slug, subtask, Bot, genFactory, **kwargs ):
"""
Initiates Bot-Object with Class given in Bot and passes params genFactory
and kwargs to it
Passes through exception generated by Bot.__init__() after logging.
@param task_slug Task slug, needed for logging
@type task_slug str
@param subtask Slug of given subtask
@type subtask str
@param Bot Bot class to build bot-object from
@type Class
@param genFactory GenFactory with parsed pagegenerator args
@type genFactory pagegenerators.GeneratorFactory
@param **kwargs Additional args for Bot()
@type **kwargs dict
@returns bot-object
@type type(Bot())
"""
# Bot gets prepared genFactory as first param and possible kwargs dict # Bot gets prepared genFactory as first param and possible kwargs dict
# It has to threw an exception if something does not work properly # It has to threw an exception if something does not work properly
try: try:
@@ -135,6 +207,23 @@ def main(*args): # noqa (temp)
"Subtask \"{task_slug}-{subtask}\" was " + "Subtask \"{task_slug}-{subtask}\" was " +
"initiated successfully" ). "initiated successfully" ).
format(task_slug=task_slug, subtask=subtask) ) format(task_slug=task_slug, subtask=subtask) )
return bot
def run_bot( task_slug, subtask, bot ):
"""
Calls the run()-method of bot-object
Passes through exceptions generated by Bot.__init__() after logging.
Catches Errors caused by missing run(0-method.
@param task_slug Task slug, needed for logging
@type task_slug str
@param subtask Slug of given subtask
@type subtask str
@param bot Bot object to call run()-method on
@type object with method run
"""
# Fire up Bot # Fire up Bot
# Bot must have implemented a run()-method # Bot must have implemented a run()-method
@@ -173,5 +262,39 @@ def main(*args): # noqa (temp)
format(task_slug=task_slug, subtask=subtask) ) format(task_slug=task_slug, subtask=subtask) )
def main(*args):
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
@param args: command line arguments
@type args: list of unicode
"""
# Process global arguments to determine desired site
local_args = pywikibot.handle_args(args)
# Get the jogobot-task_slug (basename of current file without ending)
task_slug = os.path.basename(__file__)[:-len(".py")]
# Before run, we need to check wether we are currently active or not
if not active( task_slug ):
return
# Parse local Args to get information about subtask
( subtask, genFactory, subtask_args ) = parse_local_args( local_args )
# select subtask and prepare args
( subtask, Bot, genFactory, kwargs ) = prepare_bot(
task_slug, subtask, genFactory, subtask_args )
# Init Bot
bot = init_bot( task_slug, subtask, Bot, genFactory, **kwargs)
# Run bot
run_bot( task_slug, subtask, bot )
if( __name__ == "__main__" ): if( __name__ == "__main__" ):
main() main()