syncthing-hooks/hooks.js

62 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

2020-03-18 00:30:56 +01:00
const fs = require('fs').promises;
const ms = require('ms');
const os = require('os');
const path = require('path');
2020-03-18 18:57:56 +01:00
const { spawn } = require('child_process');
2021-04-30 00:39:34 +02:00
const { getEnvVar } = require('./env.js');
2020-03-18 00:30:56 +01:00
2021-04-30 00:57:38 +02:00
const getHooksRoot = () => getEnvVar('ST_HOOK_ROOT', path.join(os.homedir(), '/.syncthing-hooks'))
2020-03-18 00:30:56 +01:00
const readHooksRoot = async root => {
try {
const files = await fs.readdir(root);
return files;
2020-03-18 18:57:56 +01:00
} catch (error) {
console.error(error);
2020-03-18 00:30:56 +01:00
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);
};
2020-03-18 18:57:56 +01:00
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],
})
);
2020-03-18 00:30:56 +01:00
module.exports = {
collectHooks,
2020-03-18 18:57:56 +01:00
runHook,
2020-03-18 00:30:56 +01:00
};