diff --git a/docs/history/hatch.md b/docs/history/hatch.md index 360cd4663..83d0aaa28 100644 --- a/docs/history/hatch.md +++ b/docs/history/hatch.md @@ -32,6 +32,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Fix nushell activation - Better handling of flat storage directory hierarchies for the `virtual` environment type +- Display useful information when running the `version` command outside of a project rather than erroring ## [1.7.0](https://github.com/pypa/hatch/releases/tag/hatch-v1.7.0) - 2023-04-03 ## {: #hatch-v1.7.0 } diff --git a/src/hatch/cli/version/__init__.py b/src/hatch/cli/version/__init__.py index c79d3e264..02fe637e2 100644 --- a/src/hatch/cli/version/__init__.py +++ b/src/hatch/cli/version/__init__.py @@ -1,11 +1,24 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + import click +if TYPE_CHECKING: + from hatch.cli.application import Application + @click.command(short_help="View or set a project's version") @click.argument('desired_version', required=False) @click.pass_obj -def version(app, desired_version): +def version(app: Application, desired_version: str | None): """View or set a project's version.""" + if app.project.root is None: + if app.project.chosen_name is None: + app.abort('No project detected') + else: + app.abort(f'Project {app.project.chosen_name} (not a project)') + if 'version' in app.project.metadata.config.get('project', {}): if desired_version: app.abort('Cannot set version when it is statically defined by the `project.version` field') diff --git a/tests/cli/version/test_version.py b/tests/cli/version/test_version.py index 1755c6ef2..80d6d9972 100644 --- a/tests/cli/version/test_version.py +++ b/tests/cli/version/test_version.py @@ -6,6 +6,36 @@ from hatchling.utils.constants import DEFAULT_BUILD_SCRIPT, DEFAULT_CONFIG_FILE +class TestNoProject: + def test_random_directory(self, hatch, temp_dir, helpers): + with temp_dir.as_cwd(): + result = hatch('version') + + assert result.exit_code == 1, result.output + assert result.output == helpers.dedent( + """ + No project detected + """ + ) + + def test_configured_project(self, hatch, temp_dir, helpers, config_file): + project = 'foo' + config_file.model.mode = 'project' + config_file.model.project = project + config_file.model.projects = {project: str(temp_dir)} + config_file.save() + + with temp_dir.as_cwd(): + result = hatch('version') + + assert result.exit_code == 1, result.output + assert result.output == helpers.dedent( + """ + Project foo (not a project) + """ + ) + + def test_incompatible_environment(hatch, temp_dir, helpers): project_name = 'My.App'