vscode 使用分支更改主题

vscode 使用分支更改主题

当我切换分支时,如何让 vscode 主题发生变化?

为每个分支提交.vscode/settings.json并设置不同的值workbench.colorTheme似乎是一个非常糟糕的主意。

答案1

钩子post-checkout可以运行并修改.vscode/settings.json文件。

#!/bin/env python3
# pip install jstyleson
# WARNING: Using this will strip comments out of the `settings.json` file
# .git/hooks/post-checkout
# https://git-scm.com/docs/githooks#_post_checkout


from pathlib import Path
import sys
import subprocess
import jstyleson

BRANCH_MAP = {
    "master": "Solarized Light",
    "dev": "Visual Studio Dark",
    "!DEFAULT": "Red",
}


def check_output(cmd):
    result = subprocess.run(cmd, stdout=subprocess.PIPE).stdout.decode("utf-8").strip()
    return result


def main():
    # print("post-checkout START")

    # pwd is git root
    oldref = sys.argv[1]
    newref = sys.argv[2]
    is_branch_change = sys.argv[3] == "1"

    settings_path = Path(".vscode/settings.json")

    if not is_branch_change:
        return

    if not settings_path.exists():
        return

    branch_cmd = "git rev-parse --abbrev-ref HEAD".split(" ")
    branch = check_output(branch_cmd)

    # print("branch:", branch)

    if branch not in BRANCH_MAP:
        branch = "!DEFAULT"

    new_theme = BRANCH_MAP[branch]

    settings = jstyleson.loads(settings_path.read_text())

    settings["workbench.colorTheme"] = new_theme

    settings_path.write_text(jstyleson.dumps(settings, indent=4))

    # print("post-checkout END")


main()

相关内容