ohos-router 1.2.6 → 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,487 +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
-
172
- if(exportClassIndex == -1){
173
- exportClassIndex = appFileDataString.indexOf("export default");
174
- }
175
- let exportContent = appFileDataString.substring(0, exportClassIndex);
176
-
177
- if (exportContent.indexOf(name + "RouterConfig") == -1) {
178
- isHaveConfig = true;
179
- importHaveConfig = importHaveConfig + "\nimport { " + name + "RouterConfig } from '" + name.toLowerCase() + "';\n"
180
- }
181
- })
182
-
183
- if (isHaveConfig) {
184
- let routerInitHaveTag = "routerInitConfig(["
185
- let routerInitHavePosition = appFileDataString.indexOf(routerInitHaveTag) + routerInitHaveTag.length
186
- let routerHaveJson = "\n" + initHaveConfig
187
- let routerInitHaveContent = insertString(appFileDataString, routerInitHavePosition, routerHaveJson)
188
- routerInitHaveContent = importHaveConfig + routerInitHaveContent
189
- FileUtil.writeFileSync(endAppPath, routerInitHaveContent);
190
- }
98
+ let destinationBuilder = ""
99
+ if (routerPathEnd.startsWith("(\"")) {
100
+ destinationBuilder = "\n if (routerGetBuilderType() == \"" + routerName + "\") {\n" +
101
+ " " + viewName + "()\n" +
102
+ " } "
191
103
  } else {
192
- let initNewConfig = ""
193
- let importNewConfig = ""
194
- entryUpperCaseNameArray.forEach((name, index) => {
195
- let isHsp = entryIsHsp[index]
196
- let endHsp = ""
197
- if (isHsp) {
198
- endHsp = "getARouter()"
199
- }
200
- initNewConfig = initNewConfig + (" new " + name + "RouterConfig(" + endHsp + "),\n")
201
- importNewConfig = importNewConfig + "\nimport { " + name + "RouterConfig } from '" + name.toLowerCase() + "';\n"
202
- })
203
- const moduleSrcEntryCount = moduleSrcEntry.split("/").length;
204
- const endSrcEntryString = "../".repeat(moduleSrcEntryCount);
205
- let routerInitTag = "onCreate(): void {"
206
- let routerInitPosition = appFileDataString.indexOf(routerInitTag) + routerInitTag.length
207
- let routerJson = "\n routerInitConfig([\n" +
208
- initNewConfig +
209
- " new EntryRouterConfig()\n" +
210
- " ])\n"
211
- let routerInitContent = insertString(appFileDataString, routerInitPosition, routerJson)
212
- routerInitContent = "import { getARouter,routerInitConfig } from '@abner/router';\n" +
213
- "import { EntryRouterConfig } from '"+endSrcEntryString+"EntryRouterConfig';\n"
214
- + importNewConfig
215
- + routerInitContent
216
- 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 "
217
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
+ }
218
139
  }
140
+ })
219
141
 
220
142
  } catch (error) {
221
- console.log(error)
143
+ console.log(error)
222
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
+ }
223
239
 
224
240
  }
225
241
 
226
242
  let moduleSrcEntry: string
227
243
 
228
244
  function moduleJson5JSONParse(json: string) {
229
- try {
230
- let moduleJson5Data = getEndJson(json);
231
- let moduleJsonBean = JSON.parse(moduleJson5Data)
232
- let module = moduleJsonBean.module
233
- moduleSrcEntry = module.srcEntry
234
- } catch (error) {
235
- console.log("moduleJson5JSONParse:" + error)
236
- }
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
+ }
237
253
  }
238
254
 
239
255
  function insertString(src: string, pos: number, val: string): string {
240
- if (pos < -src.length - 1 || pos > src.length) {
241
- throw "insert position is error";
242
- }
243
- if (pos >= 0) {
244
- return src.slice(0, pos) + val + src.slice(pos);
245
- } else {
246
- return src.slice(0, src.length + 1 + pos) + val + src.slice(src.length + 1 + pos);
247
- }
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
+ }
248
264
  }
249
265
 
