Skip to content
This repository has been archived by the owner on Jun 11, 2020. It is now read-only.

Commit

Permalink
Allow using peer dependencies in a package json to indicate that a de…
Browse files Browse the repository at this point in the history
…pendency doesn't have to be included for the package to pass - this is because styled-components infers react-native, but it doesn't need it to pass
  • Loading branch information
orta committed Sep 14, 2019
1 parent ed18949 commit a5a84ec
Show file tree
Hide file tree
Showing 7 changed files with 47 additions and 20 deletions.
19 changes: 15 additions & 4 deletions src/generate-packages.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import { emptyDir } from "fs-extra";
import { emptyDir, mkdir, mkdirp, readFileSync } from "fs-extra";
import * as yargs from "yargs";

import { FS, getDefinitelyTyped } from "./get-definitely-typed";
import { Options } from "./lib/common";
import {
AllPackages, AnyPackage, DependencyVersion, getFullNpmName, License, NotNeededPackage, PackageJsonDependency, TypingsData,
} from "./lib/packages";
import { sourceBranch, outputDirPath } from "./lib/settings";
import { outputDirPath, sourceBranch } from "./lib/settings";
import { ChangedPackages, readChangedPackages, skipBadPublishes } from "./lib/versions";
import { writeFile } from "./util/io";
import { logger, loggerWithErrors, writeLog, Logger } from "./util/logging";
import { writeTgz } from "./util/tgz";
import { assertNever, joinPaths, logUncaughtErrors, sortObjectKeys } from "./util/util";
import { makeTypesVersionsForPackageJson } from "definitelytyped-header-parser";
import { mkdir, mkdirp, readFileSync } from "fs-extra";
import * as path from "path";
import { withNpmCache, CachedNpmInfoClient, UncachedNpmInfoClient } from "./lib/npm-client";

