Skip to content

Commit

Permalink
CliOptions: write info to console instead of err
Browse files Browse the repository at this point in the history
Currently, info is written to out if out is not used for result output,
and to err otherwise.

Let's enhance this approach as follows: if out is not used, then we'll
write into to out, as before; otherwise, before resorting to err, check
if the console is available and use it then.
  • Loading branch information
kitbellew committed Sep 16, 2024
1 parent 8d9223d commit 1b1d57d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ object CliOptions {
if (parsed.quiet) Output.NoopStream
else {
val usesOut = parsed.stdIn || parsed.writeMode.usesOut
new Output.FromStream(
val cons = if (usesOut) System.console() else null
if (cons ne null) new Output.FromWriter(cons.writer())
else new Output.FromStream(
if (parsed.noStdErr || !usesOut) parsed.common.out
else parsed.common.err,
)
Expand Down
20 changes: 20 additions & 0 deletions scalafmt-cli/src/main/scala/org/scalafmt/cli/Output.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.scalafmt.cli

import java.io._
import java.nio.charset._

object Output {

Expand Down Expand Up @@ -29,4 +30,23 @@ object Output {
override def printWriter: PrintWriter = new PrintWriter(obj)
}

class FromWriter(val obj: Writer, charset: Charset = StandardCharsets.UTF_8)
extends OutputStream with StreamOrWriter {

override def write(b: Int): Unit = obj.write(b & 0xf)
override def write(b: Array[Byte]): Unit = obj.write(new String(b, charset))
override def write(b: Array[Byte], off: Int, len: Int): Unit = obj
.write(new String(b, off, len, charset))

override def flush(): Unit = obj.flush()
override def close(): Unit = obj.close()

def outputStream: OutputStream = this
override def printStream: PrintStream = new PrintStream(this)
override def printWriter: PrintWriter = obj match {
case x: PrintWriter => x
case _ => new PrintWriter(obj)
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,12 @@ class CliOptionsTest extends FunSuite {
Seq("--stdin", "--stdout").foreach { arg =>
test(s"don't write info when using $arg") {
val options = Cli.getConfig(Array(arg), baseCliOptionsWithOut).get
options.common.info match {
val cons = System.console()
if (cons ne null) options.common.info match {
case x: Output.FromWriter if x.obj eq cons.writer() =>
case x => fail(s"info should be writing to console: $x")
}
else options.common.info match {
case x: Output.FromStream if x.obj eq Output.NoopStream.printStream =>
case x => fail(s"info should be writing to NoopStream: $x")
}
Expand Down

0 comments on commit 1b1d57d

Please sign in to comment.