util.js 8.8 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
exports.getElectronVersion = exports.streamToPromise = exports.versionStringToNumber = exports.filter = exports.rebase = exports.getVersion = exports.ensureDir = exports.rreddir = exports.rimraf = exports.stripSourceMappingURL = exports.loadSourcemaps = exports.cleanNodeModules = exports.skipDirectories = exports.toFileUri = exports.setExecutableBit = exports.fixWin32DirectoryPermissions = exports.incremental = void 0;
8 9 10 11 12 13 14 15 16
const es = require("event-stream");
const debounce = require("debounce");
const _filter = require("gulp-filter");
const rename = require("gulp-rename");
const path = require("path");
const fs = require("fs");
const _rimraf = require("rimraf");
const git = require("./git");
const VinylFile = require("vinyl");
17
const root = path.dirname(path.dirname(__dirname));
18
const NoCancellationToken = { isCancellationRequested: () => false };
J
Joao Moreno 已提交
19
function incremental(streamProvider, initial, supportsCancellation) {
20 21 22 23 24 25
    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 已提交
26
        state = 'running';
27
        const stream = !supportsCancellation ? streamProvider() : streamProvider(isCancellable ? token : NoCancellationToken);
J
Joao Moreno 已提交
28 29
        input
            .pipe(stream)
30
            .pipe(es.through(undefined, () => {
J
Joao Moreno 已提交
31 32 33 34 35 36 37 38
            state = 'idle';
            eventuallyRun();
        }))
            .pipe(output);
    };
    if (initial) {
        run(initial, false);
    }
39 40
    const eventuallyRun = debounce(() => {
        const paths = Object.keys(buffer);
J
Joao Moreno 已提交
41 42 43
        if (paths.length === 0) {
            return;
        }
44
        const data = paths.map(path => buffer[path]);
J
Joao Moreno 已提交
45 46 47
        buffer = Object.create(null);
        run(es.readArray(data), true);
    }, 500);
