Skip to content

Instantly share code, notes, and snippets.

@nuno-andre
Last active February 3, 2021 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nuno-andre/3a7d0139e5424b7a49ab1a56c2f2b8d1 to your computer and use it in GitHub Desktop.
Save nuno-andre/3a7d0139e5424b7a49ab1a56c2f2b8d1 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
.code-workspace generator
https://github.com/microsoft/vscode/issues/45177#issuecomment-528254048
"""
from pathlib import Path
import json
import os
# not project dirs, they only belong to the metarepo
metadirs = {'.dev', '.git', 'bin', 'dist', 'docs', 'tests', 'vendor'}
template = {
'folders': [{'name': '.', 'path': '.'}],
'settings': {'files.exclude': {}}
}
def make_multiroot_workspace():
# It's inside './.dev', hence the '..'
root = Path(__file__).parent.joinpath('..').resolve()
dirs = [d for d in root.iterdir() if d.is_dir() and d.name not in metadirs]
for d in dirs:
walk = os.walk(root)
next(walk)
if any(d.name in dirs for _, dirs, _ in walk):
d.rename(d.with_name(f'_{d.name}'))
v = {'name': d.name, 'path': f'_{d.name}'}
else:
v = {'path': d.name}
template['folders'].append(v)
template['settings']['files.exclude'].update({f'{v["path"]}/': True})
root.joinpath(f'{root.name}.code-workspace').write_text(
json.dumps(template, indent=4))
if __name__ == '__main__':
make_multiroot_workspace()
#!/usr/bin/env python3
"""
resolve ${env:<var>} and ${workspaceFolder:<folder>} paths and open workspace
https://github.com/microsoft/vscode/issues/2809#issuecomment-770541084
"""
from functools import partial
from subprocess import run
from pathlib import Path
import commentjson as json
import sys, re, os
filepath = Path(sys.argv[1]).absolute()
tmpfile = Path(filepath).with_stem('tmp')
paths = lambda cfg: {f.get('name', f['path']): f['path'] for f in json.loads(cfg)['folders']} #1
path = lambda dct, x: dct[x[1]].replace('\\', '\\\\')
subn = lambda ptrn, dct, txt: re.subn(ptrn, partial(path, dct), txt) # 2
subs = subn(r'\${env:(.+?)}', os.environ, filepath.read_text()) # 3
while (subs := subn(r'\${workspaceFolder:(.+?)}', paths(subs[0]), subs[0]))[1]: pass # 4
tmpfile.write_text(subs[0])
run(['code', tmpfile], shell=True)
sys.stdout.write(str(tmpfile))
# usage: python script.py .code-workspace
#1: called in every iteration to get an updated workspace paths dictionary
#2: replaces a variable with its value in `paths` dict (either a path or another variable)
#3: env vars interpolation
#4: substitute variables as long as they appear
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment