refactor header modules

This commit is contained in:
olari
2021-06-27 18:13:08 +03:00
parent 954e0c12af
commit 26232c60ae

View File

@@ -1,6 +1,6 @@
from copy import deepcopy from copy import deepcopy
from datetime import datetime, timedelta from datetime import datetime, timedelta
from functools import reduce, partial from functools import reduce, partial, cache
from pathlib import Path from pathlib import Path
from shutil import copyfile, rmtree from shutil import copyfile, rmtree
from subprocess import run from subprocess import run
@@ -116,6 +116,12 @@ def evaluate_time_expression(expression):
elif expression == 'yesterday': elif expression == 'yesterday':
return datetime.now() - timedelta(days=1) return datetime.now() - timedelta(days=1)
def get_abbr_for_weekday(date):
return {
0: 'mo', 1: 'tu', 2: 'we', 3: 'th',
4: 'fr', 5: 'sa', 6: 'su',
}[parse_date(date).weekday()]
### FILE PARSERS ### FILE PARSERS
def parse_foods_file(text): def parse_foods_file(text):
@@ -197,6 +203,18 @@ def parse_tasks_file(text):
return result return result
@cache
def get_godword(journal):
return journal['files']['godword'].strip().split('\n')
@cache
def get_habits(journal):
return journal['files']['habits'].strip().split('\n')
@cache
def get_tasks(journal):
return parse_tasks_file(journal['files']['tasks'])
### HACKY HACKERY ### HACKY HACKERY
_GLOBAL_DO_NOT_USE = {} _GLOBAL_DO_NOT_USE = {}
@@ -210,30 +228,7 @@ def get_foods_file():
### HEADER MODULES ### HEADER MODULES
def create_godword(journal, date): def get_notifications_for_date(journal, date):
words = journal['files']['godword'].strip().split('\n')
return [random.choice(words) for _ in range(20)]
def parse_godword(block):
return block.split()
def generate_godword(value):
return f"{' '.join(value[:10])}\n{' '.join(value[10:])}"
def create_habits(journal, date):
return {x: False for x in journal['files']['habits'].strip().split('\n')}
def parse_habits(block):
result = {}
for habit in block.splitlines():
value, name = habit.split(maxsplit=1)
result[name.strip()] = value[1] == 'x'
return result
def generate_habits(value):
return '\n'.join(f'[{"x" if v else "-"}] {k}' for k,v in value.items())
def create_notifications(journal, date):
notifications = [] notifications = []
for day in journal['days'].values(): for day in journal['days'].values():
@@ -248,47 +243,69 @@ def create_notifications(journal, date):
return notifications return notifications
def parse_notifications(notifications): def get_yesterdays_sticky(journal, date):
result = []
for notification in notifications.splitlines():
parts = notification.split()
result.append({
'source': int(parse_timestamp(' '.join(parts[0:2]).strip('[]')).timestamp()),
'message': ' '.join(parts[2:]),
})
return result
def generate_notifications(value):
return '\n'.join(f'[[{format_timestamp(n["source"])}]] {n["message"]}' for n in value)
def create_tasks(journal, date):
tasks = parse_tasks_file(journal['files']['tasks'])
curr_day = {
0: 'mo', 1: 'tu', 2: 'we', 3: 'th',
4: 'fr', 5: 'sa', 6: 'su',
}[parse_date(date).weekday()]
return {name: False for days, name in tasks if curr_day in days}
def parse_tasks(tasks):
result = {}
for task in tasks.splitlines():
value, name = task.split(maxsplit=1)
name = name.strip()
result[name] = value[1] == 'x'
return result
def generate_tasks(value):
return '\n'.join(f'[{"x" if v else "-"}] {k}' for k,v in value.items())
def create_sticky(journal, date):
yesterday = format_date(parse_date(date) - timedelta(days=1)) yesterday = format_date(parse_date(date) - timedelta(days=1))
if day := journal['days'].get(yesterday): if day := journal['days'].get(yesterday):
if sticky := day['header'].get('sticky'): if sticky := day['header'].get('sticky'):
return sticky return sticky
header_modules = {
'godword': (
lambda j, d: [random.choice(get_godword(j)) for _ in range(20)],
lambda b: b.split(),
lambda v: f"{' '.join(v[:10])}\n{' '.join(v[10:])}"
),
'habits': (
lambda j, d: {x: False for x in get_habits(j)},
lambda b: {
name.strip(): value[1] == 'x'
for (value, name) in [
line.split(maxsplit=1)
for line in b.splitlines()
]
},
lambda v: '\n'.join(f'[{"x" if v else "-"}] {k}' for k,v in v.items())
),
'notifications': (
lambda j, d: get_notifications_for_date(j, d),
lambda b: [{
'source': int(parse_timestamp(' '.join(parts[0:2]).strip('[]')).timestamp()),
'message': ' '.join(parts[2:]),
} for parts in [line.split() for line in b.splitlines()]],
lambda v: '\n'.join(f'[[{format_timestamp(n["source"])}]] {n["message"]}' for n in v)
),
'tasks': (
lambda j, d: {name: False for days, name in get_tasks(j) if get_abbr_for_weekday(d) in days},
lambda b: {
name.strip(): value[1] == 'x'
for (value, name) in [
line.split(maxsplit=1)
for line in b.splitlines()
]
},
lambda v: '\n'.join(f'[{"x" if v else "-"}] {k}' for k,v in v.items())
),
'sticky': (
lambda j, d: get_yesterdays_sticky(j, d),
identity,
identity
)
}
def create_header_module(name, journal, date):
return header_modules[name][0](journal, date)
def parse_header_module(name, block):
return header_modules[name][1](block)
def generate_header_module(name, value):
return header_modules[name][2](value)
### ENTRY MODULES ### ENTRY MODULES
def parse_timer(block): def parse_timer(block):
@@ -468,22 +485,11 @@ def generate_stats(page):
def create_header(journal, date): def create_header(journal, date):
return { return {
'godword': create_godword(journal, date), module: create_header_module(module, journal, date)
'habits': create_habits(journal, date), for module in header_modules
'notifications': create_notifications(journal, date),
'tasks': create_tasks(journal, date),
'sticky': create_sticky(journal, date),
} }
def parse_header(header): def parse_header(header):
header_modules = {
'godword': parse_godword,
'habits': parse_habits,
'notifications': parse_notifications,
'tasks': parse_tasks,
'sticky': identity,
}
def split_into_blocks(text): def split_into_blocks(text):
return [b.strip() for b in re.split(r'\n{2,}', text) if b.strip() != ''] return [b.strip() for b in re.split(r'\n{2,}', text) if b.strip() != '']
@@ -492,21 +498,13 @@ def parse_header(header):
result = {} result = {}
for module in modules: for module in modules:
name, value = module.split('\n', maxsplit=1) name, block = module.split('\n', maxsplit=1)
name = name.lower().removesuffix(':') name = name.lower().removesuffix(':')
result[name] = header_modules[name](value) result[name] = parse_header_module(name, block)
return result return result
def generate_header(header): def generate_header(header):
header_modules = {
'godword': generate_godword,
'habits': generate_habits,
'notifications': generate_notifications,
'tasks': generate_tasks,
'sticky': identity,
}
result = '' result = ''
for name, value in header.items(): for name, value in header.items():
@@ -514,7 +512,7 @@ def generate_header(header):
continue continue
result += f'\n\n{name.title()}:\n' result += f'\n\n{name.title()}:\n'
result += header_modules[name](value) result += generate_header_module(name, value)
return result return result