eb8dbf66a1
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
72 lines
2.5 KiB
Python
72 lines
2.5 KiB
Python
"""Create a new, valid Obsidian vault on disk."""
|
|
|
|
import json
|
|
import os
|
|
|
|
|
|
def create_obsidian_vault(parent_dir: str, name: str) -> str:
|
|
"""Create a new Obsidian vault under ``parent_dir`` and return its path.
|
|
|
|
Creates ``parent_dir/name/`` together with a minimal but valid Obsidian
|
|
configuration: ``parent_dir/name/.obsidian/app.json`` containing ``{}``.
|
|
The presence of an ``.obsidian/`` directory is what Obsidian uses to
|
|
recognise a folder as a vault, so the result opens cleanly in Obsidian.
|
|
|
|
Impure: it writes to the filesystem. If the target already looks like a
|
|
vault (it already has an ``.obsidian/`` directory) a ``FileExistsError`` is
|
|
raised so an existing vault is never silently overwritten. A
|
|
``ValueError`` is raised for an empty ``name`` or one containing a path
|
|
separator.
|
|
|
|
Args:
|
|
parent_dir: Directory under which the new vault folder is created. It is
|
|
created if it does not exist yet.
|
|
name: Name of the new vault folder (a single path segment, no
|
|
separators).
|
|
|
|
Returns:
|
|
The absolute path of the created vault directory.
|
|
"""
|
|
if not name or os.sep in name or (os.altsep and os.altsep in name):
|
|
raise ValueError(f"invalid vault name: {name!r}")
|
|
|
|
vault_path = os.path.abspath(os.path.join(parent_dir, name))
|
|
obsidian_dir = os.path.join(vault_path, ".obsidian")
|
|
|
|
if os.path.isdir(obsidian_dir):
|
|
raise FileExistsError(f"vault already exists: {vault_path}")
|
|
|
|
os.makedirs(obsidian_dir, exist_ok=True)
|
|
app_json = os.path.join(obsidian_dir, "app.json")
|
|
with open(app_json, "w", encoding="utf-8") as handle:
|
|
json.dump({}, handle)
|
|
|
|
return vault_path
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import tempfile
|
|
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
path = create_obsidian_vault(tmp, "MyVault")
|
|
assert os.path.isdir(path), path
|
|
assert os.path.isfile(os.path.join(path, ".obsidian", "app.json"))
|
|
with open(os.path.join(path, ".obsidian", "app.json")) as f:
|
|
assert json.load(f) == {}
|
|
|
|
# Re-creating the same vault must fail.
|
|
try:
|
|
create_obsidian_vault(tmp, "MyVault")
|
|
raise AssertionError("expected FileExistsError")
|
|
except FileExistsError:
|
|
pass
|
|
|
|
# Invalid name must fail.
|
|
try:
|
|
create_obsidian_vault(tmp, "bad/name")
|
|
raise AssertionError("expected ValueError")
|
|
except ValueError:
|
|
pass
|
|
|
|
print("OK")
|