1
0
Fork 0
mirror of https://github.com/ethauvin/kobalt.git synced 2025-04-25 16:07:12 -07:00

Update to 1.0.0-beta.

This commit is contained in:
Cedric Beust 2015-10-22 18:18:31 -07:00
parent db40768ea0
commit 5d1d63e9b6
43 changed files with 129 additions and 128 deletions

View file

@ -1,5 +1,5 @@
buildscript { buildscript {
ext.kotlin_version = '0.14.449' ext.kotlin_version = '1.0.0-beta-1038'
repositories { repositories {
mavenCentral() mavenCentral()
@ -41,7 +41,6 @@ dependencies {
// "org.jetbrains.kotlin:kotlin-compiler:${kotlin_version}", // "org.jetbrains.kotlin:kotlin-compiler:${kotlin_version}",
'com.beust:jcommander:1.48', 'com.beust:jcommander:1.48',
'com.beust:klaxon:0.16',
'com.squareup.okhttp:okhttp:2.4.0', 'com.squareup.okhttp:okhttp:2.4.0',
'org.jsoup:jsoup:1.8.2', 'org.jsoup:jsoup:1.8.2',
'com.google.inject:guice:4.0', 'com.google.inject:guice:4.0',

View file

@ -16,18 +16,14 @@
</content> </content>
<orderEntry type="inheritedJdk" /> <orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Gradle: org.jetbrains.kotlin:kotlin-stdlib:0.14.449" level="project" />
<orderEntry type="library" name="Gradle: org.jetbrains.kotlin:kotlin-compiler-embeddable:0.14.449" level="project" />
<orderEntry type="library" name="Gradle: com.beust:jcommander:1.48" level="project" /> <orderEntry type="library" name="Gradle: com.beust:jcommander:1.48" level="project" />
<orderEntry type="library" name="Gradle: com.google.guava:guava:18.0" level="project" /> <orderEntry type="library" name="Gradle: com.google.guava:guava:18.0" level="project" />
<orderEntry type="library" name="Gradle: com.beust:klaxon:0.16" level="project" />
<orderEntry type="library" name="Gradle: com.squareup.okhttp:okhttp:2.4.0" level="project" /> <orderEntry type="library" name="Gradle: com.squareup.okhttp:okhttp:2.4.0" level="project" />
<orderEntry type="library" name="Gradle: org.jsoup:jsoup:1.8.2" level="project" /> <orderEntry type="library" name="Gradle: org.jsoup:jsoup:1.8.2" level="project" />
<orderEntry type="library" name="Gradle: com.google.inject:guice:4.0" level="project" /> <orderEntry type="library" name="Gradle: com.google.inject:guice:4.0" level="project" />
<orderEntry type="library" name="Gradle: com.google.inject.extensions:guice-assistedinject:4.0" level="project" /> <orderEntry type="library" name="Gradle: com.google.inject.extensions:guice-assistedinject:4.0" level="project" />
<orderEntry type="library" name="Gradle: org.apache.maven:maven-model:3.3.3" level="project" /> <orderEntry type="library" name="Gradle: org.apache.maven:maven-model:3.3.3" level="project" />
<orderEntry type="library" name="Gradle: com.github.spullara.mustache.java:compiler:0.8.18" level="project" /> <orderEntry type="library" name="Gradle: com.github.spullara.mustache.java:compiler:0.8.18" level="project" />
<orderEntry type="library" name="Gradle: org.jetbrains.kotlin:kotlin-runtime:0.14.449" level="project" />
<orderEntry type="library" name="Gradle: com.squareup.okio:okio:1.4.0" level="project" /> <orderEntry type="library" name="Gradle: com.squareup.okio:okio:1.4.0" level="project" />
<orderEntry type="library" name="Gradle: javax.inject:javax.inject:1" level="project" /> <orderEntry type="library" name="Gradle: javax.inject:javax.inject:1" level="project" />
<orderEntry type="library" name="Gradle: aopalliance:aopalliance:1.0" level="project" /> <orderEntry type="library" name="Gradle: aopalliance:aopalliance:1.0" level="project" />
@ -42,5 +38,8 @@
<orderEntry type="library" scope="TEST" name="Gradle: org.hamcrest:hamcrest-core:1.1" level="project" /> <orderEntry type="library" scope="TEST" name="Gradle: org.hamcrest:hamcrest-core:1.1" level="project" />
<orderEntry type="library" name="Gradle: io.reactivex:rxjava:1.0.14" level="project" /> <orderEntry type="library" name="Gradle: io.reactivex:rxjava:1.0.14" level="project" />
<orderEntry type="library" name="Gradle: com.google.code.gson:gson:2.4" level="project" /> <orderEntry type="library" name="Gradle: com.google.code.gson:gson:2.4" level="project" />
<orderEntry type="library" name="Gradle: org.jetbrains.kotlin:kotlin-stdlib:1.0.0-beta-1038" level="project" />
<orderEntry type="library" name="Gradle: org.jetbrains.kotlin:kotlin-compiler-embeddable:1.0.0-beta-1038" level="project" />
<orderEntry type="library" name="Gradle: org.jetbrains.kotlin:kotlin-runtime:1.0.0-beta-1038" level="project" />
</component> </component>
</module> </module>

View file

@ -53,12 +53,11 @@ val kobalt = kotlinProject(wrapper) {
} }
dependencies { dependencies {
compile("org.jetbrains.kotlin:kotlin-stdlib:0.14.449", compile("org.jetbrains.kotlin:kotlin-stdlib:1.0.0-beta-1038",
"org.jetbrains.kotlin:kotlin-compiler-embeddable:0.14.449", "org.jetbrains.kotlin:kotlin-compiler-embeddable:1.0.0-beta-1038",
// file(homeDir("java/jcommander/target/jcommander-1.47.jar")), // file(homeDir("java/jcommander/target/jcommander-1.47.jar")),
"com.beust:jcommander:1.48", "com.beust:jcommander:1.48",
"com.beust:klaxon:0.16",
"com.squareup.okhttp:okhttp:2.5.0", "com.squareup.okhttp:okhttp:2.5.0",
"org.jsoup:jsoup:1.8.3", "org.jsoup:jsoup:1.8.3",
"com.google.inject:guice:4.0", "com.google.inject:guice:4.0",
@ -80,7 +79,7 @@ val assembleKobalt = assemble(kobalt) {
mavenJars { mavenJars {
fatJar = true fatJar = true
manifest { manifest {
attributes("Main-Class", "com.beust.kobalt.KobaltPackage") attributes("Main-Class", "com.beust.kobalt.MainKt")
} }
} }
zip { zip {
@ -92,9 +91,9 @@ val assembleKobalt = assemble(kobalt) {
} }
} }
val cs = kotlinCompiler { //val cs = kotlinCompiler {
args("-nowarn") // args("-nowarn")
} //}
val jc = jcenter(kobalt) { val jc = jcenter(kobalt) {

View file

@ -1 +1 @@
kobalt.version=0.195 kobalt.version=0.198

View file

@ -20,7 +20,7 @@ class AsciiArt {
" |_|\\_\\ \\___/ |_.__/ \\__,_| |_| \\__| " " |_|\\_\\ \\___/ |_.__/ \\__,_| |_| \\__| "
) )
val banner : String get() = BANNERS.get(Random().nextInt(BANNERS.size())) val banner : String get() = BANNERS.get(Random().nextInt(BANNERS.size))
fun box(s: String) : List<String> { fun box(s: String) : List<String> {
val ul = "\u2554" val ul = "\u2554"
@ -38,9 +38,9 @@ class AsciiArt {
} }
return arrayListOf( return arrayListOf(
ul + r(s.length() + 2, h) + ur, ul + r(s.length + 2, h) + ur,
"$v $s $v", "$v $s $v",
bl + r(s.length() + 2, h) + br) bl + r(s.length + 2, h) + br)
} }
fun logBox(s: String) { fun logBox(s: String) {

View file

@ -11,7 +11,7 @@ import java.io.File
@Directive @Directive
fun homeDir(vararg dirs: String) : String = SystemProperties.homeDir + fun homeDir(vararg dirs: String) : String = SystemProperties.homeDir +
File.separator + dirs.toArrayList().join(File.separator) File.separator + dirs.toArrayList().joinToString(File.separator)
@Directive @Directive
fun file(file: String) : String = IClasspathDependency.PREFIX_FILE + file fun file(file: String) : String = IClasspathDependency.PREFIX_FILE + file

View file

@ -139,7 +139,7 @@ private class Main @Inject constructor(
// //
val sb = StringBuffer("List of tasks\n") val sb = StringBuffer("List of tasks\n")
Plugins.plugins.forEach { plugin -> Plugins.plugins.forEach { plugin ->
if (plugin.tasks.size() > 0) { if (plugin.tasks.size > 0) {
sb.append("\n ===== ${plugin.name} =====\n") sb.append("\n ===== ${plugin.name} =====\n")
plugin.tasks.forEach { task -> plugin.tasks.forEach { task ->
sb.append(" ${task.name}\t\t${task.doc}\n") sb.append(" ${task.name}\t\t${task.doc}\n")

View file

@ -73,7 +73,7 @@ public class Plugins @Inject constructor (val taskManagerProvider : Provider<Tas
} }
public val plugins : List<Plugin> public val plugins : List<Plugin>
get() = ArrayList(pluginMap.values()) get() = ArrayList(pluginMap.values)
/** /**
* The list of plugins found in the build file. * The list of plugins found in the build file.
@ -157,7 +157,7 @@ public class Plugins @Inject constructor (val taskManagerProvider : Provider<Tas
if (method.returnType != TaskResult::class.java) { if (method.returnType != TaskResult::class.java) {
throw IllegalArgumentException("${t}should return a TaskResult") throw IllegalArgumentException("${t}should return a TaskResult")
} }
if (method.parameterTypes.size() != 1) { if (method.parameterTypes.size != 1) {
throw IllegalArgumentException("${t}should take exactly one parameter of type a Project") throw IllegalArgumentException("${t}should take exactly one parameter of type a Project")
} }
with(method.parameterTypes) { with(method.parameterTypes) {

View file

@ -24,7 +24,8 @@ public class ProjectGenerator {
* Turns a dot property into a proper Kotlin identifier, e.g. common.version -> commonVersion * Turns a dot property into a proper Kotlin identifier, e.g. common.version -> commonVersion
*/ */
fun translate(key: String): String { fun translate(key: String): String {
return key.split('.').mapIndexed( { index, value -> if (index == 0) value else value.upperFirst() }).join("") return key.split('.').mapIndexed( { index, value -> if (index == 0) value else value.upperFirst() })
.joinToString("")
} }
} }
@ -35,12 +36,12 @@ public class ProjectGenerator {
} }
val compilerInfos = detect(File(".")) val compilerInfos = detect(File("."))
if (compilerInfos.size() > 1) { if (compilerInfos.size > 1) {
log(1, "Multi language project detected, not supported yet") log(1, "Multi language project detected, not supported yet")
} }
val map = hashMapOf<String, Any?>() val map = hashMapOf<String, Any?>()
map.put("directive", if (compilerInfos.isEmpty()) "project" else compilerInfos.get(0).directive) map.put("directive", if (compilerInfos.isEmpty()) "project" else compilerInfos.get(0).directive)
if (compilerInfos.size() > 0) { if (compilerInfos.size > 0) {
compilerInfos.get(0).let { compilerInfos.get(0).let {
val currentDir = File(".").absoluteFile.parentFile val currentDir = File(".").absoluteFile.parentFile
with(map) { with(map) {
@ -83,15 +84,13 @@ public class ProjectGenerator {
put("artifactId", pom.artifactId ?: "com.example") put("artifactId", pom.artifactId ?: "com.example")
put("version", pom.version ?: "0.1") put("version", pom.version ?: "0.1")
put("name", pom.name ?: pom.artifactId) put("name", pom.name ?: pom.artifactId)
put("repositories", pom.repositories.map({ "\"${it}\"" }).join(",")) put("repositories", pom.repositories.map({ "\"${it}\"" }).joinToString(","))
} }
val properties = pom.properties val properties = pom.properties
val mapped = properties.entrySet().toMap({it.key}, {translate(it.key)}) val mapped = properties.entries.toMap({it.key}, {translate(it.key)})
map.put("properties", properties map.put("properties", properties.entries.map({ Pair(mapped.get(it.key), it.value) }))
.entrySet()
.map({ Pair(mapped.get(it.key), it.value) }))
val partition = pom.dependencies.groupBy { it.scope } val partition = pom.dependencies.groupBy { it.scope }
.flatMap { it.value } .flatMap { it.value }
@ -105,7 +104,7 @@ public class ProjectGenerator {
private fun updateVersion(dep: Dependency, mapped: Map<String, String>) = private fun updateVersion(dep: Dependency, mapped: Map<String, String>) =
if ( dep.version.startsWith("\${")) { if ( dep.version.startsWith("\${")) {
val property = dep.version.substring(2, dep.version.length() - 1) val property = dep.version.substring(2, dep.version.length - 1)
Dependency(dep.groupId, dep.artifactId, "\${${mapped.get(property)}}", dep.optional, dep.scope) Dependency(dep.groupId, dep.artifactId, "\${${mapped.get(property)}}", dep.optional, dep.scope)
} else { } else {
dep dep
@ -119,11 +118,11 @@ public class ProjectGenerator {
val result = arrayListOf<Pair<ICompilerInfo, List<File>>>() val result = arrayListOf<Pair<ICompilerInfo, List<File>>>()
Kobalt.compilers.forEach { Kobalt.compilers.forEach {
val managedFiles = it.findManagedFiles(dir) val managedFiles = it.findManagedFiles(dir)
if (managedFiles.size() > 0) { if (managedFiles.size > 0) {
result.add(Pair(it, managedFiles)) result.add(Pair(it, managedFiles))
} }
} }
Collections.sort(result, { p1, p2 -> p1.second.size().compareTo(p2.second.size()) }) Collections.sort(result, { p1, p2 -> p1.second.size.compareTo(p2.second.size) })
return result.map { it.first } return result.map { it.first }
} }
} }

View file

@ -10,8 +10,8 @@ public class Template(val reader: Reader, val writer: PrintWriter, val map: Map<
BufferedReader(reader).let { BufferedReader(reader).let {
it.forEachLine { line -> it.forEachLine { line ->
var replacedLine = line var replacedLine = line
map.keySet().forEach { key -> map.keys.forEach { key ->
replacedLine = replacedLine.replace("{{${key}}}", map.get(key).toString(), false) replacedLine = replacedLine.replace("{{$key}}", map.get(key).toString(), false)
} }
writer.append(replacedLine).append("\n") writer.append(replacedLine).append("\n")
} }

View file

@ -80,7 +80,7 @@ public class Kobalt {
private fun readProperties(properties: Properties, ins: InputStream) { private fun readProperties(properties: Properties, ins: InputStream) {
properties.load(ins) properties.load(ins)
ins.close() ins.close()
properties.forEach { es -> System.setProperty(es.getKey().toString(), es.getValue().toString()) } properties.forEach { es -> System.setProperty(es.key.toString(), es.value.toString()) }
} }
val version = properties.getProperty(PROPERTY_KOBALT_VERSION) val version = properties.getProperty(PROPERTY_KOBALT_VERSION)

View file

@ -45,7 +45,7 @@ public class DynamicGraphExecutor<T>(val graph: DynamicGraph<T>,
*/ */
public fun run() : Int { public fun run() : Int {
var lastResult = TaskResult() var lastResult = TaskResult()
while (graph.freeNodes.size() > 0) { while (graph.freeNodes.size > 0) {
log(3, "Current count: ${graph.nodeCount}") log(3, "Current count: ${graph.nodeCount}")
synchronized(graph) { synchronized(graph) {
val freeNodes = graph.freeNodes val freeNodes = graph.freeNodes
@ -53,10 +53,10 @@ public class DynamicGraphExecutor<T>(val graph: DynamicGraph<T>,
log(3, "submitting free nodes $freeNodes") log(3, "submitting free nodes $freeNodes")
val callables : List<IWorker<T>> = factory.createWorkers(freeNodes) val callables : List<IWorker<T>> = factory.createWorkers(freeNodes)
callables.forEach { completion.submit(it) } callables.forEach { completion.submit(it) }
var n = callables.size() var n = callables.size
// When a callable ends, see if it freed a node. If not, keep looping // When a callable ends, see if it freed a node. If not, keep looping
while (n > 0 && graph.freeNodes.size() == 0) { while (n > 0 && graph.freeNodes.size == 0) {
try { try {
val future = completion.take() val future = completion.take()
val taskResult = future.get(2, TimeUnit.SECONDS) val taskResult = future.get(2, TimeUnit.SECONDS)
@ -137,7 +137,7 @@ public class DynamicGraph<T> {
// - no other nodes depend on it // - no other nodes depend on it
if (! dependedUpon.containsKey(m)) { if (! dependedUpon.containsKey(m)) {
result.add(m) result.add(m)
} else if (getUnfinishedNodes(du).size() == 0) { } else if (getUnfinishedNodes(du).size == 0) {
result.add(m) result.add(m)
} }
} }
@ -221,7 +221,7 @@ public class DynamicGraph<T> {
* @return the number of nodes in this graph. * @return the number of nodes in this graph.
*/ */
public val nodeCount: Int public val nodeCount: Int
get() = nodesReady.size() + nodesRunning.size() + nodesFinished.size() get() = nodesReady.size + nodesRunning.size + nodesFinished.size
override public fun toString() : String { override public fun toString() : String {
val result = StringBuilder("[DynamicGraph ") val result = StringBuilder("[DynamicGraph ")

View file

@ -28,14 +28,14 @@ abstract class GenericTestRunner(open val project: Project, open val classpath:
val allArgs = arrayListOf<String>() val allArgs = arrayListOf<String>()
allArgs.add(java!!.absolutePath) allArgs.add(java!!.absolutePath)
allArgs.add("-classpath") allArgs.add("-classpath")
allArgs.add(classpath.map { it.jarFile.get().absolutePath }.join(File.pathSeparator)) allArgs.add(classpath.map { it.jarFile.get().absolutePath }.joinToString(File.pathSeparator))
allArgs.add(mainClass) allArgs.add(mainClass)
allArgs.addAll(args) allArgs.addAll(args)
val pb = ProcessBuilder(allArgs) val pb = ProcessBuilder(allArgs)
pb.directory(File(project.directory)) pb.directory(File(project.directory))
pb.inheritIO() pb.inheritIO()
log(1, "Running tests with classpath size ${classpath.size()}") log(1, "Running tests with classpath size ${classpath.size}")
val process = pb.start() val process = pb.start()
val errorCode = process.waitFor() val errorCode = process.waitFor()
if (errorCode == 0) { if (errorCode == 0) {

View file

@ -99,7 +99,7 @@ abstract public class JvmCompilerPlugin @Inject constructor(
throw IllegalArgumentException("Custom source sets not supported yet: ${sourceSet}") throw IllegalArgumentException("Custom source sets not supported yet: ${sourceSet}")
} }
if (sourceDirs.size() > 0) { if (sourceDirs.size > 0) {
lp(project, "Copying ${sourceSet} resources") lp(project, "Copying ${sourceSet} resources")
val absOutputDir = File(KFiles.joinDir(project.directory, project.buildDirectory!!, outputDir)) val absOutputDir = File(KFiles.joinDir(project.directory, project.buildDirectory!!, outputDir))
sourceDirs.map { File(it) }.filter { it.exists() } .forEach { sourceDirs.map { File(it) }.filter { it.exists() } .forEach {

View file

@ -79,7 +79,7 @@ public class TaskManager @Inject constructor(val plugins: Plugins, val args: Arg
val currentFreeTask = allFreeTasks.filter { val currentFreeTask = allFreeTasks.filter {
TaskInfo(projectName, it.name).id == target TaskInfo(projectName, it.name).id == target
} }
if (currentFreeTask.size() == 1) { if (currentFreeTask.size == 1) {
currentFreeTask.get(0).let { currentFreeTask.get(0).let {
val thisTaskInfo = TaskInfo(projectName, it.name) val thisTaskInfo = TaskInfo(projectName, it.name)
graph.addNode(it) graph.addNode(it)
@ -150,13 +150,13 @@ public class TaskManager @Inject constructor(val plugins: Plugins, val args: Arg
private fun calculateFreeTasks(tasksByNames: Map<String, PluginTask>, reverseAfter: HashMap<String, String>) private fun calculateFreeTasks(tasksByNames: Map<String, PluginTask>, reverseAfter: HashMap<String, String>)
: Collection<PluginTask> { : Collection<PluginTask> {
val freeTaskMap = hashMapOf<String, PluginTask>() val freeTaskMap = hashMapOf<String, PluginTask>()
tasksByNames.keySet().forEach { tasksByNames.keys.forEach {
if (! runBefore.containsKey(it) && ! reverseAfter.containsKey(it)) { if (! runBefore.containsKey(it) && ! reverseAfter.containsKey(it)) {
freeTaskMap.put(it, tasksByNames.get(it)!!) freeTaskMap.put(it, tasksByNames.get(it)!!)
} }
} }
return freeTaskMap.values() return freeTaskMap.values
} }
/** /**
@ -172,7 +172,7 @@ public class TaskManager @Inject constructor(val plugins: Plugins, val args: Arg
var done = false var done = false
while (! done) { while (! done) {
val newToProcess = hashSetOf<TaskInfo>() val newToProcess = hashSetOf<TaskInfo>()
log(3, "toProcess size: " + toProcess.size()) log(3, "toProcess size: " + toProcess.size)
toProcess.forEach { target -> toProcess.forEach { target ->
val currentTask = TaskInfo(project.name!!, target.task) val currentTask = TaskInfo(project.name!!, target.task)
@ -209,7 +209,7 @@ class TaskWorker(val tasks: List<PluginTask>, val dryRun: Boolean) : IWorker<Plu
// } // }
override fun call() : TaskResult2<PluginTask> { override fun call() : TaskResult2<PluginTask> {
if (tasks.size() > 0) { if (tasks.size > 0) {
tasks.get(0).let { tasks.get(0).let {
log(1, "========== ${it.project.name}:${it.name}") log(1, "========== ${it.project.name}:${it.name}")
} }

View file

@ -12,12 +12,12 @@ public class TestNgRunner(override val project: Project, override val classpath:
override val args: List<String> override val args: List<String>
get() { get() {
arrayListOf<String>().let { arrayListOf<String>().let {
if (project.testArgs.size() > 0) { if (project.testArgs.size > 0) {
it.addAll(project.testArgs) it.addAll(project.testArgs)
} else { } else {
val testngXml = File(project.directory, KFiles.joinDir("src", "test", "resources", "testng.xml")) val testngXml = File(project.directory, KFiles.joinDir("src", "test", "resources", "testng.xml"))
if (testngXml.exists()) { if (testngXml.exists()) {
it.add(testngXml.getAbsolutePath()) it.add(testngXml.absolutePath)
} else { } else {
it.add("-testclass") it.add("-testclass")
it.addAll(findTestClasses()) it.addAll(findTestClasses())

View file

@ -28,7 +28,7 @@ class GetDependenciesCommand @Inject constructor(val executors: KobaltExecutors,
val buildFile = BuildFile(Paths.get(received.get("buildFile").asString), "GetDependenciesCommand") val buildFile = BuildFile(Paths.get(received.get("buildFile").asString), "GetDependenciesCommand")
val scriptCompiler = buildFileCompilerFactory.create(listOf(buildFile)) val scriptCompiler = buildFileCompilerFactory.create(listOf(buildFile))
scriptCompiler.observable.subscribe { scriptCompiler.observable.subscribe {
buildScriptInfo -> if (buildScriptInfo.projects.size() > 0) { buildScriptInfo -> if (buildScriptInfo.projects.size > 0) {
sender.sendData(toData(buildScriptInfo)) sender.sendData(toData(buildScriptInfo))
} }
} }

View file

@ -48,7 +48,7 @@ public class KobaltClient @Inject constructor() : Runnable {
} else { } else {
val data = jo.get("data").asString val data = jo.get("data").asString
val dd = Gson().fromJson(data, GetDependenciesCommand.GetDependenciesData::class.java) val dd = Gson().fromJson(data, GetDependenciesCommand.GetDependenciesData::class.java)
println("Read GetDependencyData, project count: ${dd.projects.size()}") println("Read GetDependencyData, project count: ${dd.projects.size}")
line = ins.readLine() line = ins.readLine()
} }
} }

View file

@ -72,7 +72,7 @@ public class KobaltServer @Inject constructor(val args: Args) : Runnable, IComma
while (! quit) { while (! quit) {
val clientSocket = serverSocket.accept() val clientSocket = serverSocket.accept()
outgoing = PrintWriter(clientSocket.outputStream, true) outgoing = PrintWriter(clientSocket.outputStream, true)
if (pending.size() > 0) { if (pending.size > 0) {
log(1, "Emptying the queue, size $pending.size()") log(1, "Emptying the queue, size $pending.size()")
synchronized(pending) { synchronized(pending) {
pending.forEach { sendData(it) } pending.forEach { sendData(it) }

View file

@ -122,7 +122,7 @@ public class BuildFileCompiler @Inject constructor(@Assisted("buildFiles") val b
// will add all the dynamic plugins found in this code to Plugins.dynamicPlugins // will add all the dynamic plugins found in this code to Plugins.dynamicPlugins
// //
val pluginSourceFile = KFiles.createTempFile(".kt") val pluginSourceFile = KFiles.createTempFile(".kt")
pluginSourceFile.writeText(pluginCode.join("\n"), Charset.defaultCharset()) pluginSourceFile.writeText(pluginCode.joinToString("\n"), Charset.defaultCharset())
log(2, "Saved ${pluginSourceFile.absolutePath}") log(2, "Saved ${pluginSourceFile.absolutePath}")
// //
@ -180,7 +180,7 @@ public class BuildFileCompiler @Inject constructor(@Assisted("buildFiles") val b
while (entry != null) { while (entry != null) {
val name = entry.name; val name = entry.name;
if (name.endsWith(".class")) { if (name.endsWith(".class")) {
val className = name.substring(0, name.length() - 6).replace("/", ".") val className = name.substring(0, name.length - 6).replace("/", ".")
var cl : Class<*>? = classLoader.loadClass(className) var cl : Class<*>? = classLoader.loadClass(className)
if (cl != null) { if (cl != null) {
classes.add(cl) classes.add(cl)

View file

@ -16,7 +16,7 @@ public class DepFactory @Inject constructor(val localRepo: LocalRepo,
public fun create(id: String, executor: ExecutorService, public fun create(id: String, executor: ExecutorService,
localFirst : Boolean = true) : IClasspathDependency { localFirst : Boolean = true) : IClasspathDependency {
if (id.startsWith(IClasspathDependency.PREFIX_FILE)) { if (id.startsWith(IClasspathDependency.PREFIX_FILE)) {
return FileDependency(id.substring(IClasspathDependency.PREFIX_FILE.length())) return FileDependency(id.substring(IClasspathDependency.PREFIX_FILE.length))
} else { } else {
val c = id.split(":") val c = id.split(":")
var repoResult: RepoFinder.RepoResult? var repoResult: RepoFinder.RepoResult?

View file

@ -47,7 +47,7 @@ public class Gpg {
val pb = ProcessBuilder(allArgs) val pb = ProcessBuilder(allArgs)
pb.directory(directory) pb.directory(directory)
log(2, "Signing file: " + allArgs.join(" ")) log(2, "Signing file: " + allArgs.joinToString(" "))
val process = pb.start() val process = pb.start()
val br = BufferedReader(InputStreamReader(process.errorStream)) val br = BufferedReader(InputStreamReader(process.errorStream))

View file

@ -29,7 +29,7 @@ public class Http {
val response = client.newCall(request.build()).execute() val response = client.newCall(request.build()).execute()
return Body(response.body(), response.code()) return Body(response.body(), response.code())
} catch(ex: IOException) { } catch(ex: IOException) {
throw KobaltException("Could not load URL ${url}, error: " + ex.getMessage(), ex) throw KobaltException("Could not load URL ${url}, error: " + ex.message, ex)
} }
} }

View file

@ -34,7 +34,7 @@ open public class LocalRepo(open val localRepo: String = KFiles.localRepo) {
if (files != null) { if (files != null) {
val directories = files.filter { it.isDirectory } val directories = files.filter { it.isDirectory }
if (directories.size() > 0) { if (directories.size > 0) {
Collections.sort(directories, { f1, f2 -> Collections.sort(directories, { f1, f2 ->
val v1 = Versions.toLongVersion(f1.name) val v1 = Versions.toLongVersion(f1.name)
val v2 = Versions.toLongVersion(f2.name) val v2 = Versions.toLongVersion(f2.name)

View file

@ -63,7 +63,7 @@ public class MavenDependency @Inject constructor(override @Assisted("groupId") v
fun hasVersion(id: String) : Boolean { fun hasVersion(id: String) : Boolean {
val c = id.split(":") val c = id.split(":")
return c.size() == 3 && !Strings.isEmpty(c[2]) return c.size == 3 && !Strings.isEmpty(c[2])
} }
fun toId(g: String, a: String, v: String) = "$g:$a:$v" fun toId(g: String, a: String, v: String) = "$g:$a:$v"

View file

@ -39,13 +39,13 @@ public class RepoFinder @Inject constructor(val http: Http, val executors: Kobal
* Schedule an HTTP request to each repo in its own thread. * Schedule an HTTP request to each repo in its own thread.
*/ */
private fun loadCorrectRepo(id: String): RepoResult { private fun loadCorrectRepo(id: String): RepoResult {
val executor = executors.newExecutor("RepoFinder-${id}", Kobalt.repos.size()) val executor = executors.newExecutor("RepoFinder-${id}", Kobalt.repos.size)
val cs = ExecutorCompletionService<RepoResult>(executor) val cs = ExecutorCompletionService<RepoResult>(executor)
try { try {
log(2, "Looking for $id") log(2, "Looking for $id")
Kobalt.repos.forEach { cs.submit(RepoFinderCallable(id, it)) } Kobalt.repos.forEach { cs.submit(RepoFinderCallable(id, it)) }
for (i in 0..Kobalt.repos.size() - 1) { for (i in 0..Kobalt.repos.size - 1) {
try { try {
val result = cs.take().get(2000, TimeUnit.MILLISECONDS) val result = cs.take().get(2000, TimeUnit.MILLISECONDS)
log(2, "Result for repo #${i}: ${result}") log(2, "Result for repo #${i}: ${result}")

View file

@ -33,7 +33,7 @@ public class CheckVersions @Inject constructor(val depFactory : DepFactory,
} }
} }
if (newVersions.size() > 0) { if (newVersions.size > 0) {
log(1, "New versions found:") log(1, "New versions found:")
newVersions.forEach { log(1, " ${it}") } newVersions.forEach { log(1, " ${it}") }
} else { } else {

View file

@ -1,11 +1,12 @@
package com.beust.kobalt.misc package com.beust.kobalt.misc
import com.beust.klaxon.JsonArray import com.google.gson.JsonArray
import com.beust.klaxon.JsonObject import com.google.gson.JsonObject
import com.beust.klaxon.Parser import com.google.gson.JsonParser
import com.beust.klaxon.string
import com.google.inject.Inject import com.google.inject.Inject
import java.io.BufferedReader
import java.io.IOException import java.io.IOException
import java.io.InputStreamReader
import java.net.URL import java.net.URL
import java.util.concurrent.Callable import java.util.concurrent.Callable
import java.util.concurrent.Future import java.util.concurrent.Future
@ -26,11 +27,13 @@ public class GithubApi @Inject constructor(val executors: KobaltExecutors) {
try { try {
val ins = URL(url).openConnection().inputStream val ins = URL(url).openConnection().inputStream
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
val jo = Parser().parse(ins) as JsonArray<JsonObject> val reader = BufferedReader(InputStreamReader(ins))
val jo = JsonParser().parse(reader) as JsonArray
// val jo = Parser().parse(ins) as JsonArray<JsonObject>
if (jo.size() > 0) { if (jo.size() > 0) {
var versionName = jo.get(0).string("name") var versionName = (jo.get(0) as JsonObject).get("name").asString
if (versionName == null) { if (versionName == null) {
versionName = jo.get(0).string("tag_name") versionName = (jo.get(0) as JsonObject).get("tag_name").asString
} }
if (versionName != null) { if (versionName != null) {
result = versionName result = versionName

View file

@ -55,7 +55,7 @@ public class KFiles {
public val TEST_CLASSES_DIR : String = "test-classes" public val TEST_CLASSES_DIR : String = "test-classes"
public fun joinDir(vararg ts: String): String = ts.toArrayList().join(File.separator) public fun joinDir(vararg ts: String): String = ts.toArrayList().joinToString(File.separator)
public fun makeDir(dir: String, s: String) : File { public fun makeDir(dir: String, s: String) : File {
val result = File(dir, s) val result = File(dir, s)
@ -85,7 +85,7 @@ public class KFiles {
} }
} }
// Return files relative to rootDir // Return files relative to rootDir
val r = result.map { it.substring(rootDir.absolutePath.length() + 1)} val r = result.map { it.substring(rootDir.absolutePath.length + 1)}
return r return r
} }
@ -146,7 +146,7 @@ public class KFiles {
Files.copy(from, to, option) Files.copy(from, to, option)
} catch(ex: IOException) { } catch(ex: IOException) {
// Windows is anal about this // Windows is anal about this
log(1, "Couldn't copy $from to $to: ${ex.getMessage()}") log(1, "Couldn't copy $from to $to: ${ex.message}")
} }
} }
} }

View file

@ -29,13 +29,13 @@ class KobaltExecutor(name: String, threadCount: Int)
} catch (ce: CancellationException) { } catch (ce: CancellationException) {
ex = ce; ex = ce;
} catch (ee: ExecutionException) { } catch (ee: ExecutionException) {
ex = ee.getCause(); ex = ee.cause;
} catch (ie: InterruptedException) { } catch (ie: InterruptedException) {
Thread.currentThread().interrupt(); // ignore/reset Thread.currentThread().interrupt(); // ignore/reset
} }
} }
if (ex != null) { if (ex != null) {
error(if (ex.getMessage() != null) ex.getMessage()!! else ex.javaClass.toString()) error(if (ex.message != null) ex.message!! else ex.javaClass.toString())
} }
} }
} }
@ -61,7 +61,7 @@ public class KobaltExecutors {
var remainingMs = maxMs var remainingMs = maxMs
var i = 0 var i = 0
while (i < tasks.size() && remainingMs >= 0) { while (i < tasks.size && remainingMs >= 0) {
var start = System.currentTimeMillis() var start = System.currentTimeMillis()
val r = cs.take().get(remainingMs, TimeUnit.MILLISECONDS) val r = cs.take().get(remainingMs, TimeUnit.MILLISECONDS)
progress(r) progress(r)
@ -72,7 +72,7 @@ public class KobaltExecutors {
} }
if (remainingMs < 0) { if (remainingMs < 0) {
warn("Didn't receive all the results in time: $i / ${tasks.size()}") warn("Didn't receive all the results in time: $i / ${tasks.size}")
} else { } else {
log(2, "Received all results in ${maxMs - remainingMs} ms") log(2, "Received all results in ${maxMs - remainingMs} ms")
} }

View file

@ -51,7 +51,7 @@ class Logger(val dev: Boolean) {
final fun error(tag: String, message: String, e: Throwable? = null) = final fun error(tag: String, message: String, e: Throwable? = null) =
println(getPattern("***** E", "***** ERROR ", tag, message) + println(getPattern("***** E", "***** ERROR ", tag, message) +
if (e != null) " Exception: " + e.getMessage() else "") if (e != null) " Exception: " + e.message else "")
final fun warn(tag: String, message: String, e: Throwable? = null) = final fun warn(tag: String, message: String, e: Throwable? = null) =
println(getPattern("W", "***** WARNING ", tag, message)) println(getPattern("W", "***** WARNING ", tag, message))

View file

@ -26,6 +26,6 @@ public class Strings {
/** /**
* @Return the number of times the given character occurs in the string * @Return the number of times the given character occurs in the string
*/ */
public fun String.countChar(c: Char) : Int { public infix fun String.countChar(c: Char) : Int {
return CharMatcher.`is`(c).countIn(this) return CharMatcher.`is`(c).countIn(this)
} }

View file

@ -4,7 +4,7 @@ public class ToString<T>(val name: String, vararg o: T) {
val sb = StringBuffer() val sb = StringBuffer()
init { init {
for (i in 0..o.size() - 1 step 2) { for (i in 0..o.size - 1 step 2) {
if (i > 0) sb.append(", ") if (i > 0) sb.append(", ")
sb.append(o.get(i).toString() + ":" + o.get(i + 1)) sb.append(o.get(i).toString() + ":" + o.get(i + 1))
} }

View file

@ -25,7 +25,7 @@ class Topological<T> {
val result = arrayListOf<T>() val result = arrayListOf<T>()
var dependMap = HashMultimap.create<T, T>() var dependMap = HashMultimap.create<T, T>()
dependingOn.keySet().forEach { dependMap.putAll(it, dependingOn.get(it))} dependingOn.keySet().forEach { dependMap.putAll(it, dependingOn.get(it))}
while (all.size() > 0) { while (all.size > 0) {
val freeNodes = all.filter { val freeNodes = all.filter {
dependMap.get(it).isEmpty() dependMap.get(it).isEmpty()
} }

View file

@ -50,11 +50,11 @@ public class JavaPlugin @Inject constructor(
val args = arrayListOf( val args = arrayListOf(
javac!!.absolutePath, javac!!.absolutePath,
"-d", outputDirectory.absolutePath) "-d", outputDirectory.absolutePath)
if (cpList.size() > 0) { if (cpList.size > 0) {
val stringClasspath = cpList.map { it.jarFile.get().absolutePath } val stringClasspath = cpList.map { it.jarFile.get().absolutePath }
validateClasspath(stringClasspath) validateClasspath(stringClasspath)
args.add("-classpath") args.add("-classpath")
args.add(stringClasspath.join(File.pathSeparator)) args.add(stringClasspath.joinToString(File.pathSeparator))
} }
args.addAll(sourceFiles) args.addAll(sourceFiles)
@ -64,8 +64,8 @@ public class JavaPlugin @Inject constructor(
// pb.redirectErrorStream(true) // pb.redirectErrorStream(true)
// pb.redirectError(File("/tmp/kobalt-err")) // pb.redirectError(File("/tmp/kobalt-err"))
// pb.redirectOutput(File("/tmp/kobalt-out")) // pb.redirectOutput(File("/tmp/kobalt-out"))
val line = args.join(" ") val line = args.joinToString(" ")
log(1, " Compiling ${sourceFiles.size()} files with classpath size ${cpList.size()}") log(1, " Compiling ${sourceFiles.size} files with classpath size ${cpList.size}")
log(2, " Compiling $project:\n$line") log(2, " Compiling $project:\n$line")
val process = pb.start() val process = pb.start()
val errorCode = process.waitFor() val errorCode = process.waitFor()
@ -89,7 +89,7 @@ public class JavaPlugin @Inject constructor(
val classpath = calculateClasspath(project.compileDependencies) val classpath = calculateClasspath(project.compileDependencies)
val args = arrayListOf( val args = arrayListOf(
javadoc!!.absolutePath, javadoc!!.absolutePath,
"-classpath", classpath.map { it.jarFile.get().absolutePath }.join(File.pathSeparator), "-classpath", classpath.map { it.jarFile.get().absolutePath }.joinToString(File.pathSeparator),
"-d", outputDir.absolutePath) "-d", outputDir.absolutePath)
args.addAll(sourceFiles) args.addAll(sourceFiles)
@ -127,7 +127,7 @@ public class JavaPlugin @Inject constructor(
.map { File(projectDir, it).absolutePath } .map { File(projectDir, it).absolutePath }
val result = val result =
if (absoluteSourceFiles.size() > 0) { if (absoluteSourceFiles.size > 0) {
compilePrivate(project, compilePrivate(project,
testDependencies(project), testDependencies(project),
absoluteSourceFiles, absoluteSourceFiles,

View file

@ -24,7 +24,7 @@ class KotlinCompiler @Inject constructor(override val localRepo : LocalRepo,
override val dependencyManager: DependencyManager, override val dependencyManager: DependencyManager,
override val executors: KobaltExecutors) override val executors: KobaltExecutors)
: JvmCompilerPlugin(localRepo, files, depFactory, dependencyManager, executors) { : JvmCompilerPlugin(localRepo, files, depFactory, dependencyManager, executors) {
private val KOTLIN_VERSION = "0.14.449" private val KOTLIN_VERSION = "1.0.0-beta-1038"
override val name = "kotlin" override val name = "kotlin"
@ -52,10 +52,10 @@ class KotlinCompiler @Inject constructor(override val localRepo : LocalRepo,
validateClasspath(classpathList) validateClasspath(classpathList)
log(2, "Compiling ${source.size()} files with classpath:\n " + classpathList.join("\n ")) log(2, "Compiling ${source.size} files with classpath:\n " + classpathList.joinToString("\n "))
CLICompiler.doMainNoExit(K2JVMCompiler(), arrayOf( CLICompiler.doMainNoExit(K2JVMCompiler(), arrayOf(
"-d", output, "-d", output,
"-classpath", classpathList.join(File.pathSeparator), *source.toTypedArray(), "-classpath", classpathList.joinToString(File.pathSeparator), *source.toTypedArray(),
*args.toTypedArray())) *args.toTypedArray()))
executor.shutdown() executor.shutdown()
return TaskResult() return TaskResult()

View file

@ -53,7 +53,7 @@ public class KotlinPlugin @Inject constructor(
File(projectDirectory, it).absolutePath File(projectDirectory, it).absolutePath
} }
compilePrivate(classpath, absoluteSourceFiles, buildDirectory.getAbsolutePath()) compilePrivate(classpath, absoluteSourceFiles, buildDirectory.absolutePath)
lp(project, "Compilation succeeded") lp(project, "Compilation succeeded")
return TaskResult() return TaskResult()
} }
@ -83,7 +83,7 @@ public class KotlinPlugin @Inject constructor(
outputDirectory: String): TaskResult { outputDirectory: String): TaskResult {
File(outputDirectory).mkdirs() File(outputDirectory).mkdirs()
log(1, " Compiling ${sources.size()} files with classpath size ${cpList.size()}") log(1, " Compiling ${sources.size} files with classpath size ${cpList.size}")
return kotlinCompilePrivate { return kotlinCompilePrivate {
classpath(cpList.map { it.jarFile.get().absolutePath }) classpath(cpList.map { it.jarFile.get().absolutePath })

View file

@ -57,7 +57,7 @@ public class JarUtils {
val defaultHandler: (Exception) -> Unit = { ex: Exception -> val defaultHandler: (Exception) -> Unit = { ex: Exception ->
// Ignore duplicate entry exceptions // Ignore duplicate entry exceptions
if (! ex.getMessage()?.contains("duplicate")!!) { if (! ex.message?.contains("duplicate")!!) {
throw ex throw ex
} }
} }

View file

@ -66,7 +66,7 @@ public class PackagingPlugin @Inject constructor(val dependencyManager : Depende
ex.add(FileSystems.getDefault().getPathMatcher("glob:${it.spec}")) ex.add(FileSystems.getDefault().getPathMatcher("glob:${it.spec}"))
} }
ex.forEach { ex.forEach {
if (it.matches(Paths.get(file.getName()))) { if (it.matches(Paths.get(file.name))) {
log(2, "Excluding ${file}") log(2, "Excluding ${file}")
return true return true
} }
@ -129,7 +129,7 @@ public class PackagingPlugin @Inject constructor(val dependencyManager : Depende
val filesNotExcluded : List<File> = files.filter { ! isExcluded(it, jar.excludes) } val filesNotExcluded : List<File> = files.filter { ! isExcluded(it, jar.excludes) }
val fileSpecs = arrayListOf<IFileSpec>() val fileSpecs = arrayListOf<IFileSpec>()
filesNotExcluded.forEach { filesNotExcluded.forEach {
fileSpecs.add(FileSpec(it.path.toString().substring(prefixPath.toString().length() + 1))) fileSpecs.add(FileSpec(it.path.toString().substring(prefixPath.toString().length + 1)))
} }
allFiles.add(IncludedFile(From(prefixPath.toString() + "/"), To(""), fileSpecs)) allFiles.add(IncludedFile(From(prefixPath.toString() + "/"), To(""), fileSpecs))
} else { } else {
@ -189,7 +189,7 @@ public class PackagingPlugin @Inject constructor(val dependencyManager : Depende
warn("Directory ${fromPath} doesn't exist, not including it in the jar") warn("Directory ${fromPath} doesn't exist, not including it in the jar")
} }
} }
if (includedSpecs.size() > 0) { if (includedSpecs.size > 0) {
log(3, "Including specs ${includedSpecs}") log(3, "Including specs ${includedSpecs}")
result.add(IncludedFile(From(includedFile.from), To(includedFile.to), includedSpecs)) result.add(IncludedFile(From(includedFile.from), To(includedFile.to), includedSpecs))
} }
@ -210,12 +210,12 @@ public class PackagingPlugin @Inject constructor(val dependencyManager : Depende
outputStreamFactory: (OutputStream) -> ZipOutputStream = DEFAULT_STREAM_FACTORY) : File { outputStreamFactory: (OutputStream) -> ZipOutputStream = DEFAULT_STREAM_FACTORY) : File {
val buildDir = KFiles.makeDir(project.directory, project.buildDirectory!!) val buildDir = KFiles.makeDir(project.directory, project.buildDirectory!!)
val archiveDir = KFiles.makeDir(buildDir.path, "libs") val archiveDir = KFiles.makeDir(buildDir.path, "libs")
val fullArchiveName = archiveName ?: arrayListOf(project.name!!, project.version!!).join("-") + suffix val fullArchiveName = archiveName ?: arrayListOf(project.name!!, project.version!!).joinToString("-") + suffix
val result = File(archiveDir.path, fullArchiveName) val result = File(archiveDir.path, fullArchiveName)
val outStream = outputStreamFactory(FileOutputStream(result)) val outStream = outputStreamFactory(FileOutputStream(result))
log(2, "Creating ${result}") log(2, "Creating ${result}")
JarUtils.addFiles(project.directory, includedFiles, outStream, expandJarFiles) JarUtils.addFiles(project.directory, includedFiles, outStream, expandJarFiles)
log(2, "Added ${includedFiles.size()} files to ${result}") log(2, "Added ${includedFiles.size} files to ${result}")
outStream.flush() outStream.flush()
outStream.close() outStream.close()
log(1, " Created ${result}") log(1, " Created ${result}")
@ -360,7 +360,7 @@ class IncludedFile(val fromOriginal: From, val toOriginal: To, val specs: List<I
public val from: String get() = fromOriginal.path.replace("\\", "/") public val from: String get() = fromOriginal.path.replace("\\", "/")
public val to: String get() = toOriginal.path.replace("\\", "/") public val to: String get() = toOriginal.path.replace("\\", "/")
override public fun toString() = ToString("IncludedFile", override public fun toString() = ToString("IncludedFile",
"files", specs.map { it.toString() }.join(", "), "files", specs.map { it.toString() }.joinToString(", "),
"from", from, "from", from,
"to", to) "to", to)
.s .s

View file

@ -1,6 +1,5 @@
package com.beust.kobalt.plugin.publish package com.beust.kobalt.plugin.publish
import com.beust.klaxon.*
import com.beust.kobalt.api.Project import com.beust.kobalt.api.Project
import com.beust.kobalt.internal.TaskResult import com.beust.kobalt.internal.TaskResult
import com.beust.kobalt.maven.Gpg import com.beust.kobalt.maven.Gpg
@ -8,6 +7,9 @@ import com.beust.kobalt.maven.Http
import com.beust.kobalt.maven.KobaltException import com.beust.kobalt.maven.KobaltException
import com.beust.kobalt.maven.Md5 import com.beust.kobalt.maven.Md5
import com.beust.kobalt.misc.* import com.beust.kobalt.misc.*
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.google.inject.assistedinject.Assisted import com.google.inject.assistedinject.Assisted
import com.squareup.okhttp.Response import com.squareup.okhttp.Response
import org.jetbrains.annotations.Nullable import org.jetbrains.annotations.Nullable
@ -17,8 +19,8 @@ import java.nio.charset.Charset
import javax.inject.Inject import javax.inject.Inject
data class JCenterPackage(val jo: JsonObject) { data class JCenterPackage(val jo: JsonObject) {
@Suppress("UNCHECKED_CAST") // @Suppress("UNCHECKED_CAST")
val latestPublishedVersion = (jo.get("versions") as JsonArray<String>).get(0) // val latestPublishedVersion = (jo.get("versions") as JsonArray).get(0) as JsonObject).
} }
open public class UnauthenticatedJCenterApi @Inject constructor(open val http: Http){ open public class UnauthenticatedJCenterApi @Inject constructor(open val http: Http){
@ -28,11 +30,12 @@ open public class UnauthenticatedJCenterApi @Inject constructor(open val http: H
} }
fun parseResponse(response: String) : JsonObject { fun parseResponse(response: String) : JsonObject {
return Parser().parse(ByteArrayInputStream(response.toByteArray(Charset.defaultCharset()))) as JsonObject return JsonParser().parse(response).asJsonObject
// return Parser().parse(ByteArrayInputStream(response.toByteArray(Charset.defaultCharset()))) as JsonObject
} }
fun getPackage(name: String) : JCenterPackage { fun getPackage(name: String) : JCenterPackage {
val url = arrayListOf(BINTRAY_URL_API, "packages", "cbeust", "maven", "kobalt").join("/") val url = arrayListOf(BINTRAY_URL_API, "packages", "cbeust", "maven", "kobalt").joinToString("/")
val response = http.get(url).getAsString() val response = http.get(url).getAsString()
val result = parseResponse(response) val result = parseResponse(response)
return JCenterPackage(result) return JCenterPackage(result)
@ -53,21 +56,20 @@ public class JCenterApi @Inject constructor (@Nullable @Assisted("username") val
fun packageExists(packageName: String) : Boolean { fun packageExists(packageName: String) : Boolean {
val url = arrayListOf(UnauthenticatedJCenterApi.BINTRAY_URL_API, "packages", username!!, "maven", packageName) val url = arrayListOf(UnauthenticatedJCenterApi.BINTRAY_URL_API, "packages", username!!, "maven", packageName)
.join("/") .joinToString("/")
val response = http.get(username, password, url).getAsString() val response = http.get(username, password, url).getAsString()
val jo = parseResponse(response) val jo = parseResponse(response)
return jo.string("name") == packageName return jo.get("name").asString == packageName
} }
fun createPackage(packageName: String) : String { // class ForPost(val name: String, val license: Array<String>)
val url = arrayListOf(UnauthenticatedJCenterApi.BINTRAY_URL_API, "packages", username!!, "maven").join("/") //
val jo = json { // fun createPackage(packageName: String) : String {
obj("name" to packageName) // val url = arrayListOf(UnauthenticatedJCenterApi.BINTRAY_URL_API, "packages", username!!, "maven").join("/")
obj("license" to array("Apache 2.0")) // val jsonString = Gson().toJson(ForPost(packageName, arrayOf("Apache 2.0")))
} // return http.post(username, password, url, jsonString)
return http.post(username, password, url, jo.toJsonString()) // }
}
fun uploadMaven(project: Project, files: List<File>, configuration : JCenterConfiguration?) : TaskResult { fun uploadMaven(project: Project, files: List<File>, configuration : JCenterConfiguration?) : TaskResult {
if (! packageExists(project.name!!)) { if (! packageExists(project.name!!)) {
@ -86,7 +88,7 @@ public class JCenterApi @Inject constructor (@Nullable @Assisted("username") val
project.artifactId!!, project.artifactId!!,
project.version!!, project.version!!,
f.name) f.name)
.join("/") .joinToString("/")
} }
return upload(files, configuration, fileToPath, generateMd5 = true, generateAsc = true) return upload(files, configuration, fileToPath, generateMd5 = true, generateAsc = true)
@ -126,14 +128,14 @@ public class JCenterApi @Inject constructor (@Nullable @Assisted("username") val
if (configuration?.publish == true) options.add("publish=1") if (configuration?.publish == true) options.add("publish=1")
val optionPath = StringBuffer() val optionPath = StringBuffer()
if (options.size() > 0) { if (options.size > 0) {
optionPath.append("?" + options.join("&")) optionPath.append("?" + options.joinToString("&"))
} }
// //
// Uploads can'be done in parallel or JCenter rejects them // Uploads can'be done in parallel or JCenter rejects them
// //
val fileCount = filesToUpload.size() val fileCount = filesToUpload.size
if (fileCount > 0) { if (fileCount > 0) {
log(1, " Found $fileCount artifacts to upload: " + filesToUpload.get(0) log(1, " Found $fileCount artifacts to upload: " + filesToUpload.get(0)
+ if (fileCount > 1) "..." else "") + if (fileCount > 1) "..." else "")
@ -142,8 +144,8 @@ public class JCenterApi @Inject constructor (@Nullable @Assisted("username") val
fun dots(total: Int, list: List<Boolean>) : String { fun dots(total: Int, list: List<Boolean>) : String {
val spaces : String = Array(total - list.size(), { " " }).join("") val spaces : String = Array(total - list.size, { " " }).joinToString("")
return "|" + list.map { if (it) "." else "X" }.join("") + spaces + "|" return "|" + list.map { if (it) "." else "X" }.joinToString("") + spaces + "|"
} }
val results = arrayListOf<Boolean>() val results = arrayListOf<Boolean>()
@ -153,7 +155,7 @@ public class JCenterApi @Inject constructor (@Nullable @Assisted("username") val
{ r: Response -> { r: Response ->
results.add(false) results.add(false)
val jo = parseResponse(r.body().string()) val jo = parseResponse(r.body().string())
errorMessages.add(jo.string("message") ?: "No message found") errorMessages.add(jo.get("message").asString ?: "No message found")
}) })
val end = if (i >= fileCount) "\n" else "" val end = if (i >= fileCount) "\n" else ""
log(1, " Uploading " + (i++) + " / $fileCount " + dots(fileCount, results) + end, false) log(1, " Uploading " + (i++) + " / $fileCount " + dots(fileCount, results) + end, false)
@ -161,8 +163,8 @@ public class JCenterApi @Inject constructor (@Nullable @Assisted("username") val
if (errorMessages.isEmpty()) { if (errorMessages.isEmpty()) {
return TaskResult() return TaskResult()
} else { } else {
error("Errors while uploading:\n" + errorMessages.map { " $it" }.join("\n")) error("Errors while uploading:\n" + errorMessages.map { " $it" }.joinToString("\n"))
return TaskResult(false, errorMessages.join("\n")) return TaskResult(false, errorMessages.joinToString("\n"))
} }
} else { } else {
warn("Found no artifacts to upload") warn("Found no artifacts to upload")

View file

@ -67,7 +67,7 @@ public class PublishPlugin @Inject constructor(val http: Http, val files: com.be
val jcenter = jcenterFactory.create(user, password) val jcenter = jcenterFactory.create(user, password)
val configuration = configurations.get(project.name) val configuration = configurations.getRaw(project.name)
// //
// Upload to Maven // Upload to Maven
@ -89,7 +89,7 @@ public class PublishPlugin @Inject constructor(val http: Http, val files: com.be
} }
} }
} }
return TaskResult(success, messages.join("\n ")) return TaskResult(success, messages.joinToString("\n "))
} }
/** /**

View file

@ -44,7 +44,7 @@ public class Wrapper {
private fun readProperties(properties: Properties, ins: InputStream) { private fun readProperties(properties: Properties, ins: InputStream) {
properties.load(ins) properties.load(ins)
ins.close() ins.close()
properties.forEach { es -> System.setProperty(es.getKey().toString(), es.getValue().toString()) } properties.forEach { es -> System.setProperty(es.key.toString(), es.value.toString()) }
} }
private fun maybeCreateProperties() : Properties { private fun maybeCreateProperties() : Properties {
@ -169,7 +169,7 @@ public class Wrapper {
args.addAll(argv) args.addAll(argv)
val pb = ProcessBuilder(args) val pb = ProcessBuilder(args)
pb.inheritIO() pb.inheritIO()
log(2, "Launching\n ${args.join(" ")}") log(2, "Launching\n ${args.joinToString(" ")}")
val process = pb.start() val process = pb.start()
process.waitFor() process.waitFor()
} }

View file

@ -1 +1 @@
kobalt.version=0.195 kobalt.version=0.198