Skip to content

Commit

Permalink
⚙️ Chore(configs/tsup,cli init,copyFile): fix coping files by tsup,…
Browse files Browse the repository at this point in the history
… change `init` cli cmd, add error handler for copyfile
  • Loading branch information
INeedJobToStartWork committed Jun 15, 2024
1 parent bc8d608 commit 5c0049a
Show file tree
Hide file tree
Showing 11 changed files with 103 additions and 116 deletions.
2 changes: 1 addition & 1 deletion packages/myplop/config/tsuprc/tsup.base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default defineConfig({
esbuildPlugins: [
copy({
assets: [
{ from: "./src/templates/**", to: "./configs" }
{ from: "./src/templates/**", to: "./templates" }
// { from: "./package.json", to: "./package.json" }
]
})
Expand Down
1 change: 1 addition & 0 deletions packages/myplop/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"@clack/prompts": "^0.7.0",
"chalk": "^5.3.0",
"commander": "^11.1.0",
"oh-my-error": "^1.0.0",
"zod": "^3.23.8"
},
"devDependencies": {
Expand Down
27 changes: 15 additions & 12 deletions packages/myplop/src/cli/init/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import { program } from "commander";
import * as prompter from "@clack/prompts";
import chalk from "chalk";
import { myErrorCatcher, myErrorWrapper } from "oh-my-error";

Check warning on line 4 in packages/myplop/src/cli/init/index.ts

View workflow job for this annotation

GitHub Actions / Deploy

'myErrorCatcher' is defined but never used

Check warning on line 4 in packages/myplop/src/cli/init/index.ts

View workflow job for this annotation

GitHub Actions / Deploy

'myErrorWrapper' is defined but never used
import logging from "@/utils/logging";
import { existsSync } from "fs";

Check warning on line 6 in packages/myplop/src/cli/init/index.ts

View workflow job for this annotation

GitHub Actions / Deploy

'existsSync' is defined but never used

program
.command("init")
.description("Initialize plopfile")
.option("-D, --DEBUG", "output extra debugging (default: false)", false)
.option("-D, --DEBUG", "output extra debugging", false)
.action(({ DEBUG }) => {
process.env.DEBUG = `${DEBUG}`.toUpperCase();
// process.env.DEBUG = "TRUE";

prompter
.group(
Expand All @@ -20,20 +24,19 @@ program
message: "What do you want to initialize?",
initialValue: "app",
options: [
{ label: "App", value: "app", hint: "Initialize app - required to work app" },
{ label: "Config", value: "config" },
{ label: "Profile", value: "profile", hint: "Initialize profile at config" },
{ label: "Component", value: "component", hint: "Initialize component" }
{ label: "App", value: "app.ts", hint: "Initialize app - required to work app" },
{ label: "Config", value: "config.ts" },
{ label: "Profile", value: "profile.ts", hint: "Initialize profile at config" },
{ label: "Component", value: "component.ts", hint: "Initialize component" }
]
}),
outro: () => {
prompter.outro(chalk.bgGreen("Choosed correctly!"));
},
loadModule: async ({ results }) => {
await import(/* webpackMode: "eager" */ `./options/${results.choice}`).catch(err => {
console.error("Module not found - probably file with option doesnt exist.", err);
process.exit(0);
});
try {
await import(`./options/${results.choice}`);
} catch (err) {
logging.error("Module not found - probably file with option doesnt exist.", err);
process.exit(1);
}
}
},
{
Expand Down
93 changes: 21 additions & 72 deletions packages/myplop/src/cli/init/options/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,84 +2,33 @@ import * as prompter from "@clack/prompts";
import chalk from "chalk";
import { resolve } from "path";
import { copyFiles, existFilePrompt } from "@/function";
// import { spawnSync } from "child_process";

const installerAction = () => ({
ConfirmProcess: async () => {
prompter.note(`Initialize app at: \n'${chalk.blue(process.env.CONFIGPATH)}'`, chalk.bgGreen(" ACTIONS "));
const continueAction = await prompter.confirm({ message: "Do you want to continue?" });
if (prompter.isCancel(continueAction) || !continueAction) {
prompter.cancel("Canceled.");
process.exit(0);
}
},
// ConfirmProcess: await (async () => {
// prompter.note(`Initialize app at: \n'${chalk.blue(process.env.CONFIGPATH)}'`, chalk.bgGreen(" ACTIONS "));
// const continueAction = await prompter.confirm({ message: "Do you want to continue?" });
// if (prompter.isCancel(continueAction) || !continueAction) {
// prompter.cancel("Canceled.");
// process.exit(0);
// }
// })(),
Installation: async () => {
const destination = process.env.CONFIGPATH;
const templatePath = resolve(process.env.PACKAGEPATH, `./templates/app`);

const InstallingProcess = prompter.spinner();
InstallingProcess.start("App is installing...");
await existFilePrompt(destination);
copyFiles(templatePath, destination, true).catch(err => {
InstallingProcess.stop(`❌ error \n${err}`, 1);
// throw new Error(`${chalk.bgRed(" ERROR ")} Something went wrong induring coping files.\n${err}`);
});
InstallingProcess.stop("✅", 0);
}
});

const configAction = async () => {
const generateCurrently = () => {
copyFiles(resolve(process.env.PACKAGEPATH, `./templates/config/global`), process.env.USERPATH, true).catch(err => {
throw err;
});
};
const generateNewRepo = () => {
// spawnSync("git", ["init"], { cwd: process.env.USERPATH });
};

prompter.note(`Global config it's place where you gonna import/export your config.`, "General CONFIG");

const generateType = await prompter.select({
message: "Where do you want to generate it?",
options: [
{ label: "New Repo", value: "newRepo" },
{ label: "Currently exist repo", value: "currently" }
]
});

if (generateType == "currently") generateCurrently();
generateNewRepo();
};

prompter
.group(
{
intro: () => {
prompter.intro(chalk.bgCyan(" App "));
ConfirmProcess: async () => {
prompter.note(`Initialize app at: \n'${chalk.blue(process.env.CONFIGPATH)}'`, chalk.bgGreen(" ACTIONS "));
const continueAction = await prompter.confirm({ message: "Do you want to continue?" });
if (prompter.isCancel(continueAction) || !continueAction) {
prompter.cancel("Canceled.");
process.exit(0);
}
},
typeOfAction: async () =>
prompter.select({
message: "Select action ",
initialValue: "app",
options: [
{ label: "Installation", value: "installation", hint: "required to work properly" },
{ label: "General Config", value: "generalConfig", hint: "Uses github repo to store data" }
]
}),
generation: async ({ results }) => {
if (results.typeOfAction === "installation") await installerAction();
await configAction();
Installation: async () => {
const destination = process.env.CONFIGPATH!;
const templatePath = resolve(process.env.PACKAGEPATH!, "./templates/app/installation/");

const InstallingProcess = prompter.spinner();
InstallingProcess.start("App is installing...");
await existFilePrompt(destination);
const [data, isError] = copyFiles(templatePath, destination, true);
if (isError) {
InstallingProcess.stop(`❌ Error: ${data.message?.user}`, 1);
process.exit(1);
}
InstallingProcess.stop("✅", 0);
},
outro: () => {
outro: async () => {

Check warning on line 31 in packages/myplop/src/cli/init/options/app.ts

View workflow job for this annotation

GitHub Actions / Deploy

Async method 'outro' has no 'await' expression
prompter.outro(chalk.bgGreen(" App has been installed! "));
}
},
Expand Down
9 changes: 5 additions & 4 deletions packages/myplop/src/cli/init/options/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,11 @@ prompter
const InstallingProcess = prompter.spinner();
InstallingProcess.start("App is installing...");
await existFilePrompt(destination);
copyFiles(templatePath, destination, true).catch(err => {
InstallingProcess.stop(`❌ error \n${err}`, 1);
// throw new Error(`${chalk.bgRed(" ERROR ")} Something went wrong induring coping files.\n${err}`);
});
const [data, isError] = copyFiles(templatePath, destination, true);
if (isError) {
InstallingProcess.stop(`❌ Error: ${data.message?.user}`, 1);
process.exit(1);
}
InstallingProcess.stop("✅", 0);
},
outro: () => {
Expand Down
4 changes: 2 additions & 2 deletions packages/myplop/src/function/checkSystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { platform } from "os";

type System = "linux" | "mac" | "other" | "windows";

export const checkSystem = (): System => {
export const checkSystem: System = (() => {
const system = platform();
if (system == "win32") {
return "windows";
Expand All @@ -14,5 +14,5 @@ export const checkSystem = (): System => {
return "linux";
}
return "other";
};
})();
export default checkSystem;
2 changes: 1 addition & 1 deletion packages/myplop/src/function/configPath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { checkSystem } from ".";
import { join } from "path";

export const configPath = () => {
const userSystem = checkSystem();
const userSystem = checkSystem;
if (userSystem == "windows") {
return join(process.env.APPDATA, "MyPlop");
}
Expand Down
19 changes: 9 additions & 10 deletions packages/myplop/src/function/dialogs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@ import chalk from "chalk";
import { existsSync } from "fs";

export const existFilePrompt = async (destination: string): Promise<void> => {
if (existsSync(destination)) {
console.log(chalk.bgBlue("Files already exists."));
const overwrite = await prompter.confirm({
message: "Overwrite Folders/Files?",
initialValue: false
});
if (prompter.isCancel(overwrite) || !overwrite) {
prompter.cancel("Dont overwrite file.");
process.exit(0);
}
if (!existsSync(destination)) return;
console.log(chalk.bgBlue("Files already exists."));
const overwrite = await prompter.confirm({
message: "Overwrite Folders/Files?",
initialValue: false
});
if (prompter.isCancel(overwrite) || !overwrite) {
prompter.cancel("Dont overwrite file.");
process.exit(0);
}
};
33 changes: 29 additions & 4 deletions packages/myplop/src/function/fileOperations.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,41 @@
import logging from "@/utils/logging";
import { copyFileSync, existsSync, mkdirSync, readdirSync } from "fs";
import type { TFunctionReturn, TMyErrorList } from "oh-my-error";
import { myErrorWrapper } from "oh-my-error";
import { join } from "path";

const copyFiles = async (source: string, target: string, emptyDirs = true): Promise<void> =>
new Promise(() => {
if (!existsSync(target)) mkdirSync(target);
const MyErrorList = {
CANT_MKDIR: {
code: "CP001",
hint: {},
message: { user: "Can't make dir" }
},
CANT_COPY_FILE: {
code: "CP002",
hint: {},
message: { user: "Can't Copy File" }
}
} as const satisfies TMyErrorList;

const copyFiles = (source: string, target: string, emptyDirs = true): TFunctionReturn<void> => {
if (!existsSync(target)) {
const [, isError] = myErrorWrapper(mkdirSync)(target);
if (isError) return [MyErrorList.CANT_MKDIR, true];
}

const [, isError] = myErrorWrapper(() => {
readdirSync(source, { withFileTypes: true }).forEach(file => {
logging.debug("File info: ", file);
const curSource = join(source, file.name);
if (file.isDirectory()) copyFiles(curSource, join(target, file.name), emptyDirs);
else copyFileSync(curSource, join(target, file.name));
});
});
})();
if (isError) return [MyErrorList.CANT_COPY_FILE, true];

// ERROR HANDLING DOKONCZ

return [, false];

Check warning on line 38 in packages/myplop/src/function/fileOperations.ts

View workflow job for this annotation

GitHub Actions / Deploy

Unexpected comma in middle of array
};

export { copyFiles };
13 changes: 7 additions & 6 deletions packages/myplop/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,29 @@ import chalk from "chalk";
import { program } from "commander";

import path from "path";
const DIRNAME = path.resolve();
import { fileURLToPath } from "url";
import logging from "./utils/logging";

process.env.OS = checkSystem();
process.env.OS = checkSystem;
process.env.USERPATH = process.cwd();
process.env.PACKAGEPATH = DIRNAME;
process.env.PACKAGEPATH = path.dirname(fileURLToPath(import.meta.url));
process.env.CONFIGPATH = configPath();

if (process.env.OS != "windows") {
console.log(chalk.bgRed(" ERROR "), "Currently Version support only Windows - Sorry");
logging.log(chalk.bgRed(" ERROR "), "Currently Version support only Windows - Sorry");
process.exit(1);
}

declare global {
module NodeJS {
// @ts-expect-error - ProcessEnv is default defined but we want to override it
export type ProcessEnv = Record<string, unknown> & {
OS: ReturnType<typeof checkSystem>;
OS: typeof checkSystem;
PACKAGEPATH: string;
CONFIGPATH: string;
USERPATH: string;
};
}
}

program.parse();
program.parse(process.argv);
16 changes: 12 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 5c0049a

Please sign in to comment.