<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Guillermo Mazzola on Medium]]></title>
        <description><![CDATA[Stories by Guillermo Mazzola on Medium]]></description>
        <link>https://medium.com/@gmazzo65?source=rss-af4b902983e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gpZh4h6antPY_3sPGb1BmA.jpeg</url>
            <title>Stories by Guillermo Mazzola on Medium</title>
            <link>https://medium.com/@gmazzo65?source=rss-af4b902983e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 02:57:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gmazzo65/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Generating Android/JVM aggregated coverage reports]]></title>
            <link>https://medium.com/@gmazzo65/generating-android-jvm-aggregated-coverage-reports-53e912b2e63c?source=rss-af4b902983e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/53e912b2e63c</guid>
            <category><![CDATA[sonarqube]]></category>
            <category><![CDATA[coverage-report]]></category>
            <category><![CDATA[aggregator]]></category>
            <category><![CDATA[jacoco]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Guillermo Mazzola]]></dc:creator>
            <pubDate>Wed, 24 Aug 2022 14:55:18 GMT</pubDate>
            <atom:updated>2023-04-19T16:31:24.653Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>April/2023 update</em></strong><em><br>The content of this article is now available as two Gradle plguins:<br>- </em><a href="https://plugins.gradle.org/plugin/io.github.gmazzo.test.aggregation.coverage"><em>io.github.gmazzo.test.aggregation.coverage</em></a><em> for </em><a href="https://docs.gradle.org/current/userguide/jacoco_report_aggregation_plugin.html">jacoco-report-aggregation</a> <em>support<br>- </em><a href="https://plugins.gradle.org/plugin/io.github.gmazzo.test.aggregation.results"><em>io.github.gmazzo.test.aggregation.results</em></a><em> for </em><a href="https://docs.gradle.org/current/userguide/test_report_aggregation_plugin.html">test-report-aggregation</a> <em>support</em></blockquote><p>A modern tooling build script filling the gaps between Gradle and <a href="https://developer.android.com/studio/releases/gradle-plugin">Android Gradle Plugin (AGP)</a> to provide a unified coverage report.</p><p>The Gradle team recently introduced the <a href="https://docs.gradle.org/current/userguide/jacoco_report_aggregation_plugin.html">JaCoCo Report Aggregation Plugin</a>, which works upon the <a href="https://docs.gradle.org/current/userguide/jvm_test_suite_plugin.html#jvm_test_suite_plugin">JVM Test Suite Plugin</a> (default applied by the <a href="https://docs.gradle.org/current/userguide/java_plugin.html#java_plugin">Java Plugin</a>) to aggregate coverage data produced by a multi-module build into a single coverage report. It <strong>only support the JVM modules use case</strong>.</p><p>As usual, the AGP team is a bit behind on Gradle’s latest features. They recently introduced native <a href="https://developer.android.com/reference/tools/gradle-api/7.2/com/android/build/api/dsl/BuildType#enableUnitTestCoverage()">support for code coverage reports</a> adding a create<strong><em>Variant</em></strong>UnitTestCoverageReport task per buildType having enableUnitTestCoverage = true .</p><p>Even AGP now has the capability of producing coverage reports natively, they are not (yet?) integrating with Gradle’s official aggregation mechanism for this (which is producing <a href="https://docs.gradle.org/current/userguide/test_report_aggregation_plugin.html#sec:test_report_aggregation_tasks">outgoing variants</a>, we’ll cover it later).</p><p>Before going into technical details, let’s go straight to the solution to our problem.</p><h3>Adopting the Coverage plugin</h3><p>On my <a href="https://github.com/gmazzo/android-jacoco-aggregated-demo">demo repo</a>, you can find a copy of <a href="https://github.com/gmazzo/android-jacoco-aggregated-demo/blob/main/coverage-plugin/src/main/kotlin/coverage.gradle.kts">coverage.gradle.kts</a> buildSrc ad-hoc plugin, that you can easily adopt on your projects to support a hybrid Android/JVM modules aggregated report.</p><p>Just copy <a href="https://github.com/gmazzo/android-jacoco-aggregated-demo/blob/main/coverage-plugin/src/main/kotlin/coverage.gradle.kts">coverage.gradle.kts</a> (and its companion DSL <a href="https://github.com/gmazzo/android-jacoco-aggregated-demo/blob/main/coverage-plugin/src/main/kotlin/org/gradle/kotlin/dsl/CoveragePluginDSL.kt">CoveragePluginDSL.kt</a>) into your buildSrc/src/main/kotlin (make sure to apply kotlin-dsl plugin) and then apply the id(&#39;coverage&#39;) plugin at your <a href="https://github.com/gmazzo/android-jacoco-aggregated-demo/blob/main/build.gradle.kts">root’s </a><a href="https://github.com/gmazzo/android-jacoco-aggregated-demo/blob/main/build.gradle.kts">build.gradle</a></p><p>A root :jacocoTestReport task will be registered, aggregating by default the test coverage of all Android modules and all JVM modules (that applies jacoco plugin)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HUdFeYhs6k5ZThPG.png" /></figure><p>A quick cheatsheet for adopting the plugin:</p><ol><li>Apply the coverage plugin at the root project</li><li>Every Android module debug variant will be automatically aggregated (while testCodeCoverageReport is kept to its default true )</li><li>Every JVM module that also applies the jacoco plugin will be automatically aggregated</li></ol><p>For a complete working example, check out the demo project here:<br><a href="https://github.com/gmazzo/android-jacoco-aggregated-demo">https://github.com/gmazzo/android-jacoco-aggregated-demo</a></p><h3>What does this plugin do?</h3><p>Basically, it <strong>fills the gaps</strong> between <a href="https://docs.gradle.org/current/userguide/jacoco_report_aggregation_plugin.html">JaCoCo Report Aggregation Plugin</a> and <a href="https://developer.android.com/studio/releases/gradle-plugin">AGP</a>, by providing the missing <a href="https://docs.gradle.org/current/userguide/test_report_aggregation_plugin.html#sec:test_report_aggregation_tasks">outgoing variants</a> for any variant that has native coverage reports enabled.</p><p>To understand better what this plugin does, let’s first focus on how <a href="https://docs.gradle.org/current/userguide/jacoco_report_aggregation_plugin.html">JaCoCo Report Aggregation Plugin</a> on JVM modules:</p><p>When jacoco-report-aggregation is applied, a jacocoAggregation configuration is created. If this is done in a root project (that does not apply a java plugin), you need to <a href="https://docs.gradle.org/current/userguide/jacoco_report_aggregation_plugin.html#manual_report_creation">manually configure the target aggregated report</a> to generate and from which modules will it feed.</p><p>For instance, by adding dependencies { jacocoAggregation(project(“:child”)) } you’ll tell the plugin to include the project child when generating the aggregated report. You can do this for every project (potentially all of them) in the build.</p><p>Later, the task associated with the report (matching the report name, testCodeCoverageReport if you following <a href="https://docs.gradle.org/current/userguide/jacoco_report_aggregation_plugin.html#manual_report_creation">Gradle’s official example</a>) will resolve jacocoAggregation fetching a special <a href="https://docs.gradle.org/current/userguide/test_report_aggregation_plugin.html#sec:test_report_aggregation_tasks">outgoing variant</a> for each of its dependencies, that matches <a href="https://docs.gradle.org/current/userguide/jacoco_report_aggregation_plugin.html#sec:jacoco_report_aggregation_tasks">the coverage report attributes</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xxiB2sTS8V8mQhHSzGyCKw.png" /></figure><blockquote>You an inspect a module’s outgoing variant by running the task ./gradlew mymodule:outgoingVariants</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jf9h_WR8XD-qCkb68AgymA.png" /></figure><h4>What about Android modules?</h4><p>By default on AGP logic, turning enableUnitTestCoverage on will create the required Gradle tasks to generate a coverage report. But not the required outgoing variants.</p><p>Even if you add your Android module as a dependency of jacocoAggregation, the <a href="https://docs.gradle.org/current/userguide/jacoco_report_aggregation_plugin.html">JaCoCo Report Aggregation Plugin</a> won’t be able to resolve it to fetch the JaCoCo execution data file (the build/jacoco/test.execartifact of the coverageDataElementsForTest outgoing variant for JVM; on Android it actually will be build/jacoco/test<strong><em>Variant</em></strong>UnitTest.exec if enableUnitTestCoverage is enabled)</p><p>That’s what the main gap this plugin is meant to fill: to provide the required outgoing variants for each Android module, allowing them to get discovered by the <a href="https://docs.gradle.org/current/userguide/jacoco_report_aggregation_plugin.html">JaCoCo Report Aggregation Plugin</a>.</p><p>In concrete, the plugin is adding 3 outgoing variants on each Android module:</p><p>codeCoverageExecutionData is the main entry point and basically, it tells where to find the JaCoCo execution data file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vK36TrMhaPWEeiv1HBHM-g.png" /></figure><p>JaCoCo also requires two additional inputs to compute a module: <strong>sources</strong> and <strong>classes</strong>. The plugin also provides the codeCoverageSources and codeCoverageElements variants to supply them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oII4lijZ-VQlhbGD2VGwsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TvVf48uGW4vDZDdFfYi1A.png" /></figure><h4>The Android’s multi-artifact problem</h4><p>One thing that is not trivial in comparing regular JVM modules vs Android ones, is the concept of <strong><em>variants</em></strong>.</p><p>JVM modules are easy, they just produce a single JAR. Android, on the other hand, the bare minimum will produce two main artifacts: debug and release.</p><p><a href="https://github.com/jacoco/jacoco">JaCoCo</a> is the default tool used by Gradle and Android to produce coverage reports. One of the limitations this tool has when creating reports is that it will fail if two classes with the same canonical name are found on different .exec files:<br>java.lang.IllegalStateException: Can&#39;t add different class with same name: org/hamcrest/BaseDescription</p><p>How this is a problem for Android? well any class under src/main will be present on both debug and release artifacts (assuming both have enableUnitTestCoverage enabled). The problem goes deeper if you have two different versions of the same class under src/debug and src/release respectively.</p><p>The is no correct workaround for this but just keep 1 copy of the divergent classes for the final aggregated report. The aggregated report won’t be fully accurate, but still, it will be a good approximation.</p><p>The plugin overcomes this by introducing an allVariantsClassesForCoverageReport intermediate Copy task, feeding from all aggregating variants having coverage reports enabled. This task has duplicatesStrategy = DuplicatesStrategy.WARN to let the consumer know about this potential inaccuracy, but still allowing the report to succeed.</p><blockquote>By default, the plugin will only enableUnitTestCoverage on debug. Keep in mind that enabling it for more than one variant will make all tests under src/main to run more than once (once per variant’s Test task)</blockquote><h4>Flavors makes the configuration more complex</h4><p>As you know, variants are the cartesian product of buildTypes and productFlavors.</p><p>enableUnitTestCoverage is a buildType setting, meaning all variants of it will produce a build/jacoco/test<strong><em>Variant</em></strong>UnitTest.exec file.</p><p>Even the plugin will support aggregating any number of variants in the root report, I <strong>strongly recommend only choosing one of them</strong>, to produce consistent reports.<br>You can use the dedicated aggregateTestCoverage DSL (available on buildTypes and productFlavors) to make that choice.</p><p>Look at the <a href="https://github.com/gmazzo/android-jacoco-aggregated-demo#the-aggregatetestcoverage-dsl-extension">documentation</a> for further reference on how to use it.</p><h4>Are you a SonarQube user?</h4><p>Thanks that now you have a root :jacocoTestReport that considers alls modules, you can easily report to it by adding the following build logic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*joJiPIFk13ufrjTfQC0--w.png" /></figure><h4>Why it’s not released at <a href="https://plugins.gradle.org/">Gradle Plugins Portal</a>?</h4><p>Well, because I saw in the last year AGP team catching up, like introducing native coverage reports or even test fixtures. I think it’s a matter of time for them to include this missing piece as part of AGP logic, making a possible plugin obsolete.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53e912b2e63c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Publishing a variant-aware Android library with its sources]]></title>
            <link>https://medium.com/glovo-engineering/publishing-a-variant-aware-android-library-with-its-sources-c61387323963?source=rss-af4b902983e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c61387323963</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[gradle-plugin]]></category>
            <category><![CDATA[android-libraries]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[gradle-metadata]]></category>
            <dc:creator><![CDATA[Guillermo Mazzola]]></dc:creator>
            <pubDate>Tue, 07 Sep 2021 15:13:07 GMT</pubDate>
            <atom:updated>2021-09-22T11:39:06.665Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to publish variant-aware Android libraries with their sources</h4><p>As you probably know already, a com.android.library module by default has two default buildTypes: debug and release. If you don’t declare any productFlavor those are mapped directly as your libraryVariants.</p><p>If your android library module is consumed in the same build, then you are all set up with <a href="https://docs.gradle.org/current/userguide/variant_model.html">Gradle’s variant selection feature</a>, which Android Gradle Plugin (a.k.a. AGP) uses. <br>You only need to make your app module depend on your lib module, and that’s all. The correct debug variant from lib will be picked up when the app is building in debug mode. The same applies for release and any further configuration you may have.<br>Variants itself is not the topic of this article. Check <a href="https://developer.android.com/studio/build/build-variants">Configure Build variants</a> for extra details on this matter.</p><h3>How to publish a variant-aware library</h3><p>At Glovo, we have many internal Android libraries that our main apps consume, and sometimes, we do want to have a different behavior if we are targeting a debug or a release build.<br>The best example is our logger library (a wrapper interface with very basic log methods) that will print to the logcat debug and use Firebase for release</p><p>AGP 7.0 was a big milestone for us, because it introduced the new Gradle component all , which exposes all Android variants as Gradle variants, allowing <strong>a library to be consumed in the same way than a local module</strong>.<br>The right debug, release (or whatever) variant will be picked up based on the matching attribute’s metadata.</p><p>It can easily be set up like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef74e44bc15e522a50dfaa551dfd00cf/href">https://medium.com/media/ef74e44bc15e522a50dfaa551dfd00cf/href</a></iframe><p>And will generate the following artifacts in your Maven repository:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*hpugLlqaxvpjGdaDucge8g.png" /></figure><p>Basically, instead of having one default AAR artifact, each variant will be published as a classifier.</p><p>The problem arises as soon you consume the library because they lack of asources.jar artifact.</p><h3>Attaching a source per classifier</h3><p>Publishing a source artifact per each classifier is not a big issue, we actually have logic for it assuming a ${variant.name}-sources pattern:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c12b4f0312addce8ca6e9edf0829705/href">https://medium.com/media/1c12b4f0312addce8ca6e9edf0829705/href</a></iframe><p>And will generate the following artifacts in your Maven repository:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*EX5nxK4O4GHtAuuqc_uTzg.png" /></figure><p>This is the relevant content of logger-0.1.0.module (Gradle’s metadata):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4j2DGNYjyzuZ-sO04EiOxg.png" /></figure><h3>The problem: sources artifact resolution</h3><p>For historical reasons, there is a wide convention that Maven artifacts will publish its sources in a sources classifier, with type jar (the same applies for javadocs but it’s not our topic).</p><p>For instance, in our example, our Maven coordinates are com.glovoapp.android:logger:0.1.0, the sources should be attached to com.glovoapp.android:logger:0.1.0:sources.</p><p>With the introduction of “variant-aware” dependencies by Gradle, this convention is no longer enough because you can have different variants, produced by different source code, so a unique sources artifact is not accurate. Variants are basically two different artifacts and it can be potentially two different libraries at all.</p><p>In addition to this conceptual limitation, there is a technical one:<br>AGP defines that each variant will be a classifier and for some reason, Gradle/IntelliJ are unable to resolve the sources of a dependency, when that dependency is already a classifier.</p><p>For instance, having this set of artifacts (even with the right metadata) just does not work either:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*B1oFJLintV6Fsk2S6ubpNA.png" /></figure><p>If you try to use the “Download Sources” feature from IntelliJ, you will also note their script builds an invalid dependency notation com.glovoapp.android:logger:0.1.0:debug@aar:sources, revealing the lack of support (for now) to this use case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DL4gicpr_o8mc9Ujz14o_w.png" /></figure><pre>FAILURE: Build failed with an exception.</pre><pre>* Where:<br>Initialization script &#39;/private/var/folders/v8/0x2cv3xs1895qcky7hpxhfch0000gn/T/ijmiscinit3.gradle&#39; line: 14</pre><pre>* What went wrong:<br>Execution failed for task &#39;:app:DownloadSources&#39;.<br>&gt; Supplied String module notation &#39;com.glovoapp.android:logger:0.1.0:debug@aar:sources&#39; is invalid. Example notations: &#39;org.gradle:gradle-core:2.2&#39;, &#39;org.mockito:mockito-core:1.9.5:javadoc&#39;.</pre><p>I actually had the chance to chat with a couple of Gradle engineers regarding this. They acknowledged the problem, but yet it is not clear what would be the path to fully support this use case in the future.</p><h3>The solution: Divide and Conquer</h3><p>So, let’s recap our constraints:</p><ol><li>Having the ability to dynamically choose which Android variant will be used based on who is consuming it, is a MUST ⇒ Variant aware Gradle publications</li><li>Allow our developers to see the fully documented source code of our libraries is also a MUST ⇒ Source code needs to be published</li><li>Gradle/IntelliJ seems to ignore Gradle’s metadata when resolving sources (at least for now) and only honors Maven’s sources classifier convention</li><li>Source code of the chosen variant will be automatically attached when the Gradle project when sync in IntelliJ is a NICE TO HAVE</li></ol><p>How to fulfill all constraints? well, basically by migrating from AGP’s default publication:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*b1mMR2O8RYx4nM6Vdv_y0Q.png" /><figcaption>AGP’s default publication: components[“all”]</figcaption></figure><p>Into an <strong>artifact per variant publication, plus a default variant-aware POM</strong> in the original coordinates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*xJT2Jzk5e7orBd3oEYaSzg.png" /><figcaption>Multi-artifact variant-aware library publication</figcaption></figure><p>This is how the Maven repository will look like for our logger library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*eS1eHsnuo5Za7zURxnKuSw.png" /></figure><p>In case you are looking to implement this solution, you can download our android-publish.gradle.kts script in put it directly in your buildSrc project (under src/main/kotlin)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47f13a8be457d1025dcfb1ba5a6edf96/href">https://medium.com/media/47f13a8be457d1025dcfb1ba5a6edf96/href</a></iframe><p>Make sure to apply kotlin-dsl plugin in your buildSrc module, and then you can apply the plugin at any Android module by adding:</p><pre>plugins {<br>    `android-publish`<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c61387323963" width="1" height="1" alt=""><hr><p><a href="https://medium.com/glovo-engineering/publishing-a-variant-aware-android-library-with-its-sources-c61387323963">Publishing a variant-aware Android library with its sources</a> was originally published in <a href="https://medium.com/glovo-engineering">The Glovo Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Publishing native artifacts from a Kotlin Multiplatform project]]></title>
            <link>https://medium.com/glovo-engineering/publishing-native-artifacts-from-a-kotlin-multiplatform-project-24f0abe00209?source=rss-af4b902983e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/24f0abe00209</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[gradle-plugin]]></category>
            <category><![CDATA[cocoapods]]></category>
            <dc:creator><![CDATA[Guillermo Mazzola]]></dc:creator>
            <pubDate>Mon, 19 Jul 2021 17:24:58 GMT</pubDate>
            <atom:updated>2021-08-09T07:15:33.419Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Kotlin Multiplatform technology to produce native CocoaPods and NPM packages</h4><p>In my previous post, <a href="https://medium.com/glovo-engineering/kotlin-multiplatform-at-glovo-e54173cb9f5c">Kotlin Multiplatform at Glovo</a>, I told the story of how we introduced the Kotlin Multiplatform (from now KMP) technology to solve our Tracking Events business use case.</p><p>Here, I’ll dig into our solution&#39;s technical details, the challenges we faced (and how we solved them), and the tooling we built to support it.</p><p>I encourage you to first gather a basic understanding of the fundamentals of <a href="https://kotlinlang.org/docs/multiplatform.html">Kotlin Multiplatform</a>, targeting JVM, JS, and Native/iOS. We’ll explore a different use case not yet explored by the community (at least that I am aware of), hoping it will be very interesting and enriching reading to you.</p><p>It’s a bit extensive, but I believe the topic is worth it.</p><h3>The scale restriction</h3><p>Assuming you have a bit of experience already with Kotlin Multiplatform, you may note (or may not) that it has to be “the core” of your project. And by “core” I mean the glue required to bind everything together.</p><p>Take a look at <a href="https://github.com/Kotlin/kmm-sample">Kotlin’s official KMP example repo</a> for instance. This project is a basic setup for a mobile app, and in there you can find the module for KMP, plus one per each technology: android and iOS.</p><p>I’m not going to dig deeper on Android’s setup because it’s pretty straightforward. On the other hand, if you look at the iOS’s wiring setup, you’ll notice that it’s done basically with an XCode’s build script running a Gradle task to build the project into a framework.</p><p>The same will apply if you eventually want to add a JavaScript target for a web version. The wiring will be a bit different but you basically need to have a dedicated module for your webapp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*LUpQf6U2kvPiizCMGYdF2g.png" /><figcaption>A common structure of a KMP project</figcaption></figure><p>Any mature frontend probably has a big and complex codebase, CI/CD setups, and any kind of process around them. Probably, each one has its own repository as well.<br>Because of this reason, KMP may not be a good fit for organizations to adopt.</p><p>Forcing all your platform to join on a single repo (as shown in the previous screen), and changing the build-chain to integrate with Kotlin is probably the biggest barrier you will find if you try it.</p><p>That was our case at Glovo, but we managed to provide an alternative.</p><h3>The native artifacts approach</h3><p>What about if we manage to publish a CocoaPod and an NPM package? That was my thought when I faced the problem.</p><p>In theory, everything is there already. The KMP Plugin’s output provides a Framework for iOS and a JavaScript file for web. We just needed to build all the tooling to publish the packages in their native formats.</p><p>So we took the challenge and decided to do it in a “Gradle-friendly” approach by extending Gradle’s publishing plugin and Kotlin’s KMP one like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cd8PQb26T_SJcG3dGkg-xw.png" /><figcaption>High-level of the tooling we have built</figcaption></figure><h4>Gradle’s Publishing Plugin extensions</h4><p>First, we’ve extended Gradle’s Publishing DSL with the new:</p><ul><li>CocoaPodsRepository and NPMRepository repository types (analogs to MavenArtifactRepository)</li><li>PodPublication and PackagePublication publication types (analogs to MavenPublication)</li><li>Podspec and PackageJson artifact descriptor types (analogs to MavenPom)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bcd7a745536bb34ae47ad9e35c13989/href">https://medium.com/media/1bcd7a745536bb34ae47ad9e35c13989/href</a></iframe><p>This is our DSL for CocoaPods and NPM publication in Gradle:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3234d031012f7248e11ebefb7fc0e89f/href">https://medium.com/media/3234d031012f7248e11ebefb7fc0e89f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4a34f8359fb00d757f4d86ce7b5f241/href">https://medium.com/media/f4a34f8359fb00d757f4d86ce7b5f241/href</a></iframe><p>The plugins will add the necessary tasks to support publishing each repository in an isolated way. You don’t need to do anything outside Gradle’s build.</p><p>For instance, registering a new cocoaPods repository will create a SetupCocoaPodsRepositoryTask, which then sets up an isolated local tmp gems installation and executes pod repo add command on it.</p><p>Be aware this is <strong>highly coupled with Gradle’s internal API</strong>, and is likely to break across version changes.</p><h3>Glovo’s KMP Native Library Plugin</h3><p>Once we have set up Gradle to be able to handle CocoaPods and NPM artifact’s publishing it was time to start wiring everything together with JetBrains’s KMP plugin.</p><h4>The NPM target</h4><p>Well, not really a KMP new target, but an extension of KotlinJsTarget that also registers and links a PackagePublication. Applying this target ensures the project will produce an NPM library as part of its build process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/995c5431c63265c82733dc5d763a211a/href">https://medium.com/media/995c5431c63265c82733dc5d763a211a/href</a></iframe><h4>The Pod target</h4><p>Following the same approach, we also created a new pod target but in this case, it will rely on one or more iOS’s KotlinNativeTargets.</p><p>By default, this “virtual target” will create iosArm64 (for most modern iOS devices) and iosX64 (for iOS emulators), and you can optionally also include support for iosArm32 (older iOS devices).</p><p>The target will also register a PodPublication, so will be able to define and manipulate the artifact’s Podspec file. It will also register a FatFrameworkTask (provided by KMP’s plugin) whose output will be the main artifact of the publication and will merge all intermediate frameworks produced by each KotlinNativeTargets link task.</p><p>So the output of this target will be a fully functional multi-architectural XCode Framework, published as a CocoaPod.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a95d79ca22467a26b4f3db6ad49b62da/href">https://medium.com/media/a95d79ca22467a26b4f3db6ad49b62da/href</a></iframe><h4>The Standard Layout concept</h4><p>And finally, built upon all this tooling, the concept of a “standard layout” of a native library arises. It basically means that each KMP Gradle module may apply for android, ios, mobile (android+ios), web, or backend; following this sourceSet’s structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oHXBWnqPDt9-MR9k" /><figcaption>Hierarchy of `main` sourceSets, in our standard library layout convention</figcaption></figure><p>With its test counterparts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XEojo4Sw-23-w6_q" /><figcaption>Hierarchy of `test` sourceSets, in our standard library layout convention</figcaption></figure><p>And of course, our plugin adds a dedicated DSL for your Gradle build scripts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a688b7b563569c455e24893dbcd7a8a/href">https://medium.com/media/2a688b7b563569c455e24893dbcd7a8a/href</a></iframe><h3>Designing to be as frictionless as possible</h3><p>Given the reality of Glovo as a company with many cross-dependencies between teams, having as little impact as possible in consumer repos was crucial to the success and adoption of our library.</p><p>For that reason, we decided to keep the scope at the minimum possible to achieve our main goal: the library will just be responsible for mapping logical events (represented as classes) into raw JSON data (a merge from the event itself, the device and the user session). We won’t go into any complex implementation like persistence, http requests, etc.</p><p>This is how our main entry point looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a11fbfa10cc64e294f6d2fb6053b92b/href">https://medium.com/media/3a11fbfa10cc64e294f6d2fb6053b92b/href</a></iframe><p>Basically, each consumer app has to provide an instance conforming to the AnalyticsDelegate interface. Every time an event is sent through the track method, it’s going to be serialized as raw data and then a callback function from the delegate will be invoked with it. Then, the app sends this raw data to our tracking endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/048bd232dff8dbdf6d41da9c222c8073/href">https://medium.com/media/048bd232dff8dbdf6d41da9c222c8073/href</a></iframe><p>If you have a trained eye, the previous screenshots revealed the first two frictions we had with the web and iOS team:</p><h4>JS function mangling</h4><p>Unless you give an explicit name with @JsName, functions with parameters will be mangled (adding a suffix) when compiled to JS. That’s because JS is not a typed language. So any parameterized function is a potential clash when overloaded (now or in future compilations of your code). I remember seeing some issues reported around this and proposing alternative approaches. I personally think this is fine, and it’s one of the tradeoffs you need to accept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*b5ldGwFdE6eV5xVV_xoVuQ.png" /><figcaption>Example of Kotlin stdlib’s `mapOf` function mangling once compiled into JS</figcaption></figure><h4>Lack of Thread Safe Mutable Collections in Native targets</h4><p>The second is the threadSafeMutableMap(), which is actually an expect/actual function. For JVM targets, it will just use a ConcurrentHashMap. For web targets (remember it’s single-threaded) just a regular HashMap will do.</p><p>The problem was iOS, Kotlin Native to be precise, and its concurrency memory model that enforces immutability to achieve thread-safety. We didn’t want to add extra complexity to the project, by introducing coroutines (not a stable technology at that moment) for instance.</p><p>My first attempt to overcome this was to use <a href="https://github.com/touchlab/Stately">Stately, from Touchlab</a> (we actually had <a href="https://www.linkedin.com/posts/glovo-app_kotlin-multiplatform-kmp-for-analytics-activity-6771041310766895105-leeU">a podcast</a> with them about our project, with my colleague <a href="https://www.linkedin.com/in/zeyad-gasser/">Zeyad</a>).</p><p>But at that time, they were not targeting JS (now they do).<br>So, at the end, we decided to have our own class implementing the interface, the actual value to be held by kotlin.native.concurrent.AtomicReference, and each mutable operation will try compareAndSet until it succeeds. Not perfect, but it works.</p><h4>The Kotlin Native Memory model</h4><p>At some point when you design a KMP solution, you will face this challenge.</p><p>Basically, the shared XOR mutable memory model in Kotlin Native enforces any mutable object to be accessed from the thread that has instantiated it. An exception will be thrown if this rule is violated.</p><p>To relax this limitation, you need to “freeze” the object. This means the object itself and all its references have to be “frozen” or immutable.</p><p>We wanted our KMP solution to be as simple as possible, so introducing coroutines or any complex solution was not an option. As mentioned in the previous topic, we decided to use our own mutable thread-safe collections. This decision has a price to pay in our commonMain logic.</p><p>There are a few ways to make an object “frozen” in the Kotlin Native framework. We decided to use the stdlib function kotlin.native.concurrent.freeze. The problem is that the function is only available in Native targets, and we were constructing objects in our common sourceSet.</p><p>To overcome this, we had to introduce an expect val &lt;T&gt; T.frozen: T function (other targets will just return this) and make our common code aware of this as you can see here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*5AgxOFqPcy865tLF-nkqpg.png" /><figcaption>Kotlin Native’s `frozen` aware code in `commonMain` sourceSet</figcaption></figure><h3>KMP was not designed for this</h3><p>The more I dig deeper into the framework, face and solve issues, the more I realize this was never considered as a possible use case of the KMP technology.</p><p>One of the biggest challenges we faced was around transitive dependencies, most precisely depending on other MPP modules.</p><p>Each target has its own problems with it which I’ll try to summarize here.</p><p>Our analytics solution has a base module with all the shared code, and then we have dedicated modules with specific events targeting different domains of our company. For instance, customer and courier modules define their own independent events, but they share the foundation logic depending on the base module.</p><p>For JVM build, everything works just fine through Maven support. But on iOS and web it’s another story.</p><h4>iOS transitive module dependencies issues</h4><p>iOS (native) builds don’t manage the concept of dependencies, they just create a binary bundle instead (a framework) and expose some symbols through Objective-C Header files.</p><p>Luckily there is a <a href="https://kotlinlang.org/docs/mpp-build-native-binaries.html#export-dependencies-to-binaries">little known API</a> to include any dependency into that Header file.</p><p>So we took the opinionated decision of exporting the whole apiConfiguration of the modules and that was it, all base module classes were now visible on XCode.</p><h4>JavaScript transitive module dependencies issues</h4><p>Similarly, in the JS approach, each KMP module gets compiled and translated to the project’s root as a local node module; which will later be run as a standalone app. So you will have a dedicated .js file per module and dependency resolution will be done through require or import.</p><p>One problem we observed when we published our first alpha NPM package was that the default .js contained only the classes defined in the module itself, but those from the base one were missing. Actually, we hit a runtime error trying to resolve an unknown base module (through the require) function.</p><p>To overcome this (again, an opinionated decision), we used a (not well known) feature of Node, where you can have a node_modules folder inside your NPM package. We just converted our regular NPM package into a bundled one. It required a bit of effort, but it works transparently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*tpcnYXLDSlUiMzoo8wj36g.png" /><figcaption>Content of the `npm` package built by our tooling</figcaption></figure><p>The .bundle.js file is actually the package’s main entry point, which resolves and merges the exports of all the other packages.</p><p>I’m pretty sure this was changed in Kotlin 1.5 with the new IR compiler and now it’s producing a single .js bundle. I still haven’t had time to fully check it as we have other blocking issues preventing the migration (addressed at the end of this document in the “final thoughts” section).</p><h3>Lessons learned</h3><ul><li>Kotlin Native’s shared XOR immutable memory model makes multiplatform development much more complex and introduces an extra barrier to the adoption of the technology into the iOS world. I kind of remember seeing KEEP for relaxing this limitation (maybe with an opt-in feature) and just to provide a normal (or if you like it, “legacy”) approach to concurrency and threading.<br>It seems this is going to be addressed soon:<br><a href="https://blog.jetbrains.com/kotlin/2021/05/kotlin-native-memory-management-update/">https://blog.jetbrains.com/kotlin/2021/05/kotlin-native-memory-management-update/</a></li><li>Kotlin 1.5 has introduced some breaking changes on its JS/IR compiler, preventing interfaces and enums from being exported.</li><li>KMP still has much room for improvements regarding interpolarity with other platforms than Java.</li></ul><h3>Conclusions</h3><p>As I mentioned from the very beginning, this was for me just a research and exploration experimental project (I would use more “non-ready for production” words in here) that suddenly faced the opportunity to have a real use case to test.</p><p>I think we can consider it stable enough now, but very difficult to maintain. From a professional perspective, I’ve decided to stop scaling the technology and not introduce any new multiplatform libraries.</p><p>I’d love to see other companies continuing this research further and who knows, maybe even get official support from JetBrains and Gradle for it.</p><p>Having this as an out-of-the-box feature will definitely contribute to adopting the technology incrementally for brownfield native projects, as was our use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24f0abe00209" width="1" height="1" alt=""><hr><p><a href="https://medium.com/glovo-engineering/publishing-native-artifacts-from-a-kotlin-multiplatform-project-24f0abe00209">Publishing native artifacts from a Kotlin Multiplatform project</a> was originally published in <a href="https://medium.com/glovo-engineering">The Glovo Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Multiplatform at Glovo]]></title>
            <link>https://medium.com/glovo-engineering/kotlin-multiplatform-at-glovo-e54173cb9f5c?source=rss-af4b902983e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e54173cb9f5c</guid>
            <category><![CDATA[multiplatform]]></category>
            <category><![CDATA[gradle-plugin]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[cocoapods]]></category>
            <dc:creator><![CDATA[Guillermo Mazzola]]></dc:creator>
            <pubDate>Mon, 19 Jul 2021 16:51:31 GMT</pubDate>
            <atom:updated>2021-07-30T12:49:47.127Z</atom:updated>
            <content:encoded><![CDATA[<h4>A story from my personal experience of working for more than a year with Kotlin Multiplatform at Glovo.</h4><h3>First, a bit of Kotlin history at Glovo</h3><p>I joined Glovo around 2 and half years ago, and at that moment (as you may imagine) only Androiders were the ones using the language in production.</p><p>I remember my web colleague <a href="https://www.linkedin.com/in/hdrdavies/">Huw</a> (nice person by the way) starting the #kotlinize-glovo Slack channel to raise awareness internally about its features. Java Backend had a mixture of Play Framework, Lombok and Spring to add something else into that combo.</p><p>Our first Kotlin contribution in the backend was a buildSrc plugin logic that I borrowed from our Android project.</p><p>At that moment, it was just a matter of time to let the industry catch up and we weren’t the exception. I’m proud to say that Glovo launched its first pure Kotlin microservice a few months ago, boosted by some talented new joiners who had experience working with Kotlin. And with that milestone, we archived our #kotlinize-glovo channel. Hurray!</p><h3>The “Back To School Friday” factor</h3><p>At Glovo we have Friday afternoon allocated for ourselves, so we can focus on those tiny (or not so tiny) projects that we’d like to try but never have time to.</p><p>We can use our Fridays to learn. It doesn’t matter exactly how: by reading, taking an online course, etc.</p><p>In my case, I’m one of those people who learn by experimentation. So I dedicated several Fridays to this project, which I can say now, almost 1 year and a half later, was a success but still has some caveats. I’ll dive deeper later, don’t worry.</p><h3>Our Use Case: Standardize Tracking Events</h3><p>Glovo is proud of being a Data-Driven company, which means that we make our business decisions based on hard evidence provided by the data we collect.</p><p>We have two main apps, Customer and Courier, and each of them has different platform versions: Android, iOS, and Web.</p><p>As you may think, each developer had to implement the tracking logic on its own which eventually produced discrepancies between the apps and the platforms.<br>As an example, we had events coming from Android with cityName and from iOS with city_name</p><p>The business goal for this project was to standardize the events definitions and their generation (on the apps) to assure the data we collect is trustable, reliable, and mostly the same between the platforms.</p><p>Given those requirements, I proposed KMP as the underlying technology because it would allow us to:</p><ul><li>Have a unified source of trust for our events</li><li>Share business logic across all apps</li><li>Ensure events’ raw serialized data is the same across all apps</li></ul><p>The only problem is that you can’t adopt KMP on projects already established (for iOS and web). <a href="https://medium.com/@gmazzo65/publishing-native-artifacts-from-a-kotlin-multiplatform-project-24f0abe00209">In my other post</a>, I address the reasons why in the “The scale restriction” section.</p><p>So, for this to work, we’ll have to produce some native artifacts for each platform: a CocoaPod for iOS and an NPM package for web</p><blockquote>I’d like to give a special mention to <a href="https://www.linkedin.com/in/alenadelacruz/">Alena</a>, a brilliant Product Manager we had, thanks to whom, before I even realized, my initial PoC of a Multiplatform library had become the seed of our fresh new cross-platform Tracking Events library</blockquote><h3>Drafting the concept of a Multiplatform Native library</h3><p>The idea was simple, but a big challenge. If we can manage to produce native artifacts for each platform, then we can just consume them like any regular iOS’s CocoaPod or NPM package but with KMP code inside it.</p><p>So I undusted my old Ruby/JavaScript skills, read a lot of <a href="https://guides.cocoapods.org/syntax/podfile.html">CocoaPods</a> and <a href="https://docs.npmjs.com/cli/v7/configuring-npm/package-json">NPM</a> technical specs, and started to write a viable process to produce them.</p><p>The solution consisted of a core library containing the base KMP code and using YAML to define our Tracking Events. The build process validates them and then generates Kotlin classes that represent the events we wanted to track. <br>The whole project is packaged and distributed as native libraries for each platform. We added observability around the events to keep track of the deployment status on the frontends, and a Confluence page to have them documented for everyone in the organization who queries for them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XDexFEfnc5syHFfz" /><figcaption>Build process of our KMP Tracking Analytics library</figcaption></figure><p>Backend was left out to reduce the scope, but as with any JVM-based project, integrating it won’t represent a big challenge. Actually, we’ll likely take it up again shortly</p><p>This was pretty much the idea that we had in mind on how the library is supposed to be consumed by the frontends:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vj6rR6jt9CvLZDKd" /><figcaption>Example of a YAML tracking event definition and its usage on Android and iOS platforms</figcaption></figure><p>The project was ambitious, but we had a dedicated team to work over a whole quarter and we delivered it.</p><h3>Lessons learned</h3><ul><li>KMP is great for greenfield projects, but adopting it on established traditional projects can have a big impact. Not just in code, but in the skills your team is going to need to work and perform with this new technology. This is probably the biggest barrier to overcome.</li><li>The “Multiplatform Native library” concept is something not yet explored (at least that I’m aware of). Yet, it allowed us to overcome the barrier I’ve just mentioned in the previous point.<br>Anyway, scaling this approach to other libraries without any official support for it is a risk. That’s why we are not spreading this approach to new code (at least for now).</li></ul><h3>Conclusions</h3><p>I’m proud to say that one year and a half later, this “experimental” project is considered a success and innovates on what could be the next generation of non-intrusive cross-platform coding standards.</p><p>It has been a long journey filled with challenges, searches, and learnings that I’ll cover in my next article <a href="https://medium.com/glovo-engineering/publishing-native-artifacts-from-a-kotlin-multiplatform-project-24f0abe00209">Publishing native artifacts from a Kotlin Multiplatform project</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e54173cb9f5c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/glovo-engineering/kotlin-multiplatform-at-glovo-e54173cb9f5c">Kotlin Multiplatform at Glovo</a> was originally published in <a href="https://medium.com/glovo-engineering">The Glovo Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>