Skip to content

Commit

Permalink
fixed logging issue
Browse files Browse the repository at this point in the history
  • Loading branch information
lmgyuan committed May 24, 2024
1 parent 900faa9 commit 3e7afe7
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 28 deletions.
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module.exports = {
clearMocks: true,
modulePathIgnorePatterns: ["./__mocks__(?!/loglevel.js)"],
moduleNameMapper: {
'^nimma/legacy$': '<rootDir>/node_modules/nimma/dist/legacy/cjs/index.js',
'^nimma/(.*)': '<rootDir>/node_modules/nimma/dist/cjs/$1',
Expand Down
8 changes: 4 additions & 4 deletions lib/generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,8 @@ class Generator {
}
});
});
// PR 1162: set log level during construction to avoid asynchronous issues
this.setLogLevel();
// // PR 1162: set log level during construction to avoid asynchronous issues
// this.setLogLevel();
}

/**
Expand Down Expand Up @@ -200,7 +200,7 @@ class Generator {
this.validateAsyncAPIDocument(asyncapiDocument);
await this.setupOutput();
// PR 1162: always set log level during construction to avoid asynchronous issues
// this.setLogLevel();
this.setLogLevel();

await this.installAndSetupTemplate();
await this.configureTemplateWorkflow(parseOptions);
Expand Down Expand Up @@ -856,7 +856,7 @@ class Generator {
if (renderContent === undefined) {
return;
} else if (isReactTemplate(this.templateConfig)) {
await saveRenderedReactContent(renderContent, outputPath, this.noOverwriteGlobs);
await saveRenderedReactContent(renderContent, outputPath, this.noOverwriteGlobs, this);
} else {
await writeFile(outputPath, renderContent);
}
Expand Down
7 changes: 6 additions & 1 deletion lib/logMessages.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ function conditionalFilesMatched(relativeSourceFile) {
return `${relativeSourceFile} was not generated because condition specified for this file in template configuration in conditionalFiles matched.`;
}

function skipOverwriting(filePath) {
return `Skipping overwrite for: ${filePath}`;
}

module.exports = {
TEMPLATE_INSTALL_FLAG_MSG,
TEMPLATE_INSTALL_DISK_MSG,
Expand All @@ -59,6 +63,7 @@ module.exports = {
templateSuccessfullyInstalled,
relativeSourceFileNotGenerated,
conditionalFilesMatched,
fileNotOverwritten
fileNotOverwritten,
skipOverwriting

};
15 changes: 6 additions & 9 deletions lib/renderer/react.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const path = require('path');
const AsyncReactSDK = require('@asyncapi/generator-react-sdk');
const minimatch = require('minimatch');
const log = require('loglevel');
const logMessages = require('../logMessages');
const {
writeFile
} = require('../utils');
Expand Down Expand Up @@ -61,7 +62,7 @@ reactExport.renderReact = async (asyncapiDocument, filePath, extraTemplateData,
* @param {String} outputPath Path to the file being rendered.
* @param {String[]} noOverwriteGlobs globs to check for files that should not be overwritten.
*/
const saveContentToFile = async (renderedContent, outputPath, noOverwriteGlobs = []) => {
const saveContentToFile = async (renderedContent, outputPath, noOverwriteGlobs = [], generator) => {
let filePath = outputPath;
// Might be the same as in the `fs` package, but is an active choice for our default file permission for any rendered files.
let permissions = 0o666;
Expand All @@ -86,12 +87,8 @@ const saveContentToFile = async (renderedContent, outputPath, noOverwriteGlobs =
}
}

// get the final file name of the file
const finalFileName = path.basename(filePath);
// check whether the filename should be ignored based on user's inputs
// const shouldOverwrite = !noOverwriteGlobs.some(globExp => minimatch(finalFileName, globExp));
// reuse methods from the generator.js to check if the file should be overwritten
const shouldOverwrite = await reactExport.shouldOverwriteFile(filePath, noOverwriteGlobs);
const shouldOverwrite = await generator.shouldOverwriteFile(filePath);

// Write the file only if it should not be skipped
if (shouldOverwrite) {
Expand All @@ -100,7 +97,7 @@ const saveContentToFile = async (renderedContent, outputPath, noOverwriteGlobs =
});
} else {
log.debug(`noOverwriteGlobs matched`);
log.debug(`Skipping overwrite for: ${filePath}`);
log.debug(logMessages.skipOverwriting(filePath));
}
};

