@seayoo-web/scripts 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-web/scripts",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "scripts for seayoo web monorepos",
5
5
  "type": "module",
6
6
  "source": "index.ts",
@@ -20,8 +20,8 @@
20
20
  },
21
21
  "./node": {
22
22
  "types": "./types/node.d.ts",
23
- "require": "./dist/node.cjs",
24
- "default": "./dist/node.cjs"
23
+ "import": "./dist/node.js",
24
+ "default": "./dist/node.js"
25
25
  }
26
26
  },
27
27
  "engines": {
@@ -1,223 +0,0 @@
1
- "use strict";
2
- const child_process = require("child_process");
3
- const path = require("path");
4
- const fs = require("fs-extra");
5
- require("colors");
6
- const TemplateDir = "template";
7
- const InternalDir = "internal";
8
- const WorkspaceFile = "pnpm-workspace.yaml";
9
- const root = function() {
10
- let currentDir = process.cwd();
11
- while (currentDir !== path.parse(currentDir).root) {
12
- if (fs.existsSync(path.join(currentDir, WorkspaceFile))) {
13
- return currentDir;
14
- }
15
- currentDir = path.dirname(currentDir);
16
- }
17
- if (fs.existsSync(path.join(currentDir, "pnpm-workspace.yaml"))) {
18
- return currentDir;
19
- }
20
- throw new Error("Could not find repository root with pnpm-workspace.yaml".bgRed);
21
- }();
22
- async function getTemplates() {
23
- return await getRepos(TemplateDir);
24
- }
25
- async function getRepos(project) {
26
- const projectDir = path.join(root, project);
27
- const dirs = await fs.readdir(projectDir);
28
- const repos = dirs.filter((item) => fs.statSync(path.join(projectDir, item)).isDirectory());
29
- const descs = await Promise.all(repos.map((repo) => getRepoDesc(project, repo)));
30
- return repos.map((dir, index) => ({ id: dir, desc: descs[index] })).filter((item) => item.desc !== null);
31
- }
32
- async function getRepoDesc(project, dir) {
33
- const packageFile = path.join(root, project, dir, "package.json");
34
- if (!await fs.exists(packageFile)) {
35
- return null;
36
- }
37
- const content = await fs.readJson(packageFile, "utf8");
38
- return (content.description || "") + "";
39
- }
40
- async function getProjects(returnAll) {
41
- const rootPkgPath = path.join(root, WorkspaceFile);
42
- if (await fs.pathExists(rootPkgPath)) {
43
- const content = await fs.readFile(rootPkgPath, "utf8");
44
- const dirs = (content.match(/- "(?:.+?)\/*"/g) || []).map((t) => t.slice(3, -3));
45
- const names = await Promise.all(dirs.map(getProjectName));
46
- const projects = dirs.map((id, index) => ({ id, name: names[index] })).filter((project) => !project.name.includes("disabled"));
47
- return returnAll === true ? projects : projects.filter((project) => project.id !== InternalDir && project.id !== TemplateDir);
48
- }
49
- return [];
50
- }
51
- async function getProjectName(project) {
52
- const namef = path.join(project, ".name");
53
- if (await fs.exists(namef)) {
54
- const name = await fs.readFile(namef, "utf8");
55
- return name.trim().replace(/\n[\d\D]+/g, "");
56
- }
57
- return project;
58
- }
59
- async function copyTemplate(templateName, targetDir) {
60
- const templateSourceDir = path.join(root, TemplateDir, templateName);
61
- await fs.copy(templateSourceDir, targetDir, {
62
- filter: (src) => {
63
- return !src.includes("node_modules") && !src.includes(".git") && !src.endsWith(".local");
64
- }
65
- });
66
- }
67
- async function addProjectToWorkspace(project) {
68
- const rootWorkspacePath = path.join(root, WorkspaceFile);
69
- if (await fs.pathExists(rootWorkspacePath)) {
70
- let content = await fs.readFile(rootWorkspacePath, "utf8");
71
- if (!content.includes(`- "${project}/*"`)) {
72
- content += ` - "${project}/*"
73
- `;
74
- }
75
- await fs.writeFile(rootWorkspacePath, content);
76
- }
77
- }
78
- async function removeProjectFromWorkspace(project) {
79
- const rootWorkspacePath = path.join(root, WorkspaceFile);
80
- if (await fs.pathExists(rootWorkspacePath)) {
81
- const content = (await fs.readFile(rootWorkspacePath, "utf8")).replace(
82
- new RegExp(`\\n.*\\- "${project}\\/\\*"`),
83
- ""
84
- );
85
- await fs.writeFile(rootWorkspacePath, content);
86
- }
87
- }
88
- function getNowTime() {
89
- const now = /* @__PURE__ */ new Date();
90
- return `${now.getFullYear()}/${fillZ(now.getMonth() + 1)}/${fillZ(now.getDate())} ${fillZ(now.getHours())}:${fillZ(now.getMinutes())}`;
91
- }
92
- function fillZ(a) {
93
- return ("0" + a).slice(-2);
94
- }
95
- const MainBranchName = "main";
96
- const DeployTagPrefix = "deploy#";
97
- function converToDeployTagName(deployTo) {
98
- return `${DeployTagPrefix}${deployTo.toLowerCase().replace(/(?:^https?:\/\/|\/*$)/gi, "")}`;
99
- }
100
- async function execCmd(cmd, ignoreWarning = false) {
101
- return new Promise((resolve, reject) => {
102
- child_process.exec(cmd, { cwd: root, env: { ...process.env } }, (error, stdout, stderr) => {
103
- if (error || stderr && !ignoreWarning) {
104
- console.error(cmd, error, stderr);
105
- reject(`执行命令时出错: ${(error == null ? void 0 : error.message) || stderr}`);
106
- return;
107
- }
108
- resolve(stdout.trim());
109
- });
110
- });
111
- }
112
- async function getCommitInfo(command, mode, deployTo) {
113
- if (command !== "build" || mode === "preview" || mode === "prev") {
114
- return { hash: await getCommitHash(), logs: [] };
115
- }
116
- if (await hasUncommittedChanges()) {
117
- console.error(`在部署前需要提交所有代码!`.red);
118
- process.exit(1);
119
- }
120
- if (await getCurrentBranchName() !== MainBranchName) {
121
- console.error(`正式环境部署需要在 ${`${MainBranchName}分支`.bgRed} 操作!`.red);
122
- process.exit(1);
123
- }
124
- const unCommitChanges = await countUnsubmitChanges(MainBranchName);
125
- if (unCommitChanges > 0) {
126
- console.error("正式环境部署需要先将代码同步到服务器!".red, `发现 ${unCommitChanges} 个 commit 差异`.red);
127
- process.exit(1);
128
- }
129
- const [currentCommit, lastDeployTag] = await Promise.all([getCommitHash(), getLastDeployTag(deployTo)]);
130
- const commitLogs = await getCommitLogs(currentCommit, lastDeployTag, "./");
131
- return { hash: currentCommit, logs: commitLogs };
132
- }
133
- async function getLastDeployTag(deployTo) {
134
- await fetchTags();
135
- const deployTags = await getDeployTags();
136
- const tag = converToDeployTagName(deployTo);
137
- return deployTags.includes(tag) ? tag : "";
138
- }
139
- async function createPageDeployTag(page, deployTo, finderUser) {
140
- const tagName = converToDeployTagName(deployTo);
141
- const gitUser = await execCmd(`git config user.email`).catch(() => "");
142
- await execCmd(
143
- [`git tag -f ${tagName} -m "${getNowTime()} deployed by ${gitUser || finderUser}`, page ? `from ${page}` : ""].filter((c) => !!c).join(" ")
144
- );
145
- try {
146
- await execCmd(`git push origin -f ${tagName}`, true);
147
- } catch (e) {
148
- await execCmd(`git push origin --tags`, true);
149
- }
150
- }
151
- async function getCommitHash() {
152
- return (await execCmd("git rev-parse HEAD")).slice(0, 8);
153
- }
154
- async function getCurrentBranchName() {
155
- return await execCmd("git rev-parse --abbrev-ref HEAD");
156
- }
157
- async function fetchTags() {
158
- await execCmd("git fetch --tags", true);
159
- }
160
- async function getDeployTags() {
161
- const result = await execCmd("git tag");
162
- return result.split("\n").filter((tag) => tag.startsWith(DeployTagPrefix));
163
- }
164
- async function getCommitLogs(branchOrCommit, sinceCommit, codePath) {
165
- const cmd = [
166
- "git log",
167
- sinceCommit ? `${sinceCommit}..${branchOrCommit || "HEAD"}` : branchOrCommit || "",
168
- `--oneline --pretty=format:"[%cd][%h] %s" --date=short -n 60`,
169
- `-- ${codePath}`
170
- ].filter((f) => !!f).join(" ");
171
- const result = await execCmd(cmd);
172
- return result ? result.split("\n") : [];
173
- }
174
- async function hasUncommittedChanges() {
175
- const result = await execCmd("git status --porcelain");
176
- return result !== "";
177
- }
178
- async function countUnsubmitChanges(branch) {
179
- const result = await execCmd(`git rev-list --count ${branch} "^origin/${branch}"`);
180
- return parseInt(result, 10);
181
- }
182
- async function checkGitStatusBeforeDestory() {
183
- if (await hasUncommittedChanges()) {
184
- console.error(`在销毁前需要提交所有代码!`.red);
185
- process.exit(1);
186
- }
187
- if (await getCurrentBranchName() !== MainBranchName) {
188
- console.error(`销毁操作需要在 ${`${MainBranchName}分支`.bgRed} 进行!`.red);
189
- process.exit(1);
190
- }
191
- const unCommitChanges = await countUnsubmitChanges(MainBranchName);
192
- if (unCommitChanges > 0) {
193
- console.error("销毁操作需要先将代码同步到服务器!".red, `发现 ${unCommitChanges} 个 commit 差异`.red);
194
- process.exit(1);
195
- }
196
- }
197
- async function createBackupTag(action, info) {
198
- const tagName = `backup#${action}-${info}`;
199
- const gitUser = await execCmd(`git config user.email`).catch(() => "");
200
- await execCmd(`git tag -f ${tagName} -m "${getNowTime()} destroyed by ${gitUser || "unknown"}`);
201
- try {
202
- await execCmd(`git push origin -f ${tagName}`, true);
203
- } catch (e) {
204
- await execCmd(`git push origin --tags`, true);
205
- }
206
- }
207
- async function submitAllDeletionChanges(message) {
208
- const branch = await getCurrentBranchName();
209
- await execCmd(`git add --all :/ && git commit -m "${message}" && git push origin ${branch}`, true);
210
- }
211
- exports.addProjectToWorkspace = addProjectToWorkspace;
212
- exports.checkGitStatusBeforeDestory = checkGitStatusBeforeDestory;
213
- exports.copyTemplate = copyTemplate;
214
- exports.createBackupTag = createBackupTag;
215
- exports.createPageDeployTag = createPageDeployTag;
216
- exports.getCommitInfo = getCommitInfo;
217
- exports.getNowTime = getNowTime;
218
- exports.getProjects = getProjects;
219
- exports.getRepos = getRepos;
220
- exports.getTemplates = getTemplates;
221
- exports.removeProjectFromWorkspace = removeProjectFromWorkspace;
222
- exports.root = root;
223
- exports.submitAllDeletionChanges = submitAllDeletionChanges;
package/dist/index.cjs.js DELETED
@@ -1,257 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const node_path = require("node:path");
4
- const vite = require("vite");
5
- const finder = require("@seayoo-web/finder");
6
- const vitePlugin = require("@sentry/vite-plugin");
7
- const legacy = require("@vitejs/plugin-legacy");
8
- const vue = require("@vitejs/plugin-vue");
9
- const vueDevTools = require("vite-plugin-vue-devtools");
10
- const fs = require("fs");
11
- require("colors");
12
- const git = require("./git-6CgysH-T.cjs");
13
- const skipFormatting = require("@vue/eslint-config-prettier/skip-formatting");
14
- const eslintConfigTypescript = require("@vue/eslint-config-typescript");
15
- const eslintPluginImport = require("eslint-plugin-import");
16
- const pluginVue = require("eslint-plugin-vue");
17
- const nestingPlugin = require("postcss-nesting");
18
- function defineLibBuildConfig(option) {
19
- return vite.defineConfig({
20
- build: {
21
- outDir: (option == null ? void 0 : option.outDir) || "dist",
22
- lib: {
23
- entry: node_path.join(process.cwd(), (option == null ? void 0 : option.rootEntry) || "index.ts"),
24
- formats: ["es"],
25
- fileName: (format, entryName) => {
26
- return format === "es" ? `${entryName}.js` : `${entryName}.${format}.js`;
27
- }
28
- },
29
- rollupOptions: {
30
- external: (option == null ? void 0 : option.external) || [/^@seayoo-web\/(?:request|utils)/]
31
- }
32
- }
33
- });
34
- }
35
- const EnvPrefix = "SY_";
36
- function getBuildEnv(command, mode) {
37
- const envs = vite.loadEnv(mode, process.cwd(), EnvPrefix);
38
- const envConfig = {
39
- command,
40
- stamp: git.getNowTime(),
41
- page: "",
42
- mode: "",
43
- deployUser: "",
44
- deployKey: ""
45
- };
46
- envConfig.mode = mode || "preview";
47
- const d = `${EnvPrefix}DEPLOY_DEBUG`;
48
- const t = `${EnvPrefix}DEPLOY_TO`;
49
- const s = `${EnvPrefix}SENTRY_AUTH_TOKEN`;
50
- const u = `${EnvPrefix}DEPLOY_USER`;
51
- const k = `${EnvPrefix}DEPLOY_KEY`;
52
- const execDir = process.cwd().replace(/\\/g, "/").split("/").slice(-2).join("/");
53
- const packageFile = node_path.join(process.cwd(), "./package.json");
54
- if (!fs.existsSync(packageFile)) {
55
- console.error("执行代码有误,没有找到 package.json".red);
56
- process.exit(1);
57
- }
58
- const packageJson = JSON.parse(fs.readFileSync(packageFile, { encoding: "utf-8" }).toString());
59
- if (!packageJson || !packageJson.name || packageJson.name !== `@${execDir}`) {
60
- console.error(`工程 package.json/name 属性设置错误,应该跟目录保持一致(@${execDir}),请先调整`.red);
61
- process.exit(1);
62
- }
63
- envConfig.page = execDir;
64
- if (envConfig.command === "build") {
65
- if (process.env.NODE_ENV !== "production") {
66
- console.error("部署时需要设置 NODE_ENV 为 production,请检查环境变量设置".red);
67
- process.exit(1);
68
- }
69
- envConfig.deployTo = (envs[t] || "").replace(/(?:^https?:\/\/|\/*$)/gi, "").replace(/^(.)/, "https://$1");
70
- envConfig.deployUser = envs[u];
71
- envConfig.deployKey = envs[k];
72
- envConfig.deployDebug = envs[d] === "1" || envs[d] === "y" || envs[d] === "true";
73
- if (!envConfig.deployTo) {
74
- console.error(`缺少 ${t.bgRed} 设置,请在 .env.${mode} 中配置`.red);
75
- process.exit(1);
76
- }
77
- if (!envConfig.deployUser || !envConfig.deployKey) {
78
- console.error(`缺少 ${u.bgRed} / ${k.bgRed} 设置,请在 .env.local 配置`.red);
79
- process.exit(1);
80
- }
81
- envConfig.sentryAuthToken = envs[s];
82
- if (!envConfig.sentryAuthToken) {
83
- console.warn(`尚未设置 ${s.red},推送 sourcemap 到 sentry 的功能将无效`);
84
- }
85
- }
86
- return envConfig;
87
- }
88
- function transformEnvs(envs) {
89
- return Object.entries(envs).reduce(
90
- function(result, [key, value]) {
91
- result[key] = JSON.stringify(value);
92
- return result;
93
- },
94
- {}
95
- );
96
- }
97
- function htmlInjectPlugin(data) {
98
- return {
99
- name: "html-inject-plugin",
100
- transformIndexHtml: {
101
- order: "pre",
102
- handler: (html) => html.replace(/%\s*(.*?)\s*%/g, (match, p1) => data[p1] ?? match).replace(/[\r\n]{2,}/g, "\n").replace(/(?:^[\s\r\n]*|[\s\r\n]*$)/g, "")
103
- }
104
- };
105
- }
106
- function definePageBuildConfig(option) {
107
- return vite.defineConfig(async function(viteEnvs) {
108
- const { command, mode } = viteEnvs;
109
- const envs = getBuildEnv(command, mode);
110
- const gitInfo = await git.getCommitInfo(command, mode, envs.deployTo || "");
111
- const isProductMode = mode === "production" || mode === "prod";
112
- const {
113
- plugins = [],
114
- define = {},
115
- build = {},
116
- resolve = {},
117
- server = {},
118
- sentry = {},
119
- ...optionReset
120
- } = option || {};
121
- const { alias, ...resolveReset } = resolve || {};
122
- return {
123
- base: "./",
124
- build: {
125
- emptyOutDir: true,
126
- outDir: node_path.join(process.cwd(), "./dist"),
127
- assetsDir: "assets",
128
- reportCompressedSize: false,
129
- sourcemap: command === "build" && !!envs.sentryAuthToken,
130
- ...build
131
- },
132
- plugins: [
133
- vue(),
134
- vueDevTools(),
135
- legacy({
136
- targets: ["defaults", "ie >= 10", "chrome 52"],
137
- additionalLegacyPolyfills: ["regenerator-runtime/runtime"],
138
- renderLegacyChunks: true
139
- }),
140
- htmlInjectPlugin({
141
- BUILD_TIME: envs.stamp,
142
- BUILD_MODE: envs.mode,
143
- BUILD_VERSION: gitInfo.hash
144
- }),
145
- ...plugins,
146
- command === "build" && envs.deployTo ? finder.viteDeployPlugin({
147
- deployTo: envs.deployTo,
148
- user: envs.deployUser,
149
- key: envs.deployKey,
150
- debug: envs.deployDebug,
151
- commitLogs: isProductMode && gitInfo.logs.length > 0 ? "\n" + gitInfo.logs.join("\n") : void 0,
152
- onFinished() {
153
- if (isProductMode) {
154
- git.createPageDeployTag(envs.page, envs.deployTo || "", envs.deployUser);
155
- }
156
- }
157
- }) : null,
158
- command === "build" && envs.sentryAuthToken ? vitePlugin.sentryVitePlugin({
159
- authToken: envs.sentryAuthToken,
160
- org: "sentry",
161
- url: sentry.url || "https://sentry.seayoo.com/",
162
- project: sentry.project || "gamer-fe"
163
- }) : null
164
- ],
165
- define: transformEnvs({
166
- BUILD_TIME: envs.stamp,
167
- BUILD_MODE: envs.mode,
168
- ...envs,
169
- ...define
170
- }),
171
- resolve: {
172
- alias: {
173
- "@": node_path.join(process.cwd(), "./src"),
174
- ...alias
175
- },
176
- extensions: [".mts", ".mjs", ".ts", ".js"],
177
- // allowImportingTsExtensions: true,
178
- ...resolveReset
179
- },
180
- server: {
181
- open: true,
182
- ...server
183
- },
184
- ...optionReset,
185
- // envPrefix 不允许覆盖
186
- envPrefix: EnvPrefix
187
- };
188
- });
189
- }
190
- const vueEslintConfig = [
191
- pluginVue.configs["flat/essential"],
192
- eslintConfigTypescript.vueTsConfigs.recommended,
193
- skipFormatting,
194
- {
195
- files: ["**/*.vue"],
196
- rules: {
197
- "vue/multi-word-component-names": "off"
198
- }
199
- }
200
- ];
201
- const importEslintConfig = [
202
- eslintPluginImport.flatConfigs.recommended,
203
- {
204
- rules: {
205
- "import/no-unresolved": "off",
206
- "import/named": "off",
207
- "import/namespace": "off",
208
- "import/no-named-as-default": "off",
209
- "import/no-named-as-default-member": "off",
210
- "import/export": ["error"],
211
- "import/order": [
212
- "error",
213
- {
214
- groups: ["builtin", "external", "internal", "parent", "sibling", "index", "type"],
215
- pathGroups: [
216
- {
217
- pattern: "@/**",
218
- group: "internal"
219
- }
220
- ],
221
- "newlines-between": "always",
222
- alphabetize: {
223
- order: "asc",
224
- caseInsensitive: true
225
- }
226
- }
227
- ]
228
- }
229
- }
230
- ];
231
- const stylelintConfig = {
232
- extends: ["stylelint-config-standard", "stylelint-config-recess-order"],
233
- overrides: [
234
- {
235
- files: ["**/*.vue", "**/*.html"],
236
- customSyntax: "postcss-html"
237
- }
238
- ],
239
- rules: {}
240
- };
241
- const postcssConfig = {
242
- plugins: [nestingPlugin]
243
- };
244
- Object.defineProperty(exports, "defineConfigWithVueTs", {
245
- enumerable: true,
246
- get: () => eslintConfigTypescript.defineConfigWithVueTs
247
- });
248
- exports.EnvPrefix = EnvPrefix;
249
- exports.defineLibBuildConfig = defineLibBuildConfig;
250
- exports.definePageBuildConfig = definePageBuildConfig;
251
- exports.getBuildEnv = getBuildEnv;
252
- exports.htmlInjectPlugin = htmlInjectPlugin;
253
- exports.importEslintConfig = importEslintConfig;
254
- exports.postcssConfig = postcssConfig;
255
- exports.stylelintConfig = stylelintConfig;
256
- exports.transformEnvs = transformEnvs;
257
- exports.vueEslintConfig = vueEslintConfig;
package/dist/node.cjs DELETED
@@ -1,278 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const fs = require("fs");
4
- require("colors");
5
- const path = require("path");
6
- const commander = require("commander");
7
- const fs$1 = require("fs-extra");
8
- const inquirer = require("inquirer");
9
- const ora = require("ora");
10
- const git = require("./git-6CgysH-T.cjs");
11
- const commitRE = /^(?:revert: )?(?:feat|fix|docs|style|refactor|test|chore|debug|tweak|improve)(?:\(.+\))?: .{1,100}/;
12
- function checkCommit() {
13
- const msgPath = process.argv[2];
14
- const msg = fs.readFileSync(msgPath, "utf-8").trim();
15
- if (!commitRE.test(msg) && !msg.startsWith("Merge branch")) {
16
- console.error(`ERROR!【提交的 Commit 信息格式错误,请注意使用正确的类型前缀!】`.red);
17
- process.exit(1);
18
- }
19
- }
20
- const program$1 = new commander.Command();
21
- program$1.version("1.0.0").argument("<target>");
22
- function runCreateScript() {
23
- program$1.parse(process.argv);
24
- }
25
- async function initRepoQuestions$1() {
26
- const projects = await git.getProjects();
27
- const templates = await git.getTemplates();
28
- return [
29
- {
30
- type: "list",
31
- name: "project",
32
- message: "选择项目:",
33
- choices: projects.map((project) => ({
34
- name: `${project.id} ${project.name}`,
35
- short: project.id,
36
- value: project.id
37
- }))
38
- },
39
- {
40
- type: "list",
41
- name: "template",
42
- message: "选择模板:",
43
- choices: templates.map((template) => ({
44
- name: `${template.id} ${template.desc}`,
45
- short: template.id,
46
- value: template.id
47
- }))
48
- },
49
- {
50
- type: "input",
51
- name: "repoName",
52
- message: "仓库名称:",
53
- validate: (input) => {
54
- if (/^[a-z0-9-]+$/.test(input)) return true;
55
- return "仓库名称只能包含小写字母、数字和中横线";
56
- }
57
- },
58
- {
59
- type: "input",
60
- name: "description",
61
- message: "仓库描述:",
62
- default: ""
63
- }
64
- ];
65
- }
66
- async function initProjectQuestions$1() {
67
- const projects = (await git.getProjects(true)).map((project) => project.id);
68
- return [
69
- {
70
- type: "input",
71
- name: "project",
72
- message: "项目 ID:",
73
- validate: (input) => {
74
- if (!/^[a-zA-Z0-9-_]+$/.test(input)) {
75
- return "项目名称只能包含字母、数字、下划线和横线";
76
- }
77
- if (projects.includes(input)) {
78
- return "项目已经存在,请检查";
79
- }
80
- return true;
81
- }
82
- },
83
- {
84
- type: "input",
85
- name: "name",
86
- message: "中文名称:",
87
- validate: (input) => {
88
- if (!input) {
89
- return "中文名称不能为空";
90
- }
91
- return true;
92
- }
93
- }
94
- ];
95
- }
96
- async function updatePackageFiles(targetDir, answers) {
97
- await Promise.all([
98
- // 初始化 package.json
99
- updatePackageJson(targetDir, answers),
100
- // 初始化样例文件
101
- initSampleFiles(targetDir)
102
- ]);
103
- }
104
- async function updatePackageJson(targetDir, answers) {
105
- const pkgPath = path.join(targetDir, "package.json");
106
- if (await fs$1.pathExists(pkgPath)) {
107
- const pkg = await fs$1.readJson(pkgPath);
108
- pkg.name = `@${answers.project}/${answers.repoName}`;
109
- pkg.description = answers.description || pkg.description;
110
- pkg.version = "1.0.0";
111
- await fs$1.writeJson(pkgPath, pkg, { spaces: 2 });
112
- }
113
- }
114
- async function initSampleFiles(targetDir) {
115
- const items = await fs$1.readdir(targetDir);
116
- const files = items.filter(
117
- (item) => !fs$1.statSync(path.join(targetDir, item)).isDirectory() && item.endsWith(".sample")
118
- );
119
- for (const filename of files) {
120
- const sample = path.join(targetDir, filename);
121
- if (await fs$1.pathExists(sample)) {
122
- await fs$1.writeFile(path.join(targetDir, filename.replace(/\.sample$/, "")), await fs$1.readFile(sample));
123
- fs$1.unlink(sample);
124
- }
125
- }
126
- }
127
- async function startCreateJob$1(target) {
128
- if (target === "project") {
129
- await createProject();
130
- } else {
131
- await createRepo();
132
- }
133
- }
134
- async function createProject() {
135
- const questions = await initProjectQuestions$1();
136
- const answers = await inquirer.prompt(questions);
137
- const spinner = ora("正在创建项目...").start();
138
- const projectDir = path.join(git.root, answers.project);
139
- await fs$1.mkdir(projectDir);
140
- await fs$1.writeFile(path.join(projectDir, ".name"), answers.name);
141
- await git.addProjectToWorkspace(answers.project);
142
- spinner.succeed("项目创建成功!".green);
143
- }
144
- async function createRepo() {
145
- const questions = await initRepoQuestions$1();
146
- const answers = await inquirer.prompt(questions);
147
- const spinner = ora("正在创建仓库...").start();
148
- const projectDir = path.join(git.root, answers.project);
149
- spinner.text = "检查目录...";
150
- if (!await fs$1.pathExists(projectDir)) {
151
- fs$1.mkdirSync(projectDir, { recursive: true });
152
- }
153
- const targetDir = path.join(git.root, answers.project, answers.repoName);
154
- if (await fs$1.pathExists(targetDir)) {
155
- spinner.fail(`错误:目录(${`${answers.project}/${answers.repoName}`})已存在`.red);
156
- process.exit(1);
157
- }
158
- spinner.text = "复制模板文件...";
159
- await git.copyTemplate(answers.template, targetDir);
160
- spinner.text = "更新 package.json...";
161
- await updatePackageFiles(targetDir, answers);
162
- spinner.succeed("仓库创建成功!".green);
163
- console.log("\n接下来你可以:");
164
- console.log(`cd ${answers.project}/${answers.repoName}`.cyan);
165
- console.log("pnpm i".cyan);
166
- console.log("pnpm dev".cyan);
167
- }
168
- program$1.action(startCreateJob$1);
169
- const program = new commander.Command();
170
- program.version("1.0.0").argument("<target>");
171
- function runDestoryScript() {
172
- program.parse(process.argv);
173
- }
174
- async function startCreateJob(target) {
175
- if (target === "project") {
176
- await destroyProject();
177
- } else {
178
- await destroyRepo();
179
- }
180
- }
181
- async function initProjectQuestions() {
182
- const projects = await git.getProjects();
183
- return [
184
- {
185
- type: "list",
186
- name: "project",
187
- message: "删除项目:",
188
- choices: projects.map((project) => ({
189
- name: `${project.id} ${project.name}`,
190
- short: project.id,
191
- value: project.id
192
- }))
193
- },
194
- {
195
- type: "confirm",
196
- name: "confirm",
197
- message: function(answers) {
198
- return `确认删除整个 ${answers.project} 项目 ?`;
199
- }
200
- }
201
- ];
202
- }
203
- async function destroyProject() {
204
- await git.checkGitStatusBeforeDestory();
205
- const questions = await initProjectQuestions();
206
- const answers = await inquirer.prompt(questions);
207
- if (!answers.confirm) {
208
- process.exit(0);
209
- }
210
- const spinner = ora("正在创建 Backup Tag...").start();
211
- await git.createBackupTag("project", answers.project);
212
- spinner.text = "开始清理文件...";
213
- const projectDir = path.join(git.root, answers.project);
214
- await fs$1.removeSync(projectDir);
215
- spinner.text = "调整配置文件...";
216
- await git.removeProjectFromWorkspace(answers.project);
217
- spinner.text = "提交代码中...";
218
- await git.submitAllDeletionChanges(`chore: destory project ${answers.project}`);
219
- spinner.succeed("项目已经销毁!".green);
220
- }
221
- async function initRepoQuestions() {
222
- const projects = await git.getProjects();
223
- return [
224
- {
225
- type: "list",
226
- name: "project",
227
- message: "所在项目:",
228
- choices: projects.map((project) => ({
229
- name: `${project.id} ${project.name}`,
230
- short: project.id,
231
- value: project.id
232
- }))
233
- },
234
- {
235
- type: "list",
236
- name: "page",
237
- message: "删除页面:",
238
- choices: async function(answers) {
239
- const repos = await git.getRepos(answers.project);
240
- if (repos.length === 0) {
241
- throw new Error("工程不含有任意有效 Repo!操作中止");
242
- }
243
- return repos.map((repo) => ({
244
- name: `${repo.id} ${repo.desc || ""}`,
245
- short: repo.id,
246
- value: repo.id
247
- }));
248
- }
249
- },
250
- {
251
- type: "confirm",
252
- name: "confirm",
253
- message: async function(answers) {
254
- return `确认删除页面 ${answers.project}/${answers.page} ?`;
255
- }
256
- }
257
- ];
258
- }
259
- async function destroyRepo() {
260
- await git.checkGitStatusBeforeDestory();
261
- const questions = await initRepoQuestions();
262
- const answers = await inquirer.prompt(questions);
263
- if (!answers.confirm) {
264
- process.exit(0);
265
- }
266
- const spinner = ora("正在创建 Backup Tag...").start();
267
- await git.createBackupTag("page", `${answers.project}/${answers.page}`);
268
- spinner.text = "开始清理文件...";
269
- const pageDir = path.join(git.root, answers.project, answers.page);
270
- await fs$1.removeSync(pageDir);
271
- spinner.text = "提交代码中...";
272
- await git.submitAllDeletionChanges(`chore: destory page ${answers.project}/${answers.page}`);
273
- spinner.succeed("页面已经销毁!".green);
274
- }
275
- program.action(startCreateJob);
276
- exports.checkCommit = checkCommit;
277
- exports.runCreateScript = runCreateScript;
278
- exports.runDestoryScript = runDestoryScript;
File without changes