@zwa73/dev-utils 1.0.87 → 1.0.89

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.
Files changed (108) hide show
  1. package/bin/cli +2 -2
  2. package/data/template/base/package.json +6 -6
  3. package/data/template/base/scripts/compile.ps1 +23 -6
  4. package/data/template/base/tsconfig.cjs.json +2 -1
  5. package/data/template/base/tsconfig.json +3 -5
  6. package/data/template/base/tsconfig.mjs.json +2 -2
  7. package/data/template/base/tsconfig.types.json +8 -0
  8. package/data/template/cjs/gitignore +3 -0
  9. package/data/template/cjs/package.json +19 -0
  10. package/data/template/cjs/scripts/compile.ps1 +6 -0
  11. package/data/template/cjs/scripts/expand-macro.ps1 +2 -0
  12. package/data/template/cjs/scripts/release.ps1 +4 -0
  13. package/data/template/cjs/scripts/watch.ps1 +10 -0
  14. package/data/template/cjs/src/index.ts +0 -0
  15. package/data/template/cjs/src/macro.macro.ts +6 -0
  16. package/data/template/cjs/tsconfig.compile.json +12 -0
  17. package/data/template/cjs/tsconfig.json +21 -0
  18. package/data/template/electron/package.json +25 -25
  19. package/dist/{cjs/Command → Command}/GenI18n.js +14 -10
  20. package/dist/{cjs/Command → Command}/GenTemplate.js +7 -4
  21. package/dist/{cjs/Command → Command}/MapPath.js +34 -25
  22. package/dist/{cjs/Command → Command}/Release.js +3 -1
  23. package/dist/Command/ScanDups.js +122 -0
  24. package/dist/DynImport.d.ts +15 -0
  25. package/dist/DynImport.js +15 -0
  26. package/dist/{mjs/UtilAst.d.ts → UtilAst.d.ts} +1 -1
  27. package/dist/{cjs/UtilDevTool.js → UtilDevTool.js} +13 -34
  28. package/dist/UtilInterface.d.ts +8 -0
  29. package/dist/UtilMacro.d.ts +7 -0
  30. package/dist/{cjs/UtilMacro.js → UtilMacro.js} +2 -2
  31. package/package.json +2 -8
  32. package/dist/cjs/Command/ScanDups.js +0 -101
  33. package/dist/cjs/UtilAst.d.ts +0 -13
  34. package/dist/cjs/UtilInterface.d.ts +0 -4
  35. package/dist/cjs/UtilMacro.d.ts +0 -7
  36. package/dist/cjs/test/testFileMacro.d.ts +0 -1
  37. package/dist/cjs/test/testFileMacro.js +0 -1
  38. package/dist/cjs/test/testGlobMacro.d.ts +0 -1
  39. package/dist/cjs/test/testGlobMacro.js +0 -2
  40. package/dist/cjs/test/testRegex.d.ts +0 -1
  41. package/dist/cjs/test/testRegex.js +0 -3
  42. package/dist/cjs/test/testRegexa.d.ts +0 -1
  43. package/dist/cjs/test/testRegexa.js +0 -1
  44. package/dist/mjs/Command/ExpandMacro.d.ts +0 -3
  45. package/dist/mjs/Command/ExpandMacro.js +0 -16
  46. package/dist/mjs/Command/GenI18n.d.ts +0 -3
  47. package/dist/mjs/Command/GenI18n.js +0 -75
  48. package/dist/mjs/Command/GenSchema.d.ts +0 -3
  49. package/dist/mjs/Command/GenSchema.js +0 -22
  50. package/dist/mjs/Command/GenTemplate.d.ts +0 -3
  51. package/dist/mjs/Command/GenTemplate.js +0 -61
  52. package/dist/mjs/Command/MapPath.d.ts +0 -3
  53. package/dist/mjs/Command/MapPath.js +0 -64
  54. package/dist/mjs/Command/Node.d.ts +0 -3
  55. package/dist/mjs/Command/Node.js +0 -14
  56. package/dist/mjs/Command/Release.d.ts +0 -3
  57. package/dist/mjs/Command/Release.js +0 -88
  58. package/dist/mjs/Command/Route.d.ts +0 -1
  59. package/dist/mjs/Command/Route.js +0 -20
  60. package/dist/mjs/Command/RouteInterface.d.ts +0 -24
  61. package/dist/mjs/Command/RouteInterface.js +0 -58
  62. package/dist/mjs/Command/ScanDups.d.ts +0 -3
  63. package/dist/mjs/Command/ScanDups.js +0 -94
  64. package/dist/mjs/Command/index.d.ts +0 -1
  65. package/dist/mjs/Command/index.js +0 -1
  66. package/dist/mjs/QuickFunc.d.ts +0 -2
  67. package/dist/mjs/QuickFunc.js +0 -2
  68. package/dist/mjs/UtilAst.js +0 -15
  69. package/dist/mjs/UtilDevTool.d.ts +0 -99
  70. package/dist/mjs/UtilDevTool.js +0 -297
  71. package/dist/mjs/UtilInterface.d.ts +0 -4
  72. package/dist/mjs/UtilInterface.js +0 -1
  73. package/dist/mjs/UtilMacro.d.ts +0 -7
  74. package/dist/mjs/UtilMacro.js +0 -23
  75. package/dist/mjs/index.d.ts +0 -5
  76. package/dist/mjs/index.js +0 -5
  77. package/dist/mjs/test/testFileMacro.d.ts +0 -1
  78. package/dist/mjs/test/testFileMacro.js +0 -1
  79. package/dist/mjs/test/testGlobMacro.d.ts +0 -1
  80. package/dist/mjs/test/testGlobMacro.js +0 -2
  81. package/dist/mjs/test/testRegex.d.ts +0 -1
  82. package/dist/mjs/test/testRegex.js +0 -2
  83. package/dist/mjs/test/testRegexa.d.ts +0 -1
  84. package/dist/mjs/test/testRegexa.js +0 -1
  85. /package/dist/{cjs/Command → Command}/ExpandMacro.d.ts +0 -0
  86. /package/dist/{cjs/Command → Command}/ExpandMacro.js +0 -0
  87. /package/dist/{cjs/Command → Command}/GenI18n.d.ts +0 -0
  88. /package/dist/{cjs/Command → Command}/GenSchema.d.ts +0 -0
  89. /package/dist/{cjs/Command → Command}/GenSchema.js +0 -0
  90. /package/dist/{cjs/Command → Command}/GenTemplate.d.ts +0 -0
  91. /package/dist/{cjs/Command → Command}/MapPath.d.ts +0 -0
  92. /package/dist/{cjs/Command → Command}/Node.d.ts +0 -0
  93. /package/dist/{cjs/Command → Command}/Node.js +0 -0
  94. /package/dist/{cjs/Command → Command}/Release.d.ts +0 -0
  95. /package/dist/{cjs/Command → Command}/Route.d.ts +0 -0
  96. /package/dist/{cjs/Command → Command}/Route.js +0 -0
  97. /package/dist/{cjs/Command → Command}/RouteInterface.d.ts +0 -0
  98. /package/dist/{cjs/Command → Command}/RouteInterface.js +0 -0
  99. /package/dist/{cjs/Command → Command}/ScanDups.d.ts +0 -0
  100. /package/dist/{cjs/Command → Command}/index.d.ts +0 -0
  101. /package/dist/{cjs/Command → Command}/index.js +0 -0
  102. /package/dist/{cjs/QuickFunc.d.ts → QuickFunc.d.ts} +0 -0
  103. /package/dist/{cjs/QuickFunc.js → QuickFunc.js} +0 -0
  104. /package/dist/{cjs/UtilAst.js → UtilAst.js} +0 -0
  105. /package/dist/{cjs/UtilDevTool.d.ts → UtilDevTool.d.ts} +0 -0
  106. /package/dist/{cjs/UtilInterface.js → UtilInterface.js} +0 -0
  107. /package/dist/{cjs/index.d.ts → index.d.ts} +0 -0
  108. /package/dist/{cjs/index.js → index.js} +0 -0
