Skip to content

Comments

fix: unexpected behavior of new command in existing empty directories#10431

Merged
radoering merged 6 commits intopython-poetry:mainfrom
SoSaymon:main
Jul 7, 2025
Merged

fix: unexpected behavior of new command in existing empty directories#10431
radoering merged 6 commits intopython-poetry:mainfrom
SoSaymon:main

Conversation

@SoSaymon
Copy link
Contributor

@SoSaymon SoSaymon commented Jun 14, 2025

Pull Request Check List

Resolves: #10429

Fix poetry new behavior when used in an existing empty directory

This pull request addresses unexpected behavior when running poetry new in an already existing empty directory, including the current directory (.). It ensures that poetry new handles these cases correctly, while maintaining the expected behavior of poetry init.

The fix introduces a new argument, create_layout_if_empty, to the _init_pyproject method in the InitCommand class. Additionally, it adds a conditional check to determine whether a full project layout should be created or only a pyproject.toml file.

Summary by Sourcery

Ensure 'poetry new' generates full project layout in existing empty directories while 'poetry init' only creates a pyproject.toml in such cases

Bug Fixes:

  • Fix 'poetry new' not creating project structure in existing empty directories

Enhancements:

  • Introduce 'allow_layout_creation_on_empty' flag in init_pyproject to control layout creation in empty dirs
  • Enable the new flag in the 'new' command to trigger full layout generation in empty dirs

Tests:

  • Add tests verifying that 'poetry init' only creates a pyproject.toml in empty or non-empty directories without extra files
  • Add tests verifying that 'poetry new' generates full project structure in existing empty directories and when using '.'

Add note explaining that `poetry new .` in empty directories
creates only pyproject.toml, not full project structure.

Closes python-poetry#10429
@sourcery-ai
Copy link

sourcery-ai bot commented Jun 14, 2025

Reviewer's Guide

This PR introduces a flag to control project layout creation in empty directories by updating the internal init logic and enabling it in the new command, while adding targeted tests to ensure poetry init and poetry new behave correctly across empty, non-empty, and “.” directory scenarios.

Sequence diagram for poetry new in existing empty directory

sequenceDiagram
    actor User
    participant PoetryNew as poetry new
    participant InitCommand
    User->>PoetryNew: Run 'poetry new .' (in empty dir)
    PoetryNew->>InitCommand: _init_pyproject(..., allow_layout_creation_on_empty=True)
    InitCommand->>InitCommand: Check if directory is empty
    InitCommand->>InitCommand: Create full project layout
    InitCommand-->>PoetryNew: Return success
    PoetryNew-->>User: Project scaffold created
Loading

Sequence diagram for poetry init in existing empty directory

sequenceDiagram
    actor User
    participant PoetryInit as poetry init
    participant InitCommand
    User->>PoetryInit: Run 'poetry init' (in empty dir)
    PoetryInit->>InitCommand: _init_pyproject(..., allow_layout_creation_on_empty=False)
    InitCommand->>InitCommand: Check if directory is empty
    InitCommand->>InitCommand: Only create pyproject.toml
    InitCommand-->>PoetryInit: Return success
    PoetryInit-->>User: pyproject.toml created (no layout)
Loading

Class diagram for InitCommand and new allow_layout_creation_on_empty parameter

classDiagram
    class InitCommand {
        +_init_pyproject(allow_interactive: bool, layout_name: str, readme_format: str, allow_layout_creation_on_empty: bool = False)
    }
    class NewCommand {
        +handle()
    }
    InitCommand <|-- NewCommand
    InitCommand : +_init_pyproject(..., allow_layout_creation_on_empty)
    NewCommand : +handle() calls _init_pyproject with allow_layout_creation_on_empty=True
Loading

File-Level Changes

Change Details Files
Extend _init_pyproject to support layout creation in existing empty directories
  • Add allow_layout_creation_on_empty parameter (default False) to method signature
  • Modify create_layout condition to include empty-dir check when flag is enabled
src/poetry/console/commands/init.py
Enable layout-creation flag in the poetry new command
  • Pass allow_layout_creation_on_empty=True when invoking _init_pyproject
src/poetry/console/commands/new.py
Add tests to verify poetry init does not scaffold existing directories
  • Test init in an empty existing directory creates only pyproject.toml
  • Test init in a non-empty directory leaves existing files and creates only pyproject.toml
tests/console/commands/test_init.py
Add tests to verify poetry new scaffolds existing empty directories
  • Test poetry new in an empty directory generates full project structure
  • Test poetry new . works correctly in an empty current directory
tests/console/commands/test_new.py

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @SoSaymon - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@radoering
Copy link
Member

