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

Update swanky check #195

Closed
wants to merge 16 commits into from
Closed
Show file tree
Hide file tree
Changes from 5 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
138 changes: 130 additions & 8 deletions src/commands/check/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
import { Listr } from "listr2";
import { commandStdoutOrNull } from "../../lib/index.js";
import { SwankyConfig } from "../../types/index.js";
import { pathExistsSync, readJSON } from "fs-extra/esm";
import { pathExistsSync, readJSON, writeJson } from "fs-extra/esm";
import { readFileSync } from "fs";
import path from "node:path";
import TOML from "@iarna/toml";
import semver from "semver";
import { SwankyCommand } from "../../lib/swankyCommand.js";
import { Flags } from "@oclif/core";
import chalk from "chalk";
import { cargoContractDeps } from "../../lib/cargoContractInfo.js";

interface Ctx {
os: {
platform: string;
architecture: string;
},
versions: {
tools: {
rust?: string | null;
Expand All @@ -17,7 +24,10 @@ interface Ctx {
cargoDylint?: string | null;
cargoContract?: string | null;
};
supportedInk?: string;
missingTools: string[];
contracts: Record<string, Record<string, string>>;
node?: string | null;
ipapandinas marked this conversation as resolved.
Show resolved Hide resolved
};
swankyConfig?: SwankyConfig;
mismatchedVersions?: Record<string, string>;
Expand All @@ -27,37 +37,99 @@ interface Ctx {
export default class Check extends SwankyCommand<typeof Check> {
static description = "Check installed package versions and compatibility";

static flags = {
file: Flags.string({
char: "f",
description: "File to write output to",
}),
};

public async run(): Promise<void> {
const { flags } = await this.parse(Check);
const tasks = new Listr<Ctx>([
{
title: "Check OS",
task: async (ctx) => {
ctx.os.platform = process.platform;
ctx.os.architecture = process.arch;
const supportedPlatforms = ["darwin", "linux"];
const supportedArch = ["arm64", "x64"];

if (!supportedPlatforms.includes(ctx.os.platform)) {
throw new Error(`Platform ${ctx.os.platform} is not supported!`);
}
if (!supportedArch.includes(ctx.os.architecture)) {
throw new Error(`Architecture ${ctx.os.architecture} is not supported!`);
}
},
exitOnError: false,
},
{
title: "Check Rust",
task: async (ctx) => {
ctx.versions.tools.rust = await commandStdoutOrNull("rustc --version");
if (!ctx.versions.tools.rust) {
throw new Error("Rust is not installed!");
}
},
exitOnError: false,
},
{
title: "Check cargo",
task: async (ctx) => {
ctx.versions.tools.cargo = await commandStdoutOrNull("cargo -V");
if (!ctx.versions.tools.cargo) {
throw new Error("Cargo is not installed!");
}
},
exitOnError: false,
},
{
title: "Check cargo nightly",
task: async (ctx) => {
ctx.versions.tools.cargoNightly = await commandStdoutOrNull("cargo +nightly -V");
if (!ctx.versions.tools.cargoNightly) {
throw new Error("Cargo nightly is not installed!");
}
},
exitOnError: false,
},
{
title: "Check cargo dylint",
ipapandinas marked this conversation as resolved.
Show resolved Hide resolved
task: async (ctx) => {
ctx.versions.tools.cargoDylint = await commandStdoutOrNull("cargo dylint -V");
if (!ctx.versions.tools.cargoDylint) {
throw new Error("Cargo dylint is not installed!");
}
},
exitOnError: false,
},
{
title: "Check cargo-contract",
task: async (ctx) => {
ctx.versions.tools.cargoContract = await commandStdoutOrNull("cargo contract -V");
if (!ctx.versions.tools.cargoContract) {
throw new Error("Cargo contract is not installed!");
}
const regex = /cargo-contract-contract (.*)-unknown-(.*)/;
const match = ctx.versions.tools.cargoContract.match(regex);
if (match) {
ctx.versions.tools.cargoContract = match[1];
} else {
throw new Error("Cargo contract version not found!");
}
},
exitOnError: false,
},
{
title: "Check swanky node",
task: async (ctx) => {
ctx.versions.node = this.swankyConfig.node.version !== "" ? this.swankyConfig.node.version : null;
if (!ctx.versions.node) {
throw new Error("Swanky node version not found in swanky.config.json");
}
},
exitOnError: false,
},
{
title: "Read ink dependencies",
Expand All @@ -79,7 +151,7 @@ export default class Check extends SwankyCommand<typeof Check> {
const cargoToml = TOML.parse(cargoTomlString);

const inkDependencies = Object.entries(cargoToml.dependencies)
.filter((dependency) => dependency[0].includes("ink_"))
.filter((dependency) => dependency[0].includes("ink"))
.map(([depName, depInfo]) => {
const dependency = depInfo as Dependency;
return [depName, dependency.version ?? dependency.tag];
Expand All @@ -90,16 +162,34 @@ export default class Check extends SwankyCommand<typeof Check> {
},
{
title: "Verify ink version",
ipapandinas marked this conversation as resolved.
Show resolved Hide resolved
skip: (ctx): boolean => {
return !ctx.versions.tools.cargoContract;
},
task: async (ctx) => {
const supportedInk = ctx.swankyConfig?.node.supportedInk;
let supportedInk = ctx.swankyConfig?.node.supportedInk;
const versions = cargoContractDeps.get(ctx.versions.tools.cargoContract!);
if (versions && semver.gt(versions[versions.length - 1], supportedInk!)) {
supportedInk = versions[0];
}

ctx.versions.supportedInk = supportedInk;
if (!supportedInk) {
throw new Error("Supported ink version not found in swanky.config.json");
}
},
exitOnError: false,
},
{
title: "Verify ink dependencies",
skip: (ctx) => !ctx.versions.supportedInk,
task: async (ctx) => {
const mismatched: Record<string, string> = {};
ipapandinas marked this conversation as resolved.
Show resolved Hide resolved
Object.entries(ctx.versions.contracts).forEach(([contract, inkPackages]) => {
Object.entries(inkPackages).forEach(([inkPackage, version]) => {
if (semver.gt(version, supportedInk!)) {
if (semver.gt(version, ctx.versions.supportedInk!)) {
mismatched[
`${contract}-${inkPackage}`
] = `Version of ${inkPackage} (${version}) in ${contract} is higher than supported ink version (${supportedInk})`;
] = `Version of ${inkPackage} (${version}) in ${contract} is higher than supported ink version (${ctx.versions.supportedInk})`;
}

if (!(version.startsWith("=") || version.startsWith("v"))) {
Expand All @@ -109,23 +199,55 @@ export default class Check extends SwankyCommand<typeof Check> {
});

ctx.mismatchedVersions = mismatched;
if (Object.entries(mismatched).length > 0) {
throw new Error("Ink version mismatch");
}
},
exitOnError: false,
},
{
title: "Check for missing tools",
ipapandinas marked this conversation as resolved.
Show resolved Hide resolved
task: async (ctx) => {
const missingTools: string[] = [];
for (const [toolName, toolVersion] of Object.entries(ctx.versions.tools)) {
if (!toolVersion) {
missingTools.push(toolName);
}
}
ctx.versions.missingTools = missingTools;
if (Object.entries(missingTools).length > 0) {
throw new Error("Missing tools");
}
},
exitOnError: false,
},
]);

const context = await tasks.run({
versions: { tools: {}, contracts: {} },
os: { platform: "", architecture: "" },
versions: { tools: {}, missingTools: [], contracts: {} },
looseDefinitionDetected: false,
});
console.log(context.versions);

Object.values(context.mismatchedVersions as any).forEach((mismatch) =>
ipapandinas marked this conversation as resolved.
Show resolved Hide resolved
console.error(`[ERROR] ${mismatch as string}`)
console.error(`[ERROR] ${mismatch as string}`),
);
if (context.looseDefinitionDetected) {
console.log(`\n[WARNING]Some of the ink dependencies do not have a fixed version.
This can lead to accidentally installing version higher than supported by the node.
Please use "=" to install a fixed version (Example: "=3.0.1")
`);
}

console.log(context.os);
console.log(context.versions);

const filePath = flags.file ?? null;
if (filePath) {
await this.spinner.runCommand(async () => {
writeJson(filePath, [context.os, context.versions], { spaces: 2 });
}, `Writing output to file ${chalk.yellowBright(filePath)}`);
}
}
}

Expand Down
32 changes: 25 additions & 7 deletions src/commands/init/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ 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 { choice, email, name, pickNodeVersion, pickTemplate } from "../../lib/prompts.js";
import {
checkCliDependencies,
copyCommonTemplateFiles,
Expand All @@ -20,7 +20,7 @@ import {
} from "../../lib/index.js";
import {
DEFAULT_ASTAR_NETWORK_URL,
DEFAULT_NETWORK_URL,
DEFAULT_NETWORK_URL, DEFAULT_NODE_INFO,
DEFAULT_SHIBUYA_NETWORK_URL,
DEFAULT_SHIDEN_NETWORK_URL,
} from "../../lib/consts.js";
Expand Down Expand Up @@ -93,11 +93,13 @@ export class Init extends SwankyCommand<typeof Init> {
}
projectPath = "";


configBuilder: Partial<SwankyConfig> = {
node: {
localPath: "",
polkadotPalletVersions: swankyNode.polkadotPalletVersions,
supportedInk: swankyNode.supportedInk,
polkadotPalletVersions: "",
supportedInk: "",
version: "",
},
accounts: [],
networks: {
Expand Down Expand Up @@ -161,12 +163,28 @@ export class Init extends SwankyCommand<typeof Init> {
choice("useSwankyNode", "Do you want to download Swanky node?"),
]);
if (useSwankyNode) {
const versions = Array.from(swankyNode.keys());
let nodeVersion = DEFAULT_NODE_INFO.version;
await inquirer.prompt([
pickNodeVersion(versions),
]).then((answers) => {
nodeVersion = answers.version;
});

const nodeInfo = swankyNode.get(nodeVersion)!;

this.taskQueue.push({
task: downloadNode,
args: [this.projectPath, swankyNode, this.spinner],
args: [this.projectPath, nodeInfo, this.spinner],
runningMessage: "Downloading Swanky node",
callback: (result) =>
this.configBuilder.node ? (this.configBuilder.node.localPath = result) : null,
callback: (result) => {
this.configBuilder.node = {
supportedInk: nodeInfo.supportedInk,
polkadotPalletVersions: nodeInfo.polkadotPalletVersions,
version: nodeInfo.version,
localPath: result,
};
}
});
}
}
Expand Down
33 changes: 29 additions & 4 deletions src/commands/node/install.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,38 @@
import { SwankyCommand } from "../../lib/swankyCommand.js";
import { ux } from "@oclif/core";
import { ux, Flags } from "@oclif/core";
import { downloadNode, swankyNode } from "../../lib/index.js";
import path from "node:path";
import { writeJSON } from "fs-extra/esm";
import inquirer from "inquirer";
import { DEFAULT_NODE_INFO } from "../../lib/consts.js";
import { pickNodeVersion } from "../../lib/prompts.js";

export class InstallNode extends SwankyCommand<typeof InstallNode> {
static description = "Install swanky node binary";

static flags = {
"set-version": Flags.string({
description: "Specify version of swanky node to install",
required: false,
}),
}
async run(): Promise<void> {
const { flags } = await this.parse(InstallNode);
if (flags.verbose) {
this.spinner.verbose = true;
}
let nodeVersion= DEFAULT_NODE_INFO.version;

if (flags.specifyVersion) {
nodeVersion = flags.specifyVersion;
} else {
const versions = Array.from(swankyNode.keys());
await inquirer.prompt([
pickNodeVersion(versions),
]).then((answers) => {
nodeVersion = answers.version;
});
}

const projectPath = path.resolve();

Expand All @@ -24,16 +45,20 @@ export class InstallNode extends SwankyCommand<typeof InstallNode> {
}
}

const nodeInfo = swankyNode.get(nodeVersion)!;

const taskResult = (await this.spinner.runCommand(
() => downloadNode(projectPath, swankyNode, this.spinner),
() => downloadNode(projectPath, nodeInfo, this.spinner),
"Downloading Swanky node"
)) as string;
const nodePath = path.relative(projectPath, taskResult);


this.swankyConfig.node = {
localPath: nodePath,
polkadotPalletVersions: swankyNode.polkadotPalletVersions,
supportedInk: swankyNode.supportedInk,
polkadotPalletVersions: nodeInfo.polkadotPalletVersions,
supportedInk: nodeInfo.supportedInk,
version: nodeInfo.version,
};

await this.spinner.runCommand(
Expand Down
6 changes: 5 additions & 1 deletion src/commands/node/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,15 @@ export class StartNode extends SwankyCommand<typeof StartNode> {
async run(): Promise<void> {
const { flags } = await this.parse(StartNode);

if (this.swankyConfig.node.version === "") {
this.log("Node is not installed");
return;
}
// Run persistent mode by default. non-persistent mode in case flag is provided.
// Non-Persistent mode (`--dev`) allows all CORS origin, without `--dev`, users need to specify origins by `--rpc-cors`.
await execaCommand(
`${this.swankyConfig.node.localPath} \
--finalize-delay-sec ${flags.finalizeDelaySec} \
${this.swankyConfig.node.version === "1.6.0" ? `--finalize-delay-sec ${flags.finalizeDelaySec}` : ""} \
${flags.tmp ? "--dev" : `--rpc-cors ${flags.rpcCors}`}`,
{
stdio: "inherit",
Expand Down
12 changes: 12 additions & 0 deletions src/commands/node/version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { SwankyCommand } from "../../lib/swankyCommand.js";
export class NodeVersion extends SwankyCommand<typeof NodeVersion> {
static description = "Show swanky node version";
async run(): Promise<void> {
if(this.swankyConfig.node.version === ""){
this.log("Node is not installed");
}
else {
this.log(`Node version: ${this.swankyConfig.node.version}`);
}
}
}
Loading
Loading