你如何编写一个对文件更改做出反应的 Scala 脚本 [英] How do you write a Scala script that will react to file changes

查看:43
本文介绍了你如何编写一个对文件更改做出反应的 Scala 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下批处理脚本更改为 Scala(只是为了好玩),但是,脚本必须继续运行并监听 *.mkd 文件的更改.如果更改了任何文件,则脚本应重新生成受影响的文档.文件 IO 一直是我的致命弱点...

I would like to change the following batch script to Scala (just for fun), however, the script must keep running and listen for changes to the *.mkd files. If any file is changed, then the script should re-generate the affected doc. File IO has always been my Achilles heel...

#!/bin/sh
for file in *.mkd
do
  pandoc --number-sections $file -o "${file%%.*}.pdf"
done

任何有关解决此问题的好方法的想法都将不胜感激.

Any ideas around a good approach to this will be appreciated.

推荐答案

以下代码,摘自我的回答:监视项目文件也可以监视目录并执行特定命令:

The following code, taken from my answer on: Watch for project files also can watch a directory and execute a specific command:

#!/usr/bin/env scala

import java.nio.file._
import scala.collection.JavaConversions._
import scala.sys.process._

val file = Paths.get(args(0))
val cmd = args(1)
val watcher = FileSystems.getDefault.newWatchService

file.register(
  watcher, 
  StandardWatchEventKinds.ENTRY_CREATE,
  StandardWatchEventKinds.ENTRY_MODIFY,
  StandardWatchEventKinds.ENTRY_DELETE
)

def exec = cmd run true

@scala.annotation.tailrec
def watch(proc: Process): Unit = {
  val key = watcher.take
  val events = key.pollEvents

  val newProc = 
    if (!events.isEmpty) {
      proc.destroy()
      exec
    } else proc

  if (key.reset) watch(newProc)
  else println("aborted")
}

watch(exec)

用法:

watchr.scala markdownFolder/ "echo \"Something changed!\""

必须对脚本进行扩展才能将文件名注入到命令中.到目前为止,这个片段应该被视为实际答案的基石.

Extensions have to be made to the script to inject file names into the command. As of now this snippet should just be regarded as a building block for the actual answer.

修改脚本以包含 *.mkd 通配符非常重要,因为您必须手动搜索文件并在所有文件上注册监视.重新使用上面的脚本并将所有文件放在一个目录中具有在创建新文件时拾取新文件的额外优势.

Modifying the script to incorporate the *.mkd wildcards would be non-trivial as you'd have to manually search for the files and register a watch on all of them. Re-using the script above and placing all files in a directory has the added advantage of picking up new files when they are created.

正如你所看到的,仅仅依靠 Scala & 它很快就会变得非常大和混乱.Java API,您最好依靠替代库或在使用 INotify 时坚持使用 bash.

As you can see it gets pretty big and messy pretty quick just relying on Scala & Java APIs, you would be better of relying on alternative libraries or just sticking to bash while using INotify.

这篇关于你如何编写一个对文件更改做出反应的 Scala 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