Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for customizing the output color for #582. #585

Merged
merged 2 commits into from
Oct 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for adding tests 👍

@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")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: you don't need to add Exception catch block. If code will throw uncaught exception - test will fail.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ooo whoops. Want me to fix?

}
}

@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.outputColor)
}

@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,
outputColor = 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
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be nice to use here enum type, but it will require a lot of changes :(

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree and thought the same but I wasn't sure if I could reference an enum as a command line argument? I assumed it had to be a string. If you know something I don't - let me know and I can try to adjust.


@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