ob-shell.el 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. ;;; ob-shell.el --- Babel Functions for Shell Evaluation -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2020 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-return-value-is-exit-status nil
  61. "Should we consider the shell exit status as the return value?
  62. When this is set to nil (the default), consider that the return
  63. value of a shell source block is the output of the commands.
  64. Otherwise, consider the return value to be the exit status of the
  65. last command of the block."
  66. :group 'org-babel
  67. :type 'boolean
  68. :package-version '(Org . "9.4"))
  69. (defun org-babel-execute:shell (body params)
  70. "Execute a block of Shell commands with Babel.
  71. This function is called by `org-babel-execute-src-block'."
  72. (let* ((session (org-babel-sh-initiate-session
  73. (cdr (assq :session params))))
  74. (stdin (let ((stdin (cdr (assq :stdin params))))
  75. (when stdin (org-babel-sh-var-to-string
  76. (org-babel-ref-resolve stdin)))))
  77. (value-is-exit-status (or (cdr (assq :value-is-exit-status params))
  78. org-babel-shell-return-value-is-exit-status))
  79. (cmdline (cdr (assq :cmdline params)))
  80. (full-body (concat
  81. (org-babel-expand-body:generic
  82. body params (org-babel-variable-assignments:shell params))
  83. (when value-is-exit-status "\necho $?"))))
  84. (org-babel-reassemble-table
  85. (org-babel-sh-evaluate session full-body params stdin cmdline)
  86. (org-babel-pick-name
  87. (cdr (assq :colname-names params)) (cdr (assq :colnames params)))
  88. (org-babel-pick-name
  89. (cdr (assq :rowname-names params)) (cdr (assq :rownames params))))))
  90. (defun org-babel-prep-session:shell (session params)
  91. "Prepare SESSION according to the header arguments specified in PARAMS."
  92. (let* ((session (org-babel-sh-initiate-session session))
  93. (var-lines (org-babel-variable-assignments:shell params)))
  94. (org-babel-comint-in-buffer session
  95. (mapc (lambda (var)
  96. (insert var) (comint-send-input nil t)
  97. (org-babel-comint-wait-for-output session))
  98. var-lines))
  99. session))
  100. (defun org-babel-load-session:shell (session body params)
  101. "Load BODY into SESSION."
  102. (save-window-excursion
  103. (let ((buffer (org-babel-prep-session:shell session params)))
  104. (with-current-buffer buffer
  105. (goto-char (process-mark (get-buffer-process (current-buffer))))
  106. (insert (org-babel-chomp body)))
  107. buffer)))
  108. ;;; Helper functions
  109. (defun org-babel--variable-assignments:sh-generic
  110. (varname values &optional sep hline)
  111. "Return a list of statements declaring the values as a generic variable."
  112. (format "%s=%s" varname (org-babel-sh-var-to-sh values sep hline)))
  113. (defun org-babel--variable-assignments:bash_array
  114. (varname values &optional sep hline)
  115. "Return a list of statements declaring the values as a bash array."
  116. (format "unset %s\ndeclare -a %s=( %s )"
  117. varname varname
  118. (mapconcat
  119. (lambda (value) (org-babel-sh-var-to-sh value sep hline))
  120. values
  121. " ")))
  122. (defun org-babel--variable-assignments:bash_assoc
  123. (varname values &optional sep hline)
  124. "Return a list of statements declaring the values as bash associative array."
  125. (format "unset %s\ndeclare -A %s\n%s"
  126. varname varname
  127. (mapconcat
  128. (lambda (items)
  129. (format "%s[%s]=%s"
  130. varname
  131. (org-babel-sh-var-to-sh (car items) sep hline)
  132. (org-babel-sh-var-to-sh (cdr items) sep hline)))
  133. values
  134. "\n")))
  135. (defun org-babel--variable-assignments:bash (varname values &optional sep hline)
  136. "Represent the parameters as useful Bash shell variables."
  137. (pcase values
  138. (`((,_ ,_ . ,_) . ,_) ;two-dimensional array
  139. (org-babel--variable-assignments:bash_assoc varname values sep hline))
  140. (`(,_ . ,_) ;simple list
  141. (org-babel--variable-assignments:bash_array varname values sep hline))
  142. (_ ;scalar value
  143. (org-babel--variable-assignments:sh-generic varname values sep hline))))
  144. (defun org-babel-variable-assignments:shell (params)
  145. "Return list of shell statements assigning the block's variables."
  146. (let ((sep (cdr (assq :separator params)))
  147. (hline (when (string= "yes" (cdr (assq :hlines params)))
  148. (or (cdr (assq :hline-string params))
  149. "hline"))))
  150. (mapcar
  151. (lambda (pair)
  152. (if (string-suffix-p "bash" shell-file-name)
  153. (org-babel--variable-assignments:bash
  154. (car pair) (cdr pair) sep hline)
  155. (org-babel--variable-assignments:sh-generic
  156. (car pair) (cdr pair) sep hline)))
  157. (org-babel--get-vars params))))
  158. (defun org-babel-sh-var-to-sh (var &optional sep hline)
  159. "Convert an elisp value to a shell variable.
  160. Convert an elisp var into a string of shell commands specifying a
  161. var of the same value."
  162. (concat "'" (replace-regexp-in-string
  163. "'" "'\"'\"'"
  164. (org-babel-sh-var-to-string var sep hline))
  165. "'"))
  166. (defun org-babel-sh-var-to-string (var &optional sep hline)
  167. "Convert an elisp value to a string."
  168. (let ((echo-var (lambda (v) (if (stringp v) v (format "%S" v)))))
  169. (cond
  170. ((and (listp var) (or (listp (car var)) (eq (car var) 'hline)))
  171. (orgtbl-to-generic var (list :sep (or sep "\t") :fmt echo-var
  172. :hline hline)))
  173. ((listp var)
  174. (mapconcat echo-var var "\n"))
  175. (t (funcall echo-var var)))))
  176. (defun org-babel-sh-initiate-session (&optional session _params)
  177. "Initiate a session named SESSION according to PARAMS."
  178. (when (and session (not (string= session "none")))
  179. (save-window-excursion
  180. (or (org-babel-comint-buffer-livep session)
  181. (progn
  182. (shell session)
  183. ;; Needed for Emacs 23 since the marker is initially
  184. ;; undefined and the filter functions try to use it without
  185. ;; checking.
  186. (set-marker comint-last-output-start (point))
  187. (get-buffer (current-buffer)))))))
  188. (defvar org-babel-sh-eoe-indicator "echo 'org_babel_sh_eoe'"
  189. "String to indicate that evaluation has completed.")
  190. (defvar org-babel-sh-eoe-output "org_babel_sh_eoe"
  191. "String to indicate that evaluation has completed.")
  192. (defun org-babel-sh-evaluate (session body &optional params stdin cmdline)
  193. "Pass BODY to the Shell process in BUFFER.
  194. If RESULT-TYPE equals `output' then return a list of the outputs
  195. of the statements in BODY, if RESULT-TYPE equals `value' then
  196. return the value of the last statement in BODY."
  197. (let* ((shebang (cdr (assq :shebang params)))
  198. (value-is-exit-status (or (cdr (assq :value-is-exit-status params))
  199. org-babel-shell-return-value-is-exit-status))
  200. (results
  201. (cond
  202. ((or stdin cmdline) ; external shell script w/STDIN
  203. (let ((script-file (org-babel-temp-file "sh-script-"))
  204. (stdin-file (org-babel-temp-file "sh-stdin-"))
  205. (padline (not (string= "no" (cdr (assq :padline params))))))
  206. (with-temp-file script-file
  207. (when shebang (insert shebang "\n"))
  208. (when padline (insert "\n"))
  209. (insert body))
  210. (set-file-modes script-file #o755)
  211. (with-temp-file stdin-file (insert (or stdin "")))
  212. (with-temp-buffer
  213. (call-process-shell-command
  214. (concat (if shebang script-file
  215. (format "%s %s" shell-file-name script-file))
  216. (and cmdline (concat " " cmdline)))
  217. stdin-file
  218. (current-buffer))
  219. (buffer-string))))
  220. (session ; session evaluation
  221. (mapconcat
  222. #'org-babel-sh-strip-weird-long-prompt
  223. (mapcar
  224. #'org-trim
  225. (butlast
  226. (org-babel-comint-with-output
  227. (session org-babel-sh-eoe-output t body)
  228. (dolist (line (append (split-string (org-trim body) "\n")
  229. (list org-babel-sh-eoe-indicator)))
  230. (insert line)
  231. (comint-send-input nil t)
  232. (while (save-excursion
  233. (goto-char comint-last-input-end)
  234. (not (re-search-forward
  235. comint-prompt-regexp nil t)))
  236. (accept-process-output
  237. (get-buffer-process (current-buffer))))))
  238. 2))
  239. "\n"))
  240. ;; External shell script, with or without a predefined
  241. ;; shebang.
  242. ((org-string-nw-p shebang)
  243. (let ((script-file (org-babel-temp-file "sh-script-"))
  244. (padline (not (equal "no" (cdr (assq :padline params))))))
  245. (with-temp-file script-file
  246. (insert shebang "\n")
  247. (when padline (insert "\n"))
  248. (insert body))
  249. (set-file-modes script-file #o755)
  250. (org-babel-eval script-file "")))
  251. (t (org-babel-eval shell-file-name (org-trim body))))))
  252. (when value-is-exit-status
  253. (setq results (car (reverse (split-string results "\n" t)))))
  254. (when results
  255. (let ((result-params (cdr (assq :result-params params))))
  256. (org-babel-result-cond result-params
  257. results
  258. (let ((tmp-file (org-babel-temp-file "sh-")))
  259. (with-temp-file tmp-file (insert results))
  260. (org-babel-import-elisp-from-file tmp-file)))))))
  261. (defun org-babel-sh-strip-weird-long-prompt (string)
  262. "Remove prompt cruft from a string of shell output."
  263. (while (string-match "^% +[\r\n$]+ *" string)
  264. (setq string (substring string (match-end 0))))
  265. string)
  266. (provide 'ob-shell)
  267. ;;; ob-shell.el ends here