Skip to content

Commit

Permalink
Disable code generator for files with only package-scoped options
Browse files Browse the repository at this point in the history
  • Loading branch information
thesamet committed Jan 30, 2021
1 parent d998b26 commit fc40883
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -976,6 +976,18 @@ class DescriptorImplicits private[compiler] (
file.getMessageTypes.asScala.foreach(visitMessage)
messages.result()
}

// Disable generating code when protobuf has package-scoped options and is
// otherwise empty. This is meant to allow users to add proto files with only
// package-scoped options as *source* files in their protoc command line, without
// worrying of duplicate source code being generated.
def disableOutput: Boolean =
(scalaOptions.getScope == Scalapb.ScalaPbOptions.OptionsScope.PACKAGE) &&
file.getEnumTypes().isEmpty &&
file.getMessageTypes().isEmpty() &&
file.getServices().isEmpty &&
file.getExtensions().isEmpty() &&
scalaOptions.getPreambleList().isEmpty()
}

private def allCapsToCamelCase(name: String, upperInitial: Boolean): String = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1669,7 +1669,7 @@ object ProtobufGenerator {
val validator = new ProtoValidation(implicits)
validator.validateFiles(request.allProtos)
import implicits.FileDescriptorPimp
val files = request.filesToGenerate.flatMap { file =>
val files = request.filesToGenerate.filterNot(_.disableOutput).flatMap { file =>
if (file.scalaOptions.getSingleFile)
generator.generateSingleScalaFileForFileDescriptor(file)
else generator.generateMultipleScalaFilesForFileDescriptor(file)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,30 @@ class DescriptorImplicitsSpec extends AnyFlatSpec with Matchers with ProtocInvoc
.scalaType
.fullName must be("outside.outside.C")
}

"disableOutput" should "be set for package option files" in {
val files = generateFileSet(base)
val implicits = new DescriptorImplicits(
GeneratorParams(flatPackage = false),
files,
SecondaryOutputProvider.empty
)
import implicits._

files
.find(_.getFullName() == "disable_flat.proto")
.get
.disableOutput must be(true)

files
.find(_.getFullName() == "enable_flat.proto")
.get
.disableOutput must be(false) // has a message Foo

files
.find(_.getFullName() == "inside_disable_flat.proto")
.get
.disableOutput must be(false)

}
}

0 comments on commit fc40883

Please sign in to comment.