Skip to content

Commit

Permalink
Fix Prettier inconsistencies between generated scripts and JS client (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
lorisleiva authored Jul 20, 2024
1 parent fd72e33 commit 5780c84
Show file tree
Hide file tree
Showing 19 changed files with 165 additions and 151 deletions.
5 changes: 5 additions & 0 deletions .changeset/brown-dragons-kiss.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"create-solana-program": patch
---

Fix Prettier inconsistencies between generated scripts and JS client
22 changes: 11 additions & 11 deletions scripts/build.mjs
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
#!/usr/bin/env zx
import * as esbuild from "esbuild";
import * as esbuild from 'esbuild';

await esbuild.build({
bundle: true,
entryPoints: ["index.ts"],
external: ["locales/*"],
outfile: "outfile.cjs",
format: "cjs",
platform: "node",
target: "node14",
entryPoints: ['index.ts'],
external: ['locales/*'],
outfile: 'outfile.cjs',
format: 'cjs',
platform: 'node',
target: 'node14',

plugins: [
{
name: "alias",
name: 'alias',
setup({ onResolve, resolve }) {
onResolve(
{ filter: /^prompts$/, namespace: "file" },
{ filter: /^prompts$/, namespace: 'file' },
async ({ importer, resolveDir }) => {
// we can always use non-transpiled code since we support 14.16.0+
const result = await resolve("prompts/lib/index.js", {
const result = await resolve('prompts/lib/index.js', {
importer,
resolveDir,
kind: "import-statement",
kind: 'import-statement',
});
return result;
}
Expand Down
12 changes: 6 additions & 6 deletions scripts/prepublish.mjs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
#!/usr/bin/env zx
import "zx/globals";
import { PROJECTS } from "./utils.mjs";
import 'zx/globals';
import { PROJECTS } from './utils.mjs';

await $`pnpm snapshot`;

const { version } = await fs.readJSON("./package.json");
const { version } = await fs.readJSON('./package.json');
const projects = Object.keys(PROJECTS);

const rootDirectory = path.resolve(__dirname, "..");
const projectsDirectory = path.resolve(rootDirectory, "projects");
const rootDirectory = path.resolve(__dirname, '..');
const projectsDirectory = path.resolve(rootDirectory, 'projects');

for (const projectName of projects) {
const projectDirectory = path.resolve(projectsDirectory, projectName);
Expand All @@ -19,7 +19,7 @@ for (const projectName of projects) {
try {
await $`git commit -m "version ${version} snapshot"`;
} catch (e) {
if (!e.stdout.includes("nothing to commit")) {
if (!e.stdout.includes('nothing to commit')) {
throw e;
}
}
Expand Down
38 changes: 19 additions & 19 deletions scripts/snapshot.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env zx
import "zx/globals";
import { CLIENTS, PROJECTS, executeStep } from "./utils.mjs";
import 'zx/globals';
import { CLIENTS, PROJECTS, executeStep } from './utils.mjs';

$.verbose = false;

Expand All @@ -13,11 +13,11 @@ const projects =
)
: Object.keys(PROJECTS);
const runTests = !!argv.test;
const scaffoldOnly = !!argv["scaffold-only"];
const scaffoldOnly = !!argv['scaffold-only'];

// Resolve paths.
const bin = path.resolve(__dirname, "../outfile.cjs");
const projectsDirectory = path.resolve(__dirname, "../projects/");
const bin = path.resolve(__dirname, '../outfile.cjs');
const projectsDirectory = path.resolve(__dirname, '../projects/');

if (!fs.existsSync(projectsDirectory)) {
fs.mkdirSync(projectsDirectory);
Expand All @@ -33,48 +33,48 @@ for (const projectName of projects) {
// Scaffold the project.
const args = [projectName, ...PROJECTS[projectName]];
await executeStep(
"scaffold the project",
() => $`node ${[bin, ...args, "--force", "--default"]}`
'scaffold the project',
() => $`node ${[bin, ...args, '--force', '--default']}`
);

if (scaffoldOnly) continue;

// Go inside the created project.
const projectDirectory = path.resolve(projectsDirectory, projectName);
cd(projectDirectory);
const pkg = await fs.readJSON(path.resolve(projectDirectory, "package.json"));
const pkg = await fs.readJSON(path.resolve(projectDirectory, 'package.json'));

// Install project's dependencies.
await executeStep("install NPM dependencies", async () => {
await executeStep('install NPM dependencies', async () => {
await $`pnpm install`;
});

// Generate IDLs.
if ("generate:idls" in pkg.scripts) {
await executeStep("generate IDLs", async () => {
if ('generate:idls' in pkg.scripts) {
await executeStep('generate IDLs', async () => {
await $`pnpm generate:idls`;
});
}

// Generate clients.
if ("generate:clients" in pkg.scripts) {
await executeStep("generate clients", async () => {
if ('generate:clients' in pkg.scripts) {
await executeStep('generate clients', async () => {
await $`pnpm generate:clients`;
});
}

// Build programs.
if ("programs:build" in pkg.scripts) {
await executeStep("build programs", async () => {
if ('programs:build' in pkg.scripts) {
await executeStep('build programs', async () => {
await $`pnpm programs:build`;
});
}

if (!runTests) continue;

// Test programs.
if ("programs:test" in pkg.scripts) {
await executeStep("test programs", async () => {
if ('programs:test' in pkg.scripts) {
await executeStep('test programs', async () => {
await $`pnpm programs:test`;
});
}
Expand All @@ -92,7 +92,7 @@ for (const projectName of projects) {
}

// Add line break between projects.
echo("");
echo('');
}

echo(chalk.green("All projects were created successfully!"));
echo(chalk.green('All projects were created successfully!'));
14 changes: 7 additions & 7 deletions scripts/utils.mjs
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
export const COUNTER_ADDRESS = "CounterProgram111111111111111111111111111111";
export const CLIENTS = ["js", "rust"];
export const COUNTER_ADDRESS = 'CounterProgram111111111111111111111111111111';
export const CLIENTS = ['js', 'rust'];
export const PROJECTS = {
"counter-anchor": ["counter", "--anchor", "--address", COUNTER_ADDRESS],
"counter-shank": ["counter", "--shank", "--address", COUNTER_ADDRESS],
'counter-anchor': ['counter', '--anchor', '--address', COUNTER_ADDRESS],
'counter-shank': ['counter', '--shank', '--address', COUNTER_ADDRESS],
};

export async function executeStep(title, fn) {
try {
const capitalizedTitle = title.charAt(0).toUpperCase() + title.slice(1);
if (process.env.CI) {
echo(chalk.blue("⠋") + ` ${capitalizedTitle}...`);
echo(chalk.blue('⠋') + ` ${capitalizedTitle}...`);
await fn();
} else {
await spinner(`${capitalizedTitle}...`, fn);
}
echo(chalk.green("✔︎") + ` ${capitalizedTitle}.`);
echo(chalk.green('✔︎') + ` ${capitalizedTitle}.`);
} catch (e) {
echo(chalk.red("✘") + ` Failed to ${title}.\n`);
echo(chalk.red('✘') + ` Failed to ${title}.\n`);
echo(e);
process.exit(1);
}
Expand Down
9 changes: 9 additions & 0 deletions template/base/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"semi": true,
"singleQuote": true,
"trailingComma": "es5",
"useTabs": false,
"tabWidth": 2,
"arrowParens": "always",
"printWidth": 80
}
20 changes: 10 additions & 10 deletions template/base/scripts/generate-idls.mjs
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
#!/usr/bin/env zx
import "zx/globals";
import { generateIdl } from "@metaplex-foundation/shank-js";
import { getCargo, getProgramFolders } from "./utils.mjs";
import 'zx/globals';
import { generateIdl } from '@metaplex-foundation/shank-js';
import { getCargo, getProgramFolders } from './utils.mjs';

const binaryInstallDir = path.join(__dirname, "..", ".cargo");
const binaryInstallDir = path.join(__dirname, '..', '.cargo');

getProgramFolders().forEach((folder) => {
const cargo = getCargo(folder);
const isShank = Object.keys(cargo.dependencies).includes("shank");
const programDir = path.join(__dirname, "..", folder);
const isShank = Object.keys(cargo.dependencies).includes('shank');
const programDir = path.join(__dirname, '..', folder);

generateIdl({
generator: isShank ? "shank" : "anchor",
programName: cargo.package.name.replace(/-/g, "_"),
programId: cargo.package.metadata.solana["program-id"],
generator: isShank ? 'shank' : 'anchor',
programName: cargo.package.name.replace(/-/g, '_'),
programId: cargo.package.metadata.solana['program-id'],
idlDir: programDir,
idlName: "idl",
idlName: 'idl',
programDir,
binaryInstallDir,
});
Expand Down
6 changes: 3 additions & 3 deletions template/base/scripts/program/build.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#!/usr/bin/env zx
import "zx/globals";
import { workingDirectory, getProgramFolders } from "../utils.mjs";
import 'zx/globals';
import { workingDirectory, getProgramFolders } from '../utils.mjs';

// Save external programs binaries to the output directory.
import "./dump.mjs";
import './dump.mjs';

// Build the programs.
for (const folder of getProgramFolders()) {
Expand Down
4 changes: 2 additions & 2 deletions template/base/scripts/program/clean.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env zx
import "zx/globals";
import { getExternalProgramOutputDir } from "../utils.mjs";
import 'zx/globals';
import { getExternalProgramOutputDir } from '../utils.mjs';

// Remove the programs output directories.
const externalProgramOutput = getExternalProgramOutputDir();
Expand Down
36 changes: 18 additions & 18 deletions template/base/scripts/program/dump.mjs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
#!/usr/bin/env zx
import "zx/globals";
import 'zx/globals';
import {
getExternalAccountAddresses,
getExternalProgramAddresses,
getExternalProgramOutputDir,
} from "../utils.mjs";
} from '../utils.mjs';

// Get input from environment variables.
const rpc = process.env.RPC ?? "https://api.mainnet-beta.solana.com";
const rpc = process.env.RPC ?? 'https://api.mainnet-beta.solana.com';
const outputDir = getExternalProgramOutputDir();
await dump();

Expand All @@ -17,8 +17,8 @@ async function dump() {
const programs = getExternalProgramAddresses();
const accounts = getExternalAccountAddresses();
const external = [
...programs.map((program) => [program, "so"]),
...accounts.map((account) => [account, "json"]),
...programs.map((program) => [program, 'so']),
...accounts.map((account) => [account, 'json']),
];

if (external.length === 0) return;
Expand All @@ -39,50 +39,50 @@ async function dump() {
return;
}

let sha = "sha256sum";
let sha = 'sha256sum';
let options = [];
let hasShaChecksum = await which("sha256sum", { nothrow: true });
let hasShaChecksum = await which('sha256sum', { nothrow: true });

// We might not have sha256sum on some systems, so we try shasum as well.
if (!hasShaChecksum) {
hasShaChecksum = await which("shasum", { nothrow: true });
hasShaChecksum = await which('shasum', { nothrow: true });

if (hasShaChecksum) {
sha = "shasum";
options = ["-a", "256"];
sha = 'shasum';
options = ['-a', '256'];
}
}

if (hasShaChecksum) {
try {
await copyFromChain(address, extension, "onchain-");
await copyFromChain(address, extension, 'onchain-');
const [onChainHash, localHash] = await Promise.all([
$`${sha} ${options} -b ${outputDir}/onchain-${binary} | cut -d ' ' -f 1`.quiet(),
$`${sha} ${options} -b ${outputDir}/${binary} | cut -d ' ' -f 1`.quiet(),
]);

if (onChainHash.toString() !== localHash.toString()) {
echo(
chalk.yellow("[ WARNING ]"),
chalk.yellow('[ WARNING ]'),
`on-chain and local binaries are different for '${address}'`
);
} else {
echo(
chalk.green("[ SKIPPED ]"),
chalk.green('[ SKIPPED ]'),
`on-chain and local binaries are the same for '${address}'`
);
}

await $`rm ${outputDir}/onchain-${binary}`.quiet();
} catch (error) {
echo(
chalk.yellow("[ WARNING ]"),
chalk.yellow('[ WARNING ]'),
`skipped check for '${address}' (error copying data from '${rpc}')`
);
}
} else {
echo(
chalk.yellow("[ WARNING ]"),
chalk.yellow('[ WARNING ]'),
`skipped check for '${address}' (missing 'sha256sum' command)`
);
}
Expand All @@ -91,12 +91,12 @@ async function dump() {
}

/** Helper function to copy external programs or accounts binaries from the chain. */
async function copyFromChain(address, extension, prefix = "") {
async function copyFromChain(address, extension, prefix = '') {
const binary = `${prefix}${address}.${extension}`;
switch (extension) {
case "json":
case 'json':
return $`solana account -u ${rpc} ${address} -o ${outputDir}/${binary} --output json >/dev/null`.quiet();
case "so":
case 'so':
return $`solana program dump -u ${rpc} ${address} ${outputDir}/${binary} >/dev/null`.quiet();
default:
echo(chalk.red(`[ ERROR ] unknown account type for '${binary}'`));
Expand Down
4 changes: 2 additions & 2 deletions template/base/scripts/program/format.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env zx
import "zx/globals";
import { workingDirectory, getProgramFolders } from "../utils.mjs";
import 'zx/globals';
import { workingDirectory, getProgramFolders } from '../utils.mjs';

// Format the programs.
for (const folder of getProgramFolders()) {
Expand Down
4 changes: 2 additions & 2 deletions template/base/scripts/program/lint.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env zx
import "zx/globals";
import { workingDirectory, getProgramFolders } from "../utils.mjs";
import 'zx/globals';
import { workingDirectory, getProgramFolders } from '../utils.mjs';

// Lint the programs using clippy.
for (const folder of getProgramFolders()) {
Expand Down
Loading

0 comments on commit 5780c84

Please sign in to comment.