diff --git a/.github/workflows/kotlin-tests.yml b/.github/workflows/kotlin-tests.yml new file mode 100644 index 0000000..217f321 --- /dev/null +++ b/.github/workflows/kotlin-tests.yml @@ -0,0 +1,27 @@ +name: Kotlin Tests +on: [push, pull_request] +jobs: + test: + runs-on: ubuntu-latest # Assuming Kotlin projects can be built on Linux + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v2 + with: + java-version: '11' + distribution: 'adopt' + - name: Cache Gradle packages + uses: actions/cache@v2 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*') }} + restore-keys: | + ${{ runner.os }}-gradle- + - uses: ruby/setup-ruby@v1 + with: + ruby-version: '3.2' + bundler-cache: true # Runs 'bundle install' and caches installed gems automatically + - name: Generate Kotlin Code & Run Tests + run: bundle exec rake test_kotlin diff --git a/.gitignore b/.gitignore index 8e0ab14..2459a31 100644 --- a/.gitignore +++ b/.gitignore @@ -7,8 +7,18 @@ /spec/reports/ /tmp/ -# rspec failure tracking +# Rspec failure tracking .rspec_status coverage *.gem **/.DS_Store + +# Compiled Kotlin/Java class files +*.class + +# IntelliJ IDEA files +.idea/ + +# Gradle files +.gradle/ +build/ diff --git a/README.md b/README.md index 48411c2..c373ee5 100644 --- a/README.md +++ b/README.md @@ -37,29 +37,73 @@ # Requirements +## Android + +Your project must be using the Gradle Build Tool. + ## iOS Your project must be using Swift Package Manager or CocoaPods as dependency manager (or both). No support for Carthage. Note: this gem was only tested in macOS environments. -## Android +## Preview -The Java/Kotlin code generator hasn't been implemented yet. Star and "watch" this project and check back in the future, or help us build it [here](https://github.com/rogerluan/arkana/issues/1). +### Kotlin -image +
Click here to see the Kotlin preview +

-## Preview +The image below shows how the auto-generated file looks like. + +

+ +
+ +Usage using the example code above: -
Click here to show an image with the preview! +```kotlin +import com.arkanakeys.MySecrets + +// Designed with testability and DI in mind +println(MySecrets.Global.someBooleanSecret) +println(MySecrets.Global.someIntSecret) +println(MySecrets.Global.mySecretAPIKey) + +// Simulating environment selection using a random boolean value +val keys = if (Math.random() < 0.5) MySecrets.Dev else MySecrets.Staging +println(keys.serviceKey) +``` + +

+
+ +### Swift + +
Click here to see the Swift preview

-The image below shows how the auto-generated file looks like. At the bottom of it you can see how you'll consume the code generated. +The image below shows how the auto-generated file looks like.

+Usage using the example code above: + +```swift +import ArkanaKeys + +// Designed with testability and DI in mind +print(MySecrets.Global().someBooleanSecret) +print(MySecrets.Global().someIntSecret) +print(MySecrets.Global().mySecretAPIKey) + +// This is a demo, so we are using Bool.random() to simulate the environment +let keys: MySecretsEnvironmentProtocol = Bool.random() ? MySecrets.Dev() : MySecrets.Staging() +print(keys.serviceKey) +``` +

