Repository navigation
Expand file tree
/
Copy pathutils.js
More file actions
587 lines (526 loc) · 17.3 KB
/
Copy pathutils.js
File metadata and controls
587 lines (526 loc) · 17.3 KB
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
const { Cc, Ci, Cr, Cu } = require('chrome');
const { btoa } = Cu.import("resource://gre/modules/Services.jsm", {});
const FILE_TYPE_FILE = 0;
const FILE_TYPE_DIRECTORY = 1;
Cu.import('resource://gre/modules/XPCOMUtils.jsm');
Cu.import('resource://gre/modules/FileUtils.jsm');
Cu.import('resource://gre/modules/Services.jsm');
Cu.import("resource://gre/modules/osfile.jsm")
function isSubjectToBranding(path) {
return /shared[\/\\][a-zA-Z]+[\/\\]branding$/.test(path) ||
/branding[\/\\]initlogo.png/.test(path);
}
/**
* Returns an array of nsIFile's for a given directory
*
* @param {nsIFile} dir directory to read.
* @param {boolean} recursive set to true in order to walk recursively.
* @param {RegExp} exclude optional filter to exclude file/directories.
*
* @return {Array} list of nsIFile's.
*/
function ls(dir, recursive, exclude) {
let results = [];
if (!dir.exists()) {
return results;
}
let files = dir.directoryEntries;
while (files.hasMoreElements()) {
let file = files.getNext().QueryInterface(Ci.nsILocalFile);
if (!exclude || !exclude.test(file.leafName)) {
results.push(file);
if (recursive && file.isDirectory()) {
results = results.concat(ls(file, true, exclude));
}
}
}
return results;
}
function getFileContent(file) {
try {
let fileStream = Cc['@mozilla.org/network/file-input-stream;1']
.createInstance(Ci.nsIFileInputStream);
fileStream.init(file, 1, 0, false);
let converterStream = Cc['@mozilla.org/intl/converter-input-stream;1']
.createInstance(Ci.nsIConverterInputStream);
converterStream.init(fileStream, 'utf-8', fileStream.available(),
Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
let out = {};
let count = fileStream.available();
converterStream.readString(count, out);
var content = out.value;
converterStream.close();
fileStream.close();
} catch (e) {
let msg = (file && file.path) ? '\nfile not found: ' + file.path : '';
throw new Error(' -*- build/utils.js: ' + e + msg + '\n');
}
return content;
}
function writeContent(file, content) {
var fileStream = Cc['@mozilla.org/network/file-output-stream;1']
.createInstance(Ci.nsIFileOutputStream);
fileStream.init(file, 0x02 | 0x08 | 0x20, 0666, 0);
let converterStream = Cc['@mozilla.org/intl/converter-output-stream;1']
.createInstance(Ci.nsIConverterOutputStream);
converterStream.init(fileStream, 'utf-8', 0, 0);
converterStream.writeString(content);
converterStream.close();
}
// Return an nsIFile by joining paths given as arguments
// First path has to be an absolute one
function getFile() {
try {
let file = new FileUtils.File(arguments[0]);
if (arguments.length > 1) {
for (let i = 1; i < arguments.length; i++) {
let dir = arguments[i];
dir.split('/').forEach(function(name) {
file.append(name);
});
}
}
return file;
} catch (e) {
throw new Error(' -*- build/utils.js: Invalid file path (' +
Array.slice(arguments).join(', ') + ')\n' + e + '\n');
}
}
function ensureFolderExists(file) {
if (!file.exists()) {
try {
file.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0755', 8));
} catch (e if e.result == Cr.NS_ERROR_FILE_ALREADY_EXISTS) {
// Bug 808513: Ignore races between `if exists() then create()`.
return;
}
}
}
function getJSON(file) {
try {
let content = getFileContent(file);
return JSON.parse(content);
} catch (e) {
dump('Invalid JSON file : ' + file.path + '\n');
throw e;
}
}
function getFileAsDataURI(file) {
var contentType = Cc["@mozilla.org/mime;1"]
.getService(Ci.nsIMIMEService)
.getTypeFromFile(file);
var inputStream = Cc["@mozilla.org/network/file-input-stream;1"]
.createInstance(Ci.nsIFileInputStream);
inputStream.init(file, 0x01, 0600, 0);
var stream = Cc["@mozilla.org/binaryinputstream;1"]
.createInstance(Ci.nsIBinaryInputStream);
stream.setInputStream(inputStream);
var encoded = btoa(stream.readBytes(stream.available()));
return "data:" + contentType + ";base64," + encoded;
}
function makeWebappsObject(appdirs, domain, scheme, port) {
return {
forEach: function(fun) {
appdirs.forEach(function(app) {
let appDir = getFile(app);
if (!appDir.exists()) {
throw new Error(' -*- build/utils.js: file not found (' + app + ')\n');
}
let manifestFile = appDir.clone();
manifestFile.append('manifest.webapp');
let updateFile = appDir.clone();
updateFile.append('update.webapp');
// Ignore directories without manifest
if (!manifestFile.exists() && !updateFile.exists()) {
return;
}
let manifest = manifestFile.exists() ? manifestFile : updateFile;
// Use the folder name as the the domain name
let appDomain = appDir.leafName + '.' + domain;
let webapp = {
manifest: getJSON(manifest),
manifestFile: manifest,
url: scheme + appDomain + (port ? port : ''),
domain: appDomain,
sourceDirectoryFile: manifestFile.parent,
buildDirectoryFile: manifestFile.parent,
sourceDirectoryName: appDir.leafName,
sourceAppDirectoryName: appDir.parent.leafName
};
// External webapps have a `metadata.json` file
let metaData = webapp.sourceDirectoryFile.clone();
metaData.append('metadata.json');
if (metaData.exists()) {
webapp.metaData = getJSON(metaData);
}
// Some webapps control their own build
let buildMetaData = webapp.sourceDirectoryFile.clone();
buildMetaData.append('gaia_build.json');
if (buildMetaData.exists()) {
webapp.build = getJSON(buildMetaData);
if (webapp.build.dir) {
let buildDirectoryFile = webapp.sourceDirectoryFile.clone();
webapp.build.dir.split('/').forEach(function(segment) {
if (segment == "..")
buildDirectoryFile = buildDirectoryFile.parent;
else
buildDirectoryFile.append(segment);
});
webapp.buildDirectoryFile = buildDirectoryFile;
}
}
fun(webapp);
});
}
};
}
function registerProfileDirectory(profileDir) {
let directoryProvider = {
getFile: function provider_getFile(prop, persistent) {
persistent.value = true;
if (prop != 'ProfD' && prop != 'ProfLDS') {
throw Cr.NS_ERROR_FAILURE;
}
return new FileUtils.File(profileDir);
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsIDirectoryServiceProvider,
Ci.nsISupports])
};
Cc['@mozilla.org/file/directory_service;1']
.getService(Ci.nsIProperties)
.QueryInterface(Ci.nsIDirectoryService)
.registerProvider(directoryProvider);
}
function getGaia(options) {
return {
engine: options.GAIA_ENGINE,
sharedFolder: getFile(options.GAIA_DIR, 'shared'),
webapps: makeWebappsObject(options.GAIA_APPDIRS.split(' '),
options.GAIA_DOMAIN, options.GAIA_SCHEME, options.GAIA_PORT),
aggregatePrefix: 'gaia_build_',
distributionDir: options.GAIA_DISTRIBUTION_DIR
};
}
function gaiaOriginURL(name, scheme, domain, port) {
return scheme + name + '.' + domain + (port ? port : '');
}
function gaiaManifestURL(name, scheme, domain, port) {
return gaiaOriginURL(name, scheme, domain, port) + '/manifest.webapp';
}
function getDistributionFileContent(name, defaultContent, distDir) {
if (distDir) {
let distributionFile = getFile(distDir, name + '.json');
if (distributionFile.exists()) {
return getFileContent(distributionFile);
}
}
return JSON.stringify(defaultContent, null, ' ');
}
function getAbsoluteOrRelativePath(path, gaiaDir) {
// First check relative path to gaia folder
let abs_path_chunks = [gaiaDir].concat(path.split(/\/|\\/));
let file = getFile.apply(null, abs_path_chunks);
if (!file.exists()) {
try {
// Then check absolute path
return getFile(path);
} catch (e) {}
}
return file;
}
/**
* Delete the specified file path.
*
* @param {boolean} recursive set to true in order to delete recursively.
* Note: this function is a wrapper function for node.js
*/
function deleteFile(path, recursive) {
var file = getFile(path);
if (file.exists()) {
file.remove(recursive === true);
}
}
/**
*
* Returns an array of file name's for a given directory
*
* @param {string} path directory to read.
* @param {int} type FILE_TYPE_FILE for files,
* FILE_TYPE_DIRECTORY for directories
* @param {boolean} recursive set to true in order to walk recursively.
* @param {RegExp} exclude optional filter to exclude file/directories.
*
* @return {Array} list of string which contains all files' full path.
* Note: this function is a wrapper function for node.js
*/
function listFiles(path, type, recursive, exclude) {
var file = getFile(path);
if (!file.isDirectory()) {
throw new Error('the path is not a directory.');
}
var files = ls(file, recursive === true, exclude);
var detectFunc = (type === 0 ? 'isFile' : 'isDirectory');
// To return simple JavaScript type, We need to put the file path to the array
// instead of nsIFile.
var results = [];
files.forEach(function(file) {
if (file[detectFunc]()) {
results.push(file.path);
}
});
return results;
}
/**
* check if a file or directory exists.
* Note: this function is a wrapper function for node.js
*/
function fileExists(path) {
return getFile(path).exists();
}
/**
* create dir and its parents.
* Note: this function is a wrapper function for node.js
*/
function mkdirs(path) {
ensureFolderExists(getFile(path));
}
/**
* join all path.
* Note: this function is a wrapper function for node.js
*/
function joinPath() {
return OS.Path.join.apply(OS.Path, arguments);
}
/**
* copy path to parentPath/name.
* @param {string} path directory to be copied,
* @param {string} toParent the parent folder of destination,
* @param {string} name the parent folder of destination,
* @param {boolean} override set to true to overwride it if it is existed.
* Note: this function is a wrapper function for node.js
*/
function copyFileTo(path, toParent, name, override) {
var file = getFile(path);
var parentFile = getFile(toParent);
ensureFolderExists(parentFile);
if (override) {
var toFile = getFile(toParent, name);
if (toFile.exists()) {
toFile.remove(true);
}
}
file.copyTo(parentFile, name);
}
/**
* create standard XMLHttpRequest object.
* Note: this function is a wrapper function for node.js
*/
function createXMLHttpRequest() {
let XMLHttpRequest = Cc['@mozilla.org/xmlextras/xmlhttprequest;1'];
var ret = new XMLHttpRequest();
ret.mozBackgroundRequest = true;
return ret;
}
/**
* download JSON file from internet
* Note: this function is a wrapper function for node.js
*/
function downloadJSON(url, callback) {
var xhr = createXMLHttpRequest();
xhr.open('GET', url, true);
xhr. {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else if (url.substring(0, 5) === 'https') {
// if error with https, fallback to http mode.
downloadJSON('http' + url.substring(5), callback);
} else {
callback(null);
}
}
};
xhr.send();
}
/**
* read JSON object from path, if the path is folder, it returns null.
* Note: this function is a wrapper for node.js
*/
function readJSONFromPath(path) {
var file = getFile(path);
if (file.isFile()) {
return getJSON(file);
} else {
throw new Error('The path is not a file.');
}
}
/**
* write content to a file
* Note: this function is a wrapper for node.js
*/
function writeContentToFile(path, content) {
writeContent(getFile(path), content);
}
/**
* To have XPCShell working, this function pumps the event for current thread.
* @param {function} exitResultFunc it should return an object for exit
* information:
* {
* wait: true, // a boolean to indicate we need to wait or not.
* error: null // an Error object or null to indicate an error should
* // be thrown to outside.
* }
* Note: this function is a wrapper for node.js
*/
function processEvents(exitResultFunc) {
let thread = Services.tm.currentThread;
let exitResult;
do {
exitResult = exitResultFunc();
thread.processNextEvent(true);
} while(thread.hasPendingEvents() || exitResult.wait);
if (exitResult.error) {
throw exitResult.error;
}
}
function getTempFolder(dirName) {
var file = Cc['@mozilla.org/file/directory_service;1']
.getService(Ci.nsIProperties).get('TmpD', Ci.nsIFile);
file.append(dirName);
file.createUnique(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0755', 8));
file = file.clone();
return file;
}
function getXML(file) {
try {
var parser = Cc["@mozilla.org/xmlextras/domparser;1"]
.createInstance(Ci.nsIDOMParser);
let content = getFileContent(file);
return parser.parseFromString(content, 'application/xml');
} catch (e) {
dump('Invalid XML file : ' + file.path + '\n');
throw e;
}
}
/**
* Simple log with the following format [tag] msg1 msg2. The first argument is
* used as tag.
*/
function log(/*tag, ...*/) {
if (!arguments.length) {
dump('\n');
return;
}
var msg = '[' + arguments[0] + ']';
for(var i = 1; i < arguments.length; i++) {
msg += ' ' + arguments[i];
}
dump(msg + '\n');
}
function getBuildConfig(builddir) {
var result = {};
ls(getFile(builddir), false).forEach(function(file) {
var matched = file.leafName.match(/apps-(.+)\.list$/);
if (matched) {
result[matched[1]] = {
'path': file.path,
'content': getFileContent(file)
};
}
});
return result;
}
function getAppsByList(content, gaiadir, distdir) {
var re = /(.+)\/(.+)/;
var apps = {};
content.split('\n').forEach(function(line) {
line = line.trim();
var matched = line.match(re);
if (matched) {
if (matched[2] === '*') {
ls(getFile(gaiadir, matched[1])).forEach(function(file) {
if (file.isDirectory()) {
var app = getApp(matched[1], file.leafName, gaiadir, distdir);
if (apps[app.name]) {
throw new Error('two apps with same name: \n - ' + app.path +
'\n ' + apps[app.name]);
}
apps[app.name] = app;
}
});
} else {
var app = getApp(matched[1], matched[2], gaiadir, distdir);
if (apps[app.name]) {
throw new Error('two apps with same name: \n - ' + app.path +
'\n ' + apps[app.name]);
}
apps[app.name] = app;
}
} else if (line) {
var msg = 'Unsupported path "' + line + '" in app list file.';
log('utils', msg);
throw new Error(msg);
}
});
return apps;
}
function getApp(parent, appname, gaiadir, distdir) {
var app = { 'name': appname, 'parent': parent };
var appInGaia = getFile(gaiadir, parent, appname);
var appInDist = getFile(distdir, parent, appname);
if (appInGaia.exists()) {
app.path = appInGaia.path;
} else if (appInDist.exists()) {
app.path = appInDist.path;
} else {
throw new Error('app doesn\'t exist: ' + app.name);
}
var filename;
if (getFile(app.path, 'manifest.webapp').exists()) {
filename = 'manifest.webapp';
} else if (getFile(app.path, 'update.webapp').exists()) {
filename = 'update.webapp';
} else {
throw new Error('manifest or update.webapp deosn\'t exists: ' + appname);
}
app.manifest = getJSON(getFile(app.path, filename));
return app;
}
function normalizeString(appname) {
return appname.replace(' ', '-').toLowerCase().replace(/\W/g, '');
}
exports.isSubjectToBranding = isSubjectToBranding;
exports.ls = ls;
exports.getFileContent = getFileContent;
exports.writeContent = writeContent;
exports.getFile = getFile;
exports.ensureFolderExists = ensureFolderExists;
exports.getJSON = getJSON;
exports.getFileAsDataURI = getFileAsDataURI;
exports.makeWebappsObject = makeWebappsObject;
exports.gaiaOriginURL = gaiaOriginURL;
exports.gaiaManifestURL = gaiaManifestURL;
exports.getDistributionFileContent = getDistributionFileContent;
exports.getAbsoluteOrRelativePath = getAbsoluteOrRelativePath;
exports.getGaia = getGaia;
exports.getBuildConfig = getBuildConfig;
exports.getAppsByList = getAppsByList;
exports.getApp = getApp;
exports.getXML = getXML;
exports.getTempFolder = getTempFolder;
exports.normalizeString = normalizeString;
// ===== the following functions support node.js compitable interface.
exports.FILE_TYPE_FILE = FILE_TYPE_FILE;
exports.FILE_TYPE_DIRECTORY = FILE_TYPE_DIRECTORY;
exports.deleteFile = deleteFile;
exports.listFiles = listFiles;
exports.fileExists = fileExists;
exports.mkdirs = mkdirs;
exports.joinPath = joinPath;
exports.copyFileTo = copyFileTo;
exports.createXMLHttpRequest = createXMLHttpRequest;
exports.downloadJSON = downloadJSON;
exports.readJSONFromPath = readJSONFromPath;
exports.writeContentToFile = writeContentToFile;
exports.processEvents = processEvents;
exports.log = log;