8000 Code quality: utils.make_sure_path_exists refactored and type annotated by insspb · Pull Request #1722 · cookiecutter/cookiecutter · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Code quality: utils.make_sure_path_exists refactored and type annotated #1722

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions cookiecutter/generate.py
10000
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
import shutil
import warnings
from collections import OrderedDict

from pathlib import Path
from binaryornot.check import is_binary
from jinja2 import FileSystemLoader
from jinja2 import FileSystemLoader, Environment
from jinja2.exceptions import TemplateSyntaxError, UndefinedError

from cookiecutter.environment import StrictEnvironment
Expand Down Expand Up @@ -203,19 +203,23 @@ def generate_file(project_dir, infile, context, env, skip_if_file_exists=False):


def render_and_create_dir(
dirname, context, output_dir, environment, overwrite_if_exists=False
dirname: str,
context: dict,
output_dir: "os.PathLike[str]",
environment: Environment,
overwrite_if_exists: bool = False,
):
"""Render name of a directory, create the directory, return its path."""
name_tmpl = environment.from_string(dirname)
rendered_dirname = name_tmpl.render(**context)

dir_to_create = os.path.normpath(os.path.join(output_dir, rendered_dirname))
dir_to_create = Path(output_dir, rendered_dirname)

logger.debug(
'Rendered dir %s must exist in output_dir %s', dir_to_create, output_dir
)

output_dir_exists = os.path.exists(dir_to_create)
output_dir_exists = dir_to_create.exists()

if output_dir_exists:
if overwrite_if_exists:
Expand Down
5 changes: 2 additions & 3 deletions cookiecutter/replay.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,9 @@ def get_file_name(replay_dir, template_name):
return os.path.join(replay_dir, file_name)


def dump(replay_dir, template_name, context):
def dump(replay_dir: "os.PathLike[str]", template_name: str, context: dict):
"""Write json data to file."""
if not make_sure_path_exists(replay_dir):
raise OSError(f'Unable to create replay dir at {replay_dir}')
make_sure_path_exists(replay_dir)

if not isinstance(template_name, str):
raise TypeError('Template name is required to be of type str')
Expand Down
20 changes: 9 additions & 11 deletions cookiecutter/utils.py
8000
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
"""Helper functions used throughout Cookiecutter."""
import contextlib
import errno
import logging
import os
import shutil
import stat
import sys
from pathlib import Path

from cookiecutter.prompt import read_user_yes_no
from jinja2.ext import Extension

from cookiecutter.prompt import read_user_yes_no

logger = logging.getLogger(__name__)


