Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/utils/lib/file.js
blob: e7c233681964f241d1ab4b3720647b4c206538dc (plain)
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

var io = require('io');
var implementation = require('file-platform');

for (var name in implementation) {
    if (Object.prototype.hasOwnProperty.call(implementation, name)) {
        exports[name] = implementation[name];
    }
}

/* streams */

exports.open = function (path, mode, options) {

    // it's possible to confuse options and mode,
    // particularly with exports.read(path, options).
    // if a mode string is passed into options, 
    // tollerate it.
    if (typeof options == 'string') {
        options = {
            mode: exports.mode(options)
        }
    }

    // we'll channel all of the arguments through
    // the options object, so create an empty one if none
    // was given.
    if (!options) 
        options = {};

    // if options were specified as the first (and
    // presumably only) argument, use those options,
    // overriding any in the options object if both
    // were provided.
    if (typeof path == 'object') {
        for (var key in path) {
            if (Object.prototype.hasOwnProperty.call(path, key)) {
                options[key] = path[key];
            }
        }
    }
    // if the path is a string, however, write it
    // onto the options object alone.
    if (typeof path == 'string')
        options.path = path;

    // accumulate the mode from options.mode and 
    // the mode arg through successive generations;
    // coerce the options.mode to an object, suitable
    // for updates
    options.mode = exports.mode(options.mode);
    // update options.mode with the mode argument
    if (mode)
        options.mode = exports.mode(mode, options.mode);


    // channel all the options back into local variables
    path = options.path;
    mode = options.mode;
    var permissions = options.permissions,
        charset = options.charset,
        buffering = options.buffering,
        recordSeparator = options.recordSeparator,
        fieldSeparator = options.fieldSeparator;

    // and decompose the mode object
    var read = mode.read,
        write = mode.write,
        append = mode.append,
        update = mode.update,
        binary = mode.binary;

    // read by default
    if (!(read || write || append))
        read = mode.read = true;

    // create a byte stream
    var raw = exports.FileIO(path, mode, permissions);

    // if we're in binary mode, just return the raw
    // stream
    if (binary)
        return raw;

    // otherwise, go through the courses to return the
    // appropriate reader, writer, or updater, buffered,
    // line buffered, and charset decoded/encoded
    // abstraction

    var lineBuffering = buffering == 1 || buffering === undefined && raw.isatty && raw.isatty();
    // leaving buffering undefined is a signal to the platform implementation
    //  that it ought to pick a good size on its own.
    if (buffering < 0) {
        throw new Error("invalid buffering size");
    }
    if (buffering === 0) {
        throw new Error("can't have unbuffered text IO");
    }

    return new io.TextIOWrapper(raw, mode, lineBuffering, buffering, charset, options);

};

/*
    idempotent normalization of acceptable formats for
    file modes.
*/
exports.mode = function (mode, result) {
    if (!result)
        result = {
            read: false,
            write: false,
            append: false,
            update: false,
            binary: false,
            canonical: false,
            exclusive: false
        };
    else if (typeof result != 'object')
        throw new Error("Mode to update is not a proper mode object: " + result);

    if (mode === undefined || mode === null) {
    } else if (mode instanceof String || typeof mode == "string") {
        mode.split("").forEach(function (option) {
            if (option == 'r') {
                result.read = true;
            } else if (option == 'w') {
                result.write = true;
            } else if (option == 'a') {
                result.append = true;
            } else if (option == '+') {
                result.update = false;
            } else if (option == 'b') {
                result.binary = true;
            } else if (option == 't') {
                result.binary = false;
            } else if (option == 'c') {
                result.canonical = true;
            } else if (option == 'x') {
                result.exclusive = true;
            } else {
                throw new Error("unrecognized mode option in mode: " + option);
            }
        });
    } else if (mode instanceof Array) {
        mode.forEach(function (option) {
            if (Object.prototype.hasOwnProperty.call(result, option)) {
                result[option] = true;
            } else {
                throw new Error("unrecognized mode option in mode: " + option);
            }
        });
    } else if (mode instanceof Object) {
        for (var option in mode) {
            if (Object.prototype.hasOwnProperty.call(mode, option)) {
                if (Object.prototype.hasOwnProperty.call(result, option)) {
                    result[option] = !!mode[option];
                } else {
                    throw new Error("unrecognized mode option in mode: " + option);
                }
            }
        }
    } else {
        throw new Error("unrecognized mode: " + mode);
    }

    return result;
};

