Skip to content

Commit

Permalink
fix: suggest fix action based on invocation context.
Browse files Browse the repository at this point in the history
Gradle or CLI.

Resolves issue 89
  • Loading branch information
autonomousapps committed Oct 10, 2024
1 parent 730e3df commit ac030c0
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 30 deletions.
64 changes: 40 additions & 24 deletions app/src/main/kotlin/com/squareup/sort/SortCommand.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import com.squareup.parse.BuildScriptParseException
import com.squareup.sort.Status.NOT_SORTED
import com.squareup.sort.Status.PARSE_ERROR
import com.squareup.sort.Status.SUCCESS
import com.squareup.sort.groovy.GroovySorter
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.nio.file.FileSystem
Expand All @@ -28,9 +27,7 @@ import kotlin.io.path.createTempFile
import kotlin.io.path.pathString
import kotlin.io.path.writeText

/**
* Parent command or entry point into the dependencies-sorter.
*/
/** Parent command or entry point into the dependencies-sorter. */
class SortCommand(
private val fileSystem: FileSystem = FileSystems.getDefault(),
private val buildFileFinder: BuildDotGradleFinder.Factory = object : BuildDotGradleFinder.Factory {}
Expand All @@ -51,24 +48,29 @@ class SortCommand(
}
}

private val verbose by option("-v", "--verbose", help = "Verbose mode. All logs are printed.")
.flag("--quiet", default = false)
val paths: List<Path> by argument(help = "Path(s) to sort. Required.")
.path(mustExist = false, canBeDir = true, canBeFile = true)
.multiple(required = true)

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

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)
"-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)
val context by option(
"--context",
help = "Context: [cli, gradle]. Defaults to 'cli'. Used for more helpful error messages.",
).enum<Context>().default(Context.CLI)

override fun run() {
// Use `use()` to ensure the logger is closed + dumps any close-time diagnostics
Expand Down Expand Up @@ -191,16 +193,23 @@ class SortCommand(
if (!success) {
appendLine()
appendLine("Fix by running")
appendLine(
notSorted.joinToString(
prefix = "./scripts/sort ",
separator = " ",
transform = {
// Log relative path of the unsorted file.
pwd.relativize(it.normalize()).pathString
},
)
)

when (context) {
Context.GRADLE -> appendLine("./gradlew sortDependencies")

Context.CLI -> {
appendLine(
notSorted.joinToString(
prefix = "./scripts/sort ",
separator = " ",
transform = {
// Log relative path of the unsorted file.
pwd.relativize(it.normalize()).pathString
},
)
)
}
}
}

appendLine()
Expand All @@ -219,9 +228,16 @@ class SortCommand(
}
}

enum class Context {
CLI,
GRADLE,
;
}

enum class Mode {
SORT,
CHECK,
;
}

enum class Status(val value: Int) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@ class SortDependenciesPlugin : Plugin<Project> {
const val VERSION_FILENAME = "com-squareup-sort-version.txt"
}

private lateinit var extension: SortDependenciesExtension

override fun apply(target: Project): Unit = target.run {
val extension = SortDependenciesExtension.create(this)
extension = SortDependenciesExtension.create(this)

// nb: Can't use a detached configuration because that needs a Dependency, not a dependency notation. The latter can
// be lazily evaluated (as below) while the former needs to (e.g.) know its version eagerly: it is more constrained.
val sortApp = configurations.maybeCreate("sortDependencies").apply {
Expand Down Expand Up @@ -49,6 +52,7 @@ class SortDependenciesPlugin : Plugin<Project> {
) {
buildScript.set(project.buildFile)
sortProgram.setFrom(sortApp)
version.set(extension.version)
this.mode.set(mode)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ abstract class SortDependenciesTask @Inject constructor(
@get:InputFiles
abstract val sortProgram: ConfigurableFileCollection

/** The app version limits what options we can pass it. */
@get:Input
abstract val version: Property<String>

@get:Input
abstract val mode: Property<String>

Expand All @@ -45,8 +49,7 @@ abstract class SortDependenciesTask @Inject constructor(
@get:Input
abstract val verbose: Property<Boolean>

@TaskAction
fun action() {
@TaskAction fun action() {
val buildScript = buildScript.get().asFile.absolutePath
val mode = mode.getOrElse("sort")
val verbose = verbose.getOrElse(false)
Expand All @@ -57,19 +60,35 @@ abstract class SortDependenciesTask @Inject constructor(

logger.info("Sorting '$buildScript' using mode '$mode'.")

val version = version.get().removeSuffix("-SNAPSHOT").toDouble()

execOps.javaexec { javaExecSpec ->
with(javaExecSpec) {
mainClass.set("com.squareup.sort.MainKt")
classpath = sortProgram
args = buildList {
add(buildScript)
add("--mode")
add(mode)
option("--mode", mode)

// Not really intended to be user-specified
if (version > 0.8) {
option("--context", "gradle")
}

if (verbose) {
add("--verbose")
if (version < 0.3) {
logger.warn("--verbose specified by version < 0.3. Ignoring flag.")
} else {
add("--verbose")
}
}
}
}
}
}

private fun MutableList<String>.option(name: String, value: String) {
add(name)
add(value)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,11 @@ final class FunctionalSpec extends Specification {

then: 'Dependencies are not sorted'
result.output.contains('1 scripts are not ordered correctly.')
result.output.contains(
'''\
Fix by running
./gradlew sortDependencies'''.stripIndent()
)
}

def "checks sort order when executing 'check' task"() {
Expand Down

0 comments on commit ac030c0

Please sign in to comment.