forked from EnigmaCurry/emacs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
git.el
1705 lines (1544 loc) · 68.3 KB
/
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
;;; git.el --- A user interface for git
;; Copyright (C) 2005, 2006, 2007, 2008, 2009 Alexandre Julliard <julliard@winehq.org>
;; Version: 1.0
;; This program 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 2 of
;; the License, or (at your option) any later version.
;;
;; This program 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 this program; if not, write to the Free
;; Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
;; MA 02111-1307 USA
;;; Commentary:
;; This file contains an interface for the git version control
;; system. It provides easy access to the most frequently used git
;; commands. The user interface is as far as possible identical to
;; that of the PCL-CVS mode.
;;
;; To install: put this file on the load-path and place the following
;; in your .emacs file:
;;
;; (require 'git)
;;
;; To start: `M-x git-status'
;;
;; TODO
;; - diff against other branch
;; - renaming files from the status buffer
;; - creating tags
;; - fetch/pull
;; - revlist browser
;; - git-show-branch browser
;;
;;; Compatibility:
;;
;; This file works on GNU Emacs 21 or later. It may work on older
;; versions but this is not guaranteed.
;;
;; It may work on XEmacs 21, provided that you first install the ewoc
;; and log-edit packages.
;;
(eval-when-compile (require 'cl))
(require 'ewoc)
(require 'log-edit)
(require 'easymenu)
;;;; Customizations
;;;; ------------------------------------------------------------
(defgroup git nil
"A user interface for the git versioning system."
:group 'tools)
(defcustom git-committer-name nil
"User name to use for commits.
The default is to fall back to the repository config,
then to `add-log-full-name' and then to `user-full-name'."
:group 'git
:type '(choice (const :tag "Default" nil)
(string :tag "Name")))
(defcustom git-committer-email nil
"Email address to use for commits.
The default is to fall back to the git repository config,
then to `add-log-mailing-address' and then to `user-mail-address'."
:group 'git
:type '(choice (const :tag "Default" nil)
(string :tag "Email")))
(defcustom git-commits-coding-system nil
"Default coding system for the log message of git commits."
:group 'git
:type '(choice (const :tag "From repository config" nil)
(coding-system)))
(defcustom git-append-signed-off-by nil
"Whether to append a Signed-off-by line to the commit message before editing."
:group 'git
:type 'boolean)
(defcustom git-reuse-status-buffer t
"Whether `git-status' should try to reuse an existing buffer
if there is already one that displays the same directory."
:group 'git
:type 'boolean)
(defcustom git-per-dir-ignore-file ".gitignore"
"Name of the per-directory ignore file."
:group 'git
:type 'string)
(defcustom git-show-uptodate nil
"Whether to display up-to-date files."
:group 'git
:type 'boolean)
(defcustom git-show-ignored nil
"Whether to display ignored files."
:group 'git
:type 'boolean)
(defcustom git-show-unknown t
"Whether to display unknown files."
:group 'git
:type 'boolean)
(defface git-status-face
'((((class color) (background light)) (:foreground "purple"))
(((class color) (background dark)) (:foreground "salmon")))
"Git mode face used to highlight added and modified files."
:group 'git)
(defface git-unmerged-face
'((((class color) (background light)) (:foreground "red" :bold t))
(((class color) (background dark)) (:foreground "red" :bold t)))
"Git mode face used to highlight unmerged files."
:group 'git)
(defface git-unknown-face
'((((class color) (background light)) (:foreground "goldenrod" :bold t))
(((class color) (background dark)) (:foreground "goldenrod" :bold t)))
"Git mode face used to highlight unknown files."
:group 'git)
(defface git-uptodate-face
'((((class color) (background light)) (:foreground "grey60"))
(((class color) (background dark)) (:foreground "grey40")))
"Git mode face used to highlight up-to-date files."
:group 'git)
(defface git-ignored-face
'((((class color) (background light)) (:foreground "grey60"))
(((class color) (background dark)) (:foreground "grey40")))
"Git mode face used to highlight ignored files."
:group 'git)
(defface git-mark-face
'((((class color) (background light)) (:foreground "red" :bold t))
(((class color) (background dark)) (:foreground "tomato" :bold t)))
"Git mode face used for the file marks."
:group 'git)
(defface git-header-face
'((((class color) (background light)) (:foreground "blue"))
(((class color) (background dark)) (:foreground "blue")))
"Git mode face used for commit headers."
:group 'git)
(defface git-separator-face
'((((class color) (background light)) (:foreground "brown"))
(((class color) (background dark)) (:foreground "brown")))
"Git mode face used for commit separator."
:group 'git)
(defface git-permission-face
'((((class color) (background light)) (:foreground "green" :bold t))
(((class color) (background dark)) (:foreground "green" :bold t)))
"Git mode face used for permission changes."
:group 'git)
;;;; Utilities
;;;; ------------------------------------------------------------
(defconst git-log-msg-separator "--- log message follows this line ---")
(defvar git-log-edit-font-lock-keywords
`(("^\\(Author:\\|Date:\\|Merge:\\|Signed-off-by:\\)\\(.*\\)$"
(1 font-lock-keyword-face)
(2 font-lock-function-name-face))
(,(concat "^\\(" (regexp-quote git-log-msg-separator) "\\)$")
(1 font-lock-comment-face))))
(defun git-get-env-strings (env)
"Build a list of NAME=VALUE strings from a list of environment strings."
(mapcar (lambda (entry) (concat (car entry) "=" (cdr entry))) env))
(defun git-call-process (buffer &rest args)
"Wrapper for call-process that sets environment strings."
(apply #'call-process "git" nil buffer nil args))
(defun git-call-process-display-error (&rest args)
"Wrapper for call-process that displays error messages."
(let* ((dir default-directory)
(buffer (get-buffer-create "*Git Command Output*"))
(ok (with-current-buffer buffer
(let ((default-directory dir)
(buffer-read-only nil))
(erase-buffer)
(eq 0 (apply #'git-call-process (list buffer t) args))))))
(unless ok (display-message-or-buffer buffer))
ok))
(defun git-call-process-string (&rest args)
"Wrapper for call-process that returns the process output as a string,
or nil if the git command failed."
(with-temp-buffer
(and (eq 0 (apply #'git-call-process t args))
(buffer-string))))
(defun git-call-process-string-display-error (&rest args)
"Wrapper for call-process that displays error message and returns
the process output as a string, or nil if the git command failed."
(with-temp-buffer
(if (eq 0 (apply #'git-call-process (list t t) args))
(buffer-string)
(display-message-or-buffer (current-buffer))
nil)))
(defun git-run-process-region (buffer start end program args)
"Run a git process with a buffer region as input."
(let ((output-buffer (current-buffer))
(dir default-directory))
(with-current-buffer buffer
(cd dir)
(apply #'call-process-region start end program
nil (list output-buffer t) nil args))))
(defun git-run-command-buffer (buffer-name &rest args)
"Run a git command, sending the output to a buffer named BUFFER-NAME."
(let ((dir default-directory)
(buffer (get-buffer-create buffer-name)))
(message "Running git %s..." (car args))
(with-current-buffer buffer
(let ((default-directory dir)
(buffer-read-only nil))
(erase-buffer)
(apply #'git-call-process buffer args)))
(message "Running git %s...done" (car args))
buffer))
(defun git-run-command-region (buffer start end env &rest args)
"Run a git command with specified buffer region as input."
(with-temp-buffer
(if (eq 0 (if env
(git-run-process-region
buffer start end "env"
(append (git-get-env-strings env) (list "git") args))
(git-run-process-region buffer start end "git" args)))
(buffer-string)
(display-message-or-buffer (current-buffer))
nil)))
(defun git-run-hook (hook env &rest args)
"Run a git hook and display its output if any."
(let ((dir default-directory)
(hook-name (expand-file-name (concat ".git/hooks/" hook))))
(or (not (file-executable-p hook-name))
(let (status (buffer (get-buffer-create "*Git Hook Output*")))
(with-current-buffer buffer
(erase-buffer)
(cd dir)
(setq status
(if env
(apply #'call-process "env" nil (list buffer t) nil
(append (git-get-env-strings env) (list hook-name) args))
(apply #'call-process hook-name nil (list buffer t) nil args))))
(display-message-or-buffer buffer)
(eq 0 status)))))
(defun git-get-string-sha1 (string)
"Read a SHA1 from the specified string."
(and string
(string-match "[0-9a-f]\\{40\\}" string)
(match-string 0 string)))
(defun git-get-committer-name ()
"Return the name to use as GIT_COMMITTER_NAME."
; copied from log-edit
(or git-committer-name
(git-config "user.name")
(and (boundp 'add-log-full-name) add-log-full-name)
(and (fboundp 'user-full-name) (user-full-name))
(and (boundp 'user-full-name) user-full-name)))
(defun git-get-committer-email ()
"Return the email address to use as GIT_COMMITTER_EMAIL."
; copied from log-edit
(or git-committer-email
(git-config "user.email")
(and (boundp 'add-log-mailing-address) add-log-mailing-address)
(and (fboundp 'user-mail-address) (user-mail-address))
(and (boundp 'user-mail-address) user-mail-address)))
(defun git-get-commits-coding-system ()
"Return the coding system to use for commits."
(let ((repo-config (git-config "i18n.commitencoding")))
(or git-commits-coding-system
(and repo-config
(fboundp 'locale-charset-to-coding-system)
(locale-charset-to-coding-system repo-config))
'utf-8)))
(defun git-get-logoutput-coding-system ()
"Return the coding system used for git-log output."
(let ((repo-config (or (git-config "i18n.logoutputencoding")
(git-config "i18n.commitencoding"))))
(or git-commits-coding-system
(and repo-config
(fboundp 'locale-charset-to-coding-system)
(locale-charset-to-coding-system repo-config))
'utf-8)))
(defun git-escape-file-name (name)
"Escape a file name if necessary."
(if (string-match "[\n\t\"\\]" name)
(concat "\""
(mapconcat (lambda (c)
(case c
(?\n "\\n")
(?\t "\\t")
(?\\ "\\\\")
(?\" "\\\"")
(t (char-to-string c))))
name "")
"\"")
name))
(defun git-success-message (text files)
"Print a success message after having handled FILES."
(let ((n (length files)))
(if (equal n 1)
(message "%s %s" text (car files))
(message "%s %d files" text n))))
(defun git-get-top-dir (dir)
"Retrieve the top-level directory of a git tree."
(let ((cdup (with-output-to-string
(with-current-buffer standard-output
(cd dir)
(unless (eq 0 (git-call-process t "rev-parse" "--show-cdup"))
(error "cannot find top-level git tree for %s." dir))))))
(expand-file-name (concat (file-name-as-directory dir)
(car (split-string cdup "\n"))))))
;stolen from pcl-cvs
(defun git-append-to-ignore (file)
"Add a file name to the ignore file in its directory."
(let* ((fullname (expand-file-name file))
(dir (file-name-directory fullname))
(name (file-name-nondirectory fullname))
(ignore-name (expand-file-name git-per-dir-ignore-file dir))
(created (not (file-exists-p ignore-name))))
(save-window-excursion
(set-buffer (find-file-noselect ignore-name))
(goto-char (point-max))
(unless (zerop (current-column)) (insert "\n"))
(insert "/" name "\n")
(sort-lines nil (point-min) (point-max))
(save-buffer))
(when created
(git-call-process nil "update-index" "--add" "--" (file-relative-name ignore-name)))
(git-update-status-files (list (file-relative-name ignore-name)))))
; propertize definition for XEmacs, stolen from erc-compat
(eval-when-compile
(unless (fboundp 'propertize)
(defun propertize (string &rest props)
(let ((string (copy-sequence string)))
(while props
(put-text-property 0 (length string) (nth 0 props) (nth 1 props) string)
(setq props (cddr props)))
string))))
;;;; Wrappers for basic git commands
;;;; ------------------------------------------------------------
(defun git-rev-parse (rev)
"Parse a revision name and return its SHA1."
(git-get-string-sha1
(git-call-process-string "rev-parse" rev)))
(defun git-config (key)
"Retrieve the value associated to KEY in the git repository config file."
(let ((str (git-call-process-string "config" key)))
(and str (car (split-string str "\n")))))
(defun git-symbolic-ref (ref)
"Wrapper for the git-symbolic-ref command."
(let ((str (git-call-process-string "symbolic-ref" ref)))
(and str (car (split-string str "\n")))))
(defun git-update-ref (ref newval &optional oldval reason)
"Update a reference by calling git-update-ref."
(let ((args (and oldval (list oldval))))
(when newval (push newval args))
(push ref args)
(when reason
(push reason args)
(push "-m" args))
(unless newval (push "-d" args))
(apply 'git-call-process-display-error "update-ref" args)))
(defun git-for-each-ref (&rest specs)
"Return a list of refs using git-for-each-ref.
Each entry is a cons of (SHORT-NAME . FULL-NAME)."
(let (refs)
(with-temp-buffer
(apply #'git-call-process t "for-each-ref" "--format=%(refname)" specs)
(goto-char (point-min))
(while (re-search-forward "^[^/\n]+/[^/\n]+/\\(.+\\)$" nil t)
(push (cons (match-string 1) (match-string 0)) refs)))
(nreverse refs)))
(defun git-read-tree (tree &optional index-file)
"Read a tree into the index file."
(let ((process-environment
(append (and index-file (list (concat "GIT_INDEX_FILE=" index-file))) process-environment)))
(apply 'git-call-process-display-error "read-tree" (if tree (list tree)))))
(defun git-write-tree (&optional index-file)
"Call git-write-tree and return the resulting tree SHA1 as a string."
(let ((process-environment
(append (and index-file (list (concat "GIT_INDEX_FILE=" index-file))) process-environment)))
(git-get-string-sha1
(git-call-process-string-display-error "write-tree"))))
(defun git-commit-tree (buffer tree parent)
"Create a commit and possibly update HEAD.
Create a commit with the message in BUFFER using the tree with hash TREE.
Use PARENT as the parent of the new commit. If PARENT is the current \"HEAD\",
update the \"HEAD\" reference to the new commit."
(let ((author-name (git-get-committer-name))
(author-email (git-get-committer-email))
(subject "commit (initial): ")
author-date log-start log-end args coding-system-for-write)
(when parent
(setq subject "commit: ")
(push "-p" args)
(push parent args))
(with-current-buffer buffer
(goto-char (point-min))
(if
(setq log-start (re-search-forward (concat "^" (regexp-quote git-log-msg-separator) "\n") nil t))
(save-restriction
(narrow-to-region (point-min) log-start)
(goto-char (point-min))
(when (re-search-forward "^Author: +\\(.*?\\) *<\\(.*\\)> *$" nil t)
(setq author-name (match-string 1)
author-email (match-string 2)))
(goto-char (point-min))
(when (re-search-forward "^Date: +\\(.*\\)$" nil t)
(setq author-date (match-string 1)))
(goto-char (point-min))
(when (re-search-forward "^Merge: +\\(.*\\)" nil t)
(setq subject "commit (merge): ")
(dolist (parent (split-string (match-string 1) " +" t))
(push "-p" args)
(push parent args))))
(setq log-start (point-min)))
(setq log-end (point-max))
(goto-char log-start)
(when (re-search-forward ".*$" nil t)
(setq subject (concat subject (match-string 0))))
(setq coding-system-for-write buffer-file-coding-system))
(let ((commit
(git-get-string-sha1
(let ((env `(("GIT_AUTHOR_NAME" . ,author-name)
("GIT_AUTHOR_EMAIL" . ,author-email)
("GIT_COMMITTER_NAME" . ,(git-get-committer-name))
("GIT_COMMITTER_EMAIL" . ,(git-get-committer-email)))))
(when author-date (push `("GIT_AUTHOR_DATE" . ,author-date) env))
(apply #'git-run-command-region
buffer log-start log-end env
"commit-tree" tree (nreverse args))))))
(when commit (git-update-ref "HEAD" commit parent subject))
commit)))
(defun git-empty-db-p ()
"Check if the git db is empty (no commit done yet)."
(not (eq 0 (git-call-process nil "rev-parse" "--verify" "HEAD"))))
(defun git-get-merge-heads ()
"Retrieve the merge heads from the MERGE_HEAD file if present."
(let (heads)
(when (file-readable-p ".git/MERGE_HEAD")
(with-temp-buffer
(insert-file-contents ".git/MERGE_HEAD" nil nil nil t)
(goto-char (point-min))
(while (re-search-forward "[0-9a-f]\\{40\\}" nil t)
(push (match-string 0) heads))))
(nreverse heads)))
(defun git-get-commit-description (commit)
"Get a one-line description of COMMIT."
(let ((coding-system-for-read (git-get-logoutput-coding-system)))
(let ((descr (git-call-process-string "log" "--max-count=1" "--pretty=oneline" commit)))
(if (and descr (string-match "\\`\\([0-9a-f]\\{40\\}\\) *\\(.*\\)$" descr))
(concat (substring (match-string 1 descr) 0 10) " - " (match-string 2 descr))
descr))))
;;;; File info structure
;;;; ------------------------------------------------------------
; fileinfo structure stolen from pcl-cvs
(defstruct (git-fileinfo
(:copier nil)
(:constructor git-create-fileinfo (state name &optional old-perm new-perm rename-state orig-name marked))
(:conc-name git-fileinfo->))
marked ;; t/nil
state ;; current state
name ;; file name
old-perm new-perm ;; permission flags
rename-state ;; rename or copy state
orig-name ;; original name for renames or copies
needs-update ;; whether file needs to be updated
needs-refresh) ;; whether file needs to be refreshed
(defvar git-status nil)
(defun git-set-fileinfo-state (info state)
"Set the state of a file info."
(unless (eq (git-fileinfo->state info) state)
(setf (git-fileinfo->state info) state
(git-fileinfo->new-perm info) (git-fileinfo->old-perm info)
(git-fileinfo->rename-state info) nil
(git-fileinfo->orig-name info) nil
(git-fileinfo->needs-update info) nil
(git-fileinfo->needs-refresh info) t)))
(defun git-status-filenames-map (status func files &rest args)
"Apply FUNC to the status files names in the FILES list.
The list must be sorted."
(when files
(let ((file (pop files))
(node (ewoc-nth status 0)))
(while (and file node)
(let* ((info (ewoc-data node))
(name (git-fileinfo->name info)))
(if (string-lessp name file)
(setq node (ewoc-next status node))
(if (string-equal name file)
(apply func info args))
(setq file (pop files))))))))
(defun git-set-filenames-state (status files state)
"Set the state of a list of named files. The list must be sorted"
(when files
(git-status-filenames-map status #'git-set-fileinfo-state files state)
(unless state ;; delete files whose state has been set to nil
(ewoc-filter status (lambda (info) (git-fileinfo->state info))))))
(defun git-state-code (code)
"Convert from a string to a added/deleted/modified state."
(case (string-to-char code)
(?M 'modified)
(?? 'unknown)
(?A 'added)
(?D 'deleted)
(?U 'unmerged)
(?T 'modified)
(t nil)))
(defun git-status-code-as-string (code)
"Format a git status code as string."
(case code
('modified (propertize "Modified" 'face 'git-status-face))
('unknown (propertize "Unknown " 'face 'git-unknown-face))
('added (propertize "Added " 'face 'git-status-face))
('deleted (propertize "Deleted " 'face 'git-status-face))
('unmerged (propertize "Unmerged" 'face 'git-unmerged-face))
('uptodate (propertize "Uptodate" 'face 'git-uptodate-face))
('ignored (propertize "Ignored " 'face 'git-ignored-face))
(t "? ")))
(defun git-file-type-as-string (old-perm new-perm)
"Return a string describing the file type based on its permissions."
(let* ((old-type (lsh (or old-perm 0) -9))
(new-type (lsh (or new-perm 0) -9))
(str (case new-type
(64 ;; file
(case old-type
(64 nil)
(80 " (type change symlink -> file)")
(112 " (type change subproject -> file)")))
(80 ;; symlink
(case old-type
(64 " (type change file -> symlink)")
(112 " (type change subproject -> symlink)")
(t " (symlink)")))
(112 ;; subproject
(case old-type
(64 " (type change file -> subproject)")
(80 " (type change symlink -> subproject)")
(t " (subproject)")))
(72 nil) ;; directory (internal, not a real git state)
(0 ;; deleted or unknown
(case old-type
(80 " (symlink)")
(112 " (subproject)")))
(t (format " (unknown type %o)" new-type)))))
(cond (str (propertize str 'face 'git-status-face))
((eq new-type 72) "/")
(t ""))))
(defun git-rename-as-string (info)
"Return a string describing the copy or rename associated with INFO, or an empty string if none."
(let ((state (git-fileinfo->rename-state info)))
(if state
(propertize
(concat " ("
(if (eq state 'copy) "copied from "
(if (eq (git-fileinfo->state info) 'added) "renamed from "
"renamed to "))
(git-escape-file-name (git-fileinfo->orig-name info))
")") 'face 'git-status-face)
"")))
(defun git-permissions-as-string (old-perm new-perm)
"Format a permission change as string."
(propertize
(if (or (not old-perm)
(not new-perm)
(eq 0 (logand ?\111 (logxor old-perm new-perm))))
" "
(if (eq 0 (logand ?\111 old-perm)) "+x" "-x"))
'face 'git-permission-face))
(defun git-fileinfo-prettyprint (info)
"Pretty-printer for the git-fileinfo structure."
(let ((old-perm (git-fileinfo->old-perm info))
(new-perm (git-fileinfo->new-perm info)))
(insert (concat " " (if (git-fileinfo->marked info) (propertize "*" 'face 'git-mark-face) " ")
" " (git-status-code-as-string (git-fileinfo->state info))
" " (git-permissions-as-string old-perm new-perm)
" " (git-escape-file-name (git-fileinfo->name info))
(git-file-type-as-string old-perm new-perm)
(git-rename-as-string info)))))
(defun git-update-node-fileinfo (node info)
"Update the fileinfo of the specified node. The names are assumed to match already."
(let ((data (ewoc-data node)))
(setf
;; preserve the marked flag
(git-fileinfo->marked info) (git-fileinfo->marked data)
(git-fileinfo->needs-update data) nil)
(when (not (equal info data))
(setf (git-fileinfo->needs-refresh info) t
(ewoc-data node) info))))
(defun git-insert-info-list (status infolist files)
"Insert a sorted list of file infos in the status buffer, replacing existing ones if any."
(let* ((info (pop infolist))
(node (ewoc-nth status 0))
(name (and info (git-fileinfo->name info)))
remaining)
(while info
(let ((nodename (and node (git-fileinfo->name (ewoc-data node)))))
(while (and files (string-lessp (car files) name))
(push (pop files) remaining))
(when (and files (string-equal (car files) name))
(setq files (cdr files)))
(cond ((not nodename)
(setq node (ewoc-enter-last status info))
(setq info (pop infolist))
(setq name (and info (git-fileinfo->name info))))
((string-lessp nodename name)
(setq node (ewoc-next status node)))
((string-equal nodename name)
;; preserve the marked flag
(git-update-node-fileinfo node info)
(setq info (pop infolist))
(setq name (and info (git-fileinfo->name info))))
(t
(setq node (ewoc-enter-before status node info))
(setq info (pop infolist))
(setq name (and info (git-fileinfo->name info)))))))
(nconc (nreverse remaining) files)))
(defun git-run-diff-index (status files)
"Run git-diff-index on FILES and parse the results into STATUS.
Return the list of files that haven't been handled."
(let (infolist)
(with-temp-buffer
(apply #'git-call-process t "diff-index" "-z" "-M" "HEAD" "--" files)
(goto-char (point-min))
(while (re-search-forward
":\\([0-7]\\{6\\}\\) \\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} [0-9a-f]\\{40\\} \\(\\([ADMUT]\\)\0\\([^\0]+\\)\\|\\([CR]\\)[0-9]*\0\\([^\0]+\\)\0\\([^\0]+\\)\\)\0"
nil t 1)
(let ((old-perm (string-to-number (match-string 1) 8))
(new-perm (string-to-number (match-string 2) 8))
(state (or (match-string 4) (match-string 6)))
(name (or (match-string 5) (match-string 7)))
(new-name (match-string 8)))
(if new-name ; copy or rename
(if (eq ?C (string-to-char state))
(push (git-create-fileinfo 'added new-name old-perm new-perm 'copy name) infolist)
(push (git-create-fileinfo 'deleted name 0 0 'rename new-name) infolist)
(push (git-create-fileinfo 'added new-name old-perm new-perm 'rename name) infolist))
(push (git-create-fileinfo (git-state-code state) name old-perm new-perm) infolist)))))
(setq infolist (sort (nreverse infolist)
(lambda (info1 info2)
(string-lessp (git-fileinfo->name info1)
(git-fileinfo->name info2)))))
(git-insert-info-list status infolist files)))
(defun git-find-status-file (status file)
"Find a given file in the status ewoc and return its node."
(let ((node (ewoc-nth status 0)))
(while (and node (not (string= file (git-fileinfo->name (ewoc-data node)))))
(setq node (ewoc-next status node)))
node))
(defun git-run-ls-files (status files default-state &rest options)
"Run git-ls-files on FILES and parse the results into STATUS.
Return the list of files that haven't been handled."
(let (infolist)
(with-temp-buffer
(apply #'git-call-process t "ls-files" "-z" (append options (list "--") files))
(goto-char (point-min))
(while (re-search-forward "\\([^\0]*?\\)\\(/?\\)\0" nil t 1)
(let ((name (match-string 1)))
(push (git-create-fileinfo default-state name 0
(if (string-equal "/" (match-string 2)) (lsh ?\110 9) 0))
infolist))))
(setq infolist (nreverse infolist)) ;; assume it is sorted already
(git-insert-info-list status infolist files)))
(defun git-run-ls-files-cached (status files default-state)
"Run git-ls-files -c on FILES and parse the results into STATUS.
Return the list of files that haven't been handled."
(let (infolist)
(with-temp-buffer
(apply #'git-call-process t "ls-files" "-z" "-s" "-c" "--" files)
(goto-char (point-min))
(while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 0\t\\([^\0]+\\)\0" nil t)
(let* ((new-perm (string-to-number (match-string 1) 8))
(old-perm (if (eq default-state 'added) 0 new-perm))
(name (match-string 2)))
(push (git-create-fileinfo default-state name old-perm new-perm) infolist))))
(setq infolist (nreverse infolist)) ;; assume it is sorted already
(git-insert-info-list status infolist files)))
(defun git-run-ls-unmerged (status files)
"Run git-ls-files -u on FILES and parse the results into STATUS."
(with-temp-buffer
(apply #'git-call-process t "ls-files" "-z" "-u" "--" files)
(goto-char (point-min))
(let (unmerged-files)
(while (re-search-forward "[0-7]\\{6\\} [0-9a-f]\\{40\\} [123]\t\\([^\0]+\\)\0" nil t)
(push (match-string 1) unmerged-files))
(setq unmerged-files (nreverse unmerged-files)) ;; assume it is sorted already
(git-set-filenames-state status unmerged-files 'unmerged))))
(defun git-get-exclude-files ()
"Get the list of exclude files to pass to git-ls-files."
(let (files
(config (git-config "core.excludesfile")))
(when (file-readable-p ".git/info/exclude")
(push ".git/info/exclude" files))
(when (and config (file-readable-p config))
(push config files))
files))
(defun git-run-ls-files-with-excludes (status files default-state &rest options)
"Run git-ls-files on FILES with appropriate --exclude-from options."
(let ((exclude-files (git-get-exclude-files)))
(apply #'git-run-ls-files status files default-state "--directory" "--no-empty-directory"
(concat "--exclude-per-directory=" git-per-dir-ignore-file)
(append options (mapcar (lambda (f) (concat "--exclude-from=" f)) exclude-files)))))
(defun git-update-status-files (&optional files mark-files)
"Update the status of FILES from the index.
The FILES list must be sorted."
(unless git-status (error "Not in git-status buffer."))
;; set the needs-update flag on existing files
(if files
(git-status-filenames-map
git-status (lambda (info) (setf (git-fileinfo->needs-update info) t)) files)
(ewoc-map (lambda (info) (setf (git-fileinfo->needs-update info) t) nil) git-status)
(git-call-process nil "update-index" "--refresh")
(when git-show-uptodate
(git-run-ls-files-cached git-status nil 'uptodate)))
(let ((remaining-files
(if (git-empty-db-p) ; we need some special handling for an empty db
(git-run-ls-files-cached git-status files 'added)
(git-run-diff-index git-status files))))
(git-run-ls-unmerged git-status files)
(when (or remaining-files (and git-show-unknown (not files)))
(setq remaining-files (git-run-ls-files-with-excludes git-status remaining-files 'unknown "-o")))
(when (or remaining-files (and git-show-ignored (not files)))
(setq remaining-files (git-run-ls-files-with-excludes git-status remaining-files 'ignored "-o" "-i")))
(unless files
(setq remaining-files (git-get-filenames (ewoc-collect git-status #'git-fileinfo->needs-update))))
(when remaining-files
(setq remaining-files (git-run-ls-files-cached git-status remaining-files 'uptodate)))
(git-set-filenames-state git-status remaining-files nil)
(when mark-files (git-mark-files git-status files))
(git-refresh-files)
(git-refresh-ewoc-hf git-status)))
(defun git-mark-files (status files)
"Mark all the specified FILES, and unmark the others."
(let ((file (and files (pop files)))
(node (ewoc-nth status 0)))
(while node
(let ((info (ewoc-data node)))
(if (and file (string-equal (git-fileinfo->name info) file))
(progn
(unless (git-fileinfo->marked info)
(setf (git-fileinfo->marked info) t)
(setf (git-fileinfo->needs-refresh info) t))
(setq file (pop files))
(setq node (ewoc-next status node)))
(when (git-fileinfo->marked info)
(setf (git-fileinfo->marked info) nil)
(setf (git-fileinfo->needs-refresh info) t))
(if (and file (string-lessp file (git-fileinfo->name info)))
(setq file (pop files))
(setq node (ewoc-next status node))))))))
(defun git-marked-files ()
"Return a list of all marked files, or if none a list containing just the file at cursor position."
(unless git-status (error "Not in git-status buffer."))
(or (ewoc-collect git-status (lambda (info) (git-fileinfo->marked info)))
(list (ewoc-data (ewoc-locate git-status)))))
(defun git-marked-files-state (&rest states)
"Return a sorted list of marked files that are in the specified states."
(let ((files (git-marked-files))
result)
(dolist (info files)
(when (memq (git-fileinfo->state info) states)
(push info result)))
(nreverse result)))
(defun git-refresh-files ()
"Refresh all files that need it and clear the needs-refresh flag."
(unless git-status (error "Not in git-status buffer."))
(ewoc-map
(lambda (info)
(let ((refresh (git-fileinfo->needs-refresh info)))
(setf (git-fileinfo->needs-refresh info) nil)
refresh))
git-status)
; move back to goal column
(when goal-column (move-to-column goal-column)))
(defun git-refresh-ewoc-hf (status)
"Refresh the ewoc header and footer."
(let ((branch (git-symbolic-ref "HEAD"))
(head (if (git-empty-db-p) "Nothing committed yet"
(git-get-commit-description "HEAD")))
(merge-heads (git-get-merge-heads)))
(ewoc-set-hf status
(format "Directory: %s\nBranch: %s\nHead: %s%s\n"
default-directory
(if branch
(if (string-match "^refs/heads/" branch)
(substring branch (match-end 0))
branch)
"none (detached HEAD)")
head
(if merge-heads
(concat "\nMerging: "
(mapconcat (lambda (str) (git-get-commit-description str)) merge-heads "\n "))
""))
(if (ewoc-nth status 0) "" " No changes."))))
(defun git-get-filenames (files)
(mapcar (lambda (info) (git-fileinfo->name info)) files))
(defun git-update-index (index-file files)
"Run git-update-index on a list of files."
(let ((process-environment (append (and index-file (list (concat "GIT_INDEX_FILE=" index-file)))
process-environment))
added deleted modified)
(dolist (info files)
(case (git-fileinfo->state info)
('added (push info added))
('deleted (push info deleted))
('modified (push info modified))))
(and
(or (not added) (apply #'git-call-process-display-error "update-index" "--add" "--" (git-get-filenames added)))
(or (not deleted) (apply #'git-call-process-display-error "update-index" "--remove" "--" (git-get-filenames deleted)))
(or (not modified) (apply #'git-call-process-display-error "update-index" "--" (git-get-filenames modified))))))
(defun git-run-pre-commit-hook ()
"Run the pre-commit hook if any."
(unless git-status (error "Not in git-status buffer."))
(let ((files (git-marked-files-state 'added 'deleted 'modified)))
(or (not files)
(not (file-executable-p ".git/hooks/pre-commit"))
(let ((index-file (make-temp-file "gitidx")))
(unwind-protect
(let ((head-tree (unless (git-empty-db-p) (git-rev-parse "HEAD^{tree}"))))
(git-read-tree head-tree index-file)
(git-update-index index-file files)
(git-run-hook "pre-commit" `(("GIT_INDEX_FILE" . ,index-file))))
(delete-file index-file))))))
(defun git-do-commit ()
"Perform the actual commit using the current buffer as log message."
(interactive)
(let ((buffer (current-buffer))
(index-file (make-temp-file "gitidx")))
(with-current-buffer log-edit-parent-buffer
(if (git-marked-files-state 'unmerged)
(message "You cannot commit unmerged files, resolve them first.")
(unwind-protect
(let ((files (git-marked-files-state 'added 'deleted 'modified))
head tree head-tree)
(unless (git-empty-db-p)
(setq head (git-rev-parse "HEAD")
head-tree (git-rev-parse "HEAD^{tree}")))
(message "Running git commit...")
(when
(and
(git-read-tree head-tree index-file)
(git-update-index nil files) ;update both the default index
(git-update-index index-file files) ;and the temporary one
(setq tree (git-write-tree index-file)))
(if (or (not (string-equal tree head-tree))
(yes-or-no-p "The tree was not modified, do you really want to perform an empty commit? "))
(let ((commit (git-commit-tree buffer tree head)))
(when commit
(condition-case nil (delete-file ".git/MERGE_HEAD") (error nil))
(condition-case nil (delete-file ".git/MERGE_MSG") (error nil))
(with-current-buffer buffer (erase-buffer))
(git-update-status-files (git-get-filenames files))
(git-call-process nil "rerere")
(git-call-process nil "gc" "--auto")
(message "Committed %s." commit)
(git-run-hook "post-commit" nil)))
(message "Commit aborted."))))
(delete-file index-file))))))
;;;; Interactive functions
;;;; ------------------------------------------------------------
(defun git-mark-file ()
"Mark the file that the cursor is on and move to the next one."
(interactive)
(unless git-status (error "Not in git-status buffer."))
(let* ((pos (ewoc-locate git-status))
(info (ewoc-data pos)))
(setf (git-fileinfo->marked info) t)
(ewoc-invalidate git-status pos)
(ewoc-goto-next git-status 1)))
(defun git-unmark-file ()
"Unmark the file that the cursor is on and move to the next one."
(interactive)
(unless git-status (error "Not in git-status buffer."))
(let* ((pos (ewoc-locate git-status))
(info (ewoc-data pos)))
(setf (git-fileinfo->marked info) nil)
(ewoc-invalidate git-status pos)
(ewoc-goto-next git-status 1)))
(defun git-unmark-file-up ()
"Unmark the file that the cursor is on and move to the previous one."
(interactive)
(unless git-status (error "Not in git-status buffer."))
(let* ((pos (ewoc-locate git-status))
(info (ewoc-data pos)))
(setf (git-fileinfo->marked info) nil)
(ewoc-invalidate git-status pos)
(ewoc-goto-prev git-status 1)))
(defun git-mark-all ()
"Mark all files."
(interactive)
(unless git-status (error "Not in git-status buffer."))
(ewoc-map (lambda (info) (unless (git-fileinfo->marked info)
(setf (git-fileinfo->marked info) t))) git-status)
; move back to goal column after invalidate
(when goal-column (move-to-column goal-column)))
(defun git-unmark-all ()
"Unmark all files."
(interactive)
(unless git-status (error "Not in git-status buffer."))
(ewoc-map (lambda (info) (when (git-fileinfo->marked info)
(setf (git-fileinfo->marked info) nil)
t)) git-status)
; move back to goal column after invalidate
(when goal-column (move-to-column goal-column)))
(defun git-toggle-all-marks ()
"Toggle all file marks."
(interactive)
(unless git-status (error "Not in git-status buffer."))
(ewoc-map (lambda (info) (setf (git-fileinfo->marked info) (not (git-fileinfo->marked info))) t) git-status)
; move back to goal column after invalidate