1
+ package me.arasple.mc.trchat.util
2
+
3
+ import taboolib.common.PrimitiveIO
4
+ import taboolib.common.PrimitiveSettings
5
+ import taboolib.common.platform.function.getDataFolder
6
+ import taboolib.library.configuration.ConfigurationSection
7
+ import taboolib.module.configuration.Configuration
8
+ import java.io.File
9
+
10
+ /* *
11
+ * module-starrysky
12
+ * com.mcstarrysky.starrysky.config.YamlUpdater
13
+ *
14
+ * @author 米擦亮
15
+ * @since 2023/9/6 20:50
16
+ */
17
+ object YamlUpdater {
18
+
19
+ fun update (path : String , skipNodes : Array <String > = emptyArray(), updateExists : Boolean = true) {
20
+ // 读取 Jar 包内的对应配置文件
21
+ val cache = Configuration .loadFromInputStream(javaClass.classLoader.getResourceAsStream(path) ? : error(" resource not found: $path " ))
22
+ val file = File (getDataFolder(), path)
23
+ if (! file.exists()) {
24
+ return
25
+ }
26
+ val config = Configuration .loadFromFile(file)
27
+
28
+ val updated = mutableListOf<String >()
29
+ read(cache, config, skipNodes, updated, updateExists)
30
+ if (updated.isNotEmpty()) {
31
+ config.saveToFile(config.file)
32
+ }
33
+
34
+ if (PrimitiveSettings .IS_DEBUG_MODE ) {
35
+ PrimitiveIO .println (" Auto updated configuration: $path , with ${updated.size} elements updated." )
36
+ for (node in updated) {
37
+ PrimitiveIO .println (" |- $node " )
38
+ }
39
+ }
40
+ }
41
+
42
+ private fun read (cache : ConfigurationSection , to : ConfigurationSection , skipNodes : Array <String >, updated : MutableList <String >, updateExists : Boolean ) {
43
+ var name = cache.name
44
+ var c = cache
45
+ while (c.parent != null ) {
46
+ name = " ${c.parent!! .name} .$name "
47
+ c = c.parent!!
48
+ }
49
+ if (name.isNotEmpty()) {
50
+ name + = ' .'
51
+ }
52
+ // 遍历给定新版配置文件的所有配置项目
53
+ for (key in cache.getKeys(false )) {
54
+ // 白名单配置项不进行任何检查
55
+ if (key in skipNodes) continue
56
+
57
+ // 旧版没有, 添加
58
+ if (! to.contains(key)) {
59
+ updated + = " $name$key (+)"
60
+ to[key] = cache[key]
61
+ continue
62
+ }
63
+
64
+ // 是否不更新已存在配置, 只补全缺失项
65
+ if (! updateExists) continue
66
+
67
+ // 好像 switch case 不能判断为空, 我基础没学好
68
+ if (cache[key] == null ) {
69
+ updated + = " $name$key (${to[key]} -> null)"
70
+ to[key] = null
71
+ continue
72
+ }
73
+
74
+ val read = cache[key]
75
+
76
+ if (read is ConfigurationSection ) {
77
+ val write = to[key]
78
+ // 根本不是配置选区, 那肯定要覆盖掉了, 没话说了
79
+ if (write == null || write !is ConfigurationSection ) {
80
+ updated + = " $name$key (${to[key]} -> $read )"
81
+ to[key] = read
82
+ continue
83
+ }
84
+ read(read, write, skipNodes, updated, true )
85
+ } else {
86
+ if (read == to[key]) continue
87
+ updated + = " $name$key (${to[key]} -> $read )"
88
+ to[key] = read
89
+ }
90
+ }
91
+ }
92
+ }
0 commit comments