Skip to content

Commit

Permalink
Refactor loading fixtures from jar resources
Browse files Browse the repository at this point in the history
  • Loading branch information
hfhbd committed Nov 3, 2023
1 parent 3144c1f commit 83bf74d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 27 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.alecstrong.sql.psi.test.fixtures
package com.alecstrong.sql.psi.core

import com.alecstrong.sql.psi.test.fixtures.TestHeadlessParser
import org.junit.Assert.fail
import org.junit.Test
import java.io.File
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import org.junit.Test
import java.io.File
import java.util.Enumeration
import java.util.jar.JarEntry
import java.util.jar.JarFile
import java.nio.file.FileSystems
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.copyToRecursively
import kotlin.io.path.div
import kotlin.io.path.toPath

abstract class FixturesTest(
val name: String,
Expand All @@ -18,7 +20,8 @@ abstract class FixturesTest(

abstract fun setupDialect()

@Test fun execute() {
@Test
fun execute() {
val errors = ArrayList<String>()

val newRoot = File("build/fixtureCopies/${fixtureRoot.name}Copy")
Expand Down Expand Up @@ -121,31 +124,20 @@ abstract class FixturesTest(
}
}

@OptIn(ExperimentalPathApi::class)
fun Any.loadFolderFromResources(path: String, target: File) {
val jarFile = File(javaClass.protectionDomain.codeSource.location.path)
File(target, path).apply { if (exists()) deleteRecursively() }

assert(jarFile.isFile)

val jar = JarFile(jarFile)
val entries: Enumeration<JarEntry> = jar.entries() // gives ALL entries in jar
while (entries.hasMoreElements()) {
val entry = entries.nextElement()
val name: String = entry.name
if (name.startsWith("$path/")) { // filter according to the path
if (entry.isDirectory) {
File(target, entry.name).mkdir()
} else {
File(target, entry.name).apply {
createNewFile()
jar.getInputStream(entry).use {
it.copyTo(outputStream())
}
}
}
val targetFile = File(target, path).apply { if (exists()) deleteRecursively() }
val resourcesUri = javaClass.getResource("/$path")?.toURI()
requireNotNull(resourcesUri) {
"/$path not found in resources"
}
when (resourcesUri.scheme) {
"jar" -> FileSystems.newFileSystem(resourcesUri, emptyMap<String, Nothing>(), null).use {
it.getPath("/$path").copyToRecursively(target.toPath() / path, overwrite = true, followLinks = false)
}
"file" -> resourcesUri.toPath().toFile().copyRecursively(targetFile, overwrite = true)
else -> error("Unsupported scheme ${resourcesUri.scheme} of $resourcesUri")
}
jar.close()
}

private fun formatErrorList(errors: List<String>): String {
Expand Down

0 comments on commit 83bf74d

Please sign in to comment.