aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/moe/nea/shot/Shots.kt
blob: b0956b48a2352056b4b93f1ebac6e1d2dd1ccb7f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package moe.nea.shot

import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassWriter
import java.io.Serializable
import java.nio.file.Files
import java.nio.file.Path
import java.util.zip.ZipFile
import java.util.zip.ZipOutputStream
import kotlin.io.path.createDirectories
import kotlin.io.path.exists

data class Shots(
    val injections: Map<ClassRef, ClassShots>,
) : Serializable {

    fun processEntry(toInject: ClassShots, bytes: ByteArray): ByteArray {
        val classReader = ClassReader(bytes)
        val classWriter = ClassWriter(0)
        val visitor = InjectionApplicator(toInject, classWriter)
        classReader.accept(visitor, 0)
        return classWriter.toByteArray()
    }

    fun processZipFile(input: ZipFile, output: ZipOutputStream) {
        for (entry in input.entries()) {
            val classRef = ClassRef.fromPath(entry.name)
            val toInject = classRef?.let(injections::get)
            output.putNextEntry(entry)
            if (toInject == null) {
                input.getInputStream(entry).copyTo(output)
            } else {
                val bytes = input.getInputStream(entry).use { it.readBytes() }
                val modifiedBytes = processEntry(toInject, bytes)
                output.write(modifiedBytes)
            }
        }
    }


    /**
     * Run on an extracted zip, (or alternatively, a jar file systems root path)
     */
    fun process(sourceFiles: Path, targetFiles: Path) {
        for ((classRef, toInject) in injections.entries) {
            val classSource = sourceFiles.resolve(classRef.path)
            val classTarget = targetFiles.resolve(classRef.path)
            if (!classSource.exists()) {
                continue
            }
            classTarget.parent.createDirectories()
            Files.write(classTarget, processEntry(toInject, Files.readAllBytes(classSource)))
        }
    }
}