Expand Down Expand Up @@ -112,6 +111,7 @@ function createPackageJSON(typing: TypingsData, version: string, packages: AllPa
},
scripts: {},
dependencies: getDependencies(typing.packageJsonDependencies, typing, packages),
peerDependencies: getPeerDependencies(typing.peerDependencies),
typesPublisherContentHash: typing.contentHash,
typeScriptVersion: typing.minTypeScriptVersion,
};
Expand All @@ -121,7 +121,7 @@ function createPackageJSON(typing: TypingsData, version: string, packages: AllPa

const definitelyTypedURL = "https://github.com/DefinitelyTyped/DefinitelyTyped";

/** Adds inferred dependencies to `dependencies`, if they are not already specified in either `dependencies` or `peerDependencies`. */
/** Adds inferred dependencies to `dependencies`, if they are not already specified in either `dependencies`. */
function getDependencies(packageJsonDependencies: ReadonlyArray<PackageJsonDependency>, typing: TypingsData, allPackages: AllPackages): Dependencies {
const dependencies: Dependencies = {};
for (const { name, version } of packageJsonDependencies) {
Expand All @@ -138,6 +138,15 @@ function getDependencies(packageJsonDependencies: ReadonlyArray<PackageJsonDepen
return sortObjectKeys(dependencies);
}

function getPeerDependencies(packageJsonDependencies: ReadonlyArray<PackageJsonDependency>): Dependencies {
const dependencies: Dependencies = {};
for (const { name, version } of packageJsonDependencies) {
dependencies[name] = version;
}

return sortObjectKeys(dependencies);
}

function dependencySemver(dependency: DependencyVersion): string {
return dependency === "*" ? dependency : `^${dependency}`;
}
Expand Down Expand Up @@ -185,6 +194,8 @@ function createReadme(typing: TypingsData): string {
lines.push(` * Last updated: ${(new Date()).toUTCString()}`);
const dependencies = Array.from(typing.dependencies).map(d => getFullNpmName(d.name));
lines.push(` * Dependencies: ${dependencies.length ? dependencies.join(", ") : "none"}`);
const peerDependencies = Array.from(typing.peerDependencies).map(d => getFullNpmName(d.name));
lines.push(` * Peer Dependencies: ${peerDependencies.length ? peerDependencies.join(", ") : "none"}`);
lines.push(` * Global values: ${typing.globals.length ? typing.globals.join(", ") : "none"}`);
lines.push("");

Expand Down
12 changes: 6 additions & 6 deletions src/get-definitely-typed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { Options } from "./lib/common";
import { dataDirPath, definitelyTypedZipUrl } from "./lib/settings";
import { readFile, readJson, stringOfStream } from "./util/io";
import { LoggerWithErrors, loggerWithErrors } from "./util/logging";
import { assertDefined, assertSorted, Awaitable, exec, joinPaths, logUncaughtErrors, withoutStart } from "./util/util";
import { assertDefined, assertSorted, Awaitable, joinPaths, logUncaughtErrors, withoutStart } from "./util/util";

/**
* Readonly filesystem.
Expand Down Expand Up @@ -50,11 +50,11 @@ export async function getDefinitelyTyped(options: Options, log: LoggerWithErrors
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}.`);
// 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}/`);
}
}
Expand Down
1 change: 0 additions & 1 deletion src/lib/definition-parser-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,3 @@ if (!module.parent) {
});
}


17 changes: 12 additions & 5 deletions src/lib/definition-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,15 +93,21 @@ async function combineDataForAllTypesVersions(
});
const allTypesVersions = [dataForRoot, ...dataForOtherTypesVersions];

interface OptionalPackageJSON { readonly license?: unknown; readonly dependencies?: unknown; peerDependencies?: unknown; }

// tslint:disable-next-line await-promise (tslint bug)
const packageJson = hasPackageJson ? await fs.readJson(packageJsonName) as { readonly license?: unknown, readonly dependencies?: unknown } : {};
const packageJson = hasPackageJson ? await fs.readJson(packageJsonName) as OptionalPackageJSON : {};
const license = getLicenseFromPackageJson(packageJson.license);
const packageJsonDependencies = checkPackageJsonDependencies(packageJson.dependencies, packageJsonName);
const packageJsonDependencies = checkPackageJsonDependencies(packageJson.dependencies, packageJsonName, /* checkWhitelist */ true);
const packageJsonPeerDependencies = checkPackageJsonDependencies(packageJson.peerDependencies, packageJsonName, /* checkWhitelist */ false);

const files = Array.from(flatMap(allTypesVersions, ({ typescriptVersion, declFiles }) =>
declFiles.map(file =>
typescriptVersion === undefined ? file : `ts${typescriptVersion}/${file}`)));

// Get all package dependencies and remove any peer dependencies from them
const dependencies = getAllUniqueValues<"dependencies", PackageId>(allTypesVersions, "dependencies")
.filter(dep => !packageJsonPeerDependencies.find(peerDep => peerDep.name === dep.name));
return {
libraryName,
typingsPackageName,
Expand All @@ -113,11 +119,12 @@ async function combineDataForAllTypesVersions(
typesVersions,
files,
license,
dependencies,
// TODO: Explicit type arguments shouldn't be necessary. https://github.com/Microsoft/TypeScript/issues/27507
dependencies: getAllUniqueValues<"dependencies", PackageId>(allTypesVersions, "dependencies"),
testDependencies: getAllUniqueValues<"testDependencies", string>(allTypesVersions, "testDependencies"),
pathMappings: getAllUniqueValues<"pathMappings", PathMapping>(allTypesVersions, "pathMappings"),
packageJsonDependencies,
packageJsonPeerDependencies,
contentHash: await hash(hasPackageJson ? [...files, packageJsonName] : files, mapDefined(allTypesVersions, a => a.tsconfigPathsForHash), fs),
globals: getAllUniqueValues<"globals", string>(allTypesVersions, "globals"),
declaredModules: getAllUniqueValues<"declaredModules", string>(allTypesVersions, "declaredModules"),
Expand Down Expand Up @@ -179,7 +186,7 @@ async function getTypingDataForSingleTypesVersion(
return { typescriptVersion, dependencies, testDependencies, pathMappings, globals, declaredModules, declFiles, tsconfigPathsForHash };
}

function checkPackageJsonDependencies(dependencies: unknown, path: string): ReadonlyArray<PackageJsonDependency> {
function checkPackageJsonDependencies(dependencies: unknown, path: string, checkWhitelist: boolean): ReadonlyArray<PackageJsonDependency> {
if (dependencies === undefined) { // tslint:disable-line strict-type-predicates (false positive)
return [];
}
Expand All @@ -190,7 +197,7 @@ function checkPackageJsonDependencies(dependencies: unknown, path: string): Read
const deps: PackageJsonDependency[] = [];

for (const dependencyName in dependencies) {
if (!dependenciesWhitelist.has(dependencyName)) {
if (checkWhitelist && !dependenciesWhitelist.has(dependencyName)) {
const msg = dependencyName.startsWith("@types/")
? `Don't use a 'package.json' for @types dependencies unless this package relies on
an old version of types that have since been moved to the source repo.
Expand Down
11 changes: 10 additions & 1 deletion src/lib/packages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export class AllPackages {
return this.notNeeded;
}

/** Returns all of the dependences *that have typings*, ignoring others, and including test dependencies. */
/** Returns all of the dependencies *that have typings*, ignoring others, and including test dependencies. */
*allDependencyTypings(pkg: TypingsData): Iterable<TypingsData> {
for (const { name, majorVersion } of pkg.dependencies) {
const versions = this.data.get(getMangledNameForScopedPackage(name));
Expand Down Expand Up @@ -308,8 +308,13 @@ export interface TypingsDataRaw extends BaseRaw {

// Whether a "package.json" exists
readonly license: License;

// List of dependencies which indicate they should come from npm, not def typed
readonly packageJsonDependencies: ReadonlyArray<PackageJsonDependency>;

// These should be removed from the packageJsonDependencies above
readonly packageJsonPeerDependencies: ReadonlyArray<PackageJsonDependency>;

// A hash computed from all files from this definition
readonly contentHash: string;

Expand Down Expand Up @@ -419,6 +424,10 @@ export class TypingsData extends PackageBase {
return this.data.dependencies;
}

get peerDependencies(): ReadonlyArray<PackageJsonDependency> {
return this.data.packageJsonPeerDependencies;
}

/** Path to this package, *relative* to the DefinitelyTyped directory. */
get subDirectoryPath(): string {
return this.isLatest ? this.name : `${this.name}/v${this.data.libraryMajorVersion}`;
Expand Down
6 changes: 3 additions & 3 deletions src/tester/get-affected-packages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ function transitiveClosure<T>(initialItems: Iterable<T>, getRelatedItems: (item:

/** Generate a map from a package to packages that depend on it. */
function getReverseDependencies(allPackages: AllPackages, changedPackages: PackageId[]): Map<PackageId, Set<PackageId>> {
const map = new Map<string, [PackageId, Set<PackageId>]>();
for (const changed of changedPackages) {
const map = new Map<string, [PackageId, Set<PackageId>]>();
for (const changed of changedPackages) {
map.set(packageIdToKey(changed), [changed, new Set()]);
}
}
for (const typing of allPackages.allTypings()) {
if (!map.has(packageIdToKey(typing.id))) {
map.set(packageIdToKey(typing.id), [typing.id, new Set()]);
Expand Down
1 change: 1 addition & 0 deletions src/util/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export function createTypingsVersionRaw(
typesVersions: [],
license: License.MIT,
packageJsonDependencies: [],
packageJsonPeerDependencies: [],
contentHash: "11111111111111",
projectName: "zombo.com",
globals: [],
Expand Down

0 comments on commit a5a84ec

Please sign in to comment.