/* read, write, &c */

exports.read = function (path, options) {
    path = String(path);
    var file = exports.open(path, 'r', options);
    try {
        return file.read();
    } finally {
        file.close();
    }
};

exports.write = function (path, data, options) {
    path = String(path);
    var file = exports.open(path, 'w', options);
    try {
        file.write(data);
        file.flush();
    } finally {
        file.close();
    }
};

exports.copy = function (source, target) {
    source = exports.path(source);
    target = exports.path(target);
    var data = source.read();
    target.write(data);
};

exports.list = function (path) {
    path = String(path);
    if (!path)
        path = ".";
    return implementation.list(path);
};

exports.listTree = function (path) {
    path = String(path);
    var paths = [path];
    if (exports.isDirectory(path)) {
        exports.list(path).forEach(function (child) {
            paths.push.apply(
                paths,
                exports.listTree(exports.join(path, child))
            );
        });
    }
    return paths;
};

exports.glob = function (pattern) {
    pattern = String(pattern);
    pattern = pattern.replace(/\*\*/g, '*/**/*');
    var parts = exports.split(pattern);
    var paths = [''];
    parts.forEach(function (part) {

        if (part == "") {
        } else if (part == "**") {
            paths = Array.prototype.concat.apply(
                [],
                paths.map(function (path) {
                    return exports.listTree(path);
                })
            );
        } else if (/[\*\?]/.test(part)) {
            var pattern = new RegExp('^'+
                part.split('*').map(function (part) {
                    return part.split('?').map(function (part) {
                        return RegExp.escape(part);
                    }).join('.');
                }).join('.*?')
            +'$');
            paths = Array.prototype.concat.apply([], paths.map(function (path) {
                if (path != "" && !exports.isDirectory(path))
                    return [];
                return exports.list(path).filter(function (name) {
                    return pattern.test(name);
                }).map(function (name) {
                    return exports.join(path, name);
                }).filter(function (path) {
                    return exports.exists(path);
                });
            }));
        } else if (part == "...") {
            paths = Array.prototype.concat.apply(
                [],
                paths.map(function (path) {
                    var heredity = [];
                    var parts = exports.split(exports.absolute(path));
                    while (parts.length) {
                        heredity.push(exports.join.apply(null, parts));
                        parts.pop();
                    }
                    return heredity;
                })
            );
        } else {
            paths = paths.map(function (path) {
                return exports.join(path, part);
            });
        }

        // uniqueness
        var visited = {};
        paths = paths.filter(function (path) {
            var result = !Object.prototype.hasOwnProperty.call(visited, path);
            visited[path] = true;
            return result;
        });

    });
    return paths;
};

exports.rmtree = function(path) {
    if (exports.isDirectory(path)) {
        exports.list(path).forEach(function (name) {
            exports.rmtree(exports.join(path, name));
        });
        exports.rmdir(path);
    } else {
        exports.remove(path);
    }
};

/* path manipulation */

var ROOT = implementation.ROOT;
var SEPARATOR = implementation.SEPARATOR;
var ALT_SEPARATOR = implementation.ALT_SEPARATOR;
var SEPARATORS_RE = new RegExp(
    "[" +
        RegExp.escape(SEPARATOR || '') + 
        RegExp.escape(ALT_SEPARATOR || '') + 
    "]"
);

exports.join = function () {
    return exports.normal(Array.prototype.join.call(arguments, SEPARATOR));
};

exports.split = function (path) {
    try {
        return String(path).split(SEPARATORS_RE);
    } catch (exception) {
        throw new Error("Cannot split " + (typeof path) + ', "' + path + '"');
    }
};

