Skip to content

Commit

Permalink
Some require -> import conversions
Browse files Browse the repository at this point in the history
  • Loading branch information
elibarzilay committed Nov 23, 2021
1 parent 9a78868 commit b9a4a3a
Show file tree
Hide file tree
Showing 9 changed files with 31 additions and 46 deletions.
2 changes: 1 addition & 1 deletion src/cancellationToken/cancellationToken.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/// <reference types="node"/>

import fs = require("fs");
import * as fs from "fs";

interface ServerCancellationToken {
isCancellationRequested(): boolean;
Expand Down
4 changes: 2 additions & 2 deletions src/harness/findUpDir.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { join, resolve, dirname } = require("path") as typeof import("path");
const { existsSync } = require("fs") as typeof import("fs");
import { join, resolve, dirname } from "path";
import { existsSync } from "fs";

// search directories upward to avoid hard-wired paths based on the
// build tree (same as scripts/build/findUpDir.js)
Expand Down
17 changes: 7 additions & 10 deletions src/harness/harnessGlobals.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { isArray } from "./ts";
import * as chai from "chai";

declare global {
// Block scoped definitions work poorly for global variables, temporarily enable var
/* eslint-disable no-var */

// this will work in the browser via browserify
var assert: typeof _chai.assert;
}
declare global {
var expect: typeof _chai.expect;
var assert: typeof chai.assert;
var expect: typeof chai.expect;
}
var _chai: typeof import("chai") = require("chai");
globalThis.assert = _chai.assert;

globalThis.assert = chai.assert;
{
// chai's builtin `assert.isFalse` is featureful but slow - we don't use those features,
// so we'll just overwrite it as an alterative to migrating a bunch of code off of chai
Expand Down Expand Up @@ -39,7 +39,4 @@ globalThis.assert = _chai.assert;
}
};
}
globalThis.expect = _chai.expect;
/* eslint-enable no-var */
// empty ts namespace so this file is included in the `ts.ts` namespace file generated by the module swapover
// This way, everything that ends up importing `ts` downstream also imports this file and picks up its augmentation
globalThis.expect = chai.expect;
4 changes: 2 additions & 2 deletions src/instrumenter/instrumenter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs = require("fs");
import path = require("path");
import * as fs from "fs";
import * as path from "path";

