1 parent 9136088 commit 7e39347Copy full SHA for 7e39347
2 files changed
pre_commit_hooks/file_contents_sorter.py
@@ -13,6 +13,7 @@
13
from typing import Any
14
from typing import Callable
15
from typing import IO
16
+from typing import Iterable
17
from typing import Optional
18
from typing import Sequence
19
@@ -23,12 +24,16 @@
23
24
def sort_file_contents(
25
f: IO[bytes],
26
key: Optional[Callable[[bytes], Any]],
27
+ *,
28
+ unique: bool = False,
29
) -> int:
30
before = list(f)
- after = sorted(
- (line.strip(b'\n\r') for line in before if line.strip()),
- key=key,
31
+ lines: Iterable[bytes] = (
32
+ line.rstrip(b'\n\r') for line in before if line.strip()
33
)
34
+ if unique:
35
+ lines = set(lines)
36
+ after = sorted(lines, key=key)
37
38
before_string = b''.join(before)
39
after_string = b'\n'.join(after) + b'\n'
@@ -52,13 +57,20 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
52
57
default=None,
53
58
help='fold lower case to upper case characters',
54
59
60
+ parser.add_argument(
61
+ '--unique',
62
+ action='store_true',
63
+ help='ensure each line is unique',
64
+ )
55
65
args = parser.parse_args(argv)
56
66
67
retv = PASS
68
69
for arg in args.filenames:
70
with open(arg, 'rb+') as file_obj:
- ret_for_file = sort_file_contents(file_obj, key=args.ignore_case)
71
+ ret_for_file = sort_file_contents(
72
+ file_obj, key=args.ignore_case, unique=args.unique,
73
74
75
if ret_for_file:
76
print(f'Sorting {arg}')
tests/file_contents_sorter_test.py
@@ -45,6 +45,36 @@
45
FAIL,
46
b'fee\nFie\nFoe\nfum\n',
47
),
48
+ (
49
+ b'Fie\nFoe\nfee\nfee\nfum\n',
50
+ ['--ignore-case'],
51
+ FAIL,
+ b'fee\nfee\nFie\nFoe\nfum\n',
+ ),
+ b'Fie\nFoe\nfee\nfum\n',
+ ['--unique'],
+ PASS,
+ b'Fie\nFie\nFoe\nfee\nfum\n',
+ b'fee\nFie\nFoe\nfum\n',
+ ['--unique', '--ignore-case'],
77
78
79
80
def test_integration(input_s, argv, expected_retval, output, tmpdir):
0 commit comments