Skip to content

Commit 394dccd

Browse files
committed
New distribution [0.1.1]
* fixed classvar conversion error * revised linting system * revised packaging * revised unittest
1 parent 71d7ed2 commit 394dccd

File tree

7 files changed

+111
-43
lines changed

7 files changed

+111
-43
lines changed

MANIFEST.in

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,5 @@ prune .vscode
99

1010
prune scripts
1111
prune share
12+
prune tests
13+
prune Tap

Pipfile.lock

Lines changed: 3 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
long_desc = file.read()
1616

1717
# version string
18-
__version__ = '0.1.0'
18+
__version__ = '0.1.1'
1919

2020
# set-up script for pip distribution
2121
setup(

share/walrus.1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
.\" Man page generated from reStructuredText.
22
.
3-
.TH WALRUS 1 "November 25, 2019" "v0.1.0" ""
3+
.TH WALRUS 1 "November 26, 2019" "v0.1.1" ""
44
.SH NAME
55
walrus \- back-port compiler for Python 3.8 assignment expression
66
.

share/walrus.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ walrus
66
back-port compiler for Python 3.8 assignment expression
77
-------------------------------------------------------
88

9-
:Version: v0.1.0
10-
:Date: November 25, 2019
9+
:Version: v0.1.1
10+
:Date: November 26, 2019
1111
:Manual section: 1
1212
:Author:
1313
Jarry Shaw, a newbie programmer, is the author, owner and maintainer

tests/test.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
# -*- coding: utf-8 -*-
2+
"""Unittest cases."""
3+
14
import os
25
import shutil
36
import subprocess
@@ -7,6 +10,7 @@
710

811
from walrus import get_parser
912
from walrus import main as main_func
13+
from walrus import walrus as core_func
1014

1115
# root path
1216
ROOT = os.path.dirname(os.path.realpath(__file__))
@@ -18,11 +22,14 @@
1822

1923

2024
def read_text_file(filename, encoding='utf-8'):
25+
"""Read text file."""
2126
with open(filename, 'r', encoding=encoding) as file:
2227
return file.read()
2328

2429

2530
class TestWalrus(unittest.TestCase):
31+
"""Test case."""
32+
2633
def test_get_parser(self):
2734
"""Test the argument parser."""
2835
parser = get_parser()
@@ -59,6 +66,23 @@ def test_main(self):
5966
converted_output = subprocess.check_output([sys.executable, os.path.join(tmpdir, test_case + '.py')], universal_newlines=True) # pylint: disable=line-too-long
6067
self.assertEqual(original_output, converted_output)
6168

69+
def test_core(self):
70+
"""Test the core function."""
71+
with tempfile.TemporaryDirectory(prefix='walrus-test') as tmpdir:
72+
all_test_cases = [fn[:-3] for fn in os.listdir(os.path.join(ROOT, 'sample')) if fn.endswith('.py')]
73+
74+
for test_case in all_test_cases:
75+
shutil.copy(os.path.join(ROOT, 'sample', test_case + '.py'), tmpdir)
76+
77+
for entry in os.scandir(tmpdir):
78+
core_func(entry.path)
79+
80+
for test_case in all_test_cases:
81+
with self.subTest(test_case=test_case):
82+
original_output = read_text_file(os.path.join(ROOT, 'sample', test_case + '.out'))
83+
converted_output = subprocess.check_output([sys.executable, os.path.join(tmpdir, test_case + '.py')], universal_newlines=True) # pylint: disable=line-too-long
84+
self.assertEqual(original_output, converted_output)
85+
6286

6387
if __name__ == '__main__':
6488
sys.exit(unittest.main())

walrus.py

Lines changed: 78 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
del multiprocessing
3232

3333
# version string
34-
__version__ = '0.1.0'
34+
__version__ = '0.1.1'
3535

3636
# from configparser
3737
BOOLEAN_STATES = {'1': True, '0': False,
@@ -92,12 +92,12 @@ def __walrus_wrapper_%(name)s_%(uuid)s(expr):
9292

9393
# special templates for ClassVar
9494
## locals dict
95-
LCL_DICT_TEMPLATE = 'walrus_wrapper_%(cls)s_dict = dict()'
96-
LCL_NAME_TEMPLATE = 'walrus_wrapper_%(cls)s_dict[%(name)r]'
95+
LCL_DICT_TEMPLATE = '_walrus_wrapper_%(cls)s_dict = dict()'
96+
LCL_NAME_TEMPLATE = '_walrus_wrapper_%(cls)s_dict[%(name)r]'
9797
LCL_CALL_TEMPLATE = '__WalrusWrapper%(cls)s.get_%(name)s_%(uuid)s(locals())'
9898
LCL_VARS_TEMPLATE = '''\
99-
[setattr(%(cls)s, k, v) for k, v in walrus_wrapper_%(cls)s_dict.items()]
100-
del walrus_wrapper_%(cls)s_dict
99+
[setattr(%(cls)s, k, v) for k, v in _walrus_wrapper_%(cls)s_dict.items()]
100+
del _walrus_wrapper_%(cls)s_dict
101101
'''.splitlines() # `str.splitlines` will remove trailing newline
102102
## class clause
103103
CLS_CALL_TEMPLATE = '__WalrusWrapper%(cls)s.set_%(name)s_%(uuid)s(%(expr)s)'
@@ -109,15 +109,15 @@ class __WalrusWrapper%(cls)s:
109109
%(tabsize)s@staticmethod
110110
%(tabsize)sdef set_%(name)s_%(uuid)s(expr):
111111
%(tabsize)s%(tabsize)s"""Wrapper function for assignment expression."""
112-
%(tabsize)s%(tabsize)swalrus_wrapper_%(cls)s_dict[%(name)r] = expr
113-
%(tabsize)s%(tabsize)sreturn walrus_wrapper_%(cls)s_dict[%(name)r]
112+
%(tabsize)s%(tabsize)s_walrus_wrapper_%(cls)s_dict[%(name)r] = expr
113+
%(tabsize)s%(tabsize)sreturn _walrus_wrapper_%(cls)s_dict[%(name)r]
114114
115115
%(tabsize)s@staticmethod
116116
%(tabsize)sdef get_%(name)s_%(uuid)s(locals_=locals()):
117117
%(tabsize)s%(tabsize)s"""Wrapper function for assignment expression."""
118118
%(tabsize)s%(tabsize)s# get value from buffer dict
119119
%(tabsize)s%(tabsize)stry:
120-
%(tabsize)s%(tabsize)s%(tabsize)sreturn walrus_wrapper_%(cls)s_dict[%(name)r]
120+
%(tabsize)s%(tabsize)s%(tabsize)sreturn _walrus_wrapper_%(cls)s_dict[%(name)r]
121121
%(tabsize)s%(tabsize)sexcept KeyError:
122122
%(tabsize)s%(tabsize)s%(tabsize)spass
123123
@@ -393,17 +393,27 @@ def _process_classdef(self, node):
393393
394394
"""
395395
flag = self.has_walrus(node)
396+
code = node.get_code()
396397

397398
# <Name: ...>
398399
name = node.name
399400
if flag:
401+
if self._linting:
402+
buffer = self._prefix if self._prefix_or_suffix else self._suffix
403+
404+
self += self._linesep * self.missing_whitespaces(prefix=buffer, suffix=code,
405+
blank=1, linesep=self._linesep)
406+
400407
self += '\t'.expandtabs(self._column) \
401408
+ LCL_DICT_TEMPLATE % dict(cls=name.value) \
402409
+ self._linesep
403410

404411
if self._linting:
405-
count = self.missing_whitespaces(node.get_code(), blank=2, direction=True)
406-
self += self._linesep * count
412+
blank = 2 if self._column == 0 else 1
413+
buffer = self._prefix if self._prefix_or_suffix else self._suffix
414+
415+
self += self._linesep * self.missing_whitespaces(prefix=buffer, suffix=code,
416+
blank=1, linesep=self._linesep)
407417

408418
# <Keyword: class>
409419
# <Name: ...>
@@ -421,14 +431,25 @@ def _process_classdef(self, node):
421431
tabsize = '\t'.expandtabs(self._tabsize)
422432

423433
if self._linting:
424-
self += self._linesep * self.missing_whitespaces(node.get_code(), blank=2, direction=False)
434+
blank = 2 if self._column == 0 else 1
435+
buffer = self._prefix if self._prefix_or_suffix else self._suffix
436+
self += self._linesep * self.missing_whitespaces(prefix=buffer, suffix='',
437+
blank=blank, linesep=self._linesep)
425438

426439
self += indent \
427440
+ ('%s%s' % (self._linesep, indent)).join(LCL_VARS_TEMPLATE) % dict(tabsize=tabsize, cls=name.value) \
428441
+ self._linesep
429442

430443
if self._linting:
431-
self += self._linesep * self.missing_whitespaces(node.get_code(), blank=1, direction=True)
444+
buffer = self._prefix if self._prefix_or_suffix else self._suffix
445+
446+
code = ''
447+
leaf = node.get_next_leaf()
448+
while leaf is not None:
449+
code += leaf.get_code()
450+
leaf = leaf.get_next_leaf()
451+
self += self._linesep * self.missing_whitespaces(prefix=buffer, suffix=code,
452+
blank=1, linesep=self._linesep)
432453

433454
def _process_funcdef(self, node):
434455
"""Process function definition (``funcdef``).
@@ -639,14 +660,15 @@ def _concat(self):
639660

640661
# first, the prefix codes
641662
self._buffer += self._prefix + prefix
642-
if self._linting:
643-
if self._node_before_walrus is None:
644-
blank = 0
645-
elif self._node_before_walrus.type in ('funcdef', 'classdef'):
663+
if flag and self._linting and self._vars:
664+
if (self._node_before_walrus is not None \
665+
and self._node_before_walrus.type in ('funcdef', 'classdef') \
666+
and self._column == 0):
646667
blank = 2
647668
else:
648669
blank = 1
649-
self._buffer += self._linesep * self.missing_whitespaces(self._buffer, blank=blank, direction=False)
670+
self._buffer += self._linesep * self.missing_whitespaces(prefix=self._buffer, suffix='',
671+
blank=blank, linesep=self._linesep)
650672

651673
# then, the variables and functions
652674
indent = '\t'.expandtabs(self._column)
@@ -665,8 +687,10 @@ def _concat(self):
665687
).join(FUNC_TEMPLATE) % dict(tabsize=tabsize, **func) + self._linesep
666688

667689
# finally, the suffix codes
668-
if flag and self._linting:
669-
self._buffer += self._linesep * self.missing_whitespaces(suffix, blank=2, direction=True)
690+
if flag and self._linting and self._vars:
691+
blank = 2 if self._column == 0 else 1
692+
self._buffer += self._linesep * self.missing_whitespaces(prefix=self._buffer, suffix=suffix,
693+
blank=blank, linesep=self._linesep)
670694
self._buffer += suffix
671695

672696
def _strip(self):
@@ -821,28 +845,35 @@ def is_walrus(node):
821845
return False
822846

823847
@staticmethod
824-
def missing_whitespaces(code, blank, direction):
848+
def missing_whitespaces(prefix, suffix, blank, linesep):
825849
"""Count missing preceding or succeeding blank lines.
826850
827851
Args:
828-
- `code` -- `str`, source code
829-
- `direction` -- `bool`, `True` for preceding; `False` for succeeding
852+
- `prefix` -- `str`, preceding source code
853+
- `suffix` -- `str`, succeeding source code
854+
- `blank` -- `int`, number of expecting blank lines
855+
- `linesep` -- `str`, line seperator
830856
831857
Returns:
832858
- `int` -- number of preceding blank lines
833859
834860
"""
835-
lines = code.splitlines()
836-
if not direction:
837-
lines = reversed(code.splitlines())
838-
839-
count = 0
840-
for line in lines:
841-
if line.strip():
842-
break
843-
count += 1
844-
861+
count = -1 # keep trailing newline in `prefix`
862+
if prefix:
863+
for line in reversed(prefix.split(linesep)):
864+
if line.strip():
865+
break
866+
count += 1
867+
if suffix:
868+
for line in suffix.split(linesep):
869+
if line.strip():
870+
break
871+
count += 1
872+
873+
if count < 0:
874+
count = 0
845875
missing = blank - count
876+
846877
if missing > 0:
847878
return missing
848879
return 0
@@ -1051,6 +1082,8 @@ def _process_name(self, node):
10511082

10521083
def _concat(self):
10531084
"""Concatenate final string."""
1085+
flag = self.has_walrus(self._root)
1086+
10541087
# strip suffix comments
10551088
prefix, suffix = self._strip()
10561089

@@ -1061,9 +1094,16 @@ def _concat(self):
10611094
indent = '\t'.expandtabs(self._column)
10621095
tabsize = '\t'.expandtabs(self._tabsize)
10631096
linesep = self._linesep
1064-
if self.has_walrus(self._root):
1097+
if flag:
10651098
if self._linting:
1066-
self._buffer += self._linesep * self.missing_whitespaces(self._buffer, blank=1, direction=False)
1099+
if (self._node_before_walrus is not None
1100+
and self._node_before_walrus.type in ('funcdef', 'classdef')
1101+
and self._column == 0):
1102+
blank = 2
1103+
else:
1104+
blank = 1
1105+
self._buffer += self._linesep * self.missing_whitespaces(prefix=self._buffer, suffix='',
1106+
blank=blank, linesep=self._linesep)
10671107
self._buffer += indent + (
10681108
'%s%s' % (self._linesep, indent)
10691109
).join(CLS_NAME_TEMPLATE) % dict(tabsize=tabsize, cls=self._cls_ctx) + linesep
@@ -1073,8 +1113,10 @@ def _concat(self):
10731113
).join(CLS_FUNC_TEMPLATE) % dict(tabsize=tabsize, cls=self._cls_ctx, **func) + linesep
10741114

10751115
# finally, the suffix codes
1076-
if self._linting:
1077-
self._buffer += self._linesep * self.missing_whitespaces(suffix, blank=1, direction=True)
1116+
if flag and self._linting:
1117+
blank = 2 if self._column == 0 else 1
1118+
self._buffer += self._linesep * self.missing_whitespaces(prefix=self._buffer, suffix=suffix,
1119+
blank=blank, linesep=self._linesep)
10781120
self._buffer += suffix
10791121

10801122

0 commit comments

Comments
 (0)