Skip to content

Copy the protos we need into a temp folder #848

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions src/scala/scripts/PBGenerateRequest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@ case class PBGenerateRequest(jarOutput: String, scalaPBOutput: Path, scalaPBArgs

object PBGenerateRequest {

def from(args: java.util.List[String]): PBGenerateRequest = {
def from(tmpDir: Path)(args: java.util.List[String]): PBGenerateRequest = {
val jarOutput = args.get(0)
val protoFiles = args.get(4).split(':')
val protoFilesToBuild = protoFiles.map { e => s"${tmpDir.toFile.toString}/$e"}

val includedProto = args.get(1).drop(1).split(':').distinct.map { e =>
val p = e.split(',')
// If its an empty string then it means we are local to the current repo for the key, no op
(Some(p(0)).filter(_.nonEmpty), p(1))
}.collect {
// if the to compile files contains this absolute path then we are compiling it and shoudln't try move it around(duplicate files.)
case (Some(k), v) if !protoFiles.contains(v) => (Paths.get(k), Paths.get(v))
}.toList
val absolutePath = Some(p(0)).filter(_.nonEmpty).getOrElse(p(1))
(Paths.get(absolutePath), Paths.get(p(1)))
}.toList ++ protoFiles.map { p => (Paths.get(p), Paths.get(p))}

val flagOpt = args.get(2) match {
case "-" => None
Expand All @@ -27,7 +27,7 @@ object PBGenerateRequest {
case "-" => Nil
case s if s.charAt(0) == '-' => s.tail.split(':').toList //drop padding character
case other => sys.error(s"expected a padding character of - (dash), but found: $other")
}) ++ List(".")
}) ++ List("")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

::: List("") I think is a bit more efficient on lists than ++ but maybe not...


val tmp = Paths.get(Option(System.getProperty("java.io.tmpdir")).getOrElse("/tmp"))
val scalaPBOutput = Files.createTempDirectory(tmp, "bazelscalapb")
Expand All @@ -43,15 +43,16 @@ object PBGenerateRequest {
}.toList


val scalaPBArgs = outputSettings ::: (padWithProtoPathPrefix(transitiveProtoPaths) ++ protoFiles)
val scalaPBArgs = outputSettings ::: (padWithProtoPathPrefix(tmpDir)(transitiveProtoPaths) ++ protoFilesToBuild)

val protoc = Paths.get(args.get(5))

val extraJars = args.get(7).drop(1).split(':').filter(_.nonEmpty).distinct.map {e => Paths.get(e)}.toList

new PBGenerateRequest(jarOutput, scalaPBOutput, scalaPBArgs, includedProto, protoc, namedGenerators, extraJars)
}

private def padWithProtoPathPrefix(transitiveProtoPathFlags: List[String]) =
transitiveProtoPathFlags.map("--proto_path="+_)
private def padWithProtoPathPrefix(tmpDir: Path)(transitiveProtoPathFlags: List[String]) =
transitiveProtoPathFlags.map(s"--proto_path=${tmpDir.toFile.toString}/"+_).map(_.stripSuffix("."))

}
32 changes: 23 additions & 9 deletions src/scala/scripts/ScalaPBGenerator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,16 @@ object ScalaPBWorker extends GenericWorker(new ScalaPBGenerator) {
}

class ScalaPBGenerator extends Processor {
def setupIncludedProto(includedProto: List[(Path, Path)]): Unit = {
def setupIncludedProto(tmpRoot: Path, includedProto: List[(Path, Path)]): Unit = {
includedProto.foreach { case (root, fullPath) =>
require(fullPath.toFile.exists, s"Path $fullPath does not exist, which it should as a dependency of this rule")
val relativePath = root.relativize(fullPath)
val relativePath = if(root == fullPath) fullPath else root.relativize(fullPath)
val targetPath = tmpRoot.resolve(relativePath)

relativePath.toFile.getParentFile.mkdirs
Try(Files.copy(fullPath, relativePath)) match {
targetPath.toFile.getParentFile.mkdirs
Try(Files.copy(fullPath, targetPath)) match {
case Failure(err: FileAlreadyExistsException) =>
Console.println(s"File already exists, skipping: ${err.getMessage}")
Console.println(s"File already exists, skipping copy from $fullPath to $targetPath: ${err.getMessage}")
case Failure(err) => throw err
case _ => ()
}
Expand All @@ -55,8 +56,10 @@ class ScalaPBGenerator extends Processor {
}

def processRequest(args: java.util.List[String]) {
val extractRequestResult = PBGenerateRequest.from(args)
setupIncludedProto(extractRequestResult.includedProto)
val tmpRoot = Files.createTempDirectory("proto_builder")

val extractRequestResult = PBGenerateRequest.from(tmpRoot)(args)
setupIncludedProto(tmpRoot, extractRequestResult.includedProto)

val extraClassesClassLoader = new URLClassLoader(extractRequestResult.extraJars.map { e =>
val f = e.toFile
Expand Down Expand Up @@ -89,10 +92,21 @@ class ScalaPBGenerator extends Processor {
}
JarCreator.buildJar(Array(extractRequestResult.jarOutput, extractRequestResult.scalaPBOutput.toString))
} finally {
deleteDir(tmpRoot)
deleteDir(extractRequestResult.scalaPBOutput)
}
}

protected def exec(protoc: Path): Seq[String] => Int = (args: Seq[String]) =>
new ProcessBuilder(protoc.toString +: args: _*).inheritIO().start().waitFor()
protected def exec(protoc: Path): Seq[String] => Int = (args: Seq[String]) => {
val tmpFile = Files.createTempFile("stdout", "log")
try {
val ret = new ProcessBuilder(protoc.toString +: args: _*).redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.to(tmpFile.toFile)).start().waitFor()
Try {
scala.io.Source.fromFile(tmpFile.toFile).getLines.foreach{System.out.println}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this looks like debug. Can we remove?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is how we get the stdout/stderr from protoc into the bazel output stream. So can't remove.

(prior to this PR any failure in protoc would result in just seeing a message that it exited with code 1 and no further info)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh yeah... I overlooked that. nit: can we do foreach(System.out.println) (use parens rather than {} when passing a method as a function argument)?

}
ret
} finally {
tmpFile.toFile.delete
}
}
}