I think we should prefer to fix/change the behavior rather than document it. See #10429 (comment).

SoSaymon added 4 commits June 30, 2025 01:13
Fix `poetry new` behavior when used in an existing empty directory

This commit addresses unexpected behavior when running `poetry new` in an already existing empty directory, including the current directory (`.`). It ensures that `poetry new` handles these cases correctly, while maintaining the expected behavior of `poetry init`.

The fix introduces a new argument, `create_layout_if_empty`, to the `_init_pyproject` method in the `InitCommand` class. Additionally, it adds a conditional check to determine whether a full project layout should be created or only a `pyproject.toml` file.
@SoSaymon SoSaymon changed the title docs: document poetry new behavior in existing empty directories fix: unexpected behavior of new command in existing empty directories Jun 29, 2025
@SoSaymon
Copy link
Contributor Author

@sourcery-ai review

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @SoSaymon - I've reviewed your changes - here's some feedback:

  • Consider extracting the “empty directory” check (not any(project_path.iterdir())) into a reusable helper (e.g. Path.is_empty()) to improve readability and avoid duplication.
  • The flag name create_layout_if_empty is a bit opaque—something like allow_layout_creation_on_empty or similar might more clearly convey its intent.
  • Right now hidden files (e.g. .gitignore) count as directory contents; if your intent is to treat directories with only dotfiles as “empty,” you may want to adjust the emptiness check to ignore those patterns.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider extracting the “empty directory” check (`not any(project_path.iterdir())`) into a reusable helper (e.g. `Path.is_empty()`) to improve readability and avoid duplication.
- The flag name `create_layout_if_empty` is a bit opaque—something like `allow_layout_creation_on_empty` or similar might more clearly convey its intent.
- Right now hidden files (e.g. `.gitignore`) count as directory contents; if your intent is to treat directories with only dotfiles as “empty,” you may want to adjust the emptiness check to ignore those patterns.

## Individual Comments

### Comment 1
<location> `src/poetry/console/commands/init.py:93` </location>
<code_context>
         allow_interactive: bool = True,
         layout_name: str = "standard",
         readme_format: str = "md",
+        create_layout_if_empty: bool = False,
     ) -> int:
         from poetry.core.vcs.git import GitConfig
</code_context>

<issue_to_address>
Consider documenting the new parameter's intended usage and default behavior.

Clarifying how this parameter behaves when the project path exists but is empty will help prevent confusion or misuse.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
        allow_interactive: bool = True,
        layout_name: str = "standard",
        readme_format: str = "md",
        create_layout_if_empty: bool = False,
    ) -> int:
        from poetry.core.vcs.git import GitConfig
=======
        allow_interactive: bool = True,
        layout_name: str = "standard",
        readme_format: str = "md",
        create_layout_if_empty: bool = False,
    ) -> int:
        """
        Initializes a new Poetry project in the specified directory.

        Parameters:
            allow_interactive (bool): If True, allows interactive prompts during initialization.
            layout_name (str): The name of the project layout to use.
            readme_format (str): The format for the README file.
            create_layout_if_empty (bool): If True, the project layout will be created if the target
                project path exists and is empty. Defaults to False. If False, the layout is only
                created if the project path does not exist.

        When `create_layout_if_empty` is True and the specified project path exists but contains no files,
        the command will proceed to create the project layout as if the directory were new. This helps
        avoid errors or confusion when initializing in an empty directory.
        """
        from poetry.core.vcs.git import GitConfig
>>>>>>> REPLACE

</suggested_fix>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@SoSaymon SoSaymon marked this pull request as draft June 29, 2025 23:33
@SoSaymon
Copy link
Contributor Author

SoSaymon commented Jul 4, 2025

I’ve renamed the flag to something more descriptive.

I decided not to extract the not any(project_path.iterdir()) check into a helper like Path.is_empty(), since it's only used once and introducing a helper felt unnecessary in this context.

Regarding the suggestion about dotfiles: in this case, directories containing dotfiles are deliberately treated as non-empty, which is intentional.

Happy to revisit either the helper function or the dotfile treatment if maintainers feel strongly about it.

@SoSaymon SoSaymon marked this pull request as ready for review July 4, 2025 23:24
Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @SoSaymon - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Member

@radoering radoering left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@radoering radoering merged commit 427d922 into python-poetry:main Jul 7, 2025
53 checks passed
@github-actions
Copy link

github-actions bot commented Aug 7, 2025

This pull request has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Aug 7, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unexpected Behavior: poetry new . Acts Like poetry init Without Creating Project Structure

2 participants