Skip to content

Commit

Permalink
Added support for customizing the output color for pinterest#582.
Browse files Browse the repository at this point in the history
  • Loading branch information
AdamMc331 committed Sep 30, 2019
1 parent 9abdb55 commit f5a71d1
Show file tree
Hide file tree
Showing 6 changed files with 144 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ class PlainReporter(
val out: PrintStream,
val verbose: Boolean = false,
val groupByFile: Boolean = false,
val color: Boolean = false,
val shouldColorOutput: Boolean = false,
val outputColor: Color = Color.DARK_GRAY,
val pad: Boolean = false
) : Reporter {

Expand All @@ -25,9 +26,9 @@ class PlainReporter(
acc.getOrPut(file) { ArrayList<LintError>() }.add(err)
} else {
out.println(
"${colorFileName(file)}${":".gray()}${err.line}${
":${"${err.col}:".let { if (pad) String.format("%-4s", it) else it}}".gray()
} ${err.detail}${if (verbose) " (${err.ruleId})".gray() else ""}"
"${colorFileName(file)}${":".colored()}${err.line}${
":${"${err.col}:".let { if (pad) String.format("%-4s", it) else it}}".colored()
} ${err.detail}${if (verbose) " (${err.ruleId})".colored() else ""}"
)
}
}
Expand All @@ -40,18 +41,18 @@ class PlainReporter(
for ((line, col, ruleId, detail) in errList) {
out.println(
" $line${
":${if (pad) String.format("%-3s", col) else "$col"}".gray()
} $detail${if (verbose) " ($ruleId)".gray() else ""}"
":${if (pad) String.format("%-3s", col) else "$col"}".colored()
} $detail${if (verbose) " ($ruleId)".colored() else ""}"
)
}
}
}

private fun colorFileName(fileName: String): String {
val name = fileName.substringAfterLast(File.separator)
return fileName.substring(0, fileName.length - name.length).gray() + name
return fileName.substring(0, fileName.length - name.length).colored() + name
}

private fun String.gray() =
if (color) this.color(Color.DARK_GRAY) else this
private fun String.colored() =
if (shouldColorOutput) this.color(outputColor) else this
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.pinterest.ktlint.reporter.plain

import com.pinterest.ktlint.core.Reporter
import com.pinterest.ktlint.core.ReporterProvider
import com.pinterest.ktlint.reporter.plain.internal.Color
import java.io.PrintStream

