dtoolcore 3.18.3__py3-none-any.whl

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.
dtoolcore/utils.py ADDED
@@ -0,0 +1,288 @@
1
+ """Utility functions for dtoolcore."""
2
+
3
+ import os
4
+ import errno
5
+ import getpass
6
+ import hashlib
7
+ import json
8
+ import platform
9
+ import binascii
10
+ import base64
11
+ import datetime
12
+ import re
13
+ import socket
14
+ import logging
15
+
16
+ try:
17
+ from urlparse import urlparse, urlunparse
18
+ except ImportError:
19
+ from urllib.parse import urlparse, urlunparse
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ IS_WINDOWS = False
24
+ if platform.system() == "Windows":
25
+ IS_WINDOWS = True
26
+
27
+ DEFAULT_CONFIG_PATH = os.path.expanduser("~/.config/dtool/dtool.json")
28
+ DEFAULT_CACHE_PATH = os.path.expanduser("~/.cache/dtool")
29
+
30
+ MAX_NAME_LENGTH = 80
31
+ NAME_VALID_CHARS_LIST = ["0-9", "a-z", "A-Z", "-", "_", "."]
32
+ NAME_VALID_CHARS_STR = "".join(NAME_VALID_CHARS_LIST)
33
+ NAME_VALID_CHARS_REGEX = re.compile(r"^[{}]+$".format(NAME_VALID_CHARS_STR))
34
+
35
+
36
+ def windows_to_unix_path(win_path):
37
+ """Return Unix path."""
38
+ logger.debug("In windows_to_unix_path...")
39
+ logger.debug("windows_to_unix_path.input_win_path: {}".format(win_path))
40
+ unix_path = win_path.replace("\\", "/")
41
+
42
+ # Deal with Windows path defect where path has incorrect starting /, e.g.
43
+ # /C:/some/path.
44
+ if IS_WINDOWS and len(unix_path) >=2 and unix_path[0] == "/" and unix_path[2] == ":": # NOQA
45
+ unix_path = unix_path[1:]
46
+
47
+ logger.debug("windows_to_unix_path.return: {}".format(unix_path))
48
+ return unix_path
49
+
50
+
51
+ def unix_to_windows_path(unix_path):
52
+ """Return Windows path."""
53
+ logger.debug("In unix_to_windows_path...")
54
+ logger.debug("unix_to_windows_path.input_unix_path: {}".format(unix_path))
55
+
56
+ # Deal with Windows path defect where path has incorrect starting /, e.g.
57
+ # /C:/some/path.
58
+ if IS_WINDOWS and len(unix_path) >= 2 and unix_path[0] == "/" and unix_path[2] == ":": # NOQA
59
+ unix_path = unix_path[1:]
60
+
61
+ win_path = unix_path.replace("/", "\\")
62
+ logger.debug("unix_to_windows_path.return: {}".format(win_path))
63
+ return win_path
64
+
65
+
66
+ def generous_parse_uri(uri):
67
+ """Return a urlparse.ParseResult object with the results of parsing the
68
+ given URI. This has the same properties as the result of parse_uri.
69
+
70
+ When passed a relative path, it determines the absolute path, sets the
71
+ scheme to file, the netloc to localhost and returns a parse of the result.
72
+ """
73
+ logger.debug("In generous_pase_uri...")
74
+ logger.debug("generous_pase_uri.input_uri: {}".format(uri))
75
+
76
+ parse_result = urlparse(uri)
77
+
78
+ IS_WINDOWS_DRIVE_LETTER = len(parse_result.scheme) == 1
79
+
80
+ if parse_result.scheme == '' or IS_WINDOWS_DRIVE_LETTER:
81
+ abspath = os.path.abspath(parse_result.path)
82
+ fixed_uri = "file://{}{}".format(
83
+ socket.gethostname(),
84
+ abspath
85
+ )
86
+ if IS_WINDOWS:
87
+ abspath = windows_to_unix_path(abspath)
88
+ if IS_WINDOWS_DRIVE_LETTER:
89
+ abspath = parse_result.scheme.upper() + abspath[1:]
90
+ fixed_uri = "file:///{}".format(abspath)
91
+ parse_result = urlparse(fixed_uri)
92
+
93
+ logger.debug("generouse_pase_uri.return: {}".format(parse_result))
94
+ return parse_result
95
+
96
+
97
+ def sanitise_uri(uri):
98
+ """Return fully qualified uri from the input, which might be a relpath."""
99
+ logger.debug("In sanitise_uri...")
100
+ logger.debug("sanitise_uri.input_uri: {}".format(uri))
101
+ logger.debug("sanitise_uri.calling.utils.generouse_parse_uri")
102
+ uri = urlunparse(generous_parse_uri(uri))
103
+ logger.debug("sanitise_uri.return: {}".format(uri))
104
+ return uri
105
+
106
+
107
+ def cross_platform_getuser(is_windows, no_username_in_env):
108
+ """Return the username or "unknown".
109
+
110
+ The function returns "unknown" if the platform is windows
111
+ and the username environment variable is not set.
112
+ """
113
+ if is_windows and no_username_in_env:
114
+ return "unknown"
115
+ return getpass.getuser()
116
+
117
+
118
+ def getuser():
119
+ """Return the username."""
120
+ is_windows = platform.system() == "Windows"
121
+ no_username_in_env = os.environ.get("USERNAME") is None
122
+ return cross_platform_getuser(is_windows, no_username_in_env)
123
+
124
+
125
+ def _get_config_dict_from_file(config_path=None):
126
+ """Return value if key exists in file.
127
+
128
+ Return empty string ("") if key or file does not exist.
129
+ """
130
+ if config_path is None:
131
+ config_path = DEFAULT_CONFIG_PATH
132
+
133
+ # Default (empty) content will be used if config file does not exist.
134
+ config_content = {}
135
+
136
+ # If the config file exists we use that content.
137
+ if os.path.isfile(config_path):
138
+ with open(config_path) as fh:
139
+ config_content = json.load(fh)
140
+
141
+ return config_content
142
+
143
+
144
+ def write_config_value_to_file(key, value, config_path=None):
145
+ """Write key/value pair to config file.
146
+ """
147
+ if config_path is None:
148
+ config_path = DEFAULT_CONFIG_PATH
149
+
150
+ # Get existing config.
151
+ config = _get_config_dict_from_file(config_path)
152
+
153
+ # Add/update the key/value pair.
154
+ config[key] = value
155
+
156
+ # Create parent directories if they are missing.
157
+ mkdir_parents(os.path.dirname(config_path))
158
+
159
+ # Write the content
160
+ with open(config_path, "w") as fh:
161
+ json.dump(config, fh, sort_keys=True, indent=2)
162
+
163
+ # Set 600 permissions on the config file.
164
+ os.chmod(config_path, 33216)
165
+
166
+ return get_config_value_from_file(key, config_path)
167
+
168
+
169
+ def get_config_value_from_file(key, config_path=None, default=None):
170
+ """Return value if key exists in file.
171
+
172
+ Return default if key not in config.
173
+ """
174
+ config = _get_config_dict_from_file(config_path)
175
+ if key not in config:
176
+ return default
177
+ return config[key]
178
+
179
+
180
+ def get_config_value(key, config_path=None, default=None):
181
+ """Get a configuration value.
182
+
183
+ Preference:
184
+ 1. From environment
185
+ 2. From JSON configuration file supplied in ``config_path`` argument
186
+ 3. The default supplied to the function
187
+
188
+ :param key: name of lookup value
189
+ :param config_path: path to JSON configuration file
190
+ :param default: default fall back value
191
+ :returns: value associated with the key
192
+ """
193
+ if config_path is None:
194
+ config_path = DEFAULT_CONFIG_PATH
195
+
196
+ # Start by setting default value
197
+ value = default
198
+
199
+ # Update from config file
200
+ value = get_config_value_from_file(
201
+ key=key,
202
+ config_path=config_path,
203
+ default=value
204
+ )
205
+
206
+ # Update from environment variable
207
+ value = os.environ.get(key, value)
208
+ return value
209
+
210
+
211
+ def sha1_hexdigest(input_string):
212
+ """Return hex digest of the sha1sum of the input_string."""
213
+
214
+ byte_string = input_string.encode()
215
+
216
+ return hashlib.sha1(byte_string).hexdigest()
217
+
218
+
219
+ def base64_to_hex(input_string):
220
+ """Retun the hex encoded version of the base64 encoded input string."""
221
+
222
+ return binascii.hexlify(base64.b64decode(input_string)).decode()
223
+
224
+
225
+ def generate_identifier(handle):
226
+ """Return identifier from a ProtoDataSet handle."""
227
+ return sha1_hexdigest(handle)
228
+
229
+
230
+ def mkdir_parents(path):
231
+ """Create the given directory path.
232
+ This includes all necessary parent directories. Does not raise an error if
233
+ the directory already exists.
234
+ :param path: path to create
235
+ """
236
+
237
+ try:
238
+ os.makedirs(path)
239
+ except OSError as exc:
240
+ if exc.errno == errno.EEXIST:
241
+ pass
242
+ else:
243
+ raise
244
+
245
+
246
+ def timestamp(datetime_obj):
247
+ """Return Unix timestamp as float.
248
+
249
+ The number of seconds that have elapsed since January 1, 1970.
250
+ """
251
+ start_of_time = datetime.datetime(1970, 1, 1)
252
+ diff = datetime_obj - start_of_time
253
+ return diff.total_seconds()
254
+
255
+
256
+ def name_is_valid(name):
257
+ """Return True if the dataset name is valid.
258
+
259
+ The name can only be 80 characters long.
260
+ Valid characters: Alpha numeric characters [0-9a-zA-Z]
261
+ Valid special characters: - _ .
262
+ """
263
+ # The name can only be 80 characters long.
264
+ if len(name) > MAX_NAME_LENGTH:
265
+ return False
266
+ return bool(NAME_VALID_CHARS_REGEX.match(name))
267
+
268
+
269
+ def relpath_to_handle(relpath, is_windows=False):
270
+ """Return handle from relpath.
271
+
272
+ Handles are Unix style relpaths.
273
+ Converts Windows relpath to Unix style relpath.
274
+ Strips "./" prefix.
275
+ """
276
+ if is_windows:
277
+ relpath = windows_to_unix_path(relpath)
278
+ if relpath.startswith("./"):
279
+ relpath = relpath[2:]
280
+ return relpath
281
+
282
+
283
+ def handle_to_osrelpath(handle, is_windows=False):
284
+ """Return OS specific relpath from handle."""
285
+ directories = handle.split("/")
286
+ if is_windows:
287
+ return "\\".join(directories)
288
+ return "/".join(directories)
dtoolcore/version.py ADDED
@@ -0,0 +1,16 @@
1
+ # file generated by setuptools_scm
2
+ # don't change, don't track in version control
3
+ TYPE_CHECKING = False
4
+ if TYPE_CHECKING:
5
+ from typing import Tuple, Union
6
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
7
+ else:
8
+ VERSION_TUPLE = object
9
+
10
+ version: str
11
+ __version__: str
12
+ __version_tuple__: VERSION_TUPLE
13
+ version_tuple: VERSION_TUPLE
14
+
15
+ __version__ = version = '3.18.3'
16
+ __version_tuple__ = version_tuple = (3, 18, 3)
@@ -0,0 +1,22 @@
1
+ MIT License
2
+ ===========
3
+
4
+ Copyright (c) 2017 Tjelvar Olsson
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.1
2
+ Name: dtoolcore
3
+ Version: 3.18.3
4
+ Summary: Core API for managing (scientific) data
5
+ Author-email: Tjelvar Olsson <tjelvar.olsson@gmail.com>
6
+ Project-URL: Documentation, https://dtoolcore.readthedocs.io
7
+ Project-URL: Repository, https://github.com/jic-dtool/dtoolcore
8
+ Project-URL: Changelog, https://github.com/jic-dtool/dtoolcore/blob/master/CHANGELOG.rst
9
+ Description-Content-Type: text/x-rst
10
+ License-File: LICENSE.rst
11
+ Requires-Dist: setuptools
12
+ Provides-Extra: docs
13
+ Requires-Dist: sphinx ; extra == 'docs'
14
+ Requires-Dist: sphinx-rtd-theme ; extra == 'docs'
15
+ Provides-Extra: test
16
+ Requires-Dist: pytest ; extra == 'test'
17
+ Requires-Dist: pytest-cov ; extra == 'test'
18
+ Requires-Dist: pytz ; extra == 'test'
19
+
20
+ Manage scientific data sets
21
+ ===========================
22
+
23
+ .. |dtool| image:: https://github.com/jic-dtool/dtoolcore/blob/master/icons/22x22/dtool_logo.png?raw=True
24
+ :height: 20px
25
+ :target: https://github.com/jic-dtool/dtoolcore
26
+
27
+ .. |pypi| image:: https://badge.fury.io/py/dtoolcore.svg
28
+ :target: http://badge.fury.io/py/dtoolcore
29
+ :alt: PyPi package
30
+
31
+ .. |build| image:: https://ci.appveyor.com/api/projects/status/ifd8qrfidslvs4i3?svg=true
32
+ :target: https://ci.appveyor.com/project/tjelvar-olsson/dtoolcore
33
+ :alt: AppVeyor CI build status (Windows)
34
+
35
+ .. |test| image:: https://img.shields.io/github/actions/workflow/status/jic-dtool/dtoolcore/test.yml?branch=master&label=tests
36
+ :target: https://github.com/jic-dtool/dtoolcore/actions/workflows/test.yml
37
+
38
+ .. |codecov| image:: https://codecov.io/github/jic-dtool/dtoolcore/coverage.svg?branch=master
39
+ :target: https://codecov.io/github/jic-dtool/dtoolcore?branch=master
40
+ :alt: Code Coverage
41
+
42
+ .. |docs| image:: https://readthedocs.org/projects/dtoolcore/badge/?version=latest
43
+ :target: https://readthedocs.org/projects/dtoolcore?badge=latest
44
+ :alt: Documentation Status
45
+
46
+ |dtool| |pypi| |build| |test| |test| |codecov| |docs|
47
+
48
+ - Documentation: http://dtoolcore.readthedocs.io
49
+ - GitHub: https://github.com/jic-dtool/dtoolcore
50
+ - PyPI: https://pypi.python.org/pypi/dtoolcore
51
+ - Free software: MIT License
52
+
53
+ Features
54
+ --------
55
+
56
+ - Core API for adding different types of metadata to files on disk
57
+ - Automatic generation of structural metadata
58
+ - Programmatic discovery and access of items in a dataset
59
+ - Structural metadata includes hash, size and modification time for
60
+ subsequent integrity checks
61
+ - Ability to annotate individual files with arbitrary metadata
62
+ - Metadata stored on disk as plain text files, i.e. disk datasets
63
+ generated using this API can be accessed without special tools
64
+ - Ability to create plugins for custom storage solutions
65
+ - Plugins for iRODS and Microsoft Azure storage backends available
66
+ - Cross-platform: Linux, Mac and Windows are all supported
67
+ - Works with Python 2.7, 3.5 and 3.6
68
+ - No external dependencies
69
+
70
+ Overview
71
+ --------
72
+
73
+ The dtoolcore project provides a Python API for managing (scientific) data.
74
+ It allows researchers to:
75
+
76
+ - Package data and metadata into a dataset
77
+ - Organise and backup datasets easily
78
+ - Find datasets of interest
79
+ - Verify the contents of datasets
80
+ - Discover and work with data programatically
@@ -0,0 +1,12 @@
1
+ dtoolcore/__init__.py,sha256=WBnNzl6H0mSR9UUhlvaXhQlFr9sEHMtcyI89rQIwi9I,36393
2
+ dtoolcore/compare.py,sha256=GVv09jovRq3fCeD02axLa3NWy5jdSwWutDkgL3U4HAY,2238
3
+ dtoolcore/filehasher.py,sha256=kyL3zBPw876DLxRuVueB3z0Q3fkcflGrjL00iRWZNQ8,2148
4
+ dtoolcore/storagebroker.py,sha256=h4WJKNk9H4Ka8gFtQxsSkCUMRDHN1Gu_q7rDEogmMog,26129
5
+ dtoolcore/utils.py,sha256=av8RAV-hWgM18Tr3_Qjpx4Qa5rHr2XXZFhGGZ7jUSpc,8411
6
+ dtoolcore/version.py,sha256=9xcwc9tjOBugD2SqHcu7ys4xNOx2utirD9mlGEgX0nI,413
7
+ dtoolcore-3.18.3.dist-info/LICENSE.rst,sha256=86aJiAkXSLnTuXcSVW8_TVdYTbp2of-veyzp3a3A3uA,1083
8
+ dtoolcore-3.18.3.dist-info/METADATA,sha256=FcgC54eZsHwozkmGGhw6VzSeLjZ89Qa2p5Naxp5oD48,3130
9
+ dtoolcore-3.18.3.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
10
+ dtoolcore-3.18.3.dist-info/entry_points.txt,sha256=li6y_llM_jGRDqxK8pH2tpMHU7W51umLV-dsnkEMaww,86
11
+ dtoolcore-3.18.3.dist-info/top_level.txt,sha256=MmmviczoSKxh4BGkRg88_I_xVqmuT7HadQz8QKSVRpE,10
12
+ dtoolcore-3.18.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.43.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [dtool.storage_brokers]
2
+ DiskStorageBroker = dtoolcore.storagebroker:DiskStorageBroker
@@ -0,0 +1 @@
1
+ dtoolcore