Skip to content

Instantly share code, notes, and snippets.

@swankjesse
Created February 17, 2018 16:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swankjesse/7952d0c54efc2701fe6fc0bc184549cc to your computer and use it in GitHub Desktop.
Save swankjesse/7952d0c54efc2701fe6fc0bc184549cc to your computer and use it in GitHub Desktop.
package com.squareup.refmt
import okio.Okio
import java.io.File
fun main(args: Array<String>) {
val directory = File(args[0])
Reformatter().reformatDirectory(directory)
}
class Reformatter {
fun reformatDirectory(directory: File, indent: String = "") {
if (directory.name.startsWith(".")) return // .git, .gradle, .idea
println("${indent}reformatting ${directory.name}/")
for (child in directory.listFiles()) {
if (child.isDirectory) {
reformatDirectory(child, indent + " ")
} else if (child.name.endsWith(".kt")) {
reformatKotlin(child, indent + " ")
}
}
}
private fun reformatKotlin(file: File, indent: String) {
println("${indent}reformatting ${file.name}")
val reformatted = File("${file}_reformatted")
Okio.buffer(Okio.sink(reformatted)).use { sink ->
Okio.buffer(Okio.source(file)).use { source ->
while (true) {
val line = source.readUtf8Line() ?: break
sink.writeUtf8(reformatLine(line))
sink.writeUtf8("\n")
}
}
}
reformatted.renameTo(file)
}
private fun reformatLine(line: String): String {
var spaceCount = 0
for (c in 0 until line.length) {
if (line[c] == ' ') {
spaceCount++
} else {
break
}
}
return line.substring(spaceCount / 2)
}
}
@swankjesse
Copy link
Author

I created a shell script called reformat_misk that runs the above on the current working directory. Then I run it like so to reformat a given branch. Running in on --all will reformat everything!

git filter-branch  -f  --tree-filter reformat_misk -- master_reformatted

@ryanhall07
Copy link

cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment