|
| 1 | +# !/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Automatically sync recommended extensions from .vscode/extensions.json to .gitpod.yml |
| 4 | +""" |
| 5 | + |
| 6 | +# pylint: disable=import-error |
| 7 | +import json5 as json # This is needed so comments on .vscode/extensions.json are rendered fine. |
| 8 | +import logging |
| 9 | +import os |
| 10 | +import re |
| 11 | +import subprocess |
| 12 | +import sys |
| 13 | +from datetime import date, datetime |
| 14 | +from shutil import copyfile |
| 15 | +from typing import Any |
| 16 | +import yaml |
| 17 | + |
| 18 | +REPO_HOME = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + ".." |
| 19 | +BASE_MAGE = "gitpod/workspace-full" |
| 20 | + |
| 21 | +def replace_in_file(file_path, start, end, content, add_new_line=True): |
| 22 | + # Read in the file |
| 23 | + with open(file_path, "r", encoding="utf-8") as file: |
| 24 | + file_content = file.read() |
| 25 | + # Replace the target string |
| 26 | + if add_new_line is True: |
| 27 | + replacement = f"{start}\n{content}\n{end}" |
| 28 | + else: |
| 29 | + replacement = f"{start}{content}{end}" |
| 30 | + regex = rf"{start}([\s\S]*?){end}" |
| 31 | + file_content = re.sub(regex, replacement, file_content, re.DOTALL) |
| 32 | + # Write the file out again |
| 33 | + with open(file_path, "w", encoding="utf-8") as file: |
| 34 | + file.write(file_content) |
| 35 | + logging.info("Updated " + file.name) |
| 36 | + |
| 37 | +def updateWSExtensions(): |
| 38 | + extConfigPath = f"{REPO_HOME}/.vscode/extensions.json" |
| 39 | + gitpodConfigPath = f"{REPO_HOME}/.gitpod.yml" |
| 40 | + |
| 41 | + # Load the files first as streams and the load it as Python dictionaries |
| 42 | + with open(extConfigPath) as f: |
| 43 | + extConfigVSC = json.load(f) |
| 44 | + with open(gitpodConfigPath) as f: |
| 45 | + gpConfig = yaml.load(f) |
| 46 | + |
| 47 | + # Pull and dump to memory first |
| 48 | + recommends = extConfigVSC["recommendations"] |
| 49 | + gpConfig['vscode']['extensions'] = recommends |
| 50 | + |
| 51 | + # When done, dump the changes to our Gitpod config |
| 52 | + with open(gitpodConfigPath, 'w') as configDump: |
| 53 | + yaml.dump(obj, configDump) |
| 54 | + |
| 55 | +if __name__ == "__main__": |
| 56 | + try: |
| 57 | + logging.basicConfig( |
| 58 | + force=True, |
| 59 | + level=logging.INFO, |
| 60 | + format="%(asctime)s [%(levelname)s] %(message)s", |
| 61 | + handlers=[logging.StreamHandler(sys.stdout)], |
| 62 | + ) |
| 63 | + except ValueError: |
| 64 | + logging.basicConfig( |
| 65 | + level=logging.INFO, |
| 66 | + format="%(asctime)s [%(levelname)s] %(message)s", |
| 67 | + handlers=[logging.StreamHandler(sys.stdout)], |
| 68 | + ) |
| 69 | + |
| 70 | + # Generate vscode.extensions array in .gitpod.yml |
| 71 | + updateWSExtensions() |
0 commit comments