-
Notifications
You must be signed in to change notification settings - Fork 0
/
xm_rst_to_timesheet_estimation.py
executable file
·249 lines (197 loc) · 7.76 KB
/
xm_rst_to_timesheet_estimation.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
#!/usr/bin/env python
# -*- coding: utf-8 vi:noet
# Gets worked hours from a rst document
import sys, os, re, datetime, decimal, logging
import docutils
import docutils.nodes
import docutils.utils
import docutils.parsers.rst
import docutils.frontend
import datetimeparse
logger = logging.getLogger(__name__)
def process(filename, date_range, match_title=lambda x: True, match=lambda x: True):
settings = docutils.frontend.OptionParser(
components=(docutils.parsers.rst.Parser,)) \
.get_default_values()
document = docutils.utils.new_document(filename, settings)
parser = docutils.parsers.rst.Parser()
with open(filename, "rb") as f:
input = f.read().decode('utf-8')
parser.parse(input, document)
class V_time(object):
def __init__(self, document, date_range):
self.document = document
self.entries = []
self.date = None
self.date_range = date_range
self.min_date = date_range[0]
self.max_date = date_range[1]
logger.debug(self.min_date)
logger.debug(self.max_date)
def visit(self, node):
#logger.debug(node)
pass
def dispatch_visit(self, node):
#logger.debug(node)
if node.__class__ == docutils.nodes.section:
title = node.children[0].rawsource
m = re.match(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2}) \((?P<weekday>Mon|Tue|Wed|Thu|Fri|Sat|Sun)\)", title)
if m is None:
#logger.debug("Skipping %s" % title)
return
def toi(x): return int(m.group(x))
self.date = datetime.datetime(year=toi("y"), month=toi("m"), day=toi("d"))
self.date = self.date.replace(second=1)
# Validate day
weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
weekday = weekdays.index(m.group("weekday"))
assert weekday == self.date.weekday(), "Wrong date: {}, DoW should be {}".format(title, self.date.weekday())
if node.__class__ == docutils.nodes.admonition:
title = node.children[0].rawsource
if not match_title(title):
return
assert self.date is not None, "Sonna bakana!"
logger.debug("- %s" % self.date.strftime("%Y-%m-%d"))
assert node.children[1].__class__ == docutils.nodes.bullet_list, node.children[1]
entries = node.children[1].children
dayjob = datetime.timedelta()
logger.debug(" - Entries:")
for entry in entries:
logger.debug(" - Entry:")
for idx_entry, c in enumerate(entry.children):
if idx_entry == 0 and not isinstance(c, docutils.nodes.paragraph):
raise RuntimeError(c.rawsource)
logger.debug(" - Child %s", c)
pr = entry.children[0].rawsource.replace("\n", " ") + entry.rawsource[len(entry.children[0].rawsource)+1:].replace("\n", "\\n")
def cleanup(s):
p_jira = re.compile("https://\S+.atlassian.net/browse/")
s = p_jira.sub(lambda m: "", s)
p_gitlab = re.compile("https://gitlab.com/(?P<path>\S+?)/-/merge_requests/(?P<n>\S+)")
s = p_gitlab.sub(lambda m: m.group("path") + "!" + m.group("n"), s)
return s
pr = cleanup(pr)
p = pr
re_a = r"^From :time:`(?P<from>\d{2}:\d{2}:\d{2})` to :time:`(?P<to>\d{2}:\d{2}:\d{2})`[,:]?(?P<comment>.*)$"
m = re.match(re_a, p)
if m is not None:
tsf = m.group("from")
tst = m.group("to")
f = datetime.datetime.strptime(tsf, "%H:%M:%S")
f = f.replace(year=self.date.year, month=self.date.month, day=self.date.day)
t = datetime.datetime.strptime(tst, "%H:%M:%S")
t = t.replace(year=self.date.year, month=self.date.month, day=self.date.day)
if t < f:
t += datetime.timedelta(hours=24)
if f < self.min_date:
f = self.min_date
if t > self.max_date:
t = self.max_date
dt = t-f
logging.debug(" - %s: %s" % (dt, pr))
if t > f and match(m.group("comment")):
dayjob += dt
logger.debug(" - %s: %s" % (dt, pr))
self.entries.append((self.date, dt, pr))
continue
re_a = r"^From :time:`(?P<from>\d{2}:\d{2})` to :time:`(?P<to>\d{2}:\d{2})`( less :time:`((?P<h>\d+(\.\d+)?)h)?((?P<m>\d+)m?)?`)?[,:]?(?P<comment>.*)$"
m = re.match(re_a, p)
if m is not None:
tsf = m.group("from")
tst = m.group("to")
f = datetime.datetime.strptime(tsf, "%H:%M")
f = f.replace(year=self.date.year, month=self.date.month, day=self.date.day)
t = datetime.datetime.strptime(tst, "%H:%M")
t = t.replace(year=self.date.year, month=self.date.month, day=self.date.day)
if t < f:
t += datetime.timedelta(hours=24)
if f < self.min_date:
f = self.min_date
if t > self.max_date:
t = self.max_date
dt = t-f
d = dict(m.groupdict())
h_ = float(d.get('h', 0) or 0)
m_ = float(d.get("m", 0) or 0)
dt -= datetime.timedelta(hours=h_, minutes=m_)
logging.debug(" - %s: %s" % (dt, pr))
if t > f and match(m.group("comment")):
dayjob += dt
logger.debug(" - %s: %s" % (dt, pr))
self.entries.append((self.date, dt, pr))
continue
re_a = r"^Estimated :time:`((?P<h>\d+(\.\d+)?)h)?((?P<m>\d+)m?)?`[,:]?\s*(?P<comment>.*)$"
m = re.match(re_a, p)
if m is not None:
d = dict(m.groupdict())
h_ = float(d.get('h', 0) or 0)
m_ = float(d.get("m", 0) or 0)
dt = datetime.timedelta(hours=h_, minutes=m_)
logging.debug(" - %s: %s" % (dt, pr))
if self.date >= self.min_date and self.date <= self.max_date and match(m.group("comment")):
dayjob += dt
logger.debug(" - %s: %s" % (dt, pr))
self.entries.append((self.date, dt, pr))
continue
assert False, p
logger.debug(" - Day total: %s" % datetimeparse.timedelta_str(dayjob))
def depart(self, node):
logger.debug(node)
class V_materials(object):
def __init__(self, document, date_range):
self.document = document
self.entries = []
self.date = None
self.date_range = date_range
self.min_date = date_range[0]
self.max_date = date_range[1]
logger.debug(self.min_date)
logger.debug(self.max_date)
def visit(self, node):
#logger.debug(node)
pass
def dispatch_visit(self, node):
#logger.debug(node)
if node.__class__ == docutils.nodes.section:
title = node.children[0].rawsource
m = re.match(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2}) \((Mon|Tue|Wed|Thu|Fri|Sat|Sun)\)", title)
if m is None:
#logger.debug("Skipping %s" % title)
return
def toi(x): return int(m.group(x))
self.date = datetime.datetime(year=toi("y"), month=toi("m"), day=toi("d"))
self.date = self.date.replace(second=1)
if node.__class__ == docutils.nodes.admonition:
title = node.children[0].rawsource
if not title.startswith("Expenses"):
return
assert self.date is not None, "Sonna bakana!"
logger.debug("- %s" % self.date.strftime("%Y-%m-%d"))
assert node.children[1].__class__ == docutils.nodes.bullet_list, node.children[1]
entries = node.children[1].children
day_exp = 0
logger.debug(" - Entries:")
for entry in entries:
assert len(entry.children) == 1, entry
assert entry.children[0].__class__ == docutils.nodes.paragraph
pr = entry.children[0].rawsource
p = pr.splitlines()[0]
pr = pr.replace("\n", " ")
re_a = r"^:materials:`(?P<amount>[\d.]+) ?(?P<currency>\S+)`,?.*$"
m = re.match(re_a, p)
if m is not None:
v = decimal.Decimal(m.group("amount"))
c = m.group("currency")
day_exp += v
logger.debug(" - %s: %s" % (v, pr))
if self.date >= self.min_date and self.date <= self.max_date:
self.entries.append((self.date, v, c))
continue
assert False, p
logger.debug(" - Day total: %s" % day_exp)
def depart(self, node):
logger.debug(node)
visitor_time = V_time(document, date_range)
document.walk(visitor_time)
visitor_materials = V_materials(document, date_range)
document.walk(visitor_materials)
return visitor_time.entries, visitor_materials.entries