Skip to content

Commit 430350e

Browse files
committed
fix(cli): Handle --version compatible with G_IS_TEST pattern
The previous implementation used argparse's version action which calls sys.exit(), preventing run() from returning in test mode. Now version is printed manually and returns None when G_IS_TEST is set, matching the pattern used when no VCS is found. Adds tests for --version and -V flags.
1 parent 8033764 commit 430350e

2 files changed

Lines changed: 39 additions & 3 deletions

File tree

src/g/__init__.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
from g.__about__ import __version__
1616

17-
__all__ = ["DEFAULT", "create_parser", "run", "sys", "vcspath_registry"]
17+
__all__ = ["DEFAULT", "__version__", "create_parser", "run", "sys", "vcspath_registry"]
1818

1919
vcspath_registry = {".git": "git", ".svn": "svn", ".hg": "hg"}
2020

@@ -99,8 +99,10 @@ def run(
9999
# Handle --version/-V before VCS detection
100100
assert isinstance(cmd_args, (tuple, list))
101101
if cmd_args and cmd_args[0] in ("--version", "-V"):
102-
parser = create_parser()
103-
parser.parse_args(["--version"]) # Will print version and exit
102+
print(f"g {__version__}")
103+
if os.getenv("G_IS_TEST") and __name__ != "__main__":
104+
return None
105+
sys.exit(0)
104106

105107
if cmd is DEFAULT:
106108
cmd = find_repo_type(pathlib.Path.cwd())

tests/test_cli.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,18 @@ class CommandLineTestFixture(t.NamedTuple):
8181
argv_args=["g --help"],
8282
expect_cmd=None,
8383
),
84+
CommandLineTestFixture(
85+
test_id="g-version-inside-git-dir",
86+
env=EnvFlag.Git,
87+
argv_args=["g", "--version"],
88+
expect_cmd=None, # Returns None after printing version
89+
),
90+
CommandLineTestFixture(
91+
test_id="g-version-short-inside-empty-dir",
92+
env=EnvFlag.Empty,
93+
argv_args=["g", "-V"],
94+
expect_cmd=None,
95+
),
8496
]
8597

8698

@@ -120,3 +132,25 @@ def test_command_line(
120132
shell=True,
121133
stderr=subprocess.STDOUT,
122134
)
135+
136+
137+
def test_version_output(capsys: pytest.CaptureFixture[str]) -> None:
138+
"""Test that --version prints the correct version string."""
139+
from g import __version__, sys as gsys
140+
141+
with patch.object(gsys, "argv", ["g", "--version"]):
142+
result = run()
143+
assert result is None
144+
captured = capsys.readouterr()
145+
assert f"g {__version__}" in captured.out
146+
147+
148+
def test_version_short_output(capsys: pytest.CaptureFixture[str]) -> None:
149+
"""Test that -V prints the correct version string."""
150+
from g import __version__, sys as gsys
151+
152+
with patch.object(gsys, "argv", ["g", "-V"]):
153+
result = run()
154+
assert result is None
155+
captured = capsys.readouterr()
156+
assert f"g {__version__}" in captured.out

0 commit comments

Comments
 (0)