basic-memory 0.7.0__py3-none-any.whl → 0.17.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of basic-memory might be problematic. Click here for more details.

Files changed (195) hide show
  1. basic_memory/__init__.py +5 -1
  2. basic_memory/alembic/alembic.ini +119 -0
  3. basic_memory/alembic/env.py +130 -20
  4. basic_memory/alembic/migrations.py +4 -9
  5. basic_memory/alembic/versions/314f1ea54dc4_add_postgres_full_text_search_support_.py +131 -0
  6. basic_memory/alembic/versions/502b60eaa905_remove_required_from_entity_permalink.py +51 -0
  7. basic_memory/alembic/versions/5fe1ab1ccebe_add_projects_table.py +120 -0
  8. basic_memory/alembic/versions/647e7a75e2cd_project_constraint_fix.py +112 -0
  9. basic_memory/alembic/versions/6830751f5fb6_merge_multiple_heads.py +24 -0
  10. basic_memory/alembic/versions/9d9c1cb7d8f5_add_mtime_and_size_columns_to_entity_.py +49 -0
  11. basic_memory/alembic/versions/a1b2c3d4e5f6_fix_project_foreign_keys.py +49 -0
  12. basic_memory/alembic/versions/a2b3c4d5e6f7_add_search_index_entity_cascade.py +56 -0
  13. basic_memory/alembic/versions/b3c3938bacdb_relation_to_name_unique_index.py +44 -0
  14. basic_memory/alembic/versions/cc7172b46608_update_search_index_schema.py +113 -0
  15. basic_memory/alembic/versions/e7e1f4367280_add_scan_watermark_tracking_to_project.py +37 -0
  16. basic_memory/alembic/versions/f8a9b2c3d4e5_add_pg_trgm_for_fuzzy_link_resolution.py +239 -0
  17. basic_memory/alembic/versions/g9a0b3c4d5e6_add_external_id_to_project_and_entity.py +173 -0
  18. basic_memory/api/app.py +87 -20
  19. basic_memory/api/container.py +133 -0
  20. basic_memory/api/routers/__init__.py +4 -1
  21. basic_memory/api/routers/directory_router.py +84 -0
  22. basic_memory/api/routers/importer_router.py +152 -0
  23. basic_memory/api/routers/knowledge_router.py +180 -23
  24. basic_memory/api/routers/management_router.py +80 -0
  25. basic_memory/api/routers/memory_router.py +9 -64
  26. basic_memory/api/routers/project_router.py +460 -0
  27. basic_memory/api/routers/prompt_router.py +260 -0
  28. basic_memory/api/routers/resource_router.py +136 -11
  29. basic_memory/api/routers/search_router.py +5 -5
  30. basic_memory/api/routers/utils.py +169 -0
  31. basic_memory/api/template_loader.py +292 -0
  32. basic_memory/api/v2/__init__.py +35 -0
  33. basic_memory/api/v2/routers/__init__.py +21 -0
  34. basic_memory/api/v2/routers/directory_router.py +93 -0
  35. basic_memory/api/v2/routers/importer_router.py +181 -0
  36. basic_memory/api/v2/routers/knowledge_router.py +427 -0
  37. basic_memory/api/v2/routers/memory_router.py +130 -0
  38. basic_memory/api/v2/routers/project_router.py +359 -0
  39. basic_memory/api/v2/routers/prompt_router.py +269 -0
  40. basic_memory/api/v2/routers/resource_router.py +286 -0
  41. basic_memory/api/v2/routers/search_router.py +73 -0
  42. basic_memory/cli/app.py +80 -10
  43. basic_memory/cli/auth.py +300 -0
  44. basic_memory/cli/commands/__init__.py +15 -2
  45. basic_memory/cli/commands/cloud/__init__.py +6 -0
  46. basic_memory/cli/commands/cloud/api_client.py +127 -0
  47. basic_memory/cli/commands/cloud/bisync_commands.py +110 -0
  48. basic_memory/cli/commands/cloud/cloud_utils.py +108 -0
  49. basic_memory/cli/commands/cloud/core_commands.py +195 -0
  50. basic_memory/cli/commands/cloud/rclone_commands.py +397 -0
  51. basic_memory/cli/commands/cloud/rclone_config.py +110 -0
  52. basic_memory/cli/commands/cloud/rclone_installer.py +263 -0
  53. basic_memory/cli/commands/cloud/upload.py +240 -0
  54. basic_memory/cli/commands/cloud/upload_command.py +124 -0
  55. basic_memory/cli/commands/command_utils.py +99 -0
  56. basic_memory/cli/commands/db.py +87 -12
  57. basic_memory/cli/commands/format.py +198 -0
  58. basic_memory/cli/commands/import_chatgpt.py +47 -223
  59. basic_memory/cli/commands/import_claude_conversations.py +48 -171
  60. basic_memory/cli/commands/import_claude_projects.py +53 -160
  61. basic_memory/cli/commands/import_memory_json.py +55 -111
  62. basic_memory/cli/commands/mcp.py +67 -11
  63. basic_memory/cli/commands/project.py +889 -0
  64. basic_memory/cli/commands/status.py +52 -34
  65. basic_memory/cli/commands/telemetry.py +81 -0
  66. basic_memory/cli/commands/tool.py +341 -0
  67. basic_memory/cli/container.py +84 -0
  68. basic_memory/cli/main.py +14 -6
  69. basic_memory/config.py +580 -26
  70. basic_memory/db.py +285 -28
  71. basic_memory/deps/__init__.py +293 -0
  72. basic_memory/deps/config.py +26 -0
  73. basic_memory/deps/db.py +56 -0
  74. basic_memory/deps/importers.py +200 -0
  75. basic_memory/deps/projects.py +238 -0
  76. basic_memory/deps/repositories.py +179 -0
  77. basic_memory/deps/services.py +480 -0
  78. basic_memory/deps.py +16 -185
  79. basic_memory/file_utils.py +318 -54
  80. basic_memory/ignore_utils.py +297 -0
  81. basic_memory/importers/__init__.py +27 -0
  82. basic_memory/importers/base.py +100 -0
  83. basic_memory/importers/chatgpt_importer.py +245 -0
  84. basic_memory/importers/claude_conversations_importer.py +192 -0
  85. basic_memory/importers/claude_projects_importer.py +184 -0
  86. basic_memory/importers/memory_json_importer.py +128 -0
  87. basic_memory/importers/utils.py +61 -0
  88. basic_memory/markdown/entity_parser.py +182 -23
  89. basic_memory/markdown/markdown_processor.py +70 -7
  90. basic_memory/markdown/plugins.py +43 -23
  91. basic_memory/markdown/schemas.py +1 -1
  92. basic_memory/markdown/utils.py +38 -14
  93. basic_memory/mcp/async_client.py +135 -4
  94. basic_memory/mcp/clients/__init__.py +28 -0
  95. basic_memory/mcp/clients/directory.py +70 -0
  96. basic_memory/mcp/clients/knowledge.py +176 -0
  97. basic_memory/mcp/clients/memory.py +120 -0
  98. basic_memory/mcp/clients/project.py +89 -0
  99. basic_memory/mcp/clients/resource.py +71 -0
  100. basic_memory/mcp/clients/search.py +65 -0
  101. basic_memory/mcp/container.py +110 -0
  102. basic_memory/mcp/project_context.py +155 -0
  103. basic_memory/mcp/prompts/__init__.py +19 -0
  104. basic_memory/mcp/prompts/ai_assistant_guide.py +70 -0
  105. basic_memory/mcp/prompts/continue_conversation.py +62 -0
  106. basic_memory/mcp/prompts/recent_activity.py +188 -0
  107. basic_memory/mcp/prompts/search.py +57 -0
  108. basic_memory/mcp/prompts/utils.py +162 -0
  109. basic_memory/mcp/resources/ai_assistant_guide.md +283 -0
  110. basic_memory/mcp/resources/project_info.py +71 -0
  111. basic_memory/mcp/server.py +61 -9
  112. basic_memory/mcp/tools/__init__.py +33 -21
  113. basic_memory/mcp/tools/build_context.py +120 -0
  114. basic_memory/mcp/tools/canvas.py +152 -0
  115. basic_memory/mcp/tools/chatgpt_tools.py +190 -0
  116. basic_memory/mcp/tools/delete_note.py +249 -0
  117. basic_memory/mcp/tools/edit_note.py +325 -0
  118. basic_memory/mcp/tools/list_directory.py +157 -0
  119. basic_memory/mcp/tools/move_note.py +549 -0
  120. basic_memory/mcp/tools/project_management.py +204 -0
  121. basic_memory/mcp/tools/read_content.py +281 -0
  122. basic_memory/mcp/tools/read_note.py +265 -0
  123. basic_memory/mcp/tools/recent_activity.py +528 -0
  124. basic_memory/mcp/tools/search.py +377 -24
  125. basic_memory/mcp/tools/utils.py +402 -16
  126. basic_memory/mcp/tools/view_note.py +78 -0
  127. basic_memory/mcp/tools/write_note.py +230 -0
  128. basic_memory/models/__init__.py +3 -2
  129. basic_memory/models/knowledge.py +82 -17
  130. basic_memory/models/project.py +93 -0
  131. basic_memory/models/search.py +68 -8
  132. basic_memory/project_resolver.py +222 -0
  133. basic_memory/repository/__init__.py +2 -0
  134. basic_memory/repository/entity_repository.py +437 -8
  135. basic_memory/repository/observation_repository.py +36 -3
  136. basic_memory/repository/postgres_search_repository.py +451 -0
  137. basic_memory/repository/project_info_repository.py +10 -0
  138. basic_memory/repository/project_repository.py +140 -0
  139. basic_memory/repository/relation_repository.py +79 -4
  140. basic_memory/repository/repository.py +148 -29
  141. basic_memory/repository/search_index_row.py +95 -0
  142. basic_memory/repository/search_repository.py +79 -268
  143. basic_memory/repository/search_repository_base.py +241 -0
  144. basic_memory/repository/sqlite_search_repository.py +437 -0
  145. basic_memory/runtime.py +61 -0
  146. basic_memory/schemas/__init__.py +22 -9
  147. basic_memory/schemas/base.py +131 -12
  148. basic_memory/schemas/cloud.py +50 -0
  149. basic_memory/schemas/directory.py +31 -0
  150. basic_memory/schemas/importer.py +35 -0
  151. basic_memory/schemas/memory.py +194 -25
  152. basic_memory/schemas/project_info.py +213 -0
  153. basic_memory/schemas/prompt.py +90 -0
  154. basic_memory/schemas/request.py +56 -2
  155. basic_memory/schemas/response.py +85 -28
  156. basic_memory/schemas/search.py +36 -35
  157. basic_memory/schemas/sync_report.py +72 -0
  158. basic_memory/schemas/v2/__init__.py +27 -0
  159. basic_memory/schemas/v2/entity.py +133 -0
  160. basic_memory/schemas/v2/resource.py +47 -0
  161. basic_memory/services/__init__.py +2 -1
  162. basic_memory/services/context_service.py +451 -138
  163. basic_memory/services/directory_service.py +310 -0
  164. basic_memory/services/entity_service.py +636 -71
  165. basic_memory/services/exceptions.py +21 -0
  166. basic_memory/services/file_service.py +402 -33
  167. basic_memory/services/initialization.py +216 -0
  168. basic_memory/services/link_resolver.py +50 -56
  169. basic_memory/services/project_service.py +888 -0
  170. basic_memory/services/search_service.py +232 -37
  171. basic_memory/sync/__init__.py +4 -2
  172. basic_memory/sync/background_sync.py +26 -0
  173. basic_memory/sync/coordinator.py +160 -0
  174. basic_memory/sync/sync_service.py +1200 -109
  175. basic_memory/sync/watch_service.py +432 -135
  176. basic_memory/telemetry.py +249 -0
  177. basic_memory/templates/prompts/continue_conversation.hbs +110 -0
  178. basic_memory/templates/prompts/search.hbs +101 -0
  179. basic_memory/utils.py +407 -54
  180. basic_memory-0.17.4.dist-info/METADATA +617 -0
  181. basic_memory-0.17.4.dist-info/RECORD +193 -0
  182. {basic_memory-0.7.0.dist-info → basic_memory-0.17.4.dist-info}/WHEEL +1 -1
  183. {basic_memory-0.7.0.dist-info → basic_memory-0.17.4.dist-info}/entry_points.txt +1 -0
  184. basic_memory/alembic/README +0 -1
  185. basic_memory/cli/commands/sync.py +0 -206
  186. basic_memory/cli/commands/tools.py +0 -157
  187. basic_memory/mcp/tools/knowledge.py +0 -68
  188. basic_memory/mcp/tools/memory.py +0 -170
  189. basic_memory/mcp/tools/notes.py +0 -202
  190. basic_memory/schemas/discovery.py +0 -28
  191. basic_memory/sync/file_change_scanner.py +0 -158
  192. basic_memory/sync/utils.py +0 -31
  193. basic_memory-0.7.0.dist-info/METADATA +0 -378
  194. basic_memory-0.7.0.dist-info/RECORD +0 -82
  195. {basic_memory-0.7.0.dist-info → basic_memory-0.17.4.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,263 @@
1
+ """Cross-platform rclone installation utilities."""
2
+
3
+ import os
4
+ import platform
5
+ import shutil
6
+ import subprocess
7
+ from typing import Optional
8
+
9
+ from rich.console import Console
10
+
11
+ console = Console()
12
+
13
+
14
+ class RcloneInstallError(Exception):
15
+ """Exception raised for rclone installation errors."""
16
+
17
+ pass
18
+
19
+
20
+ def is_rclone_installed() -> bool:
21
+ """Check if rclone is already installed and available in PATH."""
22
+ return shutil.which("rclone") is not None
23
+
24
+
25
+ def get_platform() -> str:
26
+ """Get the current platform identifier."""
27
+ system = platform.system().lower()
28
+ if system == "darwin":
29
+ return "macos"
30
+ elif system == "linux":
31
+ return "linux"
32
+ elif system == "windows":
33
+ return "windows"
34
+ else:
35
+ raise RcloneInstallError(f"Unsupported platform: {system}")
36
+
37
+
38
+ def run_command(command: list[str], check: bool = True) -> subprocess.CompletedProcess:
39
+ """Run a command with proper error handling."""
40
+ try:
41
+ console.print(f"[dim]Running: {' '.join(command)}[/dim]")
42
+ result = subprocess.run(command, capture_output=True, text=True, check=check)
43
+ if result.stdout:
44
+ console.print(f"[dim]Output: {result.stdout.strip()}[/dim]")
45
+ return result
46
+ except subprocess.CalledProcessError as e:
47
+ console.print(f"[red]Command failed: {e}[/red]")
48
+ if e.stderr:
49
+ console.print(f"[red]Error output: {e.stderr}[/red]")
50
+ raise RcloneInstallError(f"Command failed: {e}") from e
51
+ except FileNotFoundError as e:
52
+ raise RcloneInstallError(f"Command not found: {' '.join(command)}") from e
53
+
54
+
55
+ def install_rclone_macos() -> None:
56
+ """Install rclone on macOS using Homebrew or official script."""
57
+ # Try Homebrew first
58
+ if shutil.which("brew"):
59
+ try:
60
+ console.print("[blue]Installing rclone via Homebrew...[/blue]")
61
+ run_command(["brew", "install", "rclone"])
62
+ console.print("[green]rclone installed via Homebrew[/green]")
63
+ return
64
+ except RcloneInstallError:
65
+ console.print(
66
+ "[yellow]Homebrew installation failed, trying official script...[/yellow]"
67
+ )
68
+
69
+ # Fallback to official script
70
+ console.print("[blue]Installing rclone via official script...[/blue]")
71
+ try:
72
+ run_command(["sh", "-c", "curl https://rclone.org/install.sh | sudo bash"])
73
+ console.print("[green]rclone installed via official script[/green]")
74
+ except RcloneInstallError:
75
+ raise RcloneInstallError(
76
+ "Failed to install rclone. Please install manually: brew install rclone"
77
+ )
78
+
79
+
80
+ def install_rclone_linux() -> None:
81
+ """Install rclone on Linux using package managers or official script."""
82
+ # Try snap first (most universal)
83
+ if shutil.which("snap"):
84
+ try:
85
+ console.print("[blue]Installing rclone via snap...[/blue]")
86
+ run_command(["sudo", "snap", "install", "rclone"])
87
+ console.print("[green]rclone installed via snap[/green]")
88
+ return
89
+ except RcloneInstallError:
90
+ console.print("[yellow]Snap installation failed, trying apt...[/yellow]")
91
+
92
+ # Try apt (Debian/Ubuntu)
93
+ if shutil.which("apt"):
94
+ try:
95
+ console.print("[blue]Installing rclone via apt...[/blue]")
96
+ run_command(["sudo", "apt", "update"])
97
+ run_command(["sudo", "apt", "install", "-y", "rclone"])
98
+ console.print("[green]rclone installed via apt[/green]")
99
+ return
100
+ except RcloneInstallError:
101
+ console.print("[yellow]apt installation failed, trying official script...[/yellow]")
102
+
103
+ # Fallback to official script
104
+ console.print("[blue]Installing rclone via official script...[/blue]")
105
+ try:
106
+ run_command(["sh", "-c", "curl https://rclone.org/install.sh | sudo bash"])
107
+ console.print("[green]rclone installed via official script[/green]")
108
+ except RcloneInstallError:
109
+ raise RcloneInstallError(
110
+ "Failed to install rclone. Please install manually: sudo snap install rclone"
111
+ )
112
+
113
+
114
+ def install_rclone_windows() -> None:
115
+ """Install rclone on Windows using package managers."""
116
+ # Try winget first (built into Windows 10+)
117
+ if shutil.which("winget"):
118
+ try:
119
+ console.print("[blue]Installing rclone via winget...[/blue]")
120
+ run_command(
121
+ [
122
+ "winget",
123
+ "install",
124
+ "Rclone.Rclone",
125
+ "--accept-source-agreements",
126
+ "--accept-package-agreements",
127
+ ]
128
+ )
129
+ console.print("[green]rclone installed via winget[/green]")
130
+ return
131
+ except RcloneInstallError:
132
+ console.print("[yellow]winget installation failed, trying chocolatey...[/yellow]")
133
+
134
+ # Try chocolatey
135
+ if shutil.which("choco"):
136
+ try:
137
+ console.print("[blue]Installing rclone via chocolatey...[/blue]")
138
+ run_command(["choco", "install", "rclone", "-y"])
139
+ console.print("[green]rclone installed via chocolatey[/green]")
140
+ return
141
+ except RcloneInstallError:
142
+ console.print("[yellow]chocolatey installation failed, trying scoop...[/yellow]")
143
+
144
+ # Try scoop
145
+ if shutil.which("scoop"):
146
+ try:
147
+ console.print("[blue]Installing rclone via scoop...[/blue]")
148
+ run_command(["scoop", "install", "rclone"])
149
+ console.print("[green]rclone installed via scoop[/green]")
150
+ return
151
+ except RcloneInstallError:
152
+ console.print("[yellow]scoop installation failed[/yellow]")
153
+
154
+ # No package manager available - provide detailed instructions
155
+ error_msg = (
156
+ "Could not install rclone automatically.\n\n"
157
+ "Windows requires a package manager to install rclone. Options:\n\n"
158
+ "1. Install winget (recommended, built into Windows 11):\n"
159
+ " - Windows 11: Already installed\n"
160
+ " - Windows 10: Install 'App Installer' from Microsoft Store\n"
161
+ " - Then run: bm cloud setup\n\n"
162
+ "2. Install chocolatey:\n"
163
+ " - Visit: https://chocolatey.org/install\n"
164
+ " - Then run: bm cloud setup\n\n"
165
+ "3. Install scoop:\n"
166
+ " - Visit: https://scoop.sh\n"
167
+ " - Then run: bm cloud setup\n\n"
168
+ "4. Manual installation:\n"
169
+ " - Download from: https://rclone.org/downloads/\n"
170
+ " - Extract and add to PATH\n"
171
+ )
172
+ raise RcloneInstallError(error_msg)
173
+
174
+
175
+ def install_rclone(platform_override: Optional[str] = None) -> None:
176
+ """Install rclone for the current platform."""
177
+ if is_rclone_installed():
178
+ console.print("[green]rclone is already installed[/green]")
179
+ return
180
+
181
+ platform_name = platform_override or get_platform()
182
+ console.print(f"[blue]Installing rclone for {platform_name}...[/blue]")
183
+
184
+ try:
185
+ if platform_name == "macos":
186
+ install_rclone_macos()
187
+ elif platform_name == "linux":
188
+ install_rclone_linux()
189
+ elif platform_name == "windows":
190
+ install_rclone_windows()
191
+ refresh_windows_path()
192
+ else:
193
+ raise RcloneInstallError(f"Unsupported platform: {platform_name}")
194
+
195
+ # Verify installation
196
+ if not is_rclone_installed():
197
+ raise RcloneInstallError("rclone installation completed but command not found in PATH")
198
+
199
+ console.print("[green]rclone installation completed successfully[/green]")
200
+
201
+ except RcloneInstallError:
202
+ raise
203
+ except Exception as e:
204
+ raise RcloneInstallError(f"Unexpected error during installation: {e}") from e
205
+
206
+
207
+ def refresh_windows_path() -> None:
208
+ """Refresh the Windows PATH environment variable for the current session."""
209
+ if platform.system().lower() != "windows":
210
+ return
211
+
212
+ # Importing here after performing platform detection. Also note that we have to ignore pylance/pyright
213
+ # warnings about winreg attributes so that "errors" don't appear on non-Windows platforms.
214
+ import winreg
215
+
216
+ user_key_path = r"Environment"
217
+ system_key_path = r"System\CurrentControlSet\Control\Session Manager\Environment"
218
+ new_path = ""
219
+
220
+ # Read user PATH
221
+ try:
222
+ reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, user_key_path, 0, winreg.KEY_READ) # type: ignore[reportAttributeAccessIssue]
223
+ user_path, _ = winreg.QueryValueEx(reg_key, "PATH") # type: ignore[reportAttributeAccessIssue]
224
+ winreg.CloseKey(reg_key) # type: ignore[reportAttributeAccessIssue]
225
+ except Exception:
226
+ user_path = ""
227
+
228
+ # Read system PATH
229
+ try:
230
+ reg_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, system_key_path, 0, winreg.KEY_READ) # type: ignore[reportAttributeAccessIssue]
231
+ system_path, _ = winreg.QueryValueEx(reg_key, "PATH") # type: ignore[reportAttributeAccessIssue]
232
+ winreg.CloseKey(reg_key) # type: ignore[reportAttributeAccessIssue]
233
+ except Exception:
234
+ system_path = ""
235
+
236
+ # Merge user and system PATHs (system first, then user)
237
+ if system_path and user_path:
238
+ new_path = system_path + ";" + user_path
239
+ elif system_path:
240
+ new_path = system_path
241
+ elif user_path:
242
+ new_path = user_path
243
+
244
+ if new_path:
245
+ os.environ["PATH"] = new_path
246
+
247
+
248
+ def get_rclone_version() -> Optional[str]:
249
+ """Get the installed rclone version."""
250
+ if not is_rclone_installed():
251
+ return None
252
+
253
+ try:
254
+ result = run_command(["rclone", "version"], check=False)
255
+ if result.returncode == 0:
256
+ # Parse version from output (format: "rclone v1.64.0")
257
+ lines = result.stdout.strip().split("\n")
258
+ for line in lines:
259
+ if line.startswith("rclone v"):
260
+ return line.split()[1]
261
+ return "unknown"
262
+ except Exception:
263
+ return "unknown"
@@ -0,0 +1,240 @@
1
+ """WebDAV upload functionality for basic-memory projects."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from contextlib import AbstractAsyncContextManager
6
+ from typing import Callable
7
+
8
+ import aiofiles
9
+ import httpx
10
+
11
+ from basic_memory.ignore_utils import load_gitignore_patterns, should_ignore_path
12
+ from basic_memory.mcp.async_client import get_client
13
+ from basic_memory.mcp.tools.utils import call_put
14
+
15
+ # Archive file extensions that should be skipped during upload
16
+ ARCHIVE_EXTENSIONS = {".zip", ".tar", ".gz", ".bz2", ".xz", ".7z", ".rar", ".tgz", ".tbz2"}
17
+
18
+
19
+ async def upload_path(
20
+ local_path: Path,
21
+ project_name: str,
22
+ verbose: bool = False,
23
+ use_gitignore: bool = True,
24
+ dry_run: bool = False,
25
+ *,
26
+ client_cm_factory: Callable[[], AbstractAsyncContextManager[httpx.AsyncClient]] | None = None,
27
+ put_func=call_put,
28
+ ) -> bool:
29
+ """
30
+ Upload a file or directory to cloud project via WebDAV.
31
+
32
+ Args:
33
+ local_path: Path to local file or directory
34
+ project_name: Name of cloud project (destination)
35
+ verbose: Show detailed information about filtering and upload
36
+ use_gitignore: If False, skip .gitignore patterns (still use .bmignore)
37
+ dry_run: If True, show what would be uploaded without uploading
38
+
39
+ Returns:
40
+ True if upload succeeded, False otherwise
41
+ """
42
+ try:
43
+ # Resolve path
44
+ local_path = local_path.resolve()
45
+
46
+ # Check if path exists
47
+ if not local_path.exists():
48
+ print(f"Error: Path does not exist: {local_path}")
49
+ return False
50
+
51
+ # Get files to upload
52
+ if local_path.is_file():
53
+ files_to_upload = [(local_path, local_path.name)]
54
+ if verbose:
55
+ print(f"Uploading single file: {local_path.name}")
56
+ else:
57
+ files_to_upload = _get_files_to_upload(local_path, verbose, use_gitignore)
58
+
59
+ if not files_to_upload:
60
+ print("No files found to upload")
61
+ if verbose:
62
+ print(
63
+ "\nTip: Use --verbose to see which files are being filtered, "
64
+ "or --no-gitignore to skip .gitignore patterns"
65
+ )
66
+ return True
67
+
68
+ print(f"Found {len(files_to_upload)} file(s) to upload")
69
+
70
+ # Calculate total size
71
+ total_bytes = sum(file_path.stat().st_size for file_path, _ in files_to_upload)
72
+ skipped_count = 0
73
+
74
+ # If dry run, just show what would be uploaded
75
+ if dry_run:
76
+ print("\nFiles that would be uploaded:")
77
+ for file_path, relative_path in files_to_upload:
78
+ # Skip archive files
79
+ if _is_archive_file(file_path):
80
+ print(f" [SKIP] {relative_path} (archive file)")
81
+ skipped_count += 1
82
+ continue
83
+
84
+ size = file_path.stat().st_size
85
+ if size < 1024:
86
+ size_str = f"{size} bytes"
87
+ elif size < 1024 * 1024:
88
+ size_str = f"{size / 1024:.1f} KB"
89
+ else:
90
+ size_str = f"{size / (1024 * 1024):.1f} MB"
91
+ print(f" {relative_path} ({size_str})")
92
+ else:
93
+ # Upload files using httpx.
94
+ # Allow injection for tests (MockTransport) while keeping production default.
95
+ cm_factory = client_cm_factory or get_client
96
+ async with cm_factory() as client:
97
+ for i, (file_path, relative_path) in enumerate(files_to_upload, 1):
98
+ # Skip archive files (zip, tar, gz, etc.)
99
+ if _is_archive_file(file_path):
100
+ print(
101
+ f"Skipping archive file: {relative_path} ({i}/{len(files_to_upload)})"
102
+ )
103
+ skipped_count += 1
104
+ continue
105
+
106
+ # Build remote path: /webdav/{project_name}/{relative_path}
107
+ remote_path = f"/webdav/{project_name}/{relative_path}"
108
+ print(f"Uploading {relative_path} ({i}/{len(files_to_upload)})")
109
+
110
+ # Get file modification time
111
+ file_stat = file_path.stat()
112
+ mtime = int(file_stat.st_mtime)
113
+
114
+ # Read file content asynchronously
115
+ async with aiofiles.open(file_path, "rb") as f:
116
+ content = await f.read()
117
+
118
+ # Upload via HTTP PUT to WebDAV endpoint with mtime header
119
+ # Using X-OC-Mtime (ownCloud/Nextcloud standard)
120
+ response = await put_func(
121
+ client, remote_path, content=content, headers={"X-OC-Mtime": str(mtime)}
122
+ )
123
+ response.raise_for_status()
124
+
125
+ # Format total size based on magnitude
126
+ if total_bytes < 1024:
127
+ size_str = f"{total_bytes} bytes"
128
+ elif total_bytes < 1024 * 1024:
129
+ size_str = f"{total_bytes / 1024:.1f} KB"
130
+ else:
131
+ size_str = f"{total_bytes / (1024 * 1024):.1f} MB"
132
+
133
+ uploaded_count = len(files_to_upload) - skipped_count
134
+ if dry_run:
135
+ print(f"\nTotal: {uploaded_count} file(s) ({size_str})")
136
+ if skipped_count > 0:
137
+ print(f" Would skip {skipped_count} archive file(s)")
138
+ else:
139
+ print(f"✓ Upload complete: {uploaded_count} file(s) ({size_str})")
140
+ if skipped_count > 0:
141
+ print(f" Skipped {skipped_count} archive file(s)")
142
+
143
+ return True
144
+
145
+ except httpx.HTTPStatusError as e:
146
+ print(f"Upload failed: HTTP {e.response.status_code} - {e.response.text}")
147
+ return False
148
+ except Exception as e:
149
+ print(f"Upload failed: {e}")
150
+ return False
151
+
152
+
153
+ def _is_archive_file(file_path: Path) -> bool:
154
+ """
155
+ Check if a file is an archive file based on its extension.
156
+
157
+ Args:
158
+ file_path: Path to the file to check
159
+
160
+ Returns:
161
+ True if file is an archive, False otherwise
162
+ """
163
+ return file_path.suffix.lower() in ARCHIVE_EXTENSIONS
164
+
165
+
166
+ def _get_files_to_upload(
167
+ directory: Path, verbose: bool = False, use_gitignore: bool = True
168
+ ) -> list[tuple[Path, str]]:
169
+ """
170
+ Get list of files to upload from directory.
171
+
172
+ Uses .bmignore and optionally .gitignore patterns for filtering.
173
+
174
+ Args:
175
+ directory: Directory to scan
176
+ verbose: Show detailed filtering information
177
+ use_gitignore: If False, skip .gitignore patterns (still use .bmignore)
178
+
179
+ Returns:
180
+ List of (absolute_path, relative_path) tuples
181
+ """
182
+ files = []
183
+ ignored_files = []
184
+
185
+ # Load ignore patterns from .bmignore and optionally .gitignore
186
+ ignore_patterns = load_gitignore_patterns(directory, use_gitignore=use_gitignore)
187
+
188
+ if verbose:
189
+ gitignore_path = directory / ".gitignore"
190
+ gitignore_exists = gitignore_path.exists() and use_gitignore
191
+ print(f"\nScanning directory: {directory}")
192
+ print("Using .bmignore: Yes")
193
+ print(f"Using .gitignore: {'Yes' if gitignore_exists else 'No'}")
194
+ print(f"Ignore patterns loaded: {len(ignore_patterns)}")
195
+ if ignore_patterns and len(ignore_patterns) <= 20:
196
+ print(f"Patterns: {', '.join(sorted(ignore_patterns))}")
197
+ print()
198
+
199
+ # Walk through directory
200
+ for root, dirs, filenames in os.walk(directory):
201
+ root_path = Path(root)
202
+
203
+ # Filter directories based on ignore patterns
204
+ filtered_dirs = []
205
+ for d in dirs:
206
+ dir_path = root_path / d
207
+ if should_ignore_path(dir_path, directory, ignore_patterns):
208
+ if verbose:
209
+ rel_path = dir_path.relative_to(directory)
210
+ print(f" [IGNORED DIR] {rel_path}/")
211
+ else:
212
+ filtered_dirs.append(d)
213
+ dirs[:] = filtered_dirs
214
+
215
+ # Process files
216
+ for filename in filenames:
217
+ file_path = root_path / filename
218
+
219
+ # Calculate relative path for display/remote
220
+ rel_path = file_path.relative_to(directory)
221
+ remote_path = str(rel_path).replace("\\", "/")
222
+
223
+ # Check if file should be ignored
224
+ if should_ignore_path(file_path, directory, ignore_patterns):
225
+ ignored_files.append(remote_path)
226
+ if verbose:
227
+ print(f" [IGNORED] {remote_path}")
228
+ continue
229
+
230
+ if verbose:
231
+ print(f" [INCLUDE] {remote_path}")
232
+
233
+ files.append((file_path, remote_path))
234
+
235
+ if verbose:
236
+ print("\nSummary:")
237
+ print(f" Files to upload: {len(files)}")
238
+ print(f" Files ignored: {len(ignored_files)}")
239
+
240
+ return files
@@ -0,0 +1,124 @@
1
+ """Upload CLI commands for basic-memory projects."""
2
+
3
+ import asyncio
4
+ from pathlib import Path
5
+
6
+ import typer
7
+ from rich.console import Console
8
+
9
+ from basic_memory.cli.app import cloud_app
10
+ from basic_memory.cli.commands.cloud.cloud_utils import (
11
+ create_cloud_project,
12
+ project_exists,
13
+ sync_project,
14
+ )
15
+ from basic_memory.cli.commands.cloud.upload import upload_path
16
+
17
+ console = Console()
18
+
19
+
20
+ @cloud_app.command("upload")
21
+ def upload(
22
+ path: Path = typer.Argument(
23
+ ...,
24
+ help="Path to local file or directory to upload",
25
+ exists=True,
26
+ readable=True,
27
+ resolve_path=True,
28
+ ),
29
+ project: str = typer.Option(
30
+ ...,
31
+ "--project",
32
+ "-p",
33
+ help="Cloud project name (destination)",
34
+ ),
35
+ create_project: bool = typer.Option(
36
+ False,
37
+ "--create-project",
38
+ "-c",
39
+ help="Create project if it doesn't exist",
40
+ ),
41
+ sync: bool = typer.Option(
42
+ True,
43
+ "--sync/--no-sync",
44
+ help="Sync project after upload (default: true)",
45
+ ),
46
+ verbose: bool = typer.Option(
47
+ False,
48
+ "--verbose",
49
+ "-v",
50
+ help="Show detailed information about file filtering and upload",
51
+ ),
52
+ no_gitignore: bool = typer.Option(
53
+ False,
54
+ "--no-gitignore",
55
+ help="Skip .gitignore patterns (still respects .bmignore)",
56
+ ),
57
+ dry_run: bool = typer.Option(
58
+ False,
59
+ "--dry-run",
60
+ help="Show what would be uploaded without actually uploading",
61
+ ),
62
+ ) -> None:
63
+ """Upload local files or directories to cloud project via WebDAV.
64
+
65
+ Examples:
66
+ bm cloud upload ~/my-notes --project research
67
+ bm cloud upload notes.md --project research --create-project
68
+ bm cloud upload ~/docs --project work --no-sync
69
+ bm cloud upload ./history --project proto --verbose
70
+ bm cloud upload ./notes --project work --no-gitignore
71
+ bm cloud upload ./files --project test --dry-run
72
+ """
73
+
74
+ async def _upload():
75
+ # Check if project exists
76
+ if not await project_exists(project):
77
+ if create_project:
78
+ console.print(f"[blue]Creating cloud project '{project}'...[/blue]")
79
+ try:
80
+ await create_cloud_project(project)
81
+ console.print(f"[green]Created project '{project}'[/green]")
82
+ except Exception as e:
83
+ console.print(f"[red]Failed to create project: {e}[/red]")
84
+ raise typer.Exit(1)
85
+ else:
86
+ console.print(
87
+ f"[red]Project '{project}' does not exist.[/red]\n"
88
+ f"[yellow]Options:[/yellow]\n"
89
+ f" 1. Create it first: bm project add {project}\n"
90
+ f" 2. Use --create-project flag to create automatically"
91
+ )
92
+ raise typer.Exit(1)
93
+
94
+ # Perform upload (or dry run)
95
+ if dry_run:
96
+ console.print(
97
+ f"[yellow]DRY RUN: Showing what would be uploaded to '{project}'[/yellow]"
98
+ )
99
+ else:
100
+ console.print(f"[blue]Uploading {path} to project '{project}'...[/blue]")
101
+
102
+ success = await upload_path(
103
+ path, project, verbose=verbose, use_gitignore=not no_gitignore, dry_run=dry_run
104
+ )
105
+ if not success:
106
+ console.print("[red]Upload failed[/red]")
107
+ raise typer.Exit(1)
108
+
109
+ if dry_run:
110
+ console.print("[yellow]DRY RUN complete - no files were uploaded[/yellow]")
111
+ else:
112
+ console.print(f"[green]Successfully uploaded to '{project}'[/green]")
113
+
114
+ # Sync project if requested (skip on dry run)
115
+ # Force full scan after bisync to ensure database is up-to-date with synced files
116
+ if sync and not dry_run:
117
+ console.print(f"[blue]Syncing project '{project}'...[/blue]")
118
+ try:
119
+ await sync_project(project, force_full=True)
120
+ except Exception as e:
121
+ console.print(f"[yellow]Warning: Sync failed: {e}[/yellow]")
122
+ console.print("[dim]Files uploaded but may not be indexed yet[/dim]")
123
+
124
+ asyncio.run(_upload())