package/bin/cli CHANGED
@@ -1,5 +1,5 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env node
2
2
 
3
- const {cliRoute} = require('../dist/cjs/index.js');
3
+ const {cliRoute} = require('../dist/index.js');
4
4
 
5
5
  cliRoute();
@@ -3,12 +3,12 @@
3
3
  "version": "1.0.0",
4
4
  "description": "<%= projectDescription %>",
5
5
  "exports": {
6
- ".": {
7
- "require": "./dist/cjs/index.js",
8
- "import": "./dist/mjs/index.js"
9
- }
10
- },
11
- "types": "./dist/mjs/index.d.ts",
6
+ ".": {
7
+ "require": "./dist/cjs/index.js",
8
+ "import": "./dist/mjs/index.mjs",
9
+ "types": "./dist/types/index.d.ts"
10
+ }
11
+ },
12
12
  "scripts": {
13
13
  "test": "jest",
14
14
  "expand-macro": "powershell scripts/expand-macro",
@@ -1,8 +1,25 @@
1
- Write-Output 开始删除原dist
1
+ npm run expand-macro
2
+ Write-Output 开始删除原dist
2
3
  Remove-Item -Recurse -Force dist
3
4
  Write-Output 开始编译
4
- tsc -p tsconfig.cjs.json
5
- tsc-alias -p tsconfig.cjs.json
6
- tsc -p tsconfig.mjs.json
7
- tsc-alias -p tsconfig.mjs.json
8
- tsc-esm-fix --tsconfig "./tsconfig.mjs.json"
5
+
6
+ $CurrentDir = Get-Location
7
+
8
+ Start-Job -Name "JobCjs" -ScriptBlock {
9
+ Set-Location $using:CurrentDir
10
+ tsc -p tsconfig.cjs.json
11
+ tsc-alias -p tsconfig.cjs.json
12
+ }
13
+ Start-Job -Name "JobMjs" -ScriptBlock {
14
+ Set-Location $using:CurrentDir
15
+ tsc -p tsconfig.mjs.json
16
+ tsc-alias -p tsconfig.mjs.json
17
+ tsc-esm-fix --tsconfig "./tsconfig.mjs.json" --ext ".mjs"
18
+ }
19
+ Start-Job -Name "JobTypes" -ScriptBlock {
20
+ Set-Location $using:CurrentDir
21
+ tsc -p tsconfig.types.json
22
+ tsc-alias -p tsconfig.types.json
23
+ }
24
+ Wait-Job -State Running
25
+ Get-Job | Receive-Job
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "extends": "./tsconfig.compile.json",
3
3
  "compilerOptions": {
4
- "module": "commonjs",
4
+ "module": "node16",
5
+ "moduleResolution": "node16",
5
6
  "outDir": "./dist/cjs",
6
7
  "target": "ES2022"
7
8
  }
@@ -2,16 +2,14 @@
2
2
  "compilerOptions": {
3
3
  "allowJs": true,
4
4
  "strict": true,
5
- "module": "commonjs",
6
- "moduleResolution": "node",
7
5
  "target": "ES2022",
6
+ "module": "node16",
7
+ "moduleResolution": "node16",
8
8
  "esModuleInterop": true,
9
- "outDir": "./dist",
10
- "declaration": true,
11
- "baseUrl": ".",
12
9
  "emitDecoratorMetadata": true,
13
10
  "experimentalDecorators": true,
14
11
  "skipLibCheck": true,
12
+ "baseUrl": ".",
15
13
  "paths": {
16
14
  "@/src/*" : ["./src/*"],
17
15
  "@/*" : ["./*"],
@@ -2,8 +2,8 @@
2
2
  "extends": "./tsconfig.compile.json",
3
3
  "compilerOptions": {
4
4
  "module": "ESNext",
5
+ "moduleResolution": "bundler",
5
6
  "outDir": "./dist/mjs",
6
- "target": "ESNext",
7
- "allowSyntheticDefaultImports": true
7
+ "target": "ESNext"
8
8
  }
9
9
  }
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "./tsconfig.compile.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist/types",
5
+ "declaration": true,
6
+ "emitDeclarationOnly": true
7
+ }
8
+ }
@@ -0,0 +1,3 @@
1
+ **/node_modules/**
2
+ **/test/**
3
+ dist/**
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "<%= projectName %>",
3
+ "version": "1.0.0",
4
+ "description": "<%= projectDescription %>",
5
+ "main": "dist/index.js",
6
+ "scripts": {
7
+ "test": "jest",
8
+ "expand-macro": "powershell scripts/expand-macro",
9
+ "release": "powershell scripts/release",
10
+ "compile": "powershell scripts/compile",
11
+ "watch": "powershell scripts/watch"
12
+ },
13
+ "author": "<%= authorName %>",
14
+ "license": "ISC",
15
+ "files": [
16
+ "data",
17
+ "dist"
18
+ ]
19
+ }
@@ -0,0 +1,6 @@
1
+ npm run expand-macro
2
+ Write-Output 开始删除原dist
3
+ Remove-Item -Recurse -Force dist
4
+ Write-Output 开始编译
5
+ tsc -p tsconfig.compile.json
6
+ tsc-alias -p tsconfig.compile.json
@@ -0,0 +1,2 @@
1
+ Write-Output 开始展开宏
2
+ npx zcli Expand-Macro
@@ -0,0 +1,4 @@
1
+ Write-Output 开始编译
2
+ npm run compile
3
+ Write-Output 开始发布
4
+ npx zcli release
@@ -0,0 +1,10 @@
1
+ # 定义一个函数来运行脚本
2
+ function New-Script {
3
+ param($command)
4
+ # 在后台运行命令
5
+ Start-Process -NoNewWindow -FilePath "powershell" -ArgumentList "-Command", $command
6
+ }
7
+
8
+ # 开始运行脚本
9
+ New-Script "tsc -w -p tsconfig.compile.json"
10
+ New-Script "tsc-alias -w -p tsconfig.compile.json"
File without changes
@@ -0,0 +1,6 @@
1
+ import { UtilMacro } from '@zwa73/dev-utils';
2
+
3
+
4
+
5
+
6
+ UtilMacro.exportComment('src/**/index.ts');
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "module": "node16",
5
+ "moduleResolution": "node16",
6
+ "outDir": "./dist",
7
+ "target": "ES2022",
8
+ "declaration": true
9
+ },
10
+ "include": ["./src/**/*.ts", "./src/**/*.js"],
11
+ "exclude": ["./node_modules/**/*","./src/**/*.macro.ts","./src/**/*.schema.ts"]
12
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "allowJs": true,
4
+ "strict": true,
5
+ "target": "ES2022",
6
+ "module": "node16",
7
+ "moduleResolution": "node16",
8
+ "esModuleInterop": true,
9
+ "emitDecoratorMetadata": true,
10
+ "experimentalDecorators": true,
11
+ "skipLibCheck": true,
12
+ "baseUrl": ".",
13
+ "paths": {
14
+ "@/src/*" : ["./src/*"],
15
+ "@/*" : ["./*"],
16
+ "@" : ["./src/index"]
17
+ }
18
+ },
19
+ "include": ["./src/**/*.ts", "./src/**/*.js","./jest/**/*.ts"],
20
+ "exclude": ["./node_modules/**/*"]
21
+ }
@@ -12,29 +12,29 @@
12
12
  "lint": "eslint --ext .ts,.tsx ."
