util.js 7.3 KB
Newer Older
J
Joao Moreno 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  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 });
7 8 9 10 11 12 13 14 15 16 17
const es = require("event-stream");
const debounce = require("debounce");
const _filter = require("gulp-filter");
const rename = require("gulp-rename");
const _ = require("underscore");
const path = require("path");
const fs = require("fs");
const _rimraf = require("rimraf");
const git = require("./git");
const VinylFile = require("vinyl");
const NoCancellationToken = { isCancellationRequested: () => false };
J
Joao Moreno 已提交
18
function incremental(streamProvider, initial, supportsCancellation) {
19 20 21 22 23 24
    const input = es.through();
    const output = es.through();
    let state = 'idle';
    let buffer = Object.create(null);
    const token = !supportsCancellation ? undefined : { isCancellationRequested: () => Object.keys(buffer).length > 0 };
    const run = (input, isCancellable) => {
J
Joao Moreno 已提交
25
        state = 'running';
26
        const stream = !supportsCancellation ? streamProvider() : streamProvider(isCancellable ? token : NoCancellationToken);
J
Joao Moreno 已提交
27 28
        input
            .pipe(stream)
29
            .pipe(es.through(undefined, () => {
J
Joao Moreno 已提交
30 31 32 33 34 35 36 37
            state = 'idle';
            eventuallyRun();
        }))
            .pipe(output);
    };
    if (initial) {
        run(initial, false);
    }
38 39
    const eventuallyRun = debounce(() => {
        const paths = Object.keys(buffer);
J
Joao Moreno 已提交
40 41 42
        if (paths.length === 0) {
            return;
        }
43
        const data = paths.map(path => buffer[path]);
J
Joao Moreno 已提交
44 45 46
        buffer = Object.create(null);
        run(es.readArray(data), true);
    }, 500);
47
    input.on('data', (f) => {
J
Joao Moreno 已提交
48 49 50 51 52 53 54 55 56 57 58 59
        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();
    }
60
    return es.mapSync(f => {
J
Joao Moreno 已提交
61 62 63 64 65 66 67 68
        if (f.stat && f.stat.isDirectory && f.stat.isDirectory()) {
            f.stat.mode = 16877;
        }
        return f;
    });
}
exports.fixWin32DirectoryPermissions = fixWin32DirectoryPermissions;
function setExecutableBit(pattern) {
69
    const setBit = es.mapSync(f => {
J
Joao 已提交
70
        f.stat.mode = /* 100755 */ 33261;
J
Joao Moreno 已提交
71 72 73 74 75
        return f;
    });
    if (!pattern) {
        return setBit;
    }
76 77 78
    const input = es.through();
    const filter = _filter(pattern, { restore: true });
    const output = input
J
Joao Moreno 已提交
79 80 81 82 83 84 85
        .pipe(filter)
        .pipe(setBit)
        .pipe(filter.restore);
    return es.duplex(input, output);
}
exports.setExecutableBit = setExecutableBit;
function toFileUri(filePath) {
86
    const match = filePath.match(/^([a-z])\:(.*)$/i);
J
Joao Moreno 已提交
87 88 89 90 91 92 93
    if (match) {
        filePath = '/' + match[1].toUpperCase() + ':' + match[2];
    }
    return 'file://' + filePath.replace(/\\/g, '/');
}
exports.toFileUri = toFileUri;
function skipDirectories() {
94
    return es.mapSync(f => {
J
Joao Moreno 已提交
95 96 97 98 99 100 101
        if (!f.isDirectory()) {
            return f;
        }
    });
}
exports.skipDirectories = skipDirectories;
function cleanNodeModule(name, excludes, includes) {
102 103 104 105 106 107 108
    const toGlob = (path) => '**/node_modules/' + name + (path ? '/' + path : '');
    const negate = (str) => '!' + str;
    const allFilter = _filter(toGlob('**'), { restore: true });
    const globs = [toGlob('**')].concat(excludes.map(_.compose(negate, toGlob)));
    const input = es.through();
    const nodeModuleInput = input.pipe(allFilter);
    let output = nodeModuleInput.pipe(_filter(globs));
J
Joao Moreno 已提交
109
    if (includes) {
110
        const includeGlobs = includes.map(toGlob);
J
Joao Moreno 已提交
111 112 113 114 115 116 117
        output = es.merge(output, nodeModuleInput.pipe(_filter(includeGlobs)));
    }
    output = output.pipe(allFilter.restore);
    return es.duplex(input, output);
}
exports.cleanNodeModule = cleanNodeModule;
function loadSourcemaps() {
118 119 120
    const input = es.through();
    const output = input
        .pipe(es.map((f, cb) => {
J
Joao Moreno 已提交
121
        if (f.sourceMap) {
122
            cb(undefined, f);
J
Joao Moreno 已提交
123 124 125 126 127 128
            return;
        }
        if (!f.contents) {
            cb(new Error('empty file'));
            return;
        }
129 130 131 132
        const contents = f.contents.toString('utf8');
        const reg = /\/\/# sourceMappingURL=(.*)$/g;
        let lastMatch = null;
        let match = null;
J
Joao Moreno 已提交
133 134 135 136 137
        while (match = reg.exec(contents)) {
            lastMatch = match;
        }
        if (!lastMatch) {
            f.sourceMap = {
138
                version: '3',
J
Joao Moreno 已提交
139 140 141 142 143
                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');
148
        fs.readFile(path.join(path.dirname(f.path), lastMatch[1]), 'utf8', (err, contents) => {
J
Joao Moreno 已提交
149 150 151 152
            if (err) {
                return cb(err);
            }
            f.sourceMap = JSON.parse(contents);
153
            cb(undefined, f);
J
Joao Moreno 已提交
154 155 156 157 158 159
        });
    }));
    return es.duplex(input, output);
}
exports.loadSourcemaps = loadSourcemaps;
function stripSourceMappingURL() {
160 161 162 163
    const input = es.through();
    const output = input
        .pipe(es.mapSync(f => {
        const 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
        return f;
    }));
    return es.duplex(input, output);
}
exports.stripSourceMappingURL = stripSourceMappingURL;
function rimraf(dir) {
171 172 173
    let retries = 0;
    const retry = (cb) => {
        _rimraf(dir, { maxBusyTries: 1 }, (err) => {
J
Joao Moreno 已提交
174 175 176 177
            if (!err) {
                return cb();
            }
            if (err.code === 'ENOTEMPTY' && ++retries < 5) {
178
                return setTimeout(() => retry(cb), 10);
J
Joao Moreno 已提交
179 180 181 182
            }
            return cb(err);
        });
    };
A
Alex Dima 已提交
183 184
    retry.displayName = `clean-${path.basename(dir)}`;
    return retry;
J
Joao Moreno 已提交
185 186 187
}
exports.rimraf = rimraf;
function getVersion(root) {
188
    let version = process.env['BUILD_SOURCEVERSION'];
J
Joao Moreno 已提交
189 190 191 192 193 194 195
    if (!version || !/^[0-9a-f]{40}$/i.test(version)) {
        version = git.getVersion(root);
    }
    return version;
}
exports.getVersion = getVersion;
function rebase(count) {
196 197
    return rename(f => {
        const parts = f.dirname ? f.dirname.split(/[\/\\]/) : [];
J
Joao Moreno 已提交
198 199 200 201 202
        f.dirname = parts.slice(count).join(path.sep);
    });
}
exports.rebase = rebase;
function filter(fn) {
203
    const result = es.through(function (data) {
J
Joao Moreno 已提交
204 205 206 207 208 209 210 211 212 213 214
        if (fn(data)) {
            this.emit('data', data);
        }
        else {
            result.restore.push(data);
        }
    });
    result.restore = es.through();
    return result;
}
exports.filter = filter;
215
function versionStringToNumber(versionStr) {
216 217
    const semverRegex = /(\d+)\.(\d+)\.(\d+)/;
    const match = versionStr.match(semverRegex);
218 219 220 221 222 223
    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;