-
Notifications
You must be signed in to change notification settings - Fork 53
/
git-emacs.el
2629 lines (2302 loc) · 109 KB
/
git-emacs.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-emacs.el --- yet another git emacs mode for newbies
;;
;; Copyright (C) 2008 Taesoo Kim ([email protected])
;;
;; v.1.4.3 Modified by ovy @ 20 September 2009
;; v.1.4 Modified by ovy @ 22 March 2009
;; v.1.3 Modified by Con Digitalpit @ 29 March 2008
;;
;; Authors: Taesoo Kim <[email protected]>
;; Created: 24 March 2007
;; License: GPL
;; Keywords: git, version control, release management
;;
;; Compatibility: Emacs22 and EmacsCVS (developed on 23.0.60.2)
;; Git 1.5 and up
;; This file is *NOT* part of GNU Emacs.
;; This file is distributed under the same terms as GNU Emacs.
;; 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
;; https://github.com/tsgates/git-emacs
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;;; Commentary:
;;
;; Some related packages were used directly or as inspiration:
;; - psvn.el (Stefan Reichoer)
;; - vc-git.el (Alexandre Julliard)
;; - git.el (Alexandre Julliard)
;; - ido.el (Kim F. Storm)
;; - ...
;;
;;; Installation
;;
;; First, make sure that vc-git.el is in your load path. Emacs 23 ships it by
;; default, for older versions you can get it from git distributions prior
;; to 1.6.x.
;;
;; 1) Load at startup (simplest)
;;
;; (add-to-list 'load-path "~/.emacs.d/git-emacs") ; or your installation path
;; (require 'git-emacs)
;;
;; 2) Autoload (slimmer statup footprint, will activate when visiting a git
;; file or running some top-level functions)
;;
;; (add-to-list 'load-path "~/.emacs.d/git-emacs") ; or your installation path
;; (fmakunbound 'git-status) ; Possibly remove Debian's autoloaded version
;; (require 'git-emacs-autoloads)
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; TODO : check git environment
;; TODO : status -> index
;; TODO : pull/patch
;; TODO : fetching
;; TODO : regular exp selecting
;; TODO : enhance config! & tag!
;; TODO : save -> status-view update
;; TODO : git-log -> C-u command :=> cmd
;; TODO : status-mode function -> add status prefix
;; TODO : git set config
;; TODO : () -> fording/unfording for detail
;; TODO : show ignored files
;; TODO : locally flyspell
;;
;; DONE : turn off ido-mode globally
;; DONE : git-add
;; DONE : remote branch list
;; DONE : separate branch-mode & status-view-mode to other files
(require 'cl) ; common lisp
(require 'ediff) ; we use this a lot
(require 'vc) ; vc
(require 'vc-git) ; vc-git advises
(require 'time-stamp) ; today
(require 'git-global-keys) ; global keyboard mappings
(require 'git-emacs-autoloads) ; the minimal autoloads
;; Autoloaded submodules, those not declared in git-emacs-autoloads
(autoload 'git-blame-mode "git-blame"
"Minor mode for incremental blame for Git" t)
(autoload 'git--update-state-mark "git-modeline"
"Update modeline of git buffers with a customizable state marker" t)
(autoload 'git--update-all-state-marks "git-modeline"
"Update the modelines of all git buffers" t)
(autoload 'git-log-files "git-log"
"Launch the git log view for the current file or the selected files in git-status-mode" t)
(autoload 'git-log "git-log"
"Launch the git log view for whole repository" t)
(autoload 'git-log-other "git-log"
"Launch the git log view for an arbitrary branch or tag" t)
;;-----------------------------------------------------------------------------
;; Global preferences.
;;-----------------------------------------------------------------------------
(defgroup git-emacs nil
"A user interface for the git versioning system."
:group 'tools)
(defcustom git--use-ido t
"Whether to use ido completion for git-emacs prompts."
:type '(boolean)
:group 'git-emacs)
(defcustom git--timer-sec 1.0
"Timer to monitor .git repo to update modeline"
:type '(number)
:group 'git-emacs)
(defvar git--completing-read
(if git--use-ido
(progn
(require 'ido)
;; But this is not enough apparently. We need to strobe ido-mode
;; for ido-completing-read to work. Ugh.
(unless ido-mode (ido-mode t) (ido-mode -1))
#'ido-completing-read)
#'completing-read)
"Function to use for git-emacs minibuffer prompts with choices. It should have
the signature of `completing-read'.")
(defgroup git-emacs-faces nil
"Face customizations for git-emacs."
:group 'git-emacs)
;; Face definition macros. Used mostly in git-status.
(defmacro git--face (name fore1 prop1 fore2 prop2)
`(defface ,(intern (concat "git--" (symbol-name name) "-face"))
'((((class color) (background light)) (:foreground ,fore1 ,@prop1))
(((class color) (background dark)) (:foreground ,fore2 ,@prop2)))
,(concat "git " (symbol-name name) " face in status buffer mode")
:group 'git-emacs-faces))
(git--face bold "tomato" (:bold t) "tomato" (:bold t))
(defsubst git--bold-face (str) (propertize str 'face 'git--bold-face))
(defconst git--msg-critical (propertize "Critical Error" 'face 'git--bold-face))
(defconst git--msg-failed (propertize "Failed" 'face 'git--bold-face))
;;-----------------------------------------------------------------------------
;; Internal variables.
;;-----------------------------------------------------------------------------
(defvar git--executable "git" "Main git executable")
(defvar git--commit-log-buffer "*git commit*")
(defvar git--log-flyspell-mode t "enable flyspell-mode when editing log")
(defvar git--repository-bookmarks
'("git://github.com/tsgates/git-emacs.git"
"git://git.kernel.org/pub/scm/git/git.git"
"git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git"
)
"repository bookmarks")
(defvar git--repository-history nil)
(defconst git--repository-dir ".git")
(defconst git--reg-space " ")
(defconst git--reg-status "\\([A-Z?]\\)")
(defconst git--reg-tab "\t")
(defconst git--reg-blank "[\t\0 ]+")
(defconst git--reg-eof "\0")
(defconst git--reg-perm "\\([0-7]\\{6\\}\\)")
(defconst git--reg-type "\\([^ ]+\\)")
(defconst git--reg-sha1 "\\([0-9a-f]\\{40\\}\\)")
(defconst git--reg-file "\\([^\0]+\\)")
(defconst git--reg-branch "\\([^\n]+\\)")
(defconst git--reg-stage "\\([0-9]+\\)")
(defconst git--log-sep-line
"# --------------------------- message ---------------------------")
(defconst git--log-file-line
"# ---------------------------- files ----------------------------")
(defconst git--log-header-line
"# ----------------------------- info ----------------------------")
;;-----------------------------------------------------------------------------
;; Low-level execution functions.
;;-----------------------------------------------------------------------------
(defsubst git--exec (cmd outbuf infile &rest args)
"Low level function for calling git. CMD is the main git subcommand, args
are the remaining args. See `call-process' for the meaning of OUTBUF and
INFILE. Reeturns git's exit code."
(apply #'call-process git--executable infile outbuf nil (cons cmd args)))
(defun git--exec-pipe (cmd input &rest args)
"Execute 'git cmd args', piping INPUT (which can be a buffer or string).
Return result string."
(with-output-to-string
(with-current-buffer standard-output
(let ((tmp (make-temp-file "git-emacs-tmp")))
(unwind-protect
(progn
(if (bufferp input)
(with-current-buffer input
(write-file tmp))
(with-temp-buffer
(insert input)
(write-file tmp)))
(message "") ;hide write to file message
(apply #'git--exec cmd t tmp args))
(delete-file tmp))))))
(defsubst git--exec-buffer (cmd &rest args)
"Execute 'git' within the buffer. Return the exit code."
(apply #'git--exec cmd t nil args))
(defsubst git--exec-string-no-error (cmd &rest args)
"Execute 'git CMD ARGS' and return result string, which may be
a failure message."
(with-output-to-string
(with-current-buffer standard-output
(apply #'git--exec-buffer cmd args))))
(defun git--trim-string (str)
"Trim the spaces / newlines from the beginning and end of STR."
(let ((begin 0) (end (- (length str) 1)))
;; trim front
(while (and (< begin end)
(memq (aref str begin) '(? ?\n)))
(incf begin))
;; trim rear
(while (and (<= begin end)
(memq (aref str end) '(? ?\n)))
(decf end))
(substring str begin (+ end 1))))
(defun git--exec-string (cmd &rest args)
"Executes the specified git command, raises an error with the git output
if it fails. If the command succeeds, returns the git output."
(with-output-to-string
(with-current-buffer standard-output
(unless (eq 0
(apply #'git--exec-buffer cmd args))
(error "%s" (git--trim-string (buffer-string)))))))
;; This is nasty: the git devs changed the meaning of "git status" in git
;; 1.7, but commit --dry-run is not available in older git. Thanks much
;; guys -- I get to learn to learn how to do horrible hacks like this.
;; Hopefully the messages aren't translated or something.
(defun git--commit-dryrun-compat(outbuf &rest args)
"Executes commit --dry-run with the specified args, falls back to the
older git status if that command is not present. If OUTBUF is not nil, puts
the standard output there. Returns the git return code."
;; Going forward, this will simply succeed.
(let ((rc (apply #'git--exec "commit" (list outbuf nil) nil
"--dry-run" args)))
(when (eq rc 129)
;; gotta distinguish between bad args or no --dry-run.
(let ((has-dry-run
(string-match
"--dry-run"
(git--exec-string-no-error "commit" "--no-such-arg-show-help"))))
(unless has-dry-run
(setq rc (apply #'git--exec "status" outbuf nil args)))))
rc))
;;-----------------------------------------------------------------------------
;; utilities
;;-----------------------------------------------------------------------------
(defun git--trim-tail (str)
"Trim spaces / newlines from the end of STR."
(let ((end (- (length str) 1)))
(while (and (< 0 end)
(memq (aref str end) '(? ?\n)))
(decf end))
(substring str 0 (+ end 1))))
(defun git--pop-to-buffer(buffer)
"Wrapper around `pop-to-buffer', stores window configuration
from before `pop-to-buffer' call for later restoration. Every
buffer popped to with this function will have a local
`kill-buffer-hook' to restore previous window configuration."
(let ((git--saved-window-configuration (current-window-configuration))
(popped-buffer (pop-to-buffer buffer)))
(with-current-buffer popped-buffer
(add-hook 'kill-buffer-hook
(lexical-let ((saved-config git--saved-window-configuration))
#'(lambda()
(set-window-configuration saved-config)
)) nil t)) ;; !append local
popped-buffer))
(defsubst git--join (seq &optional sep)
"Joins the strings in SEQ with the SEP (defaults to blank)."
(mapconcat #'identity seq (if sep sep " ")))
(defsubst git--concat-path-only (path added)
"Concatenate the path with proper separator"
(concat (file-name-as-directory path) added))
(defsubst git--concat-path (path added)
(expand-file-name (git--concat-path-only path added)))
(defsubst git--expand-to-repository-dir (dir)
(git--concat-path dir git--repository-dir))
(defun git--quit-buffer ()
"Kill the current buffer, calls `kill-buffer'. Every
buffer popped with `git--pop-to-buffer' will restore previous
window-configuration when killed."
(interactive)
(kill-buffer))
(defsubst git--rev-parse (&rest args)
"Execute 'git rev-parse ARGS', return result string."
(apply #'git--exec-string "rev-parse" args))
(defmacro git-in-lowest-existing-dir (dir &rest BODY)
"Runs \"BODY\" with `default-directory' set to the nearest
existing parent of DIR; useful because git directories can come
and go when switching parents, and Emacs refuses to execute
commands in a non-existing directory. If DIR is nil, defaults to
`default-directory'. Only use this for commands that don't take
filenames, such as git branch, because relative filenames may
become invalid when we walk up -- in that case, it's better to
let the user see the invalid directory error."
`(let ((default-directory (file-name-as-directory
(if ,dir (expand-file-name ,dir)
default-directory))))
;; The default-directory might be gone if a branch was switched! Walk up.
(let (parent)
(while (not (or (file-exists-p default-directory)
(eq (setq parent (file-name-as-directory
(expand-file-name "..")))
default-directory)))
(setq default-directory parent)))
,@BODY))
(defmacro git--if-in-status-mode (THEN &rest ELSE)
"Macro that evaluates THEN when in git-status-mode, ELSE otherwise. Used to
grab status-mode filelists without the compiler complaining about the
autoloading which we know has already happened."
`(if (eq major-mode 'git-status-mode)
(progn (eval-when-compile (require 'git-status)) ,THEN)
,@ELSE))
(defun git--get-top-dir (&optional dir)
"Get the top-level git directory above DIR. If nil, use default-directory."
(git-in-lowest-existing-dir dir
(let ((cdup (git--rev-parse "--show-cdup")))
(git--concat-path default-directory (car (split-string cdup "\n"))))))
(defsubst git--interpret-to-state-symbol (stat)
"Interpret a one-letter git state string to our state symbols."
(case (string-to-char stat)
(?H 'uptodate )
(?M 'modified )
(?? 'unknown )
(?A 'added )
(?D 'deleted )
(?U 'unmerged )
(?T 'modified )
(?K 'killed )
(t nil)))
(defsubst git--build-reg (&rest args)
(apply #'concat (add-to-list 'args "\0" t)))
(defsubst git--select-from-user (prompt choices &optional history default)
"Select from choices. Shortcut to git--completing-read."
(funcall git--completing-read prompt choices nil nil nil history default))
(defmacro git--please-wait (msg &rest body)
"Macro to give feedback around actions that may take a long
time. Prints MSG..., executes BODY, then prints MSG...done (as per the elisp
style guidelines)."
`(let ((git--please-wait-msg (concat ,msg "...")))
(message git--please-wait-msg)
,@body
(message (concat git--please-wait-msg "done"))))
(defun git--find-buffers-in-dir (repo &optional predicate)
"Finds buffers corresponding to files in the given directory,
optionally satisfying PREDICATE (which should take a buffer object as
argument)."
(let* ((absolute-repo (expand-file-name (file-name-as-directory repo)))
(absolute-repo-length (length absolute-repo))
(buffers))
(dolist (buffer (buffer-list))
(let ((filename (buffer-file-name buffer)))
(when filename
(when (and (eq t (compare-strings filename
0 absolute-repo-length
absolute-repo
0 absolute-repo-length))
(or (not predicate) (funcall predicate buffer)))
(add-to-list 'buffers buffer)))))
buffers))
(defun git--find-buffers-from-file-list (filelist &optional predicate)
"Finds buffers corresponding to files in the given list,
optionally satisfying the predicate."
(let (buffers)
(dolist (filename filelist)
(let ((buffer (find-buffer-visiting filename predicate)))
(when buffer (add-to-list 'buffers buffer))))
buffers))
(defun git--find-buffers (&optional repo-or-filelist predicate)
"Find buffers satisfying PREDICATE in the given
REPO-OR-FILELIST, which can be a string (path within a git
repository), a list (filelist) or nil (current git repository)."
(cond
((eq nil repo-or-filelist) (git--find-buffers-in-dir
(git--get-top-dir default-directory)
predicate))
((stringp repo-or-filelist) (git--find-buffers-in-dir
(git--get-top-dir repo-or-filelist) predicate))
(t (git--find-buffers-from-file-list repo-or-filelist predicate))))
(defun git--maybe-ask-save (&optional repo-or-filelist)
"If there are modified buffers which visit files in the given
REPO-OR-FILELIST,ask to save them. If REPO-OR-FILELIST is nil,
look for buffers in the current git repo. Returns the number of
buffers saved."
(let ((buffers (git--find-buffers repo-or-filelist #'buffer-modified-p)))
(map-y-or-n-p
(lambda(buffer) (format "Save %s? " (buffer-name buffer)))
(lambda(buffer) (with-current-buffer buffer (save-buffer)))
buffers
'("buffer" "buffers" "save"))))
(defcustom git-working-dir-change-behaviour
'git-ask-for-all-saved
"Controls the buffer-refreshing behaviour after a git working dir change
(e.g. branch switch), when there are buffers visiting files that
have been modified by the change."
:type '(radio (const :tag "Ask about refreshing all saved buffers"
git-ask-for-all-saved)
(const :tag "Refresh all saved buffers"
git-refresh-all-saved)
(const :tag "Don't refresh" nil))
:group 'git-emacs)
(defun git-after-working-dir-change (&optional repo-or-filelist)
"This function should be called after a change to the git working dir.
If there are buffers visiting files in the given REPO-OR-FILELIST that
have changed (buffer modtime != file modtime), ask the user whether to refresh
those buffers. Updates the state mark of all the buffers not reverted
\(since revert updates the ones reverted anyway). If currently in status
buffer, refreshes the status buffer. Warns the user if there are any buffers
visiting files that no longer exist."
(interactive)
(let ((buffers (git--find-buffers
repo-or-filelist
#'(lambda(buffer)
(not (verify-visited-file-modtime buffer)))))
(buffers-that-exist nil) (buffers-that-dont-exist nil)
(num-buffers-refreshed 0))
(dolist (buffer buffers)
(if (file-exists-p (buffer-file-name buffer))
(push buffer buffers-that-exist)
(push buffer buffers-that-dont-exist)))
;; Revert buffers that exist
(unwind-protect
(let ((buffers-not-reverted (copy-sequence buffers-that-exist))
buffers-that-exist-unsaved buffers-that-exist-saved)
(cl-flet ((buffer-refresh-func (buffer)
(with-current-buffer buffer (revert-buffer t t))
;; A hash table is probably not worth it here.
(setq buffers-not-reverted
(delq buffer buffers-not-reverted))
(incf num-buffers-refreshed)))
;; Filter buffers by their saved status.
(dolist (buffer buffers-that-exist)
(if (buffer-modified-p buffer)
(push buffer buffers-that-exist-unsaved)
(push buffer buffers-that-exist-saved)))
;; Do the state mark update if the user quits the revert prompts.
;; Or, on all unsaved buffers.
(unwind-protect
(case git-working-dir-change-behaviour
('git-ask-for-all-saved
(map-y-or-n-p
(lambda(buffer) (format "%s has changed, refresh buffer? "
(buffer-name buffer)))
#'buffer-refresh-func
buffers-that-exist-saved
'("buffer" "buffers" "refresh")))
('git-refresh-all-saved
(mapc #'buffer-refresh-func buffers-that-exist-saved)))
(when buffers-not-reverted
(git--update-all-state-marks (mapcar #'buffer-file-name
buffers-not-reverted)))))
;; Refresh status buffer
(git--if-in-status-mode (git--status-view-refresh)))
;; But display the [important] files don't exist / buffers refreshed
;; warnings on failure / quit
(let ((submessages
(append
(when (> num-buffers-refreshed 0)
(list (format "%d buffers refreshed" num-buffers-refreshed)))
(when buffers-that-dont-exist
(list
(format "some open files no longer exist: %s"
(git--join
(let ((numfiles (length buffers-that-dont-exist)))
(if (> numfiles 2)
(list (buffer-name (first buffers-that-dont-exist))
(format "%d others" (- numfiles 1)))
(mapcar #'buffer-name buffers-that-dont-exist)))
", ")))))))
(when submessages
(message "Note: %s" (git--join submessages "; ")))))))
;; This belongs later with all the commit functions, but the compiler complains
;; in git-log if we don't define it before its first use.
(defun git-commit-all (&optional amend)
"Runs git commit -a, prompting for a commit message. With a prefix argument,
runs git commit --amend -a, alowing an update of the previous commit."
(interactive "P")
(git-commit amend t))
;;-----------------------------------------------------------------------------
;; fileinfo structure
;;-----------------------------------------------------------------------------
;; ewoc file info structure for each list element
(defstruct (git--fileinfo
(:copier nil)
(:constructor git--create-fileinfo
(name type &optional sha1 perm marked
stat size refresh))
(:conc-name git--fileinfo->))
marked ;; t/nil
expanded ;; t/nil
refresh ;; t/nil
stat ;; 'unknown/'modified/'uptodate/'staged etc.
type ;; 'blob/'tree/'commit (i.e. submodule)
name ;; filename
size ;; size
perm ;; permission
sha1) ;; sha1
(defsubst git--fileinfo-is-dir (info)
"Returns true if a file info is directory-like (expandable, sorted first)"
(not (eq 'blob (git--fileinfo->type info))))
(defsubst git--fileinfo-dir (info)
"Returns the directory component of a fileinfo's path. If the fileinfo is
directory-like, the directory is the path itself, with a slash appended."
(if (git--fileinfo-is-dir info)
(file-name-as-directory (git--fileinfo->name info))
(or (file-name-directory (git--fileinfo->name info)) "")))
(defun git--fileinfo-lessp (info1 info2)
"Sorting rule for git--fileinfos, such that the ordering in git-status is
right. The rule is rather complicated, but it basically results in a
properly expanded tree."
(let ((info1-dir (git--fileinfo-dir info1))
(info2-dir (git--fileinfo-dir info2)))
(let ((cmp (compare-strings info1-dir 0 nil info2-dir 0 nil)))
(if (not (eq t cmp))
;; A file in a subdirectory should always come before a file
;; in the parent directory.
(if (< cmp 0)
;; info1-dir < info2-dir
(if (eq (length info1-dir) (- -1 cmp))
;; info1-dir is a subdir of info2-dir. less == false,
;; unless info1 is a directory itself.
(git--fileinfo-is-dir info1)
t)
;; info1-dir > info2-dir
(if (eq (length info2-dir) (- cmp 1))
;; info2-dir is a subdir of info1-dir. less == true, unless
;; info2 is a directory itself.
(not (git--fileinfo-is-dir info2))
nil))
;; same directory, straight-up comparison
(string< (git--fileinfo->name info1)
(git--fileinfo->name info2))))))
;;-----------------------------------------------------------------------------
;; git commands
;;-----------------------------------------------------------------------------
(defun git--init (dir)
"Execute 'git init' in DIR (current dir, if unspecified)."
(with-temp-buffer
(when dir (cd dir))
(git--exec-string "init")))
(defun git--checkout (&rest args)
"Execute 'git checkout ARGS' and return resulting string."
(apply #'git--exec-string "checkout" args))
(defun git--clone-sentinel (proc stat)
"Process sentinel for 'git clone' processes."
(let ((cmd (git--join (process-command proc))))
(cond ((string= stat "finished\n")
(message "%s : %s" (git--bold-face "Cloned") cmd))
;; TODO : popup or state
((string= stat "killed\n")
(message "%s : %s" git--msg-failed cmd))
(t
(message "%s : %s" git--msg-critical cmd)))))
(defun git--clone (&rest args)
"Execute 'git clone ARGS', with a process sentinel showing status."
(let ((proc (apply #'start-process "git-clone" nil "git" "clone" args)))
(set-process-sentinel proc 'git--clone-sentinel)
(message "%s : %s"
(git--bold-face "Run")
(git--join (process-command proc)))))
(defun git--commit (msg &rest args)
"Execute 'git commit ARGS', pipe the MSG string"
(git--trim-string
(apply #'git--exec-pipe "commit" msg "-F" "-" args)))
(defun git--reset (&rest args)
"Execute 'git reset ARGS', return the result string."
(apply #'git--exec-string "reset" args))
(defun git--config (&rest args)
"Execute 'git config ARGS', return the result string. Return empty
if git config fails (behaviour if unconfigured as of version 1.7.1)."
(condition-case nil
(git--trim-string (apply #'git--exec-string "config" args))
(error "")))
(defun git--add (files)
"Execute 'git add' with the sequence FILES."
(when (stringp files) (setq files (list files)))
(apply #'git--exec-string "add" files))
(defun git--mv (src dst)
"Execute git mv for SRC and DST files."
(git--exec-string "mv" src dst))
(defun git--tag (&rest args)
"Execute 'git tag ARGS', return the result as string."
(apply #'git--exec-string "tag" args))
(defvar git--tag-history nil "History variable for tags entered by user.")
(defalias 'git-snapshot 'git-tag)
(defun git-tag (&optional tag-name commit)
"Create a new tag for the current commit, or a specified one.
git-snapshot is an alias to this. Returns the previous target of the tag,
nil if none."
(interactive)
(let* ((friendly-commit (if commit (git--bold-face commit)
"current tree"))
;; Don't use ido here, since the user will often select a new one
(tag-name (or tag-name
(completing-read (format "Tag %s as: " friendly-commit)
(git--tag-list)
nil nil nil 'git--tag-history)))
(old-tag-target (ignore-errors
(git--trim-string
(git--rev-parse "--short" tag-name)))))
(apply #'git--tag (delq nil (list "-f" tag-name commit)))
(message "Tagged %s with %s%s"
friendly-commit (git--bold-face tag-name)
(if old-tag-target (format " (previously %s)"
(git--bold-face old-tag-target))
""))
old-tag-target))
(defun git--tag-list ()
"Get the list of known git tags, which may not always refer to commit objects"
(split-string (git--tag "-l") "\n" t))
(defsubst git--diff-raw (args &rest files)
"Execute 'git diff --raw' with 'args' and 'files' at current buffer. This
gives, essentially, file status."
;; git-diff abbreviates by default, and also produces a diff.
(apply #'git--exec-buffer "diff" "-z" "--full-index" "--raw" "--abbrev=40"
(append args (list "--") files)))
(defun git--status-index (&rest files)
"Execute 'git-status-index' and return list of 'git--fileinfo'"
;; update fileinfo -> unmerged index
(let ((fileinfo nil)
(unmerged-info (make-hash-table :test 'equal))
(regexp (git--build-reg ":"
git--reg-perm ; matched-1: HEAD perms
git--reg-blank
git--reg-perm ; matched-2: index perms
git--reg-blank
git--reg-sha1 ; matched-3: HEAD sha1
git--reg-blank
git--reg-sha1 ; matched-4: index sha1
git--reg-blank
git--reg-status ; matched-5
git--reg-eof
git--reg-file ; matched-6
)))
(dolist (stage-and-fi (git--ls-unmerged))
;; ignore the different stages, since we're not using the sha1s
(puthash (git--fileinfo->name (cdr stage-and-fi))
(git--fileinfo->stat (cdr stage-and-fi))
unmerged-info))
(with-temp-buffer
(apply #'git--diff-raw (list "HEAD") files)
(goto-char (point-min))
(while (re-search-forward regexp nil t)
(let ((perm (match-string 2))
(stat (git--interpret-to-state-symbol (match-string 5)))
(file (match-string 6)))
;; if unmerged file
(when (gethash file unmerged-info) (setq stat 'unmerged))
;; modified vs. staged: the latter has a nonzero sha1
(when (and (eq stat 'modified)
(not (equal (match-string 4)
"0000000000000000000000000000000000000000")))
(setq stat 'staged))
;; assume all listed elements are 'blob
(push (git--create-fileinfo file 'blob nil perm nil stat) fileinfo))))
fileinfo))
(defun git--symbolic-ref (arg)
"Execute 'git symbolic-ref ARG' and return the sha1 string, or nil if the
arg is not a symbolic ref."
(let ((commit (git--exec-string-no-error "symbolic-ref" "-q" arg)))
(when (> (length commit) 0)
(car (split-string commit"\n")))))
(defun git--current-branch ()
"Execute 'git symbolic-ref'HEAD' and return branch name string. Returns
nil if there is no current branch."
(let ((branch (git-in-lowest-existing-dir nil (git--symbolic-ref "HEAD"))))
(when branch
(if (string-match "^refs/heads/" branch)
(substring branch (match-end 0))
branch))))
(defsubst git--log (&rest args)
"Execute 'git log ARGS' and return result string"
(apply #'git--exec-string "log" "-z" args))
(defsubst git--last-log-short ()
"Get the last log, as one line: <short_commit> <short_msg>"
(git--trim-string (git--log "--max-count=1" "--pretty=oneline"
"--abbrev-commit")))
(defsubst git--last-log-message ()
"Return the last commit message, as a possibly multiline string, with an "
"ending newline,"
(git--log "--max-count=1" "--pretty=format:%s%n%b"))
(defun git--get-relative-to-top(filename)
(file-relative-name filename
(git--get-top-dir (file-name-directory filename))))
(defun git--get-top-dir-or-prompt (prompt &optional dir)
"Returns the top-level git directory above DIR (or default-directory). Prompts
the user with PROMPT if not a git repository, or if DIR is t."
(or (unless (eq dir t) (ignore-errors (git--get-top-dir dir)))
(git--get-top-dir (read-directory-name prompt (unless (eq dir t) dir)))))
(defun git--ls-unmerged (&rest files)
"Get the list of unmerged files. Returns an association list of
\(stage . git--fileinfo), where stage is one of 1, 2, 3. If FILES is specified,
only checks the specified files. The list is sorted by filename."
(let (fileinfo)
(with-temp-buffer
(apply #'git--exec-buffer "ls-files" "-t" "-u" "-z" files)
(goto-char (point-min))
(let ((regexp (git--build-reg git--reg-perm ; matched-1
git--reg-space
git--reg-sha1 ; matched-2
git--reg-blank
git--reg-stage ; matched-3
git--reg-blank
git--reg-file))) ; matched-4
(while (re-search-forward regexp nil t)
(let ((perm (match-string 1))
(sha1 (match-string 2))
(stage (match-string 3))
(file (match-string 4)))
(push
(cons (string-to-number stage)
(git--create-fileinfo file 'blob sha1 perm nil 'unmerged))
fileinfo)))))
(sort fileinfo #'(lambda(cell1 cell2)
(git--fileinfo-lessp (cdr cell1) (cdr cell2))))))
(defun git--ls-files (&rest args)
"Execute 'git-ls-files' with 'args' and return the list of the
'git--fileinfo'. Does not differentiate between 'modified and
'staged."
(let (fileinfo)
(with-temp-buffer
(apply #'git--exec-buffer "ls-files" "-t" "-z" args)
(goto-char (point-min))
(let ((regexp (git--build-reg git--reg-status ; matched-1
git--reg-blank
git--reg-file))) ; matched-2
(while (re-search-forward regexp nil t)
(let* ((stat (match-string 1))
(name (match-string 2))
(file-name (directory-file-name name)))
;; Files listed with e.g "-o" might be directories
(push (git--create-fileinfo file-name
(if (equal name file-name) 'blob
'tree)
nil nil nil
(git--interpret-to-state-symbol stat))
fileinfo)))))
(sort fileinfo 'git--fileinfo-lessp)))
(defsubst git--to-type-sym (type)
"Convert a string type from git to 'blob, 'tree or 'commit (i.e. submodule)"
(cond ((string= type "blob") 'blob)
((string= type "tree") 'tree)
((string= type "commit") 'commit)
(t (error "strange type : %s" type))))
(defun git--ls-tree (&rest args)
"Execute 'git ls-tree ARGS', return a list of git--fileinfo structs."
(let (fileinfo)
(with-temp-buffer
(apply #'git--exec-buffer "ls-tree" "-z" args)
(goto-char (point-min))
(let ((regexp (git--build-reg git--reg-perm ; matched-1
git--reg-space
git--reg-type ; matched-2
git--reg-space
git--reg-sha1 ; matched-3
git--reg-tab
git--reg-file))) ; matched-4
(while (re-search-forward regexp nil t)
(let ((perm (match-string 1))
(type (match-string 2))
(sha1 (match-string 3))
(file (match-string 4)))
(push (git--create-fileinfo file
(git--to-type-sym type)
sha1
perm
nil
'uptodate)
fileinfo)))))
(sort fileinfo 'git--fileinfo-lessp)))
(defun git--merge (&rest args)
"Run 'git merge ARGS', output the return message to the user."
(message "%s" (git--trim-string (apply #'git--exec-string "merge" args))))
(defsubst git--branch (&rest args)
(apply #'git--exec-string "branch" args))
(defun git--abbrev-commit(commit &optional size)
"Returns a short yet unambiguous SHA1 checksum for a commit. The default
SIZE is 5, but it will be longer if needed (due to conflicts)."
(git--trim-string
(git--exec-string "rev-list" "--abbrev-commit" "--max-count=1"
(format "--abbrev=%d" (or size 5)) commit)))
(defsubst git--today ()
(time-stamp-string "%:y-%02m-%02d %02H:%02M:%02S"))
;;-----------------------------------------------------------------------------
;; git application
;;-----------------------------------------------------------------------------
(defsubst git--managed-on-git? ()
"Returns true if we're in a git repository."
(not (string-match "fatal: Not a git repository"
(git--rev-parse "HEAD"))))
(defun git--status-file (file)
"Return the git status of FILE, as a symbol."
(let ((fileinfo (git--status-index file)))
(unless fileinfo (setq fileinfo (git--ls-files file)))
(when (= 1 (length fileinfo))
(git--fileinfo->stat (car fileinfo)))))
(defun git--branch-list ()
"Get branch list, in the order returned by 'git branch'. Returns a cons cell
\(list-of-branches . current-branch), where current-branch may be nil."
(let ((branches) (current-branch)
(regexp (concat " *\\([*]\\)? *" git--reg-branch "\n")))
(with-temp-buffer
(git-in-lowest-existing-dir
nil
(unless (eq 0 (git--exec-buffer "branch" "-l"))
(error "%s" (git--trim-string (buffer-string)))))
(goto-char (point-min))
(while (re-search-forward regexp nil t)
(let ((branch (match-string 2)))
(unless (string= branch "(no branch)")
(push branch branches))
(when (and (not current-branch) (string= "*" (match-string 1)))
(setq current-branch branch)))))
(cons (nreverse branches) current-branch)))
(defun git--cat-file (buffer-name &rest args)
"Execute 'git cat-file ARGS' and return a new buffer named BUFFER-NAME
with the file content"
(let ((buffer (get-buffer-create buffer-name)))
(with-current-buffer buffer
(setq buffer-read-only nil)
(erase-buffer)
;; auto mode, for highlighting
(let ((buffer-file-name buffer-name)) (set-auto-mode))
(apply #'git--exec-buffer "cat-file" args)
;; set buffer readonly & quit
(setq buffer-read-only t)
;; Failed?
(goto-char (point-min))
(when (looking-at "^\\([Ff]atal\\|[Ff]ailed\\|[Ee]rror\\):")
(let ((msg (buffer-string)))
(kill-buffer nil)
(setq buffer nil)
(error "%s" (git--trim-tail msg)))))
buffer))
(defun git--select-branch (&rest excepts)
"Prompts the user for a branch name. Offers all the branches for completion,
except EXCEPTS. Returns the user's selection."
(let ((branches (car (git--branch-list))))
(git--select-from-user
"Select branch: "
(delq nil (mapcar (lambda (b) (unless (member b excepts) b))
branches)))))
;; ================================================================================
;; I will revise this code laster this week
;; ================================================================================
(defun git-pull-ff-only ()
"Interactive git pull. Prompts user for a remote branch, and pulls from it.
This command will fail if we can not do a ff-only pull from the remote branch."
(interactive)
(let ((remote (git--select-remote
(concat "Select remote for pull (local branch:"
(git--current-branch)
"): "))))
(message (git--pull-ff-only remote))))
;; XXX. should this be implemented list this way? umm..
(defsubst git--select-remote (prompt &rest excepts)
"Select remote branch interactively."
(let ((remotes (git--symbolic-commits '("remotes"))))
(git--select-from-user prompt
(delq nil (mapcar (lambda (b) (unless (member b excepts) b))
remotes)))))
(defun git--pull-ff-only (remote)
"Pull from remote into current branch, but only on a fast-forward pull."
(let ((split-remote (split-string remote "/"))
(parse-success-string (lambda (resultstring) ;; Parses success string
(let ((lines (split-string resultstring "\n")))
(if (string-equal (nth 2 lines) "Already up-to-date.")