create-cosmos-app
Version:
Set up a modern Cosmos app by running one command ⚛️
234 lines (232 loc) • 10.5 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createGitApp = void 0;
const shell = __importStar(require("shelljs"));
const semver_1 = __importDefault(require("semver"));
const c = __importStar(require("ansi-colors"));
const prompt_1 = require("./prompt");
const path_1 = require("path");
const mkdirp_1 = require("mkdirp");
const utils_1 = require("./utils");
const fs = __importStar(require("fs"));
const utils_2 = require("./utils");
const constants_1 = require("./constants");
const posixPath = require('path').posix;
const requiredTools = ['git', 'yarn'];
const motd = (cmd, printCmd) => {
const commandSection = printCmd ? `Now, run this command:\n\n${c.bold.whiteBright(cmd)}` : '';
return `
| _ _
=== |.===. '\\-//\`
(o o) {}o o{} (o o)
ooO--(_)--Ooo-ooO--(_)--Ooo-ooO--(_)--Ooo-
✨ Have fun! Now you can start on your project ⚛️
${commandSection}
`;
};
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 (0, prompt_1.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 (0, utils_2.getTemplateFolder)(argv);
const currentDirectory = process.cwd();
const tempDir = (0, utils_2.cloneRepo)(argv, repo, name);
shell.cd(name);
return { folderName, currentDirectory, tempDir };
}
async function warnIfOutdated(repo, clonedRepoDir, version) {
if (repo === constants_1.CCA_URL) {
const rootPkgPath = (0, path_1.join)(clonedRepoDir, 'packages/create-cosmos-app/package.json');
const rootPkg = JSON.parse(fs.readFileSync(rootPkgPath, 'utf-8'));
if (semver_1.default.lt(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.`));
}
}
}
const createGitApp = (repo, version) => {
return async (argv) => {
// if --no-install is set, don't touch!
if (!argv.hasOwnProperty('install'))
argv.install = true;
if (!argv.hasOwnProperty('printCmd'))
argv.printCmd = true;
// check required (git, yarn, etc...)
if (!checkRequiredTools())
return shell.exit(1);
// setup directories/repo
const name = await getAppName(argv);
const { folderName, currentDirectory, tempDir } = await setupAppDirectory(repo, argv, name);
const clonedRepoDir = (0, path_1.join)(tempDir, name);
// check version
await warnIfOutdated(repo, clonedRepoDir, version);
// get template
const list = shell.ls(`./${folderName}`);
const { template } = await (0, prompt_1.prompt)([
{
type: 'list',
name: 'template',
message: 'which template',
required: true,
choices: list
}
], argv);
argv.template = template;
const results = await (0, utils_2.getQuestionsAndAnswers)(argv, name, folderName);
const hasResults = Object.keys(results).length > 0;
// KEEP THIS CODE FOR BOILERPLATES!
let license = {};
let scopedResults = {};
if (hasResults) {
({
license,
scopedResults
} = await (0, utils_2.getPackageLicAndAccessInfo)(results));
const path = (0, path_1.join)(folderName, argv.template, '.questions.json');
shell.rm('-rf', path);
}
const files = []
.concat((0, utils_1.crossGlob)((0, path_1.join)(process.cwd(), folderName, template, '/**/.*')))
.concat((0, utils_1.crossGlob)((0, path_1.join)(process.cwd(), folderName, template, '/**/*')));
for (let i = 0; i < files.length; i++) {
const templateFile = files[i];
if (fs.lstatSync(templateFile).isDirectory())
continue;
const isImage = /\.(png|jpe?g|gif|svg|webp|ico)$/i.test(templateFile);
let content;
if (isImage) {
content = fs.readFileSync(templateFile);
}
else {
content = fs.readFileSync(templateFile).toString();
// LICENSE
if ((0, path_1.basename)(templateFile) === 'LICENSE' &&
// @ts-ignore
license.__LICENSE__ === 'closed') {
content = `Copyright (c) ${new Date().getFullYear()} __USERFULLNAME__ <__USEREMAIL__> - All Rights Reserved
Unauthorized copying via any medium is strictly prohibited
Proprietary and confidential`;
}
// swap out content from results!
Object.keys(results).forEach((key) => {
if (/^__/.test(key)) {
content = content.replace(new RegExp(key, 'g'), results[key]);
}
});
// access
if (hasResults) {
// Determine the prefix based on the conditions
let prefix = '';
if (results.__ACCESS__ === 'public') {
prefix = scopedResults.scoped ? `@${results.__USERNAME__}/` : '';
}
else {
prefix = `@${results.__USERNAME__}/`;
}
// Replace __PACKAGE_IDENTIFIER__ with the determined prefix and module name
content = content.replace(/__PACKAGE_IDENTIFIER__/g, `${prefix}${results.__MODULENAME__}`);
}
}
// Construct the file path
const relativeFilePath = templateFile.split((0, utils_1.toPosixPath)((0, path_1.join)(folderName, template) + '/'))[1];
// Replace keys in the entire file path
const replacedFilePath = Object.keys(results).reduce((filePath, key) => {
if (/^__/.test(key)) {
const safeName = results[key].replace(/[^a-zA-Z0-9_-]/g, '_'); // Replacing unsafe characters
return filePath.replace(new RegExp(key, 'g'), safeName);
}
return filePath;
}, relativeFilePath);
const targetDirPath = (0, path_1.join)(currentDirectory, name, (0, path_1.dirname)(replacedFilePath));
const targetFilePath = (0, path_1.join)(targetDirPath, (0, path_1.basename)(replacedFilePath));
// Ensure the target directory exists before writing the file
(0, mkdirp_1.sync)(targetDirPath);
fs.writeFileSync(targetFilePath, content);
}
// Clean up and change directory
shell.cd(currentDirectory);
shell.rm('-rf', tempDir);
shell.cd(name);
const fakeLongPath = '/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p';
const closestPkgJson = []
.concat((0, utils_1.crossGlob)((0, path_1.join)(currentDirectory, name, '**', 'package.json')))
.reduce((shortest, current) => {
return current.split(posixPath.sep).length < shortest.split(posixPath.sep).length ? current : shortest;
}, fakeLongPath); // long string for kicks
if (closestPkgJson === fakeLongPath) {
console.log('No package.json file found');
}
else if (closestPkgJson) {
// Read and update package.json
const pkgPath = closestPkgJson;
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
if (pkg.scripts) {
['locks:remove', 'locks:create', 'locks'].forEach(script => delete pkg.scripts[script]);
}
if (pkg.devDependencies) {
delete pkg.devDependencies['generate-lockfile'];
}
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
// Change to package directory and run yarn if necessary
const pkgDir = (0, path_1.dirname)(pkgPath);
shell.cd(pkgDir);
if (argv.install) {
shell.exec('yarn');
}
// Build the command based on the presence of results and package.json
const relPath = (0, path_1.relative)(currentDirectory, pkgDir);
let cmd = `cd ./${relPath}`;
if (!hasResults) {
cmd += ' && yarn dev';
}
console.log(motd(cmd, argv.printCmd));
}
else {
console.log('No package.json file found');
console.log(motd(`cd ${name}`, argv.printCmd));
}
// Change back to the original directory
shell.cd(currentDirectory);
};
};
exports.createGitApp = createGitApp;
//# sourceMappingURL=git-cca-template.js.map