Fix lint errors (#750)

* Fix lint errors #1

* Fix lint errors #2

* Remove unnecessary disables

* Format comment
This commit is contained in:
Gabriela Araujo Britto
2020-03-02 12:28:50 -08:00
committed by Andrew Branch
parent a6ea7167bf
commit c8a7c5dace
19 changed files with 70 additions and 60 deletions

View File

@@ -45,7 +45,7 @@
"tslint": "^5.13.0"
},
"scripts": {
"test": "npm run lint && npm run build && jest",
"test": "npm run build && jest && npm run lint",
"build": "node node_modules/typescript/lib/tsc.js",
"watch": "node node_modules/typescript/lib/tsc.js --watch",
"clean": "node -r source-map-support/register bin/clean.js",

View File

@@ -146,6 +146,7 @@ function getDependencies(packageJsonDependencies: ReadonlyArray<PackageJsonDepen
}
function dependencySemver(dependency: DependencyVersion): string {
// tslint:disable-next-line strict-string-expressions
return dependency === "*" ? dependency : `^${dependency}`;
}

View File

@@ -51,14 +51,13 @@ export async function getDefinitelyTyped(options: Options, log: LoggerWithErrors
log.info("Downloading Definitely Typed ...");
await ensureDir(dataDirPath);
return downloadAndExtractFile(definitelyTypedZipUrl);
} else {
const { error, stderr, stdout } = await exec("git diff --name-only", options.definitelyTypedPath);
if (error) { throw error; }
if (stderr) { throw new Error(stderr); }
if (stdout) { throw new Error(`'git diff' should be empty. Following files changed:\n${stdout}`); }
log.info(`Using local Definitely Typed at ${options.definitelyTypedPath}.`);
return new DiskFS(`${options.definitelyTypedPath}/`);
}
const { error, stderr, stdout } = await exec("git diff --name-only", options.definitelyTypedPath);
if (error) { throw error; }
if (stderr) { throw new Error(stderr); }
if (stdout) { throw new Error(`'git diff' should be empty. Following files changed:\n${stdout}`); }
log.info(`Using local Definitely Typed at ${options.definitelyTypedPath}.`);
return new DiskFS(`${options.definitelyTypedPath}/`);
}
export function getLocallyInstalledDefinitelyTyped(path: string): FS {
@@ -156,7 +155,7 @@ export class InMemoryDT implements FS {
return undefined;
}
if (!(entry instanceof Dir)) {
throw new Error(`No file system entry at ${this.pathToRoot}/${path}. Siblings are: ${Array.from(dir.keys())}`);
throw new Error(`No file system entry at ${this.pathToRoot}/${path}. Siblings are: ${Array.from(dir.keys()).toString()}`);
}
dir = entry;
}
@@ -218,10 +217,9 @@ class DiskFS implements FS {
private getPath(path: string | undefined): string {
if (path === undefined) {
return this.rootPrefix;
} else {
validatePath(path);
return this.rootPrefix + path;
}
validatePath(path);
return this.rootPrefix + path;
}
readdir(dirPath?: string): ReadonlyArray<string> {
@@ -257,9 +255,11 @@ class DiskFS implements FS {
function validatePath(path: string): void {
if (path.startsWith(".") && path !== ".editorconfig" && !path.startsWith("../")) {
throw new Error(`${path}: filesystem doesn't support paths of the form './x'.`);
} else if (path.startsWith("/")) {
}
if (path.startsWith("/")) {
throw new Error(`${path}: filesystem doesn't support paths of the form '/xxx'.`);
} else if (path.endsWith("/")) {
}
if (path.endsWith("/")) {
throw new Error(`${path}: filesystem doesn't support paths of the form 'xxx/'.`);
}
}

View File

@@ -75,7 +75,7 @@ async function uploadFile(container: BlobWriter, blobName: string, filePath: str
async function deleteDirectory(container: BlobWriter, uploadedDirPath: string, log: Logger): Promise<void> {
const blobs = await container.listBlobs(uploadedDirPath);
const blobNames = blobs.map(b => b.name);
log(`Deleting directory ${uploadedDirPath}: delete files ${blobNames}`);
log(`Deleting directory ${uploadedDirPath}: delete files ${blobNames.toString()}`);
await Promise.all(blobNames.map(b => container.deleteBlob(b)));
}
@@ -96,7 +96,7 @@ async function removeOldDirectories(container: BlobWriter, prefix: string, maxDi
const sortedNames = dirNames.sort();
const toDelete = sortedNames.slice(0, sortedNames.length - maxDirectories);
log(`Too many old logs, so removing the following directories: [${toDelete}]`);
log(`Too many old logs, so removing the following directories: [${toDelete.toString()}]`);
await Promise.all(toDelete.map(d => deleteDirectory(container, prefix + d, log)));
}

View File

@@ -13,6 +13,7 @@ if (!module.parent) {
process.on("message", message => {
assert(process.argv.length === 3);
const typesPath = process.argv[2];
// tslint:disable-next-line no-async-without-await
logUncaughtErrors(async () => {
for (const packageName of message as ReadonlyArray<string>) {
const data = getTypingInfo(packageName, getLocallyInstalledDefinitelyTyped(typesPath).subDir(packageName));

View File

@@ -70,12 +70,11 @@ export function getTypingInfo(packageName: string, fs: FS): TypingsVersionsRaw {
`Directory ${directoryName} indicates major.minor version ${directoryVersion.major}.${directoryVersion.minor}, ` +
`but header indicates major.minor version ${data.libraryMajorVersion}.${data.libraryMinorVersion}`,
);
} else {
throw new Error(
`Directory ${directoryName} indicates major version ${directoryVersion.major}, but header indicates major version ` +
data.libraryMajorVersion.toString(),
);
}
throw new Error(
`Directory ${directoryName} indicates major version ${directoryVersion.major}, but header indicates major version ` +
data.libraryMajorVersion.toString(),
);
}
return data;
});
@@ -124,12 +123,11 @@ export function parseVersionFromDirectoryName(directoryName: string): TypingVers
const match = /^v(\d+)(\.(\d+))?$/.exec(directoryName);
if (match === null) {
return undefined;
} else {
return {
major: Number(match[1]),
minor: match[3] !== undefined ? Number(match[3]) : undefined, // tslint:disable-line strict-type-predicates (false positive)
};
}
return {
major: Number(match[1]),
minor: match[3] !== undefined ? Number(match[3]) : undefined, // tslint:disable-line strict-type-predicates (false positive)
};
}
function combineDataForAllTypesVersions(
@@ -257,7 +255,7 @@ function checkPackageJsonDependencies(dependencies: unknown, path: string): Read
const deps: PackageJsonDependency[] = [];
for (const dependencyName in dependencies) {
for (const dependencyName of Object.keys(dependencies!)) { // `dependencies` cannot be null because of check above.
if (!dependenciesWhitelist.has(dependencyName)) {
const msg = dependencyName.startsWith("@types/")
? `Dependency ${dependencyName} not in whitelist.
@@ -335,7 +333,7 @@ function calculateDependencies(
const dependencies: PackageId[] = [];
const pathMappings: PathMapping[] = [];
for (const dependencyName in paths) {
for (const dependencyName of Object.keys(paths)) {
// Might have a path mapping for "foo/*" to support subdirectories
const rootDirectory = withoutEnd(dependencyName, "/*");
if (rootDirectory !== undefined) {
@@ -364,7 +362,8 @@ function calculateDependencies(
if (dependencyName === packageName) {
if (directoryVersion === undefined) {
throw new Error(`In ${packageName}: Latest version of a package should not have a path mapping for itself.`);
} else if (
}
if (
directoryVersion.major !== pathMappingVersion.major
|| directoryVersion.minor !== pathMappingVersion.minor
) {
@@ -472,6 +471,7 @@ function checkAllUsedRecur(ls: Iterable<string>, usedFiles: Set<string>, unusedF
const lssubdir = subdir.readdir();
if (lssubdir.length === 0) {
// tslint:disable-next-line strict-string-expressions
throw new Error(`Empty directory ${subdir} (${join(usedFiles)})`);
}
@@ -497,8 +497,7 @@ function checkAllUsedRecur(ls: Iterable<string>, usedFiles: Set<string>, unusedF
for (const unusedFile of unusedFiles) {
if (usedFiles.has(unusedFile)) {
throw new Error(`File ${fs.debugPath()}/${unusedFile} listed in ${unusedFilesName} is already reachable from tsconfig.json.`);
} else {
throw new Error(`File ${fs.debugPath()}/${unusedFile} listed in ${unusedFilesName} does not exist.`);
}
throw new Error(`File ${fs.debugPath()}/${unusedFile} listed in ${unusedFilesName} does not exist.`);
}
}

View File

@@ -183,9 +183,11 @@ function resolveModule(importSpecifier: string, fs: FS): string {
if (importSpecifier !== "." && importSpecifier !== "..") {
if (fs.exists(importSpecifier + ".d.ts")) {
return importSpecifier + ".d.ts";
} else if (fs.exists(importSpecifier + ".ts")) {
}
if (fs.exists(importSpecifier + ".ts")) {
return importSpecifier + ".ts";
} else if (fs.exists(importSpecifier + ".tsx")) {
}
if (fs.exists(importSpecifier + ".tsx")) {
return importSpecifier + ".tsx";
}
}
@@ -238,7 +240,8 @@ function findReferencedFiles(src: ts.SourceFile, packageName: string, subDirecto
ref.text = full.slice(packageName.length + 4);
refs.push(ref);
return;
} else if (full.startsWith("..")
}
if (full.startsWith("..")
&& (baseDirectory === "" || path.normalize(joinPaths(baseDirectory, full)).startsWith(".."))) {
throw new Error(
`${src.fileName}: ` +

View File

@@ -120,8 +120,8 @@ export class UncachedNpmInfoClient {
retries: true,
}) as { readonly error: string } | { readonly [key: string]: { readonly downloads: number } };
if ("error" in data) { throw new Error(data.error as string); }
for (const key in data) {
assert(key === names[out.length], `at index ${out.length} of ${Object.keys(data)} : ${key} !== ${names[out.length]}`);
for (const key of Object.keys(data)) {
assert(key === names[out.length], `at index ${out.length} of ${Object.keys(data).toString()} : ${key} !== ${names[out.length]}`);
out.push(data[key] ? data[key].downloads : 0);
}
}
@@ -141,9 +141,9 @@ export class NpmPublishClient {
static async create(config?: RegClient.Config, registry: Registry = Registry.NPM): Promise<NpmPublishClient> {
switch (registry) {
case Registry.NPM:
return new this(new RegClient(config), { token: await getSecret(Secret.NPM_TOKEN) }, npmRegistry);
return new NpmPublishClient(new RegClient(config), { token: await getSecret(Secret.NPM_TOKEN) }, npmRegistry);
case Registry.Github:
return new this(new RegClient(config), { token: await getSecret(Secret.GITHUB_PUBLISH_ACCESS_TOKEN) }, githubRegistry);
return new NpmPublishClient(new RegClient(config), { token: await getSecret(Secret.GITHUB_PUBLISH_ACCESS_TOKEN) }, githubRegistry);
default:
assertNever(registry);
}

View File

@@ -247,7 +247,7 @@ export class NotNeededPackage extends PackageBase {
super(raw);
this.sourceRepoURL = raw.sourceRepoURL;
for (const key in raw) {
for (const key of Object.keys(raw)) {
if (!["libraryName", "typingsPackageName", "sourceRepoURL", "asOfVersion"].includes(key)) {
throw new Error(`Unexpected key in not-needed package: ${key}`);
}
@@ -421,7 +421,7 @@ export function getLicenseFromPackageJson(packageJsonLicense: unknown): License
if (packageJsonLicense === undefined) { // tslint:disable-line strict-type-predicates (false positive)
return License.MIT;
}
if (packageJsonLicense === "MIT") {
if (typeof packageJsonLicense === "string" && packageJsonLicense === "MIT") {
throw new Error(`Specifying '"license": "MIT"' is redundant, this is the default.`);
}
if (allLicenses.includes(packageJsonLicense as License)) {
@@ -443,9 +443,8 @@ export class TypingsVersions {
const version = Semver.parse(key, true);
if (version) {
return [version, key];
} else {
throw new Error(`Unable to parse version ${key}`);
}
throw new Error(`Unable to parse version ${key}`);
}));
/**
@@ -456,7 +455,7 @@ export class TypingsVersions {
this.map = new Map(this.versions.map(version => {
const dataKey = versionMappings.get(version)!;
return [version, new TypingsData(data[dataKey], version === this.versions[0])];
return [version, new TypingsData(data[dataKey], version.equals(this.versions[0]))];
}));
}

View File

@@ -70,7 +70,7 @@ export async function getSecret(secret: Secret): Promise<string> {
const azureSecretName = Secret[secret].toLowerCase().replace(/_/g, "-");
// console.log("Getting secret versions for: " + azureSecretName);
const versions = await client.getSecretVersions(azureKeyvault, azureSecretName);
versions.sort((a, b) => a.attributes.created < b.attributes.created ? 1 : -1);
versions.sort((a, b) => a.attributes.created.getTime() < b.attributes.created.getTime() ? 1 : -1);
// console.log(versions);
const urlParts = versions[0].id.split("/");
const latest = urlParts[urlParts.length - 1];

View File

@@ -69,7 +69,7 @@ function findActualLatest(times: Map<string, string>) {
times, ([k, v], [bestK, bestV]) =>
(bestK === "modified" || bestK === "created") ? true :
(k === "modified" || k === "created") ? false :
new Date(v) > new Date(bestV));
new Date(v).getTime() > new Date(bestV).getTime());
if (!actual) {
throw new Error("failed to find actual latest");
}

View File

@@ -111,9 +111,8 @@ function updateOneAtATime(
if (working) {
log.info("Not starting update, because already performing one.");
return undefined;
} else {
return work();
}
return work();
async function work(): Promise<void> {
log.info("Starting update");
@@ -136,7 +135,7 @@ function checkSignature(key: string, data: string, headers: { readonly [key: str
if (typeof signature === "string" && stringEqualsConstantTime(signature, expected)) {
return true;
}
// tslint:disable-next-line strict-string-expressions
log.error(`Invalid request: expected ${expected}, got ${signature}`);
log.error(`Headers are: ${JSON.stringify(headers, undefined, 4)}`);
log.error(`Data is: ${data}`);

View File

@@ -100,8 +100,8 @@ export default async function publishPackages(
await queryGithub(`repos/DefinitelyTyped/DefinitelyTyped/pulls/${latestPr}`, githubAccessToken, fetcher) as { merged_at: string };
const latency = Date.now() - new Date(latest.merged_at).valueOf();
const commitlatency = Date.now() - new Date(commits[0].commit.author.date).valueOf();
log("Current date is " + new Date(Date.now()));
log(" Merge date is " + new Date(latest.merged_at));
log("Current date is " + new Date(Date.now()).toString());
log(" Merge date is " + new Date(latest.merged_at).toString());
const published = cp.pkg.fullNpmName + "@" + cp.version;
const publishNotification =

View File

@@ -152,7 +152,7 @@ async function validateIsSubset(notNeeded: ReadonlyArray<NotNeededPackage>, log:
const indexJson = "index.json";
const actual = await readJson(joinPaths(validateTypesRegistryPath, indexJson)) as Registry;
const expected = await readJson(joinPaths(registryOutputPath, indexJson)) as Registry;
for (const key in actual.entries) {
for (const key of Object.keys(actual.entries)) {
if (!(key in expected.entries) && !notNeeded.some(p => p.name === key)) {
throw new Error(`Actual types-registry has unexpected key ${key}`);
}
@@ -228,7 +228,7 @@ async function generateRegistry(typings: ReadonlyArray<TypingsData>, client: Cac
const info = client.getNpmInfoFromCache(typing.fullEscapedNpmName);
if (!info) {
const missings = typings.filter(t => !client.getNpmInfoFromCache(t.fullEscapedNpmName)).map(t => t.fullEscapedNpmName);
throw new Error(`${missings} not found in cached npm info.`);
throw new Error(`${missings.toString()} not found in cached npm info.`);
}
entries[typing.name] = filterTags(info.distTags);
}

View File

@@ -105,8 +105,8 @@ export async function getAffectedPackagesFromDiff(dt: FS, definitelyTypedPath: s
: selection === "affected" ? getAffectedPackages(allPackages, gitChanges(diffs))
: { changedPackages: allPackages.allTypings().filter(t => selection.test(t.name)), dependentPackages: [], allPackages };
console.log(`Testing ${affected.changedPackages.length} changed packages: ${affected.changedPackages.map(t => t.desc)}`);
console.log(`Testing ${affected.dependentPackages.length} dependent packages: ${affected.dependentPackages.map(t => t.desc)}`);
console.log(`Testing ${affected.changedPackages.length} changed packages: ${affected.changedPackages.map(t => t.desc).toString()}`);
console.log(`Testing ${affected.dependentPackages.length} dependent packages: ${affected.dependentPackages.map(t => t.desc).toString()}`);
return affected;
}

View File

@@ -1,7 +1,7 @@
import { License, PackageId, TypingsVersionsRaw } from "../lib/packages";
export function testo(o: { [s: string]: () => void }) {
for (const k in o) {
for (const k of Object.keys(o)) {
test(k, o[k], 100_000);
}
}

View File

@@ -242,6 +242,7 @@ export function sort<T>(values: Iterable<T>, comparer?: (a: T, b: T) => number):
export function join<T>(values: Iterable<T>, joiner = ", "): string {
let s = "";
for (const v of values) {
// tslint:disable-next-line strict-string-expressions
s += `${v}${joiner}`;
}
return s.slice(0, s.length - joiner.length);
@@ -593,7 +594,7 @@ export function recordToMap<T>(record: Record<string, T>): Map<string, T>;
export function recordToMap<T, U>(record: Record<string, T>, cb: (t: T) => U): Map<string, U>;
export function recordToMap<T, U>(record: Record<string, T>, cb?: (t: T) => U): Map<string, T | U> {
const m = new Map<string, T | U>();
for (const key in record) {
for (const key of Object.keys(record)) {
m.set(key, cb ? cb(record[key]) : record[key]);
}
return m;

View File

@@ -82,7 +82,7 @@ async function validatePackages(packageNames: ReadonlyArray<string>, outPath: st
log.info("");
if (failed.length) {
log.info(`These packages failed: ${failed}`);
log.info(`These packages failed: ${failed.toString()}`);
}
}
@@ -152,8 +152,7 @@ async function runCommand(commandDescription: string, log: LoggerWithErrors, dir
log.error(`${commandDescription} failed: ${JSON.stringify(error)}`);
log.info(`${commandDescription} failed, refer to error log`);
return false;
} else {
log.info(stdout);
return true;
}
log.info(stdout);
return true;
}

View File

@@ -8,6 +8,14 @@
"max-line-length": [true, 150],
"object-literal-key-quotes": [true, "as-needed"],
"only-arrow-functions": [true, "allow-declarations"],
"variable-name": [true, "check-format", "allow-leading-underscore"],
"strict-comparisons": [
true,
{
"allow-object-equal-comparison": true,
"allow-string-order-comparison": true
}
],
// TODO
"strict-boolean-expressions": false,