Skip to content

Commit 8bb0054

Browse files
authored
Merge pull request #524 from danielhoherd/sort-unique
Add --unique arg to file_contents_sorter
2 parents 9136088 + 7e39347 commit 8bb0054

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

pre_commit_hooks/file_contents_sorter.py

+16-4
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from typing import Any
1414
from typing import Callable
1515
from typing import IO
16+
from typing import Iterable
1617
from typing import Optional
1718
from typing import Sequence
1819

@@ -23,12 +24,16 @@
2324
def sort_file_contents(
2425
f: IO[bytes],
2526
key: Optional[Callable[[bytes], Any]],
27+
*,
28+
unique: bool = False,
2629
) -> int:
2730
before = list(f)
28-
after = sorted(
29-
(line.strip(b'\n\r') for line in before if line.strip()),
30-
key=key,
31+
lines: Iterable[bytes] = (
32+
line.rstrip(b'\n\r') for line in before if line.strip()
3133
)
34+
if unique:
35+
lines = set(lines)
36+
after = sorted(lines, key=key)
3237

3338
before_string = b''.join(before)
3439
after_string = b'\n'.join(after) + b'\n'
@@ -52,13 +57,20 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
5257
default=None,
5358
help='fold lower case to upper case characters',
5459
)
60+
parser.add_argument(
61+
'--unique',
62+
action='store_true',
63+
help='ensure each line is unique',
64+
)
5565
args = parser.parse_args(argv)
5666

5767
retv = PASS
5868

5969
for arg in args.filenames:
6070
with open(arg, 'rb+') as file_obj:
61-
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+
)
6274

6375
if ret_for_file:
6476
print(f'Sorting {arg}')

tests/file_contents_sorter_test.py

+30
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,36 @@
4545
FAIL,
4646
b'fee\nFie\nFoe\nfum\n',
4747
),
48+
(
49+
b'Fie\nFoe\nfee\nfee\nfum\n',
50+
['--ignore-case'],
51+
FAIL,
52+
b'fee\nfee\nFie\nFoe\nfum\n',
53+
),
54+
(
55+
b'Fie\nFoe\nfee\nfum\n',
56+
['--unique'],
57+
PASS,
58+
b'Fie\nFoe\nfee\nfum\n',
59+
),
60+
(
61+
b'Fie\nFie\nFoe\nfee\nfum\n',
62+
['--unique'],
63+
FAIL,
64+
b'Fie\nFoe\nfee\nfum\n',
65+
),
66+
(
67+
b'fee\nFie\nFoe\nfum\n',
68+
['--unique', '--ignore-case'],
69+
PASS,
70+
b'fee\nFie\nFoe\nfum\n',
71+
),
72+
(
73+
b'fee\nfee\nFie\nFoe\nfum\n',
74+
['--unique', '--ignore-case'],
75+
FAIL,
76+
b'fee\nFie\nFoe\nfum\n',
77+
),
4878
),
4979
)
5080
def test_integration(input_s, argv, expected_retval, output, tmpdir):

0 commit comments

Comments
 (0)