-
Notifications
You must be signed in to change notification settings - Fork 507
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
Add "printAST" sub command. #500
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
55 changes: 55 additions & 0 deletions
55
ktlint/src/main/kotlin/com/pinterest/ktlint/internal/FileUtils.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package com.pinterest.ktlint.internal | ||
|
||
import com.github.shyiko.klob.Glob | ||
import com.pinterest.ktlint.core.KtLint.lint | ||
import com.pinterest.ktlint.core.KtLint.lintScript | ||
import com.pinterest.ktlint.core.LintError | ||
import com.pinterest.ktlint.core.RuleSet | ||
import java.io.File | ||
import java.nio.file.Path | ||
import java.nio.file.Paths | ||
|
||
internal val workDir: String = File(".").canonicalPath | ||
|
||
internal fun List<String>.fileSequence(): Sequence<File> { | ||
val kotlinFiles = if (isEmpty()) { | ||
Glob.from("**/*.kt", "**/*.kts") | ||
.iterate( | ||
Paths.get(workDir), | ||
Glob.IterationOption.SKIP_HIDDEN | ||
) | ||
} else { | ||
val normalizedPatterns = map(::expandTilde).toTypedArray() | ||
Glob.from(*normalizedPatterns) | ||
.iterate(Paths.get(workDir)) | ||
} | ||
|
||
return kotlinFiles | ||
.asSequence() | ||
.map(Path::toFile) | ||
} | ||
|
||
// a complete solution would be to implement https://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html | ||
// this implementation takes care only of the most commonly used case (~/) | ||
internal fun expandTilde(path: String): String = path.replaceFirst(Regex("^~"), System.getProperty("user.home")) | ||
|
||
internal fun File.location( | ||
relative: Boolean | ||
) = if (relative) this.toRelativeString(File(workDir)) else this.path | ||
|
||
/** | ||
* Run lint over common kotlin file or kotlin script file. | ||
*/ | ||
internal fun lintFile( | ||
fileName: String, | ||
fileContent: String, | ||
ruleSetList: List<RuleSet>, | ||
userData: Map<String, String> = emptyMap(), | ||
lintErrorCallback: (LintError) -> Unit = {} | ||
) { | ||
if (fileName.endsWith(".kt", ignoreCase = true)) { | ||
lint(fileContent, ruleSetList, userData, lintErrorCallback) | ||
} else { | ||
lintScript(fileContent, ruleSetList, userData, lintErrorCallback) | ||
} | ||
} |
82 changes: 82 additions & 0 deletions
82
ktlint/src/main/kotlin/com/pinterest/ktlint/internal/PrintASTSubCommand.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
package com.pinterest.ktlint.internal | ||
|
||
import com.pinterest.ktlint.KtlintCommandLine | ||
import com.pinterest.ktlint.core.ParseException | ||
import com.pinterest.ktlint.core.RuleSet | ||
import com.pinterest.ktlint.test.DumpAST | ||
import java.io.File | ||
import picocli.CommandLine | ||
|
||
@CommandLine.Command( | ||
description = [ | ||
"Print AST (useful when writing/debugging rules)", | ||
"Usage of \"--print-ast\" command line option is deprecated!" | ||
], | ||
aliases = ["--print-ast"], | ||
mixinStandardHelpOptions = true, | ||
versionProvider = KtlintVersionProvider::class | ||
) | ||
internal class PrintASTSubCommand : Runnable { | ||
@CommandLine.ParentCommand | ||
private lateinit var ktlintCommand: KtlintCommandLine | ||
|
||
@CommandLine.Spec | ||
private lateinit var commandSpec: CommandLine.Model.CommandSpec | ||
|
||
@CommandLine.Parameters( | ||
description = ["include all files under this .gitignore-like patterns"] | ||
) | ||
private var patterns = ArrayList<String>() | ||
|
||
@CommandLine.Option( | ||
names = ["--stdin"], | ||
description = ["Read file content from stdin"] | ||
) | ||
private var stdin: Boolean = false | ||
|
||
private val astRuleSet by lazy(LazyThreadSafetyMode.NONE) { | ||
listOf( | ||
RuleSet("debug", DumpAST(System.out, ktlintCommand.color)) | ||
) | ||
} | ||
|
||
override fun run() { | ||
commandSpec.commandLine().printHelpOrVersionUsage() | ||
|
||
if (stdin) { | ||
printAST(STDIN_FILE, String(System.`in`.readBytes())) | ||
} else { | ||
for (file in patterns.fileSequence()) { | ||
printAST(file.path, file.readText()) | ||
} | ||
} | ||
} | ||
|
||
private fun printAST( | ||
fileName: String, | ||
fileContent: String | ||
) { | ||
if (ktlintCommand.debug) { | ||
val fileLocation = if (fileName != STDIN_FILE) { | ||
File(fileName).location(ktlintCommand.relative) | ||
} else { | ||
"stdin" | ||
} | ||
println("[DEBUG] Analyzing $fileLocation") | ||
} | ||
|
||
try { | ||
lintFile(fileName, fileContent, astRuleSet) | ||
} catch (e: Exception) { | ||
if (e is ParseException) { | ||
throw ParseException(e.line, e.col, "Not a valid Kotlin file (${e.message?.toLowerCase()})") | ||
} | ||
throw e | ||
} | ||
} | ||
|
||
companion object { | ||
internal const val COMMAND_NAME = "printAST" | ||
private const val STDIN_FILE = "<stdin>" | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
May I ask what's the reasoning behind using a camel-cased command name instead of good old '--do-something' pattern for CLI tools? The old way just looks more natural imo.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Main reason to move into subcommands direction - reduce user confusion and make command line usage more clear.
For example, now with only options, it is not clear if using
--print-ast
option will also do linting.Though I am open to subcommand name changes as I don't have strong opinion here.