Skip to content

Commit

Permalink
Add logging to Fix command
Browse files Browse the repository at this point in the history
  • Loading branch information
MaciejG604 committed Jul 25, 2023
1 parent 9788b0b commit c737202
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 22 deletions.
50 changes: 38 additions & 12 deletions modules/cli/src/main/scala/scala/cli/commands/fix/Fix.scala
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,11 @@ object Fix extends ScalaCommand[FixOptions] {

val projectFileContents = new StringBuilder()

given LoggingUtilities(logger, inputs.workspace)

// Deal with directives from the Main scope
{
val originalMainDirectives = getExtractedDirectives(mainSources, logger)
val originalMainDirectives = getExtractedDirectives(mainSources)
.filterNot(hasTargetDirectives)

val transformedMainDirectives = unifyCorrespondingNameAliases(originalMainDirectives)
Expand All @@ -78,14 +80,16 @@ object Fix extends ScalaCommand[FixOptions] {

directivesFromWritableMainInputs.foreach(d => removeDirectivesFrom(d.positions))

projectFileContents.append("// Main")
.append("\n")

val allDirectives = for {
transformedMainDirective <- transformedMainDirectives
directive <- transformedMainDirective.directives
} yield directive

if (allDirectives.nonEmpty)
projectFileContents
.append("// Main")
.append("\n")

allDirectives
.flatMap(_.explodeToStrings)
.distinct
Expand All @@ -95,7 +99,7 @@ object Fix extends ScalaCommand[FixOptions] {

// Deal with directives from the Test scope
if (testSources.paths.nonEmpty || testSources.inMemory.nonEmpty) {
val originalTestDirectives = getExtractedDirectives(testSources, logger)
val originalTestDirectives = getExtractedDirectives(testSources)
.filterNot(hasTargetDirectives)

val transformedTestDirectives = unifyCorrespondingNameAliases(originalTestDirectives)
Expand Down Expand Up @@ -128,20 +132,25 @@ object Fix extends ScalaCommand[FixOptions] {
os.write.over(inputs.workspace / Constants.projectFileName, projectFileContents.toString)
}

def getExtractedDirectives(
sources: Sources,
logger: Logger
def getExtractedDirectives(sources: Sources)(
using loggingUtilities: LoggingUtilities
): Seq[ExtractedDirectives] = {
val logger = loggingUtilities.logger

val fromPaths = sources.paths.map { (path, _) =>
val content = os.read(path).toCharArray
logger.debug(s"Extracting directives from ${loggingUtilities.relativePath(path)}")
ExtractedDirectives.from(content, Right(path), logger, _ => None).orExit(logger)
}

val fromInMemory = sources.inMemory.map { inMem =>
val originOrPath = inMem.originalPath.map((_, path) => path)
val content = originOrPath match {
case Right(path) => os.read(path).toCharArray
case Right(path) =>
logger.debug(s"Extracting directives from ${loggingUtilities.relativePath(path)}")
os.read(path).toCharArray
case Left(origin) =>
logger.debug(s"Extracting directives from $origin")
inMem.wrapperParamsOpt match {
// In case of script snippets, we need to drop the top wrapper lines
case Some(wrapperParams) => inMem.generatedContent
Expand Down Expand Up @@ -211,12 +220,22 @@ object Fix extends ScalaCommand[FixOptions] {
def removeDirectivesFrom(
position: Option[Position.File],
toKeep: Seq[StrictDirective] = Nil
)(
using loggingUtilities: LoggingUtilities
): Unit = {
position match {
case Some(Position.File(Right(path), _, endPos)) =>
val offset = endPos._2
val keepLines = toKeep.mkString("", "\n", "\n")
val newContents = keepLines + os.read(path).drop(offset + 1)
val offset = endPos._2
val keepLines = toKeep.mkString("", "\n", "\n")
val newContents = keepLines + os.read(path).drop(offset + 1)
val relativePath = loggingUtilities.relativePath(path)

loggingUtilities.logger.message(s"Removing directives from $relativePath")
if (toKeep.nonEmpty) {
loggingUtilities.logger.message(" Keeping:")
toKeep.foreach(d => loggingUtilities.logger.message(s" $d"))
}

os.write.over(path, newContents.stripLeading())
case _ => ()
}
Expand All @@ -227,4 +246,11 @@ object Fix extends ScalaCommand[FixOptions] {
noTestPrefixAvailable: Seq[StrictDirective],
positions: Option[Position.File]
)

case class LoggingUtilities(
logger: Logger,
workspacePath: os.Path
) {
def relativePath(path: os.Path) = path.relativeTo(workspacePath)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ class FixTests extends ScalaCliSuite {

val projectFileName = "project.scala"

val extraOptions = Seq("--suppress-experimental-feature-warning")

test("fix basic") {
val mainFileName = "Main.scala"
val inputs = TestInputs(
Expand All @@ -30,8 +32,14 @@ class FixTests extends ScalaCliSuite {
)

inputs.fromRoot { root =>
val fixOutput = os.proc(TestUtil.cli, "--power", "fix", ".")
.call(cwd = root).out.trim()
val fixOutput = os.proc(TestUtil.cli, "--power", "fix", ".", "-v", "-v", extraOptions)
.call(cwd = root, mergeErrIntoOut = true).out.trim()

expect(fixOutput ==
"""Extracting directives from Main.scala
|Extracting directives from project.scala
|Removing directives from Main.scala
|Removing directives from project.scala""".stripMargin)

val projectFileContents = os.read(root / projectFileName)
val mainFileContents = os.read(root / mainFileName)
Expand All @@ -52,7 +60,7 @@ class FixTests extends ScalaCliSuite {
|}
|""".stripMargin)

val runProc = os.proc(TestUtil.cli, "--power", "compile", ".")
val runProc = os.proc(TestUtil.cli, "--power", "compile", ".", extraOptions)
.call(cwd = root, stderr = os.Pipe)

expect(!runProc.err.trim.contains("Using directives detected in multiple files"))
Expand Down Expand Up @@ -92,8 +100,16 @@ class FixTests extends ScalaCliSuite {
)

inputs.fromRoot { root =>
val fixOutput = os.proc(TestUtil.cli, "--power", "fix", ".")
.call(cwd = root).out.trim()
val fixOutput = os.proc(TestUtil.cli, "--power", "fix", ".", "-v", "-v", extraOptions)
.call(cwd = root, mergeErrIntoOut = true).out.trim()

expect(fixOutput ==
"""Extracting directives from project.scala
|Extracting directives from src/Main.scala
|Removing directives from project.scala
|Removing directives from src/Main.scala
|Extracting directives from test/MyTests.scala
|Removing directives from test/MyTests.scala""".stripMargin)

val projectFileContents = os.read(root / projectFileName)
val mainFileContents = os.read(root / mainSubPath)
Expand Down Expand Up @@ -130,7 +146,7 @@ class FixTests extends ScalaCliSuite {
|}
|""".stripMargin)

val runProc = os.proc(TestUtil.cli, "--power", "compile", ".")
val runProc = os.proc(TestUtil.cli, "--power", "compile", ".", extraOptions)
.call(cwd = root, stderr = os.Pipe)

expect(!runProc.err.trim.contains("Using directives detected in multiple files"))
Expand Down Expand Up @@ -192,13 +208,31 @@ class FixTests extends ScalaCliSuite {
"fix",
".",
"--script-snippet",
"'//> using options -Xasync'"
)
"'//> using options -Xasync'",
"-v",
"-v"
) ++ extraOptions
val cmd =
s"""echo '//> using toolkit latest
| case class Foo(x: Int)' | ${cliCmd.mkString(" ")} _.scala
|""".stripMargin
val res = os.proc("bash", "-c", cmd).call(cwd = root)

val res = os.proc("bash", "-c", cmd).call(cwd = root, stderr = os.Pipe)

expect(res.err.trim() ==
"""Reading stdin
|Done reading stdin (49 B)
|Extracting directives from project.scala
|Extracting directives from src/Main.scala
|Extracting directives from src/UsedTarget.scala
|Extracting directives from <stdin>-scala-file
|Extracting directives from snippet
|Removing directives from project.scala
|Removing directives from src/Main.scala
|Extracting directives from test/MyTests.scala
|Removing directives from test/MyTests.scala
| Keeping:
| //> using scala 3.2.2""".stripMargin)

val projectFileContents = os.read(root / projectFileName)
val mainFileContents = os.read(root / mainSubPath)
Expand Down Expand Up @@ -245,7 +279,7 @@ class FixTests extends ScalaCliSuite {
expect(withUsedTargetContents == withUsedTargetContentsRead)
expect(withUnusedTargetContents == withUnusedTargetContentsRead)

val runProc = os.proc(TestUtil.cli, "--power", "compile", ".")
val runProc = os.proc(TestUtil.cli, "--power", "compile", ".", extraOptions)
.call(cwd = root, stderr = os.Pipe)

expect(!runProc.err.trim.contains("Using directives detected in multiple files"))
Expand Down

0 comments on commit c737202

Please sign in to comment.