-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
84 lines (73 loc) · 1.88 KB
/
app.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
73
74
75
76
77
78
79
80
81
82
83
84
import readline from 'readline'
import { rename } from 'fs'
import * as fsScandir from '@nodelib/fs.scandir'
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
const settings = new fsScandir.Settings({ stats: true })
export function getRootDir(question: string): Promise<string> {
return new Promise((resolve, reject) => {
try {
rl.question(question, (dir) => resolve(dir))
} catch (error) {
reject(error)
}
})
}
type TContentItem = {
dirent: fsScandir.Dirent
name: string
path: string
}
export function getDirContents(path: string): Promise<TContentItem[]> {
return new Promise((resolve, reject) => {
fsScandir.scandir(path, settings, (error, entries) => {
if (error) {
reject(error)
}
resolve(entries)
})
})
}
function onlyDirs(item: TContentItem) {
return item.dirent.isDirectory()
}
function onlyFiles(item: TContentItem) {
return item.dirent.isFile()
}
function moveFile(basePath: string, rootDir: string) {
return new Promise(async (_resolve, reject) => {
const contents = await getDirContents(basePath)
const hasFiles = contents.length > 0
if (hasFiles) {
const {
path: oldPath,
dirent: { name },
} = contents[0]
rename(oldPath, `${rootDir}/${name}`, (err) => reject(err))
}
})
}
function moveFiles(dirs: TContentItem[], rootDir: string) {
const len = dirs.length
for (let index = 0; index < len; index++) {
const dir = dirs[index]
moveFile(dir.path, rootDir)
if (index === len) {
rl.close()
}
}
}
async function main() {
try {
const rootDir = await getRootDir('Enter root directory name\n')
const rootDirContents = await getDirContents(rootDir)
const dirs = rootDirContents.filter(onlyDirs)
moveFiles(dirs, rootDir)
} catch (error) {
console.error(error)
rl.close()
}
}
main()