forked from terminalnetwork/syncthing-hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hooks.js
61 lines (54 loc) · 1.43 KB
/
hooks.js
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
const fs = require('fs').promises;
const ms = require('ms');
const os = require('os');
const path = require('path');
const { spawn } = require('child_process');
const { getEnvVar } = require('./env.js');
const getHooksRoot = () => getEnvVar('ST_HOOK_ROOT', path.join(os.homedir(), '/.syncthing-hooks'))
const readHooksRoot = async root => {
try {
const files = await fs.readdir(root);
return files;
} catch (error) {
console.error(error);
return [];
}
};
const parseHooks = (root, hooks) =>
hooks
.map(x => ({
path: path.join(root, x),
match: x.match(/(?<folder>.{11})-(?<time>.*)/),
}))
.filter(x => x.match)
.map(x => ({
path: x.path,
folder: x.match.groups.folder,
time: ms(x.match.groups.time),
}));
const collectHooks = async () => {
const root = getHooksRoot();
const hooks = await readHooksRoot(root);
return parseHooks(root, hooks);
};
const waitForProcess = childProcess =>
new Promise((resolve, reject) => {
childProcess.once('exit', code =>
code === 0
? resolve(null)
: reject(new Error(`hook failed with code: ${code}`))
);
childProcess.once('error', error => reject(error));
});
const runHook = hook =>
waitForProcess(
spawn(hook.path, [], {
cwd: path.dirname(hook.path),
shell: true,
stdio: [process.stdin, process.stdout, process.stderr],
})
);
module.exports = {
collectHooks,
runHook,
};