From db0121966c97471c9e3a518fccfee45adec4c49e Mon Sep 17 00:00:00 2001 From: Marty Oehme Date: Mon, 30 Aug 2021 23:38:49 +0200 Subject: [PATCH] Refactor repetition creation function --- loop/repetitions.py | 45 ++++++++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 17 deletions(-) diff --git a/loop/repetitions.py b/loop/repetitions.py index 4567e7a..c7c06f6 100644 --- a/loop/repetitions.py +++ b/loop/repetitions.py @@ -5,7 +5,7 @@ import re def migrate(db, habitlist, events): c = db.cursor() habits = simple_habits_list(c, habitlist) - repetitions = extract_all_repetitions(habits, events) + repetitions = get_all_repetitions(habits, events) for rep in repetitions: add_to_database( c, rep["id"], rep["timestamp"], 2 if "value" not in rep else rep["value"] @@ -15,7 +15,7 @@ def migrate(db, habitlist, events): LOOP_RANGE_VALUE_MULTIPLIER = 1000 -def extract_all_repetitions(habits, events): +def get_all_repetitions(habits, events): """Return list of all repetitions found of habits in events passed in. Parameters: habits (list): Collection of habits, with minimum necessary fields description and id. @@ -26,25 +26,36 @@ def extract_all_repetitions(habits, events): """ repetitions = [] for event in events: - text = event["note"] - tags = extract_tags(text) for habit in habits: - for tag in tags: - if habit["description"] in tag[0]: - print( - f"found repetition: {habit['name']} in {text} at {event['end']}" - ) - repetitions.append({"id": habit["id"], "timestamp": event["end"]}) - if tag[1]: - print(f"repetition contains counter: {tag[0]} ({tag[1]})") - if "type" in habit and habit["type"] == 1: - repetitions[-1]["value"] = ( - tag[1] * LOOP_RANGE_VALUE_MULTIPLIER - ) - print(f"added counter to ranged habit.") + reps = tags_to_repetitions(habit, extract_tags(event["note"]), event["end"]) + if reps: + repetitions.extend(reps) + return repetitions +def tags_to_repetitions(habit, tags, timestamp): + """Return a list of all repetitions generated from the tags and habits passed in. + Parameters: + habits (list): Collection of habits, with minimum necessary fields description and id. + tags (list): Collection of tag tuples. + Returns: + repetitions (list): Collection of habits for which a corresponding tag has + been found. If they correspond that means at the timestamp + the habit has been checked in, and a repetition is created. + Contains fields id, timestamp, value (for ranges). + """ + reps = [] + for tag in tags: + if habit["description"] in tag[0]: + repetition = {"id": habit["id"], "timestamp": timestamp} + if tag[1]: + if "type" in habit and habit["type"] == 1: + repetition["value"] = tag[1] * LOOP_RANGE_VALUE_MULTIPLIER + reps.append(repetition) + return reps + + def extract_tags(text, tagmarker="#"): """Return lists of tuples of all event tags found in text. Parameters: