-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobsidian-dev-setup
More file actions
executable file
·329 lines (269 loc) · 10.8 KB
/
obsidian-dev-setup
File metadata and controls
executable file
·329 lines (269 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
#!/usr/bin/env python3
"""
Automated Obsidian Plugin Development Setup
This script sets up an Obsidian plugin for development with hot reloading.
It creates symbolic links, builds the plugin, and configures hot reload.
Usage:
obsidian-dev-setup [vault-path] [plugin-dir]
If no arguments provided, tries to detect vault from common locations
and uses current directory as plugin-dir.
"""
import os
import sys
import json
import subprocess
from pathlib import Path
def detect_package_manager(plugin_dir):
"""Detect whether the project uses bun or npm."""
bun_lock = Path(plugin_dir) / "bun.lock"
package_lock = Path(plugin_dir) / "package-lock.json"
yarn_lock = Path(plugin_dir) / "yarn.lock"
if bun_lock.exists():
return "bun"
elif yarn_lock.exists():
return "yarn"
elif package_lock.exists():
return "npm"
else:
# Check if bun is available and package.json exists
package_json = Path(plugin_dir) / "package.json"
if package_json.exists():
try:
subprocess.run(["bun", "--version"], capture_output=True, check=True)
return "bun"
except (subprocess.CalledProcessError, FileNotFoundError):
pass
return "npm"
def find_obsidian_vaults():
"""Find potential Obsidian vault locations."""
home = Path.home()
potential_paths = [
home / "Obsidian" / "Notes",
home / "Documents" / "Obsidian",
home / "Notes",
home / "Vault",
]
vaults = []
for path in potential_paths:
if path.exists() and (path / ".obsidian").exists():
vaults.append(path)
return vaults
def get_plugin_info(plugin_dir):
"""Extract plugin information from manifest.json."""
manifest_path = Path(plugin_dir) / "manifest.json"
if not manifest_path.exists():
print(f"❌ No manifest.json found in {plugin_dir}")
print("This doesn't appear to be an Obsidian plugin directory.")
sys.exit(1)
try:
with open(manifest_path, 'r') as f:
manifest = json.load(f)
return manifest.get('id'), manifest.get('name')
except json.JSONDecodeError:
print(f"❌ Invalid JSON in {manifest_path}")
sys.exit(1)
def check_hot_reload(vault_path):
"""Check if Hot Reload plugin is installed and enabled."""
plugins_dir = vault_path / ".obsidian" / "plugins"
hot_reload_dir = plugins_dir / "hot-reload"
if not hot_reload_dir.exists():
return False, "not_installed"
# Check if it's enabled in community-plugins.json
community_plugins_path = vault_path / ".obsidian" / "community-plugins.json"
if community_plugins_path.exists():
try:
with open(community_plugins_path, 'r') as f:
enabled_plugins = json.load(f)
if "hot-reload" in enabled_plugins:
return True, "enabled"
else:
return False, "disabled"
except json.JSONDecodeError:
pass
return False, "unknown"
def build_plugin(plugin_dir, package_manager):
"""Build the plugin."""
plugin_dir = Path(plugin_dir)
main_js = plugin_dir / "main.js"
main_ts = plugin_dir / "main.ts"
# Check if build is needed
if main_js.exists() and main_ts.exists():
if main_js.stat().st_mtime > main_ts.stat().st_mtime:
print("✅ Build is up-to-date")
return True
print(f"🔨 Building plugin using {package_manager}...")
try:
result = subprocess.run(
[package_manager, "run", "build"],
cwd=plugin_dir,
capture_output=True,
text=True,
check=True
)
print("✅ Build successful")
return True
except subprocess.CalledProcessError as e:
# If build fails but main.js exists, warn but continue
if main_js.exists():
print(f"⚠️ Build failed but main.js exists, continuing...")
print(f" Build error: {e.stderr.strip()[:100]}...")
return True
else:
print(f"❌ Build failed and no main.js found: {e.stderr}")
return False
def setup_plugin_links(plugin_dir, vault_path, plugin_id):
"""Set up symbolic links for plugin files."""
plugin_dir = Path(plugin_dir)
vault_plugin_dir = vault_path / ".obsidian" / "plugins" / plugin_id
# Create plugin directory
vault_plugin_dir.mkdir(parents=True, exist_ok=True)
# Files that should be linked if they exist
files_to_link = [
"main.js", # Built JavaScript file
"manifest.json", # Plugin manifest
"styles.css", # Plugin styles
"versions.json" # Version compatibility info
]
linked_files = []
for filename in files_to_link:
source_file = plugin_dir / filename
target_file = vault_plugin_dir / filename
if source_file.exists():
# Check if symlink already exists and points to correct location
if target_file.is_symlink():
try:
if target_file.resolve() == source_file.resolve():
linked_files.append(filename)
print(f"✅ {filename} already linked correctly")
continue
except (OSError, RuntimeError):
pass # Broken symlink, will be replaced
# Remove existing file/link
if target_file.exists() or target_file.is_symlink():
target_file.unlink()
# Create symbolic link
try:
target_file.symlink_to(source_file)
linked_files.append(filename)
print(f"🔗 Linked {filename}")
except OSError as e:
print(f"❌ Failed to link {filename}: {e}")
else:
print(f"⚠️ Skipped {filename} (doesn't exist)")
return linked_files
def create_hotreload_file(vault_path, plugin_id, plugin_dir):
"""Create .hotreload file to enable automatic reloading."""
hotreload_file = vault_path / ".obsidian" / "plugins" / plugin_id / ".hotreload"
expected_content = str(Path(plugin_dir).absolute()) + '\n'
# Check if file already exists with correct content
if hotreload_file.exists():
try:
with open(hotreload_file, 'r') as f:
existing_content = f.read()
if existing_content == expected_content:
print("✅ .hotreload file already exists and is correct")
return
except OSError:
pass # File exists but can't read it, will recreate
# Create or update the file
with open(hotreload_file, 'w') as f:
f.write(expected_content)
if hotreload_file.exists():
print("🔥 Updated .hotreload file")
else:
print("🔥 Created .hotreload file")
def main():
# Parse arguments - vault first, plugin directory second
if len(sys.argv) > 1:
vault_path = Path(sys.argv[1])
else:
# Try to detect vault
vaults = find_obsidian_vaults()
if not vaults:
print("❌ No Obsidian vaults found. Please specify vault path:")
print("Usage: obsidian-dev-setup [vault-path] [plugin-dir]")
sys.exit(1)
elif len(vaults) == 1:
vault_path = vaults[0]
else:
print("Multiple Obsidian vaults found:")
for i, vault in enumerate(vaults):
print(f" {i + 1}. {vault}")
choice = input("Select vault (1-{}): ".format(len(vaults)))
try:
vault_path = vaults[int(choice) - 1]
except (ValueError, IndexError):
print("❌ Invalid selection")
sys.exit(1)
if len(sys.argv) > 2:
plugin_dir = Path(sys.argv[2])
else:
plugin_dir = Path.cwd()
# Validate paths
if not plugin_dir.exists():
print(f"❌ Plugin directory not found: {plugin_dir}")
sys.exit(1)
if not vault_path.exists():
print(f"❌ Vault not found: {vault_path}")
sys.exit(1)
if not (vault_path / ".obsidian").exists():
print(f"❌ Not an Obsidian vault (no .obsidian directory): {vault_path}")
sys.exit(1)
print(f"🚀 Setting up Obsidian plugin development")
print(f" Plugin directory: {plugin_dir}")
print(f" Vault: {vault_path}")
print()
# Get plugin info
plugin_id, plugin_name = get_plugin_info(plugin_dir)
print(f"📦 Plugin: {plugin_name} (id: {plugin_id})")
print()
# Detect package manager
package_manager = detect_package_manager(plugin_dir)
print(f"📋 Package manager: {package_manager}")
print()
# Check hot reload status
hot_reload_available, hot_reload_status = check_hot_reload(vault_path)
# Build plugin
if not build_plugin(plugin_dir, package_manager):
print("❌ Cannot continue without a successful build")
sys.exit(1)
print()
# Set up links
linked_files = setup_plugin_links(plugin_dir, vault_path, plugin_id)
print()
# Create hotreload file
create_hotreload_file(vault_path, plugin_id, plugin_dir)
print()
# Hot reload status and instructions
if hot_reload_available:
print("✅ Hot Reload plugin is installed and enabled")
print("🔥 Your plugin will automatically reload when files change")
else:
print("⚠️ Hot Reload plugin status:", hot_reload_status)
if hot_reload_status == "not_installed":
print("📝 To enable hot reloading:")
print(" 1. Go to Settings > Community Plugins")
print(" 2. Browse and install 'Hot Reload'")
print(" 3. Enable the Hot Reload plugin")
elif hot_reload_status == "disabled":
print("📝 To enable hot reloading:")
print(" 1. Go to Settings > Community Plugins")
print(" 2. Enable the Hot Reload plugin")
print()
# Development instructions
print("🎯 Development workflow:")
print(f" • One-time build: {package_manager} run build")
print(f" • Continuous development: {package_manager} run dev")
if hot_reload_available:
print(" • Files will automatically reload in Obsidian")
else:
print(" • Manually reload plugin in Obsidian after changes")
print()
print("✅ Setup complete! Your plugin is ready for development.")
# Enable plugin reminder
print()
print("💡 Don't forget to:")
print(f" 1. Enable '{plugin_name}' in Settings > Community Plugins")
print(" 2. Configure any required settings (like API keys)")
if __name__ == "__main__":
main()