-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrelaxedecor.py
1069 lines (825 loc) · 39.8 KB
/
relaxedecor.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
# -*- coding: utf-8 -*-
"""Back-port compiler for Python 3.9 relaxed decorator expressions."""
import argparse
import os
import pathlib
import re
import sys
import traceback
from typing import Generator, List, Optional, Union
import parso.python.tree
import parso.tree
import tbtrim
from bpc_utils import (BaseContext, BPCSyntaxError, Config, TaskLock, archive_files,
detect_encoding, detect_files, detect_indentation, detect_linesep,
first_non_none, get_parso_grammar_versions, map_tasks, parse_boolean_state,
parse_indentation, parse_linesep, parse_positive_integer, parso_parse,
recover_files)
from bpc_utils.typing import Linesep
from typing_extensions import Literal, final
__all__ = ['main', 'relaxedecor', 'convert', 'decorator'] # pylint: disable=undefined-all-variable
# version string
__version__ = '0.0.0.dev0'
###############################################################################
# Typings
class RelaxedecorConfig(Config):
indentation = '' # type: str
linesep = '\n' # type: Literal[Linesep]
pep8 = True # type: bool
filename = None # Optional[str]
source_version = None # Optional[str]
decorator = 'decorator' # type: str
##############################################################################
# Auxiliaries
#: Get supported source versions.
#:
#: .. seealso:: :func:`bpc_utils.get_parso_grammar_versions`
RELAXEDECOR_SOURCE_VERSIONS = get_parso_grammar_versions(minimum='3.9')
# option default values
#: Default value for the ``quiet`` option.
_default_quiet = False
#: Default value for the ``concurrency`` option.
_default_concurrency = None # auto detect
#: Default value for the ``do_archive`` option.
_default_do_archive = True
#: Default value for the ``archive_path`` option.
_default_archive_path = 'archive'
#: Default value for the ``source_version`` option.
_default_source_version = RELAXEDECOR_SOURCE_VERSIONS[-1]
#: Default value for the ``linesep`` option.
_default_linesep = None # auto detect
#: Default value for the ``indentation`` option.
_default_indentation = None # auto detect
#: Default value for the ``pep8`` option.
_default_pep8 = True
#: Default value for the ``decorator-name`` option.
_default_decorator = '_relaxedecor_decorator'
# option getter utility functions
# option value precedence is: explicit value (CLI/API arguments) > environment variable > default value
def _get_quiet_option(explicit: Optional[bool] = None) -> Optional[bool]:
"""Get the value for the ``quiet`` option.
Args:
explicit (Optional[bool]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
bool: the value for the ``quiet`` option
:Environment Variables:
:envvar:`RELAXEDECOR_QUIET` -- the value in environment variable
See Also:
:data:`_default_quiet`
"""
# We need short circuit evaluation, so first_non_none(a, b, c) does not work here
# with PEP 505 we can simply write a ?? b ?? c
def _option_layers() -> Generator[Optional[bool], None, None]:
yield explicit
yield parse_boolean_state(os.getenv('RELAXEDECOR_QUIET'))
yield _default_quiet
return first_non_none(_option_layers())
def _get_concurrency_option(explicit: Optional[int] = None) -> Optional[int]:
"""Get the value for the ``concurrency`` option.
Args:
explicit (Optional[int]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
Optional[int]: the value for the ``concurrency`` option;
:data:`None` means *auto detection* at runtime
:Environment Variables:
:envvar:`RELAXEDECOR_CONCURRENCY` -- the value in environment variable
See Also:
:data:`_default_concurrency`
"""
return parse_positive_integer(explicit or os.getenv('RELAXEDECOR_CONCURRENCY') or _default_concurrency)
def _get_do_archive_option(explicit: Optional[bool] = None) -> Optional[bool]:
"""Get the value for the ``do_archive`` option.
Args:
explicit (Optional[bool]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
bool: the value for the ``do_archive`` option
:Environment Variables:
:envvar:`RELAXEDECOR_DO_ARCHIVE` -- the value in environment variable
See Also:
:data:`_default_do_archive`
"""
def _option_layers() -> Generator[Optional[bool], None, None]:
yield explicit
yield parse_boolean_state(os.getenv('RELAXEDECOR_DO_ARCHIVE'))
yield _default_do_archive
return first_non_none(_option_layers())
def _get_archive_path_option(explicit: Optional[str] = None) -> str:
"""Get the value for the ``archive_path`` option.
Args:
explicit (Optional[str]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
str: the value for the ``archive_path`` option
:Environment Variables:
:envvar:`RELAXEDECOR_ARCHIVE_PATH` -- the value in environment variable
See Also:
:data:`_default_archive_path`
"""
return explicit or os.getenv('RELAXEDECOR_ARCHIVE_PATH') or _default_archive_path
def _get_source_version_option(explicit: Optional[str] = None) -> Optional[str]:
"""Get the value for the ``source_version`` option.
Args:
explicit (Optional[str]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
str: the value for the ``source_version`` option
:Environment Variables:
:envvar:`RELAXEDECOR_SOURCE_VERSION` -- the value in environment variable
See Also:
:data:`_default_source_version`
"""
return explicit or os.getenv('RELAXEDECOR_SOURCE_VERSION') or _default_source_version
def _get_linesep_option(explicit: Optional[str] = None) -> Optional[Linesep]:
r"""Get the value for the ``linesep`` option.
Args:
explicit (Optional[str]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
Optional[Literal['\\n', '\\r\\n', '\\r']]: the value for the ``linesep`` option;
:data:`None` means *auto detection* at runtime
:Environment Variables:
:envvar:`RELAXEDECOR_LINESEP` -- the value in environment variable
See Also:
:data:`_default_linesep`
"""
return parse_linesep(explicit or os.getenv('RELAXEDECOR_LINESEP') or _default_linesep)
def _get_indentation_option(explicit: Optional[Union[str, int]] = None) -> Optional[str]:
"""Get the value for the ``indentation`` option.
Args:
explicit (Optional[Union[str, int]]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
Optional[str]: the value for the ``indentation`` option;
:data:`None` means *auto detection* at runtime
:Environment Variables:
:envvar:`RELAXEDECOR_INDENTATION` -- the value in environment variable
See Also:
:data:`_default_indentation`
"""
return parse_indentation(explicit or os.getenv('RELAXEDECOR_INDENTATION') or _default_indentation)
def _get_pep8_option(explicit: Optional[bool] = None) -> Optional[bool]:
"""Get the value for the ``pep8`` option.
Args:
explicit (Optional[bool]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
bool: the value for the ``pep8`` option
:Environment Variables:
:envvar:`RELAXEDECOR_PEP8` -- the value in environment variable
See Also:
:data:`_default_pep8`
"""
def _option_layers() -> Generator[Optional[bool], None, None]:
yield explicit
yield parse_boolean_state(os.getenv('RELAXEDECOR_PEP8'))
yield _default_pep8
return first_non_none(_option_layers())
def _get_decorator_option(explicit: Optional[str] = None) -> Optional[str]:
"""Get the value for the ``decorator`` option.
Args:
explicit (Optional[str]): the value explicitly specified by user,
:data:`None` if not specified
Returns:
str: the value for the ``decorator`` option
:Environment Variables:
:envvar:`RELAXEDECOR_DECORATOR` -- the value in environment variable
See Also:
:data:`_default_decorator`
"""
return explicit or os.getenv('RELAXEDECOR_DECORATOR') or _default_decorator
###############################################################################
# Traceback Trimming (tbtrim)
# root path
ROOT = pathlib.Path(__file__).resolve().parent
def predicate(filename: str) -> bool:
return pathlib.Path(filename).parent == ROOT
tbtrim.set_trim_rule(predicate, strict=True, target=BPCSyntaxError)
###############################################################################
# Main convertion implementations
# cf. https://www.python.org/dev/peps/pep-0614/#motivation
DECORATOR_TEMPLATE = '''\
def %(decorator)s(expr):
%(indentation)s"""Relaxed decorator expressions runtime wrapper.
%(indentation)s
%(indentation)s Args:
%(indentation)s expr: Expected decorator expression.
%(indentation)s
%(indentation)s The decorator function may decorate regular :term:`function` to
%(indentation)s provide evaluation for relaxted decorator expressions in the
%(indentation)s backward compatible grammar.
%(indentation)s
%(indentation)s"""
%(indentation)simport functools
%(indentation)sdef caller(func):
%(indentation)s%(indentation)[email protected](func)
%(indentation)s%(indentation)sdef wrapper(*args, **kwargs):
%(indentation)s%(indentation)s%(indentation)sreturn expr(func)(*args, **kwargs)
%(indentation)s%(indentation)sreturn wrapper
%(indentation)sreturn caller
'''.splitlines() # `str.splitlines` will remove trailing newline
class Context(BaseContext):
"""General conversion context.
Args:
node (parso.tree.NodeOrLeaf): parso AST
config (Config): conversion configurations
Keyword Args:
indent_level (int): current indentation level
raw (bool): raw processing flag
Important:
``raw`` should be :data:`True` only if the ``node`` is in the clause of another *context*,
where the converted wrapper functions should be inserted.
For the :class:`Context` class of :mod:`relaxedecor` module,
it will process nodes with following methods:
* :token:`suite`
- :meth:`Context._process_suite_node`
* :token:`funcdef`
- :meth:`Context._process_funcdef`
* :token:`classdef`
- :meth:`Context._process_classdef`
* :token:`if_stmt`
- :meth:`Context._process_if_stmt`
* :token:`while_stmt`
- :meth:`Context._process_while_stmt`
* :token:`for_stmt`
- :meth:`Context._process_for_stmt`
* :token:`with_stmt`
- :meth:`Context._process_with_stmt`
* :token:`try_stmt`
- :meth:`Context._process_try_stmt`
"""
@final
@property
def decorator(self) -> str:
"""Name of the ``relaxedecor`` decorator.
:rtype: str
"""
return self._decorator
def __init__(self, node: parso.tree.NodeOrLeaf, config: RelaxedecorConfig, *,
indent_level: int = 0, raw: bool = False):
#: str: Decorator name.
self._decorator = config.decorator # type: str
super().__init__(node, config, indent_level=indent_level, raw=raw)
def _process_suite_node(self, node: parso.tree.NodeOrLeaf) -> None:
"""Process indented suite (:token:`suite` or others).
Args:
node (parso.tree.NodeOrLeaf): suite node
This method first checks if ``node`` contains positional-only parameters.
If not, it will not perform any processing, rather just append the
original source code to context buffer.
If ``node`` contains positional-only parameters, then it will initiate
another Context` instance to perform the conversion process on such
``node``.
"""
if not self.has_expr(node):
self += node.get_code()
return
indent = self._indent_level + 1
self += self._linesep + self._indentation * indent
# initialize new context
ctx = Context(node=node, config=self.config, indent_level=indent, raw=True)
self += ctx.string.lstrip()
def _process_decorator(self, node: parso.python.tree.Decorator) -> None:
"""Process decorator expression (:token:`decorator`).
Args:
node (parso.python.tree.Decorator): decorator node
"""
if not self.has_expr(node):
self += node.get_code()
return
# '@' namedexpr_test NEWLINE
children = iter(node.children)
# <Operator: @>
self._process(next(children))
# namedexpr_test
expr = next(children)
self += '%s(%s)' % (self._decorator, expr.get_code().strip())
# <Newline: '\n'>
self._process(next(children))
def _process_funcdef(self, node: parso.python.tree.Function) -> None:
"""Process function definition (:token:`funcdef`).
Args:
node (parso.python.tree.Function): function node
"""
if not self.has_expr(node):
self += node.get_code()
return
# 'def' NAME '(' PARAM ')' [ '->' NAME ] ':' SUITE
for child in node.children[:-1]:
self._process(child)
# SUITE
self._process_suite_node(node.children[-1])
def _process_classdef(self, node: parso.python.tree.Class) -> None:
"""Process class definition (:token:`classdef`).
Args:
node (parso.python.tree.Class): class node
This method converts the whole class suite context with
:meth:`~Context._process_suite_node` through :class:`Context`
respectively.
"""
# <Keyword: class>
# <Name: ...>
# [<Operator: (>, PythonNode(arglist, [...]]), <Operator: )>]
# <Operator: :>
for child in node.children[:-1]:
self._process(child)
# PythonNode(suite, [...]) / PythonNode(simple_stmt, [...])
suite = node.children[-1]
self._process_suite_node(suite)
def _process_if_stmt(self, node: parso.python.tree.IfStmt) -> None:
"""Process if statement (:token:`if_stmt`).
Args:
node (parso.python.tree.IfStmt): if node
This method processes each indented suite under the *if*, *elif*,
and *else* statements.
"""
children = iter(node.children)
# <Keyword: if>
self._process(next(children))
# namedexpr_test
self._process(next(children))
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
while True:
try:
# <Keyword: elif | else>
key = next(children)
except StopIteration:
break
self._process(key)
if key.value == 'elif':
# namedexpr_test
self._process(next(children))
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
continue
if key.value == 'else':
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
continue
def _process_while_stmt(self, node: parso.python.tree.WhileStmt) -> None:
"""Process while statement (:token:`while_stmt`).
Args:
node (parso.python.tree.WhileStmt): while node
This method processes the indented suite under the *while* and optional
*else* statements.
"""
children = iter(node.children)
# <Keyword: while>
self._process(next(children))
# namedexpr_test
self._process(next(children))
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
try:
key = next(children)
except StopIteration:
return
# <Keyword: else>
self._process(key)
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
def _process_for_stmt(self, node: parso.python.tree.ForStmt) -> None:
"""Process for statement (:token:`for_stmt`).
Args:
node (parso.python.tree.ForStmt): for node
This method processes the indented suite under the *for* and optional
*else* statements.
"""
children = iter(node.children)
# <Keyword: for>
self._process(next(children))
# exprlist
self._process(next(children))
# <Keyword: in>
self._process(next(children))
# testlist
self._process(next(children))
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
try:
key = next(children)
except StopIteration:
return
# <Keyword: else>
self._process(key)
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
def _process_with_stmt(self, node: parso.python.tree.WithStmt) -> None:
"""Process with statement (:token:`with_stmt`).
Args:
node (parso.python.tree.WithStmt): with node
This method processes the indented suite under the *with* statement.
"""
children = iter(node.children)
# <Keyword: with>
self._process(next(children))
while True:
# with_item | <Operator: ,>
item = next(children)
self._process(item)
# <Operator: :>
if item.type == 'operator' and item.value == ':':
break
# suite
self._process_suite_node(next(children))
def _process_try_stmt(self, node: parso.python.tree.TryStmt) -> None:
"""Process try statement (:token:`try_stmt`).
Args:
node (parso.python.tree.TryStmt): try node
This method processes the indented suite under the *try*, *except*,
*else*, and *finally* statements.
"""
children = iter(node.children)
while True:
try:
key = next(children)
except StopIteration:
break
# <Keyword: try | else | finally> | PythonNode(except_clause, [...]
self._process(key)
# <Operator: :>
self._process(next(children))
# suite
self._process_suite_node(next(children))
def _concat(self) -> None:
"""Concatenate final string.
This method tries to inserted the runtime wrapper decorator function
at the very location where starts to contain relaxed decorators, i.e.
between the converted code as :attr:`self._prefix <Context._prefix>` and
:attr:`self._suffix <Context._suffix>`.
The inserted code is rendered from :data:`DECORATOR_TEMPLATE`. If
:attr:`self._pep8 <Context._pep8>` is :data:`True`, it will insert the code
in compliance with :pep:`8`.
"""
if not self.has_expr(self._root):
self._buffer += self._prefix + self._suffix
return
# strip suffix comments
prefix, suffix = self.split_comments(self._suffix, self._linesep)
match = re.match(r'^(?P<linesep>(%s)*)' % self._linesep, suffix, flags=re.ASCII)
suffix_linesep = match.group('linesep') if match is not None else ''
# first, the prefix code
self._buffer += self._prefix + prefix + suffix_linesep
if self._pep8 and self._buffer:
if (self._node_before_expr is not None
and self._node_before_expr.type in ('funcdef', 'classdef')
and self._indent_level == 0):
blank = 2
else:
blank = 1
self._buffer += self._linesep * self.missing_newlines(prefix=self._buffer, suffix='',
expected=blank, linesep=self._linesep)
# then, the decorator function
self._buffer += self._linesep.join(DECORATOR_TEMPLATE) % dict(
decorator=self._decorator,
indentation=self._indentation,
) + self._linesep
# finally, the suffix code
if self._pep8:
self._buffer += self._linesep * self.missing_newlines(prefix=self._buffer, suffix='',
expected=2, linesep=self._linesep)
self._buffer += suffix.lstrip(self._linesep)
@final
@classmethod
def has_expr(cls, node: parso.tree.NodeOrLeaf) -> bool:
"""Check if node has relaxed decorator expressions.
Args:
node (parso.tree.NodeOrLeaf): parso AST
Returns:
bool: if ``node`` has relaxed decorator expressions
"""
if node.type == 'decorator':
# NOTE: referred netromdk/vermin#51 for possible solution, i.e.,
# ast.Name, ast.Attribute and ast.Load are the only scenarios for
# an old-fashioned decorator
child = node.children[1] # type: ignore[attr-defined]
if child.type == 'name':
return False
if hasattr(child, 'children'):
# <Name: ...> trailer ...
children = iter(child.children)
name = next(children)
if name.type != 'name':
return True
# <Operator: .> <Name: ...>
# <Operator: (> [arglist] <Operator: )> -> at most once without PEP 614
func_call = False # is function call detected
for child in children:
if func_call: # there is already a function call, no more things allowed after that without PEP 614
return True
# NOTE: Python 3.9 grammar takes all child nodes as trailer instead of wrapping
# them up by their types like in 3.8
if child.type == 'trailer':
# <Operator: .> <Name: ...>
# <Operator: (> <Operator: )> -> at most once without PEP 614
if len(child.children) == 2:
first, second = child.children
if (first.type == 'operator' and first.value == '.'
and second.type == 'name'): # <Operator: .> <Name: ...>
continue
if first.type == 'operator' and first.value == '(' \
and second.type == 'operator' and second.value == ')' \
and not func_call: # function call without arguments
func_call = True
continue
# <Operator: (> [arglist] <Operator: )> -> at most once without PEP 614
if len(child.children) == 3:
left, _, right = child.children
if left.type == 'operator' and left.value == '(' \
and right.type == 'operator' and right.value == ')' \
and not func_call: # function call with arguments
func_call = True
continue
return True # if it's a subscript getter, or not a trailer node
return False # if all checks of old decorator grammar passed
return True # if it's a node without children but not a Name node
if hasattr(node, 'children'):
return any(map(cls.has_expr, node.children)) # type: ignore[attr-defined]
return False
# backward compatibility and auxiliary alias
has_relaxedecor = has_expr
###############################################################################
# Public Interface
exec(os.linesep.join(DECORATOR_TEMPLATE) % dict(decorator='decorator', indentation=' ')) # nosec: B102; pylint: disable=exec-used
def convert(code: Union[str, bytes], filename: Optional[str] = None, *,
source_version: Optional[str] = None, linesep: Optional[Linesep] = None,
indentation: Optional[Union[int, str]] = None, pep8: Optional[bool] = None,
decorator: Optional[str] = None) -> str:
"""Convert the given Python source code string.
Args:
code (Union[str, bytes]): the source code to be converted
filename (Optional[str]): an optional source file name to provide a context in case of error
Keyword Args:
source_version (Optional[str]): parse the code as this Python version (uses the latest version by default)
linesep (Optional[str]): line separator of code (``LF``, ``CRLF``, ``CR``) (auto detect by default)
indentation (Optional[Union[int, str]]): code indentation style, specify an integer for the number of spaces,
or ``'t'``/``'tab'`` for tabs (auto detect by default)
pep8 (Optional[bool]): whether to make code insertion :pep:`8` compliant
:Environment Variables:
- :envvar:`RELAXEDECOR_SOURCE_VERSION` -- same as the ``source_version`` argument and the ``--source-version`` option
in CLI
- :envvar:`RELAXEDECOR_LINESEP` -- same as the `linesep` `argument` and the ``--linesep`` option in CLI
- :envvar:`RELAXEDECOR_INDENTATION` -- same as the ``indentation`` argument and the ``--indentation`` option in CLI
- :envvar:`RELAXEDECOR_PEP8` -- same as the ``pep8`` argument and the ``--no-pep8`` option in CLI (logical negation)
- :envvar:`RELAXEDECOR_DECORATOR` -- same as the ``--decorator-name`` option in CLI
Returns:
str: converted source code
Raises:
ValueError: if ``decorator`` is not a valid identifier name or starts with double underscore
"""
# parse source string
source_version = _get_source_version_option(source_version)
module = parso_parse(code, filename=filename, version=source_version)
# get linesep, indentation and pep8 options
linesep = _get_linesep_option(linesep)
indentation = _get_indentation_option(indentation)
if linesep is None:
linesep = detect_linesep(code)
if indentation is None:
indentation = detect_indentation(code)
pep8 = _get_pep8_option(pep8)
decorator = _get_decorator_option(decorator)
# validate that decorator name is valid identifier
if not decorator.isidentifier():
raise ValueError('name of decorator for runtime checks is not a valid identifier name: %r' % decorator)
# prevent using class-private names and dunder names
if decorator.startswith('__'):
raise ValueError('name of decorator for runtime checks should not start with double underscore')
# pack conversion configuration
config = Config(linesep=linesep, indentation=indentation, pep8=pep8,
filename=filename, source_version=source_version,
decorator=decorator)
# convert source string
result = Context(module, config).string # type: ignore[arg-type]
# return conversion result
return result
def relaxedecor(filename: str, *, source_version: Optional[str] = None, linesep: Optional[Linesep] = None,
indentation: Optional[Union[int, str]] = None, pep8: Optional[bool] = None,
decorator: Optional[str] = None,
quiet: Optional[bool] = None, dry_run: bool = False) -> None:
"""Convert the given Python source code file. The file will be overwritten.
Args:
filename (str): the file to convert
Keyword Args:
source_version (Optional[str]): parse the code as this Python version (uses the latest version by default)
linesep (Optional[str]): line separator of code (``LF``, ``CRLF``, ``CR``) (auto detect by default)
indentation (Optional[Union[int, str]]): code indentation style, specify an integer for the number of spaces,
or ``'t'``/``'tab'`` for tabs (auto detect by default)
pep8 (Optional[bool]): whether to make code insertion :pep:`8` compliant
quiet (Optional[bool]): whether to run in quiet mode
dry_run (bool): if :data:`True`, only print the name of the file to convert but do not perform any conversion
:Environment Variables:
- :envvar:`RELAXEDECOR_SOURCE_VERSION` -- same as the ``source-version`` argument and the ``--source-version`` option
in CLI
- :envvar:`RELAXEDECOR_LINESEP` -- same as the ``linesep`` argument and the ``--linesep`` option in CLI
- :envvar:`RELAXEDECOR_INDENTATION` -- same as the ``indentation`` argument and the ``--indentation`` option in CLI
- :envvar:`RELAXEDECOR_PEP8` -- same as the ``pep8`` argument and the ``--no-pep8`` option in CLI (logical negation)
- :envvar:`RELAXEDECOR_QUIET` -- same as the ``quiet`` argument and the ``--quiet`` option in CLI
- :envvar:`RELAXEDECOR_DECORATOR` -- same as the ``--decorator-name`` option in CLI
"""
quiet = _get_quiet_option(quiet)
if not quiet:
with TaskLock():
print('Now converting: %r' % filename, file=sys.stderr)
if dry_run:
return
# read file content
with open(filename, 'rb') as file:
content = file.read()
# detect source code encoding
encoding = detect_encoding(content)
# get linesep and indentation
linesep = _get_linesep_option(linesep)
indentation = _get_indentation_option(indentation)
if linesep is None or indentation is None:
with open(filename, 'r', encoding=encoding) as file:
if linesep is None:
linesep = detect_linesep(file)
if indentation is None:
indentation = detect_indentation(file)
# do the dirty things
result = convert(content, filename=filename, source_version=source_version,
linesep=linesep, indentation=indentation, pep8=pep8,
decorator=decorator)
# overwrite the file with conversion result
with open(filename, 'w', encoding=encoding, newline='') as file:
file.write(result)
###############################################################################
# CLI & Entry Point
# option values display
# these values are only intended for argparse help messages
# this shows default values by default, environment variables may override them
__cwd__ = os.getcwd()
__relaxedecor_quiet__ = 'quiet mode' if _get_quiet_option() else 'non-quiet mode'
__relaxedecor_concurrency__ = _get_concurrency_option() or 'auto detect'
__relaxedecor_do_archive__ = 'will do archive' if _get_do_archive_option() else 'will not do archive'
__relaxedecor_archive_path__ = os.path.join(__cwd__, _get_archive_path_option())
__relaxedecor_source_version__ = _get_source_version_option()
__relaxedecor_linesep__ = {
'\n': 'LF',
'\r\n': 'CRLF',
'\r': 'CR',
None: 'auto detect'
}[_get_linesep_option()]
__relaxedecor_indentation__ = _get_indentation_option()
if __relaxedecor_indentation__ is None:
__relaxedecor_indentation__ = 'auto detect'
elif __relaxedecor_indentation__ == '\t':
__relaxedecor_indentation__ = 'tab'
else:
__relaxedecor_indentation__ = '%d spaces' % len(__relaxedecor_indentation__)
__relaxedecor_pep8__ = 'will conform to PEP 8' if _get_pep8_option() else 'will not conform to PEP 8'
__relaxedecor_decorator__ = _get_decorator_option() or '_relaxedecor_decorator'
def get_parser() -> argparse.ArgumentParser:
"""Generate CLI parser.
Returns:
argparse.ArgumentParser: CLI parser for relaxedecor
"""
parser = argparse.ArgumentParser(prog='relaxedecor',
usage='relaxedecor [options] <Python source files and directories...>',
description='Back-port compiler for Python 3.8 position-only parameters.')
parser.add_argument('-V', '--version', action='version', version=__version__)
parser.add_argument('-q', '--quiet', action='store_true', default=None,
help='run in quiet mode (current: %s)' % __relaxedecor_quiet__)
parser.add_argument('-C', '--concurrency', action='store', type=int, metavar='N',
help='the number of concurrent processes for conversion (current: %s)' % __relaxedecor_concurrency__)
parser.add_argument('--dry-run', action='store_true',
help='list the files to be converted without actually performing conversion and archiving')
parser.add_argument('-s', '--simple', action='store', nargs='?', dest='simple_args', const='', metavar='FILE',
help='this option tells the program to operate in "simple mode"; '
'if a file name is provided, the program will convert the file but print conversion '
'result to standard output instead of overwriting the file; '
'if no file names are provided, read code for conversion from standard input and print '
'conversion result to standard output; '
'in "simple mode", no file names shall be provided via positional arguments')
archive_group = parser.add_argument_group(title='archive options',
description="backup original files in case there're any issues")
archive_group.add_argument('-na', '--no-archive', action='store_false', dest='do_archive', default=None,
help='do not archive original files (current: %s)' % __relaxedecor_do_archive__)
archive_group.add_argument('-k', '--archive-path', action='store', default=__relaxedecor_archive_path__, metavar='PATH', # pylint: disable=line-too-long
help='path to archive original files (current: %(default)s)')
archive_group.add_argument('-r', '--recover', action='store', dest='recover_file', metavar='ARCHIVE_FILE',
help='recover files from a given archive file')
archive_group.add_argument('-r2', action='store_true', help='remove the archive file after recovery')
archive_group.add_argument('-r3', action='store_true', help='remove the archive file after recovery, '
'and remove the archive directory if it becomes empty')
# TODO: revise ``--dismiss-runtime`` & ``--decorator-name`` options
convert_group = parser.add_argument_group(title='convert options', description='conversion configuration')
convert_group.add_argument('-vs', '-vf', '--source-version', '--from-version', action='store', metavar='VERSION',
default=__relaxedecor_source_version__, choices=RELAXEDECOR_SOURCE_VERSIONS,
help='parse source code as this Python version (current: %(default)s)')
convert_group.add_argument('-l', '--linesep', action='store',
help='line separator (LF, CRLF, CR) to read '
'source files (current: %s)' % __relaxedecor_linesep__)
convert_group.add_argument('-t', '--indentation', action='store', metavar='INDENT',
help='code indentation style, specify an integer for the number of spaces, '
"or 't'/'tab' for tabs (current: %s)" % __relaxedecor_indentation__)
convert_group.add_argument('-n8', '--no-pep8', action='store_false', dest='pep8', default=None,
help='do not make code insertion PEP 8 compliant (current: %s)' % __relaxedecor_pep8__)
convert_group.add_argument('-d', '--decorator-name', action='store', dest='decorator', metavar='NAME',
default=__relaxedecor_decorator__, help='name of decorator for runtime checks (current: %s)' % __relaxedecor_decorator__) # pylint: disable=line-too-long
parser.add_argument('files', action='store', nargs='*', metavar='<Python source files and directories...>',
help='Python source files and directories to be converted')
return parser
def do_relaxedecor(filename: str, **kwargs: object) -> None:
"""Wrapper function to catch exceptions."""
try:
relaxedecor(filename, **kwargs) # type: ignore[arg-type]
except Exception: # pylint: disable=broad-except
with TaskLock():
print('Failed to convert file: %r' % filename, file=sys.stderr)
traceback.print_exc()
def main(argv: Optional[List[str]] = None) -> int:
"""Entry point for relaxedecor.
Args:
argv (Optional[List[str]]): CLI arguments
:Environment Variables:
- :envvar:`RELAXEDECOR_QUIET` -- same as the ``--quiet`` option in CLI
- :envvar:`RELAXEDECOR_CONCURRENCY` -- same as the ``--concurrency`` option in CLI
- :envvar:`RELAXEDECOR_DO_ARCHIVE` -- same as the ``--no-archive`` option in CLI (logical negation)
- :envvar:`RELAXEDECOR_ARCHIVE_PATH` -- same as the ``--archive-path`` option in CLI
- :envvar:`RELAXEDECOR_SOURCE_VERSION` -- same as the ``--source-version`` option in CLI
- :envvar:`RELAXEDECOR_LINESEP` -- same as the ``--linesep`` option in CLI
- :envvar:`RELAXEDECOR_INDENTATION` -- same as the ``--indentation`` option in CLI
- :envvar:`RELAXEDECOR_PEP8` -- same as the ``--no-pep8`` option in CLI (logical negation)
- :envvar:`RELAXEDECOR_DECORATOR` -- same as the ``--decorator-name`` option in CLI
"""
parser = get_parser()
args = parser.parse_args(argv)
options = {