13
13
  },
14
14
  "devDependencies": {
15
- "@babel/core": "^7.25.2",
16
- "@babel/preset-react": "^7.24.7",
17
- "@electron-forge/cli": "^7.4.0",
18
- "@electron-forge/maker-deb": "^7.4.0",
19
- "@electron-forge/maker-rpm": "^7.4.0",
20
- "@electron-forge/maker-squirrel": "^7.4.0",
21
- "@electron-forge/maker-zip": "^7.4.0",
22
- "@electron-forge/plugin-auto-unpack-natives": "^7.4.0",
23
- "@electron-forge/plugin-fuses": "^7.4.0",
24
- "@electron-forge/plugin-webpack": "^7.4.0",
25
- "@electron/fuses": "^1.8.0",
15
+ "@babel/core": "7.25.2",
16
+ "@babel/preset-react": "7.24.7",
17
+ "@electron-forge/cli": "7.4.0",
18
+ "@electron-forge/maker-deb": "7.4.0",
19
+ "@electron-forge/maker-rpm": "7.4.0",
20
+ "@electron-forge/maker-squirrel": "7.4.0",
21
+ "@electron-forge/maker-zip": "7.4.0",
22
+ "@electron-forge/plugin-auto-unpack-natives": "7.4.0",
23
+ "@electron-forge/plugin-fuses": "7.4.0",
24
+ "@electron-forge/plugin-webpack": "7.4.0",
25
+ "@electron/fuses": "1.8.0",
26
26
  "@types/node": "^22.5.2",
27
- "@types/react": "^18.3.5",
28
- "@types/react-dom": "^18.3.0",
29
- "@vercel/webpack-asset-relocator-loader": "^1.7.3",
30
- "babel-loader": "^9.1.3",
31
- "css-loader": "^6.11.0",
32
- "electron": "*",
33
- "fork-ts-checker-webpack-plugin": "^7.3.0",
34
- "node-loader": "^2.0.0",
35
- "style-loader": "^3.3.4",
36
- "ts-loader": "^9.5.1",
37
- "ts-node": "^10.9.2",
27
+ "@types/react": "18.3.5",
28
+ "@types/react-dom": "18.3.0",
29
+ "@vercel/webpack-asset-relocator-loader": "1.7.3",
30
+ "babel-loader": "9.1.3",
31
+ "css-loader": "6.11.0",
32
+ "electron": "31.3.1",
33
+ "fork-ts-checker-webpack-plugin": "7.3.0",
34
+ "node-loader": "2.0.0",
35
+ "style-loader": "3.3.4",
36
+ "ts-loader": "9.5.1",
37
+ "ts-node": "10.9.2",
38
38
  "tsconfig-paths-webpack-plugin": "^4.1.0",
39
39
  "typescript": "~4.5.4"
40
40
  },
