Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: refactor remappings and add test import #72

Merged
merged 1 commit into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions src/smock-foundry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
smockableNode,
compileSolidityFilesFoundry,
renderAbstractUnimplementedFunctions,
getRemappings,
getTestImport,
} from './utils';
import path from 'path';
import { ensureDir } from 'fs-extra';
Expand All @@ -31,7 +33,9 @@ export async function generateMockContracts(
console.log('Parsing contracts...');

try {
const sourceUnits = await getSourceUnits(rootPath, contractsDirectories, ignoreDirectories);
const remappings: string[] = await getRemappings(rootPath);
const testImport = getTestImport(remappings);
const sourceUnits = await getSourceUnits(rootPath, contractsDirectories, ignoreDirectories, remappings);

if (!sourceUnits.length) return console.error('No solidity files found in the specified directory');

Expand Down Expand Up @@ -80,6 +84,7 @@ export async function generateMockContracts(
sourceContractRelativePath: sourceContractRelativePath,
exportedSymbols: Array.from(scope.exportedSymbols.keys()),
license: sourceUnit.license,
testImport,
});

await ensureDir(path.dirname(mockContractAbsolutePath));
Expand All @@ -89,12 +94,12 @@ export async function generateMockContracts(

// Generate SmockHelper contract
const smockHelperTemplate = await getSmockHelperTemplate();
const smockHelperCode: string = smockHelperTemplate({});
const smockHelperCode: string = smockHelperTemplate({ testImport });
writeFileSync(`${mocksPath}/SmockHelper.sol`, smockHelperCode);

console.log('Mock contracts generated successfully');

await compileSolidityFilesFoundry(rootPath, mocksDirectory);
await compileSolidityFilesFoundry(rootPath, mocksDirectory, remappings);

// Format the generated files
console.log('Formatting generated files...');
Expand Down
2 changes: 1 addition & 1 deletion src/templates/contract-template.hbs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: {{#if license}}{{license}}{{else}}UNLICENSED{{/if}}
pragma solidity ^0.8.0;

import { Test } from 'forge-std/Test.sol';
import { Test } from '{{testImport}}';
import { {{~exportedSymbols~}} } from '{{sourceContractRelativePath}}';
{{importsContent}}

Expand Down
2 changes: 1 addition & 1 deletion src/templates/helper-template.hbs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {Test} from 'forge-std/Test.sol';
import {Test} from '{{testImport}}';

contract SmockHelper is Test {
function deployMock(
Expand Down
53 changes: 45 additions & 8 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
externalOrPublicFunctionContext,
internalFunctionContext,
} from './context';
import { exec } from 'child_process';

/**
* Fixes user-defined types
Expand Down Expand Up @@ -73,7 +74,7 @@
* @param templatePath The path of the template (if it's nested)
* @returns The compiled template
*/
export function compileTemplate(templateName: string, templatePath?: string[]): HandlebarsTemplateDelegate<any> {

Check warning on line 77 in src/utils.ts

View workflow job for this annotation

GitHub Actions / Run Linters (18.x)

Unexpected any. Specify a different type
const templateContent = readTemplate(templateName, templatePath);
return Handlebars.compile(templateContent, { noEscape: true });
}
Expand All @@ -82,7 +83,7 @@
* Gets the base contract template
* @returns The contract template
*/
export function getContractTemplate(): HandlebarsTemplateDelegate<any> {

Check warning on line 86 in src/utils.ts

View workflow job for this annotation

GitHub Actions / Run Linters (18.x)

Unexpected any. Specify a different type
return compileTemplate('contract-template');
}

Expand All @@ -90,7 +91,7 @@
* Gets the smock helper template
* @returns The helper template
*/
export function getSmockHelperTemplate(): HandlebarsTemplateDelegate<any> {

Check warning on line 94 in src/utils.ts

View workflow job for this annotation

GitHub Actions / Run Linters (18.x)

Unexpected any. Specify a different type
return compileTemplate('helper-template');
}

Expand All @@ -98,13 +99,11 @@
* Compiles the solidity files in the given directory calling forge build command
* @param mockContractsDir The directory of the generated contracts
*/
export async function compileSolidityFilesFoundry(rootPath: string, mockContractsDir: string) {
export async function compileSolidityFilesFoundry(rootPath: string, mockContractsDir: string, remappings: string[]) {
console.log('Compiling contracts...');
try {
const solidityFiles: string[] = await getSolidityFilesAbsolutePaths(rootPath, [mockContractsDir]);

const remappings: string[] = await getRemappings(rootPath);

await compileSol(solidityFiles, 'auto', {
basePath: rootPath,
remapping: remappings,
Expand Down Expand Up @@ -245,7 +244,12 @@
try {
return await exports.getRemappingsFromConfig(path.join(rootPath, 'foundry.toml'));
} catch {
return [];
// If neither file exists, try to generate the remappings using forge
try {
return await exports.getRemappingsFromForge();
} catch {
return [];
}
}
}
}
Expand All @@ -265,17 +269,32 @@
const regex = /remappings[\s|\n]*=[\s\n]*\[(?<remappings>[^\]]+)]/;
const matches = foundryConfigContent.match(regex);
if (matches) {
return matches

Check warning on line 272 in src/utils.ts

View workflow job for this annotation

GitHub Actions / Run Linters (18.x)

Forbidden non-null assertion
.groups!.remappings.split(',')
.map((line) => line.trim())
.map((line) => line.replace(/["']/g, ''))
.filter((line) => line.length)
.map((line) => sanitizeRemapping(line));
} else {
return [];
throw new Error('No remappings found in foundry.toml');
}
}

/**
* Returns the remappings generated by forge
* @returns {Promise<string[]>} - The list of remappings
*/
export async function getRemappingsFromForge(): Promise<string[]> {
const remappingsContent = await new Promise<string>((resolve, reject) =>
exec('forge remappings', { encoding: 'utf8' }, (error, stdout) => (error ? reject(error) : resolve(stdout))),
);
return remappingsContent
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length)
.map((line) => sanitizeRemapping(line));
}

export function sanitizeRemapping(line: string): string {
// Make sure the key and the value both either have or don't have a trailing slash
const [key, value] = line.split('=');
Expand Down Expand Up @@ -304,12 +323,30 @@
}
}

export async function getSourceUnits(rootPath: string, contractsDirectories: string[], ignoreDirectories: string[]): Promise<SourceUnit[]> {
export function getTestImport(remappings: string[]): string {
const module = 'forge-std';

for (const remapping of remappings) {
const [alias, path] = remapping.split('='); // Split remapping into alias and path

if (alias.startsWith(module) && path.includes(module)) {
const srcPath = path.includes('/src/') ? '' : `src/`;
return `${alias}${srcPath}Test.sol`;
}
}

return 'forge-std/src/Test.sol';
}

export async function getSourceUnits(
rootPath: string,
contractsDirectories: string[],
ignoreDirectories: string[],
remappings: string[],
): Promise<SourceUnit[]> {
const files: string[] = await getSolidityFilesAbsolutePaths(rootPath, contractsDirectories);
const solidityFiles = files.filter((file) => !ignoreDirectories.some((directory) => file.includes(directory)));

const remappings: string[] = await getRemappings(rootPath);

const compiledFiles = await compileSol(solidityFiles, 'auto', {
basePath: rootPath,
remapping: remappings,
Expand Down
Loading