Skip to content

Commit

Permalink
feat: renaming templates into apps (#80)
Browse files Browse the repository at this point in the history
  • Loading branch information
Zizzamia authored Nov 24, 2023
1 parent 2abff66 commit 2241eba
Show file tree
Hide file tree
Showing 52 changed files with 328 additions and 601 deletions.
21 changes: 1 addition & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,6 @@ yarn dev

<br>

## Keep in mind

When using Build Onchain Apps remember

- To remove global installation via `npm uninstall -g @base-org/build-onchain-apps` or `yarn global remove @base-org/build-onchain-apps` to ensure that npx always uses the latest version.
- [npx](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b) comes with npm 5.2+ and higher, see [instructions for older npm versions](https://gist.github.com/gaearon/4064d3c23a77c74a3614c498a8bb1c5f)

<br>

## Contributing ☕️ 🔵

The main purpose of this repository is to continue evolving Build Onchain Apps, making it better and easier to use. Development of Build Onchain Apps happens in the open on GitHub, and we are grateful to the community for contributing bugfixes and improvements. Read below to learn how you can take part in improving Build Onchain Apps.
Expand Down Expand Up @@ -105,18 +96,8 @@ build-onchain-apps create

# After testing, unlink the package from the global npm registry
npm unlink @base-org/build-onchain-apps
npm uninstall -g @base-org/build-onchain-apps
```

#### Adding new templates

To make a new template, make a folder for it in the `templates` folder and set up your project there. Treat each template like its own Node.js project and run the commands in its folder.

```bash
cd templates/buy-me-a-coffee-app
yarn
yarn dev
```

<br>

## Community ☁️ 🌁 ☁️
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
68 changes: 23 additions & 45 deletions src/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,23 @@ import * as chalk from 'chalk';
import * as fs from 'fs';
import * as inquirer from 'inquirer';
import {
downloadAndExtractTemplates,
getTemplateDir,
getTemplateChoices,
downloadAndExtractApps,
getAppDir,
updatePackageJson,
displayFinalInstructions,
removeDownloadedTemplates,
} from './utils/templates';
removeDownloadedApps,
} from './utils/apps';
import { isRootDirWriteable, getProjectDir } from './utils/dir';

// Default location for all Onchain Applications
const APPS_DIR = 'apps/';
const MAIN_APP_NAME = 'build-onchain-apps';

/**
* Responsible for copying the
* onchain template and create new project.
* onchain app and create new project.
*/
export const createProject = async (templateName: string) => {
export const createProject = async () => {
// Check if the current directory is writeable
// If not, exit the process
if (!(await isRootDirWriteable())) {
Expand All @@ -41,55 +41,33 @@ export const createProject = async (templateName: string) => {
)}`
);

// Download the template from github.com/base-org/build-onchain-apps/templates and extract it
await downloadAndExtractTemplates();
const templateChoices = getTemplateChoices();
if (templateName && !templateChoices.includes(templateName)) {
console.log(
chalk.yellow(
`${templateName} does not exists. Choose one of the following templates: \n`
)
);
}

if (!templateName || !templateChoices.includes(templateName)) {
const answer = await inquirer.prompt([
{
type: 'list',
name: 'templateName',
message: 'Choose a template:',
choices: templateChoices,
},
]);
templateName = answer.templateName;
}

const appNameAnswer = await inquirer.prompt([
// Download the app from github.com/base-org/build-onchain-apps/apps and extract it
await downloadAndExtractApps();
const newAppNameAnswer = await inquirer.prompt([
{
type: 'input',
name: 'appName',
message: 'Enter the name for your new onchain app:',
validate: (input: string) => !!input || 'Project name cannot be empty.',
name: 'newAppName',
message: 'Enter the name for your new Onchain app:',
validate: (input: string) => !!input || 'Onchain App name cannot be empty.',
},
]);

const appName = appNameAnswer.appName;
const projectDir = getProjectDir(APPS_DIR + appName);

if (fs.existsSync(projectDir)) {
const newAppName = newAppNameAnswer.newAppName;
const newAppDir = getProjectDir(APPS_DIR + newAppName);
if (fs.existsSync(newAppDir)) {
console.error(
chalk.red('A directory with the project name already exists.')
chalk.red('A directory with the App name already exists.')
);
removeDownloadedTemplates();
removeDownloadedApps();
process.exit(1);
}

fs.cpSync(getTemplateDir(templateName), projectDir, { recursive: true });
const isPackageJsonUpdated = updatePackageJson(projectDir, appName);
fs.cpSync(getAppDir(MAIN_APP_NAME), newAppDir, { recursive: true });
const isPackageJsonUpdated = updatePackageJson(newAppDir, newAppName);

if (isPackageJsonUpdated) {
displayFinalInstructions(appName);
displayFinalInstructions(newAppName);
}

removeDownloadedTemplates();
removeDownloadedApps();
};
6 changes: 2 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@ import { createProject } from './create';
const program = new Command();

program
.command('create [templateName]')
.arguments('[templateName]')
.usage(`${chalk.green('<templateName>')} [options]`)
.description('Create a new project from a template')
.command('create')
.description('Create a new App')
.action(createProject);

program.parse(process.argv);
Expand Down
34 changes: 13 additions & 21 deletions src/utils/templates.ts → src/utils/apps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,38 +10,30 @@ import { rimraf } from 'rimraf';

import { ROOT_DIR } from './dir';

export const TEMPLATES_ENGINE_DIR = `${ROOT_DIR}/.build-onchain-apps`;
export const TEMPLATES_DIR = `${TEMPLATES_ENGINE_DIR}/templates`;
export const APPS_ENGINE_DIR = `${ROOT_DIR}/.build-onchain-apps`;
export const APPS_DIR = `${APPS_ENGINE_DIR}/apps`;

const pipeline = promisify(Stream.pipeline);

export async function downloadAndExtractTemplates(): Promise<void> {
// ensure the templates directory exists
await makeDir(TEMPLATES_DIR);
export async function downloadAndExtractApps(): Promise<void> {
// ensure the apps directory exists
await makeDir(APPS_DIR);

return pipeline(
got.stream(
'https://codeload.github.com/base-org/build-onchain-apps/tar.gz/main'
),
extract({ cwd: TEMPLATES_ENGINE_DIR, strip: 1 })
extract({ cwd: APPS_ENGINE_DIR, strip: 1 })
);
}

export const getTemplateDir = (appName: string) => {
return path.join(TEMPLATES_DIR, appName);
export const getAppDir = (appName: string) => {
return path.join(APPS_DIR, appName);
};

export const getTemplateChoices = (): string[] => {
const templates = fs.readdirSync(TEMPLATES_DIR).filter((file) => {
const filePath = path.join(TEMPLATES_DIR, file);
return fs.statSync(filePath).isDirectory();
});
return templates;
};

export async function removeDownloadedTemplates() {
export async function removeDownloadedApps() {
try {
await rimraf.sync(TEMPLATES_ENGINE_DIR);
await rimraf.sync(APPS_ENGINE_DIR);
} catch (e) {
console.error('Error while removing directories:', e);
}
Expand All @@ -58,15 +50,15 @@ export const updatePackageJson = (
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
return true;
} else {
console.warn(chalk.yellow('package.json not found in the template.'));
console.warn(chalk.yellow('package.json not found in the app.'));
return false;
}
};

export const displayFinalInstructions = (appName: string) => {
console.log(chalk.green(`🚀 Project '${appName}' created successfully!`));
console.log(chalk.green(`🚀 Onchain App '${appName}' created successfully!`));
console.log(
chalk.blue(`Type 'cd apps/${appName}' to navigate into your new project.`)
chalk.blue(`Type 'cd apps/${appName}' to navigate into your new Onchain App.\n`)
);
console.log(chalk.blue(`Run 'yarn' to install dependencies.`));
console.log(chalk.blue(`Run 'yarn dev' to start the development server.`));
Expand Down
Loading

0 comments on commit 2241eba

Please sign in to comment.