|
1 | 1 | import { Command } from "@commander-js/extra-typings"; |
| 2 | +import fs from "node:fs"; |
| 3 | +import fsPromise from "node:fs/promises"; |
| 4 | +import path from "node:path"; |
| 5 | +import { oraPromise } from "ora"; |
| 6 | +import { prettyPath } from "react-native-node-api"; |
2 | 7 |
|
3 | 8 | export const initCommand = new Command("init") |
4 | | - .description("Generate the project scaffold") |
5 | | - .argument("<name>", "Type the project name") |
6 | | - .action(() => { |
| 9 | + .description("Generate the project scaffold") |
| 10 | + .argument("<name>", "Type the project name") |
| 11 | + .action(async (str) => { |
| 12 | + const projectName = str && str.length > 0 ? str : "ferric_project"; |
| 13 | + const generatePath = path.join(process.cwd(), projectName); |
| 14 | + await oraPromise( |
| 15 | + generateProject({ outputPath: generatePath, projectName }), |
| 16 | + { |
| 17 | + text: "Generating project", |
| 18 | + successText: `Generated project ${prettyPath(generatePath)}`, |
| 19 | + failText: (error) => `Failed to generate the project: ${error.message}`, |
| 20 | + }, |
| 21 | + ); |
| 22 | + }); |
7 | 23 |
|
8 | | - }) |
| 24 | +async function replaceStrInFile( |
| 25 | + filePath: string, |
| 26 | + oldStr: string, |
| 27 | + newStr: string, |
| 28 | +) { |
| 29 | + const content = await fsPromise.readFile(filePath, "utf8"); |
| 30 | + const updatedContent = content.replace(`/${oldStr}/gi`, newStr); |
| 31 | + await fsPromise.writeFile(filePath, updatedContent, "utf8"); |
| 32 | +} |
| 33 | + |
| 34 | +function createFolder(path: string) { |
| 35 | + if (!fs.existsSync(path)) { |
| 36 | + fs.mkdirSync(path); |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +async function copyAllTemplateFiles(outputFilePath: string) { |
| 41 | + const templateDir = path.join(import.meta.dirname, "templates"); |
| 42 | + await fsPromise.cp(templateDir, outputFilePath, { |
| 43 | + recursive: true, |
| 44 | + }); |
| 45 | + await fsPromise.rename( |
| 46 | + `${outputFilePath}/lib.rs`, |
| 47 | + `${outputFilePath}/src/lib.rs`, |
| 48 | + ); |
| 49 | + await fsPromise.rename( |
| 50 | + `${outputFilePath}/gitignore`, |
| 51 | + `${outputFilePath}/.gitignore`, |
| 52 | + ); |
| 53 | +} |
| 54 | + |
| 55 | +async function generateProject({ |
| 56 | + outputPath, |
| 57 | + projectName, |
| 58 | +}: { |
| 59 | + outputPath: string; |
| 60 | + projectName: string; |
| 61 | +}) { |
| 62 | + createFolder(outputPath); |
| 63 | + createFolder(`${outputPath}/src`); |
| 64 | + await copyAllTemplateFiles(outputPath); |
| 65 | + await replaceStrInFile( |
| 66 | + `${outputPath}/package.json`, |
| 67 | + "project_name", |
| 68 | + projectName, |
| 69 | + ); |
| 70 | + await replaceStrInFile( |
| 71 | + `${outputPath}/Cargo.toml`, |
| 72 | + "project_name", |
| 73 | + projectName, |
| 74 | + ); |
| 75 | +} |
0 commit comments