Refactor repetition creation function

This commit is contained in:
Marty Oehme 2021-08-30 23:38:49 +02:00
parent b9c08758f9
commit db0121966c
Signed by: Marty
GPG key ID: B7538B8F50A1C800

View file

@ -5,7 +5,7 @@ import re
def migrate(db, habitlist, events): def migrate(db, habitlist, events):
c = db.cursor() c = db.cursor()
habits = simple_habits_list(c, habitlist) habits = simple_habits_list(c, habitlist)
repetitions = extract_all_repetitions(habits, events) repetitions = get_all_repetitions(habits, events)
for rep in repetitions: for rep in repetitions:
add_to_database( add_to_database(
c, rep["id"], rep["timestamp"], 2 if "value" not in rep else rep["value"] 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 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. """Return list of all repetitions found of habits in events passed in.
Parameters: Parameters:
habits (list): Collection of habits, with minimum necessary fields description and id. habits (list): Collection of habits, with minimum necessary fields description and id.
@ -26,23 +26,34 @@ def extract_all_repetitions(habits, events):
""" """
repetitions = [] repetitions = []
for event in events: for event in events:
text = event["note"]
tags = extract_tags(text)
for habit in habits: for habit in habits:
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: for tag in tags:
if habit["description"] in tag[0]: if habit["description"] in tag[0]:
print( repetition = {"id": habit["id"], "timestamp": timestamp}
f"found repetition: {habit['name']} in {text} at {event['end']}"
)
repetitions.append({"id": habit["id"], "timestamp": event["end"]})
if tag[1]: if tag[1]:
print(f"repetition contains counter: {tag[0]} ({tag[1]})")
if "type" in habit and habit["type"] == 1: if "type" in habit and habit["type"] == 1:
repetitions[-1]["value"] = ( repetition["value"] = tag[1] * LOOP_RANGE_VALUE_MULTIPLIER
tag[1] * LOOP_RANGE_VALUE_MULTIPLIER reps.append(repetition)
) return reps
print(f"added counter to ranged habit.")
return repetitions
def extract_tags(text, tagmarker="#"): def extract_tags(text, tagmarker="#"):