Skip to content

Switch to Clikt #91

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

Merged
merged 2 commits into from
Feb 28, 2024
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
2 changes: 1 addition & 1 deletion app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ application {

dependencies {
implementation project(':sort')
implementation libs.picocli
implementation libs.clikt
implementation libs.slf4j

testImplementation libs.spock
Expand Down
62 changes: 49 additions & 13 deletions app/src/main/kotlin/com/squareup/sort/BuildDotGradleFinder.kt
Original file line number Diff line number Diff line change
@@ -1,46 +1,82 @@
package com.squareup.sort

import java.io.File
import java.nio.file.Files
import java.nio.file.FileVisitResult
import java.nio.file.Path
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.FileVisitorBuilder
import kotlin.io.path.exists
import kotlin.io.path.name
import kotlin.io.path.pathString
import kotlin.io.path.visitFileTree

@OptIn(ExperimentalPathApi::class)
class BuildDotGradleFinder(
private val root: Path,
searchPaths: List<String>,
searchPaths: List<Path>,
skipHiddenAndBuildDirs: Boolean,
) {

private val traversalFilter: (File) -> Boolean = if (skipHiddenAndBuildDirs) {
{ dir -> !dir.name.startsWith(".") && dir.name != "build" }
} else {
{ true }
/**
* Skips `build` and cache directories (starting with `.`, like `.gradle`) in [walkEachFile].
*/
private fun FileVisitorBuilder.skipBuildAndCacheDirs() {
return onPreVisitDirectory { dir, _ ->
if (dir.name.startsWith(".") || dir.name == "build") {
FileVisitResult.SKIP_SUBTREE
} else {
FileVisitResult.CONTINUE
}
}
}

private fun Path.walkEachFile(
maxDepth: Int = Int.MAX_VALUE,
followLinks: Boolean = false,
builderAction: FileVisitorBuilder.() -> Unit = {},
): Sequence<Path> {
val files = mutableListOf<Path>()
visitFileTree(maxDepth, followLinks) {
builderAction()
onVisitFile { file, _ ->
files.add(file)
FileVisitResult.CONTINUE
}
}
return files.asSequence()
}

val buildDotGradles: Set<Path> = searchPaths.asSequence()
// nb, if the path passed to the resolve method is already an absolute path, it returns that.
.map { root.resolve(it).normalize() }
.flatMap { searchPath ->
if (searchPath.isBuildDotGradle()) {
sequenceOf(searchPath).filter(Files::exists)
sequenceOf(searchPath).filter(Path::exists)
} else {
// Use File.walk() so we have access to the `onEnter` filter.
// Can switch to Path.walk() once it's stable and offers the same API.
searchPath.toFile().walk()
.onEnter(traversalFilter)
.map(File::toPath)
searchPath.walkEachFile {
if (skipHiddenAndBuildDirs) {
skipBuildAndCacheDirs()
}
}
.filter(Path::isBuildDotGradle)
.filter(Files::exists)
.filter(Path::exists)
}
}
.toSet()

interface Factory {
fun of(
root: Path,
searchPaths: List<String>,
searchPaths: List<Path>,
skipHiddenAndBuildDirs: Boolean,
): BuildDotGradleFinder = BuildDotGradleFinder(root, searchPaths, skipHiddenAndBuildDirs)

object Default : Factory {
override fun of(root: Path, searchPaths: List<Path>, skipHiddenAndBuildDirs: Boolean): BuildDotGradleFinder {
return BuildDotGradleFinder(root, searchPaths, skipHiddenAndBuildDirs)
}
}
}
}

Expand Down
121 changes: 49 additions & 72 deletions app/src/main/kotlin/com/squareup/sort/SortCommand.kt
Original file line number Diff line number Diff line change
@@ -1,93 +1,68 @@
package com.squareup.sort

import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.ProgramResult
import com.github.ajalt.clikt.core.context
import com.github.ajalt.clikt.output.MordantHelpFormatter
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.multiple
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.types.enum
import com.github.ajalt.clikt.parameters.types.path
import com.squareup.log.DelegatingLogger
import com.squareup.parse.AlreadyOrderedException
import com.squareup.parse.BuildScriptParseException
import com.squareup.sort.Status.NOT_SORTED
import com.squareup.sort.Status.NO_BUILD_SCRIPTS_FOUND
import com.squareup.sort.Status.NO_PATH_PASSED
import com.squareup.sort.Status.PARSE_ERROR
import com.squareup.sort.Status.SUCCESS
import com.squareup.sort.Status.UNKNOWN_MODE
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import picocli.CommandLine.Command
import picocli.CommandLine.HelpCommand
import picocli.CommandLine.Option
import picocli.CommandLine.Parameters
import java.nio.file.FileSystem
import java.nio.file.FileSystems
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.util.concurrent.Callable
import kotlin.io.path.createTempFile
import kotlin.io.path.pathString
import kotlin.io.path.writeText

/**
* Parent command or entry point into the dependencies-sorter. Not implementing `Callable` nor
* `Runnable` would indicate that a subcommand _must_ be specified.
*
* @see <a href="https://picocli.info/#_required_subcommands">Picocli: Required subcommands</a>
* Parent command or entry point into the dependencies-sorter.
*/
@Command(
name = "sort",
mixinStandardHelpOptions = true,
version = ["0.1"],
description = ["Sorts dependencies"],
subcommands = [
HelpCommand::class
]
)
class SortCommand(
private val fileSystem: FileSystem = FileSystems.getDefault(),
private val buildFileFinder: BuildDotGradleFinder.Factory = object : BuildDotGradleFinder.Factory {}
) : Callable<Int> {

@Option(
names = ["-v", "--verbose"],
description = [
"Verbose mode. All logs are printed."
],
defaultValue = "false"
)
var verbose: Boolean = false

@Option(
names = ["--skip-hidden-and-build-dirs"],
description = [
"Flag to control whether file tree walking looks in build and hidden directories. True by default."
],
defaultValue = "true"
)
var skipHiddenAndBuildDirs: Boolean = true

@Option(
names = ["-m", "--mode"],
description = [
"Mode: [sort, check]. Defaults to 'sort'. Check will report if a file is already sorted"
],
defaultValue = "sort"
)
lateinit var mode: String
) : CliktCommand(
name = "sort",
help = "Sorts dependencies",
) {

@Parameters(
index = "0..*",
description = ["Path(s) to sort. Required."],
)
lateinit var paths: List<String>
init {
context { helpFormatter = { context -> MordantHelpFormatter(context = context, showDefaultValues = true, showRequiredTag = true) } }
}

private val verbose by option("-v", "--verbose", help = "Verbose mode. All logs are printed.")
.flag("--quiet", default = false)

override fun call(): Int {
private val skipHiddenAndBuildDirs by option(
"--skip-hidden-and-build-dirs",
help = "Flag to control whether file tree walking looks in build and hidden directories. True by default.",
).flag("--no-skip-hidden-and-build-dirs", default = true)

val mode by option("-m", "--mode", help = "Mode: [sort, check]. Defaults to 'sort'. Check will report if a file is already sorted")
.enum<Mode>().default(Mode.SORT)

val paths: List<Path> by argument(help = "Path(s) to sort. Required.")
.path(mustExist = false, canBeDir = true, canBeFile = true)
.multiple(required = true)

override fun run() {
// Use `use()` to ensure the logger is closed + dumps any close-time diagnostics
return logger(!verbose).use(::callWithLogger)
logger(!verbose).use(::callWithLogger)
}

private fun callWithLogger(logger: DelegatingLogger): Int {
if (!this::paths.isInitialized) {
logger.error("No paths were passed. See 'help' for usage information.")
return NO_PATH_PASSED.value
}

private fun callWithLogger(logger: DelegatingLogger) {
val pwd = fileSystem.getPath(".").toAbsolutePath().normalize()
logger.info("Sorting build.gradle(.kts) scripts in the following paths: ${paths.joinToString()}")

Expand All @@ -101,20 +76,19 @@ class SortCommand(

if (filesToSort.isEmpty()) {
logger.warn("No build.gradle(.kts) scripts found.")
return SUCCESS.value
throw ProgramResult(SUCCESS.value)
} else {
logger.info(
"It took ${findFileTime - start} ms to find ${filesToSort.size} build scripts."
)
}

val status = when (mode) {
"sort" -> sort(filesToSort, findFileTime, logger)
"check" -> check(filesToSort, findFileTime, pwd, logger)
else -> UNKNOWN_MODE
Mode.SORT -> sort(filesToSort, findFileTime, logger)
Mode.CHECK -> check(filesToSort, findFileTime, pwd, logger)
}

return status.value
throw ProgramResult(status.value)
}

private fun sort(
Expand Down Expand Up @@ -232,13 +206,16 @@ class SortCommand(
}
}

enum class Mode {
SORT,
CHECK,
}

enum class Status(val value: Int) {
SUCCESS(0),
NO_PATH_PASSED(1),
NO_BUILD_SCRIPTS_FOUND(2),
NOT_SORTED(3),
UNKNOWN_MODE(4),
PARSE_ERROR(5),
NO_BUILD_SCRIPTS_FOUND(1),
NOT_SORTED(2),
PARSE_ERROR(3),
;
}

Expand Down
7 changes: 1 addition & 6 deletions app/src/main/kotlin/com/squareup/sort/main.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
package com.squareup.sort

import picocli.CommandLine
import kotlin.system.exitProcess

fun main(vararg args: String) {
val cli = CommandLine(SortCommand())
val exitCode = cli.execute(*args)
exitProcess(exitCode)
SortCommand().main(args)
}
73 changes: 66 additions & 7 deletions app/src/test/groovy/com/squareup/SortCommandSpec.groovy
Original file line number Diff line number Diff line change
@@ -1,34 +1,93 @@
package com.squareup

import com.github.ajalt.clikt.core.ProgramResult
import com.github.ajalt.clikt.core.UsageError
import com.squareup.sort.BuildDotGradleFinder
import com.squareup.sort.Mode
import com.squareup.sort.SortCommand
import picocli.CommandLine
import spock.lang.Specification
import spock.lang.TempDir

import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Path

/**
* Very basic spec as a toehold if we want to add more robust tests at the app level.
*
* @see <a href="https://picocli.info/#_testing_your_application">Testing your application.</a>
* @see <a href="https://ajalt.github.io/clikt/testing/">Clikt testing.</a>
*/
final class SortCommandSpec extends Specification {

@TempDir
Path dir

def "can parse args"() {
given:
def commandLine = new CommandLine(newSortCommand())
def buildScript = dir.resolve('build.gradle')
Files.writeString(buildScript, """\
plugins {
id 'java-library'
id 'com.squareup.sort-dependencies'
}

dependencies {
implementation('com.squareup.okhttp3:okhttp:4.10.0')
implementation('com.squareup.okio:okio:3.2.0')
}
""".stripIndent())
def sortCommand = newSortCommand()

when:
int statusCode = runSortCommand(sortCommand, '-m', 'check', dir.toString())

then:
sortCommand.mode == Mode.CHECK
sortCommand.paths == [dir]
statusCode == 0
}

def "success when no files found"() {
given:
def sortCommand = newSortCommand()

when:
def parseResult = commandLine.parseArgs('-m', 'check', '-v')
int statusCode = runSortCommand(sortCommand, '-m', 'check', dir.toString())

then:
parseResult.expandedArgs() == ['-m', 'check', '-v']
sortCommand.mode == Mode.CHECK
sortCommand.paths == [dir]
statusCode == 0
}

def "fails with no paths passed in"() {
given:
def sortCommand = newSortCommand()

when:
int statusCode = runSortCommand(sortCommand, '-m', 'check')

then:
sortCommand.mode == Mode.CHECK
statusCode == 1
}

private static int runSortCommand(SortCommand sortCommand, String[] args) {
int statusCode = 0
try {
sortCommand.parse(args, null)
} catch (ProgramResult result) {
statusCode = result.statusCode
} catch (UsageError result) {
statusCode = result.statusCode
}
return statusCode
}

private SortCommand newSortCommand() {
private static SortCommand newSortCommand() {
return new SortCommand(
FileSystems.getDefault(),
Stub(BuildDotGradleFinder.Factory)
BuildDotGradleFinder.Factory.Default.INSTANCE
)
}
}
Loading