4
0
Fork 0
mirror of https://github.com/Anvilcraft/modpacktools synced 2024-05-29 16:54:38 +02:00

reformat with ktlint

This commit is contained in:
LordMZTE 2020-08-12 12:42:56 +02:00
parent 820c792a7b
commit be22304295
24 changed files with 199 additions and 147 deletions

View file

@ -120,9 +120,11 @@ publishing {
ktlint {
disabledRules.set(
setOf(
//Disable really stupid rules
"comment-spacing",
"curly-spacing",
"keyword-spacing"
"keyword-spacing",
"no-wildcard-imports"
)
)
}

View file

@ -15,7 +15,7 @@ import net.sourceforge.argparse4j.inf.ArgumentParserException
import okhttp3.Dispatcher
import okhttp3.OkHttpClient
import java.io.File
import java.util.*
import java.util.NoSuchElementException
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit.MICROSECONDS
@ -55,7 +55,6 @@ private val helpMessage by lazy {
sb.toString()
}
fun main(args: Array<out String>) {
runCommand(args)

View file

@ -37,7 +37,7 @@ class CommandLoader(private val pkg: String) {
if(this.needsModpackjson && MPJH.asWrapper == null)
throw ModpackJsonMissingException()
return this.execute(this.parser.parseArgs(args.slice(1 until args.size).toTypedArray()))
return this.execute(this.parser.parseArgs(args.slice(1 until args.size).toTypedArray()))
}
}
@ -54,7 +54,7 @@ class CommandLoader(private val pkg: String) {
.map {it.kotlin}
//Only annotated classes
//Cannot use it.hasAnnotation because it is experimental and requires everything to be annotated so this makes more sense
.filter {it.annotations.any {ann -> ann.annotationClass == LoadCommand::class}}
.filter {it.annotations.any {ann -> ann.annotationClass == LoadCommand::class}}
//can be object
.map {it.objectInstance ?: it}
//create new instance if it is a class, otherwise just add the current instance

View file

@ -23,4 +23,4 @@ data class CommandReturn private constructor(val ret: String?, val success: Bool
fun success(ret: String? = null) = CommandReturn(ret, true)
}
fun hasRet() = ret != null
}
}

View file

@ -42,4 +42,4 @@ interface ICommand {
@JvmDefault
val needsModpackjson: Boolean
get() = true
}
}

View file

@ -6,4 +6,4 @@ package ley.anvil.modpacktools.command
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
annotation class LoadCommand {}
annotation class LoadCommand

View file

@ -75,10 +75,14 @@ object BuildTwitch : ICommand {
}
}
downloadFiles(toDownload.mapValues {it.value.first}, {
fPrintln("downloaded file ${it.file}", TERMC.brightBlue)
fPrintln(installFile(toDownload[it.url]!!.second, it.file), TERMC.green)
}, false)
downloadFiles(
toDownload.mapValues {it.value.first},
{
fPrintln("downloaded file ${it.file}", TERMC.brightBlue)
fPrintln(installFile(toDownload[it.url]!!.second, it.file), TERMC.green)
},
false
)
fPrintln("Creating zip", TERMC.brightGreen)
val zip = ZipOutputStream(FileOutputStream("${dir.path}/$archiveName.zip"))
@ -120,9 +124,9 @@ object BuildTwitch : ICommand {
}
else -> {
return "The installer '${installer}' is not supported for Twitch export"
return "The installer '$installer' is not supported for Twitch export"
}
}
return "installed $file"
}
}
}

View file

