-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
3039 lines (2678 loc) · 103 KB
/
Copy pathmain.js
File metadata and controls
3039 lines (2678 loc) · 103 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
const {
Plugin,
PluginSettingTab,
Setting,
TFile,
TFolder,
normalizePath,
Notice,
Command,
Modal
} = require("obsidian");
const DEFAULT_SETTINGS = {
properties: [],
autoAppendSuffix: true,
ignoreFolders: [],
moveOnCreate: true,
moveOnMetadataChange: true,
moveOnStartup: true,
automaticTriggers: true,
debugLogging: false,
processExistingFiles: false,
processingDelay: 150,
maxFilesPerBatch: 0,
caseInsensitiveMatching: false,
autoCreateFolders: true,
showRibbonIcon: true,
undoCheckpoints: [],
undoMaxCheckpoints: 10,
undoAutoCooldownMs: 2000,
notificationMode: "onMove"
};
/**
* FileProcessor handles the logic of moving files based on property rules
*/
class FileProcessor {
constructor(app, settings, logger) {
this.app = app;
this.settings = settings;
this.logger = logger;
}
/**
* Determines the target folder for a file based on property mappings
* @returns {{targetFolder: string, ruleName: string, ruleValue: string}|null}
*/
findTargetFolder(frontmatter) {
const groups = Array.isArray(this.settings.properties) ? this.settings.properties : [];
for (const group of groups) {
const propName = String(group.name || "").trim();
if (!propName) continue;
const rawValue = frontmatter[propName];
if (rawValue === null || rawValue === undefined) continue;
const values = Array.isArray(rawValue) ? rawValue : [rawValue];
const normalizedValues = values
.map((value) => String(value).trim())
.filter((value) => value.length > 0);
if (normalizedValues.length === 0) continue;
const mappings = Array.isArray(group.mappings) ? group.mappings : [];
const mapping = this.findMatchingMapping(mappings, normalizedValues, rawValue, propName);
if (mapping) {
const targetFolder = String(mapping.folder || "").trim();
if (targetFolder) {
return {
targetFolder,
ruleName: propName,
ruleValue: normalizedValues[0]
};
}
}
}
return null;
}
/**
* Find matching mapping considering case sensitivity setting
* Supports: wildcard '*', operator field (equals, contains, is-empty, is-not-empty)
*/
findMatchingMapping(mappings, normalizedValues, rawFrontmatterValue, propName) {
for (const item of mappings) {
const operator = (item.operator || "equals").trim();
const mappingValue = String(item.value || "").trim();
// --- Presence operators (ignore value field) ---
if (operator === "is-empty") {
if (normalizedValues.length === 0) {
this.logger.debug(`[MATCH] is-empty matched for "${propName}"`);
return item;
}
continue;
}
if (operator === "is-not-empty") {
if (normalizedValues.length > 0) {
this.logger.debug(`[MATCH] is-not-empty matched for "${propName}"`);
return item;
}
continue;
}
// --- Value operators ---
if (mappingValue.length === 0) continue;
// Wildcard match - '*' matches any non-empty value
if (mappingValue === "*") {
if (normalizedValues.length > 0) {
this.logger.debug(`[MATCH] Wildcard matched with value: ${normalizedValues[0]}`);
return item;
}
continue;
}
let isMatch;
if (operator === "contains") {
const check = this.settings.caseInsensitiveMatching
? mappingValue.toLowerCase()
: mappingValue;
isMatch = normalizedValues.some(v => {
const val = this.settings.caseInsensitiveMatching ? v.toLowerCase() : v;
return val.includes(check);
});
} else {
// Default: equals
isMatch = this.settings.caseInsensitiveMatching
? normalizedValues.some(v => v.toLowerCase() === mappingValue.toLowerCase())
: normalizedValues.includes(mappingValue);
}
if (isMatch) return item;
}
return null;
}
/**
* Interpolate variables in folder path template
* Replaces {propertyName} and {file.*} variables with values from frontmatter or file metadata.
* Supports {file.ctime:yyyy} etc. for date formatting.
* @param {string} path - Path template with {variable} placeholders
* @param {Object} frontmatter - Frontmatter object with properties
* @param {Object} [file] - TFile instance for {file.*} variables
* @returns {string} Interpolated path
*/
interpolateVariables(path, frontmatter, file) {
if (!path || typeof path !== 'string') return path;
const FILE_VARIABLES = {
basename: function(f) { return f.basename; },
name: function(f) { return f.name; },
extension: function(f) { return f.extension; },
folder: function(f) { return f.parent ? f.parent.path : ''; },
path: function(f) { return f.path; },
ctime: function(f) { return new Date(f.stat.ctime); },
mtime: function(f) { return new Date(f.stat.mtime); }
};
const DATE_FORMATS = {
yyyy: function(d) { return String(d.getFullYear()); },
yy: function(d) { return String(d.getFullYear()).slice(-2); },
MM: function(d) { return String(d.getMonth() + 1).padStart(2, '0'); },
M: function(d) { return String(d.getMonth() + 1); },
dd: function(d) { return String(d.getDate()).padStart(2, '0'); },
d: function(d) { return String(d.getDate()); },
HH: function(d) { return String(d.getHours()).padStart(2, '0'); },
mm: function(d) { return String(d.getMinutes()).padStart(2, '0'); },
ss: function(d) { return String(d.getSeconds()).padStart(2, '0'); }
};
var that = this;
return path.replace(/{([\w.:]+)}/g, function(match, token) {
var parts = token.split(':');
var key = parts[0];
var format = parts[1] || null;
// Handle {file.*} variables
if (key.indexOf('file.') === 0) {
var fileKey = key.slice(5); // remove 'file.' prefix
if (!file || !FILE_VARIABLES[fileKey]) {
that.logger.debug('[INTERPOLATE] Unknown file variable \'' + fileKey + '\', keeping literal: ' + match);
return match;
}
var resolved = FILE_VARIABLES[fileKey](file);
if (resolved instanceof Date) {
if (format && DATE_FORMATS[format]) {
return DATE_FORMATS[format](resolved);
}
// No format given — default to ISO date string (YYYY-MM-DD)
return DATE_FORMATS['yyyy'](resolved) + '-' + DATE_FORMATS['MM'](resolved) + '-' + DATE_FORMATS['dd'](resolved);
}
return String(resolved);
}
// Frontmatter lookup (existing behavior)
var value = frontmatter ? frontmatter[key] : undefined;
if (value === null || value === undefined) {
that.logger.debug('[INTERPOLATE] Property \'' + key + '\' not found in frontmatter, keeping literal: ' + match);
return match;
}
var normalized = String(value).trim();
if (normalized.length === 0) {
that.logger.debug('[INTERPOLATE] Property \'' + key + '\' is empty, keeping literal: ' + match);
return match;
}
normalized = stripWikiLink(normalized);
that.logger.debug('[INTERPOLATE] Replaced {' + key + '} with \'' + normalized + '\'');
return normalized;
});
}
/**
* Preview what would happen if a file is processed
* @returns {Object|null} Move preview or null if no move needed
*/
previewMove(file, frontmatter) {
if (!frontmatter) {
this.logger.debug(`[PREVIEW] No frontmatter for ${file.path}`);
return null;
}
const targetResult = this.findTargetFolder(frontmatter);
if (!targetResult) {
this.logger.debug(`[PREVIEW] No matching rule for ${file.path}`);
return null;
}
// Interpolate variables in the target folder
const interpolatedFolder = this.interpolateVariables(targetResult.targetFolder, frontmatter, file);
const normalizedFolder = normalizePath(interpolatedFolder);
const targetPath = normalizePath(`${normalizedFolder}/${file.name}`);
if (file.path === targetPath) {
this.logger.debug(`[PREVIEW] File already in correct location: ${file.path}`);
return { action: "skip", reason: "already_in_target" };
}
// Check if folder exists
const folderExists = this.app.vault.getAbstractFileByPath(normalizedFolder) instanceof TFolder;
if (!folderExists && !this.settings.autoCreateFolders) {
return {
action: "skip",
reason: "folder_not_exist_no_create",
targetFolder: normalizedFolder,
template: targetResult.targetFolder,
interpolated: interpolatedFolder
};
}
const existingTarget = this.app.vault.getAbstractFileByPath(targetPath);
if (existingTarget) {
if (this.settings.autoAppendSuffix) {
return {
action: "move_with_suffix",
currentPath: file.path,
targetPath: targetPath,
targetFolder: normalizedFolder,
fileName: file.name,
template: targetResult.targetFolder,
interpolated: interpolatedFolder,
ruleName: targetResult.ruleName,
ruleValue: targetResult.ruleValue
};
} else {
return {
action: "skip",
reason: "target_exists",
targetPath: targetPath,
template: targetResult.targetFolder,
interpolated: interpolatedFolder
};
}
}
return {
action: "move",
currentPath: file.path,
targetPath: targetPath,
targetFolder: normalizedFolder,
template: targetResult.targetFolder,
interpolated: interpolatedFolder,
ruleName: targetResult.ruleName,
ruleValue: targetResult.ruleValue
};
}
/**
* Execute a file move operation with comprehensive error handling
*/
async moveFile(file, targetFolder) {
// Interpolate variables from file's frontmatter
const cache = this.app.metadataCache.getFileCache(file);
const frontmatter = cache ? cache.frontmatter : null;
const interpolatedFolder = frontmatter
? this.interpolateVariables(targetFolder, frontmatter, file)
: targetFolder;
const normalizedFolder = normalizePath(interpolatedFolder);
const targetPath = normalizePath(`${normalizedFolder}/${file.name}`);
if (file.path === targetPath) {
this.logger.debug(`File already at target: ${file.path}`);
return { success: true, action: "none", message: "File already in target location" };
}
try {
// Try to ensure folder exists
const folderCreated = await this.ensureFolder(normalizedFolder, this.settings.autoCreateFolders);
if (!folderCreated) {
const msg = `Target folder does not exist and autoCreateFolders is disabled: ${normalizedFolder}`;
this.logger.debug(msg);
return { success: false, action: "skip", message: msg };
}
const existingTarget = this.app.vault.getAbstractFileByPath(targetPath);
if (existingTarget) {
if (this.settings.autoAppendSuffix) {
const finalPath = await this.generateUniqueFileName(normalizedFolder, file.name);
await this.app.vault.rename(file, finalPath);
this.logger.debug(`Moved ${file.path} to ${finalPath} (suffix added)`);
return { success: true, action: "move_with_suffix", path: finalPath };
} else {
const msg = `Target file exists at ${targetPath}`;
this.logger.debug(msg);
return { success: false, action: "skip", message: msg };
}
} else {
await this.app.vault.rename(file, targetPath);
this.logger.debug(`Moved ${file.path} to ${targetPath}`);
return { success: true, action: "move", path: targetPath };
}
} catch (error) {
this.logger.error(`Failed to move ${file.name}: ${error.message}`);
return { success: false, action: "error", message: error.message };
}
}
/**
* Check if a file is in an ignored folder
*/
isFileInIgnoredFolder(filePath) {
const ignoreFolders = Array.isArray(this.settings.ignoreFolders)
? this.settings.ignoreFolders
: [];
const normalizedFilePath = normalizePath(filePath);
for (const ignoreFolder of ignoreFolders) {
const normalizedIgnoreFolder = normalizePath(String(ignoreFolder || "").trim());
if (!normalizedIgnoreFolder) continue;
if (
normalizedFilePath.startsWith(normalizedIgnoreFolder + "/") ||
normalizedFilePath === normalizedIgnoreFolder
) {
return true;
}
}
return false;
}
/**
* Generate a unique filename by appending numeric suffixes
*/
async generateUniqueFileName(folderPath, fileName) {
const extension = fileName.split(".").pop();
const baseName = fileName.slice(0, -(extension.length + 1));
let counter = 1;
const maxAttempts = 10000;
while (counter <= maxAttempts) {
const newFileName = `${baseName} ${counter}.${extension}`;
const fullPath = normalizePath(`${folderPath}/${newFileName}`);
const existing = this.app.vault.getAbstractFileByPath(fullPath);
if (!existing) {
this.logger.debug(`Generated unique filename: ${fullPath}`);
return fullPath;
}
counter++;
}
throw new Error(`Could not generate unique filename after ${maxAttempts} attempts for ${fileName}`);
}
/**
* Ensure a folder exists, creating it if necessary
* @param {string} folderPath - Path to the folder
* @param {boolean} autoCreate - Whether to create folder if it doesn't exist
* @returns {Promise<boolean>} True if folder exists or was created, false otherwise
*/
async ensureFolder(folderPath, autoCreate = true) {
const existing = this.app.vault.getAbstractFileByPath(folderPath);
if (existing instanceof TFolder) {
return true;
}
if (!autoCreate) {
this.logger.debug(`Folder does not exist and autoCreateFolders is disabled: ${folderPath}`);
return false;
}
try {
await this.app.vault.createFolder(folderPath);
this.logger.debug(`Created folder: ${folderPath}`);
return true;
} catch (error) {
// Folder might already exist due to race condition
if (this.app.vault.getAbstractFileByPath(folderPath)) {
return true;
}
throw error;
}
}
/**
* Validate that a file is eligible for processing
*/
isEligibleForProcessing(file) {
if (!(file instanceof TFile) || file.extension !== "md") {
return false;
}
if (this.app.metadataCache.isUserIgnored(file.path)) {
return false;
}
if (this.isFileInIgnoredFolder(file.path)) {
return false;
}
return true;
}
}
/**
* Logger utility for consistent logging with optional debug mode
*/
class Logger {
constructor(debugEnabled = false) {
this.debugEnabled = debugEnabled;
}
debug(msg) {
if (this.debugEnabled) {
console.log(`[PropMove] ${msg}`);
}
}
info(msg) {
console.log(`[PropMove] ${msg}`);
}
error(msg) {
console.error(`[PropMove] ${msg}`);
}
setDebugEnabled(enabled) {
this.debugEnabled = enabled;
}
}
/**
* Strip [[wiki-link]] wrapper from a string value.
* Handles: [[Name]], [[Name|Alias]], [[Name#heading]]
* Leaves plain text and partial links unchanged.
*/
function stripWikiLink(value) {
const match = value.match(/^\[\[([^\]\|]+)(?:\|.*)?\]\]$/);
return match ? match[1] : value;
}
module.exports = class PropMove extends Plugin {
async onload() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
this.migrateSettings();
this.pending = new Map();
this.movingPaths = new Set();
this.autoBatchQueue = new Map();
this.autoBatchTimer = null;
this.isStartup = true;
// Initialize logger and file processor
this.logger = new Logger(this.settings.debugLogging);
this.fileProcessor = new FileProcessor(this.app, this.settings, this.logger);
this.addSettingTab(new PropMoveSettingTab(this.app, this));
// Ribbon icon (configurable)
this.setupRibbonIcon();
// Register manual trigger command
this.addCommand({
id: "trigger-manual-process",
name: "Process files according to property rules",
callback: () => this.processAllFiles()
});
// Register preview command
this.addCommand({
id: "preview-moves",
name: "Preview property-based moves (shows what would be moved)",
callback: () => this.previewMoves()
});
// Register process folder command
this.addCommand({
id: "process-folder",
name: "Process files in specific folder",
callback: () => this.promptFolderAndProcess()
});
// Register preview folder command
this.addCommand({
id: "preview-folder",
name: "Preview moves in specific folder",
callback: () => this.promptFolderAndPreview()
});
// Register event handlers conditionally based on settings
if (this.settings.moveOnCreate && this.settings.automaticTriggers) {
this.registerEvent(
this.app.vault.on("create", (file) => {
this.logger.debug(`File created, queuing process: ${file.path}`);
this.queueProcess(file);
})
);
}
if (this.settings.moveOnMetadataChange && this.settings.automaticTriggers) {
this.registerEvent(
this.app.metadataCache.on("changed", (file) => {
this.logger.debug(`Metadata changed, queuing process: ${file.path}`);
// Skip processing during startup if moveOnStartup is disabled
if (this.isStartup && !this.settings.moveOnStartup) {
this.logger.debug(`Skipping startup processing for: ${file.path}`);
return;
}
this.queueProcess(file);
})
);
}
// Track folder renames and auto-update mapping paths
this.registerEvent(
this.app.vault.on("rename", (file, oldPath) => {
if (file instanceof TFolder) {
this.handleFolderRename(file.path, oldPath);
}
})
);
// Handle startup processing if enabled
if (this.settings.moveOnStartup && this.settings.automaticTriggers) {
setTimeout(() => {
this.isStartup = false;
this.logger.debug("Startup complete");
}, 2000); // Consider startup complete after 2 seconds
} else {
this.isStartup = false;
}
}
/**
* Handle folder rename by updating all mapping paths that reference the old path.
* Covers exact folder match and nested subfolder references.
*/
handleFolderRename(newPath, oldPath) {
const oldNormalized = normalizePath(oldPath);
const newNormalized = normalizePath(newPath);
let updated = 0;
this.settings.properties.forEach(group => {
// Skip properties with auto-update disabled
if (group.autoUpdatePaths === false) {
return;
}
(group.mappings || []).forEach(mapping => {
const oldFolder = normalizePath(mapping.folder);
// Exact match or parent folder
if (
oldFolder === oldNormalized ||
oldFolder.startsWith(oldNormalized + "/")
) {
// Replace the old folder path with the new one
mapping.folder = newNormalized + oldFolder.slice(oldNormalized.length);
updated++;
this.logger.debug(
`[RENAME] Updated mapping path: "${oldFolder}" -> "${mapping.folder}"`
);
}
});
});
// Also check ignoreFolders
for (let i = 0; i < this.settings.ignoreFolders.length; i++) {
const oldIgnore = normalizePath(this.settings.ignoreFolders[i]);
if (
oldIgnore === oldNormalized ||
oldIgnore.startsWith(oldNormalized + "/")
) {
this.settings.ignoreFolders[i] =
newNormalized + oldIgnore.slice(oldNormalized.length);
updated++;
this.logger.debug(
`[RENAME] Updated ignore folder: "${oldIgnore}" -> "${this.settings.ignoreFolders[i]}"`
);
}
}
if (updated > 0) {
this.saveSettings();
this.logger.info(
`[RENAME] Updated ${updated} path(s) after "${oldNormalized}" -> "${newNormalized}"`
);
}
}
onunload() {
if (this.autoBatchTimer) {
clearTimeout(this.autoBatchTimer);
this.autoBatchTimer = null;
}
this.autoBatchQueue.clear();
this.movingPaths.clear();
}
/**
* Queue a file for processing with debouncing and auto-batching.
* Auto-moves are batched into a single checkpoint within the cooldown window.
*/
queueProcess(file) {
if (!this.fileProcessor.isEligibleForProcessing(file)) {
return;
}
if (this.movingPaths.has(file.path)) {
return;
}
// Add to auto-batch queue (deduplicate by path)
if (!this.autoBatchQueue.has(file.path)) {
this.autoBatchQueue.set(file.path, file);
}
// Reset cooldown timer
if (this.autoBatchTimer) {
clearTimeout(this.autoBatchTimer);
}
this.autoBatchTimer = setTimeout(async () => {
const batchFiles = Array.from(this.autoBatchQueue.values());
this.autoBatchQueue.clear();
this.autoBatchTimer = null;
if (batchFiles.length > 0) {
await this.processFiles(batchFiles, "auto");
}
}, this.settings.undoAutoCooldownMs);
}
/**
* Process all files according to property rules
*/
async processAllFiles() {
await this.processFiles(this.app.vault.getMarkdownFiles());
}
/**
* Process files in a specific folder (including subfolders).
* @param {string} folderPath - Folder path to process
*/
async processFolder(folderPath) {
const folder = this.app.vault.getAbstractFileByPath(folderPath);
if (!(folder instanceof TFolder)) {
new Notice(`PropMove: Folder not found: ${folderPath}`);
return;
}
const normalizedFolder = normalizePath(folderPath);
const files = this.app.vault.getMarkdownFiles().filter(f =>
f.path.startsWith(normalizedFolder + '/')
);
if (files.length === 0) {
new Notice(`PropMove: No markdown files in "${folderPath}"`);
return;
}
await this.processFiles(files);
}
/**
* Core file processing loop with chunking for performance.
* @param {TFile[]} files - Files to process
*/
async processFiles(files, source) {
this.logger.debug("Starting manual processing of all files");
let processedCount = 0;
let movedCount = 0;
let skippedCount = 0;
const successfulMoves = [];
const maxFiles = this.settings.maxFilesPerBatch > 0 ? this.settings.maxFilesPerBatch : files.length;
for (const file of files) {
// Yield to UI thread every 50 files to keep the UI responsive
if (processedCount % 50 === 0 && processedCount > 0) {
await new Promise(resolve => setTimeout(resolve, 10));
}
if (processedCount >= maxFiles) {
this.logger.debug(`Reached maximum files per batch: ${maxFiles}`);
break;
}
// Skip files in ignored folders
if (this.fileProcessor.isFileInIgnoredFolder(file.path)) {
this.logger.debug(`Skipping ignored file: ${file.path}`);
continue;
}
try {
this.logger.debug(`Processing file: ${file.path}`);
const result = await this.processFile(file.path, source);
if (result && result.success) {
movedCount++;
if (result.from && result.to) {
successfulMoves.push({
file: result.file,
from: result.from,
to: result.to,
rule: result.rule
});
}
} else {
skippedCount++;
}
processedCount++;
} catch (error) {
this.logger.error(`Error processing file ${file.path}: ${error.message}`);
skippedCount++;
}
}
// Create checkpoint if there were successful moves
if (successfulMoves.length > 0) {
this.logger.info(`[UNDO] Creating checkpoint with ${successfulMoves.length} moves (source: ${source || "manual"})`);
await this.addCheckpoint(successfulMoves, source || "manual");
} else if (movedCount > 0) {
this.logger.warn(`[UNDO] movedCount=${movedCount} but successfulMoves is empty - checkpoint NOT created`);
}
this.logger.info(`PropMove: Processed ${processedCount} files, moved ${movedCount}, skipped ${skippedCount}`);
if (this.settings.notificationMode === "all" || (this.settings.notificationMode === "onMove" && movedCount > 0)) {
new Notice(`PropMove: Processed ${processedCount} files, moved ${movedCount}, skipped ${skippedCount}`);
}
}
/**
* Preview what moves would be made without actually moving files
*/
async previewMoves() {
await this.previewFiles(this.app.vault.getMarkdownFiles());
}
/**
* Preview moves in a specific folder (including subfolders).
* @param {string} folderPath - Folder path to preview
*/
async previewFolder(folderPath) {
const folder = this.app.vault.getAbstractFileByPath(folderPath);
if (!(folder instanceof TFolder)) {
new Notice(`PropMove: Folder not found: ${folderPath}`);
return;
}
const normalizedFolder = normalizePath(folderPath);
const files = this.app.vault.getMarkdownFiles().filter(f =>
f.path.startsWith(normalizedFolder + '/')
);
if (files.length === 0) {
new Notice(`PropMove: No markdown files in "${folderPath}"`);
return;
}
await this.previewFiles(files);
}
/**
* Core preview loop.
* @param {TFile[]} files - Files to preview
*/
async previewFiles(files) {
this.logger.debug("Starting preview of moves");
const previews = [];
let moveCount = 0;
let skipCount = 0;
for (const file of files) {
if (!this.fileProcessor.isEligibleForProcessing(file)) {
continue;
}
const cache = this.app.metadataCache.getFileCache(file);
const frontmatter = cache ? cache.frontmatter : null;
const preview = this.fileProcessor.previewMove(file, frontmatter);
if (preview) {
previews.push({
file: file.path,
...preview
});
if (preview.action === "move" || preview.action === "move_with_suffix") {
moveCount++;
} else {
skipCount++;
}
}
}
if (moveCount === 0 && skipCount === 0) {
this.logger.info("PropMove: No files would be moved");
if (this.settings.notificationMode === "all") {
new Notice("PropMove: No files would be moved based on current rules");
}
return;
}
// Log preview results
previews.forEach(p => {
if (p.action === "move") {
const pathInfo = p.template && p.template !== p.interpolated
? `${p.file} → ${p.targetPath} (template: ${p.template} → ${p.interpolated})`
: `${p.file} → ${p.targetPath}`;
this.logger.info(`[PREVIEW] MOVE: ${pathInfo}`);
} else if (p.action === "move_with_suffix") {
const pathInfo = p.template && p.template !== p.interpolated
? `${p.file} → ${p.targetFolder}/ (template: ${p.template} → ${p.interpolated})`
: `${p.file} → ${p.targetFolder}/`;
this.logger.info(`[PREVIEW] MOVE (with suffix): ${pathInfo}`);
} else if (p.action === "skip") {
if (p.reason === "folder_not_exist_no_create") {
this.logger.info(`[PREVIEW] SKIP: ${p.file} (folder does not exist: ${p.targetFolder})`);
} else {
this.logger.info(`[PREVIEW] SKIP: ${p.file} (${p.reason})`);
}
}
});
this.logger.info(`PropMove Preview: ${moveCount} would move, ${skipCount} would skip. Check console for details.`);
if (this.settings.notificationMode === "all") {
new Notice(`PropMove Preview: ${moveCount} would move, ${skipCount} would skip. Check console for details.`);
}
}
/**
* Prompt user to select a folder and process it.
*/
promptFolderAndProcess() {
const folders = this.collectAllFolders();
const modal = new FolderPickerModal(this.app, folders, (folder) => {
if (folder) {
this.processFolder(folder);
}
});
modal.open();
}
/**
* Prompt user to select a folder and preview moves.
*/
promptFolderAndPreview() {
const folders = this.collectAllFolders();
const modal = new FolderPickerModal(this.app, folders, (folder) => {
if (folder) {
this.previewFolder(folder);
}
});
modal.open();
}
/**
* Collect all folder paths recursively for suggestions.
* @returns {string[]} All folder paths in the vault
*/
collectAllFolders() {
const folders = [];
const root = this.app.vault.getRoot();
const traverse = (folder) => {
if (folder instanceof TFolder) {
folders.push(folder.path);
folder.children.forEach(traverse);
}
};
if (root) {
root.children.forEach(traverse);
}
return folders;
}
/**
* Render manual trigger buttons into a container using Obsidian's Setting API.
* Shared between the settings tab and the ribbon icon modal.
*/
renderManualTriggers(containerEl) {
// Row 1: Process all files - Dry Run + Execute
new Setting(containerEl)
.setName("Process all files")
.setDesc("Move all files based on current property rules")
.addButton((button) =>
button
.setButtonText("Dry Run")
.onClick(async () => {
await this.previewMoves();
})
)
.addButton((button) =>
button
.setButtonText("Execute")
.setCta()
.onClick(async () => {
await this.processAllFiles();
})
);
// Row 2: Process folder - Dry Run + Execute
new Setting(containerEl)
.setName("Process folder")
.setDesc("Select a specific folder to process files in")
.addButton((button) =>
button
.setButtonText("Dry Run")
.onClick(() => {
this.promptFolderAndPreview();
})
)
.addButton((button) =>
button
.setButtonText("Execute")
.setCta()
.onClick(() => {
this.promptFolderAndProcess();
})
);
}
/**
* Set up or remove the ribbon icon based on settings.
*/
setupRibbonIcon() {
// Remove existing icon if present
if (this.ribbonIconEl) {
this.ribbonIconEl.remove();
this.ribbonIconEl = null;
}
if (!this.settings.showRibbonIcon) return;
// Option F: Minimal + Arrow SVG
const svgPath = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="12" height="12" rx="2"/><path d="M15 15l6 6"/><path d="M21 15v6h-6"/></svg>`;
this.ribbonIconEl = this.addRibbonIcon("move", "PropMove: Quick actions", () => {
new ManualTriggerModal(this.app, this).open();
});
// Replace the default icon with our custom SVG
const iconEl = this.ribbonIconEl.querySelector("svg");
if (iconEl) {
iconEl.outerHTML = svgPath;
}
}
/**
* Process a single file and move it if applicable
*/
async processFile(filePath, source) {
const file = this.app.vault.getAbstractFileByPath(filePath);
if (!this.fileProcessor.isEligibleForProcessing(file)) {