-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.ts
243 lines (212 loc) · 7.79 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
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
import { Plugin, parseYaml, PluginSettingTab, Setting, App, MarkdownRenderer, MarkdownPostProcessorContext } from 'obsidian'
import { execSync } from 'child_process'
interface Settings {
taskBinaryPath: string
}
const DEFAULT_SETTINGS: Settings = {
taskBinaryPath: 'task'
}
export class EgoRockSettingsTab extends PluginSettingTab {
plugin: EgoRock
constructor(app: App, plugin: EgoRock) {
super(app, plugin)
this.app = app
this.plugin = plugin
}
display(): void {
let { containerEl } = this
containerEl.empty()
new Setting(containerEl)
.setName('Taskwarrior binary path')
.setDesc('The path to the taskwarrior binary. If task is on the system PATH, "task" should work. Otherwise, provide an absolute path. WSL systems can invoke taskwarrior running in WSL from windows with the path "wsl task".')
.addText((text) =>
text
.setPlaceholder('task')
.setValue(this.plugin.settings.taskBinaryPath)
.onChange(async (value) => {
this.plugin.settings.taskBinaryPath = value
await this.plugin.saveSettings()
})
)
}
}
export default class EgoRock extends Plugin {
settings: Settings
async onload() {
await this.loadSettings()
this.addSettingTab(new EgoRockSettingsTab(this.app, this))
this.registerMarkdownCodeBlockProcessor('task-table', (source, element, context) => {
this.doCommand(
parseYaml(source).command,
false,
this.buildHTMLTable,
this.handleHTMLTableError,
[element, context, parseYaml(source)]
)
})
this.registerMarkdownCodeBlockProcessor('task-table-ascii', (source, element, context) => {
this.doCommand(
parseYaml(source).command,
true,
this.buildASCIITable,
this.handleASCIITableError,
[element, context]
)
})
this.registerMarkdownCodeBlockProcessor('task-count', (source, element, context) => {
this.doCommand(
parseYaml(source).command,
false,
this.buildCount,
this.handleCountError,
[element, context]
)
})
}
onunload() {
}
handleCountError(error: Error, element: any, context: MarkdownPostProcessorContext) {
MarkdownRenderer.render(this.app, '```\n' + error.message + '\n```', element, context.sourcePath, this)
}
buildCount(tableDescription: any, el: any, context: MarkdownPostProcessorContext) {
MarkdownRenderer.render(this.app, '```\n' + tableDescription[1].length + '\n```', el, context.sourcePath, this)
}
handleASCIITableError(error: Error, element: any, context: MarkdownPostProcessorContext) {
MarkdownRenderer.render(this.app, '```\n' + error.message + '\n```', element, context.sourcePath, this)
}
buildASCIITable(rawTable: string, el: any, context: MarkdownPostProcessorContext) {
MarkdownRenderer.render(this.app, '```\n' + rawTable + '\n```', el, context.sourcePath, this)
}
handleHTMLTableError(error: Error, element: any, context: MarkdownPostProcessorContext) {
MarkdownRenderer.render(this.app, '```\n' + error.message + '\n```', element, context.sourcePath, this)
}
buildHTMLTable(tableDescription: any, el: any, context: any, config: any) {
const [columns, rows] = tableDescription
const actionsRowEl = el.createEl('div')
if (config.actions && config.actions.contains('refresh')) {
const refreshButton = actionsRowEl.createEl('button', { text: 'Refresh' })
refreshButton.on('click', 'button', () => {
el.replaceChildren()
this.doCommand(
config.command,
false,
this.buildHTMLTable,
this.handleHTMLTableError,
[el, context, config]
)
})
}
const tableEl = el.createEl('table')
const headerEl = tableEl.createEl('thead').createEl('tr')
for (let i = 0; i < columns.length; i++) {
headerEl.createEl('th', {
attr: { scope: 'col' },
text: columns[i].columnName
})
}
const body = tableEl.createEl('tbody')
for (let i = 0; i < rows.length; i++) {
const rowEl = body.createEl('tr')
for (let j = 0; j < columns.length; j++) {
rowEl.createEl('td', {
text: rows[i][columns[j].columnName],
attr: { scope: columns[j].columnName.toLowerCase() === 'id' ? 'row' : undefined }
})
}
}
}
buildTableDescription(table: Array<string>) {
const indices: Array<any> = []
const header = table[0]
const rows = []
const headerEntries = header.split(' ').filter(word => !!word)
let previousHeaderIndex = 0
for(let headerEntryIndex = 0; headerEntryIndex < headerEntries.length; headerEntryIndex++) {
let stringToFind = headerEntries[headerEntryIndex]
let stringFound = false
for (let charIndex = previousHeaderIndex; charIndex <= table[0].length; charIndex++) {
if (!stringFound && header.slice(previousHeaderIndex, charIndex) === stringToFind) {
stringFound = true
}
if (stringFound && header[charIndex] !== ' ') {
indices.push({ columnName: stringToFind.trim(), startIndex: previousHeaderIndex, endIndex: charIndex, columnIndex: headerEntryIndex })
previousHeaderIndex = charIndex
break
}
}
}
for(let rowIndex = 1; rowIndex < table.length; rowIndex++) {
let rowObj: Record<string, any> = {}
for (let columnIndex = 0; columnIndex < indices.length; columnIndex++) {
if (columnIndex !== indices.length - 1) {
rowObj[indices[columnIndex].columnName] = table[rowIndex].slice(indices[columnIndex].startIndex, indices[columnIndex].endIndex).trim()
} else {
rowObj[indices[columnIndex].columnName] = table[rowIndex].slice(indices[columnIndex].startIndex).trim()
}
}
rows.push(rowObj)
}
return [indices, rows]
}
buildCommand(commandString: string) {
const reports = this.getReportNames()
commandString = commandString.replace(/^task /, '')
const report = commandString.split(' ').slice(-1)[0]
const taskwarriorBin = this.settings.taskBinaryPath
if (reports.includes(report)) {
if (!commandString.contains('rc.defaultwidth:')) commandString = `rc.defaultwidth:1000 ${commandString}`
if (!commandString.contains('rc.detection:')) commandString = `rc.detection:off ${commandString}`
return `${taskwarriorBin.trim()} ${commandString}`
} else {
throw new Error(`Taskwarrior command must be a report, was: ${report}.`)
}
}
filterOutputToTable(output: Buffer) {
return output.toString().split('\n')
.filter((line) => {
if (line.match(/^[ -]*$/)) return false
if (line.match(/^\d+ tasks*$/)) return false
if (line.match(/^\d+ tasks, \d+ shown*$/)) return false
return true
})
}
doCommand(commandString: string, raw: boolean, processor: any, errorProcessor: any, processorArgs: any) {
let asciiTable
try {
asciiTable = this.filterOutputToTable(execSync(this.buildCommand(commandString)))
} catch (error) {
return errorProcessor.call(this, error, ...processorArgs)
}
return processor.call(this, raw ? asciiTable.join('\n') : this.buildTableDescription(asciiTable), ...processorArgs)
}
getReport(report: string) {
return this.getReports().reduce((result, line) => {
const regex = RegExp(`report\.${report}\.([^ ]*) +(.+)`)
const matches = regex.exec(line)
if (matches) {
result[matches[1].toString()] = matches[2]
return result
} else {
return result
}
}, {} as Record<string, string>)
}
getReports() {
const taskwarriorBin = this.settings.taskBinaryPath
return execSync(`${taskwarriorBin} show report`).toString().split('\n').filter(line => line.match(/^report\..+/))
}
getReportNames() {
return this.getReports().reduce((result, line) => {
const matches = /^[^\.]+\.([^\.]+).*/.exec(line)
if (matches && matches[1] && !result.includes(matches[1]))
return [ ...result, matches[1] ]
return result
}, [] as String[])
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData())
}
async saveSettings() {
await this.saveData(this.settings)
}
}