magit-git.el 87.6 KB
Newer Older
1
;;; magit-git.el --- Git functionality  -*- lexical-binding: t -*-
2

Jonas Bernoulli's avatar
Jonas Bernoulli committed
3
;; Copyright (C) 2010-2018  The Magit Project Contributors
4
;;
5 6
;; You should have received a copy of the AUTHORS.md file which
;; lists all contributors.  If not, see http://magit.vc/authors.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

;; Author: Jonas Bernoulli <jonas@bernoul.li>
;; Maintainer: Jonas Bernoulli <jonas@bernoul.li>

;; Magit is free software; you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;;
;; Magit is distributed in the hope that it will be useful, but WITHOUT
;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
;; or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
;; License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with Magit.  If not, see http://www.gnu.org/licenses.

24 25 26 27
;;; Commentary:

;; This library implements wrappers for various Git plumbing commands.

28 29 30 31 32
;;; Code:

(require 'cl-lib)
(require 'dash)

33
(require 'magit-popup)
34 35 36
(require 'magit-utils)
(require 'magit-section)

37 38 39 40 41 42 43
(declare-function magit-call-git "magit-process" (&rest args))
(declare-function magit-maybe-make-margin-overlay "magit-margin" ())
(declare-function magit-process-buffer "magit-process" (&optional nodisplay))
(declare-function magit-process-file "magit-process" (&rest args))
(declare-function magit-process-insert-section "magit-process"
                  (pwe program args &optional errcode errlog))
(declare-function magit-refresh "magit-mode" ())
44
(defvar magit-process-error-message-regexps)
45
(defvar magit-refresh-args) ; from `magit-mode' for `magit-current-file'
46
(defvar magit-branch-prefer-remote-upstream)
Jonas Bernoulli's avatar
Jonas Bernoulli committed
47
(defvar magit-published-branches)
48

49 50
(defvar magit-tramp-process-environment nil)

51 52 53 54 55 56 57
;;; Options

;; For now this is shared between `magit-process' and `magit-git'.
(defgroup magit-process nil
  "Git and other external processes used by Magit."
  :group 'magit)

58 59
(defvar magit-git-environment
  (list (format "INSIDE_EMACS=%s,magit" emacs-version))
60 61
  "Prepended to `process-environment' while running git.")

62 63 64 65 66 67 68 69 70 71 72 73
(defcustom magit-git-output-coding-system
  (and (eq system-type 'windows-nt) 'utf-8)
  "Coding system for receiving output from Git.

If non-nil, the Git config value `i18n.logOutputEncoding' should
be set via `magit-git-global-arguments' to value consistent with
this."
  :package-version '(magit . "2.9.0")
  :group 'magit-process
  :type '(choice (coding-system :tag "Coding system to decode Git output")
                 (const :tag "Use system default" nil)))

74 75 76 77 78 79
(defvar magit-git-w32-path-hack nil
  "Alist of (EXE . (PATHENTRY)).
This specifies what additional PATH setting needs to be added to
the environment in order to run the non-wrapper git executables
successfully.")

80
(defcustom magit-git-executable
81 82 83 84 85
  ;; Git might be installed in a different location on a remote, so
  ;; it is better not to use the full path to the executable, except
  ;; on Window were we would otherwise end up using one one of the
  ;; wrappers "cmd/git.exe" or "cmd/git.cmd", which are much slower
  ;; than using "bin/git.exe" directly.
86
  (or (and (eq system-type 'windows-nt)
87
           (--when-let (executable-find "git")
88 89 90 91 92 93
             (or (ignore-errors
                   ;; Git for Windows 2.x provides cygpath so we can
                   ;; ask it for native paths.  Using an upper case
                   ;; alias makes this fail on 1.x (which is good,
                   ;; because we would not want to end up using some
                   ;; other cygpath).
94 95 96 97 98 99 100 101 102 103 104
                   (let* ((core-exe
                           (car
                            (process-lines
                             it "-c"
                             "alias.X=!x() { which \"$1\" | cygpath -mf -; }; x"
                             "X" "git")))
                          (hack-entry (assoc core-exe magit-git-w32-path-hack))
                          ;; Running the libexec/git-core executable
                          ;; requires some extra PATH entries.
                          (path-hack
                           (list (concat "PATH="
105 106 107
                                         (car (process-lines
                                               it "-c"
                                               "alias.P=!cygpath -wp \"$PATH\""
108 109 110 111 112 113 114 115
                                               "P"))))))
                     ;; The defcustom STANDARD expression can be
                     ;; evaluated many times, so make sure it is
                     ;; idempotent.
                     (if hack-entry
                         (setcdr hack-entry path-hack)
                       (push (cons core-exe path-hack) magit-git-w32-path-hack))
                     core-exe))
116
                 ;; For 1.x, we search for bin/ next to cmd/.
117 118 119 120 121 122 123 124
                 (let ((alt (directory-file-name (file-name-directory it))))
                   (if (and (equal (file-name-nondirectory alt) "cmd")
                            (setq alt (expand-file-name
                                       (convert-standard-filename "bin/git.exe")
                                       (file-name-directory alt)))
                            (file-executable-p alt))
                       alt
                     it)))))
125 126 127 128 129
      "git")
  "The Git executable used by Magit."
  :group 'magit-process
  :type 'string)

130
(defcustom magit-git-global-arguments
131
  `("--no-pager" "--literal-pathspecs" "-c" "core.preloadindex=true"
132
    "-c" "log.showSignature=false"
133 134
    ,@(and (eq system-type 'windows-nt)
           (list "-c" "i18n.logOutputEncoding=UTF-8")))
135
  "Global Git arguments.
136 137 138 139 140 141 142 143 144 145 146 147

The arguments set here are used every time the git executable is
run as a subprocess.  They are placed right after the executable
itself and before the git command - as in `git HERE... COMMAND
REST'.  See the manpage `git(1)' for valid arguments.

Be careful what you add here, especially if you are using Tramp
to connect to servers with ancient Git versions.  Never remove
anything that is part of the default value, unless you really
know what you are doing.  And think very hard before adding
something; it will be used every time Magit runs Git for any
purpose."
148
  :package-version '(magit . "2.9.0")
149
  :group 'magit-git-arguments
150
  :group 'magit-process
151 152
  :type '(repeat string))

153
(defvar magit-git-debug nil
154
  "Whether to enable additional reporting of git errors.
155

156
Magit basically calls git for one of these two reasons: for
157 158
side-effects or to do something with its standard output.

159
When git is run for side-effects then its output, including error
160
messages, go into the process buffer which is shown when using \
161 162
\\<magit-status-mode-map>\\[magit-process].

163
When git's output is consumed in some way, then it would be too
164
expensive to also insert it into this buffer, but when this
165 166 167 168
option is non-nil and git returns with a non-zero exit status,
then at least its standard error is inserted into this buffer.

This is only intended for debugging purposes.  Do not enable this
169
permanently, that would negatively affect performance.")
170

171

172 173 174 175 176 177 178 179 180 181 182 183 184 185
(defcustom magit-prefer-remote-upstream nil
  "Whether to favor remote branches when reading the upstream branch.

This controls whether commands that read a branch from the user
and then set it as the upstream branch, offer a local or a remote
branch as default completion candidate, when they have the choice.

This affects all commands that use `magit-read-upstream-branch'
or `magit-read-starting-point', which includes all commands that
change the upstream and many which create new branches."
  :package-version '(magit . "2.4.2")
  :group 'magit-commands
  :type 'boolean)

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
(defcustom magit-list-refs-sortby nil
  "How to sort the ref collection in the prompt.

This affects commands that read a ref.  More specifically, it
controls the order of refs returned by `magit-list-refs', which
is called by functions like `magit-list-branch-names' to generate
the collection of refs.  By default, refs are sorted according to
their full refname (i.e., 'refs/...').

Any value accepted by the `--sort' flag of `git for-each-ref' can
be used.  For example, \"-creatordate\" places refs with more
recent committer or tagger dates earlier in the list.  A list of
strings can also be given in order to pass multiple sort keys to
`git for-each-ref'.

Note that, depending on the completion framework you use, this
may not be sufficient to change the order in which the refs are
displayed.  It only controls the order of the collection passed
to `magit-completing-read' or, for commands that support reading
multiple strings, `read-from-minibuffer'.  The completion
framework ultimately determines how the collection is displayed."
207
  :package-version '(magit . "2.11.0")
208 209 210
  :group 'magit-miscellanous
  :type '(choice string (repeat string)))

211 212
;;; Git

213 214 215
(defvar magit--refresh-cache nil)

(defmacro magit--with-refresh-cache (key &rest body)
216
  (declare (indent 1) (debug (form body)))
217 218 219 220 221 222 223 224 225 226 227 228 229
  (let ((k (cl-gensym)))
    `(if magit--refresh-cache
         (let ((,k ,key))
           (--if-let (assoc ,k (cdr magit--refresh-cache))
               (progn (cl-incf (caar magit--refresh-cache))
                      (cdr it))
             (cl-incf (cdar magit--refresh-cache))
             (let ((value ,(macroexp-progn body)))
               (push (cons ,k value)
                     (cdr magit--refresh-cache))
               value)))
       ,@body)))

230 231 232 233
(defmacro magit-with-editor (&rest body)
  "Like `with-editor' but let-bind some more variables."
  (declare (indent 0) (debug (body)))
  `(let ((magit-process-popup-time -1)
234 235 236 237 238 239
         ;; The user may have customized `shell-file-name' to
         ;; something which results in `w32-shell-dos-semantics' nil
         ;; (which changes the quoting style used by
         ;; `shell-quote-argument'), but Git for Windows expects shell
         ;; quoting in the dos style.
         (shell-file-name (if (and (eq system-type 'windows-nt)
240
                                   ;; If we have Cygwin mount points,
241 242 243 244 245
                                   ;; the git flavor is cygwin, so dos
                                   ;; shell quoting is probably wrong.
                                   (not magit-cygwin-mount-points))
                              "cmdproxy"
                            shell-file-name)))
246 247 248
     (with-editor "GIT_EDITOR"
       ,@body)))

249
(defun magit-process-git-arguments (args)
250 251 252 253 254 255 256
  "Prepare ARGS for a function that invokes Git.

Magit has many specialized functions for running Git; they all
pass arguments through this function before handing them to Git,
to do the following.

* Flatten ARGS, removing nil arguments.
257 258 259 260 261 262 263 264 265 266 267
* Prepend `magit-git-global-arguments' to ARGS.
* On w32 systems, encode to `w32-ansi-code-page'."
  (setq args (append magit-git-global-arguments (-flatten args)))
  (if (and (eq system-type 'windows-nt) (boundp 'w32-ansi-code-page))
      ;; On w32, the process arguments *must* be encoded in the
      ;; current code-page (see #3250).
      (mapcar (lambda (arg)
                (encode-coding-string
                 arg (intern (format "cp%d" w32-ansi-code-page))))
              args)
    args))
268 269 270

(defun magit-git-exit-code (&rest args)
  "Execute Git with ARGS, returning its exit code."
271
  (apply #'magit-process-file magit-git-executable nil nil nil
272 273 274 275 276 277 278 279 280 281
         (magit-process-git-arguments args)))

(defun magit-git-success (&rest args)
  "Execute Git with ARGS, returning t if its exit code is 0."
  (= (magit-git-exit-code args) 0))

(defun magit-git-failure (&rest args)
  "Execute Git with ARGS, returning t if its exit code is 1."
  (= (magit-git-exit-code args) 1))

282
(defun magit-git-str (&rest args)
283
  "Execute Git with ARGS, returning the first line of its output.
284 285
If there is no output, return nil.  If the output begins with a
newline, return an empty string.  Like `magit-git-string' but
286
ignore `magit-git-debug'."
287 288 289 290 291 292 293 294
  (setq args (-flatten args))
  (magit--with-refresh-cache (cons default-directory args)
    (with-temp-buffer
      (apply #'magit-process-file magit-git-executable nil (list t nil) nil
             (magit-process-git-arguments args))
      (unless (bobp)
        (goto-char (point-min))
        (buffer-substring-no-properties (point) (line-end-position))))))
295

296 297 298 299 300 301 302 303 304
(defun magit-git-output (&rest args)
  "Execute Git with ARGS, returning its output."
  (setq args (-flatten args))
  (magit--with-refresh-cache (cons default-directory args)
    (with-temp-buffer
      (apply #'magit-process-file magit-git-executable nil (list t nil) nil
             (magit-process-git-arguments args))
      (buffer-substring-no-properties (point-min) (point-max)))))

305 306
(define-error 'magit-invalid-git-boolean "Not a Git boolean")

307 308
(defun magit-git-true (&rest args)
  "Execute Git with ARGS, returning t if it prints \"true\".
309 310 311 312 313 314
If it prints \"false\", then return nil.  For any other output
signal `magit-invalid-git-boolean'."
  (pcase (magit-git-output args)
    ((or "true"  "true\n")  t)
    ((or "false" "false\n") nil)
    (output (signal 'magit-invalid-git-boolean output))))
315 316 317

(defun magit-git-false (&rest args)
  "Execute Git with ARGS, returning t if it prints \"false\".
318 319 320 321 322 323
If it prints \"true\", then return nil.  For any other output
signal `magit-invalid-git-boolean'."
  (pcase (magit-git-output args)
    ((or "true"  "true\n")  nil)
    ((or "false" "false\n") t)
    (output (signal 'magit-invalid-git-boolean output))))
324 325

(defun magit-git-insert (&rest args)
326
  "Execute Git with ARGS, inserting its output at point.
327 328
If Git exits with a non-zero exit status, then show a message and
add a section in the respective process buffer."
329
  (setq args (magit-process-git-arguments args))
330 331 332 333 334 335
  (if magit-git-debug
      (let (log)
        (unwind-protect
            (progn
              (setq log (make-temp-file "magit-stderr"))
              (delete-file log)
336
              (let ((exit (apply #'magit-process-file magit-git-executable
337 338 339 340 341 342 343
                                 nil (list t log) nil args)))
                (when (> exit 0)
                  (let ((msg "Git failed"))
                    (when (file-exists-p log)
                      (setq msg (with-temp-buffer
                                  (insert-file-contents log)
                                  (goto-char (point-max))
344 345 346
                                  (cond
                                   ((functionp magit-git-debug)
                                    (funcall magit-git-debug (buffer-string)))
347 348 349 350
                                   ((run-hook-wrapped
                                     'magit-process-error-message-regexps
                                     (lambda (re) (re-search-backward re nil t)))
                                    (match-string-no-properties 1)))))
351
                      (let ((magit-git-debug nil))
352
                        (with-current-buffer (magit-process-buffer t)
353 354
                          (magit-process-insert-section default-directory
                                                        magit-git-executable
355 356 357 358
                                                        args exit log))))
                    (message "%s" msg)))
                exit))
          (ignore-errors (delete-file log))))
359 360
    (apply #'magit-process-file magit-git-executable
           nil (list t nil) nil args)))
361

362 363
(defun magit-git-string (&rest args)
  "Execute Git with ARGS, returning the first line of its output.
364 365
If there is no output, return nil.  If the output begins with a
newline, return an empty string."
366 367 368 369 370 371 372
  (setq args (-flatten args))
  (magit--with-refresh-cache (cons default-directory args)
    (with-temp-buffer
      (apply #'magit-git-insert args)
      (unless (bobp)
        (goto-char (point-min))
        (buffer-substring-no-properties (point) (line-end-position))))))
373

374 375
(defun magit-git-lines (&rest args)
  "Execute Git with ARGS, returning its output as a list of lines.
376 377 378 379
Empty lines anywhere in the output are omitted.

If Git exits with a non-zero exit status, then report show a
message and add a section in the respective process buffer."
380
  (with-temp-buffer
381 382
    (apply #'magit-git-insert args)
    (split-string (buffer-string) "\n" t)))
383

384 385 386 387 388 389 390 391 392 393
(defun magit-git-items (&rest args)
  "Execute Git with ARGS, returning its null-separated output as a list.
Empty items anywhere in the output are omitted.

If Git exits with a non-zero exit status, then report show a
message and add a section in the respective process buffer."
  (with-temp-buffer
    (apply #'magit-git-insert args)
    (split-string (buffer-string) "\0" t)))

394 395 396
(defun magit-git-wash (washer &rest args)
  "Execute Git with ARGS, inserting washed output at point.
Actually first insert the raw output at point.  If there is no
397
output, call `magit-cancel-section'.  Otherwise temporarily narrow
398
the buffer to the inserted text, move to its beginning, and then
399
call function WASHER with ARGS as its sole argument."
400 401
  (declare (indent 1))
  (let ((beg (point)))
402
    (setq args (-flatten args))
403 404 405 406 407 408 409 410 411 412 413
    (magit-git-insert args)
    (if (= (point) beg)
        (magit-cancel-section)
      (unless (bolp)
        (insert "\n"))
      (save-restriction
        (narrow-to-region beg (point))
        (goto-char beg)
        (funcall washer args))
      (when (or (= (point) beg)
                (= (point) (1+ beg)))
414 415
        (magit-cancel-section))
      (magit-maybe-make-margin-overlay))))
416

417
(defun magit-git-version (&optional raw)
418 419
  (--when-let (let (magit-git-global-arguments)
                (ignore-errors (substring (magit-git-string "version") 12)))
420 421
    (if raw it (and (string-match "^\\([0-9]+\\.[0-9]+\\.[0-9]+\\)" it)
                    (match-string 1 it)))))
422

423 424
;;; Files

425 426 427 428 429
(defun magit--safe-default-directory (&optional file)
  (catch 'unsafe-default-dir
    (let ((dir (file-name-as-directory
                (expand-file-name (or file default-directory))))
          (previous nil))
430
      (while (not (magit-file-accessible-directory-p dir))
431 432 433 434 435 436
        (setq dir (file-name-directory (directory-file-name dir)))
        (when (equal dir previous)
          (throw 'unsafe-default-dir nil))
        (setq previous dir))
      dir)))

437
(defmacro magit--with-safe-default-directory (file &rest body)
438
  (declare (indent 1) (debug (form body)))
439 440
  `(-when-let (default-directory (magit--safe-default-directory ,file))
     ,@body))
441

442
(defun magit-git-dir (&optional path)
443 444 445 446 447
  "Return absolute path to the control directory of the current repository.

All symlinks are followed.  If optional PATH is non-nil, then
it has to be a path relative to the control directory and its
absolute path is returned."
448 449
  (magit--with-refresh-cache (list default-directory 'magit-git-dir path)
    (magit--with-safe-default-directory nil
450
      (-when-let (dir (magit-rev-parse-safe "--git-dir"))
451 452 453
        (setq dir (file-name-as-directory (magit-expand-git-file-name dir)))
        (unless (file-remote-p dir)
          (setq dir (concat (file-remote-p default-directory) dir)))
454
        (if path (expand-file-name (convert-standard-filename path) dir) dir)))))
455

456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
(defvar magit--separated-gitdirs nil)

(defun magit--record-separated-gitdir ()
  (let ((topdir (magit-toplevel))
        (gitdir (magit-git-dir)))
    ;; We want to delete the entry for `topdir' here, rather than within
    ;; (unless ...), in case a `--separate-git-dir' repository was switched to
    ;; the standard structure (i.e., "topdir/.git/").
    (setq magit--separated-gitdirs (cl-delete topdir
                                            magit--separated-gitdirs
                                            :key #'car :test #'equal))
    (unless (equal (file-name-as-directory (expand-file-name ".git" topdir))
                   gitdir)
      (push (cons topdir gitdir) magit--separated-gitdirs))))

471
(defun magit-toplevel (&optional directory)
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
  "Return the absolute path to the toplevel of the current repository.

From within the working tree or control directory of a repository
return the absolute path to the toplevel directory of the working
tree.  As a special case, from within a bare repository return
the control directory instead.  When called outside a repository
then return nil.

When optional DIRECTORY is non-nil then return the toplevel for
that directory instead of the one for `default-directory'.

Try to respect the option `find-file-visit-truename', i.e.  when
the value of that option is nil, then avoid needlessly returning
the truename.  When a symlink to a sub-directory of the working
tree is involved, or when called from within a sub-directory of
the gitdir or from the toplevel of a gitdir, which itself is not
located within the working tree, then it is not possible to avoid
returning the truename."
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
  (magit--with-refresh-cache
      (cons (or directory default-directory) 'magit-toplevel)
    (magit--with-safe-default-directory directory
      (-if-let (topdir (magit-rev-parse-safe "--show-toplevel"))
          (let (updir)
            (setq topdir (magit-expand-git-file-name topdir))
            (if (and
                 ;; Always honor these settings.
                 (not find-file-visit-truename)
                 (not (getenv "GIT_WORK_TREE"))
                 ;; `--show-cdup' is the relative path to the toplevel
                 ;; from `(file-truename default-directory)'.  Here we
                 ;; pretend it is relative to `default-directory', and
                 ;; go to that directory.  Then we check whether
                 ;; `--show-toplevel' still returns the same value and
                 ;; whether `--show-cdup' now is the empty string.  If
                 ;; both is the case, then we are at the toplevel of
                 ;; the same working tree, but also avoided needlessly
                 ;; following any symlinks.
                 (progn
                   (setq updir (file-name-as-directory
                                (magit-rev-parse-safe "--show-cdup")))
                   (setq updir (if (file-name-absolute-p updir)
                                   (concat (file-remote-p default-directory) updir)
                                 (expand-file-name updir)))
                   (let ((default-directory updir))
                     (and (string-equal (magit-rev-parse-safe "--show-cdup") "")
                          (--when-let (magit-rev-parse-safe "--show-toplevel")
                            (string-equal (magit-expand-git-file-name it)
                                          topdir))))))
                updir
              (concat (file-remote-p default-directory)
                      (file-name-as-directory topdir))))
        (-when-let (gitdir (magit-rev-parse-safe "--git-dir"))
          (setq gitdir (file-name-as-directory
                        (if (file-name-absolute-p gitdir)
                            ;; We might have followed a symlink.
                            (concat (file-remote-p default-directory)
                                    (magit-expand-git-file-name gitdir))
                          (expand-file-name gitdir))))
          (if (magit-bare-repo-p)
              gitdir
            (let* ((link (expand-file-name "gitdir" gitdir))
                   (wtree (and (file-exists-p link)
                               (magit-file-line link))))
535 536 537 538 539 540 541 542 543 544 545 546
              (cond
               ((and wtree
                     ;; Ignore .git/gitdir files that result from a
                     ;; Git bug.  See #2364.
                     (not (equal wtree ".git")))
                ;; Return the linked working tree.
                (file-name-directory wtree))
               ;; The working directory may not be the parent directory of
               ;; .git if it was set up with `git init --separate-git-dir'.
               ;; See #2955.
               ((car (rassoc gitdir magit--separated-gitdirs)))
               (t
547
                ;; Step outside the control directory to enter the working tree.
548
                (file-name-directory (directory-file-name gitdir)))))))))))
549 550

(defmacro magit-with-toplevel (&rest body)
551
  (declare (indent defun) (debug (body)))
552 553 554 555 556
  (let ((toplevel (cl-gensym "toplevel")))
    `(let ((,toplevel (magit-toplevel)))
       (if ,toplevel
           (let ((default-directory ,toplevel))
             ,@body)
557 558
         (magit--not-inside-repository-error)))))

559 560 561 562
(define-error 'magit-outside-git-repo "Not inside Git repository")
(define-error 'magit-git-executable-not-found
  "Git executable cannot be found (see https://magit.vc/goto/e6a78ed2)")

563 564
(defun magit--not-inside-repository-error ()
  (if (executable-find magit-git-executable)
565 566
      (signal 'magit-outside-git-repo default-directory)
    (signal 'magit-git-executable-not-found magit-git-executable)))
567

568 569 570 571 572
(defun magit-inside-gitdir-p (&optioal noerror)
  "Return t if `default-directory' is below the repository directory.
If it is below the working directory, then return nil.
If it isn't below either, then signal an error unless NOERROR
is non-nil, in which case return nil."
573 574 575 576 577 578 579 580
  (and (magit--assert-default-directory noerror)
       ;; Below a repository directory that is not located below the
       ;; working directory "git rev-parse --is-inside-git-dir" prints
       ;; "false", which is wrong.
       (let ((gitdir (magit-git-dir)))
         (cond (gitdir (file-in-directory-p default-directory gitdir))
               (noerror nil)
               (t (signal 'magit-outside-git-repo default-directory))))))
581 582 583 584 585 586

(defun magit-inside-worktree-p (&optional noerror)
  "Return t if `default-directory' is below the working directory.
If it is below the repository directory, then return nil.
If it isn't below either, then signal an error unless NOERROR
is non-nil, in which case return nil."
587 588 589 590 591 592
  (and (magit--assert-default-directory noerror)
       (condition-case nil
           (magit-rev-parse-true "--is-inside-work-tree")
         (magit-invalid-git-boolean
          (and (not noerror)
               (signal 'magit-outside-git-repo default-directory))))))
593 594 595 596 597 598

(defun magit-bare-repo-p (&optional noerror)
  "Return t if the current repository is bare.
If it is non-bare, then return nil.  If `default-directory'
isn't below a Git repository, then signal an error unless
NOERROR is non-nil, in which case return nil."
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
  (and (magit--assert-default-directory noerror)
       (condition-case nil
           (magit-rev-parse-true "--is-bare-repository")
         (magit-invalid-git-boolean
          (and (not noerror)
               (signal 'magit-outside-git-repo default-directory))))))

(defun magit--assert-default-directory (&optional noerror)
  (or (file-directory-p default-directory)
      (and (not noerror)
           (let ((exists (file-exists-p default-directory)))
	     (signal (if exists 'file-error 'file-missing)
		     (list "Running git in directory"
		           (if exists
                               "Not a directory"
                             "No such file or directory")
		           default-directory))))))
616 617 618 619

(defun magit-git-repo-p (directory &optional non-bare)
  "Return t if DIRECTORY is a Git repository.
When optional NON-BARE is non-nil also return nil if DIRECTORY is
620
a bare repository."
621 622 623 624 625 626 627
  (and (file-directory-p directory) ; Avoid archives, see #3397.
       (or (file-regular-p (expand-file-name ".git" directory))
           (file-directory-p (expand-file-name ".git" directory))
           (and (not non-bare)
                (file-regular-p (expand-file-name "HEAD" directory))
                (file-directory-p (expand-file-name "refs" directory))
                (file-directory-p (expand-file-name "objects" directory))))))
628 629 630 631 632 633 634 635

(defvar-local magit-buffer-revision  nil)
(defvar-local magit-buffer-refname   nil)
(defvar-local magit-buffer-file-name nil)
(put 'magit-buffer-revision  'permanent-local t)
(put 'magit-buffer-refname   'permanent-local t)
(put 'magit-buffer-file-name 'permanent-local t)

636
(defun magit-file-relative-name (&optional file tracked)
637
  "Return the path of FILE relative to the repository root.
638

639
If optional FILE is nil or omitted, return the relative path of
640
the file being visited in the current buffer, if any, else nil.
641
If the file is not inside a Git repository, then return nil.
642 643 644

If TRACKED is non-nil, return the path only if it matches a
tracked file."
645 646 647
  (unless file
    (with-current-buffer (or (buffer-base-buffer)
                             (current-buffer))
648 649
      (setq file (or magit-buffer-file-name buffer-file-name
                     (and (derived-mode-p 'dired-mode) default-directory)))))
650
  (when (and file (or (not tracked)
651
                      (magit-file-tracked-p (file-relative-name file))))
652
    (--when-let (magit-toplevel
653 654
                 (magit--safe-default-directory
                  (directory-file-name (file-name-directory file))))
655
      (file-relative-name file it))))
656 657 658 659

(defun magit-file-tracked-p (file)
  (magit-git-success "ls-files" "--error-unmatch" file))

660
(defun magit-list-files (&rest args)
661
  (apply #'magit-git-items "ls-files" "-z" "--full-name" args))
662

663
(defun magit-tracked-files ()
664
  (magit-list-files "--cached"))
665

666 667
(defun magit-untracked-files (&optional all files)
  (magit-list-files "--other" (unless all "--exclude-standard") "--" files))
668

669
(defun magit-unstaged-files (&optional nomodules files)
670
  (magit-git-items "diff-files" "-z" "--name-only"
671 672
                   (and nomodules "--ignore-submodules")
                   "--" files))
673

674
(defun magit-staged-files (&optional nomodules files)
675
  (magit-git-items "diff-index" "-z" "--name-only" "--cached"
676
                   (and nomodules "--ignore-submodules")
677
                   (magit-headish) "--" files))
678

679 680 681 682 683 684
(defun magit-staged-binary-files ()
  (--mapcat (and (string-match "^-\t-\t\\(.+\\)" it)
                 (list (match-string 1 it)))
            (magit-git-items "diff" "-z" "--cached"
                             "--numstat" "--ignore-submodules")))

685
(defun magit-unmerged-files ()
686
  (magit-git-items "diff-files" "-z" "--name-only" "--diff-filter=U"))
687

688 689 690 691
(defun magit-ignored-files ()
  (magit-git-items "ls-files" "-z" "--others" "--ignored"
                   "--exclude-standard" "--directory"))

692
(defun magit-revision-files (rev)
693
  (magit-with-toplevel
694
    (magit-git-items "ls-tree" "-z" "-r" "--name-only" rev)))
695

696 697 698 699 700
(defun magit-changed-files (rev-or-range &optional other-rev)
  "Return list of files the have changed between two revisions.
If OTHER-REV is non-nil, REV-OR-RANGE should be a revision, not a
range.  Otherwise, it can be any revision or range accepted by
\"git diff\" (i.e., <rev>, <revA>..<revB>, or <revA>...<revB>)."
701
  (magit-with-toplevel
702 703 704 705 706
    (magit-git-items "diff" "-z" "--name-only" rev-or-range other-rev)))

(defun magit-renamed-files (revA revB)
  (--map (cons (nth 1 it) (nth 2 it))
         (-partition 3 (magit-git-items
707
                        "diff-tree" "-r" "--diff-filter=R" "-z" "-M"
708
                        revA revB))))
709

710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
(defun magit-file-status (&rest args)
  (with-temp-buffer
    (save-excursion (magit-git-insert "status" "-z" args))
    (let ((pos (point)) status)
      (while (> (skip-chars-forward "[:print:]") 0)
        (let ((x (char-after     pos))
              (y (char-after (1+ pos)))
              (file (buffer-substring (+ pos 3) (point))))
          (forward-char)
          (if (memq x '(?R ?C))
              (progn
                (setq pos (point))
                (skip-chars-forward "[:print:]")
                (push (list file (buffer-substring pos (point)) x y) status)
                (forward-char))
            (push (list file nil x y) status)))
        (setq pos (point)))
      status)))
728

729 730 731
(defcustom magit-cygwin-mount-points
  (when (eq system-type 'windows-nt)
    (cl-sort (--map (if (string-match "^\\(.*\\) on \\(.*\\) type" it)
732 733
                        (cons (file-name-as-directory (match-string 2 it))
                              (file-name-as-directory (match-string 1 it)))
734 735
                      (lwarn '(magit) :error
                             "Failed to parse Cygwin mount: %S" it))
736 737
                    ;; If --exec-path is not a native Windows path,
                    ;; then we probably have a cygwin git.
738 739 740 741 742 743 744
                    (let ((process-environment
                           (append magit-git-environment process-environment)))
                      (and (not (string-match-p
                                 "\\`[a-zA-Z]:"
                                 (car (process-lines
                                       magit-git-executable "--exec-path"))))
                           (ignore-errors (process-lines "mount")))))
745
             #'> :key (-lambda ((cyg . _win)) (length cyg))))
746 747
  "Alist of (CYGWIN . WIN32) directory names.
Sorted from longest to shortest CYGWIN name."
748 749 750 751
  :package-version '(magit . "2.3.0")
  :group 'magit-process
  :type '(alist :key-type string :value-type directory))

752 753 754
(defun magit-expand-git-file-name (filename)
  (unless (file-name-absolute-p filename)
    (setq filename (expand-file-name filename)))
755 756 757 758
  (-if-let ((cyg . win)
            (cl-assoc filename magit-cygwin-mount-points
                      :test (lambda (f cyg) (string-prefix-p cyg f))))
      (concat win (substring filename (length cyg)))
759
    filename))
760

761 762 763
(defun magit-convert-filename-for-git (filename)
  "Convert FILENAME so that it can be passed to git.
1. If it's a remote filename, then remove the remote part.
764
2. Deal with an `windows-nt' Emacs vs. Cygwin Git incompatibility."
765 766 767 768 769 770 771
  (if (file-name-absolute-p filename)
      (-if-let ((cyg . win)
                (cl-rassoc filename magit-cygwin-mount-points
                           :test (lambda (f win) (string-prefix-p win f))))
          (concat cyg (substring filename (length win)))
        (or (file-remote-p filename 'localname)
            filename))
772 773
    filename))

774 775
(defun magit-decode-git-path (path)
  (if (eq (aref path 0) ?\")
776 777 778 779
      (decode-coding-string (read path)
                            (or magit-git-output-coding-system
                                (car default-process-coding-system))
                            t)
780 781 782 783
    path))

(defun magit-file-at-point ()
  (magit-section-case
784
    (file (oref it value))
785 786 787 788 789 790
    (hunk (magit-section-parent-value it))))

(defun magit-current-file ()
  (or (magit-file-relative-name)
      (magit-file-at-point)
      (and (derived-mode-p 'magit-log-mode)
791
           (car (nth 2 magit-refresh-args)))))
792 793 794 795 796

;;; Predicates

(defun magit-no-commit-p ()
  "Return t if there is no commit in the current Git repository."
797
  (not (magit-rev-verify "HEAD")))
798

799 800 801 802
(defun magit-merge-commit-p (commit)
  "Return t if COMMIT is a merge commit."
  (> (length (magit-commit-parents commit)) 1))

803
(defun magit-anything-staged-p (&optional ignore-submodules &rest files)
804 805 806
  "Return t if there are any staged changes.
If optional FILES is non-nil, then only changes to those files
are considered."
807 808 809
  (magit-git-failure "diff" "--quiet" "--cached"
                     (and ignore-submodules "--ignore-submodules")
                     "--" files))
810

811
(defun magit-anything-unstaged-p (&optional ignore-submodules &rest files)
812 813 814
  "Return t if there are any unstaged changes.
If optional FILES is non-nil, then only changes to those files
are considered."
815 816 817
  (magit-git-failure "diff" "--quiet"
                     (and ignore-submodules "--ignore-submodules")
                     "--" files))
818

819
(defun magit-anything-modified-p (&optional ignore-submodules &rest files)
820 821 822
  "Return t if there are any staged or unstaged changes.
If optional FILES is non-nil, then only changes to those files
are considered."
823 824
  (or (apply 'magit-anything-staged-p   ignore-submodules files)
      (apply 'magit-anything-unstaged-p ignore-submodules files)))
825 826 827 828 829 830 831

(defun magit-anything-unmerged-p (&rest files)
  "Return t if there are any merge conflicts.
If optional FILES is non-nil, then only conflicts in those files
are considered."
  (and (magit-git-string "ls-files" "--unmerged" files) t))

832 833 834 835 836 837 838
(defun magit-module-worktree-p (module)
  (magit-with-toplevel
    (file-exists-p (expand-file-name (expand-file-name ".git" module)))))

(defun magit-module-no-worktree-p (module)
  (not (magit-module-worktree-p module)))

839 840 841 842
;;; Revisions and References

(defun magit-rev-parse (&rest args)
  "Execute `git rev-parse ARGS', returning first line of output.
843
If there is no output, return nil."
844 845
  (apply #'magit-git-string "rev-parse" args))

846 847
(defun magit-rev-parse-safe (&rest args)
  "Execute `git rev-parse ARGS', returning first line of output.
848
If there is no output, return nil.  Like `magit-rev-parse' but
849 850 851
ignore `magit-git-debug'."
  (apply #'magit-git-str "rev-parse" args))

852 853 854 855 856 857 858 859 860 861 862 863
(defun magit-rev-parse-true (&rest args)
  "Execute `git rev-parse ARGS', returning t if it prints \"true\".
If it prints \"false\", then return nil.  For any other output
signal an error."
  (magit-git-true "rev-parse" args))

(defun magit-rev-parse-false (&rest args)
  "Execute `git rev-parse ARGS', returning t if it prints \"false\".
If it prints \"true\", then return nil.  For any other output
signal an error."
  (magit-git-false "rev-parse" args))

864 865 866 867
(defun magit-rev-parse-p (&rest args)
  "Execute `git rev-parse ARGS', returning t if it prints \"true\".
Return t if the first (and usually only) output line is the
string \"true\", otherwise return nil."
868
  (equal (magit-git-str "rev-parse" args) "true"))
869

870
(defun magit-rev-verify (rev)
871
  (magit-rev-parse-safe "--verify" rev))
872

873 874 875 876
(defun magit-rev-verify-commit (rev)
  "Return full hash for REV if it names an existing commit."
  (magit-rev-verify (concat rev "^{commit}")))

877 878 879
(defun magit-rev-equal (a b)
  (magit-git-success "diff" "--quiet" a b))

880 881 882 883
(defun magit-rev-eq (a b)
  (equal (magit-rev-verify a)
         (magit-rev-verify b)))

884 885 886 887
(defun magit-rev-ancestor-p (a b)
  "Return non-nil if commit A is an ancestor of commit B."
  (magit-git-success "merge-base" "--is-ancestor" a b))

888
(defun magit-rev-head-p (rev)
889
  (or (equal rev "HEAD")
890 891 892 893
      (and rev
           (not (string-match-p "\\.\\." rev))
           (equal (magit-rev-parse rev)
                  (magit-rev-parse "HEAD")))))
894

895 896 897 898 899 900 901 902
(defun magit-rev-author-p (rev)
  "Return t if the user is the author of REV.
More precisely return t if `user.name' is equal to the author
name of REV and/or `user.email' is equal to the author email
of REV."
  (or (equal (magit-get "user.name")  (magit-rev-format "%an" rev))
      (equal (magit-get "user.email") (magit-rev-format "%ae" rev))))

903
(defun magit-rev-name (rev &optional pattern)
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
  "Return a symbolic name for REV.
PATTERN is passed to the `--refs' flag of `git-name-rev' and can
be used to limit the result to a matching ref.  When structured
as \"refs/<subdir>/*\", PATTERN is taken as a namespace.  In this
case, the name returned by `git-name-rev' is discarded if it
corresponds to a ref outside of the namespace."
  (--when-let (magit-git-string "name-rev" "--name-only" "--no-undefined"
                                (and pattern (concat "--refs=" pattern))
                                rev)
    ;; We can't use name-rev's --exclude to filter out "*/PATTERN"
    ;; because --exclude wasn't added until Git v2.13.0.
    (if (and pattern
             (string-match-p "\\`refs/[^/]+/\\*\\'" pattern))
        (let ((namespace (substring pattern 0 -1)))
          (unless (and (string-match-p namespace it)
                       (not (magit-rev-verify (concat namespace it))))
            it))
      it)))
922

923 924
(defun magit-rev-branch (rev)
  (--when-let (magit-rev-name rev "refs/heads/*")
925
    (unless (string-match-p "[~^]" it) it)))
926

927
(defun magit-get-shortname (rev)
928 929 930 931
  (let* ((fn (apply-partially 'magit-rev-name rev))
         (name (or (funcall fn "refs/tags/*")
                   (funcall fn "refs/heads/*")
                   (funcall fn "refs/remotes/*"))))
932 933 934 935 936 937 938
    (cond ((not name)
           (magit-rev-parse "--short" rev))
          ((string-match "^\\(?:tags\\|remotes\\)/\\(.+\\)" name)
           (if (magit-ref-ambiguous-p (match-string 1 name))
               name
             (match-string 1 name)))
          (t (magit-ref-maybe-qualify name)))))
939

940 941 942 943 944 945 946
(defun magit-name-branch (rev &optional lax)
  (or (magit-name-local-branch rev)
      (magit-name-remote-branch rev)
      (and lax (or (magit-name-local-branch rev t)
                   (magit-name-remote-branch rev t)))))

(defun magit-name-local-branch (rev &optional lax)
947
  (--when-let (magit-rev-name rev "refs/heads/*")
948
    (and (or lax (not (string-match-p "[~^]" it))) it)))
949 950

(defun magit-name-remote-branch (rev &optional lax)
951
  (--when-let (magit-rev-name rev "refs/remotes/*")
952
    (and (or lax (not (string-match-p "[~^]" it)))
953 954 955
         (substring it 8))))

(defun magit-name-tag (rev &optional lax)
956
  (--when-let (magit-rev-name rev "refs/tags/*")
957
    (and (or lax (not (string-match-p "[~^]" it)))
958 959
         (substring it 5))))

960
(defun magit-ref-fullname (name)
961 962 963 964 965 966 967 968 969
  "Return fully qualified refname for NAME.
If NAME is ambiguous, return nil.  NAME may include suffixes such
as \"^1\" and \"~3\".  "
  (save-match-data
    (if (string-match "\\`\\([^^~]+\\)\\(.*\\)" name)
        (--when-let (magit-rev-parse "--symbolic-full-name"
                                     (match-string 1 name))
          (concat it (match-string 2 name)))
      (error "`name' has an unrecognized format"))))
970

971 972 973
(defun magit-ref-ambiguous-p (name)
  (not (magit-ref-fullname name)))

974 975 976 977 978 979
(cl-defun magit-ref-maybe-qualify (name &optional (prefix "heads/"))
  "If NAME is ambiguous, prepend PREFIX to it."
  (concat (and (magit-ref-ambiguous-p name)
               prefix)
          name))

980 981 982
(defun magit-ref-exists-p (ref)
  (magit-git-success "show-ref" "--verify" ref))

983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
(defun magit-ref-equal (a b)
  "Return t if the refs A and B are `equal'.
A symbolic-ref pointing to some ref, is `equal' to that ref,
as are two symbolic-refs pointing to the same ref."
  (equal (magit-ref-fullname a)
         (magit-ref-fullname b)))

(defun magit-ref-eq (a b)
  "Return t if the refs A and B are `eq'.
A symbolic-ref is `eq' to itself, but not to the ref it points
to, or to some other symbolic-ref that points to the same ref."
  (let ((symbolic-a (magit-symbolic-ref-p a))
        (symbolic-b (magit-symbolic-ref-p b)))
    (or (and symbolic-a
             symbolic-b
             (equal a b))
        (and (not symbolic-a)
             (not symbolic-b)
             (magit-ref-equal a b)))))

1003 1004 1005 1006 1007 1008 1009
(defun magit-headish ()
  "Return \"HEAD\" or if that doesn't exist the hash of the empty tree."
  (if (magit-no-commit-p)
      (magit-git-string "mktree")
    "HEAD"))

(defun magit-branch-at-point ()
1010
  (magit-section-case
1011 1012
    (branch (oref it value))
    (commit (magit-name-branch (oref it value)))))
1013

1014
(defun magit-local-branch-at-point ()
1015
  (magit-section-case
1016
    (branch (let ((branch (magit-ref-maybe-qualify (oref it value))))
1017 1018
              (when (member branch (magit-list-local-branch-names))
                branch)))
1019
    (commit (magit-name-local-branch (oref it value)))))
1020 1021

(defun magit-remote-branch-at-point ()
1022
  (magit-section-case
1023
    (branch (let ((branch (oref it value)))
1024 1025
              (when (member branch (magit-list-remote-branch-names))
                branch)))
1026
    (commit (magit-name-remote-branch (oref it value)))))
1027

1028
(defun magit-commit-at-point ()
1029 1030
  (or (magit-section-when commit)
      (and (derived-mode-p 'magit-revision-mode)
1031
           (car magit-refresh-args))))
1032 1033

(defun magit-branch-or-commit-at-point ()
1034 1035
  (or magit-buffer-refname
      (magit-section-case
1036 1037
        (branch (magit-ref-maybe-qualify (oref it value)))
        (commit (let ((rev (oref it value)))
1038 1039 1040
                  (or (magit-name-branch rev)
                      (magit-get-shortname rev)
                      rev)))
1041
        (tag (magit-ref-maybe-qualify (oref it value) "tags/")))
1042
      (thing-at-point 'git-revision t)
1043 1044
      (and (derived-mode-p 'magit-revision-mode
                           'magit-merge-preview-mode)
1045
           (car magit-refresh-args))))
1046

1047
(defun magit-tag-at-point ()
1048
  (magit-section-case
1049 1050
    (tag    (oref it value))
    (commit (magit-name-tag (oref it value)))))
1051

1052
(defun magit-stash-at-point ()
1053 1054 1055 1056
  (magit-section-when stash))

(defun magit-remote-at-point ()
  (magit-section-case
1057
    (remote (oref it value))
1058 1059
    (branch (magit-section-parent-value it))))

1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
(defun magit-module-at-point (&optional predicate)
  (magit-section-when
      '(submodule
        [file modules-unpulled-from-upstream]
        [file modules-unpulled-from-pushremote]
        [file modules-unpushed-to-upstream]
        [file modules-unpushed-to-pushremote])
    (let ((module (oref it value)))
      (and (or (not predicate)
               (funcall predicate module))
           module))))

1072 1073 1074 1075 1076
(defun magit-get-current-branch ()
  "Return the refname of the currently checked out branch.
Return nil if no branch is currently checked out."
  (magit-git-string "symbolic-ref" "--short" "HEAD"))

1077 1078 1079 1080
(defvar magit-get-previous-branch-timeout 0.5
  "Maximum time to spend in `magit-get-previous-branch'.
Given as a number of seconds.")

1081 1082
(defun magit-get-previous-branch ()
  "Return the refname of the previously checked out branch.
1083
Return nil if no branch can be found in the `HEAD' reflog
1084 1085 1086 1087 1088
which is different from the current branch and still exists.
The amount of time spent searching is limited by
`magit-get-previous-branch-timeout'."
  (let ((t0 (float-time))
        (current (magit-get-current-branch))
1089
        (i 1) prev)
1090 1091 1092 1093 1094
    (while (if (> (- (float-time) t0) magit-get-previous-branch-timeout)
               (setq prev nil) ;; Timed out.
             (and (setq prev (magit-rev-verify (format "@{-%i}" i)))
                  (or (not (setq prev (magit-rev-branch prev)))
                      (equal prev current))))
1095 1096 1097
      (cl-incf i))
    prev))

1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
(defun magit-get-upstream-ref (&optional branch)
  (and (or branch (setq branch (magit-get-current-branch)))
       (let ((remote (magit-get "branch" branch "remote"))
             (merge  (magit-get "branch" branch "merge")))
         (when (and remote merge)
           (cond ((string-equal remote ".") merge)
                 ((string-prefix-p "refs/heads/" merge)
                  (concat "refs/remotes/" remote "/" (substring merge 11))))))))

(defun magit-get-upstream-branch (&optional branch verify)
  (and (or branch (setq branch (magit-get-current-branch)))
1109 1110 1111 1112 1113
       (-when-let* ((remote (magit-get "branch" branch "remote"))
                    (merge  (magit-get "branch" branch "merge")))
         (and (string-prefix-p "refs/heads/" merge)
              (let* ((upstream (substring merge 11))
                     (upstream
1114 1115 1116 1117 1118 1119 1120 1121
                      (cond ((string-equal remote ".")
                             (propertize upstream 'face 'magit-branch-local))
                            ((string-match-p "[@:]" remote)
                             (propertize (concat remote " " upstream)
                                         'face 'magit-branch-remote))
                            (t
                             (propertize (concat remote "/" upstream)
                                         'face 'magit-branch-remote)))))
1122 1123 1124
                (and (or (not verify)
                         (magit-rev-verify upstream))
                     upstream))))))
1125

1126
(defun magit-get-indirect-upstream-branch (branch &optional force)
1127 1128
  (let ((remote (magit-get "branch" branch "remote")))
    (and remote (not (equal remote "."))
1129
         ;; The user has opted in...
1130 1131 1132 1133 1134
         (or force
             (--any (if (magit-git-success "check-ref-format" "--branch" it)
                        (equal it branch)
                      (string-match-p it branch))
                    magit-branch-prefer-remote-upstream))
1135
         ;; and local BRANCH tracks a remote branch...
1136 1137 1138 1139 1140 1141 1142 1143 1144
         (let ((upstream (magit-get-upstream-branch branch)))
           ;; whose upstream...
           (and upstream
                ;; has the same name as BRANCH and...
                (equal (substring upstream (1+ (length remote))) branch)
                ;; and can be fast-forwarded to BRANCH.
                (magit-rev-ancestor-p upstream branch)
                upstream)))))

1145 1146 1147
(defun magit-get-upstream-remote (&optional branch)
  (and (or branch (setq branch (magit-get-current-branch)))
       (magit-get "branch" branch "remote")))
1148

1149 1150 1151
(defun magit-get-push-remote (&optional branch)
  (or (and (or branch (setq branch (magit-get-current-branch)))
           (magit-get "branch" branch "pushRemote"))
1152 1153
      (magit-get "remote.pushDefault")))

1154 1155
(defun magit-get-push-branch (&optional branch verify)
  (and (or branch (setq branch (magit-get-current-branch)))
1156 1157 1158 1159 1160
       (-when-let* ((remote (magit-get-push-remote branch))
                    (push-branch (concat remote "/" branch)))
         (and (or (not verify)
                  (magit-rev-verify push-branch))
              push-branch))))
1161

1162 1163 1164 1165 1166 1167
(defun magit-get-@{push}-branch (&optional branch)
  (let ((ref (magit-rev-parse "--symbolic-full-name"
                              (concat branch "@{push}"))))
    (when (and ref (string-prefix-p "refs/remotes/" ref))
      (substring ref 13))))

1168 1169
(defun magit-get-remote (&optional branch)
  (when (or branch (setq branch (magit-get-current-branch)))
1170 1171 1172 1173
    (let ((remote (magit-get "branch" branch "remote")))
      (unless (equal remote ".")
        remote))))

1174 1175 1176 1177 1178 1179 1180 1181
(defun magit-get-some-remote (&optional branch)
  (or (magit-get-remote branch)
      (and (magit-branch-p "master")
           (magit-get-remote "master"))
      (let ((remotes (magit-list-remotes)))
        (or (car (member "origin" remotes))
            (car remotes)))))

1182
(defun magit-branch-merged-p (branch &optional target)
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
  "Return non-nil if BRANCH is merged into its upstream and TARGET.

TARGET defaults to the current branch.  If `HEAD' is detached and
TARGET is nil, then always return nil.  As a special case, if
TARGET is t, then return non-nil if BRANCH is merged into any one
of the other local branches.

If, and only if, BRANCH has an upstream, then only return non-nil
if BRANCH is merged into both TARGET (as described above) as well
as into its upstream."
  (and (--if-let (and (magit-branch-p branch)
                      (magit-get-upstream-branch branch))
           (magit-git-success "merge-base" "--is-ancestor" branch it)
         t)
       (if (eq target t)
           (delete (magit-name-local-branch branch)
                   (magit-list-containing-branches branch))
         (--when-let (or target (magit-get-current-branch))
           (magit-git-success "merge-base" "--is-ancestor" branch it)))))
1202

1203 1204 1205
(defun magit-split-branch-name (branch)
  (cond ((member branch (magit-list-local-branch-names))
         (cons "." branch))
1206 1207 1208
        ((string-match " " branch)
         (pcase-let ((`(,url ,branch) (split-string branch " ")))
           (cons url branch)))
1209 1210 1211 1212 1213
        ((string-match "/" branch)
         (let ((remote (substring branch 0 (match-beginning 0))))
           (if (save-match-data (member remote (magit-list-remotes)))
               (cons remote (substring branch (match-end 0)))
             (error "Invalid branch name %s" branch))))))
1214

1215 1216
(defun magit-get-current-tag (&optional rev with-distance)
  "Return the closest tag reachable from REV.
1217

1218
If optional REV is nil, then default to `HEAD'.
1219 1220
If optional WITH-DISTANCE is non-nil then return (TAG COMMITS),
if it is `dirty' return (TAG COMMIT DIRTY). COMMITS is the number
1221
of commits in `HEAD' but not in TAG and DIRTY is t if there are
1222
uncommitted changes, nil otherwise."
1223 1224
  (--when-let (magit-git-str "describe" "--long" "--tags"
                             (and (eq with-distance 'dirty) "--dirty") rev)
1225 1226 1227 1228
    (save-match-data
      (string-match
       "\\(.+\\)-\\(?:0[0-9]*\\|\\([0-9]+\\)\\)-g[0-9a-z]+\\(-dirty\\)?$" it)
      (if with-distance
1229 1230 1231
          `(,(match-string 1 it)
            ,(string-to-number (or (match-string 2 it) "0"))
            ,@(and (match-string 3 it) (list t)))
1232 1233
        (match-string 1 it)))))

1234 1235
(defun magit-get-next-tag (&optional rev with-distance)
  "Return the closest tag from which REV is reachable.
1236

1237
If optional REV is nil, then default to `HEAD'.
1238
If no such tag can be found or if the distance is 0 (in which
1239 1240
case it is the current tag, not the next), return nil instead.
If optional WITH-DISTANCE is non-nil, then return (TAG COMMITS)
1241
where COMMITS is the number of commits in TAG but not in REV."
1242
  (--when-let (magit-git-str "describe" "--contains" (or rev "HEAD"))
1243 1244 1245
    (save-match-data
      (when (string-match "^[^^~]+" it)
        (setq it (match-string 0 it))
1246
        (unless (equal it (magit-get-current-tag rev))
1247
          (if with-distance
1248
              (list it (car (magit-rev-diff-count it rev)))
1249 1250
            it))))))

1251
(defvar magit-list-refs-namespaces
1252
  '("refs/heads" "refs/remotes" "refs/tags" "refs/pull"))
1253

1254
(defun magit-list-refs (&optional namespaces format sortby)
1255 1256 1257 1258 1259
  "Return list of references.

When NAMESPACES is non-nil, list refs from these namespaces
rather than those from `magit-list-refs-namespaces'.

1260 1261 1262
FORMAT is passed to the `--format' flag of `git for-each-ref'
and defaults to \"%(refname)\".  If the format is \"%(refname)\"
or \"%(refname:short)\", then drop the symbolic-ref \"HEAD\".
1263 1264 1265

SORTBY is a key or list of keys to pass to the `--sort' flag of
`git for-each-ref'.  When nil, use `magit-list-refs-sortby'"
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
  (unless format
    (setq format "%(refname)"))
  (let ((refs (magit-git-lines "for-each-ref"
                               (concat "--format=" format)
                               (--map (concat "--sort=" it)
                                      (pcase (or sortby magit-list-refs-sortby)
                                        ((and val (pred stringp)) (list val))
                                        ((and val (pred listp)) val)))
                               (or namespaces magit-list-refs-namespaces))))
    (if (member format '("%(refname)" "%(refname:short)"))
        (--remove (string-match-p "\\(\\`\\|/\\)HEAD\\'" it) refs)
      refs)))
1278 1279

(defun magit-list-branches ()
1280
  (magit-list-refs (list "refs/heads" "refs/remotes")))
1281 1282 1283 1284 1285 1286 1287

(defun magit-list-local-branches ()
  (magit-list-refs "refs/heads"))

(defun magit-list-remote-branches (&optional remote)
  (magit-list-refs (concat "refs/remotes/" remote)))

1288
(defun magit-list-related-branches (relation &optional commit arg)
1289
  (--remove (string-match-p "\\(\\`(HEAD\\|HEAD -> \\)" it)
1290
            (--map (substring it 2)
1291
                   (magit-git-lines "branch" arg relation commit))))
1292

1293 1294
(defun magit-list-containing-branches (&optional commit arg)
  (magit-list-related-branches "--contains" commit arg))
1295

1296 1297 1298 1299
(defun magit-list-publishing-branches (&optional commit)
  (--filter (member it magit-published-branches)
            (magit-list-containing-branches commit "--remote")))

1300 1301
(defun magit-list-merged-branches (&optional commit arg)
  (magit-list-related-branches "--merged" commit arg))
1302

1303 1304
(defun magit-list-unmerged-branches (&optional commit arg)
  (magit-list-related-branches "--no-merged" commit arg))
1305 1306

(defun magit-list-unmerged-to-upstream-branches ()
1307
  (--filter (-when-let (upstream (magit-get-upstream-branch it))
1308 1309 1310
              (member it (magit-list-unmerged-branches upstream)))
            (magit-list-local-branch-names)))

1311 1312 1313 1314 1315 1316 1317 1318 1319
(defun magit-list-branches-pointing-at (commit)
  (let ((re (format "\\`%s refs/\\(heads\\|remotes\\)/\\(.*\\)\\'"
                   (magit-rev-verify commit))))
    (--keep (and (string-match re it)
                 (let ((name (match-string 2 it)))
                   (and (not (string-suffix-p "HEAD" name))
                        name)))
            (magit-git-lines "show-ref"))))

1320 1321
(defun magit-list-refnames (&optional namespaces)
  (magit-list-refs namespaces "%(refname:short)"))
1322 1323

(defun magit-list-branch-names ()
1324
  (magit-list-refnames (list "refs/heads" "refs/remotes")))
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336

(defun magit-list-local-branch-names ()
  (magit-list-refnames "refs/heads"))

(defun magit-list-remote-branch-names (&optional remote relative)
  (if (and remote relative)
      (let ((regexp (format "^refs/remotes/%s/\\(.+\\)" remote)))
        (--mapcat (when (string-match regexp it)
                    (list (match-string 1 it)))
                  (magit-list-remote-branches remote)))
    (magit-list-refnames (concat "refs/remotes/" remote))))

1337 1338 1339 1340 1341 1342 1343 1344
(defun magit-format-refs (format &rest args)
  (let ((lines (magit-git-lines
                "for-each-ref" (concat "--format=" format)
                (or args (list "refs/heads" "refs/remotes" "refs/tags")))))
    (if (string-match-p "\f" format)
        (--map (split-string it "\f") lines)
      lines)))

1345 1346 1347 1348 1349 1350
(defun magit-list-remotes ()
  (magit-git-lines "remote"))

(defun magit-list-tags ()
  (magit-git-lines "tag"))

1351 1352 1353
(defun magit-list-stashes (&optional format)
  (magit-git-lines "stash" "list" (concat "--format=" (or format "%gd"))))

1354 1355 1356
(defun magit-list-active-notes-refs ()
  "Return notes refs according to `core.notesRef' and `notes.displayRef'."
  (magit-git-lines "for-each-ref" "--format=%(refname)"
1357
                   (or (magit-get "core.notesRef") "refs/notes/commits")
1358 1359
                   (magit-get-all "notes.displayRef")))

Jonas Bernoulli's avatar
Jonas Bernoulli committed
1360 1361 1362
(defun magit-list-notes-refnames ()
  (--map (substring it 6) (magit-list-refnames "refs/notes")))

1363
(defun magit-remote-list-tags (remote)
1364 1365 1366
  (--keep (and (not (string-match-p "\\^{}$" it))
               (substring it 51))
          (magit-git-lines "ls-remote" "--tags" remote)))
1367

1368
(defun magit-remote-list-branches (remote)
1369 1370 1371
  (--keep (and (not (string-match-p "\\^{}$" it))
               (substring it 52))
          (magit-git-lines "ls-remote" "--heads" remote)))
1372

1373 1374 1375 1376 1377
(defun magit-remote-list-refs (remote)
  (--keep (and (not (string-match-p "\\^{}$" it))
               (substring it 41))
          (magit-git-lines "ls-remote" remote)))

1378
(defun magit-list-module-paths ()
1379 1380 1381
  (--mapcat (and (string-match "^160000 [0-9a-z]\\{40\\} 0\t\\(.+\\)$" it)
                 (list (match-string 1 it)))
            (magit-git-items "ls-files" "-z" "--stage")))
1382

1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
(defun magit-get-submodule-name (path)
  "Return the name of the submodule at PATH.
PATH has to be relative to the super-repository."
  (cadr (split-string
         (car (or (magit-git-items
                   "config" "-z"
                   "-f" (expand-file-name ".gitmodules" (magit-toplevel))
                   "--get-regexp" "^submodule\\..*\\.path$"
                   (concat "^" (regexp-quote (directory-file-name path)) "$"))
                  (error "No such submodule `%s'" path)))
         "\n")))

1395 1396
(defun magit-list-worktrees ()
  (let (worktrees worktree)
1397
    (dolist (line (let ((magit-git-global-arguments
1398
                         ;; KLUDGE At least in v2.8.3 this triggers a segfault.
1399
                         (remove "--no-pager" magit-git-global-arguments)))
1400
                    (magit-git-lines "worktree" "list" "--porcelain")))
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
      (cond ((string-prefix-p "worktree" line)
             (push (setq worktree (list (substring line 9) nil nil nil))
                   worktrees))
            ((string-equal line "bare")
             (let* ((default-directory (car worktree))
                    (wt (and (not (magit-get-boolean "core.bare"))
                             (magit-get "core.worktree"))))
               (if (and wt (file-exists-p (expand-file-name wt)))
                   (progn (setf (nth 0 worktree) (expand-file-name wt))
                          (setf (nth 2 worktree) (magit-rev-parse "HEAD"))
                          (setf (nth 3 worktree) (magit-get-current-branch)))
                 (setf (nth 1 worktree) t))))
            ((string-prefix-p "HEAD" line)
             (setf (nth 2 worktree) (substring line 5)))
            ((string-prefix-p "branch" line)
             (setf (nth 3 worktree) (substring line 18)))
            ((string-equal line "detached"))))
    (nreverse worktrees)))

1420 1421 1422
(defun magit-symbolic-ref-p (name)
  (magit-git-success "symbolic-ref" "--quiet" name))

1423 1424 1425 1426
(defun magit-ref-p (rev)
  (or (car (member rev (magit-list-refs)))
      (car (member rev (magit-list-refnames)))))

1427 1428 1429
(defun magit-branch-p (rev)
  (or (car (member rev (magit-list-branches)))
      (car (member rev (magit-list-branch-names)))))
1430

1431 1432 1433
(defun magit-local-branch-p (rev)
  (or (car (member rev (magit-list-local-branches)))
      (car (member rev (magit-list-local-branch-names)))))
1434

1435 1436 1437 1438
(defun magit-remote-branch-p (rev)
  (or (car (member rev (magit-list-remote-branches)))
      (car (member rev (magit-list-remote-branch-names)))))

1439 1440 1441 1442 1443
(defun magit-branch-set-face (branch)
  (propertize branch 'face (if (magit-local-branch-p branch)
                               'magit-branch-local
                             'magit-branch-remote)))

1444 1445 1446
(defun magit-tag-p (rev)
  (car (member rev (magit-list-tags))))

1447 1448 1449
(defun magit-remote-p (string)
  (car (member string (magit-list-remotes))))

1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
(defun magit-rev-diff-count (a b)
  "Return the commits in A but not B and vice versa.
Return a list of two integers: (A>B B>A)."
  (mapcar 'string-to-number
          (split-string (magit-git-string "rev-list"
                                          "--count" "--left-right"
                                          (concat a "..." b))
                        "\t")))

(defun magit-abbrev-length ()
1460 1461
  (--if-let (magit-get "core.abbrev")
      (string-to-number it)
1462 1463 1464 1465 1466 1467 1468
    ;; Guess the length git will be using based on an example
    ;; abbreviation.  Actually HEAD's abbreviation might be an
    ;; outlier, so use the shorter of the abbreviations for two
    ;; commits.  When a commit does not exist, then fall back
    ;; to the default of 7.  See #3034.
    (min (--if-let (magit-rev-parse "--short" "HEAD")  (length it) 7)
         (--if-let (magit-rev-parse "--short" "HEAD~") (length it) 7))))
1469

1470 1471 1472 1473 1474
(defun magit-abbrev-arg (&optional arg)
  (format "--%s=%d" (or arg "abbrev") (magit-abbrev-length)))

(defun magit-rev-abbrev (rev)
  (magit-rev-parse (magit-abbrev-arg "short") rev))
1475

1476 1477 1478 1479 1480 1481 1482 1483 1484
(defun magit-commit-children (commit &optional args)
  (-map #'car
        (--filter (member commit (cdr it))
                  (--map (split-string it " ")
                         (magit-git-lines
                          "log" "--format=%H %P"
                          (or args (list "--branches" "--tags" "--remotes"))
                          "--not" commit)))))

1485
(defun magit-commit-parents (commit)
1486 1487
  (--when-let (magit-git-string "rev-list" "-1" "--parents" commit)
    (cdr (split-string it))))
1488

1489 1490
(defun magit-patch-id (rev)
  (with-temp-buffer
1491 1492 1493 1494
    (magit-process-file
     shell-file-name nil '(t nil) nil shell-command-switch
     (let ((exec (shell-quote-argument magit-git-executable)))
       (format "%s diff-tree -u %s | %s patch-id" exec rev exec)))
1495 1496
    (car (split-string (buffer-string)))))

1497 1498 1499
(defun magit-rev-format (format &optional rev args)
  (let ((str (magit-git-string "show" "--no-patch"
                               (concat "--format=" format) args
1500
                               (if rev (concat rev "^{commit}") "HEAD") "--")))
1501 1502
    (unless (string-equal str "")
      str)))
1503

1504 1505 1506
(defun magit-rev-insert-format (format &optional rev args)
  (magit-git-insert "show" "--no-patch"
                    (concat "--format=" format) args