48
    input.on('data', (f) => {
J
Joao Moreno 已提交
49 50 51 52 53 54 55 56 57 58 59 60
        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();
    }
61
    return es.mapSync(f => {
J
Joao Moreno 已提交
62 63 64 65 66 67 68 69
        if (f.stat && f.stat.isDirectory && f.stat.isDirectory()) {
            f.stat.mode = 16877;
        }
        return f;
    });
}
exports.fixWin32DirectoryPermissions = fixWin32DirectoryPermissions;
function setExecutableBit(pattern) {
70
    const setBit = es.mapSync(f => {
J
Joao Moreno 已提交
71 72 73
        if (!f.stat) {
            f.stat = { isFile() { return true; } };
        }
J
Joao 已提交
74
        f.stat.mode = /* 100755 */ 33261;
J
Joao Moreno 已提交
75 76 77 78 79
        return f;
    });
    if (!pattern) {
        return setBit;
    }
80 81 82
    const input = es.through();
    const filter = _filter(pattern, { restore: true });
    const output = input
J
Joao Moreno 已提交
83 84 85 86 87 88 89
        .pipe(filter)
        .pipe(setBit)
        .pipe(filter.restore);
    return es.duplex(input, output);
}
exports.setExecutableBit = setExecutableBit;
function toFileUri(filePath) {
90
    const match = filePath.match(/^([a-z])\:(.*)$/i);
J
Joao Moreno 已提交
91 92 93 94 95 96 97
    if (match) {
        filePath = '/' + match[1].toUpperCase() + ':' + match[2];
    }
    return 'file://' + filePath.replace(/\\/g, '/');
}
exports.toFileUri = toFileUri;
function skipDirectories() {
98
    return es.mapSync(f => {
J
Joao Moreno 已提交
99 100 101 102 103 104
        if (!f.isDirectory()) {
            return f;
        }
    });
}
exports.skipDirectories = skipDirectories;
105 106 107 108 109 110 111
function cleanNodeModules(rulePath) {
    const rules = fs.readFileSync(rulePath, 'utf8')
        .split(/\r?\n/g)
        .map(line => line.trim())
        .filter(line => line && !/^#/.test(line));
    const excludes = rules.filter(line => !/^!/.test(line)).map(line => `!**/node_modules/${line}`);
    const includes = rules.filter(line => /^!/.test(line)).map(line => `**/node_modules/${line.substr(1)}`);
112
    const input = es.through();
113
    const output = es.merge(input.pipe(_filter(['**', ...excludes])), input.pipe(_filter(includes)));
J
Joao Moreno 已提交
114 115
    return es.duplex(input, output);
}
116
exports.cleanNodeModules = cleanNodeModules;
J
Joao Moreno 已提交
117
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
            return;
        }
        if (!f.contents) {
126
            cb(undefined, f);
J
Joao Moreno 已提交
127 128
            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
                names: [],
                mappings: '',
B
Benjamin Pasero 已提交
141
                sources: [f.relative],
J
Joao Moreno 已提交
142 143
                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) {
J
Joao Moreno 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    const result = () => new Promise((c, e) => {
        let retries = 0;
        const retry = () => {
            _rimraf(dir, { maxBusyTries: 1 }, (err) => {
                if (!err) {
                    return c();
                }
                if (err.code === 'ENOTEMPTY' && ++retries < 5) {
                    return setTimeout(() => retry(), 10);
                }
                return e(err);
            });
        };
        retry();
    });
    result.taskName = `clean-${path.basename(dir).toLowerCase()}`;
    return result;
J
Joao Moreno 已提交
188 189
}
exports.rimraf = rimraf;
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
function _rreaddir(dirPath, prepend, result) {
    const entries = fs.readdirSync(dirPath, { withFileTypes: true });
    for (const entry of entries) {
        if (entry.isDirectory()) {
            _rreaddir(path.join(dirPath, entry.name), `${prepend}/${entry.name}`, result);
        }
        else {
            result.push(`${prepend}/${entry.name}`);
        }
    }
}
function rreddir(dirPath) {
    let result = [];
    _rreaddir(dirPath, '', result);
    return result;
}
exports.rreddir = rreddir;
function ensureDir(dirPath) {
    if (fs.existsSync(dirPath)) {
        return;
    }
    ensureDir(path.dirname(dirPath));
    fs.mkdirSync(dirPath);
}
exports.ensureDir = ensureDir;
J
Joao Moreno 已提交
215
function getVersion(root) {
216
    let version = process.env['BUILD_SOURCEVERSION'];
J
Joao Moreno 已提交
217 218 219 220 221 222 223
    if (!version || !/^[0-9a-f]{40}$/i.test(version)) {
        version = git.getVersion(root);
    }
    return version;
}
exports.getVersion = getVersion;
function rebase(count) {
224 225
    return rename(f => {
        const parts = f.dirname ? f.dirname.split(/[\/\\]/) : [];
J
Joao Moreno 已提交
226 227 228 229 230
        f.dirname = parts.slice(count).join(path.sep);
    });
}
exports.rebase = rebase;
function filter(fn) {
231
    const result = es.through(function (data) {
J
Joao Moreno 已提交
232 233 234 235 236 237 238 239 240 241 242
        if (fn(data)) {
            this.emit('data', data);
        }
        else {
            result.restore.push(data);
        }
    });
    result.restore = es.through();
    return result;
}
exports.filter = filter;
243
function versionStringToNumber(versionStr) {
244 245
    const semverRegex = /(\d+)\.(\d+)\.(\d+)/;
    const match = versionStr.match(semverRegex);
246 247 248 249 250 251
    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;
J
Joao Moreno 已提交
252 253 254 255 256 257 258
function streamToPromise(stream) {
    return new Promise((c, e) => {
        stream.on('error', err => e(err));
        stream.on('end', () => c());
    });
}
exports.streamToPromise = streamToPromise;
259 260 261 262 263 264
function getElectronVersion() {
    const yarnrc = fs.readFileSync(path.join(root, '.yarnrc'), 'utf8');
    const target = /^target "(.*)"$/m.exec(yarnrc)[1];
    return target;
}
exports.getElectronVersion = getElectronVersion;