Skip to content

Instantly share code, notes, and snippets.

@Diogo-Rossi
Last active July 28, 2023 20:01
Show Gist options
  • Save Diogo-Rossi/cf4673aa28b4c46987717f6d63c0d8d9 to your computer and use it in GitHub Desktop.
Save Diogo-Rossi/cf4673aa28b4c46987717f6d63c0d8d9 to your computer and use it in GitHub Desktop.
Python script to sync extensions in VS Code
from __future__ import annotations
ignoreextensions = [] # cSpell:disable-line
print('-'*60)
import os
import subprocess
from dataclasses import dataclass
from packaging.version import parse as version, Version
from typing import Union
@dataclass
class Extension:
id: str
version: Version
def __eq__(self, __o: Extension) -> bool:
return self.id == __o.id
@property
def log(self) -> str:
return self.id + "@" + str(self.version)
def install(ext: Extension) -> None:
os.system('code --install-extension ' + ext.id + ' --force')
def unistall(ext: Extension) -> None:
os.system('code --uninstall-extension ' + ext.id)
extensions = []
for line in open('extensions.txt','r'):
extension_id = line.split('@')[0]
extension_version = version(line.split('@')[1].split('\n')[0])
extensions.append(Extension(extension_id,extension_version))
local_extensions_output = (subprocess.run('code --list-extensions --show-versions', stdout=subprocess.PIPE, shell=True)
.stdout.decode('utf-8')
.split('\n')[:-1])
localextensions = []
for localext in local_extensions_output:
extension_id = localext.split('@')[0]
extension_version = version(localext.split('@')[1])
localextensions.append(Extension(extension_id, extension_version))
tolog = []
answer = 'y'
yestoall = False
# Skip | install if not | install if old
for ext in extensions:
if ext.id in ignoreextensions:
print(f"-- Skipped ignored extension: '{ext.id}'")
tolog.append(ext.log + '\n')
continue
if ext not in localextensions:
print('-'*60)
if not yestoall:
answer = input(f'> Install extension {ext.id}? (y/n/yes-to-all) [y]: ')
yestoall = answer == 'yes-to-all'
if answer != 'n' or yestoall:
print(f"Extension '{ext.id}'")
install(ext)
tolog.append(ext.log + '\n')
print('-'*60)
else:
local = localextensions[localextensions.index(ext)]
if ext.version > local.version:
print('-'*60)
install(ext)
tolog.append(ext.log + '\n')
else:
print(f"Extension already updated: '{ext.id}'")
tolog.append(local.log + '\n')
# Ask for uninstall
notoall = False
for ext in localextensions:
if ext not in extensions:
print('-'*60)
if not notoall:
answer = input(f'> Uninstall extension {ext.id}? (y/n/no-to-all) [n]: ')
notoall = answer == 'no-to-all'
if answer == 'y':
unistall(ext)
else:
tolog.append(ext.log + '\n')
print('-'*60)
tolog = sorted(tolog, key=str.casefold)
with open('extensions.txt','w') as fd:
for ext in tolog:
fd.write(ext)
print('-'*60)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment