@seayoo-web/scripts 1.0.7 → 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.
@@ -0,0 +1,224 @@
1
+ import { exec } from "child_process";
2
+ import path from "path";
3
+ import fs from "fs-extra";
4
+ import "colors";
5
+ const TemplateDir = "template";
6
+ const InternalDir = "internal";
7
+ const WorkspaceFile = "pnpm-workspace.yaml";
8
+ const root = function() {
9
+ let currentDir = process.cwd();
10
+ while (currentDir !== path.parse(currentDir).root) {
11
+ if (fs.existsSync(path.join(currentDir, WorkspaceFile))) {
12
+ return currentDir;
13
+ }
14
+ currentDir = path.dirname(currentDir);
15
+ }
16
+ if (fs.existsSync(path.join(currentDir, "pnpm-workspace.yaml"))) {
17
+ return currentDir;
18
+ }
19
+ throw new Error("Could not find repository root with pnpm-workspace.yaml".bgRed);
20
+ }();
21
+ async function getTemplates() {
22
+ return await getRepos(TemplateDir);
23
+ }
24
+ async function getRepos(project) {
25
+ const projectDir = path.join(root, project);
26
+ const dirs = await fs.readdir(projectDir);
27
+ const repos = dirs.filter((item) => fs.statSync(path.join(projectDir, item)).isDirectory());
28
+ const descs = await Promise.all(repos.map((repo) => getRepoDesc(project, repo)));
29
+ return repos.map((dir, index) => ({ id: dir, desc: descs[index] })).filter((item) => item.desc !== null);
30
+ }
31
+ async function getRepoDesc(project, dir) {
32
+ const packageFile = path.join(root, project, dir, "package.json");
33
+ if (!await fs.exists(packageFile)) {
34
+ return null;
35
+ }
36
+ const content = await fs.readJson(packageFile, "utf8");
37
+ return (content.description || "") + "";
38
+ }
39
+ async function getProjects(returnAll) {
40
+ const rootPkgPath = path.join(root, WorkspaceFile);
41
+ if (await fs.pathExists(rootPkgPath)) {
42
+ const content = await fs.readFile(rootPkgPath, "utf8");
43
+ const dirs = (content.match(/- "(?:.+?)\/*"/g) || []).map((t) => t.slice(3, -3));
44
+ const names = await Promise.all(dirs.map(getProjectName));
45
+ const projects = dirs.map((id, index) => ({ id, name: names[index] })).filter((project) => !project.name.includes("disabled"));
46
+ return returnAll === true ? projects : projects.filter((project) => project.id !== InternalDir && project.id !== TemplateDir);
47
+ }
48
+ return [];
49
+ }
50
+ async function getProjectName(project) {
51
+ const namef = path.join(project, ".name");
52
+ if (await fs.exists(namef)) {
53
+ const name = await fs.readFile(namef, "utf8");
54
+ return name.trim().replace(/\n[\d\D]+/g, "");
55
+ }
56
+ return project;
57
+ }
58
+ async function copyTemplate(templateName, targetDir) {
59
+ const templateSourceDir = path.join(root, TemplateDir, templateName);
60
+ await fs.copy(templateSourceDir, targetDir, {
61
+ filter: (src) => {
62
+ return !src.includes("node_modules") && !src.includes(".git") && !src.endsWith(".local");
63
+ }
64
+ });
65
+ }
66
+ async function addProjectToWorkspace(project) {
67
+ const rootWorkspacePath = path.join(root, WorkspaceFile);
68
+ if (await fs.pathExists(rootWorkspacePath)) {
69
+ let content = await fs.readFile(rootWorkspacePath, "utf8");
70
+ if (!content.includes(`- "${project}/*"`)) {
71
+ content += ` - "${project}/*"
72
+ `;
73
+ }
74
+ await fs.writeFile(rootWorkspacePath, content);
75
+ }
76
+ }
77
+ async function removeProjectFromWorkspace(project) {
78
+ const rootWorkspacePath = path.join(root, WorkspaceFile);
79
+ if (await fs.pathExists(rootWorkspacePath)) {
80
+ const content = (await fs.readFile(rootWorkspacePath, "utf8")).replace(
81
+ new RegExp(`\\n.*\\- "${project}\\/\\*"`),
82
+ ""
83
+ );
84
+ await fs.writeFile(rootWorkspacePath, content);
85
+ }
86
+ }
87
+ function getNowTime() {
88
+ const now = /* @__PURE__ */ new Date();
89
+ return `${now.getFullYear()}/${fillZ(now.getMonth() + 1)}/${fillZ(now.getDate())} ${fillZ(now.getHours())}:${fillZ(now.getMinutes())}`;
90
+ }
91
+ function fillZ(a) {
92
+ return ("0" + a).slice(-2);
93
+ }
94
+ const MainBranchName = "main";
95
+ const DeployTagPrefix = "deploy#";
96
+ function converToDeployTagName(deployTo) {
97
+ return `${DeployTagPrefix}${deployTo.toLowerCase().replace(/(?:^https?:\/\/|\/*$)/gi, "")}`;
98
+ }
99
+ async function execCmd(cmd, ignoreWarning = false) {
100
+ return new Promise((resolve, reject) => {
101
+ exec(cmd, { cwd: root, env: { ...process.env } }, (error, stdout, stderr) => {
102
+ if (error || stderr && !ignoreWarning) {
103
+ console.error(cmd, error, stderr);
104
+ reject(`执行命令时出错: ${(error == null ? void 0 : error.message) || stderr}`);
105
+ return;
106
+ }
107
+ resolve(stdout.trim());
108
+ });
109
+ });
110
+ }
111
+ async function getCommitInfo(command, mode, deployTo) {
112
+ if (command !== "build" || mode === "preview" || mode === "prev") {
113
+ return { hash: await getCommitHash(), logs: [] };
114
+ }
115
+ if (await hasUncommittedChanges()) {
116
+ console.error(`在部署前需要提交所有代码!`.red);
117
+ process.exit(1);
118
+ }
119
+ if (await getCurrentBranchName() !== MainBranchName) {
120
+ console.error(`正式环境部署需要在 ${`${MainBranchName}分支`.bgRed} 操作!`.red);
121
+ process.exit(1);
122
+ }
123
+ const unCommitChanges = await countUnsubmitChanges(MainBranchName);
124
+ if (unCommitChanges > 0) {
125
+ console.error("正式环境部署需要先将代码同步到服务器!".red, `发现 ${unCommitChanges} 个 commit 差异`.red);
126
+ process.exit(1);
127
+ }
128
+ const [currentCommit, lastDeployTag] = await Promise.all([getCommitHash(), getLastDeployTag(deployTo)]);
129
+ const commitLogs = await getCommitLogs(currentCommit, lastDeployTag, "./");
130
+ return { hash: currentCommit, logs: commitLogs };
131
+ }
132
+ async function getLastDeployTag(deployTo) {
133
+ await fetchTags();
134
+ const deployTags = await getDeployTags();
135
+ const tag = converToDeployTagName(deployTo);
136
+ return deployTags.includes(tag) ? tag : "";
137
+ }
138
+ async function createPageDeployTag(page, deployTo, finderUser) {
139
+ const tagName = converToDeployTagName(deployTo);
140
+ const gitUser = await execCmd(`git config user.email`).catch(() => "");
141
+ await execCmd(
142
+ [`git tag -f ${tagName} -m "${getNowTime()} deployed by ${gitUser || finderUser}`, page ? `from ${page}` : ""].filter((c) => !!c).join(" ")
143
+ );
144
+ try {
145
+ await execCmd(`git push origin -f ${tagName}`, true);
146
+ } catch (e) {
147
+ await execCmd(`git push origin --tags`, true);
148
+ }
149
+ }
150
+ async function getCommitHash() {
151
+ return (await execCmd("git rev-parse HEAD")).slice(0, 8);
152
+ }
153
+ async function getCurrentBranchName() {
154
+ return await execCmd("git rev-parse --abbrev-ref HEAD");
155
+ }
156
+ async function fetchTags() {
157
+ await execCmd("git fetch --tags", true);
158
+ }
159
+ async function getDeployTags() {
160
+ const result = await execCmd("git tag");
161
+ return result.split("\n").filter((tag) => tag.startsWith(DeployTagPrefix));
162
+ }
163
+ async function getCommitLogs(branchOrCommit, sinceCommit, codePath) {
164
+ const cmd = [
165
+ "git log",
166
+ sinceCommit ? `${sinceCommit}..${branchOrCommit || "HEAD"}` : branchOrCommit || "",
167
+ `--oneline --pretty=format:"[%cd][%h] %s" --date=short -n 60`,
168
+ `-- ${codePath}`
169
+ ].filter((f) => !!f).join(" ");
170
+ const result = await execCmd(cmd);
171
+ return result ? result.split("\n") : [];
172
+ }
173
+ async function hasUncommittedChanges() {
174
+ const result = await execCmd("git status --porcelain");
175
+ return result !== "";
176
+ }
177
+ async function countUnsubmitChanges(branch) {
178
+ const result = await execCmd(`git rev-list --count ${branch} "^origin/${branch}"`);
179
+ return parseInt(result, 10);
180
+ }
181
+ async function checkGitStatusBeforeDestory() {
182
+ if (await hasUncommittedChanges()) {
183
+ console.error(`在销毁前需要提交所有代码!`.red);
184
+ process.exit(1);
185
+ }
186
+ if (await getCurrentBranchName() !== MainBranchName) {
187
+ console.error(`销毁操作需要在 ${`${MainBranchName}分支`.bgRed} 进行!`.red);
188
+ process.exit(1);
189
+ }
190
+ const unCommitChanges = await countUnsubmitChanges(MainBranchName);
191
+ if (unCommitChanges > 0) {
192
+ console.error("销毁操作需要先将代码同步到服务器!".red, `发现 ${unCommitChanges} 个 commit 差异`.red);
193
+ process.exit(1);
194
+ }
195
+ }
196
+ async function createBackupTag(action, info) {
197
+ const tagName = `backup#${action}-${info}`;
198
+ const gitUser = await execCmd(`git config user.email`).catch(() => "");
199
+ await execCmd(`git tag -f ${tagName} -m "${getNowTime()} destroyed by ${gitUser || "unknown"}`);
200
+ try {
201
+ await execCmd(`git push origin -f ${tagName}`, true);
202
+ } catch (e) {
203
+ await execCmd(`git push origin --tags`, true);
204
+ }
205
+ }
206
+ async function submitAllDeletionChanges(message) {
207
+ const branch = await getCurrentBranchName();
208
+ await execCmd(`git add --all :/ && git commit -m "${message}" && git push origin ${branch}`, true);
209
+ }
210
+ export {
211
+ getCommitInfo as a,
212
+ addProjectToWorkspace as b,
213
+ createPageDeployTag as c,
214
+ copyTemplate as d,
215
+ getProjects as e,
216
+ getTemplates as f,
217
+ getNowTime as g,
218
+ checkGitStatusBeforeDestory as h,
219
+ createBackupTag as i,
220
+ removeProjectFromWorkspace as j,
221
+ getRepos as k,
222
+ root as r,
223
+ submitAllDeletionChanges as s
224
+ };
package/dist/index.js CHANGED
@@ -7,12 +7,7 @@ import vue from "@vitejs/plugin-vue";
7
7
  import vueDevTools from "vite-plugin-vue-devtools";
