11package io .github .dreamylost .graphql .codegen
22
3- import java .nio .file .{ Path , Paths }
4- import java .util
5-
63import com .kobylynskyi .graphql .codegen .GraphQLCodegenValidate
74import com .kobylynskyi .graphql .codegen .java .JavaGraphQLCodegen
85import com .kobylynskyi .graphql .codegen .model ._
96import com .kobylynskyi .graphql .codegen .model .exception .LanguageNotSupportedException
107import com .kobylynskyi .graphql .codegen .model .GeneratedLanguage ._
118import com .kobylynskyi .graphql .codegen .scala .ScalaGraphQLCodegen
129import com .kobylynskyi .graphql .codegen .supplier .{ JsonMappingConfigSupplier , SchemaFinder }
13- import sbt .{ AutoPlugin , Def , PluginTrigger , _ }
10+ import sbt .{ AutoPlugin , PluginTrigger , _ }
1411import sbt .Keys .{ sLog , sourceManaged , _ }
1512import sbt .internal .util .complete .DefaultParsers .spaceDelimited
1613
14+ import java .nio .file .{ Path , Paths }
15+ import java .util .{ HashMap => JHashMap , HashSet => JHashSet , List => JList }
1716import scala .collection .JavaConverters ._
17+ import sbt .Def
1818
1919/**
2020 *
@@ -29,13 +29,11 @@ object GraphQLCodegenPlugin extends GraphQLCodegenPlugin(Compile, configurationP
2929class 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}
0 commit comments