config

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

magit-process.el (54262B)


      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 comes with its own problems (see #20).  To fall
    275 back to the value of `tramp-pipe-stty-settings', set this
    276 variable to nil.
    277 
    278 Also see https://github.com/magit/magit/issues/4720
    279 and https://debbugs.gnu.org/cgi/bugreport.cgi?bug=62093.")
    280 
    281 (defface magit-process-ok
    282   '((t :inherit magit-section-heading :foreground "green"))
    283   "Face for zero exit-status."
    284   :group 'magit-faces)
    285 
    286 (defface magit-process-ng
    287   '((t :inherit magit-section-heading :foreground "red"))
    288   "Face for non-zero exit-status."
    289   :group 'magit-faces)
    290 
    291 (defface magit-mode-line-process
    292   '((t :inherit mode-line-emphasis))
    293   "Face for `mode-line-process' status when Git is running for side-effects."
    294   :group 'magit-faces)
    295 
    296 (defface magit-mode-line-process-error
    297   '((t :inherit error))
    298   "Face for `mode-line-process' error status.
    299 
    300 Used when `magit-process-display-mode-line-error' is non-nil."
    301   :group 'magit-faces)
    302 
    303 ;;; Process Mode
    304 
    305 (defvar-keymap magit-process-mode-map
    306   :doc "Keymap for `magit-process-mode'."
    307   :parent magit-mode-map
    308   "<remap> <magit-delete-thing>" #'magit-process-kill)
    309 
    310 (define-derived-mode magit-process-mode magit-mode "Magit Process"
    311   "Mode for looking at Git process output."
    312   :interactive nil
    313   :group 'magit-process
    314   (magit-hack-dir-local-variables)
    315   (setq magit--imenu-item-types 'process))
    316 
    317 (defun magit-process-buffer (&optional nodisplay)
    318   "Display the current repository's process buffer.
    319 
    320 If that buffer doesn't exist yet, then create it.
    321 Non-interactively return the buffer and unless
    322 optional NODISPLAY is non-nil also display it."
    323   (interactive)
    324   (let ((topdir (magit-toplevel)))
    325     (unless topdir
    326       (magit--with-safe-default-directory nil
    327         (setq topdir default-directory)
    328         (let (prev)
    329           (while (not (equal topdir prev))
    330             (setq prev topdir)
    331             (setq topdir (file-name-directory (directory-file-name topdir)))))))
    332     (let ((buffer (or (--first (with-current-buffer it
    333                                  (and (eq major-mode 'magit-process-mode)
    334                                       (equal default-directory topdir)))
    335                                (buffer-list))
    336                       (magit-generate-new-buffer 'magit-process-mode
    337                                                  nil topdir))))
    338       (with-current-buffer buffer
    339         (if magit-root-section
    340             (when magit-process-log-max
    341               (magit-process-truncate-log))
    342           (magit-process-mode)
    343           (let ((inhibit-read-only t)
    344                 (magit-insert-section--parent  nil)
    345                 (magit-insert-section--oldroot nil))
    346             (make-local-variable 'text-property-default-nonsticky)
    347             (magit-insert-section (processbuf)
    348               (insert "\n")))))
    349       (unless nodisplay
    350         (magit-display-buffer buffer))
    351       buffer)))
    352 
    353 (defun magit-process-kill ()
    354   "Kill the process at point."
    355   (interactive)
    356   (when-let ((process (magit-section-value-if 'process)))
    357     (unless (eq (process-status process) 'run)
    358       (user-error "Process isn't running"))
    359     (magit-confirm 'kill-process)
    360     (kill-process process)))
    361 
    362 ;;; Synchronous Processes
    363 
    364 (defvar magit-process-raise-error nil)
    365 
    366 (defun magit-git (&rest args)
    367   "Call Git synchronously in a separate process, for side-effects.
    368 
    369 Option `magit-git-executable' specifies the Git executable.
    370 The arguments ARGS specify arguments to Git, they are flattened
    371 before use.
    372 
    373 Process output goes into a new section in the buffer returned by
    374 `magit-process-buffer'.  If Git exits with a non-zero status,
    375 then raise an error."
    376   (let ((magit-process-raise-error t))
    377     (magit-call-git args)))
    378 
    379 (defun magit-run-git (&rest args)
    380   "Call Git synchronously in a separate process, and refresh.
    381 
    382 Function `magit-git-executable' specifies the Git executable and
    383 option `magit-git-global-arguments' specifies constant arguments.
    384 The arguments ARGS specify arguments to Git, they are flattened
    385 before use.
    386 
    387 After Git returns, the current buffer (if it is a Magit buffer)
    388 as well as the current repository's status buffer are refreshed.
    389 
    390 Process output goes into a new section in the buffer returned by
    391 `magit-process-buffer'."
    392   (let ((magit--refresh-cache (list (cons 0 0))))
    393     (prog1 (magit-call-git args)
    394       (when (member (car args) '("init" "clone"))
    395         ;; Creating a new repository invalidates the cache.
    396         (setq magit--refresh-cache nil))
    397       (magit-refresh))))
    398 
    399 (defvar magit-pre-call-git-hook nil)
    400 
    401 (defun magit-call-git (&rest args)
    402   "Call Git synchronously in a separate process.
    403 
    404 Function `magit-git-executable' specifies the Git executable and
    405 option `magit-git-global-arguments' specifies constant arguments.
    406 The arguments ARGS specify arguments to Git, they are flattened
    407 before use.
    408 
    409 Process output goes into a new section in the buffer returned by
    410 `magit-process-buffer'."
    411   (run-hooks 'magit-pre-call-git-hook)
    412   (let ((default-process-coding-system (magit--process-coding-system)))
    413     (apply #'magit-call-process
    414            (magit-git-executable)
    415            (magit-process-git-arguments args))))
    416 
    417 (defun magit-call-process (program &rest args)
    418   "Call PROGRAM synchronously in a separate process.
    419 Process output goes into a new section in the buffer returned by
    420 `magit-process-buffer'."
    421   (pcase-let ((`(,process-buf . ,section)
    422                (magit-process-setup program args)))
    423     (magit-process-finish
    424      (let ((inhibit-read-only t))
    425        (apply #'magit-process-file program nil process-buf nil args))
    426      process-buf (current-buffer) default-directory section)))
    427 
    428 (defun magit-process-git (destination &rest args)
    429   "Call Git synchronously in a separate process, returning its exit code.
    430 DESTINATION specifies how to handle the output, like for
    431 `call-process', except that file handlers are supported.
    432 Enable Cygwin's \"noglob\" option during the call and
    433 ensure unix eol conversion."
    434   (apply #'magit-process-file
    435          (magit-git-executable)
    436          nil destination nil
    437          (magit-process-git-arguments args)))
    438 
    439 (defun magit-process-file (process &optional infile buffer display &rest args)
    440   "Process files synchronously in a separate process.
    441 Identical to `process-file' but temporarily enable Cygwin's
    442 \"noglob\" option during the call and ensure unix eol
    443 conversion."
    444   (when magit-process-extreme-logging
    445     (let ((inhibit-message t))
    446       (message "$ %s" (magit-process--format-arguments process args))))
    447   (let ((process-environment (magit-process-environment))
    448         (default-process-coding-system (magit--process-coding-system)))
    449     (apply #'process-file process infile buffer display args)))
    450 
    451 (defun magit-process-environment ()
    452   ;; The various w32 hacks are only applicable when running on the local
    453   ;; machine.  A local binding of process-environment different from the
    454   ;; top-level value affects the environment used by Tramp.
    455   (let ((local (not (file-remote-p default-directory))))
    456     (append magit-git-environment
    457             (and local
    458                  (cdr (assoc magit-git-executable magit-git-w32-path-hack)))
    459             (and local magit-need-cygwin-noglob
    460                  (mapcar (lambda (var)
    461                            (concat var "=" (if-let ((val (getenv var)))
    462                                                (concat val " noglob")
    463                                              "noglob")))
    464                          '("CYGWIN" "MSYS")))
    465             process-environment)))
    466 
    467 (defvar magit-this-process nil)
    468 
    469 (defun magit-run-git-with-input (&rest args)
    470   "Call Git in a separate process.
    471 ARGS is flattened and then used as arguments to Git.
    472 
    473 The current buffer's content is used as the process's standard
    474 input.  The buffer is assumed to be temporary and thus OK to
    475 modify.
    476 
    477 Function `magit-git-executable' specifies the Git executable and
    478 option `magit-git-global-arguments' specifies constant arguments.
    479 The remaining arguments ARGS specify arguments to Git, they are
    480 flattened before use."
    481   (when (eq system-type 'windows-nt)
    482     ;; On w32, git expects UTF-8 encoded input, ignore any user
    483     ;; configuration telling us otherwise (see #3250).
    484     (encode-coding-region (point-min) (point-max) 'utf-8-unix))
    485   (if (file-remote-p default-directory)
    486       ;; We lack `process-file-region', so fall back to asynch +
    487       ;; waiting in remote case.
    488       (progn
    489         (magit-start-git (current-buffer) args)
    490         (while (and magit-this-process
    491                     (eq (process-status magit-this-process) 'run))
    492           (sleep-for 0.005)))
    493     (run-hooks 'magit-pre-call-git-hook)
    494     (pcase-let* ((process-environment (magit-process-environment))
    495                  (default-process-coding-system (magit--process-coding-system))
    496                  (flat-args (magit-process-git-arguments args))
    497                  (`(,process-buf . ,section)
    498                   (magit-process-setup (magit-git-executable) flat-args))
    499                  (inhibit-read-only t))
    500       (magit-process-finish
    501        (apply #'call-process-region (point-min) (point-max)
    502               (magit-git-executable) nil process-buf nil flat-args)
    503        process-buf nil default-directory section))))
    504 
    505 ;;; Asynchronous Processes
    506 
    507 (defun magit-run-git-async (&rest args)
    508   "Start Git, prepare for refresh, and return the process object.
    509 ARGS is flattened and then used as arguments to Git.
    510 
    511 Display the command line arguments in the echo area.
    512 
    513 After Git returns some buffers are refreshed: the buffer that was
    514 current when this function was called (if it is a Magit buffer
    515 and still alive), as well as the respective Magit status buffer.
    516 
    517 See `magit-start-process' for more information."
    518   (message "Running %s %s" (magit-git-executable)
    519            (let ((m (string-join (flatten-tree args) " ")))
    520              (remove-list-of-text-properties 0 (length m) '(face) m)
    521              m))
    522   (magit-start-git nil args))
    523 
    524 (defun magit-run-git-with-editor (&rest args)
    525   "Export GIT_EDITOR and start Git.
    526 Also prepare for refresh and return the process object.
    527 ARGS is flattened and then used as arguments to Git.
    528 
    529 Display the command line arguments in the echo area.
    530 
    531 After Git returns some buffers are refreshed: the buffer that was
    532 current when this function was called (if it is a Magit buffer
    533 and still alive), as well as the respective Magit status buffer.
    534 
    535 See `magit-start-process' and `with-editor' for more information."
    536   (magit--record-separated-gitdir)
    537   (magit-with-editor (magit-run-git-async args)))
    538 
    539 (defun magit-run-git-sequencer (&rest args)
    540   "Export GIT_EDITOR and start Git.
    541 Also prepare for refresh and return the process object.
    542 ARGS is flattened and then used as arguments to Git.
    543 
    544 Display the command line arguments in the echo area.
    545 
    546 After Git returns some buffers are refreshed: the buffer that was
    547 current when this function was called (if it is a Magit buffer
    548 and still alive), as well as the respective Magit status buffer.
    549 If the sequence stops at a commit, make the section representing
    550 that commit the current section by moving `point' there.
    551 
    552 See `magit-start-process' and `with-editor' for more information."
    553   (apply #'magit-run-git-with-editor args)
    554   (set-process-sentinel magit-this-process #'magit-sequencer-process-sentinel)
    555   magit-this-process)
    556 
    557 (defvar magit-pre-start-git-hook nil)
    558 
    559 (defun magit-start-git (input &rest args)
    560   "Start Git, prepare for refresh, and return the process object.
    561 
    562 If INPUT is non-nil, it has to be a buffer or the name of an
    563 existing buffer.  The buffer content becomes the processes
    564 standard input.
    565 
    566 Function `magit-git-executable' specifies the Git executable and
    567 option `magit-git-global-arguments' specifies constant arguments.
    568 The remaining arguments ARGS specify arguments to Git, they are
    569 flattened before use.
    570 
    571 After Git returns some buffers are refreshed: the buffer that was
    572 current when this function was called (if it is a Magit buffer
    573 and still alive), as well as the respective Magit status buffer.
    574 
    575 See `magit-start-process' for more information."
    576   (run-hooks 'magit-pre-start-git-hook)
    577   (let ((default-process-coding-system (magit--process-coding-system)))
    578     (apply #'magit-start-process (magit-git-executable) input
    579            (magit-process-git-arguments args))))
    580 
    581 (defun magit-start-process (program &optional input &rest args)
    582   "Start PROGRAM, prepare for refresh, and return the process object.
    583 
    584 If optional argument INPUT is non-nil, it has to be a buffer or
    585 the name of an existing buffer.  The buffer content becomes the
    586 processes standard input.
    587 
    588 The process is started using `start-file-process' and then setup
    589 to use the sentinel `magit-process-sentinel' and the filter
    590 `magit-process-filter'.  Information required by these functions
    591 is stored in the process object.  When this function returns the
    592 process has not started to run yet so it is possible to override
    593 the sentinel and filter.
    594 
    595 After the process returns, `magit-process-sentinel' refreshes the
    596 buffer that was current when `magit-start-process' was called (if
    597 it is a Magit buffer and still alive), as well as the respective
    598 Magit status buffer."
    599   (pcase-let*
    600       ((`(,process-buf . ,section)
    601         (magit-process-setup program args))
    602        (process
    603         (let ((process-connection-type ;t=pty nil=pipe
    604                (or
    605                 ;; With Tramp, maybe force use a pty.  #4720
    606                 (and (file-remote-p default-directory)
    607                      (eq magit-tramp-pipe-stty-settings 'pty))
    608                 ;; Without input, don't use a pty, because it would
    609                 ;; set icrnl, which would modify the input.  #20
    610                 (and (not input) magit-process-connection-type)))
    611               (tramp-pipe-stty-settings
    612                (or (and (not (eq magit-tramp-pipe-stty-settings 'pty))
    613                         ;; Defaults to "", to allow staging hunks over
    614                         ;; Tramp again.  #4720
    615                         magit-tramp-pipe-stty-settings)
    616                    tramp-pipe-stty-settings))
    617               (process-environment (magit-process-environment))
    618               (default-process-coding-system (magit--process-coding-system)))
    619           (apply #'start-file-process
    620                  (file-name-nondirectory program)
    621                  process-buf program args))))
    622     (with-editor-set-process-filter process #'magit-process-filter)
    623     (set-process-sentinel process #'magit-process-sentinel)
    624     (set-process-buffer   process process-buf)
    625     (when (eq system-type 'windows-nt)
    626       ;; On w32, git expects UTF-8 encoded input, ignore any user
    627       ;; configuration telling us otherwise.
    628       (set-process-coding-system process nil 'utf-8-unix))
    629     (process-put process 'section section)
    630     (process-put process 'command-buf (current-buffer))
    631     (process-put process 'default-dir default-directory)
    632     (when magit-inhibit-refresh
    633       (process-put process 'inhibit-refresh t))
    634     (oset section process process)
    635     (with-current-buffer process-buf
    636       (set-marker (process-mark process) (point)))
    637     (when input
    638       (with-current-buffer input
    639         (process-send-region process (point-min) (point-max))
    640         ;; `process-send-eof' appears to be broken over
    641         ;;  Tramp from Windows. See #3624 and bug#43226.
    642         (if (and (eq system-type 'windows-nt)
    643                  (file-remote-p (process-get process 'default-dir) nil t))
    644             (process-send-string process "")
    645           (process-send-eof process))))
    646     (setq magit-this-process process)
    647     (oset section value process)
    648     (magit-process-display-buffer process)
    649     process))
    650 
    651 (defun magit-parse-git-async (&rest args)
    652   (setq args (magit-process-git-arguments args))
    653   (let ((command-buf (current-buffer))
    654         (stdout-buf (generate-new-buffer " *git-stdout*"))
    655         (stderr-buf (generate-new-buffer " *git-stderr*"))
    656         (toplevel (magit-toplevel)))
    657     (with-current-buffer stdout-buf
    658       (setq default-directory toplevel)
    659       (let ((process
    660              (let ((process-environment (magit-process-environment)))
    661                (make-process :name "git"
    662                              :buffer stdout-buf
    663                              :stderr stderr-buf
    664                              :command (cons (magit-git-executable) args)
    665                              :coding (magit--process-coding-system)
    666                              :file-handler t))))
    667         (process-put process 'command-buf command-buf)
    668         (process-put process 'stderr-buf stderr-buf)
    669         (process-put process 'parsed (point))
    670         (setq magit-this-process process)
    671         process))))
    672 
    673 ;;; Process Internals
    674 
    675 (defclass magit-process-section (magit-section)
    676   ((process :initform nil)))
    677 
    678 (setf (alist-get 'process magit--section-type-alist) 'magit-process-section)
    679 
    680 (defun magit-process-setup (program args)
    681   (magit-process-set-mode-line program args)
    682   (let ((pwd default-directory)
    683         (buf (magit-process-buffer t)))
    684     (cons buf (with-current-buffer buf
    685                 (prog1 (magit-process-insert-section pwd program args nil nil)
    686                   (backward-char 1))))))
    687 
    688 (defun magit-process-insert-section (pwd program args &optional errcode errlog)
    689   (let ((inhibit-read-only t)
    690         (magit-insert-section--parent magit-root-section)
    691         (magit-insert-section--oldroot nil))
    692     (goto-char (1- (point-max)))
    693     (magit-insert-section (process)
    694       (insert (if errcode
    695                   (format "%3s " (propertize (number-to-string errcode)
    696                                              'font-lock-face 'magit-process-ng))
    697                 "run "))
    698       (when magit-process-timestamp-format
    699         (insert (format-time-string magit-process-timestamp-format) " "))
    700       (unless (equal (expand-file-name pwd)
    701                      (expand-file-name default-directory))
    702         (insert (file-relative-name pwd default-directory) ?\s))
    703       (insert (magit-process--format-arguments program args))
    704       (magit-insert-heading)
    705       (when errlog
    706         (if (bufferp errlog)
    707             (insert (with-current-buffer errlog
    708                       (buffer-substring-no-properties (point-min) (point-max))))
    709           (insert-file-contents errlog)
    710           (goto-char (1- (point-max)))))
    711       (insert "\n"))))
    712 
    713 (defun magit-process--format-arguments (program args)
    714   (cond
    715    ((and args (equal program (magit-git-executable)))
    716     (let ((global (length magit-git-global-arguments)))
    717       (concat
    718        (propertize (file-name-nondirectory program)
    719                    'font-lock-face 'magit-section-heading)
    720        " "
    721        (propertize (magit--ellipsis)
    722                    'font-lock-face 'magit-section-heading
    723                    'help-echo (string-join (seq-take args global) " "))
    724        " "
    725        (propertize (mapconcat #'shell-quote-argument (seq-drop args global) " ")
    726                    'font-lock-face 'magit-section-heading))))
    727    ((and args (equal program shell-file-name))
    728     (propertize (cadr args)
    729                 'font-lock-face 'magit-section-heading))
    730    (t
    731     (concat (propertize (file-name-nondirectory program)
    732                         'font-lock-face 'magit-section-heading)
    733             " "
    734             (propertize (mapconcat #'shell-quote-argument args " ")
    735                         'font-lock-face 'magit-section-heading)))))
    736 
    737 (defun magit-process-truncate-log ()
    738   (let* ((head nil)
    739          (tail (oref magit-root-section children))
    740          (count (length tail)))
    741     (when (> (1+ count) magit-process-log-max)
    742       (while (and (cdr tail)
    743                   (> count (/ magit-process-log-max 2)))
    744         (let* ((inhibit-read-only t)
    745                (section (car tail))
    746                (process (oref section process)))
    747           (cond ((not process))
    748                 ((memq (process-status process) '(exit signal))
    749                  (delete-region (oref section start)
    750                                 (1+ (oref section end)))
    751                  (cl-decf count))
    752                 (t
    753                  (push section head))))
    754         (pop tail))
    755       (oset magit-root-section children
    756             (nconc (reverse head) tail)))))
    757 
    758 (defun magit-process-sentinel (process event)
    759   "Default sentinel used by `magit-start-process'."
    760   (when (memq (process-status process) '(exit signal))
    761     (setq event (substring event 0 -1))
    762     (when (string-match "^finished" event)
    763       (message (concat (capitalize (process-name process)) " finished")))
    764     (magit-process-finish process)
    765     (when (eq process magit-this-process)
    766       (setq magit-this-process nil))
    767     (unless (process-get process 'inhibit-refresh)
    768       (let ((command-buf (process-get process 'command-buf)))
    769         (if (buffer-live-p command-buf)
    770             (with-current-buffer command-buf
    771               (magit-refresh))
    772           (with-temp-buffer
    773             (setq default-directory (process-get process 'default-dir))
    774             (magit-refresh)))))))
    775 
    776 (defun magit-sequencer-process-sentinel (process event)
    777   "Special sentinel used by `magit-run-git-sequencer'."
    778   (when (memq (process-status process) '(exit signal))
    779     (magit-process-sentinel process event)
    780     (when-let* ((process-buf (process-buffer process))
    781                 ((buffer-live-p process-buf))
    782                 (status-buf (with-current-buffer process-buf
    783                               (magit-get-mode-buffer 'magit-status-mode))))
    784       (with-current-buffer status-buf
    785         (when-let ((section
    786                     (magit-get-section
    787                      `((commit . ,(magit-rev-parse "HEAD"))
    788                        (,(pcase (car (seq-drop
    789                                       (process-command process)
    790                                       (1+ (length magit-git-global-arguments))))
    791                            ((or "rebase" "am") 'rebase-sequence)
    792                            ((or "cherry-pick" "revert") 'sequence)))
    793                        (status)))))
    794           (goto-char (oref section start))
    795           (magit-section-update-highlight))))))
    796 
    797 (defun magit-process-filter (proc string)
    798   "Default filter used by `magit-start-process'."
    799   (with-current-buffer (process-buffer proc)
    800     (let ((inhibit-read-only t))
    801       (goto-char (process-mark proc))
    802       ;; Find last ^M in string.  If one was found, ignore
    803       ;; everything before it and delete the current line.
    804       (when-let ((ret-pos (cl-position ?\r string :from-end t)))
    805         (cl-callf substring string (1+ ret-pos))
    806         (delete-region (line-beginning-position) (point)))
    807       (setq string (magit-process-remove-bogus-errors string))
    808       (insert (propertize string 'magit-section
    809                           (process-get proc 'section)))
    810       (set-marker (process-mark proc) (point))
    811       ;; Make sure prompts are matched after removing ^M.
    812       (magit-process-yes-or-no-prompt proc string)
    813       (magit-process-username-prompt  proc string)
    814       (magit-process-password-prompt  proc string)
    815       (run-hook-with-args-until-success 'magit-process-prompt-functions
    816                                         proc string))))
    817 
    818 (defun magit-process-make-keymap (process parent)
    819   "Remap `abort-minibuffers' to a command that also kills PROCESS.
    820 PARENT is used as the parent of the returned keymap."
    821   (let ((cmd (lambda ()
    822                (interactive)
    823                (ignore-errors (kill-process process))
    824                (if (fboundp 'abort-minibuffers)
    825                    (abort-minibuffers)
    826                  (abort-recursive-edit)))))
    827     (define-keymap :parent parent
    828       "C-g" cmd
    829       "<remap> <abort-minibuffers>" cmd
    830       "<remap> <abort-recursive-edit>" cmd)))
    831 
    832 (defmacro magit-process-kill-on-abort (process &rest body)
    833   (declare (indent 1)
    834            (debug (form body))
    835            (obsolete magit-process-make-keymap "Magit 4.0.0"))
    836   `(let ((minibuffer-local-map
    837           (magit-process-make-keymap ,process minibuffer-local-map)))
    838      ,@body))
    839 
    840 (defun magit-process-remove-bogus-errors (str)
    841   (save-match-data
    842     (when (string-match "^\\(\\*ERROR\\*: \\)Canceled by user" str)
    843       (setq str (replace-match "" nil nil str 1)))
    844     (when (string-match "^error: There was a problem with the editor.*\n" str)
    845       (setq str (replace-match "" nil nil str)))
    846     (when (string-match
    847            "^Please supply the message using either -m or -F option\\.\n" str)
    848       (setq str (replace-match "" nil nil str))))
    849   str)
    850 
    851 (defun magit-process-yes-or-no-prompt (process string)
    852   "Forward Yes-or-No prompts to the user."
    853   (when-let ((beg (string-match magit-process-yes-or-no-prompt-regexp string)))
    854     (process-send-string
    855      process
    856      (if (save-match-data
    857            (let ((max-mini-window-height 30)
    858                  (minibuffer-local-map
    859                   (magit-process-make-keymap process minibuffer-local-map))
    860                  ;; In case yes-or-no-p is fset to that, but does
    861                  ;; not cover use-dialog-box-p and y-or-n-p-read-key.
    862                  (y-or-n-p-map
    863                   (magit-process-make-keymap process y-or-n-p-map)))
    864              (yes-or-no-p (substring string 0 beg))))
    865          (concat (downcase (match-string 1 string)) "\n")
    866        (concat (downcase (match-string 2 string)) "\n")))))
    867 
    868 (defun magit-process-password-auth-source (key)
    869   "Use `auth-source-search' to get a password.
    870 If found, return the password.  Otherwise, return nil.
    871 
    872 To use this function add it to the appropriate hook
    873   (add-hook \\='magit-process-find-password-functions
    874             \\='magit-process-password-auth-source)
    875 
    876 KEY typically derives from a prompt such as:
    877   Password for \\='https://yourname@github.com\\='
    878 in which case it would be the string
    879   yourname@github.com
    880 which matches the ~/.authinfo.gpg entry
    881   machine github.com login yourname password 12345
    882 or iff that is undefined, for backward compatibility
    883   machine yourname@github.com password 12345
    884 
    885 On github.com you should not use your password but a
    886 personal access token, see [1].  For information about
    887 the peculiarities of other forges, please consult the
    888 respective documentation.
    889 
    890 After manually editing ~/.authinfo.gpg you must reset
    891 the cache using
    892   M-x auth-source-forget-all-cached RET
    893 
    894 The above will save you from having to repeatedly type
    895 your token or password, but you might still repeatedly
    896 be asked for your username.  To prevent that, change an
    897 URL like
    898   https://github.com/foo/bar.git
    899 to
    900   https://yourname@github.com/foo/bar.git
    901 
    902 Instead of changing all such URLs manually, they can
    903 be translated on the fly by doing this once
    904   git config --global \
    905     url.https://yourname@github.com.insteadOf \
    906     https://github.com
    907 
    908 [1]: https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token."
    909   (require 'auth-source)
    910   (and (fboundp 'auth-source-search)
    911        (string-match "\\`\\(.+\\)@\\([^@]+\\)\\'" key)
    912        (let* ((user (match-string 1 key))
    913               (host (match-string 2 key))
    914               (secret
    915                (plist-get
    916                 (car (or (auth-source-search :max 1 :host host :user user)
    917                          (auth-source-search :max 1 :host key)))
    918                 :secret)))
    919          (if (functionp secret)
    920              (funcall secret)
    921            secret))))
    922 
    923 (defun magit-process-git-credential-manager-core (process string)
    924   "Authenticate using `git-credential-manager-core'.
    925 
    926 To use this function add it to the appropriate hook
    927   (add-hook \\='magit-process-prompt-functions
    928             \\='magit-process-git-credential-manager-core)"
    929   (and (string-match "^option (enter for default): $" string)
    930        (progn
    931          (magit-process-buffer)
    932          (let ((option (format "%c\n"
    933                                (read-char-choice "Option: " '(?\r ?\j ?1 ?2)))))
    934            (insert-before-markers-and-inherit option)
    935            (process-send-string process option)))))
    936 
    937 (defun magit-process-password-prompt (process string)
    938   "Find a password based on prompt STRING and send it to git.
    939 Use `magit-process-password-prompt-regexps' to find a known
    940 prompt.  If and only if one is found, then call functions in
    941 `magit-process-find-password-functions' until one of them returns
    942 the password.  If all functions return nil, then read the password
    943 from the user."
    944   (when-let ((prompt (magit-process-match-prompt
    945                       magit-process-password-prompt-regexps string)))
    946     (process-send-string
    947      process
    948      (concat (or (and-let* ((key (match-string 99 string)))
    949                    (run-hook-with-args-until-success
    950                     'magit-process-find-password-functions key))
    951                  (let ((read-passwd-map
    952                         (magit-process-make-keymap process read-passwd-map)))
    953                    (read-passwd prompt)))
    954              "\n"))))
    955 
    956 (defun magit-process-username-prompt (process string)
    957   "Forward username prompts to the user."
    958   (when-let ((prompt (magit-process-match-prompt
    959                       magit-process-username-prompt-regexps string)))
    960     (process-send-string
    961      process
    962      (let ((minibuffer-local-map
    963             (magit-process-make-keymap process minibuffer-local-map)))
    964        (concat (read-string prompt nil nil (user-login-name)) "\n")))))
    965 
    966 (defun magit-process-match-prompt (prompts string)
    967   "Match STRING against PROMPTS and set match data.
    968 Return the matched string suffixed with \": \", if needed."
    969   (when (--any-p (string-match it string) prompts)
    970     (let ((prompt (match-string 0 string)))
    971       (cond ((string-suffix-p ": " prompt) prompt)
    972             ((string-suffix-p ":"  prompt) (concat prompt " "))
    973             (t                             (concat prompt ": "))))))
    974 
    975 (defun magit--process-coding-system ()
    976   (let ((fro (or magit-git-output-coding-system
    977                  (car default-process-coding-system)))
    978         (to (cdr default-process-coding-system)))
    979     (if magit-process-ensure-unix-line-ending
    980         (cons (coding-system-change-eol-conversion fro 'unix)
    981               (coding-system-change-eol-conversion to 'unix))
    982       (cons fro to))))
    983 
    984 (defvar magit-credential-hook nil
    985   "Hook run before Git needs credentials.")
    986 
    987 (defvar magit-credential-cache-daemon-process nil)
    988 
    989 (defun magit-maybe-start-credential-cache-daemon ()
    990   "Maybe start a `git-credential-cache--daemon' process.
    991 
    992 If such a process is already running or if the value of option
    993 `magit-credential-cache-daemon-socket' is nil, then do nothing.
    994 Otherwise start the process passing the value of that options
    995 as argument."
    996   (unless (or (not magit-credential-cache-daemon-socket)
    997               (process-live-p magit-credential-cache-daemon-process)
    998               (memq magit-credential-cache-daemon-process
    999                     (list-system-processes)))
   1000     (setq magit-credential-cache-daemon-process
   1001           (or (--first (let* ((attr (process-attributes it))
   1002                               (comm (cdr (assq 'comm attr)))
   1003                               (user (cdr (assq 'user attr))))
   1004                          (and (string= comm "git-credential-cache--daemon")
   1005                               (string= user user-login-name)))
   1006                        (list-system-processes))
   1007               (condition-case nil
   1008                   (start-process "git-credential-cache--daemon"
   1009                                  " *git-credential-cache--daemon*"
   1010                                  (magit-git-executable)
   1011                                  "credential-cache--daemon"
   1012                                  magit-credential-cache-daemon-socket)
   1013                 ;; Some Git implementations (e.g., Windows) won't have
   1014                 ;; this program; if we fail the first time, stop trying.
   1015                 ((debug error)
   1016                  (remove-hook 'magit-credential-hook
   1017                               #'magit-maybe-start-credential-cache-daemon)))))))
   1018 
   1019 (add-hook 'magit-credential-hook #'magit-maybe-start-credential-cache-daemon)
   1020 
   1021 (defvar-keymap magit-mode-line-process-map
   1022   :doc "Keymap for `mode-line-process'."
   1023   "<mode-line> <mouse-1>" 'magit-process-buffer)
   1024 
   1025 (defun magit-process-set-mode-line (program args)
   1026   "Display the git command (sans arguments) in the mode line."
   1027   (when (equal program (magit-git-executable))
   1028     (setq args (nthcdr (length magit-git-global-arguments) args)))
   1029   (let ((str (concat " " (propertize
   1030                           (concat (file-name-nondirectory program)
   1031                                   (and args (concat " " (car args))))
   1032                           'mouse-face 'highlight
   1033                           'keymap magit-mode-line-process-map
   1034                           'help-echo "mouse-1: Show process buffer"
   1035                           'font-lock-face 'magit-mode-line-process))))
   1036     (magit-repository-local-set 'mode-line-process str)
   1037     (dolist (buf (magit-mode-get-buffers))
   1038       (with-current-buffer buf
   1039         (setq mode-line-process str)))
   1040     (force-mode-line-update t)))
   1041 
   1042 (defun magit-process-set-mode-line-error-status (&optional error str)
   1043   "Apply an error face to the string set by `magit-process-set-mode-line'.
   1044 
   1045 If ERROR is supplied, include it in the `mode-line-process' tooltip.
   1046 
   1047 If STR is supplied, it replaces the `mode-line-process' text."
   1048   (setq str (or str (magit-repository-local-get 'mode-line-process)))
   1049   (when str
   1050     (setq error (format "%smouse-1: Show process buffer"
   1051                         (if (stringp error)
   1052                             (concat error "\n\n")
   1053                           "")))
   1054     (setq str (concat " " (propertize
   1055                            (substring-no-properties str 1)
   1056                            'mouse-face 'highlight
   1057                            'keymap magit-mode-line-process-map
   1058                            'help-echo error
   1059                            'font-lock-face 'magit-mode-line-process-error)))
   1060     (magit-repository-local-set 'mode-line-process str)
   1061     (dolist (buf (magit-mode-get-buffers))
   1062       (with-current-buffer buf
   1063         (setq mode-line-process str)))
   1064     (force-mode-line-update t)
   1065     ;; We remove any error status from the mode line when a magit
   1066     ;; buffer is refreshed (see `magit-refresh-buffer'), but we must
   1067     ;; ensure that we ignore any refreshes during the remainder of the
   1068     ;; current command -- otherwise a newly-set error status would be
   1069     ;; removed before it was seen.  We set a flag which prevents the
   1070     ;; status from being removed prior to the next command, so that
   1071     ;; the error status is guaranteed to remain visible until then.
   1072     (let ((repokey (magit-repository-local-repository)))
   1073       ;; The following closure captures the repokey value, and is
   1074       ;; added to `pre-command-hook'.
   1075       (cl-labels ((enable-magit-process-unset-mode-line ()
   1076                     ;; Remove ourself from the hook variable, so
   1077                     ;; that we only run once.
   1078                     (remove-hook 'pre-command-hook
   1079                                  #'enable-magit-process-unset-mode-line)
   1080                     ;; Clear the inhibit flag for the repository in
   1081                     ;; which we set it.
   1082                     (magit-repository-local-set
   1083                      'inhibit-magit-process-unset-mode-line nil repokey)))
   1084         ;; Set the inhibit flag until the next command is invoked.
   1085         (magit-repository-local-set
   1086          'inhibit-magit-process-unset-mode-line t repokey)
   1087         (add-hook 'pre-command-hook
   1088                   #'enable-magit-process-unset-mode-line)))))
   1089 
   1090 (defun magit-process-unset-mode-line-error-status ()
   1091   "Remove any current error status from the mode line."
   1092   (let ((status (or mode-line-process
   1093                     (magit-repository-local-get 'mode-line-process))))
   1094     (when (and status
   1095                (eq (get-text-property 1 'font-lock-face status)
   1096                    'magit-mode-line-process-error))
   1097       (magit-process-unset-mode-line))))
   1098 
   1099 (add-hook 'magit-refresh-buffer-hook
   1100           #'magit-process-unset-mode-line-error-status)
   1101 
   1102 (defun magit-process-unset-mode-line (&optional directory)
   1103   "Remove the git command from the mode line."
   1104   (let ((default-directory (or directory default-directory)))
   1105     (unless (magit-repository-local-get 'inhibit-magit-process-unset-mode-line)
   1106       (magit-repository-local-set 'mode-line-process nil)
   1107       (dolist (buf (magit-mode-get-buffers))
   1108         (with-current-buffer buf (setq mode-line-process nil)))
   1109       (force-mode-line-update t))))
   1110 
   1111 (defvar magit-process-error-message-regexps
   1112   (list "^\\*ERROR\\*: Canceled by user$"
   1113         "^\\(?:error\\|fatal\\|git\\): \\(.*\\)$"
   1114         "^\\(Cannot rebase:.*\\)$"))
   1115 
   1116 (define-error 'magit-git-error "Git error")
   1117 
   1118 (defun magit-process-error-summary (process-buf section)
   1119   "A one-line error summary from the given SECTION."
   1120   (or (and (buffer-live-p process-buf)
   1121            (with-current-buffer process-buf
   1122              (and (oref section content)
   1123                   (save-excursion
   1124                     (goto-char (oref section end))
   1125                     (run-hook-wrapped
   1126                      'magit-process-error-message-regexps
   1127                      (lambda (re)
   1128                        (save-excursion
   1129                          (and (re-search-backward
   1130                                re (oref section start) t)
   1131                               (or (match-string-no-properties 1)
   1132                                   (and (not magit-process-raise-error)
   1133                                        'suppressed))))))))))
   1134       "Git failed"))
   1135 
   1136 (defun magit-process-error-tooltip (process-buf section)
   1137   "Returns the text from SECTION of the PROCESS-BUF buffer.
   1138 
   1139 Limited by `magit-process-error-tooltip-max-lines'."
   1140   (and (integerp magit-process-error-tooltip-max-lines)
   1141        (> magit-process-error-tooltip-max-lines 0)
   1142        (buffer-live-p process-buf)
   1143        (with-current-buffer process-buf
   1144          (save-excursion
   1145            (goto-char (or (oref section content)
   1146                           (oref section start)))
   1147            (buffer-substring-no-properties
   1148             (point)
   1149             (save-excursion
   1150               (forward-line magit-process-error-tooltip-max-lines)
   1151               (goto-char
   1152                (if (> (point) (oref section end))
   1153                    (oref section end)
   1154                  (point)))
   1155               ;; Remove any trailing whitespace.
   1156               (when (re-search-backward "[^[:space:]\n]"
   1157                                         (oref section start) t)
   1158                 (forward-char 1))
   1159               (point)))))))
   1160 
   1161 (defvar-local magit-this-error nil)
   1162 
   1163 (defvar magit-process-finish-apply-ansi-colors nil)
   1164 
   1165 (defun magit-process-finish (arg &optional process-buf command-buf
   1166                                  default-dir section)
   1167   (unless (integerp arg)
   1168     (setq process-buf (process-buffer arg))
   1169     (setq command-buf (process-get arg 'command-buf))
   1170     (setq default-dir (process-get arg 'default-dir))
   1171     (setq section     (process-get arg 'section))
   1172     (setq arg         (process-exit-status arg)))
   1173   (when (fboundp 'dired-uncache)
   1174     (dired-uncache default-dir))
   1175   (when (buffer-live-p process-buf)
   1176     (with-current-buffer process-buf
   1177       (let ((inhibit-read-only t)
   1178             (marker (oref section start)))
   1179         (goto-char marker)
   1180         (save-excursion
   1181           (delete-char 3)
   1182           (set-marker-insertion-type marker nil)
   1183           (insert (propertize (format "%3s" arg)
   1184                               'magit-section section
   1185                               'font-lock-face (if (= arg 0)
   1186                                                   'magit-process-ok
   1187                                                 'magit-process-ng)))
   1188           (set-marker-insertion-type marker t))
   1189         (when magit-process-finish-apply-ansi-colors
   1190           (ansi-color-apply-on-region (oref section content)
   1191                                       (oref section end)))
   1192         (if (= (oref section end)
   1193                (+ (line-end-position) 2))
   1194             (save-excursion
   1195               (goto-char (1+ (line-end-position)))
   1196               (delete-char -1)
   1197               (oset section content nil))
   1198           (when (and (= arg 0)
   1199                      (not (--any-p (eq (window-buffer it) process-buf)
   1200                                    (window-list))))
   1201             (magit-section-hide section))))))
   1202   (if (= arg 0)
   1203       ;; Unset the `mode-line-process' value upon success.
   1204       (magit-process-unset-mode-line default-dir)
   1205     ;; Otherwise process the error.
   1206     (let ((msg (magit-process-error-summary process-buf section)))
   1207       ;; Change `mode-line-process' to an error face upon failure.
   1208       (if magit-process-display-mode-line-error
   1209           (magit-process-set-mode-line-error-status
   1210            (or (magit-process-error-tooltip process-buf section)
   1211                msg))
   1212         (magit-process-unset-mode-line default-dir))
   1213       ;; Either signal the error, or else display the error summary in
   1214       ;; the status buffer and with a message in the echo area.
   1215       (cond
   1216        (magit-process-raise-error
   1217         (signal 'magit-git-error (list (format "%s (in %s)" msg default-dir))))
   1218        ((not (eq msg 'suppressed))
   1219         (when (buffer-live-p process-buf)
   1220           (with-current-buffer process-buf
   1221             (when-let ((status-buf (magit-get-mode-buffer 'magit-status-mode)))
   1222               (with-current-buffer status-buf
   1223                 (setq magit-this-error msg)))))
   1224         (message "%s ... [%s buffer %s for details]" msg
   1225                  (if-let ((key (and (buffer-live-p command-buf)
   1226                                     (with-current-buffer command-buf
   1227                                       (car (where-is-internal
   1228                                             'magit-process-buffer))))))
   1229                      (format "Hit %s to see" (key-description key))
   1230                    "See")
   1231                  (buffer-name process-buf))))))
   1232   arg)
   1233 
   1234 (defun magit-process-display-buffer (process)
   1235   (when (process-live-p process)
   1236     (let ((buf (process-buffer process)))
   1237       (cond ((not (buffer-live-p buf)))
   1238             ((= magit-process-popup-time 0)
   1239              (if (minibufferp)
   1240                  (switch-to-buffer-other-window buf)
   1241                (pop-to-buffer buf)))
   1242             ((> magit-process-popup-time 0)
   1243              (run-with-timer magit-process-popup-time nil
   1244                              (lambda (p)
   1245                                (when (eq (process-status p) 'run)
   1246                                  (let ((buf (process-buffer p)))
   1247                                    (when (buffer-live-p buf)
   1248                                      (if (minibufferp)
   1249                                          (switch-to-buffer-other-window buf)
   1250                                        (pop-to-buffer buf))))))
   1251                              process))))))
   1252 
   1253 (defun magit--log-action (summary line list)
   1254   (let (heading lines)
   1255     (if (cdr list)
   1256         (progn (setq heading (funcall summary list))
   1257                (setq lines (mapcar line list)))
   1258       (setq heading (funcall line (car list))))
   1259     (with-current-buffer (magit-process-buffer t)
   1260       (goto-char (1- (point-max)))
   1261       (let ((inhibit-read-only t))
   1262         (magit-insert-section (message)
   1263           (magit-insert-heading (concat "  * " heading))
   1264           (when lines
   1265             (dolist (line lines)
   1266               (insert line "\n"))
   1267             (insert "\n"))))
   1268       (let ((inhibit-message t))
   1269         (when heading
   1270           (setq lines (cons heading lines)))
   1271         (message (string-join lines "\n"))))))
   1272 
   1273 ;;; _
   1274 (provide 'magit-process)
   1275 ;;; magit-process.el ends here