Self-modify the classpath within a Scala script?

I'm trying to replace a bunch of Linux shell scripts with Scala scripts.

One of the remaining challenges is how to scan an entire directory of JARs and place them into the classpath. Currently this is done in the shell script prior to invoking the scala JVM. I'd like to eliminate the shell script completely.

Is there an elegant scala idiom for this?

I have found this other question but in Java it seems hardly worthwhile to mess with it: How do you change the CLASSPATH within Java?

Answers


The JVM itself supports a wild-card notation in the class-path. If /foo/bar is a directory holding JAR files, all of which you want to be in the class-path, you can include /foo/bar/* in the class-path instead of enumerating each JAR file individually.

I'm not sure that will suffice for your purposes, but it's handy when it's suitable.


Um, this is directly supported, you don't even need the java support. Did you try it?

scala -cp '/foo/bar/*'

This script browses the lib dir recursively:

import java.io.File
import java.util.regex.Pattern

def cp(root: File, lib: File): String = {
  var s = lib.getAbsolutePath.replaceFirst(
    Pattern.quote(root.getAbsolutePath) + File.separator + "*", "") +
    File.separator + "*"
  for (f <- lib.listFiles; if f.isDirectory)
    s += File.pathSeparator + cp(root, f)
  s
}

For example:

/project
   lib
   |__dep
   |__dep2
     |__dep3

You call:

var f = new File("/path/to/project")
cp(f, f)

Result:

/*:lib/*:lib/dep2/*:lib/dep2/dep3/*:lib/dep/*

Need Your Help

Searching for element(s) in an array and then return a new array with index(s)

java arrays

I would highly appreciate it if someone can point me in the right direction. I am learning Java by following online examples Murach's Java book. I wanted to write a function which takes two argumen...

How to put the navbar-brand on the left and ul navbar-pills li on the right?

javascript jquery html css twitter-bootstrap

this is from bootstrap and i can't figure out how to put the navbar-brand on the left and ul navbar-pills on the right of the page. please help. thanks in advance