-
-
Notifications
You must be signed in to change notification settings - Fork 800
/
magit-git.el
2891 lines (2548 loc) · 121 KB
/
magit-git.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; magit-git.el --- Git functionality -*- lexical-binding:t -*-
;; Copyright (C) 2008-2023 The Magit Project Contributors
;; Author: Jonas Bernoulli <jonas@bernoul.li>
;; Maintainer: Jonas Bernoulli <jonas@bernoul.li>
;; SPDX-License-Identifier: GPL-3.0-or-later
;; 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 of the License, 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 <https://www.gnu.org/licenses/>.
;;; Commentary:
;; This library implements wrappers for various Git plumbing commands.
;;; Code:
(require 'magit-base)
(require 'format-spec)
;; From `magit-branch'.
(defvar magit-branch-prefer-remote-upstream)
(defvar magit-published-branches)
;; From `magit-margin'.
(declare-function magit-maybe-make-margin-overlay "magit-margin" ())
;; From `magit-mode'.
(declare-function magit-get-mode-buffer "magit-mode"
(mode &optional value frame))
(declare-function magit-refresh "magit-mode" ())
(defvar magit-buffer-diff-type)
(defvar magit-buffer-diff-args)
(defvar magit-buffer-file-name)
(defvar magit-buffer-log-args)
(defvar magit-buffer-log-files)
(defvar magit-buffer-refname)
(defvar magit-buffer-revision)
;; From `magit-process'.
(declare-function magit-call-git "magit-process" (&rest args))
(declare-function magit-git "magit-process" (&rest args))
(declare-function magit-process-buffer "magit-process" (&optional nodisplay))
(declare-function magit-process-file "magit-process"
(process &optional infile buffer display &rest args))
(declare-function magit-process-git "magit-process" (destination &rest args))
(declare-function magit-process-insert-section "magit-process"
(pwd program args &optional errcode errlog))
(defvar magit-this-error)
(defvar magit-process-error-message-regexps)
(eval-when-compile
(cl-pushnew 'orig-rev eieio--known-slot-names)
(cl-pushnew 'number eieio--known-slot-names))
;;; Git implementations
(defvar magit-inhibit-libgit t
"Whether to inhibit the use of libgit.
Use of libgit is inhibited by default because support for libgit
in magit is only a stub for now. There is no benefit in using
it.")
(defvar magit--libgit-available-p 'unknown
"Whether libgit is available.
Use the function by the same name instead of this variable.")
(defun magit--libgit-available-p ()
(if (eq magit--libgit-available-p 'unknown)
(setq magit--libgit-available-p
(and module-file-suffix
(let ((libgit (locate-library "libgit")))
(and libgit
(or (locate-library "libegit2")
(let ((load-path
(cons (expand-file-name
(convert-standard-filename "build")
(file-name-directory libgit))
load-path)))
(locate-library "libegit2")))))))
magit--libgit-available-p))
(defun magit-gitimpl ()
"Return the Git implementation used in this repository."
(if (and (not magit-inhibit-libgit)
(not (file-remote-p default-directory))
(magit--libgit-available-p))
'libgit
'git))
;;; 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)
(defvar magit-git-environment
(list (format "INSIDE_EMACS=%s,magit" emacs-version))
"Prepended to `process-environment' while running git.")
(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)))
(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.")
(defcustom magit-git-executable
(or (and (eq system-type 'windows-nt)
;; Avoid the wrappers "cmd/git.exe" and "cmd/git.cmd",
;; which are much slower than using "bin/git.exe" directly.
(and-let* ((exec (executable-find "git")))
(ignore-errors
;; Git for Windows 2.x provides cygpath so we can
;; ask it for native paths.
(let* ((core-exe
(car
(process-lines
exec "-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="
(car (process-lines
exec "-c"
"alias.P=!cygpath -wp \"$PATH\""
"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))))
(and (eq system-type 'darwin)
(executable-find "git"))
"git")
"The Git executable used by Magit on the local host.
On remote machines `magit-remote-git-executable' is used instead."
:package-version '(magit . "3.2.0")
:group 'magit-process
:type 'string)
(defcustom magit-remote-git-executable "git"
"The Git executable used by Magit on remote machines.
On the local host `magit-git-executable' is used instead.
Consider customizing `tramp-remote-path' instead of this
option."
:package-version '(magit . "3.2.0")
:group 'magit-process
:type 'string)
(defcustom magit-git-global-arguments
`("--no-pager" "--literal-pathspecs"
"-c" "core.preloadindex=true"
"-c" "log.showSignature=false"
"-c" "color.ui=false"
"-c" "color.diff=false"
,@(and (eq system-type 'windows-nt)
(list "-c" "i18n.logOutputEncoding=UTF-8")))
"Global Git arguments.
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."
:package-version '(magit . "2.9.0")
:group 'magit-commands
:group 'magit-process
:type '(repeat string))
(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 most commands
that change the upstream and many that create new branches."
:package-version '(magit . "2.4.2")
:group 'magit-commands
:type 'boolean)
(defcustom magit-list-refs-namespaces
'("refs/heads"
"refs/remotes"
"refs/tags"
"refs/pullreqs")
"List of ref namespaces considered when reading a ref.
This 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."
:package-version '(magit . "3.1.0")
:group 'magit-commands
:type '(repeat string))
(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."
:package-version '(magit . "2.11.0")
:group 'magit-miscellaneous
:type '(choice string (repeat string)))
;;; Git
(defvar magit-git-debug nil
"Whether to enable additional reporting of git errors.
Magit basically calls git for one of these two reasons: for
side-effects or to do something with its standard output.
When git is run for side-effects then its output, including error
messages, go into the process buffer which is shown when using \
\\<magit-status-mode-map>\\[magit-process-buffer].
When git's output is consumed in some way, then it would be too
expensive to also insert it into this buffer, but when this
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
permanently, that would negatively affect performance. Also note
that just because git exits with a non-zero exit status and prints
an error message that usually doesn't mean that it is an error as
far as Magit is concerned, which is another reason we usually hide
these error messages. Whether some error message is relevant in
the context of some unexpected behavior has to be judged on a case
by case basis.
The command `magit-toggle-git-debug' changes the value of this
variable.
Also see `magit-process-extreme-logging'.")
(defun magit-toggle-git-debug ()
"Toggle whether additional git errors are reported.
See info node `(magit)Debugging Tools' for more information."
(interactive)
(setq magit-git-debug (not magit-git-debug))
(message "Additional reporting of Git errors %s"
(if magit-git-debug "enabled" "disabled")))
(defvar magit--refresh-cache nil)
(defmacro magit--with-refresh-cache (key &rest body)
(declare (indent 1) (debug (form body)))
(let ((k (cl-gensym))
(hit (cl-gensym)))
`(if magit--refresh-cache
(let ((,k ,key))
(if-let ((,hit (assoc ,k (cdr magit--refresh-cache))))
(progn (cl-incf (caar magit--refresh-cache))
(cdr ,hit))
(cl-incf (cdar magit--refresh-cache))
(let ((value ,(macroexp-progn body)))
(push (cons ,k value)
(cdr magit--refresh-cache))
value)))
,@body)))
(defvar magit-with-editor-envvar "GIT_EDITOR"
"The environment variable exported by `magit-with-editor'.
Set this to \"GIT_SEQUENCE_EDITOR\" if you do not want to use
Emacs to edit commit messages but would like to do so to edit
rebase sequences.")
(defmacro magit-with-editor (&rest body)
"Like `with-editor*' but let-bind some more variables.
Also respect the value of `magit-with-editor-envvar'."
(declare (indent 0) (debug (body)))
`(let ((magit-process-popup-time -1)
;; 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)
;; If we have Cygwin mount points,
;; the git flavor is cygwin, so dos
;; shell quoting is probably wrong.
(not magit-cygwin-mount-points))
"cmdproxy"
shell-file-name)))
(with-editor* magit-with-editor-envvar
,@body)))
(defmacro magit--with-temp-process-buffer (&rest body)
"Like `with-temp-buffer', but always propagate `process-environment'.
When that var is buffer-local in the calling buffer, it is not
propagated by `with-temp-buffer', so we explicitly ensure that
happens, so that processes will be invoked consistently. BODY is
as for that macro."
(declare (indent 0) (debug (body)))
(let ((p (cl-gensym)))
`(let ((,p process-environment))
(with-temp-buffer
(setq-local process-environment ,p)
,@body))))
(defsubst magit-git-executable ()
"Return value of `magit-git-executable' or `magit-remote-git-executable'.
The variable is chosen depending on whether `default-directory'
is remote."
(if (file-remote-p default-directory)
magit-remote-git-executable
magit-git-executable))
(defun magit-process-git-arguments (args)
"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.
* Prepend `magit-git-global-arguments' to ARGS.
* On w32 systems, encode to `w32-ansi-code-page'."
(setq args (append magit-git-global-arguments (flatten-tree 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))
(defun magit-git-exit-code (&rest args)
"Execute Git with ARGS, returning its exit code."
(magit-process-git nil 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))
(defun magit-git-string-p (&rest args)
"Execute Git with ARGS, returning the first line of its output.
If the exit code isn't zero or if there is no output, then return
nil. Neither of these results is considered an error; if that is
what you want, then use `magit-git-string-ng' instead.
This is an experimental replacement for `magit-git-string', and
still subject to major changes."
(magit--with-refresh-cache (cons default-directory args)
(magit--with-temp-process-buffer
(and (zerop (magit-process-git t args))
(not (bobp))
(progn
(goto-char (point-min))
(buffer-substring-no-properties (point) (line-end-position)))))))
(defun magit-git-string-ng (&rest args)
"Execute Git with ARGS, returning the first line of its output.
If the exit code isn't zero or if there is no output, then that
is considered an error, but instead of actually signaling an
error, return nil. Additionally the output is put in the process
buffer (creating it if necessary) and the error message is shown
in the status buffer (provided it exists).
This is an experimental replacement for `magit-git-string', and
still subject to major changes. Also see `magit-git-string-p'."
(magit--with-refresh-cache
(list default-directory 'magit-git-string-ng args)
(magit--with-temp-process-buffer
(let* ((args (magit-process-git-arguments args))
(status (magit-process-git t args)))
(if (zerop status)
(and (not (bobp))
(progn
(goto-char (point-min))
(buffer-substring-no-properties
(point) (line-end-position))))
(let ((buf (current-buffer)))
(with-current-buffer (magit-process-buffer t)
(magit-process-insert-section default-directory
magit-git-executable args
status buf)))
(when-let ((status-buf (magit-get-mode-buffer 'magit-status-mode)))
(let ((msg (magit--locate-error-message)))
(with-current-buffer status-buf
(setq magit-this-error msg))))
nil)))))
(defun magit-git-str (&rest args)
"Execute Git with ARGS, returning the first line of its output.
If there is no output, return nil. If the output begins with a
newline, return an empty string. Like `magit-git-string' but
ignore `magit-git-debug'."
(setq args (flatten-tree args))
(magit--with-refresh-cache (cons default-directory args)
(magit--with-temp-process-buffer
(magit-process-git (list t nil) args)
(unless (bobp)
(goto-char (point-min))
(buffer-substring-no-properties (point) (line-end-position))))))
(defun magit-git-output (&rest args)
"Execute Git with ARGS, returning its output."
(setq args (flatten-tree args))
(magit--with-refresh-cache (cons default-directory args)
(magit--with-temp-process-buffer
(magit-process-git (list t nil) args)
(buffer-substring-no-properties (point-min) (point-max)))))
(define-error 'magit-invalid-git-boolean "Not a Git boolean")
(defun magit-git-true (&rest args)
"Execute Git with ARGS, returning t if it prints \"true\".
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 (list output)))))
(defun magit-git-false (&rest args)
"Execute Git with ARGS, returning t if it prints \"false\".
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 (list output)))))
(defun magit-git-config-p (variable &optional default)
"Return the boolean value of the Git variable VARIABLE.
VARIABLE has to be specified as a string. Return DEFAULT (which
defaults to nil) if VARIABLE is unset. If VARIABLE's value isn't
a boolean, then raise an error."
(let ((args (list "config" "--bool" "--default" (if default "true" "false")
variable)))
(magit--with-refresh-cache (cons default-directory args)
(magit--with-temp-process-buffer
(let ((status (magit-process-git t args))
(output (buffer-substring (point-min) (1- (point-max)))))
(if (zerop status)
(equal output "true")
(signal 'magit-invalid-git-boolean (list output))))))))
(defun magit-git-insert (&rest args)
"Execute Git with ARGS, inserting its output at point.
If Git exits with a non-zero exit status, then show a message and
add a section in the respective process buffer."
(apply #'magit--git-insert nil args))
(defun magit--git-insert (return-error &rest args)
(setq args (magit-process-git-arguments args))
(if (or return-error magit-git-debug)
(let (log)
(unwind-protect
(let (exit errmsg)
(setq log (make-temp-file "magit-stderr"))
(delete-file log)
(setq exit (magit-process-git (list t log) args))
(when (> exit 0)
(when (file-exists-p log)
(with-temp-buffer
(insert-file-contents log)
(goto-char (point-max))
(setq errmsg
(if (functionp magit-git-debug)
(funcall magit-git-debug (buffer-string))
(magit--locate-error-message))))
(unless return-error
(let ((magit-git-debug nil))
(with-current-buffer (magit-process-buffer t)
(magit-process-insert-section default-directory
magit-git-executable
args exit log)))))
(unless return-error
(if errmsg
(message "%s" errmsg)
(message "Git returned with exit-code %s" exit))))
(or errmsg exit))
(ignore-errors (delete-file log))))
(magit-process-git (list t nil) args)))
(defun magit--locate-error-message ()
(goto-char (point-max))
(and (run-hook-wrapped 'magit-process-error-message-regexps
(lambda (re) (re-search-backward re nil t)))
(match-string-no-properties 1)))
(defun magit-git-string (&rest args)
"Execute Git with ARGS, returning the first line of its output.
If there is no output, return nil. If the output begins with a
newline, return an empty string."
(setq args (flatten-tree args))
(magit--with-refresh-cache (cons default-directory args)
(magit--with-temp-process-buffer
(apply #'magit-git-insert args)
(unless (bobp)
(goto-char (point-min))
(buffer-substring-no-properties (point) (line-end-position))))))
(defun magit-git-lines (&rest args)
"Execute Git with ARGS, returning its output as a list of lines.
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."
(magit--with-temp-process-buffer
(apply #'magit-git-insert args)
(split-string (buffer-string) "\n" t)))
(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."
(magit--with-temp-process-buffer
(apply #'magit-git-insert args)
(split-string (buffer-string) "\0" t)))
(defvar magit--git-wash-keep-error nil) ; experimental
(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
output, call `magit-cancel-section'. Otherwise temporarily narrow
the buffer to the inserted text, move to its beginning, and then
call function WASHER with ARGS as its sole argument."
(declare (indent 1))
(apply #'magit--git-wash washer magit--git-wash-keep-error args))
(defun magit--git-wash (washer keep-error &rest args)
(declare (indent 2))
(setq args (flatten-tree args))
(let ((beg (point))
(exit (magit--git-insert keep-error args)))
(when (stringp exit)
(goto-char beg)
(insert (propertize exit 'face 'error))
(unless (bolp)
(insert "\n")))
(if (= (point) beg)
(magit-cancel-section)
(unless (bolp)
(insert "\n"))
(when (equal exit 0)
(save-restriction
(narrow-to-region beg (point))
(goto-char beg)
(funcall washer args))
(when (or (= (point) beg)
(= (point) (1+ beg)))
(magit-cancel-section))
(magit-maybe-make-margin-overlay)))
exit))
(defun magit-git-executable-find (command)
"Search for COMMAND in Git's exec path, falling back to `exec-path'.
Like `executable-find', return the absolute file name of the
executable."
(or (locate-file command
(list (concat
(file-remote-p default-directory)
(or (magit-git-string "--exec-path")
(error "`git --exec-path' failed"))))
exec-suffixes
#'file-executable-p)
(compat-call executable-find command t)))
;;; Git Version
(defconst magit--git-version-regexp
"\\`git version \\([0-9]+\\(\\.[0-9]+\\)\\{1,2\\}\\)")
(defvar magit--host-git-version-cache nil)
(defun magit-git-version>= (n)
"Return t if `magit-git-version's value is greater than or equal to N."
(magit--version>= (magit-git-version) n))
(defun magit-git-version< (n)
"Return t if `magit-git-version's value is smaller than N."
(version< (magit-git-version) n))
(defun magit-git-version ()
"Return the Git version used for `default-directory'.
Raise an error if Git cannot be found, if it exits with a
non-zero status, or the output does not have the expected
format."
(magit--with-refresh-cache default-directory
(let ((host (file-remote-p default-directory)))
(or (cdr (assoc host magit--host-git-version-cache))
(magit--with-temp-process-buffer
;; Unset global arguments for ancient Git versions.
(let* ((magit-git-global-arguments nil)
(status (magit-process-git t "version"))
(output (buffer-string)))
(cond
((not (zerop status))
(display-warning
'magit
(format "%S\n\nRunning \"%s --version\" failed with output:\n\n%s"
(if host
(format "Magit cannot find Git on host %S.\n
Check the value of `magit-remote-git-executable' using
`magit-debug-git-executable' and consult the info node
`(tramp)Remote programs'." host)
"Magit cannot find Git.\n
Check the values of `magit-git-executable' and `exec-path'
using `magit-debug-git-executable'.")
(magit-git-executable)
output)))
((save-match-data
(and (string-match magit--git-version-regexp output)
(let ((version (match-string 1 output)))
(push (cons host version)
magit--host-git-version-cache)
version))))
(t (error "Unexpected \"%s --version\" output: %S"
(magit-git-executable)
output)))))))))
(defun magit-git-version-assert (&optional minimal who)
"Assert that the used Git version is greater than or equal to MINIMAL.
If optional MINIMAL is nil, compare with `magit--minimal-git'
instead. Optional WHO if non-nil specifies what functionality
needs at least MINIMAL, otherwise it defaults to \"Magit\"."
(when (magit-git-version< (or minimal magit--minimal-git))
(let* ((host (file-remote-p default-directory))
(msg (format-spec
(cond (host "\
%w requires Git %m or greater, but on %h the version is %v.
If multiple Git versions are installed on the host, then the
problem might be that TRAMP uses the wrong executable.
Check the value of `magit-remote-git-executable' and consult
the info node `(tramp)Remote programs'.\n")
(t "\
%w requires Git %m or greater, but you are using %v.
If you have multiple Git versions installed, then check the
values of `magit-remote-git-executable' and `exec-path'.\n"))
`((?w . ,(or who "Magit"))
(?m . ,(or minimal magit--minimal-git))
(?v . ,(magit-git-version))
(?h . ,host)))))
(display-warning 'magit msg :error))))
(defun magit--safe-git-version ()
"Return the Git version used for `default-directory' or an error message."
(magit--with-temp-process-buffer
(let* ((magit-git-global-arguments nil)
(status (magit-process-git t "version"))
(output (buffer-string)))
(cond ((not (zerop status)) output)
((save-match-data
(and (string-match magit--git-version-regexp output)
(match-string 1 output))))
(t output)))))
(defun magit-debug-git-executable ()
"Display a buffer with information about `magit-git-executable'.
Also include information about `magit-remote-git-executable'.
See info node `(magit)Debugging Tools' for more information."
(interactive)
(with-current-buffer (get-buffer-create "*magit-git-debug*")
(pop-to-buffer (current-buffer))
(erase-buffer)
(insert (format "magit-remote-git-executable: %S\n"
magit-remote-git-executable))
(insert (concat
(format "magit-git-executable: %S" magit-git-executable)
(and (not (file-name-absolute-p magit-git-executable))
(format " [%S]" (executable-find magit-git-executable)))
(format " (%s)\n" (magit--safe-git-version))))
(insert (format "exec-path: %S\n" exec-path))
(when-let ((diff (cl-set-difference
(seq-filter #'file-exists-p (remq nil (parse-colon-path
(getenv "PATH"))))
(seq-filter #'file-exists-p (remq nil exec-path))
:test #'file-equal-p)))
(insert (format " entries in PATH, but not in exec-path: %S\n" diff)))
(dolist (execdir exec-path)
(insert (format " %s (%s)\n" execdir (car (file-attributes execdir))))
(when (file-directory-p execdir)
(dolist (exec (directory-files
execdir t (concat
"\\`git" (regexp-opt exec-suffixes) "\\'")))
(insert (format " %s (%s)\n" exec
(magit--safe-git-version))))))))
;;; Variables
(defun magit-config-get-from-cached-list (key)
(gethash
;; `git config --list' downcases first and last components of the key.
(let* ((key (replace-regexp-in-string "\\`[^.]+" #'downcase key t t))
(key (replace-regexp-in-string "[^.]+\\'" #'downcase key t t)))
key)
(magit--with-refresh-cache (cons (magit-toplevel) 'config)
(let ((configs (make-hash-table :test #'equal)))
(dolist (conf (magit-git-items "config" "--list" "-z"))
(let* ((nl-pos (cl-position ?\n conf))
(key (substring conf 0 nl-pos))
(val (if nl-pos (substring conf (1+ nl-pos)) "")))
(puthash key (nconc (gethash key configs) (list val)) configs)))
configs))))
(defun magit-get (&rest keys)
"Return the value of the Git variable specified by KEYS."
(car (last (apply #'magit-get-all keys))))
(defun magit-get-all (&rest keys)
"Return all values of the Git variable specified by KEYS."
(let ((magit-git-debug nil)
(arg (and (or (null (car keys))
(string-prefix-p "--" (car keys)))
(pop keys)))
(key (mapconcat #'identity keys ".")))
(if (and magit--refresh-cache (not arg))
(magit-config-get-from-cached-list key)
(magit-git-items "config" arg "-z" "--get-all" key))))
(defun magit-get-boolean (&rest keys)
"Return the boolean value of the Git variable specified by KEYS.
Also see `magit-git-config-p'."
(let ((arg (and (or (null (car keys))
(string-prefix-p "--" (car keys)))
(pop keys)))
(key (mapconcat #'identity keys ".")))
(equal (if magit--refresh-cache
(car (last (magit-config-get-from-cached-list key)))
(magit-git-str "config" arg "--bool" key))
"true")))
(defun magit-set (value &rest keys)
"Set the value of the Git variable specified by KEYS to VALUE."
(let ((arg (and (or (null (car keys))
(string-prefix-p "--" (car keys)))
(pop keys)))
(key (mapconcat #'identity keys ".")))
(if value
(magit-git-success "config" arg key value)
(magit-git-success "config" arg "--unset" key))
value))
(gv-define-setter magit-get (val &rest keys)
`(magit-set ,val ,@keys))
(defun magit-set-all (values &rest keys)
"Set all values of the Git variable specified by KEYS to VALUES."
(let ((arg (and (or (null (car keys))
(string-prefix-p "--" (car keys)))
(pop keys)))
(var (mapconcat #'identity keys ".")))
(when (magit-get var)
(magit-call-git "config" arg "--unset-all" var))
(dolist (v values)
(magit-call-git "config" arg "--add" var v))))
;;; Files
(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))
(while (not (magit-file-accessible-directory-p dir))
(setq dir (file-name-directory (directory-file-name dir)))
(when (equal dir previous)
(throw 'unsafe-default-dir nil))
(setq previous dir))
dir)))
(defmacro magit--with-safe-default-directory (file &rest body)
(declare (indent 1) (debug (form body)))
`(when-let ((default-directory (magit--safe-default-directory ,file)))
,@body))
(defun magit-git-dir (&optional path)
"Like (expand-file-name PATH (magit-gitdir)) or just (magit-gitdir)."
(declare (obsolete 'magit-gitdir "Magit 4.0.0"))
(and-let* ((dir (magit-gitdir)))
(if path
(expand-file-name (convert-standard-filename path) dir)
dir)))
(defun magit-gitdir (&optional directory)
"Return the absolute and resolved path of the .git directory.
If the `GIT_DIR' environment variable is defined, return that.
Otherwise return the .git directory for DIRECTORY, or if that is
nil, then for `default-directory' instead. If the directory is
not located inside a Git repository, then return nil."
(let ((default-directory (or directory default-directory)))
(magit--with-refresh-cache (list default-directory 'magit-gitdir)
(magit--with-safe-default-directory nil
(and-let*
((dir (magit-rev-parse-safe "--git-dir"))
(dir (file-name-as-directory (magit-expand-git-file-name dir))))
(if (file-remote-p dir)
dir
(concat (file-remote-p default-directory) dir)))))))
(defvar magit--separated-gitdirs nil)
(defun magit--record-separated-gitdir ()
(let ((topdir (magit-toplevel))
(gitdir (magit-gitdir)))
;; Kludge: git-annex converts submodule gitdirs to symlinks. See #3599.
(when (file-symlink-p (directory-file-name gitdir))
(setq gitdir (file-truename gitdir)))
;; 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))))
(defun magit-toplevel (&optional directory)
"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."
(or
(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))
(cond
((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)))
(and-let*
((default-directory updir)
(top (and (string-equal
(magit-rev-parse-safe "--show-cdup") "")
(magit-rev-parse-safe "--show-toplevel"))))
(string-equal (magit-expand-git-file-name top) topdir))))
updir)
((concat (file-remote-p default-directory)
(file-name-as-directory topdir)))))
(and-let* ((gitdir (magit-rev-parse-safe "--git-dir"))
(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))))
(cond
((and wtree
;; Ignore .git/gitdir files that result from a
;; Git bug. See #2364.
(not (equal wtree ".git")))
;; Return the linked working tree.
(concat (file-remote-p default-directory)
(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)))
(;; Step outside the control directory to enter the
;; working tree.
(file-name-directory (directory-file-name gitdir))))))))))))
(defun magit--toplevel-safe ()
(or (magit-toplevel)
(magit--not-inside-repository-error)))
(defmacro magit-with-toplevel (&rest body)
(declare (indent defun) (debug (body)))
`(let ((default-directory (magit--toplevel-safe)))
,@body))
(define-error 'magit-outside-git-repo "Not inside Git repository")
(define-error 'magit-corrupt-git-config "Corrupt Git configuration")
(define-error 'magit-git-executable-not-found
"Git executable cannot be found (see https://magit.vc/goto/e6a78ed2)")
(defun magit--assert-usable-git ()
(if (not (compat-call executable-find (magit-git-executable) t))
(signal 'magit-git-executable-not-found (magit-git-executable))
(let ((magit-git-debug
(lambda (err)
(signal 'magit-corrupt-git-config
(format "%s: %s" default-directory err)))))
;; This should always succeed unless there's a corrupt config
;; (or at least a similarly severe failing state). Note that
;; git-config's --default is avoided because it's not available
;; until Git 2.18.
(magit-git-string "config" "--get-color" "" "reset"))
nil))
(defun magit--not-inside-repository-error ()
(magit--assert-usable-git)
(signal 'magit-outside-git-repo default-directory))
(defun magit-inside-gitdir-p (&optional 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."
(and (magit--assert-default-directory noerror)
;; Below a repository directory that is not located below the