96 lines
2.7 KiB
TypeScript
96 lines
2.7 KiB
TypeScript
import fs from "fs";
|
|
import path from "path";
|
|
import util from "util";
|
|
import { exec } from "child_process";
|
|
import { SyncFoldersSyncFnParams } from "../types";
|
|
|
|
const execPromise = util.promisify(exec);
|
|
|
|
export default async function sync({
|
|
options,
|
|
dirs,
|
|
dirPath,
|
|
isFiles,
|
|
firstRun,
|
|
}: SyncFoldersSyncFnParams) {
|
|
const dstDirs = dirs.filter((dr) => {
|
|
if (typeof dr == "string") return dr !== dirPath;
|
|
if (dr?.path) return dr.path !== dirPath;
|
|
return false;
|
|
});
|
|
|
|
const rsyncTrailingSlash = isFiles ? "" : "/";
|
|
|
|
const allCommandsArr: string[][] = [];
|
|
|
|
for (let j = 0; j < dstDirs.length; j++) {
|
|
const dstDr = dstDirs[j];
|
|
|
|
let cmdArray = ["rsync", firstRun ? "-az" : "-azu", "--inplace"];
|
|
|
|
if (options?.delete) {
|
|
cmdArray.push("--delete");
|
|
}
|
|
|
|
if (options?.include?.[0]) {
|
|
options.include.forEach((incl) => {
|
|
cmdArray.push(`--include='${incl}'`);
|
|
});
|
|
}
|
|
|
|
if (options?.exclude?.[0]) {
|
|
options.exclude.forEach((excl) => {
|
|
cmdArray.push(`--exclude='${excl}'`);
|
|
});
|
|
}
|
|
|
|
if (typeof dstDr == "string") {
|
|
if (!fs.existsSync(dstDr)) continue;
|
|
|
|
if (dirPath === dstDr) {
|
|
console.log(
|
|
`You can't sync the same paths. Please check your configuration and resolve duplicate paths`
|
|
);
|
|
process.exit(6);
|
|
}
|
|
|
|
cmdArray.push(
|
|
path.normalize(dirPath) + rsyncTrailingSlash,
|
|
path.normalize(dstDr) + rsyncTrailingSlash
|
|
);
|
|
} else if (dstDr.path) {
|
|
if (!dstDr.host && !fs.existsSync(dstDr.path)) continue;
|
|
|
|
if (dirPath === dstDr.path) {
|
|
console.log(
|
|
`You can't sync the same paths. Please check your configuration and resolve duplicate paths`
|
|
);
|
|
process.exit(6);
|
|
}
|
|
|
|
if (dstDr.host && dstDr.ssh_key && dstDr.user) {
|
|
cmdArray.push("-e", `'ssh -i ${dstDr.ssh_key}'`);
|
|
cmdArray.push(
|
|
path.normalize(dirPath) + rsyncTrailingSlash,
|
|
`${dstDr.user}@${dstDr.host}:${dstDr.path}${rsyncTrailingSlash}`
|
|
);
|
|
} else {
|
|
cmdArray.push(
|
|
path.normalize(dirPath),
|
|
path.normalize(dstDr.path)
|
|
);
|
|
}
|
|
}
|
|
|
|
allCommandsArr.push(cmdArray);
|
|
}
|
|
|
|
await Promise.all(
|
|
allCommandsArr.map((cmdArr) => {
|
|
return execPromise(cmdArr.join(" "));
|
|
})
|
|
);
|
|
|
|
console.log(`${dirPath} Folder Sync Complete. Exiting ...`);
|
|
}
|