From dbe6b77e317372fceaa1125793caa94bdc194aca Mon Sep 17 00:00:00 2001 From: "Maxence G. de Montauzan" Date: Fri, 20 Jul 2018 21:31:41 +0200 Subject: [PATCH] Improve command handler + doc strstr --- pits.py | 47 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/pits.py b/pits.py index d2882d0..77d13f4 100644 --- a/pits.py +++ b/pits.py @@ -27,11 +27,27 @@ def get_file_path(file_name): def strstr(haystack, needle): + """ + Return a sub-string of haystack, going from first occurence of needle until the end. + Return None if not found. + + Arguments: + haystack {string} -- the entry string + needle {string} -- the part of string searched + + Returns: + string -- sub-string of haystack, starting from needle. None if not exist. + + Examples: + email = 'name@example.com' + domain = strstr(email, '@'); + print(domain) // Display : @example.com + """ pos = haystack.find(needle) if pos < 0: # not found return None - else: - return haystack[pos:] + + return haystack[pos:] def create_connection(db_filename): db_path = get_file_path(db_filename) @@ -103,15 +119,16 @@ def pit_help(args, *_): # TODO help def main(): - command = [ 'project', 'task', 'note', 'log', 'info', 'help', 'version', 'init' ] - handler = [ - project.handle_project, - task.handle_task, - note.handle_note, - action.handle_action, - info, - pit_help, - version] + cmd_handler = [ + ('project', project.handle_project), + ('task', task.handle_task), + ('note', note.handle_note), + ('log', action.handle_action), + ('info', info), + ('help', pit_help), + ('version', version), + ('init', init) + ] candidate = -1 argv = sys.argv @@ -120,8 +137,8 @@ def main(): argv.append('help') argv.append(None) - for i in range(len(command)): - if strstr(command[i], argv[1]) == command[i]: + for i in range(len(cmd_handler)): + if strstr(cmd_handler[i][0], argv[1]) == cmd_handler[i][0]: if candidate < 0: candidate = i else: @@ -132,7 +149,7 @@ def main(): print("Invalid command ({}), run '{} help' for help".format(argv[1], os.path.basename(__file__))) sys.exit(1) - if candidate == (len(command) -1): + if candidate == (len(cmd_handler) -1): init() sys.exit(0) @@ -141,7 +158,7 @@ def main(): logging.debug('Last action: {}'.format(last_action)) logging.debug(argv) logging.debug(argv[2:]) - handler[candidate](argv[2:], last_action, conn) + cmd_handler[candidate][1](argv[2:], last_action, conn) conn.commit() conn.close()