Skip to content

Commit e0c9d51

Browse files
authored
Merge pull request #483 from mxr/parse-reqs
Parse more operators in requirements
2 parents ad928f6 + 7ebd420 commit e0c9d51

File tree

2 files changed

+37
-5
lines changed

2 files changed

+37
-5
lines changed

pre_commit_hooks/requirements_txt_fixer.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import argparse
2+
import re
23
from typing import IO
34
from typing import List
45
from typing import Optional
@@ -10,18 +11,30 @@
1011

1112

1213
class Requirement:
14+
UNTIL_COMPARISON = re.compile(b'={2,3}|!=|~=|>=?|<=?')
15+
UNTIL_SEP = re.compile(rb'[^;\s]+')
16+
1317
def __init__(self) -> None:
1418
self.value: Optional[bytes] = None
1519
self.comments: List[bytes] = []
1620

1721
@property
1822
def name(self) -> bytes:
1923
assert self.value is not None, self.value
24+
name = self.value.lower()
2025
for egg in (b'#egg=', b'&egg='):
2126
if egg in self.value:
22-
return self.value.lower().partition(egg)[-1]
27+
return name.partition(egg)[-1]
28+
29+
m = self.UNTIL_SEP.match(name)
30+
assert m is not None
31+
32+
name = m.group()
33+
m = self.UNTIL_COMPARISON.search(name)
34+
if not m:
35+
return name
2336

24-
return self.value.lower().partition(b'==')[0]
37+
return name[:m.start()]
2538

2639
def __lt__(self, requirement: 'Requirement') -> int:
2740
# \n means top of file comment, so always return True,

tests/requirements_txt_fixer_test.py

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,28 @@
3333
(b'\nfoo\nbar\n', FAIL, b'bar\n\nfoo\n'),
3434
(b'\nbar\nfoo\n', PASS, b'\nbar\nfoo\n'),
3535
(
36-
b'pyramid==1\npyramid-foo==2\n',
37-
PASS,
38-
b'pyramid==1\npyramid-foo==2\n',
36+
b'pyramid-foo==1\npyramid>=2\n',
37+
FAIL,
38+
b'pyramid>=2\npyramid-foo==1\n',
39+
),
40+
(
41+
b'a==1\n'
42+
b'c>=1\n'
43+
b'bbbb!=1\n'
44+
b'c-a>=1;python_version>="3.6"\n'
45+
b'e>=2\n'
46+
b'd>2\n'
47+
b'g<2\n'
48+
b'f<=2\n',
49+
FAIL,
50+
b'a==1\n'
51+
b'bbbb!=1\n'
52+
b'c>=1\n'
53+
b'c-a>=1;python_version>="3.6"\n'
54+
b'd>2\n'
55+
b'e>=2\n'
56+
b'f<=2\n'
57+
b'g<2\n',
3958
),
4059
(b'ocflib\nDjango\nPyMySQL\n', FAIL, b'Django\nocflib\nPyMySQL\n'),
4160
(

0 commit comments

Comments
 (0)