-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathMainGenericRunner.scala
275 lines (244 loc) · 11.6 KB
/
MainGenericRunner.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package dotty.tools
import scala.language.unsafeNulls
import scala.annotation.tailrec
import scala.io.Source
import scala.util.Try
import java.io.File
import java.lang.Thread
import scala.annotation.internal.sharable
import dotty.tools.dotc.util.ClasspathFromClassloader
import dotty.tools.runner.ObjectRunner
import dotty.tools.dotc.config.Properties.envOrNone
import dotty.tools.io.Jar
import dotty.tools.runner.ScalaClassLoader
import java.nio.file.Paths
import dotty.tools.dotc.config.CommandLineParser
import dotty.tools.scripting.StringDriver
enum ExecuteMode:
case Guess
case Script
case Repl
case Run
case PossibleRun
case Expression
case class Settings(
verbose: Boolean = false,
classPath: List[String] = List.empty,
executeMode: ExecuteMode = ExecuteMode.Guess,
exitCode: Int = 0,
javaArgs: List[String] = List.empty,
scalaArgs: List[String] = List.empty,
residualArgs: List[String] = List.empty,
possibleEntryPaths: List[String] = List.empty,
scriptArgs: List[String] = List.empty,
targetScript: String = "",
targetExpression: String = "",
targetToRun: String = "",
save: Boolean = false,
modeShouldBePossibleRun: Boolean = false,
modeShouldBeRun: Boolean = false,
compiler: Boolean = false,
) {
def withExecuteMode(em: ExecuteMode): Settings = this.executeMode match
case ExecuteMode.Guess | ExecuteMode.PossibleRun =>
this.copy(executeMode = em)
case _ =>
println(s"execute_mode==[$executeMode], attempted overwrite by [$em]")
this.copy(exitCode = 1)
end withExecuteMode
def withScalaArgs(args: String*): Settings =
this.copy(scalaArgs = scalaArgs.appendedAll(args.toList))
def withJavaArgs(args: String*): Settings =
this.copy(javaArgs = javaArgs.appendedAll(args.toList))
def withResidualArgs(args: String*): Settings =
this.copy(residualArgs = residualArgs.appendedAll(args.toList))
def withPossibleEntryPaths(args: String*): Settings =
this.copy(possibleEntryPaths = possibleEntryPaths.appendedAll(args.toList))
def withScriptArgs(args: String*): Settings =
this.copy(scriptArgs = scriptArgs.appendedAll(args.toList))
def withTargetScript(file: String): Settings =
Try(Source.fromFile(file)).toOption match
case Some(_) => this.copy(targetScript = file)
case None =>
println(s"not found $file")
this.copy(exitCode = 2)
end withTargetScript
def withTargetToRun(targetToRun: String): Settings =
this.copy(targetToRun = targetToRun)
def withExpression(scalaSource: String): Settings =
this.copy(targetExpression = scalaSource)
def withSave: Settings =
this.copy(save = true)
def noSave: Settings =
this.copy(save = false)
def withModeShouldBePossibleRun: Settings =
this.copy(modeShouldBePossibleRun = true)
def withModeShouldBeRun: Settings =
this.copy(modeShouldBeRun = true)
def withCompiler: Settings =
this.copy(compiler = true)
}
object MainGenericRunner {
val classpathSeparator = File.pathSeparator
@sharable val javaOption = raw"""-J(.*)""".r
@sharable val scalaOption = raw"""@.*""".r
@sharable val colorOption = raw"""-color:.*""".r
@tailrec
def process(args: List[String], settings: Settings): Settings = args match
case Nil =>
settings
case "-run" :: fqName :: tail =>
process(tail, settings.withExecuteMode(ExecuteMode.Run).withTargetToRun(fqName))
case ("-cp" | "-classpath" | "--class-path") :: cp :: tail =>
val cpEntries = cp.split(classpathSeparator).toList
val singleEntryClasspath: Boolean = cpEntries.take(2).size == 1
val globdir: String = if singleEntryClasspath then cp.replaceAll("[\\\\/][^\\\\/]*$", "") else "" // slash/backslash agnostic
def validGlobbedJar(s: String): Boolean = s.startsWith(globdir) && ((s.toLowerCase.endsWith(".jar") || s.toLowerCase.endsWith(".zip")))
val (tailargs, newEntries) = if singleEntryClasspath && validGlobbedJar(cpEntries.head) then
// reassemble globbed wildcard classpath
// globdir is wildcard directory for globbed jar files, reconstruct the intended classpath
val cpJars = tail.takeWhile( f => validGlobbedJar(f) )
val remainingArgs = tail.drop(cpJars.size)
(remainingArgs, cpEntries ++ cpJars)
else
(tail, cpEntries)
process(tailargs, settings.copy(classPath = settings.classPath ++ newEntries.filter(_.nonEmpty)))
case ("-version" | "--version") :: _ =>
settings.copy(
executeMode = ExecuteMode.Repl,
residualArgs = List("-version")
)
case ("-v" | "-verbose" | "--verbose") :: tail =>
process(
tail,
settings.copy(
verbose = true,
residualArgs = settings.residualArgs :+ "-verbose"
)
)
case "-save" :: tail =>
process(tail, settings.withSave)
case "-nosave" :: tail =>
process(tail, settings.noSave)
case "-with-compiler" :: tail =>
process(tail, settings.withCompiler)
case (o @ javaOption(striped)) :: tail =>
process(tail, settings.withJavaArgs(striped).withScalaArgs(o))
case (o @ scalaOption(_*)) :: tail =>
val remainingArgs = (CommandLineParser.expandArg(o) ++ tail).toList
process(remainingArgs, settings)
case (o @ colorOption(_*)) :: tail =>
process(tail, settings.withScalaArgs(o))
case "-e" :: expression :: tail =>
val mainSource = s"@main def main(args: String *): Unit =\n ${expression}"
settings
.withExecuteMode(ExecuteMode.Expression)
.withExpression(mainSource)
.withScriptArgs(tail*)
.noSave // -save not useful here
case arg :: tail =>
val line = Try(Source.fromFile(arg).getLines.toList).toOption.flatMap(_.headOption)
lazy val hasScalaHashbang = { val s = line.getOrElse("") ; s.startsWith("#!") && s.contains("scala") }
if arg.endsWith(".scala") || arg.endsWith(".sc") || hasScalaHashbang then
settings
.withExecuteMode(ExecuteMode.Script)
.withTargetScript(arg)
.withScriptArgs(tail*)
else
val newSettings = if arg.startsWith("-") then settings else settings.withPossibleEntryPaths(arg).withModeShouldBePossibleRun
process(tail, newSettings.withResidualArgs(arg))
end process
def main(args: Array[String]): Unit =
val scalaOpts = envOrNone("SCALA_OPTS").toArray.flatMap(_.split(" ")).filter(_.nonEmpty)
val allArgs = scalaOpts ++ args
val settings = process(allArgs.toList, Settings())
if settings.exitCode != 0 then System.exit(settings.exitCode)
def removeCompiler(cp: Array[String]) =
if (!settings.compiler) then // Let's remove compiler from the classpath
val compilerLibs = Seq("scala3-compiler", "scala3-interfaces", "tasty-core", "scala-asm", "scala3-staging", "scala3-tasty-inspector")
cp.filterNot(c => compilerLibs.exists(c.contains))
else
cp
def run(settings: Settings): Unit = settings.executeMode match
case ExecuteMode.Repl =>
val properArgs =
List("-classpath", settings.classPath.mkString(classpathSeparator)).filter(Function.const(settings.classPath.nonEmpty))
++ settings.residualArgs
repl.Main.main(properArgs.toArray)
case ExecuteMode.PossibleRun =>
val newClasspath = (settings.classPath :+ ".").flatMap(_.split(classpathSeparator).filter(_.nonEmpty)).map(File(_).toURI.toURL)
import dotty.tools.runner.ClassLoaderOps._
val newClassLoader = ScalaClassLoader.fromURLsParallelCapable(newClasspath)
val targetToRun = settings.possibleEntryPaths.to(LazyList).find { entryPath =>
newClassLoader.tryToLoadClass(entryPath).orElse {
Option.when(Jar.isJarOrZip(dotty.tools.io.Path(entryPath)))(Jar(entryPath).mainClass).flatten
}.isDefined
}
val newSettings = targetToRun match
case Some(fqName) =>
settings.withTargetToRun(fqName).copy(residualArgs = settings.residualArgs.filterNot(fqName.==)).withExecuteMode(ExecuteMode.Run)
case None =>
settings.withExecuteMode(ExecuteMode.Repl)
run(newSettings)
case ExecuteMode.Run =>
val scalaClasspath = ClasspathFromClassloader(Thread.currentThread().getContextClassLoader).split(classpathSeparator)
val newClasspath = (settings.classPath.flatMap(_.split(classpathSeparator).filter(_.nonEmpty)) ++ removeCompiler(scalaClasspath) :+ ".").map(File(_).toURI.toURL)
val res = ObjectRunner.runAndCatch(newClasspath, settings.targetToRun, settings.residualArgs).flatMap {
case ex: ClassNotFoundException if ex.getMessage == settings.targetToRun =>
val file = settings.targetToRun
Jar(file).mainClass match
case Some(mc) =>
ObjectRunner.runAndCatch(newClasspath :+ File(file).toURI.toURL, mc, settings.residualArgs)
case None =>
Some(IllegalArgumentException(s"No main class defined in manifest in jar: $file"))
case ex => Some(ex)
}
errorFn("", res)
case ExecuteMode.Script =>
val targetScript = Paths.get(settings.targetScript).toFile
val targetJar = settings.targetScript.replaceAll("[.][^\\/]*$", "")+".jar"
val precompiledJar = File(targetJar)
val mainClass = if !precompiledJar.isFile then "" else Jar(targetJar).mainClass.getOrElse("")
val jarIsValid = mainClass.nonEmpty && precompiledJar.lastModified >= targetScript.lastModified && settings.save
if jarIsValid then
// precompiledJar exists, is newer than targetScript, and manifest defines a mainClass
sys.props("script.path") = targetScript.toPath.toAbsolutePath.normalize.toString
val scalaClasspath = ClasspathFromClassloader(Thread.currentThread().getContextClassLoader).split(classpathSeparator)
val newClasspath = (settings.classPath.flatMap(_.split(classpathSeparator).filter(_.nonEmpty)) ++ removeCompiler(scalaClasspath) :+ ".").map(File(_).toURI.toURL)
val res = if mainClass.nonEmpty then
ObjectRunner.runAndCatch(newClasspath :+ File(targetJar).toURI.toURL, mainClass, settings.scriptArgs)
else
Some(IllegalArgumentException(s"No main class defined in manifest in jar: $precompiledJar"))
errorFn("", res)
else
val properArgs =
List("-classpath", settings.classPath.mkString(classpathSeparator)).filter(Function.const(settings.classPath.nonEmpty))
++ settings.residualArgs
++ (if settings.save then List("-save") else Nil)
++ settings.scalaArgs
++ List("-script", settings.targetScript)
++ settings.scriptArgs
scripting.Main.main(properArgs.toArray)
case ExecuteMode.Expression =>
val cp = settings.classPath match {
case Nil => ""
case list => list.mkString(classpathSeparator)
}
val cpArgs = if cp.isEmpty then Nil else List("-classpath", cp)
val properArgs = cpArgs ++ settings.residualArgs ++ settings.scalaArgs
val driver = StringDriver(properArgs.toArray, settings.targetExpression)
driver.compileAndRun(settings.classPath)
case ExecuteMode.Guess =>
if settings.modeShouldBePossibleRun then
run(settings.withExecuteMode(ExecuteMode.PossibleRun))
else if settings.modeShouldBeRun then
run(settings.withExecuteMode(ExecuteMode.Run))
else
run(settings.withExecuteMode(ExecuteMode.Repl))
run(settings)
def errorFn(str: String, e: Option[Throwable] = None, isFailure: Boolean = true): Boolean = {
if (str.nonEmpty) Console.err.println(str)
e.foreach(_.printStackTrace())
!isFailure
}
}