MiraiForum

    • Register
    • Login
    • Search
    • Popular
    • Recent
    • Unsolved
    • Tags
    • Groups
    • 友情链接

    保存只读配置文件

    技术交流板块
    kotlin console 配置文件
    2
    4
    88
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • MrXiaoM
      MrXiaoM 童心未泯 last edited by MrXiaoM

      先上代码。这可能对大多数人来说没有必要,仅仅是我个人奇怪的操作习惯。

          // 添加下面的代码到你继承了 ReadOnlyPluginData 或者 ReadOnlyPluginConfig 的配置类即可
          @OptIn(ConsoleExperimentalApi::class)
          private lateinit var owner_: PluginDataHolder
          @OptIn(ConsoleExperimentalApi::class)
          private lateinit var storage_: PluginDataStorage
          @OptIn(ConsoleExperimentalApi::class)
          override fun onInit(owner: PluginDataHolder, storage: PluginDataStorage) {
              owner_ = owner
              storage_ = storage
          }
          // 不需要设为 public,直接调用扩展方法 save 即可
          @OptIn(ConsoleExperimentalApi::class)
          private fun save() {
              kotlin.runCatching {
                  storage_.store(owner_, this)
              }.onFailure { e ->
                  // 记得处理异常
              }
      

      如果你只想关闭定时保存,不想关闭属性修改后自动保存,请用 AutoSavePluginData 或 AutoSavePluginConfig 并重写  ​shouldPerformAutoSaveWheneverChanged​() 使它返回 false

      mirai 的只读配置文件曾让我陷入了两难的局地,按照我的个人理解,PluginConfig 是给用户确定插件的一些参数的,插件不应该去修改数值,所以我没用 AutoSavePluginConfig 而是用了 ReadOnlyPluginConfig,在我编写插件调试的过程中我发现一个问题,它真的是只读的 —— 这很正常,因为它就叫只读配置,它在配置文件不存在时会保存默认配置文件,但在我添加新的配置键到类之后,却因为它的只读而没有在配置文件里更新不存在的配置键……

      这不符合我的预期,由于我当时没看到 AutoSavePluginData 里可以关定时保存,故着手研究如何保存只读配置,最后在 AutoSavePluginData 里找到了……

      重载配置文件时,reload() 再 save(),即可更新不存在的配置键。

      我只能以「简化成了我想要的样子不像 AutoSavePluginData 有我不需要的功能」来安慰自己了 :(

      补充

      经过讨论,ReadOnlyPluginData 无法保存是在旧版本 mirai 中的问题,在新版本 mirai 可正常保存(具体哪个版本我还没去验证)。添加上述代码可兼容在旧版本 mirai 保存只读配置文件。

      1 Reply Last reply Reply Quote 0
      • cssxsh
        cssxsh last edited by

        为啥要 自己实现 save

        我记得 reload 和 save 都有 扩展函数来着

        MrXiaoM 1 Reply Last reply Reply Quote 0
        • MrXiaoM
          MrXiaoM 童心未泯 @cssxsh last edited by

          @cssxsh ReadOnlyPluginData 执行 save 会报 NoSuchMethodError

          cssxsh 1 Reply Last reply Reply Quote 0
          • cssxsh
            cssxsh @MrXiaoM last edited by

            @MrXiaoM
            ?

            1 Reply Last reply Reply Quote 1
            • 1 / 1
            • First post
              Last post
            Powered by Mamoe Technologies & NodeBB | 友情链接 | 服务监控 | Contact