@ -1,6 +1,19 @@
package ley.anvil.modpacktools.commands
import j2html.TagCreator.*
import j2html.TagCreator.a
import j2html.TagCreator.b
import j2html.TagCreator.body
import j2html.TagCreator.each
import j2html.TagCreator.head
import j2html.TagCreator.html
import j2html.TagCreator.img
import j2html.TagCreator.li
import j2html.TagCreator.p
import j2html.TagCreator.style
import j2html.TagCreator.table
import j2html.TagCreator.td
import j2html.TagCreator.tr
import j2html.TagCreator.ul
import j2html.utils.CSSMin.compressCss
import ley.anvil.addonscript.wrapper.MetaData
import ley.anvil.modpacktools.MPJH
@ -108,35 +121,43 @@ object CreateModlist : ICommand {
each(getMods(all, sorting)) {
fPrintln("Writing relation ${it.name}", TERMC.blue)
tr(
td(if(it.icon != null) a(
img().withSrc(it.icon)
.withClass("img")
).withHref(it.website) else null
td(
if(it.icon != null) a(
img().withSrc(it.icon)
.withClass("img")
).withHref(it.website) else null
),
td(run {
val a = a(it.name)
//Open in new tab
.withRel("noopener noreferrer")
.withTarget("_blank")
if(it.website != null)
a.withHref(it.website)
a
}),
td(ul(
each(it.contributors) {contr ->
li(contr.key)
//for contributor colors
.withClass("contributor_${contr.value.getOrElse(0) {""}}")
td(
run {
val a = a(it.name)
//Open in new tab
.withRel("noopener noreferrer")
.withTarget("_blank")
if(it.website != null)
a.withHref(it.website)
a
}
)),
td(each(it.description?.asList() ?: listOf()) {d: String ->
p(d)
})
),
td(
ul(
each(it.contributors) {contr ->
li(contr.key)
//for contributor colors
.withClass("contributor_${contr.value.getOrElse(0) {""}}")
}
)
),
td(
each(it.description?.asList() ?: listOf()) {d: String ->
p(d)
}
)
.withClass("description")
)
}
)
)).render()
)
).render()
writer.write(html)
writer.close()
@ -152,4 +173,4 @@ object CreateModlist : ICommand {
enum class Sorting {
NAME, DESCRIPTION, AUTHOR
}
}
}

View file

@ -56,18 +56,20 @@ object DownloadMods : ICommand {
installer == "internal.dir" && (args.getBoolean("all") || dir == "mods")
}
.collect(toMap<FileOrLink, URL, File>(
{URL(it.link)},
{
val dir = it.installer.split(':').last()
.collect(
toMap<FileOrLink, URL, File>(
{URL(it.link)},
{
val dir = it.installer.split(':').last()
if(args.getBoolean("all"))
File(args.get<File>("dir"), dir)
else
args.get<File>("dir")
},
{_: File, f: File -> f}
)),
if(args.getBoolean("all"))
File(args.get<File>("dir"), dir)
else
args.get<File>("dir")
},
{_: File, f: File -> f}
)
),
{r: DownloadFileTask.Return ->
//synced so error message gets printed under response
synchronized(this) {

View file

@ -46,4 +46,4 @@ object Import : ICommand {
mpjWriter.close()
return success("Converted sucessfully")
}
}
}

View file

@ -61,4 +61,4 @@ object Init : ICommand {
}
return success("MPT dev environment created. Use the created modpack.json or use the import command to import a curse manifest (recommended)")
}
}
}

View file

@ -37,50 +37,58 @@ object ListRelations : ICommand {
if(args.getBoolean("csv")) {
metas.forEach {
println("${it.name};${it.contributors.keys.joinToString()};${it.website}".let {s ->
if(args.getBoolean("description"))
s + ";${it.description?.joinToString() ?: ""}"
else s
})
println(
"${it.name};${it.contributors.keys.joinToString()};${it.website}".let {s ->
if(args.getBoolean("description"))
s + ";${it.description?.joinToString() ?: ""}"
else s
}
)
}
} else {
val data = mutableListOf<Array<out String>>()
metas.forEach {
data.add(run {
val row = mutableListOf(
it.name ?: "",
it.contributors.keys.joinToString().let {s ->
//Limit size
if(args.getBoolean("nolimit") || s.length < 50)
s
else
s.substring(0..47) + "..."
},
it.website ?: ""
)
data.add(
run {
val row = mutableListOf(
it.name ?: "",
it.contributors.keys.joinToString().let {s ->
//Limit size
if(args.getBoolean("nolimit") || s.length < 50)
s
else
s.substring(0..47) + "..."
},
it.website ?: ""
)
if(args.getBoolean("description"))
row.add(it.description?.joinToString(" ") ?: "")
if(args.getBoolean("description"))
row.add(it.description?.joinToString(" ") ?: "")
row.toTypedArray()
})
row.toTypedArray()
}
)
}
println(FlipTable.of(run {
val header = mutableListOf(
"Name",
"Contributors",
"Website"
println(
FlipTable.of(
run {
val header = mutableListOf(
"Name",
"Contributors",
"Website"
)
if(args.getBoolean("description"))
header.add("Description")
header.toTypedArray()
},
data.toTypedArray()
)
if(args.getBoolean("description"))
header.add("Description")
header.toTypedArray()
},
data.toTypedArray()))
)
}
return success()
}
}
}

