util.js 6.4 KB
Newer Older
J
Joao Moreno 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

E
Erich Gamma 已提交
6 7 8 9 10 11 12 13 14 15 16
var es = require('event-stream');
var debounce = require('debounce');
var filter = require('gulp-filter');
var azure = require('gulp-azure-storage');
var rename = require('gulp-rename');
var vzip = require('gulp-vinyl-zip');
var util = require('gulp-util');
var _ = require('underscore');
var path = require('path');
var fs = require('fs');
var rimraf = require('rimraf');
J
Joao Moreno 已提交
17
var git = require('./git');
E
Erich Gamma 已提交
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

var NoCancellationToken = {
	isCancellationRequested: function () {
		return false;
	}
};

exports.incremental = function (streamProvider, initial, supportsCancellation) {
	var state = 'idle';
	var input = es.through();
	var output = es.through();
	var buffer = Object.create(null);

	var token = !supportsCancellation ? null : {
		isCancellationRequested: function () {
			// console.log('isCancellationRequested', Object.keys(buffer).length, new Date());
			return Object.keys(buffer).length > 0;
		}
	};

	var run = function (input, isCancellable) {
		state = 'running';

		var stream = !supportsCancellation ? streamProvider() : streamProvider(isCancellable ? token : NoCancellationToken);

		input
			.pipe(stream)
			.pipe(es.through(null, function () {
				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.fixWin32DirectoryPermissions = function () {
	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.setExecutableBit = function (pattern) {
	var setBit = es.mapSync(function (f) {
		f.stat.mode = /* 100755 */ 33261;
		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.handleAzureJson = function (env) {
	var input = es.through();
	var azureJsonFilter = filter('**/*.azure.json', { restore: true });

	var allOpts = [];
	var result = es.through();

	var output = input
		.pipe(azureJsonFilter)
		.pipe(es.through(function (f) {
			util.log('Downloading binaries from Azure:', util.colors.yellow(f.relative), '...');
			var opts = JSON.parse(f.contents.toString());
			opts.prefix = _.template(opts.zip || opts.prefix)(env);
			opts.output = path.join(path.dirname(f.relative), opts.output);
			allOpts.push(opts);
		}, function () {
			var streams = allOpts.map(function (opts) {
				var result = azure.download(_.extend(opts, { buffer: true, quiet: true }));

				if (opts.zip) {
					result = result.pipe(vzip.src());
				}

				return result.pipe(rename(function (p) {
					p.dirname = path.join(opts.output, p.dirname);
				}));
			});

			es.merge(streams)
				.pipe(result)
				.pipe(es.through(null, function() {
					util.log('Finished downloading from Azure');
					this.emit('end');
				}));
			this.emit('end');
		}))
		.pipe(azureJsonFilter.restore);

	return es.duplex(input, es.merge(output, result));
};

exports.toFileUri = function (filePath) {
	var match = filePath.match(/^([a-z])\:(.*)$/i);

	if (match) {
		filePath = '/' + match[1].toUpperCase() + ':' + match[2];
	}

	return 'file://' + filePath.replace(/\\/g, '/');
};

exports.rebase = function (base, append) {
	return es.mapSync(function (f) {
		if (append) {
			f.base = path.join(f.base, base);
		} else {
			f.base = base;
		}
		return f;
	});
};

exports.skipDirectories = function () {
	return es.mapSync(function (f) {
		if (!f.isDirectory()) {
			return f;
		}
	});
};

J
Joao Moreno 已提交
186
exports.cleanNodeModule = function (name, excludes, includes) {
E
Erich Gamma 已提交
187 188 189 190 191 192 193 194 195 196
	var glob = function (path) { return '**/node_modules/' + name + (path ? '/' + path : ''); };
	var negate = function (str) { return '!' + str; };

	var allFilter = filter(glob('**'), { restore: true });
	var globs = [glob('**')].concat(excludes.map(_.compose(negate, glob)));

	var input = es.through();
	var nodeModuleInput = input.pipe(allFilter);
	var output = nodeModuleInput.pipe(filter(globs));

J
Joao Moreno 已提交
197 198 199
	if (includes) {
		var includeGlobs = includes.map(glob);
		output = es.merge(output, nodeModuleInput.pipe(filter(includeGlobs)));
E
Erich Gamma 已提交
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
	}

	output = output.pipe(allFilter.restore);
	return es.duplex(input, output);
};

exports.loadSourcemaps = function () {
	var input = es.through();

	var output = input
		.pipe(es.map(function (f, cb) {
			if (f.sourceMap) {
				return cb(null, f);
			}

			if (!f.contents) {
				return cb(new Error('empty file'));
			}

			var contents = f.contents.toString('utf8');

			var reg = /\/\/# sourceMappingURL=(.*)$/g;
			var lastMatch = null;
			var match = null;

			while (match = reg.exec(contents)) {
				lastMatch = match;
			}

			if (!lastMatch) {
				f.sourceMap = {
					version : 3,
					names: [],
					mappings: '',
					sources: [f.relative.replace(/\//g, '/')],
					sourcesContent: [contents]
				};

				return cb(null, f);
			}

			f.contents = new Buffer(contents.replace(/\/\/# sourceMappingURL=(.*)$/g, ''), 'utf8');

			fs.readFile(path.join(path.dirname(f.path), lastMatch[1]), 'utf8', function (err, contents) {
				if (err) { return cb(err); }

				f.sourceMap = JSON.parse(contents);
				cb(null, f);
			});
		}));

	return es.duplex(input, output);
};

exports.rimraf = function(dir) {
	return function (cb) {
A
Alex Dima 已提交
256 257 258
		rimraf(dir, {
			maxBusyTries: 1
		}, cb);
E
Erich Gamma 已提交
259 260 261
	};
};

J
Joao Moreno 已提交
262 263 264 265 266 267 268 269
exports.getVersion = function (root) {
	var version = process.env['BUILD_SOURCEVERSION'];

	if (!version || !/^[0-9a-f]{40}$/i.test(version)) {
		version = git.getVersion(root);
	}

	return version;
J
Joao Moreno 已提交
270 271 272 273 274 275 276
};

exports.rebase = function (count) {
	return rename(function (f) {
		var parts = f.dirname.split(/[\/\\]/);
		f.dirname = parts.slice(count).join(path.sep);
	});
E
Erich Gamma 已提交
277
};