Skip to content

Instantly share code, notes, and snippets.

@juhasch
Created January 28, 2018 18:25
Show Gist options
  • Save juhasch/4908e377e622ed8a86c070e1fe36526d to your computer and use it in GitHub Desktop.
Save juhasch/4908e377e622ed8a86c070e1fe36526d to your computer and use it in GitHub Desktop.
Check integrity of JSON config files and remove entries for loading contrib extensions
"""Cleanup nbconfig files from notebook extension configurations
Gets list of notebook extensions from jupyter_contrib_nbextensions and removes the 'require' entry for
each found extension from the 'load_extensions' dict entry.
"""
import sys
import glob
import os
import json
import copy
from jupyter_core.paths import jupyter_config_path
import jupyter_contrib_nbextensions
extensions = jupyter_contrib_nbextensions._jupyter_nbextension_paths()
require_list = [ext['require'] for ext in extensions]
def do_cleanup(config):
"""Remove configuration entries"""
new_config = copy.deepcopy(config)
for key in config.keys():
if key == 'load_extensions':
for ext_name in config[key].keys():
if ext_name in require_list:
print('Config entry for {0} found, loading is {1}'.format(ext_name, config[key][ext_name] ))
del new_config[key][ext_name]
return new_config
def printinfo():
print('nbextensions_contrib_json_config.py [cleanup|nobackup]')
print('Check integrity of JSON config files')
print('Options:')
print(' cleanup - additionally remove all entries that load contrib extensions')
print(' nobackup - do not generate a *.backup file of the JSON config file')
def main(argv):
if 'help' in argv:
printinfo()
return
cleanup = 'cleanup' in argv
nobackup = 'nobackup' in argv
for d in jupyter_config_path():
print('Checking path {0}'.format(d))
for p in glob.glob(os.path.join(d, 'nbconfig', '*.json')):
print('Checking JSON config file {0}'.format(p))
try:
with open(p, 'r') as f:
config = json.load(f)
except json.decoder.JSONDecodeError:
print('JSONDecodeError when reading file {0}'.format(p))
new_config = do_cleanup(config)
if cleanup:
pnew = p + '.new'
if not nobackup:
print('Backing up JSON config file {0} to {1}'.format(p, pnew))
os.rename(p, os.path.join(d, '.backup'))
print('Updating JSON config file {0}'.format(p))
with open(p, 'w') as f:
json.dump(new_config, f)
if __name__ == "__main__":
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment