Implement Bazel build

TEST PLAN:
  $ bazel test gitiles-servlet/...

Run debug version:
  $ sh {path/to/src}/tools/run_bazel_dev.sh

TODO:

 * publishing maven artifacts.
 * check out Bazel's generate_workspace.
 * intellij/eclipse project generation

Change-Id: I288011ce622536ce72c59a1961f962db9fe9e761
diff --git a/gitiles-servlet/junit.bzl b/gitiles-servlet/junit.bzl
new file mode 100644
index 0000000..ee79637
--- /dev/null
+++ b/gitiles-servlet/junit.bzl
@@ -0,0 +1,60 @@
+# skylark rule to generate a Junit4 TestSuite
+# Assumes srcs are all .java Test files
+# Assumes junit4 is already added to deps by the user.
+
+# See https://github.com/bazelbuild/bazel/issues/1017 for background.
+
+_OUTPUT = """import org.junit.runners.Suite;
+import org.junit.runner.RunWith;
+
+@RunWith(Suite.class)
[email protected]({%s})
+public class %s {}
+"""
+
+_PREFIXES = ("org", "com", "edu")
+
+def _SafeIndex(l, val):
+    for i, v in enumerate(l):
+        if val == v:
+            return i
+    return -1
+
+def _AsClassName(fname):
+    fname = [x.path for x in fname.files][0]
+    toks = fname[:-5].split("/")
+    findex = -1
+    for s in _PREFIXES:
+        findex = _SafeIndex(toks, s)
+        if findex != -1:
+            break
+    if findex == -1:
+        fail("%s does not contain any of %s",
+                         fname, _PREFIXES)
+    return ".".join(toks[findex:]) + ".class"
+
+def _impl(ctx):
+    classes = ",".join(
+        [_AsClassName(x) for x in ctx.attr.srcs])
+    ctx.file_action(output=ctx.outputs.out, content=_OUTPUT % (
+            classes, ctx.attr.outname))
+
+_GenSuite = rule(
+    attrs = {
+        "srcs": attr.label_list(allow_files = True),
+        "outname": attr.string(),
+    },
+    outputs = {"out": "%{name}.java"},
+    implementation = _impl,
+)
+
+def junit_tests(name, srcs, **kwargs):
+    s_name = name + "TestSuite"
+    j_name = s_name + ".java",
+    _GenSuite(name=s_name,
+              srcs=srcs,
+              outname=s_name)
+    native.java_test(name=name,
+                     test_class=s_name,
+                     srcs = srcs + [":"+s_name],
+                     **kwargs)