|
| 1 | +import os |
| 2 | +import re |
| 3 | +import subprocess |
| 4 | +from abc import ABC, abstractmethod |
| 5 | + |
| 6 | + |
| 7 | +class BaseArchive(ABC): |
| 8 | + def __init__(self, path): |
| 9 | + self.path = path |
| 10 | + |
| 11 | + def extract(self): |
| 12 | + print("TODO") |
| 13 | + |
| 14 | + def splitext(self): |
| 15 | + base, ext = os.path.splitext(self.path) |
| 16 | + base, subext = os.path.splitext(base) |
| 17 | + return base, ext, subext |
| 18 | + |
| 19 | + |
| 20 | +class TarZstdArchive(BaseArchive): |
| 21 | + @staticmethod |
| 22 | + def test(path): |
| 23 | + return re.search(r"\.tar\.zstd?$", path) |
| 24 | + |
| 25 | + def extract(self, dir, dry_run=False): |
| 26 | + if not dir: |
| 27 | + dir = os.path.dirname(self.path) |
| 28 | + base, ext, subext = self.splitext() |
| 29 | + dir = os.path.join(dir, base) |
| 30 | + |
| 31 | + if not dry_run: |
| 32 | + os.mkdir(dir) |
| 33 | + subprocess.run( |
| 34 | + [ |
| 35 | + "tar", |
| 36 | + "--use-compress-program=unzstd", |
| 37 | + "-C", |
| 38 | + dir, |
| 39 | + "-xvf", |
| 40 | + self.path, |
| 41 | + ], |
| 42 | + check=True, |
| 43 | + ) |
| 44 | + os.remove(self.path) |
| 45 | + |
| 46 | + return dir # , base, ext, subext |
| 47 | + |
| 48 | + |
| 49 | +archiveClasses = [TarZstdArchive] |
| 50 | + |
| 51 | + |
| 52 | +def Archive(path, **kwargs): |
| 53 | + for ArchiveClass in archiveClasses: |
| 54 | + if ArchiveClass.test(path): |
| 55 | + return ArchiveClass(path, **kwargs) |
| 56 | + |
| 57 | + |
| 58 | +class BaseStorage(ABC): |
| 59 | + @staticmethod |
| 60 | + @abstractmethod |
| 61 | + def test(url): |
| 62 | + return re.search(r"^https?://", url) |
| 63 | + |
| 64 | + def __init__(self, url, **kwargs): |
| 65 | + self.url = url |
| 66 | + |
| 67 | + def splitext(self): |
| 68 | + base, ext = os.path.splitext(self.url) |
| 69 | + base, subext = os.path.splitext(base) |
| 70 | + return base, ext, subext |
| 71 | + |
| 72 | + def get_filename(self): |
| 73 | + return self.url.split("/").pop() |
| 74 | + |
| 75 | + @abstractmethod |
| 76 | + def download_file(self, dest): |
| 77 | + """Download the file to `dest`""" |
| 78 | + pass |
| 79 | + |
| 80 | + def download_and_extract(self, fname, dry_run=False): |
| 81 | + """ |
| 82 | + Downloads the file, and if it's an archive, extract it too. Returns |
| 83 | + the filename if not, or directory name (fname without extension) if |
| 84 | + it was. |
| 85 | + """ |
| 86 | + if not fname: |
| 87 | + fname = self.get_filename() |
| 88 | + |
| 89 | + dir = None |
| 90 | + archive = Archive(fname, dry_run=dry_run) |
| 91 | + if archive: |
| 92 | + # TODO, streaming pipeline |
| 93 | + self.download_file(fname) |
| 94 | + return archive.extract() |
| 95 | + else: |
| 96 | + self.download_file(fname) |
| 97 | + return fname |
0 commit comments