从Scala进程调用时,cp命令找不到文件

时间:2017-03-09 15:29:12

标签: scala sbt cp

作为sbt构建过程的一部分,我从Scala调用Linux cp来复制一个代码如下的目录结构:

Process("cp -R -f "/home/user/source/* " "/home/user/target").!

/home/user/source下,有三个目录未复制,但我收到了消息

cp: cannot stat ‘/home/user/source/*’: No such file or directory

尽管来自命令行的ls /home/user/source确实找到了目录,而且还找到了

Process("rm -R -f "/home/user/source").!

会删除目录。

从Scala Process调用时,有关cp无法正常工作的任何建议吗?

以下是我的Build.scala的完整代码:

import sbt._
import sbt.Keys._
import sys.process.Process
import java.io.File

object myBuild extends Build {
    lazy val myVersion = "1.10.0"
    lazy val myJar = "myproj-" + myVersion + ".jar"

    lazy val webjarToExtract = TaskKey[Seq[File]]("webjar-to-extract", "JAR files to be extracted")

    lazy val extractJarTarget = SettingKey[File]("extract-jar-target", "Target directory for extracted JAR file")

    lazy val extractJar = TaskKey[Unit]("extract-webjar", "Extract WebJar file")

    lazy val mySettings = Defaults.defaultSettings ++ Seq(
        webjarToExtract <<= (baseDirectory) map { dir => Seq(dir / "lib" / myJar) },

        // define the target directory
        extractJarTarget <<= (baseDirectory)(_ / "tmp"),

        // task to extract jar files
        extractJar <<= (webjarToExtract, extractJarTarget, streams) map { (jars, target, streams) =>
            jars foreach { jar =>
                streams.log.info("Extracting " + jar.getName + " to " + target)
                IO.unzip(jar, target)
            }
            val baseDir = new java.io.File(".").getCanonicalPath
            Process("cp -R -f " + baseDir + "/tmp/META-INF/resources/webjars/thejars/" + myVersion + "/* " + baseDir + "/public").!
            Process("rm -R -f " + baseDir + "/tmp/META-INF").!
        },

        // make it run before compile
        compile in Compile <<= extractJar map { _ => sbt.inc.Analysis.Empty }
    )

    lazy val myproj: Project = Project("myproj", file(".")) settings (mySettings: _*)
}

1 个答案:

答案 0 :(得分:3)

正如@Reactormonk在评论中指出的那样,要获得shell扩展,你需要调用shell。

scala> import scala.sys.process._
import scala.sys.process._

scala> Seq("cp", "JunkFrom/*", "JunkTo").!
cp: cannot stat 'JunkFrom/*': No such file or directory
res0: Int = 1

scala> Seq("sh", "-c", "cp JunkFrom/* JunkTo").!
res1: Int = 0