function instrumentForRecording(fn: string, tscPath: string) {
instrument(tscPath, `
Expand Down
6 changes: 3 additions & 3 deletions src/testRunner/externalCompileRunner.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { RunnerBase, IO, isWorker, Baseline, TestRunnerKind } from "./Harness";
import { Debug, Version, flatten, comparePathsCaseSensitive, compareValues, compareStringsCaseSensitive, stringContains } from "./ts";
const fs: typeof import("fs") = require("fs");
const path: typeof import("path") = require("path");
const del: typeof import("del") = require("del");
import * as fs from "fs";
import * as path from "path";
import * as del from "del";

interface ExecResult {
stdout: Buffer;
Expand Down
4 changes: 2 additions & 2 deletions src/testRunner/unittests/services/languageService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { ScriptSnapshot, getDefaultLibFilePath, emptyArray, LanguageServiceHost,
import { libFile, createServerHost } from "../../ts.projectSystem";
import { projectRoot } from "../../ts.tscWatch";
import * as ts from "../../ts";
const _chai: typeof import("chai") = require("chai");
const expect: typeof _chai.expect = _chai.expect;
import { expect } from "chai";

describe("unittests:: services:: languageService", () => {
const files: {
[index: string]: string;
Expand Down
10 changes: 3 additions & 7 deletions src/tsserver/nodeServer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { LogLevel, getLogLevel, findArgument, StartInput, ServerHost, BaseLogger, Msg, stringifyIndented, RequireResult, ServerCancellationToken, nullCancellationToken, StartSessionOptions, Logger, ITypingsInstaller, ProjectService, Event, InstallPackageOptionsWithProject, InstallPackageRequest, Arguments, Project, TypingInstallerRequestUnion, createInstallTypingsRequest, TypesRegistryResponse, PackageInstalledResponse, SetTypings, InvalidateCachedTypings, BeginInstallTypes, EndInstallTypes, InitializationFailedResponse, EventTypesRegistry, ActionPackageInstalled, EventInitializationFailed, protocol, EventBeginInstallTypes, EventEndInstallTypes, ActionInvalidate, ActionSet, Session, nullTypingsInstaller, formatMessage, toEvent, hasArgument } from "./ts.server";
import { CharacterCodes, stripQuotes, LanguageServiceMode, Debug, MapLike, noop, getNodeMajorVersion, combinePaths, noopFileWatcher, WatchFileKind, resolveJSModule, validateLocaleAndSetLanguage, normalizeSlashes, directorySeparator, toFileNameLowerCase, getRootLength, DirectoryWatcherCallback, WatchOptions, FileWatcher, ESMap, ApplyCodeActionCommandResult, JsTyping, getDirectoryPath, TypeAcquisition, SortedReadonlyArray, getEntries, assertType, sys, tracing, startTracing, versionMajorMinor } from "./ts";
import * as ts from "./ts";
import { execFileSync } from "child_process";

/*@internal*/
interface LogOptions {
file?: string;
Expand Down Expand Up @@ -100,12 +102,6 @@ function parseServerMode(): LanguageServiceMode | string | undefined {
/* @internal */
export function initializeNodeSystem(): StartInput {
const sys = Debug.checkDefined(ts.sys) as ServerHost;
const childProcess: {
execFileSync(file: string, args: string[], options: {
stdio: "ignore";
env: MapLike<string>;
}): string | Buffer;
} = require("child_process");

interface Stats {
isFile(): boolean;
Expand Down Expand Up @@ -207,7 +203,7 @@ export function initializeNodeSystem(): StartInput {
if (logger.hasLevel(LogLevel.verbose)) {
logger.info(`Starting ${process.execPath} with args:${stringifyIndented(args)}`);
}
childProcess.execFileSync(process.execPath, args, { stdio: "ignore", env: { ELECTRON_RUN_AS_NODE: "1" } });
execFileSync(process.execPath, args, { stdio: "ignore", env: { ELECTRON_RUN_AS_NODE: "1" } });
status = true;
if (logger.hasLevel(LogLevel.verbose)) {
logger.info(`WatchGuard for path ${path} returned: OK`);
Expand Down
22 changes: 7 additions & 15 deletions src/typingsInstaller/nodeTypingsInstaller.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
import { Log, TypingsInstaller, RequestCompletedAction, installNpmPackages } from "./ts.server.typingsInstaller";
import { nowString, InstallTypingHost, InitializationFailedResponse, Arguments, TypingInstallerRequestUnion, TypesRegistryResponse, EventTypesRegistry, PackageInstalledResponse, ActionPackageInstalled, TypingInstallerResponseUnion, findArgument, hasArgument } from "./ts.server";
import { sys, MapLike, ESMap, getEntries, combinePaths, normalizeSlashes, toPath, createGetCanonicalFileName, stringContains, Debug, version, forEachAncestorDirectory, getDirectoryPath } from "./ts";
import * as ts from "./ts";
const fs: {
appendFileSync(file: string, content: string): void;
} = require("fs");

const path: {
join(...parts: string[]): string;
dirname(path: string): string;
basename(path: string, extension?: string): string;
} = require("path");
import { sys, MapLike, Map, ESMap, getEntries, combinePaths, normalizeSlashes, toPath, createGetCanonicalFileName, stringContains, Debug, version, forEachAncestorDirectory, getDirectoryPath } from "./ts";
import { appendFileSync } from "fs";
import * as path from "path";

class FileLog implements Log {
constructor(private logFile: string | undefined) {
Expand All @@ -24,7 +16,7 @@ class FileLog implements Log {
return;

try {
fs.appendFileSync(this.logFile, `[${nowString()}] ${text}${sys.newLine}`);
appendFileSync(this.logFile, `[${nowString()}] ${text}${sys.newLine}`);
}
catch (e) {
this.logFile = undefined;
Expand Down Expand Up @@ -55,17 +47,17 @@ function loadTypesRegistryFile(typesRegistryFilePath: string, host: InstallTypin
if (log.isEnabled()) {
log.writeLine(`Types registry file '${typesRegistryFilePath}' does not exist`);
}
return new ts.Map<string, MapLike<string>>();
return new Map<string, MapLike<string>>();
}
try {
const content = JSON.parse(host.readFile(typesRegistryFilePath)!) as TypesRegistryFile;
return new ts.Map(getEntries(content.entries));
return new Map(getEntries(content.entries));
}
catch (e) {
if (log.isEnabled()) {
log.writeLine(`Error when loading types registry file '${typesRegistryFilePath}': ${(e as Error).message}, ${(e as Error).stack}`);
}
return new ts.Map<string, MapLike<string>>();
return new Map<string, MapLike<string>>();
}
}

Expand Down
8 changes: 4 additions & 4 deletions src/watchGuard/watchGuard.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
/// <reference types="node" />

import { watch } from "fs";

if (process.argv.length < 3) {
process.exit(1);
}
const directoryName = process.argv[2];
const fs: {
watch(directoryName: string, options: any, callback: () => {}): any;
} = require("fs");

// main reason why we need separate process to check if it is safe to watch some path
// is to guard against crashes that cannot be intercepted with protected blocks and
// code in tsserver already can handle normal cases, like non-existing folders.
// This means that here we treat any result (success or exception) from fs.watch as success since it does not tear down the process.
// The only case that should be considered as failure - when watchGuard process crashes.
try {
const watcher = fs.watch(directoryName, { recursive: true }, () => ({}));
const watcher = watch(directoryName, { recursive: true }, () => ({}));
watcher.close();
}
catch { /*ignore*/ }
Expand Down

0 comments on commit b9a4a3a

Please sign in to comment.