8
8
  import { existsSync, readFileSync } from "fs";
9
9
  import "colors";
10
- import path from "path";
11
- import fs from "fs-extra";
12
- import { exec } from "child_process";
13
- import { Command } from "commander";
14
- import inquirer from "inquirer";
15
- import ora from "ora";
10
+ import { g as getNowTime, a as getCommitInfo, c as createPageDeployTag } from "./git-DqZLg6mx.js";
16
11
  import skipFormatting from "@vue/eslint-config-prettier/skip-formatting";
17
12
  import { vueTsConfigs } from "@vue/eslint-config-typescript";
18
13
  import { defineConfigWithVueTs } from "@vue/eslint-config-typescript";
@@ -36,95 +31,6 @@ function defineLibBuildConfig(option) {
36
31
  }
37
32
  });
38
33
  }
39
- const TemplateDir = "template";
40
- const InternalDir = "internal";
41
- const WorkspaceFile = "pnpm-workspace.yaml";
42
- const root = function() {
43
- let currentDir = process.cwd();
44
- while (currentDir !== path.parse(currentDir).root) {
45
- if (fs.existsSync(path.join(currentDir, WorkspaceFile))) {
46
- return currentDir;
47
- }
48
- currentDir = path.dirname(currentDir);
49
- }
50
- if (fs.existsSync(path.join(currentDir, "pnpm-workspace.yaml"))) {
51
- return currentDir;
52
- }
53
- throw new Error("Could not find repository root with pnpm-workspace.yaml".bgRed);
54
- }();
55
- async function getTemplates() {
56
- return await getRepos(TemplateDir);
57
- }
58
- async function getRepos(project) {
59
- const projectDir = path.join(root, project);
60
- const dirs = await fs.readdir(projectDir);
61
- const repos = dirs.filter((item) => fs.statSync(path.join(projectDir, item)).isDirectory());
62
- const descs = await Promise.all(repos.map((repo) => getRepoDesc(project, repo)));
63
- return repos.map((dir, index) => ({ id: dir, desc: descs[index] })).filter((item) => item.desc !== null);
64
- }
65
- async function getRepoDesc(project, dir) {
66
- const packageFile = path.join(root, project, dir, "package.json");
67
- if (!await fs.exists(packageFile)) {
68
- return null;
69
- }
70
- const content = await fs.readJson(packageFile, "utf8");
71
- return (content.description || "") + "";
72
- }
73
- async function getProjects(returnAll) {
74
- const rootPkgPath = path.join(root, WorkspaceFile);
75
- if (await fs.pathExists(rootPkgPath)) {
76
- const content = await fs.readFile(rootPkgPath, "utf8");
77
- const dirs = (content.match(/- "(?:.+?)\/*"/g) || []).map((t) => t.slice(3, -3));
78
- const names = await Promise.all(dirs.map(getProjectName));
79
- const projects = dirs.map((id, index) => ({ id, name: names[index] })).filter((project) => !project.name.includes("disabled"));
80
- return returnAll === true ? projects : projects.filter((project) => project.id !== InternalDir && project.id !== TemplateDir);
81
- }
82
- return [];
83
- }
84
- async function getProjectName(project) {
85
- const namef = path.join(project, ".name");
86
- if (await fs.exists(namef)) {
87
- const name = await fs.readFile(namef, "utf8");
88
- return name.trim().replace(/\n[\d\D]+/g, "");
89
- }
90
- return project;
91
- }
92
- async function copyTemplate(templateName, targetDir) {
93
- const templateSourceDir = path.join(root, TemplateDir, templateName);
94
- await fs.copy(templateSourceDir, targetDir, {
95
- filter: (src) => {
96
- return !src.includes("node_modules") && !src.includes(".git") && !src.endsWith(".local");
97
- }
98
- });
99
- }
100
- async function addProjectToWorkspace(project) {
101
- const rootWorkspacePath = path.join(root, WorkspaceFile);
102
- if (await fs.pathExists(rootWorkspacePath)) {
103
- let content = await fs.readFile(rootWorkspacePath, "utf8");
104
- if (!content.includes(`- "${project}/*"`)) {
105
- content += ` - "${project}/*"
106
- `;
107
- }
108
- await fs.writeFile(rootWorkspacePath, content);
109
- }
110
- }
111
- async function removeProjectFromWorkspace(project) {
112
- const rootWorkspacePath = path.join(root, WorkspaceFile);
113
- if (await fs.pathExists(rootWorkspacePath)) {
114
- const content = (await fs.readFile(rootWorkspacePath, "utf8")).replace(
115
- new RegExp(`\\n.*\\- "${project}\\/\\*"`),
116
- ""
117
- );
118
- await fs.writeFile(rootWorkspacePath, content);
119
- }
120
- }
121
- function getNowTime() {
122
- const now = /* @__PURE__ */ new Date();
123
- return `${now.getFullYear()}/${fillZ(now.getMonth() + 1)}/${fillZ(now.getDate())} ${fillZ(now.getHours())}:${fillZ(now.getMinutes())}`;
124
- }
125
- function fillZ(a) {
126
- return ("0" + a).slice(-2);
127
- }
128
34
  const EnvPrefix = "SY_";
129
35
  function getBuildEnv(command, mode) {
130
36
  const envs = loadEnv(mode, process.cwd(), EnvPrefix);
@@ -187,122 +93,6 @@ function transformEnvs(envs) {
187
93
  {}
188
94
  );
189
95
  }
190
- const MainBranchName = "main";
191
- const DeployTagPrefix = "deploy#";
192
- function converToDeployTagName(deployTo) {
193
- return `${DeployTagPrefix}${deployTo.toLowerCase().replace(/(?:^https?:\/\/|\/*$)/gi, "")}`;
194
- }
195
- async function execCmd(cmd, ignoreWarning = false) {
196
- return new Promise((resolve, reject) => {
197
- exec(cmd, { cwd: root, env: { ...process.env } }, (error, stdout, stderr) => {
198
- if (error || stderr && !ignoreWarning) {
199
- console.error(cmd, error, stderr);
200
- reject(`执行命令时出错: ${(error == null ? void 0 : error.message) || stderr}`);
201
- return;
202
- }
203
- resolve(stdout.trim());
204
- });
205
- });
206
- }
207
- async function getCommitInfo(command, mode, deployTo) {
208
- if (command !== "build" || mode === "preview" || mode === "prev") {
209
- return { hash: await getCommitHash(), logs: [] };
210
- }
211
- if (await hasUncommittedChanges()) {
212
- console.error(`在部署前需要提交所有代码!`.red);
213
- process.exit(1);
214
- }
215
- if (await getCurrentBranchName() !== MainBranchName) {
216
- console.error(`正式环境部署需要在 ${`${MainBranchName}分支`.bgRed} 操作!`.red);
217
- process.exit(1);
218
- }
219
- const unCommitChanges = await countUnsubmitChanges(MainBranchName);
220
- if (unCommitChanges > 0) {
221
- console.error("正式环境部署需要先将代码同步到服务器!".red, `发现 ${unCommitChanges} 个 commit 差异`.red);
222
- process.exit(1);
223
- }
224
- const [currentCommit, lastDeployTag] = await Promise.all([getCommitHash(), getLastDeployTag(deployTo)]);
225
- const commitLogs = await getCommitLogs(currentCommit, lastDeployTag, "./");
226
- return { hash: currentCommit, logs: commitLogs };
227
- }
228
- async function getLastDeployTag(deployTo) {
229
- await fetchTags();
230
- const deployTags = await getDeployTags();
231
- const tag = converToDeployTagName(deployTo);
232
- return deployTags.includes(tag) ? tag : "";
233
- }
234
- async function createPageDeployTag(page, deployTo, finderUser) {
235
- const tagName = converToDeployTagName(deployTo);
236
- const gitUser = await execCmd(`git config user.email`).catch(() => "");
237
- await execCmd(
238
- [`git tag -f ${tagName} -m "${getNowTime()} deployed by ${gitUser || finderUser}`, page ? `from ${page}` : ""].filter((c) => !!c).join(" ")
239
- );
240
- try {
241
- await execCmd(`git push origin -f ${tagName}`, true);
242
- } catch (e) {
243
- await execCmd(`git push origin --tags`, true);
244
- }
245
- }
246
- async function getCommitHash() {
247
- return (await execCmd("git rev-parse HEAD")).slice(0, 8);
248
- }
249
- async function getCurrentBranchName() {
250
- return await execCmd("git rev-parse --abbrev-ref HEAD");
251
- }
252
- async function fetchTags() {
253
- await execCmd("git fetch --tags", true);
254
- }
255
- async function getDeployTags() {
256
- const result = await execCmd("git tag");
257
- return result.split("\n").filter((tag) => tag.startsWith(DeployTagPrefix));
258
- }
259
- async function getCommitLogs(branchOrCommit, sinceCommit, codePath) {
260
- const cmd = [
261
- "git log",
262
- sinceCommit ? `${sinceCommit}..${branchOrCommit || "HEAD"}` : branchOrCommit || "",
263
- `--oneline --pretty=format:"[%cd][%h] %s" --date=short -n 60`,
264
- `-- ${codePath}`
265
- ].filter((f) => !!f).join(" ");
266
- const result = await execCmd(cmd);
267
- return result ? result.split("\n") : [];
268
- }
269
- async function hasUncommittedChanges() {
270
- const result = await execCmd("git status --porcelain");
271
- return result !== "";
272
- }
273
- async function countUnsubmitChanges(branch) {
274
- const result = await execCmd(`git rev-list --count ${branch} "^origin/${branch}"`);
275
- return parseInt(result, 10);
276
- }
277
- async function checkGitStatusBeforeDestory() {
278
- if (await hasUncommittedChanges()) {
279
- console.error(`在销毁前需要提交所有代码!`.red);
280
- process.exit(1);
281
- }
282
- if (await getCurrentBranchName() !== MainBranchName) {
283
- console.error(`销毁操作需要在 ${`${MainBranchName}分支`.bgRed} 进行!`.red);
284
- process.exit(1);
285
- }
286
- const unCommitChanges = await countUnsubmitChanges(MainBranchName);
287
- if (unCommitChanges > 0) {
288
- console.error("销毁操作需要先将代码同步到服务器!".red, `发现 ${unCommitChanges} 个 commit 差异`.red);
289
- process.exit(1);
290
- }
291
- }
292
- async function createBackupTag(action, info) {
293
- const tagName = `backup#${action}-${info}`;
294
- const gitUser = await execCmd(`git config user.email`).catch(() => "");
295
- await execCmd(`git tag -f ${tagName} -m "${getNowTime()} destroyed by ${gitUser || "unknown"}`);
296
- try {
297
- await execCmd(`git push origin -f ${tagName}`, true);
298
- } catch (e) {
299
- await execCmd(`git push origin --tags`, true);
300
- }
301
- }
302
- async function submitAllDeletionChanges(message) {
303
- const branch = await getCurrentBranchName();
304
- await execCmd(`git add --all :/ && git commit -m "${message}" && git push origin ${branch}`, true);
305
- }
306
96
  function htmlInjectPlugin(data) {
307
97
  return {
308
98
  name: "html-inject-plugin",
@@ -396,271 +186,6 @@ function definePageBuildConfig(option) {
396
186
  };
397
187
  });
