├── .github └── workflows │ ├── ci.yml │ └── release.yml ├── .gitignore ├── .sbtopts ├── .scala-steward.conf ├── LICENSE.txt ├── README.md ├── build.sbt ├── cdk.json ├── modules └── aws-cdk-scala │ └── src │ └── main │ └── scala │ └── io │ └── burkard │ └── cdk │ ├── CdkApp.scala │ ├── CdkStack.scala │ ├── CfnTypedParameter.scala │ ├── metadata │ └── metadata.scala │ └── package.scala └── project ├── Dependencies.scala ├── ProjectPlugin.scala ├── build.properties ├── build.sbt ├── plugins.sbt ├── project └── MetaDependencies.scala └── src └── main └── scala └── io └── burkard └── cdk └── codegen ├── CdkBuilder.scala ├── CdkCodegen.scala ├── CdkEnum.scala ├── CdkFile.scala ├── FieldMethod.scala ├── SourceGenerator.scala └── package.scala /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | name: Build 12 | strategy: 13 | matrix: 14 | scala: [2.12.16, 2.13.8, 3.1.3] 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout 18 | uses: actions/checkout@v2 19 | 20 | - name: Setup Java and Scala 21 | uses: olafurpg/setup-scala@v13 22 | with: 23 | java-version: amazon-corretto@1.17.0-0.35.1 24 | 25 | - name: Cache sbt 26 | uses: actions/cache@v2 27 | with: 28 | path: | 29 | ~/.sbt 30 | ~/.ivy2/cache 31 | ~/.coursier/cache/v1 32 | ~/.cache/coursier/v1 33 | ~/AppData/Local/Coursier/Cache/v1 34 | ~/Library/Caches/Coursier/v1 35 | key: ${{ runner.os }}-sbt-cache-v2-${{ hashFiles('**/*.sbt') }}-${{ hashFiles('project/build.properties') }} 36 | 37 | - name: Compile 38 | run: sbt "++ ${{ matrix.scala }}; compile" 39 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | on: 3 | push: 4 | tags: ["*"] 5 | jobs: 6 | publish: 7 | runs-on: ubuntu-20.04 8 | steps: 9 | - uses: actions/checkout@v2.3.4 10 | with: 11 | fetch-depth: 0 12 | - uses: olafurpg/setup-scala@v13 13 | with: 14 | java-version: amazon-corretto@1.17.0-0.35.1 15 | - run: sbt ci-release 16 | env: 17 | PGP_PASSPHRASE: ${{ secrets.PGP_PASSPHRASE }} 18 | PGP_SECRET: ${{ secrets.PGP_SECRET }} 19 | SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }} 20 | SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .bsp 2 | .idea 3 | .metals 4 | .vscode 5 | cdk.out 6 | target 7 | metals.sbt 8 | -------------------------------------------------------------------------------- /.sbtopts: -------------------------------------------------------------------------------- 1 | -J-XX:MaxMetaspaceSize=1G 2 | -J-Xss2m 3 | -J-Xms512M 4 | -J-Xmx4G 5 | -J-XX:ReservedCodeCacheSize=256M 6 | -------------------------------------------------------------------------------- /.scala-steward.conf: -------------------------------------------------------------------------------- 1 | pullRequests.frequency = "7 days" 2 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AWS CDK Scala 2 | 3 | This library is now archived, no further changes will be accepted. 4 | 5 | - [Overview](#overview) 6 | - [Installation](#installation) 7 | - [Usage](#usage) 8 | - [Limitations](#limitations) 9 | - [Acknowledgements](#acknowledgements) 10 | 11 | # Overview 12 | 13 | Scala DSL for [AWS CDK v2](https://docs.aws.amazon.com/cdk/latest/guide/work-with-cdk-v2.html). 14 | 15 | ### Purpose 16 | 17 | - Pass around app & stack [scope](https://docs.aws.amazon.com/cdk/latest/guide/constructs.html) implicitly. 18 | - Avoid using Java concepts. 19 | * No builder syntax. 20 | * Required & optional parameters. 21 | * ADTs instead of enums. 22 | * Scala collections (i.e. `List` & `Map`). 23 | 24 | ### Disclaimer 25 | 26 | This library solely provides a lightweight DSL over the AWS CDK using metaprogramming. 27 | Please refer to the underlying types from the AWS CDK along with the associated CloudFormation types 28 | for official & up-to-date service documentation. 29 | 30 | ### Release Cadence 31 | 32 | - Major, minor and patch versions are increased each time [aws-cdk-lib](https://mvnrepository.com/artifact/software.amazon.awscdk/aws-cdk-lib) increases associated versions. 33 | - Patch version is increased for any non-breaking changes made to the DSL itself. 34 | 35 | ### Scala Support 36 | 37 | | Version | Supported? | 38 | | --- | --- | 39 | | <= 2.11 | ❌ | 40 | | 2.12 | ✔️| 41 | | 2.13 | ✔️| 42 | | 3 | ✔️| 43 | 44 | Anything <= 2.11 will **not** be supported. Please do not ask or submit PRs for those versions. 45 | 46 | # Installation 47 | 48 | ### CDK CLI 49 | 50 | You must install v2 of the [CDK CLI](https://docs.aws.amazon.com/cdk/latest/guide/cli.html) 51 | to synthesize CloudFormation templates. 52 | 53 | ```bash 54 | npm install -g aws-cdk 55 | ``` 56 | 57 | ### Library 58 | 59 | Just like CDK v2, a single dependency is published for the DSL. 60 | 61 | The latest version can be found on [mvn](https://mvnrepository.com/artifact/io.burkard/aws-cdk-scala) 62 | and on the [releases](https://github.com/NickBurkard/aws-cdk-scala/releases) page. 63 | 64 | ```scala 65 | val cdkVersion: String = ??? 66 | 67 | libraryDependencies += "io.burkard" %% "aws-cdk-scala" % cdkVersion 68 | ``` 69 | 70 | # Usage 71 | 72 | ### Scala 73 | 74 | Create a CDK app within a module of your project. 75 | 76 | ```scala 77 | package io.burkard.cdk.example 78 | 79 | import cats.syntax.option._ 80 | import io.burkard.cdk._ 81 | import io.burkard.cdk.metadata._ 82 | import io.burkard.cdk.services.kinesisanalytics._ 83 | import io.burkard.cdk.services.kinesisanalytics.cfnApplicationV2._ 84 | import io.burkard.cdk.services.s3._ 85 | 86 | object ExampleApp extends CdkApp { 87 | CdkStack(id = "ExampleStack".some) { implicit stackCtx => 88 | val envParameter = CfnTypedParameter.CfnStringParameter( 89 | name = "env", 90 | allowedValues = List("dev", "qa", "prod").some 91 | ) 92 | val regionParameter = CfnTypedParameter.CfnStringParameter( 93 | name = "region", 94 | allowedValues = List("us-east-1", "us-west-2", "eu-west-1").some 95 | ) 96 | 97 | val env = envParameter.value 98 | val region = regionParameter.value 99 | 100 | val bucket = Bucket( 101 | internalResourceId = "Code", 102 | accessControl = BucketAccessControl.Private.some, 103 | enforceSsl = true.some, 104 | encryption = BucketEncryption.S3Managed.some, 105 | versioned = true.some 106 | ) 107 | 108 | CfnApplicationV2( 109 | internalResourceId = "Runtime", 110 | serviceExecutionRole = "arn:example-role", 111 | runtimeEnvironment = "FLINK-1_13", 112 | tags = List( 113 | CfnTag(key = "env", value = env), 114 | CfnTag(key = "region", value = region) 115 | ).some, 116 | applicationName = s"prefix-$env-app-name-$region".some, 117 | applicationConfiguration = ApplicationConfigurationProperty( 118 | applicationCodeConfiguration = ApplicationCodeConfigurationProperty( 119 | codeContent = CodeContentProperty( 120 | s3ContentLocation = S3ContentLocationProperty( 121 | fileKey = "code-key-in-s3", 122 | bucketArn = bucket.getBucketArn, 123 | objectVersion = "code-version".some 124 | ).some 125 | ), 126 | codeContentType = "ZIPFILE" 127 | ).some 128 | ).some 129 | ) 130 | } 131 | } 132 | ``` 133 | 134 | ### CDK Configuration 135 | 136 | Create a `cdk.json` file at the root of your project, specifying the command to run your CDK app. 137 | 138 | ```json 139 | { 140 | "app": "sbt \"example/runMain io.burkard.cdk.example.ExampleApp\"" 141 | } 142 | ``` 143 | 144 | ### Synthesis 145 | 146 | Synthesize the application. 147 | 148 | ```bash 149 | cdk synth 150 | ``` 151 | 152 | The result is a CloudFormation template in YAML. 153 | 154 | ```yaml 155 | Parameters: 156 | env: 157 | Type: String 158 | AllowedValues: 159 | - dev 160 | - qa 161 | - prod 162 | NoEcho: false 163 | region: 164 | Type: String 165 | AllowedValues: 166 | - us-east-1 167 | - us-west-2 168 | - eu-west-1 169 | NoEcho: false 170 | BootstrapVersion: 171 | Type: AWS::SSM::Parameter::Value 172 | Default: /cdk-bootstrap/hnb659fds/version 173 | Description: Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip] 174 | Resources: 175 | Code5B760EEF: 176 | Type: AWS::S3::Bucket 177 | Properties: 178 | AccessControl: Private 179 | BucketEncryption: 180 | ServerSideEncryptionConfiguration: 181 | - ServerSideEncryptionByDefault: 182 | SSEAlgorithm: AES256 183 | VersioningConfiguration: 184 | Status: Enabled 185 | UpdateReplacePolicy: Retain 186 | DeletionPolicy: Retain 187 | Metadata: 188 | aws:cdk:path: ExampleStack/Code/Resource 189 | CodePolicyAA48735C: 190 | Type: AWS::S3::BucketPolicy 191 | Properties: 192 | Bucket: 193 | Ref: Code5B760EEF 194 | PolicyDocument: 195 | Statement: 196 | - Action: s3:* 197 | Condition: 198 | Bool: 199 | aws:SecureTransport: "false" 200 | Effect: Deny 201 | Principal: 202 | AWS: "*" 203 | Resource: 204 | - Fn::GetAtt: 205 | - Code5B760EEF 206 | - Arn 207 | - Fn::Join: 208 | - "" 209 | - - Fn::GetAtt: 210 | - Code5B760EEF 211 | - Arn 212 | - /* 213 | Version: "2012-10-17" 214 | Metadata: 215 | aws:cdk:path: ExampleStack/Code/Policy/Resource 216 | Runtime: 217 | Type: AWS::KinesisAnalyticsV2::Application 218 | Properties: 219 | RuntimeEnvironment: FLINK-1_13 220 | ServiceExecutionRole: arn:example-role 221 | ApplicationConfiguration: 222 | ApplicationCodeConfiguration: 223 | CodeContent: 224 | S3ContentLocation: 225 | BucketARN: 226 | Fn::GetAtt: 227 | - Code5B760EEF 228 | - Arn 229 | FileKey: code-key-in-s3 230 | ObjectVersion: code-version 231 | CodeContentType: ZIPFILE 232 | ApplicationName: 233 | Fn::Join: 234 | - "" 235 | - - prefix- 236 | - Ref: env 237 | - -app-name- 238 | - Ref: region 239 | Tags: 240 | - Key: env 241 | Value: 242 | Ref: env 243 | - Key: region 244 | Value: 245 | Ref: region 246 | Metadata: 247 | aws:cdk:path: ExampleStack/Runtime 248 | ``` 249 | 250 | # Limitations 251 | 252 | - Builders which use overloading for optional parameters (same name but different types) 253 | are represented as `paramName0`, `paramName1`, etc.. 254 | 255 | # Acknowledgements 256 | 257 | - Inspired by [AWS CDK Kotlin DSL](https://github.com/Semantic-Configuration/AWS-CDK-Kotlin-DSL). 258 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | inThisBuild( 2 | List( 3 | organization := "io.burkard", 4 | homepage := Some(url("https://github.com/NickBurkard/aws-cdk-scala")), 5 | licenses := List("Apache 2" -> url("https://github.com/NickBurkard/aws-cdk-scala/blob/master/LICENSE.txt")), 6 | developers := List( 7 | Developer( 8 | "NickBurkard", 9 | "Nick Burkard", 10 | "burkard.foss@gmail.com", 11 | url("https://burkard.io") 12 | ) 13 | ), 14 | sonatypeCredentialHost := Sonatype.sonatype01 15 | ) 16 | ) 17 | 18 | lazy val awsCdkScala = project 19 | .in(file(".")) 20 | .aggregate(`aws-cdk-scala`) 21 | .disablePublishing() 22 | 23 | lazy val `aws-cdk-scala` = project 24 | .in(file("modules/aws-cdk-scala")) 25 | .withCodegen() 26 | .withCdk() 27 | -------------------------------------------------------------------------------- /cdk.json: -------------------------------------------------------------------------------- 1 | { 2 | "app": "sbt \"example/runMain io.burkard.cdk.example.ExampleApp\"" 3 | } 4 | -------------------------------------------------------------------------------- /modules/aws-cdk-scala/src/main/scala/io/burkard/cdk/CdkApp.scala: -------------------------------------------------------------------------------- 1 | package io.burkard.cdk 2 | 3 | /** 4 | * CDK application, can have one or more stacks. 5 | * @param props Optional app properties. 6 | */ 7 | abstract class CdkApp(props: Option[software.amazon.awscdk.AppProps] = None) 8 | extends software.amazon.awscdk.App(props.orNull) { 9 | 10 | // Context for initializing one or more stacks. 11 | protected[this] implicit lazy val appCtx: software.amazon.awscdk.App = this 12 | 13 | def main(args: Array[String]): Unit = 14 | run() 15 | 16 | // Supposedly always needed due to this jsii issue: 17 | // https://github.com/aws/jsii/issues/456 18 | protected[this] final def run(): Unit = 19 | ValueDiscard[software.amazon.awscdk.cxapi.CloudAssembly](synth()) 20 | } 21 | -------------------------------------------------------------------------------- /modules/aws-cdk-scala/src/main/scala/io/burkard/cdk/CdkStack.scala: -------------------------------------------------------------------------------- 1 | package io.burkard.cdk 2 | 3 | /** 4 | * CDK stack. 5 | * @param id Optional stack ID. 6 | * @param props Optional stack properties. 7 | * @param appCtx CDK app context. 8 | */ 9 | abstract class CdkStack( 10 | id: Option[String] = None, 11 | props: Option[software.amazon.awscdk.StackProps] = None 12 | )(implicit 13 | appCtx: software.amazon.awscdk.App 14 | ) extends software.amazon.awscdk.Stack(appCtx, id.orNull, props.orNull) { 15 | 16 | // Context for initializing stack resources. 17 | protected[this] implicit lazy val stackCtx: software.amazon.awscdk.Stack = this 18 | } 19 | 20 | object CdkStack { 21 | 22 | /** 23 | * Create an anonymous instance of a custom stack. 24 | * @param id Optional stack ID. 25 | * @param props Optional stack properties. 26 | * @param resources Function for initializing stack resources. 27 | * @param appCtx CDK app context. 28 | * @tparam A Result of initializing stack resources. 29 | * @return CDK stack. 30 | */ 31 | def apply[A]( 32 | id: Option[String] = None, 33 | props: Option[software.amazon.awscdk.StackProps] = None 34 | )( 35 | resources: software.amazon.awscdk.Stack => A 36 | )(implicit appCtx: software.amazon.awscdk.App): software.amazon.awscdk.Stack = 37 | new CdkStack(id, props) { ValueDiscard[A](resources(stackCtx)) } 38 | } 39 | -------------------------------------------------------------------------------- /modules/aws-cdk-scala/src/main/scala/io/burkard/cdk/CfnTypedParameter.scala: -------------------------------------------------------------------------------- 1 | package io.burkard.cdk 2 | 3 | import scala.annotation.nowarn 4 | import scala.collection.JavaConverters._ 5 | 6 | // CFN parameter with type safety. 7 | sealed abstract class CfnTypedParameter(val name: String)(implicit 8 | val stackCtx: software.amazon.awscdk.Stack 9 | ) extends Product with Serializable { 10 | type Value 11 | 12 | def value: Value 13 | 14 | def `type`: String 15 | 16 | def underlying: software.amazon.awscdk.CfnParameter 17 | } 18 | 19 | @nowarn("cat=deprecation") 20 | object CfnTypedParameter { 21 | final case class CfnStringParameter( 22 | override val name: String, 23 | minLength: Option[Number] = None, 24 | defaultValue: Option[AnyRef] = None, 25 | maxLength: Option[Number] = None, 26 | allowedPattern: Option[String] = None, 27 | noEcho: Option[Boolean] = None, 28 | constraintDescription: Option[String] = None, 29 | description: Option[String] = None, 30 | allowedValues: Option[List[String]] = None 31 | )(implicit stackCtx: software.amazon.awscdk.Stack) extends CfnTypedParameter(name) { 32 | override type Value = String 33 | 34 | override def value: String = underlying.getValueAsString 35 | 36 | override val `type` = "String" 37 | 38 | override val underlying: software.amazon.awscdk.CfnParameter = 39 | software.amazon.awscdk.CfnParameter.Builder 40 | .create(stackCtx, name) 41 | .minLength(minLength.orNull) 42 | .defaultValue(defaultValue.orNull) 43 | .maxLength(maxLength.orNull) 44 | .allowedPattern(allowedPattern.orNull) 45 | .noEcho(noEcho.map(Boolean.box).orNull) 46 | .constraintDescription(constraintDescription.orNull) 47 | .description(description.orNull) 48 | .allowedValues(allowedValues.map(_.asJava).orNull) 49 | .`type`(`type`) 50 | .build() 51 | } 52 | 53 | final case class CfnNumberParameter( 54 | override val name: String, 55 | minValue: Option[Number] = None, 56 | defaultValue: Option[AnyRef] = None, 57 | noEcho: Option[Boolean] = None, 58 | constraintDescription: Option[String] = None, 59 | description: Option[String] = None, 60 | allowedValues: Option[List[String]] = None, 61 | maxValue: Option[Number] = None 62 | )(implicit stackCtx: software.amazon.awscdk.Stack) extends CfnTypedParameter(name) { 63 | override type Value = Number 64 | 65 | override def value: Number = underlying.getValueAsNumber 66 | 67 | override val `type`: String = "Number" 68 | 69 | override val underlying: software.amazon.awscdk.CfnParameter = 70 | software.amazon.awscdk.CfnParameter.Builder 71 | .create(stackCtx, name) 72 | .minValue(minValue.orNull) 73 | .defaultValue(defaultValue.orNull) 74 | .noEcho(noEcho.map(Boolean.box).orNull) 75 | .constraintDescription(constraintDescription.orNull) 76 | .description(description.orNull) 77 | .allowedValues(allowedValues.map(_.asJava).orNull) 78 | .maxValue(maxValue.orNull) 79 | .`type`(`type`) 80 | .build() 81 | } 82 | 83 | final case class CfnListNumberParameter( 84 | override val name: String, 85 | minValue: Option[Number] = None, 86 | defaultValue: Option[AnyRef] = None, 87 | noEcho: Option[Boolean] = None, 88 | constraintDescription: Option[String] = None, 89 | description: Option[String] = None, 90 | allowedValues: Option[List[String]] = None, 91 | maxValue: Option[Number] = None 92 | )(implicit stackCtx: software.amazon.awscdk.Stack) extends CfnTypedParameter(name) { 93 | override type Value = List[String] 94 | 95 | override def value: List[String] = underlying.getValueAsList.asScala.toList 96 | 97 | override val `type`: String = "List" 98 | 99 | override val underlying: software.amazon.awscdk.CfnParameter = 100 | software.amazon.awscdk.CfnParameter.Builder 101 | .create(stackCtx, name) 102 | .minValue(minValue.orNull) 103 | .defaultValue(defaultValue.orNull) 104 | .noEcho(noEcho.map(Boolean.box).orNull) 105 | .constraintDescription(constraintDescription.orNull) 106 | .description(description.orNull) 107 | .allowedValues(allowedValues.map(_.asJava).orNull) 108 | .maxValue(maxValue.orNull) 109 | .`type`(`type`) 110 | .build() 111 | } 112 | 113 | final case class CfnCommaDelimitedListParameter( 114 | override val name: String, 115 | minLength: Option[Number] = None, 116 | defaultValue: Option[AnyRef] = None, 117 | maxLength: Option[Number] = None, 118 | allowedPattern: Option[String] = None, 119 | noEcho: Option[Boolean] = None, 120 | constraintDescription: Option[String] = None, 121 | description: Option[String] = None, 122 | allowedValues: Option[List[String]] = None 123 | )(implicit stackCtx: software.amazon.awscdk.Stack) extends CfnTypedParameter(name) { 124 | override type Value = List[String] 125 | 126 | override def value: List[String] = underlying.getValueAsList.asScala.toList 127 | 128 | override val `type`: String = "CommaDelimitedList" 129 | 130 | override val underlying: software.amazon.awscdk.CfnParameter = 131 | software.amazon.awscdk.CfnParameter.Builder 132 | .create(stackCtx, name) 133 | .minLength(minLength.orNull) 134 | .defaultValue(defaultValue.orNull) 135 | .maxLength(maxLength.orNull) 136 | .allowedPattern(allowedPattern.orNull) 137 | .noEcho(noEcho.map(Boolean.box).orNull) 138 | .constraintDescription(constraintDescription.orNull) 139 | .description(description.orNull) 140 | .allowedValues(allowedValues.map(_.asJava).orNull) 141 | .`type`(`type`) 142 | .build() 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /modules/aws-cdk-scala/src/main/scala/io/burkard/cdk/metadata/metadata.scala: -------------------------------------------------------------------------------- 1 | package io.burkard.cdk.metadata 2 | 3 | import java.util.{Map => JMap} 4 | 5 | import scala.annotation.nowarn 6 | import scala.collection.JavaConverters._ 7 | 8 | import io.burkard.cdk.{CfnTypedParameter, JMapEncoderOps} 9 | 10 | // https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudformation-interface.html 11 | final case class CloudFormationInterface( 12 | parameterGroups: Option[List[ParameterGroup]] = None, 13 | parameterLabels: Option[ParameterLabel] = None 14 | ) 15 | 16 | object CloudFormationInterface { 17 | @nowarn("cat=deprecation") 18 | implicit val jMapEncoder: JMapEncoder[CloudFormationInterface] = { cfi => 19 | val maybeWithParameterGroups = cfi.parameterGroups.fold[Map[String, AnyRef]](Map.empty) { pgs => 20 | Map("ParameterGroups" -> pgs.map(_.encode).asJava) 21 | } 22 | 23 | cfi.parameterLabels.fold(maybeWithParameterGroups) { pl => 24 | maybeWithParameterGroups.+("ParameterLabels" -> pl.encode) 25 | }.asJava 26 | } 27 | } 28 | 29 | // https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudformation-interface-parametergroup.html 30 | final case class ParameterGroup( 31 | label: Option[Label] = None, 32 | parameters: Option[List[String]] = None 33 | ) 34 | 35 | object ParameterGroup { 36 | def build(label: Option[Label] = None, parameters: List[CfnTypedParameter]): ParameterGroup = 37 | ParameterGroup(label, Some(parameters.map(_.name))) 38 | 39 | @nowarn("cat=deprecation") 40 | implicit val jMapEncoder: JMapEncoder[ParameterGroup] = { pg => 41 | val maybeWithLabel = pg.label.fold[Map[String, AnyRef]](Map.empty) { l => 42 | Map("Label" -> l.encode) 43 | } 44 | 45 | pg.parameters.fold(maybeWithLabel) { params => 46 | maybeWithLabel.+("Parameters" -> params.asJava) 47 | }.asJava 48 | } 49 | } 50 | 51 | // https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudformation-interface-parameterlabel.html 52 | final case class ParameterLabel(labels: Map[String, Label]) 53 | 54 | object ParameterLabel { 55 | def build(labels: Map[CfnTypedParameter, Label]): ParameterLabel = 56 | ParameterLabel(labels.map { case (p, l) => p.name -> l }) 57 | 58 | @nowarn("cat=deprecation") 59 | implicit val jMapEncoder: JMapEncoder[ParameterLabel] = 60 | _.labels.map { case (id, l) => (id, l.encode: AnyRef) }.asJava 61 | } 62 | 63 | // https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudformation-interface-label.html 64 | final case class Label(default: Option[String] = None) 65 | 66 | object Label { 67 | def apply(default: String): Label = 68 | Label(Some(default)) 69 | 70 | // Not UpperCamelCase on purpose. 71 | @nowarn("cat=deprecation") 72 | implicit val jMapEncoder: JMapEncoder[Label] = 73 | _.default.fold[Map[String, AnyRef]](Map.empty)(d => Map("default" -> d)).asJava 74 | } 75 | 76 | private[cdk] trait JMapEncoder[A] { 77 | def encode(value: A): JMap[String, AnyRef] 78 | } 79 | 80 | private[cdk] object JMapEncoder { 81 | def apply[A: JMapEncoder]: JMapEncoder[A] = implicitly[JMapEncoder[A]] 82 | } 83 | -------------------------------------------------------------------------------- /modules/aws-cdk-scala/src/main/scala/io/burkard/cdk/package.scala: -------------------------------------------------------------------------------- 1 | package io.burkard 2 | 3 | import java.util.concurrent.TimeUnit 4 | import java.util.{Map => JMap} 5 | import scala.util.Try 6 | 7 | import scala.annotation.nowarn 8 | import scala.concurrent.duration.FiniteDuration 9 | import scala.collection.JavaConverters._ 10 | 11 | import software.amazon.awscdk.{Duration => AwsDuration} 12 | 13 | import io.burkard.cdk.metadata._ 14 | 15 | package object cdk { 16 | // Safely discard non-unit values. 17 | private[cdk] object ValueDiscard { 18 | def apply[A](a: => A): Unit = { 19 | val _ = a 20 | () 21 | } 22 | } 23 | 24 | implicit final class ScalaDurationToAwsDurationSyntax(private val value: FiniteDuration) extends AnyVal { 25 | def toAws: Either[String, AwsDuration] = 26 | Try(toAwsUnsafe) 27 | .toEither 28 | .left 29 | .map { 30 | case _: MatchError => 31 | // Should never reach here. TimeUnit is Java enum so Scala compiler cannot prove an exhaustive search. 32 | s"Timeunit, ${value.unit.toString}, not recognized." 33 | 34 | case t => 35 | t.getMessage 36 | } 37 | 38 | def toAwsUnsafe: AwsDuration = 39 | value.unit match { 40 | case TimeUnit.DAYS => 41 | AwsDuration.days(value.length) 42 | 43 | case TimeUnit.HOURS => 44 | AwsDuration.hours(value.length) 45 | 46 | case TimeUnit.MINUTES => 47 | AwsDuration.minutes(value.length) 48 | 49 | case TimeUnit.SECONDS => 50 | AwsDuration.seconds(value.length) 51 | 52 | case TimeUnit.MILLISECONDS => 53 | AwsDuration.millis(value.length) 54 | 55 | case TimeUnit.MICROSECONDS | TimeUnit.NANOSECONDS => 56 | throw new IllegalArgumentException("AWS duration doesn't support time units smaller than milliseconds") 57 | 58 | // Scala 3 compiler dismisses `case _ =>` checks and forces `case null =>`. Should never reach this case. 59 | case null => 60 | throw new IllegalArgumentException("Quirk in Scala 3 compiler. FiniteDuration calls `require` with not null on timeunit values, but compiler doesn't see this.") 61 | } 62 | } 63 | 64 | private[cdk] final implicit class JMapEncoderOps[A](private val value: A) extends AnyVal { 65 | def encode(implicit encoder: JMapEncoder[A]): JMap[String, AnyRef] = 66 | encoder.encode(value) 67 | } 68 | 69 | private[this] val awsCloudFormationInterfaceKey = "AWS::CloudFormation::Interface" 70 | 71 | @nowarn("cat=deprecation") 72 | final implicit class StackOps(private val stack: software.amazon.awscdk.Stack) extends AnyVal { 73 | /** 74 | * Set a CloudFormation interface in the stack's metadata. 75 | * Will overwrite a previously set CloudFormation interface if present. 76 | * https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudformation-interface.html 77 | * 78 | * @param cloudFormationInterface CloudFormation interface. 79 | */ 80 | def setCloudFormationInterface(cloudFormationInterface: CloudFormationInterface): Unit = 81 | Option(stack.getTemplateOptions.getMetadata) match { 82 | case Some(metadata) => 83 | val _ = metadata.put(awsCloudFormationInterfaceKey, cloudFormationInterface.encode) 84 | 85 | case None => 86 | stack.getTemplateOptions.setMetadata( 87 | Map[String, AnyRef](awsCloudFormationInterfaceKey -> cloudFormationInterface.encode).asJava 88 | ) 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /project/Dependencies.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | 3 | object Dependencies { 4 | object Aws { 5 | val cdk: ModuleID = "software.amazon.awscdk" % "aws-cdk-lib" % "2.39.1" 6 | 7 | val constructs: ModuleID = "software.constructs" % "constructs" % "10.1.94" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /project/ProjectPlugin.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | import sbt.Keys._ 3 | 4 | import _root_.io.burkard.cdk.codegen.CdkCodegen 5 | 6 | object ProjectPlugin extends AutoPlugin { 7 | val autoImport: ThingsToAutoImport.type = ThingsToAutoImport 8 | 9 | override val trigger: PluginTrigger = AllRequirements 10 | 11 | private[this] val `scala 2.12` = "2.12.16" 12 | 13 | private[this] val `scala 2.13` = "2.13.8" 14 | 15 | private[this] val `scala 3` = "3.1.3" 16 | 17 | override val buildSettings: Seq[Def.Setting[_]] = Seq( 18 | scalaVersion := `scala 2.13`, 19 | crossScalaVersions := Seq(`scala 2.12`, `scala 2.13`, `scala 3`) 20 | ) 21 | 22 | object ThingsToAutoImport { 23 | final implicit class ProjectOps(private val project: Project) extends AnyVal { 24 | def withCdk(): Project = 25 | project.settings( 26 | libraryDependencies ++= Seq( 27 | Dependencies.Aws.cdk, 28 | Dependencies.Aws.constructs 29 | ) 30 | ) 31 | 32 | def withCodegen(): Project = 33 | project.settings(CdkCodegen.settings(Compile)) 34 | 35 | def disablePublishing(): Project = 36 | project.settings( 37 | publish / skip := true, 38 | publishArtifact := false 39 | ) 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version = 1.7.3 2 | -------------------------------------------------------------------------------- /project/build.sbt: -------------------------------------------------------------------------------- 1 | libraryDependencies ++= Seq( 2 | MetaDependencies.Aws.cdk, 3 | MetaDependencies.Aws.constructs, 4 | MetaDependencies.Google.guava 5 | ) 6 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("io.github.davidgregory084" % "sbt-tpolecat" % "0.4.1") 2 | addSbtPlugin("com.github.sbt" % "sbt-ci-release" % "1.5.11") 3 | -------------------------------------------------------------------------------- /project/project/MetaDependencies.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | 3 | object MetaDependencies { 4 | object Aws { 5 | val cdk: ModuleID = "software.amazon.awscdk" % "aws-cdk-lib" % "2.39.1" 6 | 7 | val constructs: ModuleID = "software.constructs" % "constructs" % "10.1.94" 8 | } 9 | 10 | object Google { 11 | val guava: ModuleID = "com.google.guava" % "guava" % "31.1-jre" 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /project/src/main/scala/io/burkard/cdk/codegen/CdkBuilder.scala: -------------------------------------------------------------------------------- 1 | package io.burkard.cdk.codegen 2 | 3 | import java.lang.reflect.{Method, Modifier} 4 | 5 | import scala.annotation.nowarn 6 | import scala.util.Try 7 | 8 | import sbt._ 9 | 10 | import CdkBuilder.ConstructorType 11 | 12 | // Class instance builder provided by the CDK. 13 | final case class CdkBuilder private ( 14 | instanceCanonicalName: String, 15 | instanceSimpleName: String, 16 | constructorType: ConstructorType, 17 | underlying: Class[_] 18 | ) { 19 | // The required field names of the underlying instance. 20 | private lazy val requiredFieldNames: Set[String] = 21 | requiredFieldNamesByProps 22 | .orElse(requiredFieldNamesByInterface) 23 | .getOrElse(Set.empty) 24 | 25 | // Attempt to find required field names via `props` field. 26 | private[this] lazy val requiredFieldNamesByProps: Option[Set[String]] = 27 | for { 28 | // The `props` field is a builder for all required & optional properties. 29 | propsBuilder <- Try(underlying.getDeclaredField("props")).toOption.map(_.getType) 30 | 31 | // The `build` method returns an instance of the props itself, which needs to be inspected. 32 | props <- Try(propsBuilder.getDeclaredMethod("build")).toOption.map(_.getReturnType) 33 | } yield props.requiredFieldNames 34 | 35 | // Attempt to find required field names by the builder interface. 36 | private[this] lazy val requiredFieldNamesByInterface: Option[Set[String]] = 37 | for { 38 | genericInterfaces <- Try(underlying.getGenericInterfaces).toOption.map(_.toList) 39 | 40 | // Need to dig through generic interfaces for the associated props class name. 41 | propsClassName <- genericInterfaces.collectFirst { 42 | case i if i.getTypeName.startsWith("software.amazon.jsii.Builder<") => 43 | i.getTypeName.stripPrefix("software.amazon.jsii.Builder<").stripSuffix(">") 44 | } 45 | 46 | props <- Try(Class.forName(propsClassName)).toOption 47 | } yield props.requiredFieldNames 48 | 49 | @nowarn("cat=deprecation") 50 | // [0, N] field methods of the underlying builder. All non-optional fields appear before optional fields. 51 | private[this] lazy val fieldMethods: List[FieldMethod] = 52 | underlying 53 | .getMethods 54 | .toList 55 | // Only preserve methods with valid type names. 56 | .flatMap { method => 57 | FieldMethod 58 | .validFieldMethodTypeName(method) 59 | .map(methodName => (method.getName, method.getAnnotations.toList, methodName)) 60 | } 61 | .groupBy(_._1) 62 | .mapValues(_.map { case (_, annotations, methodName) => (annotations, methodName) }) 63 | // Potentially rename shared field methods. 64 | .flatMap { 65 | // Name is unique, do nothing extra. 66 | case (methodName, (annotations, typeName) :: Nil) => 67 | List( 68 | FieldMethod( 69 | methodName, 70 | methodName, 71 | typeName, 72 | isOptional = !requiredFieldNames.contains(methodName), 73 | annotations 74 | ) 75 | ) 76 | 77 | // Name is shared, need to rename based on index. 78 | // TODO Change to something more meaningful. 79 | case (methodName, typeNames) => 80 | typeNames.zipWithIndex.map { case ((annotations, typeName), index) => 81 | FieldMethod( 82 | s"$methodName$index", 83 | methodName, 84 | typeName, 85 | isOptional = !requiredFieldNames.contains(methodName), 86 | annotations 87 | ) 88 | } 89 | } 90 | .toList 91 | .sortBy(_.isOptional) 92 | 93 | lazy val packageName: String = renameCdkPackage(instanceCanonicalName, dropLast = 1) 94 | 95 | // `parameterName: type`, potentially with default value. 96 | lazy val typeAnnotatedParameters: List[String] = fieldMethods.map(_.asTypeAnnotatedParameter) 97 | 98 | lazy val parameterNames: List[String] = fieldMethods.map(_.actualParameterName) 99 | 100 | // `.builderMethodName(parameterName)`, potentially with Java conversions and / or default value. 101 | lazy val builderMethods: List[String] = fieldMethods.map(_.asBuilderMethod) 102 | 103 | private[this] lazy val requiresJavaConvertersImport: Boolean = { 104 | lazy val fieldMethodsRequireAsJava = fieldMethods.exists(_.requiresAsJava) 105 | lazy val createMethodsRequireAsJava = constructorType match { 106 | case CdkBuilder.ConstructorType.CreateParameters(createParameters) => 107 | createParameters.exists(_.requiresAsJava) 108 | 109 | case _ => 110 | false 111 | } 112 | 113 | fieldMethodsRequireAsJava || createMethodsRequireAsJava 114 | } 115 | 116 | // Potential imports for the source file. 117 | // TODO Switch to `scala.jdk.CollectionConverters._` after dropping Scala 2.12. 118 | lazy val imports: String = 119 | if (requiresJavaConvertersImport) { 120 | "\nimport scala.collection.JavaConverters._\n" 121 | } else { 122 | "" 123 | } 124 | 125 | lazy val suppressDeprecation: String = 126 | if (isDeprecatedBuilder || requiresJavaConvertersImport || usesDeprecatedMethods) { 127 | "\n@scala.annotation.nowarn(\"cat=deprecation\")" 128 | } else { 129 | "" 130 | } 131 | 132 | private[this] lazy val usesDeprecatedMethods: Boolean = { 133 | lazy val fieldMethodsDeprecated = fieldMethods.exists(_.isDeprecated) 134 | lazy val createMethodsDeprecated = constructorType match { 135 | case CdkBuilder.ConstructorType.CreateParameters(createParameters) => 136 | createParameters.exists(_.isDeprecated) 137 | 138 | case _ => 139 | false 140 | } 141 | 142 | fieldMethodsDeprecated || createMethodsDeprecated 143 | } 144 | 145 | private[this] lazy val isDeprecatedBuilder: Boolean = 146 | underlying.getAnnotations.toList.exists(_.annotationType().getSimpleName == "Deprecated") 147 | 148 | // What the apply method's signature looks like, based on constructor type. 149 | lazy val applyMethodSignature: String = constructorType match { 150 | // Add in fields as parameters if required. 151 | case CdkBuilder.ConstructorType.CreateContextAndId => 152 | if (fieldMethods.nonEmpty) { 153 | s"""def apply( 154 | | internalResourceId: String, 155 | | ${typeAnnotatedParameters.mkString(",\n ")} 156 | | )(implicit stackCtx: software.amazon.awscdk.Stack): $instanceCanonicalName""".stripMargin 157 | } else { 158 | s"def apply(internalResourceId: String)(implicit stackCtx: software.amazon.awscdk.Stack): $instanceCanonicalName" 159 | } 160 | 161 | // Add in create params first (required) and potentially fields as params (optional). 162 | case CdkBuilder.ConstructorType.CreateParameters(createParameters) => 163 | if (fieldMethods.nonEmpty) { 164 | s"""def apply( 165 | | ${createParameters.map(_.asTypeAnnotatedParameter).mkString(",\n ")}, 166 | | ${typeAnnotatedParameters.mkString(",\n ")} 167 | | ): $instanceCanonicalName""".stripMargin 168 | } else { 169 | s"""def apply( 170 | | ${createParameters.map(_.asTypeAnnotatedParameter).mkString(",\n ")} 171 | | ): $instanceCanonicalName""".stripMargin 172 | } 173 | 174 | // Add in fields as parameters if required. 175 | case CdkBuilder.ConstructorType.CreateNoParameters | CdkBuilder.ConstructorType.DirectConstructorNoParameters => 176 | if (fieldMethods.nonEmpty) { 177 | s"""def apply( 178 | | ${typeAnnotatedParameters.mkString(",\n ")} 179 | | ): $instanceCanonicalName""".stripMargin 180 | } else { 181 | s"def apply: $instanceCanonicalName" 182 | } 183 | } 184 | 185 | // The syntax for creating the underlying builder. 186 | lazy val builderSyntax: String = constructorType match { 187 | // Supply the implicit stack context and the resource ID. 188 | case ConstructorType.CreateContextAndId => 189 | s"""$instanceCanonicalName.Builder 190 | | .create(stackCtx, internalResourceId)""".stripMargin 191 | 192 | // Supply required parameters to the `create` method. 193 | case ConstructorType.CreateParameters(createParameters) => 194 | s"""$instanceCanonicalName.Builder 195 | | .create(${createParameters.map(_.asValue).mkString(", ")})""".stripMargin 196 | 197 | // `create` method requires no parameters. 198 | case ConstructorType.CreateNoParameters => 199 | s"""$instanceCanonicalName.Builder 200 | | .create()""".stripMargin 201 | 202 | // Builder is constructed via `new` syntax. 203 | case ConstructorType.DirectConstructorNoParameters => 204 | s"(new $instanceCanonicalName.Builder)" 205 | } 206 | } 207 | 208 | object CdkBuilder { 209 | implicit val sourceGenerator: SourceGenerator[CdkBuilder] = 210 | new SourceGenerator[CdkBuilder] { 211 | override def baseFile(root: File, source: CdkBuilder): File = 212 | root /~ source.packageName.replace('.', '/') / s"${source.instanceSimpleName}.scala" 213 | 214 | override def content(source: CdkBuilder): String = 215 | s"""package ${source.packageName} 216 | |${source.imports}${source.suppressDeprecation} 217 | |@SuppressWarnings(Array("org.wartremover.warts.DefaultArguments", "org.wartremover.warts.Null", "DisableSyntax.null")) 218 | |object ${source.instanceSimpleName} { 219 | | 220 | | ${source.applyMethodSignature} = 221 | | ${source.builderSyntax} 222 | | ${source.builderMethods.mkString("\n ")} 223 | | .build() 224 | |} 225 | |""".stripMargin 226 | } 227 | 228 | // Using Java reflection to identify which CDK classes we can codegen. 229 | // Not using Scala reflection because of 2.x/3.x API differences. 230 | def build(underlying: Class[_]): Option[CdkBuilder] = 231 | if (underlying.getSimpleName == "Builder") { 232 | for { 233 | // Pick the constructor type. 234 | constructorType <- constructorType(underlying) 235 | 236 | // Must have a `build` method. 237 | _ <- buildMethod(underlying) 238 | 239 | instanceCanonicalName = underlying.getCanonicalName.split("\\.").toList.dropRight(1).mkString(".") 240 | 241 | instanceSimpleName <- instanceCanonicalName.split("\\.").toList.lastOption 242 | } yield CdkBuilder(instanceCanonicalName, instanceSimpleName, constructorType, underlying) 243 | } else { 244 | None 245 | } 246 | 247 | // What type of constructor is used to create the builder. 248 | sealed trait ConstructorType extends Product with Serializable 249 | 250 | object ConstructorType { 251 | // public static Builder create(context, id) 252 | case object CreateContextAndId extends ConstructorType 253 | 254 | // public static Builder create(...) 255 | final case class CreateParameters(createParameters: List[FieldMethod]) extends ConstructorType 256 | 257 | // public static Builder create() 258 | case object CreateNoParameters extends ConstructorType 259 | 260 | // new Builder() 261 | case object DirectConstructorNoParameters extends ConstructorType 262 | } 263 | 264 | private[this] def constructorType(underlying: Class[_]): Option[ConstructorType] = 265 | underlying.getMethods.toList 266 | // Pick "create" method with most parameters first. 267 | .sortBy(_.getParameterCount) 268 | .collectFirst { 269 | case m if m.getName == "create" && Modifier.isStatic(m.getModifiers) => 270 | if (isContextAndIdConstructor(m)) { 271 | ConstructorType.CreateContextAndId 272 | } else if (m.getParameterCount != 0) { 273 | ConstructorType.CreateParameters( 274 | underlying 275 | .getDeclaredFields 276 | .toList 277 | .filterNot(_.getType.getName.contains("Builder")) 278 | .map { field => 279 | FieldMethod( 280 | field.getName, 281 | field.getName, 282 | field.getGenericType.getTypeName, 283 | isOptional = false, 284 | field.getAnnotations.toList 285 | ) 286 | } 287 | ) 288 | } else { 289 | ConstructorType.CreateNoParameters 290 | } 291 | } 292 | // Or, check if there's a public constructor with no parameters. 293 | .orElse( 294 | underlying.getConstructors.toList.collectFirst { 295 | case c if c.getParameterCount == 0 && Modifier.isPublic(c.getModifiers) => 296 | ConstructorType.DirectConstructorNoParameters 297 | } 298 | ) 299 | 300 | // Does a method have the type signature of `create(context, id)`? 301 | private[this] def isContextAndIdConstructor(m: Method): Boolean = 302 | m.getParameterTypes.toList.map(_.getSimpleName) match { 303 | case "Construct" :: "String" :: Nil => 304 | true 305 | 306 | case _ => 307 | false 308 | } 309 | 310 | // public Underlying build() 311 | private[this] def buildMethod(underlying: Class[_]): Option[Method] = 312 | underlying.getMethods 313 | .find(m => m.getName == "build" && !Modifier.isStatic(m.getModifiers) && m.getParameterCount == 0) 314 | } 315 | 316 | -------------------------------------------------------------------------------- /project/src/main/scala/io/burkard/cdk/codegen/CdkCodegen.scala: -------------------------------------------------------------------------------- 1 | package io.burkard.cdk.codegen 2 | 3 | import scala.annotation.nowarn 4 | import scala.collection.JavaConverters._ 5 | 6 | import sbt._ 7 | import sbt.Keys._ 8 | 9 | import com.google.common.reflect.ClassPath 10 | 11 | object CdkCodegen { 12 | private val cdkCodegen = taskKey[Seq[File]]("generate AWS CDK source files") 13 | 14 | def settings(config: Configuration): Seq[Setting[_]] = Seq( 15 | config / cdkCodegen := codegen((config / sourceManaged).value), 16 | config / sourceGenerators += (Compile / cdkCodegen), 17 | config / packageSrc / mappings ++= { 18 | val base = (config / sourceManaged).value 19 | (config / managedSources).value 20 | .flatMap(file => file.relativeTo(base).map(file -> _.getPath)) 21 | } 22 | ) 23 | 24 | private def codegen(root: File): Seq[File] = { 25 | val files = awsClasses.flatMap(c => toFile(root, c).map(_ -> c)) 26 | 27 | val collisions = files 28 | .groupBy(_._1.path) 29 | .collect { case (path, duplicates) if duplicates.length > 1 => 30 | path -> duplicates.map(_._2) 31 | } 32 | .toList 33 | 34 | if (collisions.nonEmpty) { 35 | collisions.foreach { case (name, classes) => 36 | System.err.println(s"""$name: ${classes.map(_.getCanonicalName).mkString(" ")}""") 37 | } 38 | sys.error(s"Found ${collisions.length} colliding generated files") 39 | } 40 | 41 | if (files.nonEmpty) { 42 | files.map(_._1.write()) 43 | } else { 44 | sys.error(s"Generated zero classes, something is seriously wrong! :)") 45 | } 46 | } 47 | 48 | private def toFile(root: File, underlying: Class[_]): Option[CdkFile] = 49 | CdkBuilder 50 | .build(underlying) 51 | .map(_.toCdkFile(root)) 52 | .orElse( 53 | CdkEnum 54 | .build(underlying) 55 | .map(_.toCdkFile(root)) 56 | ) 57 | 58 | @nowarn("cat=deprecation") 59 | private def awsClasses: List[Class[_]] = 60 | ClassPath 61 | .from(getClass.getClassLoader) 62 | .getAllClasses 63 | .asScala 64 | .toList 65 | .collect { case classInfo if classInfo.getPackageName.startsWith("software.amazon.awscdk") => 66 | classInfo.load() 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /project/src/main/scala/io/burkard/cdk/codegen/CdkEnum.scala: -------------------------------------------------------------------------------- 1 | package io.burkard.cdk.codegen 2 | 3 | import scala.util.Try 4 | 5 | import sbt._ 6 | 7 | import com.google.common.base.CaseFormat 8 | 9 | // Enum provided by the CDK. 10 | final case class CdkEnum private ( 11 | instanceCanonicalName: String, 12 | instanceSimpleName: String, 13 | valueNames: List[String], 14 | underlying: Class[_] 15 | ) { 16 | lazy val packageName: String = renameCdkPackage(instanceCanonicalName, dropLast = 1) 17 | 18 | // `case object ValueName extends EnumName(underlyingValue)`. 19 | lazy val valuesCases: List[String] = 20 | valueNames.map { valueName => 21 | s"""case object ${CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, valueName)} 22 | | extends $instanceSimpleName($instanceCanonicalName.$valueName)""".stripMargin 23 | } 24 | 25 | lazy val noWarnClass: String = 26 | if (underlying.getAnnotations.toList.exists(_.annotationType().getSimpleName == "Deprecated")) { 27 | "\n@scala.annotation.nowarn(\"cat=deprecation\")" 28 | } else { 29 | "" 30 | } 31 | 32 | lazy val noWarnObject: String = 33 | if (valueNames.exists(isDeprecated)) { 34 | "\n@scala.annotation.nowarn(\"cat=deprecation\")" 35 | } else { 36 | "" 37 | } 38 | 39 | private[this] def isDeprecated(valueName: String): Boolean = 40 | Try(underlying.getField(valueName)) 41 | .map(_.getAnnotations.toList.exists(_.annotationType().getSimpleName == "Deprecated")) 42 | .getOrElse(false) 43 | } 44 | 45 | object CdkEnum { 46 | implicit val sourceGenerator: SourceGenerator[CdkEnum] = 47 | new SourceGenerator[CdkEnum] { 48 | override def baseFile(root: File, source: CdkEnum): File = 49 | root /~ source.packageName.replace('.', '/') / s"${source.instanceSimpleName}.scala" 50 | 51 | override def content(source: CdkEnum): String = 52 | s"""package ${source.packageName} 53 | |${source.noWarnClass} 54 | |sealed abstract class ${source.instanceSimpleName}(val underlying: ${source.instanceCanonicalName}) 55 | | extends Product 56 | | with Serializable 57 | |${source.noWarnObject} 58 | |object ${source.instanceSimpleName} { 59 | | implicit def toAws(value: ${source.instanceSimpleName}): ${source.instanceCanonicalName} = 60 | | Option(value).map(_.underlying).orNull 61 | | 62 | | ${source.valuesCases.mkString("\n\n ")} 63 | |} 64 | |""".stripMargin 65 | } 66 | 67 | def build(underlying: Class[_]): Option[CdkEnum] = 68 | if (underlying.isEnum) { 69 | Try( 70 | underlying 71 | .getMethod("values") 72 | .invoke(null) 73 | .asInstanceOf[Array[_]] 74 | .toList 75 | .map(_.toString) 76 | ) 77 | .toOption 78 | .map( 79 | CdkEnum( 80 | underlying.getCanonicalName, 81 | underlying.getSimpleName, 82 | _, 83 | underlying 84 | ) 85 | ) 86 | } else { 87 | None 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /project/src/main/scala/io/burkard/cdk/codegen/CdkFile.scala: -------------------------------------------------------------------------------- 1 | package io.burkard.cdk.codegen 2 | 3 | import sbt.{File, IO} 4 | 5 | final case class CdkFile(file: File, content: String) { 6 | lazy val path: String = file.getPath 7 | 8 | def write(): File = { 9 | IO.write(file, content) 10 | file 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /project/src/main/scala/io/burkard/cdk/codegen/FieldMethod.scala: -------------------------------------------------------------------------------- 1 | package io.burkard.cdk.codegen 2 | 3 | import java.lang.annotation.Annotation 4 | import java.lang.reflect.{Method, Modifier} 5 | 6 | // Method associated to setting a field in a CDK builder. 7 | final case class FieldMethod private ( 8 | parameterName: String, 9 | methodName: String, 10 | typeName: String, 11 | isOptional: Boolean, 12 | annotations: List[Annotation] 13 | ) { 14 | lazy val asTypeAnnotatedParameter: String = 15 | if (isOptional) { 16 | s"$actualParameterName: Option[$fullTypeName] = None" 17 | } else { 18 | s"$actualParameterName: $fullTypeName" 19 | } 20 | 21 | lazy val asBuilderMethod: String = s".$actualMethodName($asValue)" 22 | 23 | lazy val asValue: String = s"$actualParameterName$convert$defaultValue" 24 | 25 | // Are generic collections used? 26 | lazy val requiresAsJava: Boolean = requiresJavaConverters(fullTypeName) 27 | 28 | lazy val requiresBooleanBoxing: Boolean = typeName.contains("java.lang.Boolean") 29 | 30 | lazy val defaultValue: String = 31 | if (isOptional) { 32 | ".orNull" 33 | } else { 34 | "" 35 | } 36 | 37 | private[this] lazy val convert: String = 38 | if (requiresAsJava) { 39 | val base = if ( 40 | fullTypeName.indexOf("Map[") != fullTypeName.lastIndexOf("Map[") || 41 | fullTypeName.contains("Map[") && fullTypeName.indexOf("Map[") < fullTypeName.lastIndexOf("List[") 42 | ) { 43 | ".mapValues(_.asJava).toMap.asJava" 44 | } else if ( 45 | fullTypeName.contains("Map[") && 46 | fullTypeName.indexOf("Map[") < fullTypeName.lastIndexOf("Boolean") 47 | ) { 48 | ".mapValues(Boolean.box).toMap.asJava" 49 | } else if ( 50 | fullTypeName.contains("List[") && ( 51 | fullTypeName.indexOf("List[") < fullTypeName.indexOf("Map[") || 52 | fullTypeName.indexOf("List[") < fullTypeName.lastIndexOf("List[") 53 | ) 54 | ) { 55 | ".map(_.asJava).asJava" 56 | } else { 57 | ".asJava" 58 | } 59 | 60 | if (isOptional) { 61 | s".map(_$base)" 62 | } else { 63 | base 64 | } 65 | } else if (isOptional && requiresBooleanBoxing) { 66 | ".map(Boolean.box)" 67 | } else { 68 | "" 69 | } 70 | 71 | lazy val actualParameterName: String = literallyIdentify(parameterName) 72 | 73 | lazy val actualMethodName: String = literallyIdentify(methodName) 74 | 75 | private[this] lazy val fullTypeName: String = 76 | literallyIdentify(rewriteJavaTypes(typeName)) 77 | 78 | lazy val isDeprecated: Boolean = 79 | annotations.exists(_.annotationType().getSimpleName == "Deprecated") 80 | } 81 | 82 | object FieldMethod { 83 | private[this] val nonFieldMethods: Set[String] = 84 | Set("create", "build", "equals", "getClass", "hashCode", "notify", "notifyAll", "wait", "toString") 85 | 86 | def validFieldMethodTypeName(underlying: Method): Option[String] = 87 | if (!(nonFieldMethods.contains(underlying.getName) || Modifier.isStatic(underlying.getModifiers))) { 88 | underlying.getGenericParameterTypes.toList match { 89 | // Must not be `IResolvable` from JSII. 90 | case value :: Nil => 91 | if (value.getTypeName != "software.amazon.awscdk.IResolvable") { 92 | Some(value.getTypeName.replaceAll("\\$", ".")) 93 | } else { 94 | None 95 | } 96 | 97 | case _ => 98 | None 99 | } 100 | } else { 101 | None 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /project/src/main/scala/io/burkard/cdk/codegen/SourceGenerator.scala: -------------------------------------------------------------------------------- 1 | package io.burkard.cdk.codegen 2 | 3 | import sbt.File 4 | 5 | // Code generator via some source. 6 | trait SourceGenerator[A] { 7 | def baseFile(root: File, source: A): File 8 | 9 | def content(source: A): String 10 | 11 | final def cdkFile(root: File, source: A): CdkFile = 12 | CdkFile(baseFile(root, source), content(source)) 13 | } 14 | 15 | object SourceGenerator { 16 | def apply[A: SourceGenerator]: SourceGenerator[A] = implicitly[SourceGenerator[A]] 17 | } 18 | -------------------------------------------------------------------------------- /project/src/main/scala/io/burkard/cdk/codegen/package.scala: -------------------------------------------------------------------------------- 1 | package io.burkard.cdk 2 | 3 | import java.lang.reflect.Modifier 4 | 5 | import scala.util.matching.Regex 6 | 7 | import sbt._ 8 | 9 | import com.google.common.base.CaseFormat 10 | 11 | package object codegen { 12 | def renameCdkPackage(name: String, dropLast: Int): String = 13 | name 14 | .replaceFirst("software\\.amazon\\.awscdk", "io.burkard.cdk") 15 | .split('.') 16 | .dropRight(dropLast) 17 | .map { v => 18 | if (v.headOption.exists(Character.isUpperCase)) { 19 | CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, v) 20 | } else { 21 | v 22 | } 23 | } 24 | .mkString(".") 25 | 26 | private[this] val scala2ReservedWords: Set[String] = 27 | Set( 28 | "abstract", "case", "catch", "class", "def", "do", "else", "extends", "false", "final", "finally", "for", 29 | "forSome", "if", "implicit", "import", "lazy", "match", "new", "null", "object", "override", "package", 30 | "private", "protected", "return", "sealed", "super", "then", "this", "throw", "trait", "try", "true", "type", 31 | "val", "var", "while", "with", "yield" 32 | ) 33 | 34 | // Literally identify reserved words. 35 | def literallyIdentify(name: String): String = 36 | if (scala2ReservedWords.contains(name)) { 37 | s"`$name`" 38 | } else { 39 | name 40 | } 41 | 42 | // Rewrite rules for Java types in order of descending precedence. 43 | private[this] val javaRewrites: List[(Regex, String)] = 44 | List( 45 | raw"java\.lang\.Boolean".r -> "Boolean", 46 | raw"java\.lang\.Number".r -> "Number", 47 | raw"java\.lang\.Object".r -> "AnyRef", 48 | raw"java\.lang\.String".r -> "String", 49 | raw"java\.util\.Map".r -> "Map", 50 | raw"java\.util\.List".r -> "List", 51 | raw"<".r -> "[", 52 | raw">".r -> "]", 53 | raw"extends".r -> "<:", 54 | raw"\?".r -> "_" 55 | ) 56 | 57 | // Rewrite any java types in a type name. 58 | def rewriteJavaTypes(typeName: String): String = 59 | javaRewrites.foldLeft(typeName) { case (value, (regex, replacement)) => 60 | regex.replaceAllIn(value, replacement) 61 | } 62 | 63 | // Does a type require java converters? 64 | def requiresJavaConverters(typeName: String): Boolean = 65 | typeName.contains("List[") || typeName.contains("Map[") 66 | 67 | final implicit class ClassOps(private val c: Class[_]) extends AnyVal { 68 | def requiredFieldNames: Set[String] = 69 | c.getDeclaredMethods.toList 70 | .collect { 71 | case m if !Modifier.isStatic(m.getModifiers) && m.getName.startsWith("get") && !m.isDefault => 72 | CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, m.getName.stripPrefix("get")) 73 | } 74 | .toSet 75 | } 76 | 77 | final implicit class SourceGeneratorOps[A: SourceGenerator](private val a: A) { 78 | def toCdkFile(root: File): CdkFile = 79 | SourceGenerator[A].cdkFile(root, a) 80 | } 81 | 82 | final implicit class SbtFileOps(private val root: File) extends AnyVal { 83 | // Traverse down a path that has embedded slashes. 84 | def /~(path: String): File = 85 | path.split('/').foldLeft(root)(_ / _) 86 | } 87 | } 88 | --------------------------------------------------------------------------------