Skip to content

Commit

Permalink
chore: format the code with prettier
Browse files Browse the repository at this point in the history
using 1.x and not 2.x as 2.x doesn't support Node 8
  • Loading branch information
michael-go committed Mar 29, 2020
1 parent 5162b82 commit cd86302
Show file tree
Hide file tree
Showing 20 changed files with 541 additions and 360 deletions.
5 changes: 5 additions & 0 deletions .prettierrc.json
@@ -0,0 +1,5 @@
{
"arrowParens": "always",
"trailingComma": "all",
"singleQuote": true
}
6 changes: 5 additions & 1 deletion package.json
Expand Up @@ -11,7 +11,10 @@
],
"scripts": {
"build": "tsc",
"lint": "tslint -p tsconfig.json",
"format": "prettier --write '{src,test,scripts}/**/*.ts'",
"lint:tslint": "tslint -p tsconfig.json",
"lint:prettier": "prettier --check '{src,test,scripts}/**/*.ts'",
"lint": "npm run lint:tslint && npm run lint:prettier",
"test": "jest --verbose --runInBand",
"test:coverage": "npm run test -- --coverage",
"prepare": "npm run build"
Expand Down Expand Up @@ -43,6 +46,7 @@
"graphlib": "^2.1.5",
"lodash": "^4.17.15",
"object-hash": "^1.3.1",
"prettier": "^1.19.1",
"semver": "^6.0.0",
"source-map-support": "^0.5.11",
"tslib": "^1.10.0"
Expand Down
6 changes: 4 additions & 2 deletions scripts/to-graph.ts
Expand Up @@ -2,14 +2,16 @@
// tslint:disable:no-console

import * as fs from 'fs';
import {legacy} from '../src';
import { legacy } from '../src';

const [STDIN, STDOUT] = [0, 1];

const pkgManager = process.argv[2];
if (!pkgManager) {
console.error('requires package manager argument. e.g. npm');
console.log('usage: cat tree.json | npx ts-node to-graph.ts npm > graph.json');
console.log(
'usage: cat tree.json | npx ts-node to-graph.ts npm > graph.json',
);
process.exit(1);
}

Expand Down
2 changes: 1 addition & 1 deletion scripts/to-tree.ts
Expand Up @@ -2,7 +2,7 @@
// tslint:disable:no-console

import * as fs from 'fs';
import {legacy, createFromJSON} from '../src';
import { legacy, createFromJSON } from '../src';

const [STDIN, STDOUT] = [0, 1];

Expand Down
11 changes: 6 additions & 5 deletions src/core/builder.ts
Expand Up @@ -2,12 +2,9 @@ import * as graphlib from 'graphlib';
import * as types from './types';
import { DepGraphImpl } from './dep-graph';

export {
DepGraphBuilder,
};
export { DepGraphBuilder };

class DepGraphBuilder {

get rootNodeId(): string {
return this._rootNodeId;
}
Expand Down Expand Up @@ -50,7 +47,11 @@ class DepGraphBuilder {
}

// TODO: this can create disconnected nodes
public addPkgNode(pkgInfo: types.PkgInfo, nodeId: string, nodeInfo?: types.NodeInfo) {
public addPkgNode(
pkgInfo: types.PkgInfo,
nodeId: string,
nodeInfo?: types.NodeInfo,
) {
if (nodeId === this._rootNodeId) {
throw new Error('DepGraphBuilder.addPkgNode() cant override root node');
}
Expand Down
50 changes: 27 additions & 23 deletions src/core/create-from-json.ts
Expand Up @@ -18,13 +18,11 @@ export function createFromJSON(depGraphData: DepGraphData): DepGraph {
multigraph: false,
compound: false,
});
const pkgs: {[pkgId: string]: types.PkgInfo} = {};
const pkgNodes: {[pkgId: string]: Set<string>} = {};
const pkgs: { [pkgId: string]: types.PkgInfo } = {};
const pkgNodes: { [pkgId: string]: Set<string> } = {};

for (const { id, info } of depGraphData.pkgs) {
pkgs[id] = info.version
? info
: { ...info, version: undefined };
pkgs[id] = info.version ? info : { ...info, version: undefined };
}

for (const node of depGraphData.graph.nodes) {
Expand Down Expand Up @@ -62,18 +60,22 @@ function assert(condition: boolean, msg: string) {

function validateDepGraphData(depGraphData: DepGraphData) {
assert(
!!semver.valid(depGraphData.schemaVersion)
&& semver.satisfies(depGraphData.schemaVersion, SUPPORTED_SCHEMA_RANGE),
`dep-graph schemaVersion not in "${SUPPORTED_SCHEMA_RANGE}"`);
assert(depGraphData.pkgManager && !!depGraphData.pkgManager.name, '.pkgManager.name is missing');
!!semver.valid(depGraphData.schemaVersion) &&
semver.satisfies(depGraphData.schemaVersion, SUPPORTED_SCHEMA_RANGE),
`dep-graph schemaVersion not in "${SUPPORTED_SCHEMA_RANGE}"`,
);
assert(
depGraphData.pkgManager && !!depGraphData.pkgManager.name,
'.pkgManager.name is missing',
);

const pkgsMap = depGraphData.pkgs.reduce((acc, cur) => {
assert(!(cur.id in acc), 'more than one pkg with same id');
assert(!!cur.info, '.pkgs item missing .info');

acc[cur.id] = cur.info;
return acc;
}, {} as {[pkdId: string]: types.PkgInfo});
}, {} as { [pkdId: string]: types.PkgInfo });

const nodesMap = depGraphData.graph.nodes.reduce((acc, cur) => {
assert(!(cur.nodeId in acc), 'more than on node with same id');
Expand All @@ -87,22 +89,24 @@ function validateDepGraphData(depGraphData: DepGraphData) {
assert(rootNodeId in nodesMap, `.${rootNodeId} root graph node is missing`);
const rootPkgId = rootNode.pkgId;
assert(rootPkgId in pkgsMap, `.${rootPkgId} root pkg missing`);
assert(nodesMap[rootNodeId].pkgId === rootPkgId,
`the root node .pkgId should be "${rootPkgId}"`);
assert(
nodesMap[rootNodeId].pkgId === rootPkgId,
`the root node .pkgId should be "${rootPkgId}"`,
);
const pkgIds = _.keys(pkgsMap);
// NOTE: this name@version check is very strict,
// we can relax it later, it just makes things easier now
assert(
pkgIds
.filter((pkgId) => (pkgId !== DepGraphImpl.getPkgId(pkgsMap[pkgId])))
.length === 0,
'pkgs ids should be name@version');
assert(_.values(nodesMap)
.filter((node) => !(node.pkgId in pkgsMap))
pkgIds.filter((pkgId) => pkgId !== DepGraphImpl.getPkgId(pkgsMap[pkgId]))
.length === 0,
'some instance nodes belong to non-existing pkgIds');
assert(_.values(pkgsMap)
.filter((pkg: { name: string }) => !pkg.name)
.length === 0,
'some .pkgs elements have no .name field');
'pkgs ids should be name@version',
);
assert(
_.values(nodesMap).filter((node) => !(node.pkgId in pkgsMap)).length === 0,
'some instance nodes belong to non-existing pkgIds',
);
assert(
_.values(pkgsMap).filter((pkg: { name: string }) => !pkg.name).length === 0,
'some .pkgs elements have no .name field',
);
}
63 changes: 44 additions & 19 deletions src/core/dep-graph.ts
@@ -1,11 +1,9 @@
import * as _ from 'lodash';
import * as graphlib from 'graphlib';
import * as types from './types';
import {createFromJSON} from './create-from-json';
import { createFromJSON } from './create-from-json';

export {
DepGraphImpl,
};
export { DepGraphImpl };

interface GraphNode {
pkgId: string;
Expand Down Expand Up @@ -51,8 +49,7 @@ class DepGraphImpl implements types.DepGraphInternal {
this._rootPkgId = (graph.node(rootNodeId) as GraphNode).pkgId;

this._pkgList = _.values(pkgs);
this._depPkgsList = this._pkgList
.filter((pkg) => pkg !== this.rootPkg);
this._depPkgsList = this._pkgList.filter((pkg) => pkg !== this.rootPkg);
}

get pkgManager() {
Expand Down Expand Up @@ -164,7 +161,10 @@ class DepGraphImpl implements types.DepGraphInternal {
return count;
}

public equals(other: types.DepGraph, { compareRoot = true }: { compareRoot?: boolean } = {}): boolean {
public equals(
other: types.DepGraph,
{ compareRoot = true }: { compareRoot?: boolean } = {},
): boolean {
let otherDepGraph;

if (other instanceof DepGraphImpl) {
Expand All @@ -180,7 +180,13 @@ class DepGraphImpl implements types.DepGraphInternal {
// should suffice, since node IDs will be generated in a predictable way.
// However, there might be different versions of graph and inconsistencies
// in the ordering of the arrays, so we perform a deep comparison.
return this.nodeEquals(this, this.rootNodeId, otherDepGraph, otherDepGraph.rootNodeId, compareRoot);
return this.nodeEquals(
this,
this.rootNodeId,
otherDepGraph,
otherDepGraph.rootNodeId,
compareRoot,
);
}

public directDepsLeadingTo(pkg: types.Pkg): types.PkgInfo[] {
Expand All @@ -197,8 +203,9 @@ class DepGraphImpl implements types.DepGraphInternal {
const nodeIds = this._graph.nodes();

const nodes = nodeIds.reduce((acc: types.GraphNode[], nodeId: string) => {
const deps = (this._graph.successors(nodeId) || [])
.map((depNodeId) => ({ nodeId: depNodeId }));
const deps = (this._graph.successors(nodeId) || []).map((depNodeId) => ({
nodeId: depNodeId,
}));

const node = this._graph.node(nodeId) as GraphNode;
const elem: types.GraphNode = {
Expand All @@ -213,11 +220,12 @@ class DepGraphImpl implements types.DepGraphInternal {
return acc;
}, []);

const pkgs: Array<{ id: string; info: types.PkgInfo; }> = _.keys(this._pkgs)
.map((pkgId: string) => ({
id: pkgId,
info: this._pkgs[pkgId],
}));
const pkgs: Array<{ id: string; info: types.PkgInfo }> = _.keys(
this._pkgs,
).map((pkgId: string) => ({
id: pkgId,
info: this._pkgs[pkgId],
}));

return {
schemaVersion: DepGraphImpl.SCHEMA_VERSION,
Expand All @@ -239,7 +247,10 @@ class DepGraphImpl implements types.DepGraphInternal {
traversedPairs = new Set<string>(),
): boolean {
// Skip root nodes comparision if needed.
if (compareRoot || (nodeIdA !== graphA.rootNodeId && nodeIdB !== graphB.rootNodeId)) {
if (
compareRoot ||
(nodeIdA !== graphA.rootNodeId && nodeIdB !== graphB.rootNodeId)
) {
const pkgA = graphA.getNodePkg(nodeIdA);
const pkgB = graphB.getNodePkg(nodeIdB);

Expand All @@ -266,10 +277,15 @@ class DepGraphImpl implements types.DepGraphInternal {
}

// Sort dependencies by name@version string.
const sortFn = (graph: types.DepGraphInternal) => (idA: string, idB: string) => {
const sortFn = (graph: types.DepGraphInternal) => (
idA: string,
idB: string,
) => {
const pkgA = graph.getNodePkg(idA);
const pkgB = graph.getNodePkg(idB);
return DepGraphImpl.getPkgId(pkgA).localeCompare(DepGraphImpl.getPkgId(pkgB));
return DepGraphImpl.getPkgId(pkgA).localeCompare(
DepGraphImpl.getPkgId(pkgB),
);
};

depsA = depsA.sort(sortFn(graphA));
Expand All @@ -286,7 +302,16 @@ class DepGraphImpl implements types.DepGraphInternal {

traversedPairs.add(pairKey);

if (!this.nodeEquals(graphA, depsA[i], graphB, depsB[i], compareRoot, traversedPairs)) {
if (
!this.nodeEquals(
graphA,
depsA[i],
graphB,
depsB[i],
compareRoot,
traversedPairs,
)
) {
return false;
}
}
Expand Down
4 changes: 1 addition & 3 deletions src/core/errors/index.ts
@@ -1,5 +1,3 @@
import { ValidationError } from './validation-error';

export {
ValidationError,
};
export { ValidationError };
31 changes: 18 additions & 13 deletions src/core/validate-graph.ts
Expand Up @@ -8,22 +8,27 @@ function assert(condition: boolean, msg: string) {
}
}

export function validateGraph(graph: graphlib.Graph,
rootNodeId: string,
pkgs: {[pkgId: string]: any},
pkgNodes: {[nodeId: string]: Set<string>}) {

assert((graph.predecessors(rootNodeId) || []).length === 0,
`"${rootNodeId}" is not really the root`);
export function validateGraph(
graph: graphlib.Graph,
rootNodeId: string,
pkgs: { [pkgId: string]: any },
pkgNodes: { [nodeId: string]: Set<string> },
) {
assert(
(graph.predecessors(rootNodeId) || []).length === 0,
`"${rootNodeId}" is not really the root`,
);
const reachableFromRoot = graphlib.alg.postorder(graph, [rootNodeId]);
const nodeIds = graph.nodes();

assert(JSON.stringify(nodeIds.sort()) === JSON.stringify(reachableFromRoot.sort()),
'not all graph nodes are reachable from root');
assert(
JSON.stringify(nodeIds.sort()) === JSON.stringify(reachableFromRoot.sort()),
'not all graph nodes are reachable from root',
);

const pkgIds = _.keys(pkgs) as string[];
const pkgsWithoutInstances = pkgIds
.filter((pkgId) => !pkgNodes[pkgId] || pkgNodes[pkgId].size === 0);
assert(pkgsWithoutInstances.length === 0,
'not all pkgs have instance nodes');
const pkgsWithoutInstances = pkgIds.filter(
(pkgId) => !pkgNodes[pkgId] || pkgNodes[pkgId].size === 0,
);
assert(pkgsWithoutInstances.length === 0, 'not all pkgs have instance nodes');
}
12 changes: 7 additions & 5 deletions src/legacy/event-loop-spinner.ts
Expand Up @@ -6,17 +6,19 @@ export class EventLoopSpinner {
}

public isStarving(): boolean {
return (Date.now() - this.afterLastSpin) > this.thresholdMs;
return Date.now() - this.afterLastSpin > this.thresholdMs;
}

public reset() {
this.afterLastSpin = Date.now();
}

public async spin() {
return new Promise((resolve) => setImmediate(() => {
this.reset();
resolve();
}));
return new Promise((resolve) =>
setImmediate(() => {
this.reset();
resolve();
}),
);
}
}

0 comments on commit cd86302

Please sign in to comment.