Skip to content

Commit

Permalink
Refactoring (#2842)
Browse files Browse the repository at this point in the history
Added some explicit return values and fixed some compiler warnings. 
Use `SubPath` instead of `RelPath` for tests executable paths.
Reordered in/out stream initialization for consistency.

Pull request: #2842
  • Loading branch information
lefou authored Nov 6, 2023
1 parent e813183 commit 0718394
Show file tree
Hide file tree
Showing 19 changed files with 57 additions and 65 deletions.
11 changes: 6 additions & 5 deletions build.sc
Original file line number Diff line number Diff line change
Expand Up @@ -222,11 +222,12 @@ val bridgeScalaVersions = Seq(
// of them. Compiler bridges not in this set will get downloaded and compiled
// on the fly anyway. For publishing, we publish everything or a specific version
// if given.
val compilerBridgeScalaVersions = interp.watchValue(sys.env.get("MILL_COMPILER_BRIDGE_VERSIONS")) match {
case None => Seq.empty[String]
case Some("all") => bridgeScalaVersions
case Some(versions) => versions.split(',').map(_.trim).toSeq
}
val compilerBridgeScalaVersions =
interp.watchValue(sys.env.get("MILL_COMPILER_BRIDGE_VERSIONS")) match {
case None => Seq.empty[String]
case Some("all") => bridgeScalaVersions
case Some(versions) => versions.split(',').map(_.trim).toSeq
}
val bridgeVersion = "0.0.1"

trait MillJavaModule extends JavaModule {
Expand Down
10 changes: 5 additions & 5 deletions example/src/mill/integration/ExampleTestSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ object ExampleTestSuite extends IntegrationTestSuite {
case "mill" => evalStdout(rest)
case cmd =>
val tokens = cmd +: rest
val executable = workspaceRoot / os.RelPath(tokens.head)
val executable = workspaceRoot / os.SubPath(tokens.head)
if (!os.exists(executable)) {
throw new Exception(
s"Executable $executable not found.\n" +
Expand Down Expand Up @@ -167,7 +167,7 @@ object ExampleTestSuite extends IntegrationTestSuite {
} finally { zipFile.close() }

case Seq("printf", literal, ">>", path) =>
mangleFile(os.Path(path, workspacePath), _ + ujson.read('"' + literal + '"').str)
mangleFile(os.Path(path, workspacePath), _ + ujson.read(s""""${literal}"""").str)

}
}
Expand Down Expand Up @@ -217,17 +217,17 @@ object ExampleTestSuite extends IntegrationTestSuite {
}
}

def globMatches(expected: String, filtered: String) = {
def globMatches(expected: String, filtered: String): Boolean = {
filtered
.linesIterator
.exists(
StringContext
.glob(expected.split("\\.\\.\\.", -1), _)
.glob(expected.split("\\.\\.\\.", -1).toIndexedSeq, _)
.nonEmpty
)
}

def globMatchesAny(expected: String, filtered: String) = {
def globMatchesAny(expected: String, filtered: String): Boolean = {
expected.linesIterator.exists(globMatches(_, filtered))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import utest._

object InvalidMetaModuleTests extends IntegrationTestSuite {
val tests = Tests {
val workspaceRoot = initWorkspace()
initWorkspace()

test("success") {
val res = evalStdout("resolve", "_")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import utest._

object MultipleTopLevelModulesTests extends IntegrationTestSuite {
val tests = Tests {
val workspaceRoot = initWorkspace()
initWorkspace()

test("success") {
val res = evalStdout("resolve", "_")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import utest._

object ThingsOutsideTopLevelModuleTests extends IntegrationTestSuite {
val tests = Tests {
val workspaceRoot = initWorkspace()
initWorkspace()

test("success") {
val res = evalStdout("resolve", "_")
Expand Down
4 changes: 2 additions & 2 deletions main/api/src/mill/api/SystemStreams.scala
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,13 @@ object SystemStreams {
def originalErr: PrintStream = original.err

def withStreams[T](systemStreams: SystemStreams)(t: => T): T = {
val out = System.out
val in = System.in
val out = System.out
val err = System.err
try {
System.setIn(systemStreams.in)
System.setErr(systemStreams.err)
System.setOut(systemStreams.out)
System.setErr(systemStreams.err)
Console.withIn(systemStreams.in) {
Console.withOut(systemStreams.out) {
Console.withErr(systemStreams.err) {
Expand Down
2 changes: 1 addition & 1 deletion main/codesig/src/LocalSummary.scala
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ object LocalSummary {

def hash(x: Int): Unit = insnHash = scala.util.hashing.MurmurHash3.mix(insnHash, x)

def completeHash() = {
def completeHash(): Unit = {
insnSigs.append(scala.util.hashing.MurmurHash3.finalizeHash(0, insnHash))
insnHash = 0
}
Expand Down
2 changes: 1 addition & 1 deletion main/codesig/src/ResolvedCalls.scala
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ object ResolvedCalls {

val allSamImplementors = allSamImplementors0
.groupMap(_._1)(_._2)
.mapValues(_.toSet)
.view.mapValues(_.toSet)
.toMap

allSamImplementors
Expand Down
12 changes: 6 additions & 6 deletions main/define/src/mill/define/Task.scala
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ object Task {
}

private[define] class Sequence[+T](inputs0: Seq[Task[T]]) extends Task[Seq[T]] {
val inputs = inputs0
def evaluate(ctx: mill.api.Ctx) = {
val inputs: Seq[Task[_]] = inputs0
def evaluate(ctx: mill.api.Ctx): Result[Seq[T]] = {
for (i <- 0 until ctx.args.length)
yield ctx.args(i).asInstanceOf[T]
}
Expand All @@ -63,7 +63,7 @@ object Task {
inputs0: Seq[Task[T]],
f: (IndexedSeq[T], mill.api.Ctx) => Result[V]
) extends Task[V] {
val inputs = inputs0
val inputs: Seq[Task[_]] = inputs0
def evaluate(ctx: mill.api.Ctx) = {
f(
for (i <- 0 until ctx.args.length)
Expand All @@ -75,12 +75,12 @@ object Task {

private[define] class Mapped[+T, +V](source: Task[T], f: T => V) extends Task[V] {
def evaluate(ctx: mill.api.Ctx) = f(ctx.arg(0))
val inputs = List(source)
val inputs: Seq[Task[_]] = List(source)
}

private[define] class Zipped[+T, +V](source1: Task[T], source2: Task[V]) extends Task[(T, V)] {
def evaluate(ctx: mill.api.Ctx) = (ctx.arg(0), ctx.arg(1))
val inputs = List(source1, source2)
val inputs: Seq[Task[_]] = List(source1, source2)
}
}

Expand Down Expand Up @@ -108,7 +108,7 @@ trait NamedTask[+T] extends Task[T] {
def evaluate(ctx: mill.api.Ctx) = ctx.arg[T](0)

val ctx = ctx0.withSegments(segments = ctx0.segments ++ Seq(ctx0.segment))
val inputs = Seq(t)
val inputs: Seq[Task[_]] = Seq(t)

def readWriterOpt: Option[upickle.default.ReadWriter[_]] = None

Expand Down
4 changes: 2 additions & 2 deletions main/src/mill/main/MainModule.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package mill.main

import java.util.concurrent.LinkedBlockingQueue
import mill.define.Target
import mill.main.BuildInfo
import mill.api.{Ctx, Logger, PathRef, Result}
import mill.define.{Command, NamedTask, Segments, Task}
import mill.eval.{Evaluator, EvaluatorPaths, Terminal}
Expand Down Expand Up @@ -31,7 +30,8 @@ object MainModule {
targets: Seq[String],
log: Logger,
watch0: Watchable => Unit
)(f: Seq[(Any, Option[(RunScript.TaskName, ujson.Value)])] => ujson.Value) = {
)(f: Seq[(Any, Option[(RunScript.TaskName, ujson.Value)])] => ujson.Value)
: Result[ujson.Value] = {

RunScript.evaluateTasksNamed(
// When using `show`, redirect all stdout of the evaluated tasks so the
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package mill.scalajslib.worker

// Separating ModuleSplitStyle in a standalone object avoids
// early classloading which fails in Scala.js versions where
// the classes don't exist
object ScalaJSModuleSplitStyle {
import org.scalajs.linker.interface.ModuleSplitStyle
object SmallModulesFor {
def apply(packages: List[String]): ModuleSplitStyle =
ModuleSplitStyle.SmallModulesFor(packages)
}
object FewestModules {
def apply(): ModuleSplitStyle = ModuleSplitStyle.FewestModules
}
object SmallestModules {
def apply(): ModuleSplitStyle = ModuleSplitStyle.SmallestModules
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -330,20 +330,3 @@ class ScalaJSWorkerImpl extends ScalaJSWorkerApi {
Seq(input)
}
}

// Separating ModuleSplitStyle in a standalone object avoids
// early classloading which fails in Scala.js versions where
// the classes don't exist
object ScalaJSModuleSplitStyle {
import org.scalajs.linker.interface.ModuleSplitStyle
object SmallModulesFor {
def apply(packages: List[String]): ModuleSplitStyle =
ModuleSplitStyle.SmallModulesFor(packages)
}
object FewestModules {
def apply(): ModuleSplitStyle = ModuleSplitStyle.FewestModules
}
object SmallestModules {
def apply(): ModuleSplitStyle = ModuleSplitStyle.SmallestModules
}
}
16 changes: 8 additions & 8 deletions scalalib/api/src/mill/scalalib/api/ZincWorkerUtil.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ trait ZincWorkerUtil {
val suffix = if (sources) "-sources.jar" else ".jar"
lazy val dir = if (sources) "srcs" else "jars"

def mavenStyleMatch(fname: String) =
def mavenStyleMatch(fname: String): Boolean =
fname.startsWith(s"$name-$versionPrefix") && fname.endsWith(suffix)

def ivyStyleMatch(p: os.Path) = {
def ivyStyleMatch(p: os.Path): Boolean = {
val fname = s"$name$suffix"
p.segments.toSeq match {
case _ :+ v :+ `dir` :+ `fname` if v.startsWith(versionPrefix) => true
Expand All @@ -52,7 +52,7 @@ trait ZincWorkerUtil {
val NightlyVersion = raw"""(\d+)\.(\d+)\.(\d+)-bin-[a-f0-9]*""".r
val TypelevelVersion = raw"""(\d+)\.(\d+)\.(\d+)-bin-typelevel.*""".r

def scalaBinaryVersion(scalaVersion: String) = scalaVersion match {
def scalaBinaryVersion(scalaVersion: String): String = scalaVersion match {
case Scala3EarlyVersion(milestone) => s"3.0.0-$milestone"
case Scala3Version(_, _) => "3"
case ReleaseVersion(major, minor, _) => s"$major.$minor"
Expand All @@ -65,7 +65,7 @@ trait ZincWorkerUtil {

private val ScalaJSFullVersion = """^([0-9]+)\.([0-9]+)\.([0-9]+)(-.*)?$""".r

def scalaJSBinaryVersion(scalaJSVersion: String) = scalaJSVersion match {
def scalaJSBinaryVersion(scalaJSVersion: String): String = scalaJSVersion match {
case _ if scalaJSVersion.startsWith("0.6.") =>
throw new Exception("Scala.js 0.6 is not supported")
case ScalaJSFullVersion(major, minor, patch, suffix) =>
Expand All @@ -75,7 +75,7 @@ trait ZincWorkerUtil {
major
}

def scalaJSWorkerVersion(scalaJSVersion: String) = scalaJSVersion match {
def scalaJSWorkerVersion(scalaJSVersion: String): String = scalaJSVersion match {
case _ if scalaJSVersion.startsWith("0.6.") =>
throw new Exception("Scala.js 0.6 is not supported")
case ScalaJSFullVersion(major, _, _, _) =>
Expand All @@ -84,15 +84,15 @@ trait ZincWorkerUtil {

private val ScalaNativeFullVersion = """^([0-9]+)\.([0-9]+)\.([0-9]+)(-.*)?$""".r

def scalaNativeBinaryVersion(version: String) = version match {
def scalaNativeBinaryVersion(version: String): String = version match {
case ScalaNativeFullVersion(major, minor, patch, suffix) =>
if (suffix != null && patch == "0")
version
else
s"$major.$minor"
}

def scalaNativeWorkerVersion(version: String) = version match {
def scalaNativeWorkerVersion(version: String): String = version match {
case ScalaNativeFullVersion(major, minor, _, _) =>
s"$major.$minor"
}
Expand All @@ -110,7 +110,7 @@ trait ZincWorkerUtil {
Versions.millCompilerBridgeScalaVersions.split(",").toSet

/** @return true if the compiler bridge can be downloaded as an already compiled jar */
def isBinaryBridgeAvailable(scalaVersion: String) =
def isBinaryBridgeAvailable(scalaVersion: String): Boolean =
if (millCompilerBridgeScalaVersions.contains(scalaVersion)) true
else scalaVersion match {
case DottyNightlyVersion(major, minor, _, _) =>
Expand Down
4 changes: 0 additions & 4 deletions scalalib/src/mill/scalalib/JavaModule.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package mill
package scalalib

import scala.annotation.nowarn
import coursier.Repository
import coursier.core.Dependency
import coursier.core.Resolution
Expand Down Expand Up @@ -699,8 +698,6 @@ trait JavaModule
*/
def ivyDepsTree(args: IvyDepsTreeArgs = IvyDepsTreeArgs()): Command[Unit] = {

val dependsOnModules = args.whatDependsOn.map(ModuleParser.javaOrScalaModule(_))

val (invalidModules, validModules) =
args.whatDependsOn.map(ModuleParser.javaOrScalaModule(_)).partitionMap(identity)

Expand Down Expand Up @@ -961,7 +958,6 @@ trait JavaModule
/**
* @param all If `true` fetches also source dependencies
*/
@nowarn("msg=pure expression does nothing")
override def prepareOffline(all: Flag): Command[Unit] = {
val tasks =
if (all.value) Seq(
Expand Down
2 changes: 0 additions & 2 deletions scalalib/src/mill/scalalib/ScalaModule.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package mill
package scalalib

import scala.annotation.nowarn
import mill.api.{DummyInputStream, JarManifest, PathRef, Result, SystemStreams, internal}
import mill.main.BuildInfo
import mill.util.{Jvm, Util}
Expand Down Expand Up @@ -480,7 +479,6 @@ trait ScalaModule extends JavaModule with TestModule.ScalaModuleBase { outer =>
/**
* @param all If `true` , fetches also sources, Ammonite and compiler dependencies.
*/
@nowarn("msg=pure expression does nothing")
override def prepareOffline(all: Flag): Command[Unit] = {
val ammonite = resolvedAmmoniteReplIvyDeps
val tasks =
Expand Down
4 changes: 0 additions & 4 deletions scalalib/src/mill/scalalib/ZincWorkerModule.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package mill.scalalib

import scala.annotation.nowarn
import coursier.Repository
import mainargs.Flag
import mill.Agg
Expand Down Expand Up @@ -47,7 +46,6 @@ trait ZincWorkerModule extends mill.Module with OfflineSupportModule { self: Cou
def zincLogDebug: T[Boolean] = T.input(T.ctx().log.debugEnabled)

def worker: Worker[ZincWorkerApi] = T.worker {
val ctx = T.ctx()
val jobs = T.ctx() match {
case j: Ctx.Jobs => j.jobs
case _ => 1
Expand Down Expand Up @@ -169,14 +167,12 @@ trait ZincWorkerModule extends mill.Module with OfflineSupportModule { self: Cou
} else dep
}

@nowarn("msg=pure expression does nothing")
override def prepareOffline(all: Flag): Command[Unit] = T.command {
super.prepareOffline(all)()
classpath()
()
}

@nowarn("msg=pure expression does nothing")
def prepareOfflineCompiler(scalaVersion: String, scalaOrganization: String): Command[Unit] =
T.command {
classpath()
Expand Down
5 changes: 2 additions & 3 deletions scalalib/src/mill/scalalib/bsp/BuildScAwareness.scala
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ trait BuildScAwareness {

private val MatchDep = """^import ([$]ivy[.]`([^`]+)`).*""".r
private val MatchFile = """^import ([$]file[.]([^,]+)).*""".r
private val MatchShebang = """^(#!.*)$""".r

def parseAmmoniteImports(buildScript: os.Path): Seq[Included] = {
val queue = mutable.Queue.empty[os.Path]
Expand All @@ -25,8 +24,8 @@ trait BuildScAwareness {
while (queue.nonEmpty) {
val file = queue.dequeue()
val inclusions = os.read.lines(file).collect {
case m @ MatchDep(_, dep) => IncludedDep(dep, file)
case m @ MatchFile(_, include) =>
case MatchDep(_, dep) => IncludedDep(dep, file)
case MatchFile(_, include) =>
val pat = include.split("[.]").map {
case "^" => os.up
case x => os.rel / x
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package mill.scalalib.dependency.versions

import fastparse._, NoWhitespace._
import fastparse._
import fastparse.NoWhitespace._

private[dependency] object VersionParser {

Expand Down
2 changes: 1 addition & 1 deletion scalalib/src/mill/scalalib/internal/ModuleUtils.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package mill.scalalib.internal

import mill.api.{BuildScriptException, experimental}
import mill.api.BuildScriptException
import mill.define.{Module, Segments}

import scala.annotation.tailrec
Expand Down

0 comments on commit 0718394

Please sign in to comment.