file-manager.js 6.96 KB
Newer Older
YazhouChen's avatar
YazhouChen committed
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
var path = require('path'),
    fs = require('./fs'),
    PromiseConstructor = typeof Promise === 'undefined' ? require('promise') : Promise,
    AbstractFileManager = require('../less/environment/abstract-file-manager.js');

var FileManager = function() {
    this.contents = {};
};

FileManager.prototype = new AbstractFileManager();

FileManager.prototype.supports = function(filename, currentDirectory, options, environment) {
    return true;
};
FileManager.prototype.supportsSync = function(filename, currentDirectory, options, environment) {
    return true;
};

FileManager.prototype.loadFile = function(filename, currentDirectory, options, environment, callback) {

    var fullFilename,
        isAbsoluteFilename = this.isPathAbsolute(filename),
        filenamesTried = [],
        self = this,
        prefix = filename.slice(0, 1),
        explicit = prefix === '.' || prefix === '/',
        result = null,
        isNodeModule = false,
        npmPrefix = 'npm://';

    options = options || {};

    var paths = isAbsoluteFilename ? [''] : [currentDirectory];

    if (options.paths) { paths.push.apply(paths, options.paths); }

    if (!isAbsoluteFilename && paths.indexOf('.') === -1) { paths.push('.'); }

    var prefixes = options.prefixes || [''];
    var fileParts = this.extractUrlParts(filename);

    if (options.syncImport) {
        getFileData(returnData, returnData);
        if (callback) {
            callback(result.error, result);
        }
        else {
            return result;
        }
    }
    else {
        // promise is guaranteed to be asyncronous
        // which helps as it allows the file handle
        // to be closed before it continues with the next file
        return new PromiseConstructor(getFileData);
    }

    function returnData(data) {
        if (!data.filename) {
            result = { error: data };
        }
        else {
            result = data;
        }
    }

    function getFileData(fulfill, reject) {
        (function tryPathIndex(i) {
            if (i < paths.length) {
                (function tryPrefix(j) {
                    if (j < prefixes.length) {
                        isNodeModule = false;
                        fullFilename = fileParts.rawPath + prefixes[j] + fileParts.filename;

                        if (paths[i]) {
                            fullFilename = path.join(paths[i], fullFilename);
                        }

                        if (!explicit && paths[i] === '.') {
                            try {
                                fullFilename = require.resolve(fullFilename);
                                isNodeModule = true;
                            }
                            catch (e) {
                                filenamesTried.push(npmPrefix + fullFilename);
                                tryWithExtension();
                            }
                        }
                        else {
                            tryWithExtension();
                        }

                        function tryWithExtension() {
                            var extFilename = options.ext ? self.tryAppendExtension(fullFilename, options.ext) : fullFilename;

                            if (extFilename !== fullFilename && !explicit && paths[i] === '.') {
                                try {
                                    fullFilename = require.resolve(extFilename);
                                    isNodeModule = true;
                                }
                                catch (e) {
                                    filenamesTried.push(npmPrefix + extFilename);
                                    fullFilename = extFilename;
                                }
                            }
                            else {
                                fullFilename = extFilename;
                            }
                        }

                        var modified = false;

                        if (self.contents[fullFilename]) {
                            try {
                                var stat = fs.statSync.apply(this, [fullFilename]);
                                if (stat.mtime.getTime() === self.contents[fullFilename].mtime.getTime()) {
                                    fulfill({ contents: self.contents[fullFilename].data, filename: fullFilename});
                                }
                                else {
                                    modified = true;
                                }
                            }
                            catch (e) {
                                modified = true;
                            }
                        }
                        if (modified || !self.contents[fullFilename]) {
                            var readFileArgs = [fullFilename];
                            if (!options.rawBuffer) {
                                readFileArgs.push('utf-8');
                            }
                            if (options.syncImport) {
                                try {
                                    var data = fs.readFileSync.apply(this, readFileArgs);
                                    var stat = fs.statSync.apply(this, [fullFilename]);
                                    self.contents[fullFilename] = { data: data, mtime: stat.mtime };
                                    fulfill({ contents: data, filename: fullFilename});
                                }
                                catch (e) {
                                    filenamesTried.push(isNodeModule ? npmPrefix + fullFilename : fullFilename);
                                    return tryPrefix(j + 1);
                                }
                            }
                            else {
                                readFileArgs.push(function(e, data) {
                                    if (e) {
                                        filenamesTried.push(isNodeModule ? npmPrefix + fullFilename : fullFilename);
                                        return tryPrefix(j + 1);
                                    }
                                    var stat = fs.statSync.apply(this, [fullFilename]);
                                    self.contents[fullFilename] = { data: data, mtime: stat.mtime };      
                                    fulfill({ contents: data, filename: fullFilename});
                                });
                                fs.readFile.apply(this, readFileArgs);
                            }

                        }

                    }
                    else {
                        tryPathIndex(i + 1);
                    }
                })(0);
            } else {
                reject({ type: 'File', message: '\'' + filename + '\' wasn\'t found. Tried - ' + filenamesTried.join(',') });
            }
        }(0));
    }
};

FileManager.prototype.loadFileSync = function(filename, currentDirectory, options, environment) {
    options.syncImport = true;
    return this.loadFile(filename, currentDirectory, options, environment);
};

module.exports = FileManager;