<?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 Geor Kasapidi on Medium]]></title>
        <description><![CDATA[Stories by Geor Kasapidi on Medium]]></description>
        <link>https://medium.com/@geor.kasapidi?source=rss-5488c0669d72------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1SYY1Lup8fB769TKDgpdGA.jpeg</url>
            <title>Stories by Geor Kasapidi on Medium</title>
            <link>https://medium.com/@geor.kasapidi?source=rss-5488c0669d72------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 21:59:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@geor.kasapidi/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[Mastering Thread Safety in Swift With One Runtime Trick]]></title>
            <link>https://medium.com/better-programming/mastering-thread-safety-in-swift-with-one-runtime-trick-260c358a7515?source=rss-5488c0669d72------2</link>
            <guid isPermaLink="false">https://medium.com/p/260c358a7515</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Geor Kasapidi]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 21:21:58 GMT</pubDate>
            <atom:updated>2023-08-14T21:21:58.597Z</atom:updated>
            <content:encoded><![CDATA[<h4>The optimal method to ensure memory safety in a multi-threaded environment</h4><figure><img alt="hardware becomes more powerful and compact over time… while software becomes slower and more complex" src="https://cdn-images-1.medium.com/max/1000/1*0yJrqWxsoTgGfq57r4YSAA.jpeg" /><figcaption>Popular wisdom</figcaption></figure><p>The rise of parallelism in hardware has led to significant changes in software development. This has brought about the introduction of APIs for thread management and synchronization primitives in SDKs. Crafting a multi-threaded program that runs without glitches is a challenging endeavor. Among the most daunting challenges is ensuring different threads access memory without conflict.</p><p>In true parallel systems (like multi-core or multiprocessor setups), two threads might simultaneously read from and write to the same memory location, leading to a “data race.” Delving into the finer details (such as data size, alignment, processor caches, and atomics) might get complex, but using mutexes is the conventional method to prevent data races. When a mutex instance is in place, and its lock/unlock methods are appropriately called, it ensures the atomicity of data operations and exclusive access.</p><p>On Apple’s platforms, the os_unfair_lock is the <a href="https://serhiybutz.medium.com/swift-mutex-benchmark-b21ee293d9ad">most performance-efficient lock</a> available.</p><p>In Swift, using it can be a bit more challenging compared to other locks. Prior to iOS 16, developers had to manage memory manually to prevent creating local instance copies.</p><pre>import os<br><br>public final class UnfairLock {<br>    public init() {<br>        self.pointer = .allocate(capacity: 1)<br>        self.pointer.initialize(to: os_unfair_lock())<br>    }<br><br>    deinit {<br>        self.pointer.deinitialize(count: 1)<br>        self.pointer.deallocate()<br>    }<br><br>    public func lock() {<br>        os_unfair_lock_lock(self.pointer)<br>    }<br><br>    public func unlock() {<br>        os_unfair_lock_unlock(self.pointer)<br>    }<br><br>    private let pointer: os_unfair_lock_t<br>}</pre><p>Starting with iOS 16, you can utilize the newly introduced OSAllocatedUnfairLock type. Its possible implementation might be similar to the code example provided above:</p><pre>let lock = OSAllocatedUnfairLock()<br><br>lock.lock()<br>// ...<br>lock.unlock()</pre><p>To avoid repeatedly placing paired lock/unlock calls throughout the code and to prevent data races, many developers utilize a feature known as “property wrappers.” This acts as syntactic sugar by encapsulating the lock/unlock logic within itself:</p><pre>@propertyWrapper<br>public final class ThreadSafe&lt;T&gt; {<br>    public init(wrappedValue: T) {<br>        self.value = wrappedValue<br>    }<br><br>    public var projectedValue: ThreadSafe&lt;T&gt; { self }<br><br>    public var wrappedValue: T {<br>        get {<br>            self.lock.lock(); defer { self.lock.unlock() }<br>            return self.value<br>        }<br>        set {<br>            self.lock.lock(); defer { self.lock.unlock() }<br>            self.value = newValue<br>        }<br>    }<br><br>    private let lock = UnfairLock()<br><br>    private var value: T<br>}</pre><p>But there is one implicit problem in the wrappedValue implementation:</p><blockquote>GET and SET are atomic, but GET+SET is not</blockquote><p>What does it mean? For example, you have the following code:</p><pre>@ThreadSafe<br>var x: UInt64 = 0<br><br>x += 1</pre><p>This line of code, x += 1, essentially consists of a “get” operation followed by a “set” operation (x = x + 1). While each of these operations is atomic individually, there’s a potential issue: another thread might update the value between the “get” and “set” operations, leading to unexpected outcomes in the program logic. Experienced developers recognize this pitfall and often employ a helper method to mitigate this issue, as shown below:</p><pre>public func write&lt;V&gt;(_ f: (inout T) -&gt; V) -&gt; V {<br>    self.lock.lock(); defer { self.lock.unlock() }<br>    return f(&amp;self.value)<br>}</pre><p>Which in the example with the counter leads to the following use of the property wrapper:</p><pre>@ThreadSafe<br>var x: Int = 5<br><br>$x.write { $0 += 1 }</pre><p>The solution works, but it doesn’t eliminate the human element. This is because both expressions x += 1 and $x.write { $0 += 1 } are considered valid by the compiler.</p><p>However, there’s no need to worry. Swift&#39;s undocumented feature allows you to merge paired “get+set” calls into a single operation. This feature is actively <a href="https://github.com/apple/swift/blob/5a329a65a9dbe30321e1b155698ceec2132e42bd/stdlib/public/core/Array.swift#L751">used within the standard Swift library</a> and is named _modify :</p><pre>var wrappedValue: T {<br>    get { return value }<br>    _modify { yield &amp;self.value }<br>}</pre><p>_modify is an accessor (like get and set) with two very important advantages:</p><ol><li><strong>Atomicity</strong> — combining “get+set” into one call</li><li><strong>Performance</strong> — working with data in place, without copying</li></ol><p>You can read more about _modify and yield in the <a href="https://forums.swift.org/t/modify-accessors/31872">original pitch</a> and <a href="https://trycombine.com/posts/swift-read-modify-coroutines/">this post</a>.</p><blockquote>_modify is a publicly accessible API that remains undocumented. However, based on my year and a half of experience using it in a project that serves millions of users, I&#39;ve encountered no issues.</blockquote><h3>Happy Ending</h3><p>Combining unfair lock with _modify, we achieve the most convenient and optimal method for ensuring memory safety in multi-threaded environment:</p><pre>public var wrappedValue: T {<br>    get {<br>        self.lock.lock(); defer { self.lock.unlock() }<br>        return self.value<br>    }<br>    _modify {<br>        self.lock.lock(); defer { self.lock.unlock() }<br>        yield &amp;self.value<br>    }<br>}<br><br>...<br><br>private let lock = UnfairLock()</pre><p>The code from the article is provided as a production-ready Swift package in <a href="https://github.com/geor-kasapidi/STS">this repository</a>. Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=260c358a7515" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/mastering-thread-safety-in-swift-with-one-runtime-trick-260c358a7515">Mastering Thread Safety in Swift With One Runtime Trick</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting a Swift Package Plugin for App Data Protection]]></title>
            <link>https://medium.com/better-programming/from-encryption-to-runtime-crafting-a-swift-package-plugin-for-app-data-protection-c5edec2b0495?source=rss-5488c0669d72------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5edec2b0495</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Geor Kasapidi]]></dc:creator>
            <pubDate>Sun, 30 Jul 2023 16:12:10 GMT</pubDate>
            <atom:updated>2023-07-31T08:04:21.769Z</atom:updated>
            <content:encoded><![CDATA[<h4>From encryption to runtime</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*eFfMp3M20ieB6pz_6PFXtg.png" /></figure><p>Protecting data and intellectual property is a common but challenging task in software development. No developer wishes their individual or team efforts to be unlawfully exploited by intruders or competitors. While iOS apps provide significant security — provided by Apple encryption and runtime sandbox — more in-depth analysis of the IPA file reveals that not all files are encrypted. Various resources can be easily accessed, even without jailbreaking. Apple partially solved this problem by implementing encryption of Core ML models, but many resources remain unprotected.</p><p>In this detailed article, I will show you how to implement automatic file encryption in your project using the power of SPM plugins.</p><blockquote>Note: The source code for this article can be found in this <a href="https://github.com/geor-kasapidi/PluginSPM">repository</a>.</blockquote><p>To set the stage, we will first familiarize ourselves with the theoretical aspects of SPM plugins.</p><h3>Swift Package Manager Plugins Explained</h3><p>Swift package plugins encompass two categories: command plugins and build tool plugins. Command plugins are typically invoked using the swift package &lt;command&gt; &lt;arguments&gt; syntax, whereas build tool plugins integrate into the project’s build graph, triggering automatically.</p><p>The main objective of the build tool plugins is to provide commands that enhance package building. These commands can be either build or prebuild commands:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*LtaKdXwqopkw_8kk1WF12g.png" /></figure><p>“Build” and “prebuild” indicate when a command runs: during or before the build process. If you want to create new code or resources, you should use prebuild commands:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*v4PA_0CJvp0uSV2g6ZJnVA.png" /></figure><p>Swift Package Manager insists that prebuild commands be defined as binary targets in the package manifest:</p><pre>.binaryTarget(<br>  name: &quot;MyCompiledCommand&quot;,<br>  path: &quot;mycommand.artifactbundle.zip&quot;<br>)</pre><p>An artifact bundle is essentially a compressed directory with a certain structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*jGnabafWn_NytwgpOYitsQ.png" /></figure><p>mycommand refers to the executable binary command file (its name can be arbitrary), while info.json represents the artifact scheme:</p><pre>{<br>  &quot;schemaVersion&quot;: &quot;1.0&quot;,<br>  &quot;artifacts&quot;: {<br>    &quot;mycommand&quot;: {<br>      &quot;version&quot;: &quot;0.0.1&quot;,<br>      &quot;type&quot;: &quot;executable&quot;,<br>      &quot;variants&quot;: [<br>        {<br>          &quot;path&quot;: &quot;coolproject/bin/mycommand&quot;,<br>          &quot;supportedTriples&quot;: [<br>            &quot;x86_64-apple-macosx&quot;,<br>            &quot;arm64-apple-macosx&quot;<br>          ]<br>        }<br>      ]<br>    }<br>  }<br>}</pre><blockquote>Note: The project repository includes a script for building the artifact bundle.</blockquote><p>For a plugin to utilize a command, it must be included in the plugin’s list of dependencies:</p><pre>.plugin(<br>  name: &quot;MyPlugin&quot;,<br>  capability: .buildTool(),<br>  dependencies: [&quot;MyCompiledCommand&quot;]<br>)</pre><p>Correspondingly, the plugin must be connected to the target:</p><pre>.target(<br>  name: &quot;MyTarget&quot;,<br>  plugins: [&quot;MyPlugin&quot;]<br>)</pre><p>The structure of build tool plugins is simple:</p><ol><li>The primary logic of the plugin is encapsulated within the command code.</li><li>The plugin’s code itself is designed to generate calls to the appropriate commands.</li><li>Targets equip plugins with a context based on which the plugin produces calls.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*XcVUp4zvKPqsKQ41lRXrNA.png" /></figure><p>In short, plugins link targets and commands together.</p><p>For a file encryption task, we would create a prebuild command and a plugin to execute it.</p><h3>Developing a Command and Plugin</h3><p>The command for file encryption will be introduced via an executable file, generated from an executable Swift package that utilizes the Swift Argument Parser.</p><p>It will require two arguments: the directory containing the files to be encrypted, and the destination directory where the encrypted files along with the generated code will be saved:</p><pre>@Option(completion: CompletionKind.file(), transform: URL.init(fileURLWithPath:))<br>private var inputDir: URL<br><br>@Option(completion: CompletionKind.file(), transform: URL.init(fileURLWithPath:))<br>private var outputDir: URL</pre><p>The logical flow of the command is straightforward:</p><ol><li>Acquire a list of files to be encrypted.</li><li>Individually encrypt each file using a unique key, and save it to the output directory.</li><li>Generate a code for retrieving the decrypted data at runtime.</li><li>Save the generated code.</li></ol><pre>mutating func run() throws {<br>    try self.recreateOutputDir()<br><br>    var code: [String] = [<br>        &quot;import Foundation&quot;,<br>        &quot;import CryptoKit&quot;,<br>    ]<br><br>    let files = try self.collectFilesToProtect()<br><br>    for file in files {<br>        let inName = file.lastPathComponent<br>        let outName = UUID().uuidString<br>        let key = SymmetricKey(size: .bits256)<br><br>        try self.encrypt(file: file, outName: outName, key: key)<br><br>        code.append(self.generateAccessCodeForFile(<br>            outName: outName,<br>            inName: inName,<br>            key: key<br>        ))<br>    }<br><br>    try self.save(generatedCode: code)<br>}</pre><p>Beyond this, there are only implementation details. Our main focus will be on the plugin:</p><pre>@main<br>struct MyPlugin: BuildToolPlugin {<br>    func createBuildCommands(context: PluginContext, target: Target) async throws -&gt; [Command] {<br>        try [<br>            .prebuildCommand(<br>                displayName: &quot;Protect app data&quot;,<br>                executable: context.tool(named: &quot;mycommand&quot;).path,<br>                arguments: [<br>                    &quot;--input-dir&quot;,<br>                    target.directory.appending(&quot;Files&quot;),<br>                    &quot;--output-dir&quot;,<br>                    context.pluginWorkDirectory.appending(&quot;Out&quot;),<br>                ],<br>                outputFilesDirectory: context.pluginWorkDirectory.appending(&quot;Out&quot;)<br>            ),<br>        ]<br>    }<br>}</pre><p>Despite its apparent simplicity, there are key points in the code that needs further explanation. As previously stated, the plugin connects the target and the command. To access the target directory, use target.directory. This directory is read-only.</p><p>For creating new files, the plugin context offers a special sandbox directory — pluginWorkDirectory. In the prebuild command invocation, outputFilesDirectory must be included — files from this directory will be read by the build system post-command execution and processed in accordance with the subsequent heuristics:</p><ol><li>All *.swift files will be compiled as part of the target.</li><li>Any other files will be treated as resources, subject to the rule=process, and incorporated into the target bundle following standard SPM rules.</li></ol><h3>Plugin demo</h3><p>Now, we are prepared for deployment! We need to incorporate the security files into our demo target, simultaneously excluding them from the target sources in the package manifest. This way, we can prevent the original files from being included in the bundle:</p><pre>.target(<br>    name: &quot;MyTarget&quot;,<br>    exclude: [&quot;Files&quot;],<br>    plugins: [&quot;MyPlugin&quot;]<br>)</pre><p>We initiate the build and… there we go! Due to our designated plugin and command, the system will generate corresponding code for each file housed in the Files directory (for instance, cheat_code.txt):</p><pre>public func load_cheat_code_txt() throws -&gt; Data {<br>    let data = try Data(contentsOf: Bundle.module.url(/service/forresource: &quot;C21E2BF2-DCEC-4A77-ACE4-110B918D4923&quot;, withExtension: nil)!)<br>    let sealedBox = try ChaChaPoly.SealedBox(combined: data)<br>    return try ChaChaPoly.open(sealedBox, using: .init(data: [0x8e, 0xbf, 0xf5, 0x3f, 0xf3, 0xfc, 0xb7, 0x22, 0x11, 0x68, 0x84, 0x18, 0x81, 0x3e, 0x80, 0xbf, 0x4e, 0x9a, 0xe3, 0xc1, 0x3d, 0xe8, 0x49, 0x22, 0x91, 0xc2, 0x21, 0x51, 0x88, 0xd7, 0xc2, 0x58]))<br>}</pre><p><strong>Important note</strong> — For larger, more critical projects, I recommend creating a unique key storage algorithm. Techniques can include obfuscation, inlining the code, or even uploading keys to the backend and retrieving them during the application’s runtime. Considering that jailbreak allows for both static and dynamic analysis of the application code, it is almost impossible to achieve complete protection. However, it is quite possible to significantly increase the complexity of reverse engineering.</p><p><strong>Another important note</strong> — If you need to do more than just encrypt data, like compressing entire directories, you can use the AppleArchive framework. It’s a bit complicated to use as is, so I’ve made a simple tool to help. <a href="https://github.com/geor-kasapidi/AAR">This tool</a> makes using the framework as easy as typing a single line of code.</p><h3>Conclusion</h3><p>Our custom plugin has automated the entire file encryption process. All a developer needs to do is place files in the specified directory.</p><p>Following this, the plugin automatically handles encryption and code generation. The resulting code can then be called in the suitable section of the application to retrieve the decrypted files.</p><p>This process is both efficient and straightforward, greatly simplifying the task at hand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5edec2b0495" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/from-encryption-to-runtime-crafting-a-swift-package-plugin-for-app-data-protection-c5edec2b0495">Crafting a Swift Package Plugin for App Data Protection</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Swift Package Manager to Save Gigabytes of Network Traffic and Disk Space]]></title>
            <link>https://medium.com/better-programming/how-to-use-swift-package-manager-saving-gigabytes-of-network-traffic-and-disk-space-998bd148ad56?source=rss-5488c0669d72------2</link>
            <guid isPermaLink="false">https://medium.com/p/998bd148ad56</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dependency-management]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-package-manager]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Geor Kasapidi]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 16:44:21 GMT</pubDate>
            <atom:updated>2023-07-16T21:40:08.674Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use SPM to store dependency checkouts in a repository and do it better than CocoaPods</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NAuFx5IYGdz0LE_HO-5sVg.jpeg" /><figcaption>Source: <a href="https://developer.apple.com/news/?id=uyp21www">Apple</a></figcaption></figure><p>Many of you have experienced the annoying situation — you open a project or switch a branch, and see the sad picture of how SPM resolves packages.</p><p>One of the advantages of CocoaPods, compared to SPM, is that dependency checkouts are stored with the project directly in the repository. This allows you to painlessly launch project from any commit and not waste time on CI to download dependencies and resolve them.</p><p>In this article, I will show you how to use SPM to store dependency checkouts in a repository and do it better than CocoaPods.</p><p>Before we start, let’s define a list of requirements for a future solution:</p><ol><li>We continue to live in the paradigm of Swift packages</li><li>External package dependencies become local</li><li>Requires a mechanism to locally clone external dependencies</li><li>Store only files from dependency repositories locally that are required by the project</li></ol><p>With the inputs in hand, we can start implementing.</p><p>Let’s start with cloning dependencies. To do this, we will create a separate local package and add all the required dependencies to Package.swift:</p><pre>// swift-tools-version: 5.7<br>// The swift-tools-version declares the minimum version of Swift required to build this package.<br><br>import PackageDescription<br><br>let package = Package(<br>    name: &quot;VendorPackages&quot;,<br>    platforms: [<br>        .iOS(.v15),<br>        .macOS(.v12),<br>    ],<br>    products: [<br>        .library(<br>            name: &quot;VendorPackages&quot;,<br>            targets: [&quot;VendorPackages&quot;]<br>        ),<br>    ],<br>    dependencies: [<br>        .package(<br>            url: &quot;https://github.com/devicekit/DeviceKit.git&quot;,<br>            exact: &quot;5.0.0&quot;<br>        ),<br>        .package(<br>            url: &quot;https://github.com/kean/Nuke.git&quot;,<br>            exact: &quot;12.1.2&quot;<br>        ),<br>        .package(<br>            url: &quot;https://github.com/groue/GRDB.swift.git&quot;,<br>            exact: &quot;6.15.1&quot;<br>        ),<br>        .package(<br>            url: &quot;https://github.com/SnapKit/SnapKit&quot;,<br>            exact: &quot;5.6.0&quot;<br>        ),<br>        .package(<br>            url: &quot;https://github.com/airbnb/lottie-ios&quot;,<br>            exact: &quot;4.2.0&quot;<br>        ),<br>    ],<br>    targets: [<br>        .target(<br>            name: &quot;VendorPackages&quot;,<br>            dependencies: [<br>                &quot;DeviceKit&quot;,<br>                .product(name: &quot;Nuke&quot;, package: &quot;Nuke&quot;),<br>                .product(name: &quot;NukeUI&quot;, package: &quot;Nuke&quot;),<br>                .product(name: &quot;NukeExtensions&quot;, package: &quot;Nuke&quot;),<br>                &quot;SnapKit&quot;,<br>                .product(name: &quot;GRDB&quot;, package: &quot;GRDB.swift&quot;),<br>                .product(name: &quot;Lottie&quot;, package: &quot;lottie-ios&quot;),<br>            ]<br>        ),<br>    ]<br>)</pre><p>This package contains no code. Its only value is the dependency manifest.</p><p>After opening the package in Xcode or running the swift package resolve command, notice that a hidden .build directory has appeared in the package directory with a checkouts subdirectory that contains local dependency clones:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*2YWmnTdlrpPajHbCSKC6uQ.png" /></figure><p>Let me draw your attention to the size of the .build directory. It is equal to <strong>993 MB</strong>, of which <strong>328 MB</strong> is occupied by checkouts and <strong>665 MB </strong>by repositories. I have deliberately selected popular packages (GRDB, Lottie) with a long history to demonstrate the scale of the problem.</p><p>Knowing where the local dependency clones are located, our next step is to determine the minimum files from these packages that our project needs to build. Such files are obviously the target sources of those products that are used in our original local package, where we specified the required external dependencies.</p><p>We are absolutely not interested in test target files, or various demo resources. In other words, everything that just takes up disk space and is not used when compiling the project. If necessary, these “extra” files can always be used separately.</p><p>Determining this minimum of files may at first glance seem like a rather non-trivial task, but in practice, the SPM CLI provides us with everything we need:</p><pre>swift package describe --type=json</pre><p>Let’s use this command in the directory of, for example, the Nuke package:</p><pre>{<br>  &quot;dependencies&quot; : [<br><br>  ],<br>  &quot;manifest_display_name&quot; : &quot;Nuke&quot;,<br>  &quot;name&quot; : &quot;Nuke&quot;,<br>  &quot;path&quot; : &quot;.build/checkouts/Nuke&quot;,<br>  &quot;platforms&quot; : [...],<br>  &quot;products&quot; : [...],<br>  &quot;targets&quot; : [<br>    {<br>      &quot;c99name&quot; : &quot;NukeVideo&quot;,<br>      &quot;module_type&quot; : &quot;SwiftTarget&quot;,<br>      &quot;name&quot; : &quot;NukeVideo&quot;,<br>      &quot;path&quot; : &quot;Sources/NukeVideo&quot;,<br>      &quot;product_memberships&quot; : [<br>        &quot;NukeVideo&quot;<br>      ],<br>      &quot;sources&quot; : [<br>        &quot;AVDataAsset.swift&quot;,<br>        &quot;ImageDecoders+Video.swift&quot;,<br>        &quot;VideoPlayerView.swift&quot;<br>      ],<br>      &quot;target_dependencies&quot; : [<br>        &quot;Nuke&quot;<br>      ],<br>      &quot;type&quot; : &quot;library&quot;<br>    },<br>    {<br>      &quot;c99name&quot; : &quot;NukeUI&quot;,<br>      &quot;module_type&quot; : &quot;SwiftTarget&quot;,<br>      &quot;name&quot; : &quot;NukeUI&quot;,<br>      &quot;path&quot; : &quot;Sources/NukeUI&quot;,<br>      &quot;product_memberships&quot; : [<br>        &quot;NukeUI&quot;<br>      ],<br>      &quot;sources&quot; : [<br>        &quot;FetchImage.swift&quot;,<br>        &quot;Internal.swift&quot;,<br>        &quot;LazyImage.swift&quot;,<br>        &quot;LazyImageState.swift&quot;,<br>        &quot;LazyImageView.swift&quot;<br>      ],<br>      &quot;target_dependencies&quot; : [<br>        &quot;Nuke&quot;<br>      ],<br>      &quot;type&quot; : &quot;library&quot;<br>    },<br>    {<br>      &quot;c99name&quot; : &quot;NukeExtensions&quot;,<br>      &quot;module_type&quot; : &quot;SwiftTarget&quot;,<br>      &quot;name&quot; : &quot;NukeExtensions&quot;,<br>      &quot;path&quot; : &quot;Sources/NukeExtensions&quot;,<br>      &quot;product_memberships&quot; : [<br>        &quot;NukeExtensions&quot;<br>      ],<br>      &quot;sources&quot; : [<br>        &quot;ImageLoadingOptions.swift&quot;,<br>        &quot;ImageViewExtensions.swift&quot;<br>      ],<br>      &quot;target_dependencies&quot; : [<br>        &quot;Nuke&quot;<br>      ],<br>      &quot;type&quot; : &quot;library&quot;<br>    },<br>    {<br>      &quot;c99name&quot; : &quot;Nuke&quot;,<br>      &quot;module_type&quot; : &quot;SwiftTarget&quot;,<br>      &quot;name&quot; : &quot;Nuke&quot;,<br>      &quot;path&quot; : &quot;Sources/Nuke&quot;,<br>      &quot;product_memberships&quot; : [<br>        &quot;Nuke&quot;,<br>        &quot;NukeUI&quot;,<br>        &quot;NukeVideo&quot;,<br>        &quot;NukeExtensions&quot;<br>      ],<br>      &quot;sources&quot; : [/* a lot of sources here */],<br>      &quot;type&quot; : &quot;library&quot;<br>    }<br>  ],<br>  &quot;tools_version&quot; : &quot;5.6&quot;<br>}</pre><p>JSON output contains an array of targets, which literally have all the necessary source files, as well as products that include these targets (if the target contains resources, they will be located by the “resources” key).</p><p>Boom! 100% what we need.</p><p>Since the most complex and non-trivial part turned out to be trivial and can be solved with a single command, then all that remains at this stage is to write a small script that will copy the necessary files for the products specified in our local project, preserving the directory structure.</p><p>I did it with a simple shell script and <a href="https://jqlang.github.io/jq/">jq</a> utility. You are free to use the tools familiar to you, relying on my implementation as a reference:</p><pre>rm -rf Sources &amp;&amp; mkdir -p Sources<br><br>cd _Proxy # directory for local package with remote dependencies<br><br>swift package clean<br>swift package update<br><br>required_products=$(swift package describe --type json | jq -c &#39;(.targets[] | select(.name==&quot;VendorPackages&quot;)) | .product_dependencies[]&#39;)<br><br>for repo in $(ls .build/checkouts); do<br>    echo $repo<br><br>    mkdir -p ../Sources/$repo<br><br>    cp -r .build/checkouts/$repo/Package.swift ../Sources/$repo/_Package.swift<br><br>    package_json=$(swift package --package-path .build/checkouts/$repo describe --type json | jq -c)<br><br>    targets=$(jq -c &#39;(.targets[] | select(.product_memberships != null))&#39; &lt;&lt;&lt; $package_json)<br><br>    echo &quot;$package_json&quot; | jq -c &#39;(.targets[] | select(.product_memberships != null))&#39; | while read -r target; do<br>        required_target=false<br><br>        target_products=$(jq -c &#39;.product_memberships[]&#39; &lt;&lt;&lt; &quot;$target&quot;)<br><br>        for target_product in $target_products; do<br>            for required_product in $required_products; do<br>                if [ $required_product == $target_product ]; then<br>                    required_target=true<br>                fi<br>            done<br>        done<br><br>        if ! $required_target; then<br>            continue<br>        fi<br><br>        name=$(jq -r &#39;.name&#39; &lt;&lt;&lt; $target)<br>        path=$(jq -r &#39;.path&#39; &lt;&lt;&lt; $target)<br>        type=$(jq -r &#39;.type&#39; &lt;&lt;&lt; $target)<br><br>        if [ $type == &quot;system-target&quot; ]; then<br>            mkdir -p ../Sources/$repo/$path<br>            cp -r .build/checkouts/$repo/$path/. ../Sources/$repo/$path<br>        fi<br><br>        if [ $type == &quot;library&quot; ]; then<br>            echo &quot;$target&quot; | jq --raw-output &#39;.sources[]&#39; | while read -r source; do<br>                mkdir -p ../Sources/$repo/$path/&quot;$(dirname &quot;$source&quot;)&quot;<br>                cp .build/checkouts/$repo/$path/&quot;$source&quot; ../Sources/$repo/$path/&quot;$source&quot;<br>            done<br>        fi<br>    done<br>done</pre><p>Using this script, we copied all the files needed to build the project from all external dependencies.</p><p>The last question that needs to be answered is — how to actually use the copied files in our project.</p><p>There is no single answer. For example, you can expand the script and copy package manifests along with other files, somehow removing unused targets from there: using regular expressions, AST modifications, etc.</p><p>I chose not to automate this step and added another local package, where I registered all the dependencies — specifying the local paths to the copied files:</p><pre>// swift-tools-version: 5.7<br>// The swift-tools-version declares the minimum version of Swift required to build this package.<br><br>import PackageDescription<br><br>let package = Package(<br>    name: &quot;VendorPackages&quot;,<br>    platforms: [<br>        .iOS(.v15),<br>        .macOS(.v12),<br>    ],<br>    products: [<br>        .library(name: &quot;DeviceKit&quot;, targets: [&quot;DeviceKit&quot;]),<br>        .library(name: &quot;GRDB&quot;, targets: [&quot;GRDB&quot;]),<br>        .library(name: &quot;Lottie&quot;, targets: [&quot;Lottie&quot;]),<br>        .library(name: &quot;Nuke&quot;, targets: [&quot;Nuke&quot;]),<br>        .library(name: &quot;NukeUI&quot;, targets: [&quot;NukeUI&quot;]),<br>        .library(name: &quot;NukeExtensions&quot;, targets: [&quot;NukeExtensions&quot;]),<br>        .library(name: &quot;SnapKit&quot;, targets: [&quot;SnapKit&quot;]),<br>    ],<br>    targets: [<br>        .target(<br>            name: &quot;DeviceKit&quot;,<br>            path: &quot;Sources/DeviceKit/Source&quot;<br>        ),<br>        .target(<br>            name: &quot;Nuke&quot;,<br>            path: &quot;Sources/Nuke/Sources/Nuke&quot;<br>        ),<br>        .target(<br>            name: &quot;NukeUI&quot;,<br>            dependencies: [&quot;Nuke&quot;],<br>            path: &quot;Sources/Nuke/Sources/NukeUI&quot;<br>        ),<br>        .target(<br>            name: &quot;NukeExtensions&quot;,<br>            dependencies: [&quot;Nuke&quot;],<br>            path: &quot;Sources/Nuke/Sources/NukeExtensions&quot;<br>        ),<br>        .target(<br>            name: &quot;GRDB&quot;,<br>            dependencies: [&quot;CSQLite&quot;],<br>            path: &quot;Sources/GRDB.swift/GRDB&quot;<br>        ),<br>        .systemLibrary(<br>            name: &quot;CSQLite&quot;,<br>            path: &quot;Sources/GRDB.swift/Sources/CSQLite&quot;<br>        ),<br>        .target(<br>            name: &quot;Lottie&quot;,<br>            path: &quot;Sources/lottie-ios/Sources&quot;<br>        ),<br>        .target(<br>            name: &quot;SnapKit&quot;,<br>            path: &quot;Sources/SnapKit/Sources&quot;<br>        ),<br>    ],<br>    swiftLanguageVersions: [.v5]<br>)</pre><p>The advantage of this approach is that you control the description of the targets, their settings, and so on.</p><p>Thus, we have automated the granular copying of the required dependency files but left the local package manifest that will be used in the project under manual control.</p><p>Unbelievable, but true: the size of the copied files is <strong>4.7 MB — </strong>which is <strong>211 times</strong> smaller than our .build directory.</p><p>You can find the source code for the article in <a href="https://github.com/geor-kasapidi/spm-local">this repository</a>.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=998bd148ad56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-use-swift-package-manager-saving-gigabytes-of-network-traffic-and-disk-space-998bd148ad56">How to Use Swift Package Manager to Save Gigabytes of Network Traffic and Disk Space</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>