Skip to content

Instantly share code, notes, and snippets.

@schmmd
Created May 7, 2014 16:54
Show Gist options
  • Save schmmd/a8bb248eae86d1332d72 to your computer and use it in GitHub Desktop.
Save schmmd/a8bb248eae86d1332d72 to your computer and use it in GitHub Desktop.
Scalariform Precommit
#!/bin/sh
exec scala -savecompiled "$0" $@
!#
//
// Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
// Modified 2014 AI2 <http://www.allenai.org>
//
// This script will check that the commit is correctly formatted. It only checks files that are to be committed.
// To be run this file should be at `.git/hooks/pre-commit`.
import scala.sys.process._
import java.io.File
def color(color: String, msg: String) = color + msg + Console.RESET
def log(level: String, msg: String) = println("[" + level + "] " + msg)
def info(msg: String) = log("info", msg)
def error(msg: String) = log(color(Console.RED, "error"), msg)
def success(msg: String) = log(color(Console.GREEN, "success"), msg)
info("Running formatting pre commit hook...")
// Get a list of all Scala source files in the main project that are staged to be committed.
def status = "git status -s".!!.split("\r?\n").toSeq
val stagedFiles = status
.filter(_.headOption.map(_ != ' ').getOrElse(false))
.map(_.drop(3).takeWhile(_ != ' '))
.filter(_.endsWith(".scala"))
if (stagedFiles.isEmpty) {
info("No staged scala files in main project to check")
} else {
// Run scalariform and see if anything changes
val rt = Process(Seq("sbt", "scalariformFormat")) ! ProcessLogger { s =>
// Ignore final success line
if (!s.contains("success")) {
println(s)
}
}
if (rt > 0) {
System.exit(rt)
}
// Get a list of all the unstaged changes
val unstagedChangedFiles = status
.filter(_.charAt(1) != ' ')
.map(_.drop(3).takeWhile(_ != ' ')).toSet
val changedStagedFiles = stagedFiles.filter(unstagedChangedFiles)
if (!changedStagedFiles.isEmpty) {
error("Scalariform check failed")
error("The following staged files were modified after running scalariform:")
changedStagedFiles.foreach(f => println(" " + f))
System.exit(1)
}
}
success("Pre-commit hook passed")
System.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment