ediff-ptch.el 30 KB
Newer Older
Michael Kifer's avatar
Michael Kifer committed
1 2
;;; ediff-ptch.el --- Ediff's  patch support

3
;; Copyright (C) 1996-2013 Free Software Foundation, Inc.
Michael Kifer's avatar
Michael Kifer committed
4

5
;; Author: Michael Kifer <kifer@cs.stonybrook.edu>
6
;; Package: ediff
Michael Kifer's avatar
Michael Kifer committed
7 8 9

;; This file is part of GNU Emacs.

10
;; GNU Emacs is free software: you can redistribute it and/or modify
Michael Kifer's avatar
Michael Kifer committed
11
;; it under the terms of the GNU General Public License as published by
12 13
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Michael Kifer's avatar
Michael Kifer committed
14 15 16 17 18 19 20

;; GNU Emacs 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
21
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
Michael Kifer's avatar
Michael Kifer committed
22

23
;;; Commentary:
Michael Kifer's avatar
Michael Kifer committed
24 25

;;; Code:
26

Michael Kifer's avatar
Michael Kifer committed
27

28 29
(provide 'ediff-ptch)

Michael Kifer's avatar
Michael Kifer committed
30
(defgroup ediff-ptch nil
31
  "Ediff patch support."
Michael Kifer's avatar
Michael Kifer committed
32 33 34 35
  :tag "Patch"
  :prefix "ediff-"
  :group 'ediff)

Richard M. Stallman's avatar
Richard M. Stallman committed
36
(require 'ediff-init)
Glenn Morris's avatar
Glenn Morris committed
37
(require 'ediff-util)
Richard M. Stallman's avatar
Richard M. Stallman committed
38

Michael Kifer's avatar
Michael Kifer committed
39
(defcustom ediff-patch-program  "patch"
Lute Kamstra's avatar
Lute Kamstra committed
40
  "Name of the program that applies patches.
Michael Kifer's avatar
Michael Kifer committed
41 42 43 44
It is recommended to use GNU-compatible versions."
  :type 'string
  :group 'ediff-ptch)
(defcustom ediff-patch-options "-f"
Lute Kamstra's avatar
Lute Kamstra committed
45
  "Options to pass to ediff-patch-program.
Michael Kifer's avatar
Michael Kifer committed
46 47 48 49

Note: the `-b' option should be specified in `ediff-backup-specs'.

It is recommended to pass the `-f' option to the patch program, so it won't ask
Michael Kifer's avatar
Michael Kifer committed
50
questions.  However, some implementations don't accept this option, in which
Michael Kifer's avatar
Michael Kifer committed
51 52 53 54
case the default value for this variable should be changed."
  :type 'string
  :group 'ediff-ptch)

Michael Kifer's avatar
Michael Kifer committed
55 56 57
(defvar ediff-last-dir-patch nil
  "Last directory used by an Ediff command for file to patch.")

Michael Kifer's avatar
Michael Kifer committed
58 59
;; the default backup extension
(defconst ediff-default-backup-extension
60
  (if (eq system-type 'ms-dos)
Michael Kifer's avatar
Michael Kifer committed
61
      "_orig" ".orig"))
62

Michael Kifer's avatar
Michael Kifer committed
63 64

(defcustom ediff-backup-extension ediff-default-backup-extension
Michael Kifer's avatar
Michael Kifer committed
65
  "Backup extension used by the patch program.
Michael Kifer's avatar
Michael Kifer committed
66 67 68
See also `ediff-backup-specs'."
  :type 'string
  :group 'ediff-ptch)
Michael Kifer's avatar
Michael Kifer committed
69

Michael Kifer's avatar
Michael Kifer committed
70
(defun ediff-test-patch-utility ()
71
  (condition-case nil
72
      (cond ((eq 0 (call-process ediff-patch-program nil nil nil "-z." "-b"))
73 74
	     ;; GNU `patch' v. >= 2.2
	     'gnu)
75
	    ((eq 0 (call-process ediff-patch-program nil nil nil "-b"))
76 77 78
	     'posix)
	    (t 'traditional))
    (file-error nil)))
Michael Kifer's avatar
Michael Kifer committed
79

80
(defcustom ediff-backup-specs
Michael Kifer's avatar
Michael Kifer committed
81 82 83 84 85 86 87 88 89 90 91
  (let ((type (ediff-test-patch-utility)))
    (cond ((eq type 'gnu)
	   ;; GNU `patch' v. >= 2.2
	   (format "-z%s -b" ediff-backup-extension))
	  ((eq type 'posix)
	   ;; POSIX `patch' -- ediff-backup-extension must be ".orig"
	   (setq ediff-backup-extension ediff-default-backup-extension)
	   "-b")
	  (t
	   ;; traditional `patch'
	   (format "-b %s" ediff-backup-extension))))
Lute Kamstra's avatar
Lute Kamstra committed
92
  "Backup directives to pass to the patch program.
Michael Kifer's avatar
Michael Kifer committed
93
Ediff requires that the old version of the file \(before applying the patch\)
Michael Kifer's avatar
Michael Kifer committed
94
be saved in a file named `the-patch-file.extension'.  Usually `extension' is
Michael Kifer's avatar
Michael Kifer committed
95 96 97 98
`.orig', but this can be changed by the user and may depend on the system.
Therefore, Ediff needs to know the backup extension used by the patch program.

Some versions of the patch program let you specify `-b backup-extension'.
Michael Kifer's avatar
Michael Kifer committed
99
Other versions only permit `-b', which assumes the extension `.orig'
Michael Kifer's avatar
Michael Kifer committed
100
\(in which case ediff-backup-extension MUST be also `.orig'\).  The latest
Michael Kifer's avatar
Michael Kifer committed
101
versions of GNU patch require `-b -z backup-extension'.
Michael Kifer's avatar
Michael Kifer committed
102 103

Note that both `ediff-backup-extension' and `ediff-backup-specs'
Michael Kifer's avatar
Michael Kifer committed
104
must be set properly.  If your patch program takes the option `-b',
Michael Kifer's avatar
Michael Kifer committed
105
but not `-b extension', the variable `ediff-backup-extension' must
Michael Kifer's avatar
Michael Kifer committed
106 107
still be set so Ediff will know which extension to use.

Michael Kifer's avatar
Michael Kifer committed
108
Ediff tries to guess the appropriate value for this variables.  It is believed
Michael Kifer's avatar
Michael Kifer committed
109
to be working for `traditional' patch, all versions of GNU patch, and for POSIX
Michael Kifer's avatar
Michael Kifer committed
110
patch.  So, don't change these variables, unless the default doesn't work."
Michael Kifer's avatar
Michael Kifer committed
111 112
  :type 'string
  :group 'ediff-ptch)
Michael Kifer's avatar
Michael Kifer committed
113

Michael Kifer's avatar
Michael Kifer committed
114

Michael Kifer's avatar
Michael Kifer committed
115
(defcustom ediff-patch-default-directory nil
Lute Kamstra's avatar
Lute Kamstra committed
116
  "Default directory to look for patches."
Michael Kifer's avatar
Michael Kifer committed
117 118
  :type '(choice (const nil) string)
  :group 'ediff-ptch)
Michael Kifer's avatar
Michael Kifer committed
119

120 121
;; This context diff does not recognize spaces inside files, but removing ' '
;; from [^ \t] breaks normal patches for some reason
Michael Kifer's avatar
Michael Kifer committed
122
(defcustom ediff-context-diff-label-regexp
Michael Kifer's avatar
Michael Kifer committed
123
  (concat "\\(" 	; context diff 2-liner
124
	  "^\\*\\*\\* +\\([^ \t]+\\)[^*]+[\t ]*\n--- +\\([^ \t]+\\)"
125 126
	  "\\|" 	; unified format diff 2-liner
	  "^--- +\\([^ \t]+\\).*\n\\+\\+\\+ +\\([^ \t]+\\)"
127
	  "\\)")
Lute Kamstra's avatar
Lute Kamstra committed
128
  "Regexp matching filename 2-liners at the start of each context diff.
Michael Kifer's avatar
Michael Kifer committed
129 130
You probably don't want to change that, unless you are using an obscure patch
program."
Michael Kifer's avatar
Michael Kifer committed
131 132
  :type 'regexp
  :group 'ediff-ptch)
Michael Kifer's avatar
Michael Kifer committed
133

Michael Kifer's avatar
Michael Kifer committed
134
;; The buffer of the patch file.  Local to control buffer.
Michael Kifer's avatar
Michael Kifer committed
135 136 137 138 139
(ediff-defvar-local ediff-patchbufer nil "")

;; The buffer where patch displays its diagnostics.
(ediff-defvar-local ediff-patch-diagnostics nil "")

Michael Kifer's avatar
Michael Kifer committed
140
;; Map of patch buffer.  Has the form:
Michael Kifer's avatar
Michael Kifer committed
141 142 143 144 145 146 147 148 149
;;    ((filename1 marker1 marker2) (filename2 marker1 marker2) ...)
;; where filenames are files to which patch would have applied the patch;
;; marker1 delimits the beginning of the corresponding patch and marker2 does
;; it for the end.
(ediff-defvar-local ediff-patch-map nil "")

;; strip prefix from filename
;; returns /dev/null, if can't strip prefix
(defsubst ediff-file-name-sans-prefix (filename prefix)
150 151 152 153 154 155 156 157 158 159
  (if prefix
      (save-match-data
	(if (string-match (concat "^" (if (stringp prefix)
					  (regexp-quote prefix)
					""))
			  filename)
	    (substring filename (match-end 0))
	  (concat "/null/" filename)))
    filename)
  )
Michael Kifer's avatar
Michael Kifer committed
160 161 162 163 164 165



;; no longer used
;; return the number of matches of regexp in buf starting from the beginning
(defun ediff-count-matches (regexp buf)
Michael Kifer's avatar
Michael Kifer committed
166
  (ediff-with-current-buffer buf
Michael Kifer's avatar
Michael Kifer committed
167 168 169 170 171 172 173 174 175 176 177
    (let ((count 0) opoint)
      (save-excursion
	(goto-char (point-min))
	(while (and (not (eobp))
		    (progn (setq opoint (point))
			   (re-search-forward regexp nil t)))
	  (if (= opoint (point))
	      (forward-char 1)
	    (setq count (1+ count)))))
      count)))

178
;; Scan BUF (which is supposed to contain a patch) and make a list of the form
179 180
;;    ((nil nil filename-spec1 marker1 marker2)
;;          (nil nil filename-spec2 marker1 marker2) ...)
181
;; where filename-spec[12] are files to which the `patch' program would
182 183 184 185 186 187 188
;; have applied the patch.
;; nin, nil are placeholders. See ediff-make-new-meta-list-element in
;;    ediff-meta.el for the explanations.
;; In the beginning we don't know exactly which files need to be patched.
;; We usually come up with two candidates and ediff-file-name-sans-prefix
;;    resolves this later.
;;
189 190
;; The marker `mark1' delimits the beginning of the corresponding patch and
;;    `mark2' does it for the end.
191 192 193
;; The result of ediff-map-patch-buffer is a list, which is then assigned
;; to ediff-patch-map.
;; The function returns the number of elements in the list ediff-patch-map
Michael Kifer's avatar
Michael Kifer committed
194
(defun ediff-map-patch-buffer (buf)
Michael Kifer's avatar
Michael Kifer committed
195
  (ediff-with-current-buffer buf
Michael Kifer's avatar
Michael Kifer committed
196
    (let ((count 0)
197
	  (mark1 (point-min-marker))
Michael Kifer's avatar
Michael Kifer committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211
	  (mark1-end (point-min))
	  (possible-file-names '("/dev/null" . "/dev/null"))
	  mark2-end mark2 filenames
	  beg1 beg2 end1 end2
	  patch-map opoint)
      (save-excursion
	(goto-char (point-min))
	(setq opoint (point))
	(while (and (not (eobp))
		    (re-search-forward ediff-context-diff-label-regexp nil t))
	  (if (= opoint (point))
	      (forward-char 1) ; ensure progress towards the end
	    (setq mark2 (move-marker (make-marker) (match-beginning 0))
		  mark2-end (match-end 0)
212
		  beg1 (or (match-beginning 2) (match-beginning 4))
Michael Kifer's avatar
Michael Kifer committed
213 214 215
 		  end1 (or (match-end 2) (match-end 4))
 		  beg2 (or (match-beginning 3) (match-beginning 5))
 		  end2 (or (match-end 3) (match-end 5)))
Michael Kifer's avatar
Michael Kifer committed
216 217
	    ;; possible-file-names is holding the new file names until we
	    ;; insert the old file name in the patch map
218
	    ;; It is a pair
219
	    ;;     (filename-from-1st-header-line . filename-from-2nd-line)
Michael Kifer's avatar
Michael Kifer committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233
	    (setq possible-file-names
		  (cons (if (and beg1 end1)
			    (buffer-substring beg1 end1)
			  "/dev/null")
			(if (and beg2 end2)
			    (buffer-substring beg2 end2)
			  "/dev/null")))
	    ;; check for any `Index:' or `Prereq:' lines, but don't use them
	    (if (re-search-backward "^Index:" mark1-end 'noerror)
		(move-marker mark2 (match-beginning 0)))
	    (if (re-search-backward "^Prereq:" mark1-end 'noerror)
		(move-marker mark2 (match-beginning 0)))

	    (goto-char mark2-end)
234

Michael Kifer's avatar
Michael Kifer committed
235
	    (if filenames
236 237 238 239
		(setq patch-map
		      (cons (ediff-make-new-meta-list-element
			     filenames mark1 mark2)
			    patch-map)))
Michael Kifer's avatar
Michael Kifer committed
240 241 242 243 244 245
	    (setq mark1 mark2
		  mark1-end mark2-end
		  filenames possible-file-names))
	  (setq opoint (point)
		count (1+ count))))
      (setq mark2 (point-max-marker)
246 247 248
	    patch-map (cons (ediff-make-new-meta-list-element
			     possible-file-names mark1 mark2)
			    patch-map))
Michael Kifer's avatar
Michael Kifer committed
249 250 251 252
      (setq ediff-patch-map (nreverse patch-map))
      count)))

;; Fix up the file names in the list using the argument FILENAME
253 254 255 256 257 258 259 260
;; Algorithm: find the files' directories in the patch and, if a directory is
;; absolute, cut it out from the corresponding file name in the patch.
;; Relative directories are not cut out.
;; Prepend the directory of FILENAME to each resulting file (which came
;; originally from the patch).
;; In addition, the first file in the patch document is replaced by FILENAME.
;; Each file is actually a pair of files found in the context diff header
;; In the end, for each pair, we ask the user which file to patch.
Michael Kifer's avatar
Michael Kifer committed
261
;; Note: Ediff doesn't recognize multi-file patches that are separated
Michael Kifer's avatar
Michael Kifer committed
262
;; with the `Index:' line.  It treats them as a single-file patch.
Michael Kifer's avatar
Michael Kifer committed
263 264 265 266 267 268 269 270
;;
;; Executes inside the patch buffer
(defun ediff-fixup-patch-map (filename)
  (setq filename (expand-file-name filename))
  (let ((actual-dir (if (file-directory-p filename)
			;; directory part of filename
			(file-name-as-directory filename)
		      (file-name-directory filename)))
271 272 273 274
	;; In case 2 files are possible patch targets, the user will be offered
	;; to choose file1 or file2.  In a multifile patch, if the user chooses
	;; 1 or 2, this choice is preserved to decide future alternatives.
	chosen-alternative
Michael Kifer's avatar
Michael Kifer committed
275 276 277
	)

    ;; chop off base-dirs
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
    (mapc (lambda (session-info)
	    (let* ((proposed-file-names
		    ;; Filename-spec is objA; it is represented as
		    ;; (file1 . file2). Get it using ediff-get-session-objA.
		    (ediff-get-session-objA-name session-info))
		   ;; base-dir1 is  the dir part of the 1st file in the patch
		   (base-dir1
		    (or (file-name-directory (car proposed-file-names))
			""))
		   ;; directory part of the 2nd file in the patch
		   (base-dir2
		    (or (file-name-directory (cdr proposed-file-names))
			""))
		   )
	      ;; If both base-dir1 and base-dir2 are relative and exist,
	      ;; assume that
	      ;; these dirs lead to the actual files starting at the present
	      ;; directory. So, we don't strip these relative dirs from the
	      ;; file names. This is a heuristic intended to improve guessing
	      (let ((default-directory (file-name-directory filename)))
		(unless (or (file-name-absolute-p base-dir1)
			    (file-name-absolute-p base-dir2)
			    (not (file-exists-p base-dir1))
			    (not (file-exists-p base-dir2)))
		  (setq base-dir1 ""
			base-dir2 "")))
	      (or (string= (car proposed-file-names) "/dev/null")
		  (setcar proposed-file-names
			  (ediff-file-name-sans-prefix
			   (car proposed-file-names) base-dir1)))
	      (or (string=
		   (cdr proposed-file-names) "/dev/null")
		  (setcdr proposed-file-names
			  (ediff-file-name-sans-prefix
			   (cdr proposed-file-names) base-dir2)))
	      ))
	  ediff-patch-map)
Michael Kifer's avatar
Michael Kifer committed
315 316 317 318

    ;; take the given file name into account
    (or (file-directory-p filename)
	(string= "/dev/null" filename)
319 320 321
	(setcar (ediff-get-session-objA (car ediff-patch-map))
		(cons (file-name-nondirectory filename)
		      (file-name-nondirectory filename))))
Michael Kifer's avatar
Michael Kifer committed
322 323

    ;; prepend actual-dir
324 325 326 327 328 329 330 331 332 333 334 335 336
    (mapc (lambda (session-info)
	    (let ((proposed-file-names
		   (ediff-get-session-objA-name session-info)))
	      (if (and (string-match "^/null/" (car proposed-file-names))
		       (string-match "^/null/" (cdr proposed-file-names)))
		  ;; couldn't intuit the file name to patch, so
		  ;; something is amiss
		  (progn
		    (with-output-to-temp-buffer ediff-msg-buffer
		      (ediff-with-current-buffer standard-output
			(fundamental-mode))
		      (princ
		       (format "
Michael Kifer's avatar
Michael Kifer committed
337 338 339 340
The patch file contains a context diff for
	%s
	%s
However, Ediff cannot infer the name of the actual file
Michael Kifer's avatar
Michael Kifer committed
341
to be patched on your system.  If you know the correct file name,
Michael Kifer's avatar
Michael Kifer committed
342 343 344 345 346
please enter it now.

If you don't know and still would like to apply patches to
other files, enter /dev/null
"
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
			       (substring (car proposed-file-names) 6)
			       (substring (cdr proposed-file-names) 6))))
		    (let ((directory t)
			  user-file)
		      (while directory
			(setq user-file
			      (read-file-name
			       "Please enter file name: "
			       actual-dir actual-dir t))
			(if (not (file-directory-p user-file))
			    (setq directory nil)
			  (setq directory t)
			  (beep)
			  (message "%s is a directory" user-file)
			  (sit-for 2)))
		      (setcar (ediff-get-session-objA session-info)
			      (cons user-file user-file))))
		(setcar proposed-file-names
			(expand-file-name
			 (concat actual-dir (car proposed-file-names))))
		(setcdr proposed-file-names
			(expand-file-name
			 (concat actual-dir (cdr proposed-file-names)))))
	      ))
	  ediff-patch-map)
Paul Eggert's avatar
Paul Eggert committed
372
    ;; Check for the existing files in each pair and discard the nonexistent
373
    ;; ones. If both exist, ask the user.
374 375 376 377 378
    (mapcar (lambda (session-info)
	      (let* ((file1 (car (ediff-get-session-objA-name session-info)))
		     (file2 (cdr (ediff-get-session-objA-name session-info)))
		     (session-file-object
		      (ediff-get-session-objA session-info))
Michael Kifer's avatar
Michael Kifer committed
379 380 381
		     (f1-exists (file-exists-p file1))
		     (f2-exists (file-exists-p file2)))
		(cond
382 383 384 385 386 387 388 389
		 ((and
		   ;; The patch program prefers the shortest file as the patch
		   ;; target. However, this is a questionable heuristic. In an
		   ;; interactive program, like ediff, we can offer the user a
		   ;; choice.
		   ;; (< (length file2) (length file1))
		   (not f1-exists)
		   f2-exists)
390 391
		  ;; replace file-pair with the winning file2
		  (setcar session-file-object file2))
392 393 394 395
		 ((and
		   ;; (< (length file1) (length file2))
		   (not f2-exists)
		   f1-exists)
396 397
		  ;; replace file-pair with the winning file1
		  (setcar session-file-object file1))
Michael Kifer's avatar
Michael Kifer committed
398 399
		 ((and f1-exists f2-exists
		       (string= file1 file2))
400
		  (setcar session-file-object file1))
401 402 403 404
		 ((and f1-exists f2-exists (eq chosen-alternative 1))
		  (setcar session-file-object file1))
		 ((and f1-exists f2-exists (eq chosen-alternative 2))
		  (setcar session-file-object file2))
Michael Kifer's avatar
Michael Kifer committed
405 406
		 ((and f1-exists f2-exists)
		  (with-output-to-temp-buffer ediff-msg-buffer
407 408
		    (ediff-with-current-buffer standard-output
		      (fundamental-mode))
Michael Kifer's avatar
Michael Kifer committed
409
		    (princ (format "
Michael Kifer's avatar
Michael Kifer committed
410 411 412
Ediff has inferred that
	%s
	%s
Michael Kifer's avatar
Michael Kifer committed
413
are two possible targets for applying the patch.
Michael Kifer's avatar
Michael Kifer committed
414 415
Both files seem to be plausible alternatives.

416
Please advise:
Michael Kifer's avatar
Michael Kifer committed
417 418 419
    Type `y' to use %s as the target;
    Type `n' to use %s as the target.
"
420
				   file1 file2 file1 file2)))
421
		  (setcar session-file-object
422 423 424 425 426 427 428
			  (if (y-or-n-p (format "Use %s ? " file1))
			      (progn
				(setq chosen-alternative 1)
				file1)
			    (setq chosen-alternative 2)
			    file2))
		  )
429 430
		 (f2-exists (setcar session-file-object file2))
		 (f1-exists (setcar session-file-object file1))
Michael Kifer's avatar
Michael Kifer committed
431 432
		 (t
		  (with-output-to-temp-buffer ediff-msg-buffer
433 434
		    (ediff-with-current-buffer standard-output
		      (fundamental-mode))
Michael Kifer's avatar
Michael Kifer committed
435 436 437
		    (princ "\nEdiff has inferred that")
		    (if (string= file1 file2)
			(princ (format "
Michael Kifer's avatar
Michael Kifer committed
438
	%s
439
is assumed to be the target for this patch.  However, this file does not exist."
Michael Kifer's avatar
Michael Kifer committed
440 441
				       file1))
		      (princ (format "
Michael Kifer's avatar
Michael Kifer committed
442
	%s
Michael Kifer's avatar
Michael Kifer committed
443
	%s
Michael Kifer's avatar
Michael Kifer committed
444 445 446
are two possible targets for this patch.  However, these files do not exist."
				     file1 file2)))
		    (princ "
Michael Kifer's avatar
Michael Kifer committed
447
\nPlease enter an alternative patch target ...\n"))
Michael Kifer's avatar
Michael Kifer committed
448 449 450
		  (let ((directory t)
			target)
		    (while directory
451
		      (setq target (read-file-name
Michael Kifer's avatar
Michael Kifer committed
452 453 454 455 456 457 458
				    "Please enter a patch target: "
				    actual-dir actual-dir t))
		      (if (not (file-directory-p target))
			  (setq directory nil)
			(beep)
			(message "%s is a directory" target)
			(sit-for 2)))
459
		    (setcar session-file-object target))))))
Michael Kifer's avatar
Michael Kifer committed
460 461 462 463 464 465 466 467 468 469 470
	    ediff-patch-map)
    ))

(defun ediff-show-patch-diagnostics ()
  (interactive)
  (cond ((window-live-p ediff-window-A)
	 (set-window-buffer ediff-window-A ediff-patch-diagnostics))
	((window-live-p ediff-window-B)
	 (set-window-buffer ediff-window-B ediff-patch-diagnostics))
	(t (display-buffer ediff-patch-diagnostics 'not-this-window))))

Glenn Morris's avatar
Glenn Morris committed
471 472
(defvar ediff-use-last-dir)

Michael Kifer's avatar
Michael Kifer committed
473 474
;; prompt for file, get the buffer
(defun ediff-prompt-for-patch-file ()
475 476
  (let ((dir (cond (ediff-use-last-dir ediff-last-dir-patch)
		   (ediff-patch-default-directory) ; try patch default dir
477
		   (t default-directory)))
478 479 480 481
	(coding-system-for-read ediff-coding-system-for-read)
	patch-file-name)
    (setq patch-file-name
	  (read-file-name
482
	   (format "Patch is in file%s: "
483 484 485 486 487 488 489 490 491 492 493 494
		   (cond ((and buffer-file-name
			       (equal (expand-file-name dir)
				      (file-name-directory buffer-file-name)))
			  (concat
			   " (default "
			   (file-name-nondirectory buffer-file-name)
			   ")"))
			 (t "")))
	   dir buffer-file-name 'must-match))
    (if (file-directory-p patch-file-name)
	(error "Patch file cannot be a directory: %s" patch-file-name)
      (find-file-noselect patch-file-name))
Michael Kifer's avatar
Michael Kifer committed
495 496 497 498 499 500 501
    ))


;; Try current buffer, then the other window's buffer. Else, give up.
(defun ediff-prompt-for-patch-buffer ()
  (get-buffer
   (read-buffer
502
    "Buffer that holds the patch: "
Michael Kifer's avatar
Michael Kifer committed
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
    (cond ((save-excursion
	     (goto-char (point-min))
	     (re-search-forward ediff-context-diff-label-regexp nil t))
	   (current-buffer))
	  ((save-window-excursion
	     (other-window 1)
	     (save-excursion
	       (goto-char (point-min))
	       (and (re-search-forward ediff-context-diff-label-regexp nil t)
		    (current-buffer)))))
	  ((save-window-excursion
	     (other-window -1)
	     (save-excursion
	       (goto-char (point-min))
	       (and (re-search-forward ediff-context-diff-label-regexp nil t)
		    (current-buffer)))))
519
	  (t (ediff-other-buffer (current-buffer))))
Michael Kifer's avatar
Michael Kifer committed
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
    'must-match)))


(defun ediff-get-patch-buffer (&optional arg patch-buf)
  "Obtain patch buffer.  If patch is already in a buffer---use it.
Else, read patch file into a new buffer. If patch buffer is passed as an
optional argument, then use it."
  (let ((last-nonmenu-event t) ; Emacs: don't use dialog box
	last-command-event)    ; XEmacs: don't use dialog box

    (cond ((ediff-buffer-live-p patch-buf))
	  ;; even prefix arg: patch in buffer
	  ((and (integerp arg) (eq 0 (mod arg 2)))
	   (setq patch-buf (ediff-prompt-for-patch-buffer)))
	  ;; odd prefix arg: get patch from a file
	  ((and (integerp arg) (eq 1 (mod arg 2)))
	   (setq patch-buf (ediff-prompt-for-patch-file)))
	  (t (setq patch-buf
		   (if (y-or-n-p "Is the patch already in a buffer? ")
		       (ediff-prompt-for-patch-buffer)
		     (ediff-prompt-for-patch-file)))))
541

Michael Kifer's avatar
Michael Kifer committed
542
    (ediff-with-current-buffer patch-buf
Michael Kifer's avatar
Michael Kifer committed
543 544 545 546 547 548 549 550 551 552 553 554 555 556
      (goto-char (point-min))
      (or (ediff-get-visible-buffer-window patch-buf)
	  (progn
	    (pop-to-buffer patch-buf 'other-window)
	    (select-window (previous-window)))))
    (ediff-map-patch-buffer patch-buf)
    patch-buf))

;; Dispatch the right patch file function: regular or meta-level,
;; depending on how many patches are in the patch file.
;; At present, there is no support for meta-level patches.
;; Should return either the ctl buffer or the meta-buffer
(defun ediff-dispatch-file-patching-job (patch-buf filename
						   &optional startup-hooks)
Michael Kifer's avatar
Michael Kifer committed
557
  (ediff-with-current-buffer patch-buf
Michael Kifer's avatar
Michael Kifer committed
558 559 560 561 562
    ;; relativize names in the patch with respect to source-file
    (ediff-fixup-patch-map filename)
    (if (< (length ediff-patch-map) 2)
	(ediff-patch-file-internal
	 patch-buf
563
	 (if (and ediff-patch-map
564 565 566 567
		  (not (string-match
			"^/dev/null"
			;; this is the file to patch
			(ediff-get-session-objA-name (car ediff-patch-map))))
568
		  (> (length
569 570 571
		      (ediff-get-session-objA-name (car ediff-patch-map)))
		     1))
	     (ediff-get-session-objA-name (car ediff-patch-map))
Michael Kifer's avatar
Michael Kifer committed
572 573 574 575 576 577
	   filename)
	 startup-hooks)
      (ediff-multi-patch-internal patch-buf startup-hooks))
    ))


Michael Kifer's avatar
Michael Kifer committed
578
;; When patching a buffer, never change the orig file.  Instead, create a new
Michael Kifer's avatar
Michael Kifer committed
579 580 581 582 583 584
;; buffer, ***_patched, even if the buff visits a file.
;; Users who want to actually patch the buffer should use
;; ediff-patch-file, not ediff-patch-buffer.
(defun ediff-patch-buffer-internal (patch-buf
				    buf-to-patch-name
				    &optional startup-hooks)
Michael Kifer's avatar
Michael Kifer committed
585
  (let* ((buf-to-patch (get-buffer buf-to-patch-name))
Michael Kifer's avatar
Michael Kifer committed
586
	 (visited-file (if buf-to-patch (buffer-file-name  buf-to-patch)))
Michael Kifer's avatar
Michael Kifer committed
587
	 (buf-mod-status (buffer-modified-p buf-to-patch))
Michael Kifer's avatar
Michael Kifer committed
588
	 (multifile-patch-p (> (length (ediff-with-current-buffer patch-buf
Michael Kifer's avatar
Michael Kifer committed
589 590
					 ediff-patch-map)) 1))
	 default-dir file-name ctl-buf)
Michael Kifer's avatar
Michael Kifer committed
591 592
    (if multifile-patch-p
	(error
Michael Kifer's avatar
Michael Kifer committed
593
	 "To apply multi-file patches, please use `ediff-patch-file'"))
Michael Kifer's avatar
Michael Kifer committed
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609

    ;; create a temp file to patch
    (ediff-with-current-buffer buf-to-patch
      (setq default-dir default-directory)
      (setq file-name (ediff-make-temp-file buf-to-patch))
      ;; temporarily switch visited file name, if any
      (set-visited-file-name file-name)
      ;; don't create auto-save file, if buff was visiting a file
      (or visited-file
	  (setq buffer-auto-save-file-name nil))
      ;; don't confuse the user with a new bufname
      (rename-buffer buf-to-patch-name)
      (set-buffer-modified-p nil)
      (set-visited-file-modtime) ; sync buffer and temp file
      (setq default-directory default-dir)
      )
610

Michael Kifer's avatar
Michael Kifer committed
611 612 613
    ;; dispatch a patch function
    (setq ctl-buf (ediff-dispatch-file-patching-job
		   patch-buf file-name startup-hooks))
614

Michael Kifer's avatar
Michael Kifer committed
615 616 617 618 619 620 621 622 623 624 625 626
    (ediff-with-current-buffer ctl-buf
      (delete-file (buffer-file-name ediff-buffer-A))
      (delete-file (buffer-file-name ediff-buffer-B))
      (ediff-with-current-buffer ediff-buffer-A
	(if default-dir (setq default-directory default-dir))
	(set-visited-file-name visited-file) ; visited-file might be nil
	(rename-buffer buf-to-patch-name)
	(set-buffer-modified-p buf-mod-status))
      (ediff-with-current-buffer ediff-buffer-B
	(setq buffer-auto-save-file-name nil) ; don't create auto-save file
	(if default-dir (setq default-directory default-dir))
	(set-visited-file-name nil)
627
	(rename-buffer (ediff-unique-buffer-name
Michael Kifer's avatar
Michael Kifer committed
628 629
			(concat buf-to-patch-name "_patched") ""))
	(set-buffer-modified-p t)))
Michael Kifer's avatar
Michael Kifer committed
630 631
    ))

Michael Kifer's avatar
Michael Kifer committed
632 633 634 635

;; Traditional patch has weird return codes.
;; GNU and Posix return 1 if some hanks failed and 2 in case of trouble.
;; 0 is a good code in all cases.
Paul Eggert's avatar
Paul Eggert committed
636
;; We'll do the conservative thing.
Michael Kifer's avatar
Michael Kifer committed
637 638 639 640 641 642
(defun ediff-patch-return-code-ok (code)
  (eq code 0))
;;;  (if (eq (ediff-test-patch-utility) 'traditional)
;;;      (eq code 0)
;;;    (not (eq code 2))))

Glenn Morris's avatar
Glenn Morris committed
643 644 645 646 647
(autoload 'ediff-find-file "ediff")
(declare-function ediff-buffers-internal "ediff"
		  (buf-a buf-b buf-c startup-hooks job-name
			 &optional merge-buffer-file))

Michael Kifer's avatar
Michael Kifer committed
648 649 650
(defun ediff-patch-file-internal (patch-buf source-filename
					    &optional startup-hooks)
  (setq source-filename (expand-file-name source-filename))
651

Michael Kifer's avatar
Michael Kifer committed
652
  (let* ((shell-file-name ediff-shell)
Michael Kifer's avatar
Michael Kifer committed
653 654 655 656 657 658 659
	 (patch-diagnostics (get-buffer-create "*ediff patch diagnostics*"))
	 ;; ediff-find-file may use a temp file to do the patch
	 ;; so, we save source-filename and true-source-filename as a var
	 ;; that initially is source-filename but may be changed to a temp
	 ;; file for the purpose of patching.
	 (true-source-filename source-filename)
	 (target-filename source-filename)
660 661
	 ;; this ensures that the patch process gets patch buffer in the
	 ;; encoding that Emacs thinks is right for that type of text
662
	 (coding-system-for-write
663
	  (if (boundp 'buffer-file-coding-system) buffer-file-coding-system))
664
	 target-buf buf-to-patch file-name-magic-p
Michael Kifer's avatar
Michael Kifer committed
665
	 patch-return-code ctl-buf backup-style aux-wind)
666

Michael Kifer's avatar
Michael Kifer committed
667
    (if (string-match "V" ediff-patch-options)
Michael Kifer's avatar
Michael Kifer committed
668 669
	(error
	 "Ediff doesn't take the -V option in `ediff-patch-options'--sorry"))
670

Michael Kifer's avatar
Michael Kifer committed
671 672 673 674 675 676 677 678 679 680 681 682 683
    ;; Make a temp file, if source-filename has a magic file handler (or if
    ;; it is handled via auto-mode-alist and similar magic).
    ;; Check if there is a buffer visiting source-filename and if they are in
    ;; sync; arrange for the deletion of temp file.
    (ediff-find-file 'true-source-filename 'buf-to-patch
		     'ediff-last-dir-patch 'startup-hooks)

    ;; Check if source file name has triggered black magic, such as file name
    ;; handlers or auto mode alist, and make a note of it.
    ;; true-source-filename should be either the original name or a
    ;; temporary file where we put the after-product of the file handler.
    (setq file-name-magic-p (not (equal (file-truename true-source-filename)
					(file-truename source-filename))))
684 685

    ;; Checkout orig file, if necessary, so that the patched file
Michael Kifer's avatar
Michael Kifer committed
686 687
    ;; could be checked back in.
    (ediff-maybe-checkout buf-to-patch)
Michael Kifer's avatar
Michael Kifer committed
688

Michael Kifer's avatar
Michael Kifer committed
689
    (ediff-with-current-buffer patch-diagnostics
690
      (insert-buffer-substring patch-buf)
Michael Kifer's avatar
Michael Kifer committed
691 692 693 694
      (message "Applying patch ... ")
      ;; fix environment for gnu patch, so it won't make numbered extensions
      (setq backup-style (getenv "VERSION_CONTROL"))
      (setenv "VERSION_CONTROL" nil)
Michael Kifer's avatar
Michael Kifer committed
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
      (setq patch-return-code
	    (call-process-region
	     (point-min) (point-max)
	     shell-file-name
	     t   ; delete region (which contains the patch
	     t   ; insert output (patch diagnostics) in current buffer
	     nil ; don't redisplay
	     shell-command-switch   ; usually -c
	     (format "%s %s %s %s"
		     ediff-patch-program
		     ediff-patch-options
		     ediff-backup-specs
		     (expand-file-name true-source-filename))
	     ))

Michael Kifer's avatar
Michael Kifer committed
710 711 712 713 714 715 716 717
      ;; restore environment for gnu patch
      (setenv "VERSION_CONTROL" backup-style))

    (message "Applying patch ... done")
    (message "")

    (switch-to-buffer patch-diagnostics)
    (sit-for 0) ; synchronize - let the user see diagnostics
718

Michael Kifer's avatar
Michael Kifer committed
719
    (or (and (ediff-patch-return-code-ok patch-return-code)
Michael Kifer's avatar
Michael Kifer committed
720 721 722 723
	     (file-exists-p
	      (concat true-source-filename ediff-backup-extension)))
	(progn
	  (with-output-to-temp-buffer ediff-msg-buffer
724 725
	    (ediff-with-current-buffer standard-output
	      (fundamental-mode))
726
	    (princ (format
Michael Kifer's avatar
Michael Kifer committed
727 728 729
		    "Patch program has failed due to a bad patch file,
it couldn't apply all hunks, OR
it couldn't create the backup for the file being patched.
Michael Kifer's avatar
Michael Kifer committed
730

Michael Kifer's avatar
Michael Kifer committed
731 732
The former could be caused by a corrupt patch file or because the %S
program doesn't understand the format of the patch file in use.
Michael Kifer's avatar
Michael Kifer committed
733

Michael Kifer's avatar
Michael Kifer committed
734
The second problem might be due to an incompatibility among these settings:
Michael Kifer's avatar
Michael Kifer committed
735 736
    ediff-patch-program    = %S             ediff-patch-options    = %S
    ediff-backup-extension = %S             ediff-backup-specs     = %S
Michael Kifer's avatar
Michael Kifer committed
737 738

See Ediff on-line manual for more details on these variables.
739
In particular, check the documentation for `ediff-backup-specs'.
Michael Kifer's avatar
Michael Kifer committed
740 741 742 743

In any of the above cases, Ediff doesn't compare files automatically.
However, if the patch was applied partially and the backup file was created,
you can still examine the changes via M-x ediff-files"
744 745 746 747 748 749
		    ediff-patch-program
		    ediff-patch-program
		    ediff-patch-options
		    ediff-backup-extension
		    ediff-backup-specs
		    )))
Michael Kifer's avatar
Michael Kifer committed
750 751 752 753 754
	  (beep 1)
	  (if (setq aux-wind (get-buffer-window ediff-msg-buffer))
	      (progn
		(select-window aux-wind)
		(goto-char (point-max))))
Michael Kifer's avatar
Michael Kifer committed
755
	  (switch-to-buffer-other-window patch-diagnostics)
Michael Kifer's avatar
Michael Kifer committed
756
	  (error "Patch appears to have failed")))
757

Michael Kifer's avatar
Michael Kifer committed
758
    ;; If black magic is involved, apply patch to a temp copy of the
Michael Kifer's avatar
Michael Kifer committed
759
    ;; file.  Otherwise, apply patch to the orig copy.  If patch is applied
Michael Kifer's avatar
Michael Kifer committed
760
    ;; to temp copy, we name the result old-name_patched for local files
Michael Kifer's avatar
Michael Kifer committed
761
    ;; and temp-copy_patched for remote files.  The orig file name isn't
Michael Kifer's avatar
Michael Kifer committed
762 763 764 765 766
    ;; changed, and the temp copy of the original is later deleted.
    ;; Without magic, the original file is renamed (usually into
    ;; old-name_orig) and the result of patching will have the same name as
    ;; the original.
    (if (not file-name-magic-p)
Michael Kifer's avatar
Michael Kifer committed
767
	(ediff-with-current-buffer buf-to-patch
Michael Kifer's avatar
Michael Kifer committed
768 769
	  (set-visited-file-name
	   (concat source-filename ediff-backup-extension))
Michael Kifer's avatar
Michael Kifer committed
770
	  (set-buffer-modified-p nil))
771

Michael Kifer's avatar
Michael Kifer committed
772 773 774 775 776 777 778 779 780 781
      ;; Black magic in effect.
      ;; If orig file was remote, put the patched file in the temp directory.
      ;; If orig file is local, put the patched file in the directory of
      ;; the orig file.
      (setq target-filename
	    (concat
	     (if (ediff-file-remote-p (file-truename source-filename))
		 true-source-filename
	       source-filename)
	     "_patched"))
782

Michael Kifer's avatar
Michael Kifer committed
783
      (rename-file true-source-filename target-filename t)
784

Michael Kifer's avatar
Michael Kifer committed
785
      ;; arrange that the temp copy of orig will be deleted
Michael Kifer's avatar
Michael Kifer committed
786
      (rename-file (concat true-source-filename ediff-backup-extension)
Michael Kifer's avatar
Michael Kifer committed
787
		   true-source-filename t))
788

Michael Kifer's avatar
Michael Kifer committed
789 790 791
    ;; make orig buffer read-only
    (setq startup-hooks
	  (cons 'ediff-set-read-only-in-buf-A startup-hooks))
792

Michael Kifer's avatar
Michael Kifer committed
793 794
    ;; set up a buf for the patched file
    (setq target-buf (find-file-noselect target-filename))
795

Michael Kifer's avatar
Michael Kifer committed
796 797 798 799
    (setq ctl-buf
	  (ediff-buffers-internal
	   buf-to-patch target-buf nil
	   startup-hooks 'epatch))
Michael Kifer's avatar
Michael Kifer committed
800
    (ediff-with-current-buffer ctl-buf
Michael Kifer's avatar
Michael Kifer committed
801 802
      (setq ediff-patchbufer patch-buf
	    ediff-patch-diagnostics patch-diagnostics))
803

Michael Kifer's avatar
Michael Kifer committed
804 805 806 807 808 809 810 811 812
    (bury-buffer patch-diagnostics)
    (message "Type `P', if you need to see patch diagnostics")
    ctl-buf))

(defun ediff-multi-patch-internal (patch-buf &optional startup-hooks)
  (let (meta-buf)
    (setq startup-hooks
	  ;; this sets various vars in the meta buffer inside
	  ;; ediff-prepare-meta-buffer
Michael Kifer's avatar
Michael Kifer committed
813 814 815 816 817
	  (cons `(lambda ()
		   ;; tell what to do if the user clicks on a session record
		   (setq ediff-session-action-function
			 'ediff-patch-file-form-meta
			 ediff-meta-patchbufer patch-buf) )
Michael Kifer's avatar
Michael Kifer committed
818
		startup-hooks))
819
    (setq meta-buf (ediff-prepare-meta-buffer
Michael Kifer's avatar
Michael Kifer committed
820
		    'ediff-filegroup-action
Michael Kifer's avatar
Michael Kifer committed
821
		    (ediff-with-current-buffer patch-buf
822 823 824 825 826 827 828
		      (cons (ediff-make-new-meta-list-header
			     nil                     ; regexp
			     (format "%S" patch-buf) ; obj A
			     nil nil                 ; objects B,C
			     nil                     ; merge-auto-store-dir
			     nil                     ; comparison-func
			     )
Michael Kifer's avatar
Michael Kifer committed
829 830 831 832 833 834 835 836
			    ediff-patch-map))
		    "*Ediff Session Group Panel"
		    'ediff-redraw-directory-group-buffer
		    'ediff-multifile-patch
		    startup-hooks))
    (ediff-show-meta-buffer meta-buf)
    ))

837 838


Michael Kifer's avatar
Michael Kifer committed
839

840 841 842 843 844
;; Local Variables:
;; eval: (put 'ediff-defvar-local 'lisp-indent-hook 'defun)
;; eval: (put 'ediff-with-current-buffer 'lisp-indent-hook 1)
;; eval: (put 'ediff-with-current-buffer 'edebug-form-spec '(form body))
;; End:
Michael Kifer's avatar
Michael Kifer committed
845 846

;;; ediff-ptch.el ends here