-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
301 lines (259 loc) · 10.9 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
const chokidar = require('chokidar');
const request = require('request');
const rp = require('request-promise');
const log = require('fancy-log');
const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
const YAML = require('yaml');
const PromisePool = require('es6-promise-pool');
const { Confirm } = require('enquirer');
if (process.argv.length < 3) {
console.log('Usage: outofbox-skins-sync <config.yml>');
return;
}
const config_file_path = path.resolve(process.argv[2]);
if (!fs.existsSync(config_file_path)) {
console.error('Config file not found at path', chalk.cyan("'" + config_file_path + "'"));
return;
}
const config_file_dir = path.dirname(config_file_path);
const config_in_file = YAML.parse(fs.readFileSync(config_file_path, 'utf8'));
const defaults = {
ignored: [
/(^|[\/\\])\../, // ignore dotfiles
/node_modules/
],
sync: {
since_file: null
}
};
const config = Object.assign(defaults, config_in_file);
let watch_path;
if (path.isAbsolute(config.watch.path)) {
watch_path = config.watch.path;
} else {
watch_path = path.resolve(config_file_dir + path.sep + config.watch.path);
}
const startWatcher = () => {
log('Start watch', chalk.cyan("'" + watch_path + "'"), 'and sync with', chalk.cyan("'" + config.sync.base_uri + "'"));
const watcher = chokidar.watch(watch_path, {
ignored: config.ignored,
persistent: true,
ignoreInitial: true
});
var queue = [], current_task = null;
var executeNextTask = function() {
if (current_task) {
return;
}
if (queue.length > 0) {
current_task = queue.shift();
const event = current_task[0],
fs_path = current_task[1];
log('Path', chalk.magenta("'" + fs_path + "'"), chalk.cyan("'" + event + "'"));
const relative_fs_path = path.relative(watch_path, fs_path);
let resource_url = config.sync.base_uri + relative_fs_path;
let promise = null;
let headers = {
'X-Skins-Sync-Token': config.sync.token
};
switch (event) {
case 'add':
case 'change':
promise = rp({
method: 'POST',
uri: resource_url,
headers: headers,
formData: {
content: fs.createReadStream(fs_path)
},
resolveWithFullResponse: true
})
.then(function(response) {
log(chalk.cyan('POST'), 'request success:', chalk.bgBlack(response.statusCode));
})
.catch(function (error) {
log(chalk.cyan('POST'), 'request error:', chalk.bgRed(error.response.statusCode));
})
;
break;
case 'unlink':
promise = rp({
method: 'DELETE',
uri: resource_url,
headers: headers,
resolveWithFullResponse: true
})
.then(function(response) {
log(chalk.red('DELETE'), 'request success:', chalk.bgBlack(response.statusCode));
})
.catch(function (error) {
log(chalk.red('DELETE'), 'request error:', chalk.bgRed(error.response.statusCode));
})
;
break;
case 'addDir':
promise = rp({
method: 'POST',
uri: resource_url + '/',
headers: headers,
resolveWithFullResponse: true
})
.then(function(response) {
log(chalk.cyan('POST'), 'request success:', chalk.bgBlack(response.statusCode));
})
.catch(function (error) {
log(chalk.cyan('POST'), 'request error:', chalk.bgRed(error.response.statusCode));
})
;
break;
case 'unlinkDir':
promise = rp({
method: 'DELETE',
uri: resource_url + '/',
headers: headers,
resolveWithFullResponse: true
})
.then(function(response) {
log(chalk.red('DELETE'), 'request success:', chalk.bgBlack(response.statusCode));
})
.catch(function (error) {
log(chalk.red('DELETE'), 'request error:', chalk.bgRed(error.response.statusCode));
})
;
break;
}
if (promise) {
promise.finally(() => {
current_task = null;
executeNextTask();
});
} else {
current_task = null;
executeNextTask();
}
}
};
watcher.on('all', async (event, fs_path) => {
queue.push([ event, fs_path ]);
executeNextTask();
});
};
if (config.sync.since_file) {
const since_file_path = config_file_dir + '/' + config.sync.since_file;
if (!fs.existsSync(since_file_path)) {
log.error('Since file not found at path', chalk.cyan("'" + since_file_path + "'"));
return;
}
const since__date_number = Date.parse(fs.readFileSync(since_file_path, 'utf8'));
const sinceDate = new Date();
if (!isNaN(since__date_number)) {
sinceDate.setTime(since__date_number);
}
log('Pull changed files since', chalk.cyan("'" + sinceDate.toISOString() + "'"));
const now = new Date();
let headers = {
'X-Skins-Sync-Token': config.sync.token
};
rp({
method: 'GET',
uri: config.sync.base_uri,
qs: {
since: sinceDate.toISOString()
},
headers: headers,
resolveWithFullResponse: true,
json: true
})
.then(function(response) {
return new Promise((resolve, reject) => {
if (response.body.files.length === 0) {
log('No files was changed since', chalk.cyan("'" + sinceDate.toISOString() + "'"));
resolve(0);
return;
}
log(chalk.cyan(response.body.files.length), ' file(s) was changed:');
response.body.files.forEach(file => {
log(file.path);
});
const prompt = new Confirm({
name: 'question',
message: 'Continue download these changes?'
});
function ensureDirectoryExistence(filePath) {
var dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}
prompt.run()
.then((download) => {
if (download) {
const concurrency = 3;
const createDownloadFilePromise = function(file) {
return new Promise((downloadFileResolve, downloadFileReject) => {
request({
url: file._links['download'],
headers: headers,
resolveWithFullResponse: true,
encoding: null
}, (error, response, body) => {
if (!error) {
var fs_filepath = watch_path + '/' + file.path;
ensureDirectoryExistence(fs_filepath);
fs.writeFile(fs_filepath, body, function (error) {
if (error) {
downloadFileReject(error);
} else {
log(chalk.cyan(file.path), 'downloaded');
downloadFileResolve(fs_filepath);
}
});
} else {
downloadFileReject(error);
}
});
})
};
const generateDownloadPromises = function * () {
for (var file_index in response.body.files) {
var file = response.body.files[file_index];
yield createDownloadFilePromise(file);
}
};
const downloadFilesPool = new PromisePool(generateDownloadPromises(), concurrency);
var downloadPoolPromise = downloadFilesPool.start();
downloadPoolPromise.then(() => {
fs.writeFile(since_file_path, now.toISOString(), function(error) {
if (error) {
reject(error);
} else {
resolve(0)
}
});
}, function (error) {
reject(error);
});
} else {
resolve();
}
})
.catch((error) => {
reject(error);
})
;
});
})
.then(() => {
startWatcher();
})
.catch((error) => {
log.error('Error during files sync', error);
})
;
} else {
startWatcher();
}