edq-utils 0.0.1__tar.gz → 0.0.3__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of edq-utils might be problematic. Click here for more details.
- {edq_utils-0.0.1 → edq_utils-0.0.3}/PKG-INFO +3 -1
- edq_utils-0.0.3/edq/__init__.py +5 -0
- edq_utils-0.0.3/edq/testing/__init__.py +3 -0
- edq_utils-0.0.3/edq/testing/run.py +112 -0
- edq_utils-0.0.3/edq/testing/unittest.py +54 -0
- edq_utils-0.0.3/edq/util/__init__.py +3 -0
- edq_utils-0.0.3/edq/util/dirent.py +338 -0
- edq_utils-0.0.3/edq/util/dirent_test.py +968 -0
- edq_utils-0.0.3/edq/util/json.py +163 -0
- edq_utils-0.0.3/edq/util/json_test.py +228 -0
- edq_utils-0.0.3/edq/util/pyimport.py +73 -0
- edq_utils-0.0.3/edq/util/pyimport_test.py +83 -0
- edq_utils-0.0.3/edq/util/reflection.py +32 -0
- edq_utils-0.0.3/edq/util/time.py +75 -0
- edq_utils-0.0.3/edq/util/time_test.py +107 -0
- {edq_utils-0.0.1 → edq_utils-0.0.3}/edq_utils.egg-info/PKG-INFO +3 -1
- edq_utils-0.0.3/edq_utils.egg-info/SOURCES.txt +33 -0
- {edq_utils-0.0.1 → edq_utils-0.0.3}/edq_utils.egg-info/requires.txt +2 -0
- {edq_utils-0.0.1 → edq_utils-0.0.3}/requirements-dev.txt +1 -0
- edq_utils-0.0.3/requirements.txt +1 -0
- edq_utils-0.0.1/edq/__init__.py +0 -1
- edq_utils-0.0.1/edq/util/dirent.py +0 -154
- edq_utils-0.0.1/edq/util/dirent_test.py +0 -170
- edq_utils-0.0.1/edq_utils.egg-info/SOURCES.txt +0 -21
- {edq_utils-0.0.1 → edq_utils-0.0.3}/LICENSE +0 -0
- {edq_utils-0.0.1 → edq_utils-0.0.3}/README.md +0 -0
- /edq_utils-0.0.1/edq/util/__init__.py → /edq_utils-0.0.3/edq/py.typed +0 -0
- {edq_utils-0.0.1 → edq_utils-0.0.3}/edq/util/testdata/dirent-operations/a.txt +0 -0
- {edq_utils-0.0.1 → edq_utils-0.0.3}/edq/util/testdata/dirent-operations/dir_1/b.txt +0 -0
- {edq_utils-0.0.1 → edq_utils-0.0.3}/edq/util/testdata/dirent-operations/dir_1/dir_2/c.txt +0 -0
- {edq_utils-0.0.1 → edq_utils-0.0.3}/edq/util/testdata/dirent-operations/file_empty +0 -0
- /edq_utils-0.0.1/edq/util/testdata/dirent-operations/symlinklink_a.txt → /edq_utils-0.0.3/edq/util/testdata/dirent-operations/symlink_a.txt +0 -0
- {edq_utils-0.0.1/edq/util/testdata/dirent-operations/symlinklink_dir_1 → edq_utils-0.0.3/edq/util/testdata/dirent-operations/symlink_dir_1}/b.txt +0 -0
- {edq_utils-0.0.1/edq/util/testdata/dirent-operations/symlinklink_dir_1 → edq_utils-0.0.3/edq/util/testdata/dirent-operations/symlink_dir_1}/dir_2/c.txt +0 -0
- /edq_utils-0.0.1/requirements.txt → /edq_utils-0.0.3/edq/util/testdata/dirent-operations/symlink_file_empty +0 -0
- {edq_utils-0.0.1 → edq_utils-0.0.3}/edq_utils.egg-info/dependency_links.txt +0 -0
- {edq_utils-0.0.1 → edq_utils-0.0.3}/edq_utils.egg-info/top_level.txt +0 -0
- {edq_utils-0.0.1 → edq_utils-0.0.3}/pyproject.toml +0 -0
- {edq_utils-0.0.1 → edq_utils-0.0.3}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: edq-utils
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.3
|
|
4
4
|
Summary: Common utilities used by EduLinq Python projects.
|
|
5
5
|
Author-email: Eriq Augustine <eriq@edulinq.org>
|
|
6
6
|
License: MIT License
|
|
@@ -34,8 +34,10 @@ Classifier: Programming Language :: Python :: 3.8
|
|
|
34
34
|
Requires-Python: >=3.8
|
|
35
35
|
Description-Content-Type: text/markdown
|
|
36
36
|
License-File: LICENSE
|
|
37
|
+
Requires-Dist: json5>=0.9.14
|
|
37
38
|
Provides-Extra: dev
|
|
38
39
|
Requires-Dist: mypy>=1.14.1; extra == "dev"
|
|
40
|
+
Requires-Dist: pdoc>=14.7.0; extra == "dev"
|
|
39
41
|
Requires-Dist: pylint; extra == "dev"
|
|
40
42
|
Requires-Dist: twine; extra == "dev"
|
|
41
43
|
Requires-Dist: vermin; extra == "dev"
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Discover and run unit tests (via Python's unittest package)
|
|
3
|
+
that live in this project's base package
|
|
4
|
+
(the parent of this package).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import sys
|
|
11
|
+
import typing
|
|
12
|
+
import unittest
|
|
13
|
+
|
|
14
|
+
DEFAULT_TEST_FILENAME_PATTERN: str = '*_test.py'
|
|
15
|
+
|
|
16
|
+
def _collect_tests(suite: typing.Union[unittest.TestCase, unittest.suite.TestSuite]) -> typing.List[unittest.TestCase]:
|
|
17
|
+
"""
|
|
18
|
+
Collect and return tests (unittest.TestCase) from the target directory.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
if (isinstance(suite, unittest.TestCase)):
|
|
22
|
+
return [suite]
|
|
23
|
+
|
|
24
|
+
if (not isinstance(suite, unittest.suite.TestSuite)):
|
|
25
|
+
raise ValueError(f"Unknown test type: '{str(type(suite))}'.")
|
|
26
|
+
|
|
27
|
+
test_cases = []
|
|
28
|
+
for test_object in suite:
|
|
29
|
+
test_cases += _collect_tests(test_object)
|
|
30
|
+
|
|
31
|
+
return test_cases
|
|
32
|
+
|
|
33
|
+
def run(args: argparse.Namespace) -> int:
|
|
34
|
+
"""
|
|
35
|
+
Discover and run unit tests.
|
|
36
|
+
This function may change your working directory.
|
|
37
|
+
Will raise if tests fail to load (e.g. syntax errors) and a suggested exit code otherwise.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
if (args.work_dir is not None):
|
|
41
|
+
os.chdir(args.work_dir)
|
|
42
|
+
|
|
43
|
+
if (args.path_additions is not None):
|
|
44
|
+
for path in args.path_additions:
|
|
45
|
+
sys.path.append(path)
|
|
46
|
+
|
|
47
|
+
if (args.test_dirs is None):
|
|
48
|
+
args.test_dirs = ['.']
|
|
49
|
+
|
|
50
|
+
runner = unittest.TextTestRunner(verbosity = 3)
|
|
51
|
+
test_cases = []
|
|
52
|
+
|
|
53
|
+
for test_dir in args.test_dirs:
|
|
54
|
+
discovered_suite = unittest.TestLoader().discover(test_dir, pattern = args.filename_pattern)
|
|
55
|
+
test_cases += _collect_tests(discovered_suite)
|
|
56
|
+
|
|
57
|
+
tests = unittest.suite.TestSuite()
|
|
58
|
+
|
|
59
|
+
for test_case in test_cases:
|
|
60
|
+
if (isinstance(test_case, unittest.loader._FailedTest)): # type: ignore[attr-defined]
|
|
61
|
+
raise ValueError(f"Failed to load test: '{test_case.id()}'.") from test_case._exception
|
|
62
|
+
|
|
63
|
+
if (args.pattern is None or re.search(args.pattern, test_case.id())):
|
|
64
|
+
tests.addTest(test_case)
|
|
65
|
+
else:
|
|
66
|
+
print(f"Skipping {test_case.id()} because of match pattern.")
|
|
67
|
+
|
|
68
|
+
result = runner.run(tests)
|
|
69
|
+
faults = len(result.errors) + len(result.failures)
|
|
70
|
+
|
|
71
|
+
if (not result.wasSuccessful()):
|
|
72
|
+
# This value will be used as an exit status, so it should not be larger than a byte.
|
|
73
|
+
# (Some higher values are used specially, so just keep it at a round number.)
|
|
74
|
+
return max(1, min(faults, 100))
|
|
75
|
+
|
|
76
|
+
return 0
|
|
77
|
+
|
|
78
|
+
def main() -> int:
|
|
79
|
+
""" Parse the CLI arguments and run tests. """
|
|
80
|
+
|
|
81
|
+
args = _get_parser().parse_args()
|
|
82
|
+
return run(args)
|
|
83
|
+
|
|
84
|
+
def _get_parser() -> argparse.ArgumentParser:
|
|
85
|
+
""" Build a parser for CLI arguments. """
|
|
86
|
+
|
|
87
|
+
parser = argparse.ArgumentParser(description = 'Run unit tests discovered in this project.')
|
|
88
|
+
|
|
89
|
+
parser.add_argument('--work-dir', dest = 'work_dir',
|
|
90
|
+
action = 'store', type = str, default = os.getcwd(),
|
|
91
|
+
help = 'Set the working directory when running tests, defaults to the current working directory (%(default)s).')
|
|
92
|
+
|
|
93
|
+
parser.add_argument('--tests-dir', dest = 'test_dirs',
|
|
94
|
+
action = 'append',
|
|
95
|
+
help = 'Discover tests from these directories. Defaults to the current directory.')
|
|
96
|
+
|
|
97
|
+
parser.add_argument('--add-path', dest = 'path_additions',
|
|
98
|
+
action = 'append',
|
|
99
|
+
help = 'If supplied, add this path the sys.path before running tests.')
|
|
100
|
+
|
|
101
|
+
parser.add_argument('--filename-pattern', dest = 'filename_pattern',
|
|
102
|
+
action = 'store', type = str, default = DEFAULT_TEST_FILENAME_PATTERN,
|
|
103
|
+
help = 'The pattern to use to find test files (default: %(default)s).')
|
|
104
|
+
|
|
105
|
+
parser.add_argument('pattern',
|
|
106
|
+
action = 'store', type = str, default = None, nargs = '?',
|
|
107
|
+
help = 'If supplied, only tests with names matching this pattern will be run. This pattern is used directly in re.search().')
|
|
108
|
+
|
|
109
|
+
return parser
|
|
110
|
+
|
|
111
|
+
if __name__ == '__main__':
|
|
112
|
+
sys.exit(main())
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import typing
|
|
2
|
+
import unittest
|
|
3
|
+
|
|
4
|
+
import edq.util.json
|
|
5
|
+
import edq.util.reflection
|
|
6
|
+
|
|
7
|
+
FORMAT_STR: str = "\n--- Expected ---\n%s\n--- Actual ---\n%s\n---\n"
|
|
8
|
+
|
|
9
|
+
class BaseTest(unittest.TestCase):
|
|
10
|
+
"""
|
|
11
|
+
A base class for unit tests.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
maxDiff = None
|
|
15
|
+
""" Don't limit the size of diffs. """
|
|
16
|
+
|
|
17
|
+
def assertJSONDictEqual(self, a: dict, b: dict) -> None: # pylint: disable=invalid-name
|
|
18
|
+
"""
|
|
19
|
+
Call assertDictEqual(), but supply a message containing the full JSON representation of the arguments.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
a_json = edq.util.json.dumps(a, indent = 4)
|
|
23
|
+
b_json = edq.util.json.dumps(b, indent = 4)
|
|
24
|
+
|
|
25
|
+
super().assertDictEqual(a, b, FORMAT_STR % (a_json, b_json))
|
|
26
|
+
|
|
27
|
+
def assertJSONListEqual(self, a: list, b: list) -> None: # pylint: disable=invalid-name
|
|
28
|
+
"""
|
|
29
|
+
Call assertListEqual(), but supply a message containing the full JSON representation of the arguments.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
a_json = edq.util.json.dumps(a, indent = 4)
|
|
33
|
+
b_json = edq.util.json.dumps(b, indent = 4)
|
|
34
|
+
|
|
35
|
+
super().assertListEqual(a, b, FORMAT_STR % (a_json, b_json))
|
|
36
|
+
|
|
37
|
+
def format_error_string(self, ex: typing.Union[BaseException, None]) -> str:
|
|
38
|
+
"""
|
|
39
|
+
Format an error string from an exception so it can be checked for testing.
|
|
40
|
+
The type of the error will be included,
|
|
41
|
+
and any nested errors will be joined together.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
parts = []
|
|
45
|
+
|
|
46
|
+
while (ex is not None):
|
|
47
|
+
type_name = edq.util.reflection.get_qualified_name(ex)
|
|
48
|
+
message = str(ex)
|
|
49
|
+
|
|
50
|
+
parts.append(f"{type_name}: {message}")
|
|
51
|
+
|
|
52
|
+
ex = ex.__cause__
|
|
53
|
+
|
|
54
|
+
return "; ".join(parts)
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Operations relating to directory entries (dirents).
|
|
3
|
+
|
|
4
|
+
These operations are designed for clarity and compatibility, not performance.
|
|
5
|
+
|
|
6
|
+
Only directories, files, and links will be handled.
|
|
7
|
+
Other types of dirents may result in an error being raised.
|
|
8
|
+
|
|
9
|
+
In general, all recursive operations do not follow symlinks by default and instead treat the link as a file.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import atexit
|
|
13
|
+
import os
|
|
14
|
+
import shutil
|
|
15
|
+
import tempfile
|
|
16
|
+
import typing
|
|
17
|
+
import uuid
|
|
18
|
+
|
|
19
|
+
DEFAULT_ENCODING: str = 'utf-8'
|
|
20
|
+
""" The default encoding that will be used when reading and writing. """
|
|
21
|
+
|
|
22
|
+
DEPTH_LIMIT: int = 10000
|
|
23
|
+
|
|
24
|
+
def exists(path: str) -> bool:
|
|
25
|
+
"""
|
|
26
|
+
Check if a path exists.
|
|
27
|
+
This will transparently call os.path.lexists(),
|
|
28
|
+
which will include broken links.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
return os.path.lexists(path)
|
|
32
|
+
|
|
33
|
+
def get_temp_path(prefix: str = '', suffix: str = '', rm: bool = True) -> str:
|
|
34
|
+
"""
|
|
35
|
+
Get a path to a valid (but not currently existing) temp dirent.
|
|
36
|
+
If rm is True, then the dirent will be attempted to be deleted on exit
|
|
37
|
+
(no error will occur if the path is not there).
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
path = None
|
|
41
|
+
while ((path is None) or exists(path)):
|
|
42
|
+
path = os.path.join(tempfile.gettempdir(), prefix + str(uuid.uuid4()) + suffix)
|
|
43
|
+
|
|
44
|
+
if (rm):
|
|
45
|
+
atexit.register(remove, path)
|
|
46
|
+
|
|
47
|
+
return path
|
|
48
|
+
|
|
49
|
+
def get_temp_dir(prefix: str = '', suffix: str = '', rm: bool = True) -> str:
|
|
50
|
+
"""
|
|
51
|
+
Get a temp directory.
|
|
52
|
+
The directory will exist when returned.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
path = get_temp_path(prefix = prefix, suffix = suffix, rm = rm)
|
|
56
|
+
mkdir(path)
|
|
57
|
+
return path
|
|
58
|
+
|
|
59
|
+
def mkdir(raw_path: str) -> None:
|
|
60
|
+
"""
|
|
61
|
+
Make a directory (including any required parent directories).
|
|
62
|
+
Does not complain if the directory (or parents) already exist
|
|
63
|
+
(this includes if the directory or parents are links to directories).
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
path = os.path.abspath(raw_path)
|
|
67
|
+
|
|
68
|
+
if (exists(path)):
|
|
69
|
+
if (os.path.isdir(path)):
|
|
70
|
+
return
|
|
71
|
+
|
|
72
|
+
raise ValueError(f"Target of mkdir already exists, and is not a dir: '{raw_path}'.")
|
|
73
|
+
|
|
74
|
+
_check_parent_dirs(raw_path)
|
|
75
|
+
|
|
76
|
+
os.makedirs(path, exist_ok = True)
|
|
77
|
+
|
|
78
|
+
def _check_parent_dirs(raw_path: str) -> None:
|
|
79
|
+
"""
|
|
80
|
+
Check all parents to ensure that they are all dirs (or don't exist).
|
|
81
|
+
This is naturally handled by os.makedirs(),
|
|
82
|
+
but the error messages are not consistent between POSIX and Windows.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
path = os.path.abspath(raw_path)
|
|
86
|
+
|
|
87
|
+
parent_path = path
|
|
88
|
+
for _ in range(DEPTH_LIMIT):
|
|
89
|
+
new_parent_path = os.path.dirname(parent_path)
|
|
90
|
+
if (parent_path == new_parent_path):
|
|
91
|
+
# We have reached root (are our own parent).
|
|
92
|
+
return
|
|
93
|
+
|
|
94
|
+
parent_path = new_parent_path
|
|
95
|
+
|
|
96
|
+
if (os.path.exists(parent_path) and (not os.path.isdir(parent_path))):
|
|
97
|
+
raise ValueError(f"Target of mkdir contains parent ('{os.path.basename(parent_path)}') that exists and is not a dir: '{raw_path}'.")
|
|
98
|
+
|
|
99
|
+
raise ValueError("Depth limit reached.")
|
|
100
|
+
|
|
101
|
+
def remove(path: str) -> None:
|
|
102
|
+
"""
|
|
103
|
+
Remove the given path.
|
|
104
|
+
The path can be of any type (dir, file, link),
|
|
105
|
+
and does not need to exist.
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
if (not exists(path)):
|
|
109
|
+
return
|
|
110
|
+
|
|
111
|
+
if (os.path.isfile(path) or os.path.islink(path)):
|
|
112
|
+
os.remove(path)
|
|
113
|
+
elif (os.path.isdir(path)):
|
|
114
|
+
shutil.rmtree(path)
|
|
115
|
+
else:
|
|
116
|
+
raise ValueError(f"Unknown type of dirent: '{path}'.")
|
|
117
|
+
|
|
118
|
+
def same(a: str, b: str):
|
|
119
|
+
"""
|
|
120
|
+
Check if two paths represent the same dirent.
|
|
121
|
+
If either (or both) paths do not exist, false will be returned.
|
|
122
|
+
If either paths are links, they are resolved before checking
|
|
123
|
+
(so a link and the target file are considered the "same").
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
return (exists(a) and exists(b) and os.path.samefile(a, b))
|
|
127
|
+
|
|
128
|
+
def move(raw_source: str, raw_dest: str, no_clobber: bool = False) -> None:
|
|
129
|
+
"""
|
|
130
|
+
Move the source dirent to the given destination.
|
|
131
|
+
Any existing destination will be removed before moving.
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
source = os.path.abspath(raw_source)
|
|
135
|
+
dest = os.path.abspath(raw_dest)
|
|
136
|
+
|
|
137
|
+
if (not exists(source)):
|
|
138
|
+
raise ValueError(f"Source of move does not exist: '{raw_source}'.")
|
|
139
|
+
|
|
140
|
+
# If dest is a dir, then resolve the path.
|
|
141
|
+
if (os.path.isdir(dest)):
|
|
142
|
+
dest = os.path.abspath(os.path.join(dest, os.path.basename(source)))
|
|
143
|
+
|
|
144
|
+
# Skip if this is self.
|
|
145
|
+
if (same(source, dest)):
|
|
146
|
+
return
|
|
147
|
+
|
|
148
|
+
# Check for clobber.
|
|
149
|
+
if (exists(dest)):
|
|
150
|
+
if (no_clobber):
|
|
151
|
+
raise ValueError(f"Destination of move already exists: '{raw_dest}'.")
|
|
152
|
+
|
|
153
|
+
remove(dest)
|
|
154
|
+
|
|
155
|
+
# Create any required parents.
|
|
156
|
+
os.makedirs(os.path.dirname(dest), exist_ok = True)
|
|
157
|
+
|
|
158
|
+
shutil.move(source, dest)
|
|
159
|
+
|
|
160
|
+
def copy(raw_source: str, raw_dest: str, no_clobber: bool = False) -> None:
|
|
161
|
+
"""
|
|
162
|
+
Copy a dirent or directory to a destination.
|
|
163
|
+
|
|
164
|
+
The destination will be overwritten if it exists (and no_clobber is false).
|
|
165
|
+
For copying the contents of a directory INTO another directory, use copy_contents().
|
|
166
|
+
|
|
167
|
+
No copy is made if the source and dest refer to the same dirent.
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
source = os.path.abspath(raw_source)
|
|
171
|
+
dest = os.path.abspath(raw_dest)
|
|
172
|
+
|
|
173
|
+
if (same(source, dest)):
|
|
174
|
+
return
|
|
175
|
+
|
|
176
|
+
if (not exists(source)):
|
|
177
|
+
raise ValueError(f"Source of copy does not exist: '{raw_source}'.")
|
|
178
|
+
|
|
179
|
+
if (exists(dest)):
|
|
180
|
+
if (no_clobber):
|
|
181
|
+
raise ValueError(f"Destination of copy already exists: '{raw_dest}'.")
|
|
182
|
+
|
|
183
|
+
if (contains_path(dest, source)):
|
|
184
|
+
raise ValueError(f"Destination of copy cannot contain the source. Destination: '{raw_dest}', Source: '{raw_source}'.")
|
|
185
|
+
|
|
186
|
+
remove(dest)
|
|
187
|
+
|
|
188
|
+
mkdir(os.path.dirname(dest))
|
|
189
|
+
|
|
190
|
+
if (os.path.islink(source)):
|
|
191
|
+
# shutil.copy2() can generally handle (broken) links, but Windows is inconsistent (between 3.11 and 3.12) on link handling.
|
|
192
|
+
link_target = os.readlink(source)
|
|
193
|
+
os.symlink(link_target, dest)
|
|
194
|
+
elif (os.path.isfile(source)):
|
|
195
|
+
shutil.copy2(source, dest, follow_symlinks = False)
|
|
196
|
+
elif (os.path.isdir(source)):
|
|
197
|
+
mkdir(dest)
|
|
198
|
+
|
|
199
|
+
for child in sorted(os.listdir(source)):
|
|
200
|
+
copy(os.path.join(raw_source, child), os.path.join(raw_dest, child))
|
|
201
|
+
else:
|
|
202
|
+
raise ValueError(f"Source of copy is not a dir, fie, or link: '{raw_source}'.")
|
|
203
|
+
|
|
204
|
+
def copy_contents(raw_source: str, raw_dest: str, no_clobber: bool = False) -> None:
|
|
205
|
+
"""
|
|
206
|
+
Copy a file or the contents of a directory (excluding the top-level directory itself) into a destination.
|
|
207
|
+
If the destination exists, it must be a directory.
|
|
208
|
+
|
|
209
|
+
The source and destination should not be the same file.
|
|
210
|
+
|
|
211
|
+
For a file, this is equivalent to `mkdir -p dest && cp source dest`
|
|
212
|
+
For a dir, this is equivalent to `mkdir -p dest && cp -r source/* dest`
|
|
213
|
+
"""
|
|
214
|
+
|
|
215
|
+
source = os.path.abspath(raw_source)
|
|
216
|
+
dest = os.path.abspath(raw_dest)
|
|
217
|
+
|
|
218
|
+
if (same(source, dest)):
|
|
219
|
+
raise ValueError(f"Source and destination of contents copy cannot be the same: '{raw_source}'.")
|
|
220
|
+
|
|
221
|
+
if (exists(dest) and (not os.path.isdir(dest))):
|
|
222
|
+
raise ValueError(f"Destination of contents copy exists and is not a dir: '{raw_dest}'.")
|
|
223
|
+
|
|
224
|
+
mkdir(dest)
|
|
225
|
+
|
|
226
|
+
if (os.path.isfile(source) or os.path.islink(source)):
|
|
227
|
+
copy(source, os.path.join(dest, os.path.basename(source)), no_clobber = no_clobber)
|
|
228
|
+
elif (os.path.isdir(source)):
|
|
229
|
+
for child in sorted(os.listdir(source)):
|
|
230
|
+
copy(os.path.join(raw_source, child), os.path.join(raw_dest, child), no_clobber = no_clobber)
|
|
231
|
+
else:
|
|
232
|
+
raise ValueError(f"Source of contents copy is not a dir, fie, or link: '{raw_source}'.")
|
|
233
|
+
|
|
234
|
+
def read_file(raw_path: str, strip: bool = True, encoding: str = DEFAULT_ENCODING) -> str:
|
|
235
|
+
""" Read the contents of a file. """
|
|
236
|
+
|
|
237
|
+
path = os.path.abspath(raw_path)
|
|
238
|
+
|
|
239
|
+
if (not exists(path)):
|
|
240
|
+
raise ValueError(f"Source of read does not exist: '{raw_path}'.")
|
|
241
|
+
|
|
242
|
+
with open(path, 'r', encoding = encoding) as file:
|
|
243
|
+
contents = file.read()
|
|
244
|
+
|
|
245
|
+
if (strip):
|
|
246
|
+
contents = contents.strip()
|
|
247
|
+
|
|
248
|
+
return contents
|
|
249
|
+
|
|
250
|
+
def write_file(
|
|
251
|
+
raw_path: str, contents: typing.Union[str, None],
|
|
252
|
+
strip: bool = True, newline: bool = True,
|
|
253
|
+
encoding: str = DEFAULT_ENCODING,
|
|
254
|
+
no_clobber = False) -> None:
|
|
255
|
+
"""
|
|
256
|
+
Write the contents of a file.
|
|
257
|
+
If clobbering, any existing dirent will be removed before write.
|
|
258
|
+
"""
|
|
259
|
+
|
|
260
|
+
path = os.path.abspath(raw_path)
|
|
261
|
+
|
|
262
|
+
if (exists(path)):
|
|
263
|
+
if (no_clobber):
|
|
264
|
+
raise ValueError(f"Destination of write already exists: '{raw_path}'.")
|
|
265
|
+
|
|
266
|
+
remove(path)
|
|
267
|
+
|
|
268
|
+
if (contents is None):
|
|
269
|
+
contents = ''
|
|
270
|
+
|
|
271
|
+
if (strip):
|
|
272
|
+
contents = contents.strip()
|
|
273
|
+
|
|
274
|
+
if (newline):
|
|
275
|
+
contents += "\n"
|
|
276
|
+
|
|
277
|
+
with open(path, 'w', encoding = encoding) as file:
|
|
278
|
+
file.write(contents)
|
|
279
|
+
|
|
280
|
+
def read_file_bytes(raw_path: str) -> bytes:
|
|
281
|
+
""" Read the contents of a file as bytes. """
|
|
282
|
+
|
|
283
|
+
path = os.path.abspath(raw_path)
|
|
284
|
+
|
|
285
|
+
if (not exists(path)):
|
|
286
|
+
raise ValueError(f"Source of read bytes does not exist: '{raw_path}'.")
|
|
287
|
+
|
|
288
|
+
with open(path, 'rb') as file:
|
|
289
|
+
return file.read()
|
|
290
|
+
|
|
291
|
+
def write_file_bytes(
|
|
292
|
+
raw_path: str, contents: typing.Union[bytes, None],
|
|
293
|
+
no_clobber = False) -> None:
|
|
294
|
+
"""
|
|
295
|
+
Write the contents of a file as bytes.
|
|
296
|
+
If clobbering, any existing dirent will be removed before write.
|
|
297
|
+
"""
|
|
298
|
+
|
|
299
|
+
path = os.path.abspath(raw_path)
|
|
300
|
+
|
|
301
|
+
if (exists(path)):
|
|
302
|
+
if (no_clobber):
|
|
303
|
+
raise ValueError(f"Destination of write bytes already exists: '{raw_path}'.")
|
|
304
|
+
|
|
305
|
+
remove(path)
|
|
306
|
+
|
|
307
|
+
if (contents is None):
|
|
308
|
+
contents = b''
|
|
309
|
+
|
|
310
|
+
with open(path, 'wb') as file:
|
|
311
|
+
file.write(contents)
|
|
312
|
+
|
|
313
|
+
def contains_path(parent: str, child: str) -> bool:
|
|
314
|
+
"""
|
|
315
|
+
Check if the parent path contains the child path.
|
|
316
|
+
This is pure lexical analysis, no dirent stats are checked.
|
|
317
|
+
Will return false if the (absolute) paths are the same
|
|
318
|
+
(this function does not allow a path to contain itself).
|
|
319
|
+
"""
|
|
320
|
+
|
|
321
|
+
if ((parent == '') or (child == '')):
|
|
322
|
+
return False
|
|
323
|
+
|
|
324
|
+
parent = os.path.abspath(parent)
|
|
325
|
+
child = os.path.abspath(child)
|
|
326
|
+
|
|
327
|
+
child = os.path.dirname(child)
|
|
328
|
+
for _ in range(DEPTH_LIMIT):
|
|
329
|
+
if (parent == child):
|
|
330
|
+
return True
|
|
331
|
+
|
|
332
|
+
new_child = os.path.dirname(child)
|
|
333
|
+
if (child == new_child):
|
|
334
|
+
return False
|
|
335
|
+
|
|
336
|
+
child = new_child
|
|
337
|
+
|
|
338
|
+
raise ValueError("Depth limit reached.")
|