提交 d904442b 编写于 作者: A Alex Dima

Convert build/lib/util.js to TypeScript

上级 d443f846
......@@ -298,7 +298,7 @@ export function processNlsFiles(opts:{fileHeader:string;}): ThroughStream {
if (fileName === 'nls.metadata.json') {
let json = null;
if (file.isBuffer()) {
json = JSON.parse(file.contents.toString('utf8'));
json = JSON.parse((<Buffer>file.contents).toString('utf8'));
} else {
this.emit('error', `Failed to read component file: ${file.relative}`);
}
......
此差异已折叠。
// Type definitions for compose-function
// Project: https://github.com/component/debounce
// Definitions by: Denis Sokolov <https://github.com/denis-sokolov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "debounce" {
// Overload on boolean constants would allow us to narrow further,
// but it is not implemented for TypeScript yet
function f<A extends Function>(f: A, interval?: number, immediate?: boolean): A
/**
* This is required as per:
* https://github.com/Microsoft/TypeScript/issues/5073
*/
namespace f {}
export = f;
}
\ No newline at end of file
// Type definitions for gulp-filter v3.0.1
// Project: https://github.com/sindresorhus/gulp-filter
// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'gulp-filter' {
import { ThroughStream } from 'through';
import File = require('vinyl');
import * as Minimatch from 'minimatch';
namespace filter {
interface FileFunction {
(file: File): boolean;
}
interface Options extends Minimatch.IOptions {
restore?: boolean;
passthrough?: boolean;
}
// A transform stream with a .restore object
interface Filter extends NodeJS.ReadWriteStream {
restore: NodeJS.ReadWriteStream
}
}
function fn(pattern: string): ThroughStream;
function fn(patterns: string[]): ThroughStream;
function filter(pattern: string | string[] | filter.FileFunction, options?: filter.Options): filter.Filter;
export = fn;
export = filter;
}
\ No newline at end of file
// Type definitions for gulp-rename
// Project: https://github.com/hparra/gulp-rename
// Definitions by: Asana <https://asana.com>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "gulp-rename" {
interface ParsedPath {
dirname?: string;
basename?: string;
extname?: string;
}
interface Options extends ParsedPath {
prefix?: string;
suffix?: string;
}
function rename(name: string): NodeJS.ReadWriteStream;
function rename(callback: (path: ParsedPath) => any): NodeJS.ReadWriteStream;
function rename(opts: Options): NodeJS.ReadWriteStream;
/**
* This is required as per:
* https://github.com/Microsoft/TypeScript/issues/5073
*/
namespace rename {}
export = rename;
}
\ No newline at end of file
// Type definitions for Gulp v3.8.x
// Project: http://gulpjs.com
// Definitions by: Drew Noakes <https://drewnoakes.com>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "gulp" {
import Orchestrator = require("orchestrator");
import VinylFile = require("vinyl");
namespace gulp {
interface Gulp extends Orchestrator {
/**
* Define a task
* @param name The name of the task.
* @param deps An array of task names to be executed and completed before your task will run.
* @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete:
* <ul>
* <li>Take in a callback</li>
* <li>Return a stream or a promise</li>
* </ul>
*/
task: Orchestrator.AddMethod;
/**
* Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.
* @param glob Glob or array of globs to read.
* @param opt Options to pass to node-glob through glob-stream.
*/
src: SrcMethod;
/**
* Can be piped to and it will write files. Re-emits all data passed to it so you can pipe to multiple folders.
* Folders that don't exist will be created.
*
* @param outFolder The path (output folder) to write files to. Or a function that returns it, the function will be provided a vinyl File instance.
* @param opt
*/
dest: DestMethod;
/**
* Watch files and do something when a file changes. This always returns an EventEmitter that emits change events.
*
* @param glob a single glob or array of globs that indicate which files to watch for changes.
* @param opt options, that are passed to the gaze library.
* @param fn a callback or array of callbacks to be called on each change, or names of task(s) to run when a file changes, added with task().
*/
watch: WatchMethod;
}
interface GulpPlugin {
(...args: any[]): NodeJS.ReadWriteStream;
}
interface WatchMethod {
/**
* Watch files and do something when a file changes. This always returns an EventEmitter that emits change events.
*
* @param glob a single glob or array of globs that indicate which files to watch for changes.
* @param fn a callback or array of callbacks to be called on each change, or names of task(s) to run when a file changes, added with task().
*/
(glob: string|string[], fn: (WatchCallback|string)): NodeJS.EventEmitter;
/**
* Watch files and do something when a file changes. This always returns an EventEmitter that emits change events.
*
* @param glob a single glob or array of globs that indicate which files to watch for changes.
* @param fn a callback or array of callbacks to be called on each change, or names of task(s) to run when a file changes, added with task().
*/
(glob: string|string[], fn: (WatchCallback|string)[]): NodeJS.EventEmitter;
/**
* Watch files and do something when a file changes. This always returns an EventEmitter that emits change events.
*
* @param glob a single glob or array of globs that indicate which files to watch for changes.
* @param opt options, that are passed to the gaze library.
* @param fn a callback or array of callbacks to be called on each change, or names of task(s) to run when a file changes, added with task().
*/
(glob: string|string[], opt: WatchOptions, fn: (WatchCallback|string)): NodeJS.EventEmitter;
/**
* Watch files and do something when a file changes. This always returns an EventEmitter that emits change events.
*
* @param glob a single glob or array of globs that indicate which files to watch for changes.
* @param opt options, that are passed to the gaze library.
* @param fn a callback or array of callbacks to be called on each change, or names of task(s) to run when a file changes, added with task().
*/
(glob: string|string[], opt: WatchOptions, fn: (WatchCallback|string)[]): NodeJS.EventEmitter;
}
interface DestMethod {
/**
* Can be piped to and it will write files. Re-emits all data passed to it so you can pipe to multiple folders.
* Folders that don't exist will be created.
*
* @param outFolder The path (output folder) to write files to. Or a function that returns it, the function will be provided a vinyl File instance.
* @param opt
*/
(outFolder: string|((file: VinylFile) => string), opt?: DestOptions): NodeJS.ReadWriteStream;
}
interface SrcMethod {
/**
* Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.
* @param glob Glob or array of globs to read.
* @param opt Options to pass to node-glob through glob-stream.
*/
(glob: string|string[], opt?: SrcOptions): NodeJS.ReadWriteStream;
}
/**
* Options to pass to node-glob through glob-stream.
* Specifies two options in addition to those used by node-glob:
* https://github.com/isaacs/node-glob#options
*/
interface SrcOptions {
/**
* Setting this to <code>false</code> will return <code>file.contents</code> as <code>null</code>
* and not read the file at all.
* Default: <code>true</code>.
*/
read?: boolean;
/**
* Setting this to false will return <code>file.contents</code> as a stream and not buffer files.
* This is useful when working with large files.
* Note: Plugins might not implement support for streams.
* Default: <code>true</code>.
*/
buffer?: boolean;
/**
* The base path of a glob.
*
* Default is everything before a glob starts.
*/
base?: string;
/**
* The current working directory in which to search.
* Defaults to process.cwd().
*/
cwd?: string;
/**
* The place where patterns starting with / will be mounted onto.
* Defaults to path.resolve(options.cwd, "/") (/ on Unix systems, and C:\ or some such on Windows.)
*/
root?: string;
/**
* Include .dot files in normal matches and globstar matches.
* Note that an explicit dot in a portion of the pattern will always match dot files.
*/
dot?: boolean;
/**
* Set to match only fles, not directories. Set this flag to prevent copying empty directories
*/
nodir?: boolean;
/**
* By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid
* filesystem path is returned. Set this flag to disable that behavior.
*/
nomount?: boolean;
/**
* Add a / character to directory matches. Note that this requires additional stat calls.
*/
mark?: boolean;
/**
* Don't sort the results.
*/
nosort?: boolean;
/**
* Set to true to stat all results. This reduces performance somewhat, and is completely unnecessary, unless
* readdir is presumed to be an untrustworthy indicator of file existence. It will cause ELOOP to be triggered one
* level sooner in the case of cyclical symbolic links.
*/
stat?: boolean;
/**
* When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr.
* Set the silent option to true to suppress these warnings.
*/
silent?: boolean;
/**
* When an unusual error is encountered when attempting to read a directory, the process will just continue on in
* search of other matches. Set the strict option to raise an error in these cases.
*/
strict?: boolean;
/**
* See cache property above. Pass in a previously generated cache object to save some fs calls.
*/
cache?: boolean;
/**
* A cache of results of filesystem information, to prevent unnecessary stat calls.
* While it should not normally be necessary to set this, you may pass the statCache from one glob() call to the
* options object of another, if you know that the filesystem will not change between calls.
*/
statCache?: boolean;
/**
* Perform a synchronous glob search.
*/
sync?: boolean;
/**
* In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set.
* By default, this implementation prevents duplicates in the result set. Set this flag to disable that behavior.
*/
nounique?: boolean;
/**
* Set to never return an empty set, instead returning a set containing the pattern itself.
* This is the default in glob(3).
*/
nonull?: boolean;
/**
* Perform a case-insensitive match. Note that case-insensitive filesystems will sometimes result in glob returning
* results that are case-insensitively matched anyway, since readdir and stat will not raise an error.
*/
nocase?: boolean;
/**
* Set to enable debug logging in minimatch and glob.
*/
debug?: boolean;
/**
* Set to enable debug logging in glob, but not minimatch.
*/
globDebug?: boolean;
}
interface DestOptions {
/**
* The output folder. Only has an effect if provided output folder is relative.
* Default: process.cwd()
*/
cwd?: string;
/**
* Octal permission string specifying mode for any folders that need to be created for output folder.
* Default: 0777.
*/
mode?: string;
}
/**
* Options that are passed to <code>gaze</code>.
* https://github.com/shama/gaze
*/
interface WatchOptions {
/** Interval to pass to fs.watchFile. */
interval?: number;
/** Delay for events called in succession for the same file/event. */
debounceDelay?: number;
/** Force the watch mode. Either 'auto' (default), 'watch' (force native events), or 'poll' (force stat polling). */
mode?: string;
/** The current working directory to base file patterns from. Default is process.cwd().. */
cwd?: string;
}
interface WatchEvent {
/** The type of change that occurred, either added, changed or deleted. */
type: string;
/** The path to the file that triggered the event. */
path: string;
}
/**
* Callback to be called on each watched file change.
*/
interface WatchCallback {
(event: WatchEvent): void;
}
interface TaskCallback {
/**
* Defines a task.
* Tasks may be made asynchronous if they are passing a callback or return a promise or a stream.
* @param cb callback used to signal asynchronous completion. Caller includes <code>err</code> in case of error.
*/
(cb?: (err?: any) => void): any;
}
}
var gulp: gulp.Gulp;
export = gulp;
}
\ No newline at end of file
// Type definitions for Minimatch 2.0.8
// Project: https://github.com/isaacs/minimatch
// Definitions by: vvakame <https://github.com/vvakame/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "minimatch" {
function M(target: string, pattern: string, options?: M.IOptions): boolean;
namespace M {
function match(list: string[], pattern: string, options?: IOptions): string[];
function filter(pattern: string, options?: IOptions): (element: string, indexed: number, array: string[]) => boolean;
function makeRe(pattern: string, options?: IOptions): RegExp;
var Minimatch: IMinimatchStatic;
interface IOptions {
debug?: boolean;
nobrace?: boolean;
noglobstar?: boolean;
dot?: boolean;
noext?: boolean;
nocase?: boolean;
nonull?: boolean;
matchBase?: boolean;
nocomment?: boolean;
nonegate?: boolean;
flipNegate?: boolean;
}
interface IMinimatchStatic {
new (pattern: string, options?: IOptions): IMinimatch;
prototype: IMinimatch;
}
interface IMinimatch {
pattern: string;
options: IOptions;
/** 2-dimensional array of regexp or string expressions. */
set: any[][]; // (RegExp | string)[][]
regexp: RegExp;
negate: boolean;
comment: boolean;
empty: boolean;
makeRe(): RegExp; // regexp or boolean
match(fname: string): boolean;
matchOne(files: string[], pattern: string[], partial: boolean): boolean;
/** Deprecated. For internal use. */
debug(): void;
/** Deprecated. For internal use. */
make(): void;
/** Deprecated. For internal use. */
parseNegate(): void;
/** Deprecated. For internal use. */
braceExpand(pattern: string, options: IOptions): void;
/** Deprecated. For internal use. */
parse(pattern: string, isSub?: boolean): void;
}
}
export = M;
}
\ No newline at end of file
// Type definitions for Orchestrator
// Project: https://github.com/orchestrator/orchestrator
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare type Strings = string|string[];
declare module "orchestrator" {
class Orchestrator {
add: Orchestrator.AddMethod;
/**
* Have you defined a task with this name?
* @param name The task name to query
*/
hasTask(name: string): boolean;
start: Orchestrator.StartMethod;
stop(): void;
/**
* Listen to orchestrator internals
* @param event Event name to listen to:
* <ul>
* <li>start: from start() method, shows you the task sequence
* <li>stop: from stop() method, the queue finished successfully
* <li>err: from stop() method, the queue was aborted due to a task error
* <li>task_start: from _runTask() method, task was started
* <li>task_stop: from _runTask() method, task completed successfully
* <li>task_err: from _runTask() method, task errored
* <li>task_not_found: from start() method, you're trying to start a task that doesn't exist
* <li>task_recursion: from start() method, there are recursive dependencies in your task list
* </ul>
* @param cb Passes single argument: e: event details
*/
on(event: string, cb: (e: Orchestrator.OnCallbackEvent) => any): Orchestrator;
/**
* Listen to all orchestrator events from one callback
* @param cb Passes single argument: e: event details
*/
onAll(cb: (e: Orchestrator.OnAllCallbackEvent) => any): void;
}
namespace Orchestrator {
interface AddMethodCallback {
/**
* Accept a callback
* @param callback
*/
(callback?: Function): any;
/**
* Return a promise
*/
(): Q.Promise<any>;
/**
* Return a stream: (task is marked complete when stream ends)
*/
(): any; //TODO: stream type should be here e.g. map-stream
}
/**
* Define a task
*/
interface AddMethod {
/**
* Define a task
* @param name The name of the task.
* @param deps An array of task names to be executed and completed before your task will run.
* @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete:
* <ul>
* <li>Take in a callback</li>
* <li>Return a stream or a promise</li>
* </ul>
*/
(name: string, deps?: string[], fn?: AddMethodCallback|Function): Orchestrator;
/**
* Define a task
* @param name The name of the task.
* @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete:
* <ul>
* <li>Take in a callback</li>
* <li>Return a stream or a promise</li>
* </ul>
*/
(name: string, fn?: AddMethodCallback|Function): Orchestrator;
}
/**
* Start running the tasks
*/
interface StartMethod {
/**
* Start running the tasks
* @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments.
* @param cb Callback to call after run completed.
*/
(tasks: Strings, cb?: (error?: any) => any): Orchestrator;
/**
* Start running the tasks
* @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments.
* @param cb Callback to call after run completed.
*/
(...tasks: Strings[]/*, cb?: (error: any) => any */): Orchestrator;
//TODO: TypeScript 1.5.3 cannot express varargs followed by callback as a last argument...
(task1: Strings, task2: Strings, cb?: (error?: any) => any): Orchestrator;
(task1: Strings, task2: Strings, task3: Strings, cb?: (error?: any) => any): Orchestrator;
(task1: Strings, task2: Strings, task3: Strings, task4: Strings, cb?: (error?: any) => any): Orchestrator;
(task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, cb?: (error?: any) => any): Orchestrator;
(task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, task6: Strings, cb?: (error?: any) => any): Orchestrator;
}
interface OnCallbackEvent {
message: string;
task: string;
err: any;
duration?: number;
}
interface OnAllCallbackEvent extends OnCallbackEvent {
src: string;
}
}
export = Orchestrator;
}
\ No newline at end of file
// Type definitions for rimraf
// Project: https://github.com/isaacs/rimraf
// Definitions by: Carlos Ballesteros Velasco <https://github.com/soywiz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Imported from: https://github.com/soywiz/typescript-node-definitions/rimraf.d.ts
declare module "rimraf" {
function rimraf(path: string, callback: (error: Error) => void): void;
function rimraf(path: string, opts:{}, callback: (error: Error) => void): void;
namespace rimraf {
export function sync(path: string): void;
export var EMFILE_MAX: number;
export var BUSYTRIES_MAX: number;
}
export = rimraf;
}
\ No newline at end of file
// Type definitions for source-map v0.1.38
// Project: https://github.com/mozilla/source-map
// Definitions by: Morten Houston Ludvigsen <https://github.com/MortenHoustonLudvigsen>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module SourceMap {
declare namespace SourceMap {
interface StartOfSourceMap {
file?: string;
sourceRoot?: string;
}
interface RawSourceMap extends StartOfSourceMap {
version: string;
version: string|number;
sources: Array<string>;
names: Array<string>;
sourcesContent?: string;
sourcesContent?: string[];
mappings: string;
}
......@@ -66,6 +66,7 @@ declare module SourceMap {
public setSourceContent(sourceFile: string, sourceContent: string): void;
public applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void;
public toString(): string;
public toJSON(): RawSourceMap;
}
class SourceNode {
......@@ -73,8 +74,8 @@ declare module SourceMap {
constructor(line: number, column: number, source: string);
constructor(line: number, column: number, source: string, chunk?: string, name?: string);
public static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode;
public add(chunk: string): void;
public prepend(chunk: string): void;
public add(chunk: any): SourceNode;
public prepend(chunk: any): SourceNode;
public setSourceContent(sourceFile: string, sourceContent: string): void;
public walk(fn: (chunk: string, mapping: MappedPosition) => void): void;
public walkSourceContents(fn: (file: string, content: string) => void): void;
......@@ -87,4 +88,4 @@ declare module SourceMap {
declare module 'source-map' {
export = SourceMap;
}
}
\ No newline at end of file
此差异已折叠。
// Type definitions for vinyl 0.4.3
// Project: https://github.com/wearefractal/vinyl
// Definitions by: vvakame <https://github.com/vvakame/>, jedmao <https://github.com/jedmao>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'vinyl' {
declare module "vinyl" {
import fs = require('fs');
import fs = require("fs");
/**
* A virtual file format.
*/
* A virtual file format.
*/
class File {
constructor(options?: {
/**
......@@ -17,46 +17,55 @@ declare module 'vinyl' {
*/
cwd?: string;
/**
* Used for relative pathing. Typically where a glob starts.
*/
* Used for relative pathing. Typically where a glob starts.
*/
base?: string;
/**
* Full path to the file.
*/
* Full path to the file.
*/
path?: string;
/**
* Type: Buffer|Stream|null (Default: null)
*/
contents?: any;
* Path history. Has no effect if options.path is passed.
*/
history?: string[];
/**
* The result of an fs.stat call. See fs.Stats for more information.
*/
stat?: fs.Stats;
/**
* File contents.
* Type: Buffer, Stream, or null
*/
contents?: Buffer | NodeJS.ReadWriteStream;
});
/**
* Default: process.cwd()
*/
* Default: process.cwd()
*/
public cwd: string;
/**
* Used for relative pathing. Typically where a glob starts.
*/
* Used for relative pathing. Typically where a glob starts.
*/
public base: string;
/**
* Full path to the file.
*/
* Full path to the file.
*/
public path: string;
public stat: fs.Stats;
/**
* Type: Buffer|Stream|null (Default: null)
*/
public contents: any;
* Type: Buffer|Stream|null (Default: null)
*/
public contents: Buffer | NodeJS.ReadableStream;
/**
* Returns path.relative for the file base and file path.
* Example:
* var file = new File({
* cwd: "/",
* base: "/test/",
* path: "/test/file.js"
* });
* console.log(file.relative); // file.js
*/
* Returns path.relative for the file base and file path.
* Example:
* var file = new File({
* cwd: "/",
* base: "/test/",
* path: "/test/file.js"
* });
* console.log(file.relative); // file.js
*/
public relative: string;
public isBuffer(): boolean;
......@@ -68,31 +77,36 @@ declare module 'vinyl' {
public isDirectory(): boolean;
/**
* Returns a new File object with all attributes cloned. Custom attributes are deep-cloned.
*/
* Returns a new File object with all attributes cloned. Custom attributes are deep-cloned.
*/
public clone(opts?: { contents?: boolean }): File;
/**
* If file.contents is a Buffer, it will write it to the stream.
* If file.contents is a Stream, it will pipe it to the stream.
* If file.contents is null, it will do nothing.
*/
* If file.contents is a Buffer, it will write it to the stream.
* If file.contents is a Stream, it will pipe it to the stream.
* If file.contents is null, it will do nothing.
*/
public pipe<T extends NodeJS.ReadWriteStream>(
stream: T,
opts?: {
/**
* If false, the destination stream will not be ended (same as node core).
*/
* If false, the destination stream will not be ended (same as node core).
*/
end?: boolean;
}
): T;
}): T;
/**
* Returns a pretty String interpretation of the File. Useful for console.log.
*/
* Returns a pretty String interpretation of the File. Useful for console.log.
*/
public inspect(): string;
}
/**
* This is required as per:
* https://github.com/Microsoft/TypeScript/issues/5073
*/
namespace File {}
export = File;
}
}
\ No newline at end of file
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
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 NoCancellationToken = { isCancellationRequested: () => false };
exports.incremental = (streamProvider, initial, supportsCancellation) => {
const input = es.through();
const output = es.through();
let state = 'idle';
let buffer = Object.create(null);
const token = !supportsCancellation ? null : { isCancellationRequested: () => Object.keys(buffer).length > 0 };
const run = (input, isCancellable) => {
state = 'running';
const stream = !supportsCancellation ? streamProvider() : streamProvider(isCancellable ? token : NoCancellationToken);
input
.pipe(stream)
.pipe(es.through(null, () => {
state = 'idle';
eventuallyRun();
}))
.pipe(output);
};
if (initial) {
run(initial, false);
}
const eventuallyRun = debounce(() => {
const paths = Object.keys(buffer);
if (paths.length === 0) {
return;
}
const data = paths.map(path => buffer[path]);
buffer = Object.create(null);
run(es.readArray(data), true);
}, 500);
input.on('data', f => {
buffer[f.path] = f;
if (state === 'idle') {
eventuallyRun();
}
});
return es.duplex(input, output);
};
exports.fixWin32DirectoryPermissions = () => {
if (!/win32/.test(process.platform)) {
return es.through();
}
return es.mapSync(f => {
if (f.stat && f.stat.isDirectory && f.stat.isDirectory()) {
f.stat.mode = 16877;
}
return f;
});
};
exports.setExecutableBit = pattern => {
var setBit = es.mapSync(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.toFileUri = filePath => {
const match = filePath.match(/^([a-z])\:(.*)$/i);
if (match) {
filePath = '/' + match[1].toUpperCase() + ':' + match[2];
}
return 'file://' + filePath.replace(/\\/g, '/');
};
exports.skipDirectories = () => {
return es.mapSync(f => {
if (!f.isDirectory()) {
return f;
}
});
};
exports.cleanNodeModule = (name, excludes, includes) => {
const glob = path => '**/node_modules/' + name + (path ? '/' + path : '');
const negate = str => '!' + str;
const allFilter = filter(glob('**'), { restore: true });
const globs = [glob('**')].concat(excludes.map(_.compose(negate, glob)));
const input = es.through();
const nodeModuleInput = input.pipe(allFilter);
let output = nodeModuleInput.pipe(filter(globs));
if (includes) {
const includeGlobs = includes.map(glob);
output = es.merge(output, nodeModuleInput.pipe(filter(includeGlobs)));
}
output = output.pipe(allFilter.restore);
return es.duplex(input, output);
};
exports.loadSourcemaps = () => {
const input = es.through();
const output = input
.pipe(es.map((f, cb) => {
if (f.sourceMap) {
return cb(null, f);
}
if (!f.contents) {
return cb(new Error('empty file'));
}
const contents = f.contents.toString('utf8');
const reg = /\/\/# sourceMappingURL=(.*)$/g;
let lastMatch = null, 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', (err, contents) => {
if (err) { return cb(err); }
f.sourceMap = JSON.parse(contents);
cb(null, f);
});
}));
return es.duplex(input, output);
};
exports.stripSourceMappingURL = () => {
const input = es.through();
const output = input
.pipe(es.mapSync(f => {
const contents = f.contents.toString('utf8');
f.contents = new Buffer(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, ''), 'utf8');
return f;
}));
return es.duplex(input, output);
};
exports.rimraf = dir => {
let retries = 0;
const retry = cb => {
rimraf(dir, { maxBusyTries: 1 }, err => {
if (!err) return cb();
if (err.code === 'ENOTEMPTY' && ++retries < 5) return setTimeout(() => retry(cb), 10);
else return cb(err);
});
};
return cb => retry(cb);
};
exports.getVersion = root => {
let version = process.env['BUILD_SOURCEVERSION'];
if (!version || !/^[0-9a-f]{40}$/i.test(version)) {
version = git.getVersion(root);
}
return version;
};
exports.rebase = count => {
return rename(f => {
const parts = f.dirname.split(/[\/\\]/);
f.dirname = parts.slice(count).join(path.sep);
});
};
exports.filter = fn => {
const result = es.through(function (data) {
if (fn(data)) {
this.emit('data', data);
} else {
result.restore.push(data);
}
});
result.restore = es.through();
return result;
};
\ No newline at end of file
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
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);
var token = !supportsCancellation ? null : { isCancellationRequested: function () { 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.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) {
f.stat.mode = 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.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 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));
if (includes) {
var includeGlobs = includes.map(glob);
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) {
cb(null, f);
return;
}
if (!f.contents) {
cb(new Error('empty file'));
return;
}
var contents = f.contents.toString('utf8');
var reg = /\/\/# sourceMappingURL=(.*)$/g;
var lastMatch = null, match = null;
while (match = reg.exec(contents)) {
lastMatch = match;
}
if (!lastMatch) {
f.sourceMap = {
version: 3,
names: [],
mappings: '',
sources: [f.relative.replace(/\//g, '/')],
sourcesContent: [contents]
};
cb(null, f);
return;
}
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.loadSourcemaps = loadSourcemaps;
function stripSourceMappingURL() {
var input = es.through();
var output = input
.pipe(es.mapSync(function (f) {
var contents = f.contents.toString('utf8');
f.contents = new Buffer(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, ''), 'utf8');
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);
else
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) {
var parts = f.dirname.split(/[\/\\]/);
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;
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as es from 'event-stream';
import * as debounce from 'debounce';
import * as _filter from 'gulp-filter';
import * as rename from 'gulp-rename';
import * as _ from 'underscore';
import * as path from 'path';
import * as fs from 'fs';
import * as _rimraf from 'rimraf';
import * as git from './git';
import * as VinylFile from 'vinyl';
import { ThroughStream } from 'through';
import * as sm from 'source-map';
export interface ICancellationToken {
isCancellationRequested(): boolean;
}
const NoCancellationToken:ICancellationToken = { isCancellationRequested: () => false };
export interface IStreamProvider {
(cancellationToken?:ICancellationToken): NodeJS.ReadWriteStream;
}
export function incremental(streamProvider:IStreamProvider, initial:NodeJS.ReadWriteStream, supportsCancellation:boolean): NodeJS.ReadWriteStream {
const input = es.through();
const output = es.through();
let state = 'idle';
let buffer = Object.create(null);
const token:ICancellationToken = !supportsCancellation ? null : { isCancellationRequested: () => Object.keys(buffer).length > 0 };
const run = (input, isCancellable) => {
state = 'running';
const stream = !supportsCancellation ? streamProvider() : streamProvider(isCancellable ? token : NoCancellationToken);
input
.pipe(stream)
.pipe(es.through(null, () => {
state = 'idle';
eventuallyRun();
}))
.pipe(output);
};
if (initial) {
run(initial, false);
}
const eventuallyRun = debounce(() => {
const paths = Object.keys(buffer);
if (paths.length === 0) {
return;
}
const data = paths.map(path => buffer[path]);
buffer = Object.create(null);
run(es.readArray(data), true);
}, 500);
input.on('data', f => {
buffer[f.path] = f;
if (state === 'idle') {
eventuallyRun();
}
});
return es.duplex(input, output);
}
export function fixWin32DirectoryPermissions(): NodeJS.ReadWriteStream {
if (!/win32/.test(process.platform)) {
return es.through();
}
return es.mapSync<VinylFile,VinylFile>(f => {
if (f.stat && f.stat.isDirectory && f.stat.isDirectory()) {
f.stat.mode = 16877;
}
return f;
});
}
export function setExecutableBit(pattern: string | string[]): NodeJS.ReadWriteStream {
var setBit = es.mapSync<VinylFile,VinylFile>(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);
}
export function toFileUri(filePath:string): string {
const match = filePath.match(/^([a-z])\:(.*)$/i);
if (match) {
filePath = '/' + match[1].toUpperCase() + ':' + match[2];
}
return 'file://' + filePath.replace(/\\/g, '/');
}
export function skipDirectories(): NodeJS.ReadWriteStream {
return es.mapSync<VinylFile,VinylFile>(f => {
if (!f.isDirectory()) {
return f;
}
});
}
export function cleanNodeModule(name:string, excludes:string[], includes:string[]): NodeJS.ReadWriteStream {
const glob = (path:string) => '**/node_modules/' + name + (path ? '/' + path : '');
const negate = (str:string) => '!' + str;
const allFilter = _filter(glob('**'), { restore: true });
const globs = [glob('**')].concat(excludes.map(_.compose(negate, glob)));
const input = es.through();
const nodeModuleInput = input.pipe(allFilter);
let output:NodeJS.ReadWriteStream = nodeModuleInput.pipe(_filter(globs));
if (includes) {
const includeGlobs = includes.map(glob);
output = es.merge(output, nodeModuleInput.pipe(_filter(includeGlobs)));
}
output = output.pipe(allFilter.restore);
return es.duplex(input, output);
}
declare class FileSourceMap extends VinylFile {
public sourceMap: sm.RawSourceMap;
}
export function loadSourcemaps(): NodeJS.ReadWriteStream {
const input = es.through();
const output = input
.pipe(es.map<FileSourceMap,FileSourceMap>((f, cb): FileSourceMap => {
if (f.sourceMap) {
cb(null, f);
return;
}
if (!f.contents) {
cb(new Error('empty file'));
return;
}
const contents = (<Buffer>f.contents).toString('utf8');
const reg = /\/\/# sourceMappingURL=(.*)$/g;
let lastMatch = null, match = null;
while (match = reg.exec(contents)) {
lastMatch = match;
}
if (!lastMatch) {
f.sourceMap = {
version: 3,
names: [],
mappings: '',
sources: [f.relative.replace(/\//g, '/')],
sourcesContent: [contents]
};
cb(null, f);
return;
}
f.contents = new Buffer(contents.replace(/\/\/# sourceMappingURL=(.*)$/g, ''), 'utf8');
fs.readFile(path.join(path.dirname(f.path), lastMatch[1]), 'utf8', (err, contents) => {
if (err) { return cb(err); }
f.sourceMap = JSON.parse(contents);
cb(null, f);
});
}));
return es.duplex(input, output);
}
export function stripSourceMappingURL(): NodeJS.ReadWriteStream {
const input = es.through();
const output = input
.pipe(es.mapSync<VinylFile,VinylFile>(f => {
const contents = (<Buffer>f.contents).toString('utf8');
f.contents = new Buffer(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, ''), 'utf8');
return f;
}));
return es.duplex(input, output);
}
export function rimraf(dir:string):(cb:any)=>void {
let retries = 0;
const retry = cb => {
_rimraf(dir, { maxBusyTries: 1 }, (err:any) => {
if (!err) return cb();
if (err.code === 'ENOTEMPTY' && ++retries < 5) return setTimeout(() => retry(cb), 10);
else return cb(err);
});
};
return cb => retry(cb);
}
export function getVersion(root:string): string {
let version = process.env['BUILD_SOURCEVERSION'];
if (!version || !/^[0-9a-f]{40}$/i.test(version)) {
version = git.getVersion(root);
}
return version;
}
export function rebase(count:number): NodeJS.ReadWriteStream {
return rename(f => {
const parts = f.dirname.split(/[\/\\]/);
f.dirname = parts.slice(count).join(path.sep);
});
}
export interface FilterStream extends NodeJS.ReadWriteStream {
restore: ThroughStream;
}
export function filter(fn:(data:any)=>boolean):FilterStream {
const result = <FilterStream><any>es.through(function (data) {
if (fn(data)) {
this.emit('data', data);
} else {
result.restore.push(data);
}
});
result.restore = es.through();
return result;
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册