Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
pyramation committed Apr 6, 2024
1 parent 2e25ea2 commit 84fa83f
Showing 1 changed file with 121 additions and 102 deletions.
223 changes: 121 additions & 102 deletions packages/create-cosmos-app/src/git-cca-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,48 +6,92 @@ import { join, dirname, basename, sep, relative } from 'path';
import { sync as mkdirp } from 'mkdirp';
import { sync as glob } from 'glob';
import * as fs from 'fs';
import { cloneRepo, getPackageLicAndAccessInfo, getQuestionsAndAnswers, getTemplateFolder } from './utils';
import {
cloneRepo,
getPackageLicAndAccessInfo,
getQuestionsAndAnswers,
getTemplateFolder
} from './utils';
import { CCA_URL } from './constants';

const requiredTools = ['git', 'yarn'];

const white = (cmd) => c.bold.whiteBright(cmd);
const motd = (cmd) => {
return (`
| _ _
=== |.===. '\\-//\`
(o o) {}o o{} (o o)
ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-
✨ Have fun! Now you can start on your project ⚛️
Now, run this command:
${white(cmd)}
`);
}

const checkRequiredTools = () => {
for (const tool of requiredTools) {
if (!shell.which(tool)) {
shell.echo(`Sorry, this script requires ${tool}.`);
return false;
}
}
return true;
}


async function getAppName(argv) {
let { name } = await prompt(
[{
name: 'name',
message: 'Enter your new app name',
required: true,
}],
argv
);
return name.replace(/\s/g, '-');
}


async function setupAppDirectory(repo, argv, name) {
const folderName = await getTemplateFolder(argv);
const currentDirectory = process.cwd();
const tempDir = cloneRepo(argv, repo, name);

shell.cd(name);
return { folderName, currentDirectory, tempDir };
}


async function warnIfOutdated(repo, clonedRepoDir, version) {
if (repo === CCA_URL) {
const rootPkgPath = join(clonedRepoDir, 'packages/create-cosmos-app/package.json');
const rootPkg = JSON.parse(fs.readFileSync(rootPkgPath, 'utf-8'));
if (semver.gt(rootPkg.version, version)) {
console.warn(c.yellow(`⚠️ You are using create-cosmos-app version ${c.red(rootPkg.version)}, but version ${c.green(version)} is available. Run "${c.cyan('cca upgrade')}" or "${c.cyan('npm install -g create-cosmos-app@latest')}" to upgrade.`));
}
}
}

