Skip to content

Commit

Permalink
cutbox.js can use shellCommand("command args...")
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonm23 committed Apr 8, 2023
1 parent 1cec136 commit 30348c1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
14 changes: 14 additions & 0 deletions CutBox/CutBox/Source/App/Services/JSFuncService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ class JSFuncService: NSObject {
return JSFuncService.shared.js.evaluateScript(fileContent)
}

let shellCommand: @convention(block) (String) -> String = { command in
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", command]

let pipe = Pipe()
task.standardOutput = pipe
task.launch()

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

var filterText: String = ""

var funcs: [(String, Int)] {
Expand Down Expand Up @@ -88,6 +101,7 @@ class JSFuncService: NSObject {
func setup() {
self.js = JSContext()
self.js["require"] = self.require
self.js["shellCommand"] = self.shellCommand
}

func reload() {
Expand Down
7 changes: 7 additions & 0 deletions CutBox/CutBoxUnitTests/JSFunc/JSFuncServiceSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ class JSFuncServiceSpec: QuickSpec {
}
}

describe("shellCommand") {
it("runs a shell command from JS and returns a string") {
let result = subject.repl("shellCommand('printf \"hello world\"')")
expect(result).to(equal("hello world"))
}
}

describe("require") {
let fileManager = FileManager.default
let path = "\(fileManager.currentDirectoryPath)/test-require.js"
Expand Down

0 comments on commit 30348c1

Please sign in to comment.