config

Personal configuration.
git clone git://code.dwrz.net/config
Log | Files | Refs

magit-process.el (54416B)


      1 ;;; magit-process.el --- Process functionality  -*- lexical-binding:t -*-
      2 
      3 ;; Copyright (C) 2008-2024 The Magit Project Contributors
      4 
      5 ;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev>
      6 ;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev>
      7 
      8 ;; SPDX-License-Identifier: GPL-3.0-or-later
      9 
     10 ;; Magit is free software: you can redistribute it and/or modify it
     11 ;; under the terms of the GNU General Public License as published by
     12 ;; the Free Software Foundation, either version 3 of the License, or
     13 ;; (at your option) any later version.
     14 ;;
     15 ;; Magit is distributed in the hope that it will be useful, but WITHOUT
     16 ;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
     17 ;; or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
     18 ;; License for more details.
     19 ;;
     20 ;; You should have received a copy of the GNU General Public License
     21 ;; along with Magit.  If not, see <https://www.gnu.org/licenses/>.
     22 
     23 ;;; Commentary:
     24 
     25 ;; This library implements the tools used to run Git for side-effects.
     26 
     27 ;; Note that the functions used to run Git and then consume its
     28 ;; output, are defined in `magit-git.el'.  There's a bit of overlap
     29 ;; though.
     30 
     31 ;;; Code:
     32 
     33 (require 'magit-base)
     34 (require 'magit-git)
     35 (require 'magit-mode)
     36 
     37 (require 'ansi-color)
     38 (require 'auth-source)
     39 (require 'with-editor)
     40 
     41 (defvar y-or-n-p-map)
     42 
     43 ;;; Options
     44 
     45 (defcustom magit-process-connection-type (not (eq system-type 'cygwin))
     46   "Connection type used for the Git process.
     47 
     48 If nil, use pipes: this is usually more efficient, and works on Cygwin.
     49 If t, use ptys: this enables Magit to prompt for passphrases when needed."
     50   :group 'magit-process
     51   :type '(choice (const :tag "pipe" nil)
     52                  (const :tag "pty" t)))
     53 
     54 (defcustom magit-need-cygwin-noglob
     55   (and (eq system-type 'windows-nt)
     56        (with-temp-buffer
     57          (let ((process-environment
     58                 (append magit-git-environment process-environment)))
     59            (condition-case e
     60                (process-file magit-git-executable
     61                              nil (current-buffer) nil
     62                              "-c" "alias.echo=!echo" "echo" "x{0}")
     63              (file-error
     64               (lwarn 'magit-process :warning
     65                      "Could not run Git: %S" e))))
     66          (equal "x0\n" (buffer-string))))
     67   "Whether to use a workaround for Cygwin's globbing behavior.
     68 
     69 If non-nil, add environment variables to `process-environment' to
     70 prevent the git.exe distributed by Cygwin and MSYS2 from
     71 attempting to perform glob expansion when called from a native
     72 Windows build of Emacs.  See #2246."
     73   :package-version '(magit . "2.3.0")
     74   :group 'magit-process
     75   :type '(choice (const :tag "Yes" t)
     76                  (const :tag "No" nil)))
     77 
     78 (defcustom magit-process-popup-time -1
     79   "Popup the process buffer if a command takes longer than this many seconds."
     80   :group 'magit-process
     81   :type '(choice (const :tag "Never" -1)
     82                  (const :tag "Immediately" 0)
     83                  (integer :tag "After this many seconds")))
     84 
     85 (defcustom magit-process-log-max 32
     86   "Maximum number of sections to keep in a process log buffer.
     87 When adding a new section would go beyond the limit set here,
     88 then the older half of the sections are remove.  Sections that
     89 belong to processes that are still running are never removed.
     90 When this is nil, no sections are ever removed."
     91   :package-version '(magit . "2.1.0")
     92   :group 'magit-process
     93   :type '(choice (const :tag "Never remove old sections" nil) integer))
     94 
     95 (defvar magit-process-extreme-logging nil
     96   "Whether `magit-process-file' logs to the *Messages* buffer.
     97 
     98 Only intended for temporary use when you try to figure out how
     99 Magit uses Git behind the scene.  Output that normally goes to
    100 the magit-process buffer continues to go there.  Not all output
    101 goes to either of these two buffers.
    102 
    103 Also see `magit-git-debug'.")
    104 
    105 (defcustom magit-process-error-tooltip-max-lines 20
    106   "The number of lines for `magit-process-error-lines' to return.
    107 
    108 These are displayed in a tooltip for `mode-line-process' errors.
    109 
    110 If `magit-process-error-tooltip-max-lines' is nil, the tooltip
    111 displays the text of `magit-process-error-summary' instead."
    112   :package-version '(magit . "2.12.0")
    113   :group 'magit-process
    114   :type '(choice (const :tag "Use summary line" nil)
    115                  integer))
    116 
    117 (defcustom magit-credential-cache-daemon-socket
    118   (--some (pcase-let ((`(,prog . ,args) (split-string it)))
    119             (if (and prog
    120                      (string-match-p
    121                       "\\`\\(?:\\(?:/.*/\\)?git-credential-\\)?cache\\'" prog))
    122                 (or (cl-loop for (opt val) on args
    123                              if (string= opt "--socket")
    124                              return val)
    125                     (expand-file-name "~/.git-credential-cache/socket"))))
    126           ;; Note: `magit-process-file' is not yet defined when
    127           ;; evaluating this form, so we use `process-lines'.
    128           (ignore-errors
    129             (let ((process-environment
    130                    (append magit-git-environment process-environment)))
    131               (process-lines magit-git-executable
    132                              "config" "--get-all" "credential.helper"))))
    133   "If non-nil, start a credential cache daemon using this socket.
    134 
    135 When using Git's cache credential helper in the normal way, Emacs
    136 sends a SIGHUP to the credential daemon after the git subprocess
    137 has exited, causing the daemon to also quit.  This can be avoided
    138 by starting the `git-credential-cache--daemon' process directly
    139 from Emacs.
    140 
    141 The function `magit-maybe-start-credential-cache-daemon' takes
    142 care of starting the daemon if necessary, using the value of this
    143 option as the socket.  If this option is nil, then it does not
    144 start any daemon.  Likewise if another daemon is already running,
    145 then it starts no new daemon.  This function has to be a member
    146 of the hook variable `magit-credential-hook' for this to work.
    147 If an error occurs while starting the daemon, most likely because
    148 the necessary executable is missing, then the function removes
    149 itself from the hook, to avoid further futile attempts."
    150   :package-version '(magit . "2.3.0")
    151   :group 'magit-process
    152   :type '(choice (file  :tag "Socket")
    153                  (const :tag "Don't start a cache daemon" nil)))
    154 
    155 (defcustom magit-process-yes-or-no-prompt-regexp
    156   (concat " [([]"
    157           "\\([Yy]\\(?:es\\)?\\)"
    158           "[/|]"
    159           "\\([Nn]o?\\)"
    160           ;; OpenSSH v8 prints this.  See #3969.
    161           "\\(?:/\\[fingerprint\\]\\)?"
    162           "[])] ?[?:]? ?$")
    163   "Regexp matching Yes-or-No prompts of Git and its subprocesses."
    164   :package-version '(magit . "2.1.0")
    165   :group 'magit-process
    166   :type 'regexp)
    167 
    168 (defcustom magit-process-password-prompt-regexps
    169   '("^\\(Enter \\)?[Pp]assphrase\\( for \\(RSA \\)?key '.*'\\)?: ?$"
    170     ;; Match-group 99 is used to identify the "user@host" part.
    171     "^\\(Enter \\|([^) ]+) \\)?\
    172 [Pp]assword\\( for '?\\(https?://\\)?\\(?99:[^']*\\)'?\\)?: ?$"
    173     "Please enter the passphrase for the ssh key"
    174     "Please enter the passphrase to unlock the OpenPGP secret key"
    175     "^.*'s password: ?$"
    176     "^Token: $" ; For git-credential-manager-core (#4318).
    177     "^Yubikey for .*: ?$"
    178     "^Enter PIN for .*: ?$")
    179   "List of regexps matching password prompts of Git and its subprocesses.
    180 Also see `magit-process-find-password-functions'."
    181   :package-version '(magit . "3.0.0")
    182   :group 'magit-process
    183   :type '(repeat (regexp)))
    184 
    185 (defcustom magit-process-find-password-functions nil
    186   "List of functions to try in sequence to get a password.
    187 
    188 These functions may be called when git asks for a password, which
    189 is detected using `magit-process-password-prompt-regexps'.  They
    190 are called if and only if matching the prompt resulted in the
    191 value of the 99th submatch to be non-nil.  Therefore users can
    192 control for which prompts these functions should be called by
    193 putting the host name in the 99th submatch, or not.
    194 
    195 If the functions are called, then they are called in the order
    196 given, with the host name as only argument, until one of them
    197 returns non-nil.  If they are not called or none of them returns
    198 non-nil, then the password is read from the user instead."
    199   :package-version '(magit . "2.3.0")
    200   :group 'magit-process
    201   :type 'hook
    202   :options '(magit-process-password-auth-source))
    203 
    204 (defcustom magit-process-username-prompt-regexps
    205   '("^Username for '.*': ?$")
    206   "List of regexps matching username prompts of Git and its subprocesses."
    207   :package-version '(magit . "2.1.0")
    208   :group 'magit-process
    209   :type '(repeat (regexp)))
    210 
    211 (defcustom magit-process-prompt-functions nil
    212   "List of functions used to forward arbitrary questions to the user.
    213 
    214 Magit has dedicated support for forwarding username and password
    215 prompts and Yes-or-No questions asked by Git and its subprocesses
    216 to the user.  This can be customized using other options in the
    217 `magit-process' customization group.
    218 
    219 If you encounter a new question that isn't handled by default,
    220 then those options should be used instead of this hook.
    221 
    222 However subprocesses may also ask questions that differ too much
    223 from what the code related to the above options assume, and this
    224 hook allows users to deal with such questions explicitly.
    225 
    226 Each function is called with the process and the output string
    227 as arguments until one of the functions returns non-nil.  The
    228 function is responsible for asking the user the appropriate
    229 question using, e.g., `read-char-choice' and then forwarding the
    230 answer to the process using `process-send-string'.
    231 
    232 While functions such as `magit-process-yes-or-no-prompt' may not
    233 be sufficient to handle some prompt, it may still be of benefit
    234 to look at the implementations to gain some insights on how to
    235 implement such functions."
    236   :package-version '(magit . "3.0.0")
    237   :group 'magit-process
    238   :type 'hook)
    239 
    240 (defcustom magit-process-ensure-unix-line-ending t
    241   "Whether Magit should ensure a unix coding system when talking to Git."
    242   :package-version '(magit . "2.6.0")
    243   :group 'magit-process
    244   :type 'boolean)
    245 
    246 (defcustom magit-process-display-mode-line-error t
    247   "Whether Magit should retain and highlight process errors in the mode line."
    248   :package-version '(magit . "2.12.0")
    249   :group 'magit-process
    250   :type 'boolean)
    251 
    252 (defcustom magit-process-timestamp-format nil
    253   "Format of timestamp for each process in the process buffer.
    254 If non-nil, pass this to `format-time-string' when creating a
    255 process section in the process buffer, and insert the returned
    256 string in the heading of its section."
    257   :package-version '(magit . "4.0.0")
    258   :group 'magit-process
    259   :type '(choice (const :tag "none" nil) string))
    260 
    261 (defvar tramp-pipe-stty-settings)
    262 (defvar magit-tramp-pipe-stty-settings ""
    263   "Override `tramp-pipe-stty-settings' in `magit-start-process'.
    264 
    265 The default for that Tramp variable is \"-icanon min 1 time 0\",
    266 which causes staging of individual hunks to hang.  Using \"\"
    267 prevents that, but apparently has other issues, which is why it
    268 isn't the default.
    269 
    270 This variable defaults to \"\" and is used to override the Tramp
    271 variable in `magit-start-process'.  This only has an effect when
    272 using Tramp 2.6.2 or greater.  This can also be set to `pty', in
    273 which case a pty is used instead of a pipe.  That also prevents
    274 the hanging, but doesn't work for files with DOS line endings
    275 \(see #20).
    276 
    277 For connections that have `tramp-direct-async-process' enabled,
    278 staging hunks hangs, unless this variable is set to `pty' (see
    279 #5220).
    280 
    281 To fall back to the value of `tramp-pipe-stty-settings', set this
    282 variable to nil.
    283 
    284 Also see https://github.com/magit/magit/issues/4720
    285 and https://debbugs.gnu.org/cgi/bugreport.cgi?bug=62093.")
    286 
    287 (defface magit-process-ok
    288   '((t :inherit magit-section-heading :foreground "green"))
    289   "Face for zero exit-status."
    290   :group 'magit-faces)
    291 
    292 (defface magit-process-ng
    293   '((t :inherit magit-section-heading :foreground "red"))
    294   "Face for non-zero exit-status."
    295   :group 'magit-faces)
    296 
    297 (defface magit-mode-line-process
    298   '((t :inherit mode-line-emphasis))
    299   "Face for `mode-line-process' status when Git is running for side-effects."
    300   :group 'magit-faces)
    301 
    302 (defface magit-mode-line-process-error
    303   '((t :inherit error))
    304   "Face for `mode-line-process' error status.
    305 
    306 Used when `magit-process-display-mode-line-error' is non-nil."
    307   :group 'magit-faces)
    308 
    309 ;;; Process Mode
    310 
    311 (defvar-keymap magit-process-mode-map
    312   :doc "Keymap for `magit-process-mode'."
    313   :parent magit-mode-map
    314   "<remap> <magit-delete-thing>" #'magit-process-kill)
    315 
    316 (define-derived-mode magit-process-mode magit-mode "Magit Process"
    317   "Mode for looking at Git process output."
    318   :interactive nil
    319   :group 'magit-process
    320   (magit-hack-dir-local-variables)
    321   (setq magit--imenu-item-types 'process))
    322 
    323 (defun magit-process-buffer (&optional nodisplay)
    324   "Display the current repository's process buffer.
    325 
    326 If that buffer doesn't exist yet, then create it.
    327 Non-interactively return the buffer and unless
    328 optional NODISPLAY is non-nil also display it."
    329   (interactive)
    330   (let ((topdir (magit-toplevel)))
    331     (unless topdir
    332       (magit--with-safe-default-directory nil
    333         (setq topdir default-directory)
    334         (let (prev)
    335           (while (not (equal topdir prev))
    336             (setq prev topdir)
    337             (setq topdir (file-name-directory (directory-file-name topdir)))))))
    338     (let ((buffer (or (--first (with-current-buffer it
    339                                  (and (eq major-mode 'magit-process-mode)
    340                                       (equal default-directory topdir)))
    341                                (buffer-list))
    342                       (magit-generate-new-buffer 'magit-process-mode
    343                                                  nil topdir))))
    344       (with-current-buffer buffer
    345         (if magit-root-section
    346             (when magit-process-log-max
    347               (magit-process-truncate-log))
    348           (magit-process-mode)
    349           (let ((inhibit-read-only t)
    350                 (magit-insert-section--parent  nil)
    351                 (magit-insert-section--oldroot nil))
    352             (make-local-variable 'text-property-default-nonsticky)
    353             (magit-insert-section (processbuf)
    354               (insert "\n")))))
    355       (unless nodisplay
    356         (magit-display-buffer buffer))
    357       buffer)))
    358 
    359 (defun magit-process-kill ()
    360   "Kill the process at point."
    361   (interactive)
    362   (when-let ((process (magit-section-value-if 'process)))
    363     (unless (eq (process-status process) 'run)
    364       (user-error "Process isn't running"))
    365     (magit-confirm 'kill-process)
    366     (kill-process process)))
    367 
    368 ;;; Synchronous Processes
    369 
    370 (defvar magit-process-raise-error nil)
    371 
    372 (defun magit-git (&rest args)
    373   "Call Git synchronously in a separate process, for side-effects.
    374 
    375 Option `magit-git-executable' specifies the Git executable.
    376 The arguments ARGS specify arguments to Git, they are flattened
    377 before use.
    378 
    379 Process output goes into a new section in the buffer returned by
    380 `magit-process-buffer'.  If Git exits with a non-zero status,
    381 then raise an error."
    382   (let ((magit-process-raise-error t))
    383     (magit-call-git args)))
    384 
    385 (defun magit-run-git (&rest args)
    386   "Call Git synchronously in a separate process, and refresh.
    387 
    388 Function `magit-git-executable' specifies the Git executable and
    389 option `magit-git-global-arguments' specifies constant arguments.
    390 The arguments ARGS specify arguments to Git, they are flattened
    391 before use.
    392 
    393 After Git returns, the current buffer (if it is a Magit buffer)
    394 as well as the current repository's status buffer are refreshed.
    395 
    396 Process output goes into a new section in the buffer returned by
    397 `magit-process-buffer'."
    398   (let ((magit--refresh-cache (list (cons 0 0))))
    399     (prog1 (magit-call-git args)
    400       (when (member (car args) '("init" "clone"))
    401         ;; Creating a new repository invalidates the cache.
    402         (setq magit--refresh-cache nil))
    403       (magit-refresh))))
    404 
    405 (defvar magit-pre-call-git-hook nil)
    406 
    407 (defun magit-call-git (&rest args)
    408   "Call Git synchronously in a separate process.
    409 
    410 Function `magit-git-executable' specifies the Git executable and
    411 option `magit-git-global-arguments' specifies constant arguments.
    412 The arguments ARGS specify arguments to Git, they are flattened
    413 before use.
    414 
    415 Process output goes into a new section in the buffer returned by
    416 `magit-process-buffer'."
    417   (run-hooks 'magit-pre-call-git-hook)
    418   (let ((default-process-coding-system (magit--process-coding-system)))
    419     (apply #'magit-call-process
    420            (magit-git-executable)
    421            (magit-process-git-arguments args))))
    422 
    423 (defun magit-call-process (program &rest args)
    424   "Call PROGRAM synchronously in a separate process.
    425 Process output goes into a new section in the buffer returned by
    426 `magit-process-buffer'."
    427   (pcase-let ((`(,process-buf . ,section)
    428                (magit-process-setup program args)))
    429     (magit-process-finish
    430      (let ((inhibit-read-only t))
    431        (apply #'magit-process-file program nil process-buf nil args))
    432      process-buf (current-buffer) default-directory section)))
    433 
    434 (defun magit-process-git (destination &rest args)
    435   "Call Git synchronously in a separate process, returning its exit code.
    436 DESTINATION specifies how to handle the output, like for
    437 `call-process', except that file handlers are supported.
    438 Enable Cygwin's \"noglob\" option during the call and
    439 ensure unix eol conversion."
    440   (apply #'magit-process-file
    441          (magit-git-executable)
    442          nil destination nil
    443          (magit-process-git-arguments args)))
    444 
    445 (defun magit-process-file (process &optional infile buffer display &rest args)
    446   "Process files synchronously in a separate process.
    447 Identical to `process-file' but temporarily enable Cygwin's
    448 \"noglob\" option during the call and ensure unix eol
    449 conversion."
    450   (when magit-process-extreme-logging
    451     (let ((inhibit-message t))
    452       (message "$ %s" (magit-process--format-arguments process args))))
    453   (let ((process-environment (magit-process-environment))
    454         (default-process-coding-system (magit--process-coding-system)))
    455     (apply #'process-file process infile buffer display args)))
    456 
    457 (defun magit-process-environment ()
    458   ;; The various w32 hacks are only applicable when running on the local
    459   ;; machine.  A local binding of process-environment different from the
    460   ;; top-level value affects the environment used by Tramp.
    461   (let ((local (not (file-remote-p default-directory))))
    462     (append magit-git-environment
    463             (and local
    464                  (cdr (assoc magit-git-executable magit-git-w32-path-hack)))
    465             (and local magit-need-cygwin-noglob
    466                  (mapcar (lambda (var)
    467                            (concat var "=" (if-let ((val (getenv var)))
    468                                                (concat val " noglob")
    469                                              "noglob")))
    470                          '("CYGWIN" "MSYS")))
    471             process-environment)))
    472 
    473 (defvar magit-this-process nil)
    474 
    475 (defun magit-run-git-with-input (&rest args)
    476   "Call Git in a separate process.
    477 ARGS is flattened and then used as arguments to Git.
    478 
    479 The current buffer's content is used as the process's standard
    480 input.  The buffer is assumed to be temporary and thus OK to
    481 modify.
    482 
    483 Function `magit-git-executable' specifies the Git executable and
    484 option `magit-git-global-arguments' specifies constant arguments.
    485 The remaining arguments ARGS specify arguments to Git, they are
    486 flattened before use."
    487   (when (eq system-type 'windows-nt)
    488     ;; On w32, git expects UTF-8 encoded input, ignore any user
    489     ;; configuration telling us otherwise (see #3250).
    490     (encode-coding-region (point-min) (point-max) 'utf-8-unix))
    491   (if (file-remote-p default-directory)
    492       ;; We lack `process-file-region', so fall back to asynch +
    493       ;; waiting in remote case.
    494       (progn
    495         (magit-start-git (current-buffer) args)
    496         (while (and magit-this-process
    497                     (eq (process-status magit-this-process) 'run))
    498           (sleep-for 0.005)))
    499     (run-hooks 'magit-pre-call-git-hook)
    500     (pcase-let* ((process-environment (magit-process-environment))
    501                  (default-process-coding-system (magit--process-coding-system))
    502                  (flat-args (magit-process-git-arguments args))
    503                  (`(,process-buf . ,section)
    504                   (magit-process-setup (magit-git-executable) flat-args))
    505                  (inhibit-read-only t))
    506       (magit-process-finish
    507        (apply #'call-process-region (point-min) (point-max)
    508               (magit-git-executable) nil process-buf nil flat-args)
    509        process-buf nil default-directory section))))
    510 
    511 ;;; Asynchronous Processes
    512 
    513 (defun magit-run-git-async (&rest args)
    514   "Start Git, prepare for refresh, and return the process object.
    515 ARGS is flattened and then used as arguments to Git.
    516 
    517 Display the command line arguments in the echo area.
    518 
    519 After Git returns some buffers are refreshed: the buffer that was
    520 current when this function was called (if it is a Magit buffer
    521 and still alive), as well as the respective Magit status buffer.
    522 
    523 See `magit-start-process' for more information."
    524   (message "Running %s %s" (magit-git-executable)
    525            (let ((m (string-join (flatten-tree args) " ")))
    526              (remove-list-of-text-properties 0 (length m) '(face) m)
    527              m))
    528   (magit-start-git nil args))
    529 
    530 (defun magit-run-git-with-editor (&rest args)
    531   "Export GIT_EDITOR and start Git.
    532 Also prepare for refresh and return the process object.
    533 ARGS is flattened and then used as arguments to Git.
    534 
    535 Display the command line arguments in the echo area.
    536 
    537 After Git returns some buffers are refreshed: the buffer that was
    538 current when this function was called (if it is a Magit buffer
    539 and still alive), as well as the respective Magit status buffer.
    540 
    541 See `magit-start-process' and `with-editor' for more information."
    542   (magit--record-separated-gitdir)
    543   (magit-with-editor (magit-run-git-async args)))
    544 
    545 (defun magit-run-git-sequencer (&rest args)
    546   "Export GIT_EDITOR and start Git.
    547 Also prepare for refresh and return the process object.
    548 ARGS is flattened and then used as arguments to Git.
    549 
    550 Display the command line arguments in the echo area.
    551 
    552 After Git returns some buffers are refreshed: the buffer that was
    553 current when this function was called (if it is a Magit buffer
    554 and still alive), as well as the respective Magit status buffer.
    555 If the sequence stops at a commit, make the section representing
    556 that commit the current section by moving `point' there.
    557 
    558 See `magit-start-process' and `with-editor' for more information."
    559   (apply #'magit-run-git-with-editor args)
    560   (set-process-sentinel magit-this-process #'magit-sequencer-process-sentinel)
    561   magit-this-process)
    562 
    563 (defvar magit-pre-start-git-hook nil)
    564 
    565 (defun magit-start-git (input &rest args)
    566   "Start Git, prepare for refresh, and return the process object.
    567 
    568 If INPUT is non-nil, it has to be a buffer or the name of an
    569 existing buffer.  The buffer content becomes the processes
    570 standard input.
    571 
    572 Function `magit-git-executable' specifies the Git executable and
    573 option `magit-git-global-arguments' specifies constant arguments.
    574 The remaining arguments ARGS specify arguments to Git, they are
    575 flattened before use.
    576 
    577 After Git returns some buffers are refreshed: the buffer that was
    578 current when this function was called (if it is a Magit buffer
    579 and still alive), as well as the respective Magit status buffer.
    580 
    581 See `magit-start-process' for more information."
    582   (run-hooks 'magit-pre-start-git-hook)
    583   (let ((default-process-coding-system (magit--process-coding-system)))
    584     (apply #'magit-start-process (magit-git-executable) input
    585            (magit-process-git-arguments args))))
    586 
    587 (defun magit-start-process (program &optional input &rest args)
    588   "Start PROGRAM, prepare for refresh, and return the process object.
    589 
    590 If optional argument INPUT is non-nil, it has to be a buffer or
    591 the name of an existing buffer.  The buffer content becomes the
    592 processes standard input.
    593 
    594 The process is started using `start-file-process' and then setup
    595 to use the sentinel `magit-process-sentinel' and the filter
    596 `magit-process-filter'.  Information required by these functions
    597 is stored in the process object.  When this function returns the
    598 process has not started to run yet so it is possible to override
    599 the sentinel and filter.
    600 
    601 After the process returns, `magit-process-sentinel' refreshes the
    602 buffer that was current when `magit-start-process' was called (if
    603 it is a Magit buffer and still alive), as well as the respective
    604 Magit status buffer."
    605   (pcase-let*
    606       ((`(,process-buf . ,section)
    607         (magit-process-setup program args))
    608        (process
    609         (let ((process-connection-type ;t=pty nil=pipe
    610                (or
    611                 ;; With Tramp, maybe force use a pty.  #4720
    612                 (and (file-remote-p default-directory)
    613                      (eq magit-tramp-pipe-stty-settings 'pty))
    614                 ;; Without input, don't use a pty, because it would
    615                 ;; set icrnl, which would modify the input.  #20
    616                 (and (not input) magit-process-connection-type)))
    617               (tramp-pipe-stty-settings
    618                (or (and (not (eq magit-tramp-pipe-stty-settings 'pty))
    619                         ;; Defaults to "", to allow staging hunks over
    620                         ;; Tramp again.  #4720
    621                         magit-tramp-pipe-stty-settings)
    622                    tramp-pipe-stty-settings))
    623               (process-environment (magit-process-environment))
    624               (default-process-coding-system (magit--process-coding-system)))
    625           (apply #'start-file-process
    626                  (file-name-nondirectory program)
    627                  process-buf program args))))
    628     (with-editor-set-process-filter process #'magit-process-filter)
    629     (set-process-sentinel process #'magit-process-sentinel)
    630     (set-process-buffer   process process-buf)
    631     (when (eq system-type 'windows-nt)
    632       ;; On w32, git expects UTF-8 encoded input, ignore any user
    633       ;; configuration telling us otherwise.
    634       (set-process-coding-system process nil 'utf-8-unix))
    635     (process-put process 'section section)
    636     (process-put process 'command-buf (current-buffer))
    637     (process-put process 'default-dir default-directory)
    638     (when magit-inhibit-refresh
    639       (process-put process 'inhibit-refresh t))
    640     (oset section process process)
    641     (with-current-buffer process-buf
    642       (set-marker (process-mark process) (point)))
    643     (when input
    644       (with-current-buffer input
    645         (process-send-region process (point-min) (point-max))
    646         ;; `process-send-eof' appears to be broken over
    647         ;;  Tramp from Windows. See #3624 and bug#43226.
    648         (if (and (eq system-type 'windows-nt)
    649                  (file-remote-p (process-get process 'default-dir) nil t))
    650             (process-send-string process "")
    651           (process-send-eof process))))
    652     (setq magit-this-process process)
    653     (oset section value process)
    654     (magit-process-display-buffer process)
    655     process))
    656 
    657 (defun magit-parse-git-async (&rest args)
    658   (setq args (magit-process-git-arguments args))
    659   (let ((command-buf (current-buffer))
    660         (stdout-buf (generate-new-buffer " *git-stdout*"))
    661         (stderr-buf (generate-new-buffer " *git-stderr*"))
    662         (toplevel (magit-toplevel)))
    663     (with-current-buffer stdout-buf
    664       (setq default-directory toplevel)
    665       (let ((process
    666              (let ((process-environment (magit-process-environment)))
    667                (make-process :name "git"
    668                              :buffer stdout-buf
    669                              :stderr stderr-buf
    670                              :command (cons (magit-git-executable) args)
    671                              :coding (magit--process-coding-system)
    672                              :file-handler t))))
    673         (process-put process 'command-buf command-buf)
    674         (process-put process 'stderr-buf stderr-buf)
    675         (process-put process 'parsed (point))
    676         (setq magit-this-process process)
    677         process))))
    678 
    679 ;;; Process Internals
    680 
    681 (defclass magit-process-section (magit-section)
    682   ((process :initform nil)))
    683 
    684 (setf (alist-get 'process magit--section-type-alist) 'magit-process-section)
    685 
    686 (defun magit-process-setup (program args)
    687   (magit-process-set-mode-line program args)
    688   (let ((pwd default-directory)
    689         (buf (magit-process-buffer t)))
    690     (cons buf (with-current-buffer buf
    691                 (prog1 (magit-process-insert-section pwd program args nil nil)
    692                   (backward-char 1))))))
    693 
    694 (defun magit-process-insert-section (pwd program args &optional errcode errlog)
    695   (let ((inhibit-read-only t)
    696         (magit-insert-section--parent magit-root-section)
    697         (magit-insert-section--oldroot nil))
    698     (goto-char (1- (point-max)))
    699     (magit-insert-section (process)
    700       (insert (if errcode
    701                   (format "%3s " (propertize (number-to-string errcode)
    702                                              'font-lock-face 'magit-process-ng))
    703                 "run "))
    704       (when magit-process-timestamp-format
    705         (insert (format-time-string magit-process-timestamp-format) " "))
    706       (unless (equal (expand-file-name pwd)
    707                      (expand-file-name default-directory))
    708         (insert (file-relative-name pwd default-directory) ?\s))
    709       (insert (magit-process--format-arguments program args))
    710       (magit-insert-heading)
    711       (when errlog
    712         (if (bufferp errlog)
    713             (insert (with-current-buffer errlog
    714                       (buffer-substring-no-properties (point-min) (point-max))))
    715           (insert-file-contents errlog)
    716           (goto-char (1- (point-max)))))
    717       (insert "\n"))))
    718 
    719 (defun magit-process--format-arguments (program args)
    720   (cond
    721    ((and args (equal program (magit-git-executable)))
    722     (let ((global (length magit-git-global-arguments)))
    723       (concat
    724        (propertize (file-name-nondirectory program)
    725                    'font-lock-face 'magit-section-heading)
    726        " "
    727        (propertize (magit--ellipsis)
    728                    'font-lock-face 'magit-section-heading
    729                    'help-echo (string-join (seq-take args global) " "))
    730        " "
    731        (propertize (mapconcat #'shell-quote-argument (seq-drop args global) " ")
    732                    'font-lock-face 'magit-section-heading))))
    733    ((and args (equal program shell-file-name))
    734     (propertize (cadr args)
    735                 'font-lock-face 'magit-section-heading))
    736    (t
    737     (concat (propertize (file-name-nondirectory program)
    738                         'font-lock-face 'magit-section-heading)
    739             " "
    740             (propertize (mapconcat #'shell-quote-argument args " ")
    741                         'font-lock-face 'magit-section-heading)))))
    742 
    743 (defun magit-process-truncate-log ()
    744   (let* ((head nil)
    745          (tail (oref magit-root-section children))
    746          (count (length tail)))
    747     (when (> (1+ count) magit-process-log-max)
    748       (while (and (cdr tail)
    749                   (> count (/ magit-process-log-max 2)))
    750         (let* ((inhibit-read-only t)
    751                (section (car tail))
    752                (process (oref section process)))
    753           (cond ((not process))
    754                 ((memq (process-status process) '(exit signal))
    755                  (delete-region (oref section start)
    756                                 (1+ (oref section end)))
    757                  (cl-decf count))
    758                 (t
    759                  (push section head))))
    760         (pop tail))
    761       (oset magit-root-section children
    762             (nconc (reverse head) tail)))))
    763 
    764 (defun magit-process-sentinel (process event)
    765   "Default sentinel used by `magit-start-process'."
    766   (when (memq (process-status process) '(exit signal))
    767     (setq event (substring event 0 -1))
    768     (when (string-match "^finished" event)
    769       (message (concat (capitalize (process-name process)) " finished")))
    770     (magit-process-finish process)
    771     (when (eq process magit-this-process)
    772       (setq magit-this-process nil))
    773     (unless (process-get process 'inhibit-refresh)
    774       (let ((command-buf (process-get process 'command-buf)))
    775         (if (buffer-live-p command-buf)
    776             (with-current-buffer command-buf
    777               (magit-refresh))
    778           (with-temp-buffer
    779             (setq default-directory (process-get process 'default-dir))
    780             (magit-refresh)))))))
    781 
    782 (defun magit-sequencer-process-sentinel (process event)
    783   "Special sentinel used by `magit-run-git-sequencer'."
    784   (when (memq (process-status process) '(exit signal))
    785     (magit-process-sentinel process event)
    786     (when-let* ((process-buf (process-buffer process))
    787                 ((buffer-live-p process-buf))
    788                 (status-buf (with-current-buffer process-buf
    789                               (magit-get-mode-buffer 'magit-status-mode))))
    790       (with-current-buffer status-buf
    791         (when-let ((section
    792                     (magit-get-section
    793                      `((commit . ,(magit-rev-parse "HEAD"))
    794                        (,(pcase (car (seq-drop
    795                                       (process-command process)
    796                                       (1+ (length magit-git-global-arguments))))
    797                            ((or "rebase" "am") 'rebase-sequence)
    798                            ((or "cherry-pick" "revert") 'sequence)))
    799                        (status)))))
    800           (goto-char (oref section start))
    801           (magit-section-update-highlight))))))
    802 
    803 (defun magit-process-filter (proc string)
    804   "Default filter used by `magit-start-process'."
    805   (with-current-buffer (process-buffer proc)
    806     (let ((inhibit-read-only t))
    807       (goto-char (process-mark proc))
    808       ;; Find last ^M in string.  If one was found, ignore
    809       ;; everything before it and delete the current line.
    810       (when-let ((ret-pos (cl-position ?\r string :from-end t)))
    811         (cl-callf substring string (1+ ret-pos))
    812         (delete-region (line-beginning-position) (point)))
    813       (setq string (magit-process-remove-bogus-errors string))
    814       (insert (propertize string 'magit-section
    815                           (process-get proc 'section)))
    816       (set-marker (process-mark proc) (point))
    817       ;; Make sure prompts are matched after removing ^M.
    818       (magit-process-yes-or-no-prompt proc string)
    819       (magit-process-username-prompt  proc string)
    820       (magit-process-password-prompt  proc string)
    821       (run-hook-with-args-until-success 'magit-process-prompt-functions
    822                                         proc string))))
    823 
    824 (defun magit-process-make-keymap (process parent)
    825   "Remap `abort-minibuffers' to a command that also kills PROCESS.
    826 PARENT is used as the parent of the returned keymap."
    827   (let ((cmd (lambda ()
    828                (interactive)
    829                (ignore-errors (kill-process process))
    830                (if (fboundp 'abort-minibuffers)
    831                    (abort-minibuffers)
    832                  (abort-recursive-edit)))))
    833     (define-keymap :parent parent
    834       "C-g" cmd
    835       "<remap> <abort-minibuffers>" cmd
    836       "<remap> <abort-recursive-edit>" cmd)))
    837 
    838 (defmacro magit-process-kill-on-abort (process &rest body)
    839   (declare (indent 1)
    840            (debug (form body))
    841            (obsolete magit-process-make-keymap "Magit 4.0.0"))
    842   `(let ((minibuffer-local-map
    843           (magit-process-make-keymap ,process minibuffer-local-map)))
    844      ,@body))
    845 
    846 (defun magit-process-remove-bogus-errors (str)
    847   (save-match-data
    848     (when (string-match "^\\(\\*ERROR\\*: \\)Canceled by user" str)
    849       (setq str (replace-match "" nil nil str 1)))
    850     (when (string-match "^error: There was a problem with the editor.*\n" str)
    851       (setq str (replace-match "" nil nil str)))
    852     (when (string-match
    853            "^Please supply the message using either -m or -F option\\.\n" str)
    854       (setq str (replace-match "" nil nil str))))
    855   str)
    856 
    857 (defun magit-process-yes-or-no-prompt (process string)
    858   "Forward Yes-or-No prompts to the user."
    859   (when-let ((beg (string-match magit-process-yes-or-no-prompt-regexp string)))
    860     (process-send-string
    861      process
    862      (if (save-match-data
    863            (let ((max-mini-window-height 30)
    864                  (minibuffer-local-map
    865                   (magit-process-make-keymap process minibuffer-local-map))
    866                  ;; In case yes-or-no-p is fset to that, but does
    867                  ;; not cover use-dialog-box-p and y-or-n-p-read-key.
    868                  (y-or-n-p-map
    869                   (magit-process-make-keymap process y-or-n-p-map)))
    870              (yes-or-no-p (substring string 0 beg))))
    871          (concat (downcase (match-string 1 string)) "\n")
    872        (concat (downcase (match-string 2 string)) "\n")))))
    873 
    874 (defun magit-process-password-auth-source (key)
    875   "Use `auth-source-search' to get a password.
    876 If found, return the password.  Otherwise, return nil.
    877 
    878 To use this function add it to the appropriate hook
    879   (add-hook \\='magit-process-find-password-functions
    880             \\='magit-process-password-auth-source)
    881 
    882 KEY typically derives from a prompt such as:
    883   Password for \\='https://yourname@github.com\\='
    884 in which case it would be the string
    885   yourname@github.com
    886 which matches the ~/.authinfo.gpg entry
    887   machine github.com login yourname password 12345
    888 or iff that is undefined, for backward compatibility
    889   machine yourname@github.com password 12345
    890 
    891 On github.com you should not use your password but a
    892 personal access token, see [1].  For information about
    893 the peculiarities of other forges, please consult the
    894 respective documentation.
    895 
    896 After manually editing ~/.authinfo.gpg you must reset
    897 the cache using
    898   M-x auth-source-forget-all-cached RET
    899 
    900 The above will save you from having to repeatedly type
    901 your token or password, but you might still repeatedly
    902 be asked for your username.  To prevent that, change an
    903 URL like
    904   https://github.com/foo/bar.git
    905 to
    906   https://yourname@github.com/foo/bar.git
    907 
    908 Instead of changing all such URLs manually, they can
    909 be translated on the fly by doing this once
    910   git config --global \
    911     url.https://yourname@github.com.insteadOf \
    912     https://github.com
    913 
    914 [1]: https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token."
    915   (require 'auth-source)
    916   (and (fboundp 'auth-source-search)
    917        (string-match "\\`\\(.+\\)@\\([^@]+\\)\\'" key)
    918        (let* ((user (match-string 1 key))
    919               (host (match-string 2 key))
    920               (secret
    921                (plist-get
    922                 (car (or (auth-source-search :max 1 :host host :user user)
    923                          (auth-source-search :max 1 :host key)))
    924                 :secret)))
    925          (if (functionp secret)
    926              (funcall secret)
    927            secret))))
    928 
    929 (defun magit-process-git-credential-manager-core (process string)
    930   "Authenticate using `git-credential-manager-core'.
    931 
    932 To use this function add it to the appropriate hook
    933   (add-hook \\='magit-process-prompt-functions
    934             \\='magit-process-git-credential-manager-core)"
    935   (and (string-match "^option (enter for default): $" string)
    936        (progn
    937          (magit-process-buffer)
    938          (let ((option (format "%c\n"
    939                                (read-char-choice "Option: " '(?\r ?\j ?1 ?2)))))
    940            (insert-before-markers-and-inherit option)
    941            (process-send-string process option)))))
    942 
    943 (defun magit-process-password-prompt (process string)
    944   "Find a password based on prompt STRING and send it to git.
    945 Use `magit-process-password-prompt-regexps' to find a known
    946 prompt.  If and only if one is found, then call functions in
    947 `magit-process-find-password-functions' until one of them returns
    948 the password.  If all functions return nil, then read the password
    949 from the user."
    950   (when-let ((prompt (magit-process-match-prompt
    951                       magit-process-password-prompt-regexps string)))
    952     (process-send-string
    953      process
    954      (concat (or (and-let* ((key (match-string 99 string)))
    955                    (run-hook-with-args-until-success
    956                     'magit-process-find-password-functions key))
    957                  (let ((read-passwd-map
    958                         (magit-process-make-keymap process read-passwd-map)))
    959                    (read-passwd prompt)))
    960              "\n"))))
    961 
    962 (defun magit-process-username-prompt (process string)
    963   "Forward username prompts to the user."
    964   (when-let ((prompt (magit-process-match-prompt
    965                       magit-process-username-prompt-regexps string)))
    966     (process-send-string
    967      process
    968      (let ((minibuffer-local-map
    969             (magit-process-make-keymap process minibuffer-local-map)))
    970        (concat (read-string prompt nil nil (user-login-name)) "\n")))))
    971 
    972 (defun magit-process-match-prompt (prompts string)
    973   "Match STRING against PROMPTS and set match data.
    974 Return the matched string suffixed with \": \", if needed."
    975   (when (--any-p (string-match it string) prompts)
    976     (let ((prompt (match-string 0 string)))
    977       (cond ((string-suffix-p ": " prompt) prompt)
    978             ((string-suffix-p ":"  prompt) (concat prompt " "))
    979             (t                             (concat prompt ": "))))))
    980 
    981 (defun magit--process-coding-system ()
    982   (let ((fro (or magit-git-output-coding-system
    983                  (car default-process-coding-system)))
    984         (to (cdr default-process-coding-system)))
    985     (if magit-process-ensure-unix-line-ending
    986         (cons (coding-system-change-eol-conversion fro 'unix)
    987               (coding-system-change-eol-conversion to 'unix))
    988       (cons fro to))))
    989 
    990 (defvar magit-credential-hook nil
    991   "Hook run before Git needs credentials.")
    992 
    993 (defvar magit-credential-cache-daemon-process nil)
    994 
    995 (defun magit-maybe-start-credential-cache-daemon ()
    996   "Maybe start a `git-credential-cache--daemon' process.
    997 
    998 If such a process is already running or if the value of option
    999 `magit-credential-cache-daemon-socket' is nil, then do nothing.
   1000 Otherwise start the process passing the value of that options
   1001 as argument."
   1002   (unless (or (not magit-credential-cache-daemon-socket)
   1003               (process-live-p magit-credential-cache-daemon-process)
   1004               (memq magit-credential-cache-daemon-process
   1005                     (list-system-processes)))
   1006     (setq magit-credential-cache-daemon-process
   1007           (or (--first (let* ((attr (process-attributes it))
   1008                               (comm (cdr (assq 'comm attr)))
   1009                               (user (cdr (assq 'user attr))))
   1010                          (and (string= comm "git-credential-cache--daemon")
   1011                               (string= user user-login-name)))
   1012                        (list-system-processes))
   1013               (condition-case nil
   1014                   (start-process "git-credential-cache--daemon"
   1015                                  " *git-credential-cache--daemon*"
   1016                                  (magit-git-executable)
   1017                                  "credential-cache--daemon"
   1018                                  magit-credential-cache-daemon-socket)
   1019                 ;; Some Git implementations (e.g., Windows) won't have
   1020                 ;; this program; if we fail the first time, stop trying.
   1021                 ((debug error)
   1022                  (remove-hook 'magit-credential-hook
   1023                               #'magit-maybe-start-credential-cache-daemon)))))))
   1024 
   1025 (add-hook 'magit-credential-hook #'magit-maybe-start-credential-cache-daemon)
   1026 
   1027 (defvar-keymap magit-mode-line-process-map
   1028   :doc "Keymap for `mode-line-process'."
   1029   "<mode-line> <mouse-1>" 'magit-process-buffer)
   1030 
   1031 (defun magit-process-set-mode-line (program args)
   1032   "Display the git command (sans arguments) in the mode line."
   1033   (when (equal program (magit-git-executable))
   1034     (setq args (nthcdr (length magit-git-global-arguments) args)))
   1035   (let ((str (concat " " (propertize
   1036                           (concat (file-name-nondirectory program)
   1037                                   (and args (concat " " (car args))))
   1038                           'mouse-face 'highlight
   1039                           'keymap magit-mode-line-process-map
   1040                           'help-echo "mouse-1: Show process buffer"
   1041                           'font-lock-face 'magit-mode-line-process))))
   1042     (magit-repository-local-set 'mode-line-process str)
   1043     (dolist (buf (magit-mode-get-buffers))
   1044       (with-current-buffer buf
   1045         (setq mode-line-process str)))
   1046     (force-mode-line-update t)))
   1047 
   1048 (defun magit-process-set-mode-line-error-status (&optional error str)
   1049   "Apply an error face to the string set by `magit-process-set-mode-line'.
   1050 
   1051 If ERROR is supplied, include it in the `mode-line-process' tooltip.
   1052 
   1053 If STR is supplied, it replaces the `mode-line-process' text."
   1054   (setq str (or str (magit-repository-local-get 'mode-line-process)))
   1055   (when str
   1056     (setq error (format "%smouse-1: Show process buffer"
   1057                         (if (stringp error)
   1058                             (concat error "\n\n")
   1059                           "")))
   1060     (setq str (concat " " (propertize
   1061                            (substring-no-properties str 1)
   1062                            'mouse-face 'highlight
   1063                            'keymap magit-mode-line-process-map
   1064                            'help-echo error
   1065                            'font-lock-face 'magit-mode-line-process-error)))
   1066     (magit-repository-local-set 'mode-line-process str)
   1067     (dolist (buf (magit-mode-get-buffers))
   1068       (with-current-buffer buf
   1069         (setq mode-line-process str)))
   1070     (force-mode-line-update t)
   1071     ;; We remove any error status from the mode line when a magit
   1072     ;; buffer is refreshed (see `magit-refresh-buffer'), but we must
   1073     ;; ensure that we ignore any refreshes during the remainder of the
   1074     ;; current command -- otherwise a newly-set error status would be
   1075     ;; removed before it was seen.  We set a flag which prevents the
   1076     ;; status from being removed prior to the next command, so that
   1077     ;; the error status is guaranteed to remain visible until then.
   1078     (let ((repokey (magit-repository-local-repository)))
   1079       ;; The following closure captures the repokey value, and is
   1080       ;; added to `pre-command-hook'.
   1081       (cl-labels ((enable-magit-process-unset-mode-line ()
   1082                     ;; Remove ourself from the hook variable, so
   1083                     ;; that we only run once.
   1084                     (remove-hook 'pre-command-hook
   1085                                  #'enable-magit-process-unset-mode-line)
   1086                     ;; Clear the inhibit flag for the repository in
   1087                     ;; which we set it.
   1088                     (magit-repository-local-set
   1089                      'inhibit-magit-process-unset-mode-line nil repokey)))
   1090         ;; Set the inhibit flag until the next command is invoked.
   1091         (magit-repository-local-set
   1092          'inhibit-magit-process-unset-mode-line t repokey)
   1093         (add-hook 'pre-command-hook
   1094                   #'enable-magit-process-unset-mode-line)))))
   1095 
   1096 (defun magit-process-unset-mode-line-error-status ()
   1097   "Remove any current error status from the mode line."
   1098   (let ((status (or mode-line-process
   1099                     (magit-repository-local-get 'mode-line-process))))
   1100     (when (and status
   1101                (eq (get-text-property 1 'font-lock-face status)
   1102                    'magit-mode-line-process-error))
   1103       (magit-process-unset-mode-line))))
   1104 
   1105 (add-hook 'magit-refresh-buffer-hook
   1106           #'magit-process-unset-mode-line-error-status)
   1107 
   1108 (defun magit-process-unset-mode-line (&optional directory)
   1109   "Remove the git command from the mode line."
   1110   (let ((default-directory (or directory default-directory)))
   1111     (unless (magit-repository-local-get 'inhibit-magit-process-unset-mode-line)
   1112       (magit-repository-local-set 'mode-line-process nil)
   1113       (dolist (buf (magit-mode-get-buffers))
   1114         (with-current-buffer buf (setq mode-line-process nil)))
   1115       (force-mode-line-update t))))
   1116 
   1117 (defvar magit-process-error-message-regexps
   1118   (list "^\\*ERROR\\*: Canceled by user$"
   1119         "^\\(?:error\\|fatal\\|git\\): \\(.*\\)$"
   1120         "^\\(Cannot rebase:.*\\)$"))
   1121 
   1122 (define-error 'magit-git-error "Git error")
   1123 
   1124 (defun magit-process-error-summary (process-buf section)
   1125   "A one-line error summary from the given SECTION."
   1126   (or (and (buffer-live-p process-buf)
   1127            (with-current-buffer process-buf
   1128              (and (oref section content)
   1129                   (save-excursion
   1130                     (goto-char (oref section end))
   1131                     (run-hook-wrapped
   1132                      'magit-process-error-message-regexps
   1133                      (lambda (re)
   1134                        (save-excursion
   1135                          (and (re-search-backward
   1136                                re (oref section start) t)
   1137                               (or (match-string-no-properties 1)
   1138                                   (and (not magit-process-raise-error)
   1139                                        'suppressed))))))))))
   1140       "Git failed"))
   1141 
   1142 (defun magit-process-error-tooltip (process-buf section)
   1143   "Returns the text from SECTION of the PROCESS-BUF buffer.
   1144 
   1145 Limited by `magit-process-error-tooltip-max-lines'."
   1146   (and (integerp magit-process-error-tooltip-max-lines)
   1147        (> magit-process-error-tooltip-max-lines 0)
   1148        (buffer-live-p process-buf)
   1149        (with-current-buffer process-buf
   1150          (save-excursion
   1151            (goto-char (or (oref section content)
   1152                           (oref section start)))
   1153            (buffer-substring-no-properties
   1154             (point)
   1155             (save-excursion
   1156               (forward-line magit-process-error-tooltip-max-lines)
   1157               (goto-char
   1158                (if (> (point) (oref section end))
   1159                    (oref section end)
   1160                  (point)))
   1161               ;; Remove any trailing whitespace.
   1162               (when (re-search-backward "[^[:space:]\n]"
   1163                                         (oref section start) t)
   1164                 (forward-char 1))
   1165               (point)))))))
   1166 
   1167 (defvar-local magit-this-error nil)
   1168 
   1169 (defvar magit-process-finish-apply-ansi-colors nil)
   1170 
   1171 (defun magit-process-finish (arg &optional process-buf command-buf
   1172                                  default-dir section)
   1173   (unless (integerp arg)
   1174     (setq process-buf (process-buffer arg))
   1175     (setq command-buf (process-get arg 'command-buf))
   1176     (setq default-dir (process-get arg 'default-dir))
   1177     (setq section     (process-get arg 'section))
   1178     (setq arg         (process-exit-status arg)))
   1179   (when (fboundp 'dired-uncache)
   1180     (dired-uncache default-dir))
   1181   (when (buffer-live-p process-buf)
   1182     (with-current-buffer process-buf
   1183       (let ((inhibit-read-only t)
   1184             (marker (oref section start)))
   1185         (goto-char marker)
   1186         (save-excursion
   1187           (delete-char 3)
   1188           (set-marker-insertion-type marker nil)
   1189           (insert (propertize (format "%3s" arg)
   1190                               'magit-section section
   1191                               'font-lock-face (if (= arg 0)
   1192                                                   'magit-process-ok
   1193                                                 'magit-process-ng)))
   1194           (set-marker-insertion-type marker t))
   1195         (when magit-process-finish-apply-ansi-colors
   1196           (ansi-color-apply-on-region (oref section content)
   1197                                       (oref section end)))
   1198         (if (= (oref section end)
   1199                (+ (line-end-position) 2))
   1200             (save-excursion
   1201               (goto-char (1+ (line-end-position)))
   1202               (delete-char -1)
   1203               (oset section content nil))
   1204           (when (and (= arg 0)
   1205                      (not (--any-p (eq (window-buffer it) process-buf)
   1206                                    (window-list))))
   1207             (magit-section-hide section))))))
   1208   (if (= arg 0)
   1209       ;; Unset the `mode-line-process' value upon success.
   1210       (magit-process-unset-mode-line default-dir)
   1211     ;; Otherwise process the error.
   1212     (let ((msg (magit-process-error-summary process-buf section)))
   1213       ;; Change `mode-line-process' to an error face upon failure.
   1214       (if magit-process-display-mode-line-error
   1215           (magit-process-set-mode-line-error-status
   1216            (or (magit-process-error-tooltip process-buf section)
   1217                msg))
   1218         (magit-process-unset-mode-line default-dir))
   1219       ;; Either signal the error, or else display the error summary in
   1220       ;; the status buffer and with a message in the echo area.
   1221       (cond
   1222        (magit-process-raise-error
   1223         (signal 'magit-git-error (list (format "%s (in %s)" msg default-dir))))
   1224        ((not (eq msg 'suppressed))
   1225         (when (buffer-live-p process-buf)
   1226           (with-current-buffer process-buf
   1227             (when-let ((status-buf (magit-get-mode-buffer 'magit-status-mode)))
   1228               (with-current-buffer status-buf
   1229                 (setq magit-this-error msg)))))
   1230         (message "%s ... [%s buffer %s for details]" msg
   1231                  (if-let ((key (and (buffer-live-p command-buf)
   1232                                     (with-current-buffer command-buf
   1233                                       (car (where-is-internal
   1234                                             'magit-process-buffer))))))
   1235                      (format "Hit %s to see" (key-description key))
   1236                    "See")
   1237                  (buffer-name process-buf))))))
   1238   arg)
   1239 
   1240 (defun magit-process-display-buffer (process)
   1241   (when (process-live-p process)
   1242     (let ((buf (process-buffer process)))
   1243       (cond ((not (buffer-live-p buf)))
   1244             ((= magit-process-popup-time 0)
   1245              (if (minibufferp)
   1246                  (switch-to-buffer-other-window buf)
   1247                (pop-to-buffer buf)))
   1248             ((> magit-process-popup-time 0)
   1249              (run-with-timer magit-process-popup-time nil
   1250                              (lambda (p)
   1251                                (when (eq (process-status p) 'run)
   1252                                  (let ((buf (process-buffer p)))
   1253                                    (when (buffer-live-p buf)
   1254                                      (if (minibufferp)
   1255                                          (switch-to-buffer-other-window buf)
   1256                                        (pop-to-buffer buf))))))
   1257                              process))))))
   1258 
   1259 (defun magit--log-action (summary line list)
   1260   (let (heading lines)
   1261     (if (cdr list)
   1262         (progn (setq heading (funcall summary list))
   1263                (setq lines (mapcar line list)))
   1264       (setq heading (funcall line (car list))))
   1265     (with-current-buffer (magit-process-buffer t)
   1266       (goto-char (1- (point-max)))
   1267       (let ((inhibit-read-only t))
   1268         (magit-insert-section (message)
   1269           (magit-insert-heading (concat "  * " heading))
   1270           (when lines
   1271             (dolist (line lines)
   1272               (insert line "\n"))
   1273             (insert "\n"))))
   1274       (let ((inhibit-message t))
   1275         (when heading
   1276           (setq lines (cons heading lines)))
   1277         (message (string-join lines "\n"))))))
   1278 
   1279 ;;; _
   1280 (provide 'magit-process)
   1281 ;;; magit-process.el ends here