ob-shell.el 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. ;;; ob-shell.el --- Babel Functions for Shell Evaluation -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2022 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: https://orgmode.org
  6. ;; This file is part of GNU Emacs.
  7. ;; GNU Emacs is free software: you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation, either version 3 of the License, or
  10. ;; (at your option) any later version.
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;; GNU General Public License for more details.
  15. ;; You should have received a copy of the GNU General Public License
  16. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;; Org-Babel support for evaluating shell source code.
  19. ;;; Code:
  20. (require 'ob)
  21. (require 'org-macs)
  22. (require 'shell)
  23. (require 'cl-lib)
  24. (declare-function org-babel-comint-in-buffer "ob-comint" (buffer &rest body)
  25. t)
  26. (declare-function org-babel-comint-wait-for-output "ob-comint" (buffer))
  27. (declare-function org-babel-comint-buffer-livep "ob-comint" (buffer))
  28. (declare-function org-babel-comint-with-output "ob-comint" (meta &rest body)
  29. t)
  30. (declare-function orgtbl-to-generic "org-table" (table params))
  31. (defvar org-babel-default-header-args:shell '())
  32. (defvar org-babel-shell-names)
  33. (defun org-babel-shell-initialize ()
  34. "Define execution functions associated to shell names.
  35. This function has to be called whenever `org-babel-shell-names'
  36. is modified outside the Customize interface."
  37. (interactive)
  38. (dolist (name org-babel-shell-names)
  39. (eval `(defun ,(intern (concat "org-babel-execute:" name))
  40. (body params)
  41. ,(format "Execute a block of %s commands with Babel." name)
  42. (let ((shell-file-name ,name))
  43. (org-babel-execute:shell body params))))
  44. (eval `(defalias ',(intern (concat "org-babel-variable-assignments:" name))
  45. 'org-babel-variable-assignments:shell
  46. ,(format "Return list of %s statements assigning to the block's \
  47. variables."
  48. name)))
  49. (eval `(defvar ,(intern (concat "org-babel-default-header-args:" name)) '()))))
  50. (defcustom org-babel-shell-names
  51. '("sh" "bash" "zsh" "fish" "csh" "ash" "dash" "ksh" "mksh" "posh")
  52. "List of names of shell supported by babel shell code blocks.
  53. Call `org-babel-shell-initialize' when modifying this variable
  54. outside the Customize interface."
  55. :group 'org-babel
  56. :type '(repeat (string :tag "Shell name: "))
  57. :set (lambda (symbol value)
  58. (set-default symbol value)
  59. (org-babel-shell-initialize)))
  60. (defcustom org-babel-shell-results-defaults-to-output t
  61. "Let shell execution defaults to \":results output\".
  62. When set to t, use \":results output\" when no :results setting
  63. is set. This is especially useful for inline source blocks.
  64. When set to nil, stick to the convention of using :results value
  65. as the default setting when no :results is set, the \"value\" of
  66. a shell execution being its exit code."
  67. :group 'org-babel
  68. :type 'boolean
  69. :package-version '(Org . "9.4"))
  70. (defun org-babel-execute:shell (body params)
  71. "Execute a block of Shell commands with Babel.
  72. This function is called by `org-babel-execute-src-block'."
  73. (let* ((session (org-babel-sh-initiate-session
  74. (cdr (assq :session params))))
  75. (stdin (let ((stdin (cdr (assq :stdin params))))
  76. (when stdin (org-babel-sh-var-to-string
  77. (org-babel-ref-resolve stdin)))))
  78. (results-params (cdr (assq :result-params params)))
  79. (value-is-exit-status
  80. (or (and
  81. (equal '("replace") results-params)
  82. (not org-babel-shell-results-defaults-to-output))
  83. (member "value" results-params)))
  84. (cmdline (cdr (assq :cmdline params)))
  85. (full-body (concat
  86. (org-babel-expand-body:generic
  87. body params (org-babel-variable-assignments:shell params))
  88. (when value-is-exit-status "\necho $?"))))
  89. (org-babel-reassemble-table
  90. (org-babel-sh-evaluate session full-body params stdin cmdline)
  91. (org-babel-pick-name
  92. (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
  93. (org-babel-pick-name
  94. (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))
  95. (defun org-babel-prep-session:shell (session params)
  96. "Prepare SESSION according to the header arguments specified in PARAMS."
  97. (let* ((session (org-babel-sh-initiate-session session))
  98. (var-lines (org-babel-variable-assignments:shell params)))
  99. (org-babel-comint-in-buffer session
  100. (mapc (lambda (var)
  101. (insert var) (comint-send-input nil t)
  102. (org-babel-comint-wait-for-output session))
  103. var-lines))
  104. session))
  105. (defun org-babel-load-session:shell (session body params)
  106. "Load BODY into SESSION."
  107. (save-window-excursion
  108. (let ((buffer (org-babel-prep-session:shell session params)))
  109. (with-current-buffer buffer
  110. (goto-char (process-mark (get-buffer-process (current-buffer))))
  111. (insert (org-babel-chomp body)))
  112. buffer)))
  113. ;;; Helper functions
  114. (defun org-babel--variable-assignments:sh-generic
  115. (varname values &optional sep hline)
  116. "Return a list of statements declaring the values as a generic variable."
  117. (format "%s=%s" varname (org-babel-sh-var-to-sh values sep hline)))
  118. (defun org-babel--variable-assignments:bash_array
  119. (varname values &optional sep hline)
  120. "Return a list of statements declaring the values as a bash array."
  121. (format "unset %s\ndeclare -a %s=( %s )"
  122. varname varname
  123. (mapconcat
  124. (lambda (value) (org-babel-sh-var-to-sh value sep hline))
  125. values
  126. " ")))
  127. (defun org-babel--variable-assignments:bash_assoc
  128. (varname values &optional sep hline)
  129. "Return a list of statements declaring the values as bash associative array."
  130. (format "unset %s\ndeclare -A %s\n%s"
  131. varname varname
  132. (mapconcat
  133. (lambda (items)
  134. (format "%s[%s]=%s"
  135. varname
  136. (org-babel-sh-var-to-sh (car items) sep hline)
  137. (org-babel-sh-var-to-sh (cdr items) sep hline)))
  138. values
  139. "\n")))
  140. (defun org-babel--variable-assignments:bash (varname values &optional sep hline)
  141. "Represent the parameters as useful Bash shell variables."
  142. (pcase values
  143. (`((,_ ,_ . ,_) . ,_) ;two-dimensional array
  144. (org-babel--variable-assignments:bash_assoc varname values sep hline))
  145. (`(,_ . ,_) ;simple list
  146. (org-babel--variable-assignments:bash_array varname values sep hline))
  147. (_ ;scalar value
  148. (org-babel--variable-assignments:sh-generic varname values sep hline))))
  149. (defun org-babel-variable-assignments:shell (params)
  150. "Return list of shell statements assigning the block's variables."
  151. (let ((sep (cdr (assq :separator params)))
  152. (hline (when (string= "yes" (cdr (assq :hlines params)))
  153. (or (cdr (assq :hline-string params))
  154. "hline"))))
  155. (mapcar
  156. (lambda (pair)
  157. (if (string-suffix-p "bash" shell-file-name)
  158. (org-babel--variable-assignments:bash
  159. (car pair) (cdr pair) sep hline)
  160. (org-babel--variable-assignments:sh-generic
  161. (car pair) (cdr pair) sep hline)))
  162. (org-babel--get-vars params))))
  163. (defun org-babel-sh-var-to-sh (var &optional sep hline)
  164. "Convert an elisp value to a shell variable.
  165. Convert an elisp var into a string of shell commands specifying a
  166. var of the same value."
  167. (concat "'" (replace-regexp-in-string
  168. "'" "'\"'\"'"
  169. (org-babel-sh-var-to-string var sep hline))
  170. "'"))
  171. (defun org-babel-sh-var-to-string (var &optional sep hline)
  172. "Convert an elisp value to a string."
  173. (let ((echo-var (lambda (v) (if (stringp v) v (format "%S" v)))))
  174. (cond
  175. ((and (listp var) (or (listp (car var)) (eq (car var) 'hline)))
  176. (orgtbl-to-generic var (list :sep (or sep "\t") :fmt echo-var
  177. :hline hline)))
  178. ((listp var)
  179. (mapconcat echo-var var "\n"))
  180. (t (funcall echo-var var)))))
  181. (defun org-babel-sh-initiate-session (&optional session _params)
  182. "Initiate a session named SESSION according to PARAMS."
  183. (when (and session (not (string= session "none")))
  184. (save-window-excursion
  185. (or (org-babel-comint-buffer-livep session)
  186. (progn
  187. (shell session)
  188. ;; Needed for Emacs 23 since the marker is initially
  189. ;; undefined and the filter functions try to use it without
  190. ;; checking.
  191. (set-marker comint-last-output-start (point))
  192. (get-buffer (current-buffer)))))))
  193. (defvar org-babel-sh-eoe-indicator "echo 'org_babel_sh_eoe'"
  194. "String to indicate that evaluation has completed.")
  195. (defvar org-babel-sh-eoe-output "org_babel_sh_eoe"
  196. "String to indicate that evaluation has completed.")
  197. (defun org-babel-sh-evaluate (session body &optional params stdin cmdline)
  198. "Pass BODY to the Shell process in BUFFER.
  199. If RESULT-TYPE equals `output' then return a list of the outputs
  200. of the statements in BODY, if RESULT-TYPE equals `value' then
  201. return the value of the last statement in BODY."
  202. (let* ((shebang (cdr (assq :shebang params)))
  203. (results-params (cdr (assq :result-params params)))
  204. (value-is-exit-status
  205. (or (and
  206. (equal '("replace") results-params)
  207. (not org-babel-shell-results-defaults-to-output))
  208. (member "value" results-params)))
  209. (results
  210. (cond
  211. ((or stdin cmdline) ; external shell script w/STDIN
  212. (let ((script-file (org-babel-temp-file "sh-script-"))
  213. (stdin-file (org-babel-temp-file "sh-stdin-"))
  214. (padline (not (string= "no" (cdr (assq :padline params))))))
  215. (with-temp-file script-file
  216. (when shebang (insert shebang "\n"))
  217. (when padline (insert "\n"))
  218. (insert body))
  219. (set-file-modes script-file #o755)
  220. (with-temp-file stdin-file (insert (or stdin "")))
  221. (with-temp-buffer
  222. (call-process-shell-command
  223. (concat (if shebang script-file
  224. (format "%s %s" shell-file-name script-file))
  225. (and cmdline (concat " " cmdline)))
  226. stdin-file
  227. (current-buffer))
  228. (buffer-string))))
  229. (session ; session evaluation
  230. (mapconcat
  231. #'org-babel-sh-strip-weird-long-prompt
  232. (mapcar
  233. #'org-trim
  234. (butlast
  235. (org-babel-comint-with-output
  236. (session org-babel-sh-eoe-output t body)
  237. (dolist (line (append (split-string (org-trim body) "\n")
  238. (list org-babel-sh-eoe-indicator)))
  239. (insert line)
  240. (comint-send-input nil t)
  241. (while (save-excursion
  242. (goto-char comint-last-input-end)
  243. (not (re-search-forward
  244. comint-prompt-regexp nil t)))
  245. (accept-process-output
  246. (get-buffer-process (current-buffer))))))
  247. 2))
  248. "\n"))
  249. ;; External shell script, with or without a predefined
  250. ;; shebang.
  251. ((org-string-nw-p shebang)
  252. (let ((script-file (org-babel-temp-file "sh-script-"))
  253. (padline (not (equal "no" (cdr (assq :padline params))))))
  254. (with-temp-file script-file
  255. (insert shebang "\n")
  256. (when padline (insert "\n"))
  257. (insert body))
  258. (set-file-modes script-file #o755)
  259. (org-babel-eval script-file "")))
  260. (t (org-babel-eval shell-file-name (org-trim body))))))
  261. (when value-is-exit-status
  262. (setq results (car (reverse (split-string results "\n" t)))))
  263. (when results
  264. (let ((result-params (cdr (assq :result-params params))))
  265. (org-babel-result-cond result-params
  266. results
  267. (let ((tmp-file (org-babel-temp-file "sh-")))
  268. (with-temp-file tmp-file (insert results))
  269. (org-babel-import-elisp-from-file tmp-file)))))))
  270. (defun org-babel-sh-strip-weird-long-prompt (string)
  271. "Remove prompt cruft from a string of shell output."
  272. (while (string-match "^% +[\r\n$]+ *" string)
  273. (setq string (substring string (match-end 0))))
  274. string)
  275. (provide 'ob-shell)
  276. ;;; ob-shell.el ends here