Commit 2af8f2b2ca

2af8f2b2caff0e85d9d6440967eb0586afa1663d

parent: ea71ae826c

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 19:30 UTC

Run Babel commands through /bin/sh with input from a file, as Org does

Layout: unified · split

Sources/OrgPrograms/BabelRunner.swift +22 −17
@@ -24,6 +24,22 @@ public enum BabelRunner {
2424 return paths.contains { FileManager.default.isExecutableFile(atPath: $0) }
2525 }
2626
27 /// The words `/bin/sh` makes of `command`, after expanding `~`, variables and quotes.
28 public static func words(_ command: String) -> [String] {
29 guard command.contains(where: { "~$'\"`\\".contains($0) }) else { return command.split(whereSeparator: \.isWhitespace).map(String.init) }
30 let process = Process()
31 process.executableURL = URL(fileURLWithPath: "/bin/sh")
32 process.arguments = ["-c", "printf '%s\\0' " + command]
33 process.environment = environment
34 let out = Pipe()
35 process.standardOutput = out
36 process.standardError = FileHandle.nullDevice
37 guard (try? process.run()) != nil else { return [] }
38 let data = out.fileHandleForReading.readDataToEndOfFile()
39 process.waitUntilExit()
40 return String(decoding: data, as: UTF8.self).split(separator: "\0").map(String.init)
41 }
42
2743 public static func run(_ job: BabelJob, fileDirectory: URL, timeout: Duration = .seconds(300)) async throws -> BabelOutput {
2844 for programs in job.programs where !programs.contains(where: installed) {
2945 let names = programs.count == 1 ? programs[0] : "Neither " + programs.joined(separator: " nor ")
@@ -42,7 +58,6 @@ public enum BabelRunner {
4258 let process = Process()
4359 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
4460 process.environment = environment
45 let stdin = Pipe()
4661 switch job.runner {
4762 case .process(let executable, var arguments):
4863 if let script = job.script {
@@ -51,10 +66,8 @@ public enum BabelRunner {
5166 try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.path)
5267 arguments = arguments.map { $0.replacingOccurrences(of: Babel.scriptFileToken, with: file.path) }
5368 }
54 // A command with arguments, such as `:cmd "node --no-warnings"`, runs in the shell as
55 // Org runs it.
56 process.arguments = executable.contains(where: \.isWhitespace)
57 ? ["/bin/sh", "-c", executable + " \"$@\"", "sh"] + arguments : [executable] + arguments
69 // In the shell, as Org runs it, so `:cmd "node --no-warnings"` or `~/bin/node` works.
70 process.arguments = ["/bin/sh", "-c", executable + " \"$@\"", "sh"] + arguments
5871 case .emacs:
5972 guard let emacs = EmacsRunner.executable() else { throw Failure(description: "Emacs isn't installed, so Emacs Lisp blocks can't run.") }
6073 let script = folder.appendingPathComponent("babel.el")
@@ -74,7 +87,10 @@ public enum BabelRunner {
7487 let stderr = folder.appendingPathComponent("stderr")
7588 FileManager.default.createFile(atPath: stderr.path, contents: nil)
7689 let err = try FileHandle(forWritingTo: stderr)
77 process.standardInput = stdin
90 // The input from a file, as `org-babel-eval` gives it.
91 let stdin = folder.appendingPathComponent("stdin")
92 if case .process = job.runner { try input.write(to: stdin, atomically: true, encoding: .utf8) } else { FileManager.default.createFile(atPath: stdin.path, contents: nil) }
93 process.standardInput = try FileHandle(forReadingFrom: stdin)
7894 process.standardOutput = out
7995 process.standardError = err
8096 do {
@@ -82,17 +98,6 @@ public enum BabelRunner {
8298 } catch {
8399 throw Failure(description: "Can't start \(process.arguments?.first ?? "the interpreter"): \(error.localizedDescription)")
84100 }
85 if case .process = job.runner {
86 let handle = stdin.fileHandleForWriting
87 let data = Data(input.utf8)
88 // Large programs would fill the pipe; write off the main thread.
89 Task.detached {
90 try? handle.write(contentsOf: data)
91 try? handle.close()
92 }
93 } else {
94 try stdin.fileHandleForWriting.close()
95 }
96101 let deadline = ContinuousClock.now + timeout
97102 while process.isRunning {
98103 if ContinuousClock.now > deadline {
Sources/OrgPrograms/Programs.swift +4 −1
@@ -16,7 +16,10 @@ public struct Programs: ProgramRunning {
1616 // js in JavaScriptCore when node (or `:cmd`) isn't installed. A `:cmd` with arguments runs
1717 // as written, since JavaScriptCore can't take node's options.
1818 switch job.runner {
19 case .process(let executable, _), .session(_, let executable, _):
19 case .process(let executable, _):
20 let words = BabelRunner.words(executable)
21 if words.count == 1, !BabelRunner.installed(words[0]), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output }
22 case .session(_, let executable, _):
2023 if !executable.contains(where: \.isWhitespace), !BabelRunner.installed(executable), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output }
2124 case .emacs:
2225 // Emacs Lisp in `Elisp` when Emacs isn't installed.
Tests/OrgProgramsTests/ProgramsTests.swift +45
@@ -254,6 +254,50 @@ struct JavaScriptFallbackTests {
254254 func usesNodeWhenInstalled() async throws {
255255 #expect(try await run("#+begin_src js :results output\nconsole.log(typeof require('fs').readFileSync)\n#+end_src\n").stdout == "function\n")
256256 }
257
258 /// A `:cmd` the shell expands, such as `~/../../opt/homebrew/bin/node`, runs node, as in Org.
259 @Test(.enabled(if: BabelRunner.installed("node")))
260 func expandsTheCommandAsTheShellDoes() async throws {
261 let node = try #require(BabelRunner.environment["PATH"]?.split(separator: ":").map { "\($0)/node" }
262 .first { FileManager.default.isExecutableFile(atPath: $0) })
263 let home = NSHomeDirectory()
264 let up = String(repeating: "../", count: home.split(separator: "/").count)
265 for cmd in ["~/" + up + node.dropFirst(), "$HOME/" + up + node.dropFirst(), "'\(node)'"] {
266 let output = try await run("#+begin_src js :cmd \"\(cmd)\" :results output\nconsole.log(typeof __filename)\n#+end_src\n")
267 #expect(output.stdout == "string\n", "\(cmd)")
268 }
269 }
270
271 /// An expanded `:cmd` that isn't installed runs in JavaScriptCore.
272 @Test func expandedCommandFallsBack() async throws {
273 #expect(try await run("#+begin_src js :cmd ~/no-such-node\nreturn [1, 2]\n#+end_src\n").stdout == "[ 1, 2 ]")
274 }
275}
276
277/// Interpreters run through `/bin/sh`, as Org runs them.
278struct ShellCommandTests {
279 @Test func words() {
280 #expect(BabelRunner.words("node --no-warnings") == ["node", "--no-warnings"])
281 #expect(BabelRunner.words("~/bin/node") == [NSHomeDirectory() + "/bin/node"])
282 #expect(BabelRunner.words("'a b' \"$HOME\"") == ["a b", NSHomeDirectory()])
283 }
284
285 @Test(.enabled(if: BabelRunner.installed("python3")))
286 func pythonWithOptions() async throws {
287 let text = "#+begin_src python :python \"python3 -X utf8\" :results output\nimport sys\nprint(sys.flags.utf8_mode)\n#+end_src\n"
288 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
289 guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") }
290 #expect(try await BabelRunner.run(job, fileDirectory: FileManager.default.temporaryDirectory).stdout == "1\n")
291 }
292
293 /// Standard input is a file, as `org-babel-eval` gives it.
294 @Test(.enabled(if: BabelRunner.installed("node")))
295 func standardInputIsAFile() async throws {
296 let text = "#+begin_src js :results output\nconst s = require('fs').fstatSync(0)\nconsole.log(s.isFile(), s.isFIFO(), process.stdin.constructor.name)\n#+end_src\n"
297 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
298 guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") }
299 #expect(try await BabelRunner.run(job, fileDirectory: FileManager.default.temporaryDirectory).stdout == "true false ReadStream\n")
300 }
257301}
258302
259303/// js blocks without a session run as `node FILE`, as `org-babel-execute:js` runs them.
@@ -270,6 +314,7 @@ struct NodeFileTests {
270314 "#+begin_src js :cmd \"node --no-warnings\" :results output\nconsole.log(process.argv.length, process.execArgv.join(' '))\n#+end_src\n",
271315 "#+begin_src js :results output\nconsole.log(JSON.stringify(require('fs').readFileSync(0, 'utf8')))\n#+end_src\n",
272316 "#+begin_src js :results output\nconsole.log('top'); return; console.log('not reached')\n#+end_src\n",
317 "#+begin_src js :results output\nconst s = require('fs').fstatSync(0)\nconsole.log(s.isFile(), s.isFIFO(), process.stdin.constructor.name)\n#+end_src\n",
273318 ]
274319
275320 /// The results Emacs inserts. `org-babel-temporary-directory` is set as interactive Emacs
docs/manual/guide/11-code-blocks.org +3 −3
@@ -82,7 +82,7 @@ The block's text is remembered when the run starts. If you edit the block while
8282
8383** Languages that run
8484
85On the Mac, orgstar starts each interpreter through =/usr/bin/env=. Because an app opened from the Dock does not see your shell's =PATH=, orgstar adds =/opt/homebrew/bin=, =/usr/local/bin=, =/Library/TeX/texbin=, =/usr/bin= and =/bin= to the end of it.
85On the Mac, orgstar starts each interpreter outside a =:session= through =/bin/sh=, as Org does, with standard input read from a file. Because an app opened from the Dock does not see your shell's =PATH=, orgstar adds =/opt/homebrew/bin=, =/usr/local/bin=, =/Library/TeX/texbin=, =/usr/bin= and =/bin= to the end of it.
8686
8787| Language | Program run |
8888|------------------------------------------------------------------+-----------------------------------------------------|
@@ -97,7 +97,7 @@ On the Mac, orgstar starts each interpreter through =/usr/bin/env=. Because an a
9797| =dot=, =plantuml=, =mermaid= | =dot=, =plantuml=, =mmdc=; see Graphics below |
9898| =C=, =C++=, =cpp=, =D=, =java=, =fortran=, =clojure= | A compiler, or =bb= or =clojure=; see Compiled languages below |
9999
100For =js=, =javascript= and =R=, =:cmd= names a different program. A program given with options, such as =:cmd "node --no-warnings"=, runs through =/bin/sh=, as Org runs it. =awk= takes =:cmd-line= arguments after its program, and =:in-file= as the file it reads.
100For =js=, =javascript= and =R=, =:cmd= names a different program. Since it runs through =/bin/sh=, a program in =:cmd=, =:python= or =:ruby= can be given with options, such as =:cmd "node --no-warnings"= or =:python "python3 -X utf8"=, or with =~= or a variable, such as =:cmd "~/bin/node"=. =awk= takes =:cmd-line= arguments after its program, and =:in-file= as the file it reads.
101101
102102Any other language is refused with "No way to run /language/ blocks yet."
103103
@@ -107,7 +107,7 @@ The [[file:../install.org][Mac App Store version]] starts no programs, so only E
107107
108108** JavaScript in JavaScriptCore
109109
110In the Mac App Store version and on iOS, =js= and =javascript= blocks run in JavaScriptCore, the JavaScript engine built into macOS and iOS. The download version uses it when =node=, or the program in =:cmd=, isn't installed; a =:cmd= with options, such as =node --no-warnings=, never runs in JavaScriptCore. A block runs as Emacs runs it, with =node= reading it from a file as a CommonJS module, where =this= is =module.exports= and top-level =var= declarations stay in the block. Its output and result are what node gives:
110In the Mac App Store version and on iOS, =js= and =javascript= blocks run in JavaScriptCore, the JavaScript engine built into macOS and iOS. The download version uses it when =node=, or the program in =:cmd= after =/bin/sh= expands it, isn't installed; a =:cmd= with options, such as =node --no-warnings=, never runs in JavaScriptCore. A block runs as Emacs runs it, with =node= reading it from a file as a CommonJS module, where =this= is =module.exports= and top-level =var= declarations stay in the block. Its output and result are what node gives:
111111
112112- =console.log=, =console.info= and =console.debug= write to the output, =console.warn= and =console.error= to the error output, and =console.dir= prints with =util.inspect=. =process.stdout.write= and =process.stderr.write= write text.
113113- =require('util')= has =inspect=, =format= and =formatWithOptions=, which print values as Node 26 prints them. =require('process')= has =stdout= and =stderr=.