generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
68 lines (60 loc) · 1.7 KB
/
main.ts
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
import { Editor, MarkdownView, Plugin, TFile } from 'obsidian';
import { exec } from "child_process";
const plist = require('plist');
export default class MacTagPlugin extends Plugin {
async onload() {
this.addCommand({
id: 'write-macos-tag',
name: "Write Mac OS tags",
editorCallback: (editor: Editor, view: MarkdownView) => {
this.writeTags(view.file);
}
});
this.addCommand({
id: 'write-macos-tag-folder',
name: "Write Mac OS tags for current folder",
editorCallback: (editor: Editor, view: MarkdownView) => {
view.file.parent.children.forEach((file) => {
if (file instanceof TFile) {
this.writeTags(file);
}
})
}
});
}
onunload() {
}
writeTags(file: TFile) {
//@ts-ignore
const fileWithPath = `${this.app.vault.adapter.basePath}/${file.path}`;
const plTags: string = plist.build(this.getTags(file));
exec(`xattr -w com.apple.metadata:_kMDItemUserTags '${plTags}' '${fileWithPath}'`,(error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
});
}
getTags(file: TFile): string[] {
const tags: string[] = [];
const metadata = this.app.metadataCache.getFileCache(file);
if (metadata?.tags) {
metadata.tags.forEach(function (value) {
tags.push(value.tag);
});
}
if (metadata?.frontmatter) {
if (metadata.frontmatter.tags){
const frontmattertags: string[] = typeof metadata.frontmatter.tags === "string" ? [metadata.frontmatter.tags] : metadata.frontmatter.tags;
frontmattertags.forEach(function (value) {
tags.push(value);
});
}
}
return tags.map((s: string)=> s.replace("#", ""))
}
}