-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathFileSource.ts
More file actions
1476 lines (1295 loc) · 36.7 KB
/
FileSource.ts
File metadata and controls
1476 lines (1295 loc) · 36.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
/**
* FileSource - Main implementation for FileSource feature
*
* This source integrates files as tasks into the dataflow architecture.
* It follows the same patterns as ObsidianSource and IcsSource.
*/
import type { App, TFile, EventRef, CachedMetadata } from "obsidian";
import type TaskProgressBarPlugin from "@/index";
import type { Task } from "@/types/task";
import type {
FileSourceConfiguration,
FileSourceTaskMetadata,
FileSourceStats,
FileTaskCache,
RecognitionStrategy,
PathRecognitionConfig,
TemplateRecognitionConfig,
MetadataMappingConfig,
} from "@/types/file-source";
import { Events, emit, Seq, on } from "../events/Events";
import { FileSourceConfig } from "./FileSourceConfig";
import { FileFilterManager } from "@/managers/file-filter-manager";
/**
* FileSource - Independent event source for file-based tasks
*
* Subscribes to file events and transforms qualifying files into tasks
* following the established dataflow patterns.
*/
export class FileSource {
/**
* Default status mappings from textual values to task symbols
* Provides fallback mappings when user configuration doesn't specify a mapping
*/
private static readonly DEFAULT_STATUS_MAPPINGS: Record<string, string> = {
completed: "x",
done: "x",
finished: "x",
"in-progress": "/",
"in progress": "/",
doing: "/",
planned: "?",
todo: "?",
cancelled: "-",
canceled: "-",
"not-started": " ",
"not started": " ",
};
private config: FileSourceConfig;
private isInitialized = false;
private lastUpdateSeq = 0;
// Event references for cleanup
private eventRefs: EventRef[] = [];
// Cache for tracking file task state
private fileTaskCache = new Map<string, FileTaskCache>();
// Debouncing for rapid changes
private pendingUpdates = new Map<string, NodeJS.Timeout>();
private readonly DEBOUNCE_DELAY = 300; // ms
// Statistics tracking
private stats: FileSourceStats = {
initialized: false,
trackedFileCount: 0,
recognitionBreakdown: {
metadata: 0,
tag: 0,
template: 0,
path: 0,
},
lastUpdate: 0,
lastUpdateSeq: 0,
};
constructor(
private app: App,
initialConfig?: Partial<FileSourceConfiguration>,
private fileFilterManager?: FileFilterManager,
private plugin?: TaskProgressBarPlugin
) {
this.config = new FileSourceConfig(initialConfig);
}
/**
* Initialize FileSource and start listening for events
*/
async initialize(): Promise<void> {
if (this.isInitialized) return;
if (!this.config.isEnabled()) return;
console.log("[FileSource] Initializing FileSource...");
// Subscribe to configuration changes
this.config.onChange((newConfig) => {
this.handleConfigChange(newConfig);
});
// Subscribe to file events
this.subscribeToFileEvents();
this.isInitialized = true;
this.stats.initialized = true;
try {
await this.performInitialScan();
} catch (error) {
console.error("[FileSource] Initial scan failed", error);
}
console.log(
`[FileSource] Initialized with strategies: ${this.config
.getEnabledStrategies()
.join(", ")}`
);
}
/**
* Subscribe to relevant file events
*/
private subscribeToFileEvents(): void {
// Subscribe to FILE_UPDATED events from ObsidianSource
this.eventRefs.push(
on(this.app, Events.FILE_UPDATED, (payload) => {
if (payload?.path) {
this.handleFileUpdate(payload.path, payload.reason);
}
})
);
// Subscribe to more granular events if they exist
// These would be added to Events.ts later in Phase 2
this.eventRefs.push(
on(
this.app,
"task-genius:file-metadata-changed" as any,
(payload) => {
if (payload?.path) {
this.handleFileMetadataChange(payload.path);
}
}
)
);
this.eventRefs.push(
on(
this.app,
"task-genius:file-content-changed" as any,
(payload) => {
if (payload?.path) {
this.handleFileContentChange(payload.path);
}
}
)
);
}
/**
* Handle file update events with debouncing
*/
private handleFileUpdate(filePath: string, reason: string): void {
if (!this.isInitialized || !this.config.isEnabled()) return;
const relevant = this.isRelevantFile(filePath);
if (!relevant) return;
// Clear existing timeout for this file
const existingTimeout = this.pendingUpdates.get(filePath);
if (existingTimeout) {
clearTimeout(existingTimeout);
}
// Set new debounced timeout
const timeout = setTimeout(async () => {
this.pendingUpdates.delete(filePath);
try {
await this.processFileUpdate(filePath, reason);
} catch (error) {
console.error(
`[FileSource] Error processing file update for ${filePath}:`,
error
);
}
}, this.DEBOUNCE_DELAY);
this.pendingUpdates.set(filePath, timeout);
}
/**
* Handle granular metadata changes (Phase 2 enhancement)
*/
private handleFileMetadataChange(filePath: string): void {
if (!this.shouldUpdateFileTask(filePath, "metadata")) return;
this.handleFileUpdate(filePath, "frontmatter");
}
/**
* Handle granular content changes (Phase 2 enhancement)
*/
private handleFileContentChange(filePath: string): void {
if (!this.shouldUpdateFileTask(filePath, "content")) return;
this.handleFileUpdate(filePath, "modify");
}
/**
* Process a file update and determine if it should be a file task
*/
private async processFileUpdate(
filePath: string,
reason: string
): Promise<void> {
if (reason === "delete") {
await this.removeFileTask(filePath);
return;
}
const shouldBeTask = await this.shouldCreateFileTask(filePath);
const existingCache = this.fileTaskCache.get(filePath);
const wasTask = existingCache?.fileTaskExists ?? false;
if (shouldBeTask && !wasTask) {
// File should become a task
await this.createFileTask(filePath);
} else if (shouldBeTask && wasTask) {
// File is already a task, check if it needs updating
await this.updateFileTask(filePath);
} else if (!shouldBeTask && wasTask) {
// File should no longer be a task
await this.removeFileTask(filePath);
}
// else: File is not and should not be a task, do nothing
}
/**
* Check if a file should be treated as a task
*/
async shouldCreateFileTask(filePath: string): Promise<boolean> {
// Fast reject non-relevant files before any IO
if (!this.isRelevantFile(filePath)) return false;
const file = this.app.vault.getAbstractFileByPath(filePath) as TFile;
if (!file) return false;
try {
const fileContent = await this.app.vault.cachedRead(file);
const fileCache = this.app.metadataCache.getFileCache(file);
return this.evaluateRecognitionStrategies(
filePath,
fileContent,
fileCache
);
} catch (error) {
console.error(
`[FileSource] Error reading file ${filePath}:`,
error
);
return false;
}
}
/**
* Evaluate all enabled recognition strategies
*/
private evaluateRecognitionStrategies(
filePath: string,
fileContent: string,
fileCache: CachedMetadata | null
): boolean {
const config = this.config.getConfig();
const { recognitionStrategies } = config;
// Check metadata strategy
if (recognitionStrategies.metadata.enabled) {
if (
this.matchesMetadataStrategy(
filePath,
fileContent,
fileCache,
recognitionStrategies.metadata
)
) {
return true;
}
}
// Check tag strategy
if (recognitionStrategies.tags.enabled) {
if (
this.matchesTagStrategy(
filePath,
fileContent,
fileCache,
recognitionStrategies.tags
)
) {
return true;
}
}
// Check template strategy (Phase 2)
if (recognitionStrategies.templates.enabled) {
if (
this.matchesTemplateStrategy(
filePath,
fileContent,
fileCache,
recognitionStrategies.templates
)
) {
return true;
}
}
// Check path strategy (Phase 2)
if (recognitionStrategies.paths.enabled) {
if (
this.matchesPathStrategy(
filePath,
fileContent,
fileCache,
recognitionStrategies.paths
)
) {
return true;
}
}
return false;
}
/**
* Check if file matches metadata strategy
*/
private matchesMetadataStrategy(
filePath: string,
fileContent: string,
fileCache: CachedMetadata | null,
config: any
): boolean {
if (!fileCache?.frontmatter) return false;
const { taskFields, requireAllFields } = config;
const frontmatter = fileCache.frontmatter;
const matchingFields = taskFields.filter(
(field: string) =>
frontmatter.hasOwnProperty(field) &&
frontmatter[field] !== undefined
);
if (requireAllFields) {
return matchingFields.length === taskFields.length;
} else {
return matchingFields.length > 0;
}
}
/**
* Check if file matches tag strategy
*/
private matchesTagStrategy(
filePath: string,
fileContent: string,
fileCache: CachedMetadata | null,
config: any
): boolean {
if (!fileCache?.tags) return false;
const { taskTags, matchMode } = config;
const fileTags = fileCache.tags.map((tag) => tag.tag);
return taskTags.some((taskTag: string) => {
return fileTags.some((fileTag) => {
switch (matchMode) {
case "exact":
return fileTag === taskTag;
case "prefix":
return fileTag.startsWith(taskTag);
case "contains":
return fileTag.includes(taskTag);
default:
return fileTag === taskTag;
}
});
});
}
/**
* Check if file matches template strategy
*/
private matchesTemplateStrategy(
filePath: string,
fileContent: string,
fileCache: CachedMetadata | null,
config: TemplateRecognitionConfig
): boolean {
if (
!config.enabled ||
!config.templatePaths ||
config.templatePaths.length === 0
) {
return false;
}
// Check if file matches any template path
return config.templatePaths.some((templatePath) => {
// Check direct path inclusion
if (filePath.includes(templatePath)) {
return true;
}
// Check frontmatter template references
if (config.checkTemplateMetadata && fileCache?.frontmatter) {
const frontmatter = fileCache.frontmatter;
return (
frontmatter.template === templatePath ||
frontmatter.templateFile === templatePath ||
frontmatter.templatePath === templatePath
);
}
return false;
});
}
/**
* Check if file matches path strategy
*/
private matchesPathStrategy(
filePath: string,
fileContent: string,
fileCache: CachedMetadata | null,
config: PathRecognitionConfig
): boolean {
if (
!config.enabled ||
!config.taskPaths ||
config.taskPaths.length === 0
) {
return false;
}
// Normalize path (use forward slashes)
const normalizedPath = filePath.replace(/\\/g, "/");
// Check each configured path pattern
for (const pattern of config.taskPaths) {
const normalizedPattern = pattern.replace(/\\/g, "/");
switch (config.matchMode) {
case "prefix":
if (normalizedPath.startsWith(normalizedPattern)) {
console.log(
`[FileSource] Path matches prefix pattern: ${pattern} for ${filePath}`
);
return true;
}
break;
case "regex":
try {
const regex = new RegExp(normalizedPattern);
if (regex.test(normalizedPath)) {
console.log(
`[FileSource] Path matches regex pattern: ${pattern} for ${filePath}`
);
return true;
}
} catch (e) {
console.warn(
`[FileSource] Invalid regex pattern: ${pattern}`,
e
);
}
break;
case "glob":
if (
this.matchGlobPattern(normalizedPath, normalizedPattern)
) {
console.log(
`[FileSource] Path matches glob pattern: ${pattern} for ${filePath}`
);
return true;
}
break;
}
}
return false;
}
/**
* Match a path against a glob pattern
* Supports: * (any chars except /), ** (any chars), ? (single char)
*/
private matchGlobPattern(path: string, pattern: string): boolean {
// Convert glob pattern to regular expression
let regexPattern = pattern
.replace(/[.+^${}()|[\]\\]/g, "\\$&") // Escape special chars
.replace(/\*\*/g, "§§§") // Temporary placeholder for **
.replace(/\*/g, "[^/]*") // * matches any chars except /
.replace(/§§§/g, ".*") // ** matches any chars
.replace(/\?/g, "[^/]"); // ? matches single char
// If pattern ends with /, match all files in that directory
if (pattern.endsWith("/")) {
regexPattern = `^${regexPattern}.*`;
} else {
regexPattern = `^${regexPattern}$`;
}
try {
const regex = new RegExp(regexPattern);
return regex.test(path);
} catch (e) {
console.warn(
`[FileSource] Failed to compile glob pattern: ${pattern}`,
e
);
return false;
}
}
/**
* Create a new file task
*/
async createFileTask(
filePath: string
): Promise<Task<FileSourceTaskMetadata> | null> {
const file = this.app.vault.getAbstractFileByPath(filePath) as TFile;
if (!file) return null;
try {
const fileContent = await this.app.vault.cachedRead(file);
const fileCache = this.app.metadataCache.getFileCache(file);
const fileTask = await this.buildFileTask(
filePath,
fileContent,
fileCache
);
if (!fileTask) return null;
// Update cache
this.updateFileTaskCache(filePath, fileTask);
// Update statistics
this.updateStatistics(fileTask.metadata.recognitionStrategy, 1);
// Emit file task event
this.emitFileTaskUpdate("created", fileTask);
return fileTask;
} catch (error) {
console.error(
`[FileSource] Error creating file task for ${filePath}:`,
error
);
return null;
}
}
/**
* Update an existing file task
*/
async updateFileTask(
filePath: string
): Promise<Task<FileSourceTaskMetadata> | null> {
// For Phase 1, just recreate the task
// Phase 2 will add smart update detection
return await this.createFileTask(filePath);
}
/**
* Remove a file task
*/
async removeFileTask(filePath: string): Promise<void> {
const existingCache = this.fileTaskCache.get(filePath);
if (!existingCache?.fileTaskExists) return;
// Remove from cache
this.fileTaskCache.delete(filePath);
// Update statistics
this.stats.trackedFileCount = Math.max(
0,
this.stats.trackedFileCount - 1
);
// Emit removal event
const seq = Seq.next();
this.lastUpdateSeq = seq;
emit(this.app, Events.FILE_TASK_REMOVED, {
filePath,
timestamp: Date.now(),
seq,
});
console.log(`[FileSource] Removed file task: ${filePath}`);
}
/**
* Build a file task from file data
*/
private async buildFileTask(
filePath: string,
fileContent: string,
fileCache: CachedMetadata | null
): Promise<Task<FileSourceTaskMetadata> | null> {
const config = this.config.getConfig();
const file = this.app.vault.getAbstractFileByPath(filePath) as TFile;
if (!file) return null;
// Determine which strategy matched
const strategy = this.getMatchingStrategy(
filePath,
fileContent,
fileCache
);
if (!strategy) return null;
// Generate task content based on configuration
const content = this.generateTaskContent(
filePath,
fileContent,
fileCache
);
const safeContent =
typeof content === "string"
? content
: filePath.split("/").pop() || filePath;
// Extract metadata from frontmatter
const metadataResult = this.extractTaskMetadata(
filePath,
fileContent,
fileCache,
strategy
);
// Separate rawStatus from metadata (rawStatus is not part of FileSourceTaskMetadata)
const { rawStatus, ...metadata } = metadataResult;
// Compute status symbol from raw frontmatter value (BaseTask layer)
const status = this.computeStatusSymbol(
rawStatus,
config.fileTaskProperties.defaultStatus
);
// Log status mapping if conversion occurred
if (rawStatus && status !== rawStatus) {
console.log(
`[FileSource] Mapped status '${rawStatus}' to '${status}' for ${filePath}`
);
}
// Create the file task
const fileTask: Task<FileSourceTaskMetadata> = {
id: `file-source:${filePath}`,
content: safeContent,
filePath,
line: 0, // File tasks are at line 0
completed: status === "x" || status === "X",
status: status,
originalMarkdown: `**${safeContent}**`,
metadata: {
...metadata,
source: "file-source",
recognitionStrategy: strategy.name,
recognitionCriteria: strategy.criteria,
fileTimestamps: {
created: file.stat.ctime,
modified: file.stat.mtime,
},
childTasks: [], // Will be populated in Phase 3
tags: metadata.tags || [],
children: [], // Required by StandardTaskMetadata
},
};
return fileTask;
}
/**
* Get the matching recognition strategy for a file
*/
private getMatchingStrategy(
filePath: string,
fileContent: string,
fileCache: CachedMetadata | null
): { name: RecognitionStrategy; criteria: string } | null {
const config = this.config.getConfig();
if (
config.recognitionStrategies.metadata.enabled &&
this.matchesMetadataStrategy(
filePath,
fileContent,
fileCache,
config.recognitionStrategies.metadata
)
) {
return { name: "metadata", criteria: "frontmatter" };
}
if (
config.recognitionStrategies.tags.enabled &&
this.matchesTagStrategy(
filePath,
fileContent,
fileCache,
config.recognitionStrategies.tags
)
) {
return { name: "tag", criteria: "file-tags" };
}
// Check path strategy
if (
config.recognitionStrategies.paths.enabled &&
this.matchesPathStrategy(
filePath,
fileContent,
fileCache,
config.recognitionStrategies.paths
)
) {
return {
name: "path",
criteria:
config.recognitionStrategies.paths.taskPaths.join(", "),
};
}
// Template-based recognition
const templateConfig = config.recognitionStrategies.templates;
if (templateConfig.enabled && templateConfig.templatePaths.length > 0) {
// Check if file matches any template path
const matchesTemplate = templateConfig.templatePaths.some(
(templatePath) => {
// Simple path matching - could be enhanced with more sophisticated matching
return (
filePath.includes(templatePath) ||
fileCache?.frontmatter?.template === templatePath ||
fileCache?.frontmatter?.templateFile === templatePath
);
}
);
if (matchesTemplate) {
return {
name: "template",
criteria: templateConfig.templatePaths.join(", "),
};
}
}
return null;
}
/**
* Generate task content based on configuration
*/
private generateTaskContent(
filePath: string,
fileContent: string,
fileCache: CachedMetadata | null
): string {
const config = this.config.getConfig().fileTaskProperties;
const fileName = filePath.split("/").pop() || filePath;
const fileNameWithoutExt = fileName.replace(/\.[^/.]+$/, "");
switch (config.contentSource) {
case "filename":
// If user prefers frontmatter title, show it over filename
if (
config.preferFrontmatterTitle &&
fileCache?.frontmatter?.title
) {
return fileCache.frontmatter.title as string;
}
return config.stripExtension ? fileNameWithoutExt : fileName;
case "title":
// Always prefer frontmatter title if available, fallback to filename without extension
return (
(fileCache?.frontmatter?.title as string) ||
fileNameWithoutExt
);
case "h1":
const h1 = fileCache?.headings?.find((h) => h.level === 1);
return (h1?.heading as string) || fileNameWithoutExt;
case "custom":
if (config.customContentField && fileCache?.frontmatter) {
const val =
fileCache.frontmatter[config.customContentField];
if (val) return val as string;
// If custom field not present, optionally prefer frontmatter title
if (
config.preferFrontmatterTitle &&
fileCache.frontmatter.title
) {
return fileCache.frontmatter.title as string;
}
return fileNameWithoutExt;
}
// No custom field specified: optionally prefer frontmatter title
if (
config.preferFrontmatterTitle &&
fileCache?.frontmatter?.title
) {
return fileCache.frontmatter.title as string;
}
return fileNameWithoutExt;
default:
// Default to respecting preferFrontmatterTitle when available
if (
config.preferFrontmatterTitle &&
fileCache?.frontmatter?.title
) {
return fileCache.frontmatter.title as string;
}
return config.stripExtension ? fileNameWithoutExt : fileName;
}
}
/**
* Compute task status symbol from raw metadata value
* Maps textual status values (e.g., "completed", "in-progress") to task status symbols (e.g., "x", "/")
*/
private computeStatusSymbol(
rawStatus: string | undefined,
defaultStatus: string
): string {
if (!rawStatus) return defaultStatus;
// Already a single-character mark
if (rawStatus.length === 1) return rawStatus;
const sm = this.config.getConfig().statusMapping;
const target = sm.caseSensitive
? rawStatus
: String(rawStatus).toLowerCase();
// Try configured metadata->symbol table first
for (const [k, sym] of Object.entries(sm.metadataToSymbol || {})) {
const key = sm.caseSensitive ? k : k.toLowerCase();
if (key === target) return sym;
}
// Fallback to common defaults to be robust
const norm = String(rawStatus).toLowerCase();
const defaultMapping = FileSource.DEFAULT_STATUS_MAPPINGS[norm];
if (defaultMapping !== undefined) return defaultMapping;
return defaultStatus;
}
/**
* Extract task metadata from file
* Returns metadata along with rawStatus for status symbol computation
*/
private extractTaskMetadata(
filePath: string,
fileContent: string,
fileCache: CachedMetadata | null,
strategy: { name: RecognitionStrategy; criteria: string }
): Partial<FileSourceTaskMetadata> & { rawStatus?: string } {
const config = this.config.getConfig();
const frontmatter = fileCache?.frontmatter || {};
const resolvedFrontmatter = this.applyMetadataMappings(
frontmatter,
config.metadataMappings
);
// Extract raw status value from frontmatter for later symbol mapping
const rawStatusVal = resolvedFrontmatter.status ?? "";
const rawStatus: string = typeof rawStatusVal === "string" ? rawStatusVal : String(rawStatusVal ?? "");
// TODO: Future enhancement - read frontmatter.repeat and map into FileSourceTaskMetadata (e.g., as recurrence)
// Collect all tags (from file cache and frontmatter)
const allTags = this.mergeTags(
fileCache?.tags?.map((tag) => tag.tag) || [],
resolvedFrontmatter.tags
);
// Extract project from tags as a fallback (only if not in frontmatter)
// Note: In FileSource mode, context and area come ONLY from frontmatter,
// not from tags like #context/xxx or #area/xxx
const projectTagExtraction = this.extractProjectFromTags(allTags);
const projectFromTags = projectTagExtraction.project;
// Priority order for project:
// 1. Direct frontmatter field (project: xxx) - highest priority
// 2. Metadata mapping (e.g., custom_project mapped to project via metadataMappings)
// 3. Tag extraction (#project/xxx) - lowest priority, only if frontmatter has nothing
const projectVal = resolvedFrontmatter.project ?? projectFromTags;
let projectValue: string | undefined;
if (projectVal === true) {
const fileName = filePath.split("/").pop() || filePath;
projectValue = fileName.replace(/\.md$/i, "");
} else if (typeof projectVal === "string" && projectVal.trim()) {
projectValue = projectVal.trim();
}
const shouldStripProjectTags =
!resolvedFrontmatter.project &&
Boolean(projectFromTags) &&
projectTagExtraction.matchedTags.length > 0;
const tagsForMetadata = shouldStripProjectTags
? allTags.filter(
(tag) => !projectTagExtraction.matchedTags.includes(tag)
)
: allTags;
// Extract standard task metadata
const metadata: Partial<FileSourceTaskMetadata> = {
dueDate: this.parseDate(
resolvedFrontmatter.dueDate ?? resolvedFrontmatter.due
),
startDate: this.parseDate(
resolvedFrontmatter.startDate ?? resolvedFrontmatter.start
),
scheduledDate: this.parseDate(
resolvedFrontmatter.scheduledDate ??
resolvedFrontmatter.scheduled
),
completedDate: this.parseDate(resolvedFrontmatter.completedDate),
createdDate: this.parseDate(resolvedFrontmatter.createdDate),
recurrence:
typeof resolvedFrontmatter.recurrence === "string"
? resolvedFrontmatter.recurrence
: (resolvedFrontmatter.recurrence != null
? String(resolvedFrontmatter.recurrence)
: undefined),
priority:
this.parsePriority(resolvedFrontmatter.priority) ??
config.fileTaskProperties.defaultPriority,
// Project: frontmatter (direct or mapped) > tags (#project/xxx)
project: projectValue,
// Context and area: ONLY from frontmatter (direct or mapped via metadataMappings)
context:
resolvedFrontmatter.context !== undefined &&
resolvedFrontmatter.context !== null
? String(resolvedFrontmatter.context)
: undefined,
area:
resolvedFrontmatter.area !== undefined &&
resolvedFrontmatter.area !== null
? String(resolvedFrontmatter.area)
: undefined,
tags: tagsForMetadata,
children: [],
};
// Return metadata with rawStatus for status computation in buildFileTask
return { ...metadata, rawStatus };
}
/**
* Extract project from tags
* Only extracts #project/xxx format tags as a fallback when frontmatter doesn't have project
* Note: context and area are NOT extracted from tags in FileSource mode,
* they should be defined directly in frontmatter (context: xxx, area: xxx)
*/
private extractProjectFromTags(tags: string[]): {
project?: string;
matchedTags: string[];
} {
// Get configurable project prefix from plugin settings, with fallback default
const configuredPrefix =
this.plugin?.settings?.projectTagPrefix?.["tasks"];
const projectPrefix =
typeof configuredPrefix === "string" && configuredPrefix.trim()
? configuredPrefix.trim()
: "project";
const matchedTags: string[] = [];
let projectValue: string | undefined;
for (const tag of tags) {
if (!tag || typeof tag !== "string") continue;
// Remove leading # if present
const tagWithoutHash = tag.startsWith("#") ? tag.substring(1) : tag;
// Check for project tags (case-insensitive prefix match)
if (