Skip to content

Commit 04a2628

Browse files
committed
Refactor range parsing logic for clarity and flexibility
1 parent b900d6a commit 04a2628

File tree

1 file changed

+33
-28
lines changed

1 file changed

+33
-28
lines changed

src/gptcmd/cli.py

Lines changed: 33 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -113,46 +113,51 @@ def _fragment(tpl: str, msg: Message) -> str:
113113

114114
@staticmethod
115115
def _user_range_to_python_range(
116-
ref: str,
116+
ref: str, allow_single: bool = True, strict_range: bool = True
117117
) -> Tuple[Optional[int], Optional[int]]:
118-
c = ref.count(" ")
119-
if c == 0:
120-
if ref == ".":
118+
tokens = ref.split()
119+
if not tokens:
120+
raise ValueError("No indices provided")
121+
if len(tokens) == 1:
122+
if tokens[0] == ".":
121123
return (None, None)
122-
start = end = ref
123-
elif c == 1:
124-
start, end = ref.split()
124+
if not allow_single:
125+
raise ValueError("Wrong number of indices")
126+
start = end = tokens[0]
127+
elif len(tokens) == 2:
128+
start, end = tokens
125129
else:
126130
raise ValueError("Wrong number of indices")
127131

128-
if start == ".":
129-
py_start = None
130-
else:
131-
py_start = int(start)
132-
if py_start > 0:
133-
py_start -= 1 # Python indices are zero-based
134-
if end == ".":
135-
py_end = None
136-
else:
137-
py_end = int(end)
138-
if py_end > 0:
139-
py_end -= 1 # Python indices are zero-based
140-
py_end += 1 # Python indices are end exclusive
141-
elif py_end == -1:
142-
py_end = None
132+
def _convert(token: str, is_start: bool) -> Optional[int]:
133+
if token == ".":
134+
return None
135+
val = int(token)
136+
if is_start:
137+
return val - 1 if val > 0 else val
143138
else:
144-
py_end += 1 # Python indices are end exclusive
139+
if val > 0:
140+
return val
141+
elif val == -1:
142+
return None
143+
else:
144+
return val + 1
145145

146-
if c == 0:
147-
# Don't return an empty range
146+
py_start = _convert(start, True)
147+
py_end = _convert(end, False)
148+
149+
if len(tokens) == 1:
148150
if py_start == -1:
149151
py_end = None
150152
elif py_start is not None:
151153
py_end = py_start + 1
152-
153-
if py_start is not None and py_end is not None and py_start >= py_end:
154+
if (
155+
strict_range
156+
and py_start is not None
157+
and py_end is not None
158+
and py_start >= py_end
159+
):
154160
raise ValueError("Range end is beyond its start")
155-
156161
return py_start, py_end
157162

158163
@staticmethod

0 commit comments

Comments
 (0)