Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/django/core/management/utils.py: 17%
85 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1import fnmatch
2import os
3from pathlib import Path
4from subprocess import PIPE, run
6from django.apps import apps as installed_apps
7from django.utils.crypto import get_random_string
8from django.utils.encoding import DEFAULT_LOCALE_ENCODING
10from .base import CommandError, CommandParser
13def popen_wrapper(args, stdout_encoding="utf-8"):
14 """
15 Friendly wrapper around Popen.
17 Return stdout output, stderr output, and OS status code.
18 """
19 try:
20 p = run(args, stdout=PIPE, stderr=PIPE, close_fds=os.name != "nt")
21 except OSError as err:
22 raise CommandError("Error executing %s" % args[0]) from err
23 return (
24 p.stdout.decode(stdout_encoding),
25 p.stderr.decode(DEFAULT_LOCALE_ENCODING, errors="replace"),
26 p.returncode,
27 )
30def handle_extensions(extensions):
31 """
32 Organize multiple extensions that are separated with commas or passed by
33 using --extension/-e multiple times.
35 For example: running 'django-admin makemessages -e js,txt -e xhtml -a'
36 would result in an extension list: ['.js', '.txt', '.xhtml']
38 >>> handle_extensions(['.html', 'html,js,py,py,py,.py', 'py,.py'])
39 {'.html', '.js', '.py'}
40 >>> handle_extensions(['.html, txt,.tpl'])
41 {'.html', '.tpl', '.txt'}
42 """
43 ext_list = []
44 for ext in extensions:
45 ext_list.extend(ext.replace(" ", "").split(","))
46 for i, ext in enumerate(ext_list):
47 if not ext.startswith("."):
48 ext_list[i] = ".%s" % ext_list[i]
49 return set(ext_list)
52def find_command(cmd, path=None, pathext=None):
53 if path is None:
54 path = os.environ.get("PATH", "").split(os.pathsep)
55 if isinstance(path, str):
56 path = [path]
57 # check if there are funny path extensions for executables, e.g. Windows
58 if pathext is None:
59 pathext = os.environ.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(os.pathsep)
60 # don't use extensions if the command ends with one of them
61 for ext in pathext:
62 if cmd.endswith(ext):
63 pathext = [""]
64 break
65 # check if we find the command on PATH
66 for p in path:
67 f = os.path.join(p, cmd)
68 if os.path.isfile(f):
69 return f
70 for ext in pathext:
71 fext = f + ext
72 if os.path.isfile(fext):
73 return fext
74 return None
77def get_random_secret_key():
78 """
79 Return a 50 character random string usable as a SECRET_KEY setting value.
80 """
81 chars = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)"
82 return get_random_string(50, chars)
85def parse_apps_and_model_labels(labels):
86 """
87 Parse a list of "app_label.ModelName" or "app_label" strings into actual
88 objects and return a two-element tuple:
89 (set of model classes, set of app_configs).
90 Raise a CommandError if some specified models or apps don't exist.
91 """
92 apps = set()
93 models = set()
95 for label in labels:
96 if "." in label:
97 try:
98 model = installed_apps.get_model(label)
99 except LookupError:
100 raise CommandError("Unknown model: %s" % label)
101 models.add(model)
102 else:
103 try:
104 app_config = installed_apps.get_app_config(label)
105 except LookupError as e:
106 raise CommandError(str(e))
107 apps.add(app_config)
109 return models, apps
112def get_command_line_option(argv, option):
113 """
114 Return the value of a command line option (which should include leading
115 dashes, e.g. '--testrunner') from an argument list. Return None if the
116 option wasn't passed or if the argument list couldn't be parsed.
117 """
118 parser = CommandParser(add_help=False, allow_abbrev=False)
119 parser.add_argument(option, dest="value")
120 try:
121 options, _ = parser.parse_known_args(argv[2:])
122 except CommandError:
123 return None
124 else:
125 return options.value
128def normalize_path_patterns(patterns):
129 """Normalize an iterable of glob style patterns based on OS."""
130 patterns = [os.path.normcase(p) for p in patterns]
131 dir_suffixes = {"%s*" % path_sep for path_sep in {"/", os.sep}}
132 norm_patterns = []
133 for pattern in patterns:
134 for dir_suffix in dir_suffixes:
135 if pattern.endswith(dir_suffix):
136 norm_patterns.append(pattern[: -len(dir_suffix)])
137 break
138 else:
139 norm_patterns.append(pattern)
140 return norm_patterns
143def is_ignored_path(path, ignore_patterns):
144 """
145 Check if the given path should be ignored or not based on matching
146 one of the glob style `ignore_patterns`.
147 """
148 path = Path(path)
150 def ignore(pattern):
151 return fnmatch.fnmatchcase(path.name, pattern) or fnmatch.fnmatchcase(
152 str(path), pattern
153 )
155 return any(ignore(pattern) for pattern in normalize_path_patterns(ignore_patterns))