View file

@ -34,4 +34,4 @@ object Shell : ICommand {
}
return success()
}
}
}

View file

@ -38,4 +38,4 @@ fun PrintStream.fPrintln(x: Any?, vararg formatters: (String) -> String) = this.
* @param x the object to print
* @param formatters the formatters to apply to x, they will be ran in the order they are supplied in
*/
fun fPrintln(x: Any?, vararg formatters: (String) -> String) = System.out.fPrintln(x, *formatters)
fun fPrintln(x: Any?, vararg formatters: (String) -> String) = System.out.fPrintln(x, *formatters)

View file

@ -13,7 +13,6 @@ import java.nio.file.Paths
import java.util.concurrent.CountDownLatch
import java.util.stream.Collectors
private var latch: CountDownLatch? = null
/**
@ -56,44 +55,48 @@ open class DownloadFileTask(
.build()
override fun onFailure(call: Call, e: IOException) {
callback(Return(
url,
file,
null,
null,
e
))
callback(
Return(
url,
file,
null,
null,
e
)
)
latch.countDown()
}
override fun onResponse(call: Call, response: Response) {
callback(try {
val outFile =
if(resolveFileName)
file mergeTo Paths.get(response.request.url.toUri().path).fileName.toFile()
else
file
callback(
try {
val outFile =
if(resolveFileName)
file mergeTo Paths.get(response.request.url.toUri().path).fileName.toFile()
else
file
val stream = response.body?.byteStream()
FileUtils.copyInputStreamToFile(stream, outFile)
stream!!.close()
val stream = response.body?.byteStream()
FileUtils.copyInputStreamToFile(stream, outFile)
stream!!.close()
Return(
url,
outFile,
response.code,
response.message,
null
)
} catch(e: NullPointerException) {
Return(
url,
file,
response.code,
response.message,
e
)
})
Return(
url,
outFile,
response.code,
response.message,
null
)
} catch(e: NullPointerException) {
Return(
url,
file,
response.code,
response.message,
e
)
}
)
latch.countDown()
}

View file

@ -12,7 +12,7 @@ class ModpackJsonHandler(val modpackJsonFile: File) {
//Null if no file exists
val asWrapper: ASWrapper?
get() {
return if(modpackJsonFile.exists()) {
return if (modpackJsonFile.exists()) {
val reader = FileReader(modpackJsonFile)
val ret = ASWrapper(AddonscriptJSON.read(reader, AddonscriptJSON::class.java))
reader.close()
@ -25,10 +25,15 @@ class ModpackJsonHandler(val modpackJsonFile: File) {
val mods = mutableListOf<MetaData>()
val toGet = mutableListOf<ArtifactDestination>()
for(rel in asJson!!.defaultVersion.getRelations(arrayOf("included"), /*TODO TILERA MAKE THIS NONSESE TAKE A PREDICATE AND NOT A LIST*/types)) {
if(rel.hasLocalMeta())
for (
rel in asJson!!.defaultVersion.getRelations(
arrayOf("included"), /*TODO TILERA MAKE THIS NONSESE TAKE A PREDICATE AND NOT A LIST*/
types
)
) {
if (rel.hasLocalMeta())
mods.add(rel.localMeta)
else if(rel.hasFile() && rel.file.isArtifact)
else if (rel.hasFile() && rel.file.isArtifact)
toGet.add(rel.file.artifact)
}
mods.addAll(ASWrapper.getMetaData(toGet.toTypedArray()).values)

View file

@ -93,13 +93,15 @@ fun URL.httpPostStr(payload: String, contentType: String, additionalHeaders: Map
fun URL.sanitize(): URL? =
try {
URI(this.protocol,
URI(
this.protocol,
this.userInfo,
this.host,
this.port,
this.path,
this.query,
this.ref).toURL()
this.ref
).toURL()
} catch(e: Exception) {
null
}
@ -130,14 +132,17 @@ infix fun File.mergeTo(other: File): File = File(this.path, other.name)
fun Path.toZip(zStream: ZipOutputStream) {
require(this.toFile().exists()) {"File must exist"}
Files.walkFileTree(this, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes?): FileVisitResult {
zStream.putNextEntry(ZipEntry(this@toZip.relativize(file).toString()))
Files.copy(file, zStream)
zStream.closeEntry()
return FileVisitResult.CONTINUE
Files.walkFileTree(
this,
object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes?): FileVisitResult {
zStream.putNextEntry(ZipEntry(this@toZip.relativize(file).toString()))
Files.copy(file, zStream)
zStream.closeEntry()
return FileVisitResult.CONTINUE
}
}
})
)
}
/**
@ -164,4 +169,4 @@ fun File.unzip(outputDir: File) {
FileUtils.copyToFile(stream, outfile)
}
stream.close()
}
}

View file

@ -36,4 +36,4 @@ class Config(val configName: String) {
FileUtils.copyInputStreamToFile(conf, configLocation)
conf!!.close()
}
}
}

View file

@ -55,4 +55,4 @@ class ConfigToml : Toml() {
* @param message an optional message to provide the exception
*/
fun <T> pathOrException(vararg path: String, message: String? = null): T = getPath(*path) ?: throw MissingConfigValueException(path.joinToString("/"), message)
}
}