export const createGitApp = (repo: string, version: string) => {
return async argv => {

// if --no-install is set, don't touch!
if (!argv.hasOwnProperty('install')) argv.install = true;

// check required tools
for (const tool of requiredTools) {
if (!shell.which(tool)) {
shell.echo(`Sorry, this script requires ${tool}.`);
return shell.exit(1);
}
}

let { name } = await prompt([
{
name: 'name',
message: 'Enter your new app name',
required: true,
}
], argv);
name = name.replace(/\s/g, '-');
// check required (git, yarn, etc...)
if (!checkRequiredTools()) return shell.exit(1);

const folderName = await getTemplateFolder(argv);
const currentDirectory = process.cwd();
const tempDir = cloneRepo(argv, repo, name);
// setup directories/repo
const name = await getAppName(argv);
const { folderName, currentDirectory, tempDir } = await setupAppDirectory(repo, argv, name);
const clonedRepoDir = join(tempDir, name);
// cd into the cloned repo from $dir
shell.cd(name);

// warn about upgrades
if (repo === CCA_URL) {
const rootPkgPath = join(clonedRepoDir, 'packages/create-cosmos-app/package.json');
const rootPkg = JSON.parse(fs.readFileSync(rootPkgPath, 'utf-8'));
if (semver.gt(rootPkg.version, version)) {
console.warn(c.yellow(`⚠️ You are using create-cosmos-app version ${c.red(rootPkg.version)}, but version ${c.green(version)} is available. Run "${c.cyan('cca upgrade')}" or "${c.cyan('npm install -g create-cosmos-app@latest')}" to upgrade.`));
}
}
// check version
await warnIfOutdated(repo, clonedRepoDir, version);

// get template
const list = shell.ls(`./${folderName}`);
Expand All @@ -68,7 +112,7 @@ export const createGitApp = (repo: string, version: string) => {

// KEEP THIS CODE FOR BOILERPLATES!
let license = {};
let scopedResults = {};
let scopedResults: any = {};
if (hasResults) {
({
license,
Expand Down Expand Up @@ -108,99 +152,74 @@ export const createGitApp = (repo: string, version: string) => {

// access
if (hasResults) {
// Determine the prefix based on the conditions
let prefix = '';
if (results.__ACCESS__ === 'public') {
// @ts-ignore
if (scopedResults.scoped) {
content = content.replace(
/__PACKAGE_IDENTIFIER__/g,
`@${results.__USERNAME__}/${results.__MODULENAME__}`
);
} else {
content = content.replace(
/__PACKAGE_IDENTIFIER__/g,
`${results.__MODULENAME__}`
);
}
prefix = scopedResults.scoped ? `@${results.__USERNAME__}/` : '';
} else {
content = content.replace(
/__PACKAGE_IDENTIFIER__/g,
`@${results.__USERNAME__}/${results.__MODULENAME__}`
);
prefix = `@${results.__USERNAME__}/`;
}
}

// Replace __PACKAGE_IDENTIFIER__ with the determined prefix and module name
content = content.replace(/__PACKAGE_IDENTIFIER__/g, `${prefix}${results.__MODULENAME__}`);
}

// write stuff
const localfile = templateFile.split(`${folderName}/` + template)[1];
const localdir = dirname(localfile);
const dirpath = join(currentDirectory, name, localdir);
const filepath = join(currentDirectory, name, localfile);
// Construct the file path
const relativeFilePath = templateFile.split(join(folderName, template) + sep)[1];
const targetDirPath = join(currentDirectory, name, dirname(relativeFilePath));
const targetFilePath = join(targetDirPath, basename(relativeFilePath));

mkdirp(dirpath);
fs.writeFileSync(filepath, content);
// Ensure the target directory exists before writing the file
mkdirp(targetDirPath);
fs.writeFileSync(targetFilePath, content);

}

// Clean up and change directory
shell.cd(currentDirectory);
shell.rm('-rf', tempDir);
shell.cd(`./${name}`);
shell.cd(name);

const pkgJsons = []
.concat(glob(join(currentDirectory, name, '/**/package.json')));

let pkgJsonFound = true;
let closestPkgJson = null;
if (pkgJsons.length === 0) {
console.log('No package.json file found');
pkgJsonFound = false;
} else {
// Find the shortest path
closestPkgJson = pkgJsons.reduce((shortest, current) => {
const closestPkgJson = []
.concat(glob(join(currentDirectory, name, '**', 'package.json')))
.reduce((shortest, current) => {
return current.split(sep).length < shortest.split(sep).length ? current : shortest;
});
}


let rel;
if (pkgJsonFound) {
// clean up lock-file business...
const pkg = JSON.parse(fs.readFileSync(closestPkgJson, 'utf-8'));
delete pkg.scripts['locks:remove']
delete pkg.scripts['locks:create']
delete pkg.scripts['locks']
delete pkg.devDependencies['generate-lockfile']
fs.writeFileSync(closestPkgJson, JSON.stringify(pkg, null, 2));

// now yarn...
if (closestPkgJson) {
console.log('No package.json file found');
}
if (closestPkgJson) {
// Read and update package.json
const pkgPath = closestPkgJson;
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
['locks:remove', 'locks:create', 'locks'].forEach(script => delete pkg.scripts[script]);
delete pkg.devDependencies['generate-lockfile'];
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));

// Change to package directory and run yarn if necessary
const pkgDir = dirname(pkgPath);
shell.cd(pkgDir);
if (argv.install) {
shell.cd(dirname(closestPkgJson));
shell.exec(`yarn`);
shell.exec('yarn');
}

rel = relative(currentDirectory, dirname(closestPkgJson));
}
shell.cd(currentDirectory);

// Build the command based on the presence of results and package.json
const relPath = relative(currentDirectory, pkgDir);
let cmd = `cd ./${relPath}`;
if (!hasResults) {
cmd += ' && yarn dev';
}
console.log(motd(cmd));

let cmd = `cd ./${name}`;
if (!hasResults && pkgJsonFound) {
// if rel, then set manually
cmd = `cd ./${rel}`;
cmd += `\nyarn dev`
} else {
console.log('No package.json file found');
console.log(motd(`cd ${name}`));
}

console.log(`
| _ _
=== |.===. '\\-//\`
(o o) {}o o{} (o o)
ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-
✨ Have fun! Now you can start on your project ⚛️
Now, run this command:
// Change back to the original directory
shell.cd(currentDirectory);

${c.bold.whiteBright(cmd)}
`);
};
};

0 comments on commit 84fa83f

Please sign in to comment.