Skip to content

Instantly share code, notes, and snippets.

@mpetuska
Last active June 23, 2021 08:38
Show Gist options
  • Save mpetuska/a3167f5848ea9b6f657a06d0e2c1bc72 to your computer and use it in GitHub Desktop.
Save mpetuska/a3167f5848ea9b6f657a06d0e2c1bc72 to your computer and use it in GitHub Desktop.
Script to convert a directory of files to a kotlin file with const vals of file contents

Description

A script to read all files in a given directory and convert their content to kotlin's const val file_name = """file content"""

Running

The script expects kotlinc to be on the path.

  1. Download the dirToKt.kts file
  2. Make it executable chmod +x dirToKt.kts
  3. Run is like any other script ./dirToKt.kts [targetDirectory] [outputFile]

Alternatively you could run it with kotlinc directly: kotlinc -script dirToKt.kts [targetDirectory] [outputFile]

#!/usr/bin/env kotlinc -script
import java.io.File
import java.lang.IllegalArgumentException
fun File.forEachFileRecursively(action: (File) -> Unit) {
if (isDirectory) {
listFiles().forEach { it.forEachFileRecursively(action) }
} else {
action(this)
}
}
val rootDir = File(runCatching { args[0] }.getOrElse { throw IllegalAccessException("Missing target directory argument at position [0]") })
val outFile = File(runCatching { args[1] }.getOrElse { throw IllegalArgumentException("Missing output file argument at position [1]") }).apply(File::delete)
val illegalValNameCharacterRegex = "([\\\\\\/-]|\\.|,| )".toRegex()
rootDir.forEachFileRecursively {
if(it.canonicalPath != outFile.canonicalPath) {
val name = it.relativeTo(rootDir).path.replace(illegalValNameCharacterRegex, "_")
val content = it.readText()
outFile.appendText("\nconst val $name = \"\"\"$content\"\"\"\n")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment