ohos-router 1.2.5 → 1.2.7

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/router.ts CHANGED
@@ -1,482 +1,614 @@
1
- import {HvigorNode, FileUtil} from '@ohos/hvigor';
1
+ import { HvigorNode, FileUtil } from '@ohos/hvigor';
2
2
 
3
3
  let entryModulePath = ""
4
4
  let entryUpperCaseNameArray: string[] = []
5
5
  let entryIsHsp: boolean[] = []
6
-
7
- export function pluginStart(node: HvigorNode, isExecute: boolean, filterModule: string[]) {
8
- if (!isExecute) {
9
- return
10
- }
11
- entryUpperCaseNameArray = []
12
- entryIsHsp = []
13
- node.subNodes((childNode: HvigorNode) => {
14
- try {
15
- let hvigorfilePath = FileUtil.pathResolve(childNode.getNodePath(), "hvigorfile.ts")
16
- let hvigorfileData = FileUtil.readFileSync(hvigorfilePath);
17
- let isHsp = hvigorfileData.indexOf("hspTasks") != -1
18
- let isHap = hvigorfileData.indexOf("hapTasks") != -1
19
- let nodeName = childNode.getNodeName()
20
- let upperCaseName = nodeName.substring(0, 1).toUpperCase() + nodeName.substring(1, nodeName.length)
21
- //默认Entry不追加
22
- let isFilter = filterModule.includes(nodeName)//是否包含
23
-
24
- if ("Entry" != upperCaseName && !isFilter) {
25
- entryUpperCaseNameArray.push(upperCaseName)
26
- entryIsHsp.push(isHsp)
27
- }
28
-
29
- let configPath = FileUtil.pathResolve(childNode.getNodePath(), upperCaseName + "RouterConfig.ets")
30
-
31
- if (!FileUtil.exist(configPath) && !isFilter) {
32
- FileUtil.ensureFileSync(configPath)
33
- FileUtil.writeFileSync(configPath, getRouterConfig(upperCaseName, nodeName, isHsp))
34
- if (!isHap) {
35
- let indexFilePath = FileUtil.pathResolve(childNode.getNodePath(), "Index.ets")
36
- let indexFileData = FileUtil.readFileSync(indexFilePath);
37
- if (indexFileData.indexOf(upperCaseName) == -1) {
38
- indexFileData = "export { " + upperCaseName +
39
- "RouterConfig } from './" + upperCaseName +
40
- "RouterConfig'\n" + indexFileData
41
-
42
- FileUtil.writeFileSync(indexFilePath, indexFileData)
43
- }
44
- }
6
+ let tempModuleName: string = ""
7
+
8
+ export function pluginStart(node: HvigorNode, isExecute: boolean,
9
+ filterModule: string[], moduleName: string) {
10
+ tempModuleName = moduleName;
11
+ if (!isExecute) {
12
+ return
13
+ }
14
+ entryUpperCaseNameArray = []
15
+ entryIsHsp = []
16
+ node.subNodes((childNode: HvigorNode) => {
17
+ try {
18
+ let hvigorfilePath = FileUtil.pathResolve(childNode.getNodePath(), "hvigorfile.ts")
19
+ let hvigorfileData = FileUtil.readFileSync(hvigorfilePath);
20
+ let isHsp = hvigorfileData.indexOf("hspTasks") != -1
21
+ let isHap = hvigorfileData.indexOf("hapTasks") != -1
22
+ let nodeName = childNode.getNodeName()
23
+ let upperCaseName = nodeName.substring(0, 1).toUpperCase() + nodeName.substring(1, nodeName.length)
24
+ //默认Entry不追加
25
+ let isFilter = filterModule.includes(nodeName) //是否包含
26
+
27
+ if ("Entry" != upperCaseName && !isFilter) {
28
+ entryUpperCaseNameArray.push(upperCaseName)
29
+ entryIsHsp.push(isHsp)
30
+ }
31
+
32
+ let configPath = FileUtil.pathResolve(childNode.getNodePath(), upperCaseName + "RouterConfig.ets")
33
+
34
+ if (!FileUtil.exist(configPath) && !isFilter) {
35
+ FileUtil.ensureFileSync(configPath)
36
+ FileUtil.writeFileSync(configPath, getRouterConfig(upperCaseName, nodeName, isHsp))
37
+ if (!isHap) {
38
+ let indexFilePath = FileUtil.pathResolve(childNode.getNodePath(), "Index.ets")
39
+ let indexFileData = FileUtil.readFileSync(indexFilePath);
40
+ if (indexFileData.indexOf(upperCaseName) == -1) {
41
+ indexFileData = "export { " + upperCaseName +
42
+ "RouterConfig } from './" + upperCaseName +
43
+ "RouterConfig'\n" + indexFileData
44
+ FileUtil.writeFileSync(indexFilePath, indexFileData)
45
+ }
46
+ }
47
+ }
48
+
49
+ if (isHap && !isFilter) {
50
+ entryModulePath = childNode.getNodePath()
51
+ writeBuildProfile(childNode)
52
+ }
53
+
54
+ let fileList = childNode.getNodeDir()
55
+ .asFileList()
56
+ .filter(item => {
57
+ return item.getPath().endsWith(".ets") && item.getPath().indexOf("build") == -1 &&
58
+ item.getPath().indexOf("oh_modules") == -1 && item.getPath().indexOf("ohosTest") == -1
59
+ })
60
+
61
+ fileList.forEach((file) => {
62
+ let data = FileUtil.readFileSync(file.filePath);
63
+ //非注释情况下才进行判断
64
+ if (data.indexOf("@RouterPath") != -1 && !isIdentifierInCommentOrString(data.toString(), "@RouterPath")) {
65
+ let routerPathEnd = data.toString().split("@RouterPath")[1]
66
+ let routerName = ""
67
+ if (routerPathEnd.startsWith("(\"")) {
68
+ routerName = routerPathEnd.substring(2, routerPathEnd.indexOf(")") - 1)
69
+ } else {
70
+ routerName = routerPathEnd.substring(1, routerPathEnd.indexOf(")"))
71
+ }
72
+ var importPath = "./src" + file.filePath.split("src")[1]
73
+ importPath = importPath.replace(".ets", "").replaceAll("\\", "/")
74
+ let viewName = importPath.substring(importPath.lastIndexOf("/") + 1, importPath.length)
75
+ let fileData = FileUtil.readFileSync(configPath)
76
+ if (fileData.indexOf(routerName) == -1) {
77
+ let switchTag = "switch (builderName) {"
78
+ let switchPosition = fileData.indexOf(switchTag) + switchTag.length
79
+
80
+ let switchBuilder = ""
81
+
82
+ if (routerPathEnd.startsWith("(\"")) {
83
+ switchBuilder = "\n case \"" + routerName + "\":\n" +
84
+ " import(\"" + importPath + "\")\n" +
85
+ " break"
86
+ } else {
87
+ switchBuilder = "\n case " + routerName + ":\n" +
88
+ " import(\"" + importPath + "\")\n" +
89
+ " break"
45
90
  }
46
91
 
47
- if (isHap && !isFilter) {
48
- entryModulePath = childNode.getNodePath()
49
- writeBuildProfile(childNode)
50
- }
92
+ let configEnd = insertString(fileData, switchPosition, switchBuilder)
51
93
 
52
- let fileList = childNode.getNodeDir()
53
- .asFileList()
54
- .filter(item => {
55
- return item.getPath().endsWith(".ets") && item.getPath().indexOf("build") == -1 &&
56
- item.getPath().indexOf("oh_modules") == -1 && item.getPath().indexOf("ohosTest") == -1
57
- })
58
-
59
- fileList.forEach((file) => {
60
- let data = FileUtil.readFileSync(file.filePath);
61
- if (data.indexOf("@RouterPath") != -1) {
62
- let routerPathEnd = data.toString().split("@RouterPath")[1]
63
- let routerName = ""
64
- if (routerPathEnd.startsWith("(\"")) {
65
- routerName = routerPathEnd.substring(2, routerPathEnd.indexOf(")") - 1)
66
- } else {
67
- routerName = routerPathEnd.substring(1, routerPathEnd.indexOf(")"))
68
- }
69
- var importPath = "./src" + file.filePath.split("src")[1]
70
- importPath = importPath.replace(".ets", "").replaceAll("\\", "/")
71
- let viewName = importPath.substring(importPath.lastIndexOf("/") + 1, importPath.length)
72
- let fileData = FileUtil.readFileSync(configPath)
73
- if (fileData.indexOf(routerName) == -1) {
74
- let switchTag = "switch (builderName) {"
75
- let switchPosition = fileData.indexOf(switchTag) + switchTag.length
76
-
77
- let switchBuilder = ""
78
-
79
- if (routerPathEnd.startsWith("(\"")) {
80
- switchBuilder = "\n case \"" + routerName + "\":\n" +
81
- " import(\"" + importPath + "\")\n" +
82
- " break"
83
- } else {
84
- switchBuilder = "\n case " + routerName + ":\n" +
85
- " import(\"" + importPath + "\")\n" +
86
- " break"
87
- }
88
-
89
- let configEnd = insertString(fileData, switchPosition, switchBuilder)
90
-
91
- let destinationEnd = ""
92
- let DestinationTag = "NavDestinationView() {"
93
- let destinationPosition = configEnd.indexOf(DestinationTag) + DestinationTag.length
94
-
95
- let destinationBuilder = ""
96
- if (routerPathEnd.startsWith("(\"")) {
97
- destinationBuilder = "\n if (routerGetBuilderType() == \"" + routerName + "\") {\n" +
98
- " " + viewName + "()\n" +
99
- " } "
100
- } else {
101
- destinationBuilder = "\n if (routerGetBuilderType() == " + routerName + ") {\n" +
102
- " " + viewName + "()\n" +
103
- " } "
104
- }
105
-
106
- if (configEnd.indexOf("routerGetBuilderType()") != -1) {
107
- destinationBuilder = destinationBuilder + "else "
108
- }
109
- destinationEnd = insertString(configEnd, destinationPosition, destinationBuilder)
110
-
111
- let importContent = ""
112
- if (fileData.indexOf(importPath) == -1) {
113
- importContent = "import { " + viewName +
114
- " } from '" + importPath + "';\n"
115
- }
116
- let className = routerName.split(".")[0]
117
- if (!routerPathEnd.startsWith("(\"") && fileData.indexOf("./" + className) == -1) {
118
- importContent = importContent + "import { " + className +
119
- " } from './" + className + "';\n"
120
- }
121
- destinationEnd = importContent + destinationEnd
122
-
123
- FileUtil.writeFileSync(configPath, destinationEnd);
124
- }
125
- }
126
- })
127
-
128
- } catch (error) {
129
- console.log(error)
130
- }
131
- })
94
+ let destinationEnd = ""
95
+ let DestinationTag = "NavDestinationView() {"
96
+ let destinationPosition = configEnd.indexOf(DestinationTag) + DestinationTag.length
132
97
 
133
- try {
134
- let moduleJson5Path = FileUtil.pathResolve(entryModulePath + "/src/main/", "module.json5")
135
- let moduleJson5Data = FileUtil.readFileSync(moduleJson5Path)
136
- moduleJson5JSONParse(moduleJson5Data.toString())
137
- let appPath = FileUtil.pathResolve(entryModulePath + "/src/main/ets/", "App.ets")
138
- if (moduleSrcEntry == undefined) {
139
- FileUtil.ensureFileSync(appPath)
140
- FileUtil.writeFileSync(appPath, getApp())
141
- let moduleJson5 = moduleJson5Data.toString()
142
- //同时改变module.json5
143
- let moduleTag = "\"module\": {"
144
- let modulePosition = moduleJson5.indexOf(moduleTag) + moduleTag.length
145
- let mJson = "\n \"srcEntry\": \"./ets/App.ets\","
146
- let moduleContent = insertString(moduleJson5, modulePosition, mJson)
147
- FileUtil.writeFileSync(moduleJson5Path, moduleContent);
148
- } else {
149
- let endSrc = moduleSrcEntry.substring(1, moduleSrcEntry.length)
150
- let endAppPath = entryModulePath + "/src/main" + endSrc
151
- let appFileData = FileUtil.readFileSync(endAppPath);
152
- let appFileDataString = appFileData.toString()
153
- if (appFileDataString.indexOf("routerInitConfig([") != -1) {
154
- let initHaveConfig = ""
155
- let importHaveConfig = ""
156
- let isHaveConfig = false;
157
- entryUpperCaseNameArray.forEach((name, index) => {
158
- let isHsp = entryIsHsp[index]
159
- let endHsp = ""
160
- if (isHsp) {
161
- endHsp = "getARouter()"
162
- }
163
-
164
- if (appFileDataString.indexOf("new " + name + "RouterConfig(") == -1) {
165
- isHaveConfig = true;
166
- initHaveConfig = initHaveConfig + (" new " + name + "RouterConfig(" + endHsp + "),\n")
167
- }
168
-
169
- //这个必须要带
170
- let exportClassIndex = appFileDataString.indexOf("export class");
171
- let exportContent = appFileDataString.substring(0, exportClassIndex);
172
-
173
- if (exportContent.indexOf(name + "RouterConfig") == -1) {
174
- isHaveConfig = true;
175
- importHaveConfig = importHaveConfig + "\nimport { " + name + "RouterConfig } from '" + name.toLowerCase() + "';\n"
176
- }
177
- })
178
-
179
- if (isHaveConfig) {
180
- let routerInitHaveTag = "routerInitConfig(["
181
- let routerInitHavePosition = appFileDataString.indexOf(routerInitHaveTag) + routerInitHaveTag.length
182
- let routerHaveJson = "\n" + initHaveConfig
183
- let routerInitHaveContent = insertString(appFileDataString, routerInitHavePosition, routerHaveJson)
184
- routerInitHaveContent = importHaveConfig + routerInitHaveContent
185
- FileUtil.writeFileSync(endAppPath, routerInitHaveContent);
186
- }
98
+ let destinationBuilder = ""
99
+ if (routerPathEnd.startsWith("(\"")) {
100
+ destinationBuilder = "\n if (routerGetBuilderType() == \"" + routerName + "\") {\n" +
101
+ " " + viewName + "()\n" +
102
+ " } "
187
103
  } else {
188
- let initNewConfig = ""
189
- let importNewConfig = ""
190
- entryUpperCaseNameArray.forEach((name, index) => {
191
- let isHsp = entryIsHsp[index]
192
- let endHsp = ""
193
- if (isHsp) {
194
- endHsp = "getARouter()"
195
- }
196
- initNewConfig = initNewConfig + (" new " + name + "RouterConfig(" + endHsp + "),\n")
197
- importNewConfig = importNewConfig + "\nimport { " + name + "RouterConfig } from '" + name.toLowerCase() + "';\n"
198
- })
199
-
200
- let routerInitTag = "onCreate(): void {"
201
- let routerInitPosition = appFileDataString.indexOf(routerInitTag) + routerInitTag.length
202
- let routerJson = "\n routerInitConfig([\n" +
203
- initNewConfig +
204
- " new EntryRouterConfig()\n" +
205
- " ])\n"
206
- let routerInitContent = insertString(appFileDataString, routerInitPosition, routerJson)
207
- routerInitContent = "import { getARouter,routerInitConfig } from '@abner/router';\n" +
208
- "import { EntryRouterConfig } from '../../../EntryRouterConfig';\n"
209
- + importNewConfig
210
- + routerInitContent
211
- FileUtil.writeFileSync(endAppPath, routerInitContent);
104
+ destinationBuilder = "\n if (routerGetBuilderType() == " + routerName + ") {\n" +
105
+ " " + viewName + "()\n" +
106
+ " } "
107
+ }
108
+
109
+ if (configEnd.indexOf("routerGetBuilderType()") != -1) {
110
+ destinationBuilder = destinationBuilder + "else "
212
111
  }
112
+ destinationEnd = insertString(configEnd, destinationPosition, destinationBuilder)
113
+
114
+ let importContent = ""
115
+ if (fileData.indexOf(importPath) == -1) {
116
+ //存在模块名字,直接导入模块名字
117
+ if (tempModuleName != "") {
118
+ importContent = "import { " + viewName +
119
+ " } from '" + tempModuleName + "';\n"
120
+ } else {
121
+ importContent = "import { " + viewName +
122
+ " } from '" + importPath + "';\n"
123
+ }
124
+ }
125
+ let className = routerName.split(".")[0]
126
+ if (!routerPathEnd.startsWith("(\"") && fileData.indexOf("./" + className) == -1) {
127
+ //存在模块名字,直接导入模块名字
128
+ if (tempModuleName != "") {
129
+ importContent = importContent + "import { " + className +
130
+ " } from '" + tempModuleName + "';\n"
131
+ } else {
132
+ importContent = importContent + "import { " + className +
133
+ " } from './" + className + "';\n"
134
+ }
135
+ }
136
+ destinationEnd = importContent + destinationEnd
137
+ FileUtil.writeFileSync(configPath, destinationEnd);
138
+ }
213
139
  }
140
+ })
214
141
 
215
142
  } catch (error) {
216
- console.log(error)
143
+ console.log(error)
217
144
  }
145
+ })
146
+
147
+ try {
148
+ let moduleJson5Path = FileUtil.pathResolve(entryModulePath + "/src/main/", "module.json5")
149
+ let moduleJson5Data = FileUtil.readFileSync(moduleJson5Path)
150
+ moduleJson5JSONParse(moduleJson5Data.toString())
151
+ let appPath = FileUtil.pathResolve(entryModulePath + "/src/main/ets/", "App.ets")
152
+ if (moduleSrcEntry == undefined) {
153
+ FileUtil.ensureFileSync(appPath)
154
+ FileUtil.writeFileSync(appPath, getApp())
155
+ let moduleJson5 = moduleJson5Data.toString()
156
+ //同时改变module.json5
157
+ let moduleTag = "\"module\": {"
158
+ let modulePosition = moduleJson5.indexOf(moduleTag) + moduleTag.length
159
+ let mJson = "\n \"srcEntry\": \"./ets/App.ets\","
160
+ let moduleContent = insertString(moduleJson5, modulePosition, mJson)
161
+ FileUtil.writeFileSync(moduleJson5Path, moduleContent);
162
+ } else {
163
+ let endSrc = moduleSrcEntry.substring(1, moduleSrcEntry.length)
164
+ let endAppPath = entryModulePath + "/src/main" + endSrc
165
+ let appFileData = FileUtil.readFileSync(endAppPath);
166
+ let appFileDataString = appFileData.toString()
167
+ if (appFileDataString.indexOf("routerInitConfig([") != -1) {
168
+ let initHaveConfig = ""
169
+ let importHaveConfig = ""
170
+ let isHaveConfig = false;
171
+ entryUpperCaseNameArray.forEach((name, index) => {
172
+ let isHsp = entryIsHsp[index]
173
+ let endHsp = ""
174
+ if (isHsp) {
175
+ endHsp = "getARouter()"
176
+ }
177
+
178
+ if (appFileDataString.indexOf("new " + name + "RouterConfig(") == -1) {
179
+ isHaveConfig = true;
180
+ initHaveConfig = initHaveConfig + (" new " + name + "RouterConfig(" + endHsp + "),\n")
181
+ }
182
+
183
+ //这个必须要带
184
+ let exportClassIndex = appFileDataString.indexOf("export class");
185
+
186
+ if (exportClassIndex == -1) {
187
+ exportClassIndex = appFileDataString.indexOf("export default");
188
+ }
189
+ let exportContent = appFileDataString.substring(0, exportClassIndex);
190
+
191
+ if (exportContent.indexOf(name + "RouterConfig") == -1) {
192
+ isHaveConfig = true;
193
+ importHaveConfig =
194
+ importHaveConfig + "\nimport { " + name + "RouterConfig } from '" + name.toLowerCase() + "';\n"
195
+ }
196
+ })
197
+
198
+ if (isHaveConfig) {
199
+ let routerInitHaveTag = "routerInitConfig(["
200
+ let routerInitHavePosition = appFileDataString.indexOf(routerInitHaveTag) + routerInitHaveTag.length
201
+ let routerHaveJson = "\n" + initHaveConfig
202
+ let routerInitHaveContent = insertString(appFileDataString, routerInitHavePosition, routerHaveJson)
203
+ routerInitHaveContent = importHaveConfig + routerInitHaveContent
204
+ FileUtil.writeFileSync(endAppPath, routerInitHaveContent);
205
+ }
206
+ } else {
207
+ let initNewConfig = ""
208
+ let importNewConfig = ""
209
+ entryUpperCaseNameArray.forEach((name, index) => {
210
+ let isHsp = entryIsHsp[index]
211
+ let endHsp = ""
212
+ if (isHsp) {
213
+ endHsp = "getARouter()"
214
+ }
215
+ initNewConfig = initNewConfig + (" new " + name + "RouterConfig(" + endHsp + "),\n")
216
+ importNewConfig =
217
+ importNewConfig + "\nimport { " + name + "RouterConfig } from '" + name.toLowerCase() + "';\n"
218
+ })
219
+ const moduleSrcEntryCount = moduleSrcEntry.split("/").length;
220
+ const endSrcEntryString = "../".repeat(moduleSrcEntryCount);
221
+ let routerInitTag = "onCreate(): void {"
222
+ let routerInitPosition = appFileDataString.indexOf(routerInitTag) + routerInitTag.length
223
+ let routerJson = "\n routerInitConfig([\n" +
224
+ initNewConfig +
225
+ " new EntryRouterConfig()\n" +
226
+ " ])\n"
227
+ let routerInitContent = insertString(appFileDataString, routerInitPosition, routerJson)
228
+ routerInitContent = "import { getARouter,routerInitConfig } from '@abner/router';\n" +
229
+ "import { EntryRouterConfig } from '" + endSrcEntryString + "EntryRouterConfig';\n"
230
+ + importNewConfig
231
+ + routerInitContent
232
+ FileUtil.writeFileSync(endAppPath, routerInitContent);
233
+ }
234
+ }
235
+
236
+ } catch (error) {
237
+ console.log(error)
238
+ }
218
239
 
219
240
  }
220
241
 
221
242
  let moduleSrcEntry: string
222
243
 
223
244
  function moduleJson5JSONParse(json: string) {
224
- try {
225
- let moduleJson5Data = getEndJson(json);
226
- let moduleJsonBean = JSON.parse(moduleJson5Data)
227
- let module = moduleJsonBean.module
228
- moduleSrcEntry = module.srcEntry
229
- } catch (error) {
230
- console.log("moduleJson5JSONParse:" + error)
231
- }
245
+ try {
246
+ let moduleJson5Data = getEndJson(json);
247
+ let moduleJsonBean = JSON.parse(moduleJson5Data)
248
+ let module = moduleJsonBean.module
249
+ moduleSrcEntry = module.srcEntry
250
+ } catch (error) {
251
+ console.log("moduleJson5JSONParse:" + error)
252
+ }
232
253
  }
233
254
 
234
255
  function insertString(src: string, pos: number, val: string): string {
235
- if (pos < -src.length - 1 || pos > src.length) {
236
- throw "insert position is error";
237
- }
238
- if (pos >= 0) {
239
- return src.slice(0, pos) + val + src.slice(pos);
240
- } else {
241
- return src.slice(0, src.length + 1 + pos) + val + src.slice(src.length + 1 + pos);
242
- }
256
+ if (pos < -src.length - 1 || pos > src.length) {
257
+ throw "insert position is error";
258
+ }
259
+ if (pos >= 0) {
260
+ return src.slice(0, pos) + val + src.slice(pos);
261
+ } else {
262
+ return src.slice(0, src.length + 1 + pos) + val + src.slice(src.length + 1 + pos);
263
+ }
243
264
  }
244
265
 
245
- function getRouterConfig(upperCaseName: string, nodeName: string, isHsp: boolean) {
246
- var configText = "import { ";
247
- if (isHsp) {
248
- configText = configText + " ARouter, setARouter, "
249
- }
250
- configText =
251
- configText + "RouterConfig,routerGetBuilderType, routerInitBuilder,NavDestinationView } from '@abner/router';\n" +
252
- "\n" +
253
- "/**\n" +
254
- " * AUTHOR:AbnerMing\n" +
255
- " * INTRODUCE:动态配置路径\n" +
256
- " * */\n" +
257
- "function importPath(builderName: string) {\n" +
258
- " switch (builderName) {\n" +
259
- "\n" +
260
- " }\n" +
261
- "}\n" +
262
- "\n" +
263
- "/**\n" +
264
- " * AUTHOR:AbnerMing\n" +
265
- " * INTRODUCE:动态配置组件\n" +
266
- " * */\n" +
267
- "@Builder\n" +
268
- "export function viewBuilder(params?:Object) {\n" +
269
- " NavDestinationView() {\n" +
270
- "\n" +
271
- " }\n" +
272
- "\n" +
273
- "}\n" +
274
- "\n" +
275
- "\n" +
276
- "/**\n" +
277
- " * AUTHOR:AbnerMing\n" +
278
- " * DATE:" + getNowTime() + "\n" +
279
- " * INTRODUCE:路由配置,此路由配置文件为自动生成,无特殊情况下请无须改动\n" +
280
- " * */\n" +
281
- "export class " + upperCaseName + "RouterConfig implements RouterConfig {\n";
282
-
283
- if (isHsp) {
284
- //是动态包
285
- configText = configText + " constructor(router: ARouter) {\n" +
286
- " setARouter(router)\n" +
287
- " }\n"
288
- }
266
+ /**
267
+ * 判断是否是注释中的
268
+ */
289
269
 
290
- configText = configText + " getModuleName(): string {\n" +
291
- " return \"" + nodeName + "\"\n" +
292
- " }\n" +
293
- "\n" +
294
- " async initRouter(builderName: string): Promise<void> {\n" +
295
- " return await new Promise((resolve: Function) => {\n" +
296
- " importPath(builderName)\n" +
297
- " routerInitBuilder(builderName, wrapBuilder(viewBuilder))\n" +
298
- " resolve()\n" +
299
- " })\n" +
300
- " }\n" +
301
- "}"
302
-
303
- return configText
270
+ function getRouterConfig(upperCaseName: string, nodeName: string, isHsp: boolean) {
271
+ var configText = "import { ";
272
+ if (isHsp) {
273
+ configText = configText + " ARouter, setARouter, "
274
+ }
275
+ configText =
276
+ configText + "RouterConfig,routerGetBuilderType, routerInitBuilder,NavDestinationView } from '@abner/router';\n" +
277
+ "\n" +
278
+ "/**\n" +
279
+ " * AUTHOR:AbnerMing\n" +
280
+ " * INTRODUCE:动态配置路径\n" +
281
+ " * */\n" +
282
+ "function importPath(builderName: string) {\n" +
283
+ " switch (builderName) {\n" +
284
+ "\n" +
285
+ " }\n" +
286
+ "}\n" +
287
+ "\n" +
288
+ "/**\n" +
289
+ " * AUTHOR:AbnerMing\n" +
290
+ " * INTRODUCE:动态配置组件\n" +
291
+ " * */\n" +
292
+ "@Builder\n" +
293
+ "export function viewBuilder(params?:Object) {\n" +
294
+ " NavDestinationView() {\n" +
295
+ "\n" +
296
+ " }\n" +
297
+ "\n" +
298
+ "}\n" +
299
+ "\n" +
300
+ "\n" +
301
+ "/**\n" +
302
+ " * AUTHOR:AbnerMing\n" +
303
+ " * DATE:" + getNowTime() + "\n" +
304
+ " * INTRODUCE:路由配置,此路由配置文件为自动生成,无特殊情况下请无须改动\n" +
305
+ " * */\n" +
306
+ "export class " + upperCaseName + "RouterConfig implements RouterConfig {\n";
307
+
308
+ if (isHsp) {
309
+ //是动态包
310
+ configText = configText + " constructor(router: ARouter) {\n" +
311
+ " setARouter(router)\n" +
312
+ " }\n"
313
+ }
314
+
315
+ configText = configText + " getModuleName(): string {\n" +
316
+ " return \"" + nodeName + "\"\n" +
317
+ " }\n" +
318
+ "\n" +
319
+ " async initRouter(builderName: string): Promise<void> {\n" +
320
+ " return await new Promise((resolve: Function) => {\n" +
321
+ " importPath(builderName)\n" +
322
+ " routerInitBuilder(builderName, wrapBuilder(viewBuilder))\n" +
323
+ " resolve()\n" +
324
+ " })\n" +
325
+ " }\n" +
326
+ "}"
327
+
328
+ return configText
304
329
  }
305
330
 
306
331
 
307
332
  var buildProfilePath = ""
308
333
 
309
334
  function writeBuildProfile(childNode: HvigorNode) {
310
- let ohPackagePath = FileUtil.pathResolve(childNode.getNodePath(), "oh-package.json5")
311
- let ohPackageData = FileUtil.readFileSync(ohPackagePath)
312
- dependenciesJSONParse(ohPackageData.toString())
313
- buildProfilePath = FileUtil.pathResolve(childNode.getNodePath(), "build-profile.json5")
314
- let buildProfileData = FileUtil.readFileSync(buildProfilePath)
315
- buildProfileJSONParse(buildProfileData.toString())
335
+ let ohPackagePath = FileUtil.pathResolve(childNode.getNodePath(), "oh-package.json5")
336
+ let ohPackageData = FileUtil.readFileSync(ohPackagePath)
337
+ dependenciesJSONParse(ohPackageData.toString())
338
+ buildProfilePath = FileUtil.pathResolve(childNode.getNodePath(), "build-profile.json5")
339
+ let buildProfileData = FileUtil.readFileSync(buildProfilePath)
340
+ buildProfileJSONParse(buildProfileData.toString())
316
341
  }
317
342
 
318
343
  function getNowTime() {
319
- let d = new Date();
320
- return d.getFullYear() + "年" + (d.getMonth() + 1) + "月" + d.getDate() + "日 " + d.getHours() + "时" +
321
- d.getMinutes() +
322
- "分" + d.getSeconds() + "秒"
344
+ let d = new Date();
345
+ return d.getFullYear() + "年" + (d.getMonth() + 1) + "月" + d.getDate() + "日 " + d.getHours() + "时" +
346
+ d.getMinutes() +
347
+ "分" + d.getSeconds() + "秒"
323
348
  }
324
349
 
325
350
  function log(params: string) {
326
- console.error(params);
351
+ console.error(params);
327
352
  }
328
353
 
329
354
 
330
355
  let dependenciesKey: string[]
331
356
 
332
357
  function dependenciesJSONParse(json: string) {
333
- try {
334
- let ohPackageData = getEndJson(json);
335
- dependenciesKey = []
336
- let ohPackAgeBean = JSON.parse(ohPackageData)
337
- let dependencies = ohPackAgeBean.dependencies
338
- for (var key in dependencies) {
339
- if (dependencies[key].indexOf("file:..") != -1) {
340
- dependenciesKey.push(key)
341
- }
342
- }
343
- } catch (error) {
344
- console.log("dependenciesJSONParse:" + error)
358
+ try {
359
+ let ohPackageData = getEndJson(json);
360
+ dependenciesKey = []
361
+ let ohPackAgeBean = JSON.parse(ohPackageData)
362
+ let dependencies = ohPackAgeBean.dependencies
363
+ for (var key in dependencies) {
364
+ if (dependencies[key].indexOf("file:..") != -1) {
365
+ dependenciesKey.push(key)
366
+ }
345
367
  }
368
+ } catch (error) {
369
+ console.log("dependenciesJSONParse:" + error)
370
+ }
346
371
  }
347
372
 
348
373
  function buildProfileJSONParse(json: string) {
349
- try {
350
- let buildProfileData = getEndJson(json);
351
- let buildProfileBean = JSON.parse(buildProfileData)
352
- let buildOptionBean = buildProfileBean.buildOption
353
- if (buildOptionBean.arkOptions == undefined) {
354
- printBuildProFile(buildProfileData, 0)
374
+ try {
375
+ let buildProfileData = getEndJson(json);
376
+ let buildProfileBean = JSON.parse(buildProfileData)
377
+ let buildOptionBean = buildProfileBean.buildOption
378
+ if (buildOptionBean.arkOptions == undefined) {
379
+ printBuildProFile(buildProfileData, 0)
380
+ } else {
381
+ let arkOptions = buildOptionBean.arkOptions
382
+ if (arkOptions.runtimeOnly == undefined) {
383
+ printBuildProFile(buildProfileData, 1)
384
+
385
+ } else {
386
+ let runtimeOnly = arkOptions.runtimeOnly
387
+ if (runtimeOnly.packages == undefined) {
388
+ printBuildProFile(buildProfileData, 2)
355
389
  } else {
356
- let arkOptions = buildOptionBean.arkOptions
357
- if (arkOptions.runtimeOnly == undefined) {
358
- printBuildProFile(buildProfileData, 1)
359
-
360
- } else {
361
- let runtimeOnly = arkOptions.runtimeOnly
362
- if (runtimeOnly.packages == undefined) {
363
- printBuildProFile(buildProfileData, 2)
364
- } else {
365
- if (dependenciesKey.toString() != runtimeOnly["packages"].toString()) {
366
- printBuildProFile(buildProfileData, 3)
367
- }
368
- }
369
- }
390
+ if (dependenciesKey.toString() != runtimeOnly["packages"].toString()) {
391
+ printBuildProFile(buildProfileData, 3)
392
+ }
370
393
  }
371
- } catch (error) {
372
- console.log("buildProfileJSONParse:" + error)
394
+ }
373
395
  }
396
+ } catch (error) {
397
+ console.log("buildProfileJSONParse:" + error)
398
+ }
374
399
  }
375
400
 
376
401
  function getEndJson(json: string) {
377
- var eJson = json;
378
- if (typeof json === 'object') {
379
- eJson = JSON.stringify(json);
380
- }
381
- const repairedJson = eJson.replace(/'/g, '"')
382
- .replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)(\s*:)/g, '$1"$2"$3')
383
- .replace(/,\s*}/g, '}')
384
- .replace(/,\s*]/g, ']')
385
- .replace(/\/\/.*$/gm, '')
386
- .replace(/\/\*[\s\S]*?\*\//g, '');
387
- return repairedJson;
402
+ var eJson = json;
403
+ if (typeof json === 'object') {
404
+ eJson = JSON.stringify(json);
405
+ }
406
+ const repairedJson = eJson.replace(/'/g, '"')
407
+ .replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)(\s*:)/g, '$1"$2"$3')
408
+ .replace(/,\s*}/g, '}')
409
+ .replace(/,\s*]/g, ']')
410
+ .replace(/\/\/.*$/gm, '')
411
+ .replace(/\/\*[\s\S]*?\*\//g, '');
412
+ return repairedJson;
388
413
  }
389
414
 
390
415
 
391
416
  function printBuildProFile(buildProfileData: string, type: number) {
392
- let endArray = ""
393
- let endBuildArray: string[] = [];
394
- dependenciesKey.forEach((item, index) => {
395
- if (buildProfileData.indexOf(item) == -1) {
396
- endBuildArray.push(item);
397
- }
398
- })
399
- endBuildArray.forEach((item, index) => {
400
- if (index == dependenciesKey.length - 1 && endBuildArray.length == dependenciesKey.length) {
401
- endArray = endArray + " \"" + item + "\"\n"
402
- } else {
403
- endArray = endArray + " \"" + item + "\",\n"
404
- }
405
- })
406
-
407
- if (endArray == "") {
408
- return
417
+ let endArray = ""
418
+ let endBuildArray: string[] = [];
419
+ dependenciesKey.forEach((item, index) => {
420
+ if (buildProfileData.indexOf(item) == -1) {
421
+ endBuildArray.push(item);
409
422
  }
410
-
411
- let buildProfileContent = ""
412
- if (type == 0) {
413
- let buildProfileTag = "\"buildOption\": {"
414
- let buildProfilePosition = buildProfileData.indexOf(buildProfileTag) + buildProfileTag.length
415
- let buildProfileBuilder = "\n \"arkOptions\": {\n" +
416
- " \"runtimeOnly\": {\n" +
417
- " \"sources\": [\n" +
418
- " ],\n" +
419
- " \"packages\": [\n" +
420
- endArray +
421
- " ]\n" +
422
- " }\n" +
423
- " }\n,"
424
-
425
- buildProfileContent = insertString(buildProfileData, buildProfilePosition, buildProfileBuilder)
426
- } else if (type == 1) {
427
- let buildProfileTag = " \"buildOption\": {\n" +
428
- " \"arkOptions\": {"
429
- let buildProfilePosition = buildProfileData.indexOf(buildProfileTag) + buildProfileTag.length
430
- let buildProfileBuilder = "\n \"runtimeOnly\": {\n" +
431
- " \"sources\": [\n" +
432
- " ],\n" +
433
- " \"packages\": [\n" +
434
- endArray +
435
- " ]\n" +
436
- " }"
437
- buildProfileContent = insertString(buildProfileData, buildProfilePosition, buildProfileBuilder)
438
- } else if (type == 2) {
439
- let buildProfileTag = "\"runtimeOnly\": {"
440
- let buildProfilePosition = buildProfileData.indexOf(buildProfileTag) + buildProfileTag.length
441
- let buildProfileBuilder = "\n \"packages\": [\n" +
442
- endArray +
443
- " ],\n"
444
- buildProfileContent = insertString(buildProfileData, buildProfilePosition, buildProfileBuilder)
445
- } else if (type == 3) {
446
- let buildProfileTag = "\"packages\": ["
447
- let buildProfilePosition = buildProfileData.indexOf(buildProfileTag) + buildProfileTag.length
448
- let buildProfileBuilder = "\n" + endArray
449
- buildProfileContent = insertString(buildProfileData, buildProfilePosition, buildProfileBuilder)
423
+ })
424
+ endBuildArray.forEach((item, index) => {
425
+ if (index == dependenciesKey.length - 1 && endBuildArray.length == dependenciesKey.length) {
426
+ endArray = endArray + " \"" + item + "\"\n"
427
+ } else {
428
+ endArray = endArray + " \"" + item + "\",\n"
450
429
  }
451
-
452
- FileUtil.writeFileSync(buildProfilePath, buildProfileContent);
430
+ })
431
+
432
+ if (endArray == "") {
433
+ return
434
+ }
435
+
436
+ let buildProfileContent = ""
437
+ if (type == 0) {
438
+ let buildProfileTag = "\"buildOption\": {"
439
+ let buildProfilePosition = buildProfileData.indexOf(buildProfileTag) + buildProfileTag.length
440
+ let buildProfileBuilder = "\n \"arkOptions\": {\n" +
441
+ " \"runtimeOnly\": {\n" +
442
+ " \"sources\": [\n" +
443
+ " ],\n" +
444
+ " \"packages\": [\n" +
445
+ endArray +
446
+ " ]\n" +
447
+ " }\n" +
448
+ " }\n,"
449
+
450
+ buildProfileContent = insertString(buildProfileData, buildProfilePosition, buildProfileBuilder)
451
+ } else if (type == 1) {
452
+ let buildProfileTag = " \"buildOption\": {\n" +
453
+ " \"arkOptions\": {"
454
+ let buildProfilePosition = buildProfileData.indexOf(buildProfileTag) + buildProfileTag.length
455
+ let buildProfileBuilder = "\n \"runtimeOnly\": {\n" +
456
+ " \"sources\": [\n" +
457
+ " ],\n" +
458
+ " \"packages\": [\n" +
459
+ endArray +
460
+ " ]\n" +
461
+ " }"
462
+ buildProfileContent = insertString(buildProfileData, buildProfilePosition, buildProfileBuilder)
463
+ } else if (type == 2) {
464
+ let buildProfileTag = "\"runtimeOnly\": {"
465
+ let buildProfilePosition = buildProfileData.indexOf(buildProfileTag) + buildProfileTag.length
466
+ let buildProfileBuilder = "\n \"packages\": [\n" +
467
+ endArray +
468
+ " ],\n"
469
+ buildProfileContent = insertString(buildProfileData, buildProfilePosition, buildProfileBuilder)
470
+ } else if (type == 3) {
471
+ let buildProfileTag = "\"packages\": ["
472
+ let buildProfilePosition = buildProfileData.indexOf(buildProfileTag) + buildProfileTag.length
473
+ let buildProfileBuilder = "\n" + endArray
474
+ buildProfileContent = insertString(buildProfileData, buildProfilePosition, buildProfileBuilder)
475
+ }
476
+
477
+ FileUtil.writeFileSync(buildProfilePath, buildProfileContent);
453
478
  }
454
479
 
455
480
  function getApp() {
456
- let initAppConfig = ""
457
- let importAppConfig = ""
458
- entryUpperCaseNameArray.forEach((name, index) => {
459
- let isHsp = entryIsHsp[index]
460
- let endHsp = ""
461
- if (isHsp) {
462
- endHsp = "getARouter()"
481
+ let initAppConfig = ""
482
+ let importAppConfig = ""
483
+ entryUpperCaseNameArray.forEach((name, index) => {
484
+ let isHsp = entryIsHsp[index]
485
+ let endHsp = ""
486
+ if (isHsp) {
487
+ endHsp = "getARouter()"
488
+ }
489
+ initAppConfig = initAppConfig + (" new " + name + "RouterConfig(" + endHsp + "),\n")
490
+ importAppConfig = importAppConfig + "\nimport { " + name + "RouterConfig } from '" + name.toLowerCase() + "';\n"
491
+ })
492
+
493
+ let appContent = "import { getARouter,routerInitConfig } from '@abner/router';\n" +
494
+ "import { AbilityStage } from '@kit.AbilityKit';\n" +
495
+ "import { EntryRouterConfig } from '../../../EntryRouterConfig';\n" +
496
+ importAppConfig +
497
+ "\n" +
498
+ "export class App extends AbilityStage {\n" +
499
+ " onCreate(): void {\n" +
500
+ " routerInitConfig([\n" +
501
+ initAppConfig +
502
+ " new EntryRouterConfig()\n" +
503
+ " ])\n" +
504
+ " }\n" +
505
+ "}"
506
+ return appContent
507
+ }
508
+
509
+ /**
510
+ * 判断标识符是否出现在代码的注释或字符串中
511
+ * @param code 源代码字符串
512
+ * @param identifier 要查找的标识符(区分大小写,子串匹配)
513
+ * @returns true 表示标识符出现在注释或字符串中,false 表示未出现或仅出现在普通代码中
514
+ */
515
+ function isIdentifierInCommentOrString(code: string, identifier: string): boolean {
516
+ if (!code || !identifier) {
517
+ return false;
518
+ }
519
+
520
+ const len = code.length;
521
+ let i = 0;
522
+
523
+ // 状态定义
524
+ enum State {
525
+ Normal, // 普通代码区域
526
+ SingleComment, // 单行注释 // ... 直到换行
527
+ MultiComment, // 多行注释 /* ... */
528
+ String, // 字符串(单引号或双引号)
529
+ }
530
+
531
+ let state = State.Normal;
532
+ let stringDelimiter = ''; // 记录当前字符串的结束符(' 或 ")
533
+
534
+ while (i < len) {
535
+ const ch = code[i];
536
+ const nextCh = i + 1 < len ? code[i + 1] : '';
537
+
538
+ switch (state) {
539
+ case State.Normal:
540
+ // 检测单行注释
541
+ if (ch === '/' && nextCh === '/') {
542
+ state = State.SingleComment;
543
+ i += 2;
544
+ let commentContent = '';
545
+ // 收集注释内容直到换行或文件结束
546
+ while (i < len && code[i] !== '\n' && code[i] !== '\r') {
547
+ commentContent += code[i];
548
+ i++;
549
+ }
550
+ if (commentContent.includes(identifier)) {
551
+ return true;
552
+ }
553
+ // 注释结束,恢复 Normal 状态(循环将继续处理换行符)
554
+ state = State.Normal;
555
+ // 注意:此时 i 指向换行符或 len,循环末尾会 i++ 跳过换行符
556
+ continue;
557
+ }
558
+ // 检测多行注释
559
+ else if (ch === '/' && nextCh === '*') {
560
+ state = State.MultiComment;
561
+ i += 2;
562
+ let commentContent = '';
563
+ let closed = false;
564
+ while (i < len) {
565
+ if (code[i] === '*' && i + 1 < len && code[i + 1] === '/') {
566
+ closed = true;
567
+ i += 2;
568
+ break;
569
+ }
570
+ commentContent += code[i];
571
+ i++;
572
+ }
573
+ if (commentContent.includes(identifier)) {
574
+ return true;
575
+ }
576
+ // 即使未闭合,也退出注释状态(鲁棒性)
577
+ state = State.Normal;
578
+ continue;
579
+ }
580
+ // 检测字符串开始(单引号或双引号)
581
+ else if (ch === '\'' || ch === '"') {
582
+ state = State.String;
583
+ stringDelimiter = ch;
584
+ i++;
585
+ let stringContent = '';
586
+ while (i < len) {
587
+ // 处理转义字符:跳过转义序列,不将转义后的引号视为结束
588
+ if (code[i] === '\\') {
589
+ stringContent += code[i] + (code[i + 1] || '');
590
+ i += 2;
591
+ continue;
592
+ }
593
+ if (code[i] === stringDelimiter) {
594
+ i++; // 跳过结束引号
595
+ break;
596
+ }
597
+ stringContent += code[i];
598
+ i++;
599
+ }
600
+ if (stringContent.includes(identifier)) {
601
+ return true;
602
+ }
603
+ state = State.Normal;
604
+ continue;
463
605
  }
464
- initAppConfig = initAppConfig + (" new " + name + "RouterConfig(" + endHsp + "),\n")
465
- importAppConfig = importAppConfig + "\nimport { " + name + "RouterConfig } from '" + name.toLowerCase() + "';\n"
466
- })
467
-
468
- let appContent = "import { getARouter,routerInitConfig } from '@abner/router';\n" +
469
- "import { AbilityStage } from '@kit.AbilityKit';\n" +
470
- "import { EntryRouterConfig } from '../../../EntryRouterConfig';\n" +
471
- importAppConfig +
472
- "\n" +
473
- "export class App extends AbilityStage {\n" +
474
- " onCreate(): void {\n" +
475
- " routerInitConfig([\n" +
476
- initAppConfig +
477
- " new EntryRouterConfig()\n" +
478
- " ])\n" +
479
- " }\n" +
480
- "}"
481
- return appContent
606
+ break;
607
+
608
+ }
609
+
610
+ i++; // 普通字符前进
611
+ }
612
+
613
+ return false;
482
614
  }