-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
346 lines (296 loc) · 7.83 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
'use strict'
const splitEvery = require('ramda/src/splitEvery')
const findIndex = require('ramda/src/findIndex')
const remove = require('ramda/src/remove')
const reduce = require('ramda/src/reduce')
const append = require('ramda/src/append')
const ps = require('windows-powershell')
const split = require('ramda/src/split')
const spawn = require('buffered-spawn')
const pipe = require('ramda/src/pipe')
const { relative } = require('path')
const walk = require('fswalk')
const wmicArgs = [
'freeSpace',
'size'
]
/**
* Gets various information about all the drives mounted on a given
* `computer`
*
* @param {String} computer - Computer name
* @return {Promise} - Resolves to `{ json, stdout, stderr }`
*
* @example
* statDrives('computer-name').then(log)
* // -> [{ deviceID: 'C:', freeSpace: 4324564, ...}, ...]
*/
function statDrives (computer) {
const cmd = ps.pipe(
`get-wmiobject Win32_LogicalDisk -computerName ${computer}`,
'where -property DriveType -eq 3'
)
return ps.shell(ps.toJson(cmd))
}
/**
* Mounts a network drive to the next available drive letter and returns a
* the drive letter which it was mounted on.
*
* @param {String} unc - A UNC path like `//server`
* @param {String} path - A path like `some/path/to/folder`
* @param {Object} [credentials] - `user` and `password` to log into a network
* @returns {Promise} - Resolves to the drive letter which the path was
* mounted on, rejects when the command fails
*
* @example
* // (given letter Y: is free)
* mount('server', 'c$')
* .then(log)
* .catch((err) => console.error('failed to mount', err))
* // -> Y:
*/
function mount (unc, path, credentials) {
if (!unc && !path) {
throw new Error('No `unc` or `path` specified')
}
let args = ['use', '*', toUncPath(unc, path)]
if (credentials) {
if (!credentials.user || !credentials.password) {
throw new Error(
'Please specifiy both `user` and `password` keys for credentials'
)
}
args.push(`/user:${credentials.user}`)
args.push(credentials.password)
}
return spawn('net', args)
.then((io) => parseDriveLetter(io.stdout))
}
/**
* Unmounts a network drive given a `letter` and returns the `letter`.
*
* @param {String} letter - Network drive letter
* @returns {Promise} - Resolves to the drive letter when successful, rejects
* when the command fails
*
* @example
* // (given letter Z: is mounted)
* unmount('Z:')
* .then(log)
* .catch((err) => console.error('failed to unmount', err))
* // -> Z:
*/
function unmount (letter) {
if (!letter) {
throw new Error('No Letter specified')
}
const proc = spawn(
'net',
['use', letter, '/delete']
)
return proc.then(() => letter)
}
/**
* Gets a list of mounted drive letters and their respective unc paths.
*
* @return {Array} - Array of { unc, letter } tuples
*/
function mountedDrives () {
return spawn('net', ['use'])
.then((io) => {
return pipe(
//split into lines
split('\n'),
// remove header
remove(0, 6),
// parse command
reduce((acc, line) => {
const status = parseStatus(line)
// remove if no status
if (status == null) return acc
const letter = parseDriveLetter(line)
// remove `Microsoft Windows Network` lines
if (letter == null) return acc
const unc = parseUNC(line)
return append({ letter, unc }, acc)
}, [])
)(io.stdout)
})
}
/**
* Checks if a given `unc` path is already mounted. If it's mounted returns
* the drive letter otherwise returns undefined.
*
* @param {String} unc - Unc like path `server/share$`
* @return {String|undefined} - The drive letter or if not found `undefined`
*
* @example
* isMounted('server/share$')
* .then((letter) => {
* // mounted network drive hasn't been found
* if (!letter) return
* // found
* })
*/
function isMounted (unc) {
unc = toWindowsPath(toUnc(unc))
return mountedDrives()
.then((drives) => {
const i = findIndex((el) => el.unc == unc, drives)
return i != -1
? drives[i].letter
: undefined
})
}
/**
* Gets stats by a given drive `letter` like the current size of the hdd etc.
* This also works for drives in a network. Use `statDrives()` when their are
* no login credentials, otherwise use this function to avoid firewall
* settings.
*
* @param {String} letter - The drive letter which the hdd was mounted on
* @return {Promise} - A promise which resolves to `{ freeSpace, size }`
*
* @example
* statByDriveLetter('Z:')
* // -> { freeSpace: 10700152832, size: 53579083776 }
*/
function statByDriveLetter (letter) {
const procs = wmicArgs.map(
(arg) => {
return spawn(
'wmic',
['logicaldisk', 'where', `DeviceID="${letter}"`, 'get', arg]
).then((io) => {
let obj = {}
obj[arg] = Number(parseNumber(io.stdout))
return obj
})
}
)
return Promise.all(procs)
.then((stats) => {
return stats.reduce((acc, stat) => Object.assign(acc, stat), {})
})
}
/**
* Gets various metadata about the directory and the files in it using
* a recursive walk.
*
* @param {String} path - Absolute path
* @returns {Object} - Object with `size` (directory size in bytes),
* `count` (file count) and `files` (list of files in the directory and their
* respective metadata)
*
* @example
* statDirectory('c:/temp/log')
* // -> { count: 4, size: 32636, files: [{ name: '...' }, ...]}
*/
function statDirectory (path) {
path = toWindowsPath(path)
return new Promise((resolve, reject) => {
let count = 0
let size = 0
let files = []
walk(path, onFile, onFinish)
function onFile (file, stats) {
files.push(Object.assign({name: relative(path, file)}, stats))
count += 1
size += stats.size
}
function onFinish (err) {
if (err) return reject(err)
resolve({root: path, size, count, files})
}
})
}
/**
* Replaces `/` with `\` so we can use an unix path and convert it to a
* windows path.
*
* @param {String} path - Unix style path
* @returns {String} - Windows style path
*
* @example
* toWindowsPath('some/random/folder')
* // -> some\random\folder
*/
function toWindowsPath (path) {
return path.replace(/\//g, '\\')
}
/**
* Creates a windows path given a `server` name and a unix `path`.
*
* @param {String} server - Server name
* @param {String} share - Path
*
* @example
* toUncPath('server', 'some/path/to/a/log')
* // -> `\\server\some\path\to\a\log`
*/
function toUncPath (server, share) {
return toWindowsPath(`${toUnc(server)}/${share}`)
}
/**
* Parses a number out of a given `str`.
*
* @private
*/
function parseNumber (str) {
return /\d+/.exec(str)[0]
}
/**
* Parses a given `str` for drive letters like `Z:`. Returns null if not found.
*
* @private
*
* @example
* parseDriveLetter('a String with the letter Y: in it')
* // -> Y:
*/
function parseDriveLetter (str) {
const re = /([A-Z]):/
if (re.test(str)) {
return re.exec(str)[0]
} else {
return null
}
}
/**
* Parses the status out of a `net use` command. Returns null if not found.
*
* @private
*/
function parseStatus (str) {
const re = /^\w+/
if (re.test(str)) {
return re.exec(str)[0]
} else {
return null
}
}
/**
* Parses a given `str` for UNC paths like `\\server\share$\user`.
*
* @private
*/
function parseUNC (str) {
return /\\\\[^\s]+/.exec(str)[0]
}
/**
* Converts a server name to an unc path.
*
* @private
*/
function toUnc (server) {
return `//${server}`
}
exports.statByDriveLetter = statByDriveLetter
exports.mountedDrives = mountedDrives
exports.toWindowsPath = toWindowsPath
exports.statDirectory = statDirectory
exports.statDrives = statDrives
exports.toUncPath = toUncPath
exports.isMounted = isMounted
exports.unmount = unmount
exports.mount = mount