Expand All @@ -112,11 +109,11 @@ const saveContentToFile = async (renderedContent, outputPath, noOverwriteGlobs =
* @param {String} outputPath Path to the file being rendered.
* @param {String[]} noOverwriteGlobs globs to check for files that should not be overwritten.
*/
reactExport.saveRenderedReactContent = async (renderedContent, outputPath, noOverwriteGlobs = []) => {
reactExport.saveRenderedReactContent = async (renderedContent, outputPath, noOverwriteGlobs = [], generator) => {
// If the rendered content is an array, we need to save each file individually
if (Array.isArray(renderedContent)) {
return Promise.all(renderedContent.map(content => saveContentToFile(content, outputPath, noOverwriteGlobs)));
}
// Otherwise, we can save the single file
return saveContentToFile(renderedContent, outputPath, noOverwriteGlobs);
return saveContentToFile(renderedContent, outputPath, noOverwriteGlobs, generator);
};
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
"test": "npm run test:unit && npm run test:integration && npm run test:cli",
"test:unit": "jest --coverage --testPathIgnorePatterns=integration --testPathIgnorePatterns=test-project",
"test:dev": "npm run test:unit -- --watchAll",
"test:integration": "npm run test:cleanup && jest --testPathPattern=integration --modulePathIgnorePatterns='./__mocks__'",
"test:integration:update": "jest --updateSnapshot --testPathPattern=integration --modulePathIgnorePatterns='./__mocks__'",
"test:integration": "npm run test:cleanup && jest --testPathPattern=integration --modulePathIgnorePatterns='./__mocks__(?!\\/loglevel\\.js$)'",
"test:integration:update": "jest --updateSnapshot --testPathPattern=integration --modulePathIgnorePatterns='./__mocks__(?!\\/loglevel\\.js$)'",
"test:cli": "node cli.js ./test/docs/dummy.yml ./test/test-templates/react-template -o test/output --force-write --debug && test -e test/output/test-file.md",
"test:cleanup": "rimraf \"test/temp\"",
"docs": "jsdoc2md --partial docs/jsdoc2md-handlebars/custom-sig-name.hbs docs/jsdoc2md-handlebars/main.hbs docs/jsdoc2md-handlebars/docs.hbs docs/jsdoc2md-handlebars/header.hbs docs/jsdoc2md-handlebars/defaultvalue.hbs docs/jsdoc2md-handlebars/link.hbs docs/jsdoc2md-handlebars/params-table.hbs --files lib/generator.js > docs/api.md",
Expand Down
19 changes: 7 additions & 12 deletions test/integration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const {exists, writeFile} = require('../lib/utils');
const mainTestResultPath = 'test/temp/integrationTestResult';
const reactTemplate = 'test/test-templates/react-template';
const nunjucksTemplate = 'test/test-templates/nunjucks-template';
const logMessage = require('../lib/logMessages');
const log = require('loglevel');

describe('Integration testing generateFromFile() to make sure the result of the generation is not changend comparing to snapshot', () => {
Expand Down Expand Up @@ -67,12 +68,12 @@ describe('Integration testing generateFromFile() to make sure the result of the
});

it('should ignore specified files with noOverwriteGlobs', async () => {
// const logSpyDebug = jest.spyOn(log, 'debug').mockImplementation(() => {});
log.debug = jest.fn();
const logSpyDebug = jest.spyOn(log, 'debug').mockImplementation(() => {});
// log.debug = jest.fn();

const outputDir = generateFolderName();
// Manually create a file to test if it's not overwritten
if (!await exists(outputDir)) {
if (!existsSync(outputDir)) {
mkdirSync(outputDir, { recursive: true });
}
// Create a variable to store the file content
Expand All @@ -95,15 +96,9 @@ describe('Integration testing generateFromFile() to make sure the result of the
// Check if the files have been overwritten
await expect(fileContent).toBe(testContent);
// Check if the log debug message was printed
await expect(log.debug).toHaveBeenCalledWith(`noOverwriteGlobs matched`);
await expect(log.debug).toHaveBeenCalledWith(`Skipping overwrite for: ${testFilePath}`);
// await console.log('All console.log calls:');
// await expect(logSpyDebug).toHaveBeenCalledWith(`noOverwriteGlobs matched`);
await expect(logSpyDebug).toHaveBeenCalledWith(logMessage.skipOverwriting(testFilePath));

// // Print all console.log calls
// await log.mock.calls.forEach((call, index) => {
// console.log(`${index + 1}:`, call);
// });

log.mockRestore();
logSpyDebug.mockRestore();
});
});

0 comments on commit 3e7afe7

Please sign in to comment.