@@ -87,18 +131,21 @@ Once you have create your config file, you can run Arkana: ```sh Usage: arkana [options] - -c /path/to/your/.arkana.yml, Path to your config file. Defaults to '.arkana.yml' + -c /path/to/your/.arkana.yml, Path to your config file. Defaults to '.arkana.yml' --config-filepath - -e /path/to/your/.env, Path to your dotenv file. Defaults to '.env' if one exists. + -e /path/to/your/.env, Path to your dotenv file. Defaults to '.env' if one exists. --dotenv-filepath -f, --flavor FrostedFlakes Flavors are useful, for instance, when generating secrets for white-label projects. See the README for more information + -i debug,release, Optionally pass the environments that you want Arkana to generate secrets for. Useful if you only want to build a certain environment, e.g. just Debug in local machines, while only building Staging and Release in CI. Separate the keys using a comma, without spaces. When omitted, Arkana generate secrets for all environments. + --include-environments + -l, --lang kotlin Language to produce keys for, e.g. kotlin, swift. Defaults to 'swift'. See the README for more information ``` Note that you have to prepend `bundle exec` before `arkana` if you manage your dependencies via bundler, as recommended. Arkana only has one command, which parses your config file and env vars, generating all the code needed. Arkana should always be run before attempting to build your project, to make sure the files exist _and_ are up-to-date (according to the current config file). This means you might need to add the Arkana run command in your CI/CD scripts, _fastlane_, Xcode Build Phases, or something similar. -## Importing Arkana into your project +## Importing Arkana into your iOS project Once the Arkana has been run, its files will be created according to the `package_manager` setting defined in your config file, so update that setting according to your project needs. @@ -145,12 +192,48 @@ After adding its dependency, you should be able to `import ArkanaKeys` (or the ` We recommend you to add your ArkanaKeys directory to your `.gitignore` since it's an auto-generated code that will change every time you run Arkana (since its salt gets generated on each run). For more information, see [How does it work?](#how-does-it-work) +## Importing Arkana into your Android project + +When importing Arkana into your project, you have two options: generating its files within a new Gradle module created by Arkana, or adding them to an existing module. The choice depends on the settings in your config file, so ensure these are updated to reflect your project's requirements. + +### Creating a New Arkana Gradle Module + +To generate a new Gradle module containing Arkana files, follow these steps: + +1. In your config file, set the `result_path` to the desired name for the new Arkana module. +2. Update your project's `settings.gradle` file to include this newly created Arkana module. + +### Adding Arkana to an Existing Gradle Module + +If you prefer to add Arkana files to an existing Gradle module, follow these steps: + +1. Adjust the `result_path` in your config file to specify the existing Gradle module where you want to include the Arkana files. +2. Change `should_generate_gradle_build_file` to `false`. This prevents the overwriting of your existing module's `build.gradle` file. + +### Automating Arkana Execution During Gradle Sync + +For automatic execution of Arkana during Gradle sync, modify your `settings.gradle` file by adding the following code: + +```kotlin +exec { + commandLine("arkana", "--lang", "kotlin") +} +``` + ## Options ### `--help` Will display a list of the available options. +### `--lang` + +Usage: `--lang kotlin` + +Indicates the language to produce keys for, e.g. kotlin, swift. + +Defaults to `swift`. + ### `--config-file-path` Usage: `--config-file-path /path/to/your/.arkana.yml` diff --git a/Rakefile b/Rakefile index 007674a..d548431 100644 --- a/Rakefile +++ b/Rakefile @@ -21,6 +21,16 @@ task :test_swift do FileUtils.rm_rf("tests") end +desc "Generates Kotlin source code and run its unit tests." +task :test_kotlin do + FileUtils.copy_entry("spec/fixtures/kotlin", "tests") + sh("ARKANA_RUNNING_CI_INTEGRATION_TESTS=true bin/arkana --lang kotlin --config-filepath spec/fixtures/kotlin-tests.yml --dotenv-filepath spec/fixtures/.env.fruitloops --include-environments dev,staging") + Dir.chdir("tests") do + sh("./gradlew test") + end + FileUtils.rm_rf("tests") +end + desc "Sets lib version to the semantic version given, and push it to remote." task :bump, [:v] do |_t, args| version = args[:v] || raise("A version is required. Pass it like `rake bump[1.2.3]`") diff --git a/docs/demo-used-to-gen-image.kt b/docs/demo-used-to-gen-image.kt new file mode 100644 index 0000000..eeea0af --- /dev/null +++ b/docs/demo-used-to-gen-image.kt @@ -0,0 +1,58 @@ +// DO NOT MODIFY +// Automatically generated by Arkana (https://github.com/rogerluan/arkana) +package com.arkanakeys + +object MySecrets { + private val salt = listOf(0x3f, 0xb6, 0x2, 0x3, 0xbf, 0x54, 0xf5, 0x67, 0x95, 0xc, 0x56, 0x47, 0x87, 0x55, 0x60, 0x74, 0x6, 0x77, 0x8b, 0xd6, 0x88, 0x41, 0x99, 0xe2, 0x97, 0x92, 0x9f, 0x68, 0x7d, 0x6c, 0x39, 0x64, 0xca, 0x98, 0xe7, 0x8d, 0xe8, 0x9e, 0x1f, 0xe5, 0xad, 0x45, 0x32, 0xac, 0xc5, 0xe1, 0xf6, 0x4f, 0x67, 0xcc, 0x6a, 0xee, 0x66, 0xac, 0x80, 0xea, 0x78, 0x1b, 0xd6, 0x78, 0x4, 0x97, 0xfa, 0xcc) + + internal fun decode(encoded: List, cipher: List): String { + val decoded = encoded.mapIndexed { index, item -> + (item xor cipher[(index % cipher.size)]).toByte() + }.toByteArray() + return decoded.toString(Charsets.UTF_8) + } + + internal fun decodeInt(encoded: List, cipher: List): Int { + return decode(encoded = encoded, cipher = cipher).toInt() + } + + internal fun decodeBoolean(encoded: List, cipher: List): Boolean { + return decode(encoded = encoded, cipher = cipher).toBoolean() + } + + object Global { + val someBooleanSecret: Boolean + get() { + val encoded = listOf(0x4b, 0xc4, 0x77, 0x66) + return decodeBoolean(encoded = encoded, cipher = salt) + } + + val someIntSecret: Int + get() { + val encoded = listOf(0xb, 0x84) + return decodeInt(encoded = encoded, cipher = salt) + } + + val mySecretAPIKey: String + get() { + val encoded = listOf(0x6, 0x84, 0x30, 0x30, 0x8c, 0x63, 0xc7, 0x57, 0xa6, 0x3a, 0x6e, 0x72, 0xb3, 0x62, 0x57, 0x41, 0x3e, 0x47, 0xbc, 0xef, 0xba, 0x73, 0xaa, 0xd1, 0xa0, 0xa0, 0xaf, 0x5b, 0x4b, 0x54, 0xc, 0x50, 0xfd, 0xaf, 0xd2, 0xb5, 0xd8, 0xa9) + return decode(encoded = encoded, cipher = salt) + } + } + + object Dev : MySecretsEnvironment { + override val serviceKey: String + get() { + val encoded = listOf(0x4b, 0xde, 0x6b, 0x70, 0x9f, 0x30, 0x90, 0x11, 0xb5, 0x67, 0x33, 0x3e, 0xa7, 0x3c, 0x13, 0x54, 0x75, 0x12, 0xe8, 0xa4, 0xed, 0x35) + return decode(encoded = encoded, cipher = salt) + } + } + + object Staging : MySecretsEnvironment { + override val serviceKey: String + get() { + val encoded = listOf(0x4b, 0xde, 0x6b, 0x70, 0x9f, 0x27, 0x81, 0x6, 0xf2, 0x65, 0x38, 0x20, 0xa7, 0x3e, 0x5, 0xd, 0x26, 0x1e, 0xf8, 0xf6, 0xfb, 0x24, 0xfa, 0x90, 0xf2, 0xe6) + return decode(encoded = encoded, cipher = salt) + } + } +} diff --git a/docs/demo-used-to-gen-image.swift b/docs/demo-used-to-gen-image.swift new file mode 100644 index 0000000..2dc55ff --- /dev/null +++ b/docs/demo-used-to-gen-image.swift @@ -0,0 +1,86 @@ +// DO NOT MODIFY +// Automatically generated by Arkana (https://github.com/rogerluan/arkana) + +import Foundation +import MySecretsInterfaces + +public enum MySecrets { + @inline(__always) + fileprivate static let salt: [UInt8] = [ + 0x47, 0x7c, 0xe3, 0x7f, 0x80, 0xa8, 0x41, 0x6c, 0x2, 0xc3, 0x7f, 0x3f, 0x63, 0xd9, 0xb6, 0x57, 0x3a, 0x33, 0x98, 0xed, 0xfa, 0x71, 0xcb, 0x9a, 0x55, 0x23, 0x52, 0x1c, 0x31, 0xc0, 0x74, 0xd4, 0x7e, 0x6e, 0xf5, 0xca, 0xbc, 0x25, 0x69, 0xcd, 0x9, 0, 0xcb, 0x70, 0xd3, 0x5e, 0xa5, 0x92, 0xe7, 0x6b, 0x2, 0x90, 0x29, 0xc2, 0x44, 0xc8, 0x5a, 0xc2, 0xc0, 0xc7, 0x42, 0x30, 0x40, 0xa3 + ] + + static func decode(encoded: [UInt8], cipher: [UInt8]) -> String { + return String(decoding: encoded.enumerated().map { offset, element in + element ^ cipher[offset % cipher.count] + }, as: UTF8.self) + } + + static func decode(encoded: [UInt8], cipher: [UInt8]) -> Bool { + let stringValue: String = Self.decode(encoded: encoded, cipher: cipher) + return Bool(stringValue)! + } + + static func decode(encoded: [UInt8], cipher: [UInt8]) -> Int { + let stringValue: String = Self.decode(encoded: encoded, cipher: cipher) + return Int(stringValue)! + } +} + +public extension MySecrets { + struct Global: MySecretsGlobalProtocol { + public init() {} + + @inline(__always) + public lazy var someBooleanSecret: Bool = { + let encoded: [UInt8] = [ + 0x33, 0xe, 0x96, 0x1a + ] + return MySecrets.decode(encoded: encoded, cipher: MySecrets.salt) + }() + + @inline(__always) + public lazy var someIntSecret: Int = { + let encoded: [UInt8] = [ + 0x73, 0x4e + ] + return MySecrets.decode(encoded: encoded, cipher: MySecrets.salt) + }() + + @inline(__always) + public lazy var mySecretAPIKey: String = { + let encoded: [UInt8] = [ + 0x7e, 0x4e, 0xd1, 0x4c, 0xb3, 0x9f, 0x73, 0x5c, 0x31, 0xf5, 0x47, 0xa, 0x57, 0xee, 0x81, 0x62, 0x2, 0x3, 0xaf, 0xd4, 0xc8, 0x43, 0xf8, 0xa9, 0x62, 0x11, 0x62, 0x2f, 0x7, 0xf8, 0x41, 0xe0, 0x49, 0x59, 0xc0, 0xf2, 0x8c, 0x12 + ] + return MySecrets.decode(encoded: encoded, cipher: MySecrets.salt) + }() + } +} + +public extension MySecrets { + struct Dev: MySecretsEnvironmentProtocol { + public init() {} + + @inline(__always) + public lazy var serviceKey: String = { + let encoded: [UInt8] = [ + 0x33, 0x14, 0x8a, 0xc, 0xa0, 0xcc, 0x24, 0x1a, 0x22, 0xa8, 0x1a, 0x46, 0x43, 0xb0, 0xc5, 0x77, 0x49, 0x56, 0xfb, 0x9f, 0x9f, 0x5 + ] + return MySecrets.decode(encoded: encoded, cipher: MySecrets.salt) + }() + } +} + +public extension MySecrets { + struct Staging: MySecretsEnvironmentProtocol { + public init() {} + + @inline(__always) + public lazy var serviceKey: String = { + let encoded: [UInt8] = [ + 0x33, 0x14, 0x8a, 0xc, 0xa0, 0xdb, 0x35, 0xd, 0x65, 0xaa, 0x11, 0x58, 0x43, 0xb2, 0xd3, 0x2e, 0x1a, 0x5a, 0xeb, 0xcd, 0x89, 0x14, 0xa8, 0xe8, 0x30, 0x57 + ] + return MySecrets.decode(encoded: encoded, cipher: MySecrets.salt) + }() + } +} diff --git a/docs/kotlin-demo.png b/docs/kotlin-demo.png new file mode 100644 index 0000000..d27ba56 Binary files /dev/null and b/docs/kotlin-demo.png differ diff --git a/docs/swift-demo.png b/docs/swift-demo.png index 1bcc3ef..54c17dd 100644 Binary files a/docs/swift-demo.png and b/docs/swift-demo.png differ diff --git a/lib/arkana.rb b/lib/arkana.rb index fba4b9d..589754a 100644 --- a/lib/arkana.rb +++ b/lib/arkana.rb @@ -7,6 +7,7 @@ require_relative "arkana/models/template_arguments" require_relative "arkana/salt_generator" require_relative "arkana/swift_code_generator" +require_relative "arkana/kotlin_code_generator" require_relative "arkana/version" # Top-level namespace for Arkana's execution entry point. When ran from CLI, `Arkana.run` is what is invoked. @@ -43,7 +44,14 @@ def self.run(arguments) config: config, salt: salt, ) - SwiftCodeGenerator.generate( + + generator = case config.current_lang.downcase + when "swift" then SwiftCodeGenerator + when "kotlin" then KotlinCodeGenerator + else UI.crash("Unknown output lang selected: #{config.current_lang}") + end + + generator.method(:generate).call( template_arguments: template_arguments, config: config, ) diff --git a/lib/arkana/config_parser.rb b/lib/arkana/config_parser.rb index 8808b52..cac9555 100644 --- a/lib/arkana/config_parser.rb +++ b/lib/arkana/config_parser.rb @@ -14,6 +14,7 @@ def self.parse(arguments) config = Config.new(yaml) config.include_environments(arguments.include_environments) config.current_flavor = arguments.flavor + config.current_lang = arguments.lang config.dotenv_filepath = arguments.dotenv_filepath UI.warn("Dotenv file was specified but couldn't be found at '#{config.dotenv_filepath}'") if config.dotenv_filepath && !File.exist?(config.dotenv_filepath) config diff --git a/lib/arkana/helpers/kotlin_template_helper.rb b/lib/arkana/helpers/kotlin_template_helper.rb new file mode 100644 index 0000000..4482322 --- /dev/null +++ b/lib/arkana/helpers/kotlin_template_helper.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +# Utilities to reduce the amount of boilerplate code in `.kt.erb` template files. +module KotlinTemplateHelper + def self.kotlin_type(type) + case type + when :string then "String" + when :boolean then "Boolean" + when :integer then "Int" + else raise "Unknown variable type '#{type}' received." + end + end + + def self.kotlin_decode_function(type) + case type + when :string then "decode" + when :boolean then "decodeBoolean" + when :integer then "decodeInt" + else raise "Unknown variable type '#{type}' received." + end + end +end diff --git a/lib/arkana/kotlin_code_generator.rb b/lib/arkana/kotlin_code_generator.rb new file mode 100644 index 0000000..a4ef333 --- /dev/null +++ b/lib/arkana/kotlin_code_generator.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +require "erb" +require "fileutils" +require_relative "helpers/string" + +# Responsible for generating Kotlin source and test files. +module KotlinCodeGenerator + # Generates Kotlin code and test files for the given template arguments. + def self.generate(template_arguments:, config:) + kotlin_module_dir = config.result_path + kotlin_sources_dir = File.join(kotlin_module_dir, "src", "main", config.kotlin_sources_path, config.kotlin_package_name.split(".")) + kotlin_tests_dir = File.join(kotlin_module_dir, "src", "test", config.kotlin_sources_path, config.kotlin_package_name.split(".")) + + if config.should_generate_gradle_build_file + set_up_kotlin_module(kotlin_module_dir, template_arguments) + end + + set_up_kotlin_interfaces(kotlin_sources_dir, template_arguments, config) + set_up_kotlin_classes(kotlin_sources_dir, kotlin_tests_dir, template_arguments, config) + end + + def self.set_up_kotlin_module(path, template_arguments) + dirname = File.dirname(__FILE__) + sources_dir = path + readme_template = File.read("#{dirname}/templates/readme.erb") + source_template = File.read("#{dirname}/templates/kotlin/build.gradle.kts.erb") + FileUtils.mkdir_p(path) + render(readme_template, template_arguments, File.join(path, "README.md")) + render(source_template, template_arguments, File.join(sources_dir, "build.gradle.kts")) + end + + def self.set_up_kotlin_interfaces(path, template_arguments, config) + dirname = File.dirname(__FILE__) + sources_dir = path + source_template = File.read("#{dirname}/templates/kotlin/arkana_protocol.kt.erb") + FileUtils.mkdir_p(path) + render(source_template, template_arguments, File.join(sources_dir, "#{config.namespace}Environment.kt")) + end + + def self.set_up_kotlin_classes(sources_dir, tests_dir, template_arguments, config) + dirname = File.dirname(__FILE__) + source_template = File.read("#{dirname}/templates/kotlin/arkana.kt.erb") + tests_template = File.read("#{dirname}/templates/kotlin/arkana_tests.kt.erb") + FileUtils.mkdir_p(sources_dir) + FileUtils.mkdir_p(tests_dir) if config.should_generate_unit_tests + render(source_template, template_arguments, File.join(sources_dir, "#{config.namespace}.kt")) + render(tests_template, template_arguments, File.join(tests_dir, "#{config.namespace}Test.kt")) if config.should_generate_unit_tests + end + + def self.render(template, template_arguments, destination_file) + renderer = ERB.new(template, trim_mode: ">") # Don't automatically add newlines at the end of each template tag + result = renderer.result(template_arguments.get_binding) + File.write(destination_file, result) + end +end diff --git a/lib/arkana/models/arguments.rb b/lib/arkana/models/arguments.rb index fc6a7e0..be5683e 100644 --- a/lib/arkana/models/arguments.rb +++ b/lib/arkana/models/arguments.rb @@ -12,6 +12,8 @@ class Arguments attr_reader :flavor # @returns [Array] attr_reader :include_environments + # @returns [string] + attr_reader :lang def initialize # Default values @@ -19,6 +21,7 @@ def initialize @dotenv_filepath = ".env" if File.exist?(".env") @flavor = nil @include_environments = nil + @lang = "swift" OptionParser.new do |opt| opt.on("-c", "--config-filepath /path/to/your/.arkana.yml", "Path to your config file. Defaults to '.arkana.yml'") do |o| @@ -33,6 +36,9 @@ def initialize opt.on("-i", "--include-environments debug,release", "Optionally pass the environments that you want Arkana to generate secrets for. Useful if you only want to build a certain environment, e.g. just Debug in local machines, while only building Staging and Release in CI. Separate the keys using a comma, without spaces. When omitted, Arkana generate secrets for all environments.") do |o| @include_environments = o.split(",") end + opt.on("-l", "--lang kotlin", "Language to produce keys for, e.g. kotlin, swift. Defaults to 'swift'. See the README for more information") do |o| + @lang = o + end end.parse! end end diff --git a/lib/arkana/models/config.rb b/lib/arkana/models/config.rb index 55196ba..65b3204 100644 --- a/lib/arkana/models/config.rb +++ b/lib/arkana/models/config.rb @@ -16,6 +16,10 @@ class Config attr_reader :pod_name # @returns [string] attr_reader :result_path + # @returns [string] + attr_reader :kotlin_package_name + # @returns [string] + attr_reader :kotlin_sources_path # @returns [string[]] attr_reader :flavors # @returns [string] @@ -26,11 +30,17 @@ class Config attr_reader :package_manager # @returns [boolean] attr_reader :should_cocoapods_cross_import_modules + # @returns [boolean] + attr_reader :should_generate_gradle_build_file + # @returns [int] + attr_reader :kotlin_jvm_toolchain_version # @returns [string] attr_accessor :current_flavor # @returns [string] attr_accessor :dotenv_filepath + # @returns [string] + attr_accessor :current_lang # rubocop:disable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity def initialize(yaml) @@ -42,6 +52,8 @@ def initialize(yaml) @import_name = yaml["import_name"] || default_name @pod_name = yaml["pod_name"] || default_name @result_path = yaml["result_path"] || default_name + @kotlin_package_name = yaml["kotlin_package_name"] || "com.arkanakeys" + @kotlin_sources_path = yaml["kotlin_sources_path"] || "kotlin" @flavors = yaml["flavors"] || [] @swift_declaration_strategy = yaml["swift_declaration_strategy"] || "let" @should_generate_unit_tests = yaml["should_generate_unit_tests"] @@ -49,6 +61,9 @@ def initialize(yaml) @package_manager = yaml["package_manager"] || "spm" @should_cocoapods_cross_import_modules = yaml["should_cocoapods_cross_import_modules"] @should_cocoapods_cross_import_modules = true if @should_cocoapods_cross_import_modules.nil? + @should_generate_gradle_build_file = yaml["should_generate_gradle_build_file"] + @should_generate_gradle_build_file = true if @should_generate_gradle_build_file.nil? + @kotlin_jvm_toolchain_version = yaml["kotlin_jvm_toolchain_version"] || 11 end # rubocop:enable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity diff --git a/lib/arkana/models/template_arguments.rb b/lib/arkana/models/template_arguments.rb index 77b3f70..15ba597 100644 --- a/lib/arkana/models/template_arguments.rb +++ b/lib/arkana/models/template_arguments.rb @@ -20,6 +20,10 @@ def initialize(environment_secrets:, global_secrets:, config:, salt:) @pod_name = config.pod_name # The top level namespace in which the keys will be generated. Often an enum. @namespace = config.namespace + # Name of the kotlin package to be used for the generated code. + @kotlin_package_name = config.kotlin_package_name + # The kotlin JVM toolchain JDK version to be used in the generated build.gradle file. + @kotlin_jvm_toolchain_version = config.kotlin_jvm_toolchain_version # The property declaration strategy declared in the config file. @swift_declaration_strategy = config.swift_declaration_strategy # Whether unit tests should be generated. diff --git a/lib/arkana/swift_code_generator.rb b/lib/arkana/swift_code_generator.rb index e29116b..0106d9e 100644 --- a/lib/arkana/swift_code_generator.rb +++ b/lib/arkana/swift_code_generator.rb @@ -17,11 +17,11 @@ def self.generate(template_arguments:, config:) def self.set_up_interfaces_swift_package(path, template_arguments, config) dirname = File.dirname(__FILE__) - readme_template = File.read("#{dirname}/templates/interfaces_readme.erb") - package_template = File.read("#{dirname}/templates/interfaces_package.swift.erb") - podspec_template = File.read("#{dirname}/templates/interfaces.podspec.erb") + readme_template = File.read("#{dirname}/templates/swift/interfaces_readme.erb") + package_template = File.read("#{dirname}/templates/swift/interfaces_package.swift.erb") + podspec_template = File.read("#{dirname}/templates/swift/interfaces.podspec.erb") sources_dir = File.join(path, "Sources") - source_template = File.read("#{dirname}/templates/arkana_protocol.swift.erb") + source_template = File.read("#{dirname}/templates/swift/arkana_protocol.swift.erb") FileUtils.mkdir_p(path) FileUtils.mkdir_p(sources_dir) render(podspec_template, template_arguments, File.join(path, "#{config.pod_name.capitalize_first_letter}Interfaces.podspec")) if config.package_manager == "cocoapods" @@ -33,12 +33,12 @@ def self.set_up_interfaces_swift_package(path, template_arguments, config) def self.set_up_swift_package(path, template_arguments, config) dirname = File.dirname(__FILE__) readme_template = File.read("#{dirname}/templates/readme.erb") - package_template = File.read("#{dirname}/templates/package.swift.erb") + package_template = File.read("#{dirname}/templates/swift/package.swift.erb") sources_dir = File.join(path, "Sources") - source_template = File.read("#{dirname}/templates/arkana.swift.erb") + source_template = File.read("#{dirname}/templates/swift/arkana.swift.erb") tests_dir = File.join(path, "Tests") if config.should_generate_unit_tests - tests_template = File.read("#{dirname}/templates/arkana_tests.swift.erb") - podspec_template = File.read("#{dirname}/templates/arkana.podspec.erb") + tests_template = File.read("#{dirname}/templates/swift/arkana_tests.swift.erb") + podspec_template = File.read("#{dirname}/templates/swift/arkana.podspec.erb") FileUtils.mkdir_p(path) FileUtils.mkdir_p(sources_dir) FileUtils.mkdir_p(tests_dir) if config.should_generate_unit_tests diff --git a/lib/arkana/templates/kotlin/arkana.kt.erb b/lib/arkana/templates/kotlin/arkana.kt.erb new file mode 100644 index 0000000..d364da3 --- /dev/null +++ b/lib/arkana/templates/kotlin/arkana.kt.erb @@ -0,0 +1,59 @@ +<% require "arkana/helpers/string" %> +<% require "arkana/helpers/kotlin_template_helper" %> +<% # TODO: Sort these import statements alphabetically %> +// DO NOT MODIFY +// Automatically generated by Arkana (https://github.com/rogerluan/arkana) +package <%= @kotlin_package_name %> + + +object <%= @namespace %> { + private val salt = listOf(<%= @salt.formatted %>) + + internal fun decode(encoded: List, cipher: List): String { + val decoded = encoded.mapIndexed { index, item -> + (item xor cipher[(index % cipher.size)]).toByte() + }.toByteArray() + return decoded.toString(Charsets.UTF_8) + } + + internal fun decodeInt(encoded: List, cipher: List): Int { + return decode(encoded = encoded, cipher = cipher).toInt() + } + + internal fun decodeBoolean(encoded: List, cipher: List): Boolean { + return decode(encoded = encoded, cipher = cipher).toBoolean() + } + + object Global { +<% @global_secrets.each_with_index do |secret, index| %> + val <%= secret.key.camel_case %>: <%= KotlinTemplateHelper.kotlin_type(secret.type) %> + + get() { + val encoded = listOf(<%= secret.encoded_value %>) + return <%= KotlinTemplateHelper.kotlin_decode_function(secret.type) %>(encoded = encoded, cipher = salt) + } +<% unless index == @global_secrets.length - 1 %> + +<% end %> +<% end %> + } + +<% @environments.each_with_index do |environment, env_index| %> + object <%= environment %> : <%= @namespace %>Environment { +<% environment_protocol_secrets(environment).each_with_index do |secret, secret_index| %> + override val <%= secret.protocol_key.camel_case %>: <%= KotlinTemplateHelper.kotlin_type(secret.type) %> + + get() { + val encoded = listOf(<%= secret.encoded_value %>) + return <%= KotlinTemplateHelper.kotlin_decode_function(secret.type) %>(encoded = encoded, cipher = salt) + } +<% unless secret_index == environment_protocol_secrets(environment).length - 1 %> + +<% end %> +<% end %> + } +<% unless env_index == @environments.length - 1 %> + +<% end %> +<% end %> +} diff --git a/lib/arkana/templates/kotlin/arkana_protocol.kt.erb b/lib/arkana/templates/kotlin/arkana_protocol.kt.erb new file mode 100644 index 0000000..1d313dc --- /dev/null +++ b/lib/arkana/templates/kotlin/arkana_protocol.kt.erb @@ -0,0 +1,13 @@ +<% require "arkana/helpers/string" %> +<% require "arkana/helpers/kotlin_template_helper" %> +// DO NOT MODIFY +// Automatically generated by Arkana (https://github.com/rogerluan/arkana) +package <%= @kotlin_package_name %> + + +interface <%= @namespace %>Environment { +<% for secret in @environment_secrets.uniq(&:protocol_key) %> + val <%= secret.protocol_key.camel_case %>: <%= KotlinTemplateHelper.kotlin_type(secret.type) %> + +<% end %> +} diff --git a/lib/arkana/templates/kotlin/arkana_tests.kt.erb b/lib/arkana/templates/kotlin/arkana_tests.kt.erb new file mode 100644 index 0000000..fc2ce09 --- /dev/null +++ b/lib/arkana/templates/kotlin/arkana_tests.kt.erb @@ -0,0 +1,137 @@ +<% require "arkana/helpers/string" %> +<% require "arkana/helpers/kotlin_template_helper" %> +// DO NOT MODIFY +// Automatically generated by Arkana (https://github.com/rogerluan/arkana) +package <%= @kotlin_package_name %> + + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue + +internal class <%= @namespace %>Test { + private val salt = listOf(<%= @salt.formatted %>) + private val globalSecrets = <%= @namespace %>.Global + + @Test + fun test_decodeRandomHexKey_shouldDecode() { +<% hex_key = SecureRandom.hex(64) %> +<% secret = generate_test_secret(key: hex_key) %> + val encoded = listOf(<%= secret.encoded_value %>) + assertEquals(<%= @namespace %>.decode(encoded = encoded, cipher = salt), "<%= hex_key %>") + } + + @Test + fun test_decodeRandomBase64Key_shouldDecode() { +<% base64_key = SecureRandom.base64(64) %> +<% secret = generate_test_secret(key: base64_key) %> + val encoded = listOf(<%= secret.encoded_value %>) + assertEquals(<%= @namespace %>.decode(encoded = encoded, cipher = salt), "<%= base64_key %>") + } + + @Test + fun test_decodeUUIDKey_shouldDecode() { +<% uuid_key = SecureRandom.uuid %> +<% secret = generate_test_secret(key: uuid_key) %> + val encoded = listOf(<%= secret.encoded_value %>) + assertEquals(<%= @namespace %>.decode(encoded = encoded, cipher = salt), "<%= uuid_key %>") + } + + @Test + fun test_decodeTrueBoolValue_shouldDecode() { +<% bool_key = "true" %> +<% secret = generate_test_secret(key: bool_key) %> + val encoded = listOf(<%= secret.encoded_value %>) + assertTrue(<%= @namespace %>.decodeBoolean(encoded = encoded, cipher = salt)) + } + + @Test + fun test_decodeFalseBoolValue_shouldDecode() { +<% bool_key = "false" %> +<% secret = generate_test_secret(key: bool_key) %> + val encoded = listOf(<%= secret.encoded_value %>) + assertFalse(<%= @namespace %>.decodeBoolean(encoded = encoded, cipher = salt)) + } + + @Test + fun test_decodeIntValue_shouldDecode() { +<% int_key = "42" %> +<% secret = generate_test_secret(key: int_key) %> + val encoded = listOf(<%= secret.encoded_value %>) + assertEquals(<%= @namespace %>.decodeInt(encoded = encoded, cipher = salt), 42) + } + + @Test + fun test_decodeIntValueWithLeadingZeroes_shouldDecodeAsString() { +<% int_with_leading_zeroes_key = "0001" %> +<% secret = generate_test_secret(key: int_with_leading_zeroes_key) %> + val encoded = listOf(<%= secret.encoded_value %>) + assertEquals(<%= @namespace %>.decode(encoded = encoded, cipher = salt), "0001") + } + + @Test + fun test_decodeMassiveIntValue_shouldDecodeAsString() { +<% int_with_massive_number_key = "92233720368547758079223372036854775807" %> +<% secret = generate_test_secret(key: int_with_massive_number_key) %> + val encoded = listOf(<%= secret.encoded_value %>) + assertEquals(<%= @namespace %>.decode(encoded = encoded, cipher = salt), "92233720368547758079223372036854775807") + } + + @Test + fun test_decodeNegativeIntValue_shouldDecodeAsString() { +<% negative_int_key = "-42" %> +<% secret = generate_test_secret(key: negative_int_key) %> + val encoded = listOf(<%= secret.encoded_value %>) + assertEquals(<%= @namespace %>.decode(encoded = encoded, cipher = salt), "-42") + } + + @Test + fun test_decodeFloatingPointValue_shouldDecodeAsString() { +<% float_key = "3.14" %> +<% secret = generate_test_secret(key: float_key) %> + val encoded = listOf(<%= secret.encoded_value %>) + assertEquals(<%= @namespace %>.decode(encoded = encoded, cipher = salt), "3.14") + } + + @Test + fun test_encodeAndDecodeValueWithDollarSign_shouldDecode() { +<% dollar_sign_key = "real_$lim_shady" %> +<% secret = generate_test_secret(key: dollar_sign_key) %> + val encoded = listOf(<%= secret.encoded_value %>) + assertEquals(<%= @namespace %>.decode(encoded = encoded, cipher = salt), "real_\$lim_shady") + } +<% if ENV["ARKANA_RUNNING_CI_INTEGRATION_TESTS"] %> + + @Test + fun test_decodeEnvVarFromDotfile_withDollarSign__andEscaped_andNoQuotes_shouldDecode() { + assertEquals(globalSecrets.secretWithDollarSignEscapedAndAndNoQuotesKey, "real_\$lim_shady") + } + + @Test + fun test_decodeEnvVarFromDotfile_withDollarSign__andEscaped_andDoubleQuotes_shouldDecode() { + assertEquals(globalSecrets.secretWithDollarSignEscapedAndDoubleQuoteKey, "real_\$lim_shady") + } + + @Test + fun test_decodeEnvVarFromDotfile_withDollarSign__andNotEscaped_andSingleQuotes_shouldDecode() { + assertEquals(globalSecrets.secretWithDollarSignNotEscapedAndSingleQuoteKey, "real_\$lim_shady") + } + + @Test + fun test_decodeEnvVarFromDotfile_withDollarSign__andNotEscaped_andDoubleQuotes_shouldDecodeWithUnexpectedValue() { + assertNotEquals(globalSecrets.secretWithDollarSignNotEscapedAndDoubleQuotesKey, "real_\$lim_shady") + } + + @Test + fun test_decodeEnvVarFromDotfile_withDollarSign__andNotEscaped_andNoQuotes_shouldDecodeWithUnexpectedValue() { + assertNotEquals(globalSecrets.secretWithDollarSignNotEscapedAndNoQuotesKey, "real_\$lim_shady") + } + + @Test + fun test_decodeEnvVarFromDotfile_withWeirdCharacters_shouldDecode() { + assertEquals(globalSecrets.secretWithWeirdCharactersKey, "` ~ ! @ # % ^ & * ( ) _ - + = { [ } } | : ; ' < , > . ? /") + } +<% end %> +} diff --git a/lib/arkana/templates/kotlin/build.gradle.kts.erb b/lib/arkana/templates/kotlin/build.gradle.kts.erb new file mode 100644 index 0000000..9428620 --- /dev/null +++ b/lib/arkana/templates/kotlin/build.gradle.kts.erb @@ -0,0 +1,18 @@ +// DO NOT MODIFY +// Automatically generated by Arkana (https://github.com/rogerluan/arkana) + +plugins { + id("kotlin") +} + +kotlin { + jvmToolchain(<%= @kotlin_jvm_toolchain_version %>) +} + +tasks.test { + useJUnitPlatform() +} + +dependencies { + testImplementation(kotlin("test")) +} diff --git a/lib/arkana/templates/arkana.podspec.erb b/lib/arkana/templates/swift/arkana.podspec.erb similarity index 100% rename from lib/arkana/templates/arkana.podspec.erb rename to lib/arkana/templates/swift/arkana.podspec.erb diff --git a/lib/arkana/templates/arkana.swift.erb b/lib/arkana/templates/swift/arkana.swift.erb similarity index 91% rename from lib/arkana/templates/arkana.swift.erb rename to lib/arkana/templates/swift/arkana.swift.erb index d8cf1f1..f03cebd 100644 --- a/lib/arkana/templates/arkana.swift.erb +++ b/lib/arkana/templates/swift/arkana.swift.erb @@ -1,5 +1,5 @@ -<% require 'arkana/helpers/string' %> -<% require 'arkana/helpers/swift_template_helper' %> +<% require "arkana/helpers/string" %> +<% require "arkana/helpers/swift_template_helper" %> <% # TODO: Sort these import statements alphabetically %> // DO NOT MODIFY // Automatically generated by Arkana (https://github.com/rogerluan/arkana) @@ -55,7 +55,7 @@ public extension <%= @namespace %> { } } -<% for environment in @environments %> +<% @environments.each_with_index do |environment, env_index| %> public extension <%= @namespace %> { struct <%= environment %>: <%= @namespace %>EnvironmentProtocol { public init() {} @@ -72,4 +72,7 @@ public extension <%= @namespace %> { <% end %> } } +<% unless env_index == @environments.length - 1 %> + +<% end %> <% end %> diff --git a/lib/arkana/templates/arkana_protocol.swift.erb b/lib/arkana/templates/swift/arkana_protocol.swift.erb similarity index 88% rename from lib/arkana/templates/arkana_protocol.swift.erb rename to lib/arkana/templates/swift/arkana_protocol.swift.erb index 9ba2095..2f72e06 100644 --- a/lib/arkana/templates/arkana_protocol.swift.erb +++ b/lib/arkana/templates/swift/arkana_protocol.swift.erb @@ -1,5 +1,5 @@ -<% require 'arkana/helpers/string' %> -<% require 'arkana/helpers/swift_template_helper' %> +<% require "arkana/helpers/string" %> +<% require "arkana/helpers/swift_template_helper" %> // DO NOT MODIFY // Automatically generated by Arkana (https://github.com/rogerluan/arkana) diff --git a/lib/arkana/templates/arkana_tests.swift.erb b/lib/arkana/templates/swift/arkana_tests.swift.erb similarity index 100% rename from lib/arkana/templates/arkana_tests.swift.erb rename to lib/arkana/templates/swift/arkana_tests.swift.erb diff --git a/lib/arkana/templates/interfaces.podspec.erb b/lib/arkana/templates/swift/interfaces.podspec.erb similarity index 100% rename from lib/arkana/templates/interfaces.podspec.erb rename to lib/arkana/templates/swift/interfaces.podspec.erb diff --git a/lib/arkana/templates/interfaces_package.swift.erb b/lib/arkana/templates/swift/interfaces_package.swift.erb similarity index 100% rename from lib/arkana/templates/interfaces_package.swift.erb rename to lib/arkana/templates/swift/interfaces_package.swift.erb diff --git a/lib/arkana/templates/interfaces_readme.erb b/lib/arkana/templates/swift/interfaces_readme.erb similarity index 100% rename from lib/arkana/templates/interfaces_readme.erb rename to lib/arkana/templates/swift/interfaces_readme.erb diff --git a/lib/arkana/templates/package.swift.erb b/lib/arkana/templates/swift/package.swift.erb similarity index 100% rename from lib/arkana/templates/package.swift.erb rename to lib/arkana/templates/swift/package.swift.erb diff --git a/spec/arkana_spec.rb b/spec/arkana_spec.rb index b6635b9..80622e0 100644 --- a/spec/arkana_spec.rb +++ b/spec/arkana_spec.rb @@ -47,5 +47,22 @@ expect { described_class.run(arguments) }.not_to raise_error end end + + context "when kotlin is specified as the language" do + let(:lang) { "kotlin" } + + before do + ARGV << "--lang" << lang + + config.all_keys.each do |key| + allow(ENV).to receive(:[]).with(key).and_return("lorem ipsum") + end + end + + it "calls KotlinCodeGenerator.generate" do + expect(KotlinCodeGenerator).to receive(:generate) + described_class.run(arguments) + end + end end end diff --git a/spec/config_parser_spec.rb b/spec/config_parser_spec.rb index e7bce4c..05bcfe9 100644 --- a/spec/config_parser_spec.rb +++ b/spec/config_parser_spec.rb @@ -40,6 +40,24 @@ end end + describe "#current_lang" do + describe "when language is specified in arguments" do + let(:lang) { "kotlin" } + + before { ARGV << "--lang" << lang } + + it "is the same as the language specified" do + expect(subject.current_lang).to eq lang + end + end + + describe "when flavor is not specified in arguments" do + it "is nil" do + expect(subject.current_flavor).to be_nil + end + end + end + describe "#dotenv_filepath" do context "when dotenv_filepath is specified" do context "when it exists" do diff --git a/spec/fixtures/kotlin-tests.yml b/spec/fixtures/kotlin-tests.yml new file mode 100644 index 0000000..d5e39f7 --- /dev/null +++ b/spec/fixtures/kotlin-tests.yml @@ -0,0 +1,32 @@ +namespace: 'MySecrets' +result_path: 'tests' +should_generate_unit_tests: true +should_generate_gradle_build_file: false +global_secrets: +- BoolAsStringTrueKey +- BoolAsStringFalseKey +- BoolAsBoolTrueKey +- BoolAsBoolFalseKey +- IntAsStringKey +- IntAsNumberKey +- IntWithLeadingZeroesAsStringKey +- IntWithLeadingZeroesAsNumberKey +- MassiveIntAsStringKey +- MassiveIntAsNumberKey +- NegativeIntAsStringKey +- NegativeIntAsNumberKey +- FloatAsStringKey +- FloatAsNumberKey +- SecretWithDollarSignEscapedAndAndNoQuotesKey +- SecretWithDollarSignEscapedAndDoubleQuoteKey +- SecretWithDollarSignNotEscapedAndSingleQuoteKey +- SecretWithDollarSignNotEscapedAndDoubleQuotesKey +- SecretWithDollarSignNotEscapedAndNoQuotesKey +- SecretWithWeirdCharactersKey +environments: + - dev + - staging + - prod +environment_secrets: + - ServiceKey + - Server diff --git a/spec/fixtures/kotlin/build.gradle.kts b/spec/fixtures/kotlin/build.gradle.kts new file mode 100644 index 0000000..cc22a4b --- /dev/null +++ b/spec/fixtures/kotlin/build.gradle.kts @@ -0,0 +1,22 @@ +plugins { + kotlin("jvm") version "1.8.20" + application +} + +group = "com.arkanakeys" + +repositories { + mavenCentral() +} + +dependencies { + testImplementation(kotlin("test")) +} + +tasks.test { + useJUnitPlatform() +} + +kotlin { + jvmToolchain(11) +} diff --git a/spec/fixtures/kotlin/gradle/wrapper/gradle-wrapper.jar b/spec/fixtures/kotlin/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/spec/fixtures/kotlin/gradle/wrapper/gradle-wrapper.jar differ diff --git a/spec/fixtures/kotlin/gradle/wrapper/gradle-wrapper.properties b/spec/fixtures/kotlin/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..15de902 --- /dev/null +++ b/spec/fixtures/kotlin/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/spec/fixtures/kotlin/gradlew b/spec/fixtures/kotlin/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/spec/fixtures/kotlin/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/spec/fixtures/kotlin/gradlew.bat b/spec/fixtures/kotlin/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/spec/fixtures/kotlin/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/spec/kotlin_code_generator_spec.rb b/spec/kotlin_code_generator_spec.rb new file mode 100644 index 0000000..ed9dbda --- /dev/null +++ b/spec/kotlin_code_generator_spec.rb @@ -0,0 +1,115 @@ +# frozen_string_literal: true + +RSpec.describe KotlinCodeGenerator do + let(:config) { Config.new(YAML.load_file("spec/fixtures/arkana-fixture.yml")) } + let(:salt) { SaltGenerator.generate } + let(:environment_secrets) do + Encoder.encode!( + keys: config.environment_keys, + salt: salt, + current_flavor: config.current_flavor, + environments: config.environments, + ) + end + + let(:global_secrets) do + Encoder.encode!( + keys: config.global_secrets, + salt: salt, + current_flavor: config.current_flavor, + environments: config.environments, + ) + end + + let(:template_arguments) do + TemplateArguments.new( + environment_secrets: environment_secrets, + global_secrets: global_secrets, + config: config, + salt: salt, + ) + end + + before do + config.all_keys.each do |key| + allow(ENV).to receive(:[]).with(key).and_return("value") + end + allow(ENV).to receive(:[]).with("ARKANA_RUNNING_CI_INTEGRATION_TESTS").and_return(true) + end + + after { FileUtils.rm_rf(config.result_path) } + + describe ".generate" do + let(:kotlin_module_dir) { config.result_path } + let(:kotlin_sources_dir) { File.join(kotlin_module_dir, "src", "main", config.kotlin_sources_path, config.kotlin_package_name.split(".")) } + let(:kotlin_tests_dir) { File.join(kotlin_module_dir, "src", "test", config.kotlin_sources_path, config.kotlin_package_name.split(".")) } + + # NOTE: Can't use: + # def path(...) + # Pathname.new(File.join(...)) + # end + # Until the minimum target version is Ruby 2.7 + def path(arg1, arg2, arg3 = nil) + arg1and2 = File.join(arg1, arg2) + return Pathname.new(arg1and2) unless arg3 + + Pathname.new(File.join(arg1and2, arg3)) if arg3 + end + + it "generates all necessary directories and files" do + described_class.generate(template_arguments: template_arguments, config: config) + expect(Pathname.new(config.result_path)).to be_directory + expect(path(kotlin_module_dir, "README.md")).to be_file + expect(path(kotlin_module_dir, "build.gradle.kts")).to be_file + expect(path(kotlin_sources_dir, "#{config.namespace}Environment.kt")).to be_file + expect(path(kotlin_sources_dir, "#{config.namespace}.kt")).to be_file + end + + context "when 'config.should_generate_gradle_build_file'" do + context "when is 'true'" do + before do + allow(config).to receive(:should_generate_gradle_build_file).and_return(true) + described_class.generate(template_arguments: template_arguments, config: config) + end + + it "generates gradle build file" do + expect(path(kotlin_module_dir, "build.gradle.kts")).to be_file + end + end + + context "when is 'false'" do + before do + allow(config).to receive(:should_generate_gradle_build_file).and_return(false) + described_class.generate(template_arguments: template_arguments, config: config) + end + + it "generates gradle build file" do + expect(path(kotlin_module_dir, "build.gradle.kts")).not_to be_file + end + end + end + + context "when 'config.should_generate_unit_tests' is true" do + before do + allow(config).to receive(:should_generate_unit_tests).and_return(true) + described_class.generate(template_arguments: template_arguments, config: config) + end + + it "generates test folder and files" do + expect(path(kotlin_tests_dir, "#{config.namespace}Test.kt")).to be_file + end + end + + context "when 'config.should_generate_unit_tests' is false" do + before do + allow(config).to receive(:should_generate_unit_tests).and_return(false) + described_class.generate(template_arguments: template_arguments, config: config) + end + + it "does not generate test folder or files" do + expect(path(kotlin_tests_dir, "#{config.namespace}Test.kt")).not_to be_file + expect(Pathname.new(kotlin_tests_dir)).not_to be_directory + end + end + end +end diff --git a/template.yml b/template.yml index c286e93..3ac391e 100644 --- a/template.yml +++ b/template.yml @@ -9,6 +9,10 @@ swift_declaration_strategy: let # Optional. One of: lazy var, var, let. Defaults should_generate_unit_tests: true # Optional. One of: true, false. Defaults to true. should_cocoapods_cross_import_modules: true # Optional. If false, the two generated cocoapods pods do not cross import (for manual import of the Sources folders), useful when building SDKs, for instance. One of: true, false. Defaults to true. package_manager: cocoapods # Optional. This setting defines which type of dependency management you're going to use to integrate Arkana into your project. One of: spm, cocoapods. If you use both in your project, use cocoapods here. Defaults to spm. +kotlin_package_name: 'com.arkanakeys' # Optional. The package name of the generated Kotlin module. Defaults to com.arkanakeys. +kotlin_sources_path: 'java' # Optional. The path for the generated Kotlin classes. Defaults to kotlin. +should_generate_gradle_build_file: true # Optional. Whether a build.gradle file should be generated, when running the Kotlin generator. One of: true, false. Defaults to true. +kotlin_jvm_toolchain_version: 11 # Optional. The kotlin JVM toolchain JDK version to be used in the generated build.gradle file. Defaults to 11. environments: # Optional. List of environments that will be used to generate secret keys when you have keys that are different between environments (e.g. debug/staging/prod). Defaults to empty. - Debug - Release