|
1 | 1 | package dotty.tools.scripting
|
2 | 2 |
|
3 | 3 | import java.io.File
|
4 |
| -import java.nio.file.Path |
| 4 | +import java.nio.file.{Files, Paths, Path} |
| 5 | +import dotty.tools.dotc.util.SourceFile |
| 6 | +import java.net.{ URL, URLClassLoader } |
| 7 | +import java.lang.reflect.{ Modifier, Method } |
| 8 | + |
5 | 9 |
|
6 | 10 | /** Main entry point to the Scripting execution engine */
|
7 | 11 | object Main:
|
8 | 12 | /** All arguments before -script <target_script> are compiler arguments.
|
9 | 13 | All arguments afterwards are script arguments.*/
|
10 |
| - def distinguishArgs(args: Array[String]): (Array[String], File, Array[String]) = |
11 |
| - args.foreach { printf("arg[%s]\n",_) } |
12 |
| - val (compilerArgs, rest) = args.splitAt(args.indexOf("-script")) |
13 |
| - if( rest.isEmpty ){ |
| 14 | + def distinguishArgs(args: Array[String]): (Array[String], File, Array[String], Boolean) = |
| 15 | + // NOTE: if -script is required but not present, quit with error. |
| 16 | + val (leftArgs, rest) = args.splitAt(args.indexOf("-script")) |
| 17 | + if( rest.size < 2 ) then |
14 | 18 | sys.error(s"missing: -script <scriptName>")
|
15 |
| - } |
16 |
| - val file = File(rest.take(1).mkString) |
| 19 | + |
| 20 | + val file = File(rest(1)) |
17 | 21 | val scriptArgs = rest.drop(2)
|
18 |
| - (compilerArgs, file, scriptArgs) |
| 22 | + var saveCompiled = false |
| 23 | + val compilerArgs = leftArgs.filter { |
| 24 | + case "-save" | "-savecompiled" => |
| 25 | + saveCompiled = true |
| 26 | + false |
| 27 | + case _ => |
| 28 | + true |
| 29 | + } |
| 30 | + (compilerArgs, file, scriptArgs, saveCompiled) |
19 | 31 | end distinguishArgs
|
20 | 32 |
|
| 33 | + val pathsep = sys.props("path.separator") |
| 34 | + |
21 | 35 | def main(args: Array[String]): Unit =
|
22 |
| - val (compilerArgs, scriptFile, scriptArgs) = distinguishArgs(args) |
23 |
| - try ScriptingDriver(compilerArgs, scriptFile, scriptArgs).compileAndRun{ (tmpDir:Path,classpath:String) => |
24 |
| - printf("%s\n",tmpDir.toString) |
25 |
| - printf("%s\n",classpath) |
| 36 | + val (compilerArgs, scriptFile, scriptArgs, saveCompiled) = distinguishArgs(args) |
| 37 | + if verbose then showArgs(args, compilerArgs, scriptFile, scriptArgs) |
| 38 | + try ScriptingDriver(compilerArgs, scriptFile, scriptArgs).compileAndRun { (outDir:Path, classpath:String) => |
| 39 | + val classFiles = outDir.toFile.listFiles.toList match { |
| 40 | + case Nil => sys.error(s"no files below [$outDir]") |
| 41 | + case list => list |
| 42 | + } |
| 43 | + |
| 44 | + val (mainClassName, mainMethod) = detectMainMethod(outDir, classpath, scriptFile) |
| 45 | + |
| 46 | + if saveCompiled then |
| 47 | + // write a standalone jar to the script parent directory |
| 48 | + writeJarfile(outDir, scriptFile, scriptArgs, classpath, mainClassName) |
| 49 | + |
| 50 | + try |
| 51 | + // invoke the compiled script main method |
| 52 | + mainMethod.invoke(null, scriptArgs) |
| 53 | + catch |
| 54 | + case e: java.lang.reflect.InvocationTargetException => |
| 55 | + throw e.getCause |
| 56 | + |
26 | 57 | }
|
27 | 58 | catch
|
28 |
| - case ScriptingException(msg) => |
29 |
| - println(s"Error: $msg") |
| 59 | + case e:Exception => |
| 60 | + e.printStackTrace |
| 61 | + println(s"Error: ${e.getMessage}") |
30 | 62 | sys.exit(1)
|
| 63 | + |
| 64 | + def writeJarfile(outDir: Path, scriptFile: File, scriptArgs:Array[String], classpath:String, mainClassName: String): Unit = |
| 65 | + import java.net.{URI, URL} |
| 66 | + val jarTargetDir: Path = Option(scriptFile.toPath.getParent) match { |
| 67 | + case None => sys.error(s"no parent directory for script file [$scriptFile]") |
| 68 | + case Some(parent) => parent |
| 69 | + } |
| 70 | + |
| 71 | + val scriptBasename = scriptFile.getName.takeWhile(_!='.') |
| 72 | + val jarPath = s"$jarTargetDir/$scriptBasename.jar" |
| 73 | + |
| 74 | + val cpPaths = classpath.split(pathsep).map { |
| 75 | + // protect relative paths from being converted to absolute |
| 76 | + case str if str.startsWith(".") && File(str).isDirectory => s"${str.withSlash}/" |
| 77 | + case str if str.startsWith(".") => str.withSlash |
| 78 | + case str => File(str).toURI.toURL.toString |
| 79 | + } |
| 80 | + |
| 81 | + import java.util.jar.Attributes.Name |
| 82 | + val cpString:String = cpPaths.distinct.mkString(" ") |
| 83 | + val manifestAttributes:Seq[(Name, String)] = Seq( |
| 84 | + (Name.MANIFEST_VERSION, "1.0.0"), |
| 85 | + (Name.MAIN_CLASS, mainClassName), |
| 86 | + (Name.CLASS_PATH, cpString), |
| 87 | + ) |
| 88 | + import dotty.tools.io.{Jar, Directory} |
| 89 | + val jar = new Jar(jarPath) |
| 90 | + val writer = jar.jarWriter(manifestAttributes:_*) |
| 91 | + writer.writeAllFrom(Directory(outDir)) |
| 92 | + end writeJarfile |
| 93 | + |
| 94 | + lazy val verbose = Option(System.getenv("DOTC_VERBOSE")) != None |
| 95 | + |
| 96 | + def showArgs(args:Array[String], compilerArgs:Array[String], scriptFile:File, scriptArgs:Array[String]): Unit = |
| 97 | + args.foreach { printf("args[%s]\n", _) } |
| 98 | + compilerArgs.foreach { printf("compilerArgs[%s]\n", _) } |
| 99 | + scriptArgs.foreach { printf("scriptArgs[%s]\n", _) } |
| 100 | + printf("scriptFile[%s]\n", scriptFile) |
| 101 | + |
| 102 | + private def detectMainMethod(outDir: Path, classpath: String, scriptFile: File): (String, Method) = |
| 103 | + val outDirURL = outDir.toUri.toURL |
| 104 | + val classpathUrls = classpath.split(pathsep).map(File(_).toURI.toURL) |
| 105 | + val cl = URLClassLoader(classpathUrls :+ outDirURL) |
| 106 | + |
| 107 | + def collectMainMethods(target: File, path: String): List[(String, Method)] = |
| 108 | + val nameWithoutExtension = target.getName.takeWhile(_ != '.') |
| 109 | + val targetPath = |
| 110 | + if path.nonEmpty then s"${path}.${nameWithoutExtension}" |
| 111 | + else nameWithoutExtension |
| 112 | + |
| 113 | + if verbose then printf("targetPath [%s]\n",targetPath) |
| 114 | + |
| 115 | + if target.isDirectory then |
| 116 | + for |
| 117 | + packageMember <- target.listFiles.toList |
| 118 | + membersMainMethod <- collectMainMethods(packageMember, targetPath) |
| 119 | + yield membersMainMethod |
| 120 | + else if target.getName.endsWith(".class") then |
| 121 | + val cls = cl.loadClass(targetPath) |
| 122 | + try |
| 123 | + val method = cls.getMethod("main", classOf[Array[String]]) |
| 124 | + if Modifier.isStatic(method.getModifiers) then List((cls.getName, method)) else Nil |
| 125 | + catch |
| 126 | + case _: java.lang.NoSuchMethodException => Nil |
| 127 | + else Nil |
| 128 | + end collectMainMethods |
| 129 | + |
| 130 | + val candidates = for |
| 131 | + file <- outDir.toFile.listFiles.toList |
| 132 | + method <- collectMainMethods(file, "") |
| 133 | + yield method |
| 134 | + |
| 135 | + candidates match |
| 136 | + case Nil => |
| 137 | + if verbose then outDir.toFile.listFiles.toList.foreach { f => System.err.printf("%s\n",f.toString) } |
| 138 | + throw ScriptingException(s"No main methods detected in script ${scriptFile}") |
| 139 | + case _ :: _ :: _ => |
| 140 | + throw ScriptingException("A script must contain only one main method. " + |
| 141 | + s"Detected the following main methods:\n${candidates.mkString("\n")}") |
| 142 | + case m :: Nil => m |
| 143 | + end match |
| 144 | + end detectMainMethod |
| 145 | + |
| 146 | + extension(pathstr:String) { |
| 147 | + def withSlash:String = pathstr.replace('\\', '/') |
| 148 | + } |
0 commit comments