【问题标题】:How does an sbt plugin get a path to a file in the plugin?sbt 插件如何获取插件中文件的路径?
【发布时间】:2012-01-31 06:15:07
【问题描述】:

我有一个 sbt (0.11.2) 插件,它需要获取插件内文本文件的路径。我怎么做? baseDirectory、sourceDirectories 等设置为包含插件的项目的基础,而不是插件本身的基础。

我想向插件用户提供一个命令,该命令从插件内的 ruby​​ 文件中提取默认值,然后允许插件用户覆盖这些默认值。

【问题讨论】:

    标签: scala sbt


    【解决方案1】:

    为什么不使用 Java 的 Class.getResource 或 Class.getResourceAsStream 方法呢?例如。像这样:

    object TestPlugin extends Plugin {
    
      override def settings = super.settings ++ Seq(
        commands += testCommand
      )
    
      def testCommand = Command.command("test")(action)
    
      def action(state: State) = {
        try {
          val in = getClass.getResourceAsStream("/test.txt")
          val text = Source.fromInputStream(in).getLines mkString System.getProperty("line.separator")
          logger(state).info(text)
          in.close()
          state
        } catch {
          case e: Exception =>
            logger(state).error(e.getMessage)
            state.fail
        }
      }
    }
    

    【讨论】:

    • 我认为这没有帮助。我确实需要一个指向插件根目录的路径,无论是 jar 还是目录。第一个文件中的许多内容将包含对其他相对路径的许多引用(它是 ruby​​),因此拥有流没有用,复制出流也没有用。
    • 路径到底是什么? getClass.getResource 没有帮助吗?这将返回一个 URL,例如文件:/foo/bar.
    • 是的,你是对的。我误读了文档,并认为我唯一能做的就是获取流。我最终使用了 c.getProtectionDomain.getCodeSource.getLocation.getPath。
    猜你喜欢
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    相关资源
    最近更新 更多