Skip to content

Commit

Permalink
Merge pull request #10 from jwcjs/feat/cli
Browse files Browse the repository at this point in the history
  • Loading branch information
AkaraChen authored Dec 19, 2022
2 parents f7ae05e + 5d1c2a0 commit 6bbae9d
Show file tree
Hide file tree
Showing 23 changed files with 1,410 additions and 52 deletions.
21 changes: 21 additions & 0 deletions packages/core/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Jwc.js

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
21 changes: 21 additions & 0 deletions packages/create-jwc/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Jwc.js

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
15 changes: 15 additions & 0 deletions packages/create-jwc/build.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { defineBuildConfig } from "unbuild";

export default defineBuildConfig({
entries: ["src/index"],
clean: true,
rollup: {
inlineDependencies: true,
esbuild: {
minify: true,
},
},
alias: {
prompts: "prompts/lib/index.js",
},
});
3 changes: 3 additions & 0 deletions packages/create-jwc/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/usr/bin/env node

import "./dist/index.mjs";
28 changes: 28 additions & 0 deletions packages/create-jwc/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "create-jwc",
"version": "0.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"dev": "unbuild --stub",
"build": "unbuild",
"typecheck": "tsc --noEmit",
"prepublishOnly": "npm run build"
},
"keywords": [
"jwcjs"
],
"author": "JwcJS",
"license": "MIT",
"devDependencies": {
"@types/minimist": "^1.2.2",
"@types/prompts": "^2.4.2",
"cross-spawn": "^7.0.3",
"kolorist": "^1.6.0",
"minimist": "^1.2.7",
"prompts": "^2.4.2",
"ts-node": "^10.9.1",
"unbuild": "^1.0.2"
}
}
228 changes: 228 additions & 0 deletions packages/create-jwc/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
import fs from "node:fs";
import path from "node:path";
import minimist from "minimist";
import prompts from "prompts";
import { cyan, green, red, reset } from "kolorist";
import { fileURLToPath } from "node:url";

const cwd = process.cwd();
const argv = minimist<{
t?: string;
template?: string;
}>(process.argv.slice(2), { string: ["_"] });

const TEMPLATES = [
{
name: "starter-vite-ts",
display: "Starter (Vite + TypeScript)",
color: cyan,
},
// {
// name: "starter-vite-js",
// display: "Starter (Vite + JavaScript)",
// color: blue,
// },
];

function formatTargetDir(targetDir: string | undefined) {
return targetDir?.trim().replace(/\/+$/g, "");
}

function copy(src: string, dest: string) {
const stat = fs.statSync(src);
if (stat.isDirectory()) {
copyDir(src, dest);
} else {
fs.copyFileSync(src, dest);
}
}

