Add InputStream contentEquals overload

This commit is contained in:
Jason Penilla 2023-11-17 00:05:20 -07:00
parent 5225a4d132
commit daab4fa35e
No known key found for this signature in database
GPG key ID: 0E75A301420E48F8
3 changed files with 27 additions and 21 deletions

View file

@ -23,6 +23,7 @@
package io.papermc.paperweight.util
import io.papermc.paperweight.PaperweightException
import java.io.InputStream
import java.net.URI
import java.nio.file.FileSystem
import java.nio.file.FileSystems
@ -161,31 +162,28 @@ fun Path.hashFile(algorithm: HashingAlgorithm): ByteArray = inputStream().use {
fun Path.sha256asHex(): String = hashFile(HashingAlgorithm.SHA256).asHexString()
fun Path.contentEquals(file: Path, bufferSizeBytes: Int = 8192): Boolean {
fun Path.contentEquals(two: InputStream, bufferSizeBytes: Int = 8192): Boolean {
inputStream().use { one ->
file.inputStream().use { two ->
val bufOne = ByteArray(bufferSizeBytes)
val bufTwo = ByteArray(bufferSizeBytes)
val bufOne = ByteArray(bufferSizeBytes)
val bufTwo = ByteArray(bufferSizeBytes)
while (true) {
val readOne = one.read(bufOne)
val readTwo = two.read(bufTwo)
while (true) {
val readOne = one.read(bufOne)
val readTwo = two.read(bufTwo)
if (readOne != readTwo) {
// length differs
return false
}
if (readOne != readTwo) {
// length differs
return false
}
if (readOne == -1) {
// end of content
break
}
if (readOne == -1) {
// end of content
break
}
if (!Arrays.equals(bufOne, 0, readOne, bufTwo, 0, readOne)) {
// content differs
return false
}
if (!Arrays.equals(bufOne, 0, readOne, bufTwo, 0, readOne)) {
// content differs
return false
}
}
}
@ -193,6 +191,11 @@ fun Path.contentEquals(file: Path, bufferSizeBytes: Int = 8192): Boolean {
return true
}
fun Path.contentEquals(file: Path, bufferSizeBytes: Int = 8192): Boolean =
file.inputStream().use { two ->
contentEquals(two, bufferSizeBytes)
}
fun Path.withDifferentExtension(ext: String): Path = resolveSibling("$nameWithoutExtension.$ext")
// Returns true if our process already owns the lock

View file

@ -89,7 +89,7 @@ private fun upToDate(
xmlIn: String
): Boolean {
val bin = binDest.isRegularFile() && binDest.contentEquals(binaryIn)
val xml = ivyXml.isRegularFile() && ivyXml.readText(Charsets.UTF_8) == xmlIn
val xml = ivyXml.isRegularFile() && ivyXml.contentEquals(xmlIn.byteInputStream())
val sources = if (sourcesIn == null) {
sourcesDest.notExists()
} else {

View file

@ -40,6 +40,9 @@ class FileUtilsTest {
val two = tempDir.resolve("${FileUtilsTest::class.simpleName}.class_1")
two.writeBytes(someBytes)
// assert the content equals what we just wrote
assertTrue(one.contentEquals(someBytes.inputStream()), "File content doesn't equal what was written to the file")
// assert the files have matching content
assertTrue(one.contentEquals(two), "These files have the same content")
assertTrue(two.contentEquals(one), "These files have the same content")