Skip to content

Commit

Permalink
Silent (#469)
Browse files Browse the repository at this point in the history
* wip: test stdout for load logs

* wip: refact to "basic" from "usual"

* wip: add an option `silent`

* wip: add a failing test

* Add `silent` option

* fix: Compare `silent` as some output or no output
  • Loading branch information
piglovesyou authored May 4, 2021
1 parent d3de6f3 commit ed73ee4
Show file tree
Hide file tree
Showing 18 changed files with 118 additions and 31 deletions.
File renamed without changes.
11 changes: 11 additions & 0 deletions src/__fixtures/loader/silent/.graphql-let.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
schema: schema/type-defs.graphqls
documents:
- "**/*.graphql"
- "**/*.tsx"
plugins:
- typescript
- typescript-operations
- typescript-react-apollo
respectGitIgnore: true
cacheDir: __generated__
silent: true
18 changes: 18 additions & 0 deletions src/__fixtures/loader/silent/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { gql, load } from 'graphql-let';

const { useViewerQuery } = load('./viewer.graphql');
useViewerQuery().data.viewer.name as string;
// @ts-expect-error
useViewerQuery() as number;

const { useViewerYQuery } = gql(`
# import Partial from './partial.graphql'
query ViewerY {
viewer {
...Partial
}
}
`);
useViewerYQuery().data.viewer.name as string;
// @ts-expect-error
useViewerYQuery() as number;
4 changes: 4 additions & 0 deletions src/__fixtures/loader/silent/pages/partial.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
fragment Partial on User {
id
name
}
6 changes: 6 additions & 0 deletions src/__fixtures/loader/silent/pages/viewer.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# import Partial from './partial.graphql'
query Viewer {
viewer {
...Partial
}
}
6 changes: 6 additions & 0 deletions src/__fixtures/loader/silent/pages/viewer2.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# import Partial from './partial.graphql'
query Viewer2 {
viewer {
...Partial
}
}
9 changes: 9 additions & 0 deletions src/__fixtures/loader/silent/schema/type-defs.graphqls
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
type User {
id: ID!
name: String!
status: String!
}

type Query {
viewer: User
}
19 changes: 11 additions & 8 deletions src/gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,11 @@ export async function gen({
cwd,
configFilePath,
}: CommandOpts): Promise<CodegenContext[]> {
updateLog('Scanning...');

const [config, configHash] = await loadConfig(cwd, configFilePath);
const { silent } = config;

if (!silent) updateLog('Scanning...');

const execContext = createExecContext(cwd, config, configHash);
const codegenContext: CodegenContext[] = [];

Expand All @@ -120,28 +122,29 @@ export async function gen({
);

if (isAllSkip(codegenContext)) {
updateLog(
`Nothing to do. Caches for ${codegenContext.length} GraphQL documents are fresh.`,
);
if (!silent)
updateLog(
`Nothing to do. Caches for ${codegenContext.length} GraphQL documents are fresh.`,
);
} else {
const numToProcess = codegenContext.reduce(
(i, { skip }) => (skip ? i : i + 1),
0,
);
updateLog(`Processing ${numToProcess} codegen...`);
if (!silent) updateLog(`Processing ${numToProcess} codegen...`);

writeTiIndexForContext(execContext, codegenContext);

await processCodegenForContext(execContext, codegenContext);

updateLog(`Generating ${numToProcess} d.ts...`);
if (!silent) updateLog(`Generating ${numToProcess} d.ts...`);
await processDtsForContext(execContext, codegenContext);

const displayNum =
numToProcess === codegenContext.length
? numToProcess
: `${numToProcess}/${codegenContext.length}`;
updateLog(`Done processing ${displayNum} GraphQL documents.`);
if (!silent) updateLog(`Done processing ${displayNum} GraphQL documents.`);
}

await removeObsoleteFiles(execContext, codegenContext, graphqlRelPaths);
Expand Down
2 changes: 2 additions & 0 deletions src/lib/__snapshots__/config.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ Array [
},
],
"schemaEntrypoint": "",
"silent": false,
"typeInjectEntrypoint": "node_modules/@types/graphql-let/index.d.ts",
},
"6134bbfa2c25f64acb7c526097ecc4e4014c2aa4",
Expand All @@ -67,6 +68,7 @@ Object {
"respectGitIgnore": false,
"schema": "**/*.graphql",
"schemaEntrypoint": "yeah.graphqls",
"silent": false,
"typeInjectEntrypoint": "typings/yeah.d.ts;",
}
`;
5 changes: 4 additions & 1 deletion src/lib/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,11 @@ export function buildCodegenConfig(
}

return {
silent: true,
...config,
// Regardless of `silent` value in config,
// we always suppress GraphQL code generator logs
silent: true,

// @ts-ignore
cwd,

Expand Down
2 changes: 2 additions & 0 deletions src/lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export type GraphQLLetAdditionalOptions = {
// gqlDtsEntrypoint?: string;
typeInjectEntrypoint?: string;
generateOptions?: Types.ConfiguredOutput;
silent?: boolean;
};

export type UserConfigTypes = PartialGraphqlCodegenOptions &
Expand Down Expand Up @@ -64,6 +65,7 @@ export function buildConfig(raw: UserConfigTypes): ConfigTypes {
raw.typeInjectEntrypoint || 'node_modules/@types/graphql-let/index.d.ts',
generateOptions: raw.generateOptions || Object.create(null),
schemaEntrypoint: raw.schemaEntrypoint || '',
silent: raw.silent || false,
};
}

Expand Down
38 changes: 27 additions & 11 deletions src/loader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,17 @@ import { join as pathJoin } from 'path';
import { promisify } from 'util';
import waitOn from 'wait-on';
import { Stats } from 'webpack';
import * as print from './lib/print';
import compiler from './lib/__tools/compile';
import { prepareFixtures } from './lib/__tools/file';

const unlink = promisify(fs.unlink);

let flatProjFixtureDir: string;
let basicFixtureDir: string;
let monorepoFixtureDir: string;
let silentFixtureDir: string;

const flatProjEntrypoints = ['pages/index.tsx', 'pages/viewer.graphql'];
const basicEntrypoints = ['pages/index.tsx', 'pages/viewer.graphql'];

function getOutputInfo(stats: Stats) {
const { modules } = stats.toJson()!;
Expand All @@ -32,22 +34,22 @@ function getOutputInfo(stats: Stats) {

describe('graphql-let/loader', () => {
beforeAll(async () => {
[flatProjFixtureDir] = await prepareFixtures(
[basicFixtureDir] = await prepareFixtures(
__dirname,
'__fixtures/loader/usual',
'__fixtures/loader/basic',
);
[monorepoFixtureDir] = await prepareFixtures(
__dirname,
'__fixtures/loader/monorepo',
);
[silentFixtureDir] = await prepareFixtures(
__dirname,
'__fixtures/loader/silent',
);
});

test('generates .tsx and .d.ts', async () => {
const stats = await compiler(
flatProjFixtureDir,
flatProjEntrypoints,
'node',
);
const stats = await compiler(basicFixtureDir, basicEntrypoints, 'node');
const outputs = getOutputInfo(stats);
expect(outputs).toHaveLength(4);

Expand All @@ -72,7 +74,7 @@ describe('graphql-let/loader', () => {
];
const results = await Promise.all(
expectedTargets.map(([file, target]) =>
compiler(flatProjFixtureDir, [file], target),
compiler(basicFixtureDir, [file], target),
),
);
for (const [i, stats] of results.entries()) {
Expand All @@ -82,11 +84,25 @@ describe('graphql-let/loader', () => {
expect(output).toMatchSnapshot();
}
const globResults = await glob('**/*.graphql.d.ts', {
cwd: flatProjFixtureDir,
cwd: basicFixtureDir,
});
strictEqual(globResults.length, 2);
});

test('The option "silent" suppresses standard output logs', async () => {
let messages = '';
const mockFn = (m: any) => (messages += m + '\n');
jest.spyOn(print, 'printInfo').mockImplementation(mockFn);
jest.spyOn(print, 'updateLog').mockImplementation(mockFn);

await compiler(basicFixtureDir, basicEntrypoints, 'node');
expect(messages).not.toHaveLength(0);

messages = '';
await compiler(silentFixtureDir, basicEntrypoints, 'node');
expect(messages).toHaveLength(0);
});

describe('options', () => {
async function acceptsConfigPathInOptionsConfigFile(
configFilePath: string,
Expand Down
29 changes: 18 additions & 11 deletions src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,11 @@ const processLoaderForSources = memoize(
options: GraphQLLetLoaderOptions,
): Promise<string | Buffer> => {
const [config, configHash] = await loadConfig(cwd, options.configFile);
const { silent } = config;
const execContext = createExecContext(cwd, config, configHash);
const codegenContext: CodegenContext[] = [];
const sourceRelPath = pathRelative(cwd, sourceFullPath);
updateLog(`Processing ${sourceRelPath}...`);
if (!silent) updateLog(`Processing ${sourceRelPath}...`);

const { schemaHash } = await appendFileSchemaContext(
execContext,
Expand All @@ -78,12 +79,12 @@ const processLoaderForSources = memoize(
if (!codegenContext.length) return sourceContent;

if (isAllSkip(codegenContext)) {
updateLog(`Nothing to do. Cache was fresh.`);
if (!silent) updateLog(`Nothing to do. Cache was fresh.`);
const [{ tsxFullPath }] = codegenContext;
return await readFile(tsxFullPath, 'utf-8');
}

updateLog(`Processing codegen for ${sourceRelPath}...`);
if (!silent) updateLog(`Processing codegen for ${sourceRelPath}...`);
const [[fileNode, programPath, callExpressionPathPairs]] = paths;

// Add dependencies so editing dependent GraphQL emits HMR.
Expand All @@ -107,12 +108,15 @@ const processLoaderForSources = memoize(
);
writeTiIndexForContext(execContext, codegenContext);
await processCodegenForContext(execContext, codegenContext);
updateLog(`Generating d.ts for ${sourceRelPath}...`);
if (!silent) updateLog(`Generating d.ts for ${sourceRelPath}...`);
await processDtsForContext(execContext, codegenContext);

const { code } = generator(fileNode);

updateLog(`Done processing ${sourceRelPath}.`);
if (!silent) {
updateLog(`Done processing ${sourceRelPath}.`);
updateLogDone();
}
return code;
},
(gqlFullPath: string) => gqlFullPath,
Expand All @@ -127,10 +131,11 @@ const processLoaderForDocuments = memoize(
options: GraphQLLetLoaderOptions,
): Promise<string> => {
const [config, configHash] = await loadConfig(cwd, options.configFile);
const { silent } = config;
const execContext = createExecContext(cwd, config, configHash);
const codegenContext: FileSchemaCodegenContext[] = [];
const graphqlRelPath = pathRelative(cwd, gqlFullPath);
updateLog(`Processing ${graphqlRelPath}...`);
if (!silent) updateLog(`Processing ${graphqlRelPath}...`);

// Add dependencies so editing dependent GraphQL emits HMR.
const { dependantFullPaths } = resolveGraphQLDocument(
Expand All @@ -156,19 +161,22 @@ const processLoaderForDocuments = memoize(

const { skip, tsxFullPath } = fileContext;
if (skip) {
updateLog(`Nothing to do. Cache was fresh.`);
if (!silent) updateLog(`Nothing to do. Cache was fresh.`);
return await readFile(tsxFullPath, 'utf-8');
}

updateLog(`Processing codegen for ${graphqlRelPath}...`);
if (!silent) updateLog(`Processing codegen for ${graphqlRelPath}...`);
const [{ content }] = await processCodegenForContext(execContext, [
fileContext,
]);

updateLog(`Generating d.ts for ${graphqlRelPath}...`);
if (!silent) updateLog(`Generating d.ts for ${graphqlRelPath}...`);
await processDtsForContext(execContext, [fileContext]);

updateLog(`Done processing ${graphqlRelPath}.`);
if (!silent) {
updateLog(`Done processing ${graphqlRelPath}.`);
updateLogDone();
}
return content;
},
(gqlFullPath: string) => gqlFullPath,
Expand Down Expand Up @@ -212,7 +220,6 @@ const graphQLLetLoader: loader.Loader = function (resourceContent) {

promise
.then((tsxContent) => {
updateLogDone();
callback(undefined, tsxContent);
})
.catch((e) => {
Expand Down

0 comments on commit ed73ee4

Please sign in to comment.