Skip to content

Commit

Permalink
template working as expected
Browse files Browse the repository at this point in the history
  • Loading branch information
gconnect committed Jul 15, 2024
1 parent 8c5c94a commit 95510d9
Show file tree
Hide file tree
Showing 15 changed files with 149 additions and 140 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Voucher, Batch } from "../model";
import { DAPP_ADDRESS } from "@/app/utils/constants";
import { errorAlert, successAlert } from "@/app/utils/customAlert";
// import { Chain } from "@rainbow-me/rainbowkit";
import configFile from "../../cartesi/config.json"
import configFile from "../config.json"
import { toHex } from "viem";
import { Chain } from "viem";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
import { Text } from "@chakra-ui/react";
import { useEthersSigner } from "../../utils/useEtherSigner";
import { useAccount } from "wagmi";
import VoucherView from "../../components/examples/VoucherView";
import VoucherView from "./VoucherView";
import { DAPP_ADDRESS } from "../../utils/constants";
import { Epoch } from "./Epoch";
import { depositBatchERC1155, depositERC20, depositERC721, depositEther, depositSingleERC1155 } from "../../cartesi/services/Portal";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Voucher, Batch } from "../model";
import { DAPP_ADDRESS } from "../../utils/constants";
import { errorAlert, successAlert } from "../../utils/customAlert";
// import { Chain } from "@rainbow-me/rainbowkit";
import configFile from "../../cartesi/config.json"
import configFile from "../config.json"
import { toHex } from "viem";
import { Chain } from "viem";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
import { Text } from "@chakra-ui/react";
import { useEthersSigner } from "../../utils/useEtherSigner";
import { useAccount } from "wagmi";
import VoucherView from "../../components/examples/VoucherView";
import VoucherView from "./VoucherView";
import { DAPP_ADDRESS } from "../../utils/constants";
import { Epoch } from "./Epoch";
import { depositBatchERC1155, depositERC20, depositERC721, depositEther, depositSingleERC1155 } from "../../cartesi/services/Portal";
Expand Down
44 changes: 18 additions & 26 deletions bin/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@ const fs = require("fs-extra");
const path = require('path');
const { ensureDirectory } = require('../utils/directoryUtils');
const { promptTemplateSelection, promptInclude } = require('../helper/promptUtils');
const { copyTemplateFiles } = require('../helper/copy-template-files');
const { copyTemplateFiles, printSuccessMessage } = require('../helper/copy-template-files');
const { figletText } = require( "../utils/ascii-image");
const { copyGitTemplateFiles } = require("../helper/fetch-git-repo")
const { installDependencies } = require("../helper/install-dependencies");
const { generateMonorepo } = require("../helper/generate-monorepo");
const { generateReadme } = require("../helper/generate-readme")


