forked from cfpb/regulations-xml-parser
/
regml.py.orig
executable file
·1322 lines (1109 loc) · 50.2 KB
/
regml.py.orig
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
"""
from __future__ import print_function
import glob
import json
import os
import sys
import click
from lxml import etree
from termcolor import colored, cprint
from regulation.validation import EregsValidator
import regulation.settings as settings
from regulation.tree import (build_analysis,
build_external_citations_layer,
build_formatting_layer,
build_graphics_layer,
build_internal_citations_layer,
build_interp_layer,
build_keyterm_layer,
build_meta_layer,
build_notice,
build_paragraph_marker_layer,
build_reg_tree,
build_terms_layer,
build_toc_layer)
from regulation.changes import (process_changes,
process_analysis,
generate_diff,
rectify_analysis)
# Import regparser here with the eventual goal of breaking off the parts
# we're using in the RegML parser into a library both can share.
from regparser.federalregister import fetch_notice_json
from regparser.builder import LayerCacheAggregator, tree_and_builder, Builder
from regparser.notice.compiler import compile_regulation
if (sys.version_info < (3, 0)):
reload(sys) # noqa
sys.setdefaultencoding('UTF8')
# Utility Functions ####################################################
def base_path(is_notice=False):
""" Return the base RegML path based on our configuration. """
regml_base = settings.XML_ROOT
if is_notice:
regml_base = os.path.join(regml_base, 'notice')
else:
regml_base = os.path.join(regml_base, 'regulation')
return regml_base
def find_file(file, is_notice=False, ecfr=False):
"""
Find the given file in sources available in configured
locations and read it.
For example, if we're looking for a RegML file for version
2222-33333 with the default arguments,
settings.XML_ROOT/regulation will be searched for a matching
document.
With ecfr=True and regml=False, eCFR fr-notices
(settings.LOCAL_XML_PATHS) will be searched.
"""
# See if we need to find this file somewhere
if not os.path.exists(file):
if ecfr:
ecfr_base = settings.LOCAL_XML_PATHS[0]
file = os.path.join(ecfr_base, file)
else:
file = os.path.join(base_path(is_notice=is_notice), file)
if not file.endswith('.xml') and not os.path.isdir(file):
file += '.xml'
return file
def find_all(part, is_notice=False):
""" Find all regulation RegML files for the given part.
If is_notice is True, all notice RegML files will be returned. """
regml_base = base_path(is_notice=is_notice)
regulation_pattern = os.path.join(regml_base, part, '*.xml')
files = glob.glob(regulation_pattern)
return files
def find_version(part, notice, is_notice=False):
""" Wrap find file in a semantic sort of way to find a RegML version
of a particular part """
return find_file(os.path.join(part, notice), is_notice=is_notice)
def write_layer(layer_object, reg_number, notice, layer_type,
diff_notice=None):
""" Write a layer. """
layer_path = os.path.join(settings.JSON_ROOT, layer_type, reg_number)
if diff_notice is not None:
layer_path = os.path.join(layer_path, diff_notice)
if not os.path.exists(layer_path):
os.makedirs(layer_path)
layer_file = os.path.join(layer_path, notice)
print("writing", layer_file)
json.dump(layer_object, open(layer_file, 'w'), indent=4,
separators=(',', ':'))
def get_validator(xml_tree, raise_instead_of_exiting=False):
# Validate the file relative to schema
validator = EregsValidator(settings.XSD_FILE)
validator.validate_reg(xml_tree)
if not validator.is_valid:
for event in validator.events:
print(str(event))
if raise_instead_of_exiting:
raise event
else:
sys.exit(0)
return validator
def generate_json(regulation_file, check_terms=False):
with open(find_file(regulation_file), 'r') as f:
reg_xml = f.read()
parser = etree.XMLParser(huge_tree=True)
xml_tree = etree.fromstring(reg_xml, parser)
# Validate the file relative to schema
validator = get_validator(xml_tree)
reg_tree = build_reg_tree(xml_tree)
reg_number = reg_tree.label[0]
paragraph_markers = build_paragraph_marker_layer(xml_tree)
internal_citations = build_internal_citations_layer(xml_tree)
external_citations = build_external_citations_layer(xml_tree)
terms = build_terms_layer(xml_tree)
meta = build_meta_layer(xml_tree)
toc = build_toc_layer(xml_tree)
keyterms = build_keyterm_layer(xml_tree)
graphics = build_graphics_layer(xml_tree)
formatting = build_formatting_layer(xml_tree)
interps = build_interp_layer(xml_tree)
analysis = build_analysis(xml_tree)
notice_dict = build_notice(xml_tree)
# if the validator had problems then we should report them and bail out
validator.validate_terms(xml_tree, terms)
validator.validate_internal_cites(xml_tree, internal_citations)
if check_terms:
validator.validate_term_references(xml_tree, terms, regulation_file)
for event in validator.events:
print(str(event))
reg_tree.include_children = True
reg_json = reg_tree.to_json()
notice = xml_tree.find('.//{eregs}documentNumber').text
version = os.path.split(regulation_file)[-1].replace('.xml', '')
if notice != version:
print('Notice ({}) different from version ({}), '
'using version'.format(notice, version))
notice = version
write_layer(reg_json, reg_number, notice, 'regulation')
write_layer(meta, reg_number, notice, 'layer/meta')
write_layer(paragraph_markers, reg_number, notice,
'layer/paragraph-markers')
write_layer(internal_citations, reg_number, notice,
'layer/internal-citations')
write_layer(external_citations, reg_number, notice,
'layer/external-citations')
write_layer(terms, reg_number, notice, 'layer/terms')
write_layer(toc, reg_number, notice, 'layer/toc')
write_layer(keyterms, reg_number, notice, 'layer/keyterms')
write_layer(graphics, reg_number, notice, 'layer/graphics')
write_layer(formatting, reg_number, notice, 'layer/formatting')
write_layer(interps, reg_number, notice, 'layer/interpretations')
write_layer(analysis, reg_number, notice, 'layer/analyses')
write_layer(notice_dict, reg_number, notice, 'notice')
return reg_number, notice, xml_tree
# Main CLI Commands ####################################################
# Create a general CLI that can take additional commands
@click.group()
def cli():
pass
# Perform validation on the given RegML file without any additional
# actions.
@cli.command('validate')
@click.argument('file')
@click.option('--no-terms', is_flag=True,
help="don't try to validate terms")
@click.option('--no-citations', is_flag=True,
help="don't try to validate citations")
@click.option('--no-keyterms', is_flag=True,
help="don't try to validate keyterms")
def validate(file, no_terms=False, no_citations=False, no_keyterms=False):
""" Validate a RegML file """
file = find_file(file)
with open(file, 'r') as f:
reg_xml = f.read()
parser = etree.XMLParser(huge_tree=True)
xml_tree = etree.fromstring(reg_xml, parser)
# Validate the file relative to schema
validator = get_validator(xml_tree)
# Validate regulation-specific documents
if xml_tree.tag == '{eregs}regulation':
terms = build_terms_layer(xml_tree)
internal_citations = build_internal_citations_layer(xml_tree)
if not no_terms:
validator.validate_terms(xml_tree, terms)
if not no_citations:
validator.validate_internal_cites(xml_tree, internal_citations)
if not no_keyterms:
validator.validate_keyterms(xml_tree)
for event in validator.events:
print(str(event))
# Validate notice-specific documents
if xml_tree.tag == '{eregs}notice':
pass
return validator
@cli.command('check-terms')
@click.argument('file')
@click.option('--label')
@click.option('--term')
@click.option('--with-notice')
def check_terms(file, label=None, term=None, with_notice=None):
""" Check the terms in a RegML file """
file = find_file(file)
with open(file, 'r') as f:
reg_string = f.read()
parser = etree.XMLParser(huge_tree=True)
reg_tree = etree.fromstring(reg_string, parser)
if reg_tree.tag == '{eregs}notice':
print("Cannot check terms in notice files directly.")
print("Use a regulation file and --with-notice to specify the notice that applies.")
sys.exit(1)
# If we're given a notice, apply it to the given regulation file,
# then check terms in the result and write it out to the notice file
# as changes.
notice_tree = None
if with_notice is not None:
# file is changed here so the term checker will write the notice
# instead of the regulation
file = find_file(with_notice, is_notice=True)
with open(file, 'r') as f:
notice_xml = f.read()
notice_tree = etree.fromstring(notice_xml)
# Process the notice changeset
print(colored('Applying notice...', attrs=['bold']))
reg_tree = process_changes(reg_tree, notice_tree)
# Validate the file relative to schema
validator = get_validator(reg_tree)
terms = build_terms_layer(reg_tree)
validator.validate_terms(reg_tree, terms)
validator.validate_term_references(reg_tree, terms, file,
label=label, term=term, notice=notice_tree)
@cli.command()
@click.argument('file')
@click.option('--label')
@click.option('--is-notice', is_flag=True)
def check_interp_targets(file, label=None, is_notice=False):
""" Check the interpretations targets in a RegML file """
file = find_file(file, is_notice=is_notice)
with open(file, 'r') as f:
reg_xml = f.read()
parser = etree.XMLParser(huge_tree=True)
xml_tree = etree.fromstring(reg_xml, parser)
# Validate the file relative to schema
validator = get_validator(xml_tree)
validator.validate_interp_targets(xml_tree, file, label=label)
@cli.command('check-changes')
@click.argument('file')
@click.option('--label')
def check_changes(file, label=None):
""" Check for duplicate changes in a notice RegML file """
file = find_file(file, is_notice=True)
with open(file, 'r') as f:
reg_xml = f.read()
parser = etree.XMLParser(huge_tree=True)
xml_tree = etree.fromstring(reg_xml, parser)
if xml_tree.tag != '{eregs}notice':
print("Can only check changes in notice files")
sys.exit(1)
# Validate the file relative to schema
validator = get_validator(xml_tree)
validator.remove_duplicate_changes(xml_tree, file, label=label)
validator.remove_empty_refs(xml_tree, file)
@cli.command('check-keyterms')
@click.argument('file')
@click.option('--with-notice')
def check_keyterms(file, with_notice=None):
""" Check for keyterm fragments in a RegML file
If --with-notice is used, only *new* keyterm fragments
introduced in the notice will be given. """
file = find_file(file)
with open(file, 'r') as f:
reg_string = f.read()
parser = etree.XMLParser(huge_tree=True)
reg_tree = etree.fromstring(reg_string, parser)
if reg_tree.tag == '{eregs}notice':
print("Cannot check terms in notice files directly.")
print("Use a regulation file and --with-notice to specify the notice that applies.")
sys.exit(1)
# If we're given a notice, apply it to the given regulation file,
# then check terms in the result and write it out to the notice file
# as changes.
notice_tree = None
if with_notice is not None:
# file is changed here so the term checker will write the notice
# instead of the regulation
file = find_file(with_notice, is_notice=True)
with open(file, 'r') as f:
notice_xml = f.read()
notice_tree = etree.fromstring(notice_xml)
# Process the notice changeset
print(colored('Applying notice...', attrs=['bold']))
reg_tree = process_changes(reg_tree, notice_tree)
# Validate the file relative to schema
validator = get_validator(reg_tree)
validator.validate_keyterms(reg_tree, notice_tree=notice_tree)
for event in validator.events:
print(str(event))
@cli.command('migrate-analysis')
@click.argument('cfr_title')
@click.argument('cfr_part')
def migrate_analysis(cfr_title, cfr_part):
""" Migrate analysis from its context to top-level """
# Prompt user to be sure they want to do this
print(colored('This will irrevocably modify all regulation and notice files for this regulation. '
'Is this ok?', 'red'))
answer = None
while answer not in ['y', 'n']:
answer = raw_input('Migrate all analysis? y/n: ')
if answer != 'y':
return
# Migrate regulation files
regml_reg_files = find_all(cfr_part)
for reg_file in regml_reg_files:
print(reg_file)
file_name = os.path.join(reg_file)
with open(file_name, 'r') as f:
reg_xml = f.read()
parser = etree.XMLParser(huge_tree=True)
xml_tree = etree.fromstring(reg_xml, parser)
validator = EregsValidator(settings.XSD_FILE)
validator.migrate_analysis(xml_tree, file_name)
validator.validate_reg(xml_tree)
# Migrate notices
regml_notice_files = find_all(cfr_part, is_notice=True)
regml_notices = []
for notice_file in regml_notice_files:
print(notice_file)
file_name = os.path.join(notice_file)
with open(file_name, 'r') as f:
reg_xml = f.read()
parser = etree.XMLParser(huge_tree=True)
xml_tree = etree.fromstring(reg_xml, parser)
validator = EregsValidator(settings.XSD_FILE)
validator.migrate_analysis(xml_tree, file_name)
validator.validate_reg(xml_tree)
#
@cli.command('fix-analysis')
@click.argument('file')
@click.option('--always-save', is_flag=True)
# @click.option('--label')
def fix_analysis(file, always_save=False):
"""Checks and fixes the analysis in a notice RegML file"""
file = find_file(file, is_notice=True)
with open(file, 'r') as f:
reg_xml = f.read()
parser = etree.XMLParser(huge_tree=True)
xml_tree = etree.fromstring(reg_xml, parser)
if xml_tree.tag != '{eregs}notice':
print("Can only check changes in notice files")
sys.exit(1)
# Parse through the analysis tree
print("Checking analysis tree")
new_xml_tree = rectify_analysis(xml_tree)
if new_xml_tree is None:
print(colored("ERROR: No analysis found in notice.",
attrs=['bold']))
return
# Validate the file relative to schema
print("Validating updated notice xml")
validator = get_validator(new_xml_tree)
print("Validation complete!")
# Write the new xml tree
new_xml_string = etree.tostring(new_xml_tree,
pretty_print=True,
xml_declaration=True,
encoding='UTF-8')
# Prompt user whether to update the notice
if always_save:
answer = "y"
else:
answer = None
while answer not in ["", "y", "n"]:
answer = raw_input('Save updated analysis to notice file? y/n [y] ')
if answer in ["", "y"]:
# Save the new xml tree to the original file
print("Writing regulation to {}".format(file))
with open(file, 'w') as f:
f.write(new_xml_string)
else:
# Cancel save
print("Canceling analysis fixes - changes have not been saved.")
# Validate the given regulation file (or files) and generate the JSON
# output expected by regulations-core and regulations-site if the RegML
# validates.
# If multiple RegML files are given, and belong to the same regulation,
# diff JSON will be generated between them.
@cli.command('json')
@click.argument('regulation_files', nargs=-1, required=True)
@click.option('--check-terms', is_flag=True)
@click.option('--skip_diffs', is_flag=True, help="Suppresses generation of diffs between versions.")
def json_command(regulation_files, from_notices=[], check_terms=False, skip_diffs=False):
""" Generate JSON from RegML files """
# If the "file" is a directory, assume we want to operate on all the
# files in that directory in listing order
if os.path.isdir(find_file(regulation_files[0])):
regulation_dir = find_file(regulation_files[0])
regulation_files = [os.path.join(regulation_dir, f)
for f in os.listdir(regulation_dir)]
# Generate JSON for each version
versions = {}
reg_number = None
for file in regulation_files:
print("Building JSON for {}".format(file))
reg_number, notice, reg_xml_tree = generate_json(
file, check_terms=check_terms)
versions[notice] = reg_xml_tree
# Generate diff JSON between each version
# now build diffs - include "empty" diffs comparing a version to itself
if not skip_diffs:
print(colored("\nBuilding inter-version diffs.", attrs=['bold']))
print(colored("WARNING: This may take an extended period of time.",
'red', attrs=['bold']))
print("To skip diff creation, use the --skip_diffs command line argument.\n")
for left_version, left_tree in versions.items():
for right_version, right_tree in versions.items():
diff = generate_diff(left_tree, right_tree)
write_layer(diff, reg_number, right_version, 'diff',
diff_notice=left_version)
# Given a regulation title and part number, prompts the user to select
# which notice to stop at and applies all notices applicable to the reg
@cli.command('json-through')
@click.argument('cfr_title')
@click.argument('cfr_part')
@click.option('--start', help="Performs JSON starting from document number" +
"(format: --from YYYY-#####). " +
"If no 'through' specified, goes til end.")
@click.option('--through',
help="Performs JSON through given document number " +
"(e.g. --through YYYY-#####). " +
"If no 'start' specified, starts from beginning.")
@click.option('--skip_diffs', is_flag=True,
help="Suppresses generation of diffs between versions.")
@click.option('--suppress_output', is_flag=True,
help="Suppresses output except for errors")
@click.pass_context
def json_through(ctx, cfr_title, cfr_part, start=None, through=None, suppress_output=False, skip_diffs=False):
# Get list of available regs
regml_reg_files = find_all(cfr_part)
regml_regs = []
regulation_files = []
for reg_file in regml_reg_files:
file_name = os.path.join(reg_file)
with open(file_name, 'r') as f:
reg_xml = f.read()
parser = etree.XMLParser(huge_tree=True)
xml_tree = etree.fromstring(reg_xml, parser)
doc_number = xml_tree.find(
'./{eregs}preamble/{eregs}documentNumber').text
effective_date = xml_tree.find(
'./{eregs}preamble/{eregs}effectiveDate').text
regml_regs.append((doc_number, effective_date, file_name))
regml_regs.sort(key=lambda n: n[1])
regulation_files = [r[2] for r in regml_regs]
# Generate prompt for user
print(colored("\nAvailable RegML documents for reg {}:".format(cfr_part),
attrs=['bold']))
for kk in range(len(regml_regs)):
print("{0:>3}. {1[0]:<22}(Effective: {1[1]})".format(kk,
regml_regs[kk]))
print()
# Possible answers are blank (all), the numbers, or the doc names
possible_indices = [str(kk) for kk in range(len(regml_regs))]
possible_regs = [nn[0] for nn in regml_regs]
# If number is supplied, use that one
if through is not None:
if start is not None:
print("Command-line: selected documents '{}'-'{}'".format(start, through))
else:
print("Command-line: selected document number '{}'".format(through))
answer = through
elif start is not None:
print("Command-line: selected start document number '{}'".format(start))
answer = possible_regs[-1] # JSON all documents
else:
# Get user input to specify end version
answer = None
while answer not in [""] + possible_indices + possible_regs:
answer = raw_input('Press enter to apply all or enter document number: [all] ')
print("Answer: '{}'".format(answer))
if len(answer) == 0:
# Apply JSON to all documents
last_ver_idx = len(regml_regs) - 1
elif answer in possible_indices:
# Apply through answer
last_ver_idx = int(answer)
elif answer in possible_regs:
# Find index to stop at in list
last_ver_idx = possible_regs.index(answer)
else:
print(colored("ERROR: Document", attrs=['bold']),
colored("{}".format(answer), 'red', attrs=['bold']),
colored("does not exist - no changes have been made.", attrs=['bold']))
return
# Support for telling user what we're doing on whether or not diffs will be created.
if skip_diffs:
skip_text = ", skipping creation of diffs."
else:
skip_text = ", including diffs."
if start is not None:
if start in possible_regs:
first_ver_idx = possible_regs.index(start)
else:
print(colored("ERROR: Document chosen for start", attrs=['bold']),
colored("{}".format(start), 'red', attrs=['bold']),
colored("does not exist - no changes have been made.", attrs=['bold']))
return
# Check that first_ver_idx < last_ver_idx
if first_ver_idx > last_ver_idx:
print(colored("ERROR: Start document", attrs=['bold']),
colored("{}".format(regml_regs[first_ver_idx][0]), 'red', attrs=['bold']),
colored("is not before 'through' notice"),
colored("{}".format(regml_regs[last_ver_idx][0]), 'red', attrs=['bold']))
return
print(colored("\nApplying JSON from {1[0]} through {0[0]}{2}\n".format(
regml_regs[last_ver_idx], regml_regs[first_ver_idx], skip_text),
attrs=['bold']))
# Perform the json application process
# Unlike apply-through, since json outputs its own command line output, here we
# reuse the existing json structure
ctx.invoke(json_command,
regulation_files=regulation_files[first_ver_idx:last_ver_idx+1],
skip_diffs=skip_diffs)
else:
print(colored("\nApplying JSON through {0[0]}{1}\n".format(
regml_regs[last_ver_idx], skip_text),
attrs=['bold']))
# Perform the json application process
# Unlike apply-through, since json outputs its own command line output, here we
# reuse the existing json structure
# json_command(regulation_files[:last_ver_idx+1], skip_diffs=skip_diffs)
ctx.invoke(json_command,
regulation_files=regulation_files[:last_ver_idx+1],
skip_diffs=skip_diffs)
# Given a notice, apply it to a previous RegML regulation verson to
# generate a new version in RegML.
@cli.command('apply-notice')
@click.argument('regulation_file')
@click.argument('notice_file')
def apply_notice(regulation_file, notice_file):
""" Apply notice changes """
# Read the RegML starting point
regulation_file = find_file(regulation_file)
with open(regulation_file, 'r') as f:
left_reg_xml = f.read()
parser = etree.XMLParser(huge_tree=True)
left_xml_tree = etree.fromstring(left_reg_xml, parser)
# Read the notice file
notice_file = find_file(notice_file, is_notice=True)
with open(notice_file, 'r') as f:
notice_string = f.read()
parser = etree.XMLParser(huge_tree=True)
notice_xml = etree.fromstring(notice_string, parser)
# Validate the files
regulation_validator = get_validator(left_xml_tree)
notice_validator = get_validator(notice_xml)
# Process the notice changeset
new_xml_tree = process_changes(left_xml_tree, notice_xml)
# Add in any new analysis
new_xml_tree = process_analysis(new_xml_tree, notice_xml)
# Write the new xml tree
new_xml_string = etree.tostring(new_xml_tree,
pretty_print=True,
xml_declaration=True,
encoding='UTF-8')
new_path = os.path.join(
os.path.dirname(regulation_file),
os.path.basename(notice_file))
with open(new_path, 'w') as f:
print("Writing regulation to {}".format(new_path))
f.write(new_xml_string)
# Given a regulation title and part number, prompts the user to select
# which notice to stop at and applies all notices applicable to the reg
@cli.command('apply-through')
@click.argument('cfr_title')
@click.argument('cfr_part')
@click.option('--through',
help="Skips prompt and applies notices through given notice number " +
"(e.g. --through YYYY-#####)")
@click.option('--fix-notices',
help="If set to True, use the validator to fix notices as you apply them.")
@click.option('--skip-fix-notices', multiple=True,
help="Document numbers of notices to skip. Specify this multiple times because"
"nargs='*' doesn't work in click.")
@click.option('--skip-fix-notices-through',
help='Skip fixing notices through the specified document number.')
def apply_through(cfr_title, cfr_part, start=None, through=None,
fix_notices=False, skip_fix_notices=[],
skip_fix_notices_through=None):
# Get list of notices that apply to this reg
# Look for locally available notices
regml_notice_files = find_all(cfr_part, is_notice=True)
regml_notices = []
for notice_file in regml_notice_files:
file_name = os.path.join(notice_file)
with open(file_name, 'r') as f:
notice_xml = f.read()
parser = etree.XMLParser(huge_tree=True)
try:
xml_tree = etree.fromstring(notice_xml, parser)
except etree.XMLSyntaxError as e:
print(colored('Syntax error in {}'.format(notice_file), 'red'))
print(e)
return
doc_number = xml_tree.find(
'./{eregs}preamble/{eregs}documentNumber').text
effective_date = xml_tree.find(
'./{eregs}preamble/{eregs}effectiveDate').text
applies_to = xml_tree.find(
'./{eregs}changeset').get('leftDocumentNumber')
if applies_to is None:
# Major problem here
print(colored("Error locating"),
colored("leftDocumentNumber", attrs=['bold']),
colored("attribute in"),
colored("{}".format(doc_number), 'red',
attrs=['bold']))
return
regml_notices.append((doc_number, effective_date, applies_to, file_name))
<<<<<<< HEAD
regml_notices.sort(key=lambda n: n[1])
for nt in regml_notices:
print(nt)
=======
if cfr_part in settings.CUSTOM_NOTICE_ORDER:
order = settings.CUSTOM_NOTICE_ORDER[cfr_part]
regml_notices.sort(key=lambda n: order.index(n[0]))
else:
regml_notices.sort(key=lambda n: n[1])
>>>>>>> 59af8726a789a57cebb45bb255f4366a76d2225b
regs = [nn[2] for nn in regml_notices]
regs.sort()
# If no notices found, issue error message
if not regml_notices:
print(colored("\nNo available notices for reg {} in part {}".format(cfr_part, cfr_title)))
return
# If initial version is not findable, issue error message
if regs[0] is None:
print(colored("\nError reading initial version and apply order for reg {} in part {}. No changes have been made.".format(cfr_part, cfr_title),
attrs=['bold']))
return
# Generate prompt for user
print(colored("\nAvailable notices for reg {}:".format(cfr_part),
attrs=['bold']))
print("{:>3}. {:<22}(Initial version)".format(0, regs[0]))
# Process notices found
for kk in range(len(regml_notices)):
print("{0:>3}. {1[0]:<22}(Effective: {1[1]})".format(kk+1,
regml_notices[kk]))
print()
# Possible answers are blank (all), the numbers, or the notice names
possible_indices = [str(kk) for kk in range(len(regml_notices) + 1)]
possible_notices = [nn[0] for nn in regml_notices]
# If notice number is supplied, use that one
if through is not None:
print("Command-line option selected notice '{}'".format(through))
answer = through
else:
# Get user input to specify end version
answer = None
while answer not in [""] + possible_indices + possible_notices:
answer = raw_input('Press enter to apply all or enter notice number: [all] ')
if len(answer) == 0:
# Apply notices
last_ver_idx = len(regml_notices) - 1
elif answer is "0":
# Cancel - this is just the initial version
print(colored("CANCELED: Version", attrs=['bold']),
colored("{}".format(regs[0]), 'yellow', attrs=['bold']),
colored("is the initial version - no changes have been made.", attrs=['bold']))
return
elif answer in possible_indices:
# Apply notices through answer-1 to adjust for the initial ver offset
last_ver_idx = int(answer) - 1
elif answer in possible_notices:
# Find index to stop at in notice list
last_ver_idx = possible_notices.index(answer)
else:
print(colored("ERROR: Notice", attrs=['bold']),
colored("{}".format(answer), 'red', attrs=['bold']),
colored("does not exist - no changes have been made.", attrs=['bold']))
return
print(colored("\nApplying notices through {0[0]}\n".format(regml_notices[last_ver_idx]),
attrs=['bold']))
# Perform the notice application process
reg_path = os.path.abspath(os.path.join(settings.XML_ROOT,
'regulation',
cfr_part,
'{}.xml'.format(regs[0])))
print("Opening initial version {}".format(reg_path))
regulation_file = find_file(reg_path)
with open(regulation_file, 'r') as f:
left_reg_xml = f.read()
parser = etree.XMLParser(huge_tree=True)
left_xml_tree = etree.fromstring(left_reg_xml, parser)
kk = 1
prev_tree = left_xml_tree
for notice in regml_notices[:last_ver_idx+1]:
doc_number, effective_date, prev_notice, file_name = notice
print("[{}] Applying notice {} from {} to version {}".format(kk,
doc_number,
file_name,
prev_notice))
# Open the notice file
notice_file = find_file(file_name, is_notice=True)
with open(notice_file, 'r') as f:
notice_string = f.read()
parser = etree.XMLParser(huge_tree=True)
notice_xml = etree.fromstring(notice_string, parser)
# TODO: Validate labels for json-compliance?
# Example: JSON fails on upload only for interpParagraphs without "Interp" in them
# Validate the files
regulation_validator = get_validator(prev_tree)
terms_layer = build_terms_layer(prev_tree)
try:
notice_validator = get_validator(notice_xml, raise_instead_of_exiting=True)
except Exception as e:
print("[{}]".format(kk),
colored("Exception occurred in notice", 'red'),
colored(doc_number, attrs=['bold']),
colored("; details are below. ", 'red'),
"To retry this single notice, use:\n\n",
colored("> ./regml.py apply-notice {0}/{1} {0}/{2}\n".format(cfr_part,
prev_notice,
doc_number),
attrs=['bold']))
sys.exit(0)
# validate the notice XML with the layers derived from the
# tree of the previous version
reload_notice = False
skip_notices = list(skip_fix_notices)
if skip_fix_notices_through is not None:
if skip_fix_notices_through in possible_notices:
last_fix_idx = possible_notices.index(skip_fix_notices_through)
skip_notices.extend(possible_notices[:last_fix_idx + 1])
if fix_notices and doc_number not in skip_notices:
print('Fixing notice number {}:'.format(doc_number))
notice_validator.validate_terms(notice_xml, terms_layer)
notice_validator.validate_term_references(notice_xml, terms_layer, notice_file)
notice_terms_layer = build_terms_layer(notice_xml)
notice_validator.validate_term_references(notice_xml, notice_terms_layer, notice_file)
notice_validator.fix_omitted_cites(notice_xml, notice_file)
reload_notice = True
# at this point the file has possibly changed, so we should really reload it
if reload_notice:
with open(notice_file, 'r') as f:
notice_string = f.read()
parser = etree.XMLParser(huge_tree=True)
notice_xml = etree.fromstring(notice_string, parser)
# Process the notice changeset
try:
new_xml_tree = process_changes(prev_tree, notice_xml)
except Exception as e:
print("[{}]".format(kk),
colored("Exception occurred; details are below. ".format(kk), 'red'),
"To retry this single notice, use:\n\n",
colored("> ./regml.py apply-notice {0}/{1} {0}/{2}\n".format(cfr_part,
prev_notice,
doc_number),
attrs=['bold']))
raise e
# Add in any new analysis
new_xml_tree = process_analysis(new_xml_tree, notice_xml)
# Write the new xml tree
new_xml_string = etree.tostring(new_xml_tree,
pretty_print=True,
xml_declaration=True,
encoding='UTF-8')
new_path = os.path.join(
os.path.dirname(regulation_file),
os.path.basename(notice_file))
with open(new_path, 'w') as f:
print("[{}] Writing regulation to {}".format(kk, new_path))
f.write(new_xml_string)
prev_tree = new_xml_tree
kk += 1
# Given a notice, apply it to a previous RegML regulation verson to
# generate a new version in RegML.
@cli.command('notice-changes')
@click.argument('notice_file')
def notice_changes(notice_file):
""" List changes in a given notice file """
# Read the notice file
notice_file = find_file(notice_file, is_notice=True)
with open(notice_file, 'r') as f:
notice_string = f.read()
parser = etree.XMLParser(huge_tree=True)
notice_xml = etree.fromstring(notice_string, parser)
doc_number = notice_xml.find(
'./{eregs}preamble/{eregs}documentNumber').text
print(colored("{} makes the following changes:".format(doc_number),
attrs=['bold']))
changes = notice_xml.findall('./{eregs}changeset/{eregs}change')
for change in changes:
label = change.get('label')
op = change.get('operation')
if op == 'added':
print('\t', colored(op, 'green'), label)
if op == 'modified':
print('\t', colored(op, 'yellow'), label)
if op == 'deleted':
print('\t', colored(op, 'red'), label)
# Given a regulation part number, version, and a set of notices
# apply the notices to the regulation file in sequential order,
# producing intermediate XML files along the way.
@cli.command('apply-notices')
@click.argument('cfr_part')
@click.argument('version')
@click.argument('notices', nargs=-1)
def apply_notices(cfr_part, version, notices):
regulation_file = find_file(os.path.join(cfr_part, version))
with open(regulation_file, 'r') as f:
left_reg_xml = f.read()
parser = etree.XMLParser(huge_tree=True)
left_xml_tree = etree.fromstring(left_reg_xml, parser)
prev_notice = version
prev_tree = left_xml_tree
for notice in notices:
print('Applying notice {} to version {}'.format(notice, prev_notice))
notice_file = find_file(os.path.join(cfr_part, notice), is_notice=True)
with open(notice_file, 'r') as f:
notice_string = f.read()
parser = etree.XMLParser(huge_tree=True)
notice_xml = etree.fromstring(notice_string, parser)
# Process the notice changeset
new_xml_tree = process_changes(prev_tree, notice_xml)
# Write the new xml tree
new_xml_string = etree.tostring(new_xml_tree,
pretty_print=True,
xml_declaration=True,
encoding='UTF-8')
new_path = os.path.join(
os.path.dirname(regulation_file),
os.path.basename(notice_file))
with open(new_path, 'w') as f:
print("Writing regulation to {}".format(new_path))
f.write(new_xml_string)