Skip to content

Instantly share code, notes, and snippets.

@JorgeCastello99
Last active February 12, 2023 01:52
Show Gist options
  • Save JorgeCastello99/6688955ecb581a327798f57f68cc6c9a to your computer and use it in GitHub Desktop.
Save JorgeCastello99/6688955ecb581a327798f57f68cc6c9a to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
":" //# comment; exec /usr/bin/env node --input-type=module - "$@" < "$0"
import { execSync } from "child_process";
import { existsSync, accessSync, constants } from "fs";
const color = (color, text) => {
const COLORS = {
reset: "\x1b[0m",
red: "\x1b[31m",
green: "\x1b[32m",
yellow: "\x1b[33m",
blue: "\x1b[34m",
magenta: "\x1b[35m",
cyan: "\x1b[36m"
};
return `${COLORS[color]}${text}${COLORS["reset"]}`;
};
const chop = str => str.replace(/\n$/, "");
const exec = (cmd) => chop(execSync(cmd).toString());
const VERSION = "0.3.6";
const [NAME, ...ARGS] = process.argv.slice(2).map(arg => arg.toLowerCase());
const COMMAND = process.argv[0];
const PARAMS = process.argv.slice(2).length;
const CURL = exec(`echo $(which curl)`);
const PNPM = exec(`echo $(which pnpm)`);
const YARN = exec(`echo $(which yarn)`);
const MKWEB = exec(`echo $(which mkweb)`);
const PM = PNPM ? "pnpm" : YARN ? "yarn" : "npm";
const JQ = exec(`echo $(which jq)`);
const GIT = exec(`echo $(which git)`);
const NPM = Number(exec(`echo $(npm --version)`).split(".")[0]);
if (existsSync(NAME)) {
console.log(`La carpeta ${color("red", NAME)} ya existe... Bórrala si quieres crear un proyecto nuevo`);
process.exit(-1);
}
if (!JQ) {
console.log(`${color("red", "jq")} not detected. Install with ${color("yellow", "sudo apt-get install jq")}`);
process.exit(-2);
}
if (!GIT) {
console.log(`${color("red", "git")} not detected. Install with ${color("yellow", "sudo apt-get install git")}`);
}
const isPhaser = ARGS.includes("--phaser");
const isLit = ARGS.includes("--lit");
if (NPM < 7) {
console.log(`${color("red", "npm 7")} is required. Install with ${color("yellow", "npm install -g npm")}`);
process.exit(-4);
}
if ((PARAMS === 0) || (NAME.includes("--help"))) {
console.log(`${color("green", "mkweb")} ${VERSION} - Por Jcaste ( ${color("magenta", "https://gist.github.com/JorgeCastello99")} )\n`);
console.log(`Sintaxis:`);
console.log(`mkweb <nombre-carpeta> [options]\tCrea un proyecto web.\n`);
console.log(`Ejemplos:`);
console.log(` mkweb sample-project \t\t\tCrea un proyecto HTML/CSS/Javascript nativo.`);
console.log(` mkweb phaser-project ${color("yellow", "--phaser")}\t\tCrea un proyecto Javascript con Phaser.`);
console.log(` mkweb lit-project ${color("yellow", "--lit")}\t\tCrea un proyecto Javascript con Lit.\n`);
console.log(` mkweb ${color("yellow", "--update")}\t\t\tActualiza a la última versión de mkweb.\n`);
console.log(`Recuerda que necesitas tener instalado jq y npm7+.`);
process.exit(0);
}
if (NAME === "--version") {
console.log(VERSION);
process.exit(0);
}
if (NAME === "--update") {
console.log("Actualizando mkweb...");
if (!MKWEB) {
console.log(`${color("red", "Error")}: No se encontró mkweb en la ruta. Se debe hacer actualización manual.`);
process.exit(-3);
}
try {
exec(`curl -s https://manz.dev/download/mkweb -o ${MKWEB}`);
}
catch {
console.log(`No tienes ${color("red", "permisos")} para actualizar. ¿Olvidaste el ${color("red", "sudo")}?`);
process.exit(-5);
}
console.log(`${color("green", "Actualizado a la última versión")}.`);
process.exit(0);
}
if (NAME && NAME.indexOf("--") === 0) {
console.log(`Sintaxis:`);
console.log(`mkweb <nombre-carpeta> [options] Crea un proyecto web.\n`);
console.log(`${color("red", "Error")}: Escribe primero el nombre de la carpeta y los parámetros al final.`);
process.exit(0);
}
try {
accessSync(".", constants.R_OK | constants.W_OK);
} catch {
console.log(`No tienes ${color("red", "permisos")} para escribir en la carpeta actual.`);
process.exit(-5);
}
console.log(`[${color("yellow", "1")}/3] Instalando ${color("green", "vite")}...`);
exec(`npm init vite@latest ${NAME} -y -- --template vanilla >/dev/null`);
console.log(`[${color("yellow", "2")}/3] Creando ${color("cyan", "estructura de carpetas")}...`);
process.chdir(NAME);
GIT && exec(`git init`);
exec(`cat >apackage.json << EOF
{
"scripts": {
"build": "rm -rf dist && vite build",
"deploy": "gh-pages -d dist"
},
"keywords": [],
"license": "ISC"
}
EOF
`);
exec("mkdir .vscode");
exec(`cat >.vscode/settings.json << EOF
// updated 2022-03-08 07:16
// https://github.com/antfu/vscode-file-nesting-config
{
"explorer.experimental.fileNesting.enabled": true,
"explorer.experimental.fileNesting.expand": false,
"explorer.experimental.fileNesting.patterns": {
".gitignore": ".gitattributes, .gitmodules, .gitmessage, .mailmap, .git-blame*",
"*.js": "\\$(capture).js.map, \\$(capture).min.js, \\$(capture).d.ts",
"*.jsx": "\\$(capture).js",
"*.ts": "\\$(capture).js, \\$(capture).*.ts",
"*.tsx": "\\$(capture).ts",
"index.d.ts": "*.d.ts",
"shims.d.ts": "*.d.ts",
"go.mod": ".air*, go.sum",
".env": "*.env, .env*, env.d.ts",
"dockerfile": ".dockerignore, dockerfile*",
"package.json": ".browserslist*, .circleci*, .codecov, .commitlint*, .editorconfig, .eslint*, .flowconfig, .gitlab*, .gitpod*, .huskyrc*, .jshintrc, .markdownlint*, .mocha*, .node-version, .nodemon*, .npm*, .nvmrc, .pm2*, .pnpm*, .prettier*, .releaserc*, .sentry*, .stackblitz*, .stylelint*, .tazerc*, .textlint*, .travis*, .vscode*, .watchman*, .yamllint*, .yarnrc*, api-extractor.json, appveyor*, ava.config.*, azure-pipelines*, build.config.*, commitlint*, crowdin*, cypress.json, dangerfile*, gulp*, jasmine.*, jenkins*, jest.config.*, jsconfig.*, karma*, lerna*, lint-staged*, nest-cli.*, netlify*, nodemon*, nx.*, package-lock.json, playwright.config.*, pm2.*, pnpm*, prettier*, pullapprove*, puppeteer.config.*, renovate*, rollup.config.*, stylelint*, tsconfig.*, tsdoc.*, tslint*, tsup.config.*, turbo*, vercel*, vetur.config.*, vitest.config.*, webpack.config.*, workspace.json, yarn*",
"readme.md": "authors, backers.md, changelog*.md, code_of_conduct.md, codeowners, contributing.md, contributors, copying, credits, governance.md, history.md, license*, maintainers, readme*, security.md, sponsors.md",
"cargo.toml": "cargo.lock, rust-toolchain.toml, rustfmt.toml",
"gemfile": ".ruby-version, gemfile.lock",
"vite.config.*": "*.env, .babelrc, .codecov, .env*, .mocha*, .postcssrc.*, api-extractor.json, ava.config.*, babel.config.*, cypress.json, env.d.ts, index.html, jasmine.*, jest.config.*, jsconfig.*, karma*, playwright.config.*, postcss.config.*, puppeteer.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"vue.config.*": "*.env, .babelrc, .codecov, .env*, .mocha*, .postcssrc.*, api-extractor.json, ava.config.*, babel.config.*, cypress.json, env.d.ts, jasmine.*, jest.config.*, jsconfig.*, karma*, playwright.config.*, postcss.config.*, puppeteer.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"nuxt.config.*": "*.env, .babelrc, .codecov, .env*, .mocha*, .postcssrc.*, api-extractor.json, ava.config.*, babel.config.*, cypress.json, env.d.ts, jasmine.*, jest.config.*, jsconfig.*, karma*, playwright.config.*, postcss.config.*, puppeteer.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"next.config.*": "*.env, .babelrc, .codecov, .env*, .mocha*, .postcssrc.*, api-extractor.json, ava.config.*, babel.config.*, cypress.json, env.d.ts, jasmine.*, jest.config.*, jsconfig.*, karma*, next-env.d.ts, playwright.config.*, postcss.config.*, puppeteer.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"svelte.config.*": "*.env, .babelrc, .codecov, .env*, .mocha*, .postcssrc.*, api-extractor.json, ava.config.*, babel.config.*, cypress.json, env.d.ts, jasmine.*, jest.config.*, jsconfig.*, karma*, playwright.config.*, postcss.config.*, puppeteer.config.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*",
"remix.config.*": "*.env, .babelrc, .codecov, .env*, .mocha*, .postcssrc.*, api-extractor.json, ava.config.*, babel.config.*, cypress.json, env.d.ts, jasmine.*, jest.config.*, jsconfig.*, karma*, playwright.config.*, postcss.config.*, puppeteer.config.*, remix.*, svgo.config.*, tailwind.config.*, tsconfig.*, tsdoc.*, unocss.config.*, vitest.config.*, webpack.config.*, windi.config.*"
},
"workbench.colorCustomizations": {
"activityBar.activeBackground": "#087073",
"activityBar.background": "#087073",
"activityBar.foreground": "#e7e7e7",
"activityBar.inactiveForeground": "#e7e7e799",
"activityBarBadge.background": "#590657",
"activityBarBadge.foreground": "#e7e7e7",
"commandCenter.border": "#e7e7e799",
"sash.hoverBorder": "#087073",
"statusBar.background": "#054244",
"statusBar.foreground": "#e7e7e7",
"statusBarItem.hoverBackground": "#087073",
"statusBarItem.remoteBackground": "#054244",
"statusBarItem.remoteForeground": "#e7e7e7",
"titleBar.activeBackground": "#054244",
"titleBar.activeForeground": "#e7e7e7",
"titleBar.inactiveBackground": "#05424499",
"titleBar.inactiveForeground": "#e7e7e799"
},
"peacock.remoteColor": "#054244"
}
EOF
`);
exec(`jq -s '.[0] * .[1]' package.json apackage.json >package2.json`);
exec("rm apackage.json package.json index.html");
exec("mv package2.json package.json");
exec("rm main.js style.css counter.js javascript.svg public/vite.svg");
exec("mkdir -p public src/assets src/components");
exec("touch src/index.css src/index.js");
exec(`cat >postcss.config.js << EOF
export default {
plugins: {
"postcss-nesting": true
}
};
EOF
`);
exec(`cat >src/index.html << EOF
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./index.css">
<script type="module" src="./index.js"></script>
</head>
<body>
</body>
</html>
EOF`);
exec(`cat >vite.config.js << EOF
import path from "path";
const isGitHubPages = true;
const folderName = path.basename(process.cwd()) + "/";
const mode = process.env.NODE_ENV === "production" ? "production" : "development";
const base = mode === "production" && isGitHubPages ? "/" + folderName : "/";
export default {
root: "src",
base,
mode,
publicDir: "../public",
build: {
outDir: "../dist",
assetsDir: "./"
}
};
EOF
`);
exec(`cat >.eslintrc.cjs << EOF
module.exports = {
env: {
browser: true,
es2021: true
},
extends: [
"standard"
],
parserOptions: {
ecmaVersion: "latest",
sourceType: "module"
},
rules: {
quotes: ["error", "double"],
semi: ["error", "always"],
"comma-dangle": ["error", "only-multiline"],
"space-before-function-paren": ["error", "never"],
indent: ["error", 2]
}
};
EOF
`);
exec(`cat >.stylelintrc << EOF
{
"extends": "stylelint-config-standard",
"customSyntax": "postcss-syntax",
"rules": {
"declaration-colon-newline-after": "always-multi-line",
"selector-type-no-unknown": null,
"property-no-unknown": [
true,
{
"ignoreProperties": [
"content-visibility"
]
}
]
}
}
EOF
`);
const removeItem = (array, item) => {
const pos = array.indexOf(item);
array.splice(pos, 1);
}
const DEVDEP = [
"stylelint@14.11.0", "stylelint-config-standard@28.0.0", "postcss-nesting",
"postcss", "postcss-syntax", "postcss-html", "postcss-jsx", "postcss-styled", "@stylelint/postcss-css-in-js",
"eslint", "eslint-plugin-import", "eslint-plugin-n@14.0.0", "eslint-plugin-promise", "eslint-config-standard@17.0.0-1",
"gh-pages"
];
const DEP = [];
if (isPhaser) {
exec("rm -rf src/components postcss.config.js src/assets");
exec("mkdir -p public/assets/sprites public/assets/sounds");
DEP.push("phaser");
removeItem(DEVDEP, "postcss-nesting");
}
if (isLit) {
DEP.push("lit");
}
console.log(`[${color("yellow", "3")}/3] Instalando ${color("magenta", "dependencias")}...`);
if (DEP.length > 0) {
const PACKAGES = DEP.join(" ");
exec(`npx add-dependencies ${PACKAGES} 2>/dev/null`);
}
const DEVPACKAGES = DEVDEP.join(" ");
exec(`npx add-dependencies ${DEVPACKAGES} --dev 2>/dev/null`);
console.log(`\n¡${color("green", "Listo")}! Para empezar, escribe:
cd ${NAME}
git remote add origin <repo>
${PM} install
${PM} run dev`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment