-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.ts
271 lines (249 loc) · 8.27 KB
/
run.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
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
import { Args, Flags, flush, handle } from '@oclif/core'
import { each, eachSeries, ErrorCallback } from 'async'
import { exec, ExecException } from 'child_process'
import { formatDuration, intervalToDuration } from 'date-fns'
import { Vault } from 'obsidian-utils'
import { CommandsExecutedOnVaults } from '../../commands'
import FactoryCommand, { FactoryFlags } from '../../providers/command'
import { safeLoadConfig } from '../../providers/config'
import { vaultsSelector } from '../../providers/vaults'
import {
RESERVED_VARIABLES,
VAULTS_PATH_FLAG_DESCRIPTION,
} from '../../utils/constants'
import {
CUSTOM_COMMAND_LOGGER_FILE,
customCommandLogger,
logger,
} from '../../utils/logger'
interface CommandArgs {
[key: string]: string
}
interface RunFlags {
path: string
output: string
unescape: boolean
async: boolean
silent: boolean
runFromVaultDirectoryAsWorkDir: boolean
}
interface ExecuteCustomCommandResult {
stdout: string
stderr: string
error: ExecException | null
}
export default class Run extends FactoryCommand {
static readonly aliases = ['r', 'run', 'vr', 'vaults run']
static override readonly description = `Run a shell command on selected vaults (using Node.js child_process).\nDisclaimer: Any input containing shell metacharacters may be used to trigger arbitrary command execution, using of this command is at risk of command's caller.`
static override readonly examples = [
'<%= config.bin %> <%= command.id %> --path=/path/to/vaults',
'<%= config.bin %> <%= command.id %> --path=/path/to/vaults/*/.obsidian --output=json',
'<%= config.bin %> <%= command.id %> --path=/path/to/vaults/**/.obsidian --output=json --unescape=false',
'<%= config.bin %> <%= command.id %> --output=json --async=false',
'<%= config.bin %> <%= command.id %> --output=json --silent=true',
'<%= config.bin %> <%= command.id %> --output=json --runFromVaultDirectoryAsWorkDir=false',
]
static override readonly flags = {
path: Flags.string({
char: 'p',
description: VAULTS_PATH_FLAG_DESCRIPTION,
default: '',
}),
output: Flags.string({
char: 'o',
description: 'Display the output with a specific transformer.',
default: 'table',
options: ['table', 'json'],
}),
unescape: Flags.boolean({
char: 'u',
description:
'Unescape special characters in a command to run as a single command.',
default: true,
}),
async: Flags.boolean({
char: 'a',
description: 'Run the command in parallel on the vault(s).',
default: true,
}),
silent: Flags.boolean({
char: 's',
description: 'Silent on results of the custom command on vault(s).',
default: false,
}),
runFromVaultDirectoryAsWorkDir: Flags.boolean({
char: 'r',
description: 'Run the command from the vault directory as working dir.',
default: true,
}),
...this.commonFlags,
}
static override readonly args = {
command: Args.string({
description:
'Command to run and use specified vaults with each execution.',
required: true,
}),
}
/**
* Executes the command.
* Parses the arguments and flags, and calls the action method.
* Handles errors and ensures flushing of logs.
*/
public async run() {
try {
const { args, flags } = await this.parse(Run)
await this.action(args, this.flagsInterceptor(flags))
} catch (error) {
this.handleError(error)
} finally {
flush()
}
}
/**
* Main action method for the command.
* Loads vaults, selects vaults, and gets stats about number of vaults and installed plugins per vault.
* @param {ArgInput} args - The arguments passed to the command.
* @param {FactoryFlags<RunFlags>} flags - The flags passed to the command.
* @returns {Promise<void>}
*/
private async action(
args: CommandArgs,
flags: FactoryFlags<RunFlags>,
): Promise<void> {
const { command } = args
const { path, output } = flags
const { success: loadConfigSuccess, error: loadConfigError } =
await safeLoadConfig(flags.config)
if (!loadConfigSuccess) {
logger.error('Failed to load config', { error: loadConfigError })
process.exit(1)
}
const vaults = await this.loadVaults(path)
const selectedVaults = await vaultsSelector(vaults)
const vaultsWithCommand = selectedVaults.map((vault: Vault) => ({
vault,
command: this.commandInterpolation(vault, command),
}))
const taskExecutedOnVaults: CommandsExecutedOnVaults = {}
const commandVaultIterator = async (opts: {
vault: Vault
command: CommandArgs['command']
}) => {
const { vault, command } = opts
logger.debug(`Execute command`, { vault, command })
try {
const startDate = new Date()
const result = await this.asyncExecCustomCommand(
command,
flags.runFromVaultDirectoryAsWorkDir,
vault,
)
const endDate = new Date()
const durationLessThanSecond = endDate.getTime() - startDate.getTime()
const durationMoreThanSecond = intervalToDuration({
start: startDate,
end: endDate,
})
const formattedDuration =
formatDuration(durationMoreThanSecond, {
format: ['hours', 'minutes', 'seconds'],
}) || `${durationLessThanSecond} ms`
taskExecutedOnVaults[vault.name] = {
success: null,
duration: formattedDuration,
error: null,
}
if (result) {
taskExecutedOnVaults[vault.name]['success'] = true
customCommandLogger.info('Executed successfully', {
result,
vault,
command,
})
if (!flags.silent) {
logger.info(`Run command`, { vault, command })
console.log(result)
}
}
} catch (error) {
taskExecutedOnVaults[vault.name]['error'] = JSON.stringify(error)
customCommandLogger.error('Execution failed', {
error: JSON.stringify(error),
vault,
command,
})
}
}
const commandVaultErrorCallback: ErrorCallback<Error> = (
error: Error | null | undefined,
) => {
if (error) {
logger.debug('UnhandledException', {
error: JSON.stringify(error),
path,
})
handle(error)
return error
} else {
const sortedTaskExecutedOnVaults = Object.entries(taskExecutedOnVaults)
.sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
.reduce((acc, [key, value]) => {
acc[key] = value
return acc
}, {} as CommandsExecutedOnVaults)
logger.info('Run operation finished!', {
custom_commands_log_path: CUSTOM_COMMAND_LOGGER_FILE,
})
if (output === 'table') {
console.table(sortedTaskExecutedOnVaults)
} else if (output === 'json') {
console.log(JSON.stringify(sortedTaskExecutedOnVaults, null, 2))
}
}
}
customCommandLogger.debug('Running command on selected vaults...', {
vaults: vaultsWithCommand.length,
})
if (flags.async) {
each(vaultsWithCommand, commandVaultIterator, commandVaultErrorCallback)
} else {
eachSeries(
vaultsWithCommand,
commandVaultIterator,
commandVaultErrorCallback,
)
}
}
private async asyncExecCustomCommand(
command: string,
runFromVaultDirectoryAsWorkDir: boolean,
vault: Vault,
): Promise<Pick<ExecuteCustomCommandResult, 'error'> | string> {
return new Promise((resolve, reject) => {
exec(
command,
{ cwd: runFromVaultDirectoryAsWorkDir ? vault.path : __dirname },
(error, stdout, stderr) => {
if (error) {
return reject(error)
}
resolve(`${stderr}\n${stdout}`)
},
)
})
}
private commandInterpolation(vault: Vault, command: string): string {
const variableRegex = /\{(\d*?)}/g
const replacer = (match: string, variable: string) => {
const variableFunction = RESERVED_VARIABLES[variable]
if (variableFunction) {
return variableFunction(vault)
} else {
return match
}
}
const interpolatedCommand = command.replace(variableRegex, replacer)
return interpolatedCommand
}
}