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 {
24 return paths.contains { FileManager.default.isExecutableFile(atPath: $0) } 24 return paths.contains { FileManager.default.isExecutableFile(atPath: $0) }
25 } 25 }
26 26
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
27 public static func run(_ job: BabelJob, fileDirectory: URL, timeout: Duration = .seconds(300)) async throws -> BabelOutput { 43 public static func run(_ job: BabelJob, fileDirectory: URL, timeout: Duration = .seconds(300)) async throws -> BabelOutput {
28 for programs in job.programs where !programs.contains(where: installed) { 44 for programs in job.programs where !programs.contains(where: installed) {
29 let names = programs.count == 1 ? programs[0] : "Neither " + programs.joined(separator: " nor ") 45 let names = programs.count == 1 ? programs[0] : "Neither " + programs.joined(separator: " nor ")
@@ -42,7 +58,6 @@ public enum BabelRunner {
42 let process = Process() 58 let process = Process()
43 process.executableURL = URL(fileURLWithPath: "/usr/bin/env") 59 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
44 process.environment = environment 60 process.environment = environment
45 let stdin = Pipe()
46 switch job.runner { 61 switch job.runner {
47 case .process(let executable, var arguments): 62 case .process(let executable, var arguments):
48 if let script = job.script { 63 if let script = job.script {
@@ -51,10 +66,8 @@ public enum BabelRunner {
51 try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.path) 66 try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.path)
52 arguments = arguments.map { $0.replacingOccurrences(of: Babel.scriptFileToken, with: file.path) } 67 arguments = arguments.map { $0.replacingOccurrences(of: Babel.scriptFileToken, with: file.path) }
53 } 68 }
54 // A command with arguments, such as `:cmd "node --no-warnings"`, runs in the shell as 69 // In the shell, as Org runs it, so `:cmd "node --no-warnings"` or `~/bin/node` works.
55 // Org runs it. 70 process.arguments = ["/bin/sh", "-c", executable + " \"$@\"", "sh"] + arguments
56 process.arguments = executable.contains(where: \.isWhitespace)
57 ? ["/bin/sh", "-c", executable + " \"$@\"", "sh"] + arguments : [executable] + arguments
58 case .emacs: 71 case .emacs:
59 guard let emacs = EmacsRunner.executable() else { throw Failure(description: "Emacs isn't installed, so Emacs Lisp blocks can't run.") } 72 guard let emacs = EmacsRunner.executable() else { throw Failure(description: "Emacs isn't installed, so Emacs Lisp blocks can't run.") }
60 let script = folder.appendingPathComponent("babel.el") 73 let script = folder.appendingPathComponent("babel.el")
@@ -74,7 +87,10 @@ public enum BabelRunner {
74 let stderr = folder.appendingPathComponent("stderr") 87 let stderr = folder.appendingPathComponent("stderr")
75 FileManager.default.createFile(atPath: stderr.path, contents: nil) 88 FileManager.default.createFile(atPath: stderr.path, contents: nil)
76 let err = try FileHandle(forWritingTo: stderr) 89 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)
78 process.standardOutput = out 94 process.standardOutput = out
79 process.standardError = err 95 process.standardError = err
80 do { 96 do {
@@ -82,17 +98,6 @@ public enum BabelRunner {
82 } catch { 98 } catch {
83 throw Failure(description: "Can't start \(process.arguments?.first ?? "the interpreter"): \(error.localizedDescription)") 99 throw Failure(description: "Can't start \(process.arguments?.first ?? "the interpreter"): \(error.localizedDescription)")
84 } 100 }
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 }
96 let deadline = ContinuousClock.now + timeout 101 let deadline = ContinuousClock.now + timeout
97 while process.isRunning { 102 while process.isRunning {
98 if ContinuousClock.now > deadline { 103 if ContinuousClock.now > deadline {
Sources/OrgPrograms/Programs.swift +4 −1
@@ -16,7 +16,10 @@ public struct Programs: ProgramRunning {
16 // js in JavaScriptCore when node (or `:cmd`) isn't installed. A `:cmd` with arguments runs 16 // js in JavaScriptCore when node (or `:cmd`) isn't installed. A `:cmd` with arguments runs
17 // as written, since JavaScriptCore can't take node's options. 17 // as written, since JavaScriptCore can't take node's options.
18 switch job.runner { 18 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, _):
20 if !executable.contains(where: \.isWhitespace), !BabelRunner.installed(executable), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output } 23 if !executable.contains(where: \.isWhitespace), !BabelRunner.installed(executable), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output }
21 case .emacs: 24 case .emacs:
22 // Emacs Lisp in `Elisp` when Emacs isn't installed. 25 // Emacs Lisp in `Elisp` when Emacs isn't installed.
Tests/OrgProgramsTests/ProgramsTests.swift +45
@@ -254,6 +254,50 @@ struct JavaScriptFallbackTests {
254 func usesNodeWhenInstalled() async throws { 254 func usesNodeWhenInstalled() async throws {
255 #expect(try await run("#+begin_src js :results output\nconsole.log(typeof require('fs').readFileSync)\n#+end_src\n").stdout == "function\n") 255 #expect(try await run("#+begin_src js :results output\nconsole.log(typeof require('fs').readFileSync)\n#+end_src\n").stdout == "function\n")
256 } 256 }
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 }
257} 301}
258 302
259/// js blocks without a session run as `node FILE`, as `org-babel-execute:js` runs them. 303/// js blocks without a session run as `node FILE`, as `org-babel-execute:js` runs them.
@@ -270,6 +314,7 @@ struct NodeFileTests {
270 "#+begin_src js :cmd \"node --no-warnings\" :results output\nconsole.log(process.argv.length, process.execArgv.join(' '))\n#+end_src\n", 314 "#+begin_src js :cmd \"node --no-warnings\" :results output\nconsole.log(process.argv.length, process.execArgv.join(' '))\n#+end_src\n",
271 "#+begin_src js :results output\nconsole.log(JSON.stringify(require('fs').readFileSync(0, 'utf8')))\n#+end_src\n", 315 "#+begin_src js :results output\nconsole.log(JSON.stringify(require('fs').readFileSync(0, 'utf8')))\n#+end_src\n",
272 "#+begin_src js :results output\nconsole.log('top'); return; console.log('not reached')\n#+end_src\n", 316 "#+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",
273 ] 318 ]
274 319
275 /// The results Emacs inserts. `org-babel-temporary-directory` is set as interactive Emacs 320 /// 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
82 82
83** Languages that run 83** Languages that run
84 84
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.
86 86
87| Language | Program run | 87| Language | Program run |
88|------------------------------------------------------------------+-----------------------------------------------------| 88|------------------------------------------------------------------+-----------------------------------------------------|
@@ -97,7 +97,7 @@ On the Mac, orgstar starts each interpreter through =/usr/bin/env=. Because an a
97| =dot=, =plantuml=, =mermaid= | =dot=, =plantuml=, =mmdc=; see Graphics below | 97| =dot=, =plantuml=, =mermaid= | =dot=, =plantuml=, =mmdc=; see Graphics below |
98| =C=, =C++=, =cpp=, =D=, =java=, =fortran=, =clojure= | A compiler, or =bb= or =clojure=; see Compiled languages below | 98| =C=, =C++=, =cpp=, =D=, =java=, =fortran=, =clojure= | A compiler, or =bb= or =clojure=; see Compiled languages below |
99 99
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.
101 101
102Any other language is refused with "No way to run /language/ blocks yet." 102Any other language is refused with "No way to run /language/ blocks yet."
103 103
@@ -107,7 +107,7 @@ The [[file:../install.org][Mac App Store version]] starts no programs, so only E
107 107
108** JavaScript in JavaScriptCore 108** JavaScript in JavaScriptCore
109 109
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:
111 111
112- =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. 112- =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.
113- =require('util')= has =inspect=, =format= and =formatWithOptions=, which print values as Node 26 prints them. =require('process')= has =stdout= and =stderr=. 113- =require('util')= has =inspect=, =format= and =formatWithOptions=, which print values as Node 26 prints them. =require('process')= has =stdout= and =stderr=.