Avoid assertions in vc-hg.el on MS-Windows
[emacs.git] / lisp / vc / vc-hg.el
blob99c8869ae06f0f36514f16effcbb6c93da21149f
1 ;;; vc-hg.el --- VC backend for the mercurial version control system -*- lexical-binding: t -*-
3 ;; Copyright (C) 2006-2017 Free Software Foundation, Inc.
5 ;; Author: Ivan Kanis
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Keywords: vc tools
8 ;; Package: vc
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; This is a mercurial version control backend
29 ;;; Thanks:
31 ;;; Bugs:
33 ;;; Installation:
35 ;;; Todo:
37 ;; 1) Implement the rest of the vc interface. See the comment at the
38 ;; beginning of vc.el. The current status is:
40 ;; FUNCTION NAME STATUS
41 ;; BACKEND PROPERTIES
42 ;; * revision-granularity OK
43 ;; STATE-QUERYING FUNCTIONS
44 ;; * registered (file) OK
45 ;; * state (file) OK
46 ;; - dir-status-files (dir files uf) OK
47 ;; - dir-extra-headers (dir) OK
48 ;; - dir-printer (fileinfo) OK
49 ;; * working-revision (file) OK
50 ;; * checkout-model (files) OK
51 ;; - mode-line-string (file) OK
52 ;; STATE-CHANGING FUNCTIONS
53 ;; * register (files &optional rev comment) OK
54 ;; * create-repo () OK
55 ;; - responsible-p (file) OK
56 ;; - receive-file (file rev) ?? PROBABLY NOT NEEDED
57 ;; - unregister (file) OK
58 ;; * checkin (files rev comment) OK
59 ;; * find-revision (file rev buffer) OK
60 ;; * checkout (file &optional rev) OK
61 ;; * revert (file &optional contents-done) OK
62 ;; - merge (file rev1 rev2) NEEDED
63 ;; - merge-news (file) NEEDED
64 ;; - steal-lock (file &optional revision) NOT NEEDED
65 ;; HISTORY FUNCTIONS
66 ;; * print-log (files buffer &optional shortlog start-revision limit) OK
67 ;; - log-view-mode () OK
68 ;; - show-log-entry (revision) NOT NEEDED, DEFAULT IS GOOD
69 ;; - comment-history (file) NOT NEEDED
70 ;; - update-changelog (files) NOT NEEDED
71 ;; * diff (files &optional rev1 rev2 buffer) OK
72 ;; - revision-completion-table (files) OK?
73 ;; - annotate-command (file buf &optional rev) OK
74 ;; - annotate-time () OK
75 ;; - annotate-current-time () NOT NEEDED
76 ;; - annotate-extract-revision-at-line () OK
77 ;; TAG SYSTEM
78 ;; - create-tag (dir name branchp) OK
79 ;; - retrieve-tag (dir name update) OK
80 ;; MISCELLANEOUS
81 ;; - make-version-backups-p (file) ??
82 ;; - previous-revision (file rev) OK
83 ;; - next-revision (file rev) OK
84 ;; - check-headers () ??
85 ;; - delete-file (file) TEST IT
86 ;; - rename-file (old new) OK
87 ;; - find-file-hook () added for bug#10709
89 ;; 2) Implement Stefan Monnier's advice:
90 ;; vc-hg-registered and vc-hg-state
91 ;; Both of those functions should be super extra careful to fail gracefully in
92 ;; unexpected circumstances. The reason this is important is that any error
93 ;; there will prevent the user from even looking at the file :-(
94 ;; Ideally, just like in vc-arch and vc-cvs, checking that the file is under
95 ;; mercurial's control and extracting the current revision should be done
96 ;; without even using `hg' (this way even if you don't have `hg' installed,
97 ;; Emacs is able to tell you this file is under mercurial's control).
99 ;;; History:
102 ;;; Code:
104 (eval-when-compile
105 (require 'vc)
106 (require 'vc-dir))
108 (require 'cl-lib)
110 (declare-function vc-compilation-mode "vc-dispatcher" (backend))
112 ;;; Customization options
114 (defgroup vc-hg nil
115 "VC Mercurial (hg) backend."
116 :version "24.1"
117 :group 'vc)
119 (defcustom vc-hg-global-switches nil
120 "Global switches to pass to any Hg command."
121 :type '(choice (const :tag "None" nil)
122 (string :tag "Argument String")
123 (repeat :tag "Argument List" :value ("") string))
124 :version "22.2"
125 :group 'vc-hg)
127 (defcustom vc-hg-diff-switches t ; Hg doesn't support common args like -u
128 "String or list of strings specifying switches for Hg diff under VC.
129 If nil, use the value of `vc-diff-switches'. If t, use no switches."
130 :type '(choice (const :tag "Unspecified" nil)
131 (const :tag "None" t)
132 (string :tag "Argument String")
133 (repeat :tag "Argument List" :value ("") string))
134 :version "23.1"
135 :group 'vc-hg)
137 (defcustom vc-hg-annotate-switches '("-u" "--follow")
138 "String or list of strings specifying switches for hg annotate under VC.
139 If nil, use the value of `vc-annotate-switches'. If t, use no
140 switches."
141 :type '(choice (const :tag "Unspecified" nil)
142 (const :tag "None" t)
143 (string :tag "Argument String")
144 (repeat :tag "Argument List" :value ("") string))
145 :version "25.1"
146 :group 'vc-hg)
148 (defcustom vc-hg-program "hg"
149 "Name of the Mercurial executable (excluding any arguments)."
150 :type 'string
151 :group 'vc-hg)
153 (defcustom vc-hg-root-log-format
154 `(,(concat "{rev}:{ifeq(branch, 'default','', '{branch}')}"
155 ":{bookmarks}:{tags}:{author|person}"
156 " {date|shortdate} {desc|firstline}\\n")
157 ,(concat "^\\(?:[+@o x|-]*\\)" ;Graph data.
158 "\\([0-9]+\\):\\([^:]*\\)"
159 ":\\([^:]*\\):\\([^:]*\\):\\(.*?\\)"
160 "[ \t]+\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\)")
161 ((1 'log-view-message)
162 (2 'change-log-file)
163 (3 'change-log-list)
164 (4 'change-log-conditionals)
165 (5 'change-log-name)
166 (6 'change-log-date)))
167 "Mercurial log template for `vc-hg-print-log' short format.
168 This should be a list (TEMPLATE REGEXP KEYWORDS), where TEMPLATE
169 is the \"--template\" argument string to pass to Mercurial,
170 REGEXP is a regular expression matching the resulting Mercurial
171 output, and KEYWORDS is a list of `font-lock-keywords' for
172 highlighting the Log View buffer."
173 :type '(list string string (repeat sexp))
174 :group 'vc-hg
175 :version "24.5")
178 ;;; Properties of the backend
180 (defvar vc-hg-history nil)
182 (defun vc-hg-revision-granularity () 'repository)
183 (defun vc-hg-checkout-model (_files) 'implicit)
185 ;;; State querying functions
187 ;;;###autoload (defun vc-hg-registered (file)
188 ;;;###autoload "Return non-nil if FILE is registered with hg."
189 ;;;###autoload (if (vc-find-root file ".hg") ; short cut
190 ;;;###autoload (progn
191 ;;;###autoload (load "vc-hg" nil t)
192 ;;;###autoload (vc-hg-registered file))))
194 ;; Modeled after the similar function in vc-bzr.el
195 (defun vc-hg-registered (file)
196 "Return non-nil if FILE is registered with hg."
197 (when (vc-hg-root file) ; short cut
198 (let ((state (vc-hg-state file))) ; expensive
199 (and state (not (memq state '(ignored unregistered)))))))
201 (defun vc-hg-state (file)
202 "Hg-specific version of `vc-state'."
203 (let ((state (vc-hg-state-fast file)))
204 (if (eq state 'unsupported) (vc-hg-state-slow file) state)))
206 (defun vc-hg-state-slow (file)
207 "Determine status of FILE by running hg."
208 (setq file (expand-file-name file))
209 (let*
210 ((status nil)
211 (default-directory (file-name-directory file))
212 (out
213 (with-output-to-string
214 (with-current-buffer
215 standard-output
216 (setq status
217 (condition-case nil
218 ;; Ignore all errors.
219 (let ((process-environment
220 ;; Avoid localization of messages so we
221 ;; can parse the output. Disable pager.
222 (append
223 (list "TERM=dumb" "LANGUAGE=C" "HGPLAIN=1")
224 process-environment)))
225 (process-file
226 vc-hg-program nil t nil
227 "--config" "alias.status=status"
228 "--config" "defaults.status="
229 "status" "-A" (file-relative-name file)))
230 ;; Some problem happened. E.g. We can't find an `hg'
231 ;; executable.
232 (error nil)))))))
233 (when (and (eq 0 status)
234 (> (length out) 0)
235 (null (string-match ".*: No such file or directory$" out)))
236 (let ((state (aref out 0)))
237 (cond
238 ((eq state ?=) 'up-to-date)
239 ((eq state ?A) 'added)
240 ((eq state ?M) 'edited)
241 ((eq state ?I) 'ignored)
242 ((eq state ?R) 'removed)
243 ((eq state ?!) 'missing)
244 ((eq state ??) 'unregistered)
245 ((eq state ?C) 'up-to-date) ;; Older mercurial versions use this.
246 (t 'up-to-date))))))
248 (defun vc-hg-working-revision (file)
249 "Hg-specific version of `vc-working-revision'."
250 (or (ignore-errors
251 (with-output-to-string
252 (vc-hg-command standard-output 0 file
253 "parent" "--template" "{rev}")))
254 "0"))
256 (defcustom vc-hg-symbolic-revision-styles
257 '(builtin-active-bookmark
258 "{if(bookmarks,sub(' ',',',bookmarks),if(phabdiff,phabdiff,shortest(node,6)))}")
259 "List of ways to present versions symbolically. The version
260 that we use is the first one that successfully produces a
261 non-empty string.
263 Each entry in the list can be either:
265 - The symbol `builtin-active-bookmark', which indicates that we
266 should use the active bookmark if one exists. A template can
267 supply this information as well, but `builtin-active-bookmark' is
268 handled entirely inside Emacs and so is more efficient than using
269 the generic Mercurial mechanism.
271 - A string giving the Mercurial template to supply to \"hg
272 parent\". \"hg help template\" may be useful reading.
274 - A function to call; it should accept two arguments (a revision
275 and an optional path to which to limit history) and produce a
276 string. The function is called with `default-directory' set to
277 within the repository.
279 If no list entry produces a useful revision, return `nil'."
280 :type '(repeat (choice
281 (const :tag "Active bookmark" 'bookmark)
282 (string :tag "Hg template")
283 (function :tag "Custom")))
284 :version "26.1"
285 :group 'vc-hg)
287 (defcustom vc-hg-use-file-version-for-mode-line-version nil
288 "When enabled, the modeline contains revision information for the visited file.
289 When not, the revision in the modeline is for the repository
290 working copy. `nil' is the much faster setting for
291 large repositories."
292 :type 'boolean
293 :version "26.1"
294 :group 'vc-hg)
296 (defun vc-hg--active-bookmark-internal (rev)
297 (when (equal rev ".")
298 (let* ((current-bookmarks-file ".hg/bookmarks.current"))
299 (when (file-exists-p current-bookmarks-file)
300 (ignore-errors
301 (with-temp-buffer
302 (insert-file-contents current-bookmarks-file)
303 (buffer-substring-no-properties
304 (point-min) (point-max))))))))
306 (defun vc-hg--run-log (template rev path)
307 (ignore-errors
308 (with-output-to-string
309 (if path
310 (vc-hg-command
311 standard-output 0 nil
312 "log" "-f" "-l1" "--template" template path)
313 (vc-hg-command
314 standard-output 0 nil
315 "log" "-r" rev "-l1" "--template" template)))))
317 (defun vc-hg--symbolic-revision (rev &optional path)
318 "Make a Mercurial revision human-readable.
319 REV is a Mercurial revision. `default-directory' is assumed to
320 be in the repository root of interest. PATH, if set, is a
321 specific file to query."
322 (let ((symbolic-revision nil)
323 (styles vc-hg-symbolic-revision-styles))
324 (while (and (not symbolic-revision) styles)
325 (let ((style (pop styles)))
326 (setf symbolic-revision
327 (cond ((and (null path) (eq style 'builtin-active-bookmark))
328 (vc-hg--active-bookmark-internal rev))
329 ((stringp style)
330 (vc-hg--run-log style rev path))
331 ((functionp style)
332 (funcall style rev path))))))
333 symbolic-revision))
335 (defun vc-hg-mode-line-string (file)
336 "Hg-specific version of `vc-mode-line-string'."
337 (let* ((backend-name "Hg")
338 (truename (file-truename file))
339 (state (vc-state truename))
340 (state-echo nil)
341 (face nil)
342 (rev (and state
343 (let ((default-directory
344 (expand-file-name (vc-hg-root truename))))
345 (vc-hg--symbolic-revision
347 (and vc-hg-use-file-version-for-mode-line-version
348 truename)))))
349 (rev (or rev "???")))
350 (propertize
351 (cond ((or (eq state 'up-to-date)
352 (eq state 'needs-update))
353 (setq state-echo "Up to date file")
354 (setq face 'vc-up-to-date-state)
355 (concat backend-name "-" rev))
356 ((eq state 'added)
357 (setq state-echo "Locally added file")
358 (setq face 'vc-locally-added-state)
359 (concat backend-name "@" rev))
360 ((eq state 'conflict)
361 (setq state-echo "File contains conflicts after the last merge")
362 (setq face 'vc-conflict-state)
363 (concat backend-name "!" rev))
364 ((eq state 'removed)
365 (setq state-echo "File removed from the VC system")
366 (setq face 'vc-removed-state)
367 (concat backend-name "!" rev))
368 ((eq state 'missing)
369 (setq state-echo "File tracked by the VC system, but missing from the file system")
370 (setq face 'vc-missing-state)
371 (concat backend-name "?" rev))
373 (setq state-echo "Locally modified file")
374 (setq face 'vc-edited-state)
375 (concat backend-name ":" rev)))
376 'face face
377 'help-echo (concat state-echo " under the " backend-name
378 " version control system"))))
380 ;;; History functions
382 (defcustom vc-hg-log-switches nil
383 "String or list of strings specifying switches for hg log under VC."
384 :type '(choice (const :tag "None" nil)
385 (string :tag "Argument String")
386 (repeat :tag "Argument List" :value ("") string))
387 :group 'vc-hg)
389 (autoload 'vc-setup-buffer "vc-dispatcher")
391 (defvar vc-hg-log-graph nil
392 "If non-nil, use `--graph' in the short log output.")
394 (defvar vc-hg-log-format (concat "changeset: {rev}:{node|short}\n"
395 "{tags % 'tag: {tag}\n'}"
396 "{if(parents, 'parents: {parents}\n')}"
397 "user: {author}\n"
398 "Date: {date|date}\n"
399 "summary: {desc|tabindent}\n\n")
400 "Mercurial log template for `vc-hg-print-log' long format.")
402 (defun vc-hg-print-log (files buffer &optional shortlog start-revision limit)
403 "Print commit log associated with FILES into specified BUFFER.
404 If SHORTLOG is non-nil, use a short format based on `vc-hg-root-log-format'.
405 If START-REVISION is non-nil, it is the newest revision to show.
406 If LIMIT is non-nil, show no more than this many entries."
407 ;; `vc-do-command' creates the buffer, but we need it before running
408 ;; the command.
409 (vc-setup-buffer buffer)
410 ;; If the buffer exists from a previous invocation it might be
411 ;; read-only.
412 (let ((inhibit-read-only t))
413 (with-current-buffer
414 buffer
415 (apply 'vc-hg-command buffer 'async files "log"
416 (nconc
417 (when start-revision (list (format "-r%s:0" start-revision)))
418 (when limit (list "-l" (format "%s" limit)))
419 (if shortlog
420 `(,@(if vc-hg-log-graph '("--graph"))
421 "--template"
422 ,(car vc-hg-root-log-format))
423 `("--template" ,vc-hg-log-format))
424 vc-hg-log-switches)))))
426 (defvar log-view-message-re)
427 (defvar log-view-file-re)
428 (defvar log-view-font-lock-keywords)
429 (defvar log-view-per-file-logs)
430 (defvar log-view-expanded-log-entry-function)
432 (define-derived-mode vc-hg-log-view-mode log-view-mode "Hg-Log-View"
433 (require 'add-log) ;; we need the add-log faces
434 (set (make-local-variable 'log-view-file-re) "\\`a\\`")
435 (set (make-local-variable 'log-view-per-file-logs) nil)
436 (set (make-local-variable 'log-view-message-re)
437 (if (eq vc-log-view-type 'short)
438 (cadr vc-hg-root-log-format)
439 "^changeset:[ \t]*\\([0-9]+\\):\\(.+\\)"))
440 (set (make-local-variable 'tab-width) 2)
441 ;; Allow expanding short log entries
442 (when (eq vc-log-view-type 'short)
443 (setq truncate-lines t)
444 (set (make-local-variable 'log-view-expanded-log-entry-function)
445 'vc-hg-expanded-log-entry))
446 (set (make-local-variable 'log-view-font-lock-keywords)
447 (if (eq vc-log-view-type 'short)
448 (list (cons (nth 1 vc-hg-root-log-format)
449 (nth 2 vc-hg-root-log-format)))
450 (append
451 log-view-font-lock-keywords
453 ;; Handle the case:
454 ;; user: FirstName LastName <foo@bar>
455 ("^user:[ \t]+\\([^<(]+?\\)[ \t]*[(<]\\([A-Za-z0-9_.+-]+@[A-Za-z0-9_.-]+\\)[>)]"
456 (1 'change-log-name)
457 (2 'change-log-email))
458 ;; Handle the cases:
459 ;; user: foo@bar
460 ;; and
461 ;; user: foo
462 ("^user:[ \t]+\\([A-Za-z0-9_.+-]+\\(?:@[A-Za-z0-9_.-]+\\)?\\)"
463 (1 'change-log-email))
464 ("^date: \\(.+\\)" (1 'change-log-date))
465 ("^tag: +\\([^ ]+\\)$" (1 'highlight))
466 ("^summary:[ \t]+\\(.+\\)" (1 'log-view-message)))))))
468 (autoload 'vc-switches "vc")
470 (defun vc-hg-diff (files &optional oldvers newvers buffer _async)
471 "Get a difference report using hg between two revisions of FILES."
472 (let* ((firstfile (car files))
473 (working (and firstfile (vc-working-revision firstfile))))
474 (when (and (equal oldvers working) (not newvers))
475 (setq oldvers nil))
476 (when (and (not oldvers) newvers)
477 (setq oldvers working))
478 (apply #'vc-hg-command
479 (or buffer "*vc-diff*")
480 nil ; bug#21969
481 files "diff"
482 (append
483 (vc-switches 'hg 'diff)
484 (when oldvers
485 (if newvers
486 (list "-r" oldvers "-r" newvers)
487 (list "-r" oldvers)))))))
489 (defun vc-hg-expanded-log-entry (revision)
490 (with-temp-buffer
491 (vc-hg-command t nil nil "log" "-r" revision "--template" vc-hg-log-format)
492 (goto-char (point-min))
493 (unless (eobp)
494 ;; Indent the expanded log entry.
495 (indent-region (point-min) (point-max) 2)
496 (goto-char (point-max))
497 (buffer-string))))
499 (defun vc-hg-revision-table (files)
500 (let ((default-directory (file-name-directory (car files))))
501 (with-temp-buffer
502 (vc-hg-command t nil files "log" "--template" "{rev} ")
503 (split-string
504 (buffer-substring-no-properties (point-min) (point-max))))))
506 ;; Modeled after the similar function in vc-cvs.el
507 (defun vc-hg-revision-completion-table (files)
508 (letrec ((table (lazy-completion-table
509 table (lambda () (vc-hg-revision-table files)))))
510 table))
512 (defun vc-hg-annotate-command (file buffer &optional revision)
513 "Execute \"hg annotate\" on FILE, inserting the contents in BUFFER.
514 Optional arg REVISION is a revision to annotate from."
515 (apply #'vc-hg-command buffer 0 file "annotate" "-dq" "-n"
516 (append (vc-switches 'hg 'annotate)
517 (if revision (list (concat "-r" revision))))))
519 (declare-function vc-annotate-convert-time "vc-annotate" (&optional time))
521 ;; One line printed by "hg annotate -dq -n -u --follow" looks like this:
522 ;; b56girard 114590 2012-03-13 CLOBBER: Lorem ipsum dolor sit
523 ;; i.e. AUTHOR REVISION DATE FILENAME: CONTENTS
524 ;; The user can omit options "-u" and/or "--follow". Then it'll look like:
525 ;; 114590 2012-03-13 CLOBBER:
526 ;; or
527 ;; b56girard 114590 2012-03-13:
528 (defconst vc-hg-annotate-re
529 (concat
530 "^\\(?: *[^ ]+ +\\)?\\([0-9]+\\) " ;User and revision.
531 "\\([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\\)" ;Date.
532 "\\(?: +\\([^:]+\\)\\)?:")) ;Filename.
534 (defun vc-hg-annotate-time ()
535 (when (looking-at vc-hg-annotate-re)
536 (goto-char (match-end 0))
537 (vc-annotate-convert-time
538 (let ((str (match-string-no-properties 2)))
539 (encode-time 0 0 0
540 (string-to-number (substring str 6 8))
541 (string-to-number (substring str 4 6))
542 (string-to-number (substring str 0 4)))))))
544 (defun vc-hg-annotate-extract-revision-at-line ()
545 (save-excursion
546 (beginning-of-line)
547 (when (looking-at vc-hg-annotate-re)
548 (if (match-beginning 3)
549 (cons (match-string-no-properties 1)
550 (expand-file-name (match-string-no-properties 3)
551 (vc-hg-root default-directory)))
552 (match-string-no-properties 1)))))
554 ;;; Tag system
556 (defun vc-hg-create-tag (dir name branchp)
557 "Attach the tag NAME to the state of the working copy."
558 (let ((default-directory dir))
559 (and (vc-hg-command nil 0 nil "status")
560 (vc-hg-command nil 0 nil (if branchp "bookmark" "tag") name))))
562 (defun vc-hg-retrieve-tag (dir name _update)
563 "Retrieve the version tagged by NAME of all registered files at or below DIR."
564 (let ((default-directory dir))
565 (vc-hg-command nil 0 nil "update" name)
566 ;; TODO: update *vc-change-log* buffer so can see @ if --graph
569 ;;; Native data structure reading
571 (defcustom vc-hg-parse-hg-data-structures t
572 "If true, try directly parsing Mercurial data structures
573 directly instead of always running Mercurial. We try to be safe
574 against Mercurial data structure format changes and always fall
575 back to running Mercurial directly."
576 :type 'boolean
577 :version "26.1"
578 :group 'vc-hg)
580 (defsubst vc-hg--read-u8 ()
581 "Read and advance over an unsigned byte.
582 Return a fixnum."
583 (prog1 (char-after)
584 (forward-char)))
586 (defsubst vc-hg--read-u32-be ()
587 "Read and advance over a big-endian unsigned 32-bit integer.
588 Return a fixnum; on overflow, result is undefined."
589 ;; Because elisp bytecode has an instruction for multiply and
590 ;; doesn't have one for lsh, it's somewhat counter-intuitively
591 ;; faster to multiply than to shift.
592 (+ (* (vc-hg--read-u8) (* 256 256 256))
593 (* (vc-hg--read-u8) (* 256 256))
594 (* (vc-hg--read-u8) 256)
595 (identity (vc-hg--read-u8))))
597 (defun vc-hg--raw-dirstate-search (dirstate fname)
598 (with-temp-buffer
599 (set-buffer-multibyte nil)
600 (insert-file-contents-literally dirstate)
601 (let* ((result nil)
602 (flen (length fname))
603 (case-fold-search nil)
604 (inhibit-changing-match-data t)
605 ;; Find a conservative bound for the loop below by using
606 ;; Boyer-Moore on the raw dirstate without parsing it; we
607 ;; know we can't possibly find fname _after_ the last place
608 ;; it appears, so we can bail out early if we try to parse
609 ;; past it, which especially helps when the file we're
610 ;; trying to find isn't in dirstate at all. There's no way
611 ;; to similarly bound the starting search position, since
612 ;; the file format is such that we need to parse it from
613 ;; the beginning to find record boundaries.
614 (search-limit
615 (progn
616 (goto-char (point-max))
617 (or (search-backward fname (+ (point-min) 40) t)
618 (point-min)))))
619 ;; 40 is just after the header, which contains the working
620 ;; directory parents
621 (goto-char (+ (point-min) 40))
622 ;; Iterate over all dirstate entries; we might run this loop
623 ;; hundreds of thousands of times, so performance is important
624 ;; here
625 (while (< (point) search-limit)
626 ;; 1+4*4 is the length of the dirstate item header, which we
627 ;; spell as a literal for performance, since the elisp
628 ;; compiler lacks constant propagation
629 (forward-char (1+ (* 3 4)))
630 (let ((this-flen (vc-hg--read-u32-be)))
631 (if (and (or (eq this-flen flen)
632 (and (> this-flen flen)
633 (eq (char-after (+ (point) flen)) 0)))
634 (search-forward fname (+ (point) flen) t))
635 (progn
636 (backward-char (+ flen (1+ (* 4 4))))
637 (setf result
638 (list (vc-hg--read-u8) ; status
639 (vc-hg--read-u32-be) ; mode
640 (vc-hg--read-u32-be) ; size (of file)
641 (vc-hg--read-u32-be) ; mtime
643 (goto-char (point-max)))
644 (forward-char this-flen))))
645 result)))
647 (define-error 'vc-hg-unsupported-syntax "unsupported hgignore syntax")
649 (defconst vc-hg--pcre-c-escapes
650 '((?a . ?\a)
651 (?b . ?\b)
652 (?f . ?\f)
653 (?n . ?\n)
654 (?r . ?\r)
655 (?t . ?\t)
656 (?n . ?\n)
657 (?r . ?\r)
658 (?t . ?\t)
659 (?v . ?\v)))
661 (defconst vc-hg--pcre-metacharacters
662 '(?. ?^ ?$ ?* ?+ ?? ?{ ?\\ ?\[ ?\| ?\())
664 (defconst vc-hg--elisp-metacharacters
665 '(?. ?* ?+ ?? ?\[ ?$ ?\\))
667 (defun vc-hg--escape-for-pcre (c)
668 (if (memq c vc-hg--pcre-metacharacters)
669 (string ?\\ c)
672 (defun vc-hg--parts-to-string (parts)
673 "Build a string from list PARTS. Each element is a character or string."
674 (let ((parts2 nil))
675 (while parts
676 (let* ((partcell (prog1 parts (setf parts (cdr parts))))
677 (part (car partcell)))
678 (if (stringp part)
679 (setf parts2 (nconc (append part nil) parts2))
680 (setcdr partcell parts2)
681 (setf parts2 partcell))))
682 (apply #'string parts2)))
684 (defun vc-hg--pcre-to-elisp-re (pcre prefix)
685 "Transform PCRE, a Mercurial file PCRE, into an elisp RE against PREFIX.
686 PREFIX is the directory name of the directory against which these
687 patterns are rooted. We understand only a subset of PCRE syntax;
688 if we don't understand a construct, we signal
689 `vc-hg-unsupported-syntax'."
690 (cl-assert (and (file-name-absolute-p prefix)
691 (directory-name-p prefix)))
692 (let ((parts nil)
693 (i 0)
694 (anchored nil)
695 (state 'normal)
696 (pcrelen (length pcre)))
697 (while (< i pcrelen)
698 (let ((c (aref pcre i)))
699 (cond ((eq state 'normal)
700 (cond ((string-match
701 (rx (| "}\\?" (: "(?" (not (any ":")))))
702 pcre i)
703 (signal 'vc-hg-unsupported-syntax (list pcre)))
704 ((eq c ?\\)
705 (setf state 'backslash))
706 ((eq c ?\[)
707 (setf state 'charclass-enter)
708 (push c parts))
709 ((eq c ?^)
710 (if (eq i 0) (setf anchored t)
711 (signal 'vc-hg-unsupported-syntax (list pcre))))
712 ((eq c ?$)
713 ;; Patterns can also match directories exactly,
714 ;; ignoring everything under a matched directory
715 (push "\\(?:$\\|/\\)" parts))
716 ((memq c '(?| ?\( ?\)))
717 (push ?\\ parts)
718 (push c parts))
719 (t (push c parts))))
720 ((eq state 'backslash)
721 (cond ((memq c '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9
722 ?A ?b ?B ?d ?D ?s ?S ?w ?W ?Z ?x))
723 (signal 'vc-hg-unsupported-syntax (list pcre)))
724 ((memq c vc-hg--elisp-metacharacters)
725 (push ?\\ parts)
726 (push c parts))
727 (t (push (or (cdr (assq c vc-hg--pcre-c-escapes)) c) parts)))
728 (setf state 'normal))
729 ((eq state 'charclass-enter)
730 (push c parts)
731 (setf state
732 (if (eq c ?\\)
733 'charclass
734 'charclass-backslash)))
735 ((eq state 'charclass-backslash)
736 (if (memq c '(?0 ?x))
737 (signal 'vc-hg-unsupported-syntax (list pcre)))
738 (push (or (cdr (assq c vc-hg--pcre-c-escapes)) c) parts)
739 (setf state 'charclass))
740 ((eq state 'charclass)
741 (push c parts)
742 (cond ((eq c ?\\) (setf state 'charclass-backslash))
743 ((eq c ?\]) (setf state 'normal))))
744 (t (error "invalid state")))
745 (setf i (1+ i))))
746 (unless (eq state 'normal)
747 (signal 'vc-hg-unsupported-syntax (list pcre)))
748 (concat
750 prefix
751 (if anchored "" "\\(?:.*/\\)?")
752 (vc-hg--parts-to-string parts))))
754 (defun vc-hg--glob-to-pcre (glob)
755 "Transform a glob pattern into a Mercurial file pattern regex."
756 (let ((parts nil) (i 0) (n (length glob)) (group 0) c)
757 (cl-macrolet ((peek () '(and (< i n) (aref glob i))))
758 (while (< i n)
759 (setf c (aref glob i))
760 (cl-incf i)
761 (cond ((not (memq c '(?* ?? ?\[ ?\{ ?\} ?, ?\\)))
762 (push (vc-hg--escape-for-pcre c) parts))
763 ((eq c ?*)
764 (cond ((eq (peek) ?*)
765 (cl-incf i)
766 (cond ((eq (peek) ?/)
767 (cl-incf i)
768 (push "(?:.*/)?" parts))
770 (push ".*" parts))))
771 (t (push "[^/]*" parts))))
772 ((eq c ??)
773 (push ?. parts))
774 ((eq c ?\[)
775 (let ((j i))
776 (when (and (< j n) (memq (aref glob j) '(?! ?\])))
777 (cl-incf j))
778 (while (and (< j n) (not (eq (aref glob j) ?\])))
779 (cl-incf j))
780 (cond ((>= j n)
781 (push "\\[" parts))
783 (let ((x (substring glob i j)))
784 (setf x (replace-regexp-in-string
785 "\\\\" "\\\\" x t t))
786 (setf i (1+ j))
787 (cond ((eq (aref x 0) ?!)
788 (setf (aref x 0) ?^))
789 ((eq (aref x 0) ?^)
790 (setf x (concat "\\" x))))
791 (push ?\[ parts)
792 (push x parts)
793 (push ?\] parts))))))
794 ((eq c ?\{)
795 (cl-incf group)
796 (push "(?:" parts))
797 ((eq c ?\})
798 (push ?\) parts)
799 (cl-decf group))
800 ((and (eq c ?,) (> group 0))
801 (push ?| parts))
802 ((eq c ?\\)
803 (if (eq i n)
804 (push "\\\\" parts)
805 (cl-incf i)
806 (push ?\\ parts)
807 (push c parts)))
809 (push (vc-hg--escape-for-pcre c) parts)))))
810 (concat (vc-hg--parts-to-string parts) "$")))
812 (defvar vc-hg--hgignore-patterns)
813 (defvar vc-hg--hgignore-filenames)
815 (defun vc-hg--hgignore-add-pcre (pcre prefix)
816 (push (vc-hg--pcre-to-elisp-re pcre prefix) vc-hg--hgignore-patterns))
818 (defun vc-hg--hgignore-add-glob (glob prefix)
819 (push (vc-hg--pcre-to-elisp-re (vc-hg--glob-to-pcre glob) prefix)
820 vc-hg--hgignore-patterns))
822 (defun vc-hg--hgignore-add-path (path prefix)
823 (let ((parts nil))
824 (dotimes (i (length path))
825 (push (vc-hg--escape-for-pcre (aref path i)) parts))
826 (vc-hg--hgignore-add-pcre
827 (concat "^" (vc-hg--parts-to-string parts) "$")
828 prefix)))
830 (defun vc-hg--slurp-hgignore-1 (hgignore prefix)
831 (let ((default-syntax 'vc-hg--hgignore-add-pcre))
832 (with-temp-buffer
833 (let ((attr (file-attributes hgignore)))
834 (when attr (insert-file-contents hgignore))
835 (push (list hgignore (nth 5 attr) (nth 7 attr))
836 vc-hg--hgignore-filenames))
837 (while (not (eobp))
838 ;; This list of pattern-file commands isn't complete, but it
839 ;; should cover the common cases. Remember that we fall back
840 ;; to regular hg commands if we see something we don't like.
841 (save-restriction
842 (narrow-to-region (point) (point-at-eol))
843 (cond ((looking-at "[ \t]*\\(?:#.*\\)?$"))
844 ((looking-at "syntax:[ \t]*re[ \t]*$")
845 (setf default-syntax 'vc-hg--hgignore-add-pcre))
846 ((looking-at "syntax:[ \t]*glob[ \t]*$")
847 (setf default-syntax 'vc-hg--hgignore-add-glob))
848 ((looking-at "path:\\(.+?\\)[ \t]*$")
849 (vc-hg--hgignore-add-path (match-string 1) prefix))
850 ((looking-at "glob:\\(.+?\\)[ \t]*$")
851 (vc-hg--hgignore-add-glob (match-string 1) prefix))
852 ((looking-at "re:\\(.+?\\)[ \t]*$")
853 (vc-hg--hgignore-add-pcre (match-string 1) prefix))
854 ((looking-at "\\(sub\\)?include:\\(.+?\\)[ \t]*$")
855 (let* ((sub (equal (match-string 1) "sub"))
856 (arg (match-string 2))
857 (included-file
858 (if (string-match "^/" arg) arg
859 (concat (file-name-directory hgignore) arg))))
860 (vc-hg--slurp-hgignore-1
861 included-file
862 (if sub (file-name-directory included-file) prefix))))
863 ((looking-at "[a-zA-Z0-9_]*:")
864 (signal 'vc-hg-unsupported-syntax (list (match-string 0))))
865 ((looking-at ".*$")
866 (funcall default-syntax (match-string 0) prefix))))
867 (forward-line 1)))))
869 (cl-defstruct (vc-hg--ignore-patterns
870 (:copier nil)
871 (:constructor vc-hg--ignore-patterns-make))
872 repo
873 ignore-patterns
874 file-sources)
876 (defun vc-hg--slurp-hgignore (repo)
877 "Read hg ignore patterns from REPO.
878 REPO must be the directory name of an hg repository."
879 (cl-assert (and (file-name-absolute-p repo)
880 (directory-name-p repo)))
881 (let* ((hgignore (concat repo ".hgignore"))
882 (vc-hg--hgignore-patterns nil)
883 (vc-hg--hgignore-filenames nil))
884 (vc-hg--slurp-hgignore-1 hgignore repo)
885 (vc-hg--ignore-patterns-make
886 :repo repo
887 :ignore-patterns (nreverse vc-hg--hgignore-patterns)
888 :file-sources (nreverse vc-hg--hgignore-filenames))))
890 (defun vc-hg--ignore-patterns-valid-p (hgip)
891 "Return whether the cached ignore patterns in HGIP are still valid"
892 (let ((valid t)
893 (file-sources (vc-hg--ignore-patterns-file-sources hgip)))
894 (while (and file-sources valid)
895 (let* ((fs (pop file-sources))
896 (saved-mtime (nth 1 fs))
897 (saved-size (nth 2 fs))
898 (attr (file-attributes (nth 0 fs)))
899 (current-mtime (nth 5 attr))
900 (current-size (nth 7 attr)))
901 (unless (and (equal saved-mtime current-mtime)
902 (equal saved-size current-size))
903 (setf valid nil))))
904 valid))
906 (defun vc-hg--ignore-patterns-ignored-p (hgip filename)
907 "Test whether the ignore pattern set HGIP says to ignore FILENAME.
908 FILENAME must be the file's true absolute name."
909 (let ((patterns (vc-hg--ignore-patterns-ignore-patterns hgip))
910 (inhibit-changing-match-data t)
911 (ignored nil))
912 (while (and patterns (not ignored))
913 (setf ignored (string-match (pop patterns) filename)))
914 ignored))
916 (defun vc-hg--time-to-fixnum (ts)
917 (+ (* 65536 (car ts)) (cadr ts)))
919 (defvar vc-hg--cached-ignore-patterns nil
920 "Cached pre-parsed hg ignore patterns.")
922 (defun vc-hg--file-ignored-p (repo repo-relative-filename)
923 (let ((hgip vc-hg--cached-ignore-patterns))
924 (unless (and hgip
925 (equal repo (vc-hg--ignore-patterns-repo hgip))
926 (vc-hg--ignore-patterns-valid-p hgip))
927 (setf vc-hg--cached-ignore-patterns nil)
928 (setf hgip (vc-hg--slurp-hgignore repo))
929 (setf vc-hg--cached-ignore-patterns hgip))
930 (vc-hg--ignore-patterns-ignored-p
931 hgip
932 (concat repo repo-relative-filename))))
934 (defun vc-hg--read-repo-requirements (repo)
935 (cl-assert (and (file-name-absolute-p repo)
936 (directory-name-p repo)))
937 (let* ((requires-filename (concat repo ".hg/requires")))
938 (and (file-exists-p requires-filename)
939 (with-temp-buffer
940 (set-buffer-multibyte nil)
941 (insert-file-contents-literally requires-filename)
942 (split-string (buffer-substring-no-properties
943 (point-min) (point-max)))))))
945 (defconst vc-hg-supported-requirements
946 '("dotencode"
947 "fncache"
948 "generaldelta"
949 "lz4revlog"
950 "remotefilelog"
951 "revlogv1"
952 "store")
953 "List of Mercurial repository requirements we understand; if a
954 repository requires features not present in this list, we avoid
955 attempting to parse Mercurial data structures.")
957 (defun vc-hg--requirements-understood-p (repo)
958 "Check that we understand the format of the given repository.
959 REPO is the directory name of a Mercurial repository."
960 (null (cl-set-difference (vc-hg--read-repo-requirements repo)
961 vc-hg-supported-requirements
962 :test #'equal)))
964 (defvar vc-hg--dirstate-scan-cache nil
965 "Cache of the last result of `vc-hg--raw-dirstate-search'.
966 Avoids the need to repeatedly scan dirstate on repeated calls to
967 `vc-hg-state', as we see during registration queries.")
969 (defun vc-hg--cached-dirstate-search (dirstate dirstate-attr ascii-fname)
970 (let* ((mtime (nth 5 dirstate-attr))
971 (size (nth 7 dirstate-attr))
972 (cache vc-hg--dirstate-scan-cache)
974 (if (and cache
975 (equal dirstate (pop cache))
976 (equal mtime (pop cache))
977 (equal size (pop cache))
978 (equal ascii-fname (pop cache)))
979 (pop cache)
980 (let ((result (vc-hg--raw-dirstate-search dirstate ascii-fname)))
981 (setf vc-hg--dirstate-scan-cache
982 (list dirstate mtime size ascii-fname result))
983 result))))
985 (defun vc-hg-state-fast (filename)
986 "Like `vc-hg-state', but parse internal data structures directly.
987 Returns one of the usual `vc-state' enumeration values or
988 `unsupported' if we need to take the slow path and run the
989 hg binary."
990 (let* (truename
991 repo
992 dirstate
993 dirstate-attr
994 repo-relative-filename)
995 (if (or
996 ;; Explicit user disable
997 (not vc-hg-parse-hg-data-structures)
998 ;; It'll probably be faster to run hg remotely
999 (file-remote-p filename)
1000 (progn
1001 (setf truename (file-truename filename))
1002 (file-remote-p truename))
1003 (not (setf repo (vc-hg-root truename)))
1004 ;; dirstate must exist
1005 (not (progn
1006 (setf repo (expand-file-name repo))
1007 (cl-assert (and (file-name-absolute-p repo)
1008 (directory-name-p repo)))
1009 (setf dirstate (concat repo ".hg/dirstate"))
1010 (setf dirstate-attr (file-attributes dirstate))))
1011 ;; Repository must be in an understood format
1012 (not (vc-hg--requirements-understood-p repo))
1013 ;; Dirstate too small to be valid
1014 (< (nth 7 dirstate-attr) 40)
1015 ;; We want to store 32-bit unsigned values in fixnums
1016 (< most-positive-fixnum 4294967295)
1017 (progn
1018 (setf repo-relative-filename
1019 (file-relative-name truename repo))
1020 ;; We only try dealing with ASCII filenames
1021 (string-match-p "[^[:ascii:]]" repo-relative-filename)))
1022 'unsupported
1023 (let* ((dirstate-entry
1024 (vc-hg--cached-dirstate-search
1025 dirstate dirstate-attr repo-relative-filename))
1026 (state (car dirstate-entry))
1027 (stat (file-attributes
1028 (concat repo repo-relative-filename))))
1029 (cond ((eq state ?r) 'removed)
1030 ((and (not state) stat)
1031 (condition-case nil
1032 (if (vc-hg--file-ignored-p repo repo-relative-filename)
1033 'ignored
1034 'unregistered)
1035 (vc-hg-unsupported-syntax 'unsupported)))
1036 ((and state (not stat)) 'missing)
1037 ((eq state ?n)
1038 (let ((vc-hg-size (nth 2 dirstate-entry))
1039 (vc-hg-mtime (nth 3 dirstate-entry))
1040 (fs-size (nth 7 stat))
1041 (fs-mtime (vc-hg--time-to-fixnum (nth 5 stat))))
1042 (if (and (eql vc-hg-size fs-size) (eql vc-hg-mtime fs-mtime))
1043 'up-to-date
1044 'edited)))
1045 ((eq state ?a) 'added)
1046 (state 'unsupported))))))
1048 ;;; Miscellaneous
1050 (defun vc-hg-previous-revision (_file rev)
1051 ;; We can't simply decrement by 1, because that revision might be
1052 ;; e.g. on a different branch (bug#22032).
1053 (with-temp-buffer
1054 (and (eq 0
1055 (vc-hg-command t nil nil "id" "-n" "-r" (concat rev "^")))
1056 ;; Trim the trailing newline.
1057 (buffer-substring (point-min) (1- (point-max))))))
1059 (defun vc-hg-next-revision (_file rev)
1060 (let ((newrev (1+ (string-to-number rev)))
1061 (tip-revision
1062 (with-temp-buffer
1063 (vc-hg-command t 0 nil "tip" "--style=default")
1064 (goto-char (point-min))
1065 (re-search-forward "^changeset:[ \t]*\\([0-9]+\\):")
1066 (string-to-number (match-string-no-properties 1)))))
1067 ;; We don't want to exceed the maximum possible revision number, ie
1068 ;; the tip revision.
1069 (when (<= newrev tip-revision)
1070 (number-to-string newrev))))
1072 ;; Modeled after the similar function in vc-bzr.el
1073 (defun vc-hg-delete-file (file)
1074 "Delete FILE and delete it in the hg repository."
1075 (condition-case ()
1076 (delete-file file)
1077 (file-error nil))
1078 (vc-hg-command nil 0 file "remove" "--after" "--force"))
1080 ;; Modeled after the similar function in vc-bzr.el
1081 (defun vc-hg-rename-file (old new)
1082 "Rename file from OLD to NEW using `hg mv'."
1083 (vc-hg-command nil 0 new "mv" old))
1085 (defun vc-hg-register (files &optional _comment)
1086 "Register FILES under hg. COMMENT is ignored."
1087 (vc-hg-command nil 0 files "add"))
1089 (defun vc-hg-create-repo ()
1090 "Create a new Mercurial repository."
1091 (vc-hg-command nil 0 nil "init"))
1093 (defalias 'vc-hg-responsible-p 'vc-hg-root)
1095 (defun vc-hg-unregister (file)
1096 "Unregister FILE from hg."
1097 (vc-hg-command nil 0 file "forget"))
1099 (declare-function log-edit-extract-headers "log-edit" (headers string))
1101 (defun vc-hg-checkin (files comment &optional _rev)
1102 "Hg-specific version of `vc-backend-checkin'.
1103 REV is ignored."
1104 (apply 'vc-hg-command nil 0 files
1105 (nconc (list "commit" "-m")
1106 (log-edit-extract-headers '(("Author" . "--user")
1107 ("Date" . "--date"))
1108 comment))))
1110 (defun vc-hg-find-revision (file rev buffer)
1111 (let ((coding-system-for-read 'binary)
1112 (coding-system-for-write 'binary))
1113 (if rev
1114 (vc-hg-command buffer 0 file "cat" "-r" rev)
1115 (vc-hg-command buffer 0 file "cat"))))
1117 (defun vc-hg-find-ignore-file (file)
1118 "Return the root directory of the repository of FILE."
1119 (expand-file-name ".hgignore"
1120 (vc-hg-root file)))
1122 ;; Modeled after the similar function in vc-bzr.el
1123 (defun vc-hg-checkout (file &optional rev)
1124 "Retrieve a revision of FILE.
1125 EDITABLE is ignored.
1126 REV is the revision to check out into WORKFILE."
1127 (let ((coding-system-for-read 'binary)
1128 (coding-system-for-write 'binary))
1129 (with-current-buffer (or (get-file-buffer file) (current-buffer))
1130 (if rev
1131 (vc-hg-command t 0 file "cat" "-r" rev)
1132 (vc-hg-command t 0 file "cat")))))
1134 (defun vc-hg-resolve-when-done ()
1135 "Call \"hg resolve -m\" if the conflict markers have been removed."
1136 (save-excursion
1137 (goto-char (point-min))
1138 (unless (re-search-forward "^<<<<<<< " nil t)
1139 (vc-hg-command nil 0 buffer-file-name "resolve" "-m")
1140 ;; Remove the hook so that it is not called multiple times.
1141 (remove-hook 'after-save-hook 'vc-hg-resolve-when-done t))))
1143 (defun vc-hg-find-file-hook ()
1144 (when (and buffer-file-name
1145 (file-exists-p (concat buffer-file-name ".orig"))
1146 ;; Hg does not seem to have a "conflict" status, eg
1147 ;; hg http://bz.selenic.com/show_bug.cgi?id=2724
1148 (memq (vc-file-getprop buffer-file-name 'vc-state)
1149 '(edited conflict))
1150 ;; Maybe go on to check that "hg resolve -l" says "U"?
1151 ;; If "hg resolve -l" says there's a conflict but there are no
1152 ;; conflict markers, it's not clear what we should do.
1153 (save-excursion
1154 (goto-char (point-min))
1155 (re-search-forward "^<<<<<<< " nil t)))
1156 ;; Hg may not recognize "conflict" as a state, but we can do better.
1157 (vc-file-setprop buffer-file-name 'vc-state 'conflict)
1158 (smerge-start-session)
1159 (add-hook 'after-save-hook 'vc-hg-resolve-when-done nil t)
1160 (vc-message-unresolved-conflicts buffer-file-name)))
1163 ;; Modeled after the similar function in vc-bzr.el
1164 (defun vc-hg-revert (file &optional contents-done)
1165 (unless contents-done
1166 (with-temp-buffer (vc-hg-command t 0 file "revert"))))
1168 ;;; Hg specific functionality.
1170 (defvar vc-hg-extra-menu-map
1171 (let ((map (make-sparse-keymap)))
1172 map))
1174 (defun vc-hg-extra-menu () vc-hg-extra-menu-map)
1176 (defun vc-hg-extra-status-menu () vc-hg-extra-menu-map)
1178 (defvar log-view-vc-backend)
1180 (cl-defstruct (vc-hg-extra-fileinfo
1181 (:copier nil)
1182 (:constructor vc-hg-create-extra-fileinfo (rename-state extra-name))
1183 (:conc-name vc-hg-extra-fileinfo->))
1184 rename-state ;; rename or copy state
1185 extra-name) ;; original name for copies and rename targets, new name for
1187 (declare-function vc-default-dir-printer "vc-dir" (backend fileentry))
1189 (defun vc-hg-dir-printer (info)
1190 "Pretty-printer for the vc-dir-fileinfo structure."
1191 (let ((extra (vc-dir-fileinfo->extra info)))
1192 (vc-default-dir-printer 'Hg info)
1193 (when extra
1194 (insert (propertize
1195 (format " (%s %s)"
1196 (pcase (vc-hg-extra-fileinfo->rename-state extra)
1197 (`copied "copied from")
1198 (`renamed-from "renamed from")
1199 (`renamed-to "renamed to"))
1200 (vc-hg-extra-fileinfo->extra-name extra))
1201 'face 'font-lock-comment-face)))))
1203 (defun vc-hg-after-dir-status (update-function)
1204 (let ((file nil)
1205 (translation '((?= . up-to-date)
1206 (?C . up-to-date)
1207 (?A . added)
1208 (?R . removed)
1209 (?M . edited)
1210 (?I . ignored)
1211 (?! . missing)
1212 (? . copy-rename-line)
1213 (?? . unregistered)))
1214 (translated nil)
1215 (result nil)
1216 (last-added nil)
1217 (last-line-copy nil))
1218 (goto-char (point-min))
1219 (while (not (eobp))
1220 (setq translated (cdr (assoc (char-after) translation)))
1221 (setq file
1222 (buffer-substring-no-properties (+ (point) 2)
1223 (line-end-position)))
1224 (cond ((not translated)
1225 (setq last-line-copy nil))
1226 ((eq translated 'up-to-date)
1227 (setq last-line-copy nil))
1228 ((eq translated 'copy-rename-line)
1229 ;; For copied files the output looks like this:
1230 ;; A COPIED_FILE_NAME
1231 ;; ORIGINAL_FILE_NAME
1232 (setf (nth 2 last-added)
1233 (vc-hg-create-extra-fileinfo 'copied file))
1234 (setq last-line-copy t))
1235 ((and last-line-copy (eq translated 'removed))
1236 ;; For renamed files the output looks like this:
1237 ;; A NEW_FILE_NAME
1238 ;; ORIGINAL_FILE_NAME
1239 ;; R ORIGINAL_FILE_NAME
1240 ;; We need to adjust the previous entry to not think it is a copy.
1241 (setf (vc-hg-extra-fileinfo->rename-state (nth 2 last-added))
1242 'renamed-from)
1243 (push (list file translated
1244 (vc-hg-create-extra-fileinfo
1245 'renamed-to (nth 0 last-added))) result)
1246 (setq last-line-copy nil))
1248 (setq last-added (list file translated nil))
1249 (push last-added result)
1250 (setq last-line-copy nil)))
1251 (forward-line))
1252 (funcall update-function result)))
1254 ;; Follows vc-hg-command (or vc-do-async-command), which uses vc-do-command
1255 ;; from vc-dispatcher.
1256 (declare-function vc-exec-after "vc-dispatcher" (code))
1257 ;; Follows vc-exec-after.
1258 (declare-function vc-set-async-update "vc-dispatcher" (process-buffer))
1260 (defun vc-hg-dir-status-files (_dir files update-function)
1261 ;; XXX: We can't pass DIR directly to 'hg status' because that
1262 ;; returns all ignored files if FILES is non-nil (bug#22481).
1263 ;; If honoring DIR ever becomes important, try using '-I DIR/'.
1264 (vc-hg-command (current-buffer) 'async files
1265 "status"
1266 (concat "-mardu" (if files "i"))
1267 "-C")
1268 (vc-run-delayed
1269 (vc-hg-after-dir-status update-function)))
1271 (defun vc-hg-dir-extra-header (name &rest commands)
1272 (concat (propertize name 'face 'font-lock-type-face)
1273 (propertize
1274 (with-temp-buffer
1275 (apply 'vc-hg-command (current-buffer) 0 nil commands)
1276 (buffer-substring-no-properties (point-min) (1- (point-max))))
1277 'face 'font-lock-variable-name-face)))
1279 (defun vc-hg-dir-extra-headers (dir)
1280 "Generate extra status headers for a Mercurial tree."
1281 (let ((default-directory dir))
1282 (concat
1283 (vc-hg-dir-extra-header "Root : " "root") "\n"
1284 (vc-hg-dir-extra-header "Branch : " "id" "-b") "\n"
1285 (vc-hg-dir-extra-header "Tags : " "id" "-t") ; "\n"
1286 ;; these change after each commit
1287 ;; (vc-hg-dir-extra-header "Local num : " "id" "-n") "\n"
1288 ;; (vc-hg-dir-extra-header "Global id : " "id" "-i")
1291 (defun vc-hg-log-incoming (buffer remote-location)
1292 (vc-hg-command buffer 1 nil "incoming" "-n" (unless (string= remote-location "")
1293 remote-location)))
1295 (defun vc-hg-log-outgoing (buffer remote-location)
1296 (vc-hg-command buffer 1 nil "outgoing" "-n" (unless (string= remote-location "")
1297 remote-location)))
1299 (defvar vc-hg-error-regexp-alist nil
1300 ;; 'hg pull' does not list modified files, so, for now, the only
1301 ;; benefit of `vc-compilation-mode' is that one can get rid of
1302 ;; *vc-hg* buffer with 'q' or 'z'.
1303 ;; TODO: call 'hg incoming' before pull/merge to get the list of
1304 ;; modified files
1305 "Value of `compilation-error-regexp-alist' in *vc-hg* buffers.")
1307 (autoload 'vc-do-async-command "vc-dispatcher")
1308 (autoload 'log-view-get-marked "log-view")
1309 (defvar compilation-directory)
1310 (defvar compilation-arguments) ; defined in compile.el
1312 (defun vc-hg--pushpull (command prompt &optional obsolete)
1313 "Run COMMAND (a string; either push or pull) on the current Hg branch.
1314 If PROMPT is non-nil, prompt for the Hg command to run.
1315 If OBSOLETE is non-nil, behave like the old versions of the Hg push/pull
1316 commands, which only operated on marked files."
1317 (let (marked-list)
1318 ;; The `vc-hg-pull' and `vc-hg-push' commands existed before the
1319 ;; `pull'/`push' VC actions were implemented.
1320 ;; The following is for backwards compatibility.
1321 (if (and obsolete (setq marked-list (log-view-get-marked)))
1322 (apply #'vc-hg-command
1323 nil 0 nil
1324 command
1325 (apply 'nconc
1326 (mapcar (lambda (arg) (list "-r" arg)) marked-list)))
1327 (let* ((root (vc-hg-root default-directory))
1328 (buffer (format "*vc-hg : %s*" (expand-file-name root)))
1329 (hg-program vc-hg-program)
1330 ;; Fixme: before updating the working copy to the latest
1331 ;; state, should check if it's visiting an old revision.
1332 (args (if (equal command "pull") '("-u"))))
1333 ;; If necessary, prompt for the exact command.
1334 ;; TODO if pushing, prompt if no default push location - cf bzr.
1335 (when prompt
1336 (setq args (split-string
1337 (read-shell-command
1338 (format "Hg %s command: " command)
1339 (format "%s %s%s" hg-program command
1340 (if (not args) ""
1341 (concat " " (mapconcat 'identity args " "))))
1342 'vc-hg-history)
1343 " " t))
1344 (setq hg-program (car args)
1345 command (cadr args)
1346 args (cddr args)))
1347 (apply 'vc-do-async-command buffer root hg-program command args)
1348 (with-current-buffer buffer
1349 (vc-run-delayed
1350 (vc-compilation-mode 'hg)
1351 (setq-local compile-command
1352 (concat hg-program " " command " "
1353 (if args (mapconcat 'identity args " ") "")))
1354 (setq-local compilation-directory root)
1355 ;; Either set `compilation-buffer-name-function' locally to nil
1356 ;; or use `compilation-arguments' to set `name-function'.
1357 ;; See `compilation-buffer-name'.
1358 (setq-local compilation-arguments
1359 (list compile-command nil
1360 (lambda (_name-of-mode) buffer)
1361 nil))))
1362 (vc-set-async-update buffer)))))
1364 (defun vc-hg-pull (prompt)
1365 "Issue a Mercurial pull command.
1366 If called interactively with a set of marked Log View buffers,
1367 call \"hg pull -r REVS\" to pull in the specified revisions REVS.
1369 With a prefix argument or if PROMPT is non-nil, prompt for a
1370 specific Mercurial pull command. The default is \"hg pull -u\",
1371 which fetches changesets from the default remote repository and
1372 then attempts to update the working directory."
1373 (interactive "P")
1374 (vc-hg--pushpull "pull" prompt (called-interactively-p 'interactive)))
1376 (defun vc-hg-push (prompt)
1377 "Push changes from the current Mercurial branch.
1378 Normally, this runs \"hg push\". If PROMPT is non-nil, prompt
1379 for the Hg command to run.
1381 If called interactively with a set of marked Log View buffers,
1382 call \"hg push -r REVS\" to push the specified revisions REVS."
1383 (interactive "P")
1384 (vc-hg--pushpull "push" prompt (called-interactively-p 'interactive)))
1386 (defun vc-hg-merge-branch ()
1387 "Merge incoming changes into the current working directory.
1388 This runs the command \"hg merge\"."
1389 (let* ((root (vc-hg-root default-directory))
1390 (buffer (format "*vc-hg : %s*" (expand-file-name root))))
1391 (apply 'vc-do-async-command buffer root vc-hg-program '("merge"))
1392 (with-current-buffer buffer (vc-run-delayed (vc-compilation-mode 'hg)))
1393 (vc-set-async-update buffer)))
1395 ;;; Internal functions
1397 (defun vc-hg-command (buffer okstatus file-or-list &rest flags)
1398 "A wrapper around `vc-do-command' for use in vc-hg.el.
1399 This function differs from vc-do-command in that it invokes
1400 `vc-hg-program', and passes `vc-hg-global-switches' to it before FLAGS."
1401 (apply 'vc-do-command (or buffer "*vc*") okstatus vc-hg-program file-or-list
1402 (if (stringp vc-hg-global-switches)
1403 (cons vc-hg-global-switches flags)
1404 (append vc-hg-global-switches
1405 flags))))
1407 (defun vc-hg-root (file)
1408 (vc-find-root file ".hg"))
1410 (provide 'vc-hg)
1412 ;;; vc-hg.el ends here