-
Notifications
You must be signed in to change notification settings - Fork 0
/
move.ts
72 lines (63 loc) · 2.1 KB
/
move.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
import path from 'path';
import fs from 'fs-extra';
import { absolute, exists } from '~/utils/file';
import { IFsWriteOptions } from './types';
import expose from '~/utils/expose';
import confirm from '~/utils/confirm';
import logger from '~/utils/logger';
export default expose(move);
/**
* Move files or directories. If an array of paths is passed as `src`, `dest` will be expected to be a directory.
* It is an *exposed* function: call `move.fn()`, which takes the same arguments, in order to execute on call.
* @returns An asynchronous function -hence, calling `move` won't have any effect until the returned function is called.
*/
function move(
src: string | string[] | Promise<string | string[]>,
dest: string,
options: IFsWriteOptions = {}
): () => Promise<void> {
return async () => {
src = await src;
if (Array.isArray(src)) {
for (let source of src) {
await trunk(source, path.join(dest, path.parse(source).base), options);
}
} else {
await trunk(src, dest, options);
}
};
}
/** @hidden */
export async function trunk(
src: string,
dest: string,
options: IFsWriteOptions
): Promise<void> {
options = Object.assign({ overwrite: true }, options);
const cwd = process.cwd();
src = absolute({ path: src, cwd });
dest = absolute({ path: dest, cwd });
const relatives = {
src: './' + path.relative(cwd, src),
dest: './' + path.relative(cwd, dest)
};
const srcExist = await exists(src, { fail: options.fail });
if (!srcExist) {
logger.info(`Move skipped: "${relatives.src}" to "${relatives.dest}"`);
return;
}
const destExists = await exists(dest);
if (destExists) {
if (options.fail) {
throw Error(`Destination already exists: ${relatives.dest}`);
}
if (!options.overwrite) {
logger.info(`Move skipped: "${relatives.src}" to "${relatives.dest}"`);
return;
}
}
const msg = `Move "${relatives.src}" to "${relatives.dest}"?`;
if (!(await confirm(msg, options))) return;
await fs.move(src, dest, { overwrite: options.overwrite });
logger.info(`Moved: "${relatives.src}" to "${relatives.dest}"`);
}