Skip to content

Commit

Permalink
First try supporting annotation processors.
Browse files Browse the repository at this point in the history
See discussion in bazeltools#62
  • Loading branch information
greggdonovan committed Nov 2, 2017
1 parent 7d89b39 commit cc424ec
Show file tree
Hide file tree
Showing 10 changed files with 124 additions and 18 deletions.
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,42 @@ Each group id can only appear once, so you should collocate dependencies by grou
we are using does not fail on duplicate keys, it just takes the last one, so watch out. It would be good
to fix that, but writing a new yaml parser is out of scope.

A target may also optionally add `processorClasses` to a dependency. This is for [annotation processors](https://docs.oracle.com/javase/8/docs/api/javax/annotation/processing/Processor.html).
`bazel-deps` will generate a `java_library` and a `java_plugin` for each annotation processor defined. For example, we can define Google's auto-value annotation processor via:
```
dependencies:
com.google.auto.value:
auto-value:
version: "1.5"
lang: java
processorClasses: ["com.google.auto.value.processor.AutoValueProcessor"]
```
This will yield the following:
```
java_library(
name = "auto_value",
exported_plugins = [
":auto_value_plugin",
],
visibility = [
"//visibility:public",
],
exports = [
"//external:jar/com/google/auto/value/auto_value",
],
)
java_plugin(
name = "auto_value_plugin",
processor_class = "com.google.auto.value.processor.AutoValueProcessor",
deps = [
"//external:jar/com/google/auto/value/auto_value",
],
)
```
If there is only a single `processorClasses` defined, the `java_plugin` rule is named `<java_library_name>_plugin`. If there are multiple
`processorClasses` defined, each one is named `<java_library_name>_plugin_<processor_class_to_snake_case>`.

### <a name="options">Options</a>
In the options we set:

Expand Down
3 changes: 2 additions & 1 deletion src/scala/com/github/johnynek/bazel_deps/Decoders.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import io.circe.generic.auto

object Decoders {
implicit val versionDecoder: Decoder[Version] = stringWrapper(Version(_))
implicit val processorClassDecoder: Decoder[ProcessorClass] = stringWrapper(ProcessorClass(_))
implicit val subprojDecoder: Decoder[Subproject] = stringWrapper(Subproject(_))
implicit val dirnameDecoder: Decoder[DirectoryName] = stringWrapper(DirectoryName(_))
implicit val targetDecoder: Decoder[BazelTarget] = stringWrapper(BazelTarget(_))
Expand Down Expand Up @@ -129,4 +130,4 @@ object Decoders {

private def stringWrapper[T](fn: String => T): Decoder[T] =
Decoder.decodeString.map(fn)
}
}
13 changes: 9 additions & 4 deletions src/scala/com/github/johnynek/bazel_deps/DepsModel.scala
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ case class MavenServer(id: String, contentType: String, url: String) {
List(("id", quoteDoc(id)), ("type", quoteDoc(contentType)), ("url", Doc.text(url))))
}
case class ResolvedSha1Value(sha1Value: Sha1Value, serverId: String)
case class ProcessorClass(asString: String)

object Version {
private def isNum(c: Char): Boolean =
Expand Down Expand Up @@ -276,7 +277,7 @@ case class MavenCoordinate(group: MavenGroup, artifact: MavenArtifactId, version
def toDependencies(l: Language): Dependencies =
Dependencies(Map(group ->
Map(ArtifactOrProject(artifact.asString) ->
ProjectRecord(l, Some(version), None, None, None))))
ProjectRecord(l, Some(version), None, None, None, None))))
}

