Skip to content

Commit aae27b8

Browse files
authored
Merge pull request #1014 from vhoulbreque-withings/960-fix-requirements-txt-fixer-duplicated-elements
Remove duplicated packages
2 parents 454ade9 + 0d6d0a7 commit aae27b8

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

pre_commit_hooks/requirements_txt_fixer.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,11 @@ def __lt__(self, requirement: Requirement) -> bool:
4545
elif requirement.value == b'\n':
4646
return False
4747
else:
48+
# if 2 requirements have the same name, the one with comments
49+
# needs to go first (so that when removing duplicates, the one
50+
# with comments is kept)
51+
if self.name == requirement.name:
52+
return bool(self.comments) > bool(requirement.comments)
4853
return self.name < requirement.name
4954

5055
def is_complete(self) -> bool:
@@ -113,10 +118,14 @@ def fix_requirements(f: IO[bytes]) -> int:
113118
if req.value != b'pkg-resources==0.0.0\n'
114119
]
115120

121+
# sort the requirements and remove duplicates
122+
prev = None
116123
for requirement in sorted(requirements):
117124
after.extend(requirement.comments)
118125
assert requirement.value, requirement.value
119-
after.append(requirement.value)
126+
if prev is None or requirement.value != prev.value:
127+
after.append(requirement.value)
128+
prev = requirement
120129
after.extend(rest)
121130

122131
after_string = b''.join(after)

tests/requirements_txt_fixer_test.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,12 @@
6868
b'f<=2\n'
6969
b'g<2\n',
7070
),
71+
(b'a==1\nb==1\na==1\n', FAIL, b'a==1\nb==1\n'),
72+
(
73+
b'a==1\nb==1\n#comment about a\na==1\n',
74+
FAIL,
75+
b'#comment about a\na==1\nb==1\n',
76+
),
7177
(b'ocflib\nDjango\nPyMySQL\n', FAIL, b'Django\nocflib\nPyMySQL\n'),
7278
(
7379
b'-e git+ssh://git_url@tag#egg=ocflib\nDjango\nPyMySQL\n',

0 commit comments

Comments
 (0)