YAML support for kotlinx.serialization

Overview

kaml

Pipeline Coverage License Maven Central

What is this?

This library adds YAML support to kotlinx.serialization.

YAML version 1.2 is supported.

Usage samples

Parsing from YAML to a Kotlin object

@Serializable
data class Team(
    val leader: String,
    val members: List<String>
)

val input = """
        leader: Amy
        members:
          - Bob
          - Cindy
          - Dan
    """.trimIndent()

val result = Yaml.default.decodeFromString(Team.serializer(), input)

println(result)

Serializing from a Kotlin object to YAML

@Serializable
data class Team(
    val leader: String,
    val members: List<String>
)

val input = Team("Amy", listOf("Bob", "Cindy", "Dan"))

val result = Yaml.default.encodeToString(Team.serializer(), input)

println(result)

Referencing kaml

Add the following to your Gradle build script:

Groovy DSL

plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.4.20'
    id 'org.jetbrains.kotlin.plugin.serialization' version '1.4.20'
}

dependencies {
  implementation "com.charleskorn.kaml:kaml:<version number here>" // Get the latest version number from https://github.com/charleskorn/kaml/releases/latest
}

Kotlin DSL

plugins {
    kotlin("jvm") version "1.4.20"
    kotlin("plugin.serialization") version "1.4.20"
}

dependencies {
  implementation("com.charleskorn.kaml:kaml:<version number here>") // Get the latest version number from https://github.com/charleskorn/kaml/releases/latest
}

Check the releases page for the latest release information, and the Maven Central page for examples of how to reference the library in other build systems.

Features

  • Supports most major YAML features:

  • Supports parsing YAML to Kotlin objects (deserializing) and writing Kotlin objects as YAML (serializing)

  • Supports kotlinx.serialization's polymorphism for sealed and unsealed types

    Two styles are available (set YamlConfiguration.polymorphismStyle when creating an instance of Yaml):

    • using YAML tags to specify the type:

      servers:
        - !<frontend>
          hostname: a.mycompany.com
        - !<backend>
          database: db-1
    • using a type property to specify the type:

      servers:
        - type: frontend
          hostname: a.mycompany.com
        - type: backend
          database: db-1

    The fragments above could be generated with:

    @Serializable
    sealed class Server {
      @SerialName("frontend")
      @Serializable
      data class Frontend(val hostname: String)
    
      @SerialName("backend")
      @Serializable
      data class Backend(val database: String)
    }
    
    @Serializable
    data class Config(val servers: List<Server>)
    
    val config = Config(listOf(
      Frontend("a.mycompany.com"),
      Backend("db-1")
    ))
    
    val result = Yaml.default.encodeToString(Config.serializer(), config)
    
    println(result)
  • Supports Docker Compose-style extension fields

    x-common-labels: &common-labels
      labels:
        owned-by: [email protected]
        cost-centre: myteam
    
    servers:
      server-a:
        <<: *common-labels
        kind: frontend
    
      server-b:
        <<: *common-labels
        kind: backend
    
      # server-b and server-c are equivalent
      server-c:
        labels:
          owned-by: [email protected]
          cost-centre: myteam
        kind: backend

    Specify the extension prefix by setting YamlConfiguration.extensionDefinitionPrefix when creating an instance of Yaml (eg. "x-" for the example above).

    Extensions can only be defined at the top level of a document, and only if the top level element is a map or object. Any key starting with the extension prefix must have an anchor defined (&...) and will not be included in the deserialised value.

Contributing to kaml

Pull requests and bug reports are always welcome!

kaml uses Batect to simplify development environment setup:

  • To build the library: ./batect build
  • To run the tests and static analysis tools: ./batect check
  • To run the tests and static analysis tools continuously: ./batect continuousCheck

Other commands are available by running ./batect --list-tasks

Reference links

