Skip to content

Commit

Permalink
fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
prxgr4mm3r committed Feb 19, 2024
1 parent dcb119a commit 5e89608
Show file tree
Hide file tree
Showing 6 changed files with 144 additions and 36 deletions.
97 changes: 97 additions & 0 deletions src/commands/contract/generate/tests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { Args, Flags } from "@oclif/core";
import { getTemplates, prepareTestFiles, processTemplates } from "../../../lib/index.js";
import { Contract } from "../../../lib/contract.js";
import { SwankyCommand } from "../../../lib/swankyCommand.js";
import { ConfigError, FileError } from "../../../lib/errors.js";
import path from "node:path";
import { existsSync } from "node:fs";
import inquirer from "inquirer";
import { pascalCase } from "change-case";

export class GenerateTests extends SwankyCommand<typeof GenerateTests> {
static description = "Generate types from compiled contract metadata";

static args = {
contractName: Args.string({
name: "contractName",
required: true,
description: "Name of the contract",
}),
};

static flags = {
mocha: Flags.boolean({
default: false,
description: "Generate tests with mocha",
}),
};

async run(): Promise<void> {
const { args, flags } = await this.parse(GenerateTests);

const contractRecord = this.swankyConfig.contracts[args.contractName];
if (!contractRecord) {
throw new ConfigError(
`Cannot find a contract named ${args.contractName} in swanky.config.json`
);
}

const contract = new Contract(contractRecord);

if (!(await contract.pathExists())) {
throw new FileError(
`Path to contract ${args.contractName} does not exist: ${contract.contractPath}`
);
}

const artifactsCheck = await contract.artifactsExist();

if (!artifactsCheck.result) {
throw new FileError(
`No artifact file found at path: ${artifactsCheck.missingPaths.toString()}`
);
}

const templates = getTemplates();

const testsPath = path.resolve(process.cwd(), "tests");

let owerwrite = true;
if (!flags.mocha)
{
if (existsSync(path.resolve(testsPath, "test_helpers"))) {
owerwrite = (await inquirer.prompt({
type: "confirm",
name: "overwrite",
message: "Test helpers already exist. Overwrite?",
default: false,
})).overwrite;
}
if (owerwrite) {
await this.spinner.runCommand(async () => {
await prepareTestFiles("e2e", templates.templatesPath, process.cwd(), args.contractName);
}, "Generating test helpers");
}
} else {
if (existsSync(path.resolve(testsPath, args.contractName, "index.test.ts"))) {
owerwrite = (await inquirer.prompt({
type: "confirm",
name: "overwrite",
message: `Mocha tests for ${args.contractName} are already exist. Overwrite?`,
default: false,
})).overwrite;
}
if (owerwrite) {
await this.spinner.runCommand(async () => {
await prepareTestFiles("mocha", templates.templatesPath, process.cwd(), args.contractName);
}, `Generating tests for ${args.contractName} with mocha`);
await this.spinner.runCommand(async () => {
await processTemplates(process.cwd(), {
contract_name: args.contractName,
contract_name_pascal: pascalCase(args.contractName),
})
}, 'Processing templates')
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Contract } from "../../../lib/contract.js";
import { SwankyCommand } from "../../../lib/swankyCommand.js";
import { ConfigError, FileError } from "../../../lib/errors.js";

export class ContractTestTypegen extends SwankyCommand<typeof ContractTestTypegen> {
export class GenerateTypes extends SwankyCommand<typeof GenerateTypes> {
static description = "Generate types from compiled contract metadata";

static args = {
Expand All @@ -16,7 +16,7 @@ export class ContractTestTypegen extends SwankyCommand<typeof ContractTestTypege
};

async run(): Promise<void> {
const { args } = await this.parse(ContractTestTypegen);
const { args } = await this.parse(GenerateTypes);

const contractRecord = this.swankyConfig.contracts[args.contractName];
if (!contractRecord) {
Expand Down
1 change: 0 additions & 1 deletion src/commands/contract/new.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ export class NewContract extends SwankyCommand<typeof NewContract> {
);

await ensureDir(path.resolve(projectPath, "artifacts", args.contractName));
await ensureDir(path.resolve(projectPath, "tests", args.contractName));

await this.spinner.runCommand(async () => {
this.swankyConfig.contracts[args.contractName] = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import { Flags, Args } from "@oclif/core";
import path from "node:path";
import { globby } from "globby";
import Mocha from "mocha";
import { emptyDir } from "fs-extra/esm";
import { emptyDir, pathExists } from "fs-extra/esm";
import shell from "shelljs";
import { Contract } from "../../../lib/contract.js";
import { SwankyCommand } from "../../../lib/swankyCommand.js";
import { ConfigError, FileError, InputError, ProcessError, TestError } from "../../../lib/errors.js";
import { Contract } from "../../lib/contract.js";
import { SwankyCommand } from "../../lib/swankyCommand.js";
import { ConfigError, FileError, InputError, ProcessError, TestError } from "../../lib/errors.js";
import { spawn } from "node:child_process";
import { Spinner } from "../../../lib/index.js";
import { Spinner } from "../../lib/index.js";

declare global {
var contractTypesPath: string; // eslint-disable-line no-var
Expand Down Expand Up @@ -53,8 +53,6 @@ export class TestContract extends SwankyCommand<typeof TestContract> {
? Object.keys(this.swankyConfig.contracts)
: [args.contractName];

const testDir = path.resolve("tests");

const spinner = new Spinner();

for (const contractName of contractNames) {
Expand Down Expand Up @@ -130,6 +128,12 @@ export class TestContract extends SwankyCommand<typeof TestContract> {
);
} else {

const testDir = path.resolve("tests");

if (!pathExists(testDir)) {
throw new FileError(`Tests folder does not exist: ${testDir}`);
}

const artifactsCheck = await contract.artifactsExist();

if (!artifactsCheck.result) {
Expand Down
34 changes: 18 additions & 16 deletions src/commands/init/index.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import { Args, Flags } from "@oclif/core";
import path from "node:path";
import { ensureDir, writeJSON, pathExists, copy, outputFile, readJSON, remove } from "fs-extra/esm";
import { stat, readdir, readFile } from "fs/promises";
import { copy, ensureDir, outputFile, pathExists, readJSON, remove, writeJSON } from "fs-extra/esm";
import { readdir, readFile, stat } from "fs/promises";
import { execaCommand, execaCommandSync } from "execa";
import { paramCase, pascalCase, snakeCase } from "change-case";
import inquirer from "inquirer";
import TOML from "@iarna/toml";
import { choice, email, name, pickTemplate } from "../../lib/prompts.js";
import {
ChainAccount,
checkCliDependencies,
copyCommonTemplateFiles,
copyContractTemplateFiles,
downloadNode,
getTemplates,
installDeps,
ChainAccount,
prepareTestFiles,
processTemplates,
swankyNode,
getTemplates, copyTestHelpers,
} from "../../lib/index.js";
import {
DEFAULT_ASTAR_NETWORK_URL,
Expand All @@ -26,7 +27,7 @@ import {
} from "../../lib/consts.js";
import { SwankyCommand } from "../../lib/swankyCommand.js";
import { InputError, UnknownError } from "../../lib/errors.js";
import { GlobEntry, globby } from "globby";
import { globby, GlobEntry } from "globby";
import { merge } from "lodash-es";
import inquirerFuzzyPath from "inquirer-fuzzy-path";
import { SwankyConfig } from "../../types/index.js";
Expand Down Expand Up @@ -91,6 +92,7 @@ export class Init extends SwankyCommand<typeof Init> {
super(argv, config);
(this.constructor as typeof SwankyCommand).ENSURE_SWANKY_CONFIG = false;
}

projectPath = "";

configBuilder: Partial<SwankyConfig> = {
Expand Down Expand Up @@ -188,7 +190,6 @@ export class Init extends SwankyCommand<typeof Init> {

Object.keys(this.configBuilder.contracts!).forEach(async (contractName) => {
await ensureDir(path.resolve(this.projectPath, "artifacts", contractName));
await ensureDir(path.resolve(this.projectPath, "tests", contractName));
});

this.taskQueue.push({
Expand All @@ -214,7 +215,7 @@ export class Init extends SwankyCommand<typeof Init> {
runningMessage,
successMessage,
failMessage,
shouldExitOnError
shouldExitOnError,
);
if (result && callback) {
callback(result as string);
Expand Down Expand Up @@ -271,8 +272,9 @@ export class Init extends SwankyCommand<typeof Init> {

if (contractTemplate === "psp22") {
this.taskQueue.push({
task: copyTestHelpers,
task: prepareTestFiles,
args: [
"e2e",
path.resolve(templates.templatesPath),
this.projectPath,
],
Expand Down Expand Up @@ -317,7 +319,7 @@ export class Init extends SwankyCommand<typeof Init> {
} catch (cause) {
throw new InputError(
`Error reading target directory [${chalk.yellowBright(pathToExistingProject)}]`,
{ cause }
{ cause },
);
}

Expand All @@ -337,7 +339,7 @@ export class Init extends SwankyCommand<typeof Init> {

const candidatesList: CopyCandidates = await getCopyCandidatesList(
pathToExistingProject,
copyGlobsList
copyGlobsList,
);

const testDir = await detectTests(pathToExistingProject);
Expand Down Expand Up @@ -505,10 +507,10 @@ async function confirmCopyList(candidatesList: CopyCandidates) {
(
item: PathEntry & {
group: "contracts" | "crates" | "tests";
}
},
) => {
resultingList[item.group]?.push(item);
}
},
);
return resultingList;
}
Expand All @@ -535,7 +537,7 @@ async function detectTests(pathToExistingProject: string): Promise<string | unde
type: "confirm",
name: "shouldUseDetectedTestDir",
message: `Detected test directory [${path.basename(
testDir!
testDir!,
)}]. Do you want to copy it to your new project?`,
default: true,
},
Expand Down Expand Up @@ -568,7 +570,7 @@ async function readRootCargoToml(pathToProject: string) {
async function getManualPaths(
pathToProject: string,
directoryType: "contracts" | "crates" | "tests",
paths: string[] = []
paths: string[] = [],
): Promise<string[]> {
const { selectedDirectory } = await inquirer.prompt([
{
Expand Down Expand Up @@ -606,7 +608,7 @@ async function getCopyCandidatesList(
pathsToCopy: {
contractsDirectories: string[];
cratesDirectories: string[];
}
},
) {
const detectedPaths = {
contracts: await getDirsAndFiles(projectPath, pathsToCopy.contractsDirectories),
Expand All @@ -627,7 +629,7 @@ async function getGlobPaths(projectPath: string, globList: string[], isDirOnly:
onlyDirectories: isDirOnly,
deep: 1,
objectMode: true,
}
},
);
}

Expand Down
26 changes: 16 additions & 10 deletions src/lib/tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,20 +53,26 @@ export async function copyContractTemplateFiles(
path.resolve(contractTemplatePath, "contract"),
path.resolve(projectPath, "contracts", contractName)
);
await copy(
path.resolve(contractTemplatePath, "test"),
path.resolve(projectPath, "tests", contractName)
);
}

export async function copyTestHelpers(
export async function prepareTestFiles(
testType: "e2e" | "mocha",
templatePath: string,
projectPath: string
projectPath: string,
contractName: string
) {
await copy(
path.resolve(templatePath, "test_helpers"),
path.resolve(projectPath, "tests", "test_helpers")
);
if (testType === "e2e") {
await copy(
path.resolve(templatePath, "test_helpers"),
path.resolve(projectPath, "tests", "test_helpers")
);
}
else {
await copy(
path.resolve(templatePath, "contracts", contractName, "test"),
path.resolve(projectPath, "tests", contractName)
);
}
}

export async function processTemplates(projectPath: string, templateData: Record<string, string>) {
Expand Down

0 comments on commit 5e89608

Please sign in to comment.