-
Notifications
You must be signed in to change notification settings - Fork 0
/
mjlib.py
86 lines (73 loc) · 2.74 KB
/
mjlib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env python
#
# helper functions for multijournal
#
import os, datetime
USERNAME = 'askhader'
LOCALDIR = '/scratch/mj/'
JSPATH = '/home/' + USERNAME + LOCALDIR + 'js/'
def list_entries(jtitle):
"""Return a list of { 'title': str, 'eid': int, 'date': str }"""
j_path = JSPATH + jtitle
es = []
if os.path.exists(j_path):
for jf in [f for f in os.listdir(j_path) if f.isdigit()]:
jf_handle = open(j_path + "/" + jf, 'r')
entry_title = jf_handle.readline().rstrip()
entry_date = jf_handle.readline().rstrip()
es.append({'title': entry_title, 'date': entry_date, 'eid': jf})
jf_handle.close()
return sorted(es, key=lambda a: a['eid'])
else:
raise Exception()
def get_entry_count(jtitle):
"""Return an integer representing the number of entries in a journal"""
try:
return max([int(j) for j in os.listdir(JSPATH+jtitle.lower()) if\
j.isdigit()])
except ValueError:
return 0
def get_entry(jtitle, eid):
"""Return {'title': str, 'date': str}"""
efile = open(JSPATH + jtitle + "/" + eid, 'r')
etitle = efile.readline().rstrip()
edate = efile.readline().rstrip()
body = efile.read()
return {'title': etitle, 'date': edate, 'body': body}
def list_journals():
"""Return a list of { 'title': str, 'count': int, last_entry: str }"""
js = []
for j in [d for d in os.listdir(JSPATH) if os.path.isdir(JSPATH+d)]:
c = get_entry_count(j)
if c > 0:
last_entry_path = JSPATH + j + "/" + str(c)
entry_handle = open(last_entry_path, 'r')
entry_handle.readline().rstrip()
date = entry_handle.readline().rstrip()
else:
date = ''
js.append({'title': j, 'count': c, 'last_entry': date})
js = sorted(js, key=lambda x: x['last_entry'])
js.reverse()
return js
def mkjournal(jtitle):
"""Create a journal with the given title. Return a path to the manifest"""
tstr = jtitle + "\n" + str(datetime.datetime.now()) + "\n####\n"
stripped_path = JSPATH+jtitle.replace(' ', '_').lower()
os.mkdir(stripped_path)
new_object_path = stripped_path + '/manifest'
jmf = open(new_object_path, 'w')
jmf.write(tstr)
jmf.close()
return new_object_path
def mkentry(jtitle, title):
"""Create a new journal entry with given title. Return path to the entry"""
tstr = title + "\n" + str(datetime.datetime.now()) + "\n####\n"
count = get_entry_count(jtitle)
stripped_title = jtitle.replace(' ', '_').lower()
new_object_path = JSPATH + stripped_title + "/" + str(count+1)
ef = open(new_object_path, 'w')
ef.write(tstr)
ef.close()
return new_object_path
#def journal_exists(jtitle):