|
| 1 | +# Update or download example snippets |
| 2 | +# |
| 3 | +# Automatically download and update a collection of snippets to your local snippet folder |
| 4 | + |
| 5 | +from zipfile import ZipFile |
| 6 | +from tempfile import TemporaryFile |
| 7 | +import os |
| 8 | + |
| 9 | +#TODO: Merge remote with local description or hotkey changes (AKA: if filename matches, skip the first two lines, truncate, re-write the rest) |
| 10 | + |
| 11 | +domain = b'https://gist.github.com' |
| 12 | +path = b'/psifertex/6fbc7532f536775194edd26290892ef7' # Feel free to adapt to your own setup |
| 13 | +subfolder = 'examples' # Change to save the snippets to a different sub-folder |
| 14 | +tab2space = False |
| 15 | +width = 4 |
| 16 | + |
| 17 | +def download(url): |
| 18 | + provider = next(iter(DownloadProvider)).create_instance() |
| 19 | + code, data = provider.get_response(url) |
| 20 | + if code == 0: |
| 21 | + return data |
| 22 | + else: |
| 23 | + raise ConnectionError("Unsuccessful download of %s" % url) |
| 24 | + |
| 25 | +def update_snippets(): |
| 26 | + if not interaction.show_message_box('Warning', "Use at your own risk. Do you want to automatically overwrite local snippets from gist?", buttons=MessageBoxButtonSet.YesNoButtonSet): |
| 27 | + return |
| 28 | + snippetPath = os.path.realpath(os.path.join(user_plugin_path(), '..', 'snippets', subfolder)) |
| 29 | + if not os.path.isdir(snippetPath): |
| 30 | + os.makedirs(snippetPath) |
| 31 | + url = domain + path |
| 32 | + log_info("Downloading from: %s" % url) |
| 33 | + source = download(url) |
| 34 | + zipPath = [s for s in source.split(b'\"') if s.endswith(b'.zip')] |
| 35 | + if len(zipPath) != 1: |
| 36 | + log_error("Update failed.") |
| 37 | + return |
| 38 | + url = domain + zipPath[0] |
| 39 | + |
| 40 | + log_info("Downloading from: %s" % url) |
| 41 | + zip = download(url) |
| 42 | + with TemporaryFile() as f: |
| 43 | + f.write(zip) |
| 44 | + with ZipFile(f, 'r') as zip: |
| 45 | + for item in zip.infolist(): |
| 46 | + if item.filename[-1] == '/': |
| 47 | + continue |
| 48 | + basename = os.path.basename(item.filename) |
| 49 | + with open(os.path.join(snippetPath, basename), 'wb') as f: |
| 50 | + if tab2space: |
| 51 | + f.write(zip.read(item).replace(b'\t', b' ' * width)) |
| 52 | + else: |
| 53 | + f.write(zip.read(item)) |
| 54 | + log_info("Extracting %s" % item.filename) |
| 55 | + |
| 56 | +update_snippets() |
0 commit comments