class PlainReporterProvider : ReporterProvider {
Expand All @@ -13,9 +14,14 @@ class PlainReporterProvider : ReporterProvider {
out,
verbose = opt["verbose"]?.emptyOrTrue() ?: false,
groupByFile = opt["group_by_file"]?.emptyOrTrue() ?: false,
color = opt["color"]?.emptyOrTrue() ?: false,
shouldColorOutput = opt["color"]?.emptyOrTrue() ?: false,
outputColor = getColor(opt["color_name"]),
pad = opt["pad"]?.emptyOrTrue() ?: false
)

private fun String.emptyOrTrue() = this == "" || this == "true"

private fun getColor(colorInput: String?): Color {
return Color.values().firstOrNull { it.name == colorInput } ?: throw IllegalArgumentException("Invalid color parameter.")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,19 @@ fun String.color(foreground: Color) = "\u001B[${foreground.code}m$this\u001B[0m"

enum class Color(val code: Int) {
BLACK(30),
RED(31), GREEN(32), YELLOW(33), BLUE(34), MAGENTA(35), CYAN(36),
LIGHT_GRAY(37), DARK_GRAY(90),
LIGHT_RED(91), LIGHT_GREEN(92), LIGHT_YELLOW(93), LIGHT_BLUE(94), LIGHT_MAGENTA(95), LIGHT_CYAN(96),
RED(31),
GREEN(32),
YELLOW(33),
BLUE(34),
MAGENTA(35),
CYAN(36),
LIGHT_GRAY(37),
DARK_GRAY(90),
LIGHT_RED(91),
LIGHT_GREEN(92),
LIGHT_YELLOW(93),
LIGHT_BLUE(94),
LIGHT_MAGENTA(95),
LIGHT_CYAN(96),
WHITE(97)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package com.pinterest.ktlint.reporter.plain

import com.pinterest.ktlint.reporter.plain.internal.Color
import java.io.PrintStream
import java.lang.System.out
import org.junit.Assert.assertEquals
import org.junit.Assert.fail
import org.junit.Test

class PlainReporterProviderTest {
@Test
fun testNoColorNameProvided() {
try {
PlainReporterProvider().get(
out = PrintStream(out, true),
opt = mapOf()
) as PlainReporter

fail("Expected IllegalArgumentException.")
} catch (iae: IllegalArgumentException) {
// Expected case
} catch (e: Exception) {
fail("Expected IllegalArgumentException but was: $e")
}
}

@Test
fun testEmptyColorNameProvided() {
try {
PlainReporterProvider().get(
out = PrintStream(out, true),
opt = mapOf("color_name" to "")
) as PlainReporter

fail("Expected IllegalArgumentException.")
} catch (iae: IllegalArgumentException) {
// Expected case
} catch (e: Exception) {
fail("Expected IllegalArgumentException but was: $e")
}
}

@Test
fun testValidColorNameProvided() {
val plainReporter = PlainReporterProvider().get(
out = PrintStream(out, true),
opt = mapOf("color_name" to "RED")
) as PlainReporter

assertEquals(Color.RED, plainReporter.color)
}

@Test
fun testInvalidColorNameProvided() {
try {
PlainReporterProvider().get(
out = PrintStream(out, true),
opt = mapOf("colo_namer" to "GARBAGE_INPUT")
) as PlainReporter

fail("Expected IllegalArgumentException.")
} catch (iae: IllegalArgumentException) {
// Expected case
} catch (e: Exception) {
fail("Expected IllegalArgumentException but was: $e")
}
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package com.pinterest.ktlint.reporter.plain

import com.pinterest.ktlint.core.LintError
import com.pinterest.ktlint.reporter.plain.internal.Color
import com.pinterest.ktlint.reporter.plain.internal.color
import java.io.ByteArrayOutputStream
import java.io.PrintStream
import org.assertj.core.api.Assertions.assertThat
import org.junit.Assert.assertEquals
import org.junit.Test

class PlainReporterTest {
Expand Down Expand Up @@ -55,14 +58,46 @@ class PlainReporterTest {
true
)
assertThat(String(out.toByteArray())).isEqualTo(
"""
"""
/one-fixed-and-one-not.kt:1:1: <"&'>
/two-not-fixed.kt:1:10: I thought I would again
/two-not-fixed.kt:2:20: A single thin straight line
""".trimStart().replace("\n", System.lineSeparator())
)
}

@Test
fun testColoredOutput() {
val out = ByteArrayOutputStream()
val outputColor = Color.DARK_GRAY
val reporter = PlainReporter(
PrintStream(out, true),
shouldColorOutput = true,
color = outputColor
)
reporter.onLintError(
"/one-fixed-and-one-not.kt",
LintError(
1, 1, "rule-1",
"<\"&'>"
),
false
)

val outputString = String(out.toByteArray())

// We don't expect class name, or first line to be colored
val expectedOutput =
"/".color(outputColor) +
"one-fixed-and-one-not.kt" +
":".color(outputColor) +
"1" +
":1:".color(outputColor) +
" <\"&'>\n"

assertEquals(expectedOutput, outputString)
}

@Test
fun testReportGenerationGroupedByFile() {
val out = ByteArrayOutputStream()
Expand Down Expand Up @@ -113,7 +148,7 @@ class PlainReporterTest {
reporter.after("/two-not-fixed.kt")
reporter.after("/all-corrected.kt")
assertThat(String(out.toByteArray())).isEqualTo(
"""
"""
/one-fixed-and-one-not.kt
1:1 <"&'>
/two-not-fixed.kt
Expand Down
9 changes: 8 additions & 1 deletion ktlint/src/main/kotlin/com/pinterest/ktlint/Main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import com.pinterest.ktlint.internal.formatFile
import com.pinterest.ktlint.internal.lintFile
import com.pinterest.ktlint.internal.location
import com.pinterest.ktlint.internal.printHelpOrVersionUsage
import com.pinterest.ktlint.reporter.plain.internal.Color
import java.io.File
import java.io.IOException
import java.io.PrintStream
Expand Down Expand Up @@ -132,6 +133,12 @@ class KtlintCommandLine {
)
var color: Boolean = false

@Option(
names = ["--color-name"],
description = ["Customize the output color"]
)
var colorName: String = Color.DARK_GRAY.name

@Option(
names = ["--debug"],
description = ["Turn on debug output"]
Expand Down Expand Up @@ -346,7 +353,7 @@ class KtlintCommandLine {
ReporterTemplate(
reporterId,
split.lastOrNull { it.startsWith("artifact=") }?.let { it.split("=")[1] },
mapOf("verbose" to verbose.toString(), "color" to color.toString()) + parseQuery(rawReporterConfig),
mapOf("verbose" to verbose.toString(), "color" to color.toString(), "color_name" to colorName) + parseQuery(rawReporterConfig),
split.lastOrNull { it.startsWith("output=") }?.let { it.split("=")[1] }
)
}
Expand Down

0 comments on commit f5a71d1

Please sign in to comment.