Home > front end >  Run homebrew package from Swift Command Line Tool
Run homebrew package from Swift Command Line Tool

Time:06-10

I'm developing a macOS Command Line Tool target with Swift for my app. With this target, I want to execute a Kotlin command (installed with homebrew).

Here's the Kotlin command:

kotlinc -script ./kotlin_file.kts

When I launch this Kotlin command from my terminal, there is no issue at all.

But when I run the Command Line target from Xcode, I get an error (different error depending on the method used, cf below).

I've tried multiple methods :

Method 1

let test = execute1("kotlinc",
                    args: ["-script", "./kotlin_file.kts")
    private func execute1(command: String, args: [String] = []) -> String {
        let proc = Process()
        proc.launchPath = command
        proc.arguments = args

        let pipe = Pipe()
        proc.standardOutput = pipe

        proc.launch()

        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        return String(data: data, encoding: String.Encoding.utf8)!
    }

Error :

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'launch path not accessible'

Method 2

let test = execute2("kotlinc",
                    args: ["-script", "./kotlin_file.kts")
    private func execute2(_ path: String, args: [String] = []) {
        let process = Process()
        process.executableURL = URL(fileURLWithPath: path)
        process.arguments = args

        let outputPipe = Pipe()
        process.standardOutput = outputPipe

        try? process.run()

        let output = outputPipe.fileHandleForReading.readDataToEndOfFile()
        let str = String(decoding: output, as: UTF8.self)
        print(str)
    }

Here with Method 2 it stays stuck at readDataToEndOfFile.

Method 3

I've put the Kotlin command inside a script.sh file and executed this shell file from the target, but it get this error :

kotlinc: command not found

Is it possible to achieve this?

CodePudding user response:

So I've found multiple solutions :

Solution 1 : Adding $PATH to env variables

Edit Scheme > Arguments > Environment Variables : Add PATH and set its value to ${PATH}

Solution 2 : Launch in terminal

Edit Scheme > Options : Set Console to Use Terminal . But I found this option very buggy with random errors.

  • Related