Skip to content

Commit b9b0b05

Browse files
authored
chore: rewrite readmes correctly in aws-cdk-lib and monocdk (backport #17573) (#17635)
This is an automatic backport of pull request #17573 done by [Mergify](https://mergify.com). Cherry-pick of 66e37cc has failed: ``` On branch mergify/bp/master/pr-17573 Your branch is up to date with 'origin/master'. You are currently cherry-picking commit 66e37cc. (fix conflicts and run "git cherry-pick --continue") (use "git cherry-pick --skip" to skip this patch) (use "git cherry-pick --abort" to cancel the cherry-pick operation) Changes to be committed: modified: packages/@aws-cdk/cfnspec/test/libary-creation.test.ts modified: packages/aws-cdk-lib/.gitignore modified: packages/aws-cdk-lib/package.json modified: packages/aws-cdk-lib/scripts/verify-imports-resolve-same.ts deleted: packages/aws-cdk-lib/scripts/verify-readme-import-rewrites.ts modified: packages/aws-cdk-migration/bin/rewrite-imports-v2.ts modified: packages/aws-cdk-migration/lib/rewrite.ts modified: packages/aws-cdk-migration/test/rewrite.test.ts modified: packages/monocdk/.gitignore modified: tools/@aws-cdk/cdk-build-tools/bin/cdk-build.ts modified: tools/@aws-cdk/individual-pkg-gen/transform-packages.ts modified: tools/@aws-cdk/ubergen/bin/ubergen.ts modified: tools/@aws-cdk/ubergen/package.json Unmerged paths: (use "git add <file>..." to mark resolution) both modified: packages/@aws-cdk/cfnspec/lib/library-creation.ts ``` To fix up this pull request, you can check it out locally. See documentation: https://docs.github.com/en/github/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/checking-out-pull-requests-locally --- <details> <summary>Mergify commands and options</summary> <br /> More conditions and actions can be found in the [documentation](https://docs.mergify.com/). You can also trigger Mergify actions by commenting on this pull request: - `@Mergifyio refresh` will re-evaluate the rules - `@Mergifyio rebase` will rebase this PR on its base branch - `@Mergifyio update` will merge the base branch into this PR - `@Mergifyio backport <destination>` will backport this PR on `<destination>` branch Additionally, on Mergify [dashboard](https://dashboard.mergify.com/) you can: - look at your merge queues - generate the Mergify configuration with the config editor. Finally, you can contact us on https://mergify.com </details>
1 parent 18c9ef7 commit b9b0b05

File tree

14 files changed

+262
-226
lines changed

14 files changed

+262
-226
lines changed

packages/@aws-cdk/cfnspec/lib/library-creation.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ export async function createLibraryReadme(namespace: string, readmePath: string)
7676
'This module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project.',
7777
'',
7878
'```ts nofixture',
79-
`import ${module.moduleName.toLocaleLowerCase()} = require('${module.packageName}');`,
79+
`import * as ${module.moduleName.toLocaleLowerCase().replace(/[^a-z0-9_]/g, '_')} from '${module.packageName}';`,
8080
'```',
8181
'',
8282
].join('\n'), 'utf8');

packages/@aws-cdk/cfnspec/test/libary-creation.test.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
import { createModuleDefinitionFromCfnNamespace } from '../lib';
1+
import * as path from 'path';
2+
import * as fs from 'fs-extra';
3+
import { createModuleDefinitionFromCfnNamespace, createLibraryReadme } from '../lib';
24

35
describe('createModuleDefinitionFromCfnNamespace', () => {
4-
56
test('base case', () => {
67
const module = createModuleDefinitionFromCfnNamespace('AWS::EC2');
78

@@ -55,5 +56,15 @@ describe('createModuleDefinitionFromCfnNamespace', () => {
5556
pythonModuleName: 'aws_cdk.alexa_ask',
5657
});
5758
});
59+
});
5860

61+
describe('createLibraryReadme', () => {
62+
test('library name is valid', async () => {
63+
const tempDir = fs.mkdtempSync(path.join(__dirname, 'temp'));
64+
const readmePath = path.join(tempDir, 'README.md');
65+
await createLibraryReadme('Alexa::ASK', readmePath);
66+
67+
const readme = fs.readFileSync(readmePath, { encoding: 'utf8' });
68+
expect(readme).toContain("import * as alexa_ask from '@aws-cdk/alexa-ask';");
69+
});
5970
});

packages/aws-cdk-lib/.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
!LICENSE
66
!NOTICE
77
!README.md
8-
!scripts/*
8+
!scripts/
99

1010
.LAST_BUILD
1111
*.snk

packages/aws-cdk-lib/package.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,7 @@
3838
},
3939
"stripDeprecated": true,
4040
"post": [
41-
"node ./scripts/verify-readme-import-rewrites.js",
42-
"node ./scripts/verify-import-resolve-same.js"
41+
"node ./scripts/verify-imports-resolve-same.js"
4342
]
4443
},
4544
"cdk-package": {

packages/aws-cdk-lib/scripts/verify-imports-resolve-same.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ async function compileAndResolve(fileName: string, contents: string, symbolName:
8484
}
8585

8686
// Return the filename
87-
const srcFile = sym.declarations?.[0].getSourceFile().fileName;
87+
const srcFile = sym.declarations?.[0].getSourceFile().fileName.replace(/.ts|.js|.d.ts/, '');
8888
if (!srcFile) {
8989
console.log(sym);
9090
throw new Error(`Symbol ${symbolName} in '${contents}' does not resolve to a source location`);

packages/aws-cdk-lib/scripts/verify-readme-import-rewrites.ts

Lines changed: 0 additions & 49 deletions
This file was deleted.

packages/aws-cdk-migration/bin/rewrite-imports-v2.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import * as fs from 'fs';
33
import { promisify } from 'util';
44
import * as _glob from 'glob';
55

6-
import { rewriteImports } from '../lib/rewrite';
6+
import { rewriteMonoPackageImports } from '../lib/rewrite';
77

88
const glob = promisify(_glob);
99

@@ -23,7 +23,7 @@ async function main() {
2323
const files = await glob(arg, { ignore, matchBase: true });
2424
for (const file of files) {
2525
const input = await fs.promises.readFile(file, { encoding: 'utf8' });
26-
const output = rewriteImports(input, file);
26+
const output = rewriteMonoPackageImports(input, 'aws-cdk-lib', file);
2727
if (output.trim() !== input.trim()) {
2828
await fs.promises.writeFile(file, output);
2929
}

packages/aws-cdk-migration/lib/rewrite.ts

Lines changed: 74 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,18 +42,79 @@ export interface RewriteOptions {
4242
* - `require('@aws-cdk/lib');
4343
*
4444
* @param sourceText the source code where imports should be re-written.
45+
* @param libName the mono CDK library name.
4546
* @param fileName a customized file name to provide the TypeScript processor.
4647
*
4748
* @returns the updated source code.
4849
*/
49-
export function rewriteImports(sourceText: string, fileName: string = 'index.ts', options: RewriteOptions = {}): string {
50+
export function rewriteMonoPackageImports(sourceText: string, libName: string, fileName: string = 'index.ts', options: RewriteOptions = {}): string {
51+
return rewriteImports(sourceText, (modPath, importedElements) => updatedExternalLocation(modPath, libName, options, importedElements), fileName);
52+
}
53+
54+
/**
55+
* Re-writes READMEs of "hyper-modular" CDK imports (most packages in `@aws-cdk/*`)
56+
* to the relevant "mono" CDK import path. The re-writing will only modify the imported
57+
* library path, presrving the existing quote style, etc...
58+
*
59+
* Syntax errors in the README snippets being processed may cause some import
60+
* statements to not be re-written.
61+
*
62+
* Supported import statement forms are:
63+
* - `import * as lib from '@aws-cdk/lib';`
64+
* - `import { Type } from '@aws-cdk/lib';`
65+
* - `import '@aws-cdk/lib';`
66+
* - `import lib = require('@aws-cdk/lib');`
67+
* - `import { Type } = require('@aws-cdk/lib');
68+
* - `require('@aws-cdk/lib');
69+
*
70+
* @param sourceText the README where snippet imports should be re-written.
71+
* @param libName the mono CDK library name.
72+
* @param fileName a customized file name to provide the TypeScript processor.
73+
*
74+
* @returns the updated source code.
75+
*/
76+
export function rewriteReadmeImports(sourceText: string, libName: string, fileName: string = 'index.ts', options: RewriteOptions = {}): string {
77+
return sourceText.replace(/(```(?:ts|typescript|text)[^\n]*\n)(.*?)(\n\s*```)/gs, (_m, prefix, body, suffix) => {
78+
return prefix +
79+
rewriteImports(body, (modPath, importedElements) => updatedExternalLocation(modPath, libName, options, importedElements), fileName) +
80+
suffix;
81+
});
82+
}
83+
84+
/**
85+
* Re-writes "hyper-modular" CDK imports (most packages in `@aws-cdk/*`) to the
86+
* relevant "mono" CDK import path. The re-writing will only modify the imported
87+
* library path, presrving the existing quote style, etc...
88+
*
89+
* Syntax errors in the source file being processed may cause some import
90+
* statements to not be re-written.
91+
*
92+
* Supported import statement forms are:
93+
* - `import * as lib from '@aws-cdk/lib';`
94+
* - `import { Type } from '@aws-cdk/lib';`
95+
* - `import '@aws-cdk/lib';`
96+
* - `import lib = require('@aws-cdk/lib');`
97+
* - `import { Type } = require('@aws-cdk/lib');
98+
* - `require('@aws-cdk/lib');
99+
*
100+
* @param sourceText the source code where imports should be re-written.
101+
* @param updatedLocation a function that returns the updated location of the import.
102+
* @param fileName a customized file name to provide the TypeScript processor.
103+
*
104+
* @returns the updated source code.
105+
*/
106+
export function rewriteImports(
107+
sourceText: string,
108+
updatedLocation: (modulePath: string, importedElements?: ts.NodeArray<ts.ImportSpecifier>) => string | undefined,
109+
fileName: string = 'index.ts',
110+
): string {
50111
const sourceFile = ts.createSourceFile(fileName, sourceText, ts.ScriptTarget.ES2018);
51112

52113
const replacements = new Array<{ original: ts.Node, updatedLocation: string }>();
53114

54115
const visitor = <T extends ts.Node>(node: T): ts.VisitResult<T> => {
55116
const moduleSpecifier = getModuleSpecifier(node);
56-
const newTarget = moduleSpecifier && updatedLocationOf(moduleSpecifier.text, options, getImportedElements(node));
117+
const newTarget = moduleSpecifier && updatedLocation(moduleSpecifier.text, getImportedElements(node));
57118

58119
if (moduleSpecifier != null && newTarget != null) {
59120
replacements.push({ original: moduleSpecifier, updatedLocation: newTarget });
@@ -131,15 +192,20 @@ const EXEMPTIONS = new Set([
131192
'@aws-cdk/pkglint',
132193
]);
133194

134-
function updatedLocationOf(modulePath: string, options: RewriteOptions, importedElements?: ts.NodeArray<ts.ImportSpecifier>): string | undefined {
195+
function updatedExternalLocation(
196+
modulePath: string,
197+
libName: string,
198+
options: RewriteOptions,
199+
importedElements?: ts.NodeArray<ts.ImportSpecifier>,
200+
): string | undefined {
135201
const customModulePath = options.customModules?.[modulePath];
136202
if (customModulePath) {
137203
let awsCdkLibLocation = undefined;
138204
importedElements?.forEach(e => {
139205
if (e.name.text.startsWith('Cfn') || e.propertyName?.text.startsWith('Cfn')) {
140206
// This is an L1 import, so don't return the customModulePath (which is the alpha module).
141207
// Return the relevant aws-cdk-lib location.
142-
awsCdkLibLocation = `aws-cdk-lib/${modulePath.substring('@aws-cdk/'.length)}`;
208+
awsCdkLibLocation = `${libName}/${modulePath.substring('@aws-cdk/'.length)}`;
143209
}
144210
});
145211
if (awsCdkLibLocation) {
@@ -149,7 +215,7 @@ function updatedLocationOf(modulePath: string, options: RewriteOptions, imported
149215
}
150216

151217
if (options.rewriteCfnImports && modulePath.endsWith(`${options.packageUnscopedName?.substr('aws-'.length)}.generated`)) {
152-
return `aws-cdk-lib/${options.packageUnscopedName}`;
218+
return `${libName}/${options.packageUnscopedName}`;
153219
}
154220

155221
if (
@@ -161,11 +227,11 @@ function updatedLocationOf(modulePath: string, options: RewriteOptions, imported
161227
}
162228

163229
if (modulePath.startsWith('@aws-cdk/core/lib')) {
164-
return `aws-cdk-lib/lib/core/lib/${modulePath.substring('@aws-cdk/core/lib/'.length)}`;
230+
return `${libName}/core/lib/${modulePath.substring('@aws-cdk/core/lib/'.length)}`;
165231
}
166232

167233
if (modulePath === '@aws-cdk/core') {
168-
return 'aws-cdk-lib';
234+
return libName;
169235
}
170236

171237
// These 2 are unchanged
@@ -183,7 +249,7 @@ function updatedLocationOf(modulePath: string, options: RewriteOptions, imported
183249
return '@aws-cdk/assert/jest';
184250
}
185251

186-
return `aws-cdk-lib/${modulePath.substring('@aws-cdk/'.length)}`;
252+
return `${libName}/${modulePath.substring('@aws-cdk/'.length)}`;
187253
}
188254

189255
/**

0 commit comments

Comments
 (0)