This repository has been archived by the owner on Mar 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 299
/
get-files-stream.js
81 lines (68 loc) · 2.17 KB
/
get-files-stream.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
var File = require('vinyl')
var vinylfs = require('vinyl-fs-browser')
var vmps = require('vinyl-multipart-stream')
var stream = require('stream')
var Merge = require('merge-stream')
exports = module.exports = getFilesStream
function getFilesStream (files, opts) {
if (!files) return null
if (!Array.isArray(files)) files = [files]
// merge all inputs into one stream
var adder = new Merge()
// single stream for pushing directly
var single = new stream.PassThrough({objectMode: true})
adder.add(single)
for (var i = 0; i < files.length; i++) {
var file = files[i]
if (typeof (file) === 'string') {
// add the file or dir itself
adder.add(vinylfs.src(file, {buffer: false}))
// if recursive, glob the contents
if (opts.r || opts.recursive) {
adder.add(vinylfs.src(file + '/**/*', {buffer: false}))
}
} else {
// try to create a single vinyl file, and push it.
// throws if cannot use the file.
single.push(vinylFile(file))
}
}
single.end()
return adder.pipe(vmps())
}
// vinylFile tries to cast a file object to a vinyl file.
// it's agressive. If it _cannot_ be converted to a file,
// it returns null.
function vinylFile (file) {
if (file instanceof File) {
return file // it's a vinyl file.
}
// let's try to make a vinyl file?
var f = {cwd: '/', base: '/', path: ''}
if (file.contents && file.path) {
// set the cwd + base, if there.
f.path = file.path
f.cwd = file.cwd || f.cwd
f.base = file.base || f.base
f.contents = file.contents
} else {
// ok maybe we just have contents?
f.contents = file
}
// ensure the contents are safe to pass.
// throws if vinyl cannot use the contents
f.contents = vinylContentsSafe(f.contents)
return new File(f)
}
function vinylContentsSafe (c) {
if (Buffer.isBuffer(c)) return c
if (typeof (c) === 'string') return c
if (c instanceof stream.Stream) return c
if (typeof (c.pipe) === 'function') {
// hey, looks like a stream. but vinyl won't detect it.
// pipe it to a PassThrough, and use that
var s = new stream.PassThrough()
return c.pipe(s)
}
throw new Error('vinyl will not accept: ' + c)
}