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):
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,23 +26,34 @@ def extract_all_repetitions(habits, events):
"""
repetitions = []
for event in events:
text = event["note"]
tags = extract_tags(text)
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:
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"]})
repetition = {"id": habit["id"], "timestamp": timestamp}
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.")
return repetitions
repetition["value"] = tag[1] * LOOP_RANGE_VALUE_MULTIPLIER
reps.append(repetition)
return reps
def extract_tags(text, tagmarker="#"):