File: utils.py

package info (click to toggle)
cookiecutter 1.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,328 kB
  • sloc: python: 4,126; makefile: 242; sh: 4
file content (81 lines) | stat: -rw-r--r-- 1,690 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# -*- coding: utf-8 -*-

"""
cookiecutter.utils
------------------

Helper functions used throughout Cookiecutter.
"""

from __future__ import unicode_literals
import contextlib
import errno
import logging
import os
import stat
import shutil

logger = logging.getLogger(__name__)


def force_delete(func, path, exc_info):
    """
    Error handler for `shutil.rmtree()` equivalent to `rm -rf`
    Usage: `shutil.rmtree(path, onerror=force_delete)`
    From stackoverflow.com/questions/1889597
    """

    os.chmod(path, stat.S_IWRITE)
    func(path)


def rmtree(path):
    """
    Removes a directory and all its contents. Like rm -rf on Unix.

    :param path: A directory path.
    """

    shutil.rmtree(path, onerror=force_delete)


def make_sure_path_exists(path):
    """
    Ensures that a directory exists.

    :param path: A directory path.
    """

    logger.debug('Making sure path exists: {}'.format(path))
    try:
        os.makedirs(path)
        logger.debug('Created directory at: {}'.format(path))
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            return False
    return True


@contextlib.contextmanager
def work_in(dirname=None):
    """
    Context manager version of os.chdir. When exited, returns to the working
    directory prior to entering.
    """
    curdir = os.getcwd()
    try:
        if dirname is not None:
            os.chdir(dirname)
        yield
    finally:
        os.chdir(curdir)


def make_executable(script_path):
    """
    Makes `script_path` executable

    :param script_path: The file to change
    """
    status = os.stat(script_path)
    os.chmod(script_path, status.st_mode | stat.S_IEXEC)