本文介绍了即使失败,如何在另一个任务之后执行任务或命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 sbt 中有一个相当长的运行任务,并且希望在它完成后收到通知,即使它失败了.我用这种粗鲁的方式部分做到了:

I have a rather long running task in sbt and would like to be notified audibly after it finished, even it if failed. I got partially there with this crudeness:

lazy val ding = taskKey[Unit]("plays a ding sound")
ding := {
  Seq("play", "-q", "/…/SmallGlockA.wav").run
}

我像这样调用上述任务:

I invoke aforementioned task like such:

sbt> ;test;ding

虽然如果任务成功,这很有效,但如果任务失败,它当然不会播放声音,考虑到它的测试,这是可能的.

And while this works well if the task succeeded, it will of course not play the sound if the task failed, which – given that it's tests – is likely.

有什么想法可以解决这个问题吗?它不必非常漂亮或超级健壮——这不会被提交,它对我来说只是本地的事情.

Any ideas how I can work around this? It doesn't have to be pretty or super robust – this will not get committed, it will just be a local thing for me.

推荐答案

我想出的解决方案是为 sbt 创建一个 AutoPlugin 来满足您的需求.

The solution I came up with is to create an AutoPlugin for sbt that does what you need.

project文件夹中新建一个名为DingPlugin.scala的文件,内容如下

Create a new file in project folder named DingPlugin.scala with following content

import sbt.Keys._
import sbt.PluginTrigger.AllRequirements
import sbt._

object DingPlugin extends AutoPlugin {

  private def wavPath = "/path/to/wav"
  private def playSound(wav: String) = ???

  override def trigger = AllRequirements

  override def projectSettings: Seq[Def.Setting[_]] = Seq(
    Test / test := (Test / test).andFinally(playSound(wavPath)).value
  )
}

重点是方法 andFinally 那个

定义一个新任务,该任务运行原始任务并评估副作用,而不管原始任务是否成功.任务结果为原任务结果

playSound 的实现来源于这个问题与以下代码

The implementation of playSound is derived from this question with the following code

  private def playSound(wav: String): Unit = {
    import java.io.BufferedInputStream
    import java.io.FileInputStream
    import javax.sound.sampled.AudioSystem
    val clip = AudioSystem.getClip
    val inputStream =
      AudioSystem.getAudioInputStream(
        new BufferedInputStream(new FileInputStream(wav))
      )
    clip.open(inputStream)
    clip.start()
    Thread.sleep(clip.getMicrosecondLength / 1000)
  }

现在,您只需运行sbt test,无论测试是否成功,它都会播放声音.

Now, you can just run sbt test and it will play a sound regardless of whether test succeeded or not.

这篇关于即使失败,如何在另一个任务之后执行任务或命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 09:32