-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathlawgit.py
executable file
·401 lines (335 loc) · 13.1 KB
/
lawgit.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
#!/usr/bin/env python3
"""LawGit - Semi-automatic law change commits.
Usage:
lawgit.py autocommit <repopath> [--dry-run] [--consider-old] [--grep=<grep>]
lawgit.py -h | --help
lawgit.py --version
Options:
--dry-run Make a dry run.
--consider-old Consider old laws for commits.
-h --help Show this screen.
--version Show version.
Examples:
lawgit.py autocommit ../gesetze --dry-run
"""
import re
from pathlib import Path
import json
from datetime import datetime, timedelta
from collections import defaultdict
from git import Repo, Commit, DiffIndex, Diff
from git.exc import GitCommandError
from typing import List, Dict, Tuple
def log(*message: str):
print(datetime.now(), ":", *message)
class TransientState(Exception):
pass
class BGBlSource:
"""BGBl as a source for law change"""
change_re = [
re.compile(
r'BGBl +(?P<part>I+):? *(?P<year>\d{4}), +(?:S\. )?(?P<page>\d+)'),
re.compile(
r'BGBl +(?P<part>I+):? *(?P<year>\d{4}), \d \((?P<page>\d+)\)'),
re.compile(r'BGBl +(?P<part>I+):? *(?P<year>\d{4}), (?P<page>\d+)'),
re.compile(
r'\d{1,2}\.\.?\d{1,2}\.\.?(?P<year>\d{4}) (?P<part>I+) (?:S\. )?(?P<page>\d+)'),
re.compile(
r'(?P<year>\d{4}).{,8}?BGBl\.? +(?P<part>I+):? +(?:S\. )?(?P<page>\d+)'),
# re.compile(u'Art. \d+ G v. (?P<day>\d{1,2}).(?P<month>\d{1,2}).(?P<year>\d{4})')
]
transient = (
"noch nicht berücksichtigt",
"noch nicht abschließend bearbeitet"
)
def __init__(self, source):
self.load(source)
def __str__(self):
return self.__class__.__name__
def load(self, source):
self.data = {}
data = json.load(open(source))
for key, toc_list in data.items():
for toc in toc_list:
if toc['kind'] == 'meta':
continue
toc['part_i'] = 'I' * toc['part']
self.data[(toc['year'], toc['page'], toc['part'])] = toc
def find_candidates(self, lines: List[str]):
candidates = []
for line in lines:
for c_re in self.change_re:
for match in c_re.finditer(line):
if any(t in line for t in self.transient):
raise TransientState
matchdict = match.groupdict()
if 'page' in matchdict:
key = (
int(matchdict['year']),
int(matchdict['page']),
len(matchdict['part'])
)
if key in self.data:
candidates.append(key)
# elif 'month' in matchdict:
# for key, toc in self.data.iteritems():
# if toc['date'] == '{day:0>2}.{month:0>2}.{year}'.format(**matchdict):
# candidates.append(key)
return candidates
def get_order_key(self, key):
return self.get_date(key)
def get_date(self, key):
bgbl_entry = self.data[key]
return datetime.strptime(bgbl_entry['date'], '%d.%m.%Y')
def get_branch_name(self, key):
bgbl_entry = self.data[key]
return f"bgbl/{bgbl_entry['year']}/{bgbl_entry['part']}-{bgbl_entry['number']}"
def get_ident(self, key):
bgbl_entry = self.data[key]
return bgbl_entry['href']
def get_message(self, key):
bgbl_entry = self.data[key]
return ('%(name)s\n\n%(date)s: BGBl %(part_i)s: %(year)s, '
'%(page)s (Nr. %(number)s)' % bgbl_entry)
class BAnzSource:
"""BAnz as a source for law change"""
def __init__(self, source):
self.load(source)
def __str__(self):
return self.__class__.__name__
def load(self, source):
self.data = json.load(open(source))
def find_candidates(self, lines: List[str]) -> List[str]:
candidates: List[str] = []
for line in lines:
line = re.sub(r'[^\w \.]', '', line)
line = re.sub(r' \d{4} ', ' ', line)
for key in self.data:
if key in line:
if "noch nicht berücksichtigt" in line:
raise TransientState
candidates.append(key)
return candidates
def get_order_key(self, key):
return self.get_date(key)
def get_date(self, key):
entry = self.data[key]
return datetime.strptime(entry['date'], '%d.%m.%Y')
def get_branch_name(self, key):
entry = self.data[key]
date_parts = entry['date'].split('.')
return f"banz/{date_parts[2]}/{'-'.join(reversed(date_parts[:2]))}"
def get_ident(self, key):
return key
def get_message(self, key):
entry = dict(self.data[key])
additional_str = ', '.join(entry['additional'])
if additional_str:
entry['additional_str'] = f', {additional_str}'
else:
entry['additional_str'] = ''
return ('%(name)s\n\n%(date)s: %(ident)s, %(public_body)s'
'%(additional_str)s' % entry)
class VkblSource:
"""VkBl as a source for law change"""
transient = (
"noch nicht berücksichtigt",
"noch nicht abschließend bearbeitet"
)
change_re = [
re.compile(r'VkBl: *(?P<year>\d{4}),? +(?:S\. )?(?P<page>\d+)')
]
def __init__(self, source):
self.load(source)
def __str__(self):
return self.__class__.__name__
def load(self, source):
self.data = {}
data = json.load(open(source))
for key, value in data.items():
if value['jahr'] and value['seite']:
ident = (int(value['jahr']), int(value['seite']))
value['date'] = value['verffentlichtam']
self.data[ident] = value
def find_candidates(self, lines):
candidates = []
for line in lines:
for c_re in self.change_re:
for match in c_re.finditer(line):
if any(t in line for t in self.transient):
raise TransientState
matchdict = match.groupdict()
key = (
int(matchdict['year']),
int(matchdict['page']),
)
if key in self.data:
candidates.append(key)
return candidates
def get_order_key(self, key):
return self.get_date(key)
def get_date(self, key):
entry = self.data[key]
return datetime.strptime(entry['verffentlichtam'], '%d.%m.%Y')
def get_branch_name(self, key):
entry = self.data[key]
date_parts = entry['verffentlichtam'].split('.')
return f"vkbl/{date_parts[2]}/{'-'.join(reversed(date_parts[:2]))}"
def get_ident(self, key):
return key
def get_message(self, key):
"""
{
u'description': u'',
u'vid': u'19463',
u'seite': u'945',
u'price': 3.4,
u'edition': u'23/2012',
u'aufgehobenam': u'',
'date': u'15.12.2012',
u'verffentlichtam': u'15.12.2012',
u'pages': 9,
u'title': u'Verordnung \xfcber die Betriebszeiten der Schleusen ...',
u'jahr': u'2012', u'inkraftab': u'01.01.2013',
u'verkndetam': u'22.11.2012',
u'link': u'../shop/in_basket.php?vID=19463',
u'aktenzeichen': u'',
u'genre': u'Wasserstra\xdfen,
Schifffahrt',
u'vonummer': u'215'
}"
"""
entry = dict(self.data[key])
return (f"{entry['title']}\n\n{entry['verkndetam']}: {entry['edition']} S. {entry['seite']} ({entry['vonummer']})")
class LawGit:
laws = defaultdict(list)
law_changes: Dict[str, Tuple[bool, str, Path]] = {}
bgbl_changes = defaultdict(list)
def __init__(self, path, dry_run=False, consider_old=False, grep=None):
self.path = Path(path)
self.dry_run = dry_run
self.grep = grep
self.consider_old = consider_old
self.repo = Repo(path)
self.sources = [
BGBlSource('data/bgbl.json'),
BAnzSource('data/banz.json'),
VkblSource('data/vkbl.json')
]
def prepare_commits(self):
branches = defaultdict(dict)
self.collect_laws()
for law in self.laws:
result = self.determine_source(law)
if result is None:
continue
source, key = result
date = source.get_date(key)
if not self.consider_old and date + timedelta(days=30 * 12) < datetime.now():
log(f"Skipped {law} {result} (too old)")
continue
branch_name = source.get_branch_name(key)
ident = source.get_ident(key)
branches[branch_name].setdefault(ident, [])
branches[branch_name][ident].append((law, source, key))
return branches
def collect_laws(self):
hcommit: Commit = self.repo.head.commit
wdiff: DiffIndex = hcommit.diff(None, create_patch=True)
for diff in wdiff:
diff: Diff
if diff.b_blob:
law_name = diff.b_blob.path.split('/')[1]
if self.grep and self.grep not in law_name:
continue
filename = '/'.join(diff.b_blob.path.split('/')
[:2] + ['index.md'])
filename = self.path / filename
if filename.exists():
self.laws[law_name].append(diff.b_blob.path)
self.law_changes[law_name] = (
False, diff.diff.decode(), filename)
else:
log("Found deleted law?")
for filename in self.repo.untracked_files:
law_name = filename.split('/')[1]
if self.grep and self.grep not in law_name:
continue
self.laws[law_name].append(filename)
filename = '/'.join(filename.split('/')[:2] + ['index.md'])
filename = self.path / filename
with open(filename) as f:
self.law_changes[law_name] = (True, f.read(), filename)
def determine_source(self, law_name):
new_file, text, filename = self.law_changes[law_name]
lines: List[str] = [line for line in text.splitlines()]
candidates = self.find_in_sources(lines)
if not candidates:
with open(filename) as f:
lines = [line for line in f.read().splitlines()]
candidates.extend(self.find_in_sources(lines))
if not candidates:
return None
return sorted(candidates, key=lambda x: x[0].get_order_key(x[1]))[-1]
def find_in_sources(self, lines: List[str]):
candidates = []
for source in self.sources:
try:
candidates.extend([(source, c)
for c in source.find_candidates(lines)])
except TransientState:
return []
return candidates
def autocommit(self):
branches = self.prepare_commits()
for branch in sorted(branches.keys()):
self.commit_branch(branch, branches[branch])
def commit_branch(self, branch, commits):
if not self.dry_run:
self.repo.git.stash()
try:
log(f"git checkout -b {branch}")
if not self.dry_run:
self.repo.git.checkout(b=branch)
except GitCommandError:
log(f"git checkout {branch}")
if not self.dry_run:
self.repo.git.checkout(branch)
if not self.dry_run:
self.repo.git.merge('master')
self.repo.git.stash('pop')
for ident in commits:
for law_name, source, key in commits[ident]:
for filename in self.laws[law_name]:
if (self.path / filename).exists():
log(f"git add {filename}")
if not self.dry_run:
self.repo.index.add([str(filename)])
else:
log(f"git rm {str(filename)}")
if not self.dry_run:
self.repo.index.remove([str(filename)])
msg = source.get_message(key)
log(f'git commit -m"{msg}"')
if not self.dry_run:
self.repo.index.commit(msg)
log("")
log("git checkout master")
if not self.dry_run:
self.repo.heads.master.checkout()
log(f"git merge {branch} --no-ff")
if not self.dry_run:
self.repo.git.merge(branch, no_ff=True)
def main(arguments):
kwargs = {
'dry_run': arguments['--dry-run'],
'consider_old': arguments['--consider-old'],
'grep': arguments['--grep']
}
lg = LawGit(arguments['<repopath>'], **kwargs)
if arguments['autocommit']:
lg.autocommit()
if __name__ == '__main__':
from docopt import docopt
arguments = docopt(__doc__, version='LawGit 0.0.2')
main(arguments)