exports.resolve = function () {
    var root = "";
    var parents = [];
    var children = [];
    var leaf = "";
    for (var i = 0; i < arguments.length; i++) {
        var path = String(arguments[i]);
        if (path == "")
            continue;
        if (path.charAt(0) == SEPARATOR) {
            path = path.substring(1, path.length);
            root = ROOT;
            parents = [];
            children = [];
        }
        var parts = path.split(SEPARATOR);
        leaf = parts.pop();
        if (leaf == "." || leaf == "..") {
            parts.push(leaf);
            leaf = "";
        }
        for (var j = 0; j < parts.length; j++) {
            var part = parts[j];
            if (part == "." || part == '') {
            } else if (part == "..") {
                if (children.length) {
                    children.pop();
                } else {
                    if (root) {
                    } else {
                        parents.push("..");
                    }
                }
            } else {
                children.push(part);
            }
        };
    }
    path = parents.concat(children).join(SEPARATOR);
    if (path) leaf = SEPARATOR + leaf;
    return root + path + leaf;
};

exports.relative = function (source, target) {
    source = exports.absolute(source);
    target = exports.absolute(target);
    source = source.split(SEPARATOR);
    target = target.split(SEPARATOR);
    if (source[source.length - 1] == "")
        source.pop();
    while (source.length && target.length && target[0] == source[0]) {
        source.shift();
        target.shift();
    }
    while (source.length) {
        source.shift();
        target.unshift("..");
    }
    return target.join(SEPARATOR);
};

exports.normal = function (path) {
    return exports.resolve(path);
};

exports.absolute = function (path) {
    return exports.resolve(exports.join(exports.cwd(), ''), path);
};

exports.dirname = function (path) {
    var parts = exports.split(path);
    parts.pop();
    return exports.join.apply(null, parts);
};

exports.basename = function (path) {
    return path.split(SEPARATOR).pop();
};

exports.extension =
exports.extname = function(path) {
    path = exports.basename(path);
    path = path.replace(/^\.*/, '');
    var index = path.lastIndexOf(".");
    return index <= 0 ? "" : path.substring(index);
};

/* path wrapper, for chaining */

exports.path = function (/*path*/) {
    return exports.Path(exports.join.apply(exports, arguments));
};

var Path = exports.Path = function (path) {
    if (!(this instanceof exports.Path))
        return new exports.Path(path);
    this.toString = function () {
        return path;
    };
};

Path.prototype = new String();

Path.prototype.valueOf = function () {
    return this.toString();
};

Path.prototype.join = function () {
    return exports.Path(
        exports.join.apply(
            null,
            [this.toString()].concat(Array.prototype.slice.call(arguments))
        )
    );
};

Path.prototype.resolve = function () {
    return exports.Path(
        exports.resolve.apply(
            null,
            [this.toString()].concat(Array.prototype.slice.call(arguments))
        )
    );
};

Path.prototype.to = function (target) {
    return exports.Path(exports.relative(this.toString(), target));
};

Path.prototype.from = function (target) {
    return exports.Path(exports.relative(target, this.toString()));
};

Path.prototype.listPaths = function () {
    var self = this;
    return exports.list(this).map(function (name) {
        return self.join(name);
    });
};

var pathed = [
    'absolute',
    'basename',
    'canonical',
    'dirname',
    'normal'
];

for (var i = 0; i < pathed.length; i++) {
    var name = pathed[i];
    Path.prototype[name] = (function (name) {
        return function () {
            return exports.Path(exports[name].apply(
                this,
                [this.toString()].concat(Array.prototype.slice.call(arguments))
            ));
        };
    })(name);
}

var trivia = [
    'chmod',
    'chown',
    'copy',
    'exists',
    'extname',
    'isDirectory',
    'isFile',
    'isLink',
    'isReadable',
    'isWritable',
    'link',
    'linkExists',
    'list',
    'mkdir', 
    'mkdirs',
    'move',
    'mtime',
    'open',
    'read',
    'remove',
    'rename',
    'rmdir',
    'rmtree',
    'size',
    'split',
    'stat',
    'symlink',
    'touch',
    'write'
];

for (var i = 0; i < trivia.length; i++) {
    var name = trivia[i];
    Path.prototype[name] = (function (name) {
        return function () {
            var result = exports[name].apply(
                this,
                [this.toString()].concat(Array.prototype.slice.call(arguments))
            );
            if (result === undefined)
                result = this;
            return result;
        };
    })(name);
}