-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathlib.rs
More file actions
1428 lines (1320 loc) · 49.7 KB
/
lib.rs
File metadata and controls
1428 lines (1320 loc) · 49.7 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(dead_code)]
#[cfg(test)]
mod tests;
use chrono::{SecondsFormat, Utc};
use parking_lot::Mutex;
use rusqlite::{params, Connection, OptionalExtension};
use std::{
env, fs,
path::{Path, PathBuf},
sync::Arc,
};
use thiserror::Error;
// Events module (enabled with "search" feature)
#[cfg(feature = "search")]
pub mod events;
// Search module (enabled with "search" feature)
#[cfg(feature = "search")]
pub mod search;
#[cfg(feature = "search")]
use events::{DocEvent, FolderEvent, SharedEventBus};
#[derive(Debug, Error)]
pub enum CoreError {
#[error("{0}")]
Message(String),
#[error("database error: {0}")]
Db(#[from] rusqlite::Error),
#[error("io error: {0}")]
Io(#[from] std::io::Error),
}
pub type CoreResult<T> = Result<T, CoreError>;
#[derive(Clone)]
pub struct OpenContext {
contexts_root: PathBuf,
db_path: PathBuf,
conn: Arc<Mutex<Connection>>,
#[cfg(feature = "search")]
event_bus: Option<SharedEventBus>,
}
#[derive(Debug, Clone, Default)]
pub struct EnvOverrides {
pub base_root: Option<PathBuf>,
pub contexts_root: Option<PathBuf>,
pub db_path: Option<PathBuf>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct EnvInfo {
pub contexts_root: PathBuf,
pub db_path: PathBuf,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct Folder {
pub id: i64,
pub parent_id: Option<i64>,
pub name: String,
pub rel_path: String,
pub abs_path: PathBuf,
pub description: String,
pub created_at: String,
pub updated_at: String,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct Doc {
pub id: i64,
pub folder_id: i64,
pub name: String,
pub rel_path: String,
pub abs_path: PathBuf,
pub description: String,
pub stable_id: String,
pub created_at: String,
pub updated_at: String,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct DocManifestEntry {
pub doc_name: String,
pub rel_path: String,
pub abs_path: PathBuf,
pub stable_id: String,
pub description: String,
pub updated_at: String,
}
/// Manifest response that also surfaces filesystem files which are NOT
/// registered in SQLite (i.e. created via `Write`/`Edit` bypassing the API).
/// `unindexed_files` is the list of relative paths (under the requested
/// folder) of `*.md` files that exist on disk but have no `docs` row.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ManifestResult {
pub items: Vec<DocManifestEntry>,
pub unindexed_files: Vec<String>,
}
impl OpenContext {
pub fn initialize(overrides: EnvOverrides) -> CoreResult<Self> {
let base_root = overrides
.base_root
.or_else(|| env_path("OPENCONTEXT_ROOT"))
.or_else(default_base_root)
.ok_or_else(|| CoreError::Message("Unable to resolve user home directory".into()))?;
let contexts_root = overrides
.contexts_root
.or_else(|| env_path("OPENCONTEXT_CONTEXTS_ROOT"))
.unwrap_or_else(|| base_root.join("contexts"));
let db_path = overrides
.db_path
.or_else(|| env_path("OPENCONTEXT_DB_PATH"))
.unwrap_or_else(|| base_root.join("opencontext.db"));
fs::create_dir_all(&contexts_root)?;
if let Some(parent) = db_path.parent() {
fs::create_dir_all(parent)?;
}
let conn = Connection::open(&db_path)?;
conn.pragma_update(None, "foreign_keys", "ON")?;
conn.execute_batch(
"
CREATE TABLE IF NOT EXISTS folders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
parent_id INTEGER REFERENCES folders(id) ON DELETE CASCADE,
name TEXT NOT NULL,
rel_path TEXT NOT NULL UNIQUE,
abs_path TEXT NOT NULL,
description TEXT DEFAULT '',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS docs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
folder_id INTEGER NOT NULL REFERENCES folders(id) ON DELETE CASCADE,
name TEXT NOT NULL,
rel_path TEXT NOT NULL UNIQUE,
abs_path TEXT NOT NULL,
description TEXT DEFAULT '',
stable_id TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
",
)?;
ensure_schema_migrations(&conn)?;
Ok(Self {
contexts_root,
db_path,
conn: Arc::new(Mutex::new(conn)),
#[cfg(feature = "search")]
event_bus: None,
})
}
/// Set the event bus for this context
#[cfg(feature = "search")]
pub fn with_event_bus(mut self, event_bus: SharedEventBus) -> Self {
self.event_bus = Some(event_bus);
self
}
/// Get the event bus
#[cfg(feature = "search")]
pub fn event_bus(&self) -> Option<&SharedEventBus> {
self.event_bus.as_ref()
}
/// Emit a document event
#[cfg(feature = "search")]
fn emit_doc_event(&self, event: DocEvent) {
if let Some(ref bus) = self.event_bus {
bus.emit_doc(event);
}
}
/// Emit a folder event
#[cfg(feature = "search")]
fn emit_folder_event(&self, event: FolderEvent) {
if let Some(ref bus) = self.event_bus {
bus.emit_folder(event);
}
}
pub fn get_doc_by_stable_id(&self, stable_id: &str) -> CoreResult<Doc> {
let cleaned = stable_id.trim();
if cleaned.is_empty() {
return Err(CoreError::Message("stable_id is required.".into()));
}
self.with_conn(|conn| {
let mut stmt = conn.prepare(
"SELECT id, folder_id, name, rel_path, abs_path, description, stable_id, created_at, updated_at
FROM docs WHERE stable_id = ?1",
)?;
let doc = stmt
.query_row([cleaned], row_to_doc)
.optional()?
.ok_or_else(|| CoreError::Message(format!("Document with stable_id \"{cleaned}\" not found.")))?;
Ok(doc)
})
}
pub fn get_doc_meta(&self, doc_path: &str) -> CoreResult<Doc> {
let rel_doc_path = normalize_doc_path(Some(doc_path))?;
let mut doc = self
.find_doc(&rel_doc_path)?
.ok_or_else(|| doc_not_found(&rel_doc_path))?;
// If edited outside OpenContext, sync updated_at from filesystem mtime.
if let Ok(updated) = sync_updated_at_from_fs(&doc) {
if updated != doc.updated_at {
let ts = updated.clone();
self.with_conn(|conn| {
conn.execute(
"UPDATE docs SET updated_at = ?1 WHERE id = ?2",
params![ts, doc.id],
)?;
Ok(())
})?;
doc.updated_at = updated;
}
}
Ok(doc)
}
pub fn env_info(&self) -> EnvInfo {
EnvInfo {
contexts_root: self.contexts_root.clone(),
db_path: self.db_path.clone(),
}
}
pub fn list_folders(&self, all: bool) -> CoreResult<Vec<Folder>> {
self.with_conn(|conn| {
let query = if all {
"SELECT id, parent_id, name, rel_path, abs_path, description, created_at, updated_at FROM folders ORDER BY rel_path"
} else {
"SELECT id, parent_id, name, rel_path, abs_path, description, created_at, updated_at FROM folders WHERE parent_id IS NULL ORDER BY name"
};
let mut stmt = conn.prepare(query)?;
let rows = stmt
.query_map([], row_to_folder)?
.collect::<Result<Vec<_>, _>>()?;
Ok(rows)
})
}
pub fn create_folder(
&self,
path: &str,
description: Option<&str>,
) -> CoreResult<FolderSummary> {
let rel_path = normalize_folder_path(Some(path))?;
if rel_path.is_empty() {
return Err(CoreError::Message(
"Cannot create root folder. Provide a sub-path like \"project-a\".".into(),
));
}
let parent_path = parent_rel_path(&rel_path);
if let Some(parent) = parent_path.as_deref() {
self.ensure_folder_record(parent)?;
}
let parent_for_compare = parent_path.clone().unwrap_or_default();
if rel_path != parent_for_compare && self.find_folder(&rel_path)?.is_some() {
self.update_folder_description(&rel_path, description.unwrap_or(""))?;
return Ok(FolderSummary {
rel_path: rel_path.clone(),
abs_path: self.contexts_root.join(&rel_path),
description: description.unwrap_or("").to_string(),
});
}
let ts = now_iso();
let name = rel_path
.split('/')
.next_back()
.unwrap_or(&rel_path)
.to_string();
let abs_path = self.contexts_root.join(&rel_path);
fs::create_dir_all(&abs_path)?;
self.with_conn(|conn| {
conn.execute(
"INSERT INTO folders (parent_id, name, rel_path, abs_path, description, created_at, updated_at) VALUES (
(SELECT id FROM folders WHERE rel_path = ?1),
?2, ?3, ?4, ?5, ?6, ?6
)",
params![
parent_path,
name,
rel_path,
abs_path.to_string_lossy(),
description.unwrap_or(""),
ts
],
)?;
Ok(())
})?;
Ok(FolderSummary {
rel_path,
abs_path,
description: description.unwrap_or("").to_string(),
})
}
pub fn rename_folder(&self, path: &str, new_name: &str) -> CoreResult<RenameResult> {
let rel_path = normalize_folder_path(Some(path))?;
if rel_path.is_empty() {
return Err(CoreError::Message(
"Cannot rename the root contexts directory.".into(),
));
}
if new_name.is_empty() || new_name.contains('/') {
return Err(CoreError::Message(
"New name must be a single path segment.".into(),
));
}
let folder = self
.find_folder(&rel_path)?
.ok_or_else(|| folder_not_found(&rel_path))?;
let parent_path = parent_rel_path(&rel_path);
let new_rel_path = if let Some(parent) = parent_path.as_deref() {
if parent.is_empty() {
new_name.to_string()
} else {
format!("{parent}/{new_name}")
}
} else {
new_name.to_string()
};
if self.find_folder(&new_rel_path)?.is_some() {
return Err(CoreError::Message(format!(
"Target folder \"{new_rel_path}\" already exists."
)));
}
let new_abs_path = self.contexts_root.join(&new_rel_path);
if let Some(parent) = new_abs_path.parent() {
fs::create_dir_all(parent)?;
}
fs::rename(&folder.abs_path, &new_abs_path)?;
let ts = now_iso();
// Collect affected doc paths before the transaction (for event emission)
#[cfg(feature = "search")]
let affected_doc_paths: Vec<String> = self.with_conn(|conn| {
let like_pattern = format!("{}/%", folder.rel_path);
let mut stmt = conn.prepare("SELECT rel_path FROM docs WHERE rel_path LIKE ?1")?;
let paths = stmt
.query_map([like_pattern], |row| row.get::<_, String>(0))?
.collect::<Result<Vec<_>, _>>()?;
Ok(paths)
})?;
self.with_conn(|conn| {
let tx = conn.unchecked_transaction()?;
{
tx.execute(
"UPDATE folders SET name = ?1, rel_path = ?2, abs_path = ?3, updated_at = ?4 WHERE id = ?5",
params![new_name, new_rel_path, new_abs_path.to_string_lossy(), ts, folder.id],
)?;
let like_pattern = format!("{}/%", folder.rel_path);
let mut stmt = tx.prepare("SELECT id, rel_path FROM folders WHERE rel_path LIKE ?1")?;
let folder_rows = stmt
.query_map([like_pattern.clone()], |row| {
Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
})?
.collect::<Result<Vec<_>, _>>()?;
for (id, child_rel) in folder_rows {
let suffix = &child_rel[folder.rel_path.len() + 1..];
let updated_rel = format!("{new_rel_path}/{suffix}");
let updated_abs = self.contexts_root.join(&updated_rel);
tx.execute(
"UPDATE folders SET rel_path = ?1, abs_path = ?2, updated_at = ?3 WHERE id = ?4",
params![updated_rel, updated_abs.to_string_lossy(), ts, id],
)?;
}
let mut doc_stmt =
tx.prepare("SELECT id, rel_path FROM docs WHERE rel_path LIKE ?1")?;
let doc_rows = doc_stmt
.query_map([like_pattern], |row| {
Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
})?
.collect::<Result<Vec<_>, _>>()?;
for (id, doc_rel) in doc_rows {
let suffix = &doc_rel[folder.rel_path.len() + 1..];
let updated_rel = format!("{new_rel_path}/{suffix}");
let updated_abs = self.contexts_root.join(&updated_rel);
tx.execute(
"UPDATE docs SET rel_path = ?1, abs_path = ?2, updated_at = ?3 WHERE id = ?4",
params![updated_rel, updated_abs.to_string_lossy(), ts, id],
)?;
}
}
tx.commit()?;
Ok(())
})?;
// Emit folder event with affected docs
#[cfg(feature = "search")]
{
let affected_docs: Vec<(String, String)> = affected_doc_paths
.into_iter()
.map(|old_path| {
let suffix = &old_path[folder.rel_path.len() + 1..];
let new_path = format!("{}/{}", new_rel_path, suffix);
(old_path, new_path)
})
.collect();
self.emit_folder_event(FolderEvent::Renamed {
old_path: rel_path.clone(),
new_path: new_rel_path.clone(),
affected_docs,
});
}
Ok(RenameResult {
old_path: rel_path,
new_path: new_rel_path,
})
}
pub fn move_folder(&self, path: &str, dest_folder_path: &str) -> CoreResult<RenameResult> {
let rel_path = normalize_folder_path(Some(path))?;
if rel_path.is_empty() {
return Err(CoreError::Message(
"Cannot move the root contexts directory.".into(),
));
}
let dest_rel_folder = normalize_folder_path(Some(dest_folder_path))?;
if dest_rel_folder.is_empty() {
return Err(CoreError::Message(
"Root is not supported. Please move into a folder under contexts/.".into(),
));
}
if dest_rel_folder == rel_path || dest_rel_folder.starts_with(&format!("{rel_path}/")) {
return Err(CoreError::Message(
"Cannot move a folder into itself or its descendants.".into(),
));
}
let folder = self
.find_folder(&rel_path)?
.ok_or_else(|| folder_not_found(&rel_path))?;
let dest_folder = self
.find_folder(&dest_rel_folder)?
.ok_or_else(|| folder_not_found(&dest_rel_folder))?;
let new_rel_path = if dest_folder.rel_path.is_empty() {
folder.name.clone()
} else {
format!("{}/{}", dest_folder.rel_path, folder.name)
};
if self.find_folder(&new_rel_path)?.is_some() {
return Err(CoreError::Message(format!(
"Target folder \"{new_rel_path}\" already exists."
)));
}
let new_abs_path = self.contexts_root.join(&new_rel_path);
if let Some(parent) = new_abs_path.parent() {
fs::create_dir_all(parent)?;
}
fs::rename(&folder.abs_path, &new_abs_path)?;
let ts = now_iso();
// Collect affected doc paths before the transaction (for event emission)
#[cfg(feature = "search")]
let affected_doc_paths: Vec<String> = self.with_conn(|conn| {
let like_pattern = format!("{}/%", folder.rel_path);
let mut stmt = conn.prepare("SELECT rel_path FROM docs WHERE rel_path LIKE ?1")?;
let paths = stmt
.query_map([like_pattern], |row| row.get::<_, String>(0))?
.collect::<Result<Vec<_>, _>>()?;
Ok(paths)
})?;
self.with_conn(|conn| {
let tx = conn.unchecked_transaction()?;
{
tx.execute(
"UPDATE folders SET parent_id = ?1, rel_path = ?2, abs_path = ?3, updated_at = ?4 WHERE id = ?5",
params![
dest_folder.id,
new_rel_path,
new_abs_path.to_string_lossy(),
ts,
folder.id
],
)?;
let like_pattern = format!("{}/%", folder.rel_path);
let mut stmt = tx.prepare("SELECT id, rel_path FROM folders WHERE rel_path LIKE ?1")?;
let folder_rows = stmt
.query_map([like_pattern.clone()], |row| {
Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
})?
.collect::<Result<Vec<_>, _>>()?;
for (id, child_rel) in folder_rows {
let suffix = &child_rel[folder.rel_path.len() + 1..];
let updated_rel = format!("{new_rel_path}/{suffix}");
let updated_abs = self.contexts_root.join(&updated_rel);
tx.execute(
"UPDATE folders SET rel_path = ?1, abs_path = ?2, updated_at = ?3 WHERE id = ?4",
params![updated_rel, updated_abs.to_string_lossy(), ts, id],
)?;
}
let mut doc_stmt =
tx.prepare("SELECT id, rel_path FROM docs WHERE rel_path LIKE ?1")?;
let doc_rows = doc_stmt
.query_map([like_pattern], |row| {
Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
})?
.collect::<Result<Vec<_>, _>>()?;
for (id, doc_rel) in doc_rows {
let suffix = &doc_rel[folder.rel_path.len() + 1..];
let updated_rel = format!("{new_rel_path}/{suffix}");
let updated_abs = self.contexts_root.join(&updated_rel);
tx.execute(
"UPDATE docs SET rel_path = ?1, abs_path = ?2, updated_at = ?3 WHERE id = ?4",
params![updated_rel, updated_abs.to_string_lossy(), ts, id],
)?;
}
}
tx.commit()?;
Ok(())
})?;
// Emit folder event with affected docs
#[cfg(feature = "search")]
{
let affected_docs: Vec<(String, String)> = affected_doc_paths
.into_iter()
.map(|old_path| {
let suffix = &old_path[folder.rel_path.len() + 1..];
let new_path = format!("{}/{}", new_rel_path, suffix);
(old_path, new_path)
})
.collect();
self.emit_folder_event(FolderEvent::Moved {
old_path: rel_path.clone(),
new_path: new_rel_path.clone(),
affected_docs,
});
}
Ok(RenameResult {
old_path: rel_path,
new_path: new_rel_path,
})
}
pub fn remove_folder(&self, path: &str, force: bool) -> CoreResult<Removed> {
let rel_path = normalize_folder_path(Some(path))?;
if rel_path.is_empty() {
return Err(CoreError::Message(
"Cannot remove the root contexts directory.".into(),
));
}
let folder = self
.find_folder(&rel_path)?
.ok_or_else(|| folder_not_found(&rel_path))?;
// Collect documents to be removed (for event emission)
#[cfg(feature = "search")]
let removed_docs: Vec<String> = self.with_conn(|conn| {
let like_pattern = format!("{}/%", rel_path);
let mut stmt =
conn.prepare("SELECT rel_path FROM docs WHERE rel_path LIKE ?1 OR folder_id = ?2")?;
let paths = stmt
.query_map(params![like_pattern, folder.id], |row| {
row.get::<_, String>(0)
})?
.collect::<Result<Vec<_>, _>>()?;
Ok(paths)
})?;
self.with_conn(|conn| {
let child_count: i64 = conn.query_row(
"SELECT COUNT(1) FROM folders WHERE parent_id = ?1",
params![folder.id],
|row| row.get(0),
)?;
let doc_count: i64 = conn.query_row(
"SELECT COUNT(1) FROM docs WHERE folder_id = ?1",
params![folder.id],
|row| row.get(0),
)?;
if !force && (child_count > 0 || doc_count > 0) {
return Err(CoreError::Message(format!(
"Folder \"{rel_path}\" is not empty. Use --force to delete recursively."
)));
}
let like_pattern = format!("{rel_path}/%");
let tx = conn.unchecked_transaction()?;
tx.execute(
"DELETE FROM docs WHERE rel_path LIKE ?1",
params![like_pattern.clone()],
)?;
tx.execute(
"DELETE FROM folders WHERE rel_path LIKE ?1",
params![like_pattern.clone()],
)?;
tx.execute("DELETE FROM docs WHERE folder_id = ?1", params![folder.id])?;
tx.execute("DELETE FROM folders WHERE id = ?1", params![folder.id])?;
tx.commit()?;
Ok(())
})?;
if folder.abs_path.exists() {
if force {
fs::remove_dir_all(&folder.abs_path)?;
} else {
fs::remove_dir(&folder.abs_path)?;
}
}
// Emit folder deleted event
#[cfg(feature = "search")]
self.emit_folder_event(FolderEvent::Deleted {
rel_path: rel_path.clone(),
removed_docs,
});
Ok(Removed { rel_path })
}
pub fn list_docs(&self, folder_path: &str, recursive: bool) -> CoreResult<Vec<Doc>> {
let rel_folder_path = normalize_folder_path(Some(folder_path))?;
let folder = self
.find_folder(&rel_folder_path)?
.ok_or_else(|| folder_not_found(&rel_folder_path))?;
self.with_conn(|conn| {
if recursive {
let pattern = if folder.rel_path.is_empty() {
"%".to_string()
} else {
format!("{}/%", folder.rel_path)
};
let mut stmt = conn.prepare(
"SELECT id, folder_id, name, rel_path, abs_path, description, stable_id, created_at, updated_at
FROM docs WHERE rel_path LIKE ?1 ORDER BY rel_path",
)?;
let rows = stmt
.query_map([pattern], row_to_doc)?
.collect::<Result<Vec<_>, _>>()?;
Ok(rows)
} else if rel_folder_path.is_empty() {
let mut stmt = conn.prepare(
"SELECT id, folder_id, name, rel_path, abs_path, description, stable_id, created_at, updated_at
FROM docs WHERE folder_id IS NULL ORDER BY name",
)?;
let rows = stmt
.query_map([], row_to_doc)?
.collect::<Result<Vec<_>, _>>()?;
Ok(rows)
} else {
let mut stmt = conn.prepare(
"SELECT id, folder_id, name, rel_path, abs_path, description, stable_id, created_at, updated_at
FROM docs WHERE folder_id = ?1 ORDER BY name",
)?;
let rows = stmt
.query_map([folder.id], row_to_doc)?
.collect::<Result<Vec<_>, _>>()?;
Ok(rows)
}
})
}
pub fn create_doc(
&self,
folder_path: &str,
name: &str,
description: Option<&str>,
) -> CoreResult<DocCreated> {
if name.is_empty() {
return Err(CoreError::Message("Document name is required.".into()));
}
if name.contains('/') {
return Err(CoreError::Message(
"Document name must not contain \"/\".".into(),
));
}
let rel_folder_path = normalize_folder_path(Some(folder_path))?;
let folder = self
.find_folder(&rel_folder_path)?
.ok_or_else(|| folder_not_found(&rel_folder_path))?;
let rel_path = if folder.rel_path.is_empty() {
name.to_string()
} else {
format!("{}/{}", folder.rel_path, name)
};
if self.find_doc(&rel_path)?.is_some() {
return Err(CoreError::Message(format!(
"File \"{rel_path}\" already exists."
)));
}
let abs_path = self.contexts_root.join(&rel_path);
if let Some(parent) = abs_path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&abs_path, "")?;
let ts = now_iso();
let stable_id = self.with_conn(|conn| {
let sid = generate_stable_id(conn)?;
conn.execute(
"INSERT INTO docs (folder_id, name, rel_path, abs_path, description, stable_id, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7)",
params![
folder.id,
name,
rel_path,
abs_path.to_string_lossy(),
description.unwrap_or(""),
sid,
ts
],
)?;
Ok(sid)
})?;
// Emit event
#[cfg(feature = "search")]
self.emit_doc_event(DocEvent::Created {
rel_path: rel_path.clone(),
});
Ok(DocCreated {
rel_path,
abs_path,
description: description.unwrap_or("").to_string(),
stable_id,
})
}
pub fn move_doc(&self, doc_path: &str, dest_folder_path: &str) -> CoreResult<RenameResult> {
let rel_doc_path = normalize_doc_path(Some(doc_path))?;
let doc = self
.find_doc(&rel_doc_path)?
.ok_or_else(|| doc_not_found(&rel_doc_path))?;
let dest_rel_folder = normalize_folder_path(Some(dest_folder_path))?;
let dest_folder = self
.find_folder(&dest_rel_folder)?
.ok_or_else(|| folder_not_found(&dest_rel_folder))?;
let new_rel_path = if dest_folder.rel_path.is_empty() {
doc.name.clone()
} else {
format!("{}/{}", dest_folder.rel_path, doc.name)
};
if self.find_doc(&new_rel_path)?.is_some() {
return Err(CoreError::Message(format!(
"Document \"{new_rel_path}\" already exists."
)));
}
let new_abs_path = self.contexts_root.join(&new_rel_path);
if let Some(parent) = new_abs_path.parent() {
fs::create_dir_all(parent)?;
}
fs::rename(&doc.abs_path, &new_abs_path)?;
let ts = now_iso();
self.with_conn(|conn| {
conn.execute(
"UPDATE docs SET folder_id = ?1, rel_path = ?2, abs_path = ?3, updated_at = ?4 WHERE id = ?5",
params![
dest_folder.id,
new_rel_path,
new_abs_path.to_string_lossy(),
ts,
doc.id
],
)?;
Ok(())
})?;
// Emit event
#[cfg(feature = "search")]
self.emit_doc_event(DocEvent::Moved {
old_path: rel_doc_path.clone(),
new_path: new_rel_path.clone(),
});
Ok(RenameResult {
old_path: rel_doc_path,
new_path: new_rel_path,
})
}
pub fn rename_doc(&self, doc_path: &str, new_name: &str) -> CoreResult<RenameResult> {
if new_name.is_empty() || new_name.contains('/') {
return Err(CoreError::Message(
"New name must be a single file name without \"/\".".into(),
));
}
let rel_doc_path = normalize_doc_path(Some(doc_path))?;
let doc = self
.find_doc(&rel_doc_path)?
.ok_or_else(|| doc_not_found(&rel_doc_path))?;
let folder_rel = parent_rel_path(&doc.rel_path);
let new_rel_path = folder_rel
.and_then(|p| if p.is_empty() { None } else { Some(p) })
.map(|prefix| format!("{prefix}/{new_name}"))
.unwrap_or_else(|| new_name.to_string());
if self.find_doc(&new_rel_path)?.is_some() {
return Err(CoreError::Message(format!(
"Document \"{new_rel_path}\" already exists."
)));
}
let new_abs_path = self.contexts_root.join(&new_rel_path);
if let Some(parent) = new_abs_path.parent() {
fs::create_dir_all(parent)?;
}
fs::rename(&doc.abs_path, &new_abs_path)?;
let ts = now_iso();
self.with_conn(|conn| {
conn.execute(
"UPDATE docs SET name = ?1, rel_path = ?2, abs_path = ?3, updated_at = ?4 WHERE id = ?5",
params![new_name, new_rel_path, new_abs_path.to_string_lossy(), ts, doc.id],
)?;
Ok(())
})?;
// Emit event
#[cfg(feature = "search")]
self.emit_doc_event(DocEvent::Renamed {
old_path: rel_doc_path.clone(),
new_path: new_rel_path.clone(),
});
Ok(RenameResult {
old_path: rel_doc_path,
new_path: new_rel_path,
})
}
pub fn remove_doc(&self, doc_path: &str) -> CoreResult<Removed> {
let rel_doc_path = normalize_doc_path(Some(doc_path))?;
let doc = self
.find_doc(&rel_doc_path)?
.ok_or_else(|| doc_not_found(&rel_doc_path))?;
if doc.abs_path.exists() {
fs::remove_file(&doc.abs_path)?;
}
self.with_conn(|conn| {
conn.execute("DELETE FROM docs WHERE id = ?1", params![doc.id])?;
Ok(())
})?;
// Emit event
#[cfg(feature = "search")]
self.emit_doc_event(DocEvent::Deleted {
rel_path: rel_doc_path.clone(),
});
Ok(Removed {
rel_path: rel_doc_path,
})
}
pub fn set_doc_description(&self, doc_path: &str, description: &str) -> CoreResult<DocSummary> {
let rel_doc_path = normalize_doc_path(Some(doc_path))?;
let doc = self
.find_doc(&rel_doc_path)?
.ok_or_else(|| doc_not_found(&rel_doc_path))?;
let ts = now_iso();
self.with_conn(|conn| {
conn.execute(
"UPDATE docs SET description = ?1, updated_at = ?2 WHERE id = ?3",
params![description, ts, doc.id],
)?;
Ok(())
})?;
Ok(DocSummary {
rel_path: rel_doc_path,
description: description.to_string(),
})
}
pub fn get_doc_content(&self, doc_path: &str) -> CoreResult<String> {
let rel_doc_path = normalize_doc_path(Some(doc_path))?;
let doc = self
.find_doc(&rel_doc_path)?
.ok_or_else(|| doc_not_found(&rel_doc_path))?;
// Best-effort: sync updated_at from filesystem mtime when reading.
if let Ok(updated) = sync_updated_at_from_fs(&doc) {
if updated != doc.updated_at {
let ts = updated;
self.with_conn(|conn| {
conn.execute(
"UPDATE docs SET updated_at = ?1 WHERE id = ?2",
params![ts, doc.id],
)?;
Ok(())
})?;
}
}
let content = fs::read_to_string(&doc.abs_path)?;
Ok(content)
}
pub fn save_doc_content(
&self,
doc_path: &str,
content: &str,
description: Option<&str>,
) -> CoreResult<DocSaved> {
let rel_doc_path = normalize_doc_path(Some(doc_path))?;
let doc = self
.find_doc(&rel_doc_path)?
.ok_or_else(|| doc_not_found(&rel_doc_path))?;
fs::write(&doc.abs_path, content)?;
let ts = now_iso();
self.with_conn(|conn| {
if let Some(desc) = description {
conn.execute(
"UPDATE docs SET description = ?1, updated_at = ?2 WHERE id = ?3",
params![desc, ts, doc.id],
)?;
} else {
conn.execute(
"UPDATE docs SET updated_at = ?1 WHERE id = ?2",
params![ts, doc.id],
)?;
}
Ok(())
})?;
// Emit event
#[cfg(feature = "search")]
self.emit_doc_event(DocEvent::Updated {
rel_path: rel_doc_path.clone(),
});
Ok(DocSaved {
rel_path: rel_doc_path,
abs_path: doc.abs_path,
})
}
pub fn generate_manifest(
&self,
folder_path: &str,
limit: Option<usize>,
) -> CoreResult<Vec<DocManifestEntry>> {
if let Some(l) = limit {
if l == 0 {
return Err(CoreError::Message(
"limit must be a positive integer".into(),
));
}
}
let rel_path = normalize_folder_path(Some(folder_path))?;
let folder = self
.find_folder(&rel_path)?
.ok_or_else(|| folder_not_found(&rel_path))?;
self.with_conn(|conn| {
let sql = if limit.is_some() {
"SELECT name, rel_path, abs_path, stable_id, description, updated_at FROM docs WHERE rel_path LIKE ?1 ORDER BY rel_path LIMIT ?2"
} else {
"SELECT name, rel_path, abs_path, stable_id, description, updated_at FROM docs WHERE rel_path LIKE ?1 ORDER BY rel_path"
};
let pattern = if folder.rel_path.is_empty() {
"%".to_string()
} else {
format!("{}/%", folder.rel_path)
};
let mut stmt = conn.prepare(sql)?;
if let Some(limit) = limit {
let rows = stmt
.query_map(params![pattern, limit as i64], manifest_row)?
.collect::<Result<Vec<_>, _>>()?;
Ok(rows)
} else {
let rows = stmt
.query_map([pattern], manifest_row)?
.collect::<Result<Vec<_>, _>>()?;
Ok(rows)
}
})
}
/// Like `generate_manifest`, but also scans the filesystem and returns
/// any `*.md` files that exist on disk under the folder but are NOT
/// registered in the `docs` table. Manifest itself remains read-only —
/// nothing is inserted; the caller is expected to surface a warning
/// and (optionally) invoke `reconcile_folder` to fix the drift.
pub fn generate_manifest_full(
&self,
folder_path: &str,
limit: Option<usize>,
) -> CoreResult<ManifestResult> {
let items = self.generate_manifest(folder_path, limit)?;
let rel_path = normalize_folder_path(Some(folder_path))?;