250
- function getRouterConfig(upperCaseName: string, nodeName: string, isHsp: boolean) {
251
- var configText = "import { ";
252
- if (isHsp) {
253
- configText = configText + " ARouter, setARouter, "
254
- }
255
- configText =
256
- configText + "RouterConfig,routerGetBuilderType, routerInitBuilder,NavDestinationView } from '@abner/router';\n" +
257
- "\n" +
258
- "/**\n" +
259
- " * AUTHOR:AbnerMing\n" +
260
- " * INTRODUCE:动态配置路径\n" +
261
- " * */\n" +
262
- "function importPath(builderName: string) {\n" +
263
- " switch (builderName) {\n" +
264
- "\n" +
265
- " }\n" +
266
- "}\n" +
267
- "\n" +
268
- "/**\n" +
269
- " * AUTHOR:AbnerMing\n" +
270
- " * INTRODUCE:动态配置组件\n" +
271
- " * */\n" +
272
- "@Builder\n" +
273
- "export function viewBuilder(params?:Object) {\n" +
274
- " NavDestinationView() {\n" +
275
- "\n" +
276
- " }\n" +
277
- "\n" +
278
- "}\n" +
279
- "\n" +
280
- "\n" +
281
- "/**\n" +
282
- " * AUTHOR:AbnerMing\n" +
283
- " * DATE:" + getNowTime() + "\n" +
284
- " * INTRODUCE:路由配置,此路由配置文件为自动生成,无特殊情况下请无须改动\n" +
285
- " * */\n" +
286
- "export class " + upperCaseName + "RouterConfig implements RouterConfig {\n";
287
-
288
- if (isHsp) {
289
- //是动态包
290
- configText = configText + " constructor(router: ARouter) {\n" +
291
- " setARouter(router)\n" +
292
- " }\n"
293
- }
266
+ /**
267
+ * 判断是否是注释中的
268
+ */
294
269
 
295
- configText = configText + " getModuleName(): string {\n" +
296
- " return \"" + nodeName + "\"\n" +
297
- " }\n" +
298
- "\n" +
299
- " async initRouter(builderName: string): Promise<void> {\n" +
300
- " return await new Promise((resolve: Function) => {\n" +
301
- " importPath(builderName)\n" +
302
- " routerInitBuilder(builderName, wrapBuilder(viewBuilder))\n" +
303
- " resolve()\n" +
304
- " })\n" +
305
- " }\n" +
306
- "}"
307
-
308
- 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
309
329
  }
310
330
 
311
331
 
312
332
  var buildProfilePath = ""
313
333
 
314
334
  function writeBuildProfile(childNode: HvigorNode) {
315
- let ohPackagePath = FileUtil.pathResolve(childNode.getNodePath(), "oh-package.json5")
316
- let ohPackageData = FileUtil.readFileSync(ohPackagePath)
317
- dependenciesJSONParse(ohPackageData.toString())
318
- buildProfilePath = FileUtil.pathResolve(childNode.getNodePath(), "build-profile.json5")
319
- let buildProfileData = FileUtil.readFileSync(buildProfilePath)
320
- 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())
321
341
  }
322
342
 
323
343
  function getNowTime() {
324
- let d = new Date();
325
- return d.getFullYear() + "年" + (d.getMonth() + 1) + "月" + d.getDate() + "日 " + d.getHours() + "时" +
326
- d.getMinutes() +
327
- "分" + d.getSeconds() + "秒"
344
+ let d = new Date();
345
+ return d.getFullYear() + "年" + (d.getMonth() + 1) + "月" + d.getDate() + "日 " + d.getHours() + "时" +
346
+ d.getMinutes() +
347
+ "分" + d.getSeconds() + "秒"
328
348
  }
329
349
 
330
350
  function log(params: string) {
331
- console.error(params);
351
+ console.error(params);
332
352
  }
333
353
 
334
354
 
335
355
  let dependenciesKey: string[]
336
356
 
337
357
  function dependenciesJSONParse(json: string) {
338
- try {
339
- let ohPackageData = getEndJson(json);
340
- dependenciesKey = []
341
- let ohPackAgeBean = JSON.parse(ohPackageData)
342
- let dependencies = ohPackAgeBean.dependencies
343
- for (var key in dependencies) {
344
- if (dependencies[key].indexOf("file:..") != -1) {
345
- dependenciesKey.push(key)
346
- }
347
- }
348
- } catch (error) {
349
- 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
+ }
350
367
  }
368
+ } catch (error) {
369
+ console.log("dependenciesJSONParse:" + error)
370
+ }
351
371
  }
352
372
 
353
373
  function buildProfileJSONParse(json: string) {
354
- try {
355
- let buildProfileData = getEndJson(json);
356
- let buildProfileBean = JSON.parse(buildProfileData)
357
- let buildOptionBean = buildProfileBean.buildOption
358
- if (buildOptionBean.arkOptions == undefined) {
359
- 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)
360
389
  } else {
361
- let arkOptions = buildOptionBean.arkOptions
362
- if (arkOptions.runtimeOnly == undefined) {
363
- printBuildProFile(buildProfileData, 1)
364
-
365
- } else {
366
- let runtimeOnly = arkOptions.runtimeOnly
367
- if (runtimeOnly.packages == undefined) {
368
- printBuildProFile(buildProfileData, 2)
369
- } else {
370
- if (dependenciesKey.toString() != runtimeOnly["packages"].toString()) {
371
- printBuildProFile(buildProfileData, 3)
372
- }
373
- }
374
- }
390
+ if (dependenciesKey.toString() != runtimeOnly["packages"].toString()) {
391
+ printBuildProFile(buildProfileData, 3)
392
+ }
375
393
  }
376
- } catch (error) {
377
- console.log("buildProfileJSONParse:" + error)
394
+ }
378
395
  }
396
+ } catch (error) {
397
+ console.log("buildProfileJSONParse:" + error)
398
+ }
379
399
  }
380
400
 
