forked from asciidoc-py/asciidoc-py
-
Notifications
You must be signed in to change notification settings - Fork 1
/
asciidoc.py
executable file
·6443 lines (5975 loc) · 246 KB
/
asciidoc.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
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 python3
"""
asciidoc - converts an AsciiDoc text file to HTML or DocBook
Copyright (C) 2002-2010 Stuart Rackham. Free use of this software is granted
under the terms of the GNU General Public License (GPL).
"""
import ast
import copy
import csv
import getopt
import io
import locale
import math
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
import traceback
import unicodedata
import zipfile
from ast import literal_eval
from collections import OrderedDict
# Used by asciidocapi.py #
VERSION = '9.0.0rc1' # See CHANGELOG file for version history.
MIN_PYTHON_VERSION = '3.5' # Require this version of Python or better.
# ---------------------------------------------------------------------------
# Program constants.
# ---------------------------------------------------------------------------
DEFAULT_BACKEND = 'html'
DEFAULT_DOCTYPE = 'article'
# Allowed substitution options for List, Paragraph and DelimitedBlock
# definition subs entry.
SUBS_OPTIONS = ('specialcharacters', 'quotes', 'specialwords',
'replacements', 'attributes', 'macros', 'callouts', 'normal', 'verbatim',
'none', 'replacements2', 'replacements3')
# Default value for unspecified subs and presubs configuration file entries.
SUBS_NORMAL = ('specialcharacters', 'quotes', 'attributes',
'specialwords', 'replacements', 'macros', 'replacements2')
SUBS_VERBATIM = ('specialcharacters', 'callouts')
NAME_RE = r'[^\W\d][-\w]*' # Valid section or attribute name.
OR, AND = ',', '+' # Attribute list separators.
# ---------------------------------------------------------------------------
# Utility functions and classes.
# ---------------------------------------------------------------------------
class EAsciiDoc(Exception):
pass
class AttrDict(dict):
"""
Like a dictionary except values can be accessed as attributes i.e. obj.foo
can be used in addition to obj['foo'].
If an item is not present None is returned.
"""
def __getattr__(self, key):
try:
return self[key]
except KeyError:
return None
def __setattr__(self, key, value):
self[key] = value
def __delattr__(self, key):
try:
del self[key]
except KeyError as k:
raise AttributeError(k)
def __repr__(self):
return '<AttrDict ' + dict.__repr__(self) + '>'
def __getstate__(self):
return dict(self)
def __setstate__(self, value):
for k, v in list(value.items()):
self[k] = v
class InsensitiveDict(dict):
"""
Like a dictionary except key access is case insensitive.
Keys are stored in lower case.
"""
def __getitem__(self, key):
return dict.__getitem__(self, key.lower())
def __setitem__(self, key, value):
dict.__setitem__(self, key.lower(), value)
def has_key(self, key):
return key.lower() in self
def get(self, key, default=None):
return dict.get(self, key.lower(), default)
def update(self, dict):
for k, v in list(dict.items()):
self[k] = v
def setdefault(self, key, default=None):
return dict.setdefault(self, key.lower(), default)
class Trace(object):
"""
Used in conjunction with the 'trace' attribute to generate diagnostic
output. There is a single global instance of this class named trace.
"""
SUBS_NAMES = ('specialcharacters', 'quotes', 'specialwords',
'replacements', 'attributes', 'macros', 'callouts',
'replacements2', 'replacements3')
def __init__(self):
self.name_re = '' # Regexp pattern to match trace names.
self.linenos = True
self.offset = 0
def __call__(self, name, before, after=None):
"""
Print trace message if tracing is on and the trace 'name' matches the
document 'trace' attribute (treated as a regexp).
'before' is the source text before substitution; 'after' text is the
source text after substitution.
The 'before' and 'after' messages are only printed if they differ.
"""
name_re = document.attributes.get('trace')
if name_re == 'subs': # Alias for all the inline substitutions.
name_re = '|'.join(self.SUBS_NAMES)
self.name_re = name_re
if self.name_re is not None:
msg = message.format(name, 'TRACE: ', self.linenos, offset=self.offset)
if before != after and re.match(self.name_re, name):
if is_array(before):
before = '\n'.join(before)
if after is None:
msg += '\n%s\n' % before
else:
if is_array(after):
after = '\n'.join(after)
msg += '\n<<<\n%s\n>>>\n%s\n' % (before, after)
message.stderr(msg)
class Message:
"""
Message functions.
"""
PROG = os.path.basename(os.path.splitext(__file__)[0])
def __init__(self):
# Set to True or False to globally override line numbers method
# argument. Has no effect when set to None.
self.linenos = None
self.messages = []
self.prev_msg = ''
@staticmethod
def stdout(msg):
print(msg)
def stderr(self, msg=''):
if msg == self.prev_msg: # Suppress repeated messages.
return
self.messages.append(msg)
if __name__ == '__main__':
sys.stderr.write('%s: %s%s' % (self.PROG, msg, os.linesep))
self.prev_msg = msg
def verbose(self, msg, linenos=True):
if config.verbose:
msg = self.format(msg, linenos=linenos)
self.stderr(msg)
def warning(self, msg, linenos=True, offset=0):
msg = self.format(msg, 'WARNING: ', linenos, offset=offset)
document.has_warnings = True
self.stderr(msg)
def deprecated(self, msg, linenos=True):
msg = self.format(msg, 'DEPRECATED: ', linenos)
self.stderr(msg)
def format(self, msg, prefix='', linenos=True, cursor=None, offset=0):
"""Return formatted message string."""
if self.linenos is not False and ((linenos or self.linenos) and reader.cursor):
if cursor is None:
cursor = reader.cursor
prefix += '%s: line %d: ' % (os.path.basename(cursor[0]), cursor[1]+offset)
return prefix + msg
def error(self, msg, cursor=None, halt=False):
"""
Report fatal error.
If halt=True raise EAsciiDoc exception.
If halt=False don't exit application, continue in the hope of reporting
all fatal errors finishing with a non-zero exit code.
"""
if halt:
raise EAsciiDoc(self.format(msg, linenos=False, cursor=cursor))
else:
msg = self.format(msg, 'ERROR: ', cursor=cursor)
self.stderr(msg)
document.has_errors = True
def unsafe(self, msg):
self.error('unsafe: '+msg)
def userdir():
"""
Return user's home directory or None if it is not defined.
"""
result = os.path.expanduser('~')
if result == '~':
result = None
return result
def localapp():
"""
Return True if we are not executing the system wide version
i.e. the configuration is in the executable's directory.
"""
return os.path.isfile(os.path.join(APP_DIR, 'asciidoc.conf'))
def file_in(fname, directory):
"""Return True if file fname resides inside directory."""
assert os.path.isfile(fname)
# Empty directory (not to be confused with None) is the current directory.
if directory == '':
directory = os.getcwd()
else:
assert os.path.isdir(directory)
directory = os.path.realpath(directory)
fname = os.path.realpath(fname)
return os.path.commonprefix((directory, fname)) == directory
def safe():
return document.safe
def is_safe_file(fname, directory=None):
# A safe file must reside in 'directory' (defaults to the source
# file directory).
if directory is None:
if document.infile == '<stdin>':
return not safe()
directory = os.path.dirname(document.infile)
elif directory == '':
directory = '.'
return (
not safe() or
file_in(fname, directory) or
file_in(fname, APP_DIR) or
file_in(fname, CONF_DIR)
)
def safe_filename(fname, parentdir):
"""
Return file name which must reside in the parent file directory.
Return None if file is not safe.
"""
if not os.path.isabs(fname):
# Include files are relative to parent document
# directory.
fname = os.path.normpath(os.path.join(parentdir, fname))
if not is_safe_file(fname, parentdir):
message.unsafe('include file: %s' % fname)
return None
return fname
def assign(dst, src):
"""Assign all attributes from 'src' object to 'dst' object."""
for a, v in list(src.__dict__.items()):
setattr(dst, a, v)
def strip_quotes(s):
"""Trim white space and, if necessary, quote characters from s."""
s = s.strip()
# Strip quotation mark characters from quoted strings.
if len(s) >= 3 and s[0] == '"' and s[-1] == '"':
s = s[1:-1]
return s
def is_re(s):
"""Return True if s is a valid regular expression else return False."""
try:
re.compile(s)
except:
return False
else:
return True
def re_join(relist):
"""Join list of regular expressions re1,re2,... to single regular
expression (re1)|(re2)|..."""
if len(relist) == 0:
return None
result = []
# Delete named groups to avoid ambiguity.
for s in relist:
result.append(re.sub(r'\?P<\S+?>', '', s))
result = ')|('.join(result)
result = '(' + result + ')'
return result
def lstrip_list(s):
"""
Return list with empty items from start of list removed.
"""
for i in range(len(s)):
if s[i]:
break
else:
return []
return s[i:]
def rstrip_list(s):
"""
Return list with empty items from end of list removed.
"""
for i in range(len(s) - 1, -1, -1):
if s[i]:
break
else:
return []
return s[:i + 1]
def strip_list(s):
"""
Return list with empty items from start and end of list removed.
"""
s = lstrip_list(s)
s = rstrip_list(s)
return s
def is_array(obj):
"""
Return True if object is list or tuple type.
"""
return isinstance(obj, list) or isinstance(obj, tuple)
def dovetail(lines1, lines2):
"""
Append list or tuple of strings 'lines2' to list 'lines1'. Join the last
non-blank item in 'lines1' with the first non-blank item in 'lines2' into a
single string.
"""
assert is_array(lines1)
assert is_array(lines2)
lines1 = strip_list(lines1)
lines2 = strip_list(lines2)
if not lines1 or not lines2:
return list(lines1) + list(lines2)
result = list(lines1[:-1])
result.append(lines1[-1] + lines2[0])
result += list(lines2[1:])
return result
def dovetail_tags(stag, content, etag):
"""Merge the end tag with the first content line and the last
content line with the end tag. This ensures verbatim elements don't
include extraneous opening and closing line breaks."""
return dovetail(dovetail(stag, content), etag)
def py2round(n, d=0):
"""Utility function to get python2 rounding in python3. Python3 changed it such that
given two equally close multiples, it'll round towards the even choice. For example,
round(42.5) == 42 instead of the expected round(42.5) == 43). This function gives us
back that functionality."""
p = 10 ** d
return float(math.floor((n * p) + math.copysign(0.5, n))) / p
def get_args(val):
d = {}
args = ast.parse("d(" + val + ")", mode='eval').body.args
i = 1
for arg in args:
if isinstance(arg, ast.Name):
d[str(i)] = literal_eval(arg.id)
else:
d[str(i)] = literal_eval(arg)
i += 1
return d
def get_kwargs(val):
d = {}
args = ast.parse("d(" + val + ")", mode='eval').body.keywords
for arg in args:
d[arg.arg] = literal_eval(arg.value)
return d
def parse_to_list(val):
values = ast.parse("[" + val + "]", mode='eval').body.elts
return [literal_eval(v) for v in values]
def parse_attributes(attrs, dict):
"""Update a dictionary with name/value attributes from the attrs string.
The attrs string is a comma separated list of values and keyword name=value
pairs. Values must precede keywords and are named '1','2'... The entire
attributes list is named '0'. If keywords are specified string values must
be quoted. Examples:
attrs: ''
dict: {}
attrs: 'hello,world'
dict: {'2': 'world', '0': 'hello,world', '1': 'hello'}
attrs: '"hello", planet="earth"'
dict: {'planet': 'earth', '0': '"hello",planet="earth"', '1': 'hello'}
"""
def f(*args, **keywords):
# Name and add arguments '1','2'... to keywords.
for i in range(len(args)):
if not str(i + 1) in keywords:
keywords[str(i + 1)] = args[i]
return keywords
if not attrs:
return
dict['0'] = attrs
# Replace line separators with spaces so line spanning works.
s = re.sub(r'\s', ' ', attrs)
d = {}
try:
d.update(get_args(s))
d.update(get_kwargs(s))
for v in list(d.values()):
if not (isinstance(v, str) or isinstance(v, int) or isinstance(v, float) or v is None):
raise Exception
except Exception:
s = s.replace('"', '\\"')
s = s.split(',')
s = ['"' + x.strip() + '"' for x in s]
s = ','.join(s)
try:
d = {}
d.update(get_args(s))
d.update(get_kwargs(s))
except Exception:
return # If there's a syntax error leave with {0}=attrs.
for k in list(d.keys()): # Drop any empty positional arguments.
if d[k] == '':
del d[k]
dict.update(d)
assert len(d) > 0
def parse_named_attributes(s, attrs):
"""Update a attrs dictionary with name="value" attributes from the s string.
Returns False if invalid syntax.
Example:
attrs: 'star="sun",planet="earth"'
dict: {'planet':'earth', 'star':'sun'}
"""
def f(**keywords):
return keywords
try:
d = {}
d = get_kwargs(s)
attrs.update(d)
return True
except Exception:
return False
def parse_list(s):
"""Parse comma separated string of Python literals. Return a tuple of of
parsed values."""
try:
result = tuple(parse_to_list(s))
except Exception:
raise EAsciiDoc('malformed list: ' + s)
return result
def parse_options(options, allowed, errmsg):
"""Parse comma separated string of unquoted option names and return as a
tuple of valid options. 'allowed' is a list of allowed option values.
If allowed=() then all legitimate names are allowed.
'errmsg' is an error message prefix if an illegal option error is thrown."""
result = []
if options:
for s in re.split(r'\s*,\s*', options):
if (allowed and s not in allowed) or not is_name(s):
raise EAsciiDoc('%s: %s' % (errmsg, s))
result.append(s)
return tuple(result)
def symbolize(s):
"""Drop non-symbol characters and convert to lowercase."""
return re.sub(r'[^\w\-_]', '', s).lower()
def is_name(s):
"""Return True if s is valid attribute, macro or tag name
(starts with alpha containing alphanumeric and dashes only)."""
return re.match(r'^' + NAME_RE + r'$', s) is not None
def subs_quotes(text):
"""Quoted text is marked up and the resulting text is
returned."""
keys = list(config.quotes.keys())
for q in keys:
i = q.find('|')
if i != -1 and q != '|' and q != '||':
lq = q[:i] # Left quote.
rq = q[i + 1:] # Right quote.
else:
lq = rq = q
tag = config.quotes[q]
if not tag:
continue
# Unconstrained quotes prefix the tag name with a hash.
if tag[0] == '#':
tag = tag[1:]
# Unconstrained quotes can appear anywhere.
reo = re.compile(r'(?ms)(^|.)(\[(?P<attrlist>[^[\]]+?)\])?' +
r'(?:' + re.escape(lq) + r')' +
r'(?P<content>.+?)(?:' + re.escape(rq) + r')')
else:
# The text within constrained quotes must be bounded by white space.
# Non-word (\W) characters are allowed at boundaries to accommodate
# enveloping quotes and punctuation e.g. a='x', ('x'), 'x', ['x'].
reo = re.compile(r'(?ms)(^|[^\w;:}])(\[(?P<attrlist>[^[\]]+?)\])?' +
r'(?:' + re.escape(lq) + r')' +
r'(?P<content>\S|\S.*?\S)(?:' + re.escape(rq) + r')(?=\W|$)')
pos = 0
while True:
mo = reo.search(text, pos)
if not mo:
break
if text[mo.start()] == '\\':
# Delete leading backslash.
text = text[:mo.start()] + text[mo.start() + 1:]
# Skip past start of match.
pos = mo.start() + 1
else:
attrlist = {}
parse_attributes(mo.group('attrlist'), attrlist)
stag, etag = config.tag(tag, attrlist)
s = mo.group(1) + stag + mo.group('content') + etag
text = text[:mo.start()] + s + text[mo.end():]
pos = mo.start() + len(s)
return text
def subs_tag(tag, dict={}):
"""Perform attribute substitution and split tag string returning start, end
tag tuple (c.f. Config.tag())."""
if not tag:
return [None, None]
s = subs_attrs(tag, dict)
if not s:
message.warning('tag \'%s\' dropped: contains undefined attribute' % tag)
return [None, None]
result = s.split('|')
if len(result) == 1:
return result + [None]
elif len(result) == 2:
return result
else:
raise EAsciiDoc('malformed tag: %s' % tag)
def parse_entry(entry, dict=None, unquote=False, unique_values=False,
allow_name_only=False, escape_delimiter=True):
"""Parse name=value entry to dictionary 'dict'. Return tuple (name,value)
or None if illegal entry.
If name= then value is set to ''.
If name and allow_name_only=True then value is set to ''.
If name! and allow_name_only=True then value is set to None.
Leading and trailing white space is striped from 'name' and 'value'.
'name' can contain any printable characters.
If the '=' delimiter character is allowed in the 'name' then
it must be escaped with a backslash and escape_delimiter must be True.
If 'unquote' is True leading and trailing double-quotes are stripped from
'name' and 'value'.
If unique_values' is True then dictionary entries with the same value are
removed before the parsed entry is added."""
if escape_delimiter:
mo = re.search(r'(?:[^\\](=))', entry)
else:
mo = re.search(r'(=)', entry)
if mo: # name=value entry.
if mo.group(1):
name = entry[:mo.start(1)]
if escape_delimiter:
name = name.replace(r'\=', '=') # Un-escape \= in name.
value = entry[mo.end(1):]
elif allow_name_only and entry: # name or name! entry.
name = entry
if name[-1] == '!':
name = name[:-1]
value = None
else:
value = ''
else:
return None
if unquote:
name = strip_quotes(name)
if value is not None:
value = strip_quotes(value)
else:
name = name.strip()
if value is not None:
value = value.strip()
if not name:
return None
if dict is not None:
if unique_values:
for k, v in list(dict.items()):
if v == value:
del dict[k]
dict[name] = value
return name, value
def parse_entries(entries, dict, unquote=False, unique_values=False,
allow_name_only=False, escape_delimiter=True):
"""Parse name=value entries from from lines of text in 'entries' into
dictionary 'dict'. Blank lines are skipped."""
entries = config.expand_templates(entries)
for entry in entries:
if entry and not parse_entry(entry, dict, unquote, unique_values,
allow_name_only, escape_delimiter):
raise EAsciiDoc('malformed section entry: %s' % entry)
def dump_section(name, dict, f=sys.stdout):
"""Write parameters in 'dict' as in configuration file section format with
section 'name'."""
f.write('[%s]%s' % (name, writer.newline))
for k, v in list(dict.items()):
k = str(k)
k = k.replace('=', r'\=') # Escape = in name.
# Quote if necessary.
if len(k) != len(k.strip()):
k = '"' + k + '"'
if v and len(v) != len(v.strip()):
v = '"' + v + '"'
if v is None:
# Don't dump undefined attributes.
continue
else:
s = k + '=' + v
if s[0] == '#':
s = '\\' + s # Escape so not treated as comment lines.
f.write('%s%s' % (s, writer.newline))
f.write(writer.newline)
def update_attrs(attrs, dict):
"""Update 'attrs' dictionary with parsed attributes in dictionary 'dict'."""
for k, v in list(dict.items()):
if not is_name(k):
raise EAsciiDoc('illegal attribute name: %s' % k)
attrs[k] = v
def is_attr_defined(attrs, dic):
"""
Check if the sequence of attributes is defined in dictionary 'dic'.
Valid 'attrs' sequence syntax:
<attr> Return True if single attribute is defined.
<attr1>,<attr2>,... Return True if one or more attributes are defined.
<attr1>+<attr2>+... Return True if all the attributes are defined.
"""
if OR in attrs:
for a in attrs.split(OR):
if dic.get(a.strip()) is not None:
return True
else:
return False
elif AND in attrs:
for a in attrs.split(AND):
if dic.get(a.strip()) is None:
return False
else:
return True
else:
return dic.get(attrs.strip()) is not None
def filter_lines(filter_cmd, lines, attrs={}):
"""
Run 'lines' through the 'filter_cmd' shell command and return the result.
The 'attrs' dictionary contains additional filter attributes.
"""
def findfilter(name, dir, filter):
"""Find filter file 'fname' with style name 'name' in directory
'dir'. Return found file path or None if not found."""
if name:
result = os.path.join(dir, 'filters', name, filter)
if os.path.isfile(result):
return result
result = os.path.join(dir, 'filters', filter)
if os.path.isfile(result):
return result
return None
# Return input lines if there's not filter.
if not filter_cmd or not filter_cmd.strip():
return lines
# Perform attributes substitution on the filter command.
s = subs_attrs(filter_cmd, attrs)
if not s:
message.error('undefined filter attribute in command: %s' % filter_cmd)
return []
filter_cmd = s.strip()
# Parse for quoted and unquoted command and command tail.
# Double quoted.
mo = re.match(r'^"(?P<cmd>[^"]+)"(?P<tail>.*)$', filter_cmd)
if not mo:
# Single quoted.
mo = re.match(r"^'(?P<cmd>[^']+)'(?P<tail>.*)$", filter_cmd)
if not mo:
# Unquoted catch all.
mo = re.match(r'^(?P<cmd>\S+)(?P<tail>.*)$', filter_cmd)
cmd = mo.group('cmd').strip()
found = None
if not os.path.dirname(cmd):
# Filter command has no directory path so search filter directories.
filtername = attrs.get('style')
d = document.attributes.get('docdir')
if d:
found = findfilter(filtername, d, cmd)
if not found:
if USER_DIR:
found = findfilter(filtername, USER_DIR, cmd)
if not found:
if localapp():
found = findfilter(filtername, APP_DIR, cmd)
else:
found = findfilter(filtername, CONF_DIR, cmd)
else:
if os.path.isfile(cmd):
found = cmd
else:
message.warning('filter not found: %s' % cmd)
if found:
filter_cmd = '"' + found + '"' + mo.group('tail')
if found:
if cmd.endswith('.py'):
filter_cmd = '"%s" %s' % (document.attributes['python'],
filter_cmd)
elif cmd.endswith('.rb'):
filter_cmd = 'ruby ' + filter_cmd
message.verbose('filtering: ' + filter_cmd)
if os.name == 'nt':
# Remove redundant quoting -- this is not just
# cosmetic, unnecessary quoting appears to cause
# command line truncation.
filter_cmd = re.sub(r'"([^ ]+?)"', r'\1', filter_cmd)
try:
p = subprocess.Popen(filter_cmd, shell=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output = p.communicate(os.linesep.join(lines).encode("utf-8"))[0].decode('utf-8')
except Exception:
raise EAsciiDoc('filter error: %s: %s' % (filter_cmd, sys.exc_info()[1]))
if output:
result = [s.rstrip() for s in output.split(os.linesep)]
else:
result = []
filter_status = p.wait()
if filter_status:
message.warning('filter non-zero exit code: %s: returned %d' % (filter_cmd, filter_status))
if lines and not result:
message.warning('no output from filter: %s' % filter_cmd)
return result
def system(name, args, is_macro=False, attrs=None):
"""
Evaluate a system attribute ({name:args}) or system block macro
(name::[args]).
If is_macro is True then we are processing a system block macro otherwise
it's a system attribute.
The attrs dictionary is updated by the counter and set system attributes.
NOTE: The include1 attribute is used internally by the include1::[] macro
and is not for public use.
"""
if is_macro:
syntax = '%s::[%s]' % (name, args)
separator = '\n'
else:
syntax = '{%s:%s}' % (name, args)
separator = writer.newline
if name not in ('eval', 'eval3', 'sys', 'sys2', 'sys3', 'include',
'include1', 'counter', 'counter2', 'set', 'set2', 'template'):
if is_macro:
msg = 'illegal system macro name: %s' % name
else:
msg = 'illegal system attribute name: %s' % name
message.warning(msg)
return None
if is_macro:
s = subs_attrs(args)
if s is None:
message.warning('skipped %s: undefined attribute in: %s' % (name, args))
return None
args = s
if name != 'include1':
message.verbose('evaluating: %s' % syntax)
if safe() and name not in ('include', 'include1'):
message.unsafe(syntax)
return None
result = None
if name in ('eval', 'eval3'):
try:
result = eval(args)
if result is True:
result = ''
elif result is False:
result = None
elif result is not None:
result = str(result)
except Exception:
message.warning('%s: evaluation error' % syntax)
elif name in ('sys', 'sys2', 'sys3'):
result = ''
fd, tmp = tempfile.mkstemp()
os.close(fd)
try:
cmd = args
cmd = cmd + (' > "%s"' % tmp)
if name == 'sys2':
cmd = cmd + ' 2>&1'
if os.name == 'nt':
# Remove redundant quoting -- this is not just
# cosmetic, unnecessary quoting appears to cause
# command line truncation.
cmd = re.sub(r'"([^ ]+?)"', r'\1', cmd)
message.verbose('shelling: %s' % cmd)
if os.system(cmd):
message.warning('%s: non-zero exit status' % syntax)
try:
if os.path.isfile(tmp):
with open(tmp, encoding='utf-8') as f:
lines = [s.rstrip() for s in f]
else:
lines = []
except Exception:
raise EAsciiDoc('%s: temp file read error' % syntax)
result = separator.join(lines)
finally:
if os.path.isfile(tmp):
os.remove(tmp)
elif name in ('counter', 'counter2'):
mo = re.match(r'^(?P<attr>[^:]*?)(:(?P<seed>.*))?$', args)
attr = mo.group('attr')
seed = mo.group('seed')
if seed and (not re.match(r'^\d+$', seed) and len(seed) > 1):
message.warning('%s: illegal counter seed: %s' % (syntax, seed))
return None
if not is_name(attr):
message.warning('%s: illegal attribute name' % syntax)
return None
value = document.attributes.get(attr)
if value:
if not re.match(r'^\d+$', value) and len(value) > 1:
message.warning('%s: illegal counter value: %s'
% (syntax, value))
return None
if re.match(r'^\d+$', value):
expr = value + '+1'
else:
expr = 'chr(ord("%s")+1)' % value
try:
result = str(eval(expr))
except Exception:
message.warning('%s: evaluation error: %s' % (syntax, expr))
else:
if seed:
result = seed
else:
result = '1'
document.attributes[attr] = result
if attrs is not None:
attrs[attr] = result
if name == 'counter2':
result = ''
elif name in ('set', 'set2'):
mo = re.match(r'^(?P<attr>[^:]*?)(:(?P<value>.*))?$', args)
attr = mo.group('attr')
value = mo.group('value')
if value is None:
value = ''
if attr.endswith('!'):
attr = attr[:-1]
value = None
if not is_name(attr):
message.warning('%s: illegal attribute name' % syntax)
else:
if attrs is not None:
attrs[attr] = value
if name != 'set2': # set2 only updates local attributes.
document.attributes[attr] = value
if value is None:
result = None
else:
result = ''
elif name == 'include':
if not os.path.exists(args):
message.warning('%s: file does not exist' % syntax)
elif not is_safe_file(args):
message.unsafe(syntax)
else:
with open(args, encoding='utf-8') as f:
result = [s.rstrip() for s in f]
if result:
result = subs_attrs(result)
result = separator.join(result)
result = result.expandtabs(reader.tabsize)
else:
result = ''
elif name == 'include1':
result = separator.join(config.include1[args])
elif name == 'template':
if args not in config.sections:
message.warning('%s: template does not exist' % syntax)
else:
result = []
for line in config.sections[args]:
line = subs_attrs(line)
if line is not None:
result.append(line)
result = '\n'.join(result)
else:
assert False
if result and name in ('eval3', 'sys3'):
macros.passthroughs.append(result)
result = '\x07' + str(len(macros.passthroughs) - 1) + '\x07'
return result
def subs_attrs(lines, dictionary=None):
"""Substitute 'lines' of text with attributes from the global
document.attributes dictionary and from 'dictionary' ('dictionary'
entries take precedence). Return a tuple of the substituted lines. 'lines'
containing undefined attributes are deleted. If 'lines' is a string then
return a string.
- Attribute references are substituted in the following order: simple,
conditional, system.
- Attribute references inside 'dictionary' entry values are substituted.
"""
def end_brace(text, start):
"""Return index following end brace that matches brace at start in
text."""
assert text[start] == '{'
n = 0
result = start
for c in text[start:]:
# Skip braces that are followed by a backslash.
if result == len(text) - 1 or text[result + 1] != '\\':
if c == '{':
n = n + 1
elif c == '}':