-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (60 loc) · 1.68 KB
/
index.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
62
63
64
65
66
67
'use strict';
const fs = require('fs-extra');
const path = require('path');
const globby = require('globby');
const deleteEmpty = require('delete-empty');
const defaults = {
rename: basename => {
if (/-\d$/.test(basename)) {
let arr = basename.split('-');
arr[arr.length - 1] = Number(arr[arr.length - 1]) + 1;
return arr.join('-');
}
return `${basename}-1`;
},
};
module.exports = async (dir, opts) => {
if (dir) {
dir = path.resolve(dir);
} else {
dir = process.cwd();
}
opts = Object.assign({}, defaults, opts);
const files = await globby(dir, {
expandDirectories: {
files: ['*'],
},
noext: true
});
const dirs = await globby(dir, { onlyDirectories: true, noext: true });
for (let i = 0; i < files.length; i++) {
let file = path.basename(files[i]);
if (path.relative(dir, files[i]) === file) {
continue;
}
moveFile(files[i], file, dir, opts);
}
for (let i = 0; i < dirs.length; i++) {
try {
if (fs.existsSync(dirs[i])) {
deleteEmpty.sync(dirs[i]);
}
} catch (err) {
console.error(err);
}
}
};
function moveFile(originalPath, basename, dir, opts) {
if (!fs.existsSync(path.join(dir, basename))) {
try {
fs.moveSync(originalPath, path.join(dir, basename));
} catch (err) {
console.error(err);
}
return;
}
let fileObj = path.parse(basename);
let name = opts.rename(fileObj.name);
name = name + fileObj.ext;
moveFile(originalPath, name, dir, opts);
}