Expand All @@ -31,19 +32,16 @@ def rmtree(path):
shutil.rmtree(path, >


def make_sure_path_exists(path):
def make_sure_path_exists(path: "os.PathLike[str]") -> None:
"""Ensure that a directory exists.

:param path: A directory path.
:param path: A directory tree path for creation.
"""
logger.debug('Making sure path exists: %s', path)
logger.debug('Making sure path exists (creates tree if not exist): %s', path)
try:
os.makedirs(path)
logger.debug('Created directory at: %s', path)
except OSError as exception:
if exception.errno != errno.EEXIST:
return False
return True
Path(path).mkdir(parents=True, exist_ok=True)
except OSError as error:
raise OSError(f'Unable to create directory at {path}') from error


@contextlib.contextmanager
Expand Down
11 changes: 9 additions & 2 deletions cookiecutter/vcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
import logging
import os
import subprocess # nosec
from pathlib import Path
from shutil import which
from typing import Optional

from cookiecutter.exceptions import (
RepositoryCloneFailed,
Expand Down Expand Up @@ -54,7 +56,12 @@ def is_vcs_installed(repo_type):
return bool(which(repo_type))


def clone(repo_url, checkout=None, clone_to_dir='.', no_input=False):
def clone(
repo_url: str,
checkout: Optional[str] = None,
clone_to_dir: "os.PathLike[str]" = ".",
no_input: bool = False,
):
"""Clone a repo to the current directory.

:param repo_url: Repo URL of unknown type.
Expand All @@ -66,7 +73,7 @@ def clone(repo_url, checkout=None, clone_to_dir='.', no_input=False):
:returns: str with path to the new directory of the repository.
"""
# Ensure that clone_to_dir exists
clone_to_dir = os.path.expanduser(clone_to_dir)
clone_to_dir = Path(clone_to_dir).expanduser()
make_sure_path_exists(clone_to_dir)

# identify the repo_type
Expand Down
12 changes: 10 additions & 2 deletions cookiecutter/zipfile.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Utility functions for handling and fetching repo archives in zip format."""
import os
import tempfile
from pathlib import Path
from typing import Optional
from zipfile import BadZipFile, ZipFile

import requests
Expand All @@ -10,7 +12,13 @@
from cookiecutter.utils import make_sure_path_exists, prompt_and_delete


def unzip(zip_uri, is_url, clone_to_dir='.', no_input=False, password=None):
def unzip(
zip_uri: str,
is_url: bool,
clone_to_dir: "os.PathLike[str]" = ".",
no_input: bool = False,
password: Optional[str] = None,
):
"""Download and unpack a zipfile at a given URI.

This will download the zipfile to the cookiecutter repository,
Expand All @@ -25,7 +33,7 @@ def unzip(zip_uri, is_url, clone_to_dir='.', no_input=False, password=None):
:param password: The password to use when unpacking the repository.
"""
# Ensure that clone_to_dir exists
clone_to_dir = os.path.expanduser(clone_to_dir)
clone_to_dir = Path(clone_to_dir).expanduser()
make_sure_path_exists(clone_to_dir)

if is_url:
Expand Down
6 changes: 4 additions & 2 deletions tests/replay/test_dump.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ def mock_ensure_failure(mocker):
Used to mock internal function and limit test scope.
Always return expected value: False
"""
return mocker.patch('cookiecutter.replay.make_sure_path_exists', return_value=False)
return mocker.patch(
'cookiecutter.replay.make_sure_path_exists', side_effect=OSError
)


@pytest.fixture
Expand All @@ -72,7 +74,7 @@ def mock_ensure_success(mocker):

def test_ioerror_if_replay_dir_creation_fails(mock_ensure_failure, replay_test_dir):
"""Test that replay.dump raises when the replay_dir cannot be created."""
with pytest.raises(IOError):
with pytest.raises(OSError):
replay.dump(replay_test_dir, 'foo', {'cookiecutter': {'hello': 'world'}})

mock_ensure_failure.assert_called_once_with(replay_test_dir)
Expand Down
16 changes: 6 additions & 10 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ def test_make_sure_path_exists(tmp_path):
existing_directory = tmp_path
directory_to_create = Path(tmp_path, "not_yet_created")

assert utils.make_sure_path_exists(existing_directory)
assert utils.make_sure_path_exists(directory_to_create)
utils.make_sure_path_exists(existing_directory)
utils.make_sure_path_exists(directory_to_create)

# Ensure by base system methods.
assert existing_directory.is_dir()
Expand All @@ -65,14 +65,10 @@ def test_make_sure_path_exists_correctly_handle_os_error(mocker):
Should return True if directory exist or created.
Should return False if impossible to create directory (for example protected)
"""

def raiser(*args, **kwargs):
raise OSError()

mocker.patch("os.makedirs", raiser)
uncreatable_directory = Path('protected_path')

assert not utils.make_sure_path_exists(uncreatable_directory)
mocker.patch("pathlib.Path.mkdir", side_effect=OSError)
with pytest.raises(OSError) as err:
utils.make_sure_path_exists(Path('protected_path'))
assert str(err.value) == "Unable to create directory at protected_path"


def test_work_in(tmp_path):
Expand Down
8 changes: 4 additions & 4 deletions tests/vcs/test_clone.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ def test_clone_should_rstrip_trailing_slash_in_repo_url(mocker, clone_dir):
autospec=True,
)

vcs.clone('https://github.com/foo/bar/', clone_to_dir=str(clone_dir), no_input=True)
vcs.clone('https://github.com/foo/bar/', clone_to_dir=clone_dir, no_input=True)

mock_subprocess.assert_called_once_with(
['git', 'clone', 'https://github.com/foo/bar'],
cwd=str(clone_dir),
cwd=clone_dir,
stderr=subprocess.STDOUT,
)

Expand Down Expand Up @@ -114,13 +114,13 @@ def test_clone_should_invoke_vcs_command(
branch = 'foobar'

repo_dir = vcs.clone(
repo_url, checkout=branch, clone_to_dir=str(clone_dir), no_input=True
repo_url, checkout=branch, clone_to_dir=clone_dir, no_input=True
)

assert repo_dir == expected_repo_dir

mock_subprocess.assert_any_call(
[repo_type, 'clone', repo_url], cwd=str(clone_dir), stderr=subprocess.STDOUT
[repo_type, 'clone', repo_url], cwd=clone_dir, stderr=subprocess.STDOUT
)

branch_info = [branch]
Expand Down
0