View file

@ -9,4 +9,4 @@ package ley.anvil.modpacktools.util.config
data class MissingConfigValueException(val missingValue: String, override val message: String? = null) : IllegalStateException(message) {
//overridden to get better looking stack trace
override fun toString(): String = "MissingConfigValueException: Value $missingValue not found: ${message ?: ""}"
}
}

View file

@ -27,7 +27,6 @@ fun convertAStoManifest(addonscript: ASWrapper, shouldAddLink: (ASWrapper.Relati
manifest.version = ver.versionName
manifest.author = addonscript.json!!.meta!!.contributors[0].name
for(rel in ver.getRelations(arrayOf("client"), null)) {
if(rel.isModloader) {
if(rel.relation.id == "forge") {
@ -77,4 +76,4 @@ fun convertAStoManifest(addonscript: ASWrapper, shouldAddLink: (ASWrapper.Relati
ml.manifest = manifest
return ml
}
}

View file

@ -3,7 +3,7 @@ package ley.anvil.modpacktools.util.manifest
import ley.anvil.addonscript.curse.ManifestJSON
import ley.anvil.addonscript.wrapper.FileOrLink
data class ManifestLinksPair (
data class ManifestLinksPair(
var manifest: ManifestJSON? = null,
var links: MutableMap<FileOrLink, String> = mutableMapOf()
)
)

View file

@ -18,12 +18,14 @@ class UtilTest {
val tmpDir = TemporaryFolder().apply {create()}
val testFile = tmpDir.newFile()
testFile.writeText("""
testFile.writeText(
"""
{
"someKey": "someValue"
}
""".trimIndent())
""".trimIndent()
)
assertEquals("someValue", testFile.readAsJson()["someKey"].asString)
}
}
}

View file

@ -5,10 +5,12 @@ import org.junit.Assert.assertNull
import org.junit.Test
class ConfigTomlTest {
val toml = ConfigToml().read("""
val toml = ConfigToml().read(
"""
[SomeCategory]
someValue = 123
""".trimIndent()) as ConfigToml
""".trimIndent()
) as ConfigToml
@Test
fun testGetPath() {