• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

idlesign / makeapp / 15538900042

09 Jun 2025 04:00PM UTC coverage: 90.076%. Remained the same
15538900042

push

github

idlesign
Py3.10 compat.

0 of 1 new or added line in 1 file covered. (0.0%)

826 of 917 relevant lines covered (90.08%)

3.6 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

73.44
/src/makeapp/utils.py
1
import configparser
4✔
2
import fileinput
4✔
3
import logging
4✔
4
import os
4✔
5
import shutil
4✔
6
import sys
4✔
7
import tempfile
4✔
8
from configparser import ConfigParser
4✔
9
from contextlib import contextmanager
4✔
10
from pathlib import Path
4✔
11
from subprocess import Popen, PIPE, STDOUT
4✔
12
from typing import Generator
4✔
13

14
from .exceptions import CommandError
4✔
15

16
LOG = logging.getLogger(__name__)
4✔
17
PYTHON_VERSION = sys.version_info
4✔
18

19

20
def configure_logging(
4✔
21
        level: int | None = None,
22
        logger: logging.Logger | None = None,
23
        format: str = '%(message)s'
24
):
25
    """Switches on logging at a given level. For a given logger or globally.
26

27
    :param level:
28
    :param logger:
29
    :param format:
30

31
    """
32
    logging.basicConfig(format=format, level=level if level else None)
4✔
33
    logger and logger.setLevel(level or logging.INFO)
4✔
34

35

36
def get_user_dir() -> Path:
4✔
37
    """Returns the user's home directory."""
38
    return Path(os.path.expanduser('~'))
4✔
39

40

41
def read_ini(fpath: Path) -> ConfigParser:
4✔
42
    """Read a .ini file.
43

44
    :param fpath:
45
    """
46
    cfg = configparser.ConfigParser()
×
47
    cfg.read(f'{fpath}')
×
48
    return cfg
×
49

50

51
@contextmanager
4✔
52
def chdir(target_path):
4✔
53
    """Context manager.
54
     
55
    Temporarily switches the current working directory.
56
    
57
    """
58
    curr_dir = os.getcwd()
4✔
59
    os.chdir(target_path)
4✔
60

61
    try:
4✔
62
        yield
4✔
63

64
    finally:
65
        os.chdir(curr_dir)
4✔
66

67

68
@contextmanager
4✔
69
def temp_dir() -> Generator[str, None, None]:
4✔
70
    """Context manager to temporarily create a directory."""
71

72
    dir_tmp = tempfile.mkdtemp(prefix='makeapp_')
×
73

74
    try:
×
75
        yield dir_tmp
×
76

77
    finally:
78
        shutil.rmtree(dir_tmp, ignore_errors=True)
×
79

80

81
def replace_infile(filepath: str, pairs: dict[str, str]):
4✔
82
    """Replaces some term by another in file contents.
83

84
    :param filepath:
85
    :param pairs: search -> replace.
86

87
    """
88
    with fileinput.input(files=filepath, inplace=True) as f:
×
89

90
        for line in f:
×
91

92
            for search, replace in pairs.items():
×
93
                line = line.replace(search, replace)
×
94

95
            sys.stdout.write(line)
×
96

97

98
def check_command(command: str, *, hint: str):
4✔
99
    """Checks whether a command is available.
100
    If not - raises an exception.
101

102
    :param command:
103
    :param hint:
104

105
    """
106
    try:
4✔
107
        run_command(f'type {command}')
4✔
108

109
    except CommandError:
×
110
        raise CommandError(
×
111
            f"Failed to execute '{command}' command. "
112
            f"Check {hint} is installed and available.")
113

114

115
def run_command(command: str, *, err_msg: str = '', env: dict | None = None) -> list[str]:
4✔
116
    """Runs a command in a shell process.
117

118
    Returns a list of strings gathered from a command.
119

120
    :param command:
121

122
    :param err_msg: Message to show on error.
123

124
    :param env: Environment variables to use.
125

126
    :raises: CommandError
127

128
    """
129
    if env:
4✔
130
        env = {**os.environ, **env}
×
131

132
    LOG.debug(f'Run command: `{command}` ...')
4✔
133

134
    prc = Popen(command, stdout=PIPE, stderr=STDOUT, shell=True, universal_newlines=True, env=env)
4✔
135

136
    data = []
4✔
137
    out, _ = prc.communicate()
4✔
138

139
    LOG.debug(f'Command output:\n`{out}`')
4✔
140

141
    for item in out.splitlines():
4✔
142
        item = item.strip()
4✔
143

144
        if not item:
4✔
145
            continue
×
146

147
        data.append(item)
4✔
148

149
    if prc.returncode:
4✔
NEW
150
        raise CommandError(err_msg or f"Command `{command}` failed: %s" % '\n'.join(data))
×
151

152
    return data
4✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc