Skip to content

Commit 899af2f

Browse files
author
Dane Pilcher
authored
fix: skip bad statement source on type generation and exclude type file (#738)
1 parent 648a2a5 commit 899af2f

File tree

9 files changed

+108
-26
lines changed

9 files changed

+108
-26
lines changed

packages/amplify-codegen/src/commands/add.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ async function add(context, apiId = null, region = 'us-east-1') {
133133
const newProject = {
134134
projectName: withoutInit ? 'Codegen Project' : apiDetails.name,
135135
includes: answer.includePattern,
136-
excludes: answer.excludePattern,
136+
excludes: [...answer.excludePattern, answer.generatedFileName],
137137
schema,
138138
amplifyExtension: {
139139
codeGenTarget: answer.target || '',

packages/amplify-codegen/src/commands/types.js

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -62,18 +62,29 @@ async function generateTypes(context, forceDownloadSchema, withoutInit = false,
6262
cwd: projectPath,
6363
absolute: true,
6464
});
65-
const queries = queryFilePaths.map(queryFilePath => {
66-
const fileContents = fs.readFileSync(queryFilePath, 'utf8');
67-
if (
68-
queryFilePath.endsWith('.jsx') ||
69-
queryFilePath.endsWith('.js') ||
70-
queryFilePath.endsWith('.tsx') ||
71-
queryFilePath.endsWith('.ts')
72-
) {
73-
return extractDocumentFromJavascript(fileContents, '');
74-
}
75-
return new Source(fileContents, queryFilePath);
76-
});
65+
const queries = queryFilePaths
66+
.map(queryFilePath => {
67+
const fileContents = fs.readFileSync(queryFilePath, 'utf8');
68+
if (
69+
queryFilePath.endsWith('.jsx') ||
70+
queryFilePath.endsWith('.js') ||
71+
queryFilePath.endsWith('.tsx') ||
72+
queryFilePath.endsWith('.ts')
73+
) {
74+
return [queryFilePath, extractDocumentFromJavascript(fileContents, '')];
75+
}
76+
return [queryFilePath, new Source(fileContents, queryFilePath)];
77+
})
78+
.filter(([queryFilePath, source]) => {
79+
if (!source) {
80+
context.print.warning(
81+
`Unable to extract GraphQL queries from ${queryFilePath}. Skipping source. This source matched the includes target in .grapqhlconfig.yml. Modify the includes or excludes target if this file should not be included.`,
82+
);
83+
return false;
84+
}
85+
return true;
86+
})
87+
.map(([, source]) => source);
7788
if (queries.length === 0) {
7889
throw new Error("No queries found to generate types for, you may need to run 'codegen statements' first");
7990
}

packages/amplify-codegen/src/walkthrough/configure.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,14 @@ async function configureProjectWalkThrough(context, amplifyConfig, withoutInit =
5050
selectedProjectConfig.includes = await askCodeGeneQueryFilePattern(includePattern);
5151

5252
if (!(frontend === 'android' || targetLanguage === 'javascript')) {
53-
amplifyExtension.generatedFileName = await askTargetFileName(amplifyExtension.generatedFileName || 'API', targetLanguage);
53+
const generatedFileName = await askTargetFileName(amplifyExtension.generatedFileName || 'API', targetLanguage);
54+
amplifyExtension.generatedFileName = generatedFileName;
55+
selectedProjectConfig.excludes = Array.from(new Set(selectedProjectConfig.excludes || []).add(generatedFileName));
5456
} else {
5557
amplifyExtension.generatedFileName = '';
5658
}
5759
amplifyExtension.codeGenTarget = targetLanguage;
58-
amplifyExtension.docsFilePath = getGraphQLDocPath(frontend, includePatternDefault.graphQLDirectory, selectedProjectConfig.includes)
60+
amplifyExtension.docsFilePath = getGraphQLDocPath(frontend, includePatternDefault.graphQLDirectory, selectedProjectConfig.includes);
5961
amplifyExtension.maxDepth = await askMaxDepth(amplifyExtension.maxDepth);
6062

6163
return selectedProjectConfig;

packages/amplify-codegen/tests/commands/__snapshots__/add.test.js.snap

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@ Object {
1111
"generatedFileName": "API.TS",
1212
"region": "us-east-1",
1313
},
14-
"excludes": "MOCK_EXCLUDE",
14+
"excludes": Array [
15+
"MOCK_EXCLUDE",
16+
"API.TS",
17+
],
1518
"includes": "MOCK_INCLUDE",
1619
"projectName": "Codegen Project",
1720
"schema": "/user/foo/project/schema.json",
@@ -29,7 +32,10 @@ Object {
2932
"generatedFileName": "API.TS",
3033
"region": "us-east-1",
3134
},
32-
"excludes": "MOCK_EXCLUDE",
35+
"excludes": Array [
36+
"MOCK_EXCLUDE",
37+
"API.TS",
38+
],
3339
"includes": "MOCK_INCLUDE",
3440
"projectName": "Codegen Project",
3541
"schema": "/user/foo/project/schema.json",
@@ -47,7 +53,10 @@ Object {
4753
"generatedFileName": "API.TS",
4854
"region": "us-east-1",
4955
},
50-
"excludes": "MOCK_EXCLUDE",
56+
"excludes": Array [
57+
"MOCK_EXCLUDE",
58+
"API.TS",
59+
],
5160
"includes": "MOCK_INCLUDE",
5261
"projectName": "Codegen Project",
5362
"schema": "/user/foo/project/schema.graphql",
@@ -65,7 +74,10 @@ Object {
6574
"generatedFileName": "API.TS",
6675
"region": "us-west-2",
6776
},
68-
"excludes": "MOCK_EXCLUDE",
77+
"excludes": Array [
78+
"MOCK_EXCLUDE",
79+
"API.TS",
80+
],
6981
"includes": "MOCK_INCLUDE",
7082
"projectName": "Codegen Project",
7183
"schema": "/user/foo/project/schema.json",

packages/amplify-codegen/tests/commands/add.test.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ jest.mock('process', () => ({
4545
}));
4646

4747
const MOCK_INCLUDE_PATTERN = 'MOCK_INCLUDE';
48-
const MOCK_EXCLUDE_PATTERN = 'MOCK_EXCLUDE';
48+
const MOCK_EXCLUDE_PATTERN = ['MOCK_EXCLUDE'];
4949
const MOCK_SCHEMA_LOCATION = 'INTROSPECTION_SCHEMA.JSON';
5050
const MOCK_TARGET = 'TYPE_SCRIPT_OR_FLOW_OR_ANY_OTHER_LANGUAGE';
5151
const MOCK_GENERATED_FILE_NAME = 'API.TS';
@@ -100,7 +100,7 @@ describe('command - add', () => {
100100
const newProjectConfig = LOAD_CONFIG_METHODS.addProject.mock.calls[0][0];
101101
expect(newProjectConfig.projectName).toEqual(MOCK_API_NAME);
102102
expect(newProjectConfig.includes).toEqual(MOCK_INCLUDE_PATTERN);
103-
expect(newProjectConfig.excludes).toEqual(MOCK_EXCLUDE_PATTERN);
103+
expect(newProjectConfig.excludes).toEqual([...MOCK_EXCLUDE_PATTERN, MOCK_GENERATED_FILE_NAME]);
104104
expect(newProjectConfig.schema).toEqual(MOCK_SCHEMA_FILE_LOCATION);
105105
expect(newProjectConfig.amplifyExtension.codeGenTarget).toEqual(MOCK_TARGET);
106106
expect(newProjectConfig.amplifyExtension.generatedFileName).toEqual(MOCK_GENERATED_FILE_NAME);

packages/amplify-codegen/tests/commands/mock-fs-setup.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ function setupMocks(mockFs, loadConfig, apiId, frontend, target, generatedFileNa
3636
{
3737
schema: schemaFilePath,
3838
includes: [path.join(docsFilePath[frontend], '*')],
39-
excludes: ['./amplify/**'],
39+
excludes: ['./amplify/**', './src/graphql/excluded.ts'],
4040
amplifyExtension: {
4141
codeGenTarget: target,
4242
generatedFileName,

packages/amplify-codegen/tests/commands/types-mock-fs.test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ const MOCK_APIS = [
3434
const MOCK_CONTEXT = {
3535
print: {
3636
info: jest.fn(),
37+
warning: jest.fn(),
3738
},
3839
amplify: {
3940
getProjectMeta: jest.fn(() => ({ api: { id: MOCK_API_ID } })),
@@ -121,4 +122,25 @@ describe('command - types (mock fs)', () => {
121122
await generateTypes(MOCK_CONTEXT, false);
122123
expect(fs.existsSync(generatedFileName)).toBeFalsy();
123124
});
125+
126+
it('should skip invalid sources', async () => {
127+
const { generatedFileName } = setupMocks(mockFs, loadConfig, MOCK_API_ID, 'javascript', 'typescript', 'src/graphql/API.ts', {
128+
'src/graphql/excluded.ts': '',
129+
'src/graphql/foo.ts': '',
130+
});
131+
132+
await generateStatements(MOCK_CONTEXT, false);
133+
await generateTypes(MOCK_CONTEXT, false);
134+
expect(MOCK_CONTEXT.print.warning).toHaveBeenCalledWith(
135+
expect.stringMatching(
136+
'Unable to extract GraphQL queries from .*/src/graphql/foo.ts. Skipping source. This source matched the includes target in .grapqhlconfig.yml. Modify the includes or excludes target if this file should not be included.',
137+
),
138+
);
139+
expect(MOCK_CONTEXT.print.warning).not.toHaveBeenCalledWith(
140+
expect.stringMatching(
141+
'Unable to extract GraphQL queries from .*/src/graphql/excluded.ts. Skipping source. This source matched the includes target in .grapqhlconfig.yml. Modify the includes or excludes target if this file should not be included.',
142+
),
143+
);
144+
expect(fs.existsSync(generatedFileName)).toBeTruthy();
145+
});
124146
});

packages/amplify-codegen/tests/commands/types.test.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,10 @@ describe('command - types', () => {
8080
await generateTypes(MOCK_CONTEXT, forceDownload);
8181
expect(getFrontEndHandler).toHaveBeenCalledWith(MOCK_CONTEXT);
8282
expect(loadConfig).toHaveBeenCalledWith(MOCK_CONTEXT, false);
83-
expect(sync).toHaveBeenCalledWith([MOCK_INCLUDE_PATH, `!${MOCK_EXCLUDE_PATH}`], { cwd: MOCK_PROJECT_ROOT, absolute: true });
83+
expect(sync).toHaveBeenCalledWith([MOCK_INCLUDE_PATH, `!${MOCK_EXCLUDE_PATH}`], {
84+
cwd: MOCK_PROJECT_ROOT,
85+
absolute: true,
86+
});
8487
expect(generateTypesHelper).toHaveBeenCalledWith({
8588
queries: [new Source('query 1', 'q1.gql'), new Source('query 2', 'q2.gql')],
8689
schema: 'schema',

packages/amplify-codegen/tests/walkthrough/configure.test.js

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,14 @@ describe('configure walk-through', () => {
2424
const mockGraphQLExtension = 'MOCK_GQL_EXTENSION';
2525
const MOCK_MAX_DEPTH = 'MOCK_MAX_DEPTH';
2626

27+
const projectOneExcludes = ['one/excluded/*.gql', 'one/excluded/*.graphql'];
28+
const projectTwoExcludes = ['two/excluded/*.gql', 'two/excluded/*.graphql'];
29+
2730
const mockConfigs = [
2831
{
2932
projectName: 'One',
30-
includes: ['one/**/*.gql', 'one/**/*.graohql'],
33+
includes: ['one/**/*.gql', 'one/**/*.graphql'],
34+
excludes: projectOneExcludes,
3135
amplifyExtension: {
3236
graphQLApiId: 'one',
3337
generatedFileName: 'one-1.ts',
@@ -37,7 +41,8 @@ describe('configure walk-through', () => {
3741
},
3842
{
3943
projectName: 'Two',
40-
includes: ['two/**/*.gql', 'two/**/*.graohql'],
44+
includes: ['two/**/*.gql', 'two/**/*.graphql'],
45+
excludes: projectTwoExcludes,
4146
amplifyExtension: {
4247
graphQLApiId: 'two',
4348
maxDepth: 10,
@@ -78,13 +83,40 @@ describe('configure walk-through', () => {
7883
mockConfigs[1].amplifyExtension.codeGenTarget,
7984
false,
8085
undefined,
81-
undefined
86+
undefined,
8287
);
8388
expect(askCodegneQueryFilePattern).toHaveBeenCalledWith([join(mockGraphQLDirectory, '**', mockGraphQLExtension)]);
8489
expect(askGeneratedFileName).toHaveBeenCalledWith(mockConfigs[1].amplifyExtension.generatedFileName, mockTargetLanguage);
8590
expect(askMaxDepth).toHaveBeenCalledWith(10);
8691
expect(results).toEqual({
8792
projectName: mockConfigs[1].projectName,
93+
excludes: [...projectTwoExcludes, mockGeneratedFileName],
94+
includes: mockIncludes,
95+
amplifyExtension: {
96+
graphQLApiId: mockConfigs[1].amplifyExtension.graphQLApiId,
97+
generatedFileName: mockGeneratedFileName,
98+
codeGenTarget: mockTargetLanguage,
99+
maxDepth: MOCK_MAX_DEPTH,
100+
},
101+
});
102+
});
103+
104+
it('should not add generated types file to excludes twice', async () => {
105+
const result = await configure(mockContext, mockConfigs);
106+
expect(result).toEqual({
107+
projectName: mockConfigs[1].projectName,
108+
excludes: [...projectTwoExcludes, mockGeneratedFileName],
109+
includes: mockIncludes,
110+
amplifyExtension: {
111+
graphQLApiId: mockConfigs[1].amplifyExtension.graphQLApiId,
112+
generatedFileName: mockGeneratedFileName,
113+
codeGenTarget: mockTargetLanguage,
114+
maxDepth: MOCK_MAX_DEPTH,
115+
},
116+
});
117+
expect(await configure(mockContext, [result])).toEqual({
118+
projectName: mockConfigs[1].projectName,
119+
excludes: [...projectTwoExcludes, mockGeneratedFileName],
88120
includes: mockIncludes,
89121
amplifyExtension: {
90122
graphQLApiId: mockConfigs[1].amplifyExtension.graphQLApiId,

0 commit comments

Comments
 (0)