function isValidPackageName(projectName: string) {
return /^(?:@[a-z\d\-*~][a-z\d\-*._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/.test(
projectName
);
}

function toValidPackageName(projectName: string) {
return projectName
.trim()
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/^[._]/, "")
.replace(/[^a-z\d\-~]+/g, "-");
}

function copyDir(srcDir: string, destDir: string) {
fs.mkdirSync(destDir, { recursive: true });
for (const file of fs.readdirSync(srcDir)) {
const srcFile = path.resolve(srcDir, file);
const destFile = path.resolve(destDir, file);
copy(srcFile, destFile);
}
}

function isEmpty(path: string) {
const files = fs.readdirSync(path);
return files.length === 0 || (files.length === 1 && files[0] === ".git");
}

function emptyDir(dir: string) {
if (!fs.existsSync(dir)) {
return;
}
for (const file of fs.readdirSync(dir)) {
if (file === ".git") {
continue;
}
fs.rmSync(path.resolve(dir, file), { recursive: true, force: true });
}
}

function pkgFromUserAgent(userAgent: string | undefined) {
if (!userAgent) return undefined;
const pkgSpec = userAgent.split(" ")[0];
const pkgSpecArr = pkgSpec.split("/");
return {
name: pkgSpecArr[0],
version: pkgSpecArr[1],
};
}

const defaultTargetDir = "my-jwc-app";

const renameFiles: Record<string, string | undefined> = {
_gitignore: ".gitignore",
};

async function init() {
let dir = formatTargetDir(argv._[0]);
const getProjectName = () =>
dir === "." ? path.basename(path.resolve()) : dir;
const template = argv.t || argv.template;
let result;
try {
result = await prompts(
[
{
type: dir ? null : "text",
name: "projectName",
message: reset("Project name:"),
initial: defaultTargetDir,
onState: (state) => {
dir = formatTargetDir(state.value) || defaultTargetDir;
},
},
{
type: () =>
!fs.existsSync(dir) || isEmpty(dir) ? null : "confirm",
name: "overwrite",
message: () =>
`Target directory ${dir} is not empty. Remove existing files and continue?`,
},
{
type: (_, { overwrite }) => {
if (overwrite === false)
throw new Error(`${red("✖")} Operation cancelled`);
return null;
},
name: "overwrite-confirm",
},
{
type: () =>
isValidPackageName(getProjectName()) ? null : "text",
name: "packageName",
message: reset("Project name:"),
initial: () => toValidPackageName(getProjectName()),
validate: (name) =>
isValidPackageName(name)
? true
: "Invalid project name",
},
{
type:
template && TEMPLATES.find((t) => t.name === template)
? null
: "select",
name: "template",
message: reset(
typeof template === "string" &&
!TEMPLATES.find((t) => t.name === template)
? `Template ${template} not found. Please choose a template:`
: "Select a template:"
),
initial: 0,
choices: TEMPLATES.map((t) => {
return {
title: t.color(t.display || t.name),
value: t,
};
}),
},
],
{
onCancel: () => {
throw new Error(red("✖") + " Operation cancelled");
},
}
);
} catch (err: any) {
console.error(err.message);
process.exit(1);
}

const { template: userTemplate, overwrite, packageName } = result;
const root = path.join(cwd, dir);

if (overwrite) {
emptyDir(root);
} else if (!fs.existsSync(root)) {
fs.mkdirSync(root, { recursive: true });
}

const pkginfo = pkgFromUserAgent(process.env.npm_config_user_agent);
const manager = pkginfo ? pkginfo.name : "npm";

const templateDir = path.resolve(
fileURLToPath(import.meta.url),
"../../",
userTemplate.name
);

const write = (file: string, content?: string) => {
const targetPath = path.join(root, renameFiles[file] ?? file);
if (content) {
fs.writeFileSync(targetPath, content);
} else {
copy(path.join(templateDir, file), targetPath);
}
};
const files = fs.readdirSync(templateDir);
for (const file of files.filter((f) => f !== "package.json")) {
write(file);
}
const pkg = JSON.parse(
fs.readFileSync(path.join(templateDir, "package.json"), "utf-8")
);
pkg.name = packageName || getProjectName();
write("package.json", JSON.stringify(pkg, null, 2));
console.log(`\n${green("✔")} Created project in ${root}.`);
if (root !== cwd) {
console.log(`\n${green("✔")} To get started:`);
console.log(`\n cd ${root}`);
}
switch (manager) {
case "yarn":
console.log(` yarn`);
console.log(` yarn dev`);
break;
default:
console.log(` ${manager} install`);
console.log(` ${manager} run dev`);
break;
}
console.log();
}

init().catch((e) => {
console.error(e);
});
21 changes: 21 additions & 0 deletions packages/create-jwc/starter-vite-ts/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Jwc.js

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
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.
4 changes: 4 additions & 0 deletions packages/create-jwc/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.json",
"exclude": ["**/starter-*", "**/starter-*/**/*"]
}
21 changes: 21 additions & 0 deletions packages/reactively/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Jwc.js

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
21 changes: 21 additions & 0 deletions packages/runtime/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Jwc.js

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Loading

0 comments on commit 6bbae9d

Please sign in to comment.