Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow specifying multiple source directories and target directories #13

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
module.exports = {
env: {
browser: true,
commonjs: true,
es2021: true,
mocha: true,
},
extends: [
'standard',
'plugin:mocha/recommended',
],
parserOptions: {
ecmaVersion: 12,
},
rules: {
indent: ['error', 4, { SwitchCase: 1 }],
quotes: ['error', 'single'],
semi: ['error', 'always'],
'comma-dangle': ['error', 'only-multiline', { functions: 'never' }],
'space-before-function-paren': ['error', {
anonymous: 'always',
named: 'never',
asyncArrow: 'always'
}],
'node/no-callback-literal': 'off',
},
plugins: [
'mocha',
]
};
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/.git
node_modules/*
.DS_Store
test/*
test-*
28 changes: 28 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Mocha Tests",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"--reporter",
"dot",
"--slow",
"5000",
"--timeout",
"999999999999",
"--colors",
"${workspaceFolder}/test/**/*.js",
],
"internalConsoleOptions": "openOnSessionStart",
"skipFiles": [
"<node_internals>/**"
]
}
]
}
26 changes: 21 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,33 @@ npm i sync-directory -g
```

```bash
syncdir <from> <to> [options]
syncdir [<from> <to>] [options]
```

Example: `syncdir aaa bbb -w`
Example:

Sync from `aaa` to `bbb`: `syncdir aaa bbb -w`

Sync from `aaa` to `bbb` and `ccc` to `ddd`: `syncdir -i aaa -o bbb -i ccc -o ddd -w`

options:

+ `-i, --source`

Source directory. Can be specified multiple times to sync several source directories.

Same as api `srcDirs`.

+ `-o, --target`

Target directory. Can be specified multiple times to sync several target directories. The target directories are paired with source directories in order.

Same as api `targetDirs`.

+ `-w, --watch`

Watch changes. `false` as default.

Same as api `watch`.

+ `-do, --deleteOrphaned`
Expand Down Expand Up @@ -56,8 +72,8 @@ require('sync-directory')(srcDir, targetDir[, config]);

name | description | type | values | default
---- | ---- | ---- | ---- | ----
`srcDir` | src directory | String | absolute path | -
`targetDir` | target directory | String | absolute path | -
`srcDirs` | src directory(s) | String/String[] | absolute path(s) | -
`targetDirs` | target directory(s) | String/String[] | absolute path(s) | -
`config.watch` | watch files change | Boolean | - | false
`config.type` | way to sync files | String | `'copy' / 'hardlink'` | `'hardlink'`
`config.deleteOrphaned` | Decide if you want to delete other files in targetDir when srcDir files are removed | Boolean | - | true
Expand Down
108 changes: 74 additions & 34 deletions cmd.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,54 @@
#!/usr/bin/env node
'use strict';

const path = require('path');
const fs = require('fs');
const commander = require('commander');
const isAbsoluteUrl = require('is-absolute');
const run = require('./index');

const parseArgs = (args) => {
const options = {};
let from = '';
let to = '';
let pathSetWithPositionalArg = false;
let pathSetWithNamedArg = false;
const froms = [];
const tos = [];

function readPathFromArg(arg, msg) {
if (arg == null) {
console.error('Error when reading ' + msg + ': a path is required.');
process.exit(-1);
}
if (arg.startsWith('-')) {
console.error('Error when reading ' + msg + ': a path-like string is expected when "' + arg + '" is given.');
process.exit(-1);
}
return arg;
}

for (let i = 0, len = args.length; i < len; i++) {
const item = args[i];

if (/^\-/.test(item)) {
switch(item) {
if (/^-/.test(item)) {
switch (item) {
case '-i':
case '--source':
if (pathSetWithPositionalArg) {
console.error('');
process.exit(-1);
}
froms.push(readPathFromArg(args[i + 1], 'source path'));
i += 1;
pathSetWithNamedArg = true;
break;
case '-o':
case '--target':
if (pathSetWithPositionalArg) {
console.error('');
process.exit(-1);
}
tos.push(readPathFromArg(args[i + 1], 'target path'));
i += 1;
pathSetWithNamedArg = true;
break;
case '-w':
case '--watch':
options.watch = true;
Expand All @@ -33,18 +65,26 @@ const parseArgs = (args) => {
case '--copy':
options.copy = true;
}
} else {
if (!from) {
from = item;
} else if (!to) {
to = item;
} else if (!pathSetWithNamedArg) {
if (froms.length === 0) {
froms.push(item);
pathSetWithPositionalArg = true;
} else if (tos.length === 0) {
tos.push(item);
pathSetWithPositionalArg = true;
} else {
console.error('Cannot set more than one path using positional argument. Use --source <source_path1> --target <target_path1> --source <source_path2> --target <target_path2> instead.');
process.exit(-1);
}
} else {
console.error('Cannot mix positional path argument with "--input/output".');
process.exit(-1);
}
}

return {
from,
to,
froms,
tos,
watch: !!options.watch,
deleteOrphaned: !!options.deleteOrphaned,
supportSymlink: !!options.supportSymlink,
Expand All @@ -54,51 +94,51 @@ const parseArgs = (args) => {

// error on unknown commands
commander.on('command:*', function () {
let { from, to, watch, deleteOrphaned, supportSymlink, type } = parseArgs(commander.args);
const cwd = process.cwd();
const { froms, tos, watch, deleteOrphaned, supportSymlink, type } = parseArgs(commander.args);

if (!from) {
console.error(`missing source folder path`);
process.exit(1);
}

if (!to) {
console.error(`missing target folder path`);
if (froms.length === 0) {
console.error('missing source folder path');
process.exit(1);
}

if (!isAbsoluteUrl(from)) {
from = path.join(cwd, from);
if (tos.length === 0) {
console.error('missing target folder path');
process.exit(1);
}

if (!isAbsoluteUrl(to)) {
to = path.join(cwd, to);
if (froms.length !== tos.length) {
console.error('the number of source folder paths must match the number of target folder paths');
process.exit(1);
}

if (!fs.existsSync(from)) {
console.error('source folder does not exist.');
process.exit(1);
for (let i = 0; i < froms.length; i++) {
if (!fs.existsSync(froms[i])) {
console.error('source folder does not exist.');
process.exit(1);
}
}

console.log('');
console.log('sync-directory cli options: ');
console.log(' - from: ', from);
console.log(' - to: ', to);
for (let i = 0; i < froms.length; i++) {
console.log(' - from[' + i + ']: ', froms[i]);
console.log(' - to[' + i + ']: ', tos[i]);
}
console.log(' - watch:', watch);
console.log(' - deleteOrphaned:', deleteOrphaned);
console.log(' - type: ', type);
console.log(' - supportSymlink: ', supportSymlink);
console.log('');

run(from, to, {
run(froms, tos, {
watch,
type,
deleteOrphaned,
afterSync({ type, relativePath }) {
console.log(`${type}: `, relativePath);
}
},
});
});

commander.allowUnknownOption();
commander.parse(process.argv);
commander.parse(process.argv);
67 changes: 50 additions & 17 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,70 @@
const path = require('path');
const syncLocalFiles = require('./lib/local-syncfiles');
const watchLocalFiles = require('./lib/local-watch');
const isAbsoluteUrl = require('is-absolute');
const fse = require('fs-extra');

// Copied from https://stackoverflow.com/a/42355848
const isChildOf = (child, parent) => {
if (child === parent) return false;
const parentTokens = parent.split('/').filter(i => i.length);
return parentTokens.every((t, i) => child.split('/')[i] === t);
};

/**
* Sync directories
* @param {string[] | string} srcDirs Source directory(s)
* @param {string[] | string} targetDirs Target directory(s)
* @param {import("./types").Configuration} [config] Configuration
*/
module.exports = (
srcDir,
targetDir,
{
srcDirs,
targetDirs,
{
type = 'hardlink',
forceSync = () => {},
forceSync = () => { },
exclude = null,
watch = false,
deleteOrphaned = true,
supportSymlink = false,
cb = () => { },
afterSync = () => {},
cb = () => { },
afterSync = () => { },
filter = () => true,
onError = (err) => { throw new Error(err) }
onError = (err) => { throw new Error(err); },
} = {}
) => {
// check absolute path
if (!isAbsoluteUrl(srcDir) || !isAbsoluteUrl(targetDir)) {
console.log('[sync-directory] "srcDir/targetDir" must be absolute path.');
return;
if (typeof srcDirs === 'string') {
srcDirs = [srcDirs];
}
if (typeof targetDirs === 'string') {
targetDirs = [targetDirs];
}
if (srcDirs.length !== targetDirs.length) {
throw new Error('[sync-directory] the number of source folder paths must match the number of target folder paths');
}
for (let i = 0; i < srcDirs.length; i++) {
if (!isAbsoluteUrl(srcDirs[i])) {
srcDirs[i] = path.resolve(srcDirs[i]);
}

fse.ensureDirSync(targetDir);

syncLocalFiles(srcDir, targetDir, { type, exclude, forceSync, afterSync, deleteOrphaned, supportSymlink, filter, onError });
if (!isAbsoluteUrl(targetDirs[i])) {
targetDirs[i] = path.resolve(targetDirs[i]);
}
}
for (let i = 0; i < srcDirs.length; i++) {
for (let j = i + 1; j < srcDirs.length; j++) {
const srcDir = srcDirs[i];
const srcDir2 = srcDirs[j];
if (isChildOf(srcDir, srcDir2) || isChildOf(srcDir2, srcDir)) {
throw new Error('[sync-directory] "srcDir"s must not overlap.');
}
}
}
syncLocalFiles(srcDirs, targetDirs, { type, exclude, forceSync, afterSync, deleteOrphaned, supportSymlink, filter, onError });

if (watch) {
const watcher = watchLocalFiles(srcDir, targetDir, { type, exclude, forceSync, cb, afterSync, deleteOrphaned, filter, onError });
const watcher = watchLocalFiles(srcDirs, targetDirs, { type, exclude, forceSync, cb, afterSync, deleteOrphaned, filter, onError });
return watcher;
} else {
return undefined;
}

};
2 changes: 1 addition & 1 deletion lib/config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module.exports = {
ignoredSymlinkDirs: [],
};
};
Loading