ensembl-utils 0.1.1__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.
@@ -0,0 +1,27 @@
1
+ # See the NOTICE file distributed with this work for additional information
2
+ # regarding copyright ownership.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Ensembl Python general-purpose utils library."""
16
+
17
+ __version__ = "0.1.1"
18
+
19
+ __all__ = [
20
+ "StrPath",
21
+ ]
22
+
23
+ import os
24
+ from typing import Union
25
+
26
+
27
+ StrPath = Union[str, os.PathLike]
@@ -0,0 +1,103 @@
1
+ # See the NOTICE file distributed with this work for additional information
2
+ # regarding copyright ownership.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Utils for common IO operations over archive files, e.g. tar or gzip."""
16
+
17
+ __all__ = [
18
+ "SUPPORTED_ARCHIVE_FORMATS",
19
+ "open_gz_file",
20
+ "extract_file",
21
+ ]
22
+
23
+ from contextlib import contextmanager
24
+ import gzip
25
+ from pathlib import Path
26
+ import shutil
27
+ from typing import Generator, TextIO
28
+
29
+ from ensembl.utils import StrPath
30
+ from ensembl.utils.argparse import ArgumentParser
31
+
32
+
33
+ def _unpack_gz_files(src_file: StrPath, dst_dir: StrPath) -> None:
34
+ """Unpacks `src_file` to `dst_dir`.
35
+
36
+ Args:
37
+ src_file: File path to unpack (with ".gz" extension).
38
+ dst_dir: Directory path to unpack the file into.
39
+
40
+ """
41
+ # Remove '.gz' extension to create the destination file name
42
+ dst_file = Path(dst_dir) / Path(src_file).stem
43
+ with gzip.open(src_file, "rb") as f_in:
44
+ with dst_file.open("wb") as f_out:
45
+ shutil.copyfileobj(f_in, f_out)
46
+
47
+
48
+ shutil.register_unpack_format("gzip", [".gz"], _unpack_gz_files, description="GZIP file")
49
+
50
+ # Each registered format is a tuple (name, extensions, description)
51
+ SUPPORTED_ARCHIVE_FORMATS = [ext for elem in shutil.get_unpack_formats() for ext in elem[1]]
52
+
53
+
54
+ @contextmanager
55
+ def open_gz_file(file_path: StrPath) -> Generator[TextIO, None, None]:
56
+ """Yields an open file object, even if the file is compressed with gzip.
57
+
58
+ The file is expected to contain a text, and this can be used with the usual "with".
59
+
60
+ Args:
61
+ file_path: A (single) file path to open.
62
+
63
+ """
64
+ src_file = Path(file_path)
65
+ if src_file.suffix == ".gz":
66
+ with gzip.open(src_file, "rt") as fh:
67
+ yield fh
68
+ else:
69
+ with src_file.open("rt") as fh:
70
+ yield fh
71
+
72
+
73
+ def extract_file(src_file: StrPath, dst_dir: StrPath) -> None:
74
+ """Extracts the `src_file` into `dst_dir`.
75
+
76
+ If the file is not an archive, it will be copied to `dst_dir`. `dst_dir` will be created if it
77
+ does not exist.
78
+
79
+ Args:
80
+ src_file: Path to the file to unpack.
81
+ dst_dir: Path to the folder where to extract the file.
82
+
83
+ """
84
+ src_file = Path(src_file)
85
+ extensions = {"".join(src_file.suffixes[i:]) for i in range(0, len(src_file.suffixes))}
86
+
87
+ if extensions.intersection(SUPPORTED_ARCHIVE_FORMATS):
88
+ shutil.unpack_archive(src_file, dst_dir)
89
+ else:
90
+ # Replicate the functionality of shutil.unpack_archive() by creating `dst_dir`
91
+ Path(dst_dir).mkdir(parents=True, exist_ok=True)
92
+ shutil.copy(src_file, dst_dir)
93
+
94
+
95
+ def extract_file_cli() -> None:
96
+ """Entry-point for the `extract_file` method"""
97
+ parser = ArgumentParser(description="Extracts file to the given location.")
98
+ parser.add_argument_src_path("--src_file", required=True, help="Path to the file to unpack")
99
+ parser.add_argument_dst_path(
100
+ "--dst_dir", default=Path.cwd(), help="Path to the folder where to extract the file"
101
+ )
102
+ args = parser.parse_args()
103
+ extract_file(args.src_file, args.dst_dir)
@@ -0,0 +1,246 @@
1
+ # See the NOTICE file distributed with this work for additional information
2
+ # regarding copyright ownership.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Provide an extended version of `argparse.ArgumentParser` with additional functionality.
16
+
17
+ Examples:
18
+
19
+ >>> from pathlib import Path
20
+ >>> from ensembl.util.argparse import ArgumentParser
21
+ >>> parser = ArgumentParser(description="Tool description")
22
+ >>> parser.add_argument_src_path("--src_file", required=True, help="Path to source file")
23
+ >>> parser.add_server_arguments(help="Server to connect to")
24
+ >>> args = parser.parse_args()
25
+ >>> args
26
+ Namespace(host='myserver', port=3826, src_file=PosixPath('/path/to/src_file.txt'),
27
+ url=URL('mysql://username@myserver:3826'), user='username')
28
+
29
+ """
30
+
31
+ __all__ = [
32
+ "ArgumentParser",
33
+ ]
34
+
35
+ import argparse
36
+ import os
37
+ from pathlib import Path
38
+
39
+ from sqlalchemy.engine import make_url, URL
40
+
41
+ from ensembl.utils import StrPath
42
+
43
+
44
+ class ArgumentParser(argparse.ArgumentParser):
45
+ """Extends `argparse.ArgumentParser` with additional methods and functionality.
46
+
47
+ The default behaviour of the help text will be to display the default values on every non-required
48
+ argument, i.e. optional arguments with `required=False`.
49
+
50
+ """
51
+
52
+ def __init__(self, *args, **kwargs) -> None:
53
+ """Extends the base class to include the information about default argument values by default."""
54
+ super().__init__(*args, **kwargs)
55
+ self.formatter_class = argparse.ArgumentDefaultsHelpFormatter
56
+ self.__server_groups: list[str] = []
57
+
58
+ def _validate_src_path(self, src_path: StrPath) -> Path:
59
+ """Returns the path if exists and it is readable, raises an error through the parser otherwise.
60
+
61
+ Args:
62
+ src_path: File or directory path to check.
63
+
64
+ """
65
+ src_path = Path(src_path)
66
+ if not src_path.exists():
67
+ self.error(f"'{src_path}' not found")
68
+ elif not os.access(src_path, os.R_OK):
69
+ self.error(f"'{src_path}' not readable")
70
+ return src_path
71
+
72
+ def _validate_dst_path(self, dst_path: StrPath, exists_ok: bool = False) -> Path:
73
+ """Returns the path if it is writable, raises an error through the parser otherwise.
74
+
75
+ Args:
76
+ dst_path: File or directory path to check.
77
+ exists_ok: Do not raise an error during parsing if the destination path already exists.
78
+
79
+ """
80
+ dst_path = Path(dst_path)
81
+ if dst_path.exists():
82
+ if os.access(dst_path, os.W_OK):
83
+ if exists_ok:
84
+ return dst_path
85
+ self.error(f"'{dst_path}' already exists")
86
+ else:
87
+ self.error(f"'{dst_path}' is not writable")
88
+ # Check if the first parent directory that exists is writable
89
+ for parent_path in dst_path.parents:
90
+ if parent_path.exists():
91
+ if not os.access(parent_path, os.W_OK):
92
+ self.error(f"'{dst_path}' is not writable")
93
+ break
94
+ return dst_path
95
+
96
+ def add_argument(self, *args, **kwargs) -> None: # type: ignore[override]
97
+ """Extends the parent function by excluding the default value in the help text when not provided.
98
+
99
+ Only applied to required arguments without a default value, i.e. positional arguments or optional
100
+ arguments with `required=True`.
101
+
102
+ """
103
+ if kwargs.get("required", False):
104
+ kwargs.setdefault("default", argparse.SUPPRESS)
105
+ super().add_argument(*args, **kwargs)
106
+
107
+ def add_argument_src_path(self, *args, **kwargs) -> None:
108
+ """Adds `pathlib.Path` argument, checking if it exists and it is readable at parsing time.
109
+
110
+ If "metavar" is not defined, it is added with "PATH" as value to improve help text readability.
111
+
112
+ """
113
+ kwargs.setdefault("metavar", "PATH")
114
+ kwargs["type"] = self._validate_src_path
115
+ self.add_argument(*args, **kwargs)
116
+
117
+ def add_argument_dst_path(self, *args, exists_ok: bool = True, **kwargs) -> None:
118
+ """Adds `pathlib.Path` argument, checking if it is writable at parsing time.
119
+
120
+ If "metavar" is not defined it is added with "PATH" as value to improve help text readability.
121
+
122
+ Args:
123
+ exists_ok: Do not raise an error if the destination path already exists.
124
+
125
+ """
126
+ kwargs.setdefault("metavar", "PATH")
127
+ kwargs["type"] = lambda x: self._validate_dst_path(x, exists_ok)
128
+ self.add_argument(*args, **kwargs)
129
+
130
+ def add_argument_url(self, *args, **kwargs) -> None:
131
+ """Adds `sqlalchemy.engine.URL` argument.
132
+
133
+ If "metavar" is not defined it is added with "URI" as value to improve help text readability.
134
+
135
+ """
136
+ kwargs.setdefault("metavar", "URI")
137
+ kwargs["type"] = make_url
138
+ self.add_argument(*args, **kwargs)
139
+
140
+ # pylint: disable=redefined-builtin
141
+ def add_server_arguments(self, prefix: str = "", include_database: bool = False, help: str = "") -> None:
142
+ """Adds the usual set of arguments needed to connect to a server, i.e. `--host`, `--port`, `--user`
143
+ and `--password` (optional).
144
+
145
+ Note that the parser will assume this is a MySQL server.
146
+
147
+ Args:
148
+ prefix: Prefix to add the each argument, e.g. if prefix is `src_`, the arguments will be
149
+ `--src_host`, etc.
150
+ include_database: Include `--database` argument.
151
+ help: Description message to include for this set of arguments.
152
+
153
+ """
154
+ group = self.add_argument_group(f"{prefix}server connection arguments", description=help)
155
+ group.add_argument(f"--{prefix}host", required=True, metavar="HOST", help="host name")
156
+ group.add_argument(f"--{prefix}port", required=True, type=int, metavar="PORT", help="port number")
157
+ group.add_argument(f"--{prefix}user", required=True, metavar="USER", help="user name")
158
+ group.add_argument(f"--{prefix}password", metavar="PWD", help="host password")
159
+ if include_database:
160
+ group.add_argument(f"--{prefix}database", required=True, metavar="NAME", help="database name")
161
+ self.__server_groups.append(prefix)
162
+
163
+ def add_log_arguments(self, add_log_file: bool = False) -> None:
164
+ """Adds the usual set of arguments required to set and initialise a logging system.
165
+
166
+ The current set includes a mutually exclusive group for the default logging level: `--verbose`,
167
+ `--debug` or `--log LEVEL`.
168
+
169
+ Args:
170
+ add_log_file: Add arguments to allow storing messages into a file, i.e. `--log_file` and
171
+ `--log_file_level`.
172
+
173
+ """
174
+ # Define the list of log levels available
175
+ log_levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
176
+ # NOTE: from 3.11 this list can be changed to: logging.getLevelNamesMapping().keys()
177
+ # Create logging arguments group
178
+ group = self.add_argument_group("logging arguments")
179
+ # Add 3 mutually exclusive options to set the logging level
180
+ subgroup = group.add_mutually_exclusive_group()
181
+ subgroup.add_argument(
182
+ "-v",
183
+ "--verbose",
184
+ action="store_const",
185
+ const="INFO",
186
+ dest="log_level",
187
+ help="verbose mode, i.e. 'INFO' log level",
188
+ )
189
+ subgroup.add_argument(
190
+ "--debug",
191
+ action="store_const",
192
+ const="DEBUG",
193
+ dest="log_level",
194
+ help="debugging mode, i.e. 'DEBUG' log level",
195
+ )
196
+ subgroup.add_argument(
197
+ "--log",
198
+ choices=log_levels,
199
+ type=str.upper,
200
+ default="WARNING",
201
+ metavar="LEVEL",
202
+ dest="log_level",
203
+ help="level of the events to track: %(choices)s",
204
+ )
205
+ subgroup.set_defaults(log_level="WARNING")
206
+ if add_log_file:
207
+ # Add log file-related arguments
208
+ group.add_argument(
209
+ "--log_file",
210
+ type=lambda x: self._validate_dst_path(x, exists_ok=True),
211
+ metavar="PATH",
212
+ default=None,
213
+ help="log file path",
214
+ )
215
+ group.add_argument(
216
+ "--log_file_level",
217
+ choices=log_levels,
218
+ type=str.upper,
219
+ default="DEBUG",
220
+ metavar="LEVEL",
221
+ help="level of the events to track in the log file: %(choices)s",
222
+ )
223
+
224
+ def parse_args(self, *args, **kwargs) -> argparse.Namespace: # type: ignore[override]
225
+ """Extends the parent function by adding a new URL argument for every server group added.
226
+
227
+ The type of this new argument will be `sqlalchemy.engine.URL`. It also logs all the parsed
228
+ arguments for debugging purposes when logging arguments have been added.
229
+
230
+ """
231
+ arguments = super().parse_args(*args, **kwargs)
232
+ # Build and add an sqlalchemy.engine.URL object for every server group added
233
+ for prefix in self.__server_groups:
234
+ # Raise an error rather than overwriting when the URL argument is already present
235
+ if f"{prefix}url" in arguments:
236
+ self.error(f"argument '{prefix}url' is already present")
237
+ server_url = URL.create(
238
+ "mysql",
239
+ getattr(arguments, f"{prefix}user"),
240
+ getattr(arguments, f"{prefix}password"),
241
+ getattr(arguments, f"{prefix}host"),
242
+ getattr(arguments, f"{prefix}port"),
243
+ getattr(arguments, f"{prefix}database", None),
244
+ )
245
+ setattr(arguments, f"{prefix}url", server_url)
246
+ return arguments
@@ -0,0 +1,91 @@
1
+ # See the NOTICE file distributed with this work for additional information
2
+ # regarding copyright ownership.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Easy initialisation functionality to set an event logging system.
16
+
17
+ Examples:
18
+
19
+ >>> import logging, pathlib
20
+ >>> from ensembl.utils.logging import init_logging
21
+ >>> logfile = pathlib.Path("test.log")
22
+ >>> init_logging("INFO", logfile, "DEBUG")
23
+ >>> logging.info("This message is written in both stderr and the log file")
24
+ >>> logging.debug("This message is only written in the log file")
25
+
26
+ """
27
+
28
+ __all__ = [
29
+ "LogLevel",
30
+ "init_logging",
31
+ "init_logging_with_args",
32
+ ]
33
+
34
+ import argparse
35
+ import logging
36
+ from typing import Optional, Union
37
+
38
+ from ensembl.utils import StrPath
39
+
40
+
41
+ LogLevel = Union[int, str]
42
+
43
+
44
+ def init_logging(
45
+ log_level: LogLevel = "WARNING",
46
+ log_file: Optional[StrPath] = None,
47
+ log_file_level: LogLevel = "DEBUG",
48
+ msg_format: str = "%(asctime)s\t%(levelname)s\t%(message)s",
49
+ date_format: str = r"%Y-%m-%d_%H:%M:%S",
50
+ ) -> None:
51
+ """Initialises the logging system.
52
+
53
+ By default, all the log messages corresponding to `log_level` (and above) will be printed in the
54
+ standard error. If `log_file` is provided, all messages of `log_file_level` level (and above) will
55
+ be written into the provided file.
56
+
57
+ Args:
58
+ log_level: Minimum logging level for the standard error.
59
+ log_file: Logging file where to write logging messages besides the standard error.
60
+ log_file_level: Minimum logging level for the logging file.
61
+ msg_format: A format string for the logged output as a whole. More information:
62
+ https://docs.python.org/3/library/logging.html#logrecord-attributes
63
+ date_format: A format string for the date/time portion of the logged output. More information:
64
+ https://docs.python.org/3/library/logging.html#logging.Formatter.formatTime
65
+
66
+ """
67
+ # Configure the basic logging system, setting the root logger to the minimum log level available
68
+ # to avoid filtering messages in any handler due to "parent delegation". Also close and remove any
69
+ # existing handlers before setting this configuration.
70
+ logging.basicConfig(format=msg_format, datefmt=date_format, level="DEBUG", force=True)
71
+ # Set the correct log level of the new StreamHandler (by default it is set to NOTSET)
72
+ logging.root.handlers[0].setLevel(log_level)
73
+ if log_file:
74
+ # Create the log file handler and add it to the root logger
75
+ formatter = logging.Formatter(msg_format, datefmt=date_format)
76
+ file_handler = logging.FileHandler(log_file)
77
+ file_handler.setLevel(log_file_level)
78
+ file_handler.setFormatter(formatter)
79
+ logging.root.addHandler(file_handler)
80
+
81
+
82
+ def init_logging_with_args(args: argparse.Namespace) -> None:
83
+ """Processes the Namespace object provided to call `init_logging()` with the correct arguments.
84
+
85
+ Args:
86
+ args: Namespace populated by an argument parser.
87
+
88
+ """
89
+ args_dict = vars(args)
90
+ log_args = {x: args_dict[x] for x in ["log_level", "log_file", "log_file_level"] if x in args_dict}
91
+ init_logging(**log_args)
@@ -0,0 +1,92 @@
1
+ # See the NOTICE file distributed with this work for additional information
2
+ # regarding copyright ownership.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Allow to seamlessly load / read the content of a remote file as if it was located locally."""
16
+
17
+ __all__ = ["RemoteFileLoader"]
18
+
19
+ import configparser
20
+ import json
21
+ import logging
22
+ from io import StringIO
23
+ from typing import Optional, Any
24
+
25
+ import dotenv
26
+ import requests
27
+ import requests.exceptions
28
+ import yaml
29
+
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ class RemoteFileLoader:
35
+ """Loads remote files, allowing specific format parsing options.
36
+
37
+ Args:
38
+ parser: Parser to use for this object. Default: `None` (no format-specific parsing done).
39
+
40
+ Attributes:
41
+ available_formats: File formats with ad-hoc parsers available.
42
+ parser: Parser selected for this object.
43
+
44
+ """
45
+
46
+ available_formats: set[str] = {"yaml", "ini", "env", "json"}
47
+ parser: Optional[str] = None
48
+
49
+ def __init__(self, parser: Optional[str] = None) -> None:
50
+ if parser in self.available_formats:
51
+ self.parser = parser
52
+
53
+ def __parse(self, content: str) -> Any:
54
+ if self.parser == "yaml":
55
+ return yaml.load(content, yaml.SafeLoader)
56
+ if self.parser == "ini":
57
+ config = configparser.ConfigParser()
58
+ try:
59
+ config.read_string(content)
60
+ except configparser.MissingSectionHeaderError:
61
+ content = "[DEFAULT]\n" + content
62
+ config.read_string(content)
63
+ return config
64
+ if self.parser == "env":
65
+ return dotenv.dotenv_values(stream=StringIO(content))
66
+ if self.parser == "json":
67
+ return json.loads(content)
68
+ # Only return content, no parsing
69
+ return content
70
+
71
+ def r_open(self, url: str) -> Any:
72
+ """Returns the parsed remote file from the given URL.
73
+
74
+ Args:
75
+ url: URL of the remote file to fetch.
76
+
77
+ Raises:
78
+ requests.exception.HTTPError: If loading or requesting the given URL returned an error.
79
+ requests.exception.Timeout: If a timeout was raised whilst requesting the given URL.
80
+
81
+ """
82
+ try:
83
+ r = requests.get(url, timeout=120)
84
+ if r.status_code == 200:
85
+ return self.__parse(r.text)
86
+ raise requests.exceptions.HTTPError(response=r)
87
+ except requests.exceptions.HTTPError as ex:
88
+ logger.exception(f"Error with request to {url}: {ex}")
89
+ raise ex
90
+ except requests.exceptions.Timeout as ex:
91
+ logger.exception(f"Request timed out {url}: {ex}")
92
+ raise ex
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,82 @@
1
+ Metadata-Version: 2.1
2
+ Name: ensembl-utils
3
+ Version: 0.1.1
4
+ Summary: Ensembl Python general-purpose utils
5
+ Author-email: Ensembl <dev@ensembl.org>
6
+ License: Apache License 2.0
7
+ Project-URL: homepage, https://www.ensembl.org
8
+ Project-URL: repository, https://github.com/Ensembl/ensembl-utils
9
+ Keywords: ensembl,python,utils
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Natural Language :: English
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ License-File: NOTICE
22
+ Requires-Dist: python-dotenv >=0.19.2
23
+ Requires-Dist: pyyaml ~=6.0
24
+ Requires-Dist: requests >=2.22.0
25
+ Requires-Dist: sqlalchemy ~=1.4.0
26
+ Provides-Extra: build
27
+ Requires-Dist: build ; extra == 'build'
28
+ Requires-Dist: setuptools ; extra == 'build'
29
+ Requires-Dist: setuptools-scm ; extra == 'build'
30
+ Requires-Dist: wheel ; extra == 'build'
31
+ Provides-Extra: cicd
32
+ Requires-Dist: black ; extra == 'cicd'
33
+ Requires-Dist: coverage ; extra == 'cicd'
34
+ Requires-Dist: genbadge[coverage] ; extra == 'cicd'
35
+ Requires-Dist: mypy ; extra == 'cicd'
36
+ Requires-Dist: pylint ; extra == 'cicd'
37
+ Requires-Dist: pytest ; extra == 'cicd'
38
+ Requires-Dist: pytest-dependency ; extra == 'cicd'
39
+ Requires-Dist: requests-mock >=1.8.0 ; extra == 'cicd'
40
+ Requires-Dist: types-pyyaml ; extra == 'cicd'
41
+ Requires-Dist: types-requests ; extra == 'cicd'
42
+ Provides-Extra: docs
43
+ Requires-Dist: mkdocs >=1.5.3 ; extra == 'docs'
44
+ Requires-Dist: mkdocs-autorefs ; extra == 'docs'
45
+ Requires-Dist: mkdocs-coverage ; extra == 'docs'
46
+ Requires-Dist: mkdocs-gen-files ; extra == 'docs'
47
+ Requires-Dist: mkdocs-literate-nav ; extra == 'docs'
48
+ Requires-Dist: mkdocs-material ; extra == 'docs'
49
+ Requires-Dist: mkdocs-material-extensions ; extra == 'docs'
50
+ Requires-Dist: mkdocs-section-index ; extra == 'docs'
51
+ Requires-Dist: mkdocstrings ; extra == 'docs'
52
+ Requires-Dist: mkdocstrings-python ; extra == 'docs'
53
+
54
+ # Ensembl Python general-purpose utils
55
+
56
+ [![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](https://github.com/Ensembl/ensembl-utils/blob/main/LICENSE)
57
+ [![Coverage](https://ensembl.github.io/ensembl-utils/coverage/coverage-badge.svg)](https://ensembl.github.io/ensembl-utils/coverage)
58
+ [![CI](https://github.com/Ensembl/ensembl-utils/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/Ensembl/ensembl-utils/actions/workflows/ci.yml)
59
+
60
+ Centralise generic Python utils used by other project within Ensembl design to facilitate frequent tasks such as input file path checks, archive files IO manipulation or logging setup, among others.
61
+
62
+ For more information, please consult this repository's [GitHub pages](https://ensembl.github.io/ensembl-utils/).
63
+
64
+ ## Getting Started
65
+
66
+ ### Basic installation
67
+
68
+ This library is publicly available in [pypi.org](https://pypi.org) so it can be easily installed with your favourite Python dependency and packaging management, e.g.
69
+ ```bash
70
+ pip install ensembl-utils
71
+ ```
72
+
73
+ ### Installing the development environment (with Python `venv`)
74
+
75
+ If you want to install this library in editable mode, we suggest you to do so via Python's virtual environment module ([venv](https://docs.python.org/3/library/venv.html)):
76
+ ```bash
77
+ python -m venv <VIRTUAL_ENVIRONMENT_NAME>
78
+ source <VIRTUAL_ENVIRONMENT_NAME>/bin/activate
79
+ git clone https://github.com/Ensembl/ensembl-utils.git
80
+ cd ensembl-utils
81
+ pip install -e .[cicd,dev,doc]
82
+ ```
@@ -0,0 +1,5 @@
1
+ Ensembl
2
+ Copyright [2016-2024] EMBL-European Bioinformatics Institute
3
+
4
+ This product includes software developed at:
5
+ - EMBL-European Bioinformatics Institute
@@ -0,0 +1,12 @@
1
+ ensembl/utils/__init__.py,sha256=sCcfd60bFWeSiHOqf_DTJdaInZBDrjtibQ-uHs2zfXY,832
2
+ ensembl/utils/archive.py,sha256=Nn_SPdsJEfBGWBZqqznP-hnrH8-HUn90TvcuiVGmj0s,3563
3
+ ensembl/utils/argparse.py,sha256=p-0PrpGyCdufMHx4v9UVsSbBBnHlRWodb9iOwNvmPrw,10194
4
+ ensembl/utils/logging.py,sha256=IJUolUDK7qk3lyFfEFnJPtP6FVxwM0yEKdX56U190E0,3664
5
+ ensembl/utils/rloader.py,sha256=jNLt9jkHcD1R5s0l0zovvzJAr62uK6gNEvowIBdSwXw,3150
6
+ ensembl_utils-0.1.1.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
7
+ ensembl_utils-0.1.1.dist-info/METADATA,sha256=W8EF9M4KoZc9BD4MwwcptrERdqo_v6S0RA_QedFHon8,3646
8
+ ensembl_utils-0.1.1.dist-info/NOTICE,sha256=KHSQKu-izGR6AEiAg6YL3lA2tzDM5yWvhWEKxA_R66A,156
9
+ ensembl_utils-0.1.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
10
+ ensembl_utils-0.1.1.dist-info/entry_points.txt,sha256=cN_m77zJZRLZHxqvF7CCdWawyBsPplDUUtBGG_WNlko,72
11
+ ensembl_utils-0.1.1.dist-info/top_level.txt,sha256=dUgAetY5ISlvzCun8T6ZjOtrtyC-ULeGQOJL7Bx7n0g,8
12
+ ensembl_utils-0.1.1.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
+ [console_scripts]
2
+ extract_file = ensembl.utils.archive:extract_file_cli
@@ -0,0 +1 @@
1
+ ensembl