object MavenCoordinate {
Expand Down Expand Up @@ -412,12 +413,13 @@ case class ProjectRecord(
version: Option[Version],
modules: Option[Set[Subproject]],
exports: Option[Set[(MavenGroup, ArtifactOrProject)]],
exclude: Option[Set[(MavenGroup, ArtifactOrProject)]]) {
exclude: Option[Set[(MavenGroup, ArtifactOrProject)]],
processorClasses: Option[Set[ProcessorClass]]) {


// Cache this
override lazy val hashCode: Int =
(lang, version, modules, exports, exports).hashCode
(lang, version, modules, exports, exclude, processorClasses).hashCode

def flatten(ap: ArtifactOrProject): List[(ArtifactOrProject, ProjectRecord)] =
getModules match {
Expand Down Expand Up @@ -493,7 +495,10 @@ case class ProjectRecord(
exports.toList.map { ms =>
("exports", exportsDoc(ms)) },
exclude.toList.map { ms =>
("exclude", exportsDoc(ms)) })
("exclude", exportsDoc(ms)) },
processorClasses.toList.map { pcs =>
("processorClasses", list(pcs.toList.sortBy(_.asString)) { pc => quoteDoc(pc.asString) }) }
)
.flatten
.sortBy(_._1)
packedYamlMap(record)
Expand Down
42 changes: 35 additions & 7 deletions src/scala/com/github/johnynek/bazel_deps/Target.scala
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ case class Target(
deps: Set[Label] = Set.empty,
sources: Target.SourceList = Target.SourceList.Empty,
exports: Set[Label] = Set.empty,
runtimeDeps: Set[Label] = Set.empty) {
runtimeDeps: Set[Label] = Set.empty,
processorClasses: Set[ProcessorClass] = Set.empty) {

def toDoc: Doc = {
import Target._
Expand All @@ -76,25 +77,52 @@ case class Target(

val targetType = Doc.text(s"${langName}_${kind}")

def sortKeys(items: List[(String, Doc)]): Doc = {
def sortKeys(tt: Doc, name: String, items: List[(String, Doc)]): Doc = {
// everything has a name
val nm = ("name", quote(name.name))
val nm = ("name", quote(name))
implicit val ordDoc: Ordering[Doc] = Ordering.by { d: Doc => d.renderWideStream.mkString }
val sorted = items.collect { case (s, d) if !(d.isEmpty) => (s, d) }.sorted

renderList(targetType + Doc.text("("), nm :: sorted, Doc.text(")")) { case (k, v) =>
renderList(tt + Doc.text("("), nm :: sorted, Doc.text(")")) { case (k, v) =>
k +: " = " +: v
} + Doc.line.repeat(2)
} + Doc.line
}

def labelList(ls: Set[Label]): Doc =
renderList(Doc.text("["), ls.toList.map(_.asStringFrom(name.path)).sorted, Doc.text("]"))(quote)

sortKeys(List(
def renderExportedPlugins(pcs: Set[ProcessorClass]): Doc = {
renderList(Doc.text("["), pcs.toList.map(pc => ":" + getPluginTargetName(pcs, pc)).sorted, Doc.text("]"))(quote)
}
def getPluginTargetName(pcs: Set[ProcessorClass], processorClass: ProcessorClass) =
if (pcs.size == 1) s"${name.name}_plugin"
else {
val fqnToSnakeCase = camel2Underscore(shortName(processorClass.asString))
s"${name.name}_plugin_$fqnToSnakeCase"
}
def camel2Underscore(text: String) = text.drop(1).foldLeft(text.headOption.map(_.toLower + "") getOrElse "") {
case (acc, c) if c.isUpper => acc + "_" + c.toLower
case (acc, c) if c == '$' => acc
case (acc, c) => acc + c
}
def shortName(fqn: String) = if (fqn.contains(".")) fqn.substring(fqn.lastIndexOf('.') + 1) else fqn
def renderPlugins(pcs: Set[ProcessorClass], exports: Set[Label]): Doc = {
if (pcs.isEmpty) Doc.empty
else processorClasses.toList.map(renderPlugin(pcs, _, exports)).reduce((d1, d2) => d1 + d2)
}
def renderPlugin(pcs: Set[ProcessorClass], pc: ProcessorClass, exports: Set[Label]): Doc =
sortKeys(Doc.text("java_plugin"), getPluginTargetName(pcs, pc), List(
"deps" -> labelList(exports),
"processor_class" -> quote(pc.asString)
)) + Doc.line

sortKeys(targetType, name.name, List(
"visibility" -> renderList(Doc.text("["), List("//visibility:public"), Doc.text("]"))(quote),
"deps" -> labelList(deps),
"srcs" -> sources.render,
"exports" -> labelList(exports),
"runtime_deps" -> labelList(runtimeDeps)))
"runtime_deps" -> labelList(runtimeDeps),
"exported_plugins" -> renderExportedPlugins(processorClasses)
)) + renderPlugins(processorClasses, exports) + Doc.line
}
}
8 changes: 7 additions & 1 deletion src/scala/com/github/johnynek/bazel_deps/Writer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -213,10 +213,16 @@ object Writer {
Target(lang,
Label.localTarget(pathInRoot, u, lang),
exports = exports ++ uvexports,
runtimeDeps = runtime_deps -- uvexports)
runtimeDeps = runtime_deps -- uvexports,
processorClasses = getProcessorClasses(u))
})
def targetFor(u: UnversionedCoordinate): Target =
replacedTarget(u).getOrElse(coordToTarget(u))
def getProcessorClasses(u: UnversionedCoordinate): Set[ProcessorClass] = {
val m: Option[Map[ArtifactOrProject, ProjectRecord]] = model.dependencies.toMap.get(u.group)
val projectRecord: Option[ProjectRecord] = m.flatMap(_.get(ArtifactOrProject(u.artifact.asString)))
projectRecord.flatMap(_.processorClasses).getOrElse(Set.empty)
}

Right(allUnversioned.iterator.map(targetFor).toList)
}
Expand Down
1 change: 1 addition & 0 deletions src/scala/com/github/johnynek/bazel_deps/maven/Tool.scala
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ object Tool {
Some(Version(d.version)),
None,
None,
None,
None))
}
.toList
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ object ModelGenerators {
m <- Gen.option(Gen.listOfN(sub, subprojGen).map(_.toSet))
exports <- Gen.option(Gen.listOfN(exp, join(mavenGroupGen, artifactOrProjGen)).map(_.toSet))
exclude <- Gen.option(Gen.listOfN(exc, join(mavenGroupGen, artifactOrProjGen)).map(_.toSet))
} yield ProjectRecord(lang, v, m, exports, exclude)
processorClasses <- Gen.option(Gen.listOfN(5, ProcessorClass("")).map(_.toSet)) // TODO(ggg)
} yield ProjectRecord(lang, v, m, exports, exclude, processorClasses)

