Skip to content

Commit

Permalink
feat(tools): update v8,v9 migration generators to update npmignore
Browse files Browse the repository at this point in the history
  • Loading branch information
Hotell committed May 30, 2023
1 parent 8e4a3d3 commit 85e8799
Show file tree
Hide file tree
Showing 6 changed files with 217 additions and 12 deletions.
1 change: 1 addition & 0 deletions tools/generators/migrate-converged-pkg/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1058,6 +1058,7 @@ describe('migrate-converged-pkg generator', () => {
.git*
.prettierignore
.swcrc
project.json
# exclude gitignore patterns explicitly
!lib
Expand Down
5 changes: 3 additions & 2 deletions tools/generators/migrate-converged-pkg/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ function runMigrationOnProject(tree: Tree, schema: AssertedSchema, _userLog: Use
setupNpmIgnoreConfig(tree, options);
setupBabel(tree, options);

updateNxWorkspace(tree, options);
updateNxProject(tree, options);

setupUnstableApi(tree, optionsWithTsConfigs);

Expand Down Expand Up @@ -397,6 +397,7 @@ const templates = {
.git*
.prettierignore
.swcrc
project.json
# exclude gitignore patterns explicitly
!lib
Expand Down Expand Up @@ -580,7 +581,7 @@ function uniqueArray<T extends unknown>(value: T[]) {
return Array.from(new Set(value));
}

function updateNxWorkspace(tree: Tree, options: NormalizedSchema) {
function updateNxProject(tree: Tree, options: NormalizedSchema) {
const packageType = getPackageType(tree, options);
const tags = {
web: 'platform:web',
Expand Down
88 changes: 84 additions & 4 deletions tools/generators/migrate-v8-pkg/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing';
import {
Tree,
readProjectConfiguration,
readWorkspaceConfiguration,
WorkspaceConfiguration,
serializeJson,
stripIndents,
addProjectConfiguration,
ProjectConfiguration,
logger,
readNxJson,
NxJsonConfiguration,
} from '@nrwl/devkit';
import type { Linter } from 'eslint';

Expand Down Expand Up @@ -63,9 +63,89 @@ describe('migrate-v8-pkg generator', () => {
expect(loggerInfoSpy).toHaveBeenCalled();
});
});

describe(`--name`, () => {
it(`should setup .npmignore`, async () => {
await generator(tree, options);

expect(tree.read(`packages/eight/.npmignore`, 'utf-8')).toMatchInlineSnapshot(`
"*.api.json
*.config.js
*.log
*.nuspec
*.test.*
*.yml
.editorconfig
.eslintrc*
.eslintcache
.gitattributes
.gitignore
.vscode
coverage
dist/storybook
dist/*.stats.html
dist/*.stats.json
dist/demo
fabric-test*
gulpfile.js
images
index.html
jsconfig.json
node_modules
results
src/**/*
!src/**/*.types.ts
temp
tsconfig.json
tsd.json
tslint.json
typings
visualtests
project.json
# exclude gitignore patterns explicitly
!lib
!lib-commonjs
!lib-amd
!dist"
`);
});
});

describe(`--all`, () => {
const projects = [
options.name,
'@proj/react-foo',
'@proj/react-bar',
'@proj/react-moo',
'@proj/react-zoo',
] as const;

beforeEach(() => {
setupDummyPackage(tree, { name: projects[1], version: '9.0.22' });
setupDummyPackage(tree, { name: projects[2], version: '8.0.31' });
setupDummyPackage(tree, { name: projects[3], version: '8.0.12' });
setupDummyPackage(tree, { name: projects[4], version: '8.0.1' });
});
it(`should run migration on all vNext packages in batch`, async () => {
await generator(tree, { all: true });

const configs = projects.reduce((acc, projectName) => {
acc[projectName] = readProjectConfiguration(tree, projectName);

return acc;
}, {} as Record<(typeof projects)[number], ProjectConfiguration>);

expect(configs[projects[1]].sourceRoot).not.toBeDefined();
expect(configs[options.name].sourceRoot).toBeDefined();
expect(configs[projects[2]].sourceRoot).toBeDefined();
expect(configs[projects[3]].sourceRoot).toBeDefined();
expect(configs[projects[4]].sourceRoot).toBeDefined();
});
});
});

function getNormalizedPkgName(options: { pkgName: string; workspaceConfig: WorkspaceConfiguration }) {
function getNormalizedPkgName(options: { pkgName: string; workspaceConfig: NxJsonConfiguration }) {
return options.pkgName.replace(`@${options.workspaceConfig.npmScope}/`, '');
}
function setupDummyPackage(
Expand All @@ -79,7 +159,7 @@ function setupDummyPackage(
projectConfiguration: Partial<ProjectConfiguration>;
}>,
) {
const workspaceConfig = readWorkspaceConfiguration(tree);
const workspaceConfig = readNxJson(tree) ?? {};
const defaults = {
version: '8.0.0',
dependencies: {
Expand Down
127 changes: 121 additions & 6 deletions tools/generators/migrate-v8-pkg/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as path from 'path';
import type { Linter } from 'eslint';
import {
logger,
Expand All @@ -9,11 +8,13 @@ import {
readJson,
joinPathFragments,
ProjectConfiguration,
stripIndents,
updateProjectConfiguration,
} from '@nrwl/devkit';

import { printStats } from '../print-stats';

import { getProjectConfig, getProjects, isV8Package } from '../../utils';
import { getProjectConfig, getProjects, isV8Package, printUserLogs, UserLog } from '../../utils';

import { MigrateV8PkgGeneratorSchema } from './schema';
import { PackageJson, TsConfig } from '../../types';
Expand All @@ -28,6 +29,7 @@ interface AssertedSchema extends MigrateV8PkgGeneratorSchema {
const noop = () => {};

export default async function (tree: Tree, schema: MigrateV8PkgGeneratorSchema) {
const userLog: UserLog = [];
const validatedSchema = await validateSchema(tree, schema);

if (hasSchemaFlag(validatedSchema, 'stats')) {
Expand All @@ -52,14 +54,19 @@ export default async function (tree: Tree, schema: MigrateV8PkgGeneratorSchema)
return noop;
}

if (hasSchemaFlag(validatedSchema, 'all')) {
runBatchMigration(tree, userLog);
}

if (hasSchemaFlag(validatedSchema, 'name')) {
console.log('THIS ISNT DOING ANYTHING YET, use --stats 🤝');
const normalizedOptions = normalizeOptions(tree, validatedSchema);
runMigrationOnProject(tree, validatedSchema);
}

await formatFiles(tree);

return noop;
return () => {
printUserLogs(userLog);
};
}

function normalizeOptions(tree: Tree, options: AssertedSchema) {
Expand Down Expand Up @@ -90,8 +97,16 @@ async function validateSchema(tree: Tree, schema: MigrateV8PkgGeneratorSchema) {
throw new Error('--name and --stats are mutually exclusive');
}

if (newSchema.name && newSchema.all) {
throw new Error('--name and --all are mutually exclusive');
}

if (newSchema.stats && newSchema.all) {
throw new Error('--stats and --all are mutually exclusive');
}

const shouldValidateNameInput = () => {
return !newSchema.name && !newSchema.stats;
return !newSchema.name && !(newSchema.all || newSchema.stats);
};

if (shouldValidateNameInput()) {
Expand Down Expand Up @@ -153,3 +168,103 @@ function getProjectMetadata(tree: Tree, project: ProjectConfiguration) {
}
}
}

function runBatchMigration(tree: Tree, userLog: UserLog) {
const projects = getProjects(tree);
projects.forEach((projectConfig, projectName) => {
if (!isV8Package(tree, projectConfig)) {
userLog.push({ type: 'error', message: `${projectName} is not v8 package. Skipping migration...` });
return;
}

runMigrationOnProject(tree, { name: projectName });
});

return tree;
}

function runMigrationOnProject(tree: Tree, schema: AssertedSchema) {
const options = normalizeOptions(tree, schema);

if (options.projectConfig.projectType === 'application') {
logger.warn(
stripIndents`
NOTE: you're trying to migrate an Application - ${options.name}.
We apply limited migration steps at the moment.
`,
);
return;
}

// updates start

setupNpmIgnoreConfig(tree, options);
updateNxProject(tree, options);

return tree;
}

function setupNpmIgnoreConfig(tree: Tree, options: NormalizedSchema) {
tree.write(options.paths.npmConfig, templates.npmIgnoreConfig);

return tree;
}

function updateNxProject(tree: Tree, options: NormalizedSchema) {
updateProjectConfiguration(tree, options.name, {
...options.projectConfig,
sourceRoot: joinPathFragments(options.projectConfig.root, 'src'),
tags: uniqueArray([...(options.projectConfig.tags ?? []), 'v8']),
implicitDependencies: uniqueArray([...(options.projectConfig.implicitDependencies ?? [])]),
});

return tree;
}

const templates = {
npmIgnoreConfig: stripIndents`
*.api.json
*.config.js
*.log
*.nuspec
*.test.*
*.yml
.editorconfig
.eslintrc*
.eslintcache
.gitattributes
.gitignore
.vscode
coverage
dist/storybook
dist/*.stats.html
dist/*.stats.json
dist/demo
fabric-test*
gulpfile.js
images
index.html
jsconfig.json
node_modules
results
src/**/*
!src/**/*.types.ts
temp
tsconfig.json
tsd.json
tslint.json
typings
visualtests
project.json
# exclude gitignore patterns explicitly
!lib
!lib-commonjs
!lib-amd
!dist
`,
};

function uniqueArray<T extends unknown>(value: T[]) {
return Array.from(new Set(value));
}
4 changes: 4 additions & 0 deletions tools/generators/migrate-v8-pkg/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
"index": 0
}
},
"all": {
"type": "boolean",
"description": "Run generator on all v8 packages"
},
"stats": {
"type": "boolean",
"description": "Get statistics for how many projects have been migrated"
Expand Down
4 changes: 4 additions & 0 deletions tools/generators/migrate-v8-pkg/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ export interface MigrateV8PkgGeneratorSchema {
* Library name or comma delimited library names to execute migration on multiple libraries.
*/
name?: string;
/**
* Run generator on all v8 packages
*/
all?: boolean;
/**
* Get statistics for how many projects have been migrated
*/
Expand Down

0 comments on commit 85e8799

Please sign in to comment.