util.js 7.3 KB
Newer Older
J
Joao Moreno 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
var es = require("event-stream");
var debounce = require("debounce");
var _filter = require("gulp-filter");
var rename = require("gulp-rename");
var _ = require("underscore");
var path = require("path");
var fs = require("fs");
var _rimraf = require("rimraf");
var git = require("./git");
var VinylFile = require("vinyl");
var NoCancellationToken = { isCancellationRequested: function () { return false; } };
function incremental(streamProvider, initial, supportsCancellation) {
    var input = es.through();
    var output = es.through();
    var state = 'idle';
    var buffer = Object.create(null);
23
    var token = !supportsCancellation ? undefined : { isCancellationRequested: function () { return Object.keys(buffer).length > 0; } };
J
Joao Moreno 已提交
24 25 26 27 28
    var run = function (input, isCancellable) {
        state = 'running';
        var stream = !supportsCancellation ? streamProvider() : streamProvider(isCancellable ? token : NoCancellationToken);
        input
            .pipe(stream)
29
            .pipe(es.through(undefined, function () {
J
Joao Moreno 已提交
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
            state = 'idle';
            eventuallyRun();
        }))
            .pipe(output);
    };
    if (initial) {
        run(initial, false);
    }
    var eventuallyRun = debounce(function () {
        var paths = Object.keys(buffer);
        if (paths.length === 0) {
            return;
        }
        var data = paths.map(function (path) { return buffer[path]; });
        buffer = Object.create(null);
        run(es.readArray(data), true);
    }, 500);
    input.on('data', function (f) {
        buffer[f.path] = f;
        if (state === 'idle') {
            eventuallyRun();
        }
    });
    return es.duplex(input, output);
}
exports.incremental = incremental;
function fixWin32DirectoryPermissions() {
    if (!/win32/.test(process.platform)) {
        return es.through();
    }
    return es.mapSync(function (f) {
        if (f.stat && f.stat.isDirectory && f.stat.isDirectory()) {
            f.stat.mode = 16877;
        }
        return f;
    });
}
exports.fixWin32DirectoryPermissions = fixWin32DirectoryPermissions;
function setExecutableBit(pattern) {
    var setBit = es.mapSync(function (f) {
J
Joao 已提交
70
        f.stat.mode = /* 100755 */ 33261;
J
Joao Moreno 已提交
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
        return f;
    });
    if (!pattern) {
        return setBit;
    }
    var input = es.through();
    var filter = _filter(pattern, { restore: true });
    var output = input
        .pipe(filter)
        .pipe(setBit)
        .pipe(filter.restore);
    return es.duplex(input, output);
}
exports.setExecutableBit = setExecutableBit;
function toFileUri(filePath) {
    var match = filePath.match(/^([a-z])\:(.*)$/i);
    if (match) {
        filePath = '/' + match[1].toUpperCase() + ':' + match[2];
    }
    return 'file://' + filePath.replace(/\\/g, '/');
}
exports.toFileUri = toFileUri;
function skipDirectories() {
    return es.mapSync(function (f) {
        if (!f.isDirectory()) {
            return f;
        }
    });
}
exports.skipDirectories = skipDirectories;
function cleanNodeModule(name, excludes, includes) {
    var toGlob = function (path) { return '**/node_modules/' + name + (path ? '/' + path : ''); };
    var negate = function (str) { return '!' + str; };
    var allFilter = _filter(toGlob('**'), { restore: true });
    var globs = [toGlob('**')].concat(excludes.map(_.compose(negate, toGlob)));
    var input = es.through();
    var nodeModuleInput = input.pipe(allFilter);
    var output = nodeModuleInput.pipe(_filter(globs));
    if (includes) {
        var includeGlobs = includes.map(toGlob);
        output = es.merge(output, nodeModuleInput.pipe(_filter(includeGlobs)));
    }
    output = output.pipe(allFilter.restore);
    return es.duplex(input, output);
}
exports.cleanNodeModule = cleanNodeModule;
function loadSourcemaps() {
    var input = es.through();
    var output = input
        .pipe(es.map(function (f, cb) {
        if (f.sourceMap) {
122
            cb(undefined, f);
J
Joao Moreno 已提交
123 124 125 126 127 128 129 130
            return;
        }
        if (!f.contents) {
            cb(new Error('empty file'));
            return;
        }
        var contents = f.contents.toString('utf8');
        var reg = /\/\/# sourceMappingURL=(.*)$/g;
131 132
        var lastMatch = null;
        var match = null;
J
Joao Moreno 已提交
133 134 135 136 137 138 139 140 141 142 143
        while (match = reg.exec(contents)) {
            lastMatch = match;
        }
        if (!lastMatch) {
            f.sourceMap = {
                version: 3,
                names: [],
                mappings: '',
                sources: [f.relative.replace(/\//g, '/')],
                sourcesContent: [contents]
            };
144
            cb(undefined, f);
J
Joao Moreno 已提交
145 146
            return;
        }
J
Joao Moreno 已提交
147
        f.contents = Buffer.from(contents.replace(/\/\/# sourceMappingURL=(.*)$/g, ''), 'utf8');
J
Joao Moreno 已提交
148 149 150 151 152
        fs.readFile(path.join(path.dirname(f.path), lastMatch[1]), 'utf8', function (err, contents) {
            if (err) {
                return cb(err);
            }
            f.sourceMap = JSON.parse(contents);
153
            cb(undefined, f);
J
Joao Moreno 已提交
154 155 156 157 158 159 160 161 162 163
        });
    }));
    return es.duplex(input, output);
}
exports.loadSourcemaps = loadSourcemaps;
function stripSourceMappingURL() {
    var input = es.through();
    var output = input
        .pipe(es.mapSync(function (f) {
        var contents = f.contents.toString('utf8');
J
Joao Moreno 已提交
164
        f.contents = Buffer.from(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, ''), 'utf8');
J
Joao Moreno 已提交
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
        return f;
    }));
    return es.duplex(input, output);
}
exports.stripSourceMappingURL = stripSourceMappingURL;
function rimraf(dir) {
    var retries = 0;
    var retry = function (cb) {
        _rimraf(dir, { maxBusyTries: 1 }, function (err) {
            if (!err) {
                return cb();
            }
            if (err.code === 'ENOTEMPTY' && ++retries < 5) {
                return setTimeout(function () { return retry(cb); }, 10);
            }
            return cb(err);
        });
    };
    return function (cb) { return retry(cb); };
}
exports.rimraf = rimraf;
function getVersion(root) {
    var version = process.env['BUILD_SOURCEVERSION'];
    if (!version || !/^[0-9a-f]{40}$/i.test(version)) {
        version = git.getVersion(root);
    }
    return version;
}
exports.getVersion = getVersion;
function rebase(count) {
    return rename(function (f) {
196
        var parts = f.dirname ? f.dirname.split(/[\/\\]/) : [];
J
Joao Moreno 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
        f.dirname = parts.slice(count).join(path.sep);
    });
}
exports.rebase = rebase;
function filter(fn) {
    var result = es.through(function (data) {
        if (fn(data)) {
            this.emit('data', data);
        }
        else {
            result.restore.push(data);
        }
    });
    result.restore = es.through();
    return result;
}
exports.filter = filter;
214 215 216 217 218 219 220 221 222
function versionStringToNumber(versionStr) {
    var semverRegex = /(\d+)\.(\d+)\.(\d+)/;
    var match = versionStr.match(semverRegex);
    if (!match) {
        throw new Error('Version string is not properly formatted: ' + versionStr);
    }
    return parseInt(match[1], 10) * 1e4 + parseInt(match[2], 10) * 1e2 + parseInt(match[3], 10);
}
exports.versionStringToNumber = versionStringToNumber;