Skip to content

Instantly share code, notes, and snippets.

@jrudolph
Last active August 29, 2015 14:01
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jrudolph/646fb5360ad0b2c79def to your computer and use it in GitHub Desktop.
Save jrudolph/646fb5360ad0b2c79def to your computer and use it in GitHub Desktop.
Simple script to update copyright headers
import java.io.{ FileOutputStream, File }
import scala.io.Source
import scala.util.matching.Regex
object UpdateCopyrightHeaders extends App {
val encoding = "utf-8"
val copyrightLines: Seq[String] = "Copyright (C) 1894-2014 Example Corp. <http://www.example.com>".split("\n")
val srcDir = new File("src/")
def updateCopyright(file: File): Unit = {
val contents = Source.fromFile(file, encoding).mkString
val newContents = updateCopyright(contents)
if (newContents != contents) {
val newFile = File.createTempFile("copyrighted", ".txt")
val os = new FileOutputStream(newFile)
os.write(newContents.getBytes(encoding))
os.close()
newFile.renameTo(file)
}
}
val formattedCopyrightLines = "/**\n" + Regex.quoteReplacement(copyrightLines.map(" * " + _).mkString("\n")) + "\n */\n\n$2"
// matches zero or one comment starting with "/*" or "/**" at the start of a string
val MaybeComment = """^(?s:(\s*/\*(?:(?!\*/).)*\*/\n{0,2})?(\s*.*))""".r
def updateCopyright(content: String): String =
MaybeComment.replaceAllIn(content, formattedCopyrightLines)
def recursiveFilesIn(filter: File ⇒ Boolean)(dir: File): Seq[File] =
if (dir.getName != ".." && dir.getName != ".") {
val (dirs, files) = dir.listFiles().partition(_.isDirectory)
files.filter(filter).toVector ++ dirs.flatMap(recursiveFilesIn(filter))
} else Vector.empty
def withExtension(ext: String): File ⇒ Boolean = _.getName.endsWith(s".$ext")
implicit class AddPredicateOps[T](val f: T ⇒ Boolean) extends AnyVal {
def ||(g: T ⇒ Boolean): T ⇒ Boolean = t ⇒ f(t) || g(t)
}
recursiveFilesIn(withExtension("scala") || withExtension("java"))(srcDir).foreach(updateCopyright)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment