-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
127 lines (108 loc) · 2.52 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
'use strict';
const path = require('path');
const through = require('through2');
const PluginError = require('plugin-error');
const cloudinary = require('cloudinary').v2;
const Vinyl = require('vinyl');
const vinylFile = require('vinyl-file');
module.exports = options => {
if (!process.env.CLOUDINARY_URL) {
if (!options.config) {
throw new PluginError(
'gulp-cloudinary-upload',
'Missing cloudinary config',
{showProperties: false}
);
}
cloudinary.config(options.config);
}
return through.obj((file, enc, cb) => {
const uploadParameters = {
overwrite: false,
filename: file.stem,
use_filename: true,
unique_filename: false,
...options.params
};
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isBuffer()) {
cloudinary.uploader
.upload_stream(uploadParameters, (error, result) => {
if (error) {
return cb(new PluginError('gulp-cloudinary-upload', error.message));
}
file.cloudinary = result;
return cb(null, file);
})
.end(file.contents);
}
if (file.isStream()) {
file.contents.pipe(
cloudinary.uploader.upload_stream(uploadParameters, (error, result) => {
if (error) {
return cb(new PluginError('gulp-cloudinary-upload', error.message));
}
file.cloudinary = result;
return cb(null, file);
})
);
}
});
};
const getManifestFile = async options => {
try {
return await vinylFile.read(options.path, options);
} catch (error) {
if (error.code === 'ENOENT') {
return new Vinyl(options);
}
throw error;
}
};
module.exports.manifest = options => {
options = {
path: 'cloudinary-manifest.json',
merge: false,
...options
};
options.base = path.dirname(options.path);
let manifest = {};
return through.obj(
(file, enc, cb) => {
if (!file.cloudinary) {
return cb();
}
const basename = path.basename(file.path);
manifest[basename] = file.cloudinary;
cb();
},
function (cb) {
if (Object.keys(manifest).length === 0) {
cb();
return;
}
(async () => {
try {
const manifestFile = await getManifestFile(options);
if (options.merge && !manifestFile.isNull()) {
let oldManifest = {};
try {
oldManifest = JSON.parse(manifestFile.contents.toString());
} catch {}
manifest = Object.assign(oldManifest, manifest);
}
manifestFile.contents = Buffer.from(
JSON.stringify(manifest, null, 2)
);
this.push(manifestFile);
cb();
} catch (error) {
cb(error);
}
})();
}
);
};