ob-shell.el 11 KB

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