def depGen(o: Options): Gen[Dependencies] = {
val (l1, ls) = o.getLanguages match {
Expand Down
2 changes: 1 addition & 1 deletion test/scala/com/github/johnynek/bazel_deps/ModelTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class ModelTest extends FunSuite {
val lang = Language.Scala.default
val deps = Dependencies(Map(
MavenGroup("com.twitter") -> Map(
ArtifactOrProject("finagle") -> ProjectRecord(lang, Some(Version("0.1")), Some(Set(Subproject(""), Subproject("core"))), None, None)
ArtifactOrProject("finagle") -> ProjectRecord(lang, Some(Version("0.1")), Some(Set(Subproject(""), Subproject("core"))), None, None, None)
)
))

Expand Down
32 changes: 30 additions & 2 deletions test/scala/com/github/johnynek/bazel_deps/ParseTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class ParseTest extends FunSuite {
Some(Version("0.16.0")),
Some(Set("core", "args", "date").map(Subproject(_))),
None,
None,
None))),
None,
None)))
Expand Down Expand Up @@ -56,6 +57,7 @@ class ParseTest extends FunSuite {
Some(Version("0.16.0")),
Some(Set("core", "args", "date").map(Subproject(_))),
None,
None,
None))),
None,
Some(
Expand Down Expand Up @@ -92,8 +94,8 @@ class ParseTest extends FunSuite {
Some(Version("0.16.0")),
Some(Set("", "core", "args", "date").map(Subproject(_))),
None,
None
))),
None,
None))),
None,
Some(
Options(
Expand All @@ -109,6 +111,32 @@ class ParseTest extends FunSuite {
assert(MavenArtifactId(ArtifactOrProject("a"), Subproject("")).asString === "a")
assert(MavenArtifactId(ArtifactOrProject("a"), Subproject("b")).asString === "a-b")
}


test("parse a file with an annotationProcessor defined") {
val str = """dependencies:
| com.google.auto.value:
| auto-value:
| version: "1.5"
| lang: java
| processorClasses: ["com.google.auto.value.processor.AutoValueProcessor"]
|""".stripMargin('|')

assert(Decoders.decodeModel(Yaml, str) ==
Right(Model(
Dependencies(
MavenGroup("com.google.auto.value") ->
Map(ArtifactOrProject("auto-value") ->
ProjectRecord(
Language.Java,
Some(Version("1.5")),
None,
None,
None,
Some(Set(ProcessorClass("com.google.auto.value.processor.AutoValueProcessor")))))),
None,
None)))
}
/*
* TODO make this test pass
* see: https:/johnynek/bazel-deps/issues/15
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class ParseTestCasesTest extends FunSuite {
Map(
MavenGroup("n2rr") ->
Map(
ArtifactOrProject("zmup") -> ProjectRecord(Java,Some(Version("019")),Some(Set(Subproject("wcv"))),Some(Set((MavenGroup("j9szw4"),ArtifactOrProject("i")))),None)
ArtifactOrProject("zmup") -> ProjectRecord(Java,Some(Version("019")),Some(Set(Subproject("wcv"))),Some(Set((MavenGroup("j9szw4"),ArtifactOrProject("i")))),None,None)
)
)),Some(Replacements(Map())),None)

Expand Down

0 comments on commit cc424ec

Please sign in to comment.