How to load file and run swift code from Swift Package Manager manifest file?

1.2k views Asked by At

I have and iOS Project that has a SPM dependency and I am trying to update the Package object inside the SPM manifest file(Package.swift) based on a configuration file to get something similar to:

// Package.swift
// swift-tools-version:5.3
import PackageDescription
import Foundation

var modules : [Modules] = getConfigurationFrom("file.json")

// Where getConfigurationFrom function calls to:
// Bundle.main.path(forResource: "file", ofType: "json")

if modules.first.isEnabled {
    // Build Package object with moduleA dependencies
    Package(name: "Package", ... Dependencies for ModuleA ...)
} else {
    // Build Package object with moduleB dependencies
    Package(name: "Package", ... Dependencies for ModuleB ...)
}

But I am not able to properly load the json file from the Main bundle, maybe am I missing something here? Or is there another way to build different dependencies based on a file using SPM without using party libraries?

Thank you!

1

There are 1 answers

1
szotp On BEST ANSWER

This is a bit hacky, but you can get path to current file using #file, so if you are interested in file.json that is placed in the same directory as Package.swift, you can do this:

let packageURL = URL(fileURLWithPath: #file).deletingLastPathComponent()
let fileURL = packageURL.appendingPathComponent("file.json")