Comments
  • Custom Polymorphic Serialization

    Custom Polymorphic Serialization

    Didn't want to pollute the #29 feature request, so I'm opening a new question (or bug) issue. :-)

    I tried to make a custom serializer as you suggested, following the official example https://github.com/Kotlin/kotlinx.serialization/blob/v0.20.0/runtime/commonTest/src/kotlinx/serialization/json/JsonTreeAndMapperTest.kt#L35 that is linked to from the docs about custom serializers.

    In the GitHub action yml file you can have

    outputs:
        foo:
            description: bar
            value: baz
    
    runs:
        using: composite
    

    or

    outputs:
        foo:
            description: bar
    
    runs:
        using: something else
    

    Meaning the output has a mandatory value property if it is a composite action but no value property if it is a normal action.

    Previously I didn't support composite, so I had

    @Serializable
    data class GitHubAction(
            /* ... */
            val outputs: Map<String, Output>? = null,
            /* ... */
    ) {
        /* ... */
        @Serializable
        data class Output(
                val description: String
        )
        /* ... */
    }
    

    I now changed it to

    @Serializable
    data class GitHubAction(
            /* ... */
            val outputs: Map<String, Output>? = null,
            /* ... */
    ) {
        /* ... */
        sealed class Output {
            abstract val description: String
    
            data class NormalOutput(
                    override val description: String
            ) : Output()
    
            data class CompositeOutput(
                    override val description: String,
                    val value: String
            ) : Output()
    
            @Serializer(forClass = Output::class)
            companion object : KSerializer<Output> {
                override val descriptor: SerialDescriptor = SerialDescriptor("net.kautler.dao.GitHubAction.Output", SEALED) {
                    element("normal", SerialDescriptor("net.kautler.dao.GitHubAction.Output.NormalOutput") {
                        element("description", PrimitiveDescriptor("net.kautler.dao.GitHubAction.Output.NormalOutput.description", STRING))
                    })
                    element("composite", SerialDescriptor("net.kautler.dao.GitHubAction.Output.CompositeOutput") {
                        element("description", PrimitiveDescriptor("net.kautler.dao.GitHubAction.Output.CompositeOutput.description", STRING))
                        element("value", PrimitiveDescriptor("net.kautler.dao.GitHubAction.Output.CompositeOutput.value", STRING))
                    })
                }
    
                override fun deserialize(decoder: Decoder): Output {
                    TODO("deserialize: Not yet implemented")
                }
    
                override fun serialize(encoder: Encoder, value: Output) {
                    TODO("serialize: Not yet implemented")
                }
            }
        }
        /* ... */
    }
    

    The problem is, that it seems to not being used. When I had a TODO() in the descriptor it failed accordingly. But when I now try to deserialize an action file, I get complaint from kaml about missing type tag instead of the custom serializer being used. Do I do something wrong or is there a bug in kaml?

    help wanted question 
    opened by Vampire 17
  • Question: Are you able to use Intellij with this project?

    Question: Are you able to use Intellij with this project?

    I tried to use kaml in an unrelated project and was unable to make Idea happy with it. I have the latest version of Idea for macOS 2019.3.

    So I git cloned your repo to see how it fares and see the same issues

    image

    Have you found some magic to convince IJ to work with you? Care to share that magic? thx!

    question 
    opened by javadba 12
  • Non-JVM targets are not supported

    Non-JVM targets are not supported

    Describe the bug

    Hey, TBH I'm not sure if this is a bug or just not implemented yet, I'm very new to Kotlin Multiplatform :) I'm trying to leverage Kaml to deserialize some YAML files in a MPP project, but it seems like trying to leverage Kaml in commonMain is not implemented yet when targeting non-JVM applications.

    FAILURE: Build failed with an exception.
    
    * What went wrong:
    Could not determine the dependencies of task ':satisfaketion-generators:jsTestPackageJson'.
    > Could not resolve all dependencies for configuration ':satisfaketion-generators:jsTestNpm'.
       > Could not resolve com.charleskorn.kaml:kaml:0.40.0.
         Required by:
             project :satisfaketion-generators
          > No matching variant of com.charleskorn.kaml:kaml:0.40.0 was found. The consumer was configured to find a usage of 'kotlin-runtime' of a library, preferably optimized for non-jvm, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'js', attribute 'org.jetbrains.kotlin.js.compiler' with value 'ir' but:
              - Variant 'jvmApiElements-published' capability com.charleskorn.kaml:kaml:0.40.0 declares a library:
                  - Incompatible because this component declares an API of a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'jvm' and the consumer needed a usage of 'kotlin-runtime' of a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'js'
                  - Other compatible attributes:
                      - Doesn't say anything about its target Java environment (preferred optimized for non-jvm)
                      - Doesn't say anything about org.jetbrains.kotlin.js.compiler (required 'ir')
              - Variant 'jvmRuntimeElements-published' capability com.charleskorn.kaml:kaml:0.40.0 declares a runtime of a library:
                  - Incompatible because this component declares a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'jvm' and the consumer needed a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'js'
                  - Other compatible attributes:
                      - Doesn't say anything about its target Java environment (preferred optimized for non-jvm)
                      - Doesn't say anything about org.jetbrains.kotlin.js.compiler (required 'ir')
              - Variant 'metadataApiElements' capability com.charleskorn.kaml:kaml:0.40.0 declares a library:
                  - Incompatible because this component declares a usage of 'kotlin-api' of a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'common' and the consumer needed a usage of 'kotlin-runtime' of a component, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'js'
                  - Other compatible attributes:
                      - Doesn't say anything about its target Java environment (preferred optimized for non-jvm)
                      - Doesn't say anything about org.jetbrains.kotlin.js.compiler (required 'ir')
    

    Reproduction repo

    So, this is the repo I am currently trying to convert to multiplatform https://github.com/unredundant/satisfaketion. More specifically, the generators module. I can't actually push the code b/c I have some (clearly too lofty) git hooks that prevent me from pushing a broken gradle build and I'm too lazy to delete them ๐Ÿ˜… If it would really help I can temporarily remove them and push the code. But effectively, I have a gradle build file like this

    plugins {
      kotlin("multiplatform")
      // ...
    }
    
    // ...
    
    kotlin {
      sourceSets {
        val commonMain by getting {
          dependencies {
            implementation(kotlin("stdlib"))
            api(projects.satisfaketionCore)  // project dependency (also multiplatform)
            implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2")
            implementation("com.charleskorn.kaml:kaml:0.40.0")
          }
        }
        val commonTest by getting
        val jvmMain by getting 
        val jvmTest by getting
        val jsMain by getting
        val jsTest by getting
        val nativeMain by getting
        val nativeTest by getting
      }
    }
    
    

    which leads to the error posted above.

    Steps to reproduce

    1. Import kaml dependency into MPP project which targets at least JS (presumably native has same issue?)
    2. Try to build
    3. ~~Weep~~ Profit?

    Expected behaviour

    I'm not sure this is expected behavior, but it would be nice if this was supported :)

    Actual behaviour

    Stacktrace sadness :(

    Version information

    Kaml 0.40.0
    Kotlin 1.6.10
    

    Any other information

    No response

    enhancement help wanted stale 
    opened by unredundant 10
  • Added Configuration Support for Ignoring Empty Document

    Added Configuration Support for Ignoring Empty Document

    This adds ignoreEmptyDocument to the Configuration (default false)

    When true, it doesnt throw an EmptyYamlDocumentException when the document is empty.

    Solves #284 (from Discussion #281)

    opened by DasLixou 9
  • YamlScalar loses type information

    YamlScalar loses type information

    Describe the bug

    I've written a tiny function to convert YamlNode's into JsonElement's (the stuff I'm reading is always JSON compatible). As part of that I have to convert YamlScalar to JsonPrimitive.

    I generally I don't have an issue with kaml's approach to scalars, however it is a little unfortunate that it even loses whether the scalar was a string (as-in: the value was quoted). I'm not sure how much type information snakeyaml profiles, but it would be great to retain as much as possible to make format conversions easier.

    My current converter tries to convert the string value from the scalar into the various number types until one of them work. If everything fails I assume it to be a string. However that will lead to scalars like '1' to be interpreted as a number on the JSON side, even through it was originally explicitly quoted.

    Reproduction repo

    private inline fun <T : Any> tryConversion(conversion: () -> T): T? {
        return try {
            conversion()
        } catch (e: YamlScalarFormatException) {
            null
        }
    }
    
    
    private fun yamlNodeToJsonElement(yamlNode: YamlNode): JsonElement {
        return when (yamlNode) {
            is YamlList -> JsonArray(yamlNode.items.map(::yamlNodeToJsonElement))
            is YamlMap -> JsonObject(yamlNode.entries.map { (key, value) -> Pair(key.content, yamlNodeToJsonElement(value)) }.toMap())
            is YamlNull -> JsonNull
            is YamlScalar -> {
                tryConversion { JsonPrimitive(yamlNode.toBoolean()) }
                    ?: tryConversion { JsonPrimitive(yamlNode.toByte()) }
                    ?: tryConversion { JsonPrimitive(yamlNode.toShort()) }
                    ?: tryConversion { JsonPrimitive(yamlNode.toInt()) }
                    ?: tryConversion { JsonPrimitive(yamlNode.toLong()) }
                    ?: tryConversion { JsonPrimitive(yamlNode.toFloat()) }
                    ?: tryConversion { JsonPrimitive(yamlNode.toDouble()) }
                    ?: JsonPrimitive(yamlNode.content)
            }
            is YamlTaggedNode -> yamlNodeToJsonElement(yamlNode.innerNode)
        }
    }
    
    

    Steps to reproduce

    use a document like

    some-string: '1'
    

    parse it into a YamlNode and convert it to a JsonElement of the same type.

    Expected behaviour

    Some why to extract type information from the original yaml document.

    Actual behaviour

    All type information is lost.

    Version information

    0.46.0
    

    Any other information

    No response

    wontfix stale 
    opened by pschichtel 7
  • Ability to serialize/deserialize unstructured data

    Ability to serialize/deserialize unstructured data

    Describe the problem you'd like to solve

    Sometimes I need to be able to break the glass and serialize/deserialize YAML without having well-structured POJOs/KOJOs.

    Describe the solution you'd like

    I'd like a canonical "vanilla" representation of YAML. It does not have to implement all YAML features (e.g., SnakeYAML chokes on tags in its vanilla codec implementation, and I'd be fine with that behavior). It could be a codec for YamlNode or Any or a new class created for this purpose.

    This would bring it in line with other languages' YAML implementations such as Python's and Ruby's.

    Describe alternatives you've considered

    A combination of SnakeYAML and Moshi.

    Additional context

    My context is also multi-document YAML streams from Kubernetes, just like #54 's case.

    enhancement good first issue stale 
    opened by sjshuck 7
  • Add support for different flow styles in Sequences

    Add support for different flow styles in Sequences

    This adds support for the Flow Style of rendering Sequences, by adding a parameter to YamlConfiguration

    The default block style is still used to avoid breaking anything.

    This is referenced in #33

    opened by knightzmc 7
  • Wrong encoding used for stream methods

    Wrong encoding used for stream methods

    Describe the bug

    The current code uses for example InputStreamReader(source). This uses the JVM default encoding. From Java 18 on, this will usually be UTF-8 but can also be reconfigured. Before Java 18, this is system dependent and often is not UTF-8. And even if it were always UTF-8, Yaml parsers have to support UTF-8 and UTF-16 with and without BOM for 1.1 and also UTF-32 for 1.2.

    From a quick look the writing stream methods always use UTF-8, for those it might be handy to be able to supply the wanted encoding.

    But more important, for the reading stream methods you need a detection algorithm with a push-back stream, so that you can detect BOM and act accordingly and if none found, fall back to UTF-8.

    You could also consider adding methods that take a Reader / Writer instead as there the encoding is already given by the caller.

    Reproduction repo

    No response

    Steps to reproduce

    • have a YAML with รถ in it with UTF-8 encoding
    • set the jvm default encoding to ISO-8859-1
    • deserialize the YAML and you get รƒยถ instead of the รถ

    Expected behaviour

    You get รถ

    Actual behaviour

    You get รƒยถ

    Version information

    0.46.0
    

    Any other information

    No response

    bug stale 
    opened by Vampire 6
  • Make decodeFromReader() public, add encodeToWriter(), encodeToStream()

    Make decodeFromReader() public, add encodeToWriter(), encodeToStream()

    Describe the problem you'd like to solve

    The methods on the Yaml object for reading and writing are not balanced.

    Describe the solution you'd like

    I propose to make decodeFromReader() public, and to add encodeToWriter() and encodeToStream() as encoding methods that correspond to the decoding methods.

    Describe alternatives you've considered

    No response

    Additional context

    No response

    enhancement good first issue 
    opened by Virtlink 6
  • Option to resolve $ref style references

    Option to resolve $ref style references

    Describe the problem you'd like to solve

    image I want to resolve references like this one. The reference points to another node in the same file.

    I don't know how I would do this with the normal kotlinx.serialization api, but for the yaml parser itself this should be possible.

    Describe the solution you'd like

    Could there be an option to enable that these references get resolved automatically?

    Describe alternatives you've considered

    No response

    Additional context

    No response

    opened by jakobkmar 6
  • How to remove type information with polymorphic output?

    How to remove type information with polymorphic output?

    I'm working on a dsl for Azure DevOps YAML Pipelines and they have a block called variables that can contain a few types.

    variables:
      # a variable can be created in 2 different ways
      - myVar:  'myVarValue'
      - name: myVar
         value: 'myVarValue'
         readonly: true
      # a group can be created in 1 way, but always has the same key
      - group: myFirstGroup
      - group: mySecondGroup
      - group: myThirdGroup
    

    I've been working on this for a while now and by now I have been able to create a list of Variable

    @Serializable
    abstract class VariableBase {
        abstract val name: String
    }
    
    @Serializable
    class Variable(override val name: String, val value: String, val readonly: Boolean = false) : VariableBase()
    
    @Serializable
    data class Group(override val name: String) : VariableBase()
    
    @Serializable
    class Variables {
        var variables = mutableListOf<VariableBase>()
    
        fun variable(name: String, value: String, readonly: Boolean = false) {
            this.variables.add(Variable(name, value, readonly))
        }
    
        fun group(name: String) {
            this.variables.add(Group(name))
        }
    }
    
    val variables = Variables()
    variables.variable("myVar", "myValue")
    variables.group("myFirstGroup")
    variables.group("mySecondGroup")
    variables.group("myThirdGroup")
    
    val result = Yaml(
        configuration = YamlConfiguration(
            polymorphismStyle = PolymorphismStyle.Property
        ),
        serializersModule = SerializersModule {
            polymorphic(VariableBase::class) {
                subclass(Variable::class)
                subclass(Group::class)
            }
        })
        .encodeToString(Variables.serializer(), variables)
    
    print(result)
    

    This will generate the following output:

    variables:
    - type: "Variable"
      name: "myVar"
      value: "myValue"
      readonly: false
    - type: "Group"
      name: "myFirstGroup"
    - type: "Group"
      name: "mySecondGroup"
    - type: "Group"
      name: "myThirdGroup"
    

    So how would I be able to create the list that is required to create an Azure DevOps YAML Pipeline variables block?

    I guess it might be an idea to add a PolymorphismStyle.None to prevent a type output. I'll create a PR if you think that is a good idea.

    question state:waiting for response 
    opened by johanvergeer 6
  • Update dependency com.pinterest:ktlint to v0.48.1

    Update dependency com.pinterest:ktlint to v0.48.1

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | com.pinterest:ktlint | 0.47.1 -> 0.48.1 | age | adoption | passing | confidence |


    Release Notes

    pinterest/ktlint

    v0.48.1

    Compare Source

    Added
    Removed
    Fixed
    • An enumeration class having a primary constructor and in which the list of enum entries is followed by a semicolon then do not remove the semicolon in case it is followed by code element no-semi (#โ€‹1733)
    • Add API so that KtLint API consumer is able to process a Kotlin script snippet without having to specify a file path (#โ€‹1738)
    • Disable the standard:filename rule whenever Ktlint CLI is run with option --stdin (#โ€‹1742)
    • Fix initialization of the logger when --log-level is specified. Throw exception when an invalid value is passed. (#โ€‹1749)
    • Fix loading of custom rule set JARs.
    • Rules provided via a custom rule set JAR (Ktlint CLI) or by an API provider are enabled by default. Only rules in the experimental rule set are disabled by default. (#โ€‹1747)
    Changed
    • Update Kotlin development version to 1.8.0 and Kotlin version to 1.8.0.

    v0.48.0

    Compare Source

    Indent rule

    The indent rule has been rewritten from scratch. Solving problems in the old algorithm was very difficult. With the new algorithm this becomes a lot easier. Although the new implementation of the rule has been compared against several open source projects containing over 400,000 lines of code, it is still likely that new issues will be discovered. Please report your indentation issues so that these can be fixed as well.

    .editorconfig property to disable rules

    In the previous release (0.47.x), the .editorconfig property disabled_rules was deprecated and replaced with ktlint_disabled_rules. This latter property has now been deprecated as well in favour of a more flexible and better maintainable solution. Rule and rule sets can now be enabled/disabled with a separate property per rule (set). Please read deprecation of (ktlint_)disable_rules property for more information.

    The KtLint CLI has not been changed. Although you can still use parameter --experimental to enable KtLint's Experimental rule set, you might want to set .editorconfig property ktlint_experimental = enabled instead.

    API Changes & RuleSet providers

    If you are not an API consumer or Rule Set provider then you can skip this section.

    Class relocations

    Classes below have been relocated:

    • Class com.pinterest.ktlint.core.api.UsesEditorConfigProperties.EditorConfigProperty has been replaced with com.pinterest.ktlint.core.api.editorconfig.EditorConfigProperty.
    • Class com.pinterest.ktlint.core.KtLintParseException has been replaced with com.pinterest.ktlint.core.api.KtLintParseException.
    • Class com.pinterest.ktlint.core.RuleExecutionException has been replaced with com.pinterest.ktlint.core.api.KtLintRuleException.
    • Class com.pinterest.ktlint.reporter.format.internal.Color has been moved to com.pinterest.ktlint.reporter.format.Color.
    • Class com.pinterest.ktlint.reporter.plain.internal.Color has been moved to com.pinterest.ktlint.reporter.plain.Color.
    Invoking lint and format

    This is the last release that supports the ExperimentalParams to invoke the lint and format functions of KtLint. The ExperimentalParams contains a mix of configuration settings which are not dependent on the file/code which is to be processed. Other parameters in that class describe the code/file to be processed but can be configured inconsistently (for example a file with name "foo.kt" could be marked as a Kotlin Script file).

    The static object KtLint is deprecated and replaced by class KtLintRuleEngine which is configured with KtLintRuleEngineConfiguration. The instance of the KtLintRuleEngine is intended to be reused for scanning all files in a project and should not be recreated per file.

    Both lint and format are simplified and can now be called for a code block or for an entire file.

    import java.io.File
    
    // Define a reusable instance of the KtLint Rule Engine
    val ktLintRuleEngine = KtLintRuleEngine(
      // Define configuration
    )
    
    // Process a collection of files
    val files: Set<File> // Collect files in a convenient way
    files.forEach(file in files) {
        ktLintRuleEngine.lint(file) {
            // Handle lint violations
        }
    }
    
    // or process a code sample for a given filepath
    ktLintRuleEngine.lint(
      code = "code to be linted",
      filePath = Path("/path/to/source/file")
    ) {
      // Handle lint violations
    }
    
    Retrieve .editorconfigs

    The list of .editorconfig files which will be accessed by KtLint when linting or formatting a given path can now be retrieved with the new API KtLint.editorConfigFilePaths(path: Path): List<Path>.

    This API can be called with either a file or a directory. It's intended usage is that it is called once with the root directory of a project before actually linting or formatting files of that project. When called with a directory path, all .editorconfig files in the directory or any of its subdirectories (except hidden directories) are returned. In case the given directory does not contain an .editorconfig file or if it does not contain the root=true setting, the parent directories are scanned as well until a root .editorconfig file is found.

    Calling this API with a file path results in the .editorconfig files that will be accessed when processing that specific file. In case the directory in which the file resides does not contain an .editorconfig file or if it does not contain the root=true setting, the parent directories are scanned until a root .editorconfig file is found.

    Psi filename replaces FILE_PATH_USER_DATA_KEY

    Constant KtLint.FILE_PATH_USER_DATA_KEY is deprecated and will be removed in KtLint version 0.49.0. The file name will be passed correctly to the node with element type FILE and can be retrieved as follows:

    if (node.isRoot()) {
        val fileName = (node.psi as? KtFile)?.name
        ...
    }
    
    Added
    • Wrap blocks in case the max line length is exceeded or in case the block contains a new line wrapping (#โ€‹1643)
    • patterns can be read in from stdin with the --patterns-from-stdin command line options/flags (#โ€‹1606)
    • Add basic formatting for context receiver in indent rule and new experimental rule context-receiver-wrapping (#โ€‹1672)
    • Add naming rules for classes and objects (class-naming), functions (function-naming) and properties (property-naming) (#โ€‹44)
    • Add new built-in reporter plain-summary which prints a summary the number of violation which have been autocorrected or could not be autocorrected, both split by rule.
    Fixed
    • Let a rule process all nodes even in case the rule is suppressed for a node so that the rule can update the internal state (#โ€‹1644)
    • Read .editorconfig when running CLI with options --stdin and --editorconfig (#โ€‹1651)
    • Do not add a trailing comma in case a multiline function call argument is found but no newline between the arguments trailing-comma-on-call-site (#โ€‹1642)
    • Add missing ktlint_disabled_rules to exposed editorConfigProperties (#โ€‹1671)
    • Do not add a second trailing comma, if the original trailing comma is followed by a KDOC trailing-comma-on-declaration-site and trailing-comma-on-call-site (#โ€‹1676)
    • A function signature preceded by an annotation array should be handled similar as function preceded by a singular annotation function-signature (#โ€‹1690)
    • Fix offset of annotation violations
    • Fix line offset when blank line found between class and primary constructor
    • Remove needless blank line between class followed by EOL, and primary constructor
    • Fix offset of unexpected linebreak before assignment
    • Remove whitespace before redundant semicolon if the semicolon is followed by whitespace
    Changed
    • Update Kotlin development version to 1.8.0-RC and Kotlin version to 1.7.21.
    • The default value for trailing comma's on call site is changed to true unless the android codestyle is enabled. Note that KtLint from a consistency viewpoint enforces the trailing comma on call site while default IntelliJ IDEA formatting only allows the trailing comma but leaves it up to the developer's discretion. (#โ€‹1670)
    • The default value for trailing comma's on declaration site is changed to true unless the android codestyle is enabled. Note that KtLint from a consistency viewpoint enforces the trailing comma on declaration site while default IntelliJ IDEA formatting only allows the trailing comma but leaves it up to the developer's discretion. (#โ€‹1669)
    • CLI options --debug, --trace, --verbose and -v are replaced with --log-level=<level> or the short version `-l=, see CLI log-level. (#โ€‹1632)
    • In CLI, disable logging entirely by setting --log-level=none or -l=none (#โ€‹1652)
    • Rewrite indent rule. Solving problems in the old algorithm was very difficult. With the new algorithm this becomes a lot easier. Although the new implementation of the rule has been compared against several open source projects containing over 400,000 lines of code, it is still likely that new issues will be discovered. Please report your indentation issues so that these can be fixed as well. (#โ€‹1682, #โ€‹1321, #โ€‹1200, #โ€‹1562, #โ€‹1563, #โ€‹1639)
    • Add methods "ASTNode.upsertWhitespaceBeforeMe" and "ASTNode.upsertWhitespaceAfterMe" as replacements for "LeafElement.upsertWhitespaceBeforeMe" and "LeafElement.upsertWhitespaceAfterMe". The new methods are more versatile and allow code to be written more readable in most places. (#โ€‹1687)
    • Rewrite indent rule. Solving problems in the old algorithm was very difficult. With the new algorithm this becomes a lot easier. Although the new implementation of the rule has been compared against several open source projects containing over 400,000 lines of code, it is still likely that new issues will be discovered. Please report your indentation issues so that these can be fixed as well. (#โ€‹1682, #โ€‹1321, #โ€‹1200, #โ€‹1562, #โ€‹1563, #โ€‹1639, #โ€‹1688)
    • Add support for running tests on java 19, remove support for running tests on java 18.
    • Update io.github.detekt.sarif4k:sarif4k version to 0.2.0 (#โ€‹1701).

    Configuration

    ๐Ÿ“… Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    ๐Ÿšฆ Automerge: Enabled.

    โ™ป Rebasing: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

    ๐Ÿ”• Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

    is:dependency-update 
    opened by renovate[bot] 0
  • Adding test with named enum values

    Adding test with named enum values

    Hi @charleskorn

    I ran into some trouble when parsing an enum with explicit serial names into a config using Hoplite. Was trying to pinpoint the issue, and it seems it's not in KAML ๐Ÿ™‚ If you feel there's any value to adding the tests you're welcome to merge this, otherwise just close it.

    opened by Kantis 1
  • Support for YAML transformations like there is for JSON

    Support for YAML transformations like there is for JSON

    I've just read https://github.com/Kotlin/kotlinx.serialization/blob/v0.20.0/docs/json_transformations.md and really like that. But I need that for YAML. If you want to deserialize a GitHub action definition file, you have for example exactly the use-case of polymorphism by shape. Would be really cool if kaml would also have such functionality built-in.

    (Don't wonder that I'm reading the 0.20.0 docs, I'm using this in a Gradle build and therefore I cannot use 1.4.0 yet)

    enhancement help wanted frozen 
    opened by Vampire 7
Releases(0.49.0)
Owner
Charles Korn
Charles Korn
Android Parcelable support for the Kotlinx Serialization library.

Android Parcelable support for the Kotlinx Serialization library.

Christopher 50 Nov 20, 2022
CSV and FixedLength Formats for kotlinx-serialization

Module kotlinx-serialization-csv Serialize and deserialize ordered CSV and Fixed Length Format Files with kotlinx-serialization. Source code Docs Inst

Philip Wedemann 12 Dec 16, 2022
Kotlin tooling for generating kotlinx.serialization serializers for serializing a class as a bitmask

kotlinx-serialization-bitmask Kotlin tooling for generating kotlinx.serialization serializers for serializing a class as a bitmask. Example @Serializa

marie 2 May 29, 2022
Type-safe arguments for JetPack Navigation Compose using Kotlinx.Serialization

Navigation Compose Typed Compile-time type-safe arguments for JetPack Navigation Compose library. Based on KotlinX.Serialization. Major features: Comp

Kiwi.com 32 Jan 4, 2023
KotlinX Serialization Standard Serializers (KS3)

KotlinX Serialization Standard Serializers (KS3) This project aims to provide a set of serializers for common types. โš ๏ธ Consider this project to be Al

Emil Kantis 3 Nov 5, 2022
A tiny Kotlin multiplatform library that assists in saving and restoring objects to and from disk using kotlinx.coroutines, kotlinx.serialisation and okio

Store A tiny Kotlin multiplatform library that assists in saving and restoring objects to and from disk using kotlinx.coroutines, kotlinx.serialisatio

Isuru Rajapakse 98 Jan 3, 2023
Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client

Practical Kotlin Multiplatform on the Web ๋ณธ ์ €์žฅ์†Œ๋Š” ์ฝ”ํ‹€๋ฆฐ ๋ฉ€ํ‹ฐํ”Œ๋žซํผ ๊ธฐ๋ฐ˜ ์›น ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์›Œํฌ์ˆ(๊ฐ•์ขŒ)์„ ์œ„ํ•ด ์ž‘์„ฑ๋œ ํ…œํ”Œ๋ฆฟ ํ”„๋กœ์ ํŠธ๊ฐ€ ์žˆ๋Š” ๊ณณ์ž…๋‹ˆ๋‹ค. ์›Œํฌ์ˆ ๊ณผ์ •์—์„œ ์ฝ”ํ‹€๋ฆฐ ๋ฉ€ํ‹ฐํ”Œ๋žซํผ์„ ๊ธฐ๋ฐ˜์œผ๋กœ ํ”„๋ก ํŠธ์—”๋“œ(front-end)๋Š” Ko

SpringRunner 14 Nov 5, 2022
Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client

Building a Full Stack Web App with Kotlin Multiplatform ๋ณธ ์ €์žฅ์†Œ๋Š” INFCON 2022์—์„œ ์ฝ”ํ‹€๋ฆฐ ๋ฉ€ํ‹ฐํ”Œ๋žซํผ ๊ธฐ๋ฐ˜ ์›น ํ”„๋กœ๊ทธ๋ž˜๋ฐ ํ•ธ์ฆˆ์˜จ๋žฉ์„ ์œ„ํ•ด ์ž‘์„ฑ๋œ ํ…œํ”Œ๋ฆฟ ํ”„๋กœ์ ํŠธ๊ฐ€ ์žˆ๋Š” ๊ณณ์ž…๋‹ˆ๋‹ค. ํ•ธ์ฆˆ์˜จ ๊ณผ์ •์—์„œ ์ฝ”ํ‹€๋ฆฐ ๋ฉ€ํ‹ฐํ”Œ๋žซํผ์„

Arawn Park 19 Sep 8, 2022
Automatic CoroutineDispatcher injection and extensions for kotlinx.coroutines

Dispatch Utilities for kotlinx.coroutines which make them type-safe, easier to test, and more expressive. Use the predefined types and factories or de

Rick Busarow 132 Dec 9, 2022
Small Kafka Playground to play around with Test Containers, and KotlinX Coroutines bindings while reading Kafka Definite Guide V2

KafkaPlayground Small playground where I'm playing around with Kafka in Kotlin and the Kafka SDK whilst reading the Kafka book Definite Guide from Con

Simon Vergauwen 34 Dec 30, 2022
An tool to help developer to use Retrofit elegantly while using kotlinx.coroutines.

one An tool to help developer to use Retrofit elegantly while using kotlinx.coroutines. Feature Transform different data structs to one. {errorCode, d

ChengTao 30 Dec 27, 2022
Kotlinx-murmurhash - Kotlin Multiplatform (KMP) library for hashing using MurmurHash

kotlinx-murmurhash Kotlin Multiplatform (KMP) library for MurmurHash, a non-cryp

Gonรงalo Silva 23 Dec 27, 2022
Cross-platform framework for building truly native mobile apps with Java or Kotlin. Write Once Run Anywhere support for iOS, Android, Desktop & Web.

Codename One - Cross Platform Native Apps with Java or Kotlin Codename One is a mobile first cross platform environment for Java and Kotlin developers

Codename One 1.4k Jan 9, 2023
A Kotlin work manager library for Android with progress notifications and Hilt support.

Boot Laces A kotlin work manager library for Android that includes notifications and Hilt support. User Instructions Add the JitPack repository to you

Chris Basinger 35 Oct 8, 2022
Template (pure) for KMM application with DI support

KMM di template Template (pure) for KMM application with DI support. Uses Multiplatform-DI for Dependency Injection Features Common architecture (VIP)

Anna Zharkova 8 Oct 18, 2022
Dependency Injection library for Kotlin Multiplatform, support iOS and Android

Multiplatform-DI library for Kotlin Multiplatform Lightweight dependency injection framework for Kotlin Multiplatform application Dependency injection

Anna Zharkova 32 Nov 10, 2022
Wrapper of FusedLocationProviderClient for Android to support modern usage like LiveData and Flow

FancyLocationProvider Wrapper of FusedLocationProviderClient for Android to support modern usage like LiveData or Flow. Install Add Jitpack repository

Jintin 66 Aug 15, 2022
Kotlin multiplatform decorators support

DEKORATOR [WIP] Decorator support for Kotlin! Built with โค , powered by Kotlin compiler plugin. Support The plugin only works on targets using new IR

Martynas Petuลกka 3 Mar 18, 2022
A simple, classic Kotlin MVI implementation based on coroutines with Android support, clean DSL and easy to understand logic

A simple, classic Kotlin MVI implementation based on coroutines with Android support, clean DSL and easy to understand logic

Nek.12 4 Oct 31, 2022