async function createProject(projectName) {

const { default: chalk } = await import('chalk');

const inquirer = await import('inquirer');

const templates = {
Expand All @@ -26,9 +28,9 @@ async function createProject(projectName) {
mobileApp: ['react_native_app', 'react_native_with_expo', 'flutter_app']
};

console.log(await figletText)
console.log(chalk.cyan(await figletText))

const projectDir = path.resolve(process.cwd(), `${projectName}/packages`);
const projectDir = path.resolve(process.cwd(), `${projectName}`);

await ensureDirectory(projectDir);

Expand All @@ -50,7 +52,6 @@ async function createProject(projectName) {
if (include.includeBackend) {
selectedBackend = await promptTemplateSelection( 'backend', templates.backend);
}
await generateMonorepo(projectDir)
break;
case 'backend':
selectedBackend = await promptTemplateSelection('backend', templates.backend);
Expand All @@ -63,62 +64,53 @@ async function createProject(projectName) {
if(includeConsole.includeConsole){
selectedConsole = await promptTemplateSelection('frontendConsole', templates.frontendConsole )
}
await generateMonorepo(projectDir)
break;
case 'mobileApp':
selectedMobile = await promptTemplateSelection('mobileApp', templates.mobileApp);
const includeBackend = await promptInclude('Do you want to include a backend template?', "includeBackend")
if (includeBackend.includeBackend) {
selectedBackend = await promptTemplateSelection( 'backend', templates.backend);
}
await generateMonorepo(projectDir)
break;
case 'cartesify':
selectedCartesifyBackend = await promptTemplateSelection('cartesify', templates.cartesify.backend)
selectedCartesifyFrontend = await promptTemplateSelection('cartesify', templates.cartesify.frontend)
await generateMonorepo(projectDir)
break
case 'frontendConsole':
selectedConsole = await promptTemplateSelection('frontendConsole', templates.frontendConsole)
await generateMonorepo(projectDir)
break
}

const frontendProjectDir = `${projectDir}/frontend`;
const backendProjectDir = `${projectDir}/backend`;
const mobileProjectDir = `${projectDir}/mobile-app`


const templateArray = [`${projectDir}/frontend`,`${projectDir}/backend`, `${projectDir}/mobile-app` ]

// Copy template files
if (selectedFrontend) {
console.log(selectedFrontend)
await copyTemplateFiles(selectedFrontend, frontendProjectDir, "apps/frontend");
// await installDependencies(selectedFrontend, frontendProjectDir, "apps/frontend");

await copyTemplateFiles(selectedFrontend, frontendProjectDir, "apps/frontend", projectName);
}
if (selectedBackend) {
await copyTemplateFiles(selectedBackend, backendProjectDir, "apps/backend");
// await installDependencies(selectedBackend, backendProjectDir, "apps/backend");

await copyTemplateFiles(selectedBackend, backendProjectDir, "apps/backend", projectName);
}
if(selectedCartesifyBackend){
await copyTemplateFiles(selectedCartesifyBackend, backendProjectDir, "apps/cartesify/backend");
// await installDependencies(selectedCartesifyBackend, backendProjectDir, "apps/cartesify/backend");

await copyTemplateFiles(selectedCartesifyBackend, backendProjectDir, "apps/cartesify/backend",projectName);
}
if(selectedCartesifyFrontend){
await copyTemplateFiles(selectedCartesifyFrontend, frontendProjectDir, "apps/cartesify/frontend");
// await installDependencies(selectedCartesifyFrontend, frontendProjectDir, "apps/cartesify/frontend");

await copyTemplateFiles(selectedCartesifyFrontend, frontendProjectDir, "apps/cartesify/frontend", projectName);
}
if(selectedMobile){
await copyTemplateFiles(selectedMobile, mobileProjectDir, "apps/mobileApp");
// await installDependencies(selectedMobile, mobileProjectDir, "apps/mobileApp");

await copyTemplateFiles(selectedMobile, mobileProjectDir, "apps/mobileApp", projectName);
}
if(selectedConsole){
const giturl = "https://github.com/Mugen-Builders/sunodo-frontend-console.git"
await copyGitTemplateFiles(selectedConsole, projectDir, giturl)
}
console.log("Generating template...")
await generateReadme(projectDir, projectName)
await printSuccessMessage()
}

module.exports = {
Expand Down
92 changes: 68 additions & 24 deletions helper/copy-template-files.js
Original file line number Diff line number Diff line change
@@ -1,44 +1,88 @@
const { ensureDir, copy } = require("fs-extra");
const path = require('path');
const { exludeFiles } = require("../utils/exlude-files");
const { spawn } = require('child_process');
const fs = require('fs-extra');
const { updatePackageJson } = require("../helper/update-packageJson")
const { hasPackageJson } = require("../utils/check-package")

const { installDependencies } = require("./install-dependencies")
// use this to see what is been installed
// const runCommand = (command, args, options = {}) => {
// return new Promise((resolve, reject) => {
// const process = spawn(command, args, { stdio: 'inherit', ...options });
// process.on('close', (code) => {
// if (code !== 0) {
// reject(new Error(`Process exited with code ${code}`));
// } else {
// resolve();
// }
// });
// });
// };

// Function to copy template files to the project directory
async function copyTemplateFiles(templateName, destinationDir, templateDirectory, projectName) {
const { default: chalk } = await import('chalk');

const runCommand = (command, args, options = {}) => {
return new Promise((resolve, reject) => {
const process = spawn(command, args, { stdio: 'inherit', ...options });
process.on('close', (code) => {
if (code !== 0) {
reject(new Error(`Process exited with code ${code}`));
} else {
resolve();
}
});
});
};
const filesToExclude = ['.git', '.env', 'node_modules', 'package-lock.json', 'yarn.lock', '.cartesi'];

// Function to copy template files to the project directory
async function copyTemplateFiles(templateName, destinationDir, templateDirectory) {

try {
// Use spawn to run the npm install command and log the progress
runCommand('npm', ['install'], { stdio: 'inherit' })
// Use spawn to run the npm install command and log the progress
// runCommand('npm', ['install'], { stdio: 'inherit' })
const templateDir = path.resolve(__dirname,'..', templateDirectory, templateName);
const destDir = path.resolve(process.cwd(), destinationDir);
await ensureDir(destDir); // Ensure template directory exists
// Function to filter out .git, .env, node_modules, and package-lock.json files/directories
exludeFiles(templateDir, destDir)
await copy(templateDir, destDir);
console.log(`✅ Template ${templateName} created successfully!` )

if (fs.existsSync(templateDir)) {
const files = fs.readdirSync(templateDir);
const filesToCopy = files.filter(file => !filesToExclude.includes(file));
filesToCopy.forEach(file => {
const sourceFilePath = path.join(templateDir, file);
const destFilePath = path.join(destDir, file);

//update the package directory
if(files.includes('package.json')){
updatePackageJson(projectName, destDir)
}

// function to update the package.json name to the name of the project
fs.copySync(sourceFilePath, destFilePath);
// await copy(templateDir, destDir);
});
// console.log(`✅ Starter project successfully created!` )
// console.log( "Thank you for using CartDevKit! If you have any questions or need further assistance, please refer to the README or reach out to our team.")
// console.log(chalk.magenta("Happy coding! 🎉"))
} else {
console.error('Source directory does not exist.');
}
} catch (err) {
console.error(`Error copying template files: ${err}`);
}
}

async function printSuccessMessage() {
const { default: chalk } = await import('chalk');

console.log( chalk.green(`🚀 Starter project successfully created!`));
// console.log(chalk.bold('Before you start the project, please follow these steps:'))
// console.log( chalk.green('Run the following commands from your project folder to start the project:'))

// console.log(chalk.yellow(
// 'yarn install'
// ))
// console.log('or')
// console.log(chalk.yellow(
// 'npm install'
// ))
// console.log('Depending on your preference')

console.log(`${chalk.yellow('Thank you for using CartDevKit!')} If you have any questions or need further assistance, please refer to the README or reach out to our team.`);
console.log("")
console.log(chalk.magenta("Happy coding! 🎉"));
console.log("")

}

module.exports = {
copyTemplateFiles
copyTemplateFiles,
printSuccessMessage
};
20 changes: 20 additions & 0 deletions helper/generate-readme.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const fs = require("fs-extra")
const path = require('path');


const generateReadme = async (projectDir, projectName) => {
const readmeContent = `# ${projectName}\n\nThis project was scaffolded using CartDevKit CLI tool.`;

fs.writeFile(path.join(projectDir, 'README.md'), readmeContent, (err) => {
if (err) {
console.error(`Error generating README.md: ${err.message}`);
} else {
// console.log('README.md generated successfully.');
}
});

}

module.exports = {
generateReadme
}
34 changes: 0 additions & 34 deletions helper/install-dependencies.js

This file was deleted.

2 changes: 2 additions & 0 deletions helper/promptUtils.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const { generateReadme } = require("../helper/generate-readme")

const inquirer = require('inquirer');
// let inquirer
// Function to prompt user for template selection
Expand Down
33 changes: 33 additions & 0 deletions helper/update-packageJson.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const fs = require('fs');
const path = require('path');

const updatePackageJson = (projectName, templateDir) => {
const packageJsonPath = path.join(templateDir, 'package.json');

// Check if the package.json file exists
if (!fs.existsSync(packageJsonPath)) {
// console.log(`No package.json found in ${templateDir}, continuing setup...`);
return;
}

fs.readFile(packageJsonPath, 'utf8', (err, data) => {
if (err) {
// console.error(`Error reading package.json: ${err.message}`);
// return;
console.log('')
}

const packageJson = JSON.parse(data);
packageJson.name = projectName;

fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf8', (err) => {
if (err) {
console.error(`Error updating package.json: ${err.message}`);
} else {
// console.log('package.json updated successfully.');
}
});
});
};

module.exports = { updatePackageJson };
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"cartesi"
],
"workspaces": [
"packages/*"
"bin/*"
],
"bin": {
"cartdevkit": "./bin/index.js"
Expand Down
3 changes: 2 additions & 1 deletion utils/check-package.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const { ensureDir, copy } = require("fs-extra");

function isPackageInstalled(packageName) {
try {
Expand All @@ -12,5 +13,5 @@ function isPackageInstalled(packageName) {
}

module.exports = {
isPackageInstalled
isPackageInstalled,
}
Loading

0 comments on commit 95510d9

Please sign in to comment.