Disallow --unique alongside --ignore-cases in file-contents-sorter

Closes #794: using these flags at the same time results in undefined
behavior - the final ordering is not guaranteed as --unique breaks
sorting due to passing the contents through a set.

NOTE: I added a newline before and after the mutex group to be
consistent with other usages of mutex groups (e.g.,
check_builtin_literals.py) in this repo.
This commit is contained in:
Luis Pérez 2024-10-06 00:57:18 -04:00 committed by Anthony Sottile
parent 873992cf07
commit 6883485395
2 changed files with 26 additions and 14 deletions

View File

@ -54,18 +54,21 @@ def sort_file_contents(
def main(argv: Sequence[str] | None = None) -> int: def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='+', help='Files to sort') parser.add_argument('filenames', nargs='+', help='Files to sort')
parser.add_argument(
mutex = parser.add_mutually_exclusive_group(required=False)
mutex.add_argument(
'--ignore-case', '--ignore-case',
action='store_const', action='store_const',
const=bytes.lower, const=bytes.lower,
default=None, default=None,
help='fold lower case to upper case characters', help='fold lower case to upper case characters',
) )
parser.add_argument( mutex.add_argument(
'--unique', '--unique',
action='store_true', action='store_true',
help='ensure each line is unique', help='ensure each line is unique',
) )
args = parser.parse_args(argv) args = parser.parse_args(argv)
retv = PASS retv = PASS

View File

@ -67,18 +67,6 @@ from pre_commit_hooks.file_contents_sorter import PASS
FAIL, FAIL,
b'Fie\nFoe\nfee\nfum\n', b'Fie\nFoe\nfee\nfum\n',
), ),
(
b'fee\nFie\nFoe\nfum\n',
['--unique', '--ignore-case'],
PASS,
b'fee\nFie\nFoe\nfum\n',
),
(
b'fee\nfee\nFie\nFoe\nfum\n',
['--unique', '--ignore-case'],
FAIL,
b'fee\nFie\nFoe\nfum\n',
),
), ),
) )
def test_integration(input_s, argv, expected_retval, output, tmpdir): def test_integration(input_s, argv, expected_retval, output, tmpdir):
@ -89,3 +77,24 @@ def test_integration(input_s, argv, expected_retval, output, tmpdir):
assert path.read_binary() == output assert path.read_binary() == output
assert output_retval == expected_retval assert output_retval == expected_retval
@pytest.mark.parametrize(
('input_s', 'argv'),
(
(
b'fee\nFie\nFoe\nfum\n',
['--unique', '--ignore-case'],
),
(
b'fee\nfee\nFie\nFoe\nfum\n',
['--unique', '--ignore-case'],
),
),
)
def test_integration_invalid_args(input_s, argv, tmpdir):
path = tmpdir.join('file.txt')
path.write_binary(input_s)
with pytest.raises(SystemExit):
main([str(path)] + argv)