|
| 1 | +import bz2 |
| 2 | +import gzip |
| 3 | +import io |
| 4 | +import os |
| 5 | + |
| 6 | +from . import p7z |
| 7 | +from ..errors import FileTypeError |
| 8 | + |
| 9 | +FILE_READERS = { |
| 10 | + 'gz': lambda fn: gzip.open(fn, 'rt', encoding='utf-8', errors='replace'), |
| 11 | + 'bz2': lambda fn: bz2.open(fn, 'rt', encoding='utf-8', errors='replace'), |
| 12 | + '7z': p7z.reader, |
| 13 | + 'json': lambda fn: open(fn, 'rt', encoding='utf-8', errors='replace'), |
| 14 | + 'xml': lambda fn: open(fn, 'rt', encoding='utf-8', errors='replace') |
| 15 | +} |
| 16 | +""" |
| 17 | +Maps extensions to the strategy for opening/decompressing a file |
| 18 | +""" |
| 19 | + |
| 20 | +FILE_WRITERS = { |
| 21 | + 'gz': lambda fn: gzip.open(fn, 'wt', encoding='utf-8', errors='replace'), |
| 22 | + 'bz2': lambda fn: bz2.open(fn, 'wt', encoding='utf-8', errors='replace'), |
| 23 | + 'plaintext': lambda fn: open(fn, 'wt', encoding='utf-8', errors='replace'), |
| 24 | + 'json': lambda fn: open(fn, 'wt', encoding='utf-8', errors='replace'), |
| 25 | + 'xml': lambda fn: open(fn, 'wt', encoding='utf-8', errors='replace') |
| 26 | +} |
| 27 | +""" |
| 28 | +Maps compression types to the strategy for opening/compressing a file |
| 29 | +""" |
| 30 | + |
| 31 | + |
| 32 | +def extract_extension(path): |
| 33 | + """ |
| 34 | + Reads a file path and returns the extension or None if the path |
| 35 | + contains no extension. |
| 36 | +
|
| 37 | + :Parameters: |
| 38 | + path : str |
| 39 | + A filesystem path |
| 40 | + """ |
| 41 | + filename = os.path.basename(path) |
| 42 | + parts = filename.split(".") |
| 43 | + if len(parts) == 1: |
| 44 | + return filename, None |
| 45 | + else: |
| 46 | + return ".".join(parts[:-1]), parts[-1] |
| 47 | + |
| 48 | + |
| 49 | +def normalize_path(path_or_f): |
| 50 | + """ |
| 51 | + Verifies that a file exists at a given path and that the file has a |
| 52 | + known extension type. |
| 53 | +
|
| 54 | + :Parameters: |
| 55 | + path_or_f : `str` | `file` |
| 56 | + the path to a dump file or a file handle |
| 57 | +
|
| 58 | + """ |
| 59 | + if hasattr(path_or_f, "read"): |
| 60 | + return path_or_f |
| 61 | + else: |
| 62 | + path = path_or_f |
| 63 | + |
| 64 | + path = os.path.expanduser(path) |
| 65 | + |
| 66 | + # Check if exists and is a file |
| 67 | + if os.path.isdir(path): |
| 68 | + raise IsADirectoryError("Is a directory: {0}".format(path)) |
| 69 | + elif not os.path.isfile(path): |
| 70 | + raise FileNotFoundError("No such file: {0}".format(path)) |
| 71 | + |
| 72 | + _, extension = extract_extension(path) |
| 73 | + |
| 74 | + if extension not in FILE_READERS: |
| 75 | + raise FileTypeError("Extension {0} is not supported." |
| 76 | + .format(repr(extension))) |
| 77 | + |
| 78 | + return path |
| 79 | + |
| 80 | + |
| 81 | +def normalize_dir(path): |
| 82 | + if os.path.exists(path) and not os.path.isdir(path): |
| 83 | + raise NotADirectoryError("Not a directory: {0}".format(path)) |
| 84 | + else: |
| 85 | + os.makedirs(path, exist_ok=True) |
| 86 | + |
| 87 | + return path |
| 88 | + |
| 89 | + |
| 90 | +def reader(path_or_f): |
| 91 | + """ |
| 92 | + Turns a path to a compressed file into a file-like object of (decompressed) |
| 93 | + data. |
| 94 | +
|
| 95 | + :Parameters: |
| 96 | + path : `str` |
| 97 | + the path to the dump file to read |
| 98 | + """ |
| 99 | + if hasattr(path_or_f, "read"): |
| 100 | + return path_or_f |
| 101 | + else: |
| 102 | + path = path_or_f |
| 103 | + |
| 104 | + path = normalize_path(path) |
| 105 | + _, extension = extract_extension(path) |
| 106 | + |
| 107 | + reader_func = FILE_READERS[extension] |
| 108 | + |
| 109 | + return reader_func(path) |
| 110 | + |
| 111 | + |
| 112 | +def output_dir_path(old_path, output_dir, compression): |
| 113 | + filename, extension = extract_extension(old_path) |
| 114 | + new_filename = filename + "." + compression |
| 115 | + return os.path.join(output_dir, new_filename) |
| 116 | + |
| 117 | + |
| 118 | +def writer(path): |
| 119 | + """ |
| 120 | + Creates a compressed file writer from for a path with a specified |
| 121 | + compression type. |
| 122 | + """ |
| 123 | + filename, extension = extract_extension(path) |
| 124 | + if extension in FILE_WRITERS: |
| 125 | + writer_func = FILE_WRITERS[extension] |
| 126 | + return writer_func(path) |
| 127 | + else: |
| 128 | + raise RuntimeError("Output compression {0} not supported. Type {1}" |
| 129 | + .format(extension, tuple(FILE_WRITERS.keys()))) |
| 130 | + |
| 131 | + |
| 132 | +class ConcatinatingTextReader(io.TextIOBase): |
| 133 | + |
| 134 | + def __init__(self, *items): |
| 135 | + self.items = [io.StringIO(i) if isinstance(i, str) else i |
| 136 | + for i in items] |
| 137 | + |
| 138 | + def read(self, size=-1): |
| 139 | + return "".join(self._read(size)) |
| 140 | + |
| 141 | + def readline(self): |
| 142 | + |
| 143 | + if len(self.items) > 0: |
| 144 | + line = self.items[0].readline() |
| 145 | + if line == "": |
| 146 | + self.items.pop(0) |
| 147 | + else: |
| 148 | + line = "" |
| 149 | + |
| 150 | + return line |
| 151 | + |
| 152 | + def _read(self, size): |
| 153 | + if size > 0: |
| 154 | + while len(self.items) > 0: |
| 155 | + byte_vals = self.items[0].read(size) |
| 156 | + yield byte_vals |
| 157 | + if len(byte_vals) < size: |
| 158 | + size = size - len(byte_vals) # Decrement bytes |
| 159 | + self.items.pop(0) |
| 160 | + else: |
| 161 | + break |
| 162 | + |
| 163 | + else: |
| 164 | + for item in self.items: |
| 165 | + yield item.read() |
| 166 | + |
| 167 | + |
| 168 | +def concat(*stream_items): |
| 169 | + """ |
| 170 | + Performs a streaming concatenation of `str` or `file`. |
| 171 | + :Parameters: |
| 172 | + \*stream_items : `str` | `file` |
| 173 | + A list of items to concatenate together |
| 174 | + """ |
| 175 | + return ConcatinatingTextReader(*stream_items) |
0 commit comments