Skip to content

Commit a5bad89

Browse files
minor optimization (#554)
1 parent 12cac0b commit a5bad89

File tree

8 files changed

+77
-74
lines changed

8 files changed

+77
-74
lines changed

plugins/sbt/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,4 +78,4 @@ Please refer to [Codegen Options](../../docs/codegen-options.md)
7878

7979
> in sbt plugin option
8080
- `packageName` was rename to `generatePackageName`
81-
- `generateCodegenTargetPath` can be used for setting codegen path where code have bean created by task `graphqlCodegen`, since 3.0.0 .
81+
- `generateCodegenTargetPath` Where to store generated files and add the generated code to the classpath, so that they can be referenced. since 3.0.0 .

plugins/sbt/graphql-java-codegen-sbt-plugin/build.sbt

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import sbtrelease.ReleaseStateTransformations._
33
name := "graphql-codegen-sbt-plugin"
44
// must be equals to oss Group Id
55
organization := "io.github.jxnu-liguobin"
6-
val jValidationVersion = settingKey[String]("default java Validation api")
6+
val jValidationVersion = settingKey[String]("default java Validation api").withRank(KeyRanks.Invisible)
77
jValidationVersion := "2.0.1.Final"
88

99
// keep version is equals with parent project `graphql-java-codegen`.
@@ -13,7 +13,6 @@ lazy val `graphql-codegen-sbt-plugin` = Project(id = "graphql-codegen-sbt-plugin
1313
settings(Publishing.publishSettings).
1414
settings(
1515
sbtPlugin := true,
16-
scalaVersion := "2.12.12",
1716
scriptedBufferLog := false,
1817
scriptedLaunchOpts += s"-Dplugin.version=${version.value}",
1918
scalacOptions += "-target:jvm-1.8",
@@ -34,6 +33,6 @@ lazy val `graphql-codegen-sbt-plugin` = Project(id = "graphql-codegen-sbt-plugin
3433
libraryDependencies ++= Seq(
3534
"io.github.kobylynskyi" % "graphql-java-codegen" % (version in ThisBuild).value
3635
),
37-
buildInfoKeys := Seq[BuildInfoKey](name, version, scalaVersion, sbtVersion, jValidationVersion),
36+
buildInfoKeys := Seq[BuildInfoKey](name, version, sbtVersion, jValidationVersion),
3837
buildInfoPackage := "io.github.dreamylost.graphql.codegen"
3938
)
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
sbt.version = 1.3.12
1+
sbt.version = 1.4.7

plugins/sbt/graphql-java-codegen-sbt-plugin/src/main/scala/io/github/dreamylost/graphql/codegen/GraphQLCodegenKeys.scala

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ trait GraphQLCodegenKeys {
8787

8888
val graphqlSchemas = settingKey[SchemaFinderConfig]("graphqlSchemas")
8989

90-
val outputDir = settingKey[File]("outputDir")
90+
val outputDir = settingKey[File]("Where to store generated files")
9191

9292
val graphqlSchemaPaths = settingKey[Seq[String]]("Locations of GraphQL schemas.")
9393

@@ -124,6 +124,7 @@ trait GraphQLCodegenKeys {
124124
val javaxValidationApiVersion = settingKey[Option[String]]("javax-validation-api version")
125125
val graphqlJavaCodegenVersion = settingKey[Option[String]]("graphql java codegen version")
126126

127-
val generateCodegenTargetPath = settingKey[File]("The path for graphqlCodegen to save code which generate by plugin")
127+
//some others for sbt
128+
val generateCodegenTargetPath = settingKey[File]("Where to store generated files and add the generated code to the classpath, so that they can be referenced.")
128129

129130
}

plugins/sbt/graphql-java-codegen-sbt-plugin/src/main/scala/io/github/dreamylost/graphql/codegen/GraphQLCodegenPlugin.scala

Lines changed: 67 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
11
package io.github.dreamylost.graphql.codegen
22

3-
import java.nio.file.{ Path, Paths }
4-
import java.util
5-
63
import com.kobylynskyi.graphql.codegen.GraphQLCodegenValidate
74
import com.kobylynskyi.graphql.codegen.java.JavaGraphQLCodegen
85
import com.kobylynskyi.graphql.codegen.model._
96
import com.kobylynskyi.graphql.codegen.model.exception.LanguageNotSupportedException
107
import com.kobylynskyi.graphql.codegen.model.GeneratedLanguage._
118
import com.kobylynskyi.graphql.codegen.scala.ScalaGraphQLCodegen
129
import com.kobylynskyi.graphql.codegen.supplier.{ JsonMappingConfigSupplier, SchemaFinder }
13-
import sbt.{ AutoPlugin, Def, PluginTrigger, _ }
10+
import sbt.{ AutoPlugin, PluginTrigger, _ }
1411
import sbt.Keys.{ sLog, sourceManaged, _ }
1512
import sbt.internal.util.complete.DefaultParsers.spaceDelimited
1613

14+
import java.nio.file.{ Path, Paths }
15+
import java.util.{ HashMap => JHashMap, HashSet => JHashSet, List => JList }
1716
import scala.collection.JavaConverters._
17+
import sbt.Def
1818

1919
/**
2020
*
@@ -29,13 +29,11 @@ object GraphQLCodegenPlugin extends GraphQLCodegenPlugin(Compile, configurationP
2929
class GraphQLCodegenPlugin(configuration: Configuration, private[codegen] val configurationPostfix: String = "") extends AutoPlugin with Compat {
3030
self =>
3131

32-
//override this by graphqlJavaCodegenVersion and javaxValidationApiVersion
3332
private val jValidation = BuildInfo.jValidationVersion
3433
private val codegen = BuildInfo.version
3534

3635
object GlobalImport extends GraphQLCodegenKeys {
3736

38-
//should look for a way to automatically add to the classpath
3937
lazy val GraphQLCodegenPluginDependencies: Def.Setting[Seq[ModuleID]] = libraryDependencies ++= Seq(
4038
"javax.validation" % "validation-api" % javaxValidationApiVersion.value.getOrElse(jValidation),
4139
"io.github.kobylynskyi" % "graphql-java-codegen" % graphqlJavaCodegenVersion.value.getOrElse(codegen)
@@ -48,8 +46,6 @@ class GraphQLCodegenPlugin(configuration: Configuration, private[codegen] val co
4846

4947
}
5048

51-
//no Auto trigger
52-
//Eventually I decided not to use auto trigger
5349
override def trigger: PluginTrigger = noTrigger
5450

5551
override def requires = sbt.plugins.JvmPlugin
@@ -59,21 +55,21 @@ class GraphQLCodegenPlugin(configuration: Configuration, private[codegen] val co
5955
import GlobalImport._
6056

6157
//With the implementation of some other plugins, initialization is not necessary,
62-
//but maybe should be related to the dependency of key. For convenience, this is a conservative operation
58+
//but maybe should be related to the dependency of key. For convenience, this is a conservative operation.
6359
override lazy val globalSettings: Seq[Def.Setting[_]] = Seq(
64-
generateModelOpenClasses := MappingConfigConstants.DEFAULT_GENERATE_MODEL_OPEN_CLASSES,
65-
generatedLanguage := MappingConfigConstants.DEFAULT_GENERATED_LANGUAGE,
6660
graphqlQueryIntrospectionResultPath := None,
6761
graphqlSchemas := schemaFinderConfig,
6862
jsonConfigurationFile := None,
6963
graphqlSchemaPaths := Seq.empty,
7064
graphqlSchemaValidate := Seq.empty,
71-
customTypesMapping := new util.HashMap[String, String](), //TODO use scala Map, convert to java Map
72-
customAnnotationsMapping := new util.HashMap[String, util.List[String]](),
73-
directiveAnnotationsMapping := new util.HashMap[String, util.List[String]](),
65+
customTypesMapping := new JHashMap[String, String](), //TODO use scala Map, convert to java Map
66+
customAnnotationsMapping := new JHashMap[String, JList[String]](),
67+
directiveAnnotationsMapping := new JHashMap[String, JList[String]](),
7468
javaxValidationApiVersion := None,
7569
graphqlJavaCodegenVersion := None,
7670
// suffix/prefix/strategies:
71+
generateModelOpenClasses := MappingConfigConstants.DEFAULT_GENERATE_MODEL_OPEN_CLASSES,
72+
generatedLanguage := MappingConfigConstants.DEFAULT_GENERATED_LANGUAGE,
7773
apiNamePrefix := None,
7874
apiNameSuffix := MappingConfigConstants.DEFAULT_RESOLVER_SUFFIX,
7975
apiRootInterfaceStrategy := ApiRootInterfaceStrategy.valueOf(MappingConfigConstants.DEFAULT_API_ROOT_INTERFACE_STRATEGY_STRING),
@@ -84,7 +80,7 @@ class GraphQLCodegenPlugin(configuration: Configuration, private[codegen] val co
8480
responseSuffix := MappingConfigConstants.DEFAULT_RESPONSE_SUFFIX,
8581
responseProjectionSuffix := MappingConfigConstants.DEFAULT_RESPONSE_PROJECTION_SUFFIX,
8682
parametrizedInputSuffix := MappingConfigConstants.DEFAULT_PARAMETRIZED_INPUT_SUFFIX,
87-
useObjectMapperForRequestSerialization := new util.HashSet[String](),
83+
useObjectMapperForRequestSerialization := new JHashSet[String](),
8884
typeResolverPrefix := None,
8985
typeResolverSuffix := MappingConfigConstants.DEFAULT_RESOLVER_SUFFIX,
9086
subscriptionReturnType := None,
@@ -100,8 +96,8 @@ class GraphQLCodegenPlugin(configuration: Configuration, private[codegen] val co
10096
apiPackageName := None,
10197
modelPackageName := None,
10298
// field resolvers configs:
103-
fieldsWithResolvers := new util.HashSet[String](),
104-
fieldsWithoutResolvers := new util.HashSet[String](),
99+
fieldsWithResolvers := new JHashSet[String](),
100+
fieldsWithoutResolvers := new JHashSet[String](),
105101
// various toggles:
106102
generateClient := MappingConfigConstants.DEFAULT_GENERATE_CLIENT,
107103
generateParameterizedFieldsResolvers := MappingConfigConstants.DEFAULT_GENERATE_PARAMETERIZED_FIELDS_RESOLVERS,
@@ -112,15 +108,14 @@ class GraphQLCodegenPlugin(configuration: Configuration, private[codegen] val co
112108
generateBuilder := MappingConfigConstants.DEFAULT_BUILDER,
113109
generateApis := MappingConfigConstants.DEFAULT_GENERATE_APIS,
114110
generateEqualsAndHashCode := MappingConfigConstants.DEFAULT_EQUALS_AND_HASHCODE,
115-
generateImmutableModels := MappingConfigConstants.DEFAULT_GENERATE_IMMUTABLE_MODELS,// TODO change default value
111+
generateImmutableModels := MappingConfigConstants.DEFAULT_GENERATE_IMMUTABLE_MODELS, // TODO change default value
116112
generateToString := MappingConfigConstants.DEFAULT_TO_STRING,
117113
// parent interfaces configs:
118114
parentInterfaces := parentInterfacesConfig,
119115
responseProjectionMaxDepth := MappingConfigConstants.DEFAULT_RESPONSE_PROJECTION_MAX_DEPTH
120116
)
121117

122-
private def getMappingConfig(): Def.Initialize[MappingConfig] = Def.setting[MappingConfig] {
123-
118+
private def getMappingConfig(): Def.Initialize[MappingConfig] = Def.setting {
124119
val mappingConfig = new MappingConfig
125120
mappingConfig.setPackageName((generatePackageName in GraphQLCodegenConfig).value.orNull)
126121
mappingConfig.setCustomTypesMapping((customTypesMapping in GraphQLCodegenConfig).value)
@@ -169,14 +164,15 @@ class GraphQLCodegenPlugin(configuration: Configuration, private[codegen] val co
169164
mappingConfig.setRelayConfig((relayConfig in GraphQLCodegenConfig).value)
170165
mappingConfig.setGeneratedLanguage((generatedLanguage in GraphQLCodegenConfig).value)
171166
mappingConfig.setGenerateModelOpenClasses((generateModelOpenClasses in GraphQLCodegenConfig).value)
172-
sLog.value.info(s"Version is <${BuildInfo.toString}>")
173167
mappingConfig
174168
}
175169

176170
override lazy val projectSettings: Seq[Def.Setting[_]] = inConfig(GraphQLCodegenConfig) {
177171
Seq(
172+
// `generateCodegenTargetPath` not support playframework, https://github.com/kobylynskyi/graphql-java-codegen/issues/551
173+
// There may be some problems that have not been found at present :)
178174
generateCodegenTargetPath := crossTarget.value / "src_managed_graphql",
179-
sourceManaged := (generateCodegenTargetPath in GraphQLCodegenConfig).value,
175+
sourceManaged := generateCodegenTargetPath.value,
180176
javaSource in configuration := (sourceManaged in GraphQLCodegenConfig).value,
181177
managedSourceDirectories in configuration ++= Seq((sourceManaged in GraphQLCodegenConfig).value),
182178
managedClasspath := {
@@ -187,93 +183,100 @@ class GraphQLCodegenPlugin(configuration: Configuration, private[codegen] val co
187183
if (!file.exists()) {
188184
file.mkdirs()
189185
}
190-
sLog.value.info(s"Default outputDir is <${file.getAbsolutePath}>")
186+
sLog.value.info(s"current outputDir: ${file.getAbsolutePath}")
191187
file
192-
}, //use validate that config in build.sbt
188+
},
193189
graphqlCodegenValidate := {
194-
val schemas = if ((graphqlSchemaPaths in GraphQLCodegenConfig).value.isEmpty) {
190+
val schemas = if (graphqlSchemaPaths.value.isEmpty) {
195191
Seq(((resourceDirectory in configuration).value / "schema.graphql").getCanonicalPath).asJava
196192
} else {
197-
(graphqlSchemaPaths in GraphQLCodegenConfig).value.asJava
193+
graphqlSchemaPaths.value.asJava
198194
}
199-
new GraphQLCodegenValidate(schemas).validate() //use validate at terminal by user
195+
new GraphQLCodegenValidate(schemas).validate()
200196
},
201197
graphqlSchemaValidate := {
202-
//use by user
203198
val args: Seq[String] = spaceDelimited("<arg>").parsed
204199
new GraphQLCodegenValidate(args.asJava).validate()
205-
args.foreach(a sLog.value.info(s"Obtain args <$a>"))
200+
args.foreach(a sLog.value.info(s"obtain args: $a"))
206201
args
207202
}, graphqlCodegen := {
208-
val mappingConfigSupplier: JsonMappingConfigSupplier = buildJsonSupplier((jsonConfigurationFile in GraphQLCodegenConfig).value.orNull)
209-
var result: Seq[File] = Seq.empty
203+
sLog.value.info(s"Generating files: ${BuildInfo.toString}")
204+
val mappingConfigSupplier = buildJsonSupplier(jsonConfigurationFile.value.orNull)
205+
var result = Seq.empty[File]
210206
try {
211-
val _outputDir = (outputDir in GraphQLCodegenConfig).value
212-
val _introspectionResult = (graphqlQueryIntrospectionResultPath in GraphQLCodegenConfig).value.orNull
207+
val _outputDir = outputDir.value
208+
val _introspectionResult = graphqlQueryIntrospectionResultPath.value.orNull
213209
lazy val instantiateCodegen = (mappingConfig: MappingConfig) => {
214-
(generatedLanguage in GraphQLCodegenConfig).value match {
210+
generatedLanguage.value match {
215211
case JAVA =>
216-
new JavaGraphQLCodegen(getSchemas, _introspectionResult, _outputDir, mappingConfig, mappingConfigSupplier)
212+
new JavaGraphQLCodegen(getSchemas(), _introspectionResult, _outputDir, mappingConfig, mappingConfigSupplier)
217213
case SCALA =>
218-
new ScalaGraphQLCodegen(getSchemas, _introspectionResult, _outputDir, mappingConfig, mappingConfigSupplier)
214+
new ScalaGraphQLCodegen(getSchemas(), _introspectionResult, _outputDir, mappingConfig, mappingConfigSupplier)
219215
case _ =>
220-
throw new LanguageNotSupportedException((generatedLanguage in GraphQLCodegenConfig).value)
216+
throw new LanguageNotSupportedException(generatedLanguage.value)
221217
}
222218
}
223219
result = instantiateCodegen(getMappingConfig().value).generate.asScala
224220
for (file result) {
225-
sLog.value.success(s"${file.getName}")
221+
sLog.value.info(s"${file.getName}")
226222
}
223+
sLog.value.success(s"Total files: ${result.length}")
227224
} catch {
228225
case e: Exception
229-
throw new Exception(s"${e.getLocalizedMessage}")
226+
(logLevel in configuration).?.value.orElse(state.value.get(logLevel.key)) match {
227+
case Some(Level.Debug) => e.printStackTrace()
228+
case _ => throw new Exception(s"${e.getLocalizedMessage}")
229+
}
230230
}
231231

232-
def getSchemas: util.List[String] = {
233-
if ((graphqlSchemaPaths in GraphQLCodegenConfig).value != null &&
234-
(graphqlSchemaPaths in GraphQLCodegenConfig).value.nonEmpty) {
235-
return (graphqlSchemaPaths in GraphQLCodegenConfig).value.asJava
236-
}
237-
if ((graphqlQueryIntrospectionResultPath in GraphQLCodegenConfig).value != null &&
238-
!(graphqlQueryIntrospectionResultPath in GraphQLCodegenConfig).value.isEmpty) {
239-
return List[String]().asJava
232+
def getSchemas(): JList[String] = {
233+
if (graphqlSchemaPaths.value != null &&
234+
graphqlSchemaPaths.value.nonEmpty) {
235+
graphqlSchemaPaths.value.asJava
236+
} else if (graphqlQueryIntrospectionResultPath.value != null &&
237+
graphqlQueryIntrospectionResultPath.value.isDefined) {
238+
Seq.empty[String].asJava
239+
} else {
240+
val schemasRootDir = getSchemasRootDir
241+
val finder = new SchemaFinder(schemasRootDir)
242+
finder.setRecursive(graphqlSchemas.value.recursive)
243+
finder.setIncludePattern(graphqlSchemas.value.includePattern)
244+
finder.setExcludedFiles(graphqlSchemas.value.excludedFiles.asJava)
245+
finder.findSchemas
240246
}
241-
val schemasRootDir: Path = getSchemasRootDir
242-
val finder: SchemaFinder = new SchemaFinder(schemasRootDir)
243-
finder.setRecursive((graphqlSchemas in GraphQLCodegenConfig).value.recursive)
244-
finder.setIncludePattern((graphqlSchemas in GraphQLCodegenConfig).value.includePattern)
245-
finder.setExcludedFiles((graphqlSchemas in GraphQLCodegenConfig).value.excludedFiles.asJava)
246-
finder.findSchemas
247247
}
248248

249249
def getSchemasRootDir: Path = {
250-
val rootDir = (graphqlSchemas in GraphQLCodegenConfig).value.rootDir
250+
val rootDir = graphqlSchemas.value.rootDir
251251
if (rootDir == null) {
252-
val default = getDefaultResourcesDirectory
253-
if (default == null) throw new IllegalStateException("Default resource folder not found, please provide <rootDir> in <graphqlSchemas>")
254-
else return default
252+
val default = getDefaultResourcesDirectory()
253+
if (default == null)
254+
throw new IllegalStateException("Default resource folder not found, please provide <rootDir> in <graphqlSchemas>")
255+
else default
256+
} else {
257+
Paths.get(rootDir)
255258
}
256-
Paths.get(rootDir)
257259
}
258260

259-
def getDefaultResourcesDirectory: Path = {
261+
def getDefaultResourcesDirectory(): Path = {
260262
val file = (resourceDirectory in configuration).value
261263
if (!file.exists()) {
262264
file.mkdirs()
263265
}
264266
val path = Paths.get(file.getPath)
265-
sLog.value.info(s"Default resources path <$path>")
267+
sLog.value.info(s"default resources path: $path")
266268
path
267269
}
268270

269271
result
270272
}
271-
//watch graphql schema source
272-
) ++ watchSourcesSetting ++ Seq(cleanFiles += (generateCodegenTargetPath in GraphQLCodegenConfig).value)
273+
//watch graphql schema source, I'm not sure if this will be mutually exclusive with the deletion of codegen.
274+
) ++ watchSourcesSetting ++ Seq(cleanFiles += generateCodegenTargetPath.value)
273275
}
274276

275-
private def buildJsonSupplier(jsonConfigurationFile: String): JsonMappingConfigSupplier = {
276-
if (jsonConfigurationFile != null && jsonConfigurationFile.nonEmpty) new JsonMappingConfigSupplier(jsonConfigurationFile) else null
277+
protected def buildJsonSupplier(jsonConfigurationFile: String): JsonMappingConfigSupplier = {
278+
if (jsonConfigurationFile != null && jsonConfigurationFile.nonEmpty)
279+
new JsonMappingConfigSupplier(jsonConfigurationFile) else null
277280
}
278281

279282
}
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
sbt.version=1.3.12
1+
sbt.version = 1.4.7
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
sbt.version=1.3.12
1+
sbt.version = 1.4.7
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
sbt.version=1.3.12
1+
sbt.version = 1.4.7

0 commit comments

Comments
 (0)