398
188
  }
399
- const commitRE = /^(?:revert: )?(?:feat|fix|docs|style|refactor|test|chore|debug|tweak|improve)(?:\(.+\))?: .{1,100}/;
400
- function checkCommit() {
401
- const msgPath = process.argv[2];
402
- const msg = readFileSync(msgPath, "utf-8").trim();
403
- if (!commitRE.test(msg) && !msg.startsWith("Merge branch")) {
404
- console.error(`ERROR!【提交的 Commit 信息格式错误,请注意使用正确的类型前缀!】`.red);
405
- process.exit(1);
406
- }
407
- }
408
- const program$1 = new Command();
409
- program$1.version("1.0.0").argument("<target>");
410
- function runCreateScript() {
411
- program$1.parse(process.argv);
412
- }
413
- async function initRepoQuestions$1() {
414
- const projects = await getProjects();
415
- const templates = await getTemplates();
416
- return [
417
- {
418
- type: "list",
419
- name: "project",
420
- message: "选择项目:",
421
- choices: projects.map((project) => ({
422
- name: `${project.id} ${project.name}`,
423
- short: project.id,
424
- value: project.id
425
- }))
426
- },
427
- {
428
- type: "list",
429
- name: "template",
430
- message: "选择模板:",
431
- choices: templates.map((template) => ({
432
- name: `${template.id} ${template.desc}`,
433
- short: template.id,
434
- value: template.id
435
- }))
436
- },
437
- {
438
- type: "input",
439
- name: "repoName",
440
- message: "仓库名称:",
441
- validate: (input) => {
442
- if (/^[a-z0-9-]+$/.test(input)) return true;
443
- return "仓库名称只能包含小写字母、数字和中横线";
444
- }
445
- },
446
- {
447
- type: "input",
448
- name: "description",
449
- message: "仓库描述:",
450
- default: ""
451
- }
452
- ];
453
- }
454
- async function initProjectQuestions$1() {
455
- const projects = (await getProjects(true)).map((project) => project.id);
456
- return [
457
- {
458
- type: "input",
459
- name: "project",
460
- message: "项目 ID:",
461
- validate: (input) => {
462
- if (!/^[a-zA-Z0-9-_]+$/.test(input)) {
463
- return "项目名称只能包含字母、数字、下划线和横线";
464
- }
465
- if (projects.includes(input)) {
466
- return "项目已经存在,请检查";
467
- }
468
- return true;
469
- }
470
- },
471
- {
472
- type: "input",
473
- name: "name",
474
- message: "中文名称:",
475
- validate: (input) => {
476
- if (!input) {
477
- return "中文名称不能为空";
478
- }
479
- return true;
480
- }
481
- }
482
- ];
483
- }
484
- async function updatePackageFiles(targetDir, answers) {
485
- await Promise.all([
486
- // 初始化 package.json
487
- updatePackageJson(targetDir, answers),
488
- // 初始化样例文件
489
- initSampleFiles(targetDir)
490
- ]);
491
- }
492
- async function updatePackageJson(targetDir, answers) {
493
- const pkgPath = path.join(targetDir, "package.json");
494
- if (await fs.pathExists(pkgPath)) {
495
- const pkg = await fs.readJson(pkgPath);
496
- pkg.name = `@${answers.project}/${answers.repoName}`;
497
- pkg.description = answers.description || pkg.description;
498
- pkg.version = "1.0.0";
499
- await fs.writeJson(pkgPath, pkg, { spaces: 2 });
500
- }
501
- }
502
- async function initSampleFiles(targetDir) {
503
- const items = await fs.readdir(targetDir);
504
- const files = items.filter(
505
- (item) => !fs.statSync(path.join(targetDir, item)).isDirectory() && item.endsWith(".sample")
506
- );
507
- for (const filename of files) {
508
- const sample = path.join(targetDir, filename);
509
- if (await fs.pathExists(sample)) {
510
- await fs.writeFile(path.join(targetDir, filename.replace(/\.sample$/, "")), await fs.readFile(sample));
511
- fs.unlink(sample);
512
- }
513
- }
514
- }
515
- async function startCreateJob$1(target) {
516
- if (target === "project") {
517
- await createProject();
518
- } else {
519
- await createRepo();
520
- }
521
- }
522
- async function createProject() {
523
- const questions = await initProjectQuestions$1();
524
- const answers = await inquirer.prompt(questions);
525
- const spinner = ora("正在创建项目...").start();
526
- const projectDir = path.join(root, answers.project);
527
- await fs.mkdir(projectDir);
528
- await fs.writeFile(path.join(projectDir, ".name"), answers.name);
529
- await addProjectToWorkspace(answers.project);
530
- spinner.succeed("项目创建成功!".green);
531
- }
532
- async function createRepo() {
533
- const questions = await initRepoQuestions$1();
534
- const answers = await inquirer.prompt(questions);
535
- const spinner = ora("正在创建仓库...").start();
536
- const projectDir = path.join(root, answers.project);
537
- spinner.text = "检查目录...";
538
- if (!await fs.pathExists(projectDir)) {
539
- fs.mkdirSync(projectDir, { recursive: true });
540
- }
541
- const targetDir = path.join(root, answers.project, answers.repoName);
542
- if (await fs.pathExists(targetDir)) {
543
- spinner.fail(`错误:目录(${`${answers.project}/${answers.repoName}`})已存在`.red);
544
- process.exit(1);
545
- }
546
- spinner.text = "复制模板文件...";
547
- await copyTemplate(answers.template, targetDir);
548
- spinner.text = "更新 package.json...";
549
- await updatePackageFiles(targetDir, answers);
550
- spinner.succeed("仓库创建成功!".green);
551
- console.log("\n接下来你可以:");
552
- console.log(`cd ${answers.project}/${answers.repoName}`.cyan);
553
- console.log("pnpm i".cyan);
554
- console.log("pnpm dev".cyan);
555
- }
556
- program$1.action(startCreateJob$1);
557
- const program = new Command();
558
- program.version("1.0.0").argument("<target>");
559
- function runDestoryScript() {
560
- program.parse(process.argv);
561
- }
562
- async function startCreateJob(target) {
563
- if (target === "project") {
564
- await destroyProject();
565
- } else {
566
- await destroyRepo();
567
- }
568
- }
569
- async function initProjectQuestions() {
570
- const projects = await getProjects();
571
- return [
572
- {
573
- type: "list",
574
- name: "project",
575
- message: "删除项目:",
576
- choices: projects.map((project) => ({
577
- name: `${project.id} ${project.name}`,
578
- short: project.id,
579
- value: project.id
580
- }))
581
- },
582
- {
583
- type: "confirm",
584
- name: "confirm",
585
- message: function(answers) {
586
- return `确认删除整个 ${answers.project} 项目 ?`;
587
- }
588
- }
589
- ];
590
- }
591
- async function destroyProject() {
592
- await checkGitStatusBeforeDestory();
593
- const questions = await initProjectQuestions();
594
- const answers = await inquirer.prompt(questions);
595
- if (!answers.confirm) {
596
- process.exit(0);
597
- }
598
- const spinner = ora("正在创建 Backup Tag...").start();
599
- await createBackupTag("project", answers.project);
600
- spinner.text = "开始清理文件...";
601
- const projectDir = path.join(root, answers.project);
602
- await fs.removeSync(projectDir);
603
- spinner.text = "调整配置文件...";
604
- await removeProjectFromWorkspace(answers.project);
605
- spinner.text = "提交代码中...";
606
- await submitAllDeletionChanges(`chore: destory project ${answers.project}`);
607
- spinner.succeed("项目已经销毁!".green);
608
- }
609
- async function initRepoQuestions() {
610
- const projects = await getProjects();
611
- return [
612
- {
613
- type: "list",
614
- name: "project",
615
- message: "所在项目:",
616
- choices: projects.map((project) => ({
617
- name: `${project.id} ${project.name}`,
618
- short: project.id,
619
- value: project.id
620
- }))
621
- },
622
- {
623
- type: "list",
624
- name: "page",
625
- message: "删除页面:",
626
- choices: async function(answers) {
627
- const repos = await getRepos(answers.project);
628
- if (repos.length === 0) {
629
- throw new Error("工程不含有任意有效 Repo!操作中止");
630
- }
631
- return repos.map((repo) => ({
632
- name: `${repo.id} ${repo.desc || ""}`,
633
- short: repo.id,
634
- value: repo.id
635
- }));
636
- }
637
- },
638
- {
639
- type: "confirm",
640
- name: "confirm",
641
- message: async function(answers) {
642
- return `确认删除页面 ${answers.project}/${answers.page} ?`;
643
- }
644
- }
645
- ];
646
- }
647
- async function destroyRepo() {
648
- await checkGitStatusBeforeDestory();
649
- const questions = await initRepoQuestions();
650
- const answers = await inquirer.prompt(questions);
651
- if (!answers.confirm) {
652
- process.exit(0);
653
- }
654
- const spinner = ora("正在创建 Backup Tag...").start();
655
- await createBackupTag("page", `${answers.project}/${answers.page}`);
656
- spinner.text = "开始清理文件...";
657
- const pageDir = path.join(root, answers.project, answers.page);
658
- await fs.removeSync(pageDir);
659
- spinner.text = "提交代码中...";
660
- await submitAllDeletionChanges(`chore: destory page ${answers.project}/${answers.page}`);
661
- spinner.succeed("页面已经销毁!".green);
662
- }
663
- program.action(startCreateJob);
664
189
  const vueEslintConfig = [
665
190
  pluginVue.configs["flat/essential"],
666
191
  vueTsConfigs.recommended,
@@ -717,7 +242,6 @@ const postcssConfig = {
717
242
  };
718
243
  export {
719
244
  EnvPrefix,
720
- checkCommit,
721
245
  defineConfigWithVueTs,
722
246
  defineLibBuildConfig,
723
247
  definePageBuildConfig,
@@ -725,8 +249,6 @@ export {
725
249
  htmlInjectPlugin,
726
250
  importEslintConfig,
727
251
  postcssConfig,
728
- runCreateScript,
729
- runDestoryScript,
730
252
  stylelintConfig,
731
253
  transformEnvs,
732
254
  vueEslintConfig
package/dist/node.js ADDED
@@ -0,0 +1,278 @@
1
+ import { readFileSync } from "fs";
2
+ import "colors";
3
+ import path from "path";
4
+ import { Command } from "commander";
5
+ import fs from "fs-extra";
6
+ import inquirer from "inquirer";
7
+ import ora from "ora";
8
+ import { r as root, b as addProjectToWorkspace, d as copyTemplate, e as getProjects, f as getTemplates, h as checkGitStatusBeforeDestory, i as createBackupTag, j as removeProjectFromWorkspace, s as submitAllDeletionChanges, k as getRepos } from "./git-DqZLg6mx.js";
9
+ const commitRE = /^(?:revert: )?(?:feat|fix|docs|style|refactor|test|chore|debug|tweak|improve)(?:\(.+\))?: .{1,100}/;
10
+ function checkCommit() {
11
+ const msgPath = process.argv[2];
12
+ const msg = readFileSync(msgPath, "utf-8").trim();
13
+ if (!commitRE.test(msg) && !msg.startsWith("Merge branch")) {
14
+ console.error(`ERROR!【提交的 Commit 信息格式错误,请注意使用正确的类型前缀!】`.red);
15
+ process.exit(1);
16
+ }
17
+ }
18
+ const program$1 = new Command();
19
+ program$1.version("1.0.0").argument("<target>");
20
+ function runCreateScript() {
21
+ program$1.parse(process.argv);
22
+ }
23
+ async function initRepoQuestions$1() {
24
+ const projects = await getProjects();
25
+ const templates = await getTemplates();
26
+ return [
27
+ {
28
+ type: "list",
29
+ name: "project",
30
+ message: "选择项目:",
31
+ choices: projects.map((project) => ({
32
+ name: `${project.id} ${project.name}`,
33
+ short: project.id,
34
+ value: project.id
35
+ }))
36
+ },
37
+ {
38
+ type: "list",
39
+ name: "template",
40
+ message: "选择模板:",
41
+ choices: templates.map((template) => ({
42
+ name: `${template.id} ${template.desc}`,
43
+ short: template.id,
44
+ value: template.id
45
+ }))
46
+ },
47
+ {
48
+ type: "input",
49
+ name: "repoName",
50
+ message: "仓库名称:",
51
+ validate: (input) => {
52
+ if (/^[a-z0-9-]+$/.test(input)) return true;
53
+ return "仓库名称只能包含小写字母、数字和中横线";
54
+ }
55
+ },
56
+ {
57
+ type: "input",
58
+ name: "description",
59
+ message: "仓库描述:",
60
+ default: ""
61
+ }
62
+ ];
63
+ }
64
+ async function initProjectQuestions$1() {
65
+ const projects = (await getProjects(true)).map((project) => project.id);
66
+ return [
67
+ {
68
+ type: "input",
69
+ name: "project",
70
+ message: "项目 ID:",
71
+ validate: (input) => {
72
+ if (!/^[a-zA-Z0-9-_]+$/.test(input)) {
73
+ return "项目名称只能包含字母、数字、下划线和横线";
74
+ }
75
+ if (projects.includes(input)) {
76
+ return "项目已经存在,请检查";
77
+ }
78
+ return true;
79
+ }
80
+ },
81
+ {
82
+ type: "input",
83
+ name: "name",
84
+ message: "中文名称:",
85
+ validate: (input) => {
86
+ if (!input) {
87
+ return "中文名称不能为空";
88
+ }
89
+ return true;
90
+ }
91
+ }
92
+ ];
93
+ }
94
+ async function updatePackageFiles(targetDir, answers) {
95
+ await Promise.all([
96
+ // 初始化 package.json
97
+ updatePackageJson(targetDir, answers),
98
+ // 初始化样例文件
99
+ initSampleFiles(targetDir)
100
+ ]);
101
+ }
102
+ async function updatePackageJson(targetDir, answers) {
103
+ const pkgPath = path.join(targetDir, "package.json");
104
+ if (await fs.pathExists(pkgPath)) {
105
+ const pkg = await fs.readJson(pkgPath);
106
+ pkg.name = `@${answers.project}/${answers.repoName}`;
107
+ pkg.description = answers.description || pkg.description;
108
+ pkg.version = "1.0.0";
109
+ await fs.writeJson(pkgPath, pkg, { spaces: 2 });
110
+ }
111
+ }
112
+ async function initSampleFiles(targetDir) {
113
+ const items = await fs.readdir(targetDir);
114
+ const files = items.filter(
115
+ (item) => !fs.statSync(path.join(targetDir, item)).isDirectory() && item.endsWith(".sample")
116
+ );
117
+ for (const filename of files) {
118
+ const sample = path.join(targetDir, filename);
119
+ if (await fs.pathExists(sample)) {
120
+ await fs.writeFile(path.join(targetDir, filename.replace(/\.sample$/, "")), await fs.readFile(sample));
121
+ fs.unlink(sample);
122
+ }
123
+ }
124
+ }
125
+ async function startCreateJob$1(target) {
126
+ if (target === "project") {
127
+ await createProject();
128
+ } else {
129
+ await createRepo();
130
+ }
131
+ }
132
+ async function createProject() {
133
+ const questions = await initProjectQuestions$1();
134
+ const answers = await inquirer.prompt(questions);
135
+ const spinner = ora("正在创建项目...").start();
136
+ const projectDir = path.join(root, answers.project);
137
+ await fs.mkdir(projectDir);
138
+ await fs.writeFile(path.join(projectDir, ".name"), answers.name);
139
+ await addProjectToWorkspace(answers.project);
140
+ spinner.succeed("项目创建成功!".green);
141
+ }
142
+ async function createRepo() {
143
+ const questions = await initRepoQuestions$1();
144
+ const answers = await inquirer.prompt(questions);
145
+ const spinner = ora("正在创建仓库...").start();
146
+ const projectDir = path.join(root, answers.project);
147
+ spinner.text = "检查目录...";
148
+ if (!await fs.pathExists(projectDir)) {
149
+ fs.mkdirSync(projectDir, { recursive: true });
150
+ }
151
+ const targetDir = path.join(root, answers.project, answers.repoName);
152
+ if (await fs.pathExists(targetDir)) {
153
+ spinner.fail(`错误:目录(${`${answers.project}/${answers.repoName}`})已存在`.red);
154
+ process.exit(1);
155
+ }
156
+ spinner.text = "复制模板文件...";
157
+ await copyTemplate(answers.template, targetDir);
158
+ spinner.text = "更新 package.json...";
159
+ await updatePackageFiles(targetDir, answers);
160
+ spinner.succeed("仓库创建成功!".green);
161
+ console.log("\n接下来你可以:");
162
+ console.log(`cd ${answers.project}/${answers.repoName}`.cyan);
163
+ console.log("pnpm i".cyan);
164
+ console.log("pnpm dev".cyan);
165
+ }
166
+ program$1.action(startCreateJob$1);
167
+ const program = new Command();
168
+ program.version("1.0.0").argument("<target>");
169
+ function runDestoryScript() {
170
+ program.parse(process.argv);
171
+ }
172
+ async function startCreateJob(target) {
173
+ if (target === "project") {
174
+ await destroyProject();
175
+ } else {
176
+ await destroyRepo();
177
+ }
178
+ }
179
+ async function initProjectQuestions() {
180
+ const projects = await getProjects();
181
+ return [
182
+ {
183
+ type: "list",
184
+ name: "project",
185
+ message: "删除项目:",
186
+ choices: projects.map((project) => ({
187
+ name: `${project.id} ${project.name}`,
188
+ short: project.id,
189
+ value: project.id
190
+ }))
191
+ },
192
+ {
193
+ type: "confirm",
194
+ name: "confirm",
195
+ message: function(answers) {
196
+ return `确认删除整个 ${answers.project} 项目 ?`;
197
+ }
198
+ }
199
+ ];
200
+ }
201
+ async function destroyProject() {
202
+ await checkGitStatusBeforeDestory();
203
+ const questions = await initProjectQuestions();
204
+ const answers = await inquirer.prompt(questions);
205
+ if (!answers.confirm) {
206
+ process.exit(0);
207
+ }
208
+ const spinner = ora("正在创建 Backup Tag...").start();
209
+ await createBackupTag("project", answers.project);
210
+ spinner.text = "开始清理文件...";
211
+ const projectDir = path.join(root, answers.project);
212
+ await fs.removeSync(projectDir);
213
+ spinner.text = "调整配置文件...";
214
+ await removeProjectFromWorkspace(answers.project);
215
+ spinner.text = "提交代码中...";
216
+ await submitAllDeletionChanges(`chore: destory project ${answers.project}`);
217
+ spinner.succeed("项目已经销毁!".green);
218
+ }
219
+ async function initRepoQuestions() {
220
+ const projects = await getProjects();
221
+ return [
222
+ {
223
+ type: "list",
224
+ name: "project",
225
+ message: "所在项目:",
226
+ choices: projects.map((project) => ({
227
+ name: `${project.id} ${project.name}`,
228
+ short: project.id,
229
+ value: project.id
230
+ }))
231
+ },
232
+ {
233
+ type: "list",
234
+ name: "page",
235
+ message: "删除页面:",
236
+ choices: async function(answers) {
237
+ const repos = await getRepos(answers.project);
238
+ if (repos.length === 0) {
239
+ throw new Error("工程不含有任意有效 Repo!操作中止");
240
+ }
241
+ return repos.map((repo) => ({
242
+ name: `${repo.id} ${repo.desc || ""}`,
243
+ short: repo.id,
244
+ value: repo.id
245
+ }));
246
+ }
247
+ },
248
+ {
249
+ type: "confirm",
250
+ name: "confirm",
251
+ message: async function(answers) {
252
+ return `确认删除页面 ${answers.project}/${answers.page} ?`;
253
+ }
254
+ }
255
+ ];
256
+ }
257
+ async function destroyRepo() {
258
+ await checkGitStatusBeforeDestory();
259
+ const questions = await initRepoQuestions();
260
+ const answers = await inquirer.prompt(questions);
261
+ if (!answers.confirm) {
262
+ process.exit(0);
263
+ }
264
+ const spinner = ora("正在创建 Backup Tag...").start();
265
+ await createBackupTag("page", `${answers.project}/${answers.page}`);
266
+ spinner.text = "开始清理文件...";
267
+ const pageDir = path.join(root, answers.project, answers.page);
268
+ await fs.removeSync(pageDir);
269
+ spinner.text = "提交代码中...";
270
+ await submitAllDeletionChanges(`chore: destory page ${answers.project}/${answers.page}`);
271
+ spinner.succeed("页面已经销毁!".green);
272
+ }
273
+ program.action(startCreateJob);
274
+ export {
275
+ checkCommit,
276
+ runCreateScript,
277
+ runDestoryScript
278
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-web/scripts",
3
- "version": "1.0.7",
3
+ "version": "1.1.1",
4
4
  "description": "scripts for seayoo web monorepos",
5
5
  "type": "module",
6
6
  "source": "index.ts",
@@ -12,6 +12,18 @@
12
12
  "types",
13
13
  "README.md"
14
14
  ],
15
+ "exports": {
16
+ ".": {
17
+ "types": "./types/index.d.ts",
18
+ "import": "./dist/index.js",
19
+ "default": "./dist/index.js"
20
+ },
21
+ "./node": {
22
+ "types": "./types/node.d.ts",
23
+ "import": "./dist/node.js",
24
+ "default": "./dist/node.js"
25
+ }
26
+ },
15
27
  "engines": {
16
28
  "node": ">= 18"
17
29
  },
package/types/index.d.ts CHANGED
@@ -1,10 +1,7 @@
1
1
  export * from "./src/vite.lab";
2
2
  export * from "./src/vite.page";
3
- export * from "./src/env";
4
- export * from "./src/commit";
5
3
  export * from "./src/inject";
6
- export * from "./src/create";
7
- export * from "./src/destory";
4
+ export * from "./src/env";
8
5
  export * from "./src/eslint";
9
6
  export * from "./src/stylelint";
10
7
  export * from "./src/postcss";
@@ -0,0 +1,3 @@
1
+ export * from "./src/commit";
2
+ export * from "./src/create";
3
+ export * from "./src/destory";