@@ -46,9 +46,9 @@
46
46
  "dependencies": {
47
47
  "@zwa73/react-utils": "*",
48
48
  "@zwa73/utils": "*",
49
- "electron-squirrel-startup": "^1.0.1",
50
- "react": "^18.3.1",
51
- "react-dom": "^18.3.1",
49
+ "electron-squirrel-startup": "1.0.1",
50
+ "react": "18.3.1",
51
+ "react-dom": "18.3.1",
52
52
  "styled-components": "^6.1.13"
53
53
  }
54
54
  }
@@ -5,18 +5,20 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.CmdGenI18n = void 0;
7
7
  const utils_1 = require("@zwa73/utils");
8
- const ts_morph_1 = require("ts-morph");
9
8
  const UtilAst_1 = require("../UtilAst");
10
9
  const pathe_1 = __importDefault(require("pathe"));
10
+ const DynImport_1 = require("../DynImport");
11
11
  function format(str) {
12
12
  return str.replace(/\\(.)/g, '$1').replace(/%/g, '\\%');
13
13
  }
14
14
  async function procFile(p, filePath, funckey) {
15
+ const TsMorph = await (0, DynImport_1.importTsMorph)();
16
+ const { SyntaxKind } = TsMorph;
15
17
  const date = new Date().toISOString();
16
18
  //const content = await fs.promises.readFile(filePath,'utf-8');
17
19
  const b = p.addSourceFileAtPath(filePath);
18
20
  //const b = p.createSourceFile(path.relative(process.cwd(),filePath),content,{overwrite:true});
19
- const ds = b.getDescendantsOfKind(ts_morph_1.SyntaxKind.TaggedTemplateExpression);
21
+ const ds = b.getDescendantsOfKind(SyntaxKind.TaggedTemplateExpression);
20
22
  const dats = [];
21
23
  for (const d of ds) {
22
24
  if (!funckey.includes(d.getTag().getText()))
@@ -25,17 +27,17 @@ async function procFile(p, filePath, funckey) {
25
27
  let result = '';
26
28
  let i = 0;
27
29
  UtilAst_1.UtilAst.withKind(template, {
28
- [ts_morph_1.SyntaxKind.NoSubstitutionTemplateLiteral]: (t) => result += format(t.getLiteralText()),
29
- [ts_morph_1.SyntaxKind.TemplateExpression]: (t) => {
30
+ [SyntaxKind.NoSubstitutionTemplateLiteral]: (t) => result += format(t.getLiteralText()),
31
+ [SyntaxKind.TemplateExpression]: (t) => {
30
32
  t.getChildren().forEach((c) => {
31
33
  UtilAst_1.UtilAst.withKind(c, {
32
- [ts_morph_1.SyntaxKind.TemplateHead]: (sc) => result += format(sc.getLiteralText()),
33
- [ts_morph_1.SyntaxKind.SyntaxList]: (sc) => {
34
- sc.getChildrenOfKind(ts_morph_1.SyntaxKind.TemplateSpan).forEach((span) => {
34
+ [SyntaxKind.TemplateHead]: (sc) => result += format(sc.getLiteralText()),
35
+ [SyntaxKind.SyntaxList]: (sc) => {
36
+ sc.getChildrenOfKind(SyntaxKind.TemplateSpan).forEach((span) => {
35
37
  span.getChildren().forEach((ssc) => {
36
38
  result += UtilAst_1.UtilAst.withKind(ssc, {
37
- [ts_morph_1.SyntaxKind.TemplateMiddle]: (sssc) => format(sssc.getLiteralText()),
38
- [ts_morph_1.SyntaxKind.TemplateTail]: (sssc) => format(sssc.getLiteralText()),
39
+ [SyntaxKind.TemplateMiddle]: (sssc) => format(sssc.getLiteralText()),
40
+ [SyntaxKind.TemplateTail]: (sssc) => format(sssc.getLiteralText()),
39
41
  }) ?? String(`%${i++}`);
40
42
  });
41
43
  });
@@ -57,10 +59,12 @@ async function procFile(p, filePath, funckey) {
57
59
  return dats;
58
60
  }
59
61
  async function scanI18n(i18nDataDir, include, exclude, funckey) {
62
+ const TsMorph = await (0, DynImport_1.importTsMorph)();
63
+ const { Project } = TsMorph;
60
64
  const fixedKey = typeof funckey == 'string' ? [funckey] : funckey;
61
65
  const filePaths = (await utils_1.UtilFT.fileSearchGlob(process.cwd(), include, { ingore: exclude }))
62
66
  .filter(p => ['.ts', '.tsx'].includes(pathe_1.default.parse(p).ext));
63
- const project = new ts_morph_1.Project();
67
+ const project = new Project();
64
68
  await utils_1.SI18n.init(i18nDataDir, '*');
65
69
  //console.log(filePaths);
66
70
  (await Promise.all(filePaths.map(p => procFile(project, p, fixedKey))))
@@ -41,7 +41,7 @@ const CmdGenTemplate = (program) => program
41
41
  .command("Gen-Template")
42
42
  .alias("gentemplate")
43
43
  .description("生成项目模板")
44
- .argument("<template>", "项目模板 可用 base|electron")
44
+ .argument("<template>", "项目模板 可用 base|cjs|electron")
45
45
  .requiredOption("-n, --projectName <name>", "项目名称")
46
46
  .requiredOption("-d, --projectDescription <description>", "项目描述")
47
47
  .requiredOption("-a, --authorName <name>", "作者名")
@@ -51,15 +51,18 @@ const CmdGenTemplate = (program) => program
51
51
  utils_1.SLogger.error(`模板 ${templateName} 不存在`);
52
52
  const projectPath = pathe_1.default.join(process.cwd(), opt.projectName);
53
53
  await utils_1.UtilFT.ensurePathExists(projectPath, { dir: true });
54
+ //复制模板
54
55
  await copyData(templatePath, projectPath);
55
- await installPackage(projectPath, ['@zwa73/utils'], ['@types/node']);
56
- if (await utils_1.UtilFT.pathExists(pathe_1.default.join(projectPath, "gitignore")))
57
- await fs_1.default.promises.rename(pathe_1.default.join(projectPath, "gitignore"), pathe_1.default.join(projectPath, ".gitignore"));
56
+ //修改package.json
58
57
  const packageJson = await utils_1.UtilFT.loadJSONFile(pathe_1.default.join(projectPath, 'package.json'));
59
58
  packageJson.name = opt.projectName;
60
59
  packageJson.description = opt.projectDescription;
61
60
  packageJson.author = opt.authorName;
62
61
  await utils_1.UtilFT.writeJSONFile(pathe_1.default.join(projectPath, 'package.json'), packageJson);
62
+ //安装依赖
63
+ await installPackage(projectPath, ['@zwa73/utils'], ['@types/node']);
64
+ if (await utils_1.UtilFT.pathExists(pathe_1.default.join(projectPath, "gitignore")))
65
+ await fs_1.default.promises.rename(pathe_1.default.join(projectPath, "gitignore"), pathe_1.default.join(projectPath, ".gitignore"));
63
66
  switch (templateName) {
64
67
  case 'base': break;
65
68
  case 'electron': break;
@@ -7,8 +7,7 @@ exports.CmdMapPath = void 0;
7
7
  const utils_1 = require("@zwa73/utils");
8
8
  const fs_1 = __importDefault(require("fs"));
9
9
  const pathe_1 = __importDefault(require("pathe"));
10
- const DupMethodList = ["skip", "overwrite", "move"];
11
- const DupMethodWithoutMove = DupMethodList.filter(t => t != 'move');
10
+ const DupMethodList = ["skip", "overwrite"];
12
11
  /**重命名文件或路径 */
13
12
  const CmdMapPath = (program) => program
14
13
  .command("Map-Path")
@@ -17,12 +16,14 @@ const CmdMapPath = (program) => program
17
16
  .argument("<regex>", "要匹配的正则表达式, posix风格路径")
18
17
  .argument("<replacement>", "替换字符串")
19
18
  .option("-e, --exclude <regex>", "排除文件的正则表达式")
20
- .option(`-d, --duplicate-handling <${DupMethodWithoutMove.join('|')}|[path:string]>`, `处理重名文件的方式:
19
+ .option(`-d, --duplicate-handling <${DupMethodList.join('|')}|[path:string]>`, `处理重名文件的方式:
21
20
  skip 不进行处理
22
21
  overwrite 覆盖重名
23
22
  其他字符串 将重名部分映射到指定目录下的对应位置, 再次重复将会覆盖`, "skip")
24
23
  .option("-r, --recursive", "是否处理子目录", false)
25
24
  .option("-m, --move", "重命名而不是复制文件", false)
25
+ .option("-o, --output <path>", "输出到某个绝对路径而非当前目录", '')
26
+ .option("-i, --input <path>", "扫描某个绝对路径而非当前目录", '')
26
27
  .option("-t, --test", "不对文件进行实际操作, 在控制台输出映射结果", false)
27
28
  .action(async (regexStr, replacement, options) => {
28
29
  const regex = new RegExp(regexStr);
@@ -30,42 +31,50 @@ overwrite 覆盖重名
30
31
  if (!DupMethodList.includes(options.duplicateHandling))
31
32
  (0, utils_1.throwError)(`${options.duplicateHandling} 不是有效的 duplicate-handling`);
32
33
  const duplicateHandling = options.duplicateHandling;
33
- const basePath = process.cwd();
34
+ const absout = options.output.length > 0;
35
+ const absin = options.input.length > 0;
36
+ const searchPath = absin ? options.input : process.cwd();
37
+ const outPath = absout ? options.output : process.cwd();
34
38
  // 遍历当前目录下的所有文件
35
- const filePaths = (await utils_1.UtilFT.fileSearchRegex(basePath, regex.source, { relative: options.recursive }))
36
- .map((filePath) => pathe_1.default.relative(basePath, filePath))
37
- .filter((filePath) => excludeRegex ? (!excludeRegex.test(filePath)) : true);
39
+ const filePaths = (await utils_1.UtilFT.fileSearchRegex(searchPath, regex, { relative: options.recursive }))
40
+ .map(fp => pathe_1.default.relative(searchPath, fp))
41
+ .filter(fp => excludeRegex ? (!excludeRegex.test(fp)) : true);
38
42
  //对单个路径映射
39
43
  const mapPath = async (source, target) => {
40
- const dir = pathe_1.default.parse(target).dir;
41
- await utils_1.UtilFT.ensurePathExists(dir, { dir: true });
42
44
  if (options.test)
43
45
  return utils_1.SLogger.info(`${source} -> ${target}`);
46
+ const dir = pathe_1.default.parse(target).dir;
47
+ await utils_1.UtilFT.ensurePathExists(dir, { dir: true });
44
48
  if (options.move)
45
- await fs_1.default.promises.rename(source, target);
46
- else
47
- await fs_1.default.promises.copyFile(source, target);
49
+ return fs_1.default.promises.rename(source, target);
50
+ return fs_1.default.promises.copyFile(source, target);
48
51
  };
49
- for (const filePath of filePaths) {
52
+ await Promise.all(filePaths.map(async (rawfilePath) => {
53
+ const filePath = pathe_1.default.normalize(rawfilePath);
54
+ const replacedFilePath = filePath.replace(regex, replacement);
50
55
  // 重命名文件
51
- const newFilePath = filePath.replace(regex, replacement);
56
+ const oldFilePath = absin
57
+ ? pathe_1.default.join(searchPath, filePath)
58
+ : filePath;
59
+ const newFilePath = absout
60
+ ? pathe_1.default.join(outPath, replacedFilePath) //如果是绝对路径输出则拼接绝对路径
61
+ : replacedFilePath;
52
62
  // 如果文件名发生了变化
53
- if (newFilePath === filePath)
54
- continue;
63
+ if (newFilePath === oldFilePath)
64
+ return;
55
65
  //如果文件已存在
56
66
  if (await utils_1.UtilFT.pathExists(newFilePath)) {
57
- if (DupMethodWithoutMove.includes(options.duplicateHandling)) {
58
- const fixhd = duplicateHandling;
59
- await (0, utils_1.match)(fixhd, {
67
+ //如果是跳过或覆盖
68
+ if (DupMethodList.includes(options.duplicateHandling)) {
69
+ return (0, utils_1.match)(duplicateHandling, {
60
70
  'skip': () => utils_1.SLogger.info(`重名文件存在,跳过:${newFilePath}`),
61
- 'overwrite': () => mapPath(filePath, newFilePath),
71
+ 'overwrite': () => mapPath(oldFilePath, newFilePath),
62
72
  });
63
73
  }
64
- else
65
- await mapPath(filePath, pathe_1.default.join(duplicateHandling, newFilePath));
74
+ //如果是转移位置
75
+ return mapPath(oldFilePath, pathe_1.default.join(outPath, duplicateHandling, replacedFilePath));
66
76
  }
67
- else
68
- await mapPath(filePath, newFilePath);
69
- }
77
+ return mapPath(oldFilePath, newFilePath);
78
+ }));
70
79
  });
71
80
  exports.CmdMapPath = CmdMapPath;
@@ -34,6 +34,8 @@ function checkVersion(oldVersion, newVersion) {
34
34
  async function updateVersion(newVersion) {
35
35
  const packagePath = pathe_1.default.join(RouteInterface_1.PROCESS_PATH, "package.json");
36
36
  const packageData = await (0, utils_1.memoize)(utils_1.UtilFT.loadJSONFile)(packagePath);
37
+ if (newVersion == 'current')
38
+ return packageData.version;
37
39
  if (newVersion) {
38
40
  checkVersion(packageData.version, newVersion);
39
41
  packageData.version = newVersion;
@@ -59,7 +61,7 @@ const CmdRelease = (program) => program
59
61
  .command("Release")
60
62
  .alias("release")
61
63
  .description("更新版本号并发布包")
62
- .option("-v, --version <version>", "指定发布的版本号 格式应为 `${number}.${number}.${number}`")
64
+ .option("-v, --version <version>", "指定发布的版本号, 为 `current` 时不更新版本号, 格式应为 `${number}.${number}.${number}`")
63
65
  .option("-a, --access <access>", "npm publish 的 access 参数 默认 public", "public")
64
66
  .option("-l, --local <path>", "仅打包到本地对印目录下 如./build/", undefined)
65
67
  .action(async (opt) => {
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CmdScanDups = void 0;
7
+ const utils_1 = require("@zwa73/utils");
8
+ const pathe_1 = __importDefault(require("pathe"));
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const DynImport_1 = require("../DynImport");
11
+ const { tap } = utils_1.UtilFP;
12
+ /**hashlist转为dupmap */
13
+ const reduce2Dupmap = (list) => list.reduce((acc, cur) => {
14
+ const files = acc[cur.hash] ?? [];
15
+ acc[cur.hash] = [...files, cur.filePath]; // 分类采样哈希到对应文件路径
16
+ return acc;
17
+ }, {});
18
+ /**从dupmap提取重复的filepath */
19
+ const reduce2DupFpList = (map) => Object.entries(map).reduce((acc, [hash, files]) => files.length > 1 ? [...acc, ...files] : acc, // 筛选出重复采样哈希的文件路径
20
+ []);
21
+ /**扫描文件结构 */
22
+ const scanDirStruct = (0, utils_1.memoize)(async (root) => {
23
+ const list = await fs_1.default.promises.readdir(root, { withFileTypes: true });
24
+ const stack = await Promise.all(list.map(async (fp) => fp.isDirectory()
25
+ ? [fp.name, await scanDirStruct(pathe_1.default.join(root, fp.name))]
26
+ : [fp.name, pathe_1.default.join(root, fp.name)]));
27
+ return stack.reduce((acc, cur) => ({
28
+ ...acc, [cur[0]]: cur[1],
29
+ }), {});
30
+ });
31
+ const hashQueue = new utils_1.PromiseQueue({ concurrency: 8 });
32
+ /**计算文件结构的hash */
33
+ async function struct2hash(struct, fn) {
34
+ const recursion = (struct) => {
35
+ return Object.entries(struct).map(async ([k, v]) => {
36
+ if (typeof v === "string")
37
+ return [await hashQueue.enqueue(async () => fn(v))];
38
+ return (await Promise.all(recursion(v))).flat();
39
+ });
40
+ };
41
+ return utils_1.UtilFunc.calcHash((await Promise.all(recursion(struct)))
42
+ .flat().join('|'), { algorithm: "blake2b512" });
43
+ }
44
+ /**重命名文件或路径 scan_duplicates */
45
+ const CmdScanDups = (program) => program
46
+ .command("Scan-Dups")
47
+ .alias("scandups")
48
+ .description("扫描当前目录下hash重复的文件")
49
+ .option("-i, --include <regex>", "文件的正则表达式, 使用posix路径", ".*")
50
+ .option("-o, --out <dir|console>", "输出的json文件路径, 默认 scandups.json, 为 \"console\" 时无文件输出", "scandups")
51
+ .option("-r, --recursive", "是否处理子目录, 默认 true", true)
52
+ .option("-s, --struct", `结构模式
53
+ 只扫描 -i 参数目录下的单层目录, 并计算目录是否出现相同的层次结构
54
+ 默认 false`, true)
55
+ .option("-d, --dir <dirs...>", `扫描的根目录, 以空格分隔 -d "a/b c" "d e/f", 默认为命令行当前目录`, [])
56
+ .action(async (options) => {
57
+ const { out: outtype, recursive, include, struct, dir } = options;
58
+ const regex = new RegExp(include);
59
+ const basePath = process.cwd();
60
+ const pathList = dir.length <= 0
61
+ ? [process.cwd()]
62
+ : dir.map(d => pathe_1.default.isAbsolute(d) ? d : pathe_1.default.join(process.cwd(), d));
63
+ // 添加一个多步进度条
64
+ const cliProgress = await (0, DynImport_1.importCliProgress)();
65
+ const progressBar = new cliProgress.MultiBar({
66
+ clearOnComplete: true, hideCursor: true,
67
+ format: " {task} [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | {status}",
68
+ }, cliProgress.Presets.shades_classic);
69
+ // 文件结构进度条
70
+ const structProgress = struct ? progressBar.create(1, 0, { task: "结构扫描", status: "准备中..." }) : undefined;
71
+ // 采样哈希进度条
72
+ const sampledProgress = progressBar.create(1, 0, { task: "快速扫描", status: "准备中..." });
73
+ // 完整哈希进度条
74
+ const fullHashProgress = progressBar.create(1, 0, { task: "完整扫描", status: "准备中..." });
75
+ await (0, utils_1.pipe)(
76
+ // 第一步:文件搜索,获取符合正则的文件路径
77
+ Promise.all(pathList.map(async (p) => {
78
+ if (struct)
79
+ return (await fs_1.default.promises.readdir(p, { withFileTypes: true }))
80
+ .filter(fp => fp.isDirectory())
81
+ .map(fp => pathe_1.default.join(p, fp.name));
82
+ return await utils_1.UtilFT.fileSearchRegex(p, regex.source, { recursive });
83
+ })), stacklist => stacklist.flat(), // 扁平化文件路径列表
84
+ // 如果是结构模式则先筛选相同结构
85
+ // 扁平化文件路径列表
86
+ list => struct ? (0, utils_1.pipe)(list, tap(dupFpList => (structProgress.setTotal(dupFpList.length),
87
+ structProgress.update(0, { status: `结构扫描检出 ${dupFpList.length} 个可能的相等项` }))), list => utils_1.Stream.from(list, 8)
88
+ .map(async (filePath) => ({
89
+ filePath,
90
+ hash: await struct2hash(await scanDirStruct(filePath), cpath => pathe_1.default.relative(filePath, cpath)).then(tap(() => structProgress.increment()))
91
+ }))
92
+ .toArray(), reduce2Dupmap, reduce2DupFpList) : list,
93
+ // 第二步:快速扫描,计算采样哈希
94
+ tap(list => (sampledProgress.setTotal(list.length),
95
+ sampledProgress.update(0, { status: `总计 ${list.length} 个文件` }))), list => utils_1.Stream.from(list, 8)
96
+ .map(async (filePath) => ({
97
+ filePath,
98
+ hash: struct
99
+ ? await struct2hash(await scanDirStruct(filePath), (str) => utils_1.UtilFT.calculateHash(str, { sampled: true })).then(tap(() => sampledProgress.increment()))
100
+ : await utils_1.UtilFT.calculateHash(filePath, { sampled: true }).then(tap(() => sampledProgress.increment())),
101
+ }))
102
+ .toArray(),
103
+ // 第三步:筛选重复的采样哈希 (去掉唯一的采样哈希)
104
+ reduce2Dupmap, reduce2DupFpList,
105
+ // 第四步:对筛选出的重复文件路径并发计算完整哈希
106
+ tap(dupFpList => (fullHashProgress.setTotal(dupFpList.length),
107
+ fullHashProgress.update(0, { status: `快速扫描检出 ${dupFpList.length} 个可能的相等项` }))), dupFpList => utils_1.Stream.from(dupFpList, 8)
108
+ .map(async (filePath) => ({
109
+ filePath,
110
+ hash: struct
111
+ ? await struct2hash(await scanDirStruct(filePath), (str) => utils_1.UtilFT.calculateHash(str)).then(tap(() => sampledProgress.increment()))
112
+ : await utils_1.UtilFT.calculateHash(filePath).then(tap(() => fullHashProgress.increment())), // 计算完整哈希
113
+ }))
114
+ .toArray(),
115
+ // 第五步:重新整理完整哈希结果, 过滤唯一哈希
116
+ reduce2Dupmap, map => Object.entries(map).reduce((acc, [hash, files]) => files.length <= 1 ? acc : { ...acc, [hash]: files }, {}),
117
+ // 第六步:输出结果
118
+ tap(() => progressBar.stop()), out => (0, utils_1.match)(outtype, {
119
+ "console": () => utils_1.SLogger.info(out),
120
+ }, () => utils_1.UtilFT.writeJSONFile(pathe_1.default.join(basePath, outtype), out)));
121
+ });
122
+ exports.CmdScanDups = CmdScanDups;
@@ -0,0 +1,15 @@
1
+ import type { getProgramFromFiles, buildGenerator } from 'typescript-json-schema';
2
+ import type { Project, SyntaxKind } from 'ts-morph';
3
+ import type cliProgress from "cli-progress";
4
+ type TJSInstance = {
5
+ getProgramFromFiles: typeof getProgramFromFiles;
6
+ buildGenerator: typeof buildGenerator;
7
+ };
8
+ type TsMorphInstance = {
9
+ Project: typeof Project;
10
+ SyntaxKind: typeof SyntaxKind;
11
+ };
12
+ export declare function importTsMorph(): Promise<TsMorphInstance>;
13
+ export declare function importTJS(): Promise<TJSInstance>;
14
+ export declare function importCliProgress(): Promise<typeof cliProgress>;
15
+ export {};