381
401
  function getEndJson(json: string) {
382
- var eJson = json;
383
- if (typeof json === 'object') {
384
- eJson = JSON.stringify(json);
385
- }
386
- const repairedJson = eJson.replace(/'/g, '"')
387
- .replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)(\s*:)/g, '$1"$2"$3')
388
- .replace(/,\s*}/g, '}')
389
- .replace(/,\s*]/g, ']')
390
- .replace(/\/\/.*$/gm, '')
391
- .replace(/\/\*[\s\S]*?\*\//g, '');
392
- 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;
393
413
  }
394
414
 
395
415
 
396
416
  function printBuildProFile(buildProfileData: string, type: number) {
397
- let endArray = ""
398
- let endBuildArray: string[] = [];
399
- dependenciesKey.forEach((item, index) => {
400
- if (buildProfileData.indexOf(item) == -1) {
401
- endBuildArray.push(item);
402
- }
403
- })
404
- endBuildArray.forEach((item, index) => {
405
- if (index == dependenciesKey.length - 1 && endBuildArray.length == dependenciesKey.length) {
406
- endArray = endArray + " \"" + item + "\"\n"
407
- } else {
408
- endArray = endArray + " \"" + item + "\",\n"
409
- }
410
- })
411
-
412
- if (endArray == "") {
413
- return
417
+ let endArray = ""
418
+ let endBuildArray: string[] = [];
419
+ dependenciesKey.forEach((item, index) => {
420
+ if (buildProfileData.indexOf(item) == -1) {
421
+ endBuildArray.push(item);
414
422
  }
415
-
416
- let buildProfileContent = ""
417
- if (type == 0) {
418
- let buildProfileTag = "\"buildOption\": {"
419
- let buildProfilePosition = buildProfileData.indexOf(buildProfileTag) + buildProfileTag.length
420
- let buildProfileBuilder = "\n \"arkOptions\": {\n" +
421
- " \"runtimeOnly\": {\n" +
422
- " \"sources\": [\n" +
423
- " ],\n" +
424
- " \"packages\": [\n" +
425
- endArray +
426
- " ]\n" +
427
- " }\n" +
428
- " }\n,"
429
-
430
- buildProfileContent = insertString(buildProfileData, buildProfilePosition, buildProfileBuilder)
431
- } else if (type == 1) {
432
- let buildProfileTag = " \"buildOption\": {\n" +
433
- " \"arkOptions\": {"
434
- let buildProfilePosition = buildProfileData.indexOf(buildProfileTag) + buildProfileTag.length
435
- let buildProfileBuilder = "\n \"runtimeOnly\": {\n" +
436
- " \"sources\": [\n" +
437
- " ],\n" +
438
- " \"packages\": [\n" +
439
- endArray +
440
- " ]\n" +
441
- " }"
442
- buildProfileContent = insertString(buildProfileData, buildProfilePosition, buildProfileBuilder)
443
- } else if (type == 2) {
444
- let buildProfileTag = "\"runtimeOnly\": {"
445
- let buildProfilePosition = buildProfileData.indexOf(buildProfileTag) + buildProfileTag.length
446
- let buildProfileBuilder = "\n \"packages\": [\n" +
447
- endArray +
448
- " ],\n"
449
- buildProfileContent = insertString(buildProfileData, buildProfilePosition, buildProfileBuilder)
450
- } else if (type == 3) {
451
- let buildProfileTag = "\"packages\": ["
452
- let buildProfilePosition = buildProfileData.indexOf(buildProfileTag) + buildProfileTag.length
453
- let buildProfileBuilder = "\n" + endArray
454
- 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"
455
429
  }
456
-
457
- 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);
458
478
  }
459
479
 
460
480
  function getApp() {
461
- let initAppConfig = ""
462
- let importAppConfig = ""
463
- entryUpperCaseNameArray.forEach((name, index) => {
464
- let isHsp = entryIsHsp[index]
465
- let endHsp = ""
466
- if (isHsp) {
467
- 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;
468
605
  }
469
- initAppConfig = initAppConfig + (" new " + name + "RouterConfig(" + endHsp + "),\n")
470
- importAppConfig = importAppConfig + "\nimport { " + name + "RouterConfig } from '" + name.toLowerCase() + "';\n"
471
- })
472
-
473
- let appContent = "import { getARouter,routerInitConfig } from '@abner/router';\n" +
474
- "import { AbilityStage } from '@kit.AbilityKit';\n" +
475
- "import { EntryRouterConfig } from '../../../EntryRouterConfig';\n" +
476
- importAppConfig +
477
- "\n" +
478
- "export class App extends AbilityStage {\n" +
479
- " onCreate(): void {\n" +
480
- " routerInitConfig([\n" +
481
- initAppConfig +
482
- " new EntryRouterConfig()\n" +
483
- " ])\n" +
484
- " }\n" +
485
- "}"
486
- return appContent
606
+ break;
607
+
608
+ }
609
+
610
+ i++; // 普通字符前进
611
+ }
612
+
613
+ return false;
487
614
  }