Splices the post save hook into the global Jupyter configuration file
Source code in nbautoexport/jupyter_config.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
def install_post_save_hook(config_path: Optional[Path] = None):
"""Splices the post save hook into the global Jupyter configuration file
"""
if config_path is None:
config_dir = jupyter_config_dir()
config_path = Path(config_dir) / "jupyter_notebook_config.py"
config_path = config_path.expanduser().resolve()
if not config_path.exists():
logger.debug(f"No existing Jupyter configuration detected at {config_path}. Creating...")
config_path.parent.mkdir(exist_ok=True, parents=True)
with config_path.open("w") as fp:
fp.write(post_save_hook_initialize_block)
logger.info("nbautoexport post-save hook installed.")
return
# If config exists, check for existing nbautoexport initialize block and install as appropriate
logger.debug(f"Detected existing Jupyter configuration at {config_path}")
with config_path.open("r") as fp:
config = fp.read()
if block_regex.search(config):
logger.debug("Detected existing nbautoexport post-save hook.")
version_match = version_regex.search(config)
if version_match:
existing_version = version_match.group()
logger.debug(f"Existing post-save hook is version {existing_version}")
else:
existing_version = ""
logger.debug("Existing post-save hook predates versioning.")
if parse_version(existing_version) < parse_version(__version__):
logger.info(f"Updating nbautoexport post-save hook with version {__version__}...")
with config_path.open("w") as fp:
# Open as w replaces existing file. We're replacing entire config.
fp.write(block_regex.sub(post_save_hook_initialize_block, config))
else:
logger.debug("No changes made.")
return
else:
logger.info("Installing post-save hook.")
with config_path.open("a") as fp:
# Open as a just appends. We append block at the end of existing file.
fp.write("\n" + post_save_hook_initialize_block